From a5f79b39f70f58a59c7fb3b4d68f927ca44af715 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 18 Feb 2026 18:30:53 +0000 Subject: [PATCH 1/2] Update dependencies --- Dockerfile | 2 +- action/package.json | 4 +- app/package.json | 22 +- bun.lock | 432 +++++++++++++++++++++++++-------- comparadise-utils/package.json | 2 +- docs/package.json | 8 +- package.json | 10 +- 7 files changed, 357 insertions(+), 123 deletions(-) diff --git a/Dockerfile b/Dockerfile index 719d86a8..9f92658e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM oven/bun:1.3.6 +FROM oven/bun:1.3.9 WORKDIR /app RUN useradd -ms /bin/sh admin diff --git a/action/package.json b/action/package.json index 66fab215..0a5466e2 100644 --- a/action/package.json +++ b/action/package.json @@ -5,9 +5,9 @@ "dependencies": { "@actions/core": "3.0.0", "@actions/github": "9.0.0", - "@aws-sdk/client-s3": "3.975.0", + "@aws-sdk/client-s3": "3.992.0", "bluebird": "3.7.2", - "glob": "13.0.0", + "glob": "13.0.5", "jimp": "1.6.0" }, "devDependencies": { diff --git a/app/package.json b/app/package.json index ae2f7c52..9d23c263 100644 --- a/app/package.json +++ b/app/package.json @@ -2,26 +2,26 @@ "name": "app", "private": true, "dependencies": { - "@aws-sdk/client-s3": "3.975.0", - "@aws-sdk/s3-request-presigner": "3.975.0", + "@aws-sdk/client-s3": "3.992.0", + "@aws-sdk/s3-request-presigner": "3.992.0", "@headlessui/react": "2.2.9", "@octokit/rest": "22.0.1", - "@tanstack/react-query": "5.90.20", - "@trpc/client": "11.8.1", - "@trpc/react-query": "11.8.1", - "@trpc/server": "11.8.1", - "@types/bun": "1.3.6", + "@tanstack/react-query": "5.90.21", + "@trpc/client": "11.10.0", + "@trpc/react-query": "11.10.0", + "@trpc/server": "11.10.0", + "@types/bun": "1.3.9", "@types/lodash": "4.17.23", - "@types/react": "19.2.9", + "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "bun-plugin-tailwind": "0.1.2", "lodash": "4.17.23", - "react": "19.2.3", - "react-dom": "19.2.3", + "react": "19.2.4", + "react-dom": "19.2.4", "react-router-dom": "7.13.0", "trpc-bun-adapter": "1.3.0", "shared": "workspace:*", - "tailwindcss": "4.1.18", + "tailwindcss": "4.2.0", "zod": "4.3.6" }, "devDependencies": { diff --git a/bun.lock b/bun.lock index 1f2e3406..3d31bb19 100644 --- a/bun.lock +++ b/bun.lock @@ -7,18 +7,18 @@ "devDependencies": { "@testing-library/cypress": "10.1.0", "@total-typescript/ts-reset": "0.6.1", - "@types/bun": "1.3.6", - "cypress": "15.9.0", + "@types/bun": "1.3.9", + "cypress": "15.10.0", "eslint": "9.39.2", "eslint-plugin-react": "7.37.5", "husky": "9.1.7", - "nx": "22.4.1", + "nx": "22.5.1", "prettier": "3.8.1", "prettier-plugin-tailwindcss": "0.7.2", "shared": "workspace:*", "ts-node": "10.9.2", "typescript": "5.9.3", - "typescript-eslint": "8.53.1", + "typescript-eslint": "8.56.0", }, }, "action": { @@ -26,9 +26,9 @@ "dependencies": { "@actions/core": "3.0.0", "@actions/github": "9.0.0", - "@aws-sdk/client-s3": "3.975.0", + "@aws-sdk/client-s3": "3.992.0", "bluebird": "3.7.2", - "glob": "13.0.0", + "glob": "13.0.5", "jimp": "1.6.0", }, "devDependencies": { @@ -79,7 +79,7 @@ }, "devDependencies": { "@types/pngjs": "6.0.5", - "cypress": "15.9.0", + "cypress": "15.10.0", "tsup": "8.5.1", }, "peerDependencies": { @@ -94,11 +94,11 @@ "@docusaurus/preset-classic": "3.9.2", "@docusaurus/types": "3.9.2", "@mdx-js/react": "3.1.1", - "@types/react": "19.2.9", - "ajv": "8.17.1", + "@types/react": "19.2.14", + "ajv": "8.18.0", "clsx": "2.1.1", - "react": "19.2.3", - "react-dom": "19.2.3", + "react": "19.2.4", + "react-dom": "19.2.4", }, }, "shared": { @@ -170,75 +170,75 @@ "@aws-crypto/util": ["@aws-crypto/util@5.2.0", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="], - "@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.975.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.1", "@aws-sdk/credential-provider-node": "^3.972.1", "@aws-sdk/middleware-bucket-endpoint": "^3.972.1", "@aws-sdk/middleware-expect-continue": "^3.972.1", "@aws-sdk/middleware-flexible-checksums": "^3.972.1", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-location-constraint": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-sdk-s3": "^3.972.2", "@aws-sdk/middleware-ssec": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.2", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/signature-v4-multi-region": "3.972.0", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.1", "@smithy/eventstream-serde-browser": "^4.2.8", "@smithy/eventstream-serde-config-resolver": "^4.3.8", "@smithy/eventstream-serde-node": "^4.2.8", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-blob-browser": "^4.2.9", "@smithy/hash-node": "^4.2.8", "@smithy/hash-stream-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/md5-js": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/middleware-retry": "^4.4.27", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.26", "@smithy/util-defaults-mode-node": "^4.2.29", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-aF1M/iMD29BPcpxjqoym0YFa4WR9Xie1/IhVumwOGH6TB45DaqYO7vLwantDBcYNRn/cZH6DFHksO7RmwTFBhw=="], + "@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.992.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.10", "@aws-sdk/credential-provider-node": "^3.972.9", "@aws-sdk/middleware-bucket-endpoint": "^3.972.3", "@aws-sdk/middleware-expect-continue": "^3.972.3", "@aws-sdk/middleware-flexible-checksums": "^3.972.8", "@aws-sdk/middleware-host-header": "^3.972.3", "@aws-sdk/middleware-location-constraint": "^3.972.3", "@aws-sdk/middleware-logger": "^3.972.3", "@aws-sdk/middleware-recursion-detection": "^3.972.3", "@aws-sdk/middleware-sdk-s3": "^3.972.10", "@aws-sdk/middleware-ssec": "^3.972.3", "@aws-sdk/middleware-user-agent": "^3.972.10", "@aws-sdk/region-config-resolver": "^3.972.3", "@aws-sdk/signature-v4-multi-region": "3.992.0", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-endpoints": "3.992.0", "@aws-sdk/util-user-agent-browser": "^3.972.3", "@aws-sdk/util-user-agent-node": "^3.972.8", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.23.0", "@smithy/eventstream-serde-browser": "^4.2.8", "@smithy/eventstream-serde-config-resolver": "^4.3.8", "@smithy/eventstream-serde-node": "^4.2.8", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-blob-browser": "^4.2.9", "@smithy/hash-node": "^4.2.8", "@smithy/hash-stream-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/md5-js": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.14", "@smithy/middleware-retry": "^4.4.31", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.30", "@smithy/util-defaults-mode-node": "^4.2.33", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-stream": "^4.5.12", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-6xfXGCvnWGgy5zZAse64Ru2G2qLKnPY7h8tchlsmGWVcJOWgz7iM3jmsWsQiJ79zH9A8HAPHU+ZD8TYYkwC+0Q=="], - "@aws-sdk/client-sso": ["@aws-sdk/client-sso@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-ci+GiM0c4ULo4D79UMcY06LcOLcfvUfiyt8PzNY0vbt5O8BfCPYf4QomwVgkNcLLCYmroO4ge2Yy1EsLUlcD6g=="], + "@aws-sdk/client-sso": ["@aws-sdk/client-sso@3.990.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.10", "@aws-sdk/middleware-host-header": "^3.972.3", "@aws-sdk/middleware-logger": "^3.972.3", "@aws-sdk/middleware-recursion-detection": "^3.972.3", "@aws-sdk/middleware-user-agent": "^3.972.10", "@aws-sdk/region-config-resolver": "^3.972.3", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-endpoints": "3.990.0", "@aws-sdk/util-user-agent-browser": "^3.972.3", "@aws-sdk/util-user-agent-node": "^3.972.8", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.23.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.14", "@smithy/middleware-retry": "^4.4.31", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.30", "@smithy/util-defaults-mode-node": "^4.2.33", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-xTEaPjZwOqVjGbLOP7qzwbdOWJOo1ne2mUhTZwEBBkPvNk4aXB/vcYwWwrjoSWUqtit4+GDbO75ePc/S6TUJYQ=="], - "@aws-sdk/core": ["@aws-sdk/core@3.973.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws-sdk/xml-builder": "^3.972.1", "@smithy/core": "^3.21.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-Ocubx42QsMyVs9ANSmFpRm0S+hubWljpPLjOi9UFrtcnVJjrVJTzQ51sN0e5g4e8i8QZ7uY73zosLmgYL7kZTQ=="], + "@aws-sdk/core": ["@aws-sdk/core@3.973.10", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@aws-sdk/xml-builder": "^3.972.4", "@smithy/core": "^3.23.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-4u/FbyyT3JqzfsESI70iFg6e2yp87MB5kS2qcxIA66m52VSTN1fvuvbCY1h/LKq1LvuxIrlJ1ItcyjvcKoaPLg=="], "@aws-sdk/crc64-nvme": ["@aws-sdk/crc64-nvme@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-ThlLhTqX68jvoIVv+pryOdb5coP1cX1/MaTbB9xkGDCbWbsqQcLqzPxuSoW1DCnAAIacmXCWpzUNOB9pv+xXQw=="], - "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-/etNHqnx96phy/SjI0HRC588o4vKH5F0xfkZ13yAATV7aNrb+5gYGNE6ePWafP+FuZ3HkULSSlJFj0AxgrAqYw=="], + "@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.8", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-r91OOPAcHnLCSxaeu/lzZAVRCZ/CtTNuwmJkUwpwSDshUrP7bkX1OmFn2nUMWd9kN53Q4cEo8b7226G4olt2Mg=="], - "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-mXgdaUfe5oM+tWKyeZ7Vh/iQ94FrkMky1uuzwTOmFADiRcSk5uHy/e3boEFedXiT/PRGzgBmqvJVK4F6lUISCg=="], + "@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.10", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/types": "^3.973.1", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.10", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.12", "tslib": "^2.6.2" } }, "sha512-DTtuyXSWB+KetzLcWaSahLJCtTUe/3SXtlGp4ik9PCe9xD6swHEkG8n8/BNsQ9dsihb9nhFvuUB4DpdBGDcvVg=="], - "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/credential-provider-env": "^3.972.1", "@aws-sdk/credential-provider-http": "^3.972.1", "@aws-sdk/credential-provider-login": "^3.972.1", "@aws-sdk/credential-provider-process": "^3.972.1", "@aws-sdk/credential-provider-sso": "^3.972.1", "@aws-sdk/credential-provider-web-identity": "^3.972.1", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-OdbJA3v+XlNDsrYzNPRUwr8l7gw1r/nR8l4r96MDzSBDU8WEo8T6C06SvwaXR8SpzsjO3sq5KMP86wXWg7Rj4g=="], + "@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.8", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/credential-provider-env": "^3.972.8", "@aws-sdk/credential-provider-http": "^3.972.10", "@aws-sdk/credential-provider-login": "^3.972.8", "@aws-sdk/credential-provider-process": "^3.972.8", "@aws-sdk/credential-provider-sso": "^3.972.8", "@aws-sdk/credential-provider-web-identity": "^3.972.8", "@aws-sdk/nested-clients": "3.990.0", "@aws-sdk/types": "^3.973.1", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-n2dMn21gvbBIEh00E8Nb+j01U/9rSqFIamWRdGm/mE5e+vHQ9g0cBNdrYFlM6AAiryKVHZmShWT9D1JAWJ3ISw=="], - "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-CccqDGL6ZrF3/EFWZefvKW7QwwRdxlHUO8NVBKNVcNq6womrPDvqB6xc9icACtE0XB0a7PLoSTkAg8bQVkTO2w=="], + "@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.8", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/nested-clients": "3.990.0", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-rMFuVids8ICge/X9DF5pRdGMIvkVhDV9IQFQ8aTYk6iF0rl9jOUa1C3kjepxiXUlpgJQT++sLZkT9n0TMLHhQw=="], - "@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.1", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.1", "@aws-sdk/credential-provider-http": "^3.972.1", "@aws-sdk/credential-provider-ini": "^3.972.1", "@aws-sdk/credential-provider-process": "^3.972.1", "@aws-sdk/credential-provider-sso": "^3.972.1", "@aws-sdk/credential-provider-web-identity": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-DwXPk9GfuU/xG9tmCyXFVkCr6X3W8ZCoL5Ptb0pbltEx1/LCcg7T+PBqDlPiiinNCD6ilIoMJDWsnJ8ikzZA7Q=="], + "@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.9", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.8", "@aws-sdk/credential-provider-http": "^3.972.10", "@aws-sdk/credential-provider-ini": "^3.972.8", "@aws-sdk/credential-provider-process": "^3.972.8", "@aws-sdk/credential-provider-sso": "^3.972.8", "@aws-sdk/credential-provider-web-identity": "^3.972.8", "@aws-sdk/types": "^3.973.1", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-LfJfO0ClRAq2WsSnA9JuUsNyIicD2eyputxSlSL0EiMrtxOxELLRG6ZVYDf/a1HCepaYPXeakH4y8D5OLCauag=="], - "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-bi47Zigu3692SJwdBvo8y1dEwE6B61stCwCFnuRWJVTfiM84B+VTSCV661CSWJmIZzmcy7J5J3kWyxL02iHj0w=="], + "@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.8", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-6cg26ffFltxM51OOS8NH7oE41EccaYiNlbd5VgUYwhiGCySLfHoGuGrLm2rMB4zhy+IO5nWIIG0HiodX8zdvHA=="], - "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.1", "", { "dependencies": { "@aws-sdk/client-sso": "3.974.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/token-providers": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-dLZVNhM7wSgVUFsgVYgI5hb5Z/9PUkT46pk/SHrSmUqfx6YDvoV4YcPtaiRqviPpEGGiRtdQMEadyOKIRqulUQ=="], + "@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.8", "", { "dependencies": { "@aws-sdk/client-sso": "3.990.0", "@aws-sdk/core": "^3.973.10", "@aws-sdk/token-providers": "3.990.0", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-35kqmFOVU1n26SNv+U37sM8b2TzG8LyqAcd6iM9gprqxyHEh/8IM3gzN4Jzufs3qM6IrH8e43ryZWYdvfVzzKQ=="], - "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-YMDeYgi0u687Ay0dAq/pFPKuijrlKTgsaB/UATbxCs/FzZfMiG4If5ksywHmmW7MiYUF8VVv+uou3TczvLrN4w=="], + "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.8", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/nested-clients": "3.990.0", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-CZhN1bOc1J3ubQPqbmr5b4KaMJBgdDvYsmEIZuX++wFlzmZsKj1bwkaiTEb5U2V7kXuzLlpF5HJSOM9eY/6nGA=="], - "@aws-sdk/middleware-bucket-endpoint": ["@aws-sdk/middleware-bucket-endpoint@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-arn-parser": "^3.972.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-YVvoitBdE8WOpHqIXvv49efT73F4bJ99XH2bi3Dn3mx7WngI4RwHwn/zF5i0q1Wdi5frGSCNF3vuh+pY817//w=="], + "@aws-sdk/middleware-bucket-endpoint": ["@aws-sdk/middleware-bucket-endpoint@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-arn-parser": "^3.972.2", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-fmbgWYirF67YF1GfD7cg5N6HHQ96EyRNx/rDIrTF277/zTWVuPI2qS/ZHgofwR1NZPe/NWvoppflQY01LrbVLg=="], - "@aws-sdk/middleware-expect-continue": ["@aws-sdk/middleware-expect-continue@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-6lfl2/J/kutzw/RLu1kjbahsz4vrGPysrdxWaw8fkjLYG+6M6AswocIAZFS/LgAVi/IWRwPTx9YC0/NH2wDrSw=="], + "@aws-sdk/middleware-expect-continue": ["@aws-sdk/middleware-expect-continue@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-4msC33RZsXQpUKR5QR4HnvBSNCPLGHmB55oDiROqqgyOc+TOfVu2xgi5goA7ms6MdZLeEh2905UfWMnMMF4mRg=="], - "@aws-sdk/middleware-flexible-checksums": ["@aws-sdk/middleware-flexible-checksums@3.972.1", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@aws-crypto/crc32c": "5.2.0", "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/crc64-nvme": "3.972.0", "@aws-sdk/types": "^3.973.0", "@smithy/is-array-buffer": "^4.2.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-kjVVREpqeUkYQsXr78AcsJbEUlxGH7+H6yS7zkjrnu6HyEVxbdSndkKX6VpKneFOihjCAhIXlk4wf3butDHkNQ=="], + "@aws-sdk/middleware-flexible-checksums": ["@aws-sdk/middleware-flexible-checksums@3.972.8", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@aws-crypto/crc32c": "5.2.0", "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "^3.973.10", "@aws-sdk/crc64-nvme": "3.972.0", "@aws-sdk/types": "^3.973.1", "@smithy/is-array-buffer": "^4.2.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.12", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-Hn6gumcN/3/8Fzo9z7N1pA2PRfE8S+qAqdb4g3MqzXjIOIe+VxD7edO/DKAJ1YH11639EGQIHBz0wdOb5btjtw=="], - "@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-/R82lXLPmZ9JaUGSUdKtBp2k/5xQxvBT3zZWyKiBOhyulFotlfvdlrO8TnqstBimsl4lYEYySDL+W6ldFh6ALg=="], + "@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-aknPTb2M+G3s+0qLCx4Li/qGZH8IIYjugHMv15JTYMe6mgZO8VBpYgeGYsNMGCqCZOcWzuf900jFBG5bopfzmA=="], - "@aws-sdk/middleware-location-constraint": ["@aws-sdk/middleware-location-constraint@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-YisPaCbvBk9gY5aUI8jDMDKXsLZ9Fet0WYj1MviK8tZYMgxBIYHM6l3O/OHaAIujojZvamd9F3haYYYWp5/V3w=="], + "@aws-sdk/middleware-location-constraint": ["@aws-sdk/middleware-location-constraint@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-nIg64CVrsXp67vbK0U1/Is8rik3huS3QkRHn2DRDx4NldrEFMgdkZGI/+cZMKD9k4YOS110Dfu21KZLHrFA/1g=="], - "@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-JGgFl6cHg9G2FHu4lyFIzmFN8KESBiRr84gLC3Aeni0Gt1nKm+KxWLBuha/RPcXxJygGXCcMM4AykkIwxor8RA=="], + "@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-Ftg09xNNRqaz9QNzlfdQWfpqMCJbsQdnZVJP55jfhbKi1+FTWxGuvfPoBhDHIovqWKjqbuiew3HuhxbJ0+OjgA=="], - "@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-taGzNRe8vPHjnliqXIHp9kBgIemLE/xCaRTMH1NH0cncHeaPcjxtnCroAAM9aOlPuKvBe2CpZESyvM1+D8oI7Q=="], + "@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-PY57QhzNuXHnwbJgbWYTrqIDHYSeOlhfYERTAuc16LKZpTZRJUjzBFokp9hF7u1fuGeE3D70ERXzdbMBOqQz7Q=="], - "@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-arn-parser": "^3.972.1", "@smithy/core": "^3.21.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-5f9x9/G+StE8+7wd9EVDF3d+J74xK+WBA3FhZwLSkf3pHFGLKzlmUfxJJE1kkXkbj/j/H+Dh3zL/hrtQE9hNsg=="], + "@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.10", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-arn-parser": "^3.972.2", "@smithy/core": "^3.23.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.12", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-wLkB4bshbBtsAiC2WwlHzOWXu1fx3ftL63fQl0DxEda48Q6B8bcHydZppE3KjEIpPyiNOllByfSnb07cYpIgmw=="], - "@aws-sdk/middleware-ssec": ["@aws-sdk/middleware-ssec@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-fLtRTPd/MxJT2drJKft2GVGKm35PiNEeQ1Dvz1vc/WhhgAteYrp4f1SfSgjgLaYWGMExESJL4bt8Dxqp6tVsog=="], + "@aws-sdk/middleware-ssec": ["@aws-sdk/middleware-ssec@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-dU6kDuULN3o3jEHcjm0c4zWJlY1zWVkjG9NPe9qxYLLpcbdj5kRYBS2DdWYD+1B9f910DezRuws7xDEqKkHQIg=="], - "@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@smithy/core": "^3.21.1", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-d+Exq074wy0X6wvShg/kmZVtkah+28vMuqCtuY3cydg8LUZOJBtbAolCpEJizSyb8mJJZF9BjWaTANXL4OYnkg=="], + "@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.10", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-endpoints": "3.990.0", "@smithy/core": "^3.23.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-bBEL8CAqPQkI91ZM5a9xnFAzedpzH6NYCOtNyLarRAzTUTFN2DKqaC60ugBa7pnU1jSi4mA7WAXBsrod7nJltg=="], - "@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-k3dwdo/vOiHMJc9gMnkPl1BA5aQfTrZbz+8fiDkWrPagqAioZgmo5oiaOaeX0grObfJQKDtcpPFR4iWf8cgl8Q=="], + "@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.990.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.10", "@aws-sdk/middleware-host-header": "^3.972.3", "@aws-sdk/middleware-logger": "^3.972.3", "@aws-sdk/middleware-recursion-detection": "^3.972.3", "@aws-sdk/middleware-user-agent": "^3.972.10", "@aws-sdk/region-config-resolver": "^3.972.3", "@aws-sdk/types": "^3.973.1", "@aws-sdk/util-endpoints": "3.990.0", "@aws-sdk/util-user-agent-browser": "^3.972.3", "@aws-sdk/util-user-agent-node": "^3.972.8", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.23.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.14", "@smithy/middleware-retry": "^4.4.31", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.30", "@smithy/util-defaults-mode-node": "^4.2.33", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-3NA0s66vsy8g7hPh36ZsUgO4SiMyrhwcYvuuNK1PezO52vX3hXDW4pQrC6OQLGKGJV0o6tbEyQtXb/mPs8zg8w=="], - "@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/config-resolver": "^4.4.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-voIY8RORpxLAEgEkYaTFnkaIuRwVBEc+RjVZYcSSllPV+ZEKAacai6kNhJeE3D70Le+JCfvRb52tng/AVHY+jQ=="], + "@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/config-resolver": "^4.4.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-v4J8qYAWfOMcZ4MJUyatntOicTzEMaU7j3OpkRCGGFSL2NgXQ5VbxauIyORA+pxdKZ0qQG2tCQjQjZDlXEC3Ow=="], "@aws-sdk/s3-request-presigner": ["@aws-sdk/s3-request-presigner@3.975.0", "", { "dependencies": { "@aws-sdk/signature-v4-multi-region": "3.972.0", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-format-url": "^3.972.1", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-rqDktHVSB7Ah7XXqr6BWMqDhGXEccp0h1EivaOGED73JjeG/S7taoywJPqi7YkalRb3Ka+LRc7wVoN9wSa4KQA=="], - "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.972.0", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "3.972.0", "@aws-sdk/types": "3.972.0", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-2udiRijmjpN81Pvajje4TsjbXDZNP6K9bYUanBYH8hXa/tZG5qfGCySD+TyX0sgDxCQmEDMg3LaQdfjNHBDEgQ=="], + "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.992.0", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "^3.972.10", "@aws-sdk/types": "^3.973.1", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jWoaM89xH2cYOY6O+PWMa0yqjzKlE61Ehea1hJe34kHg9QvZOkcSA5OT9CNaFXsAvafeAAHBhSE8XlDiNaJFuw=="], - "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.974.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-cBykL0LiccKIgNhGWvQRTPvsBLPZxnmJU3pYxG538jpFX8lQtrCy1L7mmIHNEdxIdIGEPgAEHF8/JQxgBToqUQ=="], + "@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.990.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.10", "@aws-sdk/nested-clients": "3.990.0", "@aws-sdk/types": "^3.973.1", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-L3BtUb2v9XmYgQdfGBzbBtKMXaP5fV973y3Qdxeevs6oUTVXFmi/mV1+LnScA/1wVPJC9/hlK+1o5vbt7cG7EQ=="], - "@aws-sdk/types": ["@aws-sdk/types@3.973.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jYIdB7a7jhRTvyb378nsjyvJh1Si+zVduJ6urMNGpz8RjkmHZ+9vM2H07XaIB2Cfq0GhJRZYOfUCH8uqQhqBkQ=="], + "@aws-sdk/types": ["@aws-sdk/types@3.973.1", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-DwHBiMNOB468JiX6+i34c+THsKHErYUdNQ3HexeXZvVn4zouLjgaS4FejiGSi2HyBuzuyHg7SuOPmjSvoU9NRg=="], - "@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-XnNit6H9PPHhqUXW/usjX6JeJ6Pm8ZNqivTjmNjgWHeOfVpblUc/MTic02UmCNR0jJLPjQ3mBKiMen0tnkNQjQ=="], + "@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-VkykWbqMjlSgBFDyrY3nOSqupMc6ivXuGmvci6Q3NnLq5kC+mKQe2QBZ4nrWRE/jqOxeFP2uYzLtwncYYcvQDg=="], - "@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.972.0", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-6JHsl1V/a1ZW8D8AFfd4R52fwZPnZ5H4U6DS8m/bWT8qad72NvbOFAC7U2cDtFs2TShqUO3TEiX/EJibtY3ijg=="], + "@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.992.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-FHgdMVbTZ2Lu7hEIoGYfkd5UazNSsAgPcupEnh15vsWKFKhuw6w/6tM1k/yNaa7l1wx0Wt1UuK0m+gQ0BJpuvg=="], "@aws-sdk/util-format-url": ["@aws-sdk/util-format-url@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-8wJ4/XOLU/RIYBHsXsIOTR04bNmalC8F2YPMyf3oL8YC750M3Rv5WGywW0Fo07HCv770KXJOzVq03Gyl68moFg=="], "@aws-sdk/util-locate-window": ["@aws-sdk/util-locate-window@3.957.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-nhmgKHnNV9K+i9daumaIz8JTLsIIML9PE/HUks5liyrjUzenjW/aHoc7WJ9/Td/gPZtayxFnXQSJRb/fDlBuJw=="], - "@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-IgF55NFmJX8d9Wql9M0nEpk2eYbuD8G4781FN4/fFgwTXBn86DvlZJuRWDCMcMqZymnBVX7HW9r+3r9ylqfW0w=="], + "@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.3", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-JurOwkRUcXD/5MTDBcqdyQ9eVedtAsZgw5rBwktsPTN7QtPiS2Ld1jkJepNgYoCufz1Wcut9iup7GJDoIHp8Fw=="], - "@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.972.1", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-oIs4JFcADzoZ0c915R83XvK2HltWupxNsXUIuZse2rgk7b97zTpkxaqXiH0h9ylh31qtgo/t8hp4tIqcsMrEbQ=="], + "@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.972.8", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.10", "@aws-sdk/types": "^3.973.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-XJZuT0LWsFCW1C8dEpPAXSa7h6Pb3krr2y//1X0Zidpcl0vmgY5nL/X0JuBZlntpBzaN3+U4hvKjuijyiiR8zw=="], - "@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.1", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" } }, "sha512-6zZGlPOqn7Xb+25MAXGb1JhgvaC5HjZj6GzszuVrnEgbhvzBRFGKYemuHBV4bho+dtqeYKPgaZUv7/e80hIGNg=="], + "@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.4", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.3.4", "tslib": "^2.6.2" } }, "sha512-0zJ05ANfYqI6+rGqj8samZBFod0dPPousBjLEqg8WdxSgbMAkRgLyn81lP215Do0rFJ/17LIXwr7q0yK24mP6Q=="], "@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.2", "", {}, "sha512-C0NBLsIqzDIae8HFw9YIrIBsbc0xTiOtt7fAukGPnqQ/+zZNaq+4jhuccltK0QuWHBnNm/a6kLIRA6GFiM10eg=="], @@ -804,25 +804,25 @@ "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], - "@nx/nx-darwin-arm64": ["@nx/nx-darwin-arm64@22.4.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-hC9XTkYpRXJMpDcUzt/yYBQpyA4IrdUg3m5eVJMPZ8uth1l+KAiv31YQL5I044XO4b3yYVuKW+4vlmS8OCppYQ=="], + "@nx/nx-darwin-arm64": ["@nx/nx-darwin-arm64@22.5.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DuvOwhXPO6l9W7/zM4/BaAbGTIXFyHVcbbCD1c7HfgZ3VfJPmcE7H4+TuQH0cigHHtpg/eGqV100NQbd7N4zwg=="], - "@nx/nx-darwin-x64": ["@nx/nx-darwin-x64@22.4.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-yaQFbLowg42qIUc0wTYZ7K5V3G+CIsbcphoQARG01gfjtfGCNs71yJ9Q8XvKH7IVzq0shlSohVzMPBg9+1Dp4Q=="], + "@nx/nx-darwin-x64": ["@nx/nx-darwin-x64@22.5.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-81Lb7+rp3Qltpgy33Kc1qxk+8IWqZLhqvdLdRFSVV1FN1pPSJDFKyPjCn9oMpRryNPSJ8DgZDpfIaVVyP85rUw=="], - "@nx/nx-freebsd-x64": ["@nx/nx-freebsd-x64@22.4.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-n6Y10jSdPPclMyKi4SSkbri3pHHnWVOQuTgWIAlLUAHAp/t5pAU6ky3BPjxwfqjUehFbvvLYeNEKDFP8vFJXOw=="], + "@nx/nx-freebsd-x64": ["@nx/nx-freebsd-x64@22.5.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-Ig8yQN3lSz9R+Zf3NQWcvEnIzwDX4NSeaFtEliPnC3OHlQXGNXbOUfkExa0U0UUgyxa4rgnCgefmwuc12H9q2Q=="], - "@nx/nx-linux-arm-gnueabihf": ["@nx/nx-linux-arm-gnueabihf@22.4.1", "", { "os": "linux", "cpu": "arm" }, "sha512-1wx5aEM3DWXPhYUprp8EBwmS5KGemB940iylFRtHBOVW/pD4nU9QfWAApAC/wkn+Ag7UQpgIG1xNI8TUhrpEpA=="], + "@nx/nx-linux-arm-gnueabihf": ["@nx/nx-linux-arm-gnueabihf@22.5.1", "", { "os": "linux", "cpu": "arm" }, "sha512-C7tGoLnR9MjKLJsLMF2VsKcDChPiygAsw6dSVgU4B650H7sBWmkEHM/QjvyRvkcZuoQBDamS/eVs/UaJu9wNhA=="], - "@nx/nx-linux-arm64-gnu": ["@nx/nx-linux-arm64-gnu@22.4.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Q8ZYk/fm/y/Tve5Snw8HnasmCqyKkaz0A6OU00muR5PhcZF104PniW2JDwXOa+14AwJd0tcRug3OSd17DYHZnQ=="], + "@nx/nx-linux-arm64-gnu": ["@nx/nx-linux-arm64-gnu@22.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-GNxei+lwhzhrO9m+nNkibgxLhbkYKyFXPSRpOKLwv9VavNzJn5UmLfKJyhjNQPBOSYuNhiVPbU1Ja/qOBcozYw=="], - "@nx/nx-linux-arm64-musl": ["@nx/nx-linux-arm64-musl@22.4.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-73QLboxmFxQz3cur8SUrYNdf01SrfECKs8IYfD6kmJuxI+5Mjvd25NxAakqHQPuZt2MW6wD7V6T9H2lhIiRUZQ=="], + "@nx/nx-linux-arm64-musl": ["@nx/nx-linux-arm64-musl@22.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-VDJtdJP2nCgS8ommbfWFAKjoZCE51VH7tZyIfh8RFI5fxwoB3Pk6d6f6cmNHI/1t98YI3V7Onuf3Y9KBkYtyfQ=="], - "@nx/nx-linux-x64-gnu": ["@nx/nx-linux-x64-gnu@22.4.1", "", { "os": "linux", "cpu": "x64" }, "sha512-jUT+Eh44WwwgVFsAMw8ZhSHOENCB9dUfFfMA1dabzCRzPRHGn1cGNROEBwOzcr69yuwrkCk8MBXKcPTEBpgZiQ=="], + "@nx/nx-linux-x64-gnu": ["@nx/nx-linux-x64-gnu@22.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-BZ/i+KTplEJmE8ZHKgPGD513Zl86DuSGyRAvbDZ7Qf19Tei7Of6vxW+ypvVDIwmDbyXfe13u54M5gDt8iiqFGQ=="], - "@nx/nx-linux-x64-musl": ["@nx/nx-linux-x64-musl@22.4.1", "", { "os": "linux", "cpu": "x64" }, "sha512-gIchvqNK//74oYuqUs96W+I+ZnOHJzGy/RH5sAnW2JexPGxJNEoWIlyHJ/CedJ/h7WGWZFJpu7TXhqlKWeVFLw=="], + "@nx/nx-linux-x64-musl": ["@nx/nx-linux-x64-musl@22.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-e0VdiV6fe88Dbhill2gUjYAD9jMhHjYsafGOPR+/uaGMAYPoI1jKur6uPGY+ik6fvwvDFFl0VT2+HACKVn7RoA=="], - "@nx/nx-win32-arm64-msvc": ["@nx/nx-win32-arm64-msvc@22.4.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-209BtB0PFqrTT8sCehjI7zWznersXjTLEwa/hy4WKKlRbaiepWebYNJWoSfBz0ZOYBGuLX15M4R7t57fM9gySA=="], + "@nx/nx-win32-arm64-msvc": ["@nx/nx-win32-arm64-msvc@22.5.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-3vWZO9y7uHKeyepcU55pE8VQTKGome3mLdicvx1TCoKKl0cA3bTR341Jdo2Zl4Waa2ENk7pGQbLWRQ3ZkaA92A=="], - "@nx/nx-win32-x64-msvc": ["@nx/nx-win32-x64-msvc@22.4.1", "", { "os": "win32", "cpu": "x64" }, "sha512-QRgvgkTBLipoRJGofg5MlzMsWhnjpjQfssuyCSBmm1tjCdatBIDac5l6Z4xaUicPmjLzE3hPfnvX/t+ivRYKpA=="], + "@nx/nx-win32-x64-msvc": ["@nx/nx-win32-x64-msvc@22.5.1", "", { "os": "win32", "cpu": "x64" }, "sha512-4e5LduuhpBx96JgD1J3fHUGCwC+/lL+tvXp3UVtjh/AOdINGsyI+scinT3uaI9vcB5GKBcybTxbBZzwcH50w9g=="], "@octokit/auth-token": ["@octokit/auth-token@6.0.0", "", {}, "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w=="], @@ -954,7 +954,7 @@ "@smithy/config-resolver": ["@smithy/config-resolver@4.4.6", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-qJpzYC64kaj3S0fueiu3kXm8xPrR3PcXDPEgnaNMRn0EjNSZFoFjvbUp0YUDsRhN1CB90EnHJtbxWKevnH99UQ=="], - "@smithy/core": ["@smithy/core@3.21.1", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-NUH8R4O6FkN8HKMojzbGg/5pNjsfTjlMmeFclyPfPaXXUrbr5TzhWgbf7t92wfrpCHRgpjyz7ffASIS3wX28aA=="], + "@smithy/core": ["@smithy/core@3.23.2", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.12", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-HaaH4VbGie4t0+9nY3tNBRSxVTr96wzIqexUa6C2qx3MPePAuz7lIxPxYtt1Wc//SPfJLNoZJzfdt0B6ksj2jA=="], "@smithy/credential-provider-imds": ["@smithy/credential-provider-imds@4.2.8", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-FNT0xHS1c/CPN8upqbMFP83+ul5YgdisfCfkZ86Jh2NSmnqw/AJ6x5pEogVCTVvSm7j9MopRU89bmDelxuDMYw=="], @@ -984,9 +984,9 @@ "@smithy/middleware-content-length": ["@smithy/middleware-content-length@4.2.8", "", { "dependencies": { "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-RO0jeoaYAB1qBRhfVyq0pMgBoUK34YEJxVxyjOWYZiOKOq2yMZ4MnVXMZCUDenpozHue207+9P5ilTV1zeda0A=="], - "@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.11", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-/WqsrycweGGfb9sSzME4CrsuayjJF6BueBmkKlcbeU5q18OhxRrvvKlmfw3tpDsK5ilx2XUJvoukwxHB0nHs/Q=="], + "@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.16", "", { "dependencies": { "@smithy/core": "^3.23.2", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-L5GICFCSsNhbJ5JSKeWFGFy16Q2OhoBizb3X2DrxaJwXSEujVvjG9Jt386dpQn2t7jINglQl0b4K/Su69BdbMA=="], - "@smithy/middleware-retry": ["@smithy/middleware-retry@4.4.27", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/service-error-classification": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-xFUYCGRVsfgiN5EjsJJSzih9+yjStgMTCLANPlf0LVQkPDYCe0hz97qbdTZosFOiYlGBlHYityGRxrQ/hxhfVQ=="], + "@smithy/middleware-retry": ["@smithy/middleware-retry@4.4.33", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/service-error-classification": "^4.2.8", "@smithy/smithy-client": "^4.11.5", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-jLqZOdJhtIL4lnA9hXnAG6GgnJlo1sD3FqsTxm9wSfjviqgWesY/TMBVnT84yr4O0Vfe0jWoXlfFbzsBVph3WA=="], "@smithy/middleware-serde": ["@smithy/middleware-serde@4.2.9", "", { "dependencies": { "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-eMNiej0u/snzDvlqRGSN3Vl0ESn3838+nKyVfF2FKNXFbi4SERYT6PR392D39iczngbqqGG0Jl1DlCnp7tBbXQ=="], @@ -994,7 +994,7 @@ "@smithy/node-config-provider": ["@smithy/node-config-provider@4.3.8", "", { "dependencies": { "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-aFP1ai4lrbVlWjfpAfRSL8KFcnJQYfTl5QxLJXY32vghJrDuFyPZ6LtUL+JEGYiFRG1PfPLHLoxj107ulncLIg=="], - "@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.8", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-q9u+MSbJVIJ1QmJ4+1u+cERXkrhuILCBDsJUBAW1MPE6sFonbCNaegFuwW9ll8kh5UdyY3jOkoOGlc7BesoLpg=="], + "@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.10", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-u4YeUwOWRZaHbWaebvrs3UhwQwj+2VNmcVCwXcYTvPIuVyM7Ex1ftAj+fdbG/P4AkBwLq/+SKn+ydOI4ZJE9PA=="], "@smithy/property-provider": ["@smithy/property-provider@4.2.8", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-EtCTbyIveCKeOXDSWSdze3k612yCPq1YbXsbqX3UHhkOSW8zKsM9NOJG5gTIya0vbY2DIaieG8pKo1rITHYL0w=="], @@ -1010,7 +1010,7 @@ "@smithy/signature-v4": ["@smithy/signature-v4@5.3.8", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-uri-escape": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-6A4vdGj7qKNRF16UIcO8HhHjKW27thsxYci+5r/uVRkdcBEkOEiY8OMPuydLX4QHSrJqGHPJzPRwwVTqbLZJhg=="], - "@smithy/smithy-client": ["@smithy/smithy-client@4.10.12", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-VKO/HKoQ5OrSHW6AJUmEnUKeXI1/5LfCwO9cwyao7CmLvGnZeM1i36Lyful3LK1XU7HwTVieTqO1y2C/6t3qtA=="], + "@smithy/smithy-client": ["@smithy/smithy-client@4.11.5", "", { "dependencies": { "@smithy/core": "^3.23.2", "@smithy/middleware-endpoint": "^4.4.16", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.12", "tslib": "^2.6.2" } }, "sha512-xixwBRqoeP2IUgcAl3U9dvJXc+qJum4lzo3maaJxifsZxKUYLfVfCXvhT4/jD01sRrHg5zjd1cw2Zmjr4/SuKQ=="], "@smithy/types": ["@smithy/types@4.12.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-9YcuJVTOBDjg9LWo23Qp0lTQ3D7fQsQtwle0jVfpbUHy9qBwCEgKuVH4FqFB3VYu0nwdHKiEMA+oXz7oV8X1kw=="], @@ -1026,9 +1026,9 @@ "@smithy/util-config-provider": ["@smithy/util-config-provider@4.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q=="], - "@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.3.26", "", { "dependencies": { "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-vva0dzYUTgn7DdE0uaha10uEdAgmdLnNFowKFjpMm6p2R0XDk5FHPX3CBJLzWQkQXuEprsb0hGz9YwbicNWhjw=="], + "@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.3.32", "", { "dependencies": { "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.11.5", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-092sjYfFMQ/iaPH798LY/OJFBcYu0sSK34Oy9vdixhsU36zlZu8OcYjF3TD4e2ARupyK7xaxPXl+T0VIJTEkkg=="], - "@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.2.29", "", { "dependencies": { "@smithy/config-resolver": "^4.4.6", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-c6D7IUBsZt/aNnTBHMTf+OVh+h/JcxUUgfTcIJaWRe6zhOum1X+pNKSZtZ+7fbOn5I99XVFtmrnXKv8yHHErTQ=="], + "@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.2.35", "", { "dependencies": { "@smithy/config-resolver": "^4.4.6", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.11.5", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-miz/ggz87M8VuM29y7jJZMYkn7+IErM5p5UgKIf8OtqVs/h2bXr1Bt3uTsREsI/4nK8a0PQERbAPsVPVNIsG7Q=="], "@smithy/util-endpoints": ["@smithy/util-endpoints@3.2.8", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-8JaVTn3pBDkhZgHQ8R0epwWt+BqPSLCjdjXXusK1onwJlRuN69fbvSK66aIKKO7SwVFM6x2J2ox5X8pOaWcUEw=="], @@ -1038,7 +1038,7 @@ "@smithy/util-retry": ["@smithy/util-retry@4.2.8", "", { "dependencies": { "@smithy/service-error-classification": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-CfJqwvoRY0kTGe5AkQokpURNCT1u/MkRzMTASWMPPo2hNSnKtF1D45dQl3DE2LKLr4m+PW9mCeBMJr5mCAVThg=="], - "@smithy/util-stream": ["@smithy/util-stream@4.5.10", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jbqemy51UFSZSp2y0ZmRfckmrzuKww95zT9BYMmuJ8v3altGcqjwoV1tzpOwuHaKrwQrCjIzOib499ymr2f98g=="], + "@smithy/util-stream": ["@smithy/util-stream@4.5.12", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.10", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-D8tgkrmhAX/UNeCZbqbEO3uqyghUnEmmoO9YEvRuwxjlkKKUE7FOgCJnqpTlQPe9MApdWPky58mNQQHbnCzoNg=="], "@smithy/util-uri-escape": ["@smithy/util-uri-escape@4.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA=="], @@ -1150,7 +1150,7 @@ "@types/bonjour": ["@types/bonjour@3.5.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-z9fJ5Im06zvUL548KvYNecEVlA7cVDkGUi6kZusb04mpyEFKCIZJvloCcmpmLaIahDpOQGHaHmG6imtPMmPXGQ=="], - "@types/bun": ["@types/bun@1.3.6", "", { "dependencies": { "bun-types": "1.3.6" } }, "sha512-uWCv6FO/8LcpREhenN1d1b6fcspAB+cefwD7uti8C8VffIv0Um08TKMn98FynpTiU38+y2dUO55T11NgDt8VAA=="], + "@types/bun": ["@types/bun@1.3.9", "", { "dependencies": { "bun-types": "1.3.9" } }, "sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw=="], "@types/connect": ["@types/connect@3.4.38", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="], @@ -1252,25 +1252,25 @@ "@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="], - "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.53.1", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.53.1", "@typescript-eslint/type-utils": "8.53.1", "@typescript-eslint/utils": "8.53.1", "@typescript-eslint/visitor-keys": "8.53.1", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.53.1", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-cFYYFZ+oQFi6hUnBTbLRXfTJiaQtYE3t4O692agbBl+2Zy+eqSKWtPjhPXJu1G7j4RLjKgeJPDdq3EqOwmX5Ag=="], + "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.56.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.56.0", "@typescript-eslint/type-utils": "8.56.0", "@typescript-eslint/utils": "8.56.0", "@typescript-eslint/visitor-keys": "8.56.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.56.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-lRyPDLzNCuae71A3t9NEINBiTn7swyOhvUj3MyUOxb8x6g6vPEFoOU+ZRmGMusNC3X3YMhqMIX7i8ShqhT74Pw=="], - "@typescript-eslint/parser": ["@typescript-eslint/parser@8.53.1", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.53.1", "@typescript-eslint/types": "8.53.1", "@typescript-eslint/typescript-estree": "8.53.1", "@typescript-eslint/visitor-keys": "8.53.1", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-nm3cvFN9SqZGXjmw5bZ6cGmvJSyJPn0wU9gHAZZHDnZl2wF9PhHv78Xf06E0MaNk4zLVHL8hb2/c32XvyJOLQg=="], + "@typescript-eslint/parser": ["@typescript-eslint/parser@8.56.0", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.56.0", "@typescript-eslint/types": "8.56.0", "@typescript-eslint/typescript-estree": "8.56.0", "@typescript-eslint/visitor-keys": "8.56.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-IgSWvLobTDOjnaxAfDTIHaECbkNlAlKv2j5SjpB2v7QHKv1FIfjwMy8FsDbVfDX/KjmCmYICcw7uGaXLhtsLNg=="], - "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.53.1", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.53.1", "@typescript-eslint/types": "^8.53.1", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-WYC4FB5Ra0xidsmlPb+1SsnaSKPmS3gsjIARwbEkHkoWloQmuzcfypljaJcR78uyLA1h8sHdWWPHSLDI+MtNog=="], + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.56.0", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.56.0", "@typescript-eslint/types": "^8.56.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-M3rnyL1vIQOMeWxTWIW096/TtVP+8W3p/XnaFflhmcFp+U4zlxUxWj4XwNs6HbDeTtN4yun0GNTTDBw/SvufKg=="], - "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.53.1", "", { "dependencies": { "@typescript-eslint/types": "8.53.1", "@typescript-eslint/visitor-keys": "8.53.1" } }, "sha512-Lu23yw1uJMFY8cUeq7JlrizAgeQvWugNQzJp8C3x8Eo5Jw5Q2ykMdiiTB9vBVOOUBysMzmRRmUfwFrZuI2C4SQ=="], + "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.56.0", "", { "dependencies": { "@typescript-eslint/types": "8.56.0", "@typescript-eslint/visitor-keys": "8.56.0" } }, "sha512-7UiO/XwMHquH+ZzfVCfUNkIXlp/yQjjnlYUyYz7pfvlK3/EyyN6BK+emDmGNyQLBtLGaYrTAI6KOw8tFucWL2w=="], - "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.53.1", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-qfvLXS6F6b1y43pnf0pPbXJ+YoXIC7HKg0UGZ27uMIemKMKA6XH2DTxsEDdpdN29D+vHV07x/pnlPNVLhdhWiA=="], + "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.56.0", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-bSJoIIt4o3lKXD3xmDh9chZcjCz5Lk8xS7Rxn+6l5/pKrDpkCwtQNQQwZ2qRPk7TkUYhrq3WPIHXOXlbXP0itg=="], - "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.53.1", "", { "dependencies": { "@typescript-eslint/types": "8.53.1", "@typescript-eslint/typescript-estree": "8.53.1", "@typescript-eslint/utils": "8.53.1", "debug": "^4.4.3", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-MOrdtNvyhy0rHyv0ENzub1d4wQYKb2NmIqG7qEqPWFW7Mpy2jzFC3pQ2yKDvirZB7jypm5uGjF2Qqs6OIqu47w=="], + "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.56.0", "", { "dependencies": { "@typescript-eslint/types": "8.56.0", "@typescript-eslint/typescript-estree": "8.56.0", "@typescript-eslint/utils": "8.56.0", "debug": "^4.4.3", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-qX2L3HWOU2nuDs6GzglBeuFXviDODreS58tLY/BALPC7iu3Fa+J7EOTwnX9PdNBxUI7Uh0ntP0YWGnxCkXzmfA=="], - "@typescript-eslint/types": ["@typescript-eslint/types@8.53.1", "", {}, "sha512-jr/swrr2aRmUAUjW5/zQHbMaui//vQlsZcJKijZf3M26bnmLj8LyZUpj8/Rd6uzaek06OWsqdofN/Thenm5O8A=="], + "@typescript-eslint/types": ["@typescript-eslint/types@8.56.0", "", {}, "sha512-DBsLPs3GsWhX5HylbP9HNG15U0bnwut55Lx12bHB9MpXxQ+R5GC8MwQe+N1UFXxAeQDvEsEDY6ZYwX03K7Z6HQ=="], - "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.53.1", "", { "dependencies": { "@typescript-eslint/project-service": "8.53.1", "@typescript-eslint/tsconfig-utils": "8.53.1", "@typescript-eslint/types": "8.53.1", "@typescript-eslint/visitor-keys": "8.53.1", "debug": "^4.4.3", "minimatch": "^9.0.5", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-RGlVipGhQAG4GxV1s34O91cxQ/vWiHJTDHbXRr0li2q/BGg3RR/7NM8QDWgkEgrwQYCvmJV9ichIwyoKCQ+DTg=="], + "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.56.0", "", { "dependencies": { "@typescript-eslint/project-service": "8.56.0", "@typescript-eslint/tsconfig-utils": "8.56.0", "@typescript-eslint/types": "8.56.0", "@typescript-eslint/visitor-keys": "8.56.0", "debug": "^4.4.3", "minimatch": "^9.0.5", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.4.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.0.0" } }, "sha512-ex1nTUMWrseMltXUHmR2GAQ4d+WjkZCT4f+4bVsps8QEdh0vlBsaCokKTPlnqBFqqGaxilDNJG7b8dolW2m43Q=="], - "@typescript-eslint/utils": ["@typescript-eslint/utils@8.53.1", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.53.1", "@typescript-eslint/types": "8.53.1", "@typescript-eslint/typescript-estree": "8.53.1" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-c4bMvGVWW4hv6JmDUEG7fSYlWOl3II2I4ylt0NM+seinYQlZMQIaKaXIIVJWt9Ofh6whrpM+EdDQXKXjNovvrg=="], + "@typescript-eslint/utils": ["@typescript-eslint/utils@8.56.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.56.0", "@typescript-eslint/types": "8.56.0", "@typescript-eslint/typescript-estree": "8.56.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-RZ3Qsmi2nFGsS+n+kjLAYDPVlrzf7UhTffrDIKr+h2yzAlYP/y5ZulU0yeDEPItos2Ph46JAL5P/On3pe7kDIQ=="], - "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.53.1", "", { "dependencies": { "@typescript-eslint/types": "8.53.1", "eslint-visitor-keys": "^4.2.1" } }, "sha512-oy+wV7xDKFPRyNggmXuZQSBzvoLnpmJs+GhzRhPjrxl2b/jIlyjVokzm47CZCDUdXKr2zd7ZLodPfOBpOPyPlg=="], + "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.56.0", "", { "dependencies": { "@typescript-eslint/types": "8.56.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-q+SL+b+05Ud6LbEE35qe4A99P+htKTKVbyiNEe45eCbJFyh/HVK9QXwlrbz+Q4L8SOW4roxSVwXYj4DMBT7Ieg=="], "@ungap/structured-clone": ["@ungap/structured-clone@1.2.1", "", {}, "sha512-fEzPV3hSkSMltkw152tJKNARhOupqbH96MZWyRjNaYZOMIzbrTeQDG+MTc6Mr2pgzFQzFxAfmhGDNP5QK++2ZA=="], @@ -1330,7 +1330,7 @@ "aggregate-error": ["aggregate-error@3.1.0", "", { "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" } }, "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA=="], - "ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], "ajv-formats": ["ajv-formats@2.1.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="], @@ -1394,6 +1394,8 @@ "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], + "async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="], + "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], "at-least-node": ["at-least-node@1.0.0", "", {}, "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg=="], @@ -1472,7 +1474,7 @@ "bun-plugin-tailwind": ["bun-plugin-tailwind@0.1.2", "", { "peerDependencies": { "bun": ">=1.0.0" } }, "sha512-41jNC1tZRSK3s1o7pTNrLuQG8kL/0vR/JgiTmZAJ1eHwe0w5j6HFPKeqEk0WAD13jfrUC7+ULuewFBBCoADPpg=="], - "bun-types": ["bun-types@1.3.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-OlFwHcnNV99r//9v5IIOgQ9Uk37gZqrNMCcqEaExdkVq3Avwqok1bJFmvGMCkCE0FqzdY8VMOZpfpR3lwI+CsQ=="], + "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], "bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="], @@ -1656,7 +1658,7 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], - "cypress": ["cypress@15.9.0", "", { "dependencies": { "@cypress/request": "^3.0.10", "@cypress/xvfb": "^1.2.4", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", "@types/tmp": "^0.2.3", "arch": "^2.2.0", "blob-util": "^2.0.2", "bluebird": "^3.7.2", "buffer": "^5.7.1", "cachedir": "^2.3.0", "chalk": "^4.1.0", "ci-info": "^4.1.0", "cli-cursor": "^3.1.0", "cli-table3": "0.6.1", "commander": "^6.2.1", "common-tags": "^1.8.0", "dayjs": "^1.10.4", "debug": "^4.3.4", "enquirer": "^2.3.6", "eventemitter2": "6.4.7", "execa": "4.1.0", "executable": "^4.1.1", "extract-zip": "2.0.1", "figures": "^3.2.0", "fs-extra": "^9.1.0", "hasha": "5.2.2", "is-installed-globally": "~0.4.0", "listr2": "^3.8.3", "lodash": "^4.17.21", "log-symbols": "^4.0.0", "minimist": "^1.2.8", "ospath": "^1.2.2", "pretty-bytes": "^5.6.0", "process": "^0.11.10", "proxy-from-env": "1.0.0", "request-progress": "^3.0.0", "supports-color": "^8.1.1", "systeminformation": "^5.27.14", "tmp": "~0.2.4", "tree-kill": "1.2.2", "untildify": "^4.0.0", "yauzl": "^2.10.0" }, "bin": { "cypress": "bin/cypress" } }, "sha512-Ks6Bdilz3TtkLZtTQyqYaqtL/WT3X3APKaSLhTV96TmTyudzSjc6EJsJCHmBb7DxO+3R12q3Jkbjgm/iPgmwfg=="], + "cypress": ["cypress@15.10.0", "", { "dependencies": { "@cypress/request": "^3.0.10", "@cypress/xvfb": "^1.2.4", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", "@types/tmp": "^0.2.3", "arch": "^2.2.0", "blob-util": "^2.0.2", "bluebird": "^3.7.2", "buffer": "^5.7.1", "cachedir": "^2.3.0", "chalk": "^4.1.0", "ci-info": "^4.1.0", "cli-cursor": "^3.1.0", "cli-table3": "0.6.1", "commander": "^6.2.1", "common-tags": "^1.8.0", "dayjs": "^1.10.4", "debug": "^4.3.4", "enquirer": "^2.3.6", "eventemitter2": "6.4.7", "execa": "4.1.0", "executable": "^4.1.1", "extract-zip": "2.0.1", "figures": "^3.2.0", "fs-extra": "^9.1.0", "hasha": "5.2.2", "is-installed-globally": "~0.4.0", "listr2": "^3.8.3", "lodash": "^4.17.23", "log-symbols": "^4.0.0", "minimist": "^1.2.8", "ospath": "^1.2.2", "pretty-bytes": "^5.6.0", "process": "^0.11.10", "proxy-from-env": "1.0.0", "request-progress": "^3.0.0", "supports-color": "^8.1.1", "systeminformation": "^5.27.14", "tmp": "~0.2.4", "tree-kill": "1.2.2", "untildify": "^4.0.0", "yauzl": "^2.10.0" }, "bin": { "cypress": "bin/cypress" } }, "sha512-OtUh7OMrfEjKoXydlAD1CfG2BvKxIqgWGY4/RMjrqQ3BKGBo5JFKoYNH+Tpcj4xKxWH4XK0Xri+9y8WkxhYbqQ=="], "dashdash": ["dashdash@1.14.1", "", { "dependencies": { "assert-plus": "^1.0.0" } }, "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g=="], @@ -1670,7 +1672,7 @@ "debounce": ["debounce@1.2.1", "", {}, "sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug=="], - "debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decode-named-character-reference": ["decode-named-character-reference@1.0.2", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg=="], @@ -1750,6 +1752,8 @@ "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], + "electron-to-chromium": ["electron-to-chromium@1.5.84", "", {}, "sha512-I+DQ8xgafao9Ha6y0qjHHvpZ9OfyA1qKlkHkjywxzniORU2awxyz7f/iVJcULmrF2yrM3nHQf+iDjJtbbexd/g=="], "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], @@ -1882,7 +1886,7 @@ "fast-uri": ["fast-uri@3.0.6", "", {}, "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw=="], - "fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], + "fast-xml-parser": ["fast-xml-parser@5.3.4", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-EFd6afGmXlCx8H8WTZHhAoDaWaGyuIBoZJ2mknrNxug+aZKjkp0a0dlars9Izl+jF+7Gu1/5f/2h68cQpe0IiA=="], "fastq": ["fastq@1.18.0", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw=="], @@ -1904,6 +1908,8 @@ "file-type": ["file-type@16.5.4", "", { "dependencies": { "readable-web-to-node-stream": "^3.0.0", "strtok3": "^6.2.4", "token-types": "^4.1.1" } }, "sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw=="], + "filelist": ["filelist@1.0.4", "", { "dependencies": { "minimatch": "^5.0.1" } }, "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q=="], + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], "finalhandler": ["finalhandler@1.3.1", "", { "dependencies": { "debug": "2.6.9", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "on-finished": "2.4.1", "parseurl": "~1.3.3", "statuses": "2.0.1", "unpipe": "~1.0.0" } }, "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ=="], @@ -1976,7 +1982,7 @@ "github-slugger": ["github-slugger@1.5.0", "", {}, "sha512-wIh+gKBI9Nshz2o46B0B3f5k/W+WI9ZAv6y5Dn5WJ5SK1t0TnDimB4WE5rmTD05ZAIn8HALCZVmCsvj0w0v0lw=="], - "glob": ["glob@13.0.0", "", { "dependencies": { "minimatch": "^10.1.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA=="], + "glob": ["glob@13.0.5", "", { "dependencies": { "minimatch": "^10.2.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-BzXxZg24Ibra1pbQ/zE7Kys4Ua1ks7Bn6pKLkVPZ9FZe4JQS6/Q7ef3LG1H+k7lUf5l4T3PLSyYyYJVYUvfgTw=="], "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], @@ -2224,6 +2230,8 @@ "jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="], + "jake": ["jake@10.9.4", "", { "dependencies": { "async": "^3.2.6", "filelist": "^1.0.4", "picocolors": "^1.1.1" }, "bin": { "jake": "bin/cli.js" } }, "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA=="], + "jest-diff": ["jest-diff@30.1.2", "", { "dependencies": { "@jest/diff-sequences": "30.0.1", "@jest/get-type": "30.1.0", "chalk": "^4.1.2", "pretty-format": "30.0.5" } }, "sha512-4+prq+9J61mOVXCa4Qp8ZjavdxzrWQXrI80GNxP8f4tkI2syPuPrJgdRPZRrfUTRvIoUwcmNLbqEJy9W800+NQ=="], "jest-util": ["jest-util@29.7.0", "", { "dependencies": { "@jest/types": "^29.6.3", "@types/node": "*", "chalk": "^4.0.0", "ci-info": "^3.2.0", "graceful-fs": "^4.2.9", "picomatch": "^2.2.3" } }, "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA=="], @@ -2524,7 +2532,7 @@ "null-loader": ["null-loader@4.0.1", "", { "dependencies": { "loader-utils": "^2.0.0", "schema-utils": "^3.0.0" }, "peerDependencies": { "webpack": "^4.0.0 || ^5.0.0" } }, "sha512-pxqVbi4U6N26lq+LmgIbB5XATP0VdZKOG25DhHi8btMmJJefGArFyDg1yc4U3hWCJbMqSrw0qyrz1UQX+qYXqg=="], - "nx": ["nx@22.4.1", "", { "dependencies": { "@napi-rs/wasm-runtime": "0.2.4", "@yarnpkg/lockfile": "^1.1.0", "@yarnpkg/parsers": "3.0.2", "@zkochan/js-yaml": "0.0.7", "axios": "^1.12.0", "chalk": "^4.1.0", "cli-cursor": "3.1.0", "cli-spinners": "2.6.1", "cliui": "^8.0.1", "dotenv": "~16.4.5", "dotenv-expand": "~11.0.6", "enquirer": "~2.3.6", "figures": "3.2.0", "flat": "^5.0.2", "front-matter": "^4.0.2", "ignore": "^7.0.5", "jest-diff": "^30.0.2", "jsonc-parser": "3.2.0", "lines-and-columns": "2.0.3", "minimatch": "10.1.1", "node-machine-id": "1.1.12", "npm-run-path": "^4.0.1", "open": "^8.4.0", "ora": "5.3.0", "resolve.exports": "2.0.3", "semver": "^7.6.3", "string-width": "^4.2.3", "tar-stream": "~2.2.0", "tmp": "~0.2.1", "tree-kill": "^1.2.2", "tsconfig-paths": "^4.1.2", "tslib": "^2.3.0", "yaml": "^2.6.0", "yargs": "^17.6.2", "yargs-parser": "21.1.1" }, "optionalDependencies": { "@nx/nx-darwin-arm64": "22.4.1", "@nx/nx-darwin-x64": "22.4.1", "@nx/nx-freebsd-x64": "22.4.1", "@nx/nx-linux-arm-gnueabihf": "22.4.1", "@nx/nx-linux-arm64-gnu": "22.4.1", "@nx/nx-linux-arm64-musl": "22.4.1", "@nx/nx-linux-x64-gnu": "22.4.1", "@nx/nx-linux-x64-musl": "22.4.1", "@nx/nx-win32-arm64-msvc": "22.4.1", "@nx/nx-win32-x64-msvc": "22.4.1" }, "peerDependencies": { "@swc-node/register": "^1.8.0", "@swc/core": "^1.3.85" }, "optionalPeers": ["@swc-node/register", "@swc/core"], "bin": { "nx": "bin/nx.js", "nx-cloud": "bin/nx-cloud.js" } }, "sha512-SSzG5sAKsvQL4Heva65/Y1ABs3HqrzIJhneba9+5qBVkhw7T2mcMjZB421UDR9akTnDB3uunDnf3NKMKpTcB0A=="], + "nx": ["nx@22.5.1", "", { "dependencies": { "@napi-rs/wasm-runtime": "0.2.4", "@yarnpkg/lockfile": "^1.1.0", "@yarnpkg/parsers": "3.0.2", "@zkochan/js-yaml": "0.0.7", "axios": "^1.12.0", "cli-cursor": "3.1.0", "cli-spinners": "2.6.1", "cliui": "^8.0.1", "dotenv": "~16.4.5", "dotenv-expand": "~11.0.6", "ejs": "^3.1.7", "enquirer": "~2.3.6", "figures": "3.2.0", "flat": "^5.0.2", "front-matter": "^4.0.2", "ignore": "^7.0.5", "jest-diff": "^30.0.2", "jsonc-parser": "3.2.0", "lines-and-columns": "2.0.3", "minimatch": "10.1.1", "node-machine-id": "1.1.12", "npm-run-path": "^4.0.1", "open": "^8.4.0", "ora": "5.3.0", "picocolors": "^1.1.0", "resolve.exports": "2.0.3", "semver": "^7.6.3", "string-width": "^4.2.3", "tar-stream": "~2.2.0", "tmp": "~0.2.1", "tree-kill": "^1.2.2", "tsconfig-paths": "^4.1.2", "tslib": "^2.3.0", "yaml": "^2.6.0", "yargs": "^17.6.2", "yargs-parser": "21.1.1" }, "optionalDependencies": { "@nx/nx-darwin-arm64": "22.5.1", "@nx/nx-darwin-x64": "22.5.1", "@nx/nx-freebsd-x64": "22.5.1", "@nx/nx-linux-arm-gnueabihf": "22.5.1", "@nx/nx-linux-arm64-gnu": "22.5.1", "@nx/nx-linux-arm64-musl": "22.5.1", "@nx/nx-linux-x64-gnu": "22.5.1", "@nx/nx-linux-x64-musl": "22.5.1", "@nx/nx-win32-arm64-msvc": "22.5.1", "@nx/nx-win32-x64-msvc": "22.5.1" }, "peerDependencies": { "@swc-node/register": "1.11.1", "@swc/core": "1.15.8" }, "optionalPeers": ["@swc-node/register", "@swc/core"], "bin": { "nx": "bin/nx.js", "nx-cloud": "bin/nx-cloud.js" } }, "sha512-KIQqOSdoshkav9JuoH/+Vp42niA5MTRtACupe+q8CaB7bHiLsWr5nctQVC7ul3NauAmsoqNWH7t5CIi8KgrPIQ=="], "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], @@ -3226,7 +3234,7 @@ "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "typescript-eslint": ["typescript-eslint@8.53.1", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.53.1", "@typescript-eslint/parser": "8.53.1", "@typescript-eslint/typescript-estree": "8.53.1", "@typescript-eslint/utils": "8.53.1" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-gB+EVQfP5RDElh9ittfXlhZJdjSU4jUSTyE2+ia8CYyNvet4ElfaLlAIqDvQV9JPknKx0jQH1racTYe/4LaLSg=="], + "typescript-eslint": ["typescript-eslint@8.56.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.56.0", "@typescript-eslint/parser": "8.56.0", "@typescript-eslint/typescript-estree": "8.56.0", "@typescript-eslint/utils": "8.56.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.0.0" } }, "sha512-c7toRLrotJ9oixgdW7liukZpsnq5CZ7PuKztubGYlNppuTqhIoWfhgHo/7EU0v06gS2l/x0i2NEFK1qMIf0rIg=="], "ufo": ["ufo@1.6.1", "", {}, "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA=="], @@ -3414,14 +3422,26 @@ "@aws-crypto/util/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.0", "", { "dependencies": { "@aws-sdk/core": "3.972.0", "@aws-sdk/types": "3.972.0", "@aws-sdk/util-arn-parser": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-0bcKFXWx+NZ7tIlOo7KjQ+O2rydiHdIQahrq+fN6k9Osky29v17guy68urUKfhTobR6iY6KvxkroFWaFtTgS5w=="], + "@aws-sdk/client-sso/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.990.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-kVwtDc9LNI3tQZHEMNbkLIOpeDK8sRSTuT8eMnzGY+O+JImPisfSTjdh+jw9OTznu+MYZjQsv0258sazVKunYg=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/types": ["@aws-sdk/types@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="], + "@aws-sdk/middleware-user-agent/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.990.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-kVwtDc9LNI3tQZHEMNbkLIOpeDK8sRSTuT8eMnzGY+O+JImPisfSTjdh+jw9OTznu+MYZjQsv0258sazVKunYg=="], - "@aws-sdk/util-endpoints/@aws-sdk/types": ["@aws-sdk/types@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="], + "@aws-sdk/nested-clients/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.990.0", "", { "dependencies": { "@aws-sdk/types": "^3.973.1", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-kVwtDc9LNI3tQZHEMNbkLIOpeDK8sRSTuT8eMnzGY+O+JImPisfSTjdh+jw9OTznu+MYZjQsv0258sazVKunYg=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.972.0", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "3.972.0", "@aws-sdk/types": "3.972.0", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-2udiRijmjpN81Pvajje4TsjbXDZNP6K9bYUanBYH8hXa/tZG5qfGCySD+TyX0sgDxCQmEDMg3LaQdfjNHBDEgQ=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/types": ["@aws-sdk/types@3.973.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jYIdB7a7jhRTvyb378nsjyvJh1Si+zVduJ6urMNGpz8RjkmHZ+9vM2H07XaIB2Cfq0GhJRZYOfUCH8uqQhqBkQ=="], + + "@aws-sdk/s3-request-presigner/@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.11", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-/WqsrycweGGfb9sSzME4CrsuayjJF6BueBmkKlcbeU5q18OhxRrvvKlmfw3tpDsK5ilx2XUJvoukwxHB0nHs/Q=="], + + "@aws-sdk/s3-request-presigner/@smithy/smithy-client": ["@smithy/smithy-client@4.10.12", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-VKO/HKoQ5OrSHW6AJUmEnUKeXI1/5LfCwO9cwyao7CmLvGnZeM1i36Lyful3LK1XU7HwTVieTqO1y2C/6t3qtA=="], + + "@aws-sdk/util-format-url/@aws-sdk/types": ["@aws-sdk/types@3.973.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jYIdB7a7jhRTvyb378nsjyvJh1Si+zVduJ6urMNGpz8RjkmHZ+9vM2H07XaIB2Cfq0GhJRZYOfUCH8uqQhqBkQ=="], "@babel/core/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], + "@babel/core/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], "@babel/helper-annotate-as-pure/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], @@ -3438,6 +3458,8 @@ "@babel/helper-define-polyfill-provider/@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.26.5", "", { "dependencies": { "@babel/compat-data": "^7.26.5", "@babel/helper-validator-option": "^7.25.9", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA=="], + "@babel/helper-define-polyfill-provider/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-define-polyfill-provider/resolve": ["resolve@1.22.10", "", { "dependencies": { "is-core-module": "^2.16.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" } }, "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w=="], "@babel/helper-member-expression-to-functions/@babel/traverse": ["@babel/traverse@7.26.5", "", { "dependencies": { "@babel/code-frame": "^7.26.2", "@babel/generator": "^7.26.5", "@babel/parser": "^7.26.5", "@babel/template": "^7.25.9", "@babel/types": "^7.26.5", "debug": "^4.3.1", "globals": "^11.1.0" } }, "sha512-rkOSPOw+AXbgtwUga3U4u8RpoK9FEFWBNAlTpcnkLFjL5CT+oyHNuUUC/xx6XefEJ16r38r8Bc/lfp6rYuHeJQ=="], @@ -3508,6 +3530,8 @@ "@babel/traverse/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], + "@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.27.1", "", {}, "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow=="], @@ -3584,8 +3608,12 @@ "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + "@eslint/config-array/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@eslint/eslintrc/ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="], + "@eslint/eslintrc/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@eslint/eslintrc/espree": ["espree@10.3.0", "", { "dependencies": { "acorn": "^8.14.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.0" } }, "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg=="], "@humanfs/node/@humanwhocodes/retry": ["@humanwhocodes/retry@0.3.1", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="], @@ -3674,32 +3702,32 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="], - "@typescript-eslint/parser/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "@typescript-eslint/project-service/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "@typescript-eslint/type-utils/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - - "@typescript-eslint/typescript-estree/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], - "@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], "@typescript-eslint/typescript-estree/semver": ["semver@7.7.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q=="], "@typescript-eslint/utils/@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.9.1", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ=="], + "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.0", "", {}, "sha512-A0XeIi7CXU7nPlfHS9loMYEKxUaONu/hTEzHTGba9Huu94Cq1hPivf+DE5erJozZOky0LfvXAyrV/tcswpLI0Q=="], + "@yarnpkg/parsers/js-yaml": ["js-yaml@3.14.1", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g=="], "accepts/negotiator": ["negotiator@0.6.3", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="], "acorn-walk/acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="], + "ajv-formats/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "ajv-keywords/ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="], "ansi-escapes/type-fest": ["type-fest@0.21.3", "", {}, "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w=="], "anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], + "app/@aws-sdk/client-s3": ["@aws-sdk/client-s3@3.975.0", "", { "dependencies": { "@aws-crypto/sha1-browser": "5.2.0", "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.1", "@aws-sdk/credential-provider-node": "^3.972.1", "@aws-sdk/middleware-bucket-endpoint": "^3.972.1", "@aws-sdk/middleware-expect-continue": "^3.972.1", "@aws-sdk/middleware-flexible-checksums": "^3.972.1", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-location-constraint": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-sdk-s3": "^3.972.2", "@aws-sdk/middleware-ssec": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.2", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/signature-v4-multi-region": "3.972.0", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.1", "@smithy/eventstream-serde-browser": "^4.2.8", "@smithy/eventstream-serde-config-resolver": "^4.3.8", "@smithy/eventstream-serde-node": "^4.2.8", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-blob-browser": "^4.2.9", "@smithy/hash-node": "^4.2.8", "@smithy/hash-stream-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/md5-js": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/middleware-retry": "^4.4.27", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.26", "@smithy/util-defaults-mode-node": "^4.2.29", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/util-waiter": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-aF1M/iMD29BPcpxjqoym0YFa4WR9Xie1/IhVumwOGH6TB45DaqYO7vLwantDBcYNRn/cZH6DFHksO7RmwTFBhw=="], + + "app/@types/bun": ["@types/bun@1.3.6", "", { "dependencies": { "bun-types": "1.3.6" } }, "sha512-uWCv6FO/8LcpREhenN1d1b6fcspAB+cefwD7uti8C8VffIv0Um08TKMn98FynpTiU38+y2dUO55T11NgDt8VAA=="], + "autoprefixer/browserslist": ["browserslist@4.25.1", "", { "dependencies": { "caniuse-lite": "^1.0.30001726", "electron-to-chromium": "^1.5.173", "node-releases": "^2.0.19", "update-browserslist-db": "^1.1.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-KGj0KoOMXLpSNkkEI6Z6mShmQy0bc1I+T7K9N81k4WWMrfz+6fQ6es80B/YLAeRoKvjYE1YSHHOW1qe9xIVzHw=="], "autoprefixer/caniuse-lite": ["caniuse-lite@1.0.30001726", "", {}, "sha512-VQAUIUzBiZ/UnlM28fSp2CRF3ivUn1BWEvxMcVTNwpw91Py1pGbPIyIKtd+tzct9C3ouceCVdGAXxZOpZAsgdw=="], @@ -3758,16 +3786,24 @@ "csso/css-tree": ["css-tree@2.2.1", "", { "dependencies": { "mdn-data": "2.0.28", "source-map-js": "^1.0.1" } }, "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA=="], - "cypress/lodash": ["lodash@4.17.21", "", {}, "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="], - "decompress-response/mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="], + "detect-port/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + + "docs/@types/react": ["@types/react@19.2.14", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="], + + "docs/react": ["react@19.2.4", "", {}, "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ=="], + + "docs/react-dom": ["react-dom@19.2.4", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="], + "dot-prop/is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], "esast-util-from-js/acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="], "eslint/ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="], + "eslint/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "estree-util-attach-comments/@types/estree": ["@types/estree@1.0.6", "", {}, "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="], "estree-util-scope/@types/estree": ["@types/estree@1.0.6", "", {}, "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="], @@ -3790,10 +3826,14 @@ "express/range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="], + "extract-zip/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], "figures/escape-string-regexp": ["escape-string-regexp@1.0.5", "", {}, "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg=="], + "filelist/minimatch": ["minimatch@5.1.6", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g=="], + "finalhandler/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "fix-dts-default-cjs-exports/rollup": ["rollup@4.34.9", "", { "dependencies": { "@types/estree": "1.0.6" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.34.9", "@rollup/rollup-android-arm64": "4.34.9", "@rollup/rollup-darwin-arm64": "4.34.9", "@rollup/rollup-darwin-x64": "4.34.9", "@rollup/rollup-freebsd-arm64": "4.34.9", "@rollup/rollup-freebsd-x64": "4.34.9", "@rollup/rollup-linux-arm-gnueabihf": "4.34.9", "@rollup/rollup-linux-arm-musleabihf": "4.34.9", "@rollup/rollup-linux-arm64-gnu": "4.34.9", "@rollup/rollup-linux-arm64-musl": "4.34.9", "@rollup/rollup-linux-loongarch64-gnu": "4.34.9", "@rollup/rollup-linux-powerpc64le-gnu": "4.34.9", "@rollup/rollup-linux-riscv64-gnu": "4.34.9", "@rollup/rollup-linux-s390x-gnu": "4.34.9", "@rollup/rollup-linux-x64-gnu": "4.34.9", "@rollup/rollup-linux-x64-musl": "4.34.9", "@rollup/rollup-win32-arm64-msvc": "4.34.9", "@rollup/rollup-win32-ia32-msvc": "4.34.9", "@rollup/rollup-win32-x64-msvc": "4.34.9", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-nF5XYqWWp9hx/LrpC8sZvvvmq0TeTjQgaZHYmAgwysT9nh8sWnZhBnM8ZyVbbJFIQBLwHDNoMqsBZBbUo4U8sQ=="], @@ -3802,7 +3842,7 @@ "front-matter/js-yaml": ["js-yaml@3.14.1", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g=="], - "glob/minimatch": ["minimatch@10.1.1", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ=="], + "glob/minimatch": ["minimatch@10.2.1", "", { "dependencies": { "brace-expansion": "^5.0.2" } }, "sha512-MClCe8IL5nRRmawL6ib/eT4oLyeKMGCghibcDWK+J0hh0Q8kqSdia6BvbRMVk6mPa6WqUa5uR2oxt6C5jd533A=="], "got/@sindresorhus/is": ["@sindresorhus/is@5.6.0", "", {}, "sha512-TV7t8GKYaJWsn00tFDqBw8+Uqmr8A0fRU1tvTQhyZzGv0sJCGRQL3JGMI3ucuKo3XIZdUP+Lx7/gh2t3lewy7g=="], @@ -3852,6 +3892,8 @@ "mdast-util-gfm-table/markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="], + "micromark/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "micromark/micromark-factory-space": ["micromark-factory-space@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg=="], "micromark/micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], @@ -4078,6 +4120,10 @@ "source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + "spdy/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + + "spdy-transport/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "stylehacks/postcss-selector-parser": ["postcss-selector-parser@6.1.2", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg=="], "sucrase/commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], @@ -4100,6 +4146,8 @@ "terser-webpack-plugin/schema-utils": ["schema-utils@4.3.0", "", { "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", "ajv-formats": "^2.1.1", "ajv-keywords": "^5.1.0" } }, "sha512-Gf9qqc58SpCA/xdziiHz35F4GNIWYWZrEshUc/G/r5BnLph6xpKuLeoJoQuj5WfBIx/eQLf+hmVPYHaxJu7V2g=="], + "tsup/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "update-notifier/boxen": ["boxen@7.1.1", "", { "dependencies": { "ansi-align": "^3.0.1", "camelcase": "^7.0.1", "chalk": "^5.2.0", "cli-boxes": "^3.0.0", "string-width": "^5.1.2", "type-fest": "^2.13.0", "widest-line": "^4.0.1", "wrap-ansi": "^8.1.0" } }, "sha512-2hCgjEmP8YLWQ130n2FerGv7rYpfBmnmp9Uy2Le1vge6X3gZIfSmEzP5QTDElFxcvVcXlEn8Aq6MU/PZygIOog=="], "update-notifier/chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="], @@ -4152,13 +4200,15 @@ "@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core": ["@aws-sdk/core@3.972.0", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@aws-sdk/xml-builder": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-nEeUW2M9F+xdIaD98F5MBcQ4ITtykj3yKbgFZ6J0JtL3bq+Z90szQ6Yy8H/BLPYXTs3V4n9ifnBo8cprRDiE6A=="], + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.0", "", { "dependencies": { "@aws-sdk/core": "3.972.0", "@aws-sdk/types": "3.972.0", "@aws-sdk/util-arn-parser": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-0bcKFXWx+NZ7tIlOo7KjQ+O2rydiHdIQahrq+fN6k9Osky29v17guy68urUKfhTobR6iY6KvxkroFWaFtTgS5w=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/types": ["@aws-sdk/types@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-RM5Mmo/KJ593iMSrALlHEOcc9YOIyOsDmS5x2NLOMdEmzv1o00fcpAkCQ02IGu1eFneBFT7uX0Mpag0HI+Cz2g=="], + "@aws-sdk/s3-request-presigner/@smithy/middleware-endpoint/@smithy/core": ["@smithy/core@3.21.1", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-NUH8R4O6FkN8HKMojzbGg/5pNjsfTjlMmeFclyPfPaXXUrbr5TzhWgbf7t92wfrpCHRgpjyz7ffASIS3wX28aA=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/core": ["@smithy/core@3.21.0", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-bg2TfzgsERyETAxc/Ims/eJX8eAnIeTi4r4LHpMpfF/2NyO6RsWis0rjKcCPaGksljmOb23BZRiCeT/3NvwkXw=="], + "@aws-sdk/s3-request-presigner/@smithy/smithy-client/@smithy/core": ["@smithy/core@3.21.1", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-NUH8R4O6FkN8HKMojzbGg/5pNjsfTjlMmeFclyPfPaXXUrbr5TzhWgbf7t92wfrpCHRgpjyz7ffASIS3wX28aA=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client": ["@smithy/smithy-client@4.10.11", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-6o804SCyHGMXAb5mFJ+iTy9kVKv7F91a9szN0J+9X6p8A0NrdpUxdaC57aye2ipQkP2C4IAqETEpGZ0Zj77Haw=="], + "@aws-sdk/s3-request-presigner/@smithy/smithy-client/@smithy/util-stream": ["@smithy/util-stream@4.5.10", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jbqemy51UFSZSp2y0ZmRfckmrzuKww95zT9BYMmuJ8v3altGcqjwoV1tzpOwuHaKrwQrCjIzOib499ymr2f98g=="], "@babel/core/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.27.1", "", {}, "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow=="], @@ -4178,6 +4228,8 @@ "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-define-polyfill-provider/@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], @@ -4188,6 +4240,8 @@ "@babel/helper-member-expression-to-functions/@babel/traverse/@babel/template": ["@babel/template@7.25.9", "", { "dependencies": { "@babel/code-frame": "^7.25.9", "@babel/parser": "^7.25.9", "@babel/types": "^7.25.9" } }, "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-member-expression-to-functions/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-member-expression-to-functions/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], @@ -4198,6 +4252,8 @@ "@babel/helper-module-imports/@babel/traverse/@babel/template": ["@babel/template@7.25.9", "", { "dependencies": { "@babel/code-frame": "^7.25.9", "@babel/parser": "^7.25.9", "@babel/types": "^7.25.9" } }, "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg=="], + "@babel/helper-module-imports/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-module-imports/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-module-imports/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], @@ -4212,6 +4268,8 @@ "@babel/helper-remap-async-to-generator/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-remap-async-to-generator/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-replace-supers/@babel/traverse/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4222,6 +4280,8 @@ "@babel/helper-replace-supers/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/helper-replace-supers/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-replace-supers/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4230,6 +4290,8 @@ "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/@babel/template": ["@babel/template@7.25.9", "", { "dependencies": { "@babel/code-frame": "^7.25.9", "@babel/parser": "^7.25.9", "@babel/types": "^7.25.9" } }, "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-skip-transparent-expression-wrappers/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-skip-transparent-expression-wrappers/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], @@ -4240,6 +4302,8 @@ "@babel/helper-wrap-function/@babel/traverse/@babel/parser": ["@babel/parser@7.26.5", "", { "dependencies": { "@babel/types": "^7.26.5" }, "bin": "./bin/babel-parser.js" }, "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw=="], + "@babel/helper-wrap-function/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/helper-wrap-function/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/helper-wrap-function/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], @@ -4252,6 +4316,8 @@ "@babel/plugin-bugfix-firefox-class-in-computed-class-key/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-bugfix-firefox-class-in-computed-class-key/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-bugfix-firefox-class-in-computed-class-key/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/@babel/traverse/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4262,6 +4328,8 @@ "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4272,6 +4340,8 @@ "@babel/plugin-transform-async-generator-functions/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-async-generator-functions/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-classes/@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], @@ -4284,6 +4354,8 @@ "@babel/plugin-transform-classes/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-classes/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-computed-properties/@babel/template/@babel/parser": ["@babel/parser@7.26.5", "", { "dependencies": { "@babel/types": "^7.26.5" }, "bin": "./bin/babel-parser.js" }, "sha512-SRJ4jYmXRqV1/Xc+TIVG84WjHBXKlxO9sHQnA2Pf12QQEAp1LOh6kDzNHXcUnbH1QI0FDoPPVOt+vyUDucxpaw=="], "@babel/plugin-transform-computed-properties/@babel/template/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], @@ -4298,6 +4370,8 @@ "@babel/plugin-transform-function-name/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-function-name/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-function-name/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse": ["@babel/traverse@7.26.5", "", { "dependencies": { "@babel/code-frame": "^7.26.2", "@babel/generator": "^7.26.5", "@babel/parser": "^7.26.5", "@babel/template": "^7.25.9", "@babel/types": "^7.26.5", "debug": "^4.3.1", "globals": "^11.1.0" } }, "sha512-rkOSPOw+AXbgtwUga3U4u8RpoK9FEFWBNAlTpcnkLFjL5CT+oyHNuUUC/xx6XefEJ16r38r8Bc/lfp6rYuHeJQ=="], @@ -4312,6 +4386,8 @@ "@babel/plugin-transform-modules-systemjs/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-modules-systemjs/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-modules-systemjs/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-modules-umd/@babel/helper-module-transforms/@babel/traverse": ["@babel/traverse@7.26.5", "", { "dependencies": { "@babel/code-frame": "^7.26.2", "@babel/generator": "^7.26.5", "@babel/parser": "^7.26.5", "@babel/template": "^7.25.9", "@babel/types": "^7.26.5", "debug": "^4.3.1", "globals": "^11.1.0" } }, "sha512-rkOSPOw+AXbgtwUga3U4u8RpoK9FEFWBNAlTpcnkLFjL5CT+oyHNuUUC/xx6XefEJ16r38r8Bc/lfp6rYuHeJQ=="], @@ -4408,6 +4484,8 @@ "@svgr/core/@babel/core/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@svgr/core/@babel/core/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@svgr/hast-util-to-babel-ast/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], "@svgr/plugin-jsx/@babel/core/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4426,6 +4504,8 @@ "@svgr/plugin-jsx/@babel/core/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@svgr/plugin-jsx/@babel/core/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@svgr/webpack/@babel/core/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], "@svgr/webpack/@babel/core/@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.26.5", "", { "dependencies": { "@babel/compat-data": "^7.26.5", "@babel/helper-validator-option": "^7.25.9", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-IXuyn5EkouFJscIDuFF5EsiSolseme1s0CZB+QxVugqJLYmKdxI1VfIBOst0SUu4rnk2Z7kqTwmoO1lp3HIfnA=="], @@ -4442,6 +4522,8 @@ "@svgr/webpack/@babel/core/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@svgr/webpack/@babel/core/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@types/react-router-config/@types/react/csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], "@types/react-router-dom/@types/react/csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], @@ -4456,10 +4538,66 @@ "ajv-keywords/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + "app/@aws-sdk/client-s3/@aws-sdk/core": ["@aws-sdk/core@3.973.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws-sdk/xml-builder": "^3.972.1", "@smithy/core": "^3.21.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-Ocubx42QsMyVs9ANSmFpRm0S+hubWljpPLjOi9UFrtcnVJjrVJTzQ51sN0e5g4e8i8QZ7uY73zosLmgYL7kZTQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.1", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.1", "@aws-sdk/credential-provider-http": "^3.972.1", "@aws-sdk/credential-provider-ini": "^3.972.1", "@aws-sdk/credential-provider-process": "^3.972.1", "@aws-sdk/credential-provider-sso": "^3.972.1", "@aws-sdk/credential-provider-web-identity": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-DwXPk9GfuU/xG9tmCyXFVkCr6X3W8ZCoL5Ptb0pbltEx1/LCcg7T+PBqDlPiiinNCD6ilIoMJDWsnJ8ikzZA7Q=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-bucket-endpoint": ["@aws-sdk/middleware-bucket-endpoint@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-arn-parser": "^3.972.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-YVvoitBdE8WOpHqIXvv49efT73F4bJ99XH2bi3Dn3mx7WngI4RwHwn/zF5i0q1Wdi5frGSCNF3vuh+pY817//w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-expect-continue": ["@aws-sdk/middleware-expect-continue@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-6lfl2/J/kutzw/RLu1kjbahsz4vrGPysrdxWaw8fkjLYG+6M6AswocIAZFS/LgAVi/IWRwPTx9YC0/NH2wDrSw=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-flexible-checksums": ["@aws-sdk/middleware-flexible-checksums@3.972.1", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@aws-crypto/crc32c": "5.2.0", "@aws-crypto/util": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/crc64-nvme": "3.972.0", "@aws-sdk/types": "^3.973.0", "@smithy/is-array-buffer": "^4.2.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-kjVVREpqeUkYQsXr78AcsJbEUlxGH7+H6yS7zkjrnu6HyEVxbdSndkKX6VpKneFOihjCAhIXlk4wf3butDHkNQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-host-header": ["@aws-sdk/middleware-host-header@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-/R82lXLPmZ9JaUGSUdKtBp2k/5xQxvBT3zZWyKiBOhyulFotlfvdlrO8TnqstBimsl4lYEYySDL+W6ldFh6ALg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-location-constraint": ["@aws-sdk/middleware-location-constraint@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-YisPaCbvBk9gY5aUI8jDMDKXsLZ9Fet0WYj1MviK8tZYMgxBIYHM6l3O/OHaAIujojZvamd9F3haYYYWp5/V3w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-logger": ["@aws-sdk/middleware-logger@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-JGgFl6cHg9G2FHu4lyFIzmFN8KESBiRr84gLC3Aeni0Gt1nKm+KxWLBuha/RPcXxJygGXCcMM4AykkIwxor8RA=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-recursion-detection": ["@aws-sdk/middleware-recursion-detection@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-taGzNRe8vPHjnliqXIHp9kBgIemLE/xCaRTMH1NH0cncHeaPcjxtnCroAAM9aOlPuKvBe2CpZESyvM1+D8oI7Q=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-arn-parser": "^3.972.1", "@smithy/core": "^3.21.1", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-5f9x9/G+StE8+7wd9EVDF3d+J74xK+WBA3FhZwLSkf3pHFGLKzlmUfxJJE1kkXkbj/j/H+Dh3zL/hrtQE9hNsg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-ssec": ["@aws-sdk/middleware-ssec@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-fLtRTPd/MxJT2drJKft2GVGKm35PiNEeQ1Dvz1vc/WhhgAteYrp4f1SfSgjgLaYWGMExESJL4bt8Dxqp6tVsog=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-user-agent": ["@aws-sdk/middleware-user-agent@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@smithy/core": "^3.21.1", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-d+Exq074wy0X6wvShg/kmZVtkah+28vMuqCtuY3cydg8LUZOJBtbAolCpEJizSyb8mJJZF9BjWaTANXL4OYnkg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/region-config-resolver": ["@aws-sdk/region-config-resolver@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/config-resolver": "^4.4.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-voIY8RORpxLAEgEkYaTFnkaIuRwVBEc+RjVZYcSSllPV+ZEKAacai6kNhJeE3D70Le+JCfvRb52tng/AVHY+jQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region": ["@aws-sdk/signature-v4-multi-region@3.972.0", "", { "dependencies": { "@aws-sdk/middleware-sdk-s3": "3.972.0", "@aws-sdk/types": "3.972.0", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-2udiRijmjpN81Pvajje4TsjbXDZNP6K9bYUanBYH8hXa/tZG5qfGCySD+TyX0sgDxCQmEDMg3LaQdfjNHBDEgQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/types": ["@aws-sdk/types@3.973.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-jYIdB7a7jhRTvyb378nsjyvJh1Si+zVduJ6urMNGpz8RjkmHZ+9vM2H07XaIB2Cfq0GhJRZYOfUCH8uqQhqBkQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/util-endpoints": ["@aws-sdk/util-endpoints@3.972.0", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-endpoints": "^3.2.8", "tslib": "^2.6.2" } }, "sha512-6JHsl1V/a1ZW8D8AFfd4R52fwZPnZ5H4U6DS8m/bWT8qad72NvbOFAC7U2cDtFs2TShqUO3TEiX/EJibtY3ijg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/util-user-agent-browser": ["@aws-sdk/util-user-agent-browser@3.972.1", "", { "dependencies": { "@aws-sdk/types": "^3.973.0", "@smithy/types": "^4.12.0", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-IgF55NFmJX8d9Wql9M0nEpk2eYbuD8G4781FN4/fFgwTXBn86DvlZJuRWDCMcMqZymnBVX7HW9r+3r9ylqfW0w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/util-user-agent-node": ["@aws-sdk/util-user-agent-node@3.972.1", "", { "dependencies": { "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@smithy/node-config-provider": "^4.3.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" }, "peerDependencies": { "aws-crt": ">=1.0.0" }, "optionalPeers": ["aws-crt"] }, "sha512-oIs4JFcADzoZ0c915R83XvK2HltWupxNsXUIuZse2rgk7b97zTpkxaqXiH0h9ylh31qtgo/t8hp4tIqcsMrEbQ=="], + + "app/@aws-sdk/client-s3/@smithy/core": ["@smithy/core@3.21.1", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-NUH8R4O6FkN8HKMojzbGg/5pNjsfTjlMmeFclyPfPaXXUrbr5TzhWgbf7t92wfrpCHRgpjyz7ffASIS3wX28aA=="], + + "app/@aws-sdk/client-s3/@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.11", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-/WqsrycweGGfb9sSzME4CrsuayjJF6BueBmkKlcbeU5q18OhxRrvvKlmfw3tpDsK5ilx2XUJvoukwxHB0nHs/Q=="], + + "app/@aws-sdk/client-s3/@smithy/middleware-retry": ["@smithy/middleware-retry@4.4.27", "", { "dependencies": { "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/service-error-classification": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-xFUYCGRVsfgiN5EjsJJSzih9+yjStgMTCLANPlf0LVQkPDYCe0hz97qbdTZosFOiYlGBlHYityGRxrQ/hxhfVQ=="], + + "app/@aws-sdk/client-s3/@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.8", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-q9u+MSbJVIJ1QmJ4+1u+cERXkrhuILCBDsJUBAW1MPE6sFonbCNaegFuwW9ll8kh5UdyY3jOkoOGlc7BesoLpg=="], + + "app/@aws-sdk/client-s3/@smithy/smithy-client": ["@smithy/smithy-client@4.10.12", "", { "dependencies": { "@smithy/core": "^3.21.1", "@smithy/middleware-endpoint": "^4.4.11", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-VKO/HKoQ5OrSHW6AJUmEnUKeXI1/5LfCwO9cwyao7CmLvGnZeM1i36Lyful3LK1XU7HwTVieTqO1y2C/6t3qtA=="], + + "app/@aws-sdk/client-s3/@smithy/util-defaults-mode-browser": ["@smithy/util-defaults-mode-browser@4.3.26", "", { "dependencies": { "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-vva0dzYUTgn7DdE0uaha10uEdAgmdLnNFowKFjpMm6p2R0XDk5FHPX3CBJLzWQkQXuEprsb0hGz9YwbicNWhjw=="], + + "app/@aws-sdk/client-s3/@smithy/util-defaults-mode-node": ["@smithy/util-defaults-mode-node@4.2.29", "", { "dependencies": { "@smithy/config-resolver": "^4.4.6", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-c6D7IUBsZt/aNnTBHMTf+OVh+h/JcxUUgfTcIJaWRe6zhOum1X+pNKSZtZ+7fbOn5I99XVFtmrnXKv8yHHErTQ=="], + + "app/@aws-sdk/client-s3/@smithy/util-stream": ["@smithy/util-stream@4.5.10", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jbqemy51UFSZSp2y0ZmRfckmrzuKww95zT9BYMmuJ8v3altGcqjwoV1tzpOwuHaKrwQrCjIzOib499ymr2f98g=="], + + "app/@types/bun/bun-types": ["bun-types@1.3.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-OlFwHcnNV99r//9v5IIOgQ9Uk37gZqrNMCcqEaExdkVq3Avwqok1bJFmvGMCkCE0FqzdY8VMOZpfpR3lwI+CsQ=="], + "autoprefixer/browserslist/electron-to-chromium": ["electron-to-chromium@1.5.178", "", {}, "sha512-wObbz/ar3Bc6e4X5vf0iO8xTN8YAjN/tgiAOJLr7yjYFtP9wAjq8Mb5h0yn6kResir+VYx2DXBj9NNobs0ETSA=="], "autoprefixer/browserslist/update-browserslist-db": ["update-browserslist-db@1.1.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw=="], + "babel-loader/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "babel-loader/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "body-parser/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], @@ -4476,12 +4614,16 @@ "copy-webpack-plugin/globby/slash": ["slash@4.0.0", "", {}, "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew=="], + "copy-webpack-plugin/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "copy-webpack-plugin/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "css-loader/postcss/nanoid": ["nanoid@3.3.8", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w=="], "css-minimizer-webpack-plugin/postcss/nanoid": ["nanoid@3.3.8", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w=="], + "css-minimizer-webpack-plugin/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "css-minimizer-webpack-plugin/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "css-select/domutils/dom-serializer": ["dom-serializer@1.4.1", "", { "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^4.2.0", "entities": "^2.0.0" } }, "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag=="], @@ -4492,6 +4634,8 @@ "express/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], + "filelist/minimatch/brace-expansion": ["brace-expansion@2.0.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="], + "finalhandler/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "fix-dts-default-cjs-exports/rollup/@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.34.9", "", { "os": "android", "cpu": "arm" }, "sha512-qZdlImWXur0CFakn2BJ2znJOdqYZKiedEPEVNTBrpfPjc/YuTGcaYZcdmNFTkUj3DU0ZM/AElcM8Ybww3xVLzA=="], @@ -4536,6 +4680,8 @@ "front-matter/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], + "glob/minimatch/brace-expansion": ["brace-expansion@5.0.2", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw=="], + "gray-matter/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], "hpack.js/readable-stream/isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], @@ -4552,6 +4698,8 @@ "mdast-util-gfm-autolink-literal/micromark-util-character/micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], + "mini-css-extract-plugin/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "mini-css-extract-plugin/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "object.entries/call-bound/call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], @@ -4600,6 +4748,8 @@ "sucrase/glob/path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], + "terser-webpack-plugin/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "terser-webpack-plugin/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "update-notifier/boxen/camelcase": ["camelcase@7.0.1", "", {}, "sha512-xlx1yCK2Oc1APsPXDL2LdlNP6+uu8OCDdhOBSVT279M/S+y75O30C2VuD8T2ogdePBBl7PfPF4504tnLgX3zfw=="], @@ -4612,6 +4762,8 @@ "webpack-dev-middleware/mime-types/mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + "webpack-dev-middleware/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "webpack-dev-middleware/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "webpack-dev-server/chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], @@ -4620,6 +4772,8 @@ "webpack-dev-server/open/define-lazy-prop": ["define-lazy-prop@3.0.0", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="], + "webpack-dev-server/schema-utils/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "webpack-dev-server/schema-utils/ajv-keywords": ["ajv-keywords@5.1.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3" }, "peerDependencies": { "ajv": "^8.8.2" } }, "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw=="], "webpack/eslint-scope/estraverse": ["estraverse@4.3.0", "", {}, "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw=="], @@ -4634,9 +4788,19 @@ "@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" } }, "sha512-POaGMcXnozzqBUyJM3HLUZ9GR6OKJWPGJEmhtTnxZXt8B6JcJ/6K3xRJ5H/j8oovVLz8Wg6vFxAHv8lvuASxMg=="], + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core": ["@aws-sdk/core@3.972.0", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@aws-sdk/xml-builder": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-nEeUW2M9F+xdIaD98F5MBcQ4ITtykj3yKbgFZ6J0JtL3bq+Z90szQ6Yy8H/BLPYXTs3V4n9ifnBo8cprRDiE6A=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-RM5Mmo/KJ593iMSrALlHEOcc9YOIyOsDmS5x2NLOMdEmzv1o00fcpAkCQ02IGu1eFneBFT7uX0Mpag0HI+Cz2g=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/core": ["@smithy/core@3.21.0", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-bg2TfzgsERyETAxc/Ims/eJX8eAnIeTi4r4LHpMpfF/2NyO6RsWis0rjKcCPaGksljmOb23BZRiCeT/3NvwkXw=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client": ["@smithy/smithy-client@4.10.11", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-6o804SCyHGMXAb5mFJ+iTy9kVKv7F91a9szN0J+9X6p8A0NrdpUxdaC57aye2ipQkP2C4IAqETEpGZ0Zj77Haw=="], - "@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client/@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.10", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-kwWpNltpxrvPabnjEFvwSmA+66l6s2ReCvgVSzW/z92LU4T28fTdgZ18IdYRYOrisu2NMQ0jUndRScbO65A/zg=="], + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/util-stream": ["@smithy/util-stream@4.5.10", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jbqemy51UFSZSp2y0ZmRfckmrzuKww95zT9BYMmuJ8v3altGcqjwoV1tzpOwuHaKrwQrCjIzOib499ymr2f98g=="], + + "@aws-sdk/s3-request-presigner/@smithy/middleware-endpoint/@smithy/core/@smithy/util-stream": ["@smithy/util-stream@4.5.10", "", { "dependencies": { "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-buffer-from": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-jbqemy51UFSZSp2y0ZmRfckmrzuKww95zT9BYMmuJ8v3altGcqjwoV1tzpOwuHaKrwQrCjIzOib499ymr2f98g=="], + + "@aws-sdk/s3-request-presigner/@smithy/smithy-client/@smithy/util-stream/@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.8", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-q9u+MSbJVIJ1QmJ4+1u+cERXkrhuILCBDsJUBAW1MPE6sFonbCNaegFuwW9ll8kh5UdyY3jOkoOGlc7BesoLpg=="], "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], @@ -4688,6 +4852,8 @@ "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-modules-commonjs/@babel/helper-module-transforms/@babel/traverse/@babel/generator": ["@babel/generator@7.26.5", "", { "dependencies": { "@babel/parser": "^7.26.5", "@babel/types": "^7.26.5", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^3.0.2" } }, "sha512-2caSP6fN9I7HOe6nqhtft7V4g7/V/gfDsC3Ag4W7kEzzvRGKqiv0pu0HogPiZ3KaVSoNDhUws6IJjDjpfmYIXw=="], @@ -4698,6 +4864,8 @@ "@babel/plugin-transform-modules-commonjs/@babel/helper-module-transforms/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-modules-commonjs/@babel/helper-module-transforms/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-modules-commonjs/@babel/helper-module-transforms/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@babel/plugin-transform-modules-systemjs/@babel/traverse/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], @@ -4712,6 +4880,8 @@ "@babel/plugin-transform-modules-umd/@babel/helper-module-transforms/@babel/traverse/@babel/types": ["@babel/types@7.26.5", "", { "dependencies": { "@babel/helper-string-parser": "^7.25.9", "@babel/helper-validator-identifier": "^7.25.9" } }, "sha512-L6mZmwFDK6Cjh1nRCLXpa6no13ZIioJDz7mdkzHv399pThrTa/k0nUlNaenOeh2kWu/iaOQYElEpKPUswUa9Vg=="], + "@babel/plugin-transform-modules-umd/@babel/helper-module-transforms/@babel/traverse/debug": ["debug@4.4.0", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA=="], + "@babel/plugin-transform-modules-umd/@babel/helper-module-transforms/@babel/traverse/globals": ["globals@11.12.0", "", {}, "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA=="], "@docusaurus/core/chokidar/readdirp/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], @@ -4740,12 +4910,38 @@ "@svgr/webpack/@babel/core/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], + "app/@aws-sdk/client-s3/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.1", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" } }, "sha512-6zZGlPOqn7Xb+25MAXGb1JhgvaC5HjZj6GzszuVrnEgbhvzBRFGKYemuHBV4bho+dtqeYKPgaZUv7/e80hIGNg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-/etNHqnx96phy/SjI0HRC588o4vKH5F0xfkZ13yAATV7aNrb+5gYGNE6ePWafP+FuZ3HkULSSlJFj0AxgrAqYw=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.2", "", { "dependencies": { "@aws-sdk/core": "^3.973.1", "@aws-sdk/types": "^3.973.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/node-http-handler": "^4.4.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.12", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-mXgdaUfe5oM+tWKyeZ7Vh/iQ94FrkMky1uuzwTOmFADiRcSk5uHy/e3boEFedXiT/PRGzgBmqvJVK4F6lUISCg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini": ["@aws-sdk/credential-provider-ini@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/credential-provider-env": "^3.972.1", "@aws-sdk/credential-provider-http": "^3.972.1", "@aws-sdk/credential-provider-login": "^3.972.1", "@aws-sdk/credential-provider-process": "^3.972.1", "@aws-sdk/credential-provider-sso": "^3.972.1", "@aws-sdk/credential-provider-web-identity": "^3.972.1", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/credential-provider-imds": "^4.2.8", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-OdbJA3v+XlNDsrYzNPRUwr8l7gw1r/nR8l4r96MDzSBDU8WEo8T6C06SvwaXR8SpzsjO3sq5KMP86wXWg7Rj4g=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-process": ["@aws-sdk/credential-provider-process@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-bi47Zigu3692SJwdBvo8y1dEwE6B61stCwCFnuRWJVTfiM84B+VTSCV661CSWJmIZzmcy7J5J3kWyxL02iHj0w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso": ["@aws-sdk/credential-provider-sso@3.972.1", "", { "dependencies": { "@aws-sdk/client-sso": "3.974.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/token-providers": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-dLZVNhM7wSgVUFsgVYgI5hb5Z/9PUkT46pk/SHrSmUqfx6YDvoV4YcPtaiRqviPpEGGiRtdQMEadyOKIRqulUQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity": ["@aws-sdk/credential-provider-web-identity@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-YMDeYgi0u687Ay0dAq/pFPKuijrlKTgsaB/UATbxCs/FzZfMiG4If5ksywHmmW7MiYUF8VVv+uou3TczvLrN4w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-bucket-endpoint/@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-XnNit6H9PPHhqUXW/usjX6JeJ6Pm8ZNqivTjmNjgWHeOfVpblUc/MTic02UmCNR0jJLPjQ3mBKiMen0tnkNQjQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/middleware-sdk-s3/@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.1", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-XnNit6H9PPHhqUXW/usjX6JeJ6Pm8ZNqivTjmNjgWHeOfVpblUc/MTic02UmCNR0jJLPjQ3mBKiMen0tnkNQjQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3": ["@aws-sdk/middleware-sdk-s3@3.972.0", "", { "dependencies": { "@aws-sdk/core": "3.972.0", "@aws-sdk/types": "3.972.0", "@aws-sdk/util-arn-parser": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-config-provider": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-0bcKFXWx+NZ7tIlOo7KjQ+O2rydiHdIQahrq+fN6k9Osky29v17guy68urUKfhTobR6iY6KvxkroFWaFtTgS5w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/types": ["@aws-sdk/types@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="], + + "app/@aws-sdk/client-s3/@aws-sdk/util-endpoints/@aws-sdk/types": ["@aws-sdk/types@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-U7xBIbLSetONxb2bNzHyDgND3oKGoIfmknrEVnoEU4GUSs+0augUOIn9DIWGUO2ETcRFdsRUnmx9KhPT9Ojbug=="], + "boxen/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], "boxen/wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], "css-select/domutils/dom-serializer/entities": ["entities@2.2.0", "", {}, "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A=="], + "glob/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.3", "", {}, "sha512-1pHv8LX9CpKut1Zp4EXey7Z8OfH11ONNH6Dhi2WDUt31VVZFXZzKwXcysBgqSumFCmR+0dqjMK5v5JiFHzi0+g=="], + "pkg-dir/find-up/locate-path/p-locate": ["p-locate@6.0.0", "", { "dependencies": { "p-limit": "^4.0.0" } }, "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw=="], "renderkid/htmlparser2/domutils/dom-serializer": ["dom-serializer@1.4.1", "", { "dependencies": { "domelementtype": "^2.0.1", "domhandler": "^4.2.0", "entities": "^2.0.0" } }, "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag=="], @@ -4766,6 +4962,14 @@ "widest-line/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" } }, "sha512-POaGMcXnozzqBUyJM3HLUZ9GR6OKJWPGJEmhtTnxZXt8B6JcJ/6K3xRJ5H/j8oovVLz8Wg6vFxAHv8lvuASxMg=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client/@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.10", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-kwWpNltpxrvPabnjEFvwSmA+66l6s2ReCvgVSzW/z92LU4T28fTdgZ18IdYRYOrisu2NMQ0jUndRScbO65A/zg=="], + + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/util-stream/@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.8", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-q9u+MSbJVIJ1QmJ4+1u+cERXkrhuILCBDsJUBAW1MPE6sFonbCNaegFuwW9ll8kh5UdyY3jOkoOGlc7BesoLpg=="], + + "@aws-sdk/s3-request-presigner/@smithy/middleware-endpoint/@smithy/core/@smithy/util-stream/@smithy/node-http-handler": ["@smithy/node-http-handler@4.4.8", "", { "dependencies": { "@smithy/abort-controller": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/querystring-builder": "^4.2.8", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-q9u+MSbJVIJ1QmJ4+1u+cERXkrhuILCBDsJUBAW1MPE6sFonbCNaegFuwW9ll8kh5UdyY3jOkoOGlc7BesoLpg=="], + "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse/@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="], "@babel/plugin-transform-modules-amd/@babel/helper-module-transforms/@babel/traverse/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], @@ -4778,12 +4982,42 @@ "@babel/plugin-transform-modules-umd/@babel/helper-module-transforms/@babel/traverse/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.25.9", "", {}, "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA=="], + "app/@aws-sdk/client-s3/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/credential-provider-login": ["@aws-sdk/credential-provider-login@3.972.1", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-CccqDGL6ZrF3/EFWZefvKW7QwwRdxlHUO8NVBKNVcNq6womrPDvqB6xc9icACtE0XB0a7PLoSTkAg8bQVkTO2w=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-ini/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-k3dwdo/vOiHMJc9gMnkPl1BA5aQfTrZbz+8fiDkWrPagqAioZgmo5oiaOaeX0grObfJQKDtcpPFR4iWf8cgl8Q=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/client-sso": ["@aws-sdk/client-sso@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-ci+GiM0c4ULo4D79UMcY06LcOLcfvUfiyt8PzNY0vbt5O8BfCPYf4QomwVgkNcLLCYmroO4ge2Yy1EsLUlcD6g=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/token-providers@3.974.0", "", { "dependencies": { "@aws-sdk/core": "^3.973.0", "@aws-sdk/nested-clients": "3.974.0", "@aws-sdk/types": "^3.973.0", "@smithy/property-provider": "^4.2.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "tslib": "^2.6.2" } }, "sha512-cBykL0LiccKIgNhGWvQRTPvsBLPZxnmJU3pYxG538jpFX8lQtrCy1L7mmIHNEdxIdIGEPgAEHF8/JQxgBToqUQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-web-identity/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-k3dwdo/vOiHMJc9gMnkPl1BA5aQfTrZbz+8fiDkWrPagqAioZgmo5oiaOaeX0grObfJQKDtcpPFR4iWf8cgl8Q=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core": ["@aws-sdk/core@3.972.0", "", { "dependencies": { "@aws-sdk/types": "3.972.0", "@aws-sdk/xml-builder": "3.972.0", "@smithy/core": "^3.20.6", "@smithy/node-config-provider": "^4.3.8", "@smithy/property-provider": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/signature-v4": "^5.3.8", "@smithy/smithy-client": "^4.10.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-nEeUW2M9F+xdIaD98F5MBcQ4ITtykj3yKbgFZ6J0JtL3bq+Z90szQ6Yy8H/BLPYXTs3V4n9ifnBo8cprRDiE6A=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/util-arn-parser": ["@aws-sdk/util-arn-parser@3.972.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-RM5Mmo/KJ593iMSrALlHEOcc9YOIyOsDmS5x2NLOMdEmzv1o00fcpAkCQ02IGu1eFneBFT7uX0Mpag0HI+Cz2g=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/core": ["@smithy/core@3.21.0", "", { "dependencies": { "@smithy/middleware-serde": "^4.2.9", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-middleware": "^4.2.8", "@smithy/util-stream": "^4.5.10", "@smithy/util-utf8": "^4.2.0", "@smithy/uuid": "^1.1.0", "tslib": "^2.6.2" } }, "sha512-bg2TfzgsERyETAxc/Ims/eJX8eAnIeTi4r4LHpMpfF/2NyO6RsWis0rjKcCPaGksljmOb23BZRiCeT/3NvwkXw=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client": ["@smithy/smithy-client@4.10.11", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-stack": "^4.2.8", "@smithy/protocol-http": "^5.3.8", "@smithy/types": "^4.12.0", "@smithy/util-stream": "^4.5.10", "tslib": "^2.6.2" } }, "sha512-6o804SCyHGMXAb5mFJ+iTy9kVKv7F91a9szN0J+9X6p8A0NrdpUxdaC57aye2ipQkP2C4IAqETEpGZ0Zj77Haw=="], + "pkg-dir/find-up/locate-path/p-locate/p-limit": ["p-limit@4.0.0", "", { "dependencies": { "yocto-queue": "^1.0.0" } }, "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ=="], "update-notifier/boxen/string-width/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], "update-notifier/boxen/wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], + "@aws-sdk/s3-request-presigner/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], + + "app/@aws-sdk/client-s3/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-sso/@aws-sdk/token-providers/@aws-sdk/nested-clients": ["@aws-sdk/nested-clients@3.974.0", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.973.0", "@aws-sdk/middleware-host-header": "^3.972.1", "@aws-sdk/middleware-logger": "^3.972.1", "@aws-sdk/middleware-recursion-detection": "^3.972.1", "@aws-sdk/middleware-user-agent": "^3.972.1", "@aws-sdk/region-config-resolver": "^3.972.1", "@aws-sdk/types": "^3.973.0", "@aws-sdk/util-endpoints": "3.972.0", "@aws-sdk/util-user-agent-browser": "^3.972.1", "@aws-sdk/util-user-agent-node": "^3.972.1", "@smithy/config-resolver": "^4.4.6", "@smithy/core": "^3.21.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", "@smithy/middleware-endpoint": "^4.4.10", "@smithy/middleware-retry": "^4.4.26", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", "@smithy/node-http-handler": "^4.4.8", "@smithy/protocol-http": "^5.3.8", "@smithy/smithy-client": "^4.10.11", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", "@smithy/util-defaults-mode-browser": "^4.3.25", "@smithy/util-defaults-mode-node": "^4.2.28", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", "@smithy/util-utf8": "^4.2.0", "tslib": "^2.6.2" } }, "sha512-k3dwdo/vOiHMJc9gMnkPl1BA5aQfTrZbz+8fiDkWrPagqAioZgmo5oiaOaeX0grObfJQKDtcpPFR4iWf8cgl8Q=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core/@aws-sdk/xml-builder": ["@aws-sdk/xml-builder@3.972.0", "", { "dependencies": { "@smithy/types": "^4.12.0", "fast-xml-parser": "5.2.5", "tslib": "^2.6.2" } }, "sha512-POaGMcXnozzqBUyJM3HLUZ9GR6OKJWPGJEmhtTnxZXt8B6JcJ/6K3xRJ5H/j8oovVLz8Wg6vFxAHv8lvuASxMg=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@smithy/smithy-client/@smithy/middleware-endpoint": ["@smithy/middleware-endpoint@4.4.10", "", { "dependencies": { "@smithy/core": "^3.21.0", "@smithy/middleware-serde": "^4.2.9", "@smithy/node-config-provider": "^4.3.8", "@smithy/shared-ini-file-loader": "^4.4.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-middleware": "^4.2.8", "tslib": "^2.6.2" } }, "sha512-kwWpNltpxrvPabnjEFvwSmA+66l6s2ReCvgVSzW/z92LU4T28fTdgZ18IdYRYOrisu2NMQ0jUndRScbO65A/zg=="], + "pkg-dir/find-up/locate-path/p-locate/p-limit/yocto-queue": ["yocto-queue@1.1.1", "", {}, "sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g=="], + + "app/@aws-sdk/client-s3/@aws-sdk/signature-v4-multi-region/@aws-sdk/middleware-sdk-s3/@aws-sdk/core/@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], } } diff --git a/comparadise-utils/package.json b/comparadise-utils/package.json index 40a17843..6254d27c 100644 --- a/comparadise-utils/package.json +++ b/comparadise-utils/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@types/pngjs": "6.0.5", - "cypress": "15.9.0", + "cypress": "15.10.0", "tsup": "8.5.1" }, "peerDependencies": { diff --git a/docs/package.json b/docs/package.json index e3645d62..d1fb4b99 100644 --- a/docs/package.json +++ b/docs/package.json @@ -11,10 +11,10 @@ "@docusaurus/preset-classic": "3.9.2", "@docusaurus/types": "3.9.2", "@mdx-js/react": "3.1.1", - "@types/react": "19.2.9", - "ajv": "8.17.1", + "@types/react": "19.2.14", + "ajv": "8.18.0", "clsx": "2.1.1", - "react": "19.2.3", - "react-dom": "19.2.3" + "react": "19.2.4", + "react-dom": "19.2.4" } } diff --git a/package.json b/package.json index df951eb0..71604e66 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,22 @@ { "name": "comparadise", - "packageManager": "bun@1.3.6", + "packageManager": "bun@1.3.9", "type": "module", "devDependencies": { "@testing-library/cypress": "10.1.0", "@total-typescript/ts-reset": "0.6.1", - "@types/bun": "1.3.6", - "cypress": "15.9.0", + "@types/bun": "1.3.9", + "cypress": "15.10.0", "eslint": "9.39.2", "eslint-plugin-react": "7.37.5", "husky": "9.1.7", - "nx": "22.4.1", + "nx": "22.5.1", "prettier": "3.8.1", "prettier-plugin-tailwindcss": "0.7.2", "shared": "workspace:*", "ts-node": "10.9.2", "typescript": "5.9.3", - "typescript-eslint": "8.53.1" + "typescript-eslint": "8.56.0" }, "scripts": { "docker": "docker build . --tag comparadise && docker compose up -d", From ad4bfa2c6fbb51af7cb0d63010bd284e91404e19 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" Date: Wed, 18 Feb 2026 18:34:00 +0000 Subject: [PATCH 2/2] chore: committing generated code --- action/dist/main.js | 21025 +++++++++++++++++--------------------- action/dist/main.js.map | 2 +- action/dist/post.js | 9132 +++++------------ action/dist/post.js.map | 2 +- bun.lock | 202 +- 5 files changed, 12279 insertions(+), 18084 deletions(-) diff --git a/action/dist/main.js b/action/dist/main.js index c5a7b687..c7ba6a8a 100644 --- a/action/dist/main.js +++ b/action/dist/main.js @@ -233,10 +233,10 @@ var require_tunnel = __commonJS({ var overrides = arguments[i6]; if (typeof overrides === "object") { var keys = Object.keys(overrides); - for (var j6 = 0, keyLen = keys.length; j6 < keyLen; ++j6) { - var k6 = keys[j6]; - if (overrides[k6] !== void 0) { - target[k6] = overrides[k6]; + for (var j7 = 0, keyLen = keys.length; j7 < keyLen; ++j7) { + var k7 = keys[j7]; + if (overrides[k7] !== void 0) { + target[k7] = overrides[k7]; } } } @@ -948,7 +948,7 @@ var require_util = __commonJS({ var assert = require("assert"); var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols(); var { IncomingMessage } = require("http"); - var stream3 = require("stream"); + var stream2 = require("stream"); var net = require("net"); var { Blob: Blob2 } = require("buffer"); var nodeUtil = require("util"); @@ -957,7 +957,7 @@ var require_util = __commonJS({ var { InvalidArgumentError } = require_errors(); var { headerNameLowerCasedRecord } = require_constants(); var { tree } = require_tree(); - var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v7) => Number(v7)); + var [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v8) => Number(v8)); var BodyAsyncIterable = class { constructor(body) { this[kBody] = body; @@ -970,7 +970,7 @@ var require_util = __commonJS({ } }; function wrapRequestBody(body) { - if (isStream2(body)) { + if (isStream(body)) { if (bodyLength(body) === 0) { body.on("data", function() { assert(false); @@ -993,7 +993,7 @@ var require_util = __commonJS({ } function nop() { } - function isStream2(obj2) { + function isStream(obj2) { return obj2 && typeof obj2 === "object" && typeof obj2.pipe === "function" && typeof obj2.on === "function"; } function isBlobLike(object) { @@ -1057,14 +1057,14 @@ var require_util = __commonJS({ } const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80; let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`; - let path7 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`; + let path6 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`; if (origin[origin.length - 1] === "/") { origin = origin.slice(0, origin.length - 1); } - if (path7 && path7[0] !== "/") { - path7 = `/${path7}`; + if (path6 && path6[0] !== "/") { + path6 = `/${path6}`; } - return new URL(`${origin}${path7}`); + return new URL(`${origin}${path6}`); } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); @@ -1111,7 +1111,7 @@ var require_util = __commonJS({ function bodyLength(body) { if (body == null) { return 0; - } else if (isStream2(body)) { + } else if (isStream(body)) { const state2 = body._readableState; return state2 && state2.objectMode === false && state2.ended === true && Number.isFinite(state2.length) ? state2.length : null; } else if (isBlobLike(body)) { @@ -1122,24 +1122,24 @@ var require_util = __commonJS({ return null; } function isDestroyed(body) { - return body && !!(body.destroyed || body[kDestroyed] || stream3.isDestroyed?.(body)); + return body && !!(body.destroyed || body[kDestroyed] || stream2.isDestroyed?.(body)); } - function destroy(stream4, err) { - if (stream4 == null || !isStream2(stream4) || isDestroyed(stream4)) { + function destroy(stream3, err) { + if (stream3 == null || !isStream(stream3) || isDestroyed(stream3)) { return; } - if (typeof stream4.destroy === "function") { - if (Object.getPrototypeOf(stream4).constructor === IncomingMessage) { - stream4.socket = null; + if (typeof stream3.destroy === "function") { + if (Object.getPrototypeOf(stream3).constructor === IncomingMessage) { + stream3.socket = null; } - stream4.destroy(err); + stream3.destroy(err); } else if (err) { queueMicrotask(() => { - stream4.emit("error", err); + stream3.emit("error", err); }); } - if (stream4.destroyed !== true) { - stream4[kDestroyed] = true; + if (stream3.destroyed !== true) { + stream3[kDestroyed] = true; } } var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; @@ -1169,7 +1169,7 @@ var require_util = __commonJS({ if (typeof headersValue === "string") { obj2[key] = headersValue; } else { - obj2[key] = Array.isArray(headersValue) ? headersValue.map((x7) => x7.toString("utf8")) : headersValue.toString("utf8"); + obj2[key] = Array.isArray(headersValue) ? headersValue.map((x8) => x8.toString("utf8")) : headersValue.toString("utf8"); } } } @@ -1186,19 +1186,19 @@ var require_util = __commonJS({ let key; let val; let kLen = 0; - for (let n6 = 0; n6 < headers.length; n6 += 2) { - key = headers[n6]; - val = headers[n6 + 1]; + for (let n12 = 0; n12 < headers.length; n12 += 2) { + key = headers[n12]; + val = headers[n12 + 1]; typeof key !== "string" && (key = key.toString()); typeof val !== "string" && (val = val.toString("utf8")); kLen = key.length; if (kLen === 14 && key[7] === "-" && (key === "content-length" || key.toLowerCase() === "content-length")) { hasContentLength = true; } else if (kLen === 19 && key[7] === "-" && (key === "content-disposition" || key.toLowerCase() === "content-disposition")) { - contentDispositionIdx = n6 + 1; + contentDispositionIdx = n12 + 1; } - ret2[n6] = key; - ret2[n6 + 1] = val; + ret2[n12] = key; + ret2[n12 + 1] = val; } if (hasContentLength && contentDispositionIdx !== -1) { ret2[contentDispositionIdx] = Buffer.from(ret2[contentDispositionIdx]).toString("latin1"); @@ -1238,13 +1238,13 @@ var require_util = __commonJS({ } } function isDisturbed(body) { - return !!(body && (stream3.isDisturbed(body) || body[kBodyUsed])); + return !!(body && (stream2.isDisturbed(body) || body[kBodyUsed])); } function isErrored(body) { - return !!(body && stream3.isErrored(body)); + return !!(body && stream2.isErrored(body)); } - function isReadable2(body) { - return !!(body && stream3.isReadable(body)); + function isReadable(body) { + return !!(body && stream2.isReadable(body)); } function getSocketInfo(socket) { return { @@ -1345,9 +1345,9 @@ var require_util = __commonJS({ function isValidHeaderValue(characters) { return !headerCharRegex.test(characters); } - function parseRangeHeader(range3) { - if (range3 == null || range3 === "") return { start: 0, end: null, size: null }; - const m6 = range3 ? range3.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; + function parseRangeHeader(range2) { + if (range2 == null || range2 === "") return { start: 0, end: null, size: null }; + const m6 = range2 ? range2.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null; return m6 ? { start: parseInt(m6[1]), end: m6[2] ? parseInt(m6[2]) : null, @@ -1402,14 +1402,14 @@ var require_util = __commonJS({ nop, isDisturbed, isErrored, - isReadable: isReadable2, + isReadable, toUSVString, isUSVString, isBlobLike, parseOrigin, parseURL: parseURL2, getServerName, - isStream: isStream2, + isStream, isIterable, isAsyncIterable, isDestroyed, @@ -1515,39 +1515,39 @@ var require_diagnostics = __commonJS({ }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { - request: { method, path: path7, origin } + request: { method, path: path6, origin } } = evt; - debuglog("sending request to %s %s/%s", method, origin, path7); + debuglog("sending request to %s %s/%s", method, origin, path6); }); diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => { const { - request: { method, path: path7, origin }, + request: { method, path: path6, origin }, response: { statusCode } } = evt; debuglog( "received response to %s %s/%s - HTTP %d", method, origin, - path7, + path6, statusCode ); }); diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => { const { - request: { method, path: path7, origin } + request: { method, path: path6, origin } } = evt; - debuglog("trailers received from %s %s/%s", method, origin, path7); + debuglog("trailers received from %s %s/%s", method, origin, path6); }); diagnosticsChannel.channel("undici:request:error").subscribe((evt) => { const { - request: { method, path: path7, origin }, + request: { method, path: path6, origin }, error: error2 } = evt; debuglog( "request to %s %s/%s errored - %s", method, origin, - path7, + path6, error2.message ); }); @@ -1596,9 +1596,9 @@ var require_diagnostics = __commonJS({ }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { - request: { method, path: path7, origin } + request: { method, path: path6, origin } } = evt; - debuglog("sending request to %s %s/%s", method, origin, path7); + debuglog("sending request to %s %s/%s", method, origin, path6); }); } diagnosticsChannel.channel("undici:websocket:open").subscribe((evt) => { @@ -1644,7 +1644,7 @@ var require_request = __commonJS({ var { isValidHTTPToken, isValidHeaderValue, - isStream: isStream2, + isStream, destroy, isBuffer, isFormDataLike, @@ -1661,7 +1661,7 @@ var require_request = __commonJS({ var kHandler = /* @__PURE__ */ Symbol("handler"); var Request2 = class { constructor(origin, { - path: path7, + path: path6, method, body, headers, @@ -1676,11 +1676,11 @@ var require_request = __commonJS({ expectContinue, servername }, handler2) { - if (typeof path7 !== "string") { + if (typeof path6 !== "string") { throw new InvalidArgumentError("path must be a string"); - } else if (path7[0] !== "/" && !(path7.startsWith("http://") || path7.startsWith("https://")) && method !== "CONNECT") { + } else if (path6[0] !== "/" && !(path6.startsWith("http://") || path6.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); - } else if (invalidPathRegex.test(path7)) { + } else if (invalidPathRegex.test(path6)) { throw new InvalidArgumentError("invalid request path"); } if (typeof method !== "string") { @@ -1710,7 +1710,7 @@ var require_request = __commonJS({ this.abort = null; if (body == null) { this.body = null; - } else if (isStream2(body)) { + } else if (isStream(body)) { this.body = body; const rState = this.body._readableState; if (!rState || !rState.autoDestroy) { @@ -1743,7 +1743,7 @@ var require_request = __commonJS({ this.completed = false; this.aborted = false; this.upgrade = upgrade || null; - this.path = query ? buildURL(path7, query) : path7; + this.path = query ? buildURL(path6, query) : path6; this.origin = origin; this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; this.blocking = blocking == null ? false : blocking; @@ -1960,8 +1960,8 @@ var require_request = __commonJS({ var require_dispatcher = __commonJS({ "../node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) { "use strict"; - var EventEmitter3 = require("events"); - var Dispatcher = class extends EventEmitter3 { + var EventEmitter2 = require("events"); + var Dispatcher = class extends EventEmitter2 { dispatch() { throw new Error("not implemented"); } @@ -2610,34 +2610,34 @@ var require_constants2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SPECIAL_HEADERS = exports2.HEADER_STATE = exports2.MINOR = exports2.MAJOR = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.STRICT_TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.STRICT_URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.FINISH = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0; var utils_1 = require_utils(); - var ERROR2; - (function(ERROR3) { - ERROR3[ERROR3["OK"] = 0] = "OK"; - ERROR3[ERROR3["INTERNAL"] = 1] = "INTERNAL"; - ERROR3[ERROR3["STRICT"] = 2] = "STRICT"; - ERROR3[ERROR3["LF_EXPECTED"] = 3] = "LF_EXPECTED"; - ERROR3[ERROR3["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; - ERROR3[ERROR3["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; - ERROR3[ERROR3["INVALID_METHOD"] = 6] = "INVALID_METHOD"; - ERROR3[ERROR3["INVALID_URL"] = 7] = "INVALID_URL"; - ERROR3[ERROR3["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; - ERROR3[ERROR3["INVALID_VERSION"] = 9] = "INVALID_VERSION"; - ERROR3[ERROR3["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; - ERROR3[ERROR3["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; - ERROR3[ERROR3["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; - ERROR3[ERROR3["INVALID_STATUS"] = 13] = "INVALID_STATUS"; - ERROR3[ERROR3["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; - ERROR3[ERROR3["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; - ERROR3[ERROR3["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; - ERROR3[ERROR3["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; - ERROR3[ERROR3["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; - ERROR3[ERROR3["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; - ERROR3[ERROR3["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; - ERROR3[ERROR3["PAUSED"] = 21] = "PAUSED"; - ERROR3[ERROR3["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; - ERROR3[ERROR3["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; - ERROR3[ERROR3["USER"] = 24] = "USER"; - })(ERROR2 = exports2.ERROR || (exports2.ERROR = {})); + var ERROR; + (function(ERROR2) { + ERROR2[ERROR2["OK"] = 0] = "OK"; + ERROR2[ERROR2["INTERNAL"] = 1] = "INTERNAL"; + ERROR2[ERROR2["STRICT"] = 2] = "STRICT"; + ERROR2[ERROR2["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR2[ERROR2["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR2[ERROR2["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR2[ERROR2["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR2[ERROR2["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR2[ERROR2["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR2[ERROR2["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR2[ERROR2["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR2[ERROR2["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR2[ERROR2["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR2[ERROR2["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR2[ERROR2["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR2[ERROR2["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR2[ERROR2["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR2[ERROR2["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR2[ERROR2["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR2[ERROR2["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR2[ERROR2["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR2[ERROR2["PAUSED"] = 21] = "PAUSED"; + ERROR2[ERROR2["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR2[ERROR2["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR2[ERROR2["USER"] = 24] = "USER"; + })(ERROR = exports2.ERROR || (exports2.ERROR = {})); var TYPE; (function(TYPE2) { TYPE2[TYPE2["BOTH"] = 0] = "BOTH"; @@ -3289,19 +3289,19 @@ var require_data_url = __commonJS({ function percentDecode(input) { const length = input.length; const output = new Uint8Array(length); - let j6 = 0; + let j7 = 0; for (let i6 = 0; i6 < length; ++i6) { const byte = input[i6]; if (byte !== 37) { - output[j6++] = byte; + output[j7++] = byte; } else if (byte === 37 && !(isHexCharByte(input[i6 + 1]) && isHexCharByte(input[i6 + 2]))) { - output[j6++] = 37; + output[j7++] = 37; } else { - output[j6++] = hexByteToNumber(input[i6 + 1]) << 4 | hexByteToNumber(input[i6 + 2]); + output[j7++] = hexByteToNumber(input[i6 + 1]) << 4 | hexByteToNumber(input[i6 + 2]); i6 += 2; } } - return length === j6 ? output : output.subarray(0, j6); + return length === j7 ? output : output.subarray(0, j7); } function parseMIMEType(input) { input = removeHTTPWhitespace(input, true, true); @@ -3552,7 +3552,7 @@ var require_data_url = __commonJS({ var require_webidl = __commonJS({ "../node_modules/undici/lib/web/fetch/webidl.js"(exports2, module2) { "use strict"; - var { types: types2, inspect } = require("util"); + var { types, inspect } = require("util"); var { markAsUncloneable } = require("worker_threads"); var { toUSVString } = require_util(); var webidl = {}; @@ -3576,15 +3576,15 @@ var require_webidl = __commonJS({ message: `"${context3.value}" is an invalid ${context3.type}.` }); }; - webidl.brandCheck = function(V2, I3, opts) { + webidl.brandCheck = function(V3, I4, opts) { if (opts?.strict !== false) { - if (!(V2 instanceof I3)) { + if (!(V3 instanceof I4)) { const err = new TypeError("Illegal invocation"); err.code = "ERR_INVALID_THIS"; throw err; } } else { - if (V2?.[Symbol.toStringTag] !== I3.prototype[Symbol.toStringTag]) { + if (V3?.[Symbol.toStringTag] !== I4.prototype[Symbol.toStringTag]) { const err = new TypeError("Illegal invocation"); err.code = "ERR_INVALID_THIS"; throw err; @@ -3605,8 +3605,8 @@ var require_webidl = __commonJS({ message: "Illegal constructor" }); }; - webidl.util.Type = function(V2) { - switch (typeof V2) { + webidl.util.Type = function(V3) { + switch (typeof V3) { case "undefined": return "Undefined"; case "boolean": @@ -3621,7 +3621,7 @@ var require_webidl = __commonJS({ return "BigInt"; case "function": case "object": { - if (V2 === null) { + if (V3 === null) { return "Null"; } return "Object"; @@ -3630,7 +3630,7 @@ var require_webidl = __commonJS({ }; webidl.util.markAsUncloneable = markAsUncloneable || (() => { }); - webidl.util.ConvertToInt = function(V2, bitLength, signedness, opts) { + webidl.util.ConvertToInt = function(V3, bitLength, signedness, opts) { let upperBound; let lowerBound; if (bitLength === 64) { @@ -3647,74 +3647,74 @@ var require_webidl = __commonJS({ lowerBound = Math.pow(-2, bitLength) - 1; upperBound = Math.pow(2, bitLength - 1) - 1; } - let x7 = Number(V2); - if (x7 === 0) { - x7 = 0; + let x8 = Number(V3); + if (x8 === 0) { + x8 = 0; } if (opts?.enforceRange === true) { - if (Number.isNaN(x7) || x7 === Number.POSITIVE_INFINITY || x7 === Number.NEGATIVE_INFINITY) { + if (Number.isNaN(x8) || x8 === Number.POSITIVE_INFINITY || x8 === Number.NEGATIVE_INFINITY) { throw webidl.errors.exception({ header: "Integer conversion", - message: `Could not convert ${webidl.util.Stringify(V2)} to an integer.` + message: `Could not convert ${webidl.util.Stringify(V3)} to an integer.` }); } - x7 = webidl.util.IntegerPart(x7); - if (x7 < lowerBound || x7 > upperBound) { + x8 = webidl.util.IntegerPart(x8); + if (x8 < lowerBound || x8 > upperBound) { throw webidl.errors.exception({ header: "Integer conversion", - message: `Value must be between ${lowerBound}-${upperBound}, got ${x7}.` + message: `Value must be between ${lowerBound}-${upperBound}, got ${x8}.` }); } - return x7; + return x8; } - if (!Number.isNaN(x7) && opts?.clamp === true) { - x7 = Math.min(Math.max(x7, lowerBound), upperBound); - if (Math.floor(x7) % 2 === 0) { - x7 = Math.floor(x7); + if (!Number.isNaN(x8) && opts?.clamp === true) { + x8 = Math.min(Math.max(x8, lowerBound), upperBound); + if (Math.floor(x8) % 2 === 0) { + x8 = Math.floor(x8); } else { - x7 = Math.ceil(x7); + x8 = Math.ceil(x8); } - return x7; + return x8; } - if (Number.isNaN(x7) || x7 === 0 && Object.is(0, x7) || x7 === Number.POSITIVE_INFINITY || x7 === Number.NEGATIVE_INFINITY) { + if (Number.isNaN(x8) || x8 === 0 && Object.is(0, x8) || x8 === Number.POSITIVE_INFINITY || x8 === Number.NEGATIVE_INFINITY) { return 0; } - x7 = webidl.util.IntegerPart(x7); - x7 = x7 % Math.pow(2, bitLength); - if (signedness === "signed" && x7 >= Math.pow(2, bitLength) - 1) { - return x7 - Math.pow(2, bitLength); + x8 = webidl.util.IntegerPart(x8); + x8 = x8 % Math.pow(2, bitLength); + if (signedness === "signed" && x8 >= Math.pow(2, bitLength) - 1) { + return x8 - Math.pow(2, bitLength); } - return x7; + return x8; }; - webidl.util.IntegerPart = function(n6) { - const r6 = Math.floor(Math.abs(n6)); - if (n6 < 0) { + webidl.util.IntegerPart = function(n12) { + const r6 = Math.floor(Math.abs(n12)); + if (n12 < 0) { return -1 * r6; } return r6; }; - webidl.util.Stringify = function(V2) { - const type = webidl.util.Type(V2); + webidl.util.Stringify = function(V3) { + const type = webidl.util.Type(V3); switch (type) { case "Symbol": - return `Symbol(${V2.description})`; + return `Symbol(${V3.description})`; case "Object": - return inspect(V2); + return inspect(V3); case "String": - return `"${V2}"`; + return `"${V3}"`; default: - return `${V2}`; + return `${V3}`; } }; webidl.sequenceConverter = function(converter) { - return (V2, prefix, argument, Iterable) => { - if (webidl.util.Type(V2) !== "Object") { + return (V3, prefix, argument, Iterable) => { + if (webidl.util.Type(V3) !== "Object") { throw webidl.errors.exception({ header: prefix, - message: `${argument} (${webidl.util.Stringify(V2)}) is not iterable.` + message: `${argument} (${webidl.util.Stringify(V3)}) is not iterable.` }); } - const method = typeof Iterable === "function" ? Iterable() : V2?.[Symbol.iterator]?.(); + const method = typeof Iterable === "function" ? Iterable() : V3?.[Symbol.iterator]?.(); const seq = []; let index = 0; if (method === void 0 || typeof method.next !== "function") { @@ -3734,29 +3734,29 @@ var require_webidl = __commonJS({ }; }; webidl.recordConverter = function(keyConverter, valueConverter) { - return (O2, prefix, argument) => { - if (webidl.util.Type(O2) !== "Object") { + return (O3, prefix, argument) => { + if (webidl.util.Type(O3) !== "Object") { throw webidl.errors.exception({ header: prefix, - message: `${argument} ("${webidl.util.Type(O2)}") is not an Object.` + message: `${argument} ("${webidl.util.Type(O3)}") is not an Object.` }); } const result = {}; - if (!types2.isProxy(O2)) { - const keys2 = [...Object.getOwnPropertyNames(O2), ...Object.getOwnPropertySymbols(O2)]; + if (!types.isProxy(O3)) { + const keys2 = [...Object.getOwnPropertyNames(O3), ...Object.getOwnPropertySymbols(O3)]; for (const key of keys2) { const typedKey = keyConverter(key, prefix, argument); - const typedValue = valueConverter(O2[key], prefix, argument); + const typedValue = valueConverter(O3[key], prefix, argument); result[typedKey] = typedValue; } return result; } - const keys = Reflect.ownKeys(O2); + const keys = Reflect.ownKeys(O3); for (const key of keys) { - const desc = Reflect.getOwnPropertyDescriptor(O2, key); + const desc = Reflect.getOwnPropertyDescriptor(O3, key); if (desc?.enumerable) { const typedKey = keyConverter(key, prefix, argument); - const typedValue = valueConverter(O2[key], prefix, argument); + const typedValue = valueConverter(O3[key], prefix, argument); result[typedKey] = typedValue; } } @@ -3764,14 +3764,14 @@ var require_webidl = __commonJS({ }; }; webidl.interfaceConverter = function(i6) { - return (V2, prefix, argument, opts) => { - if (opts?.strict !== false && !(V2 instanceof i6)) { + return (V3, prefix, argument, opts) => { + if (opts?.strict !== false && !(V3 instanceof i6)) { throw webidl.errors.exception({ header: prefix, - message: `Expected ${argument} ("${webidl.util.Stringify(V2)}") to be an instance of ${i6.name}.` + message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${i6.name}.` }); } - return V2; + return V3; }; }; webidl.dictionaryConverter = function(converters) { @@ -3816,138 +3816,138 @@ var require_webidl = __commonJS({ }; }; webidl.nullableConverter = function(converter) { - return (V2, prefix, argument) => { - if (V2 === null) { - return V2; + return (V3, prefix, argument) => { + if (V3 === null) { + return V3; } - return converter(V2, prefix, argument); + return converter(V3, prefix, argument); }; }; - webidl.converters.DOMString = function(V2, prefix, argument, opts) { - if (V2 === null && opts?.legacyNullToEmptyString) { + webidl.converters.DOMString = function(V3, prefix, argument, opts) { + if (V3 === null && opts?.legacyNullToEmptyString) { return ""; } - if (typeof V2 === "symbol") { + if (typeof V3 === "symbol") { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a DOMString.` }); } - return String(V2); + return String(V3); }; - webidl.converters.ByteString = function(V2, prefix, argument) { - const x7 = webidl.converters.DOMString(V2, prefix, argument); - for (let index = 0; index < x7.length; index++) { - if (x7.charCodeAt(index) > 255) { + webidl.converters.ByteString = function(V3, prefix, argument) { + const x8 = webidl.converters.DOMString(V3, prefix, argument); + for (let index = 0; index < x8.length; index++) { + if (x8.charCodeAt(index) > 255) { throw new TypeError( - `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x7.charCodeAt(index)} which is greater than 255.` + `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x8.charCodeAt(index)} which is greater than 255.` ); } } - return x7; + return x8; }; webidl.converters.USVString = toUSVString; - webidl.converters.boolean = function(V2) { - const x7 = Boolean(V2); - return x7; + webidl.converters.boolean = function(V3) { + const x8 = Boolean(V3); + return x8; }; - webidl.converters.any = function(V2) { - return V2; + webidl.converters.any = function(V3) { + return V3; }; - webidl.converters["long long"] = function(V2, prefix, argument) { - const x7 = webidl.util.ConvertToInt(V2, 64, "signed", void 0, prefix, argument); - return x7; + webidl.converters["long long"] = function(V3, prefix, argument) { + const x8 = webidl.util.ConvertToInt(V3, 64, "signed", void 0, prefix, argument); + return x8; }; - webidl.converters["unsigned long long"] = function(V2, prefix, argument) { - const x7 = webidl.util.ConvertToInt(V2, 64, "unsigned", void 0, prefix, argument); - return x7; + webidl.converters["unsigned long long"] = function(V3, prefix, argument) { + const x8 = webidl.util.ConvertToInt(V3, 64, "unsigned", void 0, prefix, argument); + return x8; }; - webidl.converters["unsigned long"] = function(V2, prefix, argument) { - const x7 = webidl.util.ConvertToInt(V2, 32, "unsigned", void 0, prefix, argument); - return x7; + webidl.converters["unsigned long"] = function(V3, prefix, argument) { + const x8 = webidl.util.ConvertToInt(V3, 32, "unsigned", void 0, prefix, argument); + return x8; }; - webidl.converters["unsigned short"] = function(V2, prefix, argument, opts) { - const x7 = webidl.util.ConvertToInt(V2, 16, "unsigned", opts, prefix, argument); - return x7; + webidl.converters["unsigned short"] = function(V3, prefix, argument, opts) { + const x8 = webidl.util.ConvertToInt(V3, 16, "unsigned", opts, prefix, argument); + return x8; }; - webidl.converters.ArrayBuffer = function(V2, prefix, argument, opts) { - if (webidl.util.Type(V2) !== "Object" || !types2.isAnyArrayBuffer(V2)) { + webidl.converters.ArrayBuffer = function(V3, prefix, argument, opts) { + if (webidl.util.Type(V3) !== "Object" || !types.isAnyArrayBuffer(V3)) { throw webidl.errors.conversionFailed({ prefix, - argument: `${argument} ("${webidl.util.Stringify(V2)}")`, + argument: `${argument} ("${webidl.util.Stringify(V3)}")`, types: ["ArrayBuffer"] }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V2)) { + if (opts?.allowShared === false && types.isSharedArrayBuffer(V3)) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "SharedArrayBuffer is not allowed." }); } - if (V2.resizable || V2.growable) { + if (V3.resizable || V3.growable) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "Received a resizable ArrayBuffer." }); } - return V2; + return V3; }; - webidl.converters.TypedArray = function(V2, T2, prefix, name, opts) { - if (webidl.util.Type(V2) !== "Object" || !types2.isTypedArray(V2) || V2.constructor.name !== T2.name) { + webidl.converters.TypedArray = function(V3, T3, prefix, name, opts) { + if (webidl.util.Type(V3) !== "Object" || !types.isTypedArray(V3) || V3.constructor.name !== T3.name) { throw webidl.errors.conversionFailed({ prefix, - argument: `${name} ("${webidl.util.Stringify(V2)}")`, - types: [T2.name] + argument: `${name} ("${webidl.util.Stringify(V3)}")`, + types: [T3.name] }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V2.buffer)) { + if (opts?.allowShared === false && types.isSharedArrayBuffer(V3.buffer)) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "SharedArrayBuffer is not allowed." }); } - if (V2.buffer.resizable || V2.buffer.growable) { + if (V3.buffer.resizable || V3.buffer.growable) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "Received a resizable ArrayBuffer." }); } - return V2; + return V3; }; - webidl.converters.DataView = function(V2, prefix, name, opts) { - if (webidl.util.Type(V2) !== "Object" || !types2.isDataView(V2)) { + webidl.converters.DataView = function(V3, prefix, name, opts) { + if (webidl.util.Type(V3) !== "Object" || !types.isDataView(V3)) { throw webidl.errors.exception({ header: prefix, message: `${name} is not a DataView.` }); } - if (opts?.allowShared === false && types2.isSharedArrayBuffer(V2.buffer)) { + if (opts?.allowShared === false && types.isSharedArrayBuffer(V3.buffer)) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "SharedArrayBuffer is not allowed." }); } - if (V2.buffer.resizable || V2.buffer.growable) { + if (V3.buffer.resizable || V3.buffer.growable) { throw webidl.errors.exception({ header: "ArrayBuffer", message: "Received a resizable ArrayBuffer." }); } - return V2; + return V3; }; - webidl.converters.BufferSource = function(V2, prefix, name, opts) { - if (types2.isAnyArrayBuffer(V2)) { - return webidl.converters.ArrayBuffer(V2, prefix, name, { ...opts, allowShared: false }); + webidl.converters.BufferSource = function(V3, prefix, name, opts) { + if (types.isAnyArrayBuffer(V3)) { + return webidl.converters.ArrayBuffer(V3, prefix, name, { ...opts, allowShared: false }); } - if (types2.isTypedArray(V2)) { - return webidl.converters.TypedArray(V2, V2.constructor, prefix, name, { ...opts, allowShared: false }); + if (types.isTypedArray(V3)) { + return webidl.converters.TypedArray(V3, V3.constructor, prefix, name, { ...opts, allowShared: false }); } - if (types2.isDataView(V2)) { - return webidl.converters.DataView(V2, prefix, name, { ...opts, allowShared: false }); + if (types.isDataView(V3)) { + return webidl.converters.DataView(V3, prefix, name, { ...opts, allowShared: false }); } throw webidl.errors.conversionFailed({ prefix, - argument: `${name} ("${webidl.util.Stringify(V2)}")`, + argument: `${name} ("${webidl.util.Stringify(V3)}")`, types: ["BufferSource"] }); }; @@ -4355,11 +4355,11 @@ var require_util2 = __commonJS({ } function tryUpgradeRequestToAPotentiallyTrustworthyURL(request4) { } - function sameOrigin(A3, B3) { - if (A3.origin === B3.origin && A3.origin === "null") { + function sameOrigin(A4, B4) { + if (A4.origin === B4.origin && A4.origin === "null") { return true; } - if (A3.protocol === B3.protocol && A3.hostname === B3.hostname && A3.port === B3.port) { + if (A4.protocol === B4.protocol && A4.hostname === B4.hostname && A4.port === B4.port) { return true; } return false; @@ -4533,8 +4533,8 @@ var require_util2 = __commonJS({ errorSteps(e6); } } - function isReadableStreamLike(stream3) { - return stream3 instanceof ReadableStream || stream3[Symbol.toStringTag] === "ReadableStream" && typeof stream3.tee === "function"; + function isReadableStreamLike(stream2) { + return stream2 instanceof ReadableStream || stream2[Symbol.toStringTag] === "ReadableStream" && typeof stream2.tee === "function"; } function readableStreamClose(controller) { try { @@ -4860,12 +4860,12 @@ var require_file = __commonJS({ var { webidl } = require_webidl(); var FileLike = class _FileLike { constructor(blobLike, fileName, options = {}) { - const n6 = fileName; + const n12 = fileName; const t12 = options.type; const d6 = options.lastModified ?? Date.now(); this[kState] = { blobLike, - name: n6, + name: n12, type: t12, lastModified: d6 }; @@ -5350,20 +5350,20 @@ var require_body = __commonJS({ var streamRegistry; if (hasFinalizationRegistry) { streamRegistry = new FinalizationRegistry((weakRef) => { - const stream3 = weakRef.deref(); - if (stream3 && !stream3.locked && !isDisturbed(stream3) && !isErrored(stream3)) { - stream3.cancel("Response object has been garbage collected").catch(noop2); + const stream2 = weakRef.deref(); + if (stream2 && !stream2.locked && !isDisturbed(stream2) && !isErrored(stream2)) { + stream2.cancel("Response object has been garbage collected").catch(noop2); } }); } function extractBody(object, keepalive = false) { - let stream3 = null; + let stream2 = null; if (object instanceof ReadableStream) { - stream3 = object; + stream2 = object; } else if (isBlobLike(object)) { - stream3 = object.stream(); + stream2 = object.stream(); } else { - stream3 = new ReadableStream({ + stream2 = new ReadableStream({ async pull(controller) { const buffer = typeof source === "string" ? textEncoder.encode(source) : source; if (buffer.byteLength) { @@ -5376,7 +5376,7 @@ var require_body = __commonJS({ type: "bytes" }); } - assert(isReadableStreamLike(stream3)); + assert(isReadableStreamLike(stream2)); let action = null; let source = null; let length = null; @@ -5395,7 +5395,7 @@ var require_body = __commonJS({ const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`; const prefix = `--${boundary}\r Content-Disposition: form-data`; - const escape2 = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + const escape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n"); const blobParts = []; const rn = new Uint8Array([13, 10]); @@ -5403,14 +5403,14 @@ Content-Disposition: form-data`; let hasUnknownSizeValue = false; for (const [name, value] of object) { if (typeof value === "string") { - const chunk2 = textEncoder.encode(prefix + `; name="${escape2(normalizeLinefeeds(name))}"\r + const chunk2 = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"\r \r ${normalizeLinefeeds(value)}\r `); blobParts.push(chunk2); length += chunk2.byteLength; } else { - const chunk2 = textEncoder.encode(`${prefix}; name="${escape2(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape2(value.name)}"` : "") + `\r + const chunk2 = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : "") + `\r Content-Type: ${value.type || "application/octet-stream"}\r \r `); @@ -5455,14 +5455,14 @@ Content-Type: ${value.type || "application/octet-stream"}\r "Response body object should not be disturbed or locked" ); } - stream3 = object instanceof ReadableStream ? object : ReadableStreamFrom(object); + stream2 = object instanceof ReadableStream ? object : ReadableStreamFrom(object); } if (typeof source === "string" || util17.isBuffer(source)) { length = Buffer.byteLength(source); } if (action != null) { let iterator2; - stream3 = new ReadableStream({ + stream2 = new ReadableStream({ async start() { iterator2 = action(object)[Symbol.asyncIterator](); }, @@ -5474,7 +5474,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r controller.byobRequest?.respond(0); }); } else { - if (!isErrored(stream3)) { + if (!isErrored(stream2)) { const buffer = new Uint8Array(value); if (buffer.byteLength) { controller.enqueue(buffer); @@ -5489,7 +5489,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r type: "bytes" }); } - const body = { stream: stream3, source, length }; + const body = { stream: stream2, source, length }; return [body, type]; } function safelyExtractBody(object, keepalive = false) { @@ -5696,35 +5696,35 @@ var require_client_h1 = __commonJS({ return await WebAssembly.instantiate(mod, { env: { /* eslint-disable camelcase */ - wasm_on_url: (p6, at2, len) => { + wasm_on_url: (p6, at3, len) => { return 0; }, - wasm_on_status: (p6, at2, len) => { + wasm_on_status: (p6, at3, len) => { assert(currentParser.ptr === p6); - const start = at2 - currentBufferPtr + currentBufferRef.byteOffset; + const start = at3 - currentBufferPtr + currentBufferRef.byteOffset; return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0; }, wasm_on_message_begin: (p6) => { assert(currentParser.ptr === p6); return currentParser.onMessageBegin() || 0; }, - wasm_on_header_field: (p6, at2, len) => { + wasm_on_header_field: (p6, at3, len) => { assert(currentParser.ptr === p6); - const start = at2 - currentBufferPtr + currentBufferRef.byteOffset; + const start = at3 - currentBufferPtr + currentBufferRef.byteOffset; return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0; }, - wasm_on_header_value: (p6, at2, len) => { + wasm_on_header_value: (p6, at3, len) => { assert(currentParser.ptr === p6); - const start = at2 - currentBufferPtr + currentBufferRef.byteOffset; + const start = at3 - currentBufferPtr + currentBufferRef.byteOffset; return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0; }, wasm_on_headers_complete: (p6, statusCode, upgrade, shouldKeepAlive) => { assert(currentParser.ptr === p6); return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0; }, - wasm_on_body: (p6, at2, len) => { + wasm_on_body: (p6, at3, len) => { assert(currentParser.ptr === p6); - const start = at2 - currentBufferPtr + currentBufferRef.byteOffset; + const start = at3 - currentBufferPtr + currentBufferRef.byteOffset; return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0; }, wasm_on_message_complete: (p6) => { @@ -6256,7 +6256,7 @@ var require_client_h1 = __commonJS({ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; } function writeH1(client, request4) { - const { method, path: path7, host, upgrade, blocking, reset } = request4; + const { method, path: path6, host, upgrade, blocking, reset } = request4; let { body, headers, contentLength } = request4; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH"; if (util17.isFormDataLike(body)) { @@ -6322,7 +6322,7 @@ var require_client_h1 = __commonJS({ if (blocking) { socket[kBlocking] = true; } - let header = `${method} ${path7} HTTP/1.1\r + let header = `${method} ${path6} HTTP/1.1\r `; if (typeof host === "string") { header += `host: ${host}\r @@ -6340,9 +6340,9 @@ upgrade: ${upgrade}\r header += "connection: close\r\n"; } if (Array.isArray(headers)) { - for (let n6 = 0; n6 < headers.length; n6 += 2) { - const key = headers[n6 + 0]; - const val = headers[n6 + 1]; + for (let n12 = 0; n12 < headers.length; n12 += 2) { + const key = headers[n12 + 0]; + const val = headers[n12 + 1]; if (Array.isArray(val)) { for (let i6 = 0; i6 < val.length; i6++) { header += `${key}: ${val[i6]}\r @@ -6848,16 +6848,16 @@ var require_client_h2 = __commonJS({ } function writeH2(client, request4) { const session = client[kHTTP2Session]; - const { method, path: path7, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4; + const { method, path: path6, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4; let { body } = request4; if (upgrade) { util17.errorRequest(client, request4, new Error("Upgrade not supported for H2")); return false; } const headers = {}; - for (let n6 = 0; n6 < reqHeaders.length; n6 += 2) { - const key = reqHeaders[n6 + 0]; - const val = reqHeaders[n6 + 1]; + for (let n12 = 0; n12 < reqHeaders.length; n12 += 2) { + const key = reqHeaders[n12 + 0]; + const val = reqHeaders[n12 + 1]; if (Array.isArray(val)) { for (let i6 = 0; i6 < val.length; i6++) { if (headers[key]) { @@ -6870,7 +6870,7 @@ var require_client_h2 = __commonJS({ headers[key] = val; } } - let stream3; + let stream2; const { hostname, port } = client[kUrl]; headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`; headers[HTTP2_HEADER_METHOD] = method; @@ -6880,8 +6880,8 @@ var require_client_h2 = __commonJS({ } err = err || new RequestAbortedError(); util17.errorRequest(client, request4, err); - if (stream3 != null) { - util17.destroy(stream3, err); + if (stream2 != null) { + util17.destroy(stream2, err); } util17.destroy(body, err); client[kQueue][client[kRunningIdx]++] = null; @@ -6897,25 +6897,25 @@ var require_client_h2 = __commonJS({ } if (method === "CONNECT") { session.ref(); - stream3 = session.request(headers, { endStream: false, signal }); - if (stream3.id && !stream3.pending) { - request4.onUpgrade(null, null, stream3); + stream2 = session.request(headers, { endStream: false, signal }); + if (stream2.id && !stream2.pending) { + request4.onUpgrade(null, null, stream2); ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; } else { - stream3.once("ready", () => { - request4.onUpgrade(null, null, stream3); + stream2.once("ready", () => { + request4.onUpgrade(null, null, stream2); ++session[kOpenStreams]; client[kQueue][client[kRunningIdx]++] = null; }); } - stream3.once("close", () => { + stream2.once("close", () => { session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) session.unref(); }); return true; } - headers[HTTP2_HEADER_PATH] = path7; + headers[HTTP2_HEADER_PATH] = path6; headers[HTTP2_HEADER_SCHEME] = "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { @@ -6950,36 +6950,36 @@ var require_client_h2 = __commonJS({ const shouldEndStream = method === "GET" || method === "HEAD" || body === null; if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = "100-continue"; - stream3 = session.request(headers, { endStream: shouldEndStream, signal }); - stream3.once("continue", writeBodyH2); + stream2 = session.request(headers, { endStream: shouldEndStream, signal }); + stream2.once("continue", writeBodyH2); } else { - stream3 = session.request(headers, { + stream2 = session.request(headers, { endStream: shouldEndStream, signal }); writeBodyH2(); } ++session[kOpenStreams]; - stream3.once("response", (headers2) => { + stream2.once("response", (headers2) => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2; request4.onResponseStarted(); if (request4.aborted) { const err = new RequestAbortedError(); util17.errorRequest(client, request4, err); - util17.destroy(stream3, err); + util17.destroy(stream2, err); return; } - if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream3.resume.bind(stream3), "") === false) { - stream3.pause(); + if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream2.resume.bind(stream2), "") === false) { + stream2.pause(); } - stream3.on("data", (chunk) => { + stream2.on("data", (chunk) => { if (request4.onData(chunk) === false) { - stream3.pause(); + stream2.pause(); } }); }); - stream3.once("end", () => { - if (stream3.state?.state == null || stream3.state.state < 6) { + stream2.once("end", () => { + if (stream2.state?.state == null || stream2.state.state < 6) { request4.onComplete([]); } if (session[kOpenStreams] === 0) { @@ -6990,16 +6990,16 @@ var require_client_h2 = __commonJS({ client[kPendingIdx] = client[kRunningIdx]; client[kResume](); }); - stream3.once("close", () => { + stream2.once("close", () => { session[kOpenStreams] -= 1; if (session[kOpenStreams] === 0) { session.unref(); } }); - stream3.once("error", function(err) { + stream2.once("error", function(err) { abort(err); }); - stream3.once("frameError", (type, code) => { + stream2.once("frameError", (type, code) => { abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)); }); return true; @@ -7007,7 +7007,7 @@ var require_client_h2 = __commonJS({ if (!body || contentLength === 0) { writeBuffer( abort, - stream3, + stream2, null, client, request4, @@ -7018,7 +7018,7 @@ var require_client_h2 = __commonJS({ } else if (util17.isBuffer(body)) { writeBuffer( abort, - stream3, + stream2, body, client, request4, @@ -7030,7 +7030,7 @@ var require_client_h2 = __commonJS({ if (typeof body.stream === "function") { writeIterable( abort, - stream3, + stream2, body.stream(), client, request4, @@ -7041,7 +7041,7 @@ var require_client_h2 = __commonJS({ } else { writeBlob( abort, - stream3, + stream2, body, client, request4, @@ -7055,7 +7055,7 @@ var require_client_h2 = __commonJS({ abort, client[kSocket], expectsPayload, - stream3, + stream2, body, client, request4, @@ -7064,7 +7064,7 @@ var require_client_h2 = __commonJS({ } else if (util17.isIterable(body)) { writeIterable( abort, - stream3, + stream2, body, client, request4, @@ -7268,9 +7268,9 @@ var require_redirect_handler = __commonJS({ return this.handler.onHeaders(statusCode, headers, resume, statusText); } const { origin, pathname, search } = util17.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); - const path7 = search ? `${pathname}${search}` : pathname; + const path6 = search ? `${pathname}${search}` : pathname; this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); - this.opts.path = path7; + this.opts.path = path6; this.opts.origin = origin; this.opts.maxRedirections = 0; this.opts.query = null; @@ -7584,7 +7584,7 @@ var require_client = __commonJS({ this[kQueue] = []; this[kRunningIdx] = 0; this[kPendingIdx] = 0; - this[kResume] = (sync2) => resume(this, sync2); + this[kResume] = (sync) => resume(this, sync); this[kOnError] = (err) => onError(this, err); } get pipelining() { @@ -7789,12 +7789,12 @@ var require_client = __commonJS({ client[kNeedDrain] = 0; client.emit("drain", client[kUrl], [client]); } - function resume(client, sync2) { + function resume(client, sync) { if (client[kResuming] === 2) { return; } client[kResuming] = 2; - _resume(client, sync2); + _resume(client, sync); client[kResuming] = 0; if (client[kRunningIdx] > 256) { client[kQueue].splice(0, client[kRunningIdx]); @@ -7802,7 +7802,7 @@ var require_client = __commonJS({ client[kRunningIdx] = 0; } } - function _resume(client, sync2) { + function _resume(client, sync) { while (true) { if (client.destroyed) { assert(client[kPending] === 0); @@ -7819,7 +7819,7 @@ var require_client = __commonJS({ if (client[kBusy]) { client[kNeedDrain] = 2; } else if (client[kNeedDrain] === 2) { - if (sync2) { + if (sync) { client[kNeedDrain] = 1; queueMicrotask(() => emitDrain(client)); } else { @@ -8505,10 +8505,10 @@ var require_proxy_agent = __commonJS({ }; const { origin, - path: path7 = "/", + path: path6 = "/", headers = {} } = opts; - opts.path = origin + path7; + opts.path = origin + path6; if (!("host" in headers) && !("Host" in headers)) { const { host } = new URL2(origin); headers.host = host; @@ -9001,8 +9001,8 @@ var require_retry_handler = __commonJS({ } if (this.end == null) { if (statusCode === 206) { - const range3 = parseRangeHeader(headers["content-range"]); - if (range3 == null) { + const range2 = parseRangeHeader(headers["content-range"]); + if (range2 == null) { return this.handler.onHeaders( statusCode, rawHeaders, @@ -9010,7 +9010,7 @@ var require_retry_handler = __commonJS({ statusMessage ); } - const { start, size, end = size - 1 } = range3; + const { start, size, end = size - 1 } = range2; assert( start != null && Number.isFinite(start), "content-range mismatch" @@ -9299,13 +9299,13 @@ var require_readable = __commonJS({ function isUnusable(self2) { return util17.isDisturbed(self2) || isLocked(self2); } - async function consume(stream3, type) { - assert(!stream3[kConsume]); + async function consume(stream2, type) { + assert(!stream2[kConsume]); return new Promise((resolve3, reject2) => { - if (isUnusable(stream3)) { - const rState = stream3._readableState; + if (isUnusable(stream2)) { + const rState = stream2._readableState; if (rState.destroyed && rState.closeEmitted === false) { - stream3.on("error", (err) => { + stream2.on("error", (err) => { reject2(err); }).on("close", () => { reject2(new TypeError("unusable")); @@ -9315,22 +9315,22 @@ var require_readable = __commonJS({ } } else { queueMicrotask(() => { - stream3[kConsume] = { + stream2[kConsume] = { type, - stream: stream3, + stream: stream2, resolve: resolve3, reject: reject2, length: 0, body: [] }; - stream3.on("error", function(err) { + stream2.on("error", function(err) { consumeFinish(this[kConsume], err); }).on("close", function() { if (this[kConsume].body !== null) { consumeFinish(this[kConsume], new RequestAbortedError()); } }); - consumeStart(stream3[kConsume]); + consumeStart(stream2[kConsume]); }); } }); @@ -9343,8 +9343,8 @@ var require_readable = __commonJS({ if (state2.bufferIndex) { const start = state2.bufferIndex; const end = state2.buffer.length; - for (let n6 = start; n6 < end; n6++) { - consumePush(consume2, state2.buffer[n6]); + for (let n12 = start; n12 < end; n12++) { + consumePush(consume2, state2.buffer[n12]); } } else { for (const chunk of state2.buffer) { @@ -9388,7 +9388,7 @@ var require_readable = __commonJS({ return buffer; } function consumeEnd(consume2) { - const { type, body, resolve: resolve3, stream: stream3, length } = consume2; + const { type, body, resolve: resolve3, stream: stream2, length } = consume2; try { if (type === "text") { resolve3(chunksDecode(body, length)); @@ -9397,13 +9397,13 @@ var require_readable = __commonJS({ } else if (type === "arrayBuffer") { resolve3(chunksConcat(body, length).buffer); } else if (type === "blob") { - resolve3(new Blob(body, { type: stream3[kContentType] })); + resolve3(new Blob(body, { type: stream2[kContentType] })); } else if (type === "bytes") { resolve3(chunksConcat(body, length)); } consumeFinish(consume2); } catch (err) { - stream3.destroy(err); + stream2.destroy(err); } } function consumePush(consume2, chunk) { @@ -9881,10 +9881,10 @@ var require_api_stream = __commonJS({ } } }; - function stream3(opts, factory, callback) { + function stream2(opts, factory, callback) { if (callback === void 0) { return new Promise((resolve3, reject2) => { - stream3.call(this, opts, factory, (err, data) => { + stream2.call(this, opts, factory, (err, data) => { return err ? reject2(err) : resolve3(data); }); }); @@ -9899,7 +9899,7 @@ var require_api_stream = __commonJS({ queueMicrotask(() => callback(err, { opaque })); } } - module2.exports = stream3; + module2.exports = stream2; } }); @@ -10369,15 +10369,15 @@ var require_mock_utils = __commonJS({ isPromise } } = require("util"); - function matchValue(match2, value) { - if (typeof match2 === "string") { - return match2 === value; + function matchValue(match, value) { + if (typeof match === "string") { + return match === value; } - if (match2 instanceof RegExp) { - return match2.test(value); + if (match instanceof RegExp) { + return match.test(value); } - if (typeof match2 === "function") { - return match2(value) === true; + if (typeof match === "function") { + return match(value) === true; } return false; } @@ -10431,20 +10431,20 @@ var require_mock_utils = __commonJS({ } return true; } - function safeUrl(path7) { - if (typeof path7 !== "string") { - return path7; + function safeUrl(path6) { + if (typeof path6 !== "string") { + return path6; } - const pathSegments = path7.split("?"); + const pathSegments = path6.split("?"); if (pathSegments.length !== 2) { - return path7; + return path6; } const qp = new URLSearchParams(pathSegments.pop()); qp.sort(); return [...pathSegments, qp.toString()].join("?"); } - function matchKey(mockDispatch2, { path: path7, method, body, headers }) { - const pathMatch = matchValue(mockDispatch2.path, path7); + function matchKey(mockDispatch2, { path: path6, method, body, headers }) { + const pathMatch = matchValue(mockDispatch2.path, path6); const methodMatch = matchValue(mockDispatch2.method, method); const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true; const headersMatch = matchHeaders(mockDispatch2, headers); @@ -10466,7 +10466,7 @@ var require_mock_utils = __commonJS({ function getMockDispatch(mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path; const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath; - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path7 }) => matchValue(safeUrl(path7), resolvedPath)); + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path6 }) => matchValue(safeUrl(path6), resolvedPath)); if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`); } @@ -10504,9 +10504,9 @@ var require_mock_utils = __commonJS({ } } function buildKey(opts) { - const { path: path7, method, body, headers, query } = opts; + const { path: path6, method, body, headers, query } = opts; return { - path: path7, + path: path6, method, body, headers, @@ -10521,8 +10521,8 @@ var require_mock_utils = __commonJS({ const value = data[key]; const name = Buffer.from(`${key}`); if (Array.isArray(value)) { - for (let j6 = 0; j6 < value.length; ++j6) { - result.push(name, Buffer.from(`${value[j6]}`)); + for (let j7 = 0; j7 < value.length; ++j7) { + result.push(name, Buffer.from(`${value[j7]}`)); } } else { result.push(name, Buffer.from(`${value}`)); @@ -10969,10 +10969,10 @@ var require_pending_interceptors_formatter = __commonJS({ } format(pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( - ({ method, path: path7, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + ({ method, path: path6, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, - Path: path7, + Path: path6, "Status code": statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, @@ -11645,10 +11645,10 @@ var require_headers = __commonJS({ } function headerValueNormalize(potentialValue) { let i6 = 0; - let j6 = potentialValue.length; - while (j6 > i6 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j6 - 1))) --j6; - while (j6 > i6 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i6))) ++i6; - return i6 === 0 && j6 === potentialValue.length ? potentialValue : potentialValue.substring(i6, j6); + let j7 = potentialValue.length; + while (j7 > i6 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j7 - 1))) --j7; + while (j7 > i6 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i6))) ++i6; + return i6 === 0 && j7 === potentialValue.length ? potentialValue : potentialValue.substring(i6, j7); } function fill(headers, object) { if (Array.isArray(object)) { @@ -11827,26 +11827,26 @@ var require_headers = __commonJS({ const firstValue = iterator2.next().value; array[0] = [firstValue[0], firstValue[1].value]; assert(firstValue[1].value !== null); - for (let i6 = 1, j6 = 0, right = 0, left = 0, pivot3 = 0, x7, value; i6 < size; ++i6) { + for (let i6 = 1, j7 = 0, right = 0, left = 0, pivot3 = 0, x8, value; i6 < size; ++i6) { value = iterator2.next().value; - x7 = array[i6] = [value[0], value[1].value]; - assert(x7[1] !== null); + x8 = array[i6] = [value[0], value[1].value]; + assert(x8[1] !== null); left = 0; right = i6; while (left < right) { pivot3 = left + (right - left >> 1); - if (array[pivot3][0] <= x7[0]) { + if (array[pivot3][0] <= x8[0]) { left = pivot3 + 1; } else { right = pivot3; } } if (i6 !== pivot3) { - j6 = i6; - while (j6 > left) { - array[j6] = array[--j6]; + j7 = i6; + while (j7 > left) { + array[j7] = array[--j7]; } - array[left] = x7; + array[left] = x8; } } if (!iterator2.next().done) { @@ -11987,8 +11987,8 @@ var require_headers = __commonJS({ for (let i6 = 0; i6 < names3.length; ++i6) { const { 0: name, 1: value } = names3[i6]; if (name === "set-cookie") { - for (let j6 = 0; j6 < cookies.length; ++j6) { - headers.push([name, cookies[j6]]); + for (let j7 = 0; j7 < cookies.length; ++j7) { + headers.push([name, cookies[j7]]); } } else { headers.push([name, value]); @@ -12034,19 +12034,19 @@ var require_headers = __commonJS({ enumerable: false } }); - webidl.converters.HeadersInit = function(V2, prefix, argument) { - if (webidl.util.Type(V2) === "Object") { - const iterator2 = Reflect.get(V2, Symbol.iterator); - if (!util17.types.isProxy(V2) && iterator2 === Headers3.prototype.entries) { + webidl.converters.HeadersInit = function(V3, prefix, argument) { + if (webidl.util.Type(V3) === "Object") { + const iterator2 = Reflect.get(V3, Symbol.iterator); + if (!util17.types.isProxy(V3) && iterator2 === Headers3.prototype.entries) { try { - return getHeadersList(V2).entriesList; + return getHeadersList(V3).entriesList; } catch { } } if (typeof iterator2 === "function") { - return webidl.converters["sequence>"](V2, prefix, argument, iterator2.bind(V2)); + return webidl.converters["sequence>"](V3, prefix, argument, iterator2.bind(V3)); } - return webidl.converters["record"](V2, prefix, argument); + return webidl.converters["record"](V3, prefix, argument); } throw webidl.errors.conversionFailed({ prefix: "Headers constructor", @@ -12097,7 +12097,7 @@ var require_response = __commonJS({ var { URLSerializer } = require_data_url(); var { kConstruct } = require_symbols(); var assert = require("assert"); - var { types: types2 } = require("util"); + var { types } = require("util"); var textEncoder = new TextEncoder("utf-8"); var Response = class _Response { // Creates network error Response. @@ -12411,32 +12411,32 @@ var require_response = __commonJS({ webidl.converters.URLSearchParams = webidl.interfaceConverter( URLSearchParams ); - webidl.converters.XMLHttpRequestBodyInit = function(V2, prefix, name) { - if (typeof V2 === "string") { - return webidl.converters.USVString(V2, prefix, name); + webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name) { + if (typeof V3 === "string") { + return webidl.converters.USVString(V3, prefix, name); } - if (isBlobLike(V2)) { - return webidl.converters.Blob(V2, prefix, name, { strict: false }); + if (isBlobLike(V3)) { + return webidl.converters.Blob(V3, prefix, name, { strict: false }); } - if (ArrayBuffer.isView(V2) || types2.isArrayBuffer(V2)) { - return webidl.converters.BufferSource(V2, prefix, name); + if (ArrayBuffer.isView(V3) || types.isArrayBuffer(V3)) { + return webidl.converters.BufferSource(V3, prefix, name); } - if (util17.isFormDataLike(V2)) { - return webidl.converters.FormData(V2, prefix, name, { strict: false }); + if (util17.isFormDataLike(V3)) { + return webidl.converters.FormData(V3, prefix, name, { strict: false }); } - if (V2 instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V2, prefix, name); + if (V3 instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V3, prefix, name); } - return webidl.converters.DOMString(V2, prefix, name); + return webidl.converters.DOMString(V3, prefix, name); }; - webidl.converters.BodyInit = function(V2, prefix, argument) { - if (V2 instanceof ReadableStream) { - return webidl.converters.ReadableStream(V2, prefix, argument); + webidl.converters.BodyInit = function(V3, prefix, argument) { + if (V3 instanceof ReadableStream) { + return webidl.converters.ReadableStream(V3, prefix, argument); } - if (V2?.[Symbol.asyncIterator]) { - return V2; + if (V3?.[Symbol.asyncIterator]) { + return V3; } - return webidl.converters.XMLHttpRequestBodyInit(V2, prefix, argument); + return webidl.converters.XMLHttpRequestBodyInit(V3, prefix, argument); }; webidl.converters.ResponseInit = webidl.dictionaryConverter([ { @@ -13105,14 +13105,14 @@ var require_request2 = __commonJS({ webidl.converters.Request = webidl.interfaceConverter( Request2 ); - webidl.converters.RequestInfo = function(V2, prefix, argument) { - if (typeof V2 === "string") { - return webidl.converters.USVString(V2, prefix, argument); + webidl.converters.RequestInfo = function(V3, prefix, argument) { + if (typeof V3 === "string") { + return webidl.converters.USVString(V3, prefix, argument); } - if (V2 instanceof Request2) { - return webidl.converters.Request(V2, prefix, argument); + if (V3 instanceof Request2) { + return webidl.converters.Request(V3, prefix, argument); } - return webidl.converters.USVString(V2, prefix, argument); + return webidl.converters.USVString(V3, prefix, argument); }; webidl.converters.AbortSignal = webidl.interfaceConverter( AbortSignal @@ -13265,7 +13265,7 @@ var require_fetch = __commonJS({ } = require_constants3(); var EE = require("events"); var { Readable: Readable8, pipeline, finished } = require("stream"); - var { addAbortListener, isErrored, isReadable: isReadable2, bufferToLowerCasedHeaderName } = require_util(); + var { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = require_util(); var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url(); var { getGlobalDispatcher } = require_global2(); var { webidl } = require_webidl(); @@ -13400,7 +13400,7 @@ var require_fetch = __commonJS({ if (p6) { p6.reject(error2); } - if (request4.body != null && isReadable2(request4.body?.stream)) { + if (request4.body != null && isReadable(request4.body?.stream)) { request4.body.stream.cancel(error2).catch((err) => { if (err.code === "ERR_INVALID_STATE") { return; @@ -13412,7 +13412,7 @@ var require_fetch = __commonJS({ return; } const response = responseObject[kState]; - if (response.body != null && isReadable2(response.body?.stream)) { + if (response.body != null && isReadable(response.body?.stream)) { response.body.stream.cancel(error2).catch((err) => { if (err.code === "ERR_INVALID_STATE") { return; @@ -14049,7 +14049,7 @@ var require_fetch = __commonJS({ fetchParams.controller.abort(reason); } }; - const stream3 = new ReadableStream( + const stream2 = new ReadableStream( { async start(controller) { fetchParams.controller.controller = controller; @@ -14063,7 +14063,7 @@ var require_fetch = __commonJS({ type: "bytes" } ); - response.body = { stream: stream3, source: null, length: null }; + response.body = { stream: stream2, source: null, length: null }; fetchParams.controller.onAborted = onAborted; fetchParams.controller.on("terminated", onAborted); fetchParams.controller.resume = async () => { @@ -14098,7 +14098,7 @@ var require_fetch = __commonJS({ if (buffer.byteLength) { fetchParams.controller.controller.enqueue(buffer); } - if (isErrored(stream3)) { + if (isErrored(stream2)) { fetchParams.controller.terminate(); return; } @@ -14110,13 +14110,13 @@ var require_fetch = __commonJS({ function onAborted(reason) { if (isAborted17(fetchParams)) { response.aborted = true; - if (isReadable2(stream3)) { + if (isReadable(stream2)) { fetchParams.controller.controller.error( fetchParams.controller.serializedAbortReason ); } } else { - if (isReadable2(stream3)) { + if (isReadable(stream2)) { fetchParams.controller.controller.error(new TypeError("terminated", { cause: isErrorLike(reason) ? reason : void 0 })); @@ -14654,8 +14654,8 @@ var require_util4 = __commonJS({ var { ProgressEvent } = require_progressevent(); var { getEncoding } = require_encoding(); var { serializeAMimeType, parseMIMEType } = require_data_url(); - var { types: types2 } = require("util"); - var { StringDecoder: StringDecoder2 } = require("string_decoder"); + var { types } = require("util"); + var { StringDecoder } = require("string_decoder"); var { btoa } = require("buffer"); var staticPropertyDescriptors = { enumerable: true, @@ -14669,8 +14669,8 @@ var require_util4 = __commonJS({ fr[kState] = "loading"; fr[kResult] = null; fr[kError] = null; - const stream3 = blob.stream(); - const reader = stream3.getReader(); + const stream2 = blob.stream(); + const reader = stream2.getReader(); const bytes = []; let chunkPromise = reader.read(); let isFirstChunk = true; @@ -14684,7 +14684,7 @@ var require_util4 = __commonJS({ }); } isFirstChunk = false; - if (!done && types2.isUint8Array(value)) { + if (!done && types.isUint8Array(value)) { bytes.push(value); if ((fr[kLastProgressEventFired] === void 0 || Date.now() - fr[kLastProgressEventFired] >= 50) && !fr[kAborted]) { fr[kLastProgressEventFired] = Date.now(); @@ -14746,7 +14746,7 @@ var require_util4 = __commonJS({ dataURL += serializeAMimeType(parsed); } dataURL += ";base64,"; - const decoder = new StringDecoder2("latin1"); + const decoder = new StringDecoder("latin1"); for (const chunk of bytes) { dataURL += btoa(decoder.write(chunk)); } @@ -14775,7 +14775,7 @@ var require_util4 = __commonJS({ } case "BinaryString": { let binaryString = ""; - const decoder = new StringDecoder2("latin1"); + const decoder = new StringDecoder("latin1"); for (const chunk of bytes) { binaryString += decoder.write(chunk); } @@ -15101,9 +15101,9 @@ var require_util5 = __commonJS({ var assert = require("assert"); var { URLSerializer } = require_data_url(); var { isValidHeaderName } = require_util2(); - function urlEquals(A3, B3, excludeFragment = false) { - const serializedA = URLSerializer(A3, excludeFragment); - const serializedB = URLSerializer(B3, excludeFragment); + function urlEquals(A4, B4, excludeFragment = false) { + const serializedA = URLSerializer(A4, excludeFragment); + const serializedB = URLSerializer(B4, excludeFragment); return serializedA === serializedB; } function getFieldValues(header) { @@ -15329,8 +15329,8 @@ var require_cache = __commonJS({ const clonedResponse = cloneResponse(innerResponse); const bodyReadPromise = createDeferredPromise(); if (innerResponse.body != null) { - const stream3 = innerResponse.body.stream; - const reader = stream3.getReader(); + const stream2 = innerResponse.body.stream; + const reader = stream2.getReader(); readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject); } else { bodyReadPromise.resolve(void 0); @@ -15853,9 +15853,9 @@ var require_util6 = __commonJS({ } } } - function validateCookiePath(path7) { - for (let i6 = 0; i6 < path7.length; ++i6) { - const code = path7.charCodeAt(i6); + function validateCookiePath(path6) { + for (let i6 = 0; i6 < path6.length; ++i6) { + const code = path6.charCodeAt(i6); if (code < 32 || // exclude CTLs (0-31) code === 127 || // DEL code === 59) { @@ -15891,7 +15891,7 @@ var require_util6 = __commonJS({ "Nov", "Dec" ]; - var IMFPaddedNumbers = Array(61).fill(0).map((_, i6) => i6.toString().padStart(2, "0")); + var IMFPaddedNumbers = Array(61).fill(0).map((_2, i6) => i6.toString().padStart(2, "0")); function toIMFDate(date2) { if (typeof date2 === "number") { date2 = new Date(date2); @@ -16580,24 +16580,24 @@ var require_util7 = __commonJS({ var { ErrorEvent, createFastMessageEvent } = require_events(); var { isUtf8 } = require("buffer"); var { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require_data_url(); - function isConnecting(ws) { - return ws[kReadyState] === states.CONNECTING; + function isConnecting(ws2) { + return ws2[kReadyState] === states.CONNECTING; } - function isEstablished(ws) { - return ws[kReadyState] === states.OPEN; + function isEstablished(ws2) { + return ws2[kReadyState] === states.OPEN; } - function isClosing(ws) { - return ws[kReadyState] === states.CLOSING; + function isClosing(ws2) { + return ws2[kReadyState] === states.CLOSING; } - function isClosed(ws) { - return ws[kReadyState] === states.CLOSED; + function isClosed(ws2) { + return ws2[kReadyState] === states.CLOSED; } function fireEvent(e6, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { const event = eventFactory(e6, eventInitDict); target.dispatchEvent(event); } - function websocketMessageReceived(ws, type, data) { - if (ws[kReadyState] !== states.OPEN) { + function websocketMessageReceived(ws2, type, data) { + if (ws2[kReadyState] !== states.OPEN) { return; } let dataForEvent; @@ -16605,18 +16605,18 @@ var require_util7 = __commonJS({ try { dataForEvent = utf8Decode(data); } catch { - failWebsocketConnection(ws, "Received invalid UTF-8 in text frame."); + failWebsocketConnection(ws2, "Received invalid UTF-8 in text frame."); return; } } else if (type === opcodes.BINARY) { - if (ws[kBinaryType] === "blob") { + if (ws2[kBinaryType] === "blob") { dataForEvent = new Blob([data]); } else { dataForEvent = toArrayBuffer(data); } } - fireEvent("message", ws, createFastMessageEvent, { - origin: ws[kWebSocketURL].origin, + fireEvent("message", ws2, createFastMessageEvent, { + origin: ws2[kWebSocketURL].origin, data: dataForEvent }); } @@ -16663,14 +16663,14 @@ var require_util7 = __commonJS({ } return code >= 3e3 && code <= 4999; } - function failWebsocketConnection(ws, reason) { - const { [kController]: controller, [kResponse]: response } = ws; + function failWebsocketConnection(ws2, reason) { + const { [kController]: controller, [kResponse]: response } = ws2; controller.abort(); if (response?.socket && !response.socket.destroyed) { response.socket.destroy(); } if (reason) { - fireEvent("error", ws, (type, init) => new ErrorEvent(type, init), { + fireEvent("error", ws2, (type, init) => new ErrorEvent(type, init), { error: new Error(reason), message: reason }); @@ -16842,7 +16842,7 @@ var require_connection = __commonJS({ crypto3 = require("crypto"); } catch { } - function establishWebSocketConnection(url, protocols, client, ws, onEstablish, options) { + function establishWebSocketConnection(url, protocols, client, ws2, onEstablish, options) { const requestURL = url; requestURL.protocol = url.protocol === "ws:" ? "http:" : "https:"; const request4 = makeRequest({ @@ -16873,25 +16873,25 @@ var require_connection = __commonJS({ dispatcher: options.dispatcher, processResponse(response) { if (response.type === "error" || response.status !== 101) { - failWebsocketConnection(ws, "Received network error or non-101 status code."); + failWebsocketConnection(ws2, "Received network error or non-101 status code."); return; } if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) { - failWebsocketConnection(ws, "Server did not respond with sent protocols."); + failWebsocketConnection(ws2, "Server did not respond with sent protocols."); return; } if (response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") { - failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".'); + failWebsocketConnection(ws2, 'Server did not set Upgrade header to "websocket".'); return; } if (response.headersList.get("Connection")?.toLowerCase() !== "upgrade") { - failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".'); + failWebsocketConnection(ws2, 'Server did not set Connection header to "upgrade".'); return; } const secWSAccept = response.headersList.get("Sec-WebSocket-Accept"); const digest = crypto3.createHash("sha1").update(keyValue + uid).digest("base64"); if (secWSAccept !== digest) { - failWebsocketConnection(ws, "Incorrect hash received in Sec-WebSocket-Accept header."); + failWebsocketConnection(ws2, "Incorrect hash received in Sec-WebSocket-Accept header."); return; } const secExtension = response.headersList.get("Sec-WebSocket-Extensions"); @@ -16899,7 +16899,7 @@ var require_connection = __commonJS({ if (secExtension !== null) { extensions = parseExtensions(secExtension); if (!extensions.has("permessage-deflate")) { - failWebsocketConnection(ws, "Sec-WebSocket-Extensions header does not match."); + failWebsocketConnection(ws2, "Sec-WebSocket-Extensions header does not match."); return; } } @@ -16907,7 +16907,7 @@ var require_connection = __commonJS({ if (secProtocol !== null) { const requestProtocols = getDecodeSplit("sec-websocket-protocol", request4.headersList); if (!requestProtocols.includes(secProtocol)) { - failWebsocketConnection(ws, "Protocol was not set in the opening handshake."); + failWebsocketConnection(ws2, "Protocol was not set in the opening handshake."); return; } } @@ -16926,13 +16926,13 @@ var require_connection = __commonJS({ }); return controller; } - function closeWebSocketConnection(ws, code, reason, reasonByteLength) { - if (isClosing(ws) || isClosed(ws)) { - } else if (!isEstablished(ws)) { - failWebsocketConnection(ws, "Connection was closed before it was established."); - ws[kReadyState] = states.CLOSING; - } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { - ws[kSentClose] = sentCloseFrameState.PROCESSING; + function closeWebSocketConnection(ws2, code, reason, reasonByteLength) { + if (isClosing(ws2) || isClosed(ws2)) { + } else if (!isEstablished(ws2)) { + failWebsocketConnection(ws2, "Connection was closed before it was established."); + ws2[kReadyState] = states.CLOSING; + } else if (ws2[kSentClose] === sentCloseFrameState.NOT_SENT) { + ws2[kSentClose] = sentCloseFrameState.PROCESSING; const frame = new WebsocketFrameSend(); if (code !== void 0 && reason === void 0) { frame.frameData = Buffer.allocUnsafe(2); @@ -16944,12 +16944,12 @@ var require_connection = __commonJS({ } else { frame.frameData = emptyBuffer; } - const socket = ws[kResponse].socket; + const socket = ws2[kResponse].socket; socket.write(frame.createFrame(opcodes.CLOSE)); - ws[kSentClose] = sentCloseFrameState.SENT; - ws[kReadyState] = states.CLOSING; + ws2[kSentClose] = sentCloseFrameState.SENT; + ws2[kReadyState] = states.CLOSING; } else { - ws[kReadyState] = states.CLOSING; + ws2[kReadyState] = states.CLOSING; } } function onSocketData(chunk) { @@ -16958,38 +16958,38 @@ var require_connection = __commonJS({ } } function onSocketClose() { - const { ws } = this; - const { [kResponse]: response } = ws; + const { ws: ws2 } = this; + const { [kResponse]: response } = ws2; response.socket.off("data", onSocketData); response.socket.off("close", onSocketClose); response.socket.off("error", onSocketError); - const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]; + const wasClean = ws2[kSentClose] === sentCloseFrameState.SENT && ws2[kReceivedClose]; let code = 1005; let reason = ""; - const result = ws[kByteParser].closingInfo; + const result = ws2[kByteParser].closingInfo; if (result && !result.error) { code = result.code ?? 1005; reason = result.reason; - } else if (!ws[kReceivedClose]) { + } else if (!ws2[kReceivedClose]) { code = 1006; } - ws[kReadyState] = states.CLOSED; - fireEvent("close", ws, (type, init) => new CloseEvent(type, init), { + ws2[kReadyState] = states.CLOSED; + fireEvent("close", ws2, (type, init) => new CloseEvent(type, init), { wasClean, code, reason }); if (channels.close.hasSubscribers) { channels.close.publish({ - websocket: ws, + websocket: ws2, code, reason }); } } function onSocketError(error2) { - const { ws } = this; - ws[kReadyState] = states.CLOSING; + const { ws: ws2 } = this; + ws2[kReadyState] = states.CLOSING; if (channels.socketError.hasSubscribers) { channels.socketError.publish(error2); } @@ -17088,9 +17088,9 @@ var require_receiver = __commonJS({ #fragments = []; /** @type {Map} */ #extensions; - constructor(ws, extensions) { + constructor(ws2, extensions) { super(); - this.ws = ws; + this.ws = ws2; this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; if (this.#extensions.has("permessage-deflate")) { this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions)); @@ -17100,7 +17100,7 @@ var require_receiver = __commonJS({ * @param {Buffer} chunk * @param {() => void} callback */ - _write(chunk, _, callback) { + _write(chunk, _2, callback) { this.#buffers.push(chunk); this.#byteOffset += chunk.length; this.#loop = true; @@ -17246,34 +17246,34 @@ var require_receiver = __commonJS({ * @param {number} n * @returns {Buffer} */ - consume(n6) { - if (n6 > this.#byteOffset) { + consume(n12) { + if (n12 > this.#byteOffset) { throw new Error("Called consume() before buffers satiated."); - } else if (n6 === 0) { + } else if (n12 === 0) { return emptyBuffer; } - if (this.#buffers[0].length === n6) { + if (this.#buffers[0].length === n12) { this.#byteOffset -= this.#buffers[0].length; return this.#buffers.shift(); } - const buffer = Buffer.allocUnsafe(n6); + const buffer = Buffer.allocUnsafe(n12); let offset = 0; - while (offset !== n6) { + while (offset !== n12) { const next = this.#buffers[0]; const { length } = next; - if (length + offset === n6) { + if (length + offset === n12) { buffer.set(this.#buffers.shift(), offset); break; - } else if (length + offset > n6) { - buffer.set(next.subarray(0, n6 - offset), offset); - this.#buffers[0] = next.subarray(n6 - offset); + } else if (length + offset > n12) { + buffer.set(next.subarray(0, n12 - offset), offset); + this.#buffers[0] = next.subarray(n12 - offset); break; } else { buffer.set(this.#buffers.shift(), offset); offset += next.length; } } - this.#byteOffset -= n6; + this.#byteOffset -= n12; return buffer; } parseCloseBody(data) { @@ -17472,7 +17472,7 @@ var require_websocket = __commonJS({ var { ByteParser } = require_receiver(); var { kEnumerableProperty, isBlobLike } = require_util(); var { getGlobalDispatcher } = require_global2(); - var { types: types2 } = require("util"); + var { types } = require("util"); var { ErrorEvent, CloseEvent } = require_events(); var { SendQueue } = require_sender(); var WebSocket = class _WebSocket extends EventTarget { @@ -17595,7 +17595,7 @@ var require_websocket = __commonJS({ this.#sendQueue.add(data, () => { this.#bufferedAmount -= length; }, sendHints.string); - } else if (types2.isArrayBuffer(data)) { + } else if (types.isArrayBuffer(data)) { this.#bufferedAmount += data.byteLength; this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength; @@ -17768,11 +17768,11 @@ var require_websocket = __commonJS({ webidl.converters["sequence"] = webidl.sequenceConverter( webidl.converters.DOMString ); - webidl.converters["DOMString or sequence"] = function(V2, prefix, argument) { - if (webidl.util.Type(V2) === "Object" && Symbol.iterator in V2) { - return webidl.converters["sequence"](V2); + webidl.converters["DOMString or sequence"] = function(V3, prefix, argument) { + if (webidl.util.Type(V3) === "Object" && Symbol.iterator in V3) { + return webidl.converters["sequence"](V3); } - return webidl.converters.DOMString(V2, prefix, argument); + return webidl.converters.DOMString(V3, prefix, argument); }; webidl.converters.WebSocketInit = webidl.dictionaryConverter([ { @@ -17790,22 +17790,22 @@ var require_websocket = __commonJS({ converter: webidl.nullableConverter(webidl.converters.HeadersInit) } ]); - webidl.converters["DOMString or sequence or WebSocketInit"] = function(V2) { - if (webidl.util.Type(V2) === "Object" && !(Symbol.iterator in V2)) { - return webidl.converters.WebSocketInit(V2); + webidl.converters["DOMString or sequence or WebSocketInit"] = function(V3) { + if (webidl.util.Type(V3) === "Object" && !(Symbol.iterator in V3)) { + return webidl.converters.WebSocketInit(V3); } - return { protocols: webidl.converters["DOMString or sequence"](V2) }; + return { protocols: webidl.converters["DOMString or sequence"](V3) }; }; - webidl.converters.WebSocketSendData = function(V2) { - if (webidl.util.Type(V2) === "Object") { - if (isBlobLike(V2)) { - return webidl.converters.Blob(V2, { strict: false }); + webidl.converters.WebSocketSendData = function(V3) { + if (webidl.util.Type(V3) === "Object") { + if (isBlobLike(V3)) { + return webidl.converters.Blob(V3, { strict: false }); } - if (ArrayBuffer.isView(V2) || types2.isArrayBuffer(V2)) { - return webidl.converters.BufferSource(V2); + if (ArrayBuffer.isView(V3) || types.isArrayBuffer(V3)) { + return webidl.converters.BufferSource(V3); } } - return webidl.converters.USVString(V2); + return webidl.converters.USVString(V3); }; function onParserDrain() { this.ws[kResponse].socket.resume(); @@ -17842,9 +17842,9 @@ var require_util8 = __commonJS({ } return true; } - function delay(ms) { + function delay(ms2) { return new Promise((resolve3) => { - setTimeout(resolve3, ms).unref(); + setTimeout(resolve3, ms2).unref(); }); } module2.exports = { @@ -18104,7 +18104,7 @@ var require_eventsource = __commonJS({ var defaultReconnectionTime = 3e3; var CONNECTING = 0; var OPEN = 1; - var CLOSED2 = 2; + var CLOSED = 2; var ANONYMOUS = "anonymous"; var USE_CREDENTIALS = "use-credentials"; var EventSource = class _EventSource extends EventTarget { @@ -18202,7 +18202,7 @@ var require_eventsource = __commonJS({ return this.#withCredentials; } #connect() { - if (this.#readyState === CLOSED2) return; + if (this.#readyState === CLOSED) return; this.#readyState = CONNECTING; const fetchParams = { request: this.#request, @@ -18265,7 +18265,7 @@ var require_eventsource = __commonJS({ * @returns {Promise} */ async #reconnect() { - if (this.#readyState === CLOSED2) return; + if (this.#readyState === CLOSED) return; this.#readyState = CONNECTING; this.dispatchEvent(new Event("error")); await delay(this.#state.reconnectionTime); @@ -18281,8 +18281,8 @@ var require_eventsource = __commonJS({ */ close() { webidl.brandCheck(this, _EventSource); - if (this.#readyState === CLOSED2) return; - this.#readyState = CLOSED2; + if (this.#readyState === CLOSED) return; + this.#readyState = CLOSED; this.#controller.abort(); this.#request = null; } @@ -18348,7 +18348,7 @@ var require_eventsource = __commonJS({ __proto__: null, configurable: false, enumerable: true, - value: CLOSED2, + value: CLOSED, writable: false } }; @@ -18449,11 +18449,11 @@ var require_undici = __commonJS({ if (typeof opts.path !== "string") { throw new InvalidArgumentError("invalid opts.path"); } - let path7 = opts.path; + let path6 = opts.path; if (!opts.path.startsWith("/")) { - path7 = `/${path7}`; + path6 = `/${path6}`; } - url = new URL(util17.parseOrigin(url).origin + path7); + url = new URL(util17.parseOrigin(url).origin + path6); } else { if (!opts) { opts = typeof url === "object" ? url : {}; @@ -19857,14 +19857,14 @@ var makePagedClientRequest, get; var init_createPaginator = __esm({ "../node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { "use strict"; - makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { + makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_2) => _2, ...args) => { let command = new CommandCtor(input); command = withCommand(command) ?? command; return await client.send(command, ...args); }; - get = (fromObject, path7) => { + get = (fromObject, path6) => { let cursor = fromObject; - const pathComponents = path7.split("."); + const pathComponents = path6.split("."); for (const step of pathComponents) { if (!cursor || typeof cursor !== "object") { return void 0; @@ -20107,7 +20107,7 @@ var isReadableStream, isBlob; var init_stream_type_check = __esm({ "../node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() { "use strict"; - isReadableStream = (stream3) => typeof ReadableStream === "function" && (stream3?.constructor?.name === ReadableStream.name || stream3 instanceof ReadableStream); + isReadableStream = (stream2) => typeof ReadableStream === "function" && (stream2?.constructor?.name === ReadableStream.name || stream2 instanceof ReadableStream); isBlob = (blob) => { return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); }; @@ -20423,9 +20423,9 @@ ${value}\r }); // ../node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js -function getAwsChunkedEncodingStream2(stream3, options) { - const readable = stream3; - const readableStream2 = stream3; +function getAwsChunkedEncodingStream2(stream2, options) { + const readable = stream2; + const readableStream2 = stream2; if (isReadableStream(readableStream2)) { return getAwsChunkedEncodingStream(readableStream2, options); } @@ -20471,10 +20471,10 @@ var init_getAwsChunkedEncodingStream = __esm({ }); // ../node_modules/@smithy/util-stream/dist-es/headStream.browser.js -async function headStream(stream3, bytes) { +async function headStream(stream2, bytes) { let byteLengthCounter = 0; const chunks = []; - const reader = stream3.getReader(); + const reader = stream2.getReader(); let isDone = false; while (!isDone) { const { done, value } = await reader.read(); @@ -20515,15 +20515,15 @@ var init_headStream = __esm({ import_stream2 = require("stream"); init_headStream_browser(); init_stream_type_check(); - headStream2 = (stream3, bytes) => { - if (isReadableStream(stream3)) { - return headStream(stream3, bytes); + headStream2 = (stream2, bytes) => { + if (isReadableStream(stream2)) { + return headStream(stream2, bytes); } return new Promise((resolve3, reject2) => { const collector = new Collector(); collector.limit = bytes; - stream3.pipe(collector); - stream3.on("error", (err) => { + stream2.pipe(collector); + stream2.on("error", (err) => { collector.end(); reject2(err); }); @@ -20637,7 +20637,7 @@ var init_timing = __esm({ "../node_modules/@smithy/node-http-handler/dist-es/timing.js"() { "use strict"; timing = { - setTimeout: (cb2, ms) => setTimeout(cb2, ms), + setTimeout: (cb2, ms2) => setTimeout(cb2, ms2), clearTimeout: (timeoutId) => clearTimeout(timeoutId) }; } @@ -20809,8 +20809,14 @@ function writeBody(httpRequest2, body) { return; } if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest2.end(body); + const isBuffer = Buffer.isBuffer(body); + const isString = typeof body === "string"; + if (isBuffer || isString) { + if (isBuffer && body.byteLength === 0) { + httpRequest2.end(); + } else { + httpRequest2.end(body); + } return; } const uint8 = body; @@ -20897,7 +20903,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf }); } resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout } = options || {}; + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger2 } = options || {}; const keepAlive = true; const maxSockets = 50; return { @@ -20920,7 +20926,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf } return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); })(), - logger: console + logger: logger2 }; } destroy() { @@ -20971,12 +20977,12 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf const password = request4.password ?? ""; auth2 = `${username}:${password}`; } - let path7 = request4.path; + let path6 = request4.path; if (queryString) { - path7 += `?${queryString}`; + path6 += `?${queryString}`; } if (request4.fragment) { - path7 += `#${request4.fragment}`; + path6 += `#${request4.fragment}`; } let hostname = request4.hostname ?? ""; if (hostname[0] === "[" && hostname.endsWith("]")) { @@ -20988,7 +20994,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf headers: request4.headers, host: hostname, method: request4.method, - path: path7, + path: path6, port: request4.port, agent, auth: auth2 @@ -21082,9 +21088,9 @@ var init_collector = __esm({ }); // ../node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js -async function collectReadableStream(stream3) { +async function collectReadableStream(stream2) { const chunks = []; - const reader = stream3.getReader(); + const reader = stream2.getReader(); let isDone = false; let length = 0; while (!isDone) { @@ -21108,14 +21114,14 @@ var init_stream_collector = __esm({ "../node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"() { "use strict"; init_collector(); - streamCollector = (stream3) => { - if (isReadableStreamInstance(stream3)) { - return collectReadableStream(stream3); + streamCollector = (stream2) => { + if (isReadableStreamInstance(stream2)) { + return collectReadableStream(stream2); } return new Promise((resolve3, reject2) => { const collector = new Collector2(); - stream3.pipe(collector); - stream3.on("error", (err) => { + stream2.pipe(collector); + stream2.on("error", (err) => { collector.end(); reject2(err); }); @@ -21126,7 +21132,7 @@ var init_stream_collector = __esm({ }); }); }; - isReadableStreamInstance = (stream3) => typeof ReadableStream === "function" && stream3 instanceof ReadableStream; + isReadableStreamInstance = (stream2) => typeof ReadableStream === "function" && stream2 instanceof ReadableStream; } }); @@ -21153,9 +21159,9 @@ async function collectBlob(blob) { const arrayBuffer = fromBase64(base64); return new Uint8Array(arrayBuffer); } -async function collectStream(stream3) { +async function collectStream(stream2) { const chunks = []; - const reader = stream3.getReader(); + const reader = stream2.getReader(); let isDone = false; let length = 0; while (!isDone) { @@ -21196,14 +21202,14 @@ var init_stream_collector2 = __esm({ "../node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() { "use strict"; init_dist_es8(); - streamCollector2 = async (stream3) => { - if (typeof Blob === "function" && stream3 instanceof Blob || stream3.constructor?.name === "Blob") { + streamCollector2 = async (stream2) => { + if (typeof Blob === "function" && stream2 instanceof Blob || stream2.constructor?.name === "Blob") { if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream3.arrayBuffer()); + return new Uint8Array(await stream2.arrayBuffer()); } - return collectBlob(stream3); + return collectBlob(stream2); } - return collectStream(stream3); + return collectStream(stream2); }; } }); @@ -21268,9 +21274,9 @@ var init_sdk_stream_mixin_browser = __esm({ init_dist_es7(); init_stream_type_check(); ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; - sdkStreamMixin = (stream3) => { - if (!isBlobInstance(stream3) && !isReadableStream(stream3)) { - const name = stream3?.__proto__?.constructor?.name || stream3; + sdkStreamMixin = (stream2) => { + if (!isBlobInstance(stream2) && !isReadableStream(stream2)) { + const name = stream2?.__proto__?.constructor?.name || stream2; throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); } let transformed = false; @@ -21279,7 +21285,7 @@ var init_sdk_stream_mixin_browser = __esm({ throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; - return await streamCollector2(stream3); + return await streamCollector2(stream2); }; const blobToWebStream = (blob) => { if (typeof blob.stream !== "function") { @@ -21287,7 +21293,7 @@ var init_sdk_stream_mixin_browser = __esm({ } return blob.stream(); }; - return Object.assign(stream3, { + return Object.assign(stream2, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); @@ -21308,17 +21314,17 @@ var init_sdk_stream_mixin_browser = __esm({ throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); } transformed = true; - if (isBlobInstance(stream3)) { - return blobToWebStream(stream3); - } else if (isReadableStream(stream3)) { - return stream3; + if (isBlobInstance(stream2)) { + return blobToWebStream(stream2); + } else if (isReadableStream(stream2)) { + return stream2; } else { - throw new Error(`Cannot transform payload to web stream, got ${stream3}`); + throw new Error(`Cannot transform payload to web stream, got ${stream2}`); } } }); }; - isBlobInstance = (stream3) => typeof Blob === "function" && stream3 instanceof Blob; + isBlobInstance = (stream2) => typeof Blob === "function" && stream2 instanceof Blob; } }); @@ -21332,12 +21338,12 @@ var init_sdk_stream_mixin = __esm({ import_stream5 = require("stream"); init_sdk_stream_mixin_browser(); ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2 = "The stream has already been transformed."; - sdkStreamMixin2 = (stream3) => { - if (!(stream3 instanceof import_stream5.Readable)) { + sdkStreamMixin2 = (stream2) => { + if (!(stream2 instanceof import_stream5.Readable)) { try { - return sdkStreamMixin(stream3); + return sdkStreamMixin(stream2); } catch (e6) { - const name = stream3?.__proto__?.constructor?.name || stream3; + const name = stream2?.__proto__?.constructor?.name || stream2; throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); } } @@ -21347,9 +21353,9 @@ var init_sdk_stream_mixin = __esm({ throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2); } transformed = true; - return await streamCollector(stream3); + return await streamCollector(stream2); }; - return Object.assign(stream3, { + return Object.assign(stream2, { transformToByteArray, transformToString: async (encoding) => { const buf = await transformToByteArray(); @@ -21364,14 +21370,14 @@ var init_sdk_stream_mixin = __esm({ if (transformed) { throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2); } - if (stream3.readableFlowing !== null) { + if (stream2.readableFlowing !== null) { throw new Error("The stream has been consumed by other callbacks."); } if (typeof import_stream5.Readable.toWeb !== "function") { throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); } transformed = true; - return import_stream5.Readable.toWeb(stream3); + return import_stream5.Readable.toWeb(stream2); } }); }; @@ -21379,11 +21385,11 @@ var init_sdk_stream_mixin = __esm({ }); // ../node_modules/@smithy/util-stream/dist-es/splitStream.browser.js -async function splitStream(stream3) { - if (typeof stream3.stream === "function") { - stream3 = stream3.stream(); +async function splitStream(stream2) { + if (typeof stream2.stream === "function") { + stream2 = stream2.stream(); } - const readableStream2 = stream3; + const readableStream2 = stream2; return readableStream2.tee(); } var init_splitStream_browser = __esm({ @@ -21393,14 +21399,14 @@ var init_splitStream_browser = __esm({ }); // ../node_modules/@smithy/util-stream/dist-es/splitStream.js -async function splitStream2(stream3) { - if (isReadableStream(stream3) || isBlob(stream3)) { - return splitStream(stream3); +async function splitStream2(stream2) { + if (isReadableStream(stream2) || isBlob(stream2)) { + return splitStream(stream2); } const stream1 = new import_stream6.PassThrough(); const stream22 = new import_stream6.PassThrough(); - stream3.pipe(stream1); - stream3.pipe(stream22); + stream2.pipe(stream1); + stream2.pipe(stream22); return [stream1, stream22]; } var import_stream6; @@ -21499,9 +21505,9 @@ var init_schemaDeserializationMiddleware = __esm({ schemaDeserializationMiddleware = (config) => (next, context3) => async (args) => { const { response } = await next(args); const { operationSchema } = getSmithyContext(context3); - const [, ns, n6, t12, i6, o6] = operationSchema ?? []; + const [, ns2, n12, t12, i6, o6] = operationSchema ?? []; try { - const parsed = await config.protocol.deserializeResponse(operation(ns, n6, t12, i6, o6), { + const parsed = await config.protocol.deserializeResponse(operation(ns2, n12, t12, i6, o6), { ...config, ...context3 }, response); @@ -21550,8 +21556,8 @@ var init_schemaDeserializationMiddleware = __esm({ } }; findHeader = (pattern, headers) => { - return (headers.find(([k6]) => { - return k6.match(pattern); + return (headers.find(([k7]) => { + return k7.match(pattern); }) || [void 0, void 0])[1]; }; } @@ -21566,9 +21572,9 @@ var init_schemaSerializationMiddleware = __esm({ init_operation(); schemaSerializationMiddleware = (config) => (next, context3) => async (args) => { const { operationSchema } = getSmithyContext(context3); - const [, ns, n6, t12, i6, o6] = operationSchema ?? []; + const [, ns2, n12, t12, i6, o6] = operationSchema ?? []; const endpoint2 = context3.endpointV2?.url && config.urlParser ? async () => config.urlParser(context3.endpointV2.url) : config.endpoint; - const request4 = await config.protocol.serializeRequest(operation(ns, n6, t12, i6, o6), args.input, { + const request4 = await config.protocol.serializeRequest(operation(ns2, n12, t12, i6, o6), args.input, { ...config, ...context3, endpoint: endpoint2 @@ -21759,8 +21765,8 @@ var init_NormalizedSchema = __esm({ static [Symbol.hasInstance](lhs) { const isPrototype = this.prototype.isPrototypeOf(lhs); if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const ns = lhs; - return ns.symbol === this.symbol; + const ns2 = lhs; + return ns2.symbol === this.symbol; } return isPrototype; } @@ -21770,10 +21776,10 @@ var init_NormalizedSchema = __esm({ return sc; } if (isMemberSchema(sc)) { - const [ns, traits] = sc; - if (ns instanceof _NormalizedSchema) { - Object.assign(ns.getMergedTraits(), translateTraits(traits)); - return ns; + const [ns2, traits] = sc; + if (ns2 instanceof _NormalizedSchema) { + Object.assign(ns2.getMergedTraits(), translateTraits(traits)); + return ns2; } throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); } @@ -21781,7 +21787,7 @@ var init_NormalizedSchema = __esm({ } getSchema() { const sc = this.schema; - if (sc[0] === 0) { + if (Array.isArray(sc) && sc[0] === 0) { return sc[4]; } return sc; @@ -21807,11 +21813,17 @@ var init_NormalizedSchema = __esm({ } isStructSchema() { const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } const id = sc[0]; return id === 3 || id === -3 || id === 4; } isUnionSchema() { const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } return sc[0] === 4; } isBlobSchema() { @@ -21895,8 +21907,8 @@ var init_NormalizedSchema = __esm({ getMemberSchemas() { const buffer = {}; try { - for (const [k6, v7] of this.structIterator()) { - buffer[k6] = v7; + for (const [k7, v8] of this.structIterator()) { + buffer[k7] = v8; } } catch (ignored) { } @@ -21921,18 +21933,18 @@ var init_NormalizedSchema = __esm({ } const struct = this.getSchema(); const z3 = struct[4].length; - let it = struct[anno.it]; - if (it && z3 === it.length) { - yield* it; + let it2 = struct[anno.it]; + if (it2 && z3 === it2.length) { + yield* it2; return; } - it = Array(z3); + it2 = Array(z3); for (let i6 = 0; i6 < z3; ++i6) { - const k6 = struct[4][i6]; - const v7 = member([struct[5][i6], 0], k6); - yield it[i6] = [k6, v7]; + const k7 = struct[4][i6]; + const v8 = member([struct[5][i6], 0], k7); + yield it2[i6] = [k7, v8]; } - struct[anno.it] = it; + struct[anno.it] = it2; } }; isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; @@ -21975,10 +21987,24 @@ var init_TypeRegistry = __esm({ } return _TypeRegistry.registries.get(namespace); } + copyFrom(other) { + const { schemas, exceptions } = this; + for (const [k7, v8] of other.schemas) { + if (!schemas.has(k7)) { + schemas.set(k7, v8); + } + } + for (const [k7, v8] of other.exceptions) { + if (!exceptions.has(k7)) { + exceptions.set(k7, v8); + } + } + } register(shapeId, schema) { const qualifiedName = this.normalizeShapeId(shapeId); - const registry = _TypeRegistry.for(qualifiedName.split("#")[0]); - registry.schemas.set(qualifiedName, schema); + for (const r6 of [this, _TypeRegistry.for(qualifiedName.split("#")[0])]) { + r6.schemas.set(qualifiedName, schema); + } } getSchema(shapeId) { const id = this.normalizeShapeId(shapeId); @@ -21987,22 +22013,27 @@ var init_TypeRegistry = __esm({ } return this.schemas.get(id); } - registerError(es, ctor) { - const $error = es; - const registry = _TypeRegistry.for($error[1]); - registry.schemas.set($error[1] + "#" + $error[2], $error); - registry.exceptions.set($error, ctor); + registerError(es2, ctor) { + const $error = es2; + const ns2 = $error[1]; + for (const r6 of [this, _TypeRegistry.for(ns2)]) { + r6.schemas.set(ns2 + "#" + $error[2], $error); + r6.exceptions.set($error, ctor); + } } - getErrorCtor(es) { - const $error = es; + getErrorCtor(es2) { + const $error = es2; + if (this.exceptions.has($error)) { + return this.exceptions.get($error); + } const registry = _TypeRegistry.for($error[1]); return registry.exceptions.get($error); } getBaseException() { for (const exceptionKey of this.exceptions.keys()) { if (Array.isArray(exceptionKey)) { - const [, ns, name] = exceptionKey; - const id = ns + "#" + name; + const [, ns2, name] = exceptionKey; + const id = ns2 + "#" + name; if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { return exceptionKey; } @@ -22187,11 +22218,11 @@ var init_date_utils = __esm({ if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - const match2 = RFC3339.exec(value); - if (!match2) { + const match = RFC3339.exec(value); + if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2; + const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; const year2 = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); @@ -22205,11 +22236,11 @@ var init_date_utils = __esm({ if (typeof value !== "string") { throw new TypeError("RFC-3339 date-times must be expressed as strings"); } - const match2 = RFC3339_WITH_OFFSET.exec(value); - if (!match2) { + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { throw new TypeError("Invalid RFC-3339 date-time value"); } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2; + const [_2, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; const year2 = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); @@ -22229,14 +22260,14 @@ var init_date_utils = __esm({ if (typeof value !== "string") { throw new TypeError("RFC-7231 date-times must be expressed as strings"); } - let match2 = IMF_FIXDATE.exec(value); - if (match2) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2; + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_2, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } - match2 = RFC_850_DATE.exec(value); - if (match2) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2; + match = RFC_850_DATE.exec(value); + if (match) { + const [_2, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, @@ -22244,9 +22275,9 @@ var init_date_utils = __esm({ fractionalMilliseconds })); } - match2 = ASC_TIME.exec(value); - if (match2) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2; + match = ASC_TIME.exec(value); + if (match) { + const [_2, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); } throw new TypeError("Invalid RFC-7231 date-time value"); @@ -22366,7 +22397,7 @@ var init_v4 = __esm({ "../node_modules/@smithy/uuid/dist-es/v4.js"() { "use strict"; init_randomUUID(); - decimalToHex = Array.from({ length: 256 }, (_, i6) => i6.toString(16).padStart(2, "0")); + decimalToHex = Array.from({ length: 256 }, (_2, i6) => i6.toString(16).padStart(2, "0")); v4 = () => { if (randomUUID) { return randomUUID(); @@ -22441,8 +22472,8 @@ var init_quote_header = __esm({ }); // ../node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js -function range(v7, min, max) { - const _v = Number(v7); +function range(v8, min, max) { + const _v = Number(v8); if (_v < min || _v > max) { throw new Error(`Value ${_v} out of range [${min}, ${max}]`); } @@ -22492,13 +22523,13 @@ var init_schema_date_utils = __esm({ if (!matches) { throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); } - const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms2, offsetStr] = matches; range(monthStr, 1, 12); range(dayStr, 1, 31); range(hours, 0, 23); range(minutes, 0, 59); range(seconds, 0, 60); - const date2 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0)); + const date2 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms2) ? Math.round(parseFloat(`0.${ms2}`) * 1e3) : 0)); date2.setUTCFullYear(Number(yearStr)); if (offsetStr.toUpperCase() != "Z") { const [, sign2, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; @@ -22608,16 +22639,16 @@ var init_split_header = __esm({ prevChar = char; } values.push(value.slice(anchor)); - return values.map((v7) => { - v7 = v7.trim(); - const z4 = v7.length; + return values.map((v8) => { + v8 = v8.trim(); + const z4 = v8.length; if (z4 < 2) { - return v7; + return v8; } - if (v7[0] === `"` && v7[z4 - 1] === `"`) { - v7 = v7.slice(1, z4 - 1); + if (v8[0] === `"` && v8[z4 - 1] === `"`) { + v8 = v8.slice(1, z4 - 1); } - return v7.replace(/\\"/g, '"'); + return v8.replace(/\\"/g, '"'); }); }; } @@ -22908,6 +22939,8 @@ var init_EventStreamSerde = __esm({ } else { serializer.write(eventSchema, event[unionMember]); } + } else if (eventSchema.isUnitSchema()) { + serializer.write(eventSchema, {}); } else { throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); } @@ -22947,9 +22980,14 @@ var init_HttpProtocol = __esm({ init_SerdeContext(); HttpProtocol = class extends SerdeContext { options; + compositeErrorRegistry; constructor(options) { super(); this.options = options; + this.compositeErrorRegistry = TypeRegistry.for(options.defaultNamespace); + for (const etr of options.errorTypeRegistries ?? []) { + this.compositeErrorRegistry.copyFrom(etr); + } } getRequestType() { return HttpRequest; @@ -22977,8 +23015,8 @@ var init_HttpProtocol = __esm({ if (!request4.query) { request4.query = {}; } - for (const [k6, v7] of endpoint2.url.searchParams.entries()) { - request4.query[k6] = v7; + for (const [k7, v8] of endpoint2.url.searchParams.entries()) { + request4.query[k7] = v8; } return request4; } else { @@ -23090,8 +23128,8 @@ var init_HttpBindingProtocol = __esm({ const query = {}; const headers = {}; const endpoint2 = await context3.endpoint(); - const ns = NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); + const ns2 = NormalizedSchema.of(operationSchema?.input); + const schema = ns2.getSchema(); let hasNonHttpBindingMember = false; let payload; const request4 = new HttpRequest({ @@ -23110,17 +23148,17 @@ var init_HttpBindingProtocol = __esm({ const opTraits = translateTraits(operationSchema.traits); if (opTraits.http) { request4.method = opTraits.http[0]; - const [path7, search] = opTraits.http[1].split("?"); + const [path6, search] = opTraits.http[1].split("?"); if (request4.path == "/") { - request4.path = path7; + request4.path = path6; } else { - request4.path += path7; + request4.path += path6; } const traitSearchParams = new URLSearchParams(search ?? ""); Object.assign(query, Object.fromEntries(traitSearchParams)); } } - for (const [memberName, memberNs] of ns.structIterator()) { + for (const [memberName, memberNs] of ns2.structIterator()) { const memberTraits = memberNs.getMergedTraits() ?? {}; const inputMemberValue = input[memberName]; if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { @@ -23139,7 +23177,7 @@ var init_HttpBindingProtocol = __esm({ if (input[memberName]) { payload = await this.serializeEventStream({ eventStream: input[memberName], - requestSchema: ns + requestSchema: ns2 }); } } else { @@ -23186,13 +23224,13 @@ var init_HttpBindingProtocol = __esm({ request4.body = payload; return request4; } - serializeQuery(ns, data, query) { + serializeQuery(ns2, data, query) { const serializer = this.serializer; - const traits = ns.getMergedTraits(); + const traits = ns2.getMergedTraits(); if (traits.httpQueryParams) { for (const [key, val] of Object.entries(data)) { if (!(key in query)) { - const valueSchema = ns.getValueSchema(); + const valueSchema = ns2.getValueSchema(); Object.assign(valueSchema.getMergedTraits(), { ...traits, httpQuery: key, @@ -23203,11 +23241,11 @@ var init_HttpBindingProtocol = __esm({ } return; } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; + if (ns2.isListSchema()) { + const sparse = !!ns2.getMergedTraits().sparse; const buffer = []; for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); + serializer.write([ns2.getValueSchema(), traits], item); const serializable = serializer.flush(); if (sparse || serializable !== void 0) { buffer.push(serializable); @@ -23215,13 +23253,13 @@ var init_HttpBindingProtocol = __esm({ } query[traits.httpQuery] = buffer; } else { - serializer.write([ns, traits], data); + serializer.write([ns2, traits], data); query[traits.httpQuery] = serializer.flush(); } } async deserializeResponse(operationSchema, context3, response) { const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); + const ns2 = NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes = await collectBody(response.body, context3); @@ -23236,13 +23274,15 @@ var init_HttpBindingProtocol = __esm({ delete response.headers[header]; response.headers[header.toLowerCase()] = value; } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context3, response, dataObject); + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns2, context3, response, dataObject); if (nonHttpBindingMembers.length) { const bytes = await collectBody(response.body, context3); if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); + const dataFromBody = await deserializer.read(ns2, bytes); for (const member2 of nonHttpBindingMembers) { - dataObject[member2] = dataFromBody[member2]; + if (dataFromBody[member2] != null) { + dataObject[member2] = dataFromBody[member2]; + } } } } else if (nonHttpBindingMembers.discardResponseBody) { @@ -23260,9 +23300,9 @@ var init_HttpBindingProtocol = __esm({ } let discardResponseBody = true; const deserializer = this.deserializer; - const ns = NormalizedSchema.of(schema); + const ns2 = NormalizedSchema.of(schema); const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { + for (const [memberName, memberSchema] of ns2.structIterator()) { const memberTraits = memberSchema.getMemberTraits(); if (memberTraits.httpPayload) { discardResponseBody = false; @@ -23272,7 +23312,7 @@ var init_HttpBindingProtocol = __esm({ if (isEventStream) { dataObject[memberName] = await this.deserializeEventStream({ response, - responseSchema: ns + responseSchema: ns2 }); } else { dataObject[memberName] = sdkStreamMixin2(response.body); @@ -23342,8 +23382,8 @@ var init_RpcProtocol = __esm({ const query = {}; const headers = {}; const endpoint2 = await context3.endpoint(); - const ns = NormalizedSchema.of(operationSchema?.input); - const schema = ns.getSchema(); + const ns2 = NormalizedSchema.of(operationSchema?.input); + const schema = ns2.getSchema(); let payload; const request4 = new HttpRequest({ protocol: "", @@ -23363,11 +23403,11 @@ var init_RpcProtocol = __esm({ ...input }; if (input) { - const eventStreamMember = ns.getEventStreamMember(); + const eventStreamMember = ns2.getEventStreamMember(); if (eventStreamMember) { if (_input[eventStreamMember]) { const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { + for (const [memberName, memberSchema] of ns2.structIterator()) { if (memberName !== eventStreamMember && _input[memberName]) { serializer.write(memberSchema, _input[memberName]); initialRequest[memberName] = serializer.flush(); @@ -23375,7 +23415,7 @@ var init_RpcProtocol = __esm({ } payload = await this.serializeEventStream({ eventStream: _input[eventStreamMember], - requestSchema: ns, + requestSchema: ns2, initialRequest }); } @@ -23392,7 +23432,7 @@ var init_RpcProtocol = __esm({ } async deserializeResponse(operationSchema, context3, response) { const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); + const ns2 = NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes = await collectBody(response.body, context3); @@ -23407,17 +23447,17 @@ var init_RpcProtocol = __esm({ delete response.headers[header]; response.headers[header.toLowerCase()] = value; } - const eventStreamMember = ns.getEventStreamMember(); + const eventStreamMember = ns2.getEventStreamMember(); if (eventStreamMember) { dataObject[eventStreamMember] = await this.deserializeEventStream({ response, - responseSchema: ns, + responseSchema: ns2, initialResponseContainer: dataObject }); } else { const bytes = await collectBody(response.body, context3); if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); + Object.assign(dataObject, await deserializer.read(ns2, bytes)); } } dataObject.$metadata = this.deserializeMetadata(response); @@ -23442,13 +23482,13 @@ var init_requestBuilder = __esm({ }); // ../node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js -function determineTimestampFormat(ns, settings) { +function determineTimestampFormat(ns2, settings) { if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === 5 || ns.getSchema() === 6 || ns.getSchema() === 7)) { - return ns.getSchema(); + if (ns2.isTimestampSchema() && (ns2.getSchema() === 5 || ns2.getSchema() === 6 || ns2.getSchema() === 7)) { + return ns2.getSchema(); } } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns2.getMergedTraits(); const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? 6 : Boolean(httpQuery) || Boolean(httpLabel) ? 5 : void 0 : void 0; return bindingFormat ?? settings.timestampFormat.default; } @@ -23476,15 +23516,15 @@ var init_FromStringShapeDeserializer = __esm({ this.settings = settings; } read(_schema, data) { - const ns = NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); + const ns2 = NormalizedSchema.of(_schema); + if (ns2.isListSchema()) { + return splitHeader(data).map((item) => this.read(ns2.getValueSchema(), item)); } - if (ns.isBlobSchema()) { + if (ns2.isBlobSchema()) { return (this.serdeContext?.base64Decoder ?? fromBase64)(data); } - if (ns.isTimestampSchema()) { - const format2 = determineTimestampFormat(ns, this.settings); + if (ns2.isTimestampSchema()) { + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: return _parseRfc3339DateTimeWithOffset(data); @@ -23497,11 +23537,11 @@ var init_FromStringShapeDeserializer = __esm({ return new Date(data); } } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; + if (ns2.isStringSchema()) { + const mediaType = ns2.getMergedTraits().mediaType; let intermediateValue = data; if (mediaType) { - if (ns.getMergedTraits().httpHeader) { + if (ns2.getMergedTraits().httpHeader) { intermediateValue = this.base64ToUtf8(intermediateValue); } const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); @@ -23511,16 +23551,16 @@ var init_FromStringShapeDeserializer = __esm({ return intermediateValue; } } - if (ns.isNumericSchema()) { + if (ns2.isNumericSchema()) { return Number(data); } - if (ns.isBigIntegerSchema()) { + if (ns2.isBigIntegerSchema()) { return BigInt(data); } - if (ns.isBigDecimalSchema()) { + if (ns2.isBigDecimalSchema()) { return new NumericValue(data, "bigDecimal"); } - if (ns.isBooleanSchema()) { + if (ns2.isBooleanSchema()) { return String(data).toLowerCase() === "true"; } return data; @@ -23555,27 +23595,27 @@ var init_HttpInterceptingShapeDeserializer = __esm({ this.serdeContext = serdeContext; } read(schema, data) { - const ns = NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); + const ns2 = NormalizedSchema.of(schema); + const traits = ns2.getMergedTraits(); const toString2 = this.serdeContext?.utf8Encoder ?? toUtf8; if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString2(data)); + return this.stringDeserializer.read(ns2, toString2(data)); } if (traits.httpPayload) { - if (ns.isBlobSchema()) { + if (ns2.isBlobSchema()) { const toBytes = this.serdeContext?.utf8Decoder ?? fromUtf8; if (typeof data === "string") { return toBytes(data); } return data; - } else if (ns.isStringSchema()) { + } else if (ns2.isStringSchema()) { if ("byteLength" in data) { return toString2(data); } return data; } } - return this.codecDeserializer.read(ns, data); + return this.codecDeserializer.read(ns2, data); } }; } @@ -23599,18 +23639,18 @@ var init_ToStringShapeSerializer = __esm({ this.settings = settings; } write(schema, value) { - const ns = NormalizedSchema.of(schema); + const ns2 = NormalizedSchema.of(schema); switch (typeof value) { case "object": if (value === null) { this.stringBuffer = "null"; return; } - if (ns.isTimestampSchema()) { + if (ns2.isTimestampSchema()) { if (!(value instanceof Date)) { - throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns2.getName(true)}`); } - const format2 = determineTimestampFormat(ns, this.settings); + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: this.stringBuffer = value.toISOString().replace(".000Z", "Z"); @@ -23627,16 +23667,16 @@ var init_ToStringShapeSerializer = __esm({ } return; } - if (ns.isBlobSchema() && "byteLength" in value) { + if (ns2.isBlobSchema() && "byteLength" in value) { this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(value); return; } - if (ns.isListSchema() && Array.isArray(value)) { + if (ns2.isListSchema() && Array.isArray(value)) { let buffer = ""; for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + this.write([ns2.getValueSchema(), ns2.getMergedTraits()], item); const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); + const serialized = ns2.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); if (buffer !== "") { buffer += ", "; } @@ -23648,14 +23688,14 @@ var init_ToStringShapeSerializer = __esm({ this.stringBuffer = JSON.stringify(value, null, 2); break; case "string": - const mediaType = ns.getMergedTraits().mediaType; + const mediaType = ns2.getMergedTraits().mediaType; let intermediateValue = value; if (mediaType) { const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { intermediateValue = LazyJsonString.from(intermediateValue); } - if (ns.getMergedTraits().httpHeader) { + if (ns2.getMergedTraits().httpHeader) { this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(intermediateValue.toString()); return; } @@ -23663,7 +23703,7 @@ var init_ToStringShapeSerializer = __esm({ this.stringBuffer = value; break; default: - if (ns.isIdempotencyToken()) { + if (ns2.isIdempotencyToken()) { this.stringBuffer = v4(); } else { this.stringBuffer = String(value); @@ -23699,14 +23739,14 @@ var init_HttpInterceptingShapeSerializer = __esm({ this.stringSerializer.setSerdeContext(serdeContext); } write(schema, value) { - const ns = NormalizedSchema.of(schema); - const traits = ns.getMergedTraits(); + const ns2 = NormalizedSchema.of(schema); + const traits = ns2.getMergedTraits(); if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); + this.stringSerializer.write(ns2, value); this.buffer = this.stringSerializer.flush(); return; } - return this.codecSerializer.write(ns, value); + return this.codecSerializer.write(ns2, value); } flush() { if (this.buffer !== void 0) { @@ -24087,7 +24127,7 @@ var init_resolveAwsSdkSigV4AConfig = __esm({ NODE_SIGV4A_CONFIG_OPTIONS = { environmentVariableSelector(env3) { if (env3.AWS_SIGV4A_SIGNING_REGION_SET) { - return env3.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + return env3.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_2) => _2.trim()); } throw new ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { tryNextLink: true @@ -24095,7 +24135,7 @@ var init_resolveAwsSdkSigV4AConfig = __esm({ }, configFileSelector(profile) { if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_2) => _2.trim()); } throw new ProviderError("sigv4a_signing_region_set not set in profile.", { tryNextLink: true @@ -24527,10 +24567,10 @@ ${longDate} ${credentialScope} ${toHex(hashedRequest)}`; } - getCanonicalPath({ path: path7 }) { + getCanonicalPath({ path: path6 }) { if (this.uriEscapePath) { const normalizedPathSegments = []; - for (const pathSegment of path7.split("/")) { + for (const pathSegment of path6.split("/")) { if (pathSegment?.length === 0) continue; if (pathSegment === ".") @@ -24541,11 +24581,11 @@ ${toHex(hashedRequest)}`; normalizedPathSegments.push(pathSegment); } } - const normalizedPath = `${path7?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path7?.endsWith("/") ? "/" : ""}`; + const normalizedPath = `${path6?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path6?.endsWith("/") ? "/" : ""}`; const doubleEncoded = escapeUri(normalizedPath); return doubleEncoded.replace(/%2F/g, "/"); } - return path7; + return path6; } validateResolvedCredentials(credentials) { if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { @@ -25230,24 +25270,24 @@ function schemaLogFilter(schema, data) { if (data == null) { return data; } - const ns = NormalizedSchema.of(schema); - if (ns.getMergedTraits().sensitive) { + const ns2 = NormalizedSchema.of(schema); + if (ns2.getMergedTraits().sensitive) { return SENSITIVE_STRING; } - if (ns.isListSchema()) { - const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (ns2.isListSchema()) { + const isSensitive = !!ns2.getValueSchema().getMergedTraits().sensitive; if (isSensitive) { return SENSITIVE_STRING; } - } else if (ns.isMapSchema()) { - const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + } else if (ns2.isMapSchema()) { + const isSensitive = !!ns2.getKeySchema().getMergedTraits().sensitive || !!ns2.getValueSchema().getMergedTraits().sensitive; if (isSensitive) { return SENSITIVE_STRING; } - } else if (ns.isStructSchema() && typeof data === "object") { + } else if (ns2.isStructSchema() && typeof data === "object") { const object = data; const newObject = {}; - for (const [member2, memberNs] of ns.structIterator()) { + for (const [member2, memberNs] of ns2.structIterator()) { if (object[member2] != null) { newObject[member2] = schemaLogFilter(memberNs, object[member2]); } @@ -25343,7 +25383,7 @@ var init_command2 = __esm({ this._commandName = commandName; return this; } - f(inputFilter = (_) => _, outputFilter = (_) => _) { + f(inputFilter = (_2) => _2, outputFilter = (_2) => _2) { this._inputFilterSensitiveLog = inputFilter; this._outputFilterSensitiveLog = outputFilter; return this; @@ -25384,8 +25424,8 @@ var init_command2 = __esm({ middlewareFn: closure._middlewareFn, clientName: closure._clientName, commandName: closure._commandName, - inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _), - outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _), + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_2) => _2), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_2) => _2), smithyContext: closure._smithyContext, additionalContext: closure._additionalContext }); @@ -25410,9 +25450,8 @@ var createAggregatedClient; var init_create_aggregated_client = __esm({ "../node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() { "use strict"; - createAggregatedClient = (commands5, Client2) => { - for (const command of Object.keys(commands5)) { - const CommandCtor = commands5[command]; + createAggregatedClient = (commands5, Client2, options) => { + for (const [command, CommandCtor] of Object.entries(commands5)) { const methodImpl = async function(args, optionsOrCb, cb2) { const command2 = new CommandCtor(args); if (typeof optionsOrCb === "function") { @@ -25428,6 +25467,33 @@ var init_create_aggregated_client = __esm({ const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); Client2.prototype[methodName] = methodImpl; } + const { paginators: paginators2 = {}, waiters = {} } = options ?? {}; + for (const [paginatorName, paginatorFn] of Object.entries(paginators2)) { + if (Client2.prototype[paginatorName] === void 0) { + Client2.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) { + return paginatorFn({ + ...paginationConfiguration, + client: this + }, commandInput, ...rest); + }; + } + } + for (const [waiterName, waiterFn] of Object.entries(waiters)) { + if (Client2.prototype[waiterName] === void 0) { + Client2.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) { + let config = waiterConfiguration; + if (typeof waiterConfiguration === "number") { + config = { + maxWaitTime: waiterConfiguration + }; + } + return waiterFn({ + ...config, + client: this + }, commandInput, ...rest); + }; + } + } }; } }); @@ -25472,9 +25538,9 @@ var init_exceptions = __esm({ } }; decorateServiceException = (exception, additions = {}) => { - Object.entries(additions).filter(([, v7]) => v7 !== void 0).forEach(([k6, v7]) => { - if (exception[k6] == void 0 || exception[k6] === "") { - exception[k6] = v7; + Object.entries(additions).filter(([, v8]) => v8 !== void 0).forEach(([k7, v8]) => { + if (exception[k7] == void 0 || exception[k7] === "") { + exception[k7] = v8; } }); const message = exception.message || exception.Message || "UnknownError"; @@ -25834,8 +25900,8 @@ var init_ProtocolLib = __esm({ Type }; Object.assign(output, Error2); - for (const [k6, v7] of entries) { - Error2[k6 === "message" ? "Message" : k6] = v7; + for (const [k7, v8] of entries) { + Error2[k7 === "message" ? "Message" : k7] = v8; } delete Error2.__type; output.Error = Error2; @@ -25891,53 +25957,6 @@ var init_ConfigurableSerdeContext = __esm({ } }); -// ../node_modules/@aws-sdk/core/dist-es/submodules/protocols/structIterator.js -function* serializingStructIterator(ns, sourceObject) { - if (ns.isUnitSchema()) { - return; - } - const struct = ns.getSchema(); - for (let i6 = 0; i6 < struct[4].length; ++i6) { - const key = struct[4][i6]; - const memberSchema = struct[5][i6]; - const memberNs = new NormalizedSchema([memberSchema, 0], key); - if (!(key in sourceObject) && !memberNs.isIdempotencyToken()) { - continue; - } - yield [key, memberNs]; - } -} -function* deserializingStructIterator(ns, sourceObject, nameTrait) { - if (ns.isUnitSchema()) { - return; - } - const struct = ns.getSchema(); - let keysRemaining = Object.keys(sourceObject).filter((k6) => k6 !== "__type").length; - for (let i6 = 0; i6 < struct[4].length; ++i6) { - if (keysRemaining === 0) { - break; - } - const key = struct[4][i6]; - const memberSchema = struct[5][i6]; - const memberNs = new NormalizedSchema([memberSchema, 0], key); - let serializationKey = key; - if (nameTrait) { - serializationKey = memberNs.getMergedTraits()[nameTrait] ?? key; - } - if (!(serializationKey in sourceObject)) { - continue; - } - yield [key, memberNs]; - keysRemaining -= 1; - } -} -var init_structIterator = __esm({ - "../node_modules/@aws-sdk/core/dist-es/submodules/protocols/structIterator.js"() { - "use strict"; - init_schema2(); - } -}); - // ../node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js var UnionSerde; var init_UnionSerde = __esm({ @@ -25950,7 +25969,7 @@ var init_UnionSerde = __esm({ constructor(from, to2) { this.from = from; this.to = to2; - this.keys = new Set(Object.keys(this.from).filter((k6) => k6 !== "__type")); + this.keys = new Set(Object.keys(this.from).filter((k7) => k7 !== "__type")); } mark(key) { this.keys.delete(key); @@ -25960,9 +25979,9 @@ var init_UnionSerde = __esm({ } writeUnknown() { if (this.hasUnknown()) { - const k6 = this.keys.values().next().value; - const v7 = this.from[k6]; - this.to.$unknown = [k6, v7]; + const k7 = this.keys.values().next().value; + const v8 = this.from[k7]; + this.to.$unknown = [k7, v8]; } } }; @@ -26026,7 +26045,7 @@ var init_parseJsonBody = __esm({ return {}; }); loadRestJsonErrorCode = (output, data) => { - const findKey = (object, key) => Object.keys(object).find((k6) => k6.toLowerCase() === key.toLowerCase()); + const findKey = (object, key) => Object.keys(object).find((k7) => k7.toLowerCase() === key.toLowerCase()); const sanitizeErrorCode = (rawValue) => { let cleanValue = rawValue; if (typeof cleanValue === "number") { @@ -26070,7 +26089,6 @@ var init_JsonShapeDeserializer = __esm({ init_serde2(); init_dist_es8(); init_ConfigurableSerdeContext(); - init_structIterator(); init_UnionSerde(); init_jsonReviver(); init_parseJsonBody(); @@ -26088,11 +26106,11 @@ var init_JsonShapeDeserializer = __esm({ } _read(schema, value) { const isObject2 = value !== null && typeof value === "object"; - const ns = NormalizedSchema.of(schema); + const ns2 = NormalizedSchema.of(schema); if (isObject2) { - if (ns.isStructSchema()) { + if (ns2.isStructSchema()) { const record = value; - const union = ns.isUnionSchema(); + const union = ns2.isUnionSchema(); const out = {}; let nameMap = void 0; const { jsonName } = this.settings; @@ -26103,7 +26121,7 @@ var init_JsonShapeDeserializer = __esm({ if (union) { unionSerde = new UnionSerde(record, out); } - for (const [memberName, memberSchema] of deserializingStructIterator(ns, record, jsonName ? "jsonName" : false)) { + for (const [memberName, memberSchema] of ns2.structIterator()) { let fromKey = memberName; if (jsonName) { fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; @@ -26119,19 +26137,19 @@ var init_JsonShapeDeserializer = __esm({ if (union) { unionSerde.writeUnknown(); } else if (typeof record.__type === "string") { - for (const [k6, v7] of Object.entries(record)) { - const t12 = jsonName ? nameMap[k6] ?? k6 : k6; + for (const [k7, v8] of Object.entries(record)) { + const t12 = jsonName ? nameMap[k7] ?? k7 : k7; if (!(t12 in out)) { - out[t12] = v7; + out[t12] = v8; } } } return out; } - if (Array.isArray(value) && ns.isListSchema()) { - const listMember = ns.getValueSchema(); + if (Array.isArray(value) && ns2.isListSchema()) { + const listMember = ns2.getValueSchema(); const out = []; - const sparse = !!ns.getMergedTraits().sparse; + const sparse = !!ns2.getMergedTraits().sparse; for (const item of value) { if (sparse || item != null) { out.push(this._read(listMember, item)); @@ -26139,10 +26157,10 @@ var init_JsonShapeDeserializer = __esm({ } return out; } - if (ns.isMapSchema()) { - const mapMember = ns.getValueSchema(); + if (ns2.isMapSchema()) { + const mapMember = ns2.getValueSchema(); const out = {}; - const sparse = !!ns.getMergedTraits().sparse; + const sparse = !!ns2.getMergedTraits().sparse; for (const [_k, _v] of Object.entries(value)) { if (sparse || _v != null) { out[_k] = this._read(mapMember, _v); @@ -26151,19 +26169,19 @@ var init_JsonShapeDeserializer = __esm({ return out; } } - if (ns.isBlobSchema() && typeof value === "string") { + if (ns2.isBlobSchema() && typeof value === "string") { return fromBase64(value); } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const mediaType = ns2.getMergedTraits().mediaType; + if (ns2.isStringSchema() && typeof value === "string" && mediaType) { const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { return LazyJsonString.from(value); } return value; } - if (ns.isTimestampSchema() && value != null) { - const format2 = determineTimestampFormat(ns, this.settings); + if (ns2.isTimestampSchema() && value != null) { + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: return parseRfc3339DateTimeWithOffset(value); @@ -26176,10 +26194,10 @@ var init_JsonShapeDeserializer = __esm({ return new Date(value); } } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + if (ns2.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { return BigInt(value); } - if (ns.isBigDecimalSchema() && value != void 0) { + if (ns2.isBigDecimalSchema() && value != void 0) { if (value instanceof NumericValue) { return value; } @@ -26189,7 +26207,7 @@ var init_JsonShapeDeserializer = __esm({ } return new NumericValue(String(value), "bigDecimal"); } - if (ns.isNumericSchema() && typeof value === "string") { + if (ns2.isNumericSchema() && typeof value === "string") { switch (value) { case "Infinity": return Infinity; @@ -26200,14 +26218,14 @@ var init_JsonShapeDeserializer = __esm({ } return value; } - if (ns.isDocumentSchema()) { + if (ns2.isDocumentSchema()) { if (isObject2) { const out = Array.isArray(value) ? [] : {}; - for (const [k6, v7] of Object.entries(value)) { - if (v7 instanceof NumericValue) { - out[k6] = v7; + for (const [k7, v8] of Object.entries(value)) { + if (v8 instanceof NumericValue) { + out[k7] = v8; } else { - out[k6] = this._read(ns, v7); + out[k7] = this._read(ns2, v8); } } return out; @@ -26242,15 +26260,15 @@ var init_jsonReplacer = __esm({ this.stage = 1; return (key, value) => { if (value instanceof NumericValue) { - const v7 = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v7}"`, value.string); - return v7; + const v8 = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v8}"`, value.string); + return v8; } if (typeof value === "bigint") { const s6 = value.toString(); - const v7 = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s6; - this.values.set(`"${v7}"`, s6); - return v7; + const v8 = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s6; + this.values.set(`"${v8}"`, s6); + return v8; } return value; }; @@ -26285,7 +26303,6 @@ var init_JsonShapeSerializer = __esm({ init_serde2(); init_dist_es8(); init_ConfigurableSerdeContext(); - init_structIterator(); init_jsonReplacer(); JsonShapeSerializer = class extends SerdeContextConfig { settings; @@ -26321,9 +26338,9 @@ var init_JsonShapeSerializer = __esm({ } _write(schema, value, container) { const isObject2 = value !== null && typeof value === "object"; - const ns = NormalizedSchema.of(schema); + const ns2 = NormalizedSchema.of(schema); if (isObject2) { - if (ns.isStructSchema()) { + if (ns2.isStructSchema()) { const record = value; const out = {}; const { jsonName } = this.settings; @@ -26331,8 +26348,8 @@ var init_JsonShapeSerializer = __esm({ if (jsonName) { nameMap = {}; } - for (const [memberName, memberSchema] of serializingStructIterator(ns, record)) { - const serializableValue = this._write(memberSchema, record[memberName], ns); + for (const [memberName, memberSchema] of ns2.structIterator()) { + const serializableValue = this._write(memberSchema, record[memberName], ns2); if (serializableValue !== void 0) { let targetKey = memberName; if (jsonName) { @@ -26342,26 +26359,26 @@ var init_JsonShapeSerializer = __esm({ out[targetKey] = serializableValue; } } - if (ns.isUnionSchema() && Object.keys(out).length === 0) { + if (ns2.isUnionSchema() && Object.keys(out).length === 0) { const { $unknown } = record; if (Array.isArray($unknown)) { - const [k6, v7] = $unknown; - out[k6] = this._write(15, v7); + const [k7, v8] = $unknown; + out[k7] = this._write(15, v8); } } else if (typeof record.__type === "string") { - for (const [k6, v7] of Object.entries(record)) { - const targetKey = jsonName ? nameMap[k6] ?? k6 : k6; + for (const [k7, v8] of Object.entries(record)) { + const targetKey = jsonName ? nameMap[k7] ?? k7 : k7; if (!(targetKey in out)) { - out[targetKey] = this._write(15, v7); + out[targetKey] = this._write(15, v8); } } } return out; } - if (Array.isArray(value) && ns.isListSchema()) { - const listMember = ns.getValueSchema(); + if (Array.isArray(value) && ns2.isListSchema()) { + const listMember = ns2.getValueSchema(); const out = []; - const sparse = !!ns.getMergedTraits().sparse; + const sparse = !!ns2.getMergedTraits().sparse; for (const item of value) { if (sparse || item != null) { out.push(this._write(listMember, item)); @@ -26369,10 +26386,10 @@ var init_JsonShapeSerializer = __esm({ } return out; } - if (ns.isMapSchema()) { - const mapMember = ns.getValueSchema(); + if (ns2.isMapSchema()) { + const mapMember = ns2.getValueSchema(); const out = {}; - const sparse = !!ns.getMergedTraits().sparse; + const sparse = !!ns2.getMergedTraits().sparse; for (const [_k, _v] of Object.entries(value)) { if (sparse || _v != null) { out[_k] = this._write(mapMember, _v); @@ -26380,14 +26397,14 @@ var init_JsonShapeSerializer = __esm({ } return out; } - if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { - if (ns === this.rootSchema) { + if (value instanceof Uint8Array && (ns2.isBlobSchema() || ns2.isDocumentSchema())) { + if (ns2 === this.rootSchema) { return value; } return (this.serdeContext?.base64Encoder ?? toBase64)(value); } - if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { - const format2 = determineTimestampFormat(ns, this.settings); + if (value instanceof Date && (ns2.isTimestampSchema() || ns2.isDocumentSchema())) { + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: return value.toISOString().replace(".000Z", "Z"); @@ -26407,11 +26424,11 @@ var init_JsonShapeSerializer = __esm({ if (value === null && container?.isStructSchema()) { return void 0; } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { + if (ns2.isStringSchema()) { + if (typeof value === "undefined" && ns2.isIdempotencyToken()) { return v4(); } - const mediaType = ns.getMergedTraits().mediaType; + const mediaType = ns2.getMergedTraits().mediaType; if (value != null && mediaType) { const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); if (isJson) { @@ -26420,14 +26437,14 @@ var init_JsonShapeSerializer = __esm({ } return value; } - if (typeof value === "number" && ns.isNumericSchema()) { + if (typeof value === "number" && ns2.isNumericSchema()) { if (Math.abs(value) === Infinity || isNaN(value)) { return String(value); } return value; } - if (typeof value === "string" && ns.isBlobSchema()) { - if (ns === this.rootSchema) { + if (typeof value === "string" && ns2.isBlobSchema()) { + if (ns2 === this.rootSchema) { return value; } return (this.serdeContext?.base64Encoder ?? toBase64)(value); @@ -26435,15 +26452,15 @@ var init_JsonShapeSerializer = __esm({ if (typeof value === "bigint") { this.useReplacer = true; } - if (ns.isDocumentSchema()) { + if (ns2.isDocumentSchema()) { if (isObject2) { const out = Array.isArray(value) ? [] : {}; - for (const [k6, v7] of Object.entries(value)) { - if (v7 instanceof NumericValue) { + for (const [k7, v8] of Object.entries(value)) { + if (v8 instanceof NumericValue) { this.useReplacer = true; - out[k6] = v7; + out[k7] = v8; } else { - out[k6] = this._write(ns, v7); + out[k7] = this._write(ns2, v8); } } return out; @@ -26574,18 +26591,18 @@ var init_AwsRestJsonProtocol = __esm({ async handleError(operationSchema, context3, response, dataObject, metadata) { const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = NormalizedSchema.of(errorSchema); + const ns2 = NormalizedSchema.of(errorSchema); const message = dataObject.message ?? dataObject.Message ?? "Unknown"; const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; const exception = new ErrorCtor(message); await this.deserializeHttpMessage(errorSchema, context3, response, dataObject); const output = {}; - for (const [name, member2] of ns.structIterator()) { + for (const [name, member2] of ns2.structIterator()) { const target = member2.getMergedTraits().jsonName ?? name; output[name] = this.codec.createDeserializer().readObject(member2, dataObject[target]); } throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, + $fault: ns2.getMergedTraits().error, message }, output), dataObject); } @@ -26740,21 +26757,21 @@ var init_XmlNode = __esm({ // ../node_modules/fast-xml-parser/src/util.js function getAllMatches(string, regex) { const matches = []; - let match2 = regex.exec(string); - while (match2) { + let match = regex.exec(string); + while (match) { const allmatches = []; - allmatches.startIndex = regex.lastIndex - match2[0].length; - const len = match2.length; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; for (let index = 0; index < len; index++) { - allmatches.push(match2[index]); + allmatches.push(match[index]); } matches.push(allmatches); - match2 = regex.exec(string); + match = regex.exec(string); } return matches; } -function isExist(v7) { - return typeof v7 !== "undefined"; +function isExist(v8) { + return typeof v8 !== "undefined"; } var nameStartChar, nameChar, nameRegexp, regexName, isName; var init_util2 = __esm({ @@ -26765,8 +26782,8 @@ var init_util2 = __esm({ nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; regexName = new RegExp("^" + nameRegexp + "$"); isName = function(string) { - const match2 = regexName.exec(string); - return !(match2 === null || typeof match2 === "undefined"); + const match = regexName.exec(string); + return !(match === null || typeof match === "undefined"); }; } }); @@ -27010,15 +27027,15 @@ function validateAttributeString(attrStr, options) { return true; } function validateNumberAmpersand(xmlData, i6) { - let re = /\d/; + let re2 = /\d/; if (xmlData[i6] === "x") { i6++; - re = /[\da-fA-F]/; + re2 = /[\da-fA-F]/; } for (; i6 < xmlData.length; i6++) { if (xmlData[i6] === ";") return i6; - if (!xmlData[i6].match(re)) + if (!xmlData[i6].match(re2)) break; } return -1; @@ -27065,8 +27082,8 @@ function getLineNumberForPosition(xmlData, index) { col: lines[lines.length - 1].length + 1 }; } -function getPositionFromMatch(match2) { - return match2.startIndex + match2[1].length; +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; } var defaultOptions, doubleQuote, singleQuote, validAttrStrRegxp; var init_validator = __esm({ @@ -27180,166 +27197,9 @@ var init_xmlNode = __esm({ }); // ../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js -function readDocType(xmlData, i6) { - const entities = {}; - if (xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "C" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "Y" && xmlData[i6 + 7] === "P" && xmlData[i6 + 8] === "E") { - i6 = i6 + 9; - let angleBracketsCount = 1; - let hasBody = false, comment = false; - let exp = ""; - for (; i6 < xmlData.length; i6++) { - if (xmlData[i6] === "<" && !comment) { - if (hasBody && hasSeq(xmlData, "!ENTITY", i6)) { - i6 += 7; - let entityName, val; - [entityName, val, i6] = readEntityExp(xmlData, i6 + 1); - if (val.indexOf("&") === -1) - entities[entityName] = { - regx: RegExp(`&${entityName};`, "g"), - val - }; - } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i6)) { - i6 += 8; - const { index } = readElementExp(xmlData, i6 + 1); - i6 = index; - } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i6)) { - i6 += 8; - } else if (hasBody && hasSeq(xmlData, "!NOTATION", i6)) { - i6 += 9; - const { index } = readNotationExp(xmlData, i6 + 1); - i6 = index; - } else if (hasSeq(xmlData, "!--", i6)) comment = true; - else throw new Error(`Invalid DOCTYPE`); - angleBracketsCount++; - exp = ""; - } else if (xmlData[i6] === ">") { - if (comment) { - if (xmlData[i6 - 1] === "-" && xmlData[i6 - 2] === "-") { - comment = false; - angleBracketsCount--; - } - } else { - angleBracketsCount--; - } - if (angleBracketsCount === 0) { - break; - } - } else if (xmlData[i6] === "[") { - hasBody = true; - } else { - exp += xmlData[i6]; - } - } - if (angleBracketsCount !== 0) { - throw new Error(`Unclosed DOCTYPE`); - } - } else { - throw new Error(`Invalid Tag instead of DOCTYPE`); - } - return { entities, i: i6 }; -} -function readEntityExp(xmlData, i6) { - i6 = skipWhitespace(xmlData, i6); - let entityName = ""; - while (i6 < xmlData.length && !/\s/.test(xmlData[i6]) && xmlData[i6] !== '"' && xmlData[i6] !== "'") { - entityName += xmlData[i6]; - i6++; - } - validateEntityName(entityName); - i6 = skipWhitespace(xmlData, i6); - if (xmlData.substring(i6, i6 + 6).toUpperCase() === "SYSTEM") { - throw new Error("External entities are not supported"); - } else if (xmlData[i6] === "%") { - throw new Error("Parameter entities are not supported"); - } - let entityValue = ""; - [i6, entityValue] = readIdentifierVal(xmlData, i6, "entity"); - i6--; - return [entityName, entityValue, i6]; -} -function readNotationExp(xmlData, i6) { - i6 = skipWhitespace(xmlData, i6); - let notationName = ""; - while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { - notationName += xmlData[i6]; - i6++; - } - validateEntityName(notationName); - i6 = skipWhitespace(xmlData, i6); - const identifierType = xmlData.substring(i6, i6 + 6).toUpperCase(); - if (identifierType !== "SYSTEM" && identifierType !== "PUBLIC") { - throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`); - } - i6 += identifierType.length; - i6 = skipWhitespace(xmlData, i6); - let publicIdentifier = null; - let systemIdentifier = null; - if (identifierType === "PUBLIC") { - [i6, publicIdentifier] = readIdentifierVal(xmlData, i6, "publicIdentifier"); - i6 = skipWhitespace(xmlData, i6); - if (xmlData[i6] === '"' || xmlData[i6] === "'") { - [i6, systemIdentifier] = readIdentifierVal(xmlData, i6, "systemIdentifier"); - } - } else if (identifierType === "SYSTEM") { - [i6, systemIdentifier] = readIdentifierVal(xmlData, i6, "systemIdentifier"); - if (!systemIdentifier) { - throw new Error("Missing mandatory system identifier for SYSTEM notation"); - } - } - return { notationName, publicIdentifier, systemIdentifier, index: --i6 }; -} -function readIdentifierVal(xmlData, i6, type) { - let identifierVal = ""; - const startChar = xmlData[i6]; - if (startChar !== '"' && startChar !== "'") { - throw new Error(`Expected quoted string, found "${startChar}"`); - } - i6++; - while (i6 < xmlData.length && xmlData[i6] !== startChar) { - identifierVal += xmlData[i6]; - i6++; - } - if (xmlData[i6] !== startChar) { - throw new Error(`Unterminated ${type} value`); - } - i6++; - return [i6, identifierVal]; -} -function readElementExp(xmlData, i6) { - i6 = skipWhitespace(xmlData, i6); - let elementName = ""; - while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { - elementName += xmlData[i6]; - i6++; - } - if (!validateEntityName(elementName)) { - throw new Error(`Invalid element name: "${elementName}"`); - } - i6 = skipWhitespace(xmlData, i6); - let contentModel = ""; - if (xmlData[i6] === "E" && hasSeq(xmlData, "MPTY", i6)) i6 += 4; - else if (xmlData[i6] === "A" && hasSeq(xmlData, "NY", i6)) i6 += 2; - else if (xmlData[i6] === "(") { - i6++; - while (i6 < xmlData.length && xmlData[i6] !== ")") { - contentModel += xmlData[i6]; - i6++; - } - if (xmlData[i6] !== ")") { - throw new Error("Unterminated content model"); - } - } else { - throw new Error(`Invalid Element Expression, found "${xmlData[i6]}"`); - } - return { - elementName, - contentModel: contentModel.trim(), - index: i6 - }; -} function hasSeq(data, seq, i6) { - for (let j6 = 0; j6 < seq.length; j6++) { - if (seq[j6] !== data[i6 + j6 + 1]) return false; + for (let j7 = 0; j7 < seq.length; j7++) { + if (seq[j7] !== data[i6 + j7 + 1]) return false; } return true; } @@ -27349,11 +27209,253 @@ function validateEntityName(name) { else throw new Error(`Invalid entity name ${name}`); } -var skipWhitespace; +var DocTypeReader, skipWhitespace; var init_DocTypeReader = __esm({ "../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"() { "use strict"; init_util2(); + DocTypeReader = class { + constructor(processEntities) { + this.suppressValidationErr = !processEntities; + } + readDocType(xmlData, i6) { + const entities = {}; + if (xmlData[i6 + 3] === "O" && xmlData[i6 + 4] === "C" && xmlData[i6 + 5] === "T" && xmlData[i6 + 6] === "Y" && xmlData[i6 + 7] === "P" && xmlData[i6 + 8] === "E") { + i6 = i6 + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i6 < xmlData.length; i6++) { + if (xmlData[i6] === "<" && !comment) { + if (hasBody && hasSeq(xmlData, "!ENTITY", i6)) { + i6 += 7; + let entityName, val; + [entityName, val, i6] = this.readEntityExp(xmlData, i6 + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) + entities[entityName] = { + regx: RegExp(`&${entityName};`, "g"), + val + }; + } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i6)) { + i6 += 8; + const { index } = this.readElementExp(xmlData, i6 + 1); + i6 = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i6)) { + i6 += 8; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i6)) { + i6 += 9; + const { index } = this.readNotationExp(xmlData, i6 + 1, this.suppressValidationErr); + i6 = index; + } else if (hasSeq(xmlData, "!--", i6)) comment = true; + else throw new Error(`Invalid DOCTYPE`); + angleBracketsCount++; + exp = ""; + } else if (xmlData[i6] === ">") { + if (comment) { + if (xmlData[i6 - 1] === "-" && xmlData[i6 - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i6] === "[") { + hasBody = true; + } else { + exp += xmlData[i6]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i: i6 }; + } + readEntityExp(xmlData, i6) { + i6 = skipWhitespace(xmlData, i6); + let entityName = ""; + while (i6 < xmlData.length && !/\s/.test(xmlData[i6]) && xmlData[i6] !== '"' && xmlData[i6] !== "'") { + entityName += xmlData[i6]; + i6++; + } + validateEntityName(entityName); + i6 = skipWhitespace(xmlData, i6); + if (!this.suppressValidationErr) { + if (xmlData.substring(i6, i6 + 6).toUpperCase() === "SYSTEM") { + throw new Error("External entities are not supported"); + } else if (xmlData[i6] === "%") { + throw new Error("Parameter entities are not supported"); + } + } + let entityValue = ""; + [i6, entityValue] = this.readIdentifierVal(xmlData, i6, "entity"); + i6--; + return [entityName, entityValue, i6]; + } + readNotationExp(xmlData, i6) { + i6 = skipWhitespace(xmlData, i6); + let notationName = ""; + while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { + notationName += xmlData[i6]; + i6++; + } + !this.suppressValidationErr && validateEntityName(notationName); + i6 = skipWhitespace(xmlData, i6); + const identifierType = xmlData.substring(i6, i6 + 6).toUpperCase(); + if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") { + throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`); + } + i6 += identifierType.length; + i6 = skipWhitespace(xmlData, i6); + let publicIdentifier = null; + let systemIdentifier = null; + if (identifierType === "PUBLIC") { + [i6, publicIdentifier] = this.readIdentifierVal(xmlData, i6, "publicIdentifier"); + i6 = skipWhitespace(xmlData, i6); + if (xmlData[i6] === '"' || xmlData[i6] === "'") { + [i6, systemIdentifier] = this.readIdentifierVal(xmlData, i6, "systemIdentifier"); + } + } else if (identifierType === "SYSTEM") { + [i6, systemIdentifier] = this.readIdentifierVal(xmlData, i6, "systemIdentifier"); + if (!this.suppressValidationErr && !systemIdentifier) { + throw new Error("Missing mandatory system identifier for SYSTEM notation"); + } + } + return { notationName, publicIdentifier, systemIdentifier, index: --i6 }; + } + readIdentifierVal(xmlData, i6, type) { + let identifierVal = ""; + const startChar = xmlData[i6]; + if (startChar !== '"' && startChar !== "'") { + throw new Error(`Expected quoted string, found "${startChar}"`); + } + i6++; + while (i6 < xmlData.length && xmlData[i6] !== startChar) { + identifierVal += xmlData[i6]; + i6++; + } + if (xmlData[i6] !== startChar) { + throw new Error(`Unterminated ${type} value`); + } + i6++; + return [i6, identifierVal]; + } + readElementExp(xmlData, i6) { + i6 = skipWhitespace(xmlData, i6); + let elementName = ""; + while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { + elementName += xmlData[i6]; + i6++; + } + if (!this.suppressValidationErr && !isName(elementName)) { + throw new Error(`Invalid element name: "${elementName}"`); + } + i6 = skipWhitespace(xmlData, i6); + let contentModel = ""; + if (xmlData[i6] === "E" && hasSeq(xmlData, "MPTY", i6)) i6 += 4; + else if (xmlData[i6] === "A" && hasSeq(xmlData, "NY", i6)) i6 += 2; + else if (xmlData[i6] === "(") { + i6++; + while (i6 < xmlData.length && xmlData[i6] !== ")") { + contentModel += xmlData[i6]; + i6++; + } + if (xmlData[i6] !== ")") { + throw new Error("Unterminated content model"); + } + } else if (!this.suppressValidationErr) { + throw new Error(`Invalid Element Expression, found "${xmlData[i6]}"`); + } + return { + elementName, + contentModel: contentModel.trim(), + index: i6 + }; + } + readAttlistExp(xmlData, i6) { + i6 = skipWhitespace(xmlData, i6); + let elementName = ""; + while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { + elementName += xmlData[i6]; + i6++; + } + validateEntityName(elementName); + i6 = skipWhitespace(xmlData, i6); + let attributeName = ""; + while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { + attributeName += xmlData[i6]; + i6++; + } + if (!validateEntityName(attributeName)) { + throw new Error(`Invalid attribute name: "${attributeName}"`); + } + i6 = skipWhitespace(xmlData, i6); + let attributeType = ""; + if (xmlData.substring(i6, i6 + 8).toUpperCase() === "NOTATION") { + attributeType = "NOTATION"; + i6 += 8; + i6 = skipWhitespace(xmlData, i6); + if (xmlData[i6] !== "(") { + throw new Error(`Expected '(', found "${xmlData[i6]}"`); + } + i6++; + let allowedNotations = []; + while (i6 < xmlData.length && xmlData[i6] !== ")") { + let notation = ""; + while (i6 < xmlData.length && xmlData[i6] !== "|" && xmlData[i6] !== ")") { + notation += xmlData[i6]; + i6++; + } + notation = notation.trim(); + if (!validateEntityName(notation)) { + throw new Error(`Invalid notation name: "${notation}"`); + } + allowedNotations.push(notation); + if (xmlData[i6] === "|") { + i6++; + i6 = skipWhitespace(xmlData, i6); + } + } + if (xmlData[i6] !== ")") { + throw new Error("Unterminated list of notations"); + } + i6++; + attributeType += " (" + allowedNotations.join("|") + ")"; + } else { + while (i6 < xmlData.length && !/\s/.test(xmlData[i6])) { + attributeType += xmlData[i6]; + i6++; + } + const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; + if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) { + throw new Error(`Invalid attribute type: "${attributeType}"`); + } + } + i6 = skipWhitespace(xmlData, i6); + let defaultValue = ""; + if (xmlData.substring(i6, i6 + 8).toUpperCase() === "#REQUIRED") { + defaultValue = "#REQUIRED"; + i6 += 8; + } else if (xmlData.substring(i6, i6 + 7).toUpperCase() === "#IMPLIED") { + defaultValue = "#IMPLIED"; + i6 += 7; + } else { + [i6, defaultValue] = this.readIdentifierVal(xmlData, i6, "ATTLIST"); + } + return { + elementName, + attributeName, + attributeType, + defaultValue, + index: i6 + }; + } + }; skipWhitespace = (data, index) => { while (index < data.length && /\s/.test(data[index])) { index++; @@ -27375,11 +27477,11 @@ function toNumber(str, options = {}) { } else if (trimmedStr.includes("e") || trimmedStr.includes("E")) { return resolveEnotation(str, trimmedStr, options); } else { - const match2 = numRegex.exec(trimmedStr); - if (match2) { - const sign2 = match2[1] || ""; - const leadingZeros = match2[2]; - let numTrimmedByZeros = trimZeros(match2[3]); + const match = numRegex.exec(trimmedStr); + if (match) { + const sign2 = match[1] || ""; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); const decimalAdjacentToLeadingZeros = sign2 ? ( // 0., -00., 000. str[leadingZeros.length + 1] === "." @@ -27399,11 +27501,11 @@ function toNumber(str, options = {}) { else if (parsedStr === `${sign2}${numTrimmedByZeros}`) return num; else return str; } - let n6 = leadingZeros ? numTrimmedByZeros : trimmedStr; + let n12 = leadingZeros ? numTrimmedByZeros : trimmedStr; if (leadingZeros) { - return n6 === parsedStr || sign2 + n6 === parsedStr ? num : str; + return n12 === parsedStr || sign2 + n12 === parsedStr ? num : str; } else { - return n6 === parsedStr || n6 === sign2 + parsedStr ? num : str; + return n12 === parsedStr || n12 === sign2 + parsedStr ? num : str; } } } else { @@ -27541,7 +27643,7 @@ function resolveNameSpace(tagname) { } return tagname; } -function buildAttributesMap(attrStr, jPath, tagName) { +function buildAttributesMap(attrStr, jPath) { if (this.options.ignoreAttributes !== true && typeof attrStr === "string") { const matches = getAllMatches(attrStr, attrsRegx); const len = matches.length; @@ -27619,12 +27721,9 @@ function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { } return textData; } -function isItStopNode(stopNodes, jPath, currentTagName) { - const allNodesExp = "*." + currentTagName; - for (const stopNodePath in stopNodes) { - const stopNodeExp = stopNodes[stopNodePath]; - if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; - } +function isItStopNode(stopNodesExact, stopNodesWildcard, jPath, currentTagName) { + if (stopNodesWildcard && stopNodesWildcard.has(currentTagName)) return true; + if (stopNodesExact && stopNodesExact.has(jPath)) return true; return false; } function tagExpWithClosingIndex(xmlData, i6, closingChar = ">") { @@ -27746,6 +27845,14 @@ function parseValue(val, shouldParse, options) { } } } +function fromCodePoint(str, base, prefix) { + const codePoint = Number.parseInt(str, base); + if (codePoint >= 0 && codePoint <= 1114111) { + return String.fromCodePoint(codePoint); + } else { + return prefix + str + ";"; + } +} var OrderedObjParser, attrsRegx, parseXml, replaceEntitiesValue; var init_OrderedObjParser = __esm({ "../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"() { @@ -27782,8 +27889,8 @@ var init_OrderedObjParser = __esm({ "copyright": { regex: /&(copy|#169);/g, val: "\xA9" }, "reg": { regex: /&(reg|#174);/g, val: "\xAE" }, "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" }, - "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) }, - "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) } + "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_2, str) => fromCodePoint(str, 10, "&#") }, + "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_2, str) => fromCodePoint(str, 16, "&#x") } }; this.addExternalEntities = addExternalEntities; this.parseXml = parseXml; @@ -27796,6 +27903,19 @@ var init_OrderedObjParser = __esm({ this.saveTextToParentTag = saveTextToParentTag; this.addChild = addChild; this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes); + if (this.options.stopNodes && this.options.stopNodes.length > 0) { + this.stopNodesExact = /* @__PURE__ */ new Set(); + this.stopNodesWildcard = /* @__PURE__ */ new Set(); + for (let i6 = 0; i6 < this.options.stopNodes.length; i6++) { + const stopNodeExp = this.options.stopNodes[i6]; + if (typeof stopNodeExp !== "string") continue; + if (stopNodeExp.startsWith("*.")) { + this.stopNodesWildcard.add(stopNodeExp.substring(2)); + } else { + this.stopNodesExact.add(stopNodeExp); + } + } + } } }; attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); @@ -27805,6 +27925,7 @@ var init_OrderedObjParser = __esm({ let currentNode = xmlObj; let textData = ""; let jPath = ""; + const docTypeReader = new DocTypeReader(this.options.processEntities); for (let i6 = 0; i6 < xmlData.length; i6++) { const ch2 = xmlData[i6]; if (ch2 === "<") { @@ -27847,7 +27968,7 @@ var init_OrderedObjParser = __esm({ const childNode = new XmlNode2(tagData.tagName); childNode.add(this.options.textNodeName, ""); if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName); + childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath); } this.addChild(currentNode, childNode, jPath, i6); } @@ -27861,7 +27982,7 @@ var init_OrderedObjParser = __esm({ } i6 = endIndex; } else if (xmlData.substr(i6 + 1, 2) === "!D") { - const result = readDocType(xmlData, i6); + const result = docTypeReader.readDocType(xmlData, i6); this.docTypeEntities = result.entities; i6 = result.i; } else if (xmlData.substr(i6 + 1, 2) === "![") { @@ -27884,7 +28005,11 @@ var init_OrderedObjParser = __esm({ let attrExpPresent = result.attrExpPresent; let closeIndex = result.closeIndex; if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + const newTagName = this.options.transformTagName(tagName); + if (tagExp === tagName) { + tagExp = newTagName; + } + tagName = newTagName; } if (currentNode && textData) { if (currentNode.tagname !== "!xml") { @@ -27900,7 +28025,7 @@ var init_OrderedObjParser = __esm({ jPath += jPath ? "." + tagName : tagName; } const startIndex = i6; - if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) { + if (this.isItStopNode(this.stopNodesExact, this.stopNodesWildcard, jPath, tagName)) { let tagContent = ""; if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) { if (tagName[tagName.length - 1] === "/") { @@ -27921,7 +28046,10 @@ var init_OrderedObjParser = __esm({ } const childNode = new XmlNode2(tagName); if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + childNode[":@"] = this.buildAttributesMap( + tagExp, + jPath + ); } if (tagContent) { tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true); @@ -27939,11 +28067,15 @@ var init_OrderedObjParser = __esm({ tagExp = tagExp.substr(0, tagExp.length - 1); } if (this.options.transformTagName) { - tagName = this.options.transformTagName(tagName); + const newTagName = this.options.transformTagName(tagName); + if (tagExp === tagName) { + tagExp = newTagName; + } + tagName = newTagName; } const childNode = new XmlNode2(tagName); if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + childNode[":@"] = this.buildAttributesMap(tagExp, jPath); } this.addChild(currentNode, childNode, jPath, startIndex); jPath = jPath.substr(0, jPath.lastIndexOf(".")); @@ -27951,7 +28083,7 @@ var init_OrderedObjParser = __esm({ const childNode = new XmlNode2(tagName); this.tagsNodeStack.push(currentNode); if (tagName !== tagExp && attrExpPresent) { - childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName); + childNode[":@"] = this.buildAttributesMap(tagExp, jPath); } this.addChild(currentNode, childNode, jPath, startIndex); currentNode = childNode; @@ -28098,14 +28230,13 @@ var init_XMLParser = __esm({ } /** * Parse XML dats to JS object - * @param {string|Buffer} xmlData + * @param {string|Uint8Array} xmlData * @param {boolean|Object} validationOption */ parse(xmlData, validationOption) { - if (typeof xmlData === "string") { - } else if (xmlData.toString) { + if (typeof xmlData !== "string" && xmlData.toString) { xmlData = xmlData.toString(); - } else { + } else if (typeof xmlData !== "string") { throw new Error("XML data is accepted in String or Bytes[] form."); } if (validationOption) { @@ -28178,7 +28309,7 @@ var init_xml_parser = __esm({ ignoreDeclaration: true, parseTagValue: false, trimValues: false, - tagValueProcessor: (_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0 + tagValueProcessor: (_2, val) => val.trim() === "" && val.includes("\n") ? "" : void 0 }); parser.addEntity("#xD", "\r"); parser.addEntity("#10", "\n"); @@ -28220,9 +28351,9 @@ var init_XmlShapeDeserializer = __esm({ this.stringDeserializer.setSerdeContext(serdeContext); } read(schema, bytes, key) { - const ns = NormalizedSchema.of(schema); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { + const ns2 = NormalizedSchema.of(schema); + const memberSchemas = ns2.getMemberSchemas(); + const isEventPayload = ns2.isStructSchema() && ns2.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { return !!memberNs.getMemberTraits().eventPayload; }); if (isEventPayload) { @@ -28241,13 +28372,13 @@ var init_XmlShapeDeserializer = __esm({ return this.readSchema(schema, key ? parsedObject[key] : parsedObject); } readSchema(_schema, value) { - const ns = NormalizedSchema.of(_schema); - if (ns.isUnitSchema()) { + const ns2 = NormalizedSchema.of(_schema); + if (ns2.isUnitSchema()) { return; } - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); + const traits = ns2.getMergedTraits(); + if (ns2.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns2, [value]); } if (value == null) { return value; @@ -28255,23 +28386,23 @@ var init_XmlShapeDeserializer = __esm({ if (typeof value === "object") { const sparse = !!traits.sparse; const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); + if (ns2.isListSchema()) { + const listValue = ns2.getValueSchema(); const buffer2 = []; const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; const source = flat ? value : (value[0] ?? value)[sourceKey]; const sourceArray = Array.isArray(source) ? source : [source]; - for (const v7 of sourceArray) { - if (v7 != null || sparse) { - buffer2.push(this.readSchema(listValue, v7)); + for (const v8 of sourceArray) { + if (v8 != null || sparse) { + buffer2.push(this.readSchema(listValue, v8)); } } return buffer2; } const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); + if (ns2.isMapSchema()) { + const keyNs = ns2.getKeySchema(); + const memberNs = ns2.getValueSchema(); let entries; if (flat) { entries = Array.isArray(value) ? value : [value]; @@ -28289,13 +28420,13 @@ var init_XmlShapeDeserializer = __esm({ } return buffer; } - if (ns.isStructSchema()) { - const union = ns.isUnionSchema(); + if (ns2.isStructSchema()) { + const union = ns2.isUnionSchema(); let unionSerde; if (union) { unionSerde = new UnionSerde(value, buffer); } - for (const [memberName, memberSchema] of ns.structIterator()) { + for (const [memberName, memberSchema] of ns2.structIterator()) { const memberTraits = memberSchema.getMergedTraits(); const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); if (union) { @@ -28310,18 +28441,18 @@ var init_XmlShapeDeserializer = __esm({ } return buffer; } - if (ns.isDocumentSchema()) { + if (ns2.isDocumentSchema()) { return value; } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns2.getName(true)}`); } - if (ns.isListSchema()) { + if (ns2.isListSchema()) { return []; } - if (ns.isMapSchema() || ns.isStructSchema()) { + if (ns2.isMapSchema() || ns2.isStructSchema()) { return {}; } - return this.stringDeserializer.read(ns, value); + return this.stringDeserializer.read(ns2, value); } parseXml(xml) { if (xml.length) { @@ -28362,7 +28493,6 @@ var init_QueryShapeSerializer = __esm({ init_dist_es20(); init_dist_es8(); init_ConfigurableSerdeContext(); - init_structIterator(); QueryShapeSerializer = class extends SerdeContextConfig { settings; buffer; @@ -28374,37 +28504,37 @@ var init_QueryShapeSerializer = __esm({ if (this.buffer === void 0) { this.buffer = ""; } - const ns = NormalizedSchema.of(schema); + const ns2 = NormalizedSchema.of(schema); if (prefix && !prefix.endsWith(".")) { prefix += "."; } - if (ns.isBlobSchema()) { + if (ns2.isBlobSchema()) { if (typeof value === "string" || value instanceof Uint8Array) { this.writeKey(prefix); this.writeValue((this.serdeContext?.base64Encoder ?? toBase64)(value)); } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + } else if (ns2.isBooleanSchema() || ns2.isNumericSchema() || ns2.isStringSchema()) { if (value != null) { this.writeKey(prefix); this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { + } else if (ns2.isIdempotencyToken()) { this.writeKey(prefix); this.writeValue(v4()); } - } else if (ns.isBigIntegerSchema()) { + } else if (ns2.isBigIntegerSchema()) { if (value != null) { this.writeKey(prefix); this.writeValue(String(value)); } - } else if (ns.isBigDecimalSchema()) { + } else if (ns2.isBigDecimalSchema()) { if (value != null) { this.writeKey(prefix); this.writeValue(value instanceof NumericValue ? value.string : String(value)); } - } else if (ns.isTimestampSchema()) { + } else if (ns2.isTimestampSchema()) { if (value instanceof Date) { this.writeKey(prefix); - const format2 = determineTimestampFormat(ns, this.settings); + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: this.writeValue(value.toISOString().replace(".000Z", "Z")); @@ -28417,7 +28547,7 @@ var init_QueryShapeSerializer = __esm({ break; } } - } else if (ns.isDocumentSchema()) { + } else if (ns2.isDocumentSchema()) { if (Array.isArray(value)) { this.write(64 | 15, value, prefix); } else if (value instanceof Date) { @@ -28430,7 +28560,7 @@ var init_QueryShapeSerializer = __esm({ this.writeKey(prefix); this.writeValue(String(value)); } - } else if (ns.isListSchema()) { + } else if (ns2.isListSchema()) { if (Array.isArray(value)) { if (value.length === 0) { if (this.settings.serializeEmptyLists) { @@ -28438,63 +28568,67 @@ var init_QueryShapeSerializer = __esm({ this.writeValue(""); } } else { - const member2 = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + const member2 = ns2.getValueSchema(); + const flat = this.settings.flattenLists || ns2.getMergedTraits().xmlFlattened; let i6 = 1; for (const item of value) { if (item == null) { continue; } - const suffix = this.getKey("member", member2.getMergedTraits().xmlName); + const traits = member2.getMergedTraits(); + const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName); const key = flat ? `${prefix}${i6}` : `${prefix}${suffix}.${i6}`; this.write(member2, item, key); ++i6; } } } - } else if (ns.isMapSchema()) { + } else if (ns2.isMapSchema()) { if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; + const keySchema = ns2.getKeySchema(); + const memberSchema = ns2.getValueSchema(); + const flat = ns2.getMergedTraits().xmlFlattened; let i6 = 1; - for (const [k6, v7] of Object.entries(value)) { - if (v7 == null) { + for (const [k7, v8] of Object.entries(value)) { + if (v8 == null) { continue; } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); + const keyTraits = keySchema.getMergedTraits(); + const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName); const key = flat ? `${prefix}${i6}.${keySuffix}` : `${prefix}entry.${i6}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); + const valTraits = memberSchema.getMergedTraits(); + const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName); const valueKey = flat ? `${prefix}${i6}.${valueSuffix}` : `${prefix}entry.${i6}.${valueSuffix}`; - this.write(keySchema, k6, key); - this.write(memberSchema, v7, valueKey); + this.write(keySchema, k7, key); + this.write(memberSchema, v8, valueKey); ++i6; } } - } else if (ns.isStructSchema()) { + } else if (ns2.isStructSchema()) { if (value && typeof value === "object") { let didWriteMember = false; - for (const [memberName, member2] of serializingStructIterator(ns, value)) { + for (const [memberName, member2] of ns2.structIterator()) { if (value[memberName] == null && !member2.isIdempotencyToken()) { continue; } - const suffix = this.getKey(memberName, member2.getMergedTraits().xmlName); + const traits = member2.getMergedTraits(); + const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct"); const key = `${prefix}${suffix}`; this.write(member2, value[memberName], key); didWriteMember = true; } - if (!didWriteMember && ns.isUnionSchema()) { + if (!didWriteMember && ns2.isUnionSchema()) { const { $unknown } = value; if (Array.isArray($unknown)) { - const [k6, v7] = $unknown; - const key = `${prefix}${k6}`; - this.write(15, v7, key); + const [k7, v8] = $unknown; + const key = `${prefix}${k7}`; + this.write(15, v8, key); } } } - } else if (ns.isUnitSchema()) { + } else if (ns2.isUnitSchema()) { } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns2.getName(true)}`); } } flush() { @@ -28505,9 +28639,13 @@ var init_QueryShapeSerializer = __esm({ delete this.buffer; return str; } - getKey(memberName, xmlName) { + getKey(memberName, xmlName, ec2QueryName, keySource) { + const { ec2, capitalizeKeys } = this.settings; + if (ec2 && ec2QueryName) { + return ec2QueryName; + } const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { + if (capitalizeKeys && keySource === "struct") { return key[0].toUpperCase() + key.slice(1); } return key; @@ -28588,7 +28726,7 @@ var init_AwsQueryProtocol = __esm({ } async deserializeResponse(operationSchema, context3, response) { const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); + const ns2 = NormalizedSchema.of(operationSchema.output); const dataObject = {}; if (response.statusCode >= 300) { const bytes2 = await collectBody(response.body, context3); @@ -28603,10 +28741,10 @@ var init_AwsQueryProtocol = __esm({ response.headers[header.toLowerCase()] = value; } const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; + const awsQueryResultKey = ns2.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; const bytes = await collectBody(response.body, context3); if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + Object.assign(dataObject, await deserializer.read(ns2, bytes, awsQueryResultKey)); } const output = { $metadata: this.deserializeMetadata(response), @@ -28628,7 +28766,7 @@ var init_AwsQueryProtocol = __esm({ Message: message }; const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError); - const ns = NormalizedSchema.of(errorSchema); + const ns2 = NormalizedSchema.of(errorSchema); const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; const exception = new ErrorCtor(message); const output = { @@ -28636,13 +28774,13 @@ var init_AwsQueryProtocol = __esm({ Code: errorData.Error.Code, Error: errorData.Error }; - for (const [name, member2] of ns.structIterator()) { + for (const [name, member2] of ns2.structIterator()) { const target = member2.getMergedTraits().xmlName ?? name; const value = errorData[target] ?? dataObject[target]; output[name] = this.deserializer.readSchema(member2, value); } throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, + $fault: ns2.getMergedTraits().error, message }, output), dataObject); } @@ -28707,7 +28845,6 @@ var init_XmlShapeSerializer = __esm({ init_dist_es20(); init_dist_es8(); init_ConfigurableSerdeContext(); - init_structIterator(); XmlShapeSerializer = class extends SerdeContextConfig { settings; stringBuffer; @@ -28718,16 +28855,16 @@ var init_XmlShapeSerializer = __esm({ this.settings = settings; } write(schema, value) { - const ns = NormalizedSchema.of(schema); - if (ns.isStringSchema() && typeof value === "string") { + const ns2 = NormalizedSchema.of(schema); + if (ns2.isStringSchema() && typeof value === "string") { this.stringBuffer = value; - } else if (ns.isBlobSchema()) { + } else if (ns2.isBlobSchema()) { this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? fromBase64)(value); } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); + this.buffer = this.writeStruct(ns2, value, void 0); + const traits = ns2.getMergedTraits(); if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); + this.buffer.withName(ns2.getName()); } } } @@ -28751,15 +28888,15 @@ var init_XmlShapeSerializer = __esm({ delete this.buffer; return buffer.toString(); } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + writeStruct(ns2, value, parentXmlns) { + const traits = ns2.getMergedTraits(); + const name = ns2.isMemberSchema() && !traits.httpPayload ? ns2.getMemberTraits().xmlName ?? ns2.getMemberName() : traits.xmlName ?? ns2.getName(); + if (!name || !ns2.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns2.getName(true)}.`); } const structXmlNode = XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of serializingStructIterator(ns, value)) { + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns2, parentXmlns); + for (const [memberName, memberSchema] of ns2.structIterator()) { const val = value[memberName]; if (val != null || memberSchema.isIdempotencyToken()) { if (memberSchema.getMergedTraits().xmlAttribute) { @@ -28780,17 +28917,17 @@ var init_XmlShapeSerializer = __esm({ } } const { $unknown } = value; - if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { - const [k6, v7] = $unknown; - const node = XmlNode.of(k6); - if (typeof v7 !== "string") { + if ($unknown && ns2.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { + const [k7, v8] = $unknown; + const node = XmlNode.of(k7); + if (typeof v8 !== "string") { if (value instanceof XmlNode || value instanceof XmlText) { structXmlNode.addChildNode(value); } else { throw new Error(`@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`); } } - this.writeSimpleInto(0, v7, node, xmlns); + this.writeSimpleInto(0, v8, node, xmlns); structXmlNode.addChildNode(node); } if (xmlns) { @@ -28904,13 +29041,13 @@ var init_XmlShapeSerializer = __esm({ if (null === value) { throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); } - const ns = NormalizedSchema.of(_schema); + const ns2 = NormalizedSchema.of(_schema); let nodeContents = null; if (value && typeof value === "object") { - if (ns.isBlobSchema()) { + if (ns2.isBlobSchema()) { nodeContents = (this.serdeContext?.base64Encoder ?? toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const format2 = determineTimestampFormat(ns, this.settings); + } else if (ns2.isTimestampSchema() && value instanceof Date) { + const format2 = determineTimestampFormat(ns2, this.settings); switch (format2) { case 5: nodeContents = value.toISOString().replace(".000Z", "Z"); @@ -28926,44 +29063,44 @@ var init_XmlShapeSerializer = __esm({ nodeContents = dateToUtcString(value); break; } - } else if (ns.isBigDecimalSchema() && value) { + } else if (ns2.isBigDecimalSchema() && value) { if (value instanceof NumericValue) { return value.string; } return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { + } else if (ns2.isMapSchema() || ns2.isListSchema()) { throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); } else { - throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns2.getName(true)}`); } } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + if (ns2.isBooleanSchema() || ns2.isNumericSchema() || ns2.isBigIntegerSchema() || ns2.isBigDecimalSchema()) { nodeContents = String(value); } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { + if (ns2.isStringSchema()) { + if (value === void 0 && ns2.isIdempotencyToken()) { nodeContents = v4(); } else { nodeContents = String(value); } } if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + throw new Error(`Unhandled schema-value pair ${ns2.getName(true)}=${value}`); } return nodeContents; } writeSimpleInto(_schema, value, into, parentXmlns) { const nodeContents = this.writeSimple(_schema, value); - const ns = NormalizedSchema.of(_schema); + const ns2 = NormalizedSchema.of(_schema); const content = new XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns2, parentXmlns); if (xmlns) { into.addAttribute(xmlnsAttr, xmlns); } into.addChildNode(content); } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); + getXmlnsAttribute(ns2, parentXmlns) { + const traits = ns2.getMergedTraits(); const [prefix, xmlns] = traits.xmlNamespace ?? []; if (xmlns && xmlns !== parentXmlns) { return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; @@ -29057,28 +29194,39 @@ var init_AwsRestXmlProtocol = __esm({ } async handleError(operationSchema, context3, response, dataObject, metadata) { const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + if (dataObject.Error && typeof dataObject.Error === "object") { + for (const key of Object.keys(dataObject.Error)) { + dataObject[key] = dataObject.Error[key]; + if (key.toLowerCase() === "message") { + dataObject.message = dataObject.Error[key]; + } + } + } + if (dataObject.RequestId && !metadata.requestId) { + metadata.requestId = dataObject.RequestId; + } const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = NormalizedSchema.of(errorSchema); + const ns2 = NormalizedSchema.of(errorSchema); const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; const exception = new ErrorCtor(message); await this.deserializeHttpMessage(errorSchema, context3, response, dataObject); const output = {}; - for (const [name, member2] of ns.structIterator()) { + for (const [name, member2] of ns2.structIterator()) { const target = member2.getMergedTraits().xmlName ?? name; const value = dataObject.Error?.[target] ?? dataObject[target]; output[name] = this.codec.createDeserializer().readSchema(member2, value); } throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, + $fault: ns2.getMergedTraits().error, message }, output), dataObject); } getDefaultContentType() { return "application/xml"; } - hasUnstructuredPayloadBinding(ns) { - for (const [, member2] of ns.structIterator()) { + hasUnstructuredPayloadBinding(ns2) { + for (const [, member2] of ns2.structIterator()) { if (member2.getMergedTraits().httpPayload) { return !(member2.isStructSchema() || member2.isMapSchema() || member2.isListSchema()); } @@ -29713,18 +29861,18 @@ var init_getAttrPathList = __esm({ "../node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() { "use strict"; init_types3(); - getAttrPathList = (path7) => { - const parts = path7.split("."); + getAttrPathList = (path6) => { + const parts = path6.split("."); const pathList = []; for (const part of parts) { const squareBracketIndex = part.indexOf("["); if (squareBracketIndex !== -1) { if (part.indexOf("]") !== part.length - 1) { - throw new EndpointError(`Path: '${path7}' does not end with ']'`); + throw new EndpointError(`Path: '${path6}' does not end with ']'`); } const arrayIndex = part.slice(squareBracketIndex + 1, -1); if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path7}'`); + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path6}'`); } if (squareBracketIndex !== 0) { pathList.push(part.slice(0, squareBracketIndex)); @@ -29746,9 +29894,9 @@ var init_getAttr = __esm({ "use strict"; init_types3(); init_getAttrPathList(); - getAttr = (value, path7) => getAttrPathList(path7).reduce((acc, index) => { + getAttr = (value, path6) => getAttrPathList(path6).reduce((acc, index) => { if (typeof acc !== "object") { - throw new EndpointError(`Index '${index}' in '${path7}' not found in '${JSON.stringify(value)}'`); + throw new EndpointError(`Index '${index}' in '${path6}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { return acc[parseInt(index)]; } @@ -29793,9 +29941,9 @@ var init_parseURL = __esm({ return value; } if (typeof value === "object" && "hostname" in value) { - const { hostname: hostname2, port, protocol: protocol2 = "", path: path7 = "", query = {} } = value; - const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path7}`); - url.search = Object.entries(query).map(([k6, v7]) => `${k6}=${v7}`).join("&"); + const { hostname: hostname2, port, protocol: protocol2 = "", path: path6 = "", query = {} } = value; + const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path6}`); + url.search = Object.entries(query).map(([k7, v8]) => `${k7}=${v8}`).join("&"); return url; } return new URL(value); @@ -30257,13 +30405,13 @@ var init_resolveEndpoint = __esm({ const { endpointParams, logger: logger2 } = options; const { parameters, rules } = ruleSetObject; options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); - const paramsWithDefault = Object.entries(parameters).filter(([, v7]) => v7.default != null).map(([k6, v7]) => [k6, v7.default]); + const paramsWithDefault = Object.entries(parameters).filter(([, v8]) => v8.default != null).map(([k7, v8]) => [k7, v8.default]); if (paramsWithDefault.length > 0) { for (const [paramKey, paramDefaultValue] of paramsWithDefault) { endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; } } - const requiredParams = Object.entries(parameters).filter(([, v7]) => v7.required).map(([k6]) => k6); + const requiredParams = Object.entries(parameters).filter(([, v8]) => v8.required).map(([k7]) => k7); for (const requiredParam of requiredParams) { if (endpointParams[requiredParam] == null) { throw new EndpointError(`Missing required parameter: '${requiredParam}'`); @@ -30289,18 +30437,18 @@ var init_dist_es27 = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js var init_isIpAddress2 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { "use strict"; init_dist_es27(); } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js var isVirtualHostableS3Bucket; var init_isVirtualHostableS3Bucket = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { "use strict"; init_dist_es27(); init_isIpAddress2(); @@ -30330,10 +30478,10 @@ var init_isVirtualHostableS3Bucket = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn; var init_parseArn = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { "use strict"; ARN_DELIMITER = ":"; RESOURCE_DELIMITER = "/"; @@ -30341,12 +30489,12 @@ var init_parseArn = __esm({ const segments = value.split(ARN_DELIMITER); if (segments.length < 6) return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + const [arn, partition5, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition5 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null; const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); return { - partition: partition2, + partition: partition5, service, region, accountId, @@ -30356,10 +30504,10 @@ var init_parseArn = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json var partitions_default; var init_partitions = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { partitions_default = { partitions: [{ id: "aws", @@ -30630,18 +30778,18 @@ var init_partitions = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix; var init_partition = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { "use strict"; init_partitions(); selectedPartitionsInfo = partitions_default; selectedUserAgentPrefix = ""; partition = (value) => { const { partitions } = selectedPartitionsInfo; - for (const partition2 of partitions) { - const { regions, outputs } = partition2; + for (const partition5 of partitions) { + const { regions, outputs } = partition5; for (const [region, regionData] of Object.entries(regions)) { if (region === value) { return { @@ -30651,15 +30799,15 @@ var init_partition = __esm({ } } } - for (const partition2 of partitions) { - const { regionRegex, outputs } = partition2; + for (const partition5 of partitions) { + const { regionRegex, outputs } = partition5; if (new RegExp(regionRegex).test(value)) { return { ...outputs }; } } - const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); + const DEFAULT_PARTITION = partitions.find((partition5) => partition5.id === "aws"); if (!DEFAULT_PARTITION) { throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); } @@ -30671,10 +30819,10 @@ var init_partition = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/aws.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js var awsEndpointFunctions; var init_aws = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { "use strict"; init_dist_es27(); init_isVirtualHostableS3Bucket(); @@ -30743,65 +30891,65 @@ var init_dist_es29 = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js var init_resolveDefaultAwsRegionalEndpointsConfig = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js var init_resolveEndpoint2 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js var init_EndpointError2 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js var init_EndpointRuleObject3 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js var init_ErrorRuleObject3 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js var init_RuleSetObject3 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js var init_TreeRuleObject3 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js var init_shared3 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { "use strict"; } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js var init_types4 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { "use strict"; init_EndpointError2(); init_EndpointRuleObject3(); @@ -30812,9 +30960,9 @@ var init_types4 = __esm({ } }); -// ../node_modules/@aws-sdk/util-endpoints/dist-es/index.js +// ../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/index.js var init_dist_es30 = __esm({ - "../node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { + "../node_modules/@aws-sdk/middleware-user-agent/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { "use strict"; init_aws(); init_partition(); @@ -31279,9 +31427,9 @@ var init_s3 = __esm({ DOTS_PATTERN = /\.\./; isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); isArnBucketName = (bucketName) => { - const [arn, partition2, service, , , bucket] = bucketName.split(":"); + const [arn, partition5, service, , , bucket] = bucketName.split(":"); const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition2 && service && bucket); + const isValidArn = Boolean(isArn && partition5 && service && bucket); if (isArn && !isValidArn) { throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); } @@ -31343,8 +31491,8 @@ var init_createConfigValueProvider = __esm({ return endpoint2.url.href; } if ("hostname" in endpoint2) { - const { protocol, hostname, port, path: path7 } = endpoint2; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path7}`; + const { protocol, hostname, port, path: path6 } = endpoint2; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path6}`; } } return endpoint2; @@ -31592,14 +31740,14 @@ var init_readFile = __esm({ import_promises2 = require("fs/promises"); filePromises = {}; fileIntercept = {}; - readFile2 = (path7, options) => { - if (fileIntercept[path7] !== void 0) { - return fileIntercept[path7]; + readFile2 = (path6, options) => { + if (fileIntercept[path6] !== void 0) { + return fileIntercept[path6]; } - if (!filePromises[path7] || options?.ignoreCache) { - filePromises[path7] = (0, import_promises2.readFile)(path7, "utf8"); + if (!filePromises[path6] || options?.ignoreCache) { + filePromises[path6] = (0, import_promises2.readFile)(path6, "utf8"); } - return filePromises[path7]; + return filePromises[path6]; }; } }); @@ -31717,8 +31865,8 @@ var init_externalDataInterceptor = __esm({ getFileRecord() { return fileIntercept; }, - interceptFile(path7, contents) { - fileIntercept[path7] = Promise.resolve(contents); + interceptFile(path6, contents) { + fileIntercept[path6] = Promise.resolve(contents); }, getTokenRecord() { return tokenIntercept; @@ -33321,16 +33469,16 @@ function createGetRequest(url) { hostname: url.hostname, port: Number(url.port), path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k6, v7]) => { - acc[k6] = v7; + query: Array.from(url.searchParams.entries()).reduce((acc, [k7, v8]) => { + acc[k7] = v8; return acc; }, {}), fragment: url.hash }); } async function getCredentials(response, logger2) { - const stream3 = sdkStreamMixin2(response.body); - const str = await stream3.transformToString(); + const stream2 = sdkStreamMixin2(response.body); + const str = await stream2.transformToString(); if (response.statusCode === 200) { const parsed = JSON.parse(str); if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") { @@ -33573,7 +33721,7 @@ var init_package = __esm({ "../node_modules/@aws-sdk/nested-clients/package.json"() { package_default2 = { name: "@aws-sdk/nested-clients", - version: "3.974.0", + version: "3.990.0", description: "Nested clients for AWS SDK packages.", main: "./dist-cjs/index.js", module: "./dist-es/index.js", @@ -33602,37 +33750,37 @@ var init_package = __esm({ dependencies: { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.0", - "@aws-sdk/middleware-host-header": "^3.972.1", - "@aws-sdk/middleware-logger": "^3.972.1", - "@aws-sdk/middleware-recursion-detection": "^3.972.1", - "@aws-sdk/middleware-user-agent": "^3.972.1", - "@aws-sdk/region-config-resolver": "^3.972.1", - "@aws-sdk/types": "^3.973.0", - "@aws-sdk/util-endpoints": "3.972.0", - "@aws-sdk/util-user-agent-browser": "^3.972.1", - "@aws-sdk/util-user-agent-node": "^3.972.1", + "@aws-sdk/core": "^3.973.10", + "@aws-sdk/middleware-host-header": "^3.972.3", + "@aws-sdk/middleware-logger": "^3.972.3", + "@aws-sdk/middleware-recursion-detection": "^3.972.3", + "@aws-sdk/middleware-user-agent": "^3.972.10", + "@aws-sdk/region-config-resolver": "^3.972.3", + "@aws-sdk/types": "^3.973.1", + "@aws-sdk/util-endpoints": "3.990.0", + "@aws-sdk/util-user-agent-browser": "^3.972.3", + "@aws-sdk/util-user-agent-node": "^3.972.8", "@smithy/config-resolver": "^4.4.6", - "@smithy/core": "^3.21.0", + "@smithy/core": "^3.23.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", - "@smithy/middleware-endpoint": "^4.4.10", - "@smithy/middleware-retry": "^4.4.26", + "@smithy/middleware-endpoint": "^4.4.14", + "@smithy/middleware-retry": "^4.4.31", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", - "@smithy/node-http-handler": "^4.4.8", + "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", - "@smithy/smithy-client": "^4.10.11", + "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", - "@smithy/util-defaults-mode-browser": "^4.3.25", - "@smithy/util-defaults-mode-node": "^4.2.28", + "@smithy/util-defaults-mode-browser": "^4.3.30", + "@smithy/util-defaults-mode-node": "^4.2.33", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", @@ -33968,6 +34116,486 @@ var init_dist_es46 = __esm({ } }); +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js +var init_isIpAddress3 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { + "use strict"; + init_dist_es27(); + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js +var isVirtualHostableS3Bucket3; +var init_isVirtualHostableS3Bucket2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { + "use strict"; + init_dist_es27(); + init_isIpAddress3(); + isVirtualHostableS3Bucket3 = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket3(label)) { + return false; + } + } + return true; + } + if (!isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (isIpAddress(value)) { + return false; + } + return true; + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js +var ARN_DELIMITER3, RESOURCE_DELIMITER3, parseArn3; +var init_parseArn2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { + "use strict"; + ARN_DELIMITER3 = ":"; + RESOURCE_DELIMITER3 = "/"; + parseArn3 = (value) => { + const segments = value.split(ARN_DELIMITER3); + if (segments.length < 6) + return null; + const [arn, partition5, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition5 === "" || service === "" || resourcePath.join(ARN_DELIMITER3) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER3)).flat(); + return { + partition: partition5, + service, + region, + accountId, + resourceId + }; + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json +var partitions_default3; +var init_partitions2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { + partitions_default3 = { + partitions: [{ + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "AWS European Sovereign Cloud (Germany)" + } + } + }, { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + description: "US ISOB West" + } + } + }, { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + }], + version: "1.1" + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js +var selectedPartitionsInfo3, partition3; +var init_partition2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { + "use strict"; + init_partitions2(); + selectedPartitionsInfo3 = partitions_default3; + partition3 = (value) => { + const { partitions } = selectedPartitionsInfo3; + for (const partition5 of partitions) { + const { regions, outputs } = partition5; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } + } + } + for (const partition5 of partitions) { + const { regionRegex, outputs } = partition5; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition5) => partition5.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs + }; + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js +var awsEndpointFunctions3; +var init_aws2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { + "use strict"; + init_dist_es27(); + init_isVirtualHostableS3Bucket2(); + init_parseArn2(); + init_partition2(); + awsEndpointFunctions3 = { + isVirtualHostableS3Bucket: isVirtualHostableS3Bucket3, + parseArn: parseArn3, + partition: partition3 + }; + customEndpointFunctions.aws = awsEndpointFunctions3; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js +var init_resolveDefaultAwsRegionalEndpointsConfig2 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js +var init_resolveEndpoint3 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js +var init_EndpointError3 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js +var init_EndpointRuleObject4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js +var init_ErrorRuleObject4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js +var init_RuleSetObject4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js +var init_TreeRuleObject4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js +var init_shared4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js +var init_types9 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { + "use strict"; + init_EndpointError3(); + init_EndpointRuleObject4(); + init_ErrorRuleObject4(); + init_RuleSetObject4(); + init_TreeRuleObject4(); + init_shared4(); + } +}); + +// ../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/index.js +var init_dist_es47 = __esm({ + "../node_modules/@aws-sdk/nested-clients/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { + "use strict"; + init_aws2(); + init_partition2(); + init_isIpAddress3(); + init_resolveDefaultAwsRegionalEndpointsConfig2(); + init_resolveEndpoint3(); + init_types9(); + } +}); + // ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js var u2, v2, w2, x2, a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2, q2, r2, s2, t8, _data2, ruleSet2; var init_ruleset = __esm({ @@ -34007,7 +34635,7 @@ var cache2, defaultEndpointResolver2; var init_endpointResolver = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() { "use strict"; - init_dist_es30(); + init_dist_es47(); init_dist_es27(); init_ruleset(); cache2 = new EndpointCache({ @@ -34020,294 +34648,7 @@ var init_endpointResolver = __esm({ logger: context3.logger })); }; - customEndpointFunctions.aws = awsEndpointFunctions; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js -var getRuntimeConfig; -var init_runtimeConfig_shared = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() { - "use strict"; - init_dist_es22(); - init_protocols2(); - init_dist_es16(); - init_dist_es20(); - init_dist_es29(); - init_dist_es8(); - init_dist_es7(); - init_httpAuthSchemeProvider(); - init_endpointResolver(); - getRuntimeConfig = (config) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config?.base64Decoder ?? fromBase64, - base64Encoder: config?.base64Encoder ?? toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config?.logger ?? new NoOpLogger(), - protocol: config?.protocol ?? AwsRestJsonProtocol, - protocolSettings: config?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.ssooidc", - version: "2019-06-10", - serviceTarget: "AWSSSOOIDCService" - }, - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? parseUrl, - utf8Decoder: config?.utf8Decoder ?? fromUtf8, - utf8Encoder: config?.utf8Encoder ?? toUtf8 - }; - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js -var getRuntimeConfig2; -var init_runtimeConfig = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() { - "use strict"; - init_package(); - init_dist_es22(); - init_dist_es43(); - init_dist_es32(); - init_dist_es44(); - init_dist_es39(); - init_dist_es35(); - init_dist_es11(); - init_dist_es20(); - init_dist_es45(); - init_dist_es46(); - init_dist_es38(); - init_runtimeConfig_shared(); - getRuntimeConfig2 = (config) => { - emitWarningIfUnsupportedVersion2(process.version); - const defaultsMode = resolveDefaultsModeConfig(config); - const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig(config); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }), - maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? loadConfig({ - ...NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE - }, config), - sha256: config?.sha256 ?? Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// ../node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js -var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration; -var init_extensions4 = __esm({ - "../node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() { - "use strict"; - getAwsRegionExtensionConfiguration = (runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - } - }; - }; - resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; - }; - } -}); - -// ../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/awsRegionConfig.js -var init_awsRegionConfig = __esm({ - "../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/awsRegionConfig.js"() { - "use strict"; - } -}); - -// ../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/stsRegionDefaultResolver.js -function stsRegionDefaultResolver(loaderConfig = {}) { - return loadConfig({ - ...NODE_REGION_CONFIG_OPTIONS, - async default() { - if (!warning2.silence) { - console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); - } - return "us-east-1"; - } - }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); -} -var warning2; -var init_stsRegionDefaultResolver = __esm({ - "../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/stsRegionDefaultResolver.js"() { - "use strict"; - init_dist_es32(); - init_dist_es35(); - warning2 = { - silence: false - }; - } -}); - -// ../node_modules/@aws-sdk/region-config-resolver/dist-es/index.js -var init_dist_es47 = __esm({ - "../node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() { - "use strict"; - init_extensions4(); - init_awsRegionConfig(); - init_stsRegionDefaultResolver(); - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig; -var init_httpAuthExtensionConfiguration = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() { - "use strict"; - getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js -var resolveRuntimeExtensions; -var init_runtimeExtensions = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() { - "use strict"; - init_dist_es47(); - init_dist_es2(); - init_dist_es20(); - init_httpAuthExtensionConfiguration(); - resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js -var SSOOIDCClient; -var init_SSOOIDCClient = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() { - "use strict"; - init_dist_es23(); - init_dist_es24(); - init_dist_es25(); - init_dist_es31(); - init_dist_es32(); - init_dist_es16(); - init_schema2(); - init_dist_es33(); - init_dist_es36(); - init_dist_es39(); - init_dist_es20(); - init_httpAuthSchemeProvider(); - init_EndpointParameters(); - init_runtimeConfig(); - init_runtimeExtensions(); - SSOOIDCClient = class extends Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig2(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters2(_config_0); - const _config_2 = resolveUserAgentConfig(_config_1); - const _config_3 = resolveRetryConfig(_config_2); - const _config_4 = resolveRegionConfig(_config_3); - const _config_5 = resolveHostHeaderConfig(_config_4); - const _config_6 = resolveEndpointConfig(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig2(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(getUserAgentPlugin(this.config)); - this.middlewareStack.use(getRetryPlugin(this.config)); - this.middlewareStack.use(getContentLengthPlugin(this.config)); - this.middlewareStack.use(getHostHeaderPlugin(this.config)); - this.middlewareStack.use(getLoggerPlugin(this.config)); - this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; + customEndpointFunctions.aws = awsEndpointFunctions3; } }); @@ -34516,7 +34857,7 @@ var init_errors = __esm({ }); // ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js -var _ADE, _APE, _AT2, _CS2, _CT2, _CTR, _CTRr, _CV, _ETE, _ICE, _IGE, _IRE, _ISE, _ISEn, _IT2, _RT2, _SDE, _UCE, _UGTE, _aT, _c2, _cI, _cS, _cV, _co, _dC, _e2, _eI, _ed, _gT, _h2, _hE2, _iT2, _r, _rT, _rU, _s2, _se, _sm2, _tT, n02, AccessToken, ClientSecret, CodeVerifier, IdToken, RefreshToken, AccessDeniedException$, AuthorizationPendingException$, CreateTokenRequest$, CreateTokenResponse$, ExpiredTokenException$, InternalServerException$, InvalidClientException$, InvalidGrantException$, InvalidRequestException$, InvalidScopeException$, SlowDownException$, UnauthorizedClientException$, UnsupportedGrantTypeException$, SSOOIDCServiceException$, Scopes, CreateToken$; +var _ADE, _APE, _AT2, _CS2, _CT2, _CTR, _CTRr, _CV, _ETE, _ICE, _IGE, _IRE, _ISE, _ISEn, _IT2, _RT2, _SDE, _UCE, _UGTE, _aT, _c2, _cI, _cS, _cV, _co, _dC, _e2, _eI, _ed, _gT, _h2, _hE2, _iT2, _r, _rT, _rU, _s2, _sc, _se, _tT, n02, _s_registry2, SSOOIDCServiceException$, n0_registry2, AccessDeniedException$, AuthorizationPendingException$, ExpiredTokenException$, InternalServerException$, InvalidClientException$, InvalidGrantException$, InvalidRequestException$, InvalidScopeException$, SlowDownException$, UnauthorizedClientException$, UnsupportedGrantTypeException$, errorTypeRegistries2, AccessToken, ClientSecret, CodeVerifier, IdToken, RefreshToken, CreateTokenRequest$, CreateTokenResponse$, Scopes, CreateToken$; var init_schemas_0 = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js"() { "use strict"; @@ -34559,16 +34900,15 @@ var init_schemas_0 = __esm({ _r = "reason"; _rT = "refreshToken"; _rU = "redirectUri"; - _s2 = "scope"; + _s2 = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; + _sc = "scope"; _se = "server"; - _sm2 = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; _tT = "tokenType"; n02 = "com.amazonaws.ssooidc"; - AccessToken = [0, n02, _AT2, 8, 0]; - ClientSecret = [0, n02, _CS2, 8, 0]; - CodeVerifier = [0, n02, _CV, 8, 0]; - IdToken = [0, n02, _IT2, 8, 0]; - RefreshToken = [0, n02, _RT2, 8, 0]; + _s_registry2 = TypeRegistry.for(_s2); + SSOOIDCServiceException$ = [-3, _s2, "SSOOIDCServiceException", 0, [], []]; + _s_registry2.registerError(SSOOIDCServiceException$, SSOOIDCServiceException); + n0_registry2 = TypeRegistry.for(n02); AccessDeniedException$ = [ -3, n02, @@ -34577,7 +34917,7 @@ var init_schemas_0 = __esm({ [_e2, _r, _ed], [0, 0, 0] ]; - TypeRegistry.for(n02).registerError(AccessDeniedException$, AccessDeniedException); + n0_registry2.registerError(AccessDeniedException$, AccessDeniedException); AuthorizationPendingException$ = [ -3, n02, @@ -34586,32 +34926,15 @@ var init_schemas_0 = __esm({ [_e2, _ed], [0, 0] ]; - TypeRegistry.for(n02).registerError(AuthorizationPendingException$, AuthorizationPendingException); - CreateTokenRequest$ = [ - 3, - n02, - _CTR, - 0, - [_cI, _cS, _gT, _dC, _co, _rT, _s2, _rU, _cV], - [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], - 3 - ]; - CreateTokenResponse$ = [ - 3, - n02, - _CTRr, - 0, - [_aT, _tT, _eI, _rT, _iT2], - [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] - ]; + n0_registry2.registerError(AuthorizationPendingException$, AuthorizationPendingException); ExpiredTokenException$ = [-3, n02, _ETE, { [_e2]: _c2, [_hE2]: 400 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(ExpiredTokenException$, ExpiredTokenException); + n0_registry2.registerError(ExpiredTokenException$, ExpiredTokenException); InternalServerException$ = [-3, n02, _ISE, { [_e2]: _se, [_hE2]: 500 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(InternalServerException$, InternalServerException); + n0_registry2.registerError(InternalServerException$, InternalServerException); InvalidClientException$ = [-3, n02, _ICE, { [_e2]: _c2, [_hE2]: 401 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(InvalidClientException$, InvalidClientException); + n0_registry2.registerError(InvalidClientException$, InvalidClientException); InvalidGrantException$ = [-3, n02, _IGE, { [_e2]: _c2, [_hE2]: 400 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(InvalidGrantException$, InvalidGrantException); + n0_registry2.registerError(InvalidGrantException$, InvalidGrantException); InvalidRequestException$ = [ -3, n02, @@ -34620,11 +34943,11 @@ var init_schemas_0 = __esm({ [_e2, _r, _ed], [0, 0, 0] ]; - TypeRegistry.for(n02).registerError(InvalidRequestException$, InvalidRequestException); + n0_registry2.registerError(InvalidRequestException$, InvalidRequestException); InvalidScopeException$ = [-3, n02, _ISEn, { [_e2]: _c2, [_hE2]: 400 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(InvalidScopeException$, InvalidScopeException); + n0_registry2.registerError(InvalidScopeException$, InvalidScopeException); SlowDownException$ = [-3, n02, _SDE, { [_e2]: _c2, [_hE2]: 400 }, [_e2, _ed], [0, 0]]; - TypeRegistry.for(n02).registerError(SlowDownException$, SlowDownException); + n0_registry2.registerError(SlowDownException$, SlowDownException); UnauthorizedClientException$ = [ -3, n02, @@ -34633,7 +34956,7 @@ var init_schemas_0 = __esm({ [_e2, _ed], [0, 0] ]; - TypeRegistry.for(n02).registerError(UnauthorizedClientException$, UnauthorizedClientException); + n0_registry2.registerError(UnauthorizedClientException$, UnauthorizedClientException); UnsupportedGrantTypeException$ = [ -3, n02, @@ -34642,9 +34965,30 @@ var init_schemas_0 = __esm({ [_e2, _ed], [0, 0] ]; - TypeRegistry.for(n02).registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); - SSOOIDCServiceException$ = [-3, _sm2, "SSOOIDCServiceException", 0, [], []]; - TypeRegistry.for(_sm2).registerError(SSOOIDCServiceException$, SSOOIDCServiceException); + n0_registry2.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); + errorTypeRegistries2 = [_s_registry2, n0_registry2]; + AccessToken = [0, n02, _AT2, 8, 0]; + ClientSecret = [0, n02, _CS2, 8, 0]; + CodeVerifier = [0, n02, _CV, 8, 0]; + IdToken = [0, n02, _IT2, 8, 0]; + RefreshToken = [0, n02, _RT2, 8, 0]; + CreateTokenRequest$ = [ + 3, + n02, + _CTR, + 0, + [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV], + [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], + 3 + ]; + CreateTokenResponse$ = [ + 3, + n02, + _CTRr, + 0, + [_aT, _tT, _eI, _rT, _iT2], + [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] + ]; Scopes = 64 | 0; CreateToken$ = [ 9, @@ -34657,6 +35001,295 @@ var init_schemas_0 = __esm({ } }); +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js +var getRuntimeConfig; +var init_runtimeConfig_shared = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() { + "use strict"; + init_dist_es22(); + init_protocols2(); + init_dist_es16(); + init_dist_es20(); + init_dist_es29(); + init_dist_es8(); + init_dist_es7(); + init_httpAuthSchemeProvider(); + init_endpointResolver(); + init_schemas_0(); + getRuntimeConfig = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver2, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.ssooidc", + errorTypeRegistries: errorTypeRegistries2, + version: "2019-06-10", + serviceTarget: "AWSSSOOIDCService" + }, + serviceId: config?.serviceId ?? "SSO OIDC", + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8 + }; + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js +var getRuntimeConfig2; +var init_runtimeConfig = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() { + "use strict"; + init_package(); + init_dist_es22(); + init_dist_es43(); + init_dist_es32(); + init_dist_es44(); + init_dist_es39(); + init_dist_es35(); + init_dist_es11(); + init_dist_es20(); + init_dist_es45(); + init_dist_es46(); + init_dist_es38(); + init_runtimeConfig_shared(); + getRuntimeConfig2 = (config) => { + emitWarningIfUnsupportedVersion2(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig(config); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE + }, config), + sha256: config?.sha256 ?? Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// ../node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js +var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration; +var init_extensions4 = __esm({ + "../node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() { + "use strict"; + getAwsRegionExtensionConfiguration = (runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + } + }; + }; + resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; + }; + } +}); + +// ../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/awsRegionConfig.js +var init_awsRegionConfig = __esm({ + "../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/awsRegionConfig.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/stsRegionDefaultResolver.js +function stsRegionDefaultResolver(loaderConfig = {}) { + return loadConfig({ + ...NODE_REGION_CONFIG_OPTIONS, + async default() { + if (!warning2.silence) { + console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); + } + return "us-east-1"; + } + }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); +} +var warning2; +var init_stsRegionDefaultResolver = __esm({ + "../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/stsRegionDefaultResolver.js"() { + "use strict"; + init_dist_es32(); + init_dist_es35(); + warning2 = { + silence: false + }; + } +}); + +// ../node_modules/@aws-sdk/region-config-resolver/dist-es/index.js +var init_dist_es48 = __esm({ + "../node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() { + "use strict"; + init_extensions4(); + init_awsRegionConfig(); + init_stsRegionDefaultResolver(); + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig; +var init_httpAuthExtensionConfiguration = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() { + "use strict"; + getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js +var resolveRuntimeExtensions; +var init_runtimeExtensions = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() { + "use strict"; + init_dist_es48(); + init_dist_es2(); + init_dist_es20(); + init_httpAuthExtensionConfiguration(); + resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js +var SSOOIDCClient; +var init_SSOOIDCClient = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() { + "use strict"; + init_dist_es23(); + init_dist_es24(); + init_dist_es25(); + init_dist_es31(); + init_dist_es32(); + init_dist_es16(); + init_schema2(); + init_dist_es33(); + init_dist_es36(); + init_dist_es39(); + init_dist_es20(); + init_httpAuthSchemeProvider(); + init_EndpointParameters(); + init_runtimeConfig(); + init_runtimeExtensions(); + SSOOIDCClient = class extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig2(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters2(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig2(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + // ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js var CreateTokenCommand; var init_CreateTokenCommand = __esm({ @@ -34666,7 +35299,7 @@ var init_CreateTokenCommand = __esm({ init_dist_es20(); init_EndpointParameters(); init_schemas_0(); - CreateTokenCommand = class extends Command2.classBuilder().ep(commonParams2).m(function(Command3, cs2, config, o6) { + CreateTokenCommand = class extends Command2.classBuilder().ep(commonParams2).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").sc(CreateToken$).build() { }; @@ -34758,7 +35391,8 @@ __export(sso_oidc_exports, { UnauthorizedClientException$: () => UnauthorizedClientException$, UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, UnsupportedGrantTypeException$: () => UnsupportedGrantTypeException$, - __Client: () => Client + __Client: () => Client, + errorTypeRegistries: () => errorTypeRegistries2 }); var init_sso_oidc = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() { @@ -34957,7 +35591,7 @@ var init_nodeProvider = __esm({ }); // ../node_modules/@aws-sdk/token-providers/dist-es/index.js -var init_dist_es48 = __esm({ +var init_dist_es49 = __esm({ "../node_modules/@aws-sdk/token-providers/dist-es/index.js"() { "use strict"; init_fromEnvSigningName(); @@ -35072,7 +35706,7 @@ var init_package2 = __esm({ package_default3 = { name: "@aws-sdk/client-sso", description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native", - version: "3.974.0", + version: "3.990.0", scripts: { build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", "build:cjs": "node ../../scripts/compilation/inline client-sso", @@ -35092,37 +35726,37 @@ var init_package2 = __esm({ dependencies: { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.0", - "@aws-sdk/middleware-host-header": "^3.972.1", - "@aws-sdk/middleware-logger": "^3.972.1", - "@aws-sdk/middleware-recursion-detection": "^3.972.1", - "@aws-sdk/middleware-user-agent": "^3.972.1", - "@aws-sdk/region-config-resolver": "^3.972.1", - "@aws-sdk/types": "^3.973.0", - "@aws-sdk/util-endpoints": "3.972.0", - "@aws-sdk/util-user-agent-browser": "^3.972.1", - "@aws-sdk/util-user-agent-node": "^3.972.1", + "@aws-sdk/core": "^3.973.10", + "@aws-sdk/middleware-host-header": "^3.972.3", + "@aws-sdk/middleware-logger": "^3.972.3", + "@aws-sdk/middleware-recursion-detection": "^3.972.3", + "@aws-sdk/middleware-user-agent": "^3.972.10", + "@aws-sdk/region-config-resolver": "^3.972.3", + "@aws-sdk/types": "^3.973.1", + "@aws-sdk/util-endpoints": "3.990.0", + "@aws-sdk/util-user-agent-browser": "^3.972.3", + "@aws-sdk/util-user-agent-node": "^3.972.8", "@smithy/config-resolver": "^4.4.6", - "@smithy/core": "^3.21.0", + "@smithy/core": "^3.23.0", "@smithy/fetch-http-handler": "^5.3.9", "@smithy/hash-node": "^4.2.8", "@smithy/invalid-dependency": "^4.2.8", "@smithy/middleware-content-length": "^4.2.8", - "@smithy/middleware-endpoint": "^4.4.10", - "@smithy/middleware-retry": "^4.4.26", + "@smithy/middleware-endpoint": "^4.4.14", + "@smithy/middleware-retry": "^4.4.31", "@smithy/middleware-serde": "^4.2.9", "@smithy/middleware-stack": "^4.2.8", "@smithy/node-config-provider": "^4.3.8", - "@smithy/node-http-handler": "^4.4.8", + "@smithy/node-http-handler": "^4.4.10", "@smithy/protocol-http": "^5.3.8", - "@smithy/smithy-client": "^4.10.11", + "@smithy/smithy-client": "^4.11.3", "@smithy/types": "^4.12.0", "@smithy/url-parser": "^4.2.8", "@smithy/util-base64": "^4.3.0", "@smithy/util-body-length-browser": "^4.2.0", "@smithy/util-body-length-node": "^4.2.1", - "@smithy/util-defaults-mode-browser": "^4.3.25", - "@smithy/util-defaults-mode-node": "^4.2.28", + "@smithy/util-defaults-mode-browser": "^4.3.30", + "@smithy/util-defaults-mode-node": "^4.2.33", "@smithy/util-endpoints": "^3.2.8", "@smithy/util-middleware": "^4.2.8", "@smithy/util-retry": "^4.2.8", @@ -35171,6 +35805,486 @@ var init_package2 = __esm({ } }); +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js +var init_isIpAddress4 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { + "use strict"; + init_dist_es27(); + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js +var isVirtualHostableS3Bucket4; +var init_isVirtualHostableS3Bucket3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { + "use strict"; + init_dist_es27(); + init_isIpAddress4(); + isVirtualHostableS3Bucket4 = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket4(label)) { + return false; + } + } + return true; + } + if (!isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (isIpAddress(value)) { + return false; + } + return true; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js +var ARN_DELIMITER4, RESOURCE_DELIMITER4, parseArn4; +var init_parseArn3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { + "use strict"; + ARN_DELIMITER4 = ":"; + RESOURCE_DELIMITER4 = "/"; + parseArn4 = (value) => { + const segments = value.split(ARN_DELIMITER4); + if (segments.length < 6) + return null; + const [arn, partition5, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition5 === "" || service === "" || resourcePath.join(ARN_DELIMITER4) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER4)).flat(); + return { + partition: partition5, + service, + region, + accountId, + resourceId + }; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json +var partitions_default4; +var init_partitions3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { + partitions_default4 = { + partitions: [{ + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "AWS European Sovereign Cloud (Germany)" + } + } + }, { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + description: "US ISOB West" + } + } + }, { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + }], + version: "1.1" + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js +var selectedPartitionsInfo4, partition4; +var init_partition3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { + "use strict"; + init_partitions3(); + selectedPartitionsInfo4 = partitions_default4; + partition4 = (value) => { + const { partitions } = selectedPartitionsInfo4; + for (const partition5 of partitions) { + const { regions, outputs } = partition5; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } + } + } + for (const partition5 of partitions) { + const { regionRegex, outputs } = partition5; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition5) => partition5.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs + }; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js +var awsEndpointFunctions4; +var init_aws3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { + "use strict"; + init_dist_es27(); + init_isVirtualHostableS3Bucket3(); + init_parseArn3(); + init_partition3(); + awsEndpointFunctions4 = { + isVirtualHostableS3Bucket: isVirtualHostableS3Bucket4, + parseArn: parseArn4, + partition: partition4 + }; + customEndpointFunctions.aws = awsEndpointFunctions4; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js +var init_resolveDefaultAwsRegionalEndpointsConfig3 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js +var init_resolveEndpoint4 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js +var init_EndpointError4 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js +var init_EndpointRuleObject5 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js +var init_ErrorRuleObject5 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js +var init_RuleSetObject5 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js +var init_TreeRuleObject5 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js +var init_shared5 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { + "use strict"; + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js +var init_types10 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { + "use strict"; + init_EndpointError4(); + init_EndpointRuleObject5(); + init_ErrorRuleObject5(); + init_RuleSetObject5(); + init_TreeRuleObject5(); + init_shared5(); + } +}); + +// ../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/index.js +var init_dist_es50 = __esm({ + "../node_modules/@aws-sdk/client-sso/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { + "use strict"; + init_aws3(); + init_partition3(); + init_isIpAddress4(); + init_resolveDefaultAwsRegionalEndpointsConfig3(); + init_resolveEndpoint4(); + init_types10(); + } +}); + // ../node_modules/@aws-sdk/client-sso/dist-es/endpoint/ruleset.js var u3, v3, w3, x3, a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3, q3, r3, s3, t9, _data3, ruleSet3; var init_ruleset2 = __esm({ @@ -35210,7 +36324,7 @@ var cache3, defaultEndpointResolver3; var init_endpointResolver2 = __esm({ "../node_modules/@aws-sdk/client-sso/dist-es/endpoint/endpointResolver.js"() { "use strict"; - init_dist_es30(); + init_dist_es50(); init_dist_es27(); init_ruleset2(); cache3 = new EndpointCache({ @@ -35223,230 +36337,7 @@ var init_endpointResolver2 = __esm({ logger: context3.logger })); }; - customEndpointFunctions.aws = awsEndpointFunctions; - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js -var getRuntimeConfig3; -var init_runtimeConfig_shared2 = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js"() { - "use strict"; - init_dist_es22(); - init_protocols2(); - init_dist_es16(); - init_dist_es20(); - init_dist_es29(); - init_dist_es8(); - init_dist_es7(); - init_httpAuthSchemeProvider2(); - init_endpointResolver2(); - getRuntimeConfig3 = (config) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config?.base64Decoder ?? fromBase64, - base64Encoder: config?.base64Encoder ?? toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? defaultEndpointResolver3, - extensions: config?.extensions ?? [], - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config?.logger ?? new NoOpLogger(), - protocol: config?.protocol ?? AwsRestJsonProtocol, - protocolSettings: config?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.sso", - version: "2019-06-10", - serviceTarget: "SWBPortalService" - }, - serviceId: config?.serviceId ?? "SSO", - urlParser: config?.urlParser ?? parseUrl, - utf8Decoder: config?.utf8Decoder ?? fromUtf8, - utf8Encoder: config?.utf8Encoder ?? toUtf8 - }; - }; - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js -var getRuntimeConfig4; -var init_runtimeConfig2 = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js"() { - "use strict"; - init_package2(); - init_dist_es22(); - init_dist_es43(); - init_dist_es32(); - init_dist_es44(); - init_dist_es39(); - init_dist_es35(); - init_dist_es11(); - init_dist_es20(); - init_dist_es45(); - init_dist_es46(); - init_dist_es38(); - init_runtimeConfig_shared2(); - getRuntimeConfig4 = (config) => { - emitWarningIfUnsupportedVersion2(process.version); - const defaultsMode = resolveDefaultsModeConfig(config); - const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig3(config); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }), - maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - retryMode: config?.retryMode ?? loadConfig({ - ...NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE - }, config), - sha256: config?.sha256 ?? Hash.bind(null, "sha256"), - streamCollector: config?.streamCollector ?? streamCollector, - useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2; -var init_httpAuthExtensionConfiguration2 = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js"() { - "use strict"; - getHttpAuthExtensionConfiguration2 = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig2 = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; - }; - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js -var resolveRuntimeExtensions2; -var init_runtimeExtensions2 = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js"() { - "use strict"; - init_dist_es47(); - init_dist_es2(); - init_dist_es20(); - init_httpAuthExtensionConfiguration2(); - resolveRuntimeExtensions2 = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration)); - }; - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js -var SSOClient; -var init_SSOClient = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js"() { - "use strict"; - init_dist_es23(); - init_dist_es24(); - init_dist_es25(); - init_dist_es31(); - init_dist_es32(); - init_dist_es16(); - init_schema2(); - init_dist_es33(); - init_dist_es36(); - init_dist_es39(); - init_dist_es20(); - init_httpAuthSchemeProvider2(); - init_EndpointParameters2(); - init_runtimeConfig2(); - init_runtimeExtensions2(); - SSOClient = class extends Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig4(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters3(_config_0); - const _config_2 = resolveUserAgentConfig(_config_1); - const _config_3 = resolveRetryConfig(_config_2); - const _config_4 = resolveRegionConfig(_config_3); - const _config_5 = resolveHostHeaderConfig(_config_4); - const _config_6 = resolveEndpointConfig(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig3(_config_6); - const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(getUserAgentPlugin(this.config)); - this.middlewareStack.use(getRetryPlugin(this.config)); - this.middlewareStack.use(getContentLengthPlugin(this.config)); - this.middlewareStack.use(getHostHeaderPlugin(this.config)); - this.middlewareStack.use(getLoggerPlugin(this.config)); - this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; + customEndpointFunctions.aws = awsEndpointFunctions4; } }); @@ -35523,7 +36414,7 @@ var init_errors2 = __esm({ }); // ../node_modules/@aws-sdk/client-sso/dist-es/schemas/schemas_0.js -var _AI2, _ALT, _ATT, _GRC, _GRCR, _GRCRe, _IRE2, _L2, _LA, _LAR, _LARR, _LARRi, _LARi, _LARis, _LR2, _RC2, _RI, _RLT, _RNFE, _SAKT, _STT, _TMRE, _UE, _aI, _aKI, _aL, _aN, _aT2, _ai, _c3, _e3, _eA, _ex, _h3, _hE3, _hH2, _hQ2, _m2, _mR, _mr, _nT, _nt, _rC, _rL, _rN, _rn, _s3, _sAK, _sT, _xasbt, n03, AccessTokenType, SecretAccessKeyType, SessionTokenType, AccountInfo$, GetRoleCredentialsRequest$, GetRoleCredentialsResponse$, InvalidRequestException$2, ListAccountRolesRequest$, ListAccountRolesResponse$, ListAccountsRequest$, ListAccountsResponse$, LogoutRequest$, ResourceNotFoundException$, RoleCredentials$, RoleInfo$, TooManyRequestsException$, UnauthorizedException$, __Unit2, SSOServiceException$, AccountListType, RoleListType, GetRoleCredentials$, ListAccountRoles$, ListAccounts$, Logout$; +var _AI2, _ALT, _ATT, _GRC, _GRCR, _GRCRe, _IRE2, _L2, _LA, _LAR, _LARR, _LARRi, _LARi, _LARis, _LR2, _RC2, _RI, _RLT, _RNFE, _SAKT, _STT, _TMRE, _UE, _aI, _aKI, _aL, _aN, _aT2, _ai, _c3, _e3, _eA, _ex, _h3, _hE3, _hH2, _hQ2, _m2, _mR, _mr, _nT, _nt, _rC, _rL, _rN, _rn, _s3, _sAK, _sT, _xasbt, n03, _s_registry3, SSOServiceException$, n0_registry3, InvalidRequestException$2, ResourceNotFoundException$, TooManyRequestsException$, UnauthorizedException$, errorTypeRegistries3, AccessTokenType, SecretAccessKeyType, SessionTokenType, AccountInfo$, GetRoleCredentialsRequest$, GetRoleCredentialsResponse$, ListAccountRolesRequest$, ListAccountRolesResponse$, ListAccountsRequest$, ListAccountsResponse$, LogoutRequest$, RoleCredentials$, RoleInfo$, __Unit2, AccountListType, RoleListType, GetRoleCredentials$, ListAccountRoles$, ListAccounts$, Logout$; var init_schemas_02 = __esm({ "../node_modules/@aws-sdk/client-sso/dist-es/schemas/schemas_0.js"() { "use strict"; @@ -35581,6 +36472,50 @@ var init_schemas_02 = __esm({ _sT = "sessionToken"; _xasbt = "x-amz-sso_bearer_token"; n03 = "com.amazonaws.sso"; + _s_registry3 = TypeRegistry.for(_s3); + SSOServiceException$ = [-3, _s3, "SSOServiceException", 0, [], []]; + _s_registry3.registerError(SSOServiceException$, SSOServiceException); + n0_registry3 = TypeRegistry.for(n03); + InvalidRequestException$2 = [ + -3, + n03, + _IRE2, + { [_e3]: _c3, [_hE3]: 400 }, + [_m2], + [0] + ]; + n0_registry3.registerError(InvalidRequestException$2, InvalidRequestException2); + ResourceNotFoundException$ = [ + -3, + n03, + _RNFE, + { [_e3]: _c3, [_hE3]: 404 }, + [_m2], + [0] + ]; + n0_registry3.registerError(ResourceNotFoundException$, ResourceNotFoundException); + TooManyRequestsException$ = [ + -3, + n03, + _TMRE, + { [_e3]: _c3, [_hE3]: 429 }, + [_m2], + [0] + ]; + n0_registry3.registerError(TooManyRequestsException$, TooManyRequestsException); + UnauthorizedException$ = [ + -3, + n03, + _UE, + { [_e3]: _c3, [_hE3]: 401 }, + [_m2], + [0] + ]; + n0_registry3.registerError(UnauthorizedException$, UnauthorizedException); + errorTypeRegistries3 = [ + _s_registry3, + n0_registry3 + ]; AccessTokenType = [0, n03, _ATT, 8, 0]; SecretAccessKeyType = [0, n03, _SAKT, 8, 0]; SessionTokenType = [0, n03, _STT, 8, 0]; @@ -35609,15 +36544,6 @@ var init_schemas_02 = __esm({ [_rC], [[() => RoleCredentials$, 0]] ]; - InvalidRequestException$2 = [ - -3, - n03, - _IRE2, - { [_e3]: _c3, [_hE3]: 400 }, - [_m2], - [0] - ]; - TypeRegistry.for(n03).registerError(InvalidRequestException$2, InvalidRequestException2); ListAccountRolesRequest$ = [ 3, n03, @@ -35661,15 +36587,6 @@ var init_schemas_02 = __esm({ [[() => AccessTokenType, { [_hH2]: _xasbt }]], 1 ]; - ResourceNotFoundException$ = [ - -3, - n03, - _RNFE, - { [_e3]: _c3, [_hE3]: 404 }, - [_m2], - [0] - ]; - TypeRegistry.for(n03).registerError(ResourceNotFoundException$, ResourceNotFoundException); RoleCredentials$ = [ 3, n03, @@ -35686,27 +36603,7 @@ var init_schemas_02 = __esm({ [_rN, _aI], [0, 0] ]; - TooManyRequestsException$ = [ - -3, - n03, - _TMRE, - { [_e3]: _c3, [_hE3]: 429 }, - [_m2], - [0] - ]; - TypeRegistry.for(n03).registerError(TooManyRequestsException$, TooManyRequestsException); - UnauthorizedException$ = [ - -3, - n03, - _UE, - { [_e3]: _c3, [_hE3]: 401 }, - [_m2], - [0] - ]; - TypeRegistry.for(n03).registerError(UnauthorizedException$, UnauthorizedException); __Unit2 = "unit"; - SSOServiceException$ = [-3, _s3, "SSOServiceException", 0, [], []]; - TypeRegistry.for(_s3).registerError(SSOServiceException$, SSOServiceException); AccountListType = [ 1, n03, @@ -35756,6 +36653,231 @@ var init_schemas_02 = __esm({ } }); +// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js +var getRuntimeConfig3; +var init_runtimeConfig_shared2 = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.shared.js"() { + "use strict"; + init_dist_es22(); + init_protocols2(); + init_dist_es16(); + init_dist_es20(); + init_dist_es29(); + init_dist_es8(); + init_dist_es7(); + init_httpAuthSchemeProvider2(); + init_endpointResolver2(); + init_schemas_02(); + getRuntimeConfig3 = (config) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver3, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config?.logger ?? new NoOpLogger(), + protocol: config?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.sso", + errorTypeRegistries: errorTypeRegistries3, + version: "2019-06-10", + serviceTarget: "SWBPortalService" + }, + serviceId: config?.serviceId ?? "SSO", + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8 + }; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js +var getRuntimeConfig4; +var init_runtimeConfig2 = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/runtimeConfig.js"() { + "use strict"; + init_package2(); + init_dist_es22(); + init_dist_es43(); + init_dist_es32(); + init_dist_es44(); + init_dist_es39(); + init_dist_es35(); + init_dist_es11(); + init_dist_es20(); + init_dist_es45(); + init_dist_es46(); + init_dist_es38(); + init_runtimeConfig_shared2(); + getRuntimeConfig4 = (config) => { + emitWarningIfUnsupportedVersion2(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig3(config); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? loadConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default3.version }), + maxAttempts: config?.maxAttempts ?? loadConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? loadConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE + }, config), + sha256: config?.sha256 ?? Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? loadConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? loadConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2; +var init_httpAuthExtensionConfiguration2 = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/auth/httpAuthExtensionConfiguration.js"() { + "use strict"; + getHttpAuthExtensionConfiguration2 = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig2 = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js +var resolveRuntimeExtensions2; +var init_runtimeExtensions2 = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/runtimeExtensions.js"() { + "use strict"; + init_dist_es48(); + init_dist_es2(); + init_dist_es20(); + init_httpAuthExtensionConfiguration2(); + resolveRuntimeExtensions2 = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration)); + }; + } +}); + +// ../node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js +var SSOClient; +var init_SSOClient = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/SSOClient.js"() { + "use strict"; + init_dist_es23(); + init_dist_es24(); + init_dist_es25(); + init_dist_es31(); + init_dist_es32(); + init_dist_es16(); + init_schema2(); + init_dist_es33(); + init_dist_es36(); + init_dist_es39(); + init_dist_es20(); + init_httpAuthSchemeProvider2(); + init_EndpointParameters2(); + init_runtimeConfig2(); + init_runtimeExtensions2(); + SSOClient = class extends Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig4(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters3(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig3(_config_6); + const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + // ../node_modules/@aws-sdk/client-sso/dist-es/commands/GetRoleCredentialsCommand.js var GetRoleCredentialsCommand; var init_GetRoleCredentialsCommand = __esm({ @@ -35765,7 +36887,7 @@ var init_GetRoleCredentialsCommand = __esm({ init_dist_es20(); init_EndpointParameters2(); init_schemas_02(); - GetRoleCredentialsCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs2, config, o6) { + GetRoleCredentialsCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").sc(GetRoleCredentials$).build() { }; @@ -35781,7 +36903,7 @@ var init_ListAccountRolesCommand = __esm({ init_dist_es20(); init_EndpointParameters2(); init_schemas_02(); - ListAccountRolesCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs2, config, o6) { + ListAccountRolesCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").sc(ListAccountRoles$).build() { }; @@ -35797,7 +36919,7 @@ var init_ListAccountsCommand = __esm({ init_dist_es20(); init_EndpointParameters2(); init_schemas_02(); - ListAccountsCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs2, config, o6) { + ListAccountsCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").sc(ListAccounts$).build() { }; @@ -35813,15 +36935,39 @@ var init_LogoutCommand = __esm({ init_dist_es20(); init_EndpointParameters2(); init_schemas_02(); - LogoutCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs2, config, o6) { + LogoutCommand = class extends Command2.classBuilder().ep(commonParams3).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").sc(Logout$).build() { }; } }); +// ../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js +var paginateListAccountRoles; +var init_ListAccountRolesPaginator = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js"() { + "use strict"; + init_dist_es16(); + init_ListAccountRolesCommand(); + init_SSOClient(); + paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); + } +}); + +// ../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js +var paginateListAccounts; +var init_ListAccountsPaginator = __esm({ + "../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js"() { + "use strict"; + init_dist_es16(); + init_ListAccountsCommand(); + init_SSOClient(); + paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); + } +}); + // ../node_modules/@aws-sdk/client-sso/dist-es/SSO.js -var commands2, SSO; +var commands2, paginators, SSO; var init_SSO = __esm({ "../node_modules/@aws-sdk/client-sso/dist-es/SSO.js"() { "use strict"; @@ -35830,6 +36976,8 @@ var init_SSO = __esm({ init_ListAccountRolesCommand(); init_ListAccountsCommand(); init_LogoutCommand(); + init_ListAccountRolesPaginator(); + init_ListAccountsPaginator(); init_SSOClient(); commands2 = { GetRoleCredentialsCommand, @@ -35837,9 +36985,13 @@ var init_SSO = __esm({ ListAccountsCommand, LogoutCommand }; + paginators = { + paginateListAccountRoles, + paginateListAccounts + }; SSO = class extends SSOClient { }; - createAggregatedClient(commands2, SSO); + createAggregatedClient(commands2, SSO, { paginators }); } }); @@ -35861,30 +37013,6 @@ var init_Interfaces = __esm({ } }); -// ../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js -var paginateListAccountRoles; -var init_ListAccountRolesPaginator = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountRolesPaginator.js"() { - "use strict"; - init_dist_es16(); - init_ListAccountRolesCommand(); - init_SSOClient(); - paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - } -}); - -// ../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js -var paginateListAccounts; -var init_ListAccountsPaginator = __esm({ - "../node_modules/@aws-sdk/client-sso/dist-es/pagination/ListAccountsPaginator.js"() { - "use strict"; - init_dist_es16(); - init_ListAccountsCommand(); - init_SSOClient(); - paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); - } -}); - // ../node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js var init_pagination2 = __esm({ "../node_modules/@aws-sdk/client-sso/dist-es/pagination/index.js"() { @@ -35903,7 +37031,7 @@ var init_models_02 = __esm({ }); // ../node_modules/@aws-sdk/client-sso/dist-es/index.js -var init_dist_es49 = __esm({ +var init_dist_es51 = __esm({ "../node_modules/@aws-sdk/client-sso/dist-es/index.js"() { "use strict"; init_SSOClient(); @@ -35925,7 +37053,7 @@ __export(loadSso_exports, { var init_loadSso = __esm({ "../node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js"() { "use strict"; - init_dist_es49(); + init_dist_es51(); } }); @@ -35935,7 +37063,7 @@ var init_resolveSSOCredentials = __esm({ "../node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js"() { "use strict"; init_client2(); - init_dist_es48(); + init_dist_es49(); init_dist_es17(); init_dist_es34(); SHOULD_FAIL_CREDENTIAL_CHAIN = false; @@ -36127,7 +37255,7 @@ var init_fromSSO = __esm({ }); // ../node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js -var init_types9 = __esm({ +var init_types11 = __esm({ "../node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js"() { "use strict"; } @@ -36140,12 +37268,12 @@ __export(dist_es_exports4, { isSsoProfile: () => isSsoProfile, validateSsoProfile: () => validateSsoProfile }); -var init_dist_es50 = __esm({ +var init_dist_es52 = __esm({ "../node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js"() { "use strict"; init_fromSSO(); init_isSsoProfile(); - init_types9(); + init_types11(); init_validateSsoProfile(); } }); @@ -36322,7 +37450,7 @@ var cache4, defaultEndpointResolver4; var init_endpointResolver3 = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() { "use strict"; - init_dist_es30(); + init_dist_es47(); init_dist_es27(); init_ruleset3(); cache4 = new EndpointCache({ @@ -36335,7 +37463,315 @@ var init_endpointResolver3 = __esm({ logger: context3.logger })); }; - customEndpointFunctions.aws = awsEndpointFunctions; + customEndpointFunctions.aws = awsEndpointFunctions3; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js +var STSServiceException; +var init_STSServiceException = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() { + "use strict"; + init_dist_es20(); + STSServiceException = class _STSServiceException extends ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); + } + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js +var ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException; +var init_errors3 = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js"() { + "use strict"; + init_STSServiceException(); + ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + } + }; + MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); + } + }; + PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); + } + }; + RegionDisabledException = class _RegionDisabledException extends STSServiceException { + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _RegionDisabledException.prototype); + } + }; + IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); + } + }; + InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + } + }; + IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { + name = "IDPCommunicationErrorException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); + } + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js +var _A2, _AKI2, _AR2, _ARI2, _ARR, _ARRs, _ARU, _ARWWI, _ARWWIR, _ARWWIRs, _Au, _C2, _CA2, _DS, _E2, _EI, _ETE2, _IDPCEE, _IDPRCE, _IITE, _K2, _MPDE, _P2, _PA, _PAr, _PC2, _PCLT, _PCr, _PDT, _PI2, _PPS, _PPTLE, _Pr2, _RA, _RDE, _RSN, _SAK2, _SFWIT, _SI, _SN, _ST2, _T2, _TC2, _TTK, _Ta2, _V2, _WIT, _a, _aKST, _aQE, _c4, _cTT, _e4, _hE4, _m3, _pDLT, _s4, _tLT, n04, _s_registry4, STSServiceException$, n0_registry4, ExpiredTokenException$2, IDPCommunicationErrorException$, IDPRejectedClaimException$, InvalidIdentityTokenException$, MalformedPolicyDocumentException$, PackedPolicyTooLargeException$, RegionDisabledException$, errorTypeRegistries4, accessKeySecretType, clientTokenType, AssumedRoleUser$, AssumeRoleRequest$, AssumeRoleResponse$, AssumeRoleWithWebIdentityRequest$, AssumeRoleWithWebIdentityResponse$, Credentials$, PolicyDescriptorType$, ProvidedContext$, Tag$2, policyDescriptorListType, ProvidedContextsListType, tagKeyListType, tagListType, AssumeRole$, AssumeRoleWithWebIdentity$; +var init_schemas_03 = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js"() { + "use strict"; + init_schema2(); + init_errors3(); + init_STSServiceException(); + _A2 = "Arn"; + _AKI2 = "AccessKeyId"; + _AR2 = "AssumeRole"; + _ARI2 = "AssumedRoleId"; + _ARR = "AssumeRoleRequest"; + _ARRs = "AssumeRoleResponse"; + _ARU = "AssumedRoleUser"; + _ARWWI = "AssumeRoleWithWebIdentity"; + _ARWWIR = "AssumeRoleWithWebIdentityRequest"; + _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; + _Au = "Audience"; + _C2 = "Credentials"; + _CA2 = "ContextAssertion"; + _DS = "DurationSeconds"; + _E2 = "Expiration"; + _EI = "ExternalId"; + _ETE2 = "ExpiredTokenException"; + _IDPCEE = "IDPCommunicationErrorException"; + _IDPRCE = "IDPRejectedClaimException"; + _IITE = "InvalidIdentityTokenException"; + _K2 = "Key"; + _MPDE = "MalformedPolicyDocumentException"; + _P2 = "Policy"; + _PA = "PolicyArns"; + _PAr = "ProviderArn"; + _PC2 = "ProvidedContexts"; + _PCLT = "ProvidedContextsListType"; + _PCr = "ProvidedContext"; + _PDT = "PolicyDescriptorType"; + _PI2 = "ProviderId"; + _PPS = "PackedPolicySize"; + _PPTLE = "PackedPolicyTooLargeException"; + _Pr2 = "Provider"; + _RA = "RoleArn"; + _RDE = "RegionDisabledException"; + _RSN = "RoleSessionName"; + _SAK2 = "SecretAccessKey"; + _SFWIT = "SubjectFromWebIdentityToken"; + _SI = "SourceIdentity"; + _SN = "SerialNumber"; + _ST2 = "SessionToken"; + _T2 = "Tags"; + _TC2 = "TokenCode"; + _TTK = "TransitiveTagKeys"; + _Ta2 = "Tag"; + _V2 = "Value"; + _WIT = "WebIdentityToken"; + _a = "arn"; + _aKST = "accessKeySecretType"; + _aQE = "awsQueryError"; + _c4 = "client"; + _cTT = "clientTokenType"; + _e4 = "error"; + _hE4 = "httpError"; + _m3 = "message"; + _pDLT = "policyDescriptorListType"; + _s4 = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; + _tLT = "tagListType"; + n04 = "com.amazonaws.sts"; + _s_registry4 = TypeRegistry.for(_s4); + STSServiceException$ = [-3, _s4, "STSServiceException", 0, [], []]; + _s_registry4.registerError(STSServiceException$, STSServiceException); + n0_registry4 = TypeRegistry.for(n04); + ExpiredTokenException$2 = [ + -3, + n04, + _ETE2, + { [_aQE]: [`ExpiredTokenException`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(ExpiredTokenException$2, ExpiredTokenException2); + IDPCommunicationErrorException$ = [ + -3, + n04, + _IDPCEE, + { [_aQE]: [`IDPCommunicationError`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException); + IDPRejectedClaimException$ = [ + -3, + n04, + _IDPRCE, + { [_aQE]: [`IDPRejectedClaim`, 403], [_e4]: _c4, [_hE4]: 403 }, + [_m3], + [0] + ]; + n0_registry4.registerError(IDPRejectedClaimException$, IDPRejectedClaimException); + InvalidIdentityTokenException$ = [ + -3, + n04, + _IITE, + { [_aQE]: [`InvalidIdentityToken`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException); + MalformedPolicyDocumentException$ = [ + -3, + n04, + _MPDE, + { [_aQE]: [`MalformedPolicyDocument`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException); + PackedPolicyTooLargeException$ = [ + -3, + n04, + _PPTLE, + { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException); + RegionDisabledException$ = [ + -3, + n04, + _RDE, + { [_aQE]: [`RegionDisabledException`, 403], [_e4]: _c4, [_hE4]: 403 }, + [_m3], + [0] + ]; + n0_registry4.registerError(RegionDisabledException$, RegionDisabledException); + errorTypeRegistries4 = [_s_registry4, n0_registry4]; + accessKeySecretType = [0, n04, _aKST, 8, 0]; + clientTokenType = [0, n04, _cTT, 8, 0]; + AssumedRoleUser$ = [3, n04, _ARU, 0, [_ARI2, _A2], [0, 0], 2]; + AssumeRoleRequest$ = [ + 3, + n04, + _ARR, + 0, + [_RA, _RSN, _PA, _P2, _DS, _T2, _TTK, _EI, _SN, _TC2, _SI, _PC2], + [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], + 2 + ]; + AssumeRoleResponse$ = [ + 3, + n04, + _ARRs, + 0, + [_C2, _ARU, _PPS, _SI], + [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0] + ]; + AssumeRoleWithWebIdentityRequest$ = [ + 3, + n04, + _ARWWIR, + 0, + [_RA, _RSN, _WIT, _PI2, _PA, _P2, _DS], + [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], + 3 + ]; + AssumeRoleWithWebIdentityResponse$ = [ + 3, + n04, + _ARWWIRs, + 0, + [_C2, _SFWIT, _ARU, _PPS, _Pr2, _Au, _SI], + [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0] + ]; + Credentials$ = [ + 3, + n04, + _C2, + 0, + [_AKI2, _SAK2, _ST2, _E2], + [0, [() => accessKeySecretType, 0], 0, 4], + 4 + ]; + PolicyDescriptorType$ = [3, n04, _PDT, 0, [_a], [0]]; + ProvidedContext$ = [3, n04, _PCr, 0, [_PAr, _CA2], [0, 0]]; + Tag$2 = [3, n04, _Ta2, 0, [_K2, _V2], [0, 0], 2]; + policyDescriptorListType = [1, n04, _pDLT, 0, () => PolicyDescriptorType$]; + ProvidedContextsListType = [1, n04, _PCLT, 0, () => ProvidedContext$]; + tagKeyListType = 64 | 0; + tagListType = [1, n04, _tLT, 0, () => Tag$2]; + AssumeRole$ = [9, n04, _AR2, 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$]; + AssumeRoleWithWebIdentity$ = [ + 9, + n04, + _ARWWI, + 0, + () => AssumeRoleWithWebIdentityRequest$, + () => AssumeRoleWithWebIdentityResponse$ + ]; } }); @@ -36353,6 +37789,7 @@ var init_runtimeConfig_shared3 = __esm({ init_dist_es7(); init_httpAuthSchemeProvider3(); init_endpointResolver3(); + init_schemas_03(); getRuntimeConfig5 = (config) => { return { apiVersion: "2011-06-15", @@ -36378,6 +37815,7 @@ var init_runtimeConfig_shared3 = __esm({ protocol: config?.protocol ?? AwsQueryProtocol, protocolSettings: config?.protocolSettings ?? { defaultNamespace: "com.amazonaws.sts", + errorTypeRegistries: errorTypeRegistries4, xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", version: "2011-06-15", serviceTarget: "AWSSecurityTokenServiceV20110615" @@ -36507,7 +37945,7 @@ var resolveRuntimeExtensions3; var init_runtimeExtensions3 = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() { "use strict"; - init_dist_es47(); + init_dist_es48(); init_dist_es2(); init_dist_es20(); init_httpAuthExtensionConfiguration3(); @@ -36576,311 +38014,6 @@ var init_STSClient = __esm({ } }); -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js -var STSServiceException; -var init_STSServiceException = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() { - "use strict"; - init_dist_es20(); - STSServiceException = class _STSServiceException extends ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js -var ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException; -var init_errors3 = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js"() { - "use strict"; - init_STSServiceException(); - ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException { - name = "ExpiredTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } - }; - MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - name = "MalformedPolicyDocumentException"; - $fault = "client"; - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } - }; - PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - name = "PackedPolicyTooLargeException"; - $fault = "client"; - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } - }; - RegionDisabledException = class _RegionDisabledException extends STSServiceException { - name = "RegionDisabledException"; - $fault = "client"; - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } - }; - IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - name = "IDPRejectedClaimException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } - }; - InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - name = "InvalidIdentityTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } - }; - IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - name = "IDPCommunicationErrorException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js -var _A2, _AKI2, _AR2, _ARI2, _ARR, _ARRs, _ARU, _ARWWI, _ARWWIR, _ARWWIRs, _Au, _C2, _CA2, _DS, _E2, _EI, _ETE2, _IDPCEE, _IDPRCE, _IITE, _K2, _MPDE, _P2, _PA, _PAr, _PC2, _PCLT, _PCr, _PDT, _PI2, _PPS, _PPTLE, _Pr2, _RA, _RDE, _RSN, _SAK2, _SFWIT, _SI, _SN, _ST2, _T2, _TC2, _TTK, _Ta2, _V2, _WIT, _a, _aKST, _aQE, _c4, _cTT, _e4, _hE4, _m3, _pDLT, _s4, _tLT, n04, accessKeySecretType, clientTokenType, AssumedRoleUser$, AssumeRoleRequest$, AssumeRoleResponse$, AssumeRoleWithWebIdentityRequest$, AssumeRoleWithWebIdentityResponse$, Credentials$, ExpiredTokenException$2, IDPCommunicationErrorException$, IDPRejectedClaimException$, InvalidIdentityTokenException$, MalformedPolicyDocumentException$, PackedPolicyTooLargeException$, PolicyDescriptorType$, ProvidedContext$, RegionDisabledException$, Tag$2, STSServiceException$, policyDescriptorListType, ProvidedContextsListType, tagKeyListType, tagListType, AssumeRole$, AssumeRoleWithWebIdentity$; -var init_schemas_03 = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js"() { - "use strict"; - init_schema2(); - init_errors3(); - init_STSServiceException(); - _A2 = "Arn"; - _AKI2 = "AccessKeyId"; - _AR2 = "AssumeRole"; - _ARI2 = "AssumedRoleId"; - _ARR = "AssumeRoleRequest"; - _ARRs = "AssumeRoleResponse"; - _ARU = "AssumedRoleUser"; - _ARWWI = "AssumeRoleWithWebIdentity"; - _ARWWIR = "AssumeRoleWithWebIdentityRequest"; - _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; - _Au = "Audience"; - _C2 = "Credentials"; - _CA2 = "ContextAssertion"; - _DS = "DurationSeconds"; - _E2 = "Expiration"; - _EI = "ExternalId"; - _ETE2 = "ExpiredTokenException"; - _IDPCEE = "IDPCommunicationErrorException"; - _IDPRCE = "IDPRejectedClaimException"; - _IITE = "InvalidIdentityTokenException"; - _K2 = "Key"; - _MPDE = "MalformedPolicyDocumentException"; - _P2 = "Policy"; - _PA = "PolicyArns"; - _PAr = "ProviderArn"; - _PC2 = "ProvidedContexts"; - _PCLT = "ProvidedContextsListType"; - _PCr = "ProvidedContext"; - _PDT = "PolicyDescriptorType"; - _PI2 = "ProviderId"; - _PPS = "PackedPolicySize"; - _PPTLE = "PackedPolicyTooLargeException"; - _Pr2 = "Provider"; - _RA = "RoleArn"; - _RDE = "RegionDisabledException"; - _RSN = "RoleSessionName"; - _SAK2 = "SecretAccessKey"; - _SFWIT = "SubjectFromWebIdentityToken"; - _SI = "SourceIdentity"; - _SN = "SerialNumber"; - _ST2 = "SessionToken"; - _T2 = "Tags"; - _TC2 = "TokenCode"; - _TTK = "TransitiveTagKeys"; - _Ta2 = "Tag"; - _V2 = "Value"; - _WIT = "WebIdentityToken"; - _a = "arn"; - _aKST = "accessKeySecretType"; - _aQE = "awsQueryError"; - _c4 = "client"; - _cTT = "clientTokenType"; - _e4 = "error"; - _hE4 = "httpError"; - _m3 = "message"; - _pDLT = "policyDescriptorListType"; - _s4 = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; - _tLT = "tagListType"; - n04 = "com.amazonaws.sts"; - accessKeySecretType = [0, n04, _aKST, 8, 0]; - clientTokenType = [0, n04, _cTT, 8, 0]; - AssumedRoleUser$ = [3, n04, _ARU, 0, [_ARI2, _A2], [0, 0], 2]; - AssumeRoleRequest$ = [ - 3, - n04, - _ARR, - 0, - [_RA, _RSN, _PA, _P2, _DS, _T2, _TTK, _EI, _SN, _TC2, _SI, _PC2], - [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], - 2 - ]; - AssumeRoleResponse$ = [ - 3, - n04, - _ARRs, - 0, - [_C2, _ARU, _PPS, _SI], - [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0] - ]; - AssumeRoleWithWebIdentityRequest$ = [ - 3, - n04, - _ARWWIR, - 0, - [_RA, _RSN, _WIT, _PI2, _PA, _P2, _DS], - [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], - 3 - ]; - AssumeRoleWithWebIdentityResponse$ = [ - 3, - n04, - _ARWWIRs, - 0, - [_C2, _SFWIT, _ARU, _PPS, _Pr2, _Au, _SI], - [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0] - ]; - Credentials$ = [ - 3, - n04, - _C2, - 0, - [_AKI2, _SAK2, _ST2, _E2], - [0, [() => accessKeySecretType, 0], 0, 4], - 4 - ]; - ExpiredTokenException$2 = [ - -3, - n04, - _ETE2, - { [_aQE]: [`ExpiredTokenException`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(ExpiredTokenException$2, ExpiredTokenException2); - IDPCommunicationErrorException$ = [ - -3, - n04, - _IDPCEE, - { [_aQE]: [`IDPCommunicationError`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException); - IDPRejectedClaimException$ = [ - -3, - n04, - _IDPRCE, - { [_aQE]: [`IDPRejectedClaim`, 403], [_e4]: _c4, [_hE4]: 403 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(IDPRejectedClaimException$, IDPRejectedClaimException); - InvalidIdentityTokenException$ = [ - -3, - n04, - _IITE, - { [_aQE]: [`InvalidIdentityToken`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException); - MalformedPolicyDocumentException$ = [ - -3, - n04, - _MPDE, - { [_aQE]: [`MalformedPolicyDocument`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException); - PackedPolicyTooLargeException$ = [ - -3, - n04, - _PPTLE, - { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException); - PolicyDescriptorType$ = [3, n04, _PDT, 0, [_a], [0]]; - ProvidedContext$ = [3, n04, _PCr, 0, [_PAr, _CA2], [0, 0]]; - RegionDisabledException$ = [ - -3, - n04, - _RDE, - { [_aQE]: [`RegionDisabledException`, 403], [_e4]: _c4, [_hE4]: 403 }, - [_m3], - [0] - ]; - TypeRegistry.for(n04).registerError(RegionDisabledException$, RegionDisabledException); - Tag$2 = [3, n04, _Ta2, 0, [_K2, _V2], [0, 0], 2]; - STSServiceException$ = [-3, _s4, "STSServiceException", 0, [], []]; - TypeRegistry.for(_s4).registerError(STSServiceException$, STSServiceException); - policyDescriptorListType = [1, n04, _pDLT, 0, () => PolicyDescriptorType$]; - ProvidedContextsListType = [1, n04, _PCLT, 0, () => ProvidedContext$]; - tagKeyListType = 64 | 0; - tagListType = [1, n04, _tLT, 0, () => Tag$2]; - AssumeRole$ = [9, n04, _AR2, 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$]; - AssumeRoleWithWebIdentity$ = [ - 9, - n04, - _ARWWI, - 0, - () => AssumeRoleWithWebIdentityRequest$, - () => AssumeRoleWithWebIdentityResponse$ - ]; - } -}); - // ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js var AssumeRoleCommand; var init_AssumeRoleCommand = __esm({ @@ -36890,7 +38023,7 @@ var init_AssumeRoleCommand = __esm({ init_dist_es20(); init_EndpointParameters3(); init_schemas_03(); - AssumeRoleCommand = class extends Command2.classBuilder().ep(commonParams4).m(function(Command3, cs2, config, o6) { + AssumeRoleCommand = class extends Command2.classBuilder().ep(commonParams4).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").sc(AssumeRole$).build() { }; @@ -36906,7 +38039,7 @@ var init_AssumeRoleWithWebIdentityCommand = __esm({ init_dist_es20(); init_EndpointParameters3(); init_schemas_03(); - AssumeRoleWithWebIdentityCommand = class extends Command2.classBuilder().ep(commonParams4).m(function(Command3, cs2, config, o6) { + AssumeRoleWithWebIdentityCommand = class extends Command2.classBuilder().ep(commonParams4).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").sc(AssumeRoleWithWebIdentity$).build() { }; @@ -36954,7 +38087,7 @@ var init_defaultStsRoleAssumers = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() { "use strict"; init_client2(); - init_dist_es47(); + init_dist_es48(); init_AssumeRoleCommand(); init_AssumeRoleWithWebIdentityCommand(); getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { @@ -37125,6 +38258,7 @@ __export(sts_exports, { Tag$: () => Tag$2, __Client: () => Client, decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + errorTypeRegistries: () => errorTypeRegistries4, getDefaultRoleAssumer: () => getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 }); @@ -37336,7 +38470,7 @@ var cache5, defaultEndpointResolver5; var init_endpointResolver4 = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js"() { "use strict"; - init_dist_es30(); + init_dist_es47(); init_dist_es27(); init_ruleset4(); cache5 = new EndpointCache({ @@ -37349,7 +38483,217 @@ var init_endpointResolver4 = __esm({ logger: context3.logger })); }; - customEndpointFunctions.aws = awsEndpointFunctions; + customEndpointFunctions.aws = awsEndpointFunctions3; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js +var SigninServiceException; +var init_SigninServiceException = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js"() { + "use strict"; + init_dist_es20(); + SigninServiceException = class _SigninServiceException extends ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SigninServiceException.prototype); + } + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js +var AccessDeniedException2, InternalServerException2, TooManyRequestsError, ValidationException; +var init_errors4 = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js"() { + "use strict"; + init_SigninServiceException(); + AccessDeniedException2 = class _AccessDeniedException extends SigninServiceException { + name = "AccessDeniedException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + } + }; + InternalServerException2 = class _InternalServerException extends SigninServiceException { + name = "InternalServerException"; + $fault = "server"; + error; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + } + }; + TooManyRequestsError = class _TooManyRequestsError extends SigninServiceException { + name = "TooManyRequestsError"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "TooManyRequestsError", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsError.prototype); + this.error = opts.error; + } + }; + ValidationException = class _ValidationException extends SigninServiceException { + name = "ValidationException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ValidationException.prototype); + this.error = opts.error; + } + }; + } +}); + +// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js +var _ADE2, _AT3, _COAT, _COATR, _COATRB, _COATRBr, _COATRr, _ISE2, _RT3, _TMRE2, _VE, _aKI2, _aT3, _c5, _cI2, _cV2, _co2, _e5, _eI2, _gT2, _h4, _hE5, _iT3, _jN, _m4, _rT2, _rU2, _s5, _sAK2, _sT2, _se2, _tI, _tO, _tT2, n05, _s_registry5, SigninServiceException$, n0_registry5, AccessDeniedException$2, InternalServerException$2, TooManyRequestsError$, ValidationException$, errorTypeRegistries5, RefreshToken2, AccessToken$, CreateOAuth2TokenRequest$, CreateOAuth2TokenRequestBody$, CreateOAuth2TokenResponse$, CreateOAuth2TokenResponseBody$, CreateOAuth2Token$; +var init_schemas_04 = __esm({ + "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js"() { + "use strict"; + init_schema2(); + init_errors4(); + init_SigninServiceException(); + _ADE2 = "AccessDeniedException"; + _AT3 = "AccessToken"; + _COAT = "CreateOAuth2Token"; + _COATR = "CreateOAuth2TokenRequest"; + _COATRB = "CreateOAuth2TokenRequestBody"; + _COATRBr = "CreateOAuth2TokenResponseBody"; + _COATRr = "CreateOAuth2TokenResponse"; + _ISE2 = "InternalServerException"; + _RT3 = "RefreshToken"; + _TMRE2 = "TooManyRequestsError"; + _VE = "ValidationException"; + _aKI2 = "accessKeyId"; + _aT3 = "accessToken"; + _c5 = "client"; + _cI2 = "clientId"; + _cV2 = "codeVerifier"; + _co2 = "code"; + _e5 = "error"; + _eI2 = "expiresIn"; + _gT2 = "grantType"; + _h4 = "http"; + _hE5 = "httpError"; + _iT3 = "idToken"; + _jN = "jsonName"; + _m4 = "message"; + _rT2 = "refreshToken"; + _rU2 = "redirectUri"; + _s5 = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; + _sAK2 = "secretAccessKey"; + _sT2 = "sessionToken"; + _se2 = "server"; + _tI = "tokenInput"; + _tO = "tokenOutput"; + _tT2 = "tokenType"; + n05 = "com.amazonaws.signin"; + _s_registry5 = TypeRegistry.for(_s5); + SigninServiceException$ = [-3, _s5, "SigninServiceException", 0, [], []]; + _s_registry5.registerError(SigninServiceException$, SigninServiceException); + n0_registry5 = TypeRegistry.for(n05); + AccessDeniedException$2 = [-3, n05, _ADE2, { [_e5]: _c5 }, [_e5, _m4], [0, 0], 2]; + n0_registry5.registerError(AccessDeniedException$2, AccessDeniedException2); + InternalServerException$2 = [-3, n05, _ISE2, { [_e5]: _se2, [_hE5]: 500 }, [_e5, _m4], [0, 0], 2]; + n0_registry5.registerError(InternalServerException$2, InternalServerException2); + TooManyRequestsError$ = [-3, n05, _TMRE2, { [_e5]: _c5, [_hE5]: 429 }, [_e5, _m4], [0, 0], 2]; + n0_registry5.registerError(TooManyRequestsError$, TooManyRequestsError); + ValidationException$ = [-3, n05, _VE, { [_e5]: _c5, [_hE5]: 400 }, [_e5, _m4], [0, 0], 2]; + n0_registry5.registerError(ValidationException$, ValidationException); + errorTypeRegistries5 = [_s_registry5, n0_registry5]; + RefreshToken2 = [0, n05, _RT3, 8, 0]; + AccessToken$ = [ + 3, + n05, + _AT3, + 8, + [_aKI2, _sAK2, _sT2], + [ + [0, { [_jN]: _aKI2 }], + [0, { [_jN]: _sAK2 }], + [0, { [_jN]: _sT2 }] + ], + 3 + ]; + CreateOAuth2TokenRequest$ = [ + 3, + n05, + _COATR, + 0, + [_tI], + [[() => CreateOAuth2TokenRequestBody$, 16]], + 1 + ]; + CreateOAuth2TokenRequestBody$ = [ + 3, + n05, + _COATRB, + 0, + [_cI2, _gT2, _co2, _rU2, _cV2, _rT2], + [ + [0, { [_jN]: _cI2 }], + [0, { [_jN]: _gT2 }], + 0, + [0, { [_jN]: _rU2 }], + [0, { [_jN]: _cV2 }], + [() => RefreshToken2, { [_jN]: _rT2 }] + ], + 2 + ]; + CreateOAuth2TokenResponse$ = [ + 3, + n05, + _COATRr, + 0, + [_tO], + [[() => CreateOAuth2TokenResponseBody$, 16]], + 1 + ]; + CreateOAuth2TokenResponseBody$ = [ + 3, + n05, + _COATRBr, + 0, + [_aT3, _tT2, _eI2, _rT2, _iT3], + [ + [() => AccessToken$, { [_jN]: _aT3 }], + [0, { [_jN]: _tT2 }], + [1, { [_jN]: _eI2 }], + [() => RefreshToken2, { [_jN]: _rT2 }], + [0, { [_jN]: _iT3 }] + ], + 4 + ]; + CreateOAuth2Token$ = [ + 9, + n05, + _COAT, + { [_h4]: ["POST", "/v1/token", 200] }, + () => CreateOAuth2TokenRequest$, + () => CreateOAuth2TokenResponse$ + ]; } }); @@ -37367,6 +38711,7 @@ var init_runtimeConfig_shared4 = __esm({ init_dist_es7(); init_httpAuthSchemeProvider4(); init_endpointResolver4(); + init_schemas_04(); getRuntimeConfig7 = (config) => { return { apiVersion: "2023-01-01", @@ -37392,6 +38737,7 @@ var init_runtimeConfig_shared4 = __esm({ protocol: config?.protocol ?? AwsRestJsonProtocol, protocolSettings: config?.protocolSettings ?? { defaultNamespace: "com.amazonaws.signin", + errorTypeRegistries: errorTypeRegistries5, version: "2023-01-01", serviceTarget: "Signin" }, @@ -37507,7 +38853,7 @@ var resolveRuntimeExtensions4; var init_runtimeExtensions4 = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js"() { "use strict"; - init_dist_es47(); + init_dist_es48(); init_dist_es2(); init_dist_es20(); init_httpAuthExtensionConfiguration4(); @@ -37576,213 +38922,6 @@ var init_SigninClient = __esm({ } }); -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js -var SigninServiceException; -var init_SigninServiceException = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js"() { - "use strict"; - init_dist_es20(); - SigninServiceException = class _SigninServiceException extends ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SigninServiceException.prototype); - } - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js -var AccessDeniedException2, InternalServerException2, TooManyRequestsError, ValidationException; -var init_errors4 = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js"() { - "use strict"; - init_SigninServiceException(); - AccessDeniedException2 = class _AccessDeniedException extends SigninServiceException { - name = "AccessDeniedException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - } - }; - InternalServerException2 = class _InternalServerException extends SigninServiceException { - name = "InternalServerException"; - $fault = "server"; - error; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - } - }; - TooManyRequestsError = class _TooManyRequestsError extends SigninServiceException { - name = "TooManyRequestsError"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "TooManyRequestsError", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsError.prototype); - this.error = opts.error; - } - }; - ValidationException = class _ValidationException extends SigninServiceException { - name = "ValidationException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "ValidationException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ValidationException.prototype); - this.error = opts.error; - } - }; - } -}); - -// ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js -var _ADE2, _AT3, _COAT, _COATR, _COATRB, _COATRBr, _COATRr, _ISE2, _RT3, _TMRE2, _VE, _aKI2, _aT3, _c5, _cI2, _cV2, _co2, _e5, _eI2, _gT2, _h4, _hE5, _iT3, _jN, _m4, _rT2, _rU2, _s5, _sAK2, _sT2, _sm3, _tI, _tO, _tT2, n05, RefreshToken2, AccessDeniedException$2, AccessToken$, CreateOAuth2TokenRequest$, CreateOAuth2TokenRequestBody$, CreateOAuth2TokenResponse$, CreateOAuth2TokenResponseBody$, InternalServerException$2, TooManyRequestsError$, ValidationException$, SigninServiceException$, CreateOAuth2Token$; -var init_schemas_04 = __esm({ - "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js"() { - "use strict"; - init_schema2(); - init_errors4(); - init_SigninServiceException(); - _ADE2 = "AccessDeniedException"; - _AT3 = "AccessToken"; - _COAT = "CreateOAuth2Token"; - _COATR = "CreateOAuth2TokenRequest"; - _COATRB = "CreateOAuth2TokenRequestBody"; - _COATRBr = "CreateOAuth2TokenResponseBody"; - _COATRr = "CreateOAuth2TokenResponse"; - _ISE2 = "InternalServerException"; - _RT3 = "RefreshToken"; - _TMRE2 = "TooManyRequestsError"; - _VE = "ValidationException"; - _aKI2 = "accessKeyId"; - _aT3 = "accessToken"; - _c5 = "client"; - _cI2 = "clientId"; - _cV2 = "codeVerifier"; - _co2 = "code"; - _e5 = "error"; - _eI2 = "expiresIn"; - _gT2 = "grantType"; - _h4 = "http"; - _hE5 = "httpError"; - _iT3 = "idToken"; - _jN = "jsonName"; - _m4 = "message"; - _rT2 = "refreshToken"; - _rU2 = "redirectUri"; - _s5 = "server"; - _sAK2 = "secretAccessKey"; - _sT2 = "sessionToken"; - _sm3 = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; - _tI = "tokenInput"; - _tO = "tokenOutput"; - _tT2 = "tokenType"; - n05 = "com.amazonaws.signin"; - RefreshToken2 = [0, n05, _RT3, 8, 0]; - AccessDeniedException$2 = [-3, n05, _ADE2, { [_e5]: _c5 }, [_e5, _m4], [0, 0], 2]; - TypeRegistry.for(n05).registerError(AccessDeniedException$2, AccessDeniedException2); - AccessToken$ = [ - 3, - n05, - _AT3, - 8, - [_aKI2, _sAK2, _sT2], - [ - [0, { [_jN]: _aKI2 }], - [0, { [_jN]: _sAK2 }], - [0, { [_jN]: _sT2 }] - ], - 3 - ]; - CreateOAuth2TokenRequest$ = [ - 3, - n05, - _COATR, - 0, - [_tI], - [[() => CreateOAuth2TokenRequestBody$, 16]], - 1 - ]; - CreateOAuth2TokenRequestBody$ = [ - 3, - n05, - _COATRB, - 0, - [_cI2, _gT2, _co2, _rU2, _cV2, _rT2], - [ - [0, { [_jN]: _cI2 }], - [0, { [_jN]: _gT2 }], - 0, - [0, { [_jN]: _rU2 }], - [0, { [_jN]: _cV2 }], - [() => RefreshToken2, { [_jN]: _rT2 }] - ], - 2 - ]; - CreateOAuth2TokenResponse$ = [ - 3, - n05, - _COATRr, - 0, - [_tO], - [[() => CreateOAuth2TokenResponseBody$, 16]], - 1 - ]; - CreateOAuth2TokenResponseBody$ = [ - 3, - n05, - _COATRBr, - 0, - [_aT3, _tT2, _eI2, _rT2, _iT3], - [ - [() => AccessToken$, { [_jN]: _aT3 }], - [0, { [_jN]: _tT2 }], - [1, { [_jN]: _eI2 }], - [() => RefreshToken2, { [_jN]: _rT2 }], - [0, { [_jN]: _iT3 }] - ], - 4 - ]; - InternalServerException$2 = [-3, n05, _ISE2, { [_e5]: _s5, [_hE5]: 500 }, [_e5, _m4], [0, 0], 2]; - TypeRegistry.for(n05).registerError(InternalServerException$2, InternalServerException2); - TooManyRequestsError$ = [-3, n05, _TMRE2, { [_e5]: _c5, [_hE5]: 429 }, [_e5, _m4], [0, 0], 2]; - TypeRegistry.for(n05).registerError(TooManyRequestsError$, TooManyRequestsError); - ValidationException$ = [-3, n05, _VE, { [_e5]: _c5, [_hE5]: 400 }, [_e5, _m4], [0, 0], 2]; - TypeRegistry.for(n05).registerError(ValidationException$, ValidationException); - SigninServiceException$ = [-3, _sm3, "SigninServiceException", 0, [], []]; - TypeRegistry.for(_sm3).registerError(SigninServiceException$, SigninServiceException); - CreateOAuth2Token$ = [ - 9, - n05, - _COAT, - { [_h4]: ["POST", "/v1/token", 200] }, - () => CreateOAuth2TokenRequest$, - () => CreateOAuth2TokenResponse$ - ]; - } -}); - // ../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js var CreateOAuth2TokenCommand; var init_CreateOAuth2TokenCommand = __esm({ @@ -37792,7 +38931,7 @@ var init_CreateOAuth2TokenCommand = __esm({ init_dist_es20(); init_EndpointParameters4(); init_schemas_04(); - CreateOAuth2TokenCommand = class extends Command2.classBuilder().ep(commonParams5).m(function(Command3, cs2, config, o6) { + CreateOAuth2TokenCommand = class extends Command2.classBuilder().ep(commonParams5).m(function(Command3, cs3, config, o6) { return [getEndpointPlugin(config, Command3.getEndpointParameterInstructions())]; }).s("Signin", "CreateOAuth2Token", {}).n("SigninClient", "CreateOAuth2TokenCommand").sc(CreateOAuth2Token$).build() { }; @@ -37871,7 +39010,8 @@ __export(signin_exports, { TooManyRequestsError$: () => TooManyRequestsError$, ValidationException: () => ValidationException, ValidationException$: () => ValidationException$, - __Client: () => Client + __Client: () => Client, + errorTypeRegistries: () => errorTypeRegistries5 }); var init_signin = __esm({ "../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js"() { @@ -38026,7 +39166,7 @@ var init_LoginCredentialsFetcher = __esm({ tokenData = await import_node_fs2.promises.readFile(tokenFilePath, "utf8"); } const token = JSON.parse(tokenData); - const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k6) => !token[k6]); + const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k7) => !token[k7]); if (!token.accessToken?.accountId) { missingFields.push("accountId"); } @@ -38115,7 +39255,7 @@ var init_LoginCredentialsFetcher = __esm({ break; } } - const x7 = publicDer.slice(pointStart + 1, pointStart + 33); + const x8 = publicDer.slice(pointStart + 1, pointStart + 33); const y4 = publicDer.slice(pointStart + 33, pointStart + 65); const header = { alg: "ES256", @@ -38123,7 +39263,7 @@ var init_LoginCredentialsFetcher = __esm({ jwk: { kty: "EC", crv: "P-256", - x: x7.toString("base64url"), + x: x8.toString("base64url"), y: y4.toString("base64url") } }; @@ -38178,18 +39318,18 @@ var init_fromLoginCredentials = __esm({ }); // ../node_modules/@aws-sdk/credential-provider-login/dist-es/types.js -var init_types10 = __esm({ +var init_types12 = __esm({ "../node_modules/@aws-sdk/credential-provider-login/dist-es/types.js"() { "use strict"; } }); // ../node_modules/@aws-sdk/credential-provider-login/dist-es/index.js -var init_dist_es51 = __esm({ +var init_dist_es53 = __esm({ "../node_modules/@aws-sdk/credential-provider-login/dist-es/index.js"() { "use strict"; init_fromLoginCredentials(); - init_types10(); + init_types12(); } }); @@ -38199,7 +39339,7 @@ var init_resolveLoginCredentials = __esm({ "../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js"() { "use strict"; init_client2(); - init_dist_es51(); + init_dist_es53(); isLoginProfile = (data) => { return Boolean(data && data.login_session); }; @@ -38313,7 +39453,7 @@ var dist_es_exports5 = {}; __export(dist_es_exports5, { fromProcess: () => fromProcess }); -var init_dist_es52 = __esm({ +var init_dist_es54 = __esm({ "../node_modules/@aws-sdk/credential-provider-process/dist-es/index.js"() { "use strict"; init_fromProcess(); @@ -38327,7 +39467,7 @@ var init_resolveProcessCredentials2 = __esm({ "use strict"; init_client2(); isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; - resolveProcessCredentials2 = async (options, profile) => Promise.resolve().then(() => (init_dist_es52(), dist_es_exports5)).then(({ fromProcess: fromProcess2 }) => fromProcess2({ + resolveProcessCredentials2 = async (options, profile) => Promise.resolve().then(() => (init_dist_es54(), dist_es_exports5)).then(({ fromProcess: fromProcess2 }) => fromProcess2({ ...options, profile })().then((creds) => setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); @@ -38341,7 +39481,7 @@ var init_resolveSsoCredentials = __esm({ "use strict"; init_client2(); resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => { - const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es50(), dist_es_exports4)); + const { fromSSO: fromSSO2 } = await Promise.resolve().then(() => (init_dist_es52(), dist_es_exports4)); return fromSSO2({ profile, logger: options.logger, @@ -38458,7 +39598,7 @@ __export(dist_es_exports6, { fromTokenFile: () => fromTokenFile, fromWebToken: () => fromWebToken }); -var init_dist_es53 = __esm({ +var init_dist_es55 = __esm({ "../node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js"() { "use strict"; init_fromTokenFile(); @@ -38473,7 +39613,7 @@ var init_resolveWebIdentityCredentials = __esm({ "use strict"; init_client2(); isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; - resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => Promise.resolve().then(() => (init_dist_es53(), dist_es_exports6)).then(({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({ + resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => Promise.resolve().then(() => (init_dist_es55(), dist_es_exports6)).then(({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({ webIdentityTokenFile: profile.web_identity_token_file, roleArn: profile.role_arn, roleSessionName: profile.role_session_name, @@ -38548,7 +39688,7 @@ var dist_es_exports7 = {}; __export(dist_es_exports7, { fromIni: () => fromIni }); -var init_dist_es54 = __esm({ +var init_dist_es56 = __esm({ "../node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js"() { "use strict"; init_fromIni(); @@ -38666,7 +39806,7 @@ var require_util9 = __commonJS({ } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; - function T2() { + function T3() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { @@ -38675,8 +39815,8 @@ var require_util9 = __commonJS({ } } } - T2.prototype = Parent.prototype; - Child.prototype = new T2(); + T3.prototype = Parent.prototype; + Child.prototype = new T3(); return Child.prototype; }; function isPrimitive(val) { @@ -38867,11 +40007,11 @@ var require_util9 = __commonJS({ function classString(obj2) { return {}.toString.call(obj2); } - function copyDescriptors(from, to2, filter2) { + function copyDescriptors(from, to2, filter) { var keys = es5.names(from); for (var i6 = 0; i6 < keys.length; ++i6) { var key = keys[i6]; - if (filter2(key)) { + if (filter(key)) { try { es5.defineProperty(to2, key, es5.getDescriptor(from, key)); } catch (ignore) { @@ -38879,29 +40019,29 @@ var require_util9 = __commonJS({ } } } - var asArray = function(v7) { - if (es5.isArray(v7)) { - return v7; + var asArray = function(v8) { + if (es5.isArray(v8)) { + return v8; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { - ArrayFrom = typeof Array.from === "function" ? function(v7) { - return Array.from(v7); - } : function(v7) { + ArrayFrom = typeof Array.from === "function" ? function(v8) { + return Array.from(v8); + } : function(v8) { var ret2 = []; - var it = v7[Symbol.iterator](); + var it2 = v8[Symbol.iterator](); var itResult; - while (!(itResult = it.next()).done) { + while (!(itResult = it2.next()).done) { ret2.push(itResult.value); } return ret2; }; - asArray = function(v7) { - if (es5.isArray(v7)) { - return v7; - } else if (v7 != null && typeof v7[Symbol.iterator] === "function") { - return ArrayFrom(v7); + asArray = function(v8) { + if (es5.isArray(v8)) { + return v8; + } else if (v8 != null && typeof v8[Symbol.iterator] === "function") { + return ArrayFrom(v8); } return null; }; @@ -39086,9 +40226,9 @@ var require_queue = __commonJS({ "../node_modules/bluebird/js/release/queue.js"(exports2, module2) { "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j6 = 0; j6 < len; ++j6) { - dst[j6 + dstIndex] = src[j6 + srcIndex]; - src[j6 + srcIndex] = void 0; + for (var j7 = 0; j7 < len; ++j7) { + dst[j7 + dstIndex] = src[j7 + srcIndex]; + src[j7 + srcIndex] = void 0; } } function Queue(capacity) { @@ -39114,12 +40254,12 @@ var require_queue = __commonJS({ this._pushOne(arg); return; } - var j6 = this._front + length - 3; + var j7 = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; - this[j6 + 0 & wrapMask] = fn; - this[j6 + 1 & wrapMask] = receiver2; - this[j6 + 2 & wrapMask] = arg; + this[j7 + 0 & wrapMask] = fn; + this[j7 + 1 & wrapMask] = receiver2; + this[j7 + 2 & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function() { @@ -39325,8 +40465,8 @@ var require_errors2 = __commonJS({ for (var i7 = 0; i7 < this.length; ++i7) { var str = this[i7] === this ? "[Circular AggregateError]" : this[i7] + ""; var lines = str.split("\n"); - for (var j6 = 0; j6 < lines.length; ++j6) { - lines[j6] = indent + lines[j6]; + for (var j7 = 0; j7 < lines.length; ++j7) { + lines[j7] = indent + lines[j7]; } str = lines.join("\n"); ret2 += str + "\n"; @@ -39431,14 +40571,14 @@ var require_thenables = __commonJS({ return false; } } - function doThenable(x7, then, context3) { + function doThenable(x8, then, context3) { var promise = new Promise2(INTERNAL); var ret2 = promise; if (context3) context3._pushContext(); promise._captureStackTrace(); if (context3) context3._popContext(); var synchronous = true; - var result = util17.tryCatch(then).call(x7, resolve3, reject2); + var result = util17.tryCatch(then).call(x8, resolve3, reject2); synchronous = false; if (promise && result === errorObj2) { promise._rejectCallback(result.e, true, true); @@ -39497,7 +40637,7 @@ var require_promise_array = __commonJS({ PromiseArray.prototype.promise = function() { return this._promise; }; - PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + PromiseArray.prototype._init = function init(_2, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise2) { values = values._target(); @@ -40271,14 +41411,14 @@ var require_debuggability = __commonJS({ var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; - for (var j6 = prev.length - 1; j6 >= 0; --j6) { - if (prev[j6] === currentLastLine) { - commonRootMeetPoint = j6; + for (var j7 = prev.length - 1; j7 >= 0; --j7) { + if (prev[j7] === currentLastLine) { + commonRootMeetPoint = j7; break; } } - for (var j6 = commonRootMeetPoint; j6 >= 0; --j6) { - var line = prev[j6]; + for (var j7 = commonRootMeetPoint; j7 >= 0; --j7) { + var line = prev[j7]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; @@ -40490,8 +41630,8 @@ var require_debuggability = __commonJS({ cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; - for (var j6 = i6 - 2; j6 >= 0; --j6) { - nodes[j6]._length = currentChildLength; + for (var j7 = i6 - 2; j7 >= 0; --j7) { + nodes[j7]._length = currentChildLength; currentChildLength++; } return; @@ -40661,8 +41801,8 @@ var require_catch_filter = __commonJS({ } } else if (util17.isObject(e6)) { var keys = getKeys(item); - for (var j6 = 0; j6 < keys.length; ++j6) { - var key = keys[j6]; + for (var j7 = 0; j7 < keys.length; ++j7) { + var key = keys[j7]; if (item[key] != e6[key]) { continue predicateLoop; } @@ -40797,18 +41937,18 @@ var require_finally = __commonJS({ finallyHandler ); } else { - var catchInstances = new Array(len - 1), j6 = 0, i6; + var catchInstances = new Array(len - 1), j7 = 0, i6; for (i6 = 0; i6 < len - 1; ++i6) { var item = arguments[i6]; if (util17.isObject(item)) { - catchInstances[j6++] = item; + catchInstances[j7++] = item; } else { return Promise2.reject(new TypeError( "tapCatch statement predicate: expecting an object but got " + util17.classString(item) )); } } - catchInstances.length = j6; + catchInstances.length = j7; var handler2 = arguments[i6]; return this._passThrough( catchFilter(catchInstances, handler2, this), @@ -40950,7 +42090,7 @@ var require_bind = __commonJS({ "use strict"; module2.exports = function(Promise2, INTERNAL, tryConvertToPromise, debug2) { var calledBind = false; - var rejectThis = function(_, e6) { + var rejectThis = function(_2, e6) { this._reject(e6); }; var targetRejected = function(e6, context3) { @@ -41849,11 +42989,11 @@ var require_map = __commonJS({ MappingPromiseArray.prototype._filter = function(booleans, values) { var len = values.length; var ret2 = new Array(len); - var j6 = 0; + var j7 = 0; for (var i6 = 0; i6 < len; ++i6) { - if (booleans[i6]) ret2[j6++] = values[i6]; + if (booleans[i6]) ret2[j7++] = values[i6]; } - ret2.length = j6; + ret2.length = j7; this._resolve(ret2); }; MappingPromiseArray.prototype.preservedValues = function() { @@ -41999,22 +43139,22 @@ var require_promisify = __commonJS({ var key = ret2[i6]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j6 = 0; j6 < ret2.length; j6 += 2) { - if (ret2[j6] === keyWithoutAsyncSuffix) { + for (var j7 = 0; j7 < ret2.length; j7 += 2) { + if (ret2[j7] === keyWithoutAsyncSuffix) { throw new TypeError2("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s", suffix)); } } } } } - function promisifiableMethods(obj2, suffix, suffixRegexp, filter2) { + function promisifiableMethods(obj2, suffix, suffixRegexp, filter) { var keys = util17.inheritedDataKeys(obj2); var ret2 = []; for (var i6 = 0; i6 < keys.length; ++i6) { var key = keys[i6]; var value = obj2[key]; - var passesDefaultFilter = filter2 === defaultFilter ? true : defaultFilter(key, value, obj2); - if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj2, key, suffix) && filter2(key, value, obj2, passesDefaultFilter)) { + var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj2); + if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj2, key, suffix) && filter(key, value, obj2, passesDefaultFilter)) { ret2.push(key, value); } } @@ -42053,7 +43193,7 @@ var require_promisify = __commonJS({ } return 0; }; - makeNodePromisifiedEval = function(callback, receiver2, originalName, fn, _, multiArgs) { + makeNodePromisifiedEval = function(callback, receiver2, originalName, fn, _2, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver2 === THIS; @@ -42105,7 +43245,7 @@ var require_promisify = __commonJS({ ); }; } - function makeNodePromisifiedClosure(callback, receiver2, _, fn, __, multiArgs) { + function makeNodePromisifiedClosure(callback, receiver2, _2, fn, __, multiArgs) { var defaultThis = /* @__PURE__ */ (function() { return this; })(); @@ -42132,9 +43272,9 @@ var require_promisify = __commonJS({ return promisified; } var makeNodePromisified = canEvaluate2 ? makeNodePromisifiedEval : makeNodePromisifiedClosure; - function promisifyAll(obj2, suffix, filter2, promisifier, multiArgs) { + function promisifyAll(obj2, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods19 = promisifiableMethods(obj2, suffix, suffixRegexp, filter2); + var methods19 = promisifiableMethods(obj2, suffix, suffixRegexp, filter); for (var i6 = 0, len = methods19.length; i6 < len; i6 += 2) { var key = methods19[i6]; var fn = methods19[i6 + 1]; @@ -42191,8 +43331,8 @@ var require_promisify = __commonJS({ var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; - var filter2 = options.filter; - if (typeof filter2 !== "function") filter2 = defaultFilter; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util17.isIdentifier(suffix)) { @@ -42205,14 +43345,14 @@ var require_promisify = __commonJS({ promisifyAll( value.prototype, suffix, - filter2, + filter, promisifier, multiArgs ); - promisifyAll(value, suffix, filter2, promisifier, multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); } } - return promisifyAll(target, suffix, filter2, promisifier, multiArgs); + return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; } @@ -42453,8 +43593,8 @@ var require_reduce = __commonJS({ i6 = 1; } this._currentCancellable = value; - for (var j6 = i6; j6 < length; ++j6) { - var maybePromise = values[j6]; + for (var j7 = i6; j7 < length; ++j7) { + var maybePromise = values[j7]; if (maybePromise instanceof Promise2) { maybePromise.suppressUnhandledRejections(); } @@ -42733,11 +43873,11 @@ var require_timers2 = __commonJS({ var afterValue = function(value) { return delay(+this).thenReturn(value); }; - var delay = Promise2.delay = function(ms, value) { + var delay = Promise2.delay = function(ms2, value) { var ret2; var handle; if (value !== void 0) { - ret2 = Promise2.resolve(value)._then(afterValue, null, null, ms, void 0); + ret2 = Promise2.resolve(value)._then(afterValue, null, null, ms2, void 0); if (debug2.cancellation() && value instanceof Promise2) { ret2._setOnCancel(value); } @@ -42745,7 +43885,7 @@ var require_timers2 = __commonJS({ ret2 = new Promise2(INTERNAL); handle = setTimeout(function() { ret2._fulfill(); - }, +ms); + }, +ms2); if (debug2.cancellation()) { ret2._setOnCancel(new HandleWrapper(handle)); } @@ -42754,8 +43894,8 @@ var require_timers2 = __commonJS({ ret2._setAsyncGuaranteed(); return ret2; }; - Promise2.prototype.delay = function(ms) { - return delay(ms, this); + Promise2.prototype.delay = function(ms2) { + return delay(ms2, this); }; var afterTimeout = function(promise, message, parent) { var err; @@ -42783,14 +43923,14 @@ var require_timers2 = __commonJS({ clearTimeout(this.handle); throw reason; } - Promise2.prototype.timeout = function(ms, message) { - ms = +ms; + Promise2.prototype.timeout = function(ms2, message) { + ms2 = +ms2; var ret2, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret2.isPending()) { afterTimeout(ret2, message, parent); } - }, ms)); + }, ms2)); if (debug2.cancellation()) { parent = this.then(); ret2 = parent._then( @@ -43210,16 +44350,16 @@ var require_promise = __commonJS({ Promise2.prototype.caught = Promise2.prototype["catch"] = function(fn) { var len = arguments.length; if (len > 1) { - var catchInstances = new Array(len - 1), j6 = 0, i6; + var catchInstances = new Array(len - 1), j7 = 0, i6; for (i6 = 0; i6 < len - 1; ++i6) { var item = arguments[i6]; if (util17.isObject(item)) { - catchInstances[j6++] = item; + catchInstances[j7++] = item; } else { return apiRejection("Catch statement predicate: expecting an object but got " + util17.classString(item)); } } - catchInstances.length = j6; + catchInstances.length = j7; fn = arguments[i6]; if (typeof fn !== "function") { throw new TypeError2("The last argument to .catch() must be a function, got " + util17.toString(fn)); @@ -43323,7 +44463,7 @@ var require_promise = __commonJS({ } return async.setScheduler(fn); }; - Promise2.prototype._then = function(didFulfill, didReject, _, receiver2, internalData) { + Promise2.prototype._then = function(didFulfill, didReject, _2, receiver2, internalData) { var haveInternalData = internalData !== void 0; var promise = haveInternalData ? internalData : new Promise2(INTERNAL); var target = this._target(); @@ -43553,27 +44693,27 @@ var require_promise = __commonJS({ var bitField = promise._bitField; if ((bitField & 65536) !== 0) return; promise._pushContext(); - var x7; + var x8; if (receiver2 === APPLY) { if (!value || typeof value.length !== "number") { - x7 = errorObj2; - x7.e = new TypeError2("cannot .spread() a non-array: " + util17.classString(value)); + x8 = errorObj2; + x8.e = new TypeError2("cannot .spread() a non-array: " + util17.classString(value)); } else { - x7 = tryCatch2(handler2).apply(this._boundValue(), value); + x8 = tryCatch2(handler2).apply(this._boundValue(), value); } } else { - x7 = tryCatch2(handler2).call(receiver2, value); + x8 = tryCatch2(handler2).call(receiver2, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if ((bitField & 65536) !== 0) return; - if (x7 === NEXT_FILTER) { + if (x8 === NEXT_FILTER) { promise._reject(value); - } else if (x7 === errorObj2) { - promise._rejectCallback(x7.e, false); + } else if (x8 === errorObj2) { + promise._rejectCallback(x8.e, false); } else { - debug2.checkForgottenReturns(x7, promiseCreated, "", promise, this); - promise._resolveCallback(x7); + debug2.checkForgottenReturns(x8, promiseCreated, "", promise, this); + promise._resolveCallback(x8); } }; Promise2.prototype._target = function() { @@ -43743,11 +44883,11 @@ var require_promise = __commonJS({ } }); } - function deferResolve(v7) { - this.promise._resolveCallback(v7); + function deferResolve(v8) { + this.promise._resolveCallback(v8); } - function deferReject(v7) { - this.promise._rejectCallback(v7, false); + function deferReject(v8) { + this.promise._rejectCallback(v8, false); } Promise2.defer = Promise2.pending = function() { debug2.deprecated("Promise.defer", "new Promise"); @@ -43922,13 +45062,13 @@ var require_omggif = __commonJS({ buf[p6++] = 0; } var ended = false; - this.addFrame = function(x7, y4, w6, h6, indexed_pixels, opts) { + this.addFrame = function(x8, y4, w6, h6, indexed_pixels, opts) { if (ended === true) { --p6; ended = false; } opts = opts === void 0 ? {} : opts; - if (x7 < 0 || y4 < 0 || x7 > 65535 || y4 > 65535) + if (x8 < 0 || y4 < 0 || x8 > 65535 || y4 > 65535) throw new Error("x/y invalid."); if (w6 <= 0 || h6 <= 0 || w6 > 65535 || h6 > 65535) throw new Error("Width/Height invalid."); @@ -43969,8 +45109,8 @@ var require_omggif = __commonJS({ buf[p6++] = 0; } buf[p6++] = 44; - buf[p6++] = x7 & 255; - buf[p6++] = x7 >> 8 & 255; + buf[p6++] = x8 & 255; + buf[p6++] = x8 >> 8 & 255; buf[p6++] = y4 & 255; buf[p6++] = y4 >> 8 & 255; buf[p6++] = w6 & 255; @@ -44004,14 +45144,14 @@ var require_omggif = __commonJS({ this.getOutputBuffer = function() { return buf; }; - this.setOutputBuffer = function(v7) { - buf = v7; + this.setOutputBuffer = function(v8) { + buf = v8; }; this.getOutputBufferPosition = function() { return p6; }; - this.setOutputBufferPosition = function(v7) { - p6 = v7; + this.setOutputBufferPosition = function(v8) { + p6 = v8; }; } function GifWriterOutputLZWCodeStream(buf, p6, min_code_size, index_stream) { @@ -44044,8 +45184,8 @@ var require_omggif = __commonJS({ var code_table = {}; emit_code(clear_code); for (var i6 = 1, il = index_stream.length; i6 < il; ++i6) { - var k6 = index_stream[i6] & code_mask; - var cur_key = ib_code << 8 | k6; + var k7 = index_stream[i6] & code_mask; + var cur_key = ib_code << 8 | k7; var cur_code = code_table[cur_key]; if (cur_code === void 0) { cur |= ib_code << cur_shift; @@ -44068,7 +45208,7 @@ var require_omggif = __commonJS({ if (next_code >= 1 << cur_code_size) ++cur_code_size; code_table[cur_key] = next_code++; } - ib_code = k6; + ib_code = k7; } else { ib_code = cur_code; } @@ -44159,7 +45299,7 @@ var require_omggif = __commonJS({ } break; case 44: - var x7 = buf[p6++] | buf[p6++] << 8; + var x8 = buf[p6++] | buf[p6++] << 8; var y4 = buf[p6++] | buf[p6++] << 8; var w6 = buf[p6++] | buf[p6++] << 8; var h6 = buf[p6++] | buf[p6++] << 8; @@ -44186,7 +45326,7 @@ var require_omggif = __commonJS({ p6 += block_size; } frames.push({ - x: x7, + x: x8, y: y4, width: w6, height: h6, @@ -44364,17 +45504,17 @@ var require_omggif = __commonJS({ chase = code_table[chase] >> 8; ++chase_length; } - var k6 = chase; + var k7 = chase; var op_end = op + chase_length + (chase_code !== code ? 1 : 0); if (op_end > output_length) { console.log("Warning, gif stream longer than expected."); return; } - output[op++] = k6; + output[op++] = k7; op += chase_length; var b6 = op; if (chase_code !== code) - output[op++] = k6; + output[op++] = k7; chase = chase_code; while (chase_length--) { chase = code_table[chase]; @@ -44382,7 +45522,7 @@ var require_omggif = __commonJS({ chase >>= 8; } if (prev_code !== null && next_code < 4096) { - code_table[next_code++] = prev_code << 8 | k6; + code_table[next_code++] = prev_code << 8 | k7; if (next_code >= code_mask + 1 && cur_code_size < 12) { ++cur_code_size; code_mask = code_mask << 1 | 1; @@ -44492,12 +45632,12 @@ var require_bitmapimage = __commonJS({ const sourceByteWidth = this.bitmap.width * 4; const targetByteWidth = toImage.bitmap.width * 4; const copyByteWidth = fromWidth * 4; - let si = fromY * sourceByteWidth + fromX * 4; - let ti = toY * targetByteWidth + toX * 4; + let si2 = fromY * sourceByteWidth + fromX * 4; + let ti2 = toY * targetByteWidth + toX * 4; while (--fromHeight >= 0) { - sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth); - si += sourceByteWidth; - ti += targetByteWidth; + sourceBuf.copy(targetBuf, ti2, si2, si2 + copyByteWidth); + si2 += sourceByteWidth; + ti2 += targetByteWidth; } return this; } @@ -44510,14 +45650,14 @@ var require_bitmapimage = __commonJS({ fillRGBA(rgba) { const buf = this.bitmap.data; const bufByteWidth = this.bitmap.height * 4; - let bi2 = 0; - while (bi2 < bufByteWidth) { - buf.writeUInt32BE(rgba, bi2); - bi2 += 4; + let bi3 = 0; + while (bi3 < bufByteWidth) { + buf.writeUInt32BE(rgba, bi3); + bi3 += 4; } - while (bi2 < buf.length) { - buf.copy(buf, bi2, 0, bufByteWidth); - bi2 += bufByteWidth; + while (bi3 < buf.length) { + buf.copy(buf, bi3, 0, bufByteWidth); + bi3 += bufByteWidth; } return this; } @@ -44528,9 +45668,9 @@ var require_bitmapimage = __commonJS({ * @param {number} y y-coord of pixel * @return {number} RGBA of pixel in 0xRRGGBBAA form */ - getRGBA(x7, y4) { - const bi2 = (y4 * this.bitmap.width + x7) * 4; - return this.bitmap.data.readUInt32BE(bi2); + getRGBA(x8, y4) { + const bi3 = (y4 * this.bitmap.width + x8) * 4; + return this.bitmap.data.readUInt32BE(bi3); } /** * Gets a set of all RGBA colors found within the image. @@ -44540,8 +45680,8 @@ var require_bitmapimage = __commonJS({ getRGBASet() { const rgbaSet = /* @__PURE__ */ new Set(); const buf = this.bitmap.data; - for (let bi2 = 0; bi2 < buf.length; bi2 += 4) { - rgbaSet.add(buf.readUInt32BE(bi2, true)); + for (let bi3 = 0; bi3 < buf.length; bi3 += 4) { + rgbaSet.add(buf.readUInt32BE(bi3, true)); } return rgbaSet; } @@ -44552,7 +45692,7 @@ var require_bitmapimage = __commonJS({ */ greyscale() { const buf = this.bitmap.data; - this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x7, y4, idx) => { + this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x8, y4, idx) => { const grey = Math.round( 0.299 * buf[idx] + 0.587 * buf[idx + 1] + 0.114 * buf[idx + 2] ); @@ -44615,7 +45755,7 @@ var require_bitmapimage = __commonJS({ let destIndex = 0; for (let y4 = 0; y4 < sourceHeight; ++y4) { priorDestRowIndex = destIndex; - for (let x7 = 0; x7 < sourceWidth; ++x7) { + for (let x8 = 0; x8 < sourceWidth; ++x8) { const color = sourceBuf.readUInt32BE(sourceIndex, true); for (let cx2 = 0; cx2 < factor; ++cx2) { destBuf.writeUInt32BE(color, destIndex); @@ -44645,12 +45785,12 @@ var require_bitmapimage = __commonJS({ scanAllCoords(scanHandler) { const width = this.bitmap.width; const bufferLength = this.bitmap.data.length; - let x7 = 0; + let x8 = 0; let y4 = 0; - for (let bi2 = 0; bi2 < bufferLength; bi2 += 4) { - scanHandler(x7, y4, bi2); - if (++x7 === width) { - x7 = 0; + for (let bi3 = 0; bi3 < bufferLength; bi3 += 4) { + scanHandler(x8, y4, bi3); + if (++x8 === width) { + x8 = 0; ++y4; } } @@ -44663,8 +45803,8 @@ var require_bitmapimage = __commonJS({ */ scanAllIndexes(scanHandler) { const bufferLength = this.bitmap.data.length; - for (let bi2 = 0; bi2 < bufferLength; bi2 += 4) { - scanHandler(bi2); + for (let bi3 = 0; bi3 < bufferLength; bi3 += 4) { + scanHandler(bi3); } } }; @@ -44785,24 +45925,24 @@ var require_image_q = __commonJS({ }); var bt709_exports2 = {}; __export3(bt709_exports2, { - Y: () => Y3, - x: () => x7, + Y: () => Y4, + x: () => x8, y: () => y4 }); - var Y3 = /* @__PURE__ */ ((Y22) => { + var Y4 = /* @__PURE__ */ ((Y22) => { Y22[Y22["RED"] = 0.2126] = "RED"; Y22[Y22["GREEN"] = 0.7152] = "GREEN"; Y22[Y22["BLUE"] = 0.0722] = "BLUE"; Y22[Y22["WHITE"] = 1] = "WHITE"; return Y22; - })(Y3 || {}); - var x7 = /* @__PURE__ */ ((x22) => { + })(Y4 || {}); + var x8 = /* @__PURE__ */ ((x22) => { x22[x22["RED"] = 0.64] = "RED"; x22[x22["GREEN"] = 0.3] = "GREEN"; x22[x22["BLUE"] = 0.15] = "BLUE"; x22[x22["WHITE"] = 0.3127] = "WHITE"; return x22; - })(x7 || {}); + })(x8 || {}); var y4 = /* @__PURE__ */ ((y22) => { y22[y22["RED"] = 0.33] = "RED"; y22[y22["GREEN"] = 0.6] = "GREEN"; @@ -44820,8 +45960,8 @@ var require_image_q = __commonJS({ xyz2lab: () => xyz2lab2, xyz2rgb: () => xyz2rgb2 }); - function correctGamma3(n6) { - return n6 > 0.04045 ? ((n6 + 0.055) / 1.055) ** 2.4 : n6 / 12.92; + function correctGamma3(n12) { + return n12 > 0.04045 ? ((n12 + 0.055) / 1.055) ** 2.4 : n12 / 12.92; } function rgb2xyz2(r6, g6, b6) { r6 = correctGamma3(r6 / 255); @@ -44843,8 +45983,8 @@ var require_image_q = __commonJS({ min3: () => min32, stableSort: () => stableSort2 }); - function degrees2radians2(n6) { - return n6 * (Math.PI / 180); + function degrees2radians2(n12) { + return n12 * (Math.PI / 180); } function max32(a6, b6, c7) { let m6 = a6; @@ -44869,20 +46009,20 @@ var require_image_q = __commonJS({ value = low; return value | 0; } - function inRange0to255Rounded2(n6) { - n6 = Math.round(n6); - if (n6 > 255) - n6 = 255; - else if (n6 < 0) - n6 = 0; - return n6; - } - function inRange0to2552(n6) { - if (n6 > 255) - n6 = 255; - else if (n6 < 0) - n6 = 0; - return n6; + function inRange0to255Rounded2(n12) { + n12 = Math.round(n12); + if (n12 > 255) + n12 = 255; + else if (n12 < 0) + n12 = 0; + return n12; + } + function inRange0to2552(n12) { + if (n12 > 255) + n12 = 255; + else if (n12 < 0) + n12 = 0; + return n12; } function stableSort2(arrayToSort, callback) { const type = typeof arrayToSort[0]; @@ -44928,8 +46068,8 @@ var require_image_q = __commonJS({ var refX3 = 0.95047; var refY3 = 1; var refZ3 = 1.08883; - function pivot3(n6) { - return n6 > 8856e-6 ? n6 ** (1 / 3) : 7.787 * n6 + 16 / 116; + function pivot3(n12) { + return n12 > 8856e-6 ? n12 ** (1 / 3) : 7.787 * n12 + 16 / 116; } function xyz2lab2(x22, y22, z3) { x22 = pivot3(x22 / refX3); @@ -44950,11 +46090,11 @@ var require_image_q = __commonJS({ var refX22 = 0.95047; var refY22 = 1; var refZ22 = 1.08883; - function pivot22(n6) { - return n6 > 0.206893034 ? n6 ** 3 : (n6 - 16 / 116) / 7.787; + function pivot22(n12) { + return n12 > 0.206893034 ? n12 ** 3 : (n12 - 16 / 116) / 7.787; } - function lab2xyz2(L2, a6, b6) { - const y22 = (L2 + 16) / 116; + function lab2xyz2(L3, a6, b6) { + const y22 = (L3 + 16) / 116; const x22 = a6 / 500 + y22; const z3 = y22 - b6 / 200; return { @@ -44963,8 +46103,8 @@ var require_image_q = __commonJS({ z: refZ22 * pivot22(z3) }; } - function correctGamma22(n6) { - return n6 > 31308e-7 ? 1.055 * n6 ** (1 / 2.4) - 0.055 : 12.92 * n6; + function correctGamma22(n12) { + return n12 > 31308e-7 ? 1.055 * n12 ** (1 / 2.4) - 0.055 : 12.92 * n12; } function xyz2rgb2(x22, y22, z3) { const r6 = correctGamma22(x22 * 3.2406 + y22 * -1.5372 + z3 * -0.4986); @@ -44976,8 +46116,8 @@ var require_image_q = __commonJS({ b: inRange0to255Rounded2(b6 * 255) }; } - function lab2rgb2(L2, a6, b6) { - const xyz = lab2xyz2(L2, a6, b6); + function lab2rgb2(L3, a6, b6) { + const xyz = lab2xyz2(L3, a6, b6); return xyz2rgb2(xyz.x, xyz.y, xyz.z); } var distance_exports2 = {}; @@ -45102,31 +46242,31 @@ var require_image_q = __commonJS({ const L1 = Lab1.L; const a1 = Lab1.a; const b1 = Lab1.b; - const L2 = Lab2.L; + const L22 = Lab2.L; const a22 = Lab2.a; const b22 = Lab2.b; const C1 = Math.sqrt(a1 * a1 + b1 * b1); const C22 = Math.sqrt(a22 * a22 + b22 * b22); const pow_a_C1_C2_to_7 = ((C1 + C22) / 2) ** 7; - const G3 = 0.5 * (1 - Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + _CIEDE20002._pow25to7))); - const a1p = (1 + G3) * a1; - const a2p = (1 + G3) * a22; + const G4 = 0.5 * (1 - Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + _CIEDE20002._pow25to7))); + const a1p = (1 + G4) * a1; + const a2p = (1 + G4) * a22; const C1p = Math.sqrt(a1p * a1p + b1 * b1); const C2p = Math.sqrt(a2p * a2p + b22 * b22); const C1pC2p = C1p * C2p; const h1p = _CIEDE20002._calculatehp(b1, a1p); const h2p = _CIEDE20002._calculatehp(b22, a2p); const h_bar = Math.abs(h1p - h2p); - const dLp = L2 - L1; + const dLp = L22 - L1; const dCp = C2p - C1p; const dHp = _CIEDE20002._calculate_dHp(C1pC2p, h_bar, h2p, h1p); const ahp = _CIEDE20002._calculate_ahp(C1pC2p, h_bar, h1p, h2p); - const T2 = _CIEDE20002._calculateT(ahp); + const T3 = _CIEDE20002._calculateT(ahp); const aCp = (C1p + C2p) / 2; - const aLp_minus_50_square = ((L1 + L2) / 2 - 50) ** 2; + const aLp_minus_50_square = ((L1 + L22) / 2 - 50) ** 2; const S_L = 1 + 0.015 * aLp_minus_50_square / Math.sqrt(20 + aLp_minus_50_square); const S_C = 1 + 0.045 * aCp; - const S_H = 1 + 0.015 * T2 * aCp; + const S_H = 1 + 0.015 * T3 * aCp; const R_T = _CIEDE20002._calculateRT(ahp, aCp); const dLpSL = dLp / S_L; const dCpSC = dCp / S_C; @@ -45728,8 +46868,8 @@ var require_image_q = __commonJS({ rad = radius >> _NeuQuant2._radiusBiasShift; if (rad <= 1) rad = 0; - for (let j6 = 0; j6 < rad; j6++) { - this._radPower[j6] = alpha * ((rad * rad - j6 * j6) * _NeuQuant2._radBias / (rad * rad)) >>> 0; + for (let j7 = 0; j7 < rad; j7++) { + this._radPower[j7] = alpha * ((rad * rad - j7 * j7) * _NeuQuant2._radBias / (rad * rad)) >>> 0; } } } @@ -45746,28 +46886,28 @@ var require_image_q = __commonJS({ let lo = i6 - rad; if (lo < -1) lo = -1; - let hi = i6 + rad; - if (hi > this._networkSize) - hi = this._networkSize; - let j6 = i6 + 1; - let k6 = i6 - 1; + let hi2 = i6 + rad; + if (hi2 > this._networkSize) + hi2 = this._networkSize; + let j7 = i6 + 1; + let k7 = i6 - 1; let m6 = 1; - while (j6 < hi || k6 > lo) { + while (j7 < hi2 || k7 > lo) { const a6 = this._radPower[m6++] / _NeuQuant2._alphaRadBias; - if (j6 < hi) { - const p6 = this._network[j6++]; + if (j7 < hi2) { + const p6 = this._network[j7++]; p6.subtract(a6 * (p6.r - r6), a6 * (p6.g - g6), a6 * (p6.b - b6), a6 * (p6.a - al2)); } - if (k6 > lo) { - const p6 = this._network[k6--]; + if (k7 > lo) { + const p6 = this._network[k7--]; p6.subtract(a6 * (p6.r - r6), a6 * (p6.g - g6), a6 * (p6.b - b6), a6 * (p6.a - al2)); } } } _alterSingle(alpha, i6, b6, g6, r6, a6) { alpha /= _NeuQuant2._initAlpha; - const n6 = this._network[i6]; - n6.subtract(alpha * (n6.r - r6), alpha * (n6.g - g6), alpha * (n6.b - b6), alpha * (n6.a - a6)); + const n12 = this._network[i6]; + n12.subtract(alpha * (n12.r - r6), alpha * (n12.g - g6), alpha * (n12.b - b6), alpha * (n12.a - a6)); } _contest(b6, g6, r6, a6) { const multiplier = 255 * 4 << networkBiasShift3; @@ -45776,8 +46916,8 @@ var require_image_q = __commonJS({ let bestpos = -1; let bestbiaspos = bestpos; for (let i6 = 0; i6 < this._networkSize; i6++) { - const n6 = this._network[i6]; - const dist = this._distance.calculateNormalized(n6, { r: r6, g: g6, b: b6, a: a6 }) * multiplier | 0; + const n12 = this._network[i6]; + const dist = this._distance.calculateNormalized(n12, { r: r6, g: g6, b: b6, a: a6 }) * multiplier | 0; if (dist < bestd) { bestd = dist; bestpos = i6; @@ -45932,8 +47072,8 @@ var require_image_q = __commonJS({ rad = radius >> _NeuQuantFloat2._radiusBiasShift; if (rad <= 1) rad = 0; - for (let j6 = 0; j6 < rad; j6++) { - this._radPower[j6] = alpha * ((rad * rad - j6 * j6) * _NeuQuantFloat2._radBias / (rad * rad)); + for (let j7 = 0; j7 < rad; j7++) { + this._radPower[j7] = alpha * ((rad * rad - j7 * j7) * _NeuQuantFloat2._radBias / (rad * rad)); } } } @@ -45950,28 +47090,28 @@ var require_image_q = __commonJS({ let lo = i6 - rad; if (lo < -1) lo = -1; - let hi = i6 + rad; - if (hi > this._networkSize) - hi = this._networkSize; - let j6 = i6 + 1; - let k6 = i6 - 1; + let hi2 = i6 + rad; + if (hi2 > this._networkSize) + hi2 = this._networkSize; + let j7 = i6 + 1; + let k7 = i6 - 1; let m6 = 1; - while (j6 < hi || k6 > lo) { + while (j7 < hi2 || k7 > lo) { const a6 = this._radPower[m6++] / _NeuQuantFloat2._alphaRadBias; - if (j6 < hi) { - const p6 = this._network[j6++]; + if (j7 < hi2) { + const p6 = this._network[j7++]; p6.subtract(a6 * (p6.r - r6), a6 * (p6.g - g6), a6 * (p6.b - b6), a6 * (p6.a - al2)); } - if (k6 > lo) { - const p6 = this._network[k6--]; + if (k7 > lo) { + const p6 = this._network[k7--]; p6.subtract(a6 * (p6.r - r6), a6 * (p6.g - g6), a6 * (p6.b - b6), a6 * (p6.a - al2)); } } } _alterSingle(alpha, i6, b6, g6, r6, a6) { alpha /= _NeuQuantFloat2._initAlpha; - const n6 = this._network[i6]; - n6.subtract(alpha * (n6.r - r6), alpha * (n6.g - g6), alpha * (n6.b - b6), alpha * (n6.a - a6)); + const n12 = this._network[i6]; + n12.subtract(alpha * (n12.r - r6), alpha * (n12.g - g6), alpha * (n12.b - b6), alpha * (n12.a - a6)); } _contest(b6, g6, r6, al2) { const multiplier = 255 * 4 << networkBiasShift22; @@ -45980,8 +47120,8 @@ var require_image_q = __commonJS({ let bestpos = -1; let bestbiaspos = bestpos; for (let i6 = 0; i6 < this._networkSize; i6++) { - const n6 = this._network[i6]; - const dist = this._distance.calculateNormalized(n6, { r: r6, g: g6, b: b6, a: al2 }) * multiplier; + const n12 = this._network[i6]; + const dist = this._distance.calculateNormalized(n12, { r: r6, g: g6, b: b6, a: al2 }) * multiplier; if (dist < bestd) { bestd = dist; bestpos = i6; @@ -46070,7 +47210,7 @@ var require_image_q = __commonJS({ default: throw new Error("Incorrect method"); } - return idxi32.map((v7) => +v7); + return idxi32.map((v8) => +v8); } _colorStats1D(pointContainer) { const histG = this._histogram; @@ -46209,14 +47349,14 @@ var require_image_q = __commonJS({ if (usageArray[i6] === 0) continue; const pxi = colorArray[i6]; - for (let j6 = i6 + 1; j6 < len; j6++) { - if (usageArray[j6] === 0) + for (let j7 = i6 + 1; j7 < len; j7++) { + if (usageArray[j7] === 0) continue; - const pxj = colorArray[j6]; + const pxj = colorArray[j7]; const dist = this._distance.calculateNormalized(pxi, pxj); if (dist < thold) { - memDist.push(new RemovedColor2(j6, pxj, dist)); - usageArray[j6] = 0; + memDist.push(new RemovedColor2(j7, pxj, dist)); + usageArray[j7] = 0; palLen--; } } @@ -46225,12 +47365,12 @@ var require_image_q = __commonJS({ } if (palLen < this._colors) { stableSort2(memDist, (a6, b6) => b6.distance - a6.distance); - let k6 = 0; - while (palLen < this._colors && k6 < memDist.length) { - const removedColor = memDist[k6]; + let k7 = 0; + while (palLen < this._colors && k7 < memDist.length) { + const removedColor = memDist[k7]; usageArray[removedColor.index] = 1; palLen++; - k6++; + k7++; } } let colors = colorArray.length; @@ -46252,8 +47392,8 @@ var require_image_q = __commonJS({ }; function createArray1D2(dimension1) { const a6 = []; - for (let k6 = 0; k6 < dimension1; k6++) { - a6[k6] = 0; + for (let k7 = 0; k7 < dimension1; k7++) { + a6[k7] = 0; } return a6; } @@ -46261,12 +47401,12 @@ var require_image_q = __commonJS({ const a6 = new Array(dimension1); for (let i6 = 0; i6 < dimension1; i6++) { a6[i6] = new Array(dimension2); - for (let j6 = 0; j6 < dimension2; j6++) { - a6[i6][j6] = new Array(dimension3); - for (let k6 = 0; k6 < dimension3; k6++) { - a6[i6][j6][k6] = new Array(dimension4); + for (let j7 = 0; j7 < dimension2; j7++) { + a6[i6][j7] = new Array(dimension3); + for (let k7 = 0; k7 < dimension3; k7++) { + a6[i6][j7][k7] = new Array(dimension4); for (let l6 = 0; l6 < dimension4; l6++) { - a6[i6][j6][k6][l6] = 0; + a6[i6][j7][k7][l6] = 0; } } } @@ -46277,10 +47417,10 @@ var require_image_q = __commonJS({ const a6 = new Array(dimension1); for (let i6 = 0; i6 < dimension1; i6++) { a6[i6] = new Array(dimension2); - for (let j6 = 0; j6 < dimension2; j6++) { - a6[i6][j6] = new Array(dimension3); - for (let k6 = 0; k6 < dimension3; k6++) { - a6[i6][j6][k6] = 0; + for (let j7 = 0; j7 < dimension2; j7++) { + a6[i6][j7] = new Array(dimension3); + for (let k7 = 0; k7 < dimension3; k7++) { + a6[i6][j7][k7] = 0; } } } @@ -46289,10 +47429,10 @@ var require_image_q = __commonJS({ function fillArray3D2(a6, dimension1, dimension2, dimension3, value) { for (let i6 = 0; i6 < dimension1; i6++) { a6[i6] = []; - for (let j6 = 0; j6 < dimension2; j6++) { - a6[i6][j6] = []; - for (let k6 = 0; k6 < dimension3; k6++) { - a6[i6][j6][k6] = value; + for (let j7 = 0; j7 < dimension2; j7++) { + a6[i6][j7] = []; + for (let k7 = 0; k7 < dimension3; k7++) { + a6[i6][j7][k7] = value; } } } @@ -46399,18 +47539,18 @@ var require_image_q = __commonJS({ const lookupGreen = []; const lookupBlue = []; const lookupAlpha = []; - for (let k6 = 0; k6 < this._colors; ++k6) { - const weight = _WuQuant2._volume(this._cubes[k6], this._weights); + for (let k7 = 0; k7 < this._colors; ++k7) { + const weight = _WuQuant2._volume(this._cubes[k7], this._weights); if (weight > 0) { - lookupRed[k6] = _WuQuant2._volume(this._cubes[k6], this._momentsRed) / weight | 0; - lookupGreen[k6] = _WuQuant2._volume(this._cubes[k6], this._momentsGreen) / weight | 0; - lookupBlue[k6] = _WuQuant2._volume(this._cubes[k6], this._momentsBlue) / weight | 0; - lookupAlpha[k6] = _WuQuant2._volume(this._cubes[k6], this._momentsAlpha) / weight | 0; + lookupRed[k7] = _WuQuant2._volume(this._cubes[k7], this._momentsRed) / weight | 0; + lookupGreen[k7] = _WuQuant2._volume(this._cubes[k7], this._momentsGreen) / weight | 0; + lookupBlue[k7] = _WuQuant2._volume(this._cubes[k7], this._momentsBlue) / weight | 0; + lookupAlpha[k7] = _WuQuant2._volume(this._cubes[k7], this._momentsAlpha) / weight | 0; } else { - lookupRed[k6] = 0; - lookupGreen[k6] = 0; - lookupBlue[k6] = 0; - lookupAlpha[k6] = 0; + lookupRed[k7] = 0; + lookupGreen[k7] = 0; + lookupBlue[k7] = 0; + lookupAlpha[k7] = 0; } } this._reds = createArray1D2(this._colors + 1); @@ -46420,8 +47560,8 @@ var require_image_q = __commonJS({ this._sums = createArray1D2(this._colors + 1); for (let index = 0, l6 = this._pixels.length; index < l6; index++) { const color = this._pixels[index]; - const match2 = -1; - let bestMatch = match2; + const match = -1; + let bestMatch = match; let bestDistance = Number.MAX_VALUE; for (let lookup = 0; lookup < this._colors; lookup++) { const foundRed = lookupRed[lookup]; @@ -47241,18 +48381,18 @@ var require_image_q = __commonJS({ ssim: () => ssim2 }); var K12 = 0.01; - var K22 = 0.03; + var K23 = 0.03; function ssim2(image1, image2) { if (image1.getHeight() !== image2.getHeight() || image1.getWidth() !== image2.getWidth()) { throw new Error("Images have different sizes!"); } const bitsPerComponent = 8; - const L2 = (1 << bitsPerComponent) - 1; - const c1 = (K12 * L2) ** 2; - const c22 = (K22 * L2) ** 2; + const L3 = (1 << bitsPerComponent) - 1; + const c1 = (K12 * L3) ** 2; + const c22 = (K23 * L3) ** 2; let numWindows = 0; let mssim = 0; - iterate3(image1, image2, (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => { + iterate2(image1, image2, (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => { let sigxy = 0; let sigsqx = 0; let sigsqy = 0; @@ -47273,7 +48413,7 @@ var require_image_q = __commonJS({ }); return mssim / numWindows; } - function iterate3(image1, image2, callback) { + function iterate2(image1, image2, callback) { const windowSize = 8; const width = image1.getWidth(); const height = image1.getHeight(); @@ -47293,8 +48433,8 @@ var require_image_q = __commonJS({ const pointArray = image2.getPointArray(); const lumaValues = []; let counter = 0; - for (let j6 = y22; j6 < y22 + height; j6++) { - const offset = j6 * image2.getWidth(); + for (let j7 = y22; j7 < y22 + height; j7++) { + const offset = j7 * image2.getWidth(); for (let i6 = x22; i6 < x22 + width; i6++) { const point = pointArray[offset + i6]; lumaValues[counter] = point.r * 0.2126 + point.g * 0.7152 + point.b * 0.0722; @@ -47604,7 +48744,7 @@ var require_gifframe = __commonJS({ var require_gifutil = __commonJS({ "../node_modules/gifwrap/src/gifutil.js"(exports2) { "use strict"; - var fs6 = require("fs"); + var fs7 = require("fs"); var ImageQ = require_image_q(); var BitmapImage2 = require_bitmapimage(); var { GifFrame: GifFrame2 } = require_gifframe(); @@ -47719,14 +48859,14 @@ var require_gifutil = __commonJS({ jimpImage.bitmap.data = bitmapImageToShare.bitmap.data; return jimpImage; }; - exports2.write = function(path7, frames, spec, encoder) { + exports2.write = function(path6, frames, spec, encoder) { encoder = encoder || defaultCodec; - const matches = path7.match(/\.[a-zA-Z]+$/); + const matches = path6.match(/\.[a-zA-Z]+$/); if (matches !== null && INVALID_SUFFIXES.includes(matches[0].toLowerCase())) { - throw new Error(`GIF '${path7}' has an unexpected suffix`); + throw new Error(`GIF '${path6}' has an unexpected suffix`); } return encoder.encodeGif(frames, spec).then((gif2) => { - return _writeBinary(path7, gif2.buffer).then(() => { + return _writeBinary(path6, gif2.buffer).then(() => { return gif2; }); }); @@ -47777,8 +48917,8 @@ var require_gifutil = __commonJS({ const imageBuf = image2.bitmap.data; const inputBuf = new ArrayBuffer(imageBuf.length); const inputArray = new Uint32Array(inputBuf); - for (let bi2 = 0, ai2 = 0; bi2 < imageBuf.length; bi2 += 4, ++ai2) { - inputArray[ai2] = imageBuf.readUInt32LE(bi2, true); + for (let bi3 = 0, ai3 = 0; bi3 < imageBuf.length; bi3 += 4, ++ai3) { + inputArray[ai3] = imageBuf.readUInt32LE(bi3, true); } const inputContainer = ImageQ.utils.PointContainer.fromUint32Array( inputArray, @@ -47793,14 +48933,14 @@ var require_gifutil = __commonJS({ const imageBuf = images[i6].bitmap.data; const outputContainer = imageMaker.quantizeSync(inputContainers[i6], limitedPalette); const outputArray = outputContainer.toUint32Array(); - for (let bi2 = 0, ai2 = 0; bi2 < imageBuf.length; bi2 += 4, ++ai2) { - imageBuf.writeUInt32LE(outputArray[ai2], bi2); + for (let bi3 = 0, ai3 = 0; bi3 < imageBuf.length; bi3 += 4, ++ai3) { + imageBuf.writeUInt32LE(outputArray[ai3], bi3); } } } - function _readBinary(path7) { + function _readBinary(path6) { return new Promise((resolve3, reject2) => { - fs6.readFile(path7, (err, buffer) => { + fs7.readFile(path6, (err, buffer) => { if (err) { return reject2(err); } @@ -47808,9 +48948,9 @@ var require_gifutil = __commonJS({ }); }); } - function _writeBinary(path7, buffer) { + function _writeBinary(path6, buffer) { return new Promise((resolve3, reject2) => { - fs6.writeFile(path7, buffer, (err) => { + fs7.writeFile(path6, buffer, (err) => { if (err) { return reject2(err); } @@ -47927,12 +49067,12 @@ var require_gifcodec = __commonJS({ buffer = buffer.slice(info2.y * reader.width * 4); } if (reader.width > info2.width) { - for (let ii = 0; ii < info2.height; ++ii) { + for (let ii2 = 0; ii2 < info2.height; ++ii2) { buffer.copy( buffer, - ii * info2.width * 4, - (info2.x + ii * reader.width) * 4, - (info2.x + ii * reader.width) * 4 + info2.width * 4 + ii2 * info2.width * 4, + (info2.x + ii2 * reader.width) * 4, + (info2.x + ii2 * reader.width) * 4 + info2.width * 4 ); } } @@ -48022,11 +49162,11 @@ var require_gifcodec = __commonJS({ return index === -1 ? null : index; } function _colorLookupBinary(colors, color) { - var lo = 0, hi = colors.length - 1, mid; - while (lo <= hi) { - mid = Math.floor((lo + hi) / 2); + var lo = 0, hi2 = colors.length - 1, mid; + while (lo <= hi2) { + mid = Math.floor((lo + hi2) / 2); if (colors[mid] > color) - hi = mid - 1; + hi2 = mid - 1; else if (colors[mid] < color) lo = mid + 1; else @@ -48110,16 +49250,16 @@ var require_gifcodec = __commonJS({ const colorBuffer = frame.bitmap.data; const indexBuffer = new Buffer(colorBuffer.length / 4); let transparentIndex = colors.length; - let i6 = 0, j6 = 0; + let i6 = 0, j7 = 0; while (i6 < colorBuffer.length) { if (colorBuffer[i6 + 3] !== 0) { const color = colorBuffer.readUInt32BE(i6, true) >> 8 & 16777215; - indexBuffer[j6] = colorToIndexFunc(colors, color); + indexBuffer[j7] = colorToIndexFunc(colors, color); } else { - indexBuffer[j6] = transparentIndex; + indexBuffer[j7] = transparentIndex; } i6 += 4; - ++j6; + ++j7; } if (palette2.usesTransparency) { if (transparentIndex === 256) { @@ -48780,14 +49920,14 @@ var require_encoder = __commonJS({ 99, 99 ]; - for (var j6 = 0; j6 < 64; j6++) { - var u6 = ffloor((UVQT[j6] * sf + 50) / 100); + for (var j7 = 0; j7 < 64; j7++) { + var u6 = ffloor((UVQT[j7] * sf + 50) / 100); if (u6 < 1) { u6 = 1; } else if (u6 > 255) { u6 = 255; } - UVTable[ZigZag[j6]] = u6; + UVTable[ZigZag[j7]] = u6; } var aasf = [ 1, @@ -48799,12 +49939,12 @@ var require_encoder = __commonJS({ 0.5411961, 0.275899379 ]; - var k6 = 0; + var k7 = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { - fdtbl_Y[k6] = 1 / (YTable[ZigZag[k6]] * aasf[row] * aasf[col] * 8); - fdtbl_UV[k6] = 1 / (UVTable[ZigZag[k6]] * aasf[row] * aasf[col] * 8); - k6++; + fdtbl_Y[k7] = 1 / (YTable[ZigZag[k7]] * aasf[row] * aasf[col] * 8); + fdtbl_UV[k7] = 1 / (UVTable[ZigZag[k7]] * aasf[row] * aasf[col] * 8); + k7++; } } } @@ -48812,11 +49952,11 @@ var require_encoder = __commonJS({ var codevalue = 0; var pos_in_table = 0; var HT = new Array(); - for (var k6 = 1; k6 <= 16; k6++) { - for (var j6 = 1; j6 <= nrcodes[k6]; j6++) { + for (var k7 = 1; k7 <= 16; k7++) { + for (var j7 = 1; j7 <= nrcodes[k7]; j7++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; - HT[std_table[pos_in_table]][1] = k6; + HT[std_table[pos_in_table]][1] = k7; pos_in_table++; codevalue++; } @@ -48862,9 +50002,9 @@ var require_encoder = __commonJS({ RGB_YUV_TABLE[i6 + 1792 >> 0] = -5329 * i6; } } - function writeBits(bs2) { - var value = bs2[0]; - var posval = bs2[1] - 1; + function writeBits(bs3) { + var value = bs3[0]; + var posval = bs3[1] - 1; while (posval >= 0) { if (value & 1 << posval) { bytenew |= 1 << bytepos; @@ -49044,8 +50184,8 @@ var require_encoder = __commonJS({ writeByte(YTable[i6]); } writeByte(1); - for (var j6 = 0; j6 < 64; j6++) { - writeByte(UVTable[j6]); + for (var j7 = 0; j7 < 64; j7++) { + writeByte(UVTable[j7]); } } function writeDHT() { @@ -49055,12 +50195,12 @@ var require_encoder = __commonJS({ for (var i6 = 0; i6 < 16; i6++) { writeByte(std_dc_luminance_nrcodes[i6 + 1]); } - for (var j6 = 0; j6 <= 11; j6++) { - writeByte(std_dc_luminance_values[j6]); + for (var j7 = 0; j7 <= 11; j7++) { + writeByte(std_dc_luminance_values[j7]); } writeByte(16); - for (var k6 = 0; k6 < 16; k6++) { - writeByte(std_ac_luminance_nrcodes[k6 + 1]); + for (var k7 = 0; k7 < 16; k7++) { + writeByte(std_ac_luminance_nrcodes[k7 + 1]); } for (var l6 = 0; l6 <= 161; l6++) { writeByte(std_ac_luminance_values[l6]); @@ -49069,8 +50209,8 @@ var require_encoder = __commonJS({ for (var m6 = 0; m6 < 16; m6++) { writeByte(std_dc_chrominance_nrcodes[m6 + 1]); } - for (var n6 = 0; n6 <= 11; n6++) { - writeByte(std_dc_chrominance_values[n6]); + for (var n12 = 0; n12 <= 11; n12++) { + writeByte(std_dc_chrominance_values[n12]); } writeByte(17); for (var o6 = 0; o6 < 16; o6++) { @@ -49114,8 +50254,8 @@ var require_encoder = __commonJS({ var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); - for (var j6 = 0; j6 < I64; ++j6) { - DU[ZigZag[j6]] = DU_DCT[j6]; + for (var j7 = 0; j7 < I64; ++j7) { + DU[ZigZag[j7]] = DU_DCT[j7]; } var Diff = DU[0] - DC; DC = DU[0]; @@ -49188,13 +50328,13 @@ var require_encoder = __commonJS({ var height = image2.height; var quadWidth = width * 4; var tripleWidth = width * 3; - var x7, y4 = 0; + var x8, y4 = 0; var r6, g6, b6; var start, p6, col, row, pos; while (y4 < height) { - x7 = 0; - while (x7 < quadWidth) { - start = quadWidth * y4 + x7; + x8 = 0; + while (x8 < quadWidth) { + start = quadWidth * y4 + x8; p6 = start; col = -1; row = 0; @@ -49205,8 +50345,8 @@ var require_encoder = __commonJS({ if (y4 + row >= height) { p6 -= quadWidth * (y4 + 1 + row - height); } - if (x7 + col >= quadWidth) { - p6 -= x7 + col - quadWidth + 4; + if (x8 + col >= quadWidth) { + p6 -= x8 + col - quadWidth + 4; } r6 = imageData[p6++]; g6 = imageData[p6++]; @@ -49218,7 +50358,7 @@ var require_encoder = __commonJS({ DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - x7 += 32; + x8 += 32; } y4 += 8; } @@ -49367,15 +50507,15 @@ var require_decoder = __commonJS({ function constructor() { } function buildHuffmanTable(codeLengths, values) { - var k6 = 0, code = [], i6, j6, length = 16; + var k7 = 0, code = [], i6, j7, length = 16; while (length > 0 && !codeLengths[length - 1]) length--; code.push({ children: [], index: 0 }); - var p6 = code[0], q6; + var p6 = code[0], q7; for (i6 = 0; i6 < length; i6++) { - for (j6 = 0; j6 < codeLengths[i6]; j6++) { + for (j7 = 0; j7 < codeLengths[i6]; j7++) { p6 = code.pop(); - p6.children[p6.index] = values[k6]; + p6.children[p6.index] = values[k7]; while (p6.index > 0) { if (code.length === 0) throw new Error("Could not recreate Huffman Table"); @@ -49384,16 +50524,16 @@ var require_decoder = __commonJS({ p6.index++; code.push(p6); while (code.length <= i6) { - code.push(q6 = { children: [], index: 0 }); - p6.children[p6.index] = q6.children; - p6 = q6; + code.push(q7 = { children: [], index: 0 }); + p6.children[p6.index] = q7.children; + p6 = q7; } - k6++; + k7++; } if (i6 + 1 < length) { - code.push(q6 = { children: [], index: 0 }); - p6.children[p6.index] = q6.children; - p6 = q6; + code.push(q7 = { children: [], index: 0 }); + p6.children[p6.index] = q7.children; + p6 = q7; } } return code[0].children; @@ -49433,39 +50573,39 @@ var require_decoder = __commonJS({ return null; } function receive(length) { - var n7 = 0; + var n13 = 0; while (length > 0) { var bit = readBit(); if (bit === null) return; - n7 = n7 << 1 | bit; + n13 = n13 << 1 | bit; length--; } - return n7; + return n13; } function receiveAndExtend(length) { - var n7 = receive(length); - if (n7 >= 1 << length - 1) - return n7; - return n7 + (-1 << length) + 1; + var n13 = receive(length); + if (n13 >= 1 << length - 1) + return n13; + return n13 + (-1 << length) + 1; } function decodeBaseline(component2, zz) { var t12 = decodeHuffman(component2.huffmanTableDC); var diff2 = t12 === 0 ? 0 : receiveAndExtend(t12); zz[0] = component2.pred += diff2; - var k7 = 1; - while (k7 < 64) { - var rs = decodeHuffman(component2.huffmanTableAC); - var s6 = rs & 15, r6 = rs >> 4; + var k8 = 1; + while (k8 < 64) { + var rs2 = decodeHuffman(component2.huffmanTableAC); + var s6 = rs2 & 15, r6 = rs2 >> 4; if (s6 === 0) { if (r6 < 15) break; - k7 += 16; + k8 += 16; continue; } - k7 += r6; - var z3 = dctZigZag[k7]; + k8 += r6; + var z3 = dctZigZag[k8]; zz[z3] = receiveAndExtend(s6); - k7++; + k8++; } } function decodeDCFirst(component2, zz) { @@ -49482,34 +50622,34 @@ var require_decoder = __commonJS({ eobrun--; return; } - var k7 = spectralStart, e6 = spectralEnd; - while (k7 <= e6) { - var rs = decodeHuffman(component2.huffmanTableAC); - var s6 = rs & 15, r6 = rs >> 4; + var k8 = spectralStart, e6 = spectralEnd; + while (k8 <= e6) { + var rs2 = decodeHuffman(component2.huffmanTableAC); + var s6 = rs2 & 15, r6 = rs2 >> 4; if (s6 === 0) { if (r6 < 15) { eobrun = receive(r6) + (1 << r6) - 1; break; } - k7 += 16; + k8 += 16; continue; } - k7 += r6; - var z3 = dctZigZag[k7]; + k8 += r6; + var z3 = dctZigZag[k8]; zz[z3] = receiveAndExtend(s6) * (1 << successive); - k7++; + k8++; } } var successiveACState = 0, successiveACNextValue; function decodeACSuccessive(component2, zz) { - var k7 = spectralStart, e6 = spectralEnd, r6 = 0; - while (k7 <= e6) { - var z3 = dctZigZag[k7]; + var k8 = spectralStart, e6 = spectralEnd, r6 = 0; + while (k8 <= e6) { + var z3 = dctZigZag[k8]; var direction = zz[z3] < 0 ? -1 : 1; switch (successiveACState) { case 0: - var rs = decodeHuffman(component2.huffmanTableAC); - var s6 = rs & 15, r6 = rs >> 4; + var rs2 = decodeHuffman(component2.huffmanTableAC); + var s6 = rs2 & 15, r6 = rs2 >> 4; if (s6 === 0) { if (r6 < 15) { eobrun = receive(r6) + (1 << r6); @@ -49549,7 +50689,7 @@ var require_decoder = __commonJS({ zz[z3] += (readBit() << successive) * direction; break; } - k7++; + k8++; } if (successiveACState === 4) { eobrun--; @@ -49574,7 +50714,7 @@ var require_decoder = __commonJS({ decode4(component2, component2.blocks[blockRow][blockCol]); } var componentsLength = components.length; - var component, i6, j6, k6, n6; + var component, i6, j7, k7, n12; var decodeFn; if (progressive) { if (spectralStart === 0) @@ -49592,26 +50732,26 @@ var require_decoder = __commonJS({ mcuExpected = mcusPerLine * frame.mcusPerColumn; } if (!resetInterval) resetInterval = mcuExpected; - var h6, v7; + var h6, v8; while (mcu < mcuExpected) { for (i6 = 0; i6 < componentsLength; i6++) components[i6].pred = 0; eobrun = 0; if (componentsLength == 1) { component = components[0]; - for (n6 = 0; n6 < resetInterval; n6++) { + for (n12 = 0; n12 < resetInterval; n12++) { decodeBlock(component, decodeFn, mcu); mcu++; } } else { - for (n6 = 0; n6 < resetInterval; n6++) { + for (n12 = 0; n12 < resetInterval; n12++) { for (i6 = 0; i6 < componentsLength; i6++) { component = components[i6]; h6 = component.h; - v7 = component.v; - for (j6 = 0; j6 < v7; j6++) { - for (k6 = 0; k6 < h6; k6++) { - decodeMcu(component, decodeFn, mcu, j6, k6); + v8 = component.v; + for (j7 = 0; j7 < v8; j7++) { + for (k7 = 0; k7 < h6; k7++) { + decodeMcu(component, decodeFn, mcu, j7, k7); } } } @@ -49646,14 +50786,14 @@ var require_decoder = __commonJS({ var blocksPerLine = component.blocksPerLine; var blocksPerColumn = component.blocksPerColumn; var samplesPerLine = blocksPerLine << 3; - var R2 = new Int32Array(64), r6 = new Uint8Array(64); + var R3 = new Int32Array(64), r6 = new Uint8Array(64); function quantizeAndInverse(zz, dataOut, dataIn) { - var qt = component.quantizationTable; - var v0, v1, v22, v32, v42, v52, v62, v7, t12; + var qt2 = component.quantizationTable; + var v0, v1, v22, v32, v42, v52, v62, v72, t12; var p6 = dataIn; var i7; for (i7 = 0; i7 < 64; i7++) - p6[i7] = zz[i7] * qt[i7]; + p6[i7] = zz[i7] * qt2[i7]; for (i7 = 0; i7 < 8; ++i7) { var row = 8 * i7; if (p6[1 + row] == 0 && p6[2 + row] == 0 && p6[3 + row] == 0 && p6[4 + row] == 0 && p6[5 + row] == 0 && p6[6 + row] == 0 && p6[7 + row] == 0) { @@ -49673,7 +50813,7 @@ var require_decoder = __commonJS({ v22 = p6[2 + row]; v32 = p6[6 + row]; v42 = dctSqrt1d2 * (p6[1 + row] - p6[7 + row]) + 128 >> 8; - v7 = dctSqrt1d2 * (p6[1 + row] + p6[7 + row]) + 128 >> 8; + v72 = dctSqrt1d2 * (p6[1 + row] + p6[7 + row]) + 128 >> 8; v52 = p6[3 + row] << 4; v62 = p6[5 + row] << 4; t12 = v0 - v1 + 1 >> 1; @@ -49685,23 +50825,23 @@ var require_decoder = __commonJS({ t12 = v42 - v62 + 1 >> 1; v42 = v42 + v62 + 1 >> 1; v62 = t12; - t12 = v7 + v52 + 1 >> 1; - v52 = v7 - v52 + 1 >> 1; - v7 = t12; + t12 = v72 + v52 + 1 >> 1; + v52 = v72 - v52 + 1 >> 1; + v72 = t12; t12 = v0 - v32 + 1 >> 1; v0 = v0 + v32 + 1 >> 1; v32 = t12; t12 = v1 - v22 + 1 >> 1; v1 = v1 + v22 + 1 >> 1; v22 = t12; - t12 = v42 * dctSin3 + v7 * dctCos3 + 2048 >> 12; - v42 = v42 * dctCos3 - v7 * dctSin3 + 2048 >> 12; - v7 = t12; + t12 = v42 * dctSin3 + v72 * dctCos3 + 2048 >> 12; + v42 = v42 * dctCos3 - v72 * dctSin3 + 2048 >> 12; + v72 = t12; t12 = v52 * dctSin1 + v62 * dctCos1 + 2048 >> 12; v52 = v52 * dctCos1 - v62 * dctSin1 + 2048 >> 12; v62 = t12; - p6[0 + row] = v0 + v7; - p6[7 + row] = v0 - v7; + p6[0 + row] = v0 + v72; + p6[7 + row] = v0 - v72; p6[1 + row] = v1 + v62; p6[6 + row] = v1 - v62; p6[2 + row] = v22 + v52; @@ -49728,7 +50868,7 @@ var require_decoder = __commonJS({ v22 = p6[2 * 8 + col]; v32 = p6[6 * 8 + col]; v42 = dctSqrt1d2 * (p6[1 * 8 + col] - p6[7 * 8 + col]) + 2048 >> 12; - v7 = dctSqrt1d2 * (p6[1 * 8 + col] + p6[7 * 8 + col]) + 2048 >> 12; + v72 = dctSqrt1d2 * (p6[1 * 8 + col] + p6[7 * 8 + col]) + 2048 >> 12; v52 = p6[3 * 8 + col]; v62 = p6[5 * 8 + col]; t12 = v0 - v1 + 1 >> 1; @@ -49740,23 +50880,23 @@ var require_decoder = __commonJS({ t12 = v42 - v62 + 1 >> 1; v42 = v42 + v62 + 1 >> 1; v62 = t12; - t12 = v7 + v52 + 1 >> 1; - v52 = v7 - v52 + 1 >> 1; - v7 = t12; + t12 = v72 + v52 + 1 >> 1; + v52 = v72 - v52 + 1 >> 1; + v72 = t12; t12 = v0 - v32 + 1 >> 1; v0 = v0 + v32 + 1 >> 1; v32 = t12; t12 = v1 - v22 + 1 >> 1; v1 = v1 + v22 + 1 >> 1; v22 = t12; - t12 = v42 * dctSin3 + v7 * dctCos3 + 2048 >> 12; - v42 = v42 * dctCos3 - v7 * dctSin3 + 2048 >> 12; - v7 = t12; + t12 = v42 * dctSin3 + v72 * dctCos3 + 2048 >> 12; + v42 = v42 * dctCos3 - v72 * dctSin3 + 2048 >> 12; + v72 = t12; t12 = v52 * dctSin1 + v62 * dctCos1 + 2048 >> 12; v52 = v52 * dctCos1 - v62 * dctSin1 + 2048 >> 12; v62 = t12; - p6[0 * 8 + col] = v0 + v7; - p6[7 * 8 + col] = v0 - v7; + p6[0 * 8 + col] = v0 + v72; + p6[7 * 8 + col] = v0 - v72; p6[1 * 8 + col] = v1 + v62; p6[6 * 8 + col] = v1 - v62; p6[2 * 8 + col] = v22 + v52; @@ -49770,16 +50910,16 @@ var require_decoder = __commonJS({ } } requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8); - var i6, j6; + var i6, j7; for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { var scanLine = blockRow << 3; for (i6 = 0; i6 < 8; i6++) lines.push(new Uint8Array(samplesPerLine)); for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { - quantizeAndInverse(component.blocks[blockRow][blockCol], r6, R2); + quantizeAndInverse(component.blocks[blockRow][blockCol], r6, R3); var offset = 0, sample = blockCol << 3; - for (j6 = 0; j6 < 8; j6++) { - var line = lines[scanLine + j6]; + for (j7 = 0; j7 < 8; j7++) { + var line = lines[scanLine + j7]; for (i6 = 0; i6 < 8; i6++) line[sample + i6] = r6[offset++]; } @@ -49791,9 +50931,9 @@ var require_decoder = __commonJS({ return a6 < 0 ? 0 : a6 > 255 ? 255 : a6; } constructor.prototype = { - load: function load(path7) { + load: function load(path6) { var xhr = new XMLHttpRequest(); - xhr.open("GET", path7, true); + xhr.open("GET", path6, true); xhr.responseType = "arraybuffer"; xhr.onload = (function() { var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); @@ -49841,7 +50981,7 @@ var require_decoder = __commonJS({ requestMemoryAllocation(blocksToAllocate * 256); for (var i7 = 0; i7 < blocksPerColumnForMcu; i7++) { var row = []; - for (var j7 = 0; j7 < blocksPerLineForMcu; j7++) + for (var j8 = 0; j8 < blocksPerLineForMcu; j8++) row.push(new Int32Array(64)); blocks.push(row); } @@ -49869,7 +51009,7 @@ var require_decoder = __commonJS({ } fileMarker = readUint16(); while (fileMarker != 65497) { - var i6, j6, l6; + var i6, j7, l6; switch (fileMarker) { case 65280: break; @@ -49948,13 +51088,13 @@ var require_decoder = __commonJS({ requestMemoryAllocation(64 * 4); var tableData = new Int32Array(64); if (quantizationTableSpec >> 4 === 0) { - for (j6 = 0; j6 < 64; j6++) { - var z3 = dctZigZag[j6]; + for (j7 = 0; j7 < 64; j7++) { + var z3 = dctZigZag[j7]; tableData[z3] = data[offset++]; } } else if (quantizationTableSpec >> 4 === 1) { - for (j6 = 0; j6 < 64; j6++) { - var z3 = dctZigZag[j6]; + for (j7 = 0; j7 < 64; j7++) { + var z3 = dctZigZag[j7]; tableData[z3] = readUint16(); } } else @@ -49986,15 +51126,15 @@ var require_decoder = __commonJS({ for (i6 = 0; i6 < componentsCount; i6++) { componentId = data[offset]; var h6 = data[offset + 1] >> 4; - var v7 = data[offset + 1] & 15; + var v8 = data[offset + 1] & 15; var qId = data[offset + 2]; - if (h6 <= 0 || v7 <= 0) { + if (h6 <= 0 || v8 <= 0) { throw new Error("Invalid sampling factor, expected values above 0"); } frame.componentsOrder.push(componentId); frame.components[componentId] = { h: h6, - v: v7, + v: v8, quantizationIdx: qId }; offset += 3; @@ -50008,13 +51148,13 @@ var require_decoder = __commonJS({ var huffmanTableSpec = data[offset++]; var codeLengths = new Uint8Array(16); var codeLengthSum = 0; - for (j6 = 0; j6 < 16; j6++, offset++) { - codeLengthSum += codeLengths[j6] = data[offset]; + for (j7 = 0; j7 < 16; j7++, offset++) { + codeLengthSum += codeLengths[j7] = data[offset]; } requestMemoryAllocation(16 + codeLengthSum); var huffmanValues = new Uint8Array(codeLengthSum); - for (j6 = 0; j6 < codeLengthSum; j6++, offset++) - huffmanValues[j6] = data[offset]; + for (j7 = 0; j7 < codeLengthSum; j7++, offset++) + huffmanValues[j7] = data[offset]; i6 += 17 + codeLengthSum; (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues); } @@ -50083,9 +51223,9 @@ var require_decoder = __commonJS({ throw new Error("only single frame JPEGs supported"); for (var i6 = 0; i6 < frames.length; i6++) { var cp2 = frames[i6].components; - for (var j6 in cp2) { - cp2[j6].quantizationTable = quantizationTables[cp2[j6].quantizationIdx]; - delete cp2[j6].quantizationIdx; + for (var j7 in cp2) { + cp2[j7].quantizationTable = quantizationTables[cp2[j7].quantizationIdx]; + delete cp2[j7].quantizationIdx; } } this.width = frame.samplesPerLine; @@ -50106,9 +51246,9 @@ var require_decoder = __commonJS({ var scaleX = this.width / width, scaleY = this.height / height; var component1, component2, component3, component4; var component1Line, component2Line, component3Line, component4Line; - var x7, y4; + var x8, y4; var offset = 0; - var Y3, Cb, Cr, K3, C3, M2, Ye, R2, G3, B3; + var Y4, Cb, Cr2, K3, C4, M3, Ye2, R3, G4, B4; var colorTransform; var dataLength = width * height * this.components.length; requestMemoryAllocation(dataLength); @@ -50118,9 +51258,9 @@ var require_decoder = __commonJS({ component1 = this.components[0]; for (y4 = 0; y4 < height; y4++) { component1Line = component1.lines[0 | y4 * component1.scaleY * scaleY]; - for (x7 = 0; x7 < width; x7++) { - Y3 = component1Line[0 | x7 * component1.scaleX * scaleX]; - data[offset++] = Y3; + for (x8 = 0; x8 < width; x8++) { + Y4 = component1Line[0 | x8 * component1.scaleX * scaleX]; + data[offset++] = Y4; } } break; @@ -50130,11 +51270,11 @@ var require_decoder = __commonJS({ for (y4 = 0; y4 < height; y4++) { component1Line = component1.lines[0 | y4 * component1.scaleY * scaleY]; component2Line = component2.lines[0 | y4 * component2.scaleY * scaleY]; - for (x7 = 0; x7 < width; x7++) { - Y3 = component1Line[0 | x7 * component1.scaleX * scaleX]; - data[offset++] = Y3; - Y3 = component2Line[0 | x7 * component2.scaleX * scaleX]; - data[offset++] = Y3; + for (x8 = 0; x8 < width; x8++) { + Y4 = component1Line[0 | x8 * component1.scaleX * scaleX]; + data[offset++] = Y4; + Y4 = component2Line[0 | x8 * component2.scaleX * scaleX]; + data[offset++] = Y4; } } break; @@ -50151,22 +51291,22 @@ var require_decoder = __commonJS({ component1Line = component1.lines[0 | y4 * component1.scaleY * scaleY]; component2Line = component2.lines[0 | y4 * component2.scaleY * scaleY]; component3Line = component3.lines[0 | y4 * component3.scaleY * scaleY]; - for (x7 = 0; x7 < width; x7++) { + for (x8 = 0; x8 < width; x8++) { if (!colorTransform) { - R2 = component1Line[0 | x7 * component1.scaleX * scaleX]; - G3 = component2Line[0 | x7 * component2.scaleX * scaleX]; - B3 = component3Line[0 | x7 * component3.scaleX * scaleX]; + R3 = component1Line[0 | x8 * component1.scaleX * scaleX]; + G4 = component2Line[0 | x8 * component2.scaleX * scaleX]; + B4 = component3Line[0 | x8 * component3.scaleX * scaleX]; } else { - Y3 = component1Line[0 | x7 * component1.scaleX * scaleX]; - Cb = component2Line[0 | x7 * component2.scaleX * scaleX]; - Cr = component3Line[0 | x7 * component3.scaleX * scaleX]; - R2 = clampTo8bit(Y3 + 1.402 * (Cr - 128)); - G3 = clampTo8bit(Y3 - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); - B3 = clampTo8bit(Y3 + 1.772 * (Cb - 128)); + Y4 = component1Line[0 | x8 * component1.scaleX * scaleX]; + Cb = component2Line[0 | x8 * component2.scaleX * scaleX]; + Cr2 = component3Line[0 | x8 * component3.scaleX * scaleX]; + R3 = clampTo8bit(Y4 + 1.402 * (Cr2 - 128)); + G4 = clampTo8bit(Y4 - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr2 - 128)); + B4 = clampTo8bit(Y4 + 1.772 * (Cb - 128)); } - data[offset++] = R2; - data[offset++] = G3; - data[offset++] = B3; + data[offset++] = R3; + data[offset++] = G4; + data[offset++] = B4; } } break; @@ -50187,24 +51327,24 @@ var require_decoder = __commonJS({ component2Line = component2.lines[0 | y4 * component2.scaleY * scaleY]; component3Line = component3.lines[0 | y4 * component3.scaleY * scaleY]; component4Line = component4.lines[0 | y4 * component4.scaleY * scaleY]; - for (x7 = 0; x7 < width; x7++) { + for (x8 = 0; x8 < width; x8++) { if (!colorTransform) { - C3 = component1Line[0 | x7 * component1.scaleX * scaleX]; - M2 = component2Line[0 | x7 * component2.scaleX * scaleX]; - Ye = component3Line[0 | x7 * component3.scaleX * scaleX]; - K3 = component4Line[0 | x7 * component4.scaleX * scaleX]; + C4 = component1Line[0 | x8 * component1.scaleX * scaleX]; + M3 = component2Line[0 | x8 * component2.scaleX * scaleX]; + Ye2 = component3Line[0 | x8 * component3.scaleX * scaleX]; + K3 = component4Line[0 | x8 * component4.scaleX * scaleX]; } else { - Y3 = component1Line[0 | x7 * component1.scaleX * scaleX]; - Cb = component2Line[0 | x7 * component2.scaleX * scaleX]; - Cr = component3Line[0 | x7 * component3.scaleX * scaleX]; - K3 = component4Line[0 | x7 * component4.scaleX * scaleX]; - C3 = 255 - clampTo8bit(Y3 + 1.402 * (Cr - 128)); - M2 = 255 - clampTo8bit(Y3 - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); - Ye = 255 - clampTo8bit(Y3 + 1.772 * (Cb - 128)); + Y4 = component1Line[0 | x8 * component1.scaleX * scaleX]; + Cb = component2Line[0 | x8 * component2.scaleX * scaleX]; + Cr2 = component3Line[0 | x8 * component3.scaleX * scaleX]; + K3 = component4Line[0 | x8 * component4.scaleX * scaleX]; + C4 = 255 - clampTo8bit(Y4 + 1.402 * (Cr2 - 128)); + M3 = 255 - clampTo8bit(Y4 - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr2 - 128)); + Ye2 = 255 - clampTo8bit(Y4 + 1.772 * (Cb - 128)); } - data[offset++] = 255 - C3; - data[offset++] = 255 - M2; - data[offset++] = 255 - Ye; + data[offset++] = 255 - C4; + data[offset++] = 255 - M3; + data[offset++] = 255 - Ye2; data[offset++] = 255 - K3; } } @@ -50218,52 +51358,52 @@ var require_decoder = __commonJS({ var width = imageData.width, height = imageData.height; var imageDataArray = imageData.data; var data = this.getData(width, height); - var i6 = 0, j6 = 0, x7, y4; - var Y3, K3, C3, M2, R2, G3, B3; + var i6 = 0, j7 = 0, x8, y4; + var Y4, K3, C4, M3, R3, G4, B4; switch (this.components.length) { case 1: for (y4 = 0; y4 < height; y4++) { - for (x7 = 0; x7 < width; x7++) { - Y3 = data[i6++]; - imageDataArray[j6++] = Y3; - imageDataArray[j6++] = Y3; - imageDataArray[j6++] = Y3; + for (x8 = 0; x8 < width; x8++) { + Y4 = data[i6++]; + imageDataArray[j7++] = Y4; + imageDataArray[j7++] = Y4; + imageDataArray[j7++] = Y4; if (formatAsRGBA) { - imageDataArray[j6++] = 255; + imageDataArray[j7++] = 255; } } } break; case 3: for (y4 = 0; y4 < height; y4++) { - for (x7 = 0; x7 < width; x7++) { - R2 = data[i6++]; - G3 = data[i6++]; - B3 = data[i6++]; - imageDataArray[j6++] = R2; - imageDataArray[j6++] = G3; - imageDataArray[j6++] = B3; + for (x8 = 0; x8 < width; x8++) { + R3 = data[i6++]; + G4 = data[i6++]; + B4 = data[i6++]; + imageDataArray[j7++] = R3; + imageDataArray[j7++] = G4; + imageDataArray[j7++] = B4; if (formatAsRGBA) { - imageDataArray[j6++] = 255; + imageDataArray[j7++] = 255; } } } break; case 4: for (y4 = 0; y4 < height; y4++) { - for (x7 = 0; x7 < width; x7++) { - C3 = data[i6++]; - M2 = data[i6++]; - Y3 = data[i6++]; + for (x8 = 0; x8 < width; x8++) { + C4 = data[i6++]; + M3 = data[i6++]; + Y4 = data[i6++]; K3 = data[i6++]; - R2 = 255 - clampTo8bit(C3 * (1 - K3 / 255) + K3); - G3 = 255 - clampTo8bit(M2 * (1 - K3 / 255) + K3); - B3 = 255 - clampTo8bit(Y3 * (1 - K3 / 255) + K3); - imageDataArray[j6++] = R2; - imageDataArray[j6++] = G3; - imageDataArray[j6++] = B3; + R3 = 255 - clampTo8bit(C4 * (1 - K3 / 255) + K3); + G4 = 255 - clampTo8bit(M3 * (1 - K3 / 255) + K3); + B4 = 255 - clampTo8bit(Y4 * (1 - K3 / 255) + K3); + imageDataArray[j7++] = R3; + imageDataArray[j7++] = G4; + imageDataArray[j7++] = B4; if (formatAsRGBA) { - imageDataArray[j6++] = 255; + imageDataArray[j7++] = 255; } } } @@ -50365,9 +51505,9 @@ var require_chunkstream = __commonJS({ "../node_modules/pngjs/lib/chunkstream.js"(exports2, module2) { "use strict"; var util17 = require("util"); - var Stream2 = require("stream"); + var Stream = require("stream"); var ChunkStream = module2.exports = function() { - Stream2.call(this); + Stream.call(this); this._buffers = []; this._buffered = 0; this._reads = []; @@ -50375,7 +51515,7 @@ var require_chunkstream = __commonJS({ this._encoding = "utf8"; this.writable = true; }; - util17.inherits(ChunkStream, Stream2); + util17.inherits(ChunkStream, Stream); ChunkStream.prototype.read = function(length, callback) { this._reads.push({ length: Math.abs(length), @@ -50549,15 +51689,15 @@ var require_interlace = __commonJS({ let pass = imagePasses[i6]; let passWidth = xRepeats * pass.x.length; let passHeight = yRepeats * pass.y.length; - for (let j6 = 0; j6 < pass.x.length; j6++) { - if (pass.x[j6] < xLeftOver) { + for (let j7 = 0; j7 < pass.x.length; j7++) { + if (pass.x[j7] < xLeftOver) { passWidth++; } else { break; } } - for (let j6 = 0; j6 < pass.y.length; j6++) { - if (pass.y[j6] < yLeftOver) { + for (let j7 = 0; j7 < pass.y.length; j7++) { + if (pass.y[j7] < yLeftOver) { passHeight++; } else { break; @@ -50570,9 +51710,9 @@ var require_interlace = __commonJS({ return images; }; exports2.getInterlaceIterator = function(width) { - return function(x7, y4, pass) { - let outerXLeftOver = x7 % imagePasses[pass].x.length; - let outerX = (x7 - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver]; + return function(x8, y4, pass) { + let outerXLeftOver = x8 % imagePasses[pass].x.length; + let outerX = (x8 - outerXLeftOver) / imagePasses[pass].x.length * 8 + imagePasses[pass].x[outerXLeftOver]; let outerYLeftOver = y4 % imagePasses[pass].y.length; let outerY = (y4 - outerYLeftOver) / imagePasses[pass].y.length * 8 + imagePasses[pass].y[outerYLeftOver]; return outerX * 4 + outerY * width * 4; @@ -50658,55 +51798,55 @@ var require_filter_parse = __commonJS({ Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; - for (let x7 = 0; x7 < byteWidth; x7++) { - let rawByte = rawData[1 + x7]; - let f1Left = x7 > xBiggerThan ? unfilteredLine[x7 - xComparison] : 0; - unfilteredLine[x7] = rawByte + f1Left; + for (let x8 = 0; x8 < byteWidth; x8++) { + let rawByte = rawData[1 + x8]; + let f1Left = x8 > xBiggerThan ? unfilteredLine[x8 - xComparison] : 0; + unfilteredLine[x8] = rawByte + f1Left; } }; Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) { let lastLine = this._lastLine; - for (let x7 = 0; x7 < byteWidth; x7++) { - let rawByte = rawData[1 + x7]; - let f2Up = lastLine ? lastLine[x7] : 0; - unfilteredLine[x7] = rawByte + f2Up; + for (let x8 = 0; x8 < byteWidth; x8++) { + let rawByte = rawData[1 + x8]; + let f2Up = lastLine ? lastLine[x8] : 0; + unfilteredLine[x8] = rawByte + f2Up; } }; Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; let lastLine = this._lastLine; - for (let x7 = 0; x7 < byteWidth; x7++) { - let rawByte = rawData[1 + x7]; - let f3Up = lastLine ? lastLine[x7] : 0; - let f3Left = x7 > xBiggerThan ? unfilteredLine[x7 - xComparison] : 0; + for (let x8 = 0; x8 < byteWidth; x8++) { + let rawByte = rawData[1 + x8]; + let f3Up = lastLine ? lastLine[x8] : 0; + let f3Left = x8 > xBiggerThan ? unfilteredLine[x8 - xComparison] : 0; let f3Add = Math.floor((f3Left + f3Up) / 2); - unfilteredLine[x7] = rawByte + f3Add; + unfilteredLine[x8] = rawByte + f3Add; } }; Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) { let xComparison = this._xComparison; let xBiggerThan = xComparison - 1; let lastLine = this._lastLine; - for (let x7 = 0; x7 < byteWidth; x7++) { - let rawByte = rawData[1 + x7]; - let f4Up = lastLine ? lastLine[x7] : 0; - let f4Left = x7 > xBiggerThan ? unfilteredLine[x7 - xComparison] : 0; - let f4UpLeft = x7 > xBiggerThan && lastLine ? lastLine[x7 - xComparison] : 0; + for (let x8 = 0; x8 < byteWidth; x8++) { + let rawByte = rawData[1 + x8]; + let f4Up = lastLine ? lastLine[x8] : 0; + let f4Left = x8 > xBiggerThan ? unfilteredLine[x8 - xComparison] : 0; + let f4UpLeft = x8 > xBiggerThan && lastLine ? lastLine[x8 - xComparison] : 0; let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); - unfilteredLine[x7] = rawByte + f4Add; + unfilteredLine[x8] = rawByte + f4Add; } }; Filter.prototype._reverseFilterLine = function(rawData) { - let filter2 = rawData[0]; + let filter = rawData[0]; let unfilteredLine; let currentImage = this._images[this._imageIndex]; let byteWidth = currentImage.byteWidth; - if (filter2 === 0) { + if (filter === 0) { unfilteredLine = rawData.slice(1, byteWidth + 1); } else { unfilteredLine = Buffer.alloc(byteWidth); - switch (filter2) { + switch (filter) { case 1: this._unFilterType1(rawData, unfilteredLine, byteWidth); break; @@ -50720,7 +51860,7 @@ var require_filter_parse = __commonJS({ this._unFilterType4(rawData, unfilteredLine, byteWidth); break; default: - throw new Error("Unrecognised filter type - " + filter2); + throw new Error("Unrecognised filter type - " + filter); } } this.write(unfilteredLine); @@ -50811,7 +51951,7 @@ var require_crc = __commonJS({ (function() { for (let i6 = 0; i6 < 256; i6++) { let currentCrc = i6; - for (let j6 = 0; j6 < 8; j6++) { + for (let j7 = 0; j7 < 8; j7++) { if (currentCrc & 1) { currentCrc = 3988292384 ^ currentCrc >>> 1; } else { @@ -50940,7 +52080,7 @@ var require_parser = __commonJS({ let depth = data[8]; let colorType = data[9]; let compr = data[10]; - let filter2 = data[11]; + let filter = data[11]; let interlace = data[12]; if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) { this.error(new Error("Unsupported bit depth " + depth)); @@ -50954,7 +52094,7 @@ var require_parser = __commonJS({ this.error(new Error("Unsupported compression method")); return; } - if (filter2 !== 0) { + if (filter !== 0) { this.error(new Error("Unsupported filter method")); return; } @@ -51226,8 +52366,8 @@ var require_bitmapper = __commonJS({ let imageHeight = image2.height; let imagePass = image2.index; for (let y4 = 0; y4 < imageHeight; y4++) { - for (let x7 = 0; x7 < imageWidth; x7++) { - let pxPos = getPxPos(x7, y4, imagePass); + for (let x8 = 0; x8 < imageWidth; x8++) { + let pxPos = getPxPos(x8, y4, imagePass); pixelBppMapper[bpp](pxData, data, pxPos, rawPos); rawPos += bpp; } @@ -51239,9 +52379,9 @@ var require_bitmapper = __commonJS({ let imageHeight = image2.height; let imagePass = image2.index; for (let y4 = 0; y4 < imageHeight; y4++) { - for (let x7 = 0; x7 < imageWidth; x7++) { + for (let x8 = 0; x8 < imageWidth; x8++) { let pixelData = bits.get(bpp); - let pxPos = getPxPos(x7, y4, imagePass); + let pxPos = getPxPos(x8, y4, imagePass); pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); } bits.resetAfterLine(); @@ -51319,7 +52459,7 @@ var require_format_normaliser = __commonJS({ function dePalette(indata, outdata, width, height, palette2) { let pxPos = 0; for (let y4 = 0; y4 < height; y4++) { - for (let x7 = 0; x7 < width; x7++) { + for (let x8 = 0; x8 < width; x8++) { let color = palette2[indata[pxPos]]; if (!color) { throw new Error("index " + indata[pxPos] + " not in palette"); @@ -51334,7 +52474,7 @@ var require_format_normaliser = __commonJS({ function replaceTransparentColor(indata, outdata, width, height, transColor) { let pxPos = 0; for (let y4 = 0; y4 < height; y4++) { - for (let x7 = 0; x7 < width; x7++) { + for (let x8 = 0; x8 < width; x8++) { let makeTrans = false; if (transColor.length === 1) { if (transColor[0] === indata[pxPos]) { @@ -51357,7 +52497,7 @@ var require_format_normaliser = __commonJS({ let maxInSample = Math.pow(2, depth) - 1; let pxPos = 0; for (let y4 = 0; y4 < height; y4++) { - for (let x7 = 0; x7 < width; x7++) { + for (let x8 = 0; x8 < width; x8++) { for (let i6 = 0; i6 < 4; i6++) { outdata[pxPos + i6] = Math.floor( indata[pxPos + i6] * maxOutSample / maxInSample + 0.5 @@ -51624,7 +52764,7 @@ var require_bitpacker = __commonJS({ return { red, green, blue, alpha }; } for (let y4 = 0; y4 < height; y4++) { - for (let x7 = 0; x7 < width; x7++) { + for (let x8 = 0; x8 < width; x8++) { let rgba = getRGBA(data, inIndex); switch (options.colorType) { case constants4.COLORTYPE_COLOR_ALPHA: @@ -51679,8 +52819,8 @@ var require_filter_pack = __commonJS({ "use strict"; var paethPredictor = require_paeth_predictor(); function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { - for (let x7 = 0; x7 < byteWidth; x7++) { - rawData[rawPos + x7] = pxData[pxPos + x7]; + for (let x8 = 0; x8 < byteWidth; x8++) { + rawData[rawPos + x8] = pxData[pxPos + x8]; } } function filterSumNone(pxData, pxPos, byteWidth) { @@ -51692,72 +52832,72 @@ var require_filter_pack = __commonJS({ return sum; } function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let val = pxData[pxPos + x7] - left; - rawData[rawPos + x7] = val; + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let val = pxData[pxPos + x8] - left; + rawData[rawPos + x8] = val; } } function filterSumSub(pxData, pxPos, byteWidth, bpp) { let sum = 0; - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let val = pxData[pxPos + x7] - left; + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let val = pxData[pxPos + x8] - left; sum += Math.abs(val); } return sum; } function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { - for (let x7 = 0; x7 < byteWidth; x7++) { - let up = pxPos > 0 ? pxData[pxPos + x7 - byteWidth] : 0; - let val = pxData[pxPos + x7] - up; - rawData[rawPos + x7] = val; + for (let x8 = 0; x8 < byteWidth; x8++) { + let up = pxPos > 0 ? pxData[pxPos + x8 - byteWidth] : 0; + let val = pxData[pxPos + x8] - up; + rawData[rawPos + x8] = val; } } function filterSumUp(pxData, pxPos, byteWidth) { let sum = 0; let length = pxPos + byteWidth; - for (let x7 = pxPos; x7 < length; x7++) { - let up = pxPos > 0 ? pxData[x7 - byteWidth] : 0; - let val = pxData[x7] - up; + for (let x8 = pxPos; x8 < length; x8++) { + let up = pxPos > 0 ? pxData[x8 - byteWidth] : 0; + let val = pxData[x8] - up; sum += Math.abs(val); } return sum; } function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let up = pxPos > 0 ? pxData[pxPos + x7 - byteWidth] : 0; - let val = pxData[pxPos + x7] - (left + up >> 1); - rawData[rawPos + x7] = val; + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x8 - byteWidth] : 0; + let val = pxData[pxPos + x8] - (left + up >> 1); + rawData[rawPos + x8] = val; } } function filterSumAvg(pxData, pxPos, byteWidth, bpp) { let sum = 0; - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let up = pxPos > 0 ? pxData[pxPos + x7 - byteWidth] : 0; - let val = pxData[pxPos + x7] - (left + up >> 1); + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x8 - byteWidth] : 0; + let val = pxData[pxPos + x8] - (left + up >> 1); sum += Math.abs(val); } return sum; } function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let up = pxPos > 0 ? pxData[pxPos + x7 - byteWidth] : 0; - let upleft = pxPos > 0 && x7 >= bpp ? pxData[pxPos + x7 - (byteWidth + bpp)] : 0; - let val = pxData[pxPos + x7] - paethPredictor(left, up, upleft); - rawData[rawPos + x7] = val; + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x8 - byteWidth] : 0; + let upleft = pxPos > 0 && x8 >= bpp ? pxData[pxPos + x8 - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x8] - paethPredictor(left, up, upleft); + rawData[rawPos + x8] = val; } } function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { let sum = 0; - for (let x7 = 0; x7 < byteWidth; x7++) { - let left = x7 >= bpp ? pxData[pxPos + x7 - bpp] : 0; - let up = pxPos > 0 ? pxData[pxPos + x7 - byteWidth] : 0; - let upleft = pxPos > 0 && x7 >= bpp ? pxData[pxPos + x7 - (byteWidth + bpp)] : 0; - let val = pxData[pxPos + x7] - paethPredictor(left, up, upleft); + for (let x8 = 0; x8 < byteWidth; x8++) { + let left = x8 >= bpp ? pxData[pxPos + x8 - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x8 - byteWidth] : 0; + let upleft = pxPos > 0 && x8 >= bpp ? pxData[pxPos + x8 - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x8] - paethPredictor(left, up, upleft); sum += Math.abs(val); } return sum; @@ -51822,7 +52962,7 @@ var require_packer = __commonJS({ var constants4 = require_constants6(); var CrcStream = require_crc(); var bitPacker = require_bitpacker(); - var filter2 = require_filter_pack(); + var filter = require_filter_pack(); var zlib2 = require("zlib"); var Packer = module2.exports = function(options) { this._options = options; @@ -51873,7 +53013,7 @@ var require_packer = __commonJS({ Packer.prototype.filterData = function(data, width, height) { let packedData = bitPacker(data, width, height, this._options); let bpp = constants4.COLORTYPE_TO_BPP_MAP[this._options.colorType]; - let filteredData = filter2(packedData, width, height, this._options, bpp); + let filteredData = filter(packedData, width, height, this._options, bpp); return filteredData; }; Packer.prototype._packChunk = function(type, data) { @@ -51920,17 +53060,17 @@ var require_packer_async = __commonJS({ "../node_modules/pngjs/lib/packer-async.js"(exports2, module2) { "use strict"; var util17 = require("util"); - var Stream2 = require("stream"); + var Stream = require("stream"); var constants4 = require_constants6(); var Packer = require_packer(); var PackerAsync = module2.exports = function(opt) { - Stream2.call(this); + Stream.call(this); let options = opt || {}; this._packer = new Packer(options); this._deflate = this._packer.createDeflate(); this.readable = true; }; - util17.inherits(PackerAsync, Stream2); + util17.inherits(PackerAsync, Stream); PackerAsync.prototype.pack = function(data, width, height, gamma) { this.emit("data", Buffer.from(constants4.PNG_SIGNATURE)); this.emit("data", this._packer.packIHDR(width, height)); @@ -52141,7 +53281,7 @@ var require_filter_parse_sync = __commonJS({ exports2.process = function(inBuffer, bitmapInfo) { let outBuffers = []; let reader = new SyncReader(inBuffer); - let filter2 = new Filter(bitmapInfo, { + let filter = new Filter(bitmapInfo, { read: reader.read.bind(reader), write: function(bufferPart) { outBuffers.push(bufferPart); @@ -52149,7 +53289,7 @@ var require_filter_parse_sync = __commonJS({ complete: function() { } }); - filter2.start(); + filter.start(); reader.process(); return Buffer.concat(outBuffers); }; @@ -52316,12 +53456,12 @@ var require_png = __commonJS({ "../node_modules/pngjs/lib/png.js"(exports2) { "use strict"; var util17 = require("util"); - var Stream2 = require("stream"); + var Stream = require("stream"); var Parser = require_parser_async(); var Packer = require_packer_async(); var PNGSync = require_png_sync(); var PNG2 = exports2.PNG = function(options) { - Stream2.call(this); + Stream.call(this); options = options || {}; this.width = options.width | 0; this.height = options.height | 0; @@ -52349,7 +53489,7 @@ var require_png = __commonJS({ this._parser.on("close", this._handleClose.bind(this)); this._packer.on("error", this.emit.bind(this, "error")); }; - util17.inherits(PNG2, Stream2); + util17.inherits(PNG2, Stream); PNG2.sync = PNGSync; PNG2.prototype.pack = function() { if (!this.data || !this.data.length) { @@ -52430,8 +53570,8 @@ var require_png = __commonJS({ PNG2.adjustGamma = function(src) { if (src.gamma) { for (let y4 = 0; y4 < src.height; y4++) { - for (let x7 = 0; x7 < src.width; x7++) { - let idx = src.width * y4 + x7 << 2; + for (let x8 = 0; x8 < src.width; x8++) { + let idx = src.width * y4 + x8 << 2; for (let i6 = 0; i6 < 3; i6++) { let sample = src.data[idx + i6] / 255; sample = Math.pow(sample, 1 / 2.2 / src.gamma); @@ -52669,7 +53809,7 @@ var require_trees = __commonJS({ var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h6; - var n6, m6; + var n12, m6; var bits; var xbits; var f6; @@ -52679,25 +53819,25 @@ var require_trees = __commonJS({ } tree[s6.heap[s6.heap_max] * 2 + 1] = 0; for (h6 = s6.heap_max + 1; h6 < HEAP_SIZE; h6++) { - n6 = s6.heap[h6]; - bits = tree[tree[n6 * 2 + 1] * 2 + 1] + 1; + n12 = s6.heap[h6]; + bits = tree[tree[n12 * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } - tree[n6 * 2 + 1] = bits; - if (n6 > max_code) { + tree[n12 * 2 + 1] = bits; + if (n12 > max_code) { continue; } s6.bl_count[bits]++; xbits = 0; - if (n6 >= base) { - xbits = extra[n6 - base]; + if (n12 >= base) { + xbits = extra[n12 - base]; } - f6 = tree[n6 * 2]; + f6 = tree[n12 * 2]; s6.opt_len += f6 * (bits + xbits); if (has_stree) { - s6.static_len += f6 * (stree[n6 * 2 + 1] + xbits); + s6.static_len += f6 * (stree[n12 * 2 + 1] + xbits); } } if (overflow === 0) { @@ -52714,8 +53854,8 @@ var require_trees = __commonJS({ overflow -= 2; } while (overflow > 0); for (bits = max_length; bits !== 0; bits--) { - n6 = s6.bl_count[bits]; - while (n6 !== 0) { + n12 = s6.bl_count[bits]; + while (n12 !== 0) { m6 = s6.heap[--h6]; if (m6 > max_code) { continue; @@ -52724,7 +53864,7 @@ var require_trees = __commonJS({ s6.opt_len += (bits - tree[m6 * 2 + 1]) * tree[m6 * 2]; tree[m6 * 2 + 1] = bits; } - n6--; + n12--; } } } @@ -52732,20 +53872,20 @@ var require_trees = __commonJS({ var next_code = new Array(MAX_BITS + 1); var code = 0; var bits; - var n6; + var n12; for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = code + bl_count[bits - 1] << 1; } - for (n6 = 0; n6 <= max_code; n6++) { - var len = tree[n6 * 2 + 1]; + for (n12 = 0; n12 <= max_code; n12++) { + var len = tree[n12 * 2 + 1]; if (len === 0) { continue; } - tree[n6 * 2] = bi_reverse(next_code[len]++, len); + tree[n12 * 2] = bi_reverse(next_code[len]++, len); } } function tr_static_init() { - var n6; + var n12; var bits; var length; var code; @@ -52754,7 +53894,7 @@ var require_trees = __commonJS({ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; - for (n6 = 0; n6 < 1 << extra_lbits[code]; n6++) { + for (n12 = 0; n12 < 1 << extra_lbits[code]; n12++) { _length_code[length++] = code; } } @@ -52762,60 +53902,60 @@ var require_trees = __commonJS({ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; - for (n6 = 0; n6 < 1 << extra_dbits[code]; n6++) { + for (n12 = 0; n12 < 1 << extra_dbits[code]; n12++) { _dist_code[dist++] = code; } } dist >>= 7; for (; code < D_CODES; code++) { base_dist[code] = dist << 7; - for (n6 = 0; n6 < 1 << extra_dbits[code] - 7; n6++) { + for (n12 = 0; n12 < 1 << extra_dbits[code] - 7; n12++) { _dist_code[256 + dist++] = code; } } for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } - n6 = 0; - while (n6 <= 143) { - static_ltree[n6 * 2 + 1] = 8; - n6++; + n12 = 0; + while (n12 <= 143) { + static_ltree[n12 * 2 + 1] = 8; + n12++; bl_count[8]++; } - while (n6 <= 255) { - static_ltree[n6 * 2 + 1] = 9; - n6++; + while (n12 <= 255) { + static_ltree[n12 * 2 + 1] = 9; + n12++; bl_count[9]++; } - while (n6 <= 279) { - static_ltree[n6 * 2 + 1] = 7; - n6++; + while (n12 <= 279) { + static_ltree[n12 * 2 + 1] = 7; + n12++; bl_count[7]++; } - while (n6 <= 287) { - static_ltree[n6 * 2 + 1] = 8; - n6++; + while (n12 <= 287) { + static_ltree[n12 * 2 + 1] = 8; + n12++; bl_count[8]++; } gen_codes(static_ltree, L_CODES + 1, bl_count); - for (n6 = 0; n6 < D_CODES; n6++) { - static_dtree[n6 * 2 + 1] = 5; - static_dtree[n6 * 2] = bi_reverse(n6, 5); + for (n12 = 0; n12 < D_CODES; n12++) { + static_dtree[n12 * 2 + 1] = 5; + static_dtree[n12 * 2] = bi_reverse(n12, 5); } static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); } function init_block(s6) { - var n6; - for (n6 = 0; n6 < L_CODES; n6++) { - s6.dyn_ltree[n6 * 2] = 0; + var n12; + for (n12 = 0; n12 < L_CODES; n12++) { + s6.dyn_ltree[n12 * 2] = 0; } - for (n6 = 0; n6 < D_CODES; n6++) { - s6.dyn_dtree[n6 * 2] = 0; + for (n12 = 0; n12 < D_CODES; n12++) { + s6.dyn_dtree[n12 * 2] = 0; } - for (n6 = 0; n6 < BL_CODES; n6++) { - s6.bl_tree[n6 * 2] = 0; + for (n12 = 0; n12 < BL_CODES; n12++) { + s6.bl_tree[n12 * 2] = 0; } s6.dyn_ltree[END_BLOCK * 2] = 1; s6.opt_len = s6.static_len = 0; @@ -52839,26 +53979,26 @@ var require_trees = __commonJS({ utils2.arraySet(s6.pending_buf, s6.window, buf, len, s6.pending); s6.pending += len; } - function smaller(tree, n6, m6, depth) { - var _n2 = n6 * 2; + function smaller(tree, n12, m6, depth) { + var _n2 = n12 * 2; var _m22 = m6 * 2; - return tree[_n2] < tree[_m22] || tree[_n2] === tree[_m22] && depth[n6] <= depth[m6]; + return tree[_n2] < tree[_m22] || tree[_n2] === tree[_m22] && depth[n12] <= depth[m6]; } - function pqdownheap(s6, tree, k6) { - var v7 = s6.heap[k6]; - var j6 = k6 << 1; - while (j6 <= s6.heap_len) { - if (j6 < s6.heap_len && smaller(tree, s6.heap[j6 + 1], s6.heap[j6], s6.depth)) { - j6++; + function pqdownheap(s6, tree, k7) { + var v8 = s6.heap[k7]; + var j7 = k7 << 1; + while (j7 <= s6.heap_len) { + if (j7 < s6.heap_len && smaller(tree, s6.heap[j7 + 1], s6.heap[j7], s6.depth)) { + j7++; } - if (smaller(tree, v7, s6.heap[j6], s6.depth)) { + if (smaller(tree, v8, s6.heap[j7], s6.depth)) { break; } - s6.heap[k6] = s6.heap[j6]; - k6 = j6; - j6 <<= 1; + s6.heap[k7] = s6.heap[j7]; + k7 = j7; + j7 <<= 1; } - s6.heap[k6] = v7; + s6.heap[k7] = v8; } function compress_block(s6, ltree, dtree) { var dist; @@ -52899,17 +54039,17 @@ var require_trees = __commonJS({ var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; - var n6, m6; + var n12, m6; var max_code = -1; var node; s6.heap_len = 0; s6.heap_max = HEAP_SIZE; - for (n6 = 0; n6 < elems; n6++) { - if (tree[n6 * 2] !== 0) { - s6.heap[++s6.heap_len] = max_code = n6; - s6.depth[n6] = 0; + for (n12 = 0; n12 < elems; n12++) { + if (tree[n12 * 2] !== 0) { + s6.heap[++s6.heap_len] = max_code = n12; + s6.depth[n12] = 0; } else { - tree[n6 * 2 + 1] = 0; + tree[n12 * 2 + 1] = 0; } } while (s6.heap_len < 2) { @@ -52922,12 +54062,12 @@ var require_trees = __commonJS({ } } desc.max_code = max_code; - for (n6 = s6.heap_len >> 1; n6 >= 1; n6--) { - pqdownheap(s6, tree, n6); + for (n12 = s6.heap_len >> 1; n12 >= 1; n12--) { + pqdownheap(s6, tree, n12); } node = elems; do { - n6 = s6.heap[ + n12 = s6.heap[ 1 /*SMALLEST*/ ]; @@ -52945,11 +54085,11 @@ var require_trees = __commonJS({ 1 /*SMALLEST*/ ]; - s6.heap[--s6.heap_max] = n6; + s6.heap[--s6.heap_max] = n12; s6.heap[--s6.heap_max] = m6; - tree[node * 2] = tree[n6 * 2] + tree[m6 * 2]; - s6.depth[node] = (s6.depth[n6] >= s6.depth[m6] ? s6.depth[n6] : s6.depth[m6]) + 1; - tree[n6 * 2 + 1] = tree[m6 * 2 + 1] = node; + tree[node * 2] = tree[n12 * 2] + tree[m6 * 2]; + s6.depth[node] = (s6.depth[n12] >= s6.depth[m6] ? s6.depth[n12] : s6.depth[m6]) + 1; + tree[n12 * 2 + 1] = tree[m6 * 2 + 1] = node; s6.heap[ 1 /*SMALLEST*/ @@ -52969,7 +54109,7 @@ var require_trees = __commonJS({ gen_codes(tree, max_code, s6.bl_count); } function scan_tree(s6, tree, max_code) { - var n6; + var n12; var prevlen = -1; var curlen; var nextlen = tree[0 * 2 + 1]; @@ -52981,9 +54121,9 @@ var require_trees = __commonJS({ min_count = 3; } tree[(max_code + 1) * 2 + 1] = 65535; - for (n6 = 0; n6 <= max_code; n6++) { + for (n12 = 0; n12 <= max_code; n12++) { curlen = nextlen; - nextlen = tree[(n6 + 1) * 2 + 1]; + nextlen = tree[(n12 + 1) * 2 + 1]; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { @@ -53013,7 +54153,7 @@ var require_trees = __commonJS({ } } function send_tree(s6, tree, max_code) { - var n6; + var n12; var prevlen = -1; var curlen; var nextlen = tree[0 * 2 + 1]; @@ -53024,9 +54164,9 @@ var require_trees = __commonJS({ max_count = 138; min_count = 3; } - for (n6 = 0; n6 <= max_code; n6++) { + for (n12 = 0; n12 <= max_code; n12++) { curlen = nextlen; - nextlen = tree[(n6 + 1) * 2 + 1]; + nextlen = tree[(n12 + 1) * 2 + 1]; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { @@ -53087,17 +54227,17 @@ var require_trees = __commonJS({ } function detect_data_type(s6) { var black_mask = 4093624447; - var n6; - for (n6 = 0; n6 <= 31; n6++, black_mask >>>= 1) { - if (black_mask & 1 && s6.dyn_ltree[n6 * 2] !== 0) { + var n12; + for (n12 = 0; n12 <= 31; n12++, black_mask >>>= 1) { + if (black_mask & 1 && s6.dyn_ltree[n12 * 2] !== 0) { return Z_BINARY; } } if (s6.dyn_ltree[9 * 2] !== 0 || s6.dyn_ltree[10 * 2] !== 0 || s6.dyn_ltree[13 * 2] !== 0) { return Z_TEXT; } - for (n6 = 32; n6 < LITERALS; n6++) { - if (s6.dyn_ltree[n6 * 2] !== 0) { + for (n12 = 32; n12 < LITERALS; n12++) { + if (s6.dyn_ltree[n12 * 2] !== 0) { return Z_TEXT; } } @@ -53186,14 +54326,14 @@ var require_adler32 = __commonJS({ "../node_modules/pako/lib/zlib/adler32.js"(exports2, module2) { "use strict"; function adler32(adler, buf, len, pos) { - var s1 = adler & 65535 | 0, s22 = adler >>> 16 & 65535 | 0, n6 = 0; + var s1 = adler & 65535 | 0, s22 = adler >>> 16 & 65535 | 0, n12 = 0; while (len !== 0) { - n6 = len > 2e3 ? 2e3 : len; - len -= n6; + n12 = len > 2e3 ? 2e3 : len; + len -= n12; do { s1 = s1 + buf[pos++] | 0; s22 = s22 + s1 | 0; - } while (--n6); + } while (--n12); s1 %= 65521; s22 %= 65521; } @@ -53209,12 +54349,12 @@ var require_crc32 = __commonJS({ "use strict"; function makeTable() { var c7, table = []; - for (var n6 = 0; n6 < 256; n6++) { - c7 = n6; - for (var k6 = 0; k6 < 8; k6++) { + for (var n12 = 0; n12 < 256; n12++) { + c7 = n12; + for (var k7 = 0; k7 < 8; k7++) { c7 = c7 & 1 ? 3988292384 ^ c7 >>> 1 : c7 >>> 1; } - table[n6] = c7; + table[n12] = c7; } return table; } @@ -53377,7 +54517,7 @@ var require_deflate = __commonJS({ function longest_match(s6, cur_match) { var chain_length = s6.max_chain_length; var scan2 = s6.strstart; - var match2; + var match; var len; var best_len = s6.prev_length; var nice_match = s6.nice_match; @@ -53395,14 +54535,14 @@ var require_deflate = __commonJS({ nice_match = s6.lookahead; } do { - match2 = cur_match; - if (_win[match2 + best_len] !== scan_end || _win[match2 + best_len - 1] !== scan_end1 || _win[match2] !== _win[scan2] || _win[++match2] !== _win[scan2 + 1]) { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan2] || _win[++match] !== _win[scan2 + 1]) { continue; } scan2 += 2; - match2++; + match++; do { - } while (_win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && _win[++scan2] === _win[++match2] && scan2 < strend); + } while (_win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && _win[++scan2] === _win[++match] && scan2 < strend); len = MAX_MATCH - (strend - scan2); scan2 = strend - MAX_MATCH; if (len > best_len) { @@ -53422,7 +54562,7 @@ var require_deflate = __commonJS({ } function fill_window(s6) { var _w_size = s6.w_size; - var p6, n6, m6, more, str; + var p6, n12, m6, more, str; do { more = s6.window_size - s6.lookahead - s6.strstart; if (s6.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { @@ -53430,25 +54570,25 @@ var require_deflate = __commonJS({ s6.match_start -= _w_size; s6.strstart -= _w_size; s6.block_start -= _w_size; - n6 = s6.hash_size; - p6 = n6; + n12 = s6.hash_size; + p6 = n12; do { m6 = s6.head[--p6]; s6.head[p6] = m6 >= _w_size ? m6 - _w_size : 0; - } while (--n6); - n6 = _w_size; - p6 = n6; + } while (--n12); + n12 = _w_size; + p6 = n12; do { m6 = s6.prev[--p6]; s6.prev[p6] = m6 >= _w_size ? m6 - _w_size : 0; - } while (--n6); + } while (--n12); more += _w_size; } if (s6.strm.avail_in === 0) { break; } - n6 = read_buf(s6.strm, s6.window, s6.strstart + s6.lookahead, more); - s6.lookahead += n6; + n12 = read_buf(s6.strm, s6.window, s6.strstart + s6.lookahead, more); + s6.lookahead += n12; if (s6.lookahead + s6.insert >= MIN_MATCH) { str = s6.strstart - s6.insert; s6.ins_h = s6.window[str]; @@ -54233,7 +55373,7 @@ var require_deflate = __commonJS({ function deflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var s6; - var str, n6; + var str, n12; var wrap; var avail; var next; @@ -54272,13 +55412,13 @@ var require_deflate = __commonJS({ fill_window(s6); while (s6.lookahead >= MIN_MATCH) { str = s6.strstart; - n6 = s6.lookahead - (MIN_MATCH - 1); + n12 = s6.lookahead - (MIN_MATCH - 1); do { s6.ins_h = (s6.ins_h << s6.hash_shift ^ s6.window[str + MIN_MATCH - 1]) & s6.hash_mask; s6.prev[str & s6.w_mask] = s6.head[s6.ins_h]; s6.head[s6.ins_h] = str; str++; - } while (--n6); + } while (--n12); s6.strstart = str; s6.lookahead = MIN_MATCH - 1; fill_window(s6); @@ -54325,10 +55465,10 @@ var require_strings = __commonJS({ STR_APPLY_UIA_OK = false; } var _utf8len = new utils2.Buf8(256); - for (q6 = 0; q6 < 256; q6++) { - _utf8len[q6] = q6 >= 252 ? 6 : q6 >= 248 ? 5 : q6 >= 240 ? 4 : q6 >= 224 ? 3 : q6 >= 192 ? 2 : 1; + for (q7 = 0; q7 < 256; q7++) { + _utf8len[q7] = q7 >= 252 ? 6 : q7 >= 248 ? 5 : q7 >= 240 ? 4 : q7 >= 224 ? 3 : q7 >= 192 ? 2 : 1; } - var q6; + var q7; _utf8len[254] = _utf8len[254] = 1; exports2.string2buf = function(str) { var buf, c7, c22, m_pos, i6, str_len = str.length, buf_len = 0; @@ -55236,8 +56376,8 @@ var require_inflate = __commonJS({ var ENOUGH_DISTS = 592; var MAX_WBITS = 15; var DEF_WBITS = MAX_WBITS; - function zswap32(q6) { - return (q6 >>> 24 & 255) + (q6 >>> 8 & 65280) + ((q6 & 65280) << 8) + ((q6 & 255) << 24); + function zswap32(q7) { + return (q7 >>> 24 & 255) + (q7 >>> 8 & 65280) + ((q7 & 65280) << 8) + ((q7 & 255) << 24); } function InflateState() { this.mode = 0; @@ -55444,7 +56584,7 @@ var require_inflate = __commonJS({ var ret2; var hbuf = new utils2.Buf8(4); var opts; - var n6; + var n12; var order = ( /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] @@ -55941,8 +57081,8 @@ var require_inflate = __commonJS({ state2.lens[state2.have++] = here_val; } else { if (here_val === 16) { - n6 = here_bits + 2; - while (bits < n6) { + n12 = here_bits + 2; + while (bits < n12) { if (have === 0) { break inf_leave; } @@ -55962,8 +57102,8 @@ var require_inflate = __commonJS({ hold >>>= 2; bits -= 2; } else if (here_val === 17) { - n6 = here_bits + 3; - while (bits < n6) { + n12 = here_bits + 3; + while (bits < n12) { if (have === 0) { break inf_leave; } @@ -55978,8 +57118,8 @@ var require_inflate = __commonJS({ hold >>>= 3; bits -= 3; } else { - n6 = here_bits + 7; - while (bits < n6) { + n12 = here_bits + 7; + while (bits < n12) { if (have === 0) { break inf_leave; } @@ -56123,8 +57263,8 @@ var require_inflate = __commonJS({ /* falls through */ case LENEXT: if (state2.extra) { - n6 = state2.extra; - while (bits < n6) { + n12 = state2.extra; + while (bits < n12) { if (have === 0) { break inf_leave; } @@ -56193,8 +57333,8 @@ var require_inflate = __commonJS({ /* falls through */ case DISTEXT: if (state2.extra) { - n6 = state2.extra; - while (bits < n6) { + n12 = state2.extra; + while (bits < n12) { if (have === 0) { break inf_leave; } @@ -56689,292 +57829,292 @@ var require_UTIF = __commonJS({ (function(UTIF2, pako2) { (function() { "use strict"; - var W2 = (function a1() { - function W3(p6) { + var W3 = (function a1() { + function W4(p6) { this.message = "JPEG error: " + p6; } - W3.prototype = new Error(); - W3.prototype.name = "JpegError"; - W3.constructor = W3; - return W3; + W4.prototype = new Error(); + W4.prototype.name = "JpegError"; + W4.constructor = W4; + return W4; })(), ak2 = (function ag2() { - var p6 = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t12 = 4017, ac2 = 799, ah2 = 3406, ao2 = 2276, ar2 = 1567, ai2 = 3784, s6 = 5793, ad2 = 2896; - function ak3(Q2) { - if (Q2 == null) Q2 = {}; - if (Q2.w == null) Q2.w = -1; - this.V = Q2.n; - this.N = Q2.w; - } - function a52(Q2, h6) { - var f6 = 0, G3 = [], n6, E3, a6 = 16, F3; - while (a6 > 0 && !Q2[a6 - 1]) { + var p6 = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t12 = 4017, ac2 = 799, ah2 = 3406, ao2 = 2276, ar2 = 1567, ai3 = 3784, s6 = 5793, ad2 = 2896; + function ak3(Q3) { + if (Q3 == null) Q3 = {}; + if (Q3.w == null) Q3.w = -1; + this.V = Q3.n; + this.N = Q3.w; + } + function a52(Q3, h6) { + var f6 = 0, G4 = [], n12, E3, a6 = 16, F4; + while (a6 > 0 && !Q3[a6 - 1]) { a6--; } - G3.push({ children: [], index: 0 }); - var C3 = G3[0]; - for (n6 = 0; n6 < a6; n6++) { - for (E3 = 0; E3 < Q2[n6]; E3++) { - C3 = G3.pop(); - C3.children[C3.index] = h6[f6]; - while (C3.index > 0) { - C3 = G3.pop(); + G4.push({ children: [], index: 0 }); + var C4 = G4[0]; + for (n12 = 0; n12 < a6; n12++) { + for (E3 = 0; E3 < Q3[n12]; E3++) { + C4 = G4.pop(); + C4.children[C4.index] = h6[f6]; + while (C4.index > 0) { + C4 = G4.pop(); } - C3.index++; - G3.push(C3); - while (G3.length <= n6) { - G3.push(F3 = { children: [], index: 0 }); - C3.children[C3.index] = F3.children; - C3 = F3; + C4.index++; + G4.push(C4); + while (G4.length <= n12) { + G4.push(F4 = { children: [], index: 0 }); + C4.children[C4.index] = F4.children; + C4 = F4; } f6++; } - if (n6 + 1 < a6) { - G3.push(F3 = { children: [], index: 0 }); - C3.children[C3.index] = F3.children; - C3 = F3; + if (n12 + 1 < a6) { + G4.push(F4 = { children: [], index: 0 }); + C4.children[C4.index] = F4.children; + C4 = F4; } } - return G3[0].children; + return G4[0].children; } - function a22(Q2, h6, f6) { - return 64 * ((Q2.P + 1) * h6 + f6); + function a22(Q3, h6, f6) { + return 64 * ((Q3.P + 1) * h6 + f6); } - function a7(Q2, h6, f6, G3, n6, E3, a6, C3, F3, d6) { + function a7(Q3, h6, f6, G4, n12, E3, a6, C4, F4, d6) { if (d6 == null) d6 = false; - var T2 = f6.m, U2 = f6.Z, z3 = h6, J3 = 0, V2 = 0, r6 = 0, D3 = 0, a8, q6 = 0, X2, O2, _, N2, e6, K3, x7 = 0, k6, g6, R2, c7; - function Y3() { - if (V2 > 0) { - V2--; - return J3 >> V2 & 1; + var T3 = f6.m, U3 = f6.Z, z3 = h6, J3 = 0, V3 = 0, r6 = 0, D4 = 0, a8, q7 = 0, X3, O3, _2, N3, e6, K3, x8 = 0, k7, g6, R3, c7; + function Y4() { + if (V3 > 0) { + V3--; + return J3 >> V3 & 1; } - J3 = Q2[h6++]; + J3 = Q3[h6++]; if (J3 === 255) { - var I3 = Q2[h6++]; - if (I3) { - if (I3 === 220 && d6) { + var I4 = Q3[h6++]; + if (I4) { + if (I4 === 220 && d6) { h6 += 2; - var l6 = Z2(Q2, h6); + var l6 = Z2(Q3, h6); h6 += 2; if (l6 > 0 && l6 !== f6.s) { throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l6); } - } else if (I3 === 217) { + } else if (I4 === 217) { if (d6) { - var M2 = q6 * 8; - if (M2 > 0 && M2 < f6.s / 10) { - throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter", M2); + var M3 = q7 * 8; + if (M3 > 0 && M3 < f6.s / 10) { + throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter", M3); } } throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data"); } - throw new W2("unexpected marker"); + throw new W3("unexpected marker"); } } - V2 = 7; + V3 = 7; return J3 >>> 7; } - function u6(I3) { - var l6 = I3; + function u6(I4) { + var l6 = I4; while (true) { - l6 = l6[Y3()]; + l6 = l6[Y4()]; switch (typeof l6) { case "number": return l6; case "object": continue; } - throw new W2("invalid huffman sequence"); + throw new W3("invalid huffman sequence"); } } - function m6(I3) { + function m6(I4) { var e7 = 0; - while (I3 > 0) { - e7 = e7 << 1 | Y3(); - I3--; + while (I4 > 0) { + e7 = e7 << 1 | Y4(); + I4--; } return e7; } - function j6(I3) { - if (I3 === 1) { - return Y3() === 1 ? 1 : -1; + function j7(I4) { + if (I4 === 1) { + return Y4() === 1 ? 1 : -1; } - var e7 = m6(I3); - if (e7 >= 1 << I3 - 1) { + var e7 = m6(I4); + if (e7 >= 1 << I4 - 1) { return e7; } - return e7 + (-1 << I3) + 1; + return e7 + (-1 << I4) + 1; } - function v7(X3, I3) { - var l6 = u6(X3.J), M2 = l6 === 0 ? 0 : j6(l6), N3 = 1; - X3.D[I3] = X3.Q += M2; - while (N3 < 64) { - var S2 = u6(X3.i), i6 = S2 & 15, A3 = S2 >> 4; + function v8(X4, I4) { + var l6 = u6(X4.J), M3 = l6 === 0 ? 0 : j7(l6), N4 = 1; + X4.D[I4] = X4.Q += M3; + while (N4 < 64) { + var S2 = u6(X4.i), i6 = S2 & 15, A4 = S2 >> 4; if (i6 === 0) { - if (A3 < 15) { + if (A4 < 15) { break; } - N3 += 16; + N4 += 16; continue; } - N3 += A3; - var o6 = p6[N3]; - X3.D[I3 + o6] = j6(i6); - N3++; + N4 += A4; + var o6 = p6[N4]; + X4.D[I4 + o6] = j7(i6); + N4++; } } - function $(X3, I3) { - var l6 = u6(X3.J), M2 = l6 === 0 ? 0 : j6(l6) << F3; - X3.D[I3] = X3.Q += M2; + function $(X4, I4) { + var l6 = u6(X4.J), M3 = l6 === 0 ? 0 : j7(l6) << F4; + X4.D[I4] = X4.Q += M3; } - function b6(X3, I3) { - X3.D[I3] |= Y3() << F3; + function b6(X4, I4) { + X4.D[I4] |= Y4() << F4; } - function P2(X3, I3) { + function P3(X4, I4) { if (r6 > 0) { r6--; return; } - var N3 = E3, l6 = a6; - while (N3 <= l6) { - var M2 = u6(X3.i), S2 = M2 & 15, i6 = M2 >> 4; + var N4 = E3, l6 = a6; + while (N4 <= l6) { + var M3 = u6(X4.i), S2 = M3 & 15, i6 = M3 >> 4; if (S2 === 0) { if (i6 < 15) { r6 = m6(i6) + (1 << i6) - 1; break; } - N3 += 16; + N4 += 16; continue; } - N3 += i6; - var A3 = p6[N3]; - X3.D[I3 + A3] = j6(S2) * (1 << F3); - N3++; + N4 += i6; + var A4 = p6[N4]; + X4.D[I4 + A4] = j7(S2) * (1 << F4); + N4++; } } - function a42(X3, I3) { - var N3 = E3, l6 = a6, M2 = 0, S2, i6; - while (N3 <= l6) { - var A3 = I3 + p6[N3], o6 = X3.D[A3] < 0 ? -1 : 1; - switch (D3) { + function a42(X4, I4) { + var N4 = E3, l6 = a6, M3 = 0, S2, i6; + while (N4 <= l6) { + var A4 = I4 + p6[N4], o6 = X4.D[A4] < 0 ? -1 : 1; + switch (D4) { case 0: - i6 = u6(X3.i); + i6 = u6(X4.i); S2 = i6 & 15; - M2 = i6 >> 4; + M3 = i6 >> 4; if (S2 === 0) { - if (M2 < 15) { - r6 = m6(M2) + (1 << M2); - D3 = 4; + if (M3 < 15) { + r6 = m6(M3) + (1 << M3); + D4 = 4; } else { - M2 = 16; - D3 = 1; + M3 = 16; + D4 = 1; } } else { if (S2 !== 1) { - throw new W2("invalid ACn encoding"); + throw new W3("invalid ACn encoding"); } - a8 = j6(S2); - D3 = M2 ? 2 : 3; + a8 = j7(S2); + D4 = M3 ? 2 : 3; } continue; case 1: case 2: - if (X3.D[A3]) { - X3.D[A3] += o6 * (Y3() << F3); + if (X4.D[A4]) { + X4.D[A4] += o6 * (Y4() << F4); } else { - M2--; - if (M2 === 0) { - D3 = D3 === 2 ? 3 : 0; + M3--; + if (M3 === 0) { + D4 = D4 === 2 ? 3 : 0; } } break; case 3: - if (X3.D[A3]) { - X3.D[A3] += o6 * (Y3() << F3); + if (X4.D[A4]) { + X4.D[A4] += o6 * (Y4() << F4); } else { - X3.D[A3] = a8 << F3; - D3 = 0; + X4.D[A4] = a8 << F4; + D4 = 0; } break; case 4: - if (X3.D[A3]) { - X3.D[A3] += o6 * (Y3() << F3); + if (X4.D[A4]) { + X4.D[A4] += o6 * (Y4() << F4); } break; } - N3++; + N4++; } - if (D3 === 4) { + if (D4 === 4) { r6--; if (r6 === 0) { - D3 = 0; + D4 = 0; } } } - function H3(X3, I3, x8, l6, M2) { - var S2 = x8 / T2 | 0, i6 = x8 % T2; - q6 = S2 * X3.A + l6; - var A3 = i6 * X3.h + M2, o6 = a22(X3, q6, A3); - I3(X3, o6); + function H4(X4, I4, x9, l6, M3) { + var S2 = x9 / T3 | 0, i6 = x9 % T3; + q7 = S2 * X4.A + l6; + var A4 = i6 * X4.h + M3, o6 = a22(X4, q7, A4); + I4(X4, o6); } - function w6(X3, I3, x8) { - q6 = x8 / X3.P | 0; - var l6 = x8 % X3.P, M2 = a22(X3, q6, l6); - I3(X3, M2); + function w6(X4, I4, x9) { + q7 = x9 / X4.P | 0; + var l6 = x9 % X4.P, M3 = a22(X4, q7, l6); + I4(X4, M3); } - var y4 = G3.length; - if (U2) { + var y4 = G4.length; + if (U3) { if (E3 === 0) { - K3 = C3 === 0 ? $ : b6; + K3 = C4 === 0 ? $ : b6; } else { - K3 = C3 === 0 ? P2 : a42; + K3 = C4 === 0 ? P3 : a42; } } else { - K3 = v7; + K3 = v8; } if (y4 === 1) { - g6 = G3[0].P * G3[0].c; + g6 = G4[0].P * G4[0].c; } else { - g6 = T2 * f6.R; + g6 = T3 * f6.R; } - while (x7 <= g6) { - var L2 = n6 ? Math.min(g6 - x7, n6) : g6; - if (L2 > 0) { - for (O2 = 0; O2 < y4; O2++) { - G3[O2].Q = 0; + while (x8 <= g6) { + var L3 = n12 ? Math.min(g6 - x8, n12) : g6; + if (L3 > 0) { + for (O3 = 0; O3 < y4; O3++) { + G4[O3].Q = 0; } r6 = 0; if (y4 === 1) { - X2 = G3[0]; - for (e6 = 0; e6 < L2; e6++) { - w6(X2, K3, x7); - x7++; + X3 = G4[0]; + for (e6 = 0; e6 < L3; e6++) { + w6(X3, K3, x8); + x8++; } } else { - for (e6 = 0; e6 < L2; e6++) { - for (O2 = 0; O2 < y4; O2++) { - X2 = G3[O2]; - R2 = X2.h; - c7 = X2.A; - for (_ = 0; _ < c7; _++) { - for (N2 = 0; N2 < R2; N2++) { - H3(X2, K3, x7, _, N2); + for (e6 = 0; e6 < L3; e6++) { + for (O3 = 0; O3 < y4; O3++) { + X3 = G4[O3]; + R3 = X3.h; + c7 = X3.A; + for (_2 = 0; _2 < c7; _2++) { + for (N3 = 0; N3 < R3; N3++) { + H4(X3, K3, x8, _2, N3); } } } - x7++; + x8++; } } } - V2 = 0; - k6 = an2(Q2, h6); - if (!k6) { + V3 = 0; + k7 = an2(Q3, h6); + if (!k7) { break; } - if (k6.u) { - var a62 = L2 > 0 ? "unexpected" : "excessive"; - h6 = k6.offset; + if (k7.u) { + var a62 = L3 > 0 ? "unexpected" : "excessive"; + h6 = k7.offset; } - if (k6.M >= 65488 && k6.M <= 65495) { + if (k7.M >= 65488 && k7.M <= 65495) { h6 += 2; } else { break; @@ -56982,22 +58122,22 @@ var require_UTIF = __commonJS({ } return h6 - z3; } - function al2(Q2, h6, f6) { - var G3 = Q2.$, n6 = Q2.D, E3, a6, C3, F3, d6, T2, U2, z3, J3, V2, Y3, u6, m6, j6, v7, $, b6; - if (!G3) { - throw new W2("missing required Quantization Table."); + function al2(Q3, h6, f6) { + var G4 = Q3.$, n12 = Q3.D, E3, a6, C4, F4, d6, T3, U3, z3, J3, V3, Y4, u6, m6, j7, v8, $, b6; + if (!G4) { + throw new W3("missing required Quantization Table."); } for (var r6 = 0; r6 < 64; r6 += 8) { - J3 = n6[h6 + r6]; - V2 = n6[h6 + r6 + 1]; - Y3 = n6[h6 + r6 + 2]; - u6 = n6[h6 + r6 + 3]; - m6 = n6[h6 + r6 + 4]; - j6 = n6[h6 + r6 + 5]; - v7 = n6[h6 + r6 + 6]; - $ = n6[h6 + r6 + 7]; - J3 *= G3[r6]; - if ((V2 | Y3 | u6 | m6 | j6 | v7 | $) === 0) { + J3 = n12[h6 + r6]; + V3 = n12[h6 + r6 + 1]; + Y4 = n12[h6 + r6 + 2]; + u6 = n12[h6 + r6 + 3]; + m6 = n12[h6 + r6 + 4]; + j7 = n12[h6 + r6 + 5]; + v8 = n12[h6 + r6 + 6]; + $ = n12[h6 + r6 + 7]; + J3 *= G4[r6]; + if ((V3 | Y4 | u6 | m6 | j7 | v8 | $) === 0) { b6 = s6 * J3 + 512 >> 10; f6[r6] = b6; f6[r6 + 1] = b6; @@ -57009,59 +58149,59 @@ var require_UTIF = __commonJS({ f6[r6 + 7] = b6; continue; } - V2 *= G3[r6 + 1]; - Y3 *= G3[r6 + 2]; - u6 *= G3[r6 + 3]; - m6 *= G3[r6 + 4]; - j6 *= G3[r6 + 5]; - v7 *= G3[r6 + 6]; - $ *= G3[r6 + 7]; + V3 *= G4[r6 + 1]; + Y4 *= G4[r6 + 2]; + u6 *= G4[r6 + 3]; + m6 *= G4[r6 + 4]; + j7 *= G4[r6 + 5]; + v8 *= G4[r6 + 6]; + $ *= G4[r6 + 7]; E3 = s6 * J3 + 128 >> 8; a6 = s6 * m6 + 128 >> 8; - C3 = Y3; - F3 = v7; - d6 = ad2 * (V2 - $) + 128 >> 8; - z3 = ad2 * (V2 + $) + 128 >> 8; - T2 = u6 << 4; - U2 = j6 << 4; + C4 = Y4; + F4 = v8; + d6 = ad2 * (V3 - $) + 128 >> 8; + z3 = ad2 * (V3 + $) + 128 >> 8; + T3 = u6 << 4; + U3 = j7 << 4; E3 = E3 + a6 + 1 >> 1; a6 = E3 - a6; - b6 = C3 * ai2 + F3 * ar2 + 128 >> 8; - C3 = C3 * ar2 - F3 * ai2 + 128 >> 8; - F3 = b6; - d6 = d6 + U2 + 1 >> 1; - U2 = d6 - U2; - z3 = z3 + T2 + 1 >> 1; - T2 = z3 - T2; - E3 = E3 + F3 + 1 >> 1; - F3 = E3 - F3; - a6 = a6 + C3 + 1 >> 1; - C3 = a6 - C3; + b6 = C4 * ai3 + F4 * ar2 + 128 >> 8; + C4 = C4 * ar2 - F4 * ai3 + 128 >> 8; + F4 = b6; + d6 = d6 + U3 + 1 >> 1; + U3 = d6 - U3; + z3 = z3 + T3 + 1 >> 1; + T3 = z3 - T3; + E3 = E3 + F4 + 1 >> 1; + F4 = E3 - F4; + a6 = a6 + C4 + 1 >> 1; + C4 = a6 - C4; b6 = d6 * ao2 + z3 * ah2 + 2048 >> 12; d6 = d6 * ah2 - z3 * ao2 + 2048 >> 12; z3 = b6; - b6 = T2 * ac2 + U2 * t12 + 2048 >> 12; - T2 = T2 * t12 - U2 * ac2 + 2048 >> 12; - U2 = b6; + b6 = T3 * ac2 + U3 * t12 + 2048 >> 12; + T3 = T3 * t12 - U3 * ac2 + 2048 >> 12; + U3 = b6; f6[r6] = E3 + z3; f6[r6 + 7] = E3 - z3; - f6[r6 + 1] = a6 + U2; - f6[r6 + 6] = a6 - U2; - f6[r6 + 2] = C3 + T2; - f6[r6 + 5] = C3 - T2; - f6[r6 + 3] = F3 + d6; - f6[r6 + 4] = F3 - d6; + f6[r6 + 1] = a6 + U3; + f6[r6 + 6] = a6 - U3; + f6[r6 + 2] = C4 + T3; + f6[r6 + 5] = C4 - T3; + f6[r6 + 3] = F4 + d6; + f6[r6 + 4] = F4 - d6; } - for (var P2 = 0; P2 < 8; ++P2) { - J3 = f6[P2]; - V2 = f6[P2 + 8]; - Y3 = f6[P2 + 16]; - u6 = f6[P2 + 24]; - m6 = f6[P2 + 32]; - j6 = f6[P2 + 40]; - v7 = f6[P2 + 48]; - $ = f6[P2 + 56]; - if ((V2 | Y3 | u6 | m6 | j6 | v7 | $) === 0) { + for (var P3 = 0; P3 < 8; ++P3) { + J3 = f6[P3]; + V3 = f6[P3 + 8]; + Y4 = f6[P3 + 16]; + u6 = f6[P3 + 24]; + m6 = f6[P3 + 32]; + j7 = f6[P3 + 40]; + v8 = f6[P3 + 48]; + $ = f6[P3 + 56]; + if ((V3 | Y4 | u6 | m6 | j7 | v8 | $) === 0) { b6 = s6 * J3 + 8192 >> 14; if (b6 < -2040) { b6 = 0; @@ -57070,51 +58210,51 @@ var require_UTIF = __commonJS({ } else { b6 = b6 + 2056 >> 4; } - n6[h6 + P2] = b6; - n6[h6 + P2 + 8] = b6; - n6[h6 + P2 + 16] = b6; - n6[h6 + P2 + 24] = b6; - n6[h6 + P2 + 32] = b6; - n6[h6 + P2 + 40] = b6; - n6[h6 + P2 + 48] = b6; - n6[h6 + P2 + 56] = b6; + n12[h6 + P3] = b6; + n12[h6 + P3 + 8] = b6; + n12[h6 + P3 + 16] = b6; + n12[h6 + P3 + 24] = b6; + n12[h6 + P3 + 32] = b6; + n12[h6 + P3 + 40] = b6; + n12[h6 + P3 + 48] = b6; + n12[h6 + P3 + 56] = b6; continue; } E3 = s6 * J3 + 2048 >> 12; a6 = s6 * m6 + 2048 >> 12; - C3 = Y3; - F3 = v7; - d6 = ad2 * (V2 - $) + 2048 >> 12; - z3 = ad2 * (V2 + $) + 2048 >> 12; - T2 = u6; - U2 = j6; + C4 = Y4; + F4 = v8; + d6 = ad2 * (V3 - $) + 2048 >> 12; + z3 = ad2 * (V3 + $) + 2048 >> 12; + T3 = u6; + U3 = j7; E3 = (E3 + a6 + 1 >> 1) + 4112; a6 = E3 - a6; - b6 = C3 * ai2 + F3 * ar2 + 2048 >> 12; - C3 = C3 * ar2 - F3 * ai2 + 2048 >> 12; - F3 = b6; - d6 = d6 + U2 + 1 >> 1; - U2 = d6 - U2; - z3 = z3 + T2 + 1 >> 1; - T2 = z3 - T2; - E3 = E3 + F3 + 1 >> 1; - F3 = E3 - F3; - a6 = a6 + C3 + 1 >> 1; - C3 = a6 - C3; + b6 = C4 * ai3 + F4 * ar2 + 2048 >> 12; + C4 = C4 * ar2 - F4 * ai3 + 2048 >> 12; + F4 = b6; + d6 = d6 + U3 + 1 >> 1; + U3 = d6 - U3; + z3 = z3 + T3 + 1 >> 1; + T3 = z3 - T3; + E3 = E3 + F4 + 1 >> 1; + F4 = E3 - F4; + a6 = a6 + C4 + 1 >> 1; + C4 = a6 - C4; b6 = d6 * ao2 + z3 * ah2 + 2048 >> 12; d6 = d6 * ah2 - z3 * ao2 + 2048 >> 12; z3 = b6; - b6 = T2 * ac2 + U2 * t12 + 2048 >> 12; - T2 = T2 * t12 - U2 * ac2 + 2048 >> 12; - U2 = b6; + b6 = T3 * ac2 + U3 * t12 + 2048 >> 12; + T3 = T3 * t12 - U3 * ac2 + 2048 >> 12; + U3 = b6; J3 = E3 + z3; $ = E3 - z3; - V2 = a6 + U2; - v7 = a6 - U2; - Y3 = C3 + T2; - j6 = C3 - T2; - u6 = F3 + d6; - m6 = F3 - d6; + V3 = a6 + U3; + v8 = a6 - U3; + Y4 = C4 + T3; + j7 = C4 - T3; + u6 = F4 + d6; + m6 = F4 - d6; if (J3 < 16) { J3 = 0; } else if (J3 >= 4080) { @@ -57122,19 +58262,19 @@ var require_UTIF = __commonJS({ } else { J3 >>= 4; } - if (V2 < 16) { - V2 = 0; - } else if (V2 >= 4080) { - V2 = 255; + if (V3 < 16) { + V3 = 0; + } else if (V3 >= 4080) { + V3 = 255; } else { - V2 >>= 4; + V3 >>= 4; } - if (Y3 < 16) { - Y3 = 0; - } else if (Y3 >= 4080) { - Y3 = 255; + if (Y4 < 16) { + Y4 = 0; + } else if (Y4 >= 4080) { + Y4 = 255; } else { - Y3 >>= 4; + Y4 >>= 4; } if (u6 < 16) { u6 = 0; @@ -57150,19 +58290,19 @@ var require_UTIF = __commonJS({ } else { m6 >>= 4; } - if (j6 < 16) { - j6 = 0; - } else if (j6 >= 4080) { - j6 = 255; + if (j7 < 16) { + j7 = 0; + } else if (j7 >= 4080) { + j7 = 255; } else { - j6 >>= 4; + j7 >>= 4; } - if (v7 < 16) { - v7 = 0; - } else if (v7 >= 4080) { - v7 = 255; + if (v8 < 16) { + v8 = 0; + } else if (v8 >= 4080) { + v8 = 255; } else { - v7 >>= 4; + v8 >>= 4; } if ($ < 16) { $ = 0; @@ -57171,81 +58311,81 @@ var require_UTIF = __commonJS({ } else { $ >>= 4; } - n6[h6 + P2] = J3; - n6[h6 + P2 + 8] = V2; - n6[h6 + P2 + 16] = Y3; - n6[h6 + P2 + 24] = u6; - n6[h6 + P2 + 32] = m6; - n6[h6 + P2 + 40] = j6; - n6[h6 + P2 + 48] = v7; - n6[h6 + P2 + 56] = $; + n12[h6 + P3] = J3; + n12[h6 + P3 + 8] = V3; + n12[h6 + P3 + 16] = Y4; + n12[h6 + P3 + 24] = u6; + n12[h6 + P3 + 32] = m6; + n12[h6 + P3 + 40] = j7; + n12[h6 + P3 + 48] = v8; + n12[h6 + P3 + 56] = $; } } - function a0(Q2, h6) { - var f6 = h6.P, G3 = h6.c, n6 = new Int16Array(64); - for (var E3 = 0; E3 < G3; E3++) { + function a0(Q3, h6) { + var f6 = h6.P, G4 = h6.c, n12 = new Int16Array(64); + for (var E3 = 0; E3 < G4; E3++) { for (var a6 = 0; a6 < f6; a6++) { - var C3 = a22(h6, E3, a6); - al2(h6, C3, n6); + var C4 = a22(h6, E3, a6); + al2(h6, C4, n12); } } return h6.D; } - function an2(Q2, h6, f6) { + function an2(Q3, h6, f6) { if (f6 == null) f6 = h6; - var G3 = Q2.length - 1, n6 = f6 < h6 ? f6 : h6; - if (h6 >= G3) { + var G4 = Q3.length - 1, n12 = f6 < h6 ? f6 : h6; + if (h6 >= G4) { return null; } - var E3 = Z2(Q2, h6); + var E3 = Z2(Q3, h6); if (E3 >= 65472 && E3 <= 65534) { return { u: null, M: E3, offset: h6 }; } - var a6 = Z2(Q2, n6); + var a6 = Z2(Q3, n12); while (!(a6 >= 65472 && a6 <= 65534)) { - if (++n6 >= G3) { + if (++n12 >= G4) { return null; } - a6 = Z2(Q2, n6); + a6 = Z2(Q3, n12); } - return { u: E3.toString(16), M: a6, offset: n6 }; + return { u: E3.toString(16), M: a6, offset: n12 }; } - ak3.prototype = { parse(Q2, h6) { + ak3.prototype = { parse(Q3, h6) { if (h6 == null) h6 = {}; - var f6 = h6.F, E3 = 0, a6 = null, C3 = null, F3, d6, T2 = 0; - function G3() { - var o6 = Z2(Q2, E3); + var f6 = h6.F, E3 = 0, a6 = null, C4 = null, F4, d6, T3 = 0; + function G4() { + var o6 = Z2(Q3, E3); E3 += 2; - var B3 = E3 + o6 - 2, V3 = an2(Q2, B3, E3); - if (V3 && V3.u) { - B3 = V3.offset; + var B4 = E3 + o6 - 2, V4 = an2(Q3, B4, E3); + if (V4 && V4.u) { + B4 = V4.offset; } - var ab2 = Q2.subarray(E3, B3); + var ab2 = Q3.subarray(E3, B4); E3 += ab2.length; return ab2; } - function n6(F4) { - var o6 = Math.ceil(F4.o / 8 / F4.X), B3 = Math.ceil(F4.s / 8 / F4.B); - for (var Y4 = 0; Y4 < F4.W.length; Y4++) { - R2 = F4.W[Y4]; - var ab2 = Math.ceil(Math.ceil(F4.o / 8) * R2.h / F4.X), af2 = Math.ceil(Math.ceil(F4.s / 8) * R2.A / F4.B), ap2 = o6 * R2.h, aq2 = B3 * R2.A, ae2 = 64 * aq2 * (ap2 + 1); - R2.D = new Int16Array(ae2); - R2.P = ab2; - R2.c = af2; + function n12(F5) { + var o6 = Math.ceil(F5.o / 8 / F5.X), B4 = Math.ceil(F5.s / 8 / F5.B); + for (var Y5 = 0; Y5 < F5.W.length; Y5++) { + R3 = F5.W[Y5]; + var ab2 = Math.ceil(Math.ceil(F5.o / 8) * R3.h / F5.X), af2 = Math.ceil(Math.ceil(F5.s / 8) * R3.A / F5.B), ap2 = o6 * R3.h, aq2 = B4 * R3.A, ae3 = 64 * aq2 * (ap2 + 1); + R3.D = new Int16Array(ae3); + R3.P = ab2; + R3.c = af2; } - F4.m = o6; - F4.R = B3; + F5.m = o6; + F5.R = B4; } - var U2 = [], z3 = [], J3 = [], V2 = Z2(Q2, E3); + var U3 = [], z3 = [], J3 = [], V3 = Z2(Q3, E3); E3 += 2; - if (V2 !== 65496) { - throw new W2("SOI not found"); + if (V3 !== 65496) { + throw new W3("SOI not found"); } - V2 = Z2(Q2, E3); + V3 = Z2(Q3, E3); E3 += 2; - markerLoop: while (V2 !== 65497) { - var Y3, u6, m6; - switch (V2) { + markerLoop: while (V3 !== 65497) { + var Y4, u6, m6; + switch (V3) { case 65504: case 65505: case 65506: @@ -57263,119 +58403,119 @@ var require_UTIF = __commonJS({ case 65518: case 65519: case 65534: - var j6 = G3(); - if (V2 === 65504) { - if (j6[0] === 74 && j6[1] === 70 && j6[2] === 73 && j6[3] === 70 && j6[4] === 0) { - a6 = { version: { d: j6[5], T: j6[6] }, K: j6[7], j: j6[8] << 8 | j6[9], H: j6[10] << 8 | j6[11], S: j6[12], I: j6[13], C: j6.subarray(14, 14 + 3 * j6[12] * j6[13]) }; + var j7 = G4(); + if (V3 === 65504) { + if (j7[0] === 74 && j7[1] === 70 && j7[2] === 73 && j7[3] === 70 && j7[4] === 0) { + a6 = { version: { d: j7[5], T: j7[6] }, K: j7[7], j: j7[8] << 8 | j7[9], H: j7[10] << 8 | j7[11], S: j7[12], I: j7[13], C: j7.subarray(14, 14 + 3 * j7[12] * j7[13]) }; } } - if (V2 === 65518) { - if (j6[0] === 65 && j6[1] === 100 && j6[2] === 111 && j6[3] === 98 && j6[4] === 101) { - C3 = { version: j6[5] << 8 | j6[6], k: j6[7] << 8 | j6[8], q: j6[9] << 8 | j6[10], a: j6[11] }; + if (V3 === 65518) { + if (j7[0] === 65 && j7[1] === 100 && j7[2] === 111 && j7[3] === 98 && j7[4] === 101) { + C4 = { version: j7[5] << 8 | j7[6], k: j7[7] << 8 | j7[8], q: j7[9] << 8 | j7[10], a: j7[11] }; } } break; case 65499: - var v7 = Z2(Q2, E3), b6; + var v8 = Z2(Q3, E3), b6; E3 += 2; - var $ = v7 + E3 - 2; + var $ = v8 + E3 - 2; while (E3 < $) { - var r6 = Q2[E3++], P2 = new Uint16Array(64); + var r6 = Q3[E3++], P3 = new Uint16Array(64); if (r6 >> 4 === 0) { for (u6 = 0; u6 < 64; u6++) { b6 = p6[u6]; - P2[b6] = Q2[E3++]; + P3[b6] = Q3[E3++]; } } else if (r6 >> 4 === 1) { for (u6 = 0; u6 < 64; u6++) { b6 = p6[u6]; - P2[b6] = Z2(Q2, E3); + P3[b6] = Z2(Q3, E3); E3 += 2; } } else { - throw new W2("DQT - invalid table spec"); + throw new W3("DQT - invalid table spec"); } - U2[r6 & 15] = P2; + U3[r6 & 15] = P3; } break; case 65472: case 65473: case 65474: - if (F3) { - throw new W2("Only single frame JPEGs supported"); + if (F4) { + throw new W3("Only single frame JPEGs supported"); } E3 += 2; - F3 = {}; - F3.G = V2 === 65473; - F3.Z = V2 === 65474; - F3.precision = Q2[E3++]; - var D3 = Z2(Q2, E3), a42, q6 = 0, H3 = 0; + F4 = {}; + F4.G = V3 === 65473; + F4.Z = V3 === 65474; + F4.precision = Q3[E3++]; + var D4 = Z2(Q3, E3), a42, q7 = 0, H4 = 0; E3 += 2; - F3.s = f6 || D3; - F3.o = Z2(Q2, E3); + F4.s = f6 || D4; + F4.o = Z2(Q3, E3); E3 += 2; - F3.W = []; - F3._ = {}; - var a8 = Q2[E3++]; - for (Y3 = 0; Y3 < a8; Y3++) { - a42 = Q2[E3]; - var w6 = Q2[E3 + 1] >> 4, y4 = Q2[E3 + 1] & 15; - if (q6 < w6) { - q6 = w6; + F4.W = []; + F4._ = {}; + var a8 = Q3[E3++]; + for (Y4 = 0; Y4 < a8; Y4++) { + a42 = Q3[E3]; + var w6 = Q3[E3 + 1] >> 4, y4 = Q3[E3 + 1] & 15; + if (q7 < w6) { + q7 = w6; } - if (H3 < y4) { - H3 = y4; + if (H4 < y4) { + H4 = y4; } - var X2 = Q2[E3 + 2]; - m6 = F3.W.push({ h: w6, A: y4, L: X2, $: null }); - F3._[a42] = m6 - 1; + var X3 = Q3[E3 + 2]; + m6 = F4.W.push({ h: w6, A: y4, L: X3, $: null }); + F4._[a42] = m6 - 1; E3 += 3; } - F3.X = q6; - F3.B = H3; - n6(F3); + F4.X = q7; + F4.B = H4; + n12(F4); break; case 65476: - var O2 = Z2(Q2, E3); + var O3 = Z2(Q3, E3); E3 += 2; - for (Y3 = 2; Y3 < O2; ) { - var _ = Q2[E3++], N2 = new Uint8Array(16), e6 = 0; + for (Y4 = 2; Y4 < O3; ) { + var _2 = Q3[E3++], N3 = new Uint8Array(16), e6 = 0; for (u6 = 0; u6 < 16; u6++, E3++) { - e6 += N2[u6] = Q2[E3]; + e6 += N3[u6] = Q3[E3]; } var K3 = new Uint8Array(e6); for (u6 = 0; u6 < e6; u6++, E3++) { - K3[u6] = Q2[E3]; + K3[u6] = Q3[E3]; } - Y3 += 17 + e6; - (_ >> 4 === 0 ? J3 : z3)[_ & 15] = a52(N2, K3); + Y4 += 17 + e6; + (_2 >> 4 === 0 ? J3 : z3)[_2 & 15] = a52(N3, K3); } break; case 65501: E3 += 2; - d6 = Z2(Q2, E3); + d6 = Z2(Q3, E3); E3 += 2; break; case 65498: - var x7 = ++T2 === 1 && !f6, R2; + var x8 = ++T3 === 1 && !f6, R3; E3 += 2; - var k6 = Q2[E3++], g6 = []; - for (Y3 = 0; Y3 < k6; Y3++) { - var c7 = Q2[E3++], L2 = F3._[c7]; - R2 = F3.W[L2]; - R2.index = c7; - var a62 = Q2[E3++]; - R2.J = J3[a62 >> 4]; - R2.i = z3[a62 & 15]; - g6.push(R2); + var k7 = Q3[E3++], g6 = []; + for (Y4 = 0; Y4 < k7; Y4++) { + var c7 = Q3[E3++], L3 = F4._[c7]; + R3 = F4.W[L3]; + R3.index = c7; + var a62 = Q3[E3++]; + R3.J = J3[a62 >> 4]; + R3.i = z3[a62 & 15]; + g6.push(R3); } - var I3 = Q2[E3++], l6 = Q2[E3++], M2 = Q2[E3++]; + var I4 = Q3[E3++], l6 = Q3[E3++], M3 = Q3[E3++]; try { - var S2 = a7(Q2, E3, F3, g6, d6, I3, l6, M2 >> 4, M2 & 15, x7); + var S2 = a7(Q3, E3, F4, g6, d6, I4, l6, M3 >> 4, M3 & 15, x8); E3 += S2; } catch (ex) { if (ex instanceof DNLMarkerError) { - return this.parse(Q2, { F: ex.s }); + return this.parse(Q3, { F: ex.s }); } else if (ex instanceof EOIMarkerError) { break markerLoop; } @@ -57386,77 +58526,77 @@ var require_UTIF = __commonJS({ E3 += 4; break; case 65535: - if (Q2[E3] !== 255) { + if (Q3[E3] !== 255) { E3--; } break; default: - var i6 = an2(Q2, E3 - 2, E3 - 3); + var i6 = an2(Q3, E3 - 2, E3 - 3); if (i6 && i6.u) { E3 = i6.offset; break; } - if (E3 >= Q2.length - 1) { + if (E3 >= Q3.length - 1) { break markerLoop; } - throw new W2("JpegImage.parse - unknown marker: " + V2.toString(16)); + throw new W3("JpegImage.parse - unknown marker: " + V3.toString(16)); } - V2 = Z2(Q2, E3); + V3 = Z2(Q3, E3); E3 += 2; } - this.width = F3.o; - this.height = F3.s; + this.width = F4.o; + this.height = F4.s; this.g = a6; - this.b = C3; + this.b = C4; this.W = []; - for (Y3 = 0; Y3 < F3.W.length; Y3++) { - R2 = F3.W[Y3]; - var A3 = U2[R2.L]; - if (A3) { - R2.$ = A3; + for (Y4 = 0; Y4 < F4.W.length; Y4++) { + R3 = F4.W[Y4]; + var A4 = U3[R3.L]; + if (A4) { + R3.$ = A4; } - this.W.push({ index: R2.index, e: a0(F3, R2), l: R2.h / F3.X, t: R2.A / F3.B, P: R2.P, c: R2.c }); + this.W.push({ index: R3.index, e: a0(F4, R3), l: R3.h / F4.X, t: R3.A / F4.B, P: R3.P, c: R3.c }); } this.p = this.W.length; return void 0; - }, Y(Q2, h6, f6) { + }, Y(Q3, h6, f6) { if (f6 == null) f6 = false; - var G3 = this.width / Q2, n6 = this.height / h6, E3, a6, C3, F3, d6, T2, U2, z3, J3, V2, Y3 = 0, u6, m6 = this.W.length, j6 = Q2 * h6 * m6, v7 = new Uint8ClampedArray(j6), $ = new Uint32Array(Q2), b6 = 4294967288, r6; - for (U2 = 0; U2 < m6; U2++) { - E3 = this.W[U2]; - a6 = E3.l * G3; - C3 = E3.t * n6; - Y3 = U2; + var G4 = this.width / Q3, n12 = this.height / h6, E3, a6, C4, F4, d6, T3, U3, z3, J3, V3, Y4 = 0, u6, m6 = this.W.length, j7 = Q3 * h6 * m6, v8 = new Uint8ClampedArray(j7), $ = new Uint32Array(Q3), b6 = 4294967288, r6; + for (U3 = 0; U3 < m6; U3++) { + E3 = this.W[U3]; + a6 = E3.l * G4; + C4 = E3.t * n12; + Y4 = U3; u6 = E3.e; - F3 = E3.P + 1 << 3; + F4 = E3.P + 1 << 3; if (a6 !== r6) { - for (d6 = 0; d6 < Q2; d6++) { + for (d6 = 0; d6 < Q3; d6++) { z3 = 0 | d6 * a6; $[d6] = (z3 & b6) << 3 | z3 & 7; } r6 = a6; } - for (T2 = 0; T2 < h6; T2++) { - z3 = 0 | T2 * C3; - V2 = F3 * (z3 & b6) | (z3 & 7) << 3; - for (d6 = 0; d6 < Q2; d6++) { - v7[Y3] = u6[V2 + $[d6]]; - Y3 += m6; + for (T3 = 0; T3 < h6; T3++) { + z3 = 0 | T3 * C4; + V3 = F4 * (z3 & b6) | (z3 & 7) << 3; + for (d6 = 0; d6 < Q3; d6++) { + v8[Y4] = u6[V3 + $[d6]]; + Y4 += m6; } } } - var P2 = this.V; - if (!f6 && m6 === 4 && !P2) { - P2 = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); + var P3 = this.V; + if (!f6 && m6 === 4 && !P3) { + P3 = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); } - if (P2) { - for (U2 = 0; U2 < j6; ) { - for (z3 = 0, J3 = 0; z3 < m6; z3++, U2++, J3 += 2) { - v7[U2] = (v7[U2] * P2[J3] >> 8) + P2[J3 + 1]; + if (P3) { + for (U3 = 0; U3 < j7; ) { + for (z3 = 0, J3 = 0; z3 < m6; z3++, U3++, J3 += 2) { + v8[U3] = (v8[U3] * P3[J3] >> 8) + P3[J3 + 1]; } } } - return v7; + return v8; }, get f() { if (this.b) { return !!this.b.a; @@ -57473,76 +58613,76 @@ var require_UTIF = __commonJS({ return true; } return false; - }, z: function aj2(Q2) { - var h6, f6, G3; - for (var n6 = 0, E3 = Q2.length; n6 < E3; n6 += 3) { - h6 = Q2[n6]; - f6 = Q2[n6 + 1]; - G3 = Q2[n6 + 2]; - Q2[n6] = h6 - 179.456 + 1.402 * G3; - Q2[n6 + 1] = h6 + 135.459 - 0.344 * f6 - 0.714 * G3; - Q2[n6 + 2] = h6 - 226.816 + 1.772 * f6; + }, z: function aj2(Q3) { + var h6, f6, G4; + for (var n12 = 0, E3 = Q3.length; n12 < E3; n12 += 3) { + h6 = Q3[n12]; + f6 = Q3[n12 + 1]; + G4 = Q3[n12 + 2]; + Q3[n12] = h6 - 179.456 + 1.402 * G4; + Q3[n12 + 1] = h6 + 135.459 - 0.344 * f6 - 0.714 * G4; + Q3[n12 + 2] = h6 - 226.816 + 1.772 * f6; } - return Q2; - }, O: function aa2(Q2) { - var h6, f6, G3, n6, E3 = 0; - for (var a6 = 0, C3 = Q2.length; a6 < C3; a6 += 4) { - h6 = Q2[a6]; - f6 = Q2[a6 + 1]; - G3 = Q2[a6 + 2]; - n6 = Q2[a6 + 3]; - Q2[E3++] = -122.67195406894 + f6 * (-660635669420364e-19 * f6 + 437130475926232e-18 * G3 - 54080610064599e-18 * h6 + 48449797120281e-17 * n6 - 0.154362151871126) + G3 * (-957964378445773e-18 * G3 + 817076911346625e-18 * h6 - 0.00477271405408747 * n6 + 1.53380253221734) + h6 * (961250184130688e-18 * h6 - 0.00266257332283933 * n6 + 0.48357088451265) + n6 * (-336197177618394e-18 * n6 + 0.484791561490776); - Q2[E3++] = 107.268039397724 + f6 * (219927104525741e-19 * f6 - 640992018297945e-18 * G3 + 659397001245577e-18 * h6 + 426105652938837e-18 * n6 - 0.176491792462875) + G3 * (-778269941513683e-18 * G3 + 0.00130872261408275 * h6 + 770482631801132e-18 * n6 - 0.151051492775562) + h6 * (0.00126935368114843 * h6 - 0.00265090189010898 * n6 + 0.25802910206845) + n6 * (-318913117588328e-18 * n6 - 0.213742400323665); - Q2[E3++] = -20.810012546947 + f6 * (-570115196973677e-18 * f6 - 263409051004589e-19 * G3 + 0.0020741088115012 * h6 - 0.00288260236853442 * n6 + 0.814272968359295) + G3 * (-153496057440975e-19 * G3 - 132689043961446e-18 * h6 + 560833691242812e-18 * n6 - 0.195152027534049) + h6 * (0.00174418132927582 * h6 - 0.00255243321439347 * n6 + 0.116935020465145) + n6 * (-343531996510555e-18 * n6 + 0.24165260232407); + return Q3; + }, O: function aa2(Q3) { + var h6, f6, G4, n12, E3 = 0; + for (var a6 = 0, C4 = Q3.length; a6 < C4; a6 += 4) { + h6 = Q3[a6]; + f6 = Q3[a6 + 1]; + G4 = Q3[a6 + 2]; + n12 = Q3[a6 + 3]; + Q3[E3++] = -122.67195406894 + f6 * (-660635669420364e-19 * f6 + 437130475926232e-18 * G4 - 54080610064599e-18 * h6 + 48449797120281e-17 * n12 - 0.154362151871126) + G4 * (-957964378445773e-18 * G4 + 817076911346625e-18 * h6 - 0.00477271405408747 * n12 + 1.53380253221734) + h6 * (961250184130688e-18 * h6 - 0.00266257332283933 * n12 + 0.48357088451265) + n12 * (-336197177618394e-18 * n12 + 0.484791561490776); + Q3[E3++] = 107.268039397724 + f6 * (219927104525741e-19 * f6 - 640992018297945e-18 * G4 + 659397001245577e-18 * h6 + 426105652938837e-18 * n12 - 0.176491792462875) + G4 * (-778269941513683e-18 * G4 + 0.00130872261408275 * h6 + 770482631801132e-18 * n12 - 0.151051492775562) + h6 * (0.00126935368114843 * h6 - 0.00265090189010898 * n12 + 0.25802910206845) + n12 * (-318913117588328e-18 * n12 - 0.213742400323665); + Q3[E3++] = -20.810012546947 + f6 * (-570115196973677e-18 * f6 - 263409051004589e-19 * G4 + 0.0020741088115012 * h6 - 0.00288260236853442 * n12 + 0.814272968359295) + G4 * (-153496057440975e-19 * G4 - 132689043961446e-18 * h6 + 560833691242812e-18 * n12 - 0.195152027534049) + h6 * (0.00174418132927582 * h6 - 0.00255243321439347 * n12 + 0.116935020465145) + n12 * (-343531996510555e-18 * n12 + 0.24165260232407); } - return Q2.subarray(0, E3); - }, r: function a32(Q2) { - var h6, f6, G3; - for (var n6 = 0, E3 = Q2.length; n6 < E3; n6 += 4) { - h6 = Q2[n6]; - f6 = Q2[n6 + 1]; - G3 = Q2[n6 + 2]; - Q2[n6] = 434.456 - h6 - 1.402 * G3; - Q2[n6 + 1] = 119.541 - h6 + 0.344 * f6 + 0.714 * G3; - Q2[n6 + 2] = 481.816 - h6 - 1.772 * f6; + return Q3.subarray(0, E3); + }, r: function a32(Q3) { + var h6, f6, G4; + for (var n12 = 0, E3 = Q3.length; n12 < E3; n12 += 4) { + h6 = Q3[n12]; + f6 = Q3[n12 + 1]; + G4 = Q3[n12 + 2]; + Q3[n12] = 434.456 - h6 - 1.402 * G4; + Q3[n12 + 1] = 119.541 - h6 + 0.344 * f6 + 0.714 * G4; + Q3[n12 + 2] = 481.816 - h6 - 1.772 * f6; } - return Q2; - }, U: function as2(Q2) { - var h6, f6, G3, n6, E3 = 0; - for (var a6 = 0, C3 = Q2.length; a6 < C3; a6 += 4) { - h6 = Q2[a6]; - f6 = Q2[a6 + 1]; - G3 = Q2[a6 + 2]; - n6 = Q2[a6 + 3]; - Q2[E3++] = 255 + h6 * (-6747147073602441e-20 * h6 + 8379262121013727e-19 * f6 + 2894718188643294e-19 * G3 + 0.003264231057537806 * n6 - 1.1185611867203937) + f6 * (26374107616089405e-21 * f6 - 8626949158638572e-20 * G3 - 2748769067499491e-19 * n6 - 0.02155688794978967) + G3 * (-3878099212869363e-20 * G3 - 3267808279485286e-19 * n6 + 0.0686742238595345) - n6 * (3361971776183937e-19 * n6 + 0.7430659151342254); - Q2[E3++] = 255 + h6 * (13596372813588848e-20 * h6 + 924537132573585e-18 * f6 + 10567359618683593e-20 * G3 + 4791864687436512e-19 * n6 - 0.3109689587515875) + f6 * (-23545346108370344e-20 * f6 + 2702845253534714e-19 * G3 + 0.0020200308977307156 * n6 - 0.7488052167015494) + G3 * (6834815998235662e-20 * G3 + 15168452363460973e-20 * n6 - 0.09751927774728933) - n6 * (3189131175883281e-19 * n6 + 0.7364883807733168); - Q2[E3++] = 255 + h6 * (13598650411385307e-21 * h6 + 12423956175490851e-20 * f6 + 4751985097583589e-19 * G3 - 36729317476630422e-22 * n6 - 0.05562186980264034) + f6 * (16141380598724676e-20 * f6 + 9692239130725186e-19 * G3 + 7782692450036253e-19 * n6 - 0.44015232367526463) + G3 * (5068882914068769e-22 * G3 + 0.0017778369011375071 * n6 - 0.7591454649749609) - n6 * (3435319965105553e-19 * n6 + 0.7063770186160144); + return Q3; + }, U: function as3(Q3) { + var h6, f6, G4, n12, E3 = 0; + for (var a6 = 0, C4 = Q3.length; a6 < C4; a6 += 4) { + h6 = Q3[a6]; + f6 = Q3[a6 + 1]; + G4 = Q3[a6 + 2]; + n12 = Q3[a6 + 3]; + Q3[E3++] = 255 + h6 * (-6747147073602441e-20 * h6 + 8379262121013727e-19 * f6 + 2894718188643294e-19 * G4 + 0.003264231057537806 * n12 - 1.1185611867203937) + f6 * (26374107616089405e-21 * f6 - 8626949158638572e-20 * G4 - 2748769067499491e-19 * n12 - 0.02155688794978967) + G4 * (-3878099212869363e-20 * G4 - 3267808279485286e-19 * n12 + 0.0686742238595345) - n12 * (3361971776183937e-19 * n12 + 0.7430659151342254); + Q3[E3++] = 255 + h6 * (13596372813588848e-20 * h6 + 924537132573585e-18 * f6 + 10567359618683593e-20 * G4 + 4791864687436512e-19 * n12 - 0.3109689587515875) + f6 * (-23545346108370344e-20 * f6 + 2702845253534714e-19 * G4 + 0.0020200308977307156 * n12 - 0.7488052167015494) + G4 * (6834815998235662e-20 * G4 + 15168452363460973e-20 * n12 - 0.09751927774728933) - n12 * (3189131175883281e-19 * n12 + 0.7364883807733168); + Q3[E3++] = 255 + h6 * (13598650411385307e-21 * h6 + 12423956175490851e-20 * f6 + 4751985097583589e-19 * G4 - 36729317476630422e-22 * n12 - 0.05562186980264034) + f6 * (16141380598724676e-20 * f6 + 9692239130725186e-19 * G4 + 7782692450036253e-19 * n12 - 0.44015232367526463) + G4 * (5068882914068769e-22 * G4 + 0.0017778369011375071 * n12 - 0.7591454649749609) - n12 * (3435319965105553e-19 * n12 + 0.7063770186160144); } - return Q2.subarray(0, E3); - }, getData: function(Q2) { - var h6 = Q2.width, f6 = Q2.height, G3 = Q2.forceRGB, n6 = Q2.isSourcePDF; + return Q3.subarray(0, E3); + }, getData: function(Q3) { + var h6 = Q3.width, f6 = Q3.height, G4 = Q3.forceRGB, n12 = Q3.isSourcePDF; if (this.p > 4) { - throw new W2("Unsupported color mode"); + throw new W3("Unsupported color mode"); } - var E3 = this.Y(h6, f6, n6); - if (this.p === 1 && G3) { - var a6 = E3.length, C3 = new Uint8ClampedArray(a6 * 3), F3 = 0; + var E3 = this.Y(h6, f6, n12); + if (this.p === 1 && G4) { + var a6 = E3.length, C4 = new Uint8ClampedArray(a6 * 3), F4 = 0; for (var d6 = 0; d6 < a6; d6++) { - var T2 = E3[d6]; - C3[F3++] = T2; - C3[F3++] = T2; - C3[F3++] = T2; + var T3 = E3[d6]; + C4[F4++] = T3; + C4[F4++] = T3; + C4[F4++] = T3; } - return C3; + return C4; } else if (this.p === 3 && this.f) { return this.z(E3); } else if (this.p === 4) { if (this.f) { - if (G3) { + if (G4) { return this.O(E3); } return this.r(E3); - } else if (G3) { + } else if (G4) { return this.U(E3); } } @@ -57669,21 +58809,21 @@ var require_UTIF = __commonJS({ var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0); console.log("====", tx, ty); for (var y4 = 0; y4 < ty; y4++) - for (var x7 = 0; x7 < tx; x7++) { - var i6 = y4 * tx + x7; + for (var x8 = 0; x8 < tx; x8++) { + var i6 = y4 * tx + x8; tbuff.fill(0); UTIF2.decode._decompress(img, ifds, data, soff[i6], bcnt[i6], cmpr, tbuff, 0, fo, tw, th); if (cmpr == 6) bytes = tbuff; - else UTIF2._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x7 * tw * bipp / 8) | 0, y4 * th); + else UTIF2._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x8 * tw * bipp / 8) | 0, y4 * th); } bilen = bytes.length * 8; } else { if (soff == null) return; - var rps2 = img["t278"] ? img["t278"][0] : img.height; - rps2 = Math.min(rps2, img.height); + var rps = img["t278"] ? img["t278"][0] : img.height; + rps = Math.min(rps, img.height); for (var i6 = 0; i6 < soff.length; i6++) { - UTIF2.decode._decompress(img, ifds, data, soff[i6], bcnt[i6], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps2); - bilen += bipl * rps2; + UTIF2.decode._decompress(img, ifds, data, soff[i6], bcnt[i6], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps); + bilen += bipl * rps; } bilen = Math.min(bilen, bytes.length * 8); } @@ -57692,7 +58832,7 @@ var require_UTIF = __commonJS({ UTIF2.decode._decompress = function(img, ifds, data, off, len, cmpr, tgt, toff, fo, w6, h6) { if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) cmpr = 34316; if (false) { - } else if (cmpr == 1) for (var j6 = 0; j6 < len; j6++) tgt[toff + j6] = data[off + j6]; + } else if (cmpr == 1) for (var j7 = 0; j7 < len; j7++) tgt[toff + j7] = data[off + j7]; else if (cmpr == 2) UTIF2.decode._decodeG2(data, off, len, tgt, toff, w6, fo); else if (cmpr == 3) UTIF2.decode._decodeG3(data, off, len, tgt, toff, w6, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false); else if (cmpr == 4) UTIF2.decode._decodeG4(data, off, len, tgt, toff, w6, fo); @@ -57717,26 +58857,26 @@ var require_UTIF = __commonJS({ if (bps == 16 && !img.isLE && img["t33422"] == null) for (var y4 = 0; y4 < h6; y4++) { var roff = toff + y4 * bpl; - for (var x7 = 1; x7 < bpl; x7 += 2) { - var t12 = tgt[roff + x7]; - tgt[roff + x7] = tgt[roff + x7 - 1]; - tgt[roff + x7 - 1] = t12; + for (var x8 = 1; x8 < bpl; x8 += 2) { + var t12 = tgt[roff + x8]; + tgt[roff + x8] = tgt[roff + x8 - 1]; + tgt[roff + x8 - 1] = t12; } } if (img["t317"] && img["t317"][0] == 2) { for (var y4 = 0; y4 < h6; y4++) { var ntoff = toff + y4 * bpl; - if (bps == 16) for (var j6 = bpp; j6 < bpl; j6 += 2) { - var nv = (tgt[ntoff + j6 + 1] << 8 | tgt[ntoff + j6]) + (tgt[ntoff + j6 - bpp + 1] << 8 | tgt[ntoff + j6 - bpp]); - tgt[ntoff + j6] = nv & 255; - tgt[ntoff + j6 + 1] = nv >>> 8 & 255; + if (bps == 16) for (var j7 = bpp; j7 < bpl; j7 += 2) { + var nv = (tgt[ntoff + j7 + 1] << 8 | tgt[ntoff + j7]) + (tgt[ntoff + j7 - bpp + 1] << 8 | tgt[ntoff + j7 - bpp]); + tgt[ntoff + j7] = nv & 255; + tgt[ntoff + j7 + 1] = nv >>> 8 & 255; } - else if (noc == 3) for (var j6 = 3; j6 < bpl; j6 += 3) { - tgt[ntoff + j6] = tgt[ntoff + j6] + tgt[ntoff + j6 - 3] & 255; - tgt[ntoff + j6 + 1] = tgt[ntoff + j6 + 1] + tgt[ntoff + j6 - 2] & 255; - tgt[ntoff + j6 + 2] = tgt[ntoff + j6 + 2] + tgt[ntoff + j6 - 1] & 255; + else if (noc == 3) for (var j7 = 3; j7 < bpl; j7 += 3) { + tgt[ntoff + j7] = tgt[ntoff + j7] + tgt[ntoff + j7 - 3] & 255; + tgt[ntoff + j7 + 1] = tgt[ntoff + j7 + 1] + tgt[ntoff + j7 - 2] & 255; + tgt[ntoff + j7 + 2] = tgt[ntoff + j7 + 2] + tgt[ntoff + j7 - 1] & 255; } - else for (var j6 = bpp; j6 < bpl; j6++) tgt[ntoff + j6] = tgt[ntoff + j6] + tgt[ntoff + j6 - bpp] & 255; + else for (var j7 = bpp; j7 < bpl; j7++) tgt[ntoff + j7] = tgt[ntoff + j7] + tgt[ntoff + j7 - bpp] & 255; } } }; @@ -57752,7 +58892,7 @@ var require_UTIF = __commonJS({ var byte = 0; var arr_a, arr_b; var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16); - var i6, j6, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; + var i6, j7, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; var row, col, crow; var buffer = new Uint8Array(16384); var result = new Uint16Array(tgt.buffer); @@ -57905,12 +59045,12 @@ var require_UTIF = __commonJS({ if (i6 % 3 == 2) sh = 4 >> 3 - getDataRaw(2); if (nonz[isOdd]) { - j6 = getDataRaw(8); - if (j6 != 0) { + j7 = getDataRaw(8); + if (j7 != 0) { pred[isOdd] -= 128 << sh; if (pred[isOdd] < 0 || sh == 4) pred[isOdd] &= ~(-1 << sh); - pred[isOdd] += j6 << sh; + pred[isOdd] += j7 << sh; } } else { nonz[isOdd] = getDataRaw(8); @@ -57923,7 +59063,7 @@ var require_UTIF = __commonJS({ } else throw RW2_Format; }; UTIF2.decode._decodeVC5 = (function() { - var x7 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o6, C3, k6, P2 = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V2 = 24576, ar2 = 16384, H3 = 8192, az2 = ar2 | H3; + var x8 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o6, C4, k7, P3 = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V3 = 24576, ar2 = 16384, H4 = 8192, az2 = ar2 | H4; function d6(t12) { var E3 = t12[1], h6 = t12[0][E3 >>> 3] >>> 7 - (E3 & 7) & 1; t12[1]++; @@ -57932,17 +59072,17 @@ var require_UTIF = __commonJS({ function ag2(t12, E3) { if (o6 == null) { o6 = {}; - for (var h6 = 0; h6 < x7.length; h6 += 4) o6[x7[h6 + 1]] = x7.slice(h6, h6 + 4); + for (var h6 = 0; h6 < x8.length; h6 += 4) o6[x8[h6 + 1]] = x8.slice(h6, h6 + 4); } - var L2 = d6(t12), g6 = o6[L2]; + var L3 = d6(t12), g6 = o6[L3]; while (g6 == null) { - L2 = L2 << 1 | d6(t12); - g6 = o6[L2]; + L3 = L3 << 1 | d6(t12); + g6 = o6[L3]; } - var n6 = g6[3]; - if (n6 != 0) n6 = d6(t12) == 0 ? n6 : -n6; + var n12 = g6[3]; + if (n12 != 0) n12 = d6(t12) == 0 ? n12 : -n12; E3[0] = g6[2]; - E3[1] = n6; + E3[1] = n12; } function m6(t12, E3) { for (var h6 = 0; h6 < E3; h6++) { @@ -57951,158 +59091,158 @@ var require_UTIF = __commonJS({ } return t12; } - function A3(t12, E3) { + function A4(t12, E3) { return t12 >> E3; } - function O2(t12, E3, h6, L2, g6, n6) { - E3[h6] = A3(A3(11 * t12[g6] - 4 * t12[g6 + n6] + t12[g6 + n6 + n6] + 4, 3) + t12[L2], 1); - E3[h6 + n6] = A3(A3(5 * t12[g6] + 4 * t12[g6 + n6] - t12[g6 + n6 + n6] + 4, 3) - t12[L2], 1); + function O3(t12, E3, h6, L3, g6, n12) { + E3[h6] = A4(A4(11 * t12[g6] - 4 * t12[g6 + n12] + t12[g6 + n12 + n12] + 4, 3) + t12[L3], 1); + E3[h6 + n12] = A4(A4(5 * t12[g6] + 4 * t12[g6 + n12] - t12[g6 + n12 + n12] + 4, 3) - t12[L3], 1); } - function J3(t12, E3, h6, L2, g6, n6) { - var W2 = t12[g6 - n6] - t12[g6 + n6], j6 = t12[g6], $ = t12[L2]; - E3[h6] = A3(A3(W2 + 4, 3) + j6 + $, 1); - E3[h6 + n6] = A3(A3(-W2 + 4, 3) + j6 - $, 1); + function J3(t12, E3, h6, L3, g6, n12) { + var W3 = t12[g6 - n12] - t12[g6 + n12], j7 = t12[g6], $ = t12[L3]; + E3[h6] = A4(A4(W3 + 4, 3) + j7 + $, 1); + E3[h6 + n12] = A4(A4(-W3 + 4, 3) + j7 - $, 1); } - function y4(t12, E3, h6, L2, g6, n6) { - E3[h6] = A3(A3(5 * t12[g6] + 4 * t12[g6 - n6] - t12[g6 - n6 - n6] + 4, 3) + t12[L2], 1); - E3[h6 + n6] = A3(A3(11 * t12[g6] - 4 * t12[g6 - n6] + t12[g6 - n6 - n6] + 4, 3) - t12[L2], 1); + function y4(t12, E3, h6, L3, g6, n12) { + E3[h6] = A4(A4(5 * t12[g6] + 4 * t12[g6 - n12] - t12[g6 - n12 - n12] + 4, 3) + t12[L3], 1); + E3[h6 + n12] = A4(A4(11 * t12[g6] - 4 * t12[g6 - n12] + t12[g6 - n12 - n12] + 4, 3) - t12[L3], 1); } - function q6(t12) { + function q7(t12) { t12 = t12 < 0 ? 0 : t12 > 4095 ? 4095 : t12; - t12 = k6[t12] >>> 2; + t12 = k7[t12] >>> 2; return t12; } - function av2(t12, E3, h6, L2, g6, n6) { - L2 = new Uint16Array(L2.buffer); - var W2 = Date.now(), j6 = UTIF2._binBE, $ = E3 + h6, r6, u6, X2, I3, ax2, a32, R2, ai2, aa2, ap2, ah2, ae2, aD2, al2, i6, aE2, T2, B3; + function av2(t12, E3, h6, L3, g6, n12) { + L3 = new Uint16Array(L3.buffer); + var W3 = Date.now(), j7 = UTIF2._binBE, $ = E3 + h6, r6, u6, X3, I4, ax2, a32, R3, ai3, aa2, ap2, ah2, ae3, aD2, al2, i6, aE2, T3, B4; E3 += 4; - var a52 = n6[0] == 1; + var a52 = n12[0] == 1; while (E3 < $) { - var S2 = j6.readShort(t12, E3), s6 = j6.readUshort(t12, E3 + 2); + var S2 = j7.readShort(t12, E3), s6 = j7.readUshort(t12, E3 + 2); E3 += 4; if (S2 == 12) r6 = s6; else if (S2 == 20) u6 = s6; - else if (S2 == 21) X2 = s6; - else if (S2 == 48) I3 = s6; + else if (S2 == 21) X3 = s6; + else if (S2 == 48) I4 = s6; else if (S2 == 53) ax2 = s6; else if (S2 == 35) a32 = s6; - else if (S2 == 62) R2 = s6; - else if (S2 == 101) ai2 = s6; + else if (S2 == 62) R3 = s6; + else if (S2 == 101) ai3 = s6; else if (S2 == 109) aa2 = s6; else if (S2 == 84) ap2 = s6; else if (S2 == 106) ah2 = s6; - else if (S2 == 107) ae2 = s6; + else if (S2 == 107) ae3 = s6; else if (S2 == 108) aD2 = s6; else if (S2 == 102) al2 = s6; else if (S2 == 104) i6 = s6; else if (S2 == 105) aE2 = s6; else { - var F3 = S2 < 0 ? -S2 : S2, D3 = F3 & 65280, _ = 0; - if (F3 & az2) { - if (F3 & H3) { - _ = s6 & 65535; - _ += (F3 & 255) << 16; + var F4 = S2 < 0 ? -S2 : S2, D4 = F4 & 65280, _2 = 0; + if (F4 & az2) { + if (F4 & H4) { + _2 = s6 & 65535; + _2 += (F4 & 255) << 16; } else { - _ = s6 & 65535; + _2 = s6 & 65535; } } - if ((F3 & V2) == V2) { - if (T2 == null) { - T2 = []; - for (var M2 = 0; M2 < 4; M2++) T2[M2] = new Int16Array((u6 >>> 1) * (X2 >>> 1)); - B3 = new Int16Array((u6 >>> 1) * (X2 >>> 1)); - C3 = new Int16Array(1024); - for (var M2 = 0; M2 < 1024; M2++) { - var aG2 = M2 - 512, p6 = Math.abs(aG2), r6 = Math.floor(768 * p6 * p6 * p6 / (255 * 255 * 255)) + p6; - C3[M2] = Math.sign(aG2) * r6; + if ((F4 & V3) == V3) { + if (T3 == null) { + T3 = []; + for (var M3 = 0; M3 < 4; M3++) T3[M3] = new Int16Array((u6 >>> 1) * (X3 >>> 1)); + B4 = new Int16Array((u6 >>> 1) * (X3 >>> 1)); + C4 = new Int16Array(1024); + for (var M3 = 0; M3 < 1024; M3++) { + var aG2 = M3 - 512, p6 = Math.abs(aG2), r6 = Math.floor(768 * p6 * p6 * p6 / (255 * 255 * 255)) + p6; + C4[M3] = Math.sign(aG2) * r6; } - k6 = new Uint16Array(4096); + k7 = new Uint16Array(4096); var aA2 = (1 << 16) - 1; - for (var M2 = 0; M2 < 4096; M2++) { - var at2 = M2, a1 = aA2 * (Math.pow(113, at2 / 4095) - 1) / 112; - k6[M2] = Math.min(a1, aA2); + for (var M3 = 0; M3 < 4096; M3++) { + var at3 = M3, a1 = aA2 * (Math.pow(113, at3 / 4095) - 1) / 112; + k7[M3] = Math.min(a1, aA2); } } - var w6 = T2[R2], v7 = m6(u6, 1 + P2[I3]), N2 = m6(X2, 1 + P2[I3]); - if (I3 == 0) { - for (var b6 = 0; b6 < N2; b6++) for (var G3 = 0; G3 < v7; G3++) { - var c7 = E3 + (b6 * v7 + G3) * 2; - w6[b6 * (u6 >>> 1) + G3] = t12[c7] << 8 | t12[c7 + 1]; + var w6 = T3[R3], v8 = m6(u6, 1 + P3[I4]), N3 = m6(X3, 1 + P3[I4]); + if (I4 == 0) { + for (var b6 = 0; b6 < N3; b6++) for (var G4 = 0; G4 < v8; G4++) { + var c7 = E3 + (b6 * v8 + G4) * 2; + w6[b6 * (u6 >>> 1) + G4] = t12[c7] << 8 | t12[c7 + 1]; } } else { - var a7 = [t12, E3 * 8], a42 = [], ay2 = 0, aw2 = v7 * N2, f6 = [0, 0], Q2 = 0, s6 = 0; + var a7 = [t12, E3 * 8], a42 = [], ay2 = 0, aw2 = v8 * N3, f6 = [0, 0], Q3 = 0, s6 = 0; while (ay2 < aw2) { ag2(a7, f6); - Q2 = f6[0]; + Q3 = f6[0]; s6 = f6[1]; - while (Q2 > 0) { + while (Q3 > 0) { a42[ay2++] = s6; - Q2--; + Q3--; } } - var l6 = (I3 - 1) % 3, aF2 = l6 != 1 ? v7 : 0, a22 = l6 != 0 ? N2 : 0; - for (var b6 = 0; b6 < N2; b6++) { - var af2 = (b6 + a22) * (u6 >>> 1) + aF2, au2 = b6 * v7; - for (var G3 = 0; G3 < v7; G3++) w6[af2 + G3] = C3[a42[au2 + G3] + 512] * ax2; + var l6 = (I4 - 1) % 3, aF2 = l6 != 1 ? v8 : 0, a22 = l6 != 0 ? N3 : 0; + for (var b6 = 0; b6 < N3; b6++) { + var af2 = (b6 + a22) * (u6 >>> 1) + aF2, au2 = b6 * v8; + for (var G4 = 0; G4 < v8; G4++) w6[af2 + G4] = C4[a42[au2 + G4] + 512] * ax2; } if (l6 == 2) { - var i6 = u6 >>> 1, an2 = v7 * 2, a9 = N2 * 2; - for (var b6 = 0; b6 < N2; b6++) { - for (var G3 = 0; G3 < an2; G3++) { - var M2 = b6 * 2 * i6 + G3, a6 = b6 * i6 + G3, e6 = N2 * i6 + a6; - if (b6 == 0) O2(w6, B3, M2, e6, a6, i6); - else if (b6 == N2 - 1) y4(w6, B3, M2, e6, a6, i6); - else J3(w6, B3, M2, e6, a6, i6); + var i6 = u6 >>> 1, an2 = v8 * 2, a9 = N3 * 2; + for (var b6 = 0; b6 < N3; b6++) { + for (var G4 = 0; G4 < an2; G4++) { + var M3 = b6 * 2 * i6 + G4, a6 = b6 * i6 + G4, e6 = N3 * i6 + a6; + if (b6 == 0) O3(w6, B4, M3, e6, a6, i6); + else if (b6 == N3 - 1) y4(w6, B4, M3, e6, a6, i6); + else J3(w6, B4, M3, e6, a6, i6); } } var Z2 = w6; - w6 = B3; - B3 = Z2; + w6 = B4; + B4 = Z2; for (var b6 = 0; b6 < a9; b6++) { - for (var G3 = 0; G3 < v7; G3++) { - var M2 = b6 * i6 + 2 * G3, a6 = b6 * i6 + G3, e6 = v7 + a6; - if (G3 == 0) O2(w6, B3, M2, e6, a6, 1); - else if (G3 == v7 - 1) y4(w6, B3, M2, e6, a6, 1); - else J3(w6, B3, M2, e6, a6, 1); + for (var G4 = 0; G4 < v8; G4++) { + var M3 = b6 * i6 + 2 * G4, a6 = b6 * i6 + G4, e6 = v8 + a6; + if (G4 == 0) O3(w6, B4, M3, e6, a6, 1); + else if (G4 == v8 - 1) y4(w6, B4, M3, e6, a6, 1); + else J3(w6, B4, M3, e6, a6, 1); } } var Z2 = w6; - w6 = B3; - B3 = Z2; - var aC2 = [], aB2 = 2 - ~~((I3 - 1) / 3); + w6 = B4; + B4 = Z2; + var aC2 = [], aB2 = 2 - ~~((I4 - 1) / 3); for (var K3 = 0; K3 < 3; K3++) aC2[K3] = aa2 >> 14 - K3 * 2 & 3; var a62 = aC2[aB2]; - if (a62 != 0) for (var b6 = 0; b6 < a9; b6++) for (var G3 = 0; G3 < an2; G3++) { - var M2 = b6 * i6 + G3; - w6[M2] = w6[M2] << a62; + if (a62 != 0) for (var b6 = 0; b6 < a9; b6++) for (var G4 = 0; G4 < an2; G4++) { + var M3 = b6 * i6 + G4; + w6[M3] = w6[M3] << a62; } } } - if (I3 == 9 && R2 == 3) { - var a8 = T2[0], ab2 = T2[1], aq2 = T2[2], as2 = T2[3]; - for (var b6 = 0; b6 < X2; b6 += 2) for (var G3 = 0; G3 < u6; G3 += 2) { - var U2 = b6 * u6 + G3, c7 = (b6 >>> 1) * (u6 >>> 1) + (G3 >>> 1), z3 = a8[c7], ao2 = ab2[c7] - 2048, ak2 = aq2[c7] - 2048, ad2 = as2[c7] - 2048, aj2 = (ao2 << 1) + z3, a0 = (ak2 << 1) + z3, aH2 = z3 + ad2, am2 = z3 - ad2; + if (I4 == 9 && R3 == 3) { + var a8 = T3[0], ab2 = T3[1], aq2 = T3[2], as3 = T3[3]; + for (var b6 = 0; b6 < X3; b6 += 2) for (var G4 = 0; G4 < u6; G4 += 2) { + var U3 = b6 * u6 + G4, c7 = (b6 >>> 1) * (u6 >>> 1) + (G4 >>> 1), z3 = a8[c7], ao2 = ab2[c7] - 2048, ak2 = aq2[c7] - 2048, ad2 = as3[c7] - 2048, aj2 = (ao2 << 1) + z3, a0 = (ak2 << 1) + z3, aH2 = z3 + ad2, am2 = z3 - ad2; if (a52) { - L2[U2] = q6(aH2); - L2[U2 + 1] = q6(a0); - L2[U2 + u6] = q6(aj2); - L2[U2 + u6 + 1] = q6(am2); + L3[U3] = q7(aH2); + L3[U3 + 1] = q7(a0); + L3[U3 + u6] = q7(aj2); + L3[U3 + u6 + 1] = q7(am2); } else { - L2[U2] = q6(aj2); - L2[U2 + 1] = q6(aH2); - L2[U2 + u6] = q6(am2); - L2[U2 + u6 + 1] = q6(a0); + L3[U3] = q7(aj2); + L3[U3 + 1] = q7(aH2); + L3[U3 + u6] = q7(am2); + L3[U3 + u6 + 1] = q7(a0); } } } - E3 += _ * 4; - } else if (F3 == 16388) { - E3 += _ * 4; - } else if (D3 == 8192 || D3 == 8448 || D3 == 9216) { - } else throw F3.toString(16); + E3 += _2 * 4; + } else if (F4 == 16388) { + E3 += _2 * 4; + } else if (D4 == 8192 || D4 == 8448 || D4 == 9216) { + } else throw F4.toString(16); } } - console.log(Date.now() - W2); + console.log(Date.now() - W3); } return av2; })(); @@ -58115,21 +59255,21 @@ var require_UTIF = __commonJS({ var c7 = data[off + io]; io++; if (c7 < 128) { - for (var j6 = 0; j6 < c7; j6++) out[oo + j6] = data[off + io + j6]; + for (var j7 = 0; j7 < c7; j7++) out[oo + j7] = data[off + io + j7]; oo += c7; io += c7; } else { c7 = c7 - 126; - for (var j6 = 0; j6 < c7; j6++) out[oo + j6] = data[off + io]; + for (var j7 = 0; j7 < c7; j7++) out[oo + j7] = data[off + io]; oo += c7; io++; } } - for (var x7 = 0; x7 < w6; x7++) { - tgt[toff + 0] = out[x7]; - tgt[toff + 1] = out[x7 + w6]; - tgt[toff + 2] = out[x7 + w6 * 2]; - tgt[toff + 4] = out[x7 + w6 * 3]; + for (var x8 = 0; x8 < w6; x8++) { + tgt[toff + 0] = out[x8]; + tgt[toff + 1] = out[x8 + w6]; + tgt[toff + 2] = out[x8 + w6 * 2]; + tgt[toff + 4] = out[x8 + w6 * 3]; toff += 6; } } @@ -58170,12 +59310,12 @@ var require_UTIF = __commonJS({ 514, 513 ]; - var i6, c7, n6, col, row, sum = 0; + var i6, c7, n12, col, row, sum = 0; var ljpeg_diff = UTIF2.decode._ljpeg_diff; huff[0] = 15; - for (n6 = i6 = 0; i6 < 18; i6++) { + for (n12 = i6 = 0; i6 < 18; i6++) { var lim = 32768 >>> (tab[i6] >>> 8); - for (var c7 = 0; c7 < lim; c7++) huff[++n6] = tab[i6]; + for (var c7 = 0; c7 < lim; c7++) huff[++n12] = tab[i6]; } for (col = raw_width; col--; ) for (row = 0; row < height + 1; row += 2) { @@ -58201,7 +59341,7 @@ var require_UTIF = __commonJS({ var row, col, val, max, min, imax, imin, sh, bit, i6, dp; var data = new Uint8Array(raw_width + 1); for (row = 0; row < height; row++) { - for (var j6 = 0; j6 < raw_width; j6++) data[j6] = inp[off++]; + for (var j7 = 0; j7 < raw_width; j7++) data[j7] = inp[off++]; for (dp = 0, col = 0; col < raw_width - 30; dp += 16) { max = 2047 & (val = bin.readUint(data, dp)); min = 2047 & val >>> 11; @@ -58442,8 +59582,8 @@ var require_UTIF = __commonJS({ if (ver0 == 70) tree = 2; if (tiff_bps == 14) tree += 3; var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF2._binLE : UTIF2._binBE; - for (var i6 = 0; i6 < 2; i6++) for (var j6 = 0; j6 < 2; j6++) { - vpred[i6][j6] = bin.readShort(md, mdo); + for (var i6 = 0; i6 < 2; i6++) for (var j7 = 0; j7 < 2; j7++) { + vpred[i6][j7] = bin.readShort(md, mdo); mdo += 2; } var max = 1 << tiff_bps & 32767, step = 0; @@ -58477,12 +59617,12 @@ var require_UTIF = __commonJS({ } } }; - UTIF2.decode._putsF = function(dt, pos, val) { + UTIF2.decode._putsF = function(dt2, pos, val) { val = val << 8 - (pos & 7); var o6 = pos >>> 3; - dt[o6] |= val >>> 16; - dt[o6 + 1] |= val >>> 8; - dt[o6 + 2] |= val; + dt2[o6] |= val >>> 16; + dt2[o6 + 1] |= val >>> 8; + dt2[o6 + 2] |= val; }; UTIF2.decode._getbithuff = function(data, prm, nbits, huff) { var zero_after_ff = 0; @@ -58508,16 +59648,16 @@ var require_UTIF = __commonJS({ return c7; }; UTIF2.decode._make_decoder = function(source) { - var max, len, h6, i6, j6; + var max, len, h6, i6, j7; var huff = []; for (max = 16; max != 0 && !source[max]; max--) ; - var si = 17; + var si2 = 17; huff[0] = max; for (h6 = len = 1; len <= max; len++) - for (i6 = 0; i6 < source[len]; i6++, ++si) - for (j6 = 0; j6 < 1 << max - len; j6++) + for (i6 = 0; i6 < source[len]; i6++, ++si2) + for (j7 = 0; j7 < 1 << max - len; j7++) if (h6 <= 1 << max) - huff[h6++] = len << 8 | source[si]; + huff[h6++] = len << 8 | source[si2]; return huff; }; UTIF2.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff) { @@ -58565,7 +59705,7 @@ var require_UTIF = __commonJS({ }; UTIF2.decode._decodeOldJPEGInit = function(img, data, off, len) { var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218; - var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i6, j6, k6; + var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i6, j7, k7; var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0; var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0; var soffTag = img["t324"] || img["t273"] || jpgIchgFmt; @@ -58611,21 +59751,21 @@ var require_UTIF = __commonJS({ out[ooff++] = 0; out[ooff++] = 67; out[ooff++] = i6; - for (j6 = 0; j6 < 64; j6++) out[ooff++] = data[off + qtables[i6] + j6]; + for (j7 = 0; j7 < 64; j7++) out[ooff++] = data[off + qtables[i6] + j7]; } - for (k6 = 0; k6 < 2; k6++) { - var htables = img[k6 == 0 ? "t520" : "t521"]; - if (htables == null) throw new Error((k6 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); + for (k7 = 0; k7 < 2; k7++) { + var htables = img[k7 == 0 ? "t520" : "t521"]; + if (htables == null) throw new Error((k7 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); for (i6 = 0; i6 < htables.length; i6++) { out[ooff++] = 255; out[ooff++] = DHT; var nc = 19; - for (j6 = 0; j6 < 16; j6++) nc += data[off + htables[i6] + j6]; + for (j7 = 0; j7 < 16; j7++) nc += data[off + htables[i6] + j7]; out[ooff++] = nc >>> 8; out[ooff++] = nc & 255; - out[ooff++] = i6 | k6 << 4; - for (j6 = 0; j6 < 16; j6++) out[ooff++] = data[off + htables[i6] + j6]; - for (j6 = 0; j6 < nc; j6++) out[ooff++] = data[off + htables[i6] + 16 + j6]; + out[ooff++] = i6 | k7 << 4; + for (j7 = 0; j7 < 16; j7++) out[ooff++] = data[off + htables[i6] + j7]; + for (j7 = 0; j7 < nc; j7++) out[ooff++] = data[off + htables[i6] + 16 + j7]; } } out[ooff++] = 255; @@ -58754,15 +59894,15 @@ var require_UTIF = __commonJS({ UTIF2.decode._decodePackBits = function(data, off, len, tgt, toff) { var sa = new Int8Array(data.buffer), ta = new Int8Array(tgt.buffer), lim = off + len; while (off < lim) { - var n6 = sa[off]; + var n12 = sa[off]; off++; - if (n6 >= 0 && n6 < 128) for (var i6 = 0; i6 < n6 + 1; i6++) { + if (n12 >= 0 && n12 < 128) for (var i6 = 0; i6 < n12 + 1; i6++) { ta[toff] = sa[off]; toff++; off++; } - if (n6 >= -127 && n6 < 0) { - for (var i6 = 0; i6 < -n6 + 1; i6++) { + if (n12 >= -127 && n12 < 0) { + for (var i6 = 0; i6 < -n12 + 1; i6++) { ta[toff] = sa[off]; toff++; } @@ -58775,19 +59915,19 @@ var require_UTIF = __commonJS({ var d22 = [0, 1, 0, -1], d32 = [0, 1, 2, 3, 0, -3, -2, -1]; var lim = off + len, qoff = toff * 2, px = 0; while (off < lim) { - var b6 = data[off], msk = b6 >>> 6, n6 = b6 & 63; + var b6 = data[off], msk = b6 >>> 6, n12 = b6 & 63; off++; if (msk == 3) { - px = n6 & 15; + px = n12 & 15; tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); qoff++; } - if (msk == 0) for (var i6 = 0; i6 < n6; i6++) { + if (msk == 0) for (var i6 = 0; i6 < n12; i6++) { tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); qoff++; } if (msk == 2) for (var i6 = 0; i6 < 2; i6++) { - var d6 = n6 >>> 3 * (1 - i6) & 7; + var d6 = n12 >>> 3 * (1 - i6) & 7; if (d6 != 4) { px += d32[d6]; tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); @@ -58795,7 +59935,7 @@ var require_UTIF = __commonJS({ } } if (msk == 1) for (var i6 = 0; i6 < 3; i6++) { - var d6 = n6 >>> 2 * (2 - i6) & 3; + var d6 = n12 >>> 2 * (2 - i6) & 3; if (d6 != 2) { px += d22[d6]; tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1); @@ -58829,27 +59969,27 @@ var require_UTIF = __commonJS({ return [lensW, lensB]; })(); UTIF2.decode._decodeG4 = function(data, off, slen, tgt, toff, w6, fo) { - var U2 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; + var U3 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; var line = [], pline = []; for (var i6 = 0; i6 < w6; i6++) pline.push(0); - pline = U2._makeDiff(pline); + pline = U3._makeDiff(pline); var a0 = 0, a1 = 0, a22 = 0, b1 = 0, b22 = 0, clr = 0; var y4 = 0, mode = "", toRead = 0; var bipl = Math.ceil(w6 / 8) * 8; while (boff >>> 3 < off + slen) { - b1 = U2._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U2._findDiff(pline, b1, clr); + b1 = U3._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U3._findDiff(pline, b1, clr); var bit = 0; if (fo == 1) bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1; if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; boff++; wrd += bit; if (mode == "H") { - if (U2._lens[clr][wrd] != null) { - var dl = U2._lens[clr][wrd]; + if (U3._lens[clr][wrd] != null) { + var dl = U3._lens[clr][wrd]; wrd = ""; len += dl; if (dl < 64) { - U2._addNtimes(line, len, clr); + U3._addNtimes(line, len, clr); a0 += len; clr = 1 - clr; len = 0; @@ -58860,7 +60000,7 @@ var require_UTIF = __commonJS({ } else { if (wrd == "0001") { wrd = ""; - U2._addNtimes(line, b22 - a0, clr); + U3._addNtimes(line, b22 - a0, clr); a0 = b22; } if (wrd == "001") { @@ -58868,26 +60008,26 @@ var require_UTIF = __commonJS({ mode = "H"; toRead = 2; } - if (U2._dmap[wrd] != null) { - a1 = b1 + U2._dmap[wrd]; - U2._addNtimes(line, a1 - a0, clr); + if (U3._dmap[wrd] != null) { + a1 = b1 + U3._dmap[wrd]; + U3._addNtimes(line, a1 - a0, clr); a0 = a1; wrd = ""; clr = 1 - clr; } } if (line.length == w6 && mode == "") { - U2._writeBits(line, tgt, toff * 8 + y4 * bipl); + U3._writeBits(line, tgt, toff * 8 + y4 * bipl); clr = 0; y4++; a0 = 0; - pline = U2._makeDiff(line); + pline = U3._makeDiff(line); line = []; } } }; - UTIF2.decode._findDiff = function(line, x7, clr) { - for (var i6 = 0; i6 < line.length; i6 += 2) if (line[i6] >= x7 && line[i6 + 1] == clr) return line[i6]; + UTIF2.decode._findDiff = function(line, x8, clr) { + for (var i6 = 0; i6 < line.length; i6 += 2) if (line[i6] >= x8 && line[i6 + 1] == clr) return line[i6]; }; UTIF2.decode._makeDiff = function(line) { var out = []; @@ -58897,7 +60037,7 @@ var require_UTIF = __commonJS({ return out; }; UTIF2.decode._decodeG2 = function(data, off, slen, tgt, toff, w6, fo) { - var U2 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; + var U3 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; var line = []; var clr = 0; var y4 = 0; @@ -58908,13 +60048,13 @@ var require_UTIF = __commonJS({ if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; boff++; wrd += bit; - len = U2._lens[clr][wrd]; + len = U3._lens[clr][wrd]; if (len != null) { - U2._addNtimes(line, len, clr); + U3._addNtimes(line, len, clr); wrd = ""; if (len < 64) clr = 1 - clr; if (line.length == w6) { - U2._writeBits(line, tgt, toff * 8 + y4 * bipl); + U3._writeBits(line, tgt, toff * 8 + y4 * bipl); line = []; y4++; clr = 0; @@ -58925,38 +60065,38 @@ var require_UTIF = __commonJS({ } }; UTIF2.decode._decodeG3 = function(data, off, slen, tgt, toff, w6, fo, twoDim) { - var U2 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; + var U3 = UTIF2.decode, boff = off << 3, len = 0, wrd = ""; var line = [], pline = []; for (var i6 = 0; i6 < w6; i6++) line.push(0); var a0 = 0, a1 = 0, a22 = 0, b1 = 0, b22 = 0, clr = 0; var y4 = -1, mode = "", toRead = 0, is1D = true; var bipl = Math.ceil(w6 / 8) * 8; while (boff >>> 3 < off + slen) { - b1 = U2._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U2._findDiff(pline, b1, clr); + b1 = U3._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U3._findDiff(pline, b1, clr); var bit = 0; if (fo == 1) bit = data[boff >>> 3] >>> 7 - (boff & 7) & 1; if (fo == 2) bit = data[boff >>> 3] >>> (boff & 7) & 1; boff++; wrd += bit; if (is1D) { - if (U2._lens[clr][wrd] != null) { - var dl = U2._lens[clr][wrd]; + if (U3._lens[clr][wrd] != null) { + var dl = U3._lens[clr][wrd]; wrd = ""; len += dl; if (dl < 64) { - U2._addNtimes(line, len, clr); + U3._addNtimes(line, len, clr); clr = 1 - clr; len = 0; } } } else { if (mode == "H") { - if (U2._lens[clr][wrd] != null) { - var dl = U2._lens[clr][wrd]; + if (U3._lens[clr][wrd] != null) { + var dl = U3._lens[clr][wrd]; wrd = ""; len += dl; if (dl < 64) { - U2._addNtimes(line, len, clr); + U3._addNtimes(line, len, clr); a0 += len; clr = 1 - clr; len = 0; @@ -58967,7 +60107,7 @@ var require_UTIF = __commonJS({ } else { if (wrd == "0001") { wrd = ""; - U2._addNtimes(line, b22 - a0, clr); + U3._addNtimes(line, b22 - a0, clr); a0 = b22; } if (wrd == "001") { @@ -58975,9 +60115,9 @@ var require_UTIF = __commonJS({ mode = "H"; toRead = 2; } - if (U2._dmap[wrd] != null) { - a1 = b1 + U2._dmap[wrd]; - U2._addNtimes(line, a1 - a0, clr); + if (U3._dmap[wrd] != null) { + a1 = b1 + U3._dmap[wrd]; + U3._addNtimes(line, a1 - a0, clr); a0 = a1; wrd = ""; clr = 1 - clr; @@ -58985,7 +60125,7 @@ var require_UTIF = __commonJS({ } } if (wrd.endsWith("000000000001")) { - if (y4 >= 0) U2._writeBits(line, tgt, toff * 8 + y4 * bipl); + if (y4 >= 0) U3._writeBits(line, tgt, toff * 8 + y4 * bipl); if (twoDim) { if (fo == 1) is1D = (data[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1; if (fo == 2) is1D = (data[boff >>> 3] >>> (boff & 7) & 1) == 1; @@ -58995,79 +60135,79 @@ var require_UTIF = __commonJS({ clr = 0; y4++; a0 = 0; - pline = U2._makeDiff(line); + pline = U3._makeDiff(line); line = []; } } - if (line.length == w6) U2._writeBits(line, tgt, toff * 8 + y4 * bipl); + if (line.length == w6) U3._writeBits(line, tgt, toff * 8 + y4 * bipl); }; - UTIF2.decode._addNtimes = function(arr, n6, val) { - for (var i6 = 0; i6 < n6; i6++) arr.push(val); + UTIF2.decode._addNtimes = function(arr, n12, val) { + for (var i6 = 0; i6 < n12; i6++) arr.push(val); }; UTIF2.decode._writeBits = function(bits, tgt, boff) { for (var i6 = 0; i6 < bits.length; i6++) tgt[boff + i6 >>> 3] |= bits[i6] << 7 - (boff + i6 & 7); }; UTIF2.decode._decodeLZW = UTIF2.decode._decodeLZW = (function() { - var e6, U2, Z2, u6, K3 = 0, V2 = 0, g6 = 0, N2 = 0, O2 = function() { - var S2 = e6 >>> 3, A3 = U2[S2] << 16 | U2[S2 + 1] << 8 | U2[S2 + 2], j6 = A3 >>> 24 - (e6 & 7) - V2 & (1 << V2) - 1; - e6 += V2; - return j6; + var e6, U3, Z2, u6, K3 = 0, V3 = 0, g6 = 0, N3 = 0, O3 = function() { + var S2 = e6 >>> 3, A4 = U3[S2] << 16 | U3[S2 + 1] << 8 | U3[S2 + 2], j7 = A4 >>> 24 - (e6 & 7) - V3 & (1 << V3) - 1; + e6 += V3; + return j7; }, h6 = new Uint32Array(4096 * 4), w6 = 0, m6 = function(S2) { if (S2 == w6) return; w6 = S2; g6 = 1 << S2; - N2 = g6 + 1; - for (var A3 = 0; A3 < N2 + 1; A3++) { - h6[4 * A3] = h6[4 * A3 + 3] = A3; - h6[4 * A3 + 1] = 65535; - h6[4 * A3 + 2] = 1; + N3 = g6 + 1; + for (var A4 = 0; A4 < N3 + 1; A4++) { + h6[4 * A4] = h6[4 * A4 + 3] = A4; + h6[4 * A4 + 1] = 65535; + h6[4 * A4 + 2] = 1; } }, i6 = function(S2) { - V2 = S2 + 1; - K3 = N2 + 1; - }, D3 = function(S2) { - var A3 = S2 << 2, j6 = h6[A3 + 2], a6 = u6 + j6 - 1; - while (A3 != 65535) { - Z2[a6--] = h6[A3]; - A3 = h6[A3 + 1]; - } - u6 += j6; - }, L2 = function(S2, A3) { - var j6 = K3 << 2, a6 = S2 << 2; - h6[j6] = h6[(A3 << 2) + 3]; - h6[j6 + 1] = a6; - h6[j6 + 2] = h6[a6 + 2] + 1; - h6[j6 + 3] = h6[a6 + 3]; + V3 = S2 + 1; + K3 = N3 + 1; + }, D4 = function(S2) { + var A4 = S2 << 2, j7 = h6[A4 + 2], a6 = u6 + j7 - 1; + while (A4 != 65535) { + Z2[a6--] = h6[A4]; + A4 = h6[A4 + 1]; + } + u6 += j7; + }, L3 = function(S2, A4) { + var j7 = K3 << 2, a6 = S2 << 2; + h6[j7] = h6[(A4 << 2) + 3]; + h6[j7 + 1] = a6; + h6[j7 + 2] = h6[a6 + 2] + 1; + h6[j7 + 3] = h6[a6 + 3]; K3++; - if (K3 + 1 == 1 << V2 && V2 != 12) V2++; - }, T2 = function(S2, A3, j6, a6, n6, q6) { - e6 = A3 << 3; - U2 = S2; + if (K3 + 1 == 1 << V3 && V3 != 12) V3++; + }, T3 = function(S2, A4, j7, a6, n12, q7) { + e6 = A4 << 3; + U3 = S2; Z2 = a6; - u6 = n6; - var B3 = A3 + j6 << 3, _ = 0, t12 = 0; - m6(q6); - i6(q6); - while (e6 < B3 && (_ = O2()) != N2) { - if (_ == g6) { - i6(q6); - _ = O2(); - if (_ == N2) break; - D3(_); + u6 = n12; + var B4 = A4 + j7 << 3, _2 = 0, t12 = 0; + m6(q7); + i6(q7); + while (e6 < B4 && (_2 = O3()) != N3) { + if (_2 == g6) { + i6(q7); + _2 = O3(); + if (_2 == N3) break; + D4(_2); } else { - if (_ < K3) { - D3(_); - L2(t12, _); + if (_2 < K3) { + D4(_2); + L3(t12, _2); } else { - L2(t12, t12); - D3(K3 - 1); + L3(t12, t12); + D4(K3 - 1); } } - t12 = _; + t12 = _2; } return u6; }; - return T2; + return T3; })(); UTIF2.tags = {}; UTIF2._types = (function() { @@ -59112,26 +60252,26 @@ var require_UTIF = __commonJS({ else arr = new Uint8Array(data.buffer, o0, len); } if (type == 3) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readUshort(data, (num < 3 ? offset - 4 : voff) + 2 * j6)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readUshort(data, (num < 3 ? offset - 4 : voff) + 2 * j7)); } if (type == 4 || type == 13) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readUint(data, (num < 2 ? offset - 4 : voff) + 4 * j6)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readUint(data, (num < 2 ? offset - 4 : voff) + 4 * j7)); } if (type == 5 || type == 10) { - var ri = type == 5 ? bin.readUint : bin.readInt; - for (var j6 = 0; j6 < num; j6++) arr.push([ri(data, voff + j6 * 8), ri(data, voff + j6 * 8 + 4)]); + var ri2 = type == 5 ? bin.readUint : bin.readInt; + for (var j7 = 0; j7 < num; j7++) arr.push([ri2(data, voff + j7 * 8), ri2(data, voff + j7 * 8 + 4)]); } if (type == 8) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readShort(data, (num < 3 ? offset - 4 : voff) + 2 * j6)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readShort(data, (num < 3 ? offset - 4 : voff) + 2 * j7)); } if (type == 9) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readInt(data, (num < 2 ? offset - 4 : voff) + 4 * j6)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readInt(data, (num < 2 ? offset - 4 : voff) + 4 * j7)); } if (type == 11) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readFloat(data, voff + j6 * 4)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readFloat(data, voff + j7 * 4)); } if (type == 12) { - for (var j6 = 0; j6 < num; j6++) arr.push(bin.readDouble(data, voff + j6 * 8)); + for (var j7 = 0; j7 < num; j7++) arr.push(bin.readDouble(data, voff + j7 * 8)); } if (num != 0 && arr.length == 0) { log(tag, "unknown TIFF tag type: ", type, "num:", num); @@ -59144,7 +60284,7 @@ var require_UTIF = __commonJS({ } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data, bin.readUint(arr, 0)) < 300 || tag == 61440) { var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr; var subfd = []; - for (var j6 = 0; j6 < oarr.length; j6++) UTIF2._readIFD(bin, data, oarr[j6], subfd, depth + 1, prm); + for (var j7 = 0; j7 < oarr.length; j7++) UTIF2._readIFD(bin, data, oarr[j7], subfd, depth + 1, prm); if (tag == 330) ifd.subIFD = subfd; if (tag == 34665) ifd.exifIFD = subfd[0]; if (tag == 34853) ifd.gpsiIFD = subfd[0]; @@ -59159,11 +60299,11 @@ var require_UTIF = __commonJS({ var subsub = []; UTIF2._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm); var obj2 = ifd.makerNote = subsub.pop(); - for (var j6 = 0; j6 < inds.length; j6++) { - var k6 = "t" + inds[j6]; - if (obj2[k6] == null) continue; - UTIF2._readIFD(bin, mn, obj2[k6][0], subsub, depth + 1, prm); - obj2[k6] = subsub.pop(); + for (var j7 = 0; j7 < inds.length; j7++) { + var k7 = "t" + inds[j7]; + if (obj2[k7] == null) continue; + UTIF2._readIFD(bin, mn, obj2[k7][0], subsub, depth + 1, prm); + obj2[k7] = subsub.pop(); } if (obj2["t12288"]) { UTIF2._readIFD(bin, obj2["t12288"], 0, subsub, depth + 1, prm); @@ -59180,24 +60320,24 @@ var require_UTIF = __commonJS({ if (prm.debug) log(" ".repeat(depth), "<<<---------------"); return offset; }; - UTIF2._writeIFD = function(bin, types2, data, offset, ifd) { + UTIF2._writeIFD = function(bin, types, data, offset, ifd) { var keys = Object.keys(ifd), knum = keys.length; if (ifd["exifIFD"]) knum--; if (ifd["gpsiIFD"]) knum--; bin.writeUshort(data, offset, knum); offset += 2; var eoff = offset + knum * 12 + 4; - for (var ki = 0; ki < keys.length; ki++) { - var key = keys[ki]; + for (var ki2 = 0; ki2 < keys.length; ki2++) { + var key = keys[ki2]; if (key == "t34665" || key == "t34853") continue; if (key == "exifIFD") key = "t34665"; if (key == "gpsiIFD") key = "t34853"; - var tag = parseInt(key.slice(1)), type = types2.main[tag]; - if (type == null) type = types2.rest[tag]; + var tag = parseInt(key.slice(1)), type = types.main[tag]; + if (type == null) type = types.rest[tag]; if (type == null || type == 0) throw new Error("unknown type of tag: " + tag); var val = ifd[key]; if (tag == 34665) { - var outp = UTIF2._writeIFD(bin, types2, data, eoff, ifd["exifIFD"]); + var outp = UTIF2._writeIFD(bin, types, data, eoff, ifd["exifIFD"]); val = [eoff]; eoff = outp[1]; } @@ -59231,10 +60371,10 @@ var require_UTIF = __commonJS({ } else if (type == 5 || type == 10) { var wr = type == 5 ? bin.writeUint : bin.writeInt; for (var i6 = 0; i6 < num; i6++) { - var v7 = val[i6], nu = v7[0], de = v7[1]; + var v8 = val[i6], nu = v8[0], de2 = v8[1]; if (nu == null) throw "e"; wr(data, toff + 8 * i6, nu); - wr(data, toff + 8 * i6 + 4, de); + wr(data, toff + 8 * i6 + 4, de2); } } else if (type == 9) { for (var i6 = 0; i6 < num; i6++) bin.writeInt(data, toff + 4 * i6, val[i6]); @@ -59250,8 +60390,8 @@ var require_UTIF = __commonJS({ return [offset, eoff]; }; UTIF2.toRGBA8 = function(out, scl) { - function gamma(x8) { - return x8 < 31308e-7 ? 12.92 * x8 : 1.055 * Math.pow(x8, 1 / 2.4) - 0.055; + function gamma(x9) { + return x9 < 31308e-7 ? 12.92 * x9 : 1.055 * Math.pow(x9, 1 / 2.4) - 0.055; } var w6 = out.width, h6 = out.height, area = w6 * h6, qarea = area * 4, data = out.data; var img = new Uint8Array(area * 4); @@ -59325,32 +60465,32 @@ var require_UTIF = __commonJS({ img[4 * i6 + 3] = 255; } if (smpls == 3) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * 3; - img[qi] = data[ti]; - img[qi + 1] = data[ti + 1]; - img[qi + 2] = data[ti + 2]; + var qi = i6 << 2, ti2 = i6 * 3; + img[qi] = data[ti2]; + img[qi + 1] = data[ti2 + 1]; + img[qi + 2] = data[ti2 + 2]; img[qi + 3] = 255; } if (smpls >= 4) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * smpls; - img[qi] = data[ti]; - img[qi + 1] = data[ti + 1]; - img[qi + 2] = data[ti + 2]; - img[qi + 3] = data[ti + 3]; + var qi = i6 << 2, ti2 = i6 * smpls; + img[qi] = data[ti2]; + img[qi + 1] = data[ti2 + 1]; + img[qi + 2] = data[ti2 + 2]; + img[qi + 3] = data[ti2 + 3]; } } else if (bps == 16) { if (smpls == 4) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * 8 + 1; - img[qi] = data[ti]; - img[qi + 1] = data[ti + 2]; - img[qi + 2] = data[ti + 4]; - img[qi + 3] = data[ti + 6]; + var qi = i6 << 2, ti2 = i6 * 8 + 1; + img[qi] = data[ti2]; + img[qi + 1] = data[ti2 + 2]; + img[qi + 2] = data[ti2 + 4]; + img[qi + 3] = data[ti2 + 6]; } if (smpls == 3) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * 6 + 1; - img[qi] = data[ti]; - img[qi + 1] = data[ti + 2]; - img[qi + 2] = data[ti + 4]; + var qi = i6 << 2, ti2 = i6 * 6 + 1; + img[qi] = data[ti2]; + img[qi + 1] = data[ti2 + 2]; + img[qi + 2] = data[ti2 + 4]; img[qi + 3] = 255; } } else if (bps == 32) { @@ -59372,18 +60512,18 @@ var require_UTIF = __commonJS({ ndt[i6] = pmap[~~(0.5 + cv2 * 65535)]; } if (smpls == 3) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * 3; - img[qi] = ~~(0.5 + ndt[ti] * 255); - img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); - img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + var qi = i6 << 2, ti2 = i6 * 3; + img[qi] = ~~(0.5 + ndt[ti2] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti2 + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti2 + 2] * 255); img[qi + 3] = 255; } else if (smpls == 4) for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, ti = i6 * 4; - img[qi] = ~~(0.5 + ndt[ti] * 255); - img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); - img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); - img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255); + var qi = i6 << 2, ti2 = i6 * 4; + img[qi] = ~~(0.5 + ndt[ti2] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti2 + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti2 + 2] * 255); + img[qi + 3] = ~~(0.5 + ndt[ti2 + 3] * 255); } else throw smpls; } else throw bps; @@ -59392,49 +60532,49 @@ var require_UTIF = __commonJS({ var cn2 = 1 << bps; var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0; for (var y4 = 0; y4 < h6; y4++) - for (var x7 = 0; x7 < w6; x7++) { - var i6 = y4 * w6 + x7; - var qi = i6 << 2, mi = 0; + for (var x8 = 0; x8 < w6; x8++) { + var i6 = y4 * w6 + x8; + var qi = i6 << 2, mi2 = 0; var dof = y4 * bpl; if (false) { - } else if (bps == 1) mi = data[dof + (x7 >>> 3)] >>> 7 - (x7 & 7) & 1; - else if (bps == 2) mi = data[dof + (x7 >>> 2)] >>> 6 - 2 * (x7 & 3) & 3; - else if (bps == 4) mi = data[dof + (x7 >>> 1)] >>> 4 - 4 * (x7 & 1) & 15; - else if (bps == 8) mi = data[dof + x7 * smpls]; + } else if (bps == 1) mi2 = data[dof + (x8 >>> 3)] >>> 7 - (x8 & 7) & 1; + else if (bps == 2) mi2 = data[dof + (x8 >>> 2)] >>> 6 - 2 * (x8 & 3) & 3; + else if (bps == 4) mi2 = data[dof + (x8 >>> 1)] >>> 4 - 4 * (x8 & 1) & 15; + else if (bps == 8) mi2 = data[dof + x8 * smpls]; else throw bps; - img[qi] = map2[mi] >> 8; - img[qi + 1] = map2[cn2 + mi] >> 8; - img[qi + 2] = map2[cn2 + cn2 + mi] >> 8; - img[qi + 3] = nexta ? data[dof + x7 * smpls + 1] : 255; + img[qi] = map2[mi2] >> 8; + img[qi + 1] = map2[cn2 + mi2] >> 8; + img[qi + 2] = map2[cn2 + cn2 + mi2] >> 8; + img[qi + 3] = nexta ? data[dof + x8 * smpls + 1] : 255; } } else if (intp == 5) { var gotAlpha = smpls > 4 ? 1 : 0; for (var i6 = 0; i6 < area; i6++) { - var qi = i6 << 2, si = i6 * smpls; + var qi = i6 << 2, si2 = i6 * smpls; if (window.UDOC) { - var C3 = data[si], M2 = data[si + 1], Y3 = data[si + 2], K3 = data[si + 3]; - var c7 = UDOC.C.cmykToRgb([C3 * (1 / 255), M2 * (1 / 255), Y3 * (1 / 255), K3 * (1 / 255)]); + var C4 = data[si2], M3 = data[si2 + 1], Y4 = data[si2 + 2], K3 = data[si2 + 3]; + var c7 = UDOC.C.cmykToRgb([C4 * (1 / 255), M3 * (1 / 255), Y4 * (1 / 255), K3 * (1 / 255)]); img[qi] = ~~(0.5 + 255 * c7[0]); img[qi + 1] = ~~(0.5 + 255 * c7[1]); img[qi + 2] = ~~(0.5 + 255 * c7[2]); } else { - var C3 = 255 - data[si], M2 = 255 - data[si + 1], Y3 = 255 - data[si + 2], K3 = (255 - data[si + 3]) * (1 / 255); - img[qi] = ~~(C3 * K3 + 0.5); - img[qi + 1] = ~~(M2 * K3 + 0.5); - img[qi + 2] = ~~(Y3 * K3 + 0.5); + var C4 = 255 - data[si2], M3 = 255 - data[si2 + 1], Y4 = 255 - data[si2 + 2], K3 = (255 - data[si2 + 3]) * (1 / 255); + img[qi] = ~~(C4 * K3 + 0.5); + img[qi + 1] = ~~(M3 * K3 + 0.5); + img[qi + 2] = ~~(Y4 * K3 + 0.5); } - img[qi + 3] = 255 * (1 - gotAlpha) + data[si + 4] * gotAlpha; + img[qi + 3] = 255 * (1 - gotAlpha) + data[si2 + 4] * gotAlpha; } } else if (intp == 6 && out["t278"]) { - var rps2 = out["t278"][0]; - for (var y4 = 0; y4 < h6; y4 += rps2) { - var i6 = y4 * w6, len = rps2 * w6; - for (var j6 = 0; j6 < len; j6++) { - var qi = 4 * (i6 + j6), si = 3 * i6 + 4 * (j6 >>> 1); - var Y3 = data[si + (j6 & 1)], Cb = data[si + 2] - 128, Cr = data[si + 3] - 128; - var r6 = Y3 + ((Cr >> 2) + (Cr >> 3) + (Cr >> 5)); - var g6 = Y3 - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)); - var b6 = Y3 + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); + var rps = out["t278"][0]; + for (var y4 = 0; y4 < h6; y4 += rps) { + var i6 = y4 * w6, len = rps * w6; + for (var j7 = 0; j7 < len; j7++) { + var qi = 4 * (i6 + j7), si2 = 3 * i6 + 4 * (j7 >>> 1); + var Y4 = data[si2 + (j7 & 1)], Cb = data[si2 + 2] - 128, Cr2 = data[si2 + 3] - 128; + var r6 = Y4 + ((Cr2 >> 2) + (Cr2 >> 3) + (Cr2 >> 5)); + var g6 = Y4 - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr2 >> 1) + (Cr2 >> 3) + (Cr2 >> 4) + (Cr2 >> 5)); + var b6 = Y4 + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); img[qi] = Math.max(0, Math.min(255, r6)); img[qi + 1] = Math.max(0, Math.min(255, g6)); img[qi + 2] = Math.max(0, Math.min(255, b6)); @@ -59443,19 +60583,19 @@ var require_UTIF = __commonJS({ } } else if (intp == 32845) { for (var y4 = 0; y4 < h6; y4++) - for (var x7 = 0; x7 < w6; x7++) { - var si = (y4 * w6 + x7) * 6, qi = (y4 * w6 + x7) * 4; - var L2 = data[si + 1] << 8 | data[si]; - var L2 = Math.pow(2, (L2 + 0.5) / 256 - 64); - var u6 = (data[si + 3] + 0.5) / 410; - var v7 = (data[si + 5] + 0.5) / 410; - var sX = 9 * u6 / (6 * u6 - 16 * v7 + 12); - var sY = 4 * v7 / (6 * u6 - 16 * v7 + 12); - var bY2 = L2; - var X2 = sX * bY2 / sY, Y3 = bY2, Z2 = (1 - sX - sY) * bY2 / sY; - var r6 = 2.69 * X2 - 1.276 * Y3 - 0.414 * Z2; - var g6 = -1.022 * X2 + 1.978 * Y3 + 0.044 * Z2; - var b6 = 0.061 * X2 - 0.224 * Y3 + 1.163 * Z2; + for (var x8 = 0; x8 < w6; x8++) { + var si2 = (y4 * w6 + x8) * 6, qi = (y4 * w6 + x8) * 4; + var L3 = data[si2 + 1] << 8 | data[si2]; + var L3 = Math.pow(2, (L3 + 0.5) / 256 - 64); + var u6 = (data[si2 + 3] + 0.5) / 410; + var v8 = (data[si2 + 5] + 0.5) / 410; + var sX = 9 * u6 / (6 * u6 - 16 * v8 + 12); + var sY = 4 * v8 / (6 * u6 - 16 * v8 + 12); + var bY2 = L3; + var X3 = sX * bY2 / sY, Y4 = bY2, Z2 = (1 - sX - sY) * bY2 / sY; + var r6 = 2.69 * X3 - 1.276 * Y4 - 0.414 * Z2; + var g6 = -1.022 * X3 + 1.978 * Y4 + 0.044 * Z2; + var b6 = 0.061 * X3 - 0.224 * Y4 + 1.163 * Z2; img[qi] = gamma(Math.min(r6, 1)) * 255; img[qi + 1] = gamma(Math.min(g6, 1)) * 255; img[qi + 2] = gamma(Math.min(b6, 1)) * 255; @@ -59557,29 +60697,29 @@ var require_UTIF = __commonJS({ for (var i6 = 0; i6 < 8; i6++) a6[i6] = buff[p6 + 7 - i6]; return UTIF2._binBE.fl64[0]; }, - writeUshort: function(buff, p6, n6) { - buff[p6] = n6 >> 8 & 255; - buff[p6 + 1] = n6 & 255; + writeUshort: function(buff, p6, n12) { + buff[p6] = n12 >> 8 & 255; + buff[p6 + 1] = n12 & 255; }, - writeInt: function(buff, p6, n6) { + writeInt: function(buff, p6, n12) { var a6 = UTIF2._binBE.ui8; - UTIF2._binBE.i32[0] = n6; + UTIF2._binBE.i32[0] = n12; buff[p6 + 3] = a6[0]; buff[p6 + 2] = a6[1]; buff[p6 + 1] = a6[2]; buff[p6 + 0] = a6[3]; }, - writeUint: function(buff, p6, n6) { - buff[p6] = n6 >> 24 & 255; - buff[p6 + 1] = n6 >> 16 & 255; - buff[p6 + 2] = n6 >> 8 & 255; - buff[p6 + 3] = n6 >> 0 & 255; + writeUint: function(buff, p6, n12) { + buff[p6] = n12 >> 24 & 255; + buff[p6 + 1] = n12 >> 16 & 255; + buff[p6 + 2] = n12 >> 8 & 255; + buff[p6 + 3] = n12 >> 0 & 255; }, writeASCII: function(buff, p6, s6) { for (var i6 = 0; i6 < s6.length; i6++) buff[p6 + i6] = s6.charCodeAt(i6); }, - writeDouble: function(buff, p6, n6) { - UTIF2._binBE.fl64[0] = n6; + writeDouble: function(buff, p6, n12) { + UTIF2._binBE.fl64[0] = n12; for (var i6 = 0; i6 < 8; i6++) buff[p6 + i6] = UTIF2._binBE.ui8[7 - i6]; } }; @@ -59627,23 +60767,23 @@ var require_UTIF = __commonJS({ for (var i6 = 0; i6 < 8; i6++) a6[i6] = buff[p6 + i6]; return UTIF2._binBE.fl64[0]; }, - writeUshort: function(buff, p6, n6) { - buff[p6] = n6 & 255; - buff[p6 + 1] = n6 >> 8 & 255; + writeUshort: function(buff, p6, n12) { + buff[p6] = n12 & 255; + buff[p6 + 1] = n12 >> 8 & 255; }, - writeInt: function(buff, p6, n6) { + writeInt: function(buff, p6, n12) { var a6 = UTIF2._binBE.ui8; - UTIF2._binBE.i32[0] = n6; + UTIF2._binBE.i32[0] = n12; buff[p6 + 0] = a6[0]; buff[p6 + 1] = a6[1]; buff[p6 + 2] = a6[2]; buff[p6 + 3] = a6[3]; }, - writeUint: function(buff, p6, n6) { - buff[p6] = n6 >>> 0 & 255; - buff[p6 + 1] = n6 >>> 8 & 255; - buff[p6 + 2] = n6 >>> 16 & 255; - buff[p6 + 3] = n6 >>> 24 & 255; + writeUint: function(buff, p6, n12) { + buff[p6] = n12 >>> 0 & 255; + buff[p6 + 1] = n12 >>> 8 & 255; + buff[p6 + 2] = n12 >>> 16 & 255; + buff[p6 + 3] = n12 >>> 24 & 255; }, writeASCII: UTIF2._binBE.writeASCII }; @@ -59653,279 +60793,279 @@ var require_UTIF = __commonJS({ for (var y4 = 0; y4 < ylim; y4++) { var tof = (yoff + y4) * w6 + xoff; var sof = y4 * tw; - for (var x7 = 0; x7 < xlim; x7++) b6[tof + x7] = tb[sof + x7]; + for (var x8 = 0; x8 < xlim; x8++) b6[tof + x8] = tb[sof + x8]; } }; UTIF2.LosslessJpegDecode = /* @__PURE__ */ (function() { - var b6, O2; + var b6, O3; function l6() { - return b6[O2++]; + return b6[O3++]; } function m6() { - return b6[O2++] << 8 | b6[O2++]; + return b6[O3++] << 8 | b6[O3++]; } function a0(h6) { - var V2 = l6(), I3 = [0, 0, 0, 255], f6 = [], G3 = 8; + var V3 = l6(), I4 = [0, 0, 0, 255], f6 = [], G4 = 8; for (var w6 = 0; w6 < 16; w6++) f6[w6] = l6(); for (var w6 = 0; w6 < 16; w6++) { - for (var x7 = 0; x7 < f6[w6]; x7++) { - var T2 = z3(I3, 0, w6 + 1, 1); - I3[T2 + 3] = l6(); + for (var x8 = 0; x8 < f6[w6]; x8++) { + var T3 = z3(I4, 0, w6 + 1, 1); + I4[T3 + 3] = l6(); } } - var E3 = new Uint8Array(1 << G3); - h6[V2] = [new Uint8Array(I3), E3]; - for (var w6 = 0; w6 < 1 << G3; w6++) { - var s6 = G3, _ = w6, Y3 = 0, F3 = 0; - while (I3[Y3 + 3] == 255 && s6 != 0) { - F3 = _ >> --s6 & 1; - Y3 = I3[Y3 + F3]; + var E3 = new Uint8Array(1 << G4); + h6[V3] = [new Uint8Array(I4), E3]; + for (var w6 = 0; w6 < 1 << G4; w6++) { + var s6 = G4, _2 = w6, Y4 = 0, F4 = 0; + while (I4[Y4 + 3] == 255 && s6 != 0) { + F4 = _2 >> --s6 & 1; + Y4 = I4[Y4 + F4]; } - E3[w6] = Y3; + E3[w6] = Y4; } } - function z3(h6, V2, I3, f6) { - if (h6[V2 + 3] != 255) return 0; - if (I3 == 0) return V2; + function z3(h6, V3, I4, f6) { + if (h6[V3 + 3] != 255) return 0; + if (I4 == 0) return V3; for (var w6 = 0; w6 < 2; w6++) { - if (h6[V2 + w6] == 0) { - h6[V2 + w6] = h6.length; + if (h6[V3 + w6] == 0) { + h6[V3 + w6] = h6.length; h6.push(0, 0, f6, 255); } - var x7 = z3(h6, h6[V2 + w6], I3 - 1, f6 + 1); - if (x7 != 0) return x7; + var x8 = z3(h6, h6[V3 + w6], I4 - 1, f6 + 1); + if (x8 != 0) return x8; } return 0; } function i6(h6) { - var V2 = h6.b, I3 = h6.f; - while (V2 < 25 && h6.a < h6.d) { + var V3 = h6.b, I4 = h6.f; + while (V3 < 25 && h6.a < h6.d) { var f6 = h6.data[h6.a++]; if (f6 == 255 && !h6.c) h6.a++; - I3 = I3 << 8 | f6; - V2 += 8; - } - if (V2 < 0) throw "e"; - h6.b = V2; - h6.f = I3; - } - function H3(h6, V2) { - if (V2.b < h6) i6(V2); - return V2.f >> (V2.b -= h6) & 65535 >> 16 - h6; - } - function g6(h6, V2) { - var I3 = h6[0], f6 = 0, w6 = 255, x7 = 0; - if (V2.b < 16) i6(V2); - var T2 = V2.f >> V2.b - 8 & 255; - f6 = h6[1][T2]; - w6 = I3[f6 + 3]; - V2.b -= I3[f6 + 2]; + I4 = I4 << 8 | f6; + V3 += 8; + } + if (V3 < 0) throw "e"; + h6.b = V3; + h6.f = I4; + } + function H4(h6, V3) { + if (V3.b < h6) i6(V3); + return V3.f >> (V3.b -= h6) & 65535 >> 16 - h6; + } + function g6(h6, V3) { + var I4 = h6[0], f6 = 0, w6 = 255, x8 = 0; + if (V3.b < 16) i6(V3); + var T3 = V3.f >> V3.b - 8 & 255; + f6 = h6[1][T3]; + w6 = I4[f6 + 3]; + V3.b -= I4[f6 + 2]; while (w6 == 255) { - x7 = V2.f >> --V2.b & 1; - f6 = I3[f6 + x7]; - w6 = I3[f6 + 3]; + x8 = V3.f >> --V3.b & 1; + f6 = I4[f6 + x8]; + w6 = I4[f6 + 3]; } return w6; } - function P2(h6, V2) { - if (h6 < 32768 >> 16 - V2) h6 += -(1 << V2) + 1; + function P3(h6, V3) { + if (h6 < 32768 >> 16 - V3) h6 += -(1 << V3) + 1; return h6; } - function a22(h6, V2) { - var I3 = g6(h6, V2); - if (I3 == 0) return 0; - if (I3 == 16) return -32768; - var f6 = H3(I3, V2); - return P2(f6, I3); - } - function X2(h6, V2, I3, f6, w6, x7) { - var T2 = 0; - for (var G3 = 0; G3 < x7; G3++) { - var s6 = G3 * V2; - for (var _ = 0; _ < V2; _ += w6) { - T2++; - for (var Y3 = 0; Y3 < w6; Y3++) h6[s6 + _ + Y3] = a22(f6[Y3], I3); + function a22(h6, V3) { + var I4 = g6(h6, V3); + if (I4 == 0) return 0; + if (I4 == 16) return -32768; + var f6 = H4(I4, V3); + return P3(f6, I4); + } + function X3(h6, V3, I4, f6, w6, x8) { + var T3 = 0; + for (var G4 = 0; G4 < x8; G4++) { + var s6 = G4 * V3; + for (var _2 = 0; _2 < V3; _2 += w6) { + T3++; + for (var Y4 = 0; Y4 < w6; Y4++) h6[s6 + _2 + Y4] = a22(f6[Y4], I4); } - if (I3.e != 0 && T2 % I3.e == 0 && G3 != 0) { - var F3 = I3.a, t12 = I3.data; - while (t12[F3] != 255 || !(208 <= t12[F3 + 1] && t12[F3 + 1] <= 215)) F3--; - I3.a = F3 + 2; - I3.f = 0; - I3.b = 0; + if (I4.e != 0 && T3 % I4.e == 0 && G4 != 0) { + var F4 = I4.a, t12 = I4.data; + while (t12[F4] != 255 || !(208 <= t12[F4 + 1] && t12[F4 + 1] <= 215)) F4--; + I4.a = F4 + 2; + I4.f = 0; + I4.b = 0; } } } - function o6(h6, V2) { - return P2(H3(h6, V2), h6); + function o6(h6, V3) { + return P3(H4(h6, V3), h6); } - function a1(h6, V2, I3, f6, w6) { - var x7 = b6.length - O2; - for (var T2 = 0; T2 < x7; T2 += 4) { - var G3 = b6[O2 + T2]; - b6[O2 + T2] = b6[O2 + T2 + 3]; - b6[O2 + T2 + 3] = G3; - var G3 = b6[O2 + T2 + 1]; - b6[O2 + T2 + 1] = b6[O2 + T2 + 2]; - b6[O2 + T2 + 2] = G3; + function a1(h6, V3, I4, f6, w6) { + var x8 = b6.length - O3; + for (var T3 = 0; T3 < x8; T3 += 4) { + var G4 = b6[O3 + T3]; + b6[O3 + T3] = b6[O3 + T3 + 3]; + b6[O3 + T3 + 3] = G4; + var G4 = b6[O3 + T3 + 1]; + b6[O3 + T3 + 1] = b6[O3 + T3 + 2]; + b6[O3 + T3 + 2] = G4; } for (var E3 = 0; E3 < w6; E3++) { - var s6 = 32768, _ = 32768; - for (var Y3 = 0; Y3 < V2; Y3 += 2) { - var F3 = g6(f6, I3), t12 = g6(f6, I3); - if (F3 != 0) s6 += o6(F3, I3); - if (t12 != 0) _ += o6(t12, I3); - h6[E3 * V2 + Y3] = s6 & 65535; - h6[E3 * V2 + Y3 + 1] = _ & 65535; + var s6 = 32768, _2 = 32768; + for (var Y4 = 0; Y4 < V3; Y4 += 2) { + var F4 = g6(f6, I4), t12 = g6(f6, I4); + if (F4 != 0) s6 += o6(F4, I4); + if (t12 != 0) _2 += o6(t12, I4); + h6[E3 * V3 + Y4] = s6 & 65535; + h6[E3 * V3 + Y4 + 1] = _2 & 65535; } } } - function C3(h6) { + function C4(h6) { b6 = h6; - O2 = 0; + O3 = 0; if (m6() != 65496) throw "e"; - var V2 = [], I3 = 0, f6 = 0, w6 = 0, x7 = [], T2 = [], G3 = [], E3 = 0, s6 = 0, _ = 0; + var V3 = [], I4 = 0, f6 = 0, w6 = 0, x8 = [], T3 = [], G4 = [], E3 = 0, s6 = 0, _2 = 0; while (true) { - var Y3 = m6(); - if (Y3 == 65535) { - O2--; + var Y4 = m6(); + if (Y4 == 65535) { + O3--; continue; } - var F3 = m6(); - if (Y3 == 65475) { + var F4 = m6(); + if (Y4 == 65475) { f6 = l6(); s6 = m6(); - _ = m6(); + _2 = m6(); E3 = l6(); for (var t12 = 0; t12 < E3; t12++) { var a6 = l6(), J3 = l6(), r6 = l6(); if (r6 != 0) throw "e"; - V2[a6] = [t12, J3 >> 4, J3 & 15]; + V3[a6] = [t12, J3 >> 4, J3 & 15]; } - } else if (Y3 == 65476) { - var a32 = O2 + F3 - 2; - while (O2 < a32) a0(T2); - } else if (Y3 == 65498) { - O2++; + } else if (Y4 == 65476) { + var a32 = O3 + F4 - 2; + while (O3 < a32) a0(T3); + } else if (Y4 == 65498) { + O3++; for (var t12 = 0; t12 < E3; t12++) { - var a52 = l6(), v7 = V2[a52]; - G3[v7[0]] = T2[l6() >>> 4]; - x7[v7[0]] = v7.slice(1); + var a52 = l6(), v8 = V3[a52]; + G4[v8[0]] = T3[l6() >>> 4]; + x8[v8[0]] = v8.slice(1); } - I3 = l6(); - O2 += 2; + I4 = l6(); + O3 += 2; break; - } else if (Y3 == 65501) { + } else if (Y4 == 65501) { w6 = m6(); } else { - O2 += F3 - 2; + O3 += F4 - 2; } } - var a42 = f6 > 8 ? Uint16Array : Uint8Array, $ = new a42(s6 * _ * E3), M2 = { b: 0, f: 0, c: I3 == 8, a: O2, data: b6, d: b6.length, e: w6 }; - if (M2.c) a1($, _ * E3, M2, G3[0], s6); + var a42 = f6 > 8 ? Uint16Array : Uint8Array, $ = new a42(s6 * _2 * E3), M3 = { b: 0, f: 0, c: I4 == 8, a: O3, data: b6, d: b6.length, e: w6 }; + if (M3.c) a1($, _2 * E3, M3, G4[0], s6); else { - var c7 = [], p6 = 0, D3 = 0; + var c7 = [], p6 = 0, D4 = 0; for (var t12 = 0; t12 < E3; t12++) { - var N2 = x7[t12], S2 = N2[0], K3 = N2[1]; + var N3 = x8[t12], S2 = N3[0], K3 = N3[1]; if (S2 > p6) p6 = S2; - if (K3 > D3) D3 = K3; + if (K3 > D4) D4 = K3; c7.push(S2 * K3); } - if (p6 != 1 || D3 != 1) { + if (p6 != 1 || D4 != 1) { if (E3 != 3 || c7[1] != 1 || c7[2] != 1) throw "e"; - if (p6 != 2 || D3 != 1 && D3 != 2) throw "e"; + if (p6 != 2 || D4 != 1 && D4 != 2) throw "e"; var u6 = [], Z2 = 0; for (var t12 = 0; t12 < E3; t12++) { - for (var R2 = 0; R2 < c7[t12]; R2++) u6.push(G3[t12]); + for (var R3 = 0; R3 < c7[t12]; R3++) u6.push(G4[t12]); Z2 += c7[t12]; } - var B3 = _ / p6, e6 = s6 / D3, d6 = B3 * e6; - X2($, B3 * Z2, M2, u6, Z2, e6); - j6($, I3, B3, e6, Z2 - 2, Z2, Z2, f6); - var A3 = new Uint16Array(d6 * c7[0]); - if (p6 == 2 && D3 == 2) { + var B4 = _2 / p6, e6 = s6 / D4, d6 = B4 * e6; + X3($, B4 * Z2, M3, u6, Z2, e6); + j7($, I4, B4, e6, Z2 - 2, Z2, Z2, f6); + var A4 = new Uint16Array(d6 * c7[0]); + if (p6 == 2 && D4 == 2) { for (var t12 = 0; t12 < d6; t12++) { - A3[4 * t12] = $[6 * t12]; - A3[4 * t12 + 1] = $[6 * t12 + 1]; - A3[4 * t12 + 2] = $[6 * t12 + 2]; - A3[4 * t12 + 3] = $[6 * t12 + 3]; + A4[4 * t12] = $[6 * t12]; + A4[4 * t12 + 1] = $[6 * t12 + 1]; + A4[4 * t12 + 2] = $[6 * t12 + 2]; + A4[4 * t12 + 3] = $[6 * t12 + 3]; } - j6(A3, I3, B3 * 4, e6, 0, 1, 1, f6); + j7(A4, I4, B4 * 4, e6, 0, 1, 1, f6); for (var t12 = 0; t12 < d6; t12++) { - $[6 * t12] = A3[4 * t12]; - $[6 * t12 + 1] = A3[4 * t12 + 1]; - $[6 * t12 + 2] = A3[4 * t12 + 2]; - $[6 * t12 + 3] = A3[4 * t12 + 3]; + $[6 * t12] = A4[4 * t12]; + $[6 * t12 + 1] = A4[4 * t12 + 1]; + $[6 * t12 + 2] = A4[4 * t12 + 2]; + $[6 * t12 + 3] = A4[4 * t12 + 3]; } } - if (p6 == 2 && D3 == 1) { + if (p6 == 2 && D4 == 1) { for (var t12 = 0; t12 < d6; t12++) { - A3[2 * t12] = $[4 * t12]; - A3[2 * t12 + 1] = $[4 * t12 + 1]; + A4[2 * t12] = $[4 * t12]; + A4[2 * t12 + 1] = $[4 * t12 + 1]; } - j6(A3, I3, B3 * 2, e6, 0, 1, 1, f6); + j7(A4, I4, B4 * 2, e6, 0, 1, 1, f6); for (var t12 = 0; t12 < d6; t12++) { - $[4 * t12] = A3[2 * t12]; - $[4 * t12 + 1] = A3[2 * t12 + 1]; + $[4 * t12] = A4[2 * t12]; + $[4 * t12 + 1] = A4[2 * t12 + 1]; } } - var n6 = $.slice(0); + var n12 = $.slice(0); for (var K3 = 0; K3 < s6; K3++) { - if (D3 == 2) for (var S2 = 0; S2 < _; S2++) { - var q6 = (K3 * _ + S2) * E3, k6 = ((K3 >>> 1) * B3 + (S2 >>> 1)) * Z2, y4 = (K3 & 1) * 2 + (S2 & 1); - $[q6] = n6[k6 + y4]; - $[q6 + 1] = n6[k6 + 4]; - $[q6 + 2] = n6[k6 + 5]; + if (D4 == 2) for (var S2 = 0; S2 < _2; S2++) { + var q7 = (K3 * _2 + S2) * E3, k7 = ((K3 >>> 1) * B4 + (S2 >>> 1)) * Z2, y4 = (K3 & 1) * 2 + (S2 & 1); + $[q7] = n12[k7 + y4]; + $[q7 + 1] = n12[k7 + 4]; + $[q7 + 2] = n12[k7 + 5]; } - else for (var S2 = 0; S2 < _; S2++) { - var q6 = (K3 * _ + S2) * E3, k6 = (K3 * B3 + (S2 >>> 1)) * Z2, y4 = S2 & 1; - $[q6] = n6[k6 + y4]; - $[q6 + 1] = n6[k6 + 2]; - $[q6 + 2] = n6[k6 + 3]; + else for (var S2 = 0; S2 < _2; S2++) { + var q7 = (K3 * _2 + S2) * E3, k7 = (K3 * B4 + (S2 >>> 1)) * Z2, y4 = S2 & 1; + $[q7] = n12[k7 + y4]; + $[q7 + 1] = n12[k7 + 2]; + $[q7 + 2] = n12[k7 + 3]; } } } else { - X2($, _ * E3, M2, G3, E3, s6); - if (w6 == 0) j6($, I3, _, s6, 0, E3, E3, f6); + X3($, _2 * E3, M3, G4, E3, s6); + if (w6 == 0) j7($, I4, _2, s6, 0, E3, E3, f6); else { - var U2 = Math.floor(w6 / _); - for (var K3 = 0; K3 < s6; K3 += U2) { - var L2 = $.slice(K3 * _ * E3, (K3 + U2) * _ * E3); - j6(L2, I3, _, U2, 0, E3, E3, f6); - $.set(L2, K3 * _ * E3); + var U3 = Math.floor(w6 / _2); + for (var K3 = 0; K3 < s6; K3 += U3) { + var L3 = $.slice(K3 * _2 * E3, (K3 + U3) * _2 * E3); + j7(L3, I4, _2, U3, 0, E3, E3, f6); + $.set(L3, K3 * _2 * E3); } } } } return $; } - function j6(h6, V2, I3, f6, w6, x7, G3, E3) { - var s6 = I3 * G3; - for (var _ = w6; _ < x7; _++) h6[_] += 1 << E3 - 1; - for (var Y3 = G3; Y3 < s6; Y3 += G3) for (var _ = w6; _ < x7; _++) h6[Y3 + _] += h6[Y3 + _ - G3]; - for (var F3 = 1; F3 < f6; F3++) { - var t12 = F3 * s6; - for (var _ = w6; _ < x7; _++) h6[t12 + _] += h6[t12 + _ - s6]; - for (var Y3 = G3; Y3 < s6; Y3 += G3) { - for (var _ = w6; _ < x7; _++) { - var a6 = t12 + Y3 + _, J3 = a6 - s6, r6 = h6[a6 - G3], Q2 = 0; - if (V2 == 0) Q2 = 0; - else if (V2 == 1) Q2 = r6; - else if (V2 == 2) Q2 = h6[J3]; - else if (V2 == 3) Q2 = h6[J3 - G3]; - else if (V2 == 4) Q2 = r6 + (h6[J3] - h6[J3 - G3]); - else if (V2 == 5) Q2 = r6 + (h6[J3] - h6[J3 - G3] >>> 1); - else if (V2 == 6) Q2 = h6[J3] + (r6 - h6[J3 - G3] >>> 1); - else if (V2 == 7) Q2 = r6 + h6[J3] >>> 1; - else throw V2; - h6[a6] += Q2; + function j7(h6, V3, I4, f6, w6, x8, G4, E3) { + var s6 = I4 * G4; + for (var _2 = w6; _2 < x8; _2++) h6[_2] += 1 << E3 - 1; + for (var Y4 = G4; Y4 < s6; Y4 += G4) for (var _2 = w6; _2 < x8; _2++) h6[Y4 + _2] += h6[Y4 + _2 - G4]; + for (var F4 = 1; F4 < f6; F4++) { + var t12 = F4 * s6; + for (var _2 = w6; _2 < x8; _2++) h6[t12 + _2] += h6[t12 + _2 - s6]; + for (var Y4 = G4; Y4 < s6; Y4 += G4) { + for (var _2 = w6; _2 < x8; _2++) { + var a6 = t12 + Y4 + _2, J3 = a6 - s6, r6 = h6[a6 - G4], Q3 = 0; + if (V3 == 0) Q3 = 0; + else if (V3 == 1) Q3 = r6; + else if (V3 == 2) Q3 = h6[J3]; + else if (V3 == 3) Q3 = h6[J3 - G4]; + else if (V3 == 4) Q3 = r6 + (h6[J3] - h6[J3 - G4]); + else if (V3 == 5) Q3 = r6 + (h6[J3] - h6[J3 - G4] >>> 1); + else if (V3 == 6) Q3 = h6[J3] + (r6 - h6[J3 - G4] >>> 1); + else if (V3 == 7) Q3 = r6 + h6[J3] >>> 1; + else throw V3; + h6[a6] += Q3; } } } } - return C3; + return C4; })(); (function() { - var G3 = 0, F3 = 1, i6 = 2, b6 = 3, J3 = 4, N2 = 5, E3 = 6, s6 = 7, c7 = 8, T2 = 9, a32 = 10, f6 = 11, q6 = 12, M2 = 13, m6 = 14, x7 = 15, L2 = 16, $ = 17, p6 = 18; + var G4 = 0, F4 = 1, i6 = 2, b6 = 3, J3 = 4, N3 = 5, E3 = 6, s6 = 7, c7 = 8, T3 = 9, a32 = 10, f6 = 11, q7 = 12, M3 = 13, m6 = 14, x8 = 15, L3 = 16, $ = 17, p6 = 18; function a52(t12) { var Z2 = UTIF2._binBE.readUshort, u6 = { b: Z2(t12, 0), i: t12[2], C: t12[3], u: t12[4], q: Z2(t12, 5), k: Z2(t12, 7), e: Z2(t12, 9), l: Z2(t12, 11), s: t12[13], d: Z2(t12, 14) }; if (u6.b != 18771 || u6.i > 1 || u6.q < 6 || u6.q % 6 || u6.e < 768 || u6.e % 24 || u6.l != 768 || u6.k < u6.l || u6.k % u6.l || u6.k - u6.e >= u6.l || u6.s > 16 || u6.s != u6.k / u6.l || u6.s != Math.ceil(u6.e / u6.l) || u6.d != u6.q / 6 || u6.u != 12 && u6.u != 14 && u6.u != 16 || u6.C != 16 && u6.C != 0) { @@ -59943,17 +61083,17 @@ var require_UTIF = __commonJS({ return u6; } function a7(t12, Z2) { - var u6 = new Array(Z2.s), e6 = 4 * Z2.s, Q2 = 16 + e6; - if (e6 & 12) Q2 += 16 - (e6 & 12); - for (var V2 = 0, O2 = 16; V2 < Z2.s; O2 += 4) { - var o6 = UTIF2._binBE.readUint(t12, O2); - u6[V2] = t12.slice(Q2, Q2 + o6); - u6[V2].j = 0; - u6[V2].a = 0; - Q2 += o6; - V2++; - } - if (Q2 != t12.length) throw "Invalid data"; + var u6 = new Array(Z2.s), e6 = 4 * Z2.s, Q3 = 16 + e6; + if (e6 & 12) Q3 += 16 - (e6 & 12); + for (var V3 = 0, O3 = 16; V3 < Z2.s; O3 += 4) { + var o6 = UTIF2._binBE.readUint(t12, O3); + u6[V3] = t12.slice(Q3, Q3 + o6); + u6[V3].j = 0; + u6[V3].a = 0; + Q3 += o6; + V3++; + } + if (Q3 != t12.length) throw "Invalid data"; return u6; } function a6(t12, Z2) { @@ -59974,11 +61114,11 @@ var require_UTIF = __commonJS({ a1(Z2, 0, t12.g); return Z2; } - function D3(t12) { + function D4(t12) { var Z2 = [[], [], []], u6 = Math.max(2, t12.w + 32 >>> 6); for (var e6 = 0; e6 < 3; e6++) { - for (var Q2 = 0; Q2 < 41; Q2++) { - Z2[e6][Q2] = [u6, 1]; + for (var Q3 = 0; Q3 < 41; Q3++) { + Z2[e6][Q3] = [u6, 1]; } } return Z2; @@ -59993,7 +61133,7 @@ var require_UTIF = __commonJS({ return Z2; } function K3(t12, Z2) { - var u6 = 0, e6 = 8 - t12.a, Q2 = t12.j, V2 = t12.a; + var u6 = 0, e6 = 8 - t12.a, Q3 = t12.j, V3 = t12.a; if (Z2) { if (Z2 >= e6) { do { @@ -60020,139 +61160,139 @@ var require_UTIF = __commonJS({ } return u6; } - function r6(t12, Z2, u6, e6, Q2, V2, O2, o6) { + function r6(t12, Z2, u6, e6, Q3, V3, O3, o6) { if (o6 == null) o6 = 0; - var X2 = V2 + 1, k6 = X2 % 2, j6 = 0, I3 = 0, a10 = 0, l6, R2, w6 = e6[Q2], S2 = e6[Q2 - 1], H3 = e6[Q2 - 2][X2], g6 = S2[X2 - 1], Y3 = S2[X2], P2 = S2[X2 + 1], A3 = w6[X2 - 1], v7 = w6[X2 + 1], y4 = Math.abs, d6, C3, n6, h6; - if (k6) { - d6 = y4(P2 - Y3); - C3 = y4(H3 - Y3); - n6 = y4(g6 - Y3); - } - if (k6) { - h6 = d6 > n6 && C3 < d6 ? H3 + g6 : d6 < n6 && C3 < n6 ? H3 + P2 : P2 + g6; - h6 = h6 + 2 * Y3 >>> 2; + var X3 = V3 + 1, k7 = X3 % 2, j7 = 0, I4 = 0, a10 = 0, l6, R3, w6 = e6[Q3], S2 = e6[Q3 - 1], H4 = e6[Q3 - 2][X3], g6 = S2[X3 - 1], Y4 = S2[X3], P3 = S2[X3 + 1], A4 = w6[X3 - 1], v8 = w6[X3 + 1], y4 = Math.abs, d6, C4, n12, h6; + if (k7) { + d6 = y4(P3 - Y4); + C4 = y4(H4 - Y4); + n12 = y4(g6 - Y4); + } + if (k7) { + h6 = d6 > n12 && C4 < d6 ? H4 + g6 : d6 < n12 && C4 < n12 ? H4 + P3 : P3 + g6; + h6 = h6 + 2 * Y4 >>> 2; if (o6) { - w6[X2] = h6; + w6[X3] = h6; return; } - l6 = Z2.t * Z2.c[t12.g + Y3 - H3] + Z2.c[t12.g + g6 - Y3]; + l6 = Z2.t * Z2.c[t12.g + Y4 - H4] + Z2.c[t12.g + g6 - Y4]; } else { - h6 = Y3 > g6 && Y3 > P2 || Y3 < g6 && Y3 < P2 ? v7 + A3 + 2 * Y3 >>> 2 : A3 + v7 >>> 1; - l6 = Z2.t * Z2.c[t12.g + Y3 - g6] + Z2.c[t12.g + g6 - A3]; - } - R2 = y4(l6); - var W2 = a42(u6); - if (W2 < t12.n - Z2.v - 1) { - var z3 = a0(O2[R2][0], O2[R2][1]); - a10 = K3(u6, z3) + (W2 << z3); + h6 = Y4 > g6 && Y4 > P3 || Y4 < g6 && Y4 < P3 ? v8 + A4 + 2 * Y4 >>> 2 : A4 + v8 >>> 1; + l6 = Z2.t * Z2.c[t12.g + Y4 - g6] + Z2.c[t12.g + g6 - A4]; + } + R3 = y4(l6); + var W3 = a42(u6); + if (W3 < t12.n - Z2.v - 1) { + var z3 = a0(O3[R3][0], O3[R3][1]); + a10 = K3(u6, z3) + (W3 << z3); } else { a10 = K3(u6, Z2.v) + 1; } a10 = a10 & 1 ? -1 - (a10 >>> 1) : a10 >>> 1; - O2[R2][0] += y4(a10); - if (O2[R2][1] == t12.f) { - O2[R2][0] >>>= 1; - O2[R2][1] >>>= 1; + O3[R3][0] += y4(a10); + if (O3[R3][1] == t12.f) { + O3[R3][0] >>>= 1; + O3[R3][1] >>>= 1; } - O2[R2][1]++; + O3[R3][1]++; h6 = l6 < 0 ? h6 - a10 : h6 + a10; if (t12.i) { if (h6 < 0) h6 += Z2.w; else if (h6 > t12.g) h6 -= Z2.w; } - w6[X2] = h6 >= 0 ? Math.min(h6, t12.g) : 0; + w6[X3] = h6 >= 0 ? Math.min(h6, t12.g) : 0; } - function U2(t12, Z2, u6) { + function U3(t12, Z2, u6) { var e6 = t12[0].length; - for (var Q2 = Z2; Q2 <= u6; Q2++) { - t12[Q2][0] = t12[Q2 - 1][1]; - t12[Q2][e6 - 1] = t12[Q2 - 1][e6 - 2]; + for (var Q3 = Z2; Q3 <= u6; Q3++) { + t12[Q3][0] = t12[Q3 - 1][1]; + t12[Q3][e6 - 1] = t12[Q3 - 1][e6 - 2]; } } - function B3(t12) { - U2(t12, s6, q6); - U2(t12, i6, J3); - U2(t12, x7, $); + function B4(t12) { + U3(t12, s6, q7); + U3(t12, i6, J3); + U3(t12, x8, $); } - function _(t12, Z2, u6, e6, Q2, V2, O2, o6, X2, k6, j6, I3, a10) { - var l6 = 0, R2 = 1, w6 = Q2 < M2 && Q2 > J3; - while (R2 < t12.m) { + function _2(t12, Z2, u6, e6, Q3, V3, O3, o6, X3, k7, j7, I4, a10) { + var l6 = 0, R3 = 1, w6 = Q3 < M3 && Q3 > J3; + while (R3 < t12.m) { if (l6 < t12.m) { - r6(t12, Z2, u6, e6, Q2, l6, O2[X2], t12.h && (w6 && k6 || !w6 && (j6 || (l6 & I3) == a10))); - r6(t12, Z2, u6, e6, V2, l6, O2[X2], t12.h && (!w6 && k6 || w6 && (j6 || (l6 & I3) == a10))); + r6(t12, Z2, u6, e6, Q3, l6, O3[X3], t12.h && (w6 && k7 || !w6 && (j7 || (l6 & I4) == a10))); + r6(t12, Z2, u6, e6, V3, l6, O3[X3], t12.h && (!w6 && k7 || w6 && (j7 || (l6 & I4) == a10))); l6 += 2; } if (l6 > 8) { - r6(t12, Z2, u6, e6, Q2, R2, o6[X2]); - r6(t12, Z2, u6, e6, V2, R2, o6[X2]); - R2 += 2; + r6(t12, Z2, u6, e6, Q3, R3, o6[X3]); + r6(t12, Z2, u6, e6, V3, R3, o6[X3]); + R3 += 2; } } - B3(e6); - } - function a8(t12, Z2, u6, e6, Q2, V2) { - _(t12, Z2, u6, e6, i6, s6, Q2, V2, 0, 0, 1, 0, 8); - _(t12, Z2, u6, e6, c7, x7, Q2, V2, 1, 0, 1, 0, 8); - _(t12, Z2, u6, e6, b6, T2, Q2, V2, 2, 1, 0, 3, 0); - _(t12, Z2, u6, e6, a32, L2, Q2, V2, 0, 0, 0, 3, 2); - _(t12, Z2, u6, e6, J3, f6, Q2, V2, 1, 0, 0, 3, 2); - _(t12, Z2, u6, e6, q6, $, Q2, V2, 2, 1, 0, 3, 0); - } - function a9(t12, Z2, u6, e6, Q2, V2) { - var O2 = V2.length, o6 = t12.l; - if (Q2 + 1 == t12.s) o6 = t12.e - Q2 * t12.l; - var X2 = 6 * t12.e * e6 + Q2 * t12.l; - for (var k6 = 0; k6 < 6; k6++) { - for (var j6 = 0; j6 < o6; j6++) { - var I3 = V2[k6 % O2][j6 % O2], a10; - if (I3 == 0) { - a10 = i6 + (k6 >>> 1); - } else if (I3 == 2) { - a10 = x7 + (k6 >>> 1); + B4(e6); + } + function a8(t12, Z2, u6, e6, Q3, V3) { + _2(t12, Z2, u6, e6, i6, s6, Q3, V3, 0, 0, 1, 0, 8); + _2(t12, Z2, u6, e6, c7, x8, Q3, V3, 1, 0, 1, 0, 8); + _2(t12, Z2, u6, e6, b6, T3, Q3, V3, 2, 1, 0, 3, 0); + _2(t12, Z2, u6, e6, a32, L3, Q3, V3, 0, 0, 0, 3, 2); + _2(t12, Z2, u6, e6, J3, f6, Q3, V3, 1, 0, 0, 3, 2); + _2(t12, Z2, u6, e6, q7, $, Q3, V3, 2, 1, 0, 3, 0); + } + function a9(t12, Z2, u6, e6, Q3, V3) { + var O3 = V3.length, o6 = t12.l; + if (Q3 + 1 == t12.s) o6 = t12.e - Q3 * t12.l; + var X3 = 6 * t12.e * e6 + Q3 * t12.l; + for (var k7 = 0; k7 < 6; k7++) { + for (var j7 = 0; j7 < o6; j7++) { + var I4 = V3[k7 % O3][j7 % O3], a10; + if (I4 == 0) { + a10 = i6 + (k7 >>> 1); + } else if (I4 == 2) { + a10 = x8 + (k7 >>> 1); } else { - a10 = s6 + k6; + a10 = s6 + k7; } - var l6 = t12.h ? (j6 * 2 / 3 & 2147483646 | j6 % 3 & 1) + (j6 % 3 >>> 1) : j6 >>> 1; - Z2[X2 + j6] = u6[a10][l6 + 1]; + var l6 = t12.h ? (j7 * 2 / 3 & 2147483646 | j7 % 3 & 1) + (j7 % 3 >>> 1) : j7 >>> 1; + Z2[X3 + j7] = u6[a10][l6 + 1]; } - X2 += t12.e; + X3 += t12.e; } } UTIF2._decompressRAF = function(t12, Z2) { - var u6 = a52(t12), e6 = a7(t12, u6), Q2 = a22(u6), V2 = new Int16Array(u6.e * u6.q); + var u6 = a52(t12), e6 = a7(t12, u6), Q3 = a22(u6), V3 = new Int16Array(u6.e * u6.q); if (Z2 == null) { Z2 = u6.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]; } - var O2 = [[G3, b6], [F3, J3], [N2, f6], [E3, q6], [M2, L2], [m6, $]], o6 = []; - for (var X2 = 0; X2 < p6; X2++) { - o6[X2] = new Uint16Array(u6.A); + var O3 = [[G4, b6], [F4, J3], [N3, f6], [E3, q7], [M3, L3], [m6, $]], o6 = []; + for (var X3 = 0; X3 < p6; X3++) { + o6[X3] = new Uint16Array(u6.A); } - for (var k6 = 0; k6 < u6.s; k6++) { - var j6 = D3(Q2), I3 = D3(Q2); - for (var X2 = 0; X2 < p6; X2++) { + for (var k7 = 0; k7 < u6.s; k7++) { + var j7 = D4(Q3), I4 = D4(Q3); + for (var X3 = 0; X3 < p6; X3++) { for (var a10 = 0; a10 < u6.A; a10++) { - o6[X2][a10] = 0; + o6[X3][a10] = 0; } } for (var l6 = 0; l6 < u6.d; l6++) { - a8(u6, Q2, e6[k6], o6, j6, I3); - for (var X2 = 0; X2 < 6; X2++) { + a8(u6, Q3, e6[k7], o6, j7, I4); + for (var X3 = 0; X3 < 6; X3++) { for (var a10 = 0; a10 < u6.A; a10++) { - o6[O2[X2][0]][a10] = o6[O2[X2][1]][a10]; + o6[O3[X3][0]][a10] = o6[O3[X3][1]][a10]; } } - a9(u6, V2, o6, l6, k6, Z2); - for (var X2 = i6; X2 < p6; X2++) { - if ([N2, E3, M2, m6].indexOf(X2) == -1) { + a9(u6, V3, o6, l6, k7, Z2); + for (var X3 = i6; X3 < p6; X3++) { + if ([N3, E3, M3, m6].indexOf(X3) == -1) { for (var a10 = 0; a10 < u6.A; a10++) { - o6[X2][a10] = 0; + o6[X3][a10] = 0; } } } - B3(o6); + B4(o6); } } - return V2; + return V3; }; })(); })(UTIF, pako); @@ -60199,7 +61339,7 @@ var require_ieee754 = __commonJS({ var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var rt2 = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i6 = isLE ? 0 : nBytes - 1; var d6 = isLE ? 1 : -1; var s6 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; @@ -60214,9 +61354,9 @@ var require_ieee754 = __commonJS({ c7 *= 2; } if (e6 + eBias >= 1) { - value += rt / c7; + value += rt2 / c7; } else { - value += rt * Math.pow(2, 1 - eBias); + value += rt2 * Math.pow(2, 1 - eBias); } if (value * c7 >= 2) { e6++; @@ -61032,9 +62172,9 @@ var require_ReadStreamTokenizer = __commonJS({ var peek_readable_1 = require_lib2(); var maxBufferSize = 256e3; var ReadStreamTokenizer = class extends AbstractTokenizer_1.AbstractTokenizer { - constructor(stream3, fileInfo) { + constructor(stream2, fileInfo) { super(fileInfo); - this.streamReader = new peek_readable_1.StreamReader(stream3); + this.streamReader = new peek_readable_1.StreamReader(stream2); } /** * Get file information, an HTTP-client may implement this doing a HEAD request @@ -61193,9 +62333,9 @@ var require_core = __commonJS({ Object.defineProperty(exports2, "EndOfStreamError", { enumerable: true, get: function() { return peek_readable_1.EndOfStreamError; } }); - function fromStream2(stream3, fileInfo) { + function fromStream2(stream2, fileInfo) { fileInfo = fileInfo ? fileInfo : {}; - return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream3, fileInfo); + return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream2, fileInfo); } exports2.fromStream = fromStream2; function fromBuffer2(uint8Array, fileInfo) { @@ -61534,8 +62674,8 @@ var require_core2 = __commonJS({ } = require_util10(); var supported = require_supported(); var minimumBytes = 4100; - async function fromStream(stream3) { - const tokenizer = await strtok3.fromStream(stream3); + async function fromStream(stream2) { + const tokenizer = await strtok3.fromStream(stream2); try { return await fromTokenizer(tokenizer); } finally { @@ -62074,8 +63214,8 @@ var require_core2 = __commonJS({ --children2; } } - const re = await readElement(); - const docType = await readChildren(1, re.len); + const re2 = await readElement(); + const docType = await readChildren(1, re2.len); switch (docType) { case "webm": return { @@ -62497,7 +63637,7 @@ var require_core2 = __commonJS({ mime: "application/x-asar" }; } - } catch (_) { + } catch (_2) { } } } @@ -62672,30 +63812,30 @@ var require_Mime = __commonJS({ }); type = type.toLowerCase(); for (let i6 = 0; i6 < extensions.length; i6++) { - const ext2 = extensions[i6]; - if (ext2[0] === "*") { + const ext = extensions[i6]; + if (ext[0] === "*") { continue; } - if (!force && ext2 in this._types) { + if (!force && ext in this._types) { throw new Error( - 'Attempt to change mapping for "' + ext2 + '" extension from "' + this._types[ext2] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext2 + '" from the list of extensions for "' + type + '".' + 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".' ); } - this._types[ext2] = type; + this._types[ext] = type; } if (force || !this._extensions[type]) { - const ext2 = extensions[0]; - this._extensions[type] = ext2[0] !== "*" ? ext2 : ext2.substr(1); + const ext = extensions[0]; + this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1); } } }; - Mime.prototype.getType = function(path7) { - path7 = String(path7); - let last = path7.replace(/^.*[/\\]/, "").toLowerCase(); - let ext2 = last.replace(/^.*\./, "").toLowerCase(); - let hasPath = last.length < path7.length; - let hasDot = ext2.length < last.length - 1; - return (hasDot || !hasPath) && this._types[ext2] || null; + Mime.prototype.getType = function(path6) { + path6 = String(path6); + let last = path6.replace(/^.*[/\\]/, "").toLowerCase(); + let ext = last.replace(/^.*\./, "").toLowerCase(); + let hasPath = last.length < path6.length; + let hasDot = ext.length < last.length - 1; + return (hasDot || !hasPath) && this._types[ext] || null; }; Mime.prototype.getExtension = function(type) { type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; @@ -62727,29 +63867,29 @@ var require_jpeg = __commonJS({ "../node_modules/exif-parser/lib/jpeg.js"(exports2, module2) { "use strict"; module2.exports = { - parseSections: function(stream3, iterator2) { + parseSections: function(stream2, iterator2) { var len, markerType; - stream3.setBigEndian(true); - while (stream3.remainingLength() > 0 && markerType !== 218) { - if (stream3.nextUInt8() !== 255) { + stream2.setBigEndian(true); + while (stream2.remainingLength() > 0 && markerType !== 218) { + if (stream2.nextUInt8() !== 255) { throw new Error("Invalid JPEG section offset"); } - markerType = stream3.nextUInt8(); + markerType = stream2.nextUInt8(); if (markerType >= 208 && markerType <= 217 || markerType === 218) { len = 0; } else { - len = stream3.nextUInt16() - 2; + len = stream2.nextUInt16() - 2; } - iterator2(markerType, stream3.branch(0, len)); - stream3.skip(len); + iterator2(markerType, stream2.branch(0, len)); + stream2.skip(len); } }, //stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator - getSizeFromSOFSection: function(stream3) { - stream3.skip(1); + getSizeFromSOFSection: function(stream2) { + stream2.skip(1); return { - height: stream3.nextUInt16(), - width: stream3.nextUInt16() + height: stream2.nextUInt16(), + width: stream2.nextUInt16() }; }, getSectionName: function(markerType) { @@ -62805,28 +63945,28 @@ var require_jpeg = __commonJS({ var require_exif = __commonJS({ "../node_modules/exif-parser/lib/exif.js"(exports2, module2) { "use strict"; - function readExifValue(format2, stream3) { + function readExifValue(format2, stream2) { switch (format2) { case 1: - return stream3.nextUInt8(); + return stream2.nextUInt8(); case 3: - return stream3.nextUInt16(); + return stream2.nextUInt16(); case 4: - return stream3.nextUInt32(); + return stream2.nextUInt32(); case 5: - return [stream3.nextUInt32(), stream3.nextUInt32()]; + return [stream2.nextUInt32(), stream2.nextUInt32()]; case 6: - return stream3.nextInt8(); + return stream2.nextInt8(); case 8: - return stream3.nextUInt16(); + return stream2.nextUInt16(); case 9: - return stream3.nextUInt32(); + return stream2.nextUInt32(); case 10: - return [stream3.nextInt32(), stream3.nextInt32()]; + return [stream2.nextInt32(), stream2.nextInt32()]; case 11: - return stream3.nextFloat(); + return stream2.nextFloat(); case 12: - return stream3.nextDouble(); + return stream2.nextDouble(); default: throw new Error("Invalid format while decoding: " + format2); } @@ -62853,52 +63993,52 @@ var require_exif = __commonJS({ return 0; } } - function readExifTag(tiffMarker, stream3) { - var tagType = stream3.nextUInt16(), format2 = stream3.nextUInt16(), bytesPerComponent = getBytesPerComponent(format2), components = stream3.nextUInt32(), valueBytes = bytesPerComponent * components, values, value, c7; + function readExifTag(tiffMarker, stream2) { + var tagType = stream2.nextUInt16(), format2 = stream2.nextUInt16(), bytesPerComponent = getBytesPerComponent(format2), components = stream2.nextUInt32(), valueBytes = bytesPerComponent * components, values, value, c7; if (valueBytes > 4) { - stream3 = tiffMarker.openWithOffset(stream3.nextUInt32()); + stream2 = tiffMarker.openWithOffset(stream2.nextUInt32()); } if (format2 === 2) { - values = stream3.nextString(components); + values = stream2.nextString(components); var lastNull = values.indexOf("\0"); if (lastNull !== -1) { values = values.substr(0, lastNull); } } else if (format2 === 7) { - values = stream3.nextBuffer(components); + values = stream2.nextBuffer(components); } else if (format2 !== 0) { values = []; for (c7 = 0; c7 < components; ++c7) { - values.push(readExifValue(format2, stream3)); + values.push(readExifValue(format2, stream2)); } } if (valueBytes < 4) { - stream3.skip(4 - valueBytes); + stream2.skip(4 - valueBytes); } return [tagType, values, format2]; } - function readIFDSection(tiffMarker, stream3, iterator2) { - var numberOfEntries = stream3.nextUInt16(), tag, i6; + function readIFDSection(tiffMarker, stream2, iterator2) { + var numberOfEntries = stream2.nextUInt16(), tag, i6; for (i6 = 0; i6 < numberOfEntries; ++i6) { - tag = readExifTag(tiffMarker, stream3); + tag = readExifTag(tiffMarker, stream2); iterator2(tag[0], tag[1], tag[2]); } } - function readHeader(stream3) { - var exifHeader = stream3.nextString(6); + function readHeader(stream2) { + var exifHeader = stream2.nextString(6); if (exifHeader !== "Exif\0\0") { throw new Error("Invalid EXIF header"); } - var tiffMarker = stream3.mark(); - var tiffHeader = stream3.nextUInt16(); + var tiffMarker = stream2.mark(); + var tiffHeader = stream2.nextUInt16(); if (tiffHeader === 18761) { - stream3.setBigEndian(false); + stream2.setBigEndian(false); } else if (tiffHeader === 19789) { - stream3.setBigEndian(true); + stream2.setBigEndian(true); } else { throw new Error("Invalid TIFF header"); } - if (stream3.nextUInt16() !== 42) { + if (stream2.nextUInt16() !== 42) { throw new Error("Invalid TIFF data"); } return tiffMarker; @@ -62909,15 +64049,15 @@ var require_exif = __commonJS({ GPSIFD: 3, SubIFD: 4, InteropIFD: 5, - parseTags: function(stream3, iterator2) { + parseTags: function(stream2, iterator2) { var tiffMarker; try { - tiffMarker = readHeader(stream3); + tiffMarker = readHeader(stream2); } catch (e6) { return false; } var subIfdOffset, gpsOffset, interopOffset; - var ifd0Stream = tiffMarker.openWithOffset(stream3.nextUInt32()), IFD0 = this.IFD0; + var ifd0Stream = tiffMarker.openWithOffset(stream2.nextUInt32()), IFD0 = this.IFD0; readIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format2) { switch (tagType) { case 34853: @@ -63628,8 +64768,8 @@ var require_parser2 = __commonJS({ return this.imageSize; }, getThumbnailSize: function() { - var stream3 = this._getThumbnailStream(), size; - jpeg2.parseSections(stream3, function(sectionType, sectionStream) { + var stream2 = this._getThumbnailStream(), size; + jpeg2.parseSections(stream2, function(sectionType, sectionStream) { if (jpeg2.getSectionName(sectionType).name === "SOF") { size = jpeg2.getSizeFromSOFSection(sectionStream); } @@ -63637,8 +64777,8 @@ var require_parser2 = __commonJS({ return size; } }; - function Parser(stream3) { - this.stream = stream3; + function Parser(stream2) { + this.stream = stream2; this.flags = { readBinaryTags: false, resolveTagNames: true, @@ -63674,7 +64814,7 @@ var require_parser2 = __commonJS({ return this; }, parse: function() { - var start = this.stream.mark(), stream3 = start.openWithOffset(0), flags = this.flags, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset, tagNames, getTagValue, setTagValue; + var start = this.stream.mark(), stream2 = start.openWithOffset(0), flags = this.flags, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset, tagNames, getTagValue, setTagValue; if (flags.resolveTagNames) { tagNames = require_exif_tags(); } @@ -63706,7 +64846,7 @@ var require_parser2 = __commonJS({ } }; } - jpeg2.parseSections(stream3, function(sectionType, sectionStream) { + jpeg2.parseSections(stream2, function(sectionType, sectionStream) { var validExifHeaders, sectionOffset = sectionStream.offsetFrom(start); if (sectionType === 225) { validExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format2) { @@ -64110,18 +65250,18 @@ var require_parse_bmfont_ascii = __commonJS({ }); var data = []; for (var i6 = 0; i6 < line.length; i6++) { - var dt = line[i6]; + var dt2 = line[i6]; if (i6 === 0) { data.push({ - key: dt[0], + key: dt2[0], data: "" }); } else if (i6 === line.length - 1) { - data[data.length - 1].data = parseData(dt[0]); + data[data.length - 1].data = parseData(dt2[0]); } else { - data[data.length - 1].data = parseData(dt[0]); + data[data.length - 1].data = parseData(dt2[0]); data.push({ - key: dt[1], + key: dt2[1], data: "" }); } @@ -64130,8 +65270,8 @@ var require_parse_bmfont_ascii = __commonJS({ key, data: {} }; - data.forEach(function(v7) { - out.data[v7.key] = v7.data; + data.forEach(function(v8) { + out.data[v8.key] = v8.data; }); return out; } @@ -64637,7 +65777,7 @@ var require_XMLElement = __commonJS({ module2.exports = XMLElement = (function(superClass) { extend(XMLElement2, superClass); function XMLElement2(parent, name, attributes) { - var child2, j6, len, ref1; + var child2, j7, len, ref1; XMLElement2.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing element name. " + this.debugInfo()); @@ -64655,8 +65795,8 @@ var require_XMLElement = __commonJS({ parent.rootObject = this; if (parent.children) { ref1 = parent.children; - for (j6 = 0, len = ref1.length; j6 < len; j6++) { - child2 = ref1[j6]; + for (j7 = 0, len = ref1.length; j7 < len; j7++) { + child2 = ref1[j7]; if (child2.type === NodeType.DocType) { child2.name = this.name; break; @@ -64754,14 +65894,14 @@ var require_XMLElement = __commonJS({ return this; }; XMLElement2.prototype.removeAttribute = function(name) { - var attName, j6, len; + var attName, j7, len; if (name == null) { throw new Error("Missing attribute name. " + this.debugInfo()); } name = getValue(name); if (Array.isArray(name)) { - for (j6 = 0, len = name.length; j6 < len; j6++) { - attName = name[j6]; + for (j7 = 0, len = name.length; j7 < len; j7++) { + attName = name[j7]; delete this.attribs[attName]; } } else { @@ -64851,7 +65991,7 @@ var require_XMLElement = __commonJS({ throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLElement2.prototype.isEqualNode = function(node) { - var i6, j6, ref1; + var i6, j7, ref1; if (!XMLElement2.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { return false; } @@ -64867,7 +66007,7 @@ var require_XMLElement = __commonJS({ if (node.attribs.length !== this.attribs.length) { return false; } - for (i6 = j6 = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j6 <= ref1 : j6 >= ref1; i6 = 0 <= ref1 ? ++j6 : --j6) { + for (i6 = j7 = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j7 <= ref1 : j7 >= ref1; i6 = 0 <= ref1 ? ++j7 : --j7) { if (!this.attribs[i6].isEqualNode(node.attribs[i6])) { return false; } @@ -65175,7 +66315,7 @@ var require_XMLDTDEntity = __commonJS({ NodeType = require_NodeType(); module2.exports = XMLDTDEntity = (function(superClass) { extend(XMLDTDEntity2, superClass); - function XMLDTDEntity2(parent, pe, name, value) { + function XMLDTDEntity2(parent, pe2, name, value) { XMLDTDEntity2.__super__.constructor.call(this, parent); if (name == null) { throw new Error("Missing DTD entity name. " + this.debugInfo(name)); @@ -65183,7 +66323,7 @@ var require_XMLDTDEntity = __commonJS({ if (value == null) { throw new Error("Missing DTD entity value. " + this.debugInfo(name)); } - this.pe = !!pe; + this.pe = !!pe2; this.name = this.stringify.name(name); this.type = NodeType.EntityDeclaration; if (!isObject2(value)) { @@ -65874,12 +67014,12 @@ var require_XMLNode = __commonJS({ }); Object.defineProperty(XMLNode2.prototype, "textContent", { get: function() { - var child2, j6, len, ref2, str; + var child2, j7, len, ref2, str; if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) { str = ""; ref2 = this.children; - for (j6 = 0, len = ref2.length; j6 < len; j6++) { - child2 = ref2[j6]; + for (j7 = 0, len = ref2.length; j7 < len; j7++) { + child2 = ref2[j7]; if (child2.textContent) { str += child2.textContent; } @@ -65894,7 +67034,7 @@ var require_XMLNode = __commonJS({ } }); XMLNode2.prototype.setParent = function(parent) { - var child2, j6, len, ref2, results; + var child2, j7, len, ref2, results; this.parent = parent; if (parent) { this.options = parent.options; @@ -65902,14 +67042,14 @@ var require_XMLNode = __commonJS({ } ref2 = this.children; results = []; - for (j6 = 0, len = ref2.length; j6 < len; j6++) { - child2 = ref2[j6]; + for (j7 = 0, len = ref2.length; j7 < len; j7++) { + child2 = ref2[j7]; results.push(child2.setParent(this)); } return results; }; XMLNode2.prototype.element = function(name, attributes, text) { - var childNode, item, j6, k6, key, lastChild, len, len1, ref2, ref3, val; + var childNode, item, j7, k7, key, lastChild, len, len1, ref2, ref3, val; lastChild = null; if (attributes === null && text == null) { ref2 = [{}, null], attributes = ref2[0], text = ref2[1]; @@ -65925,8 +67065,8 @@ var require_XMLNode = __commonJS({ name = getValue(name); } if (Array.isArray(name)) { - for (j6 = 0, len = name.length; j6 < len; j6++) { - item = name[j6]; + for (j7 = 0, len = name.length; j7 < len; j7++) { + item = name[j7]; lastChild = this.element(item); } } else if (isFunction2(name)) { @@ -65947,8 +67087,8 @@ var require_XMLNode = __commonJS({ } else if (!this.options.keepNullNodes && val == null) { lastChild = this.dummy(); } else if (!this.options.separateArrayItems && Array.isArray(val)) { - for (k6 = 0, len1 = val.length; k6 < len1; k6++) { - item = val[k6]; + for (k7 = 0, len1 = val.length; k7 < len1; k7++) { + item = val[k7]; childNode = {}; childNode[key] = item; lastChild = this.element(childNode); @@ -66098,7 +67238,7 @@ var require_XMLNode = __commonJS({ return child2; }; XMLNode2.prototype.instruction = function(target, value) { - var insTarget, insValue, instruction, j6, len; + var insTarget, insValue, instruction, j7, len; if (target != null) { target = getValue(target); } @@ -66106,8 +67246,8 @@ var require_XMLNode = __commonJS({ value = getValue(value); } if (Array.isArray(target)) { - for (j6 = 0, len = target.length; j6 < len; j6++) { - insTarget = target[j6]; + for (j7 = 0, len = target.length; j7 < len; j7++) { + insTarget = target[j7]; this.instruction(insTarget); } } else if (isObject2(target)) { @@ -66155,11 +67295,11 @@ var require_XMLNode = __commonJS({ return doc.root() || doc; }; XMLNode2.prototype.dtd = function(pubID, sysID) { - var child2, doc, doctype, i6, j6, k6, len, len1, ref2, ref3; + var child2, doc, doctype, i6, j7, k7, len, len1, ref2, ref3; doc = this.document(); doctype = new XMLDocType(doc, pubID, sysID); ref2 = doc.children; - for (i6 = j6 = 0, len = ref2.length; j6 < len; i6 = ++j6) { + for (i6 = j7 = 0, len = ref2.length; j7 < len; i6 = ++j7) { child2 = ref2[i6]; if (child2.type === NodeType.DocType) { doc.children[i6] = doctype; @@ -66167,7 +67307,7 @@ var require_XMLNode = __commonJS({ } } ref3 = doc.children; - for (i6 = k6 = 0, len1 = ref3.length; k6 < len1; i6 = ++k6) { + for (i6 = k7 = 0, len1 = ref3.length; k7 < len1; i6 = ++k7) { child2 = ref3[i6]; if (child2.isRoot) { doc.children.splice(i6, 0, doctype); @@ -66358,14 +67498,14 @@ var require_XMLNode = __commonJS({ throw new Error("This DOM method is not implemented." + this.debugInfo()); }; XMLNode2.prototype.isEqualNode = function(node) { - var i6, j6, ref2; + var i6, j7, ref2; if (node.nodeType !== this.nodeType) { return false; } if (node.children.length !== this.children.length) { return false; } - for (i6 = j6 = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j6 <= ref2 : j6 >= ref2; i6 = 0 <= ref2 ? ++j6 : --j6) { + for (i6 = j7 = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j7 <= ref2 : j7 >= ref2; i6 = 0 <= ref2 ? ++j7 : --j7) { if (!this.children[i6].isEqualNode(node.children[i6])) { return false; } @@ -66388,10 +67528,10 @@ var require_XMLNode = __commonJS({ return other === this || this.isDescendant(other); }; XMLNode2.prototype.isDescendant = function(node) { - var child2, isDescendantChild, j6, len, ref2; + var child2, isDescendantChild, j7, len, ref2; ref2 = this.children; - for (j6 = 0, len = ref2.length; j6 < len; j6++) { - child2 = ref2[j6]; + for (j7 = 0, len = ref2.length; j7 < len; j7++) { + child2 = ref2[j7]; if (node === child2) { return true; } @@ -66442,11 +67582,11 @@ var require_XMLNode = __commonJS({ } }; XMLNode2.prototype.foreachTreeNode = function(node, func) { - var child2, j6, len, ref2, res; + var child2, j7, len, ref2, res; node || (node = this.document()); ref2 = node.children; - for (j6 = 0, len = ref2.length; j6 < len; j6++) { - child2 = ref2[j6]; + for (j7 = 0, len = ref2.length; j7 < len; j7++) { + child2 = ref2[j7]; if (res = func(child2)) { return res; } else { @@ -66468,9 +67608,9 @@ var require_XMLStringifier = __commonJS({ "../node_modules/xmlbuilder/lib/XMLStringifier.js"(exports2, module2) { "use strict"; (function() { - var XMLStringifier, bind2 = function(fn, me) { + var XMLStringifier, bind2 = function(fn, me2) { return function() { - return fn.apply(me, arguments); + return fn.apply(me2, arguments); }; }, hasProp = {}.hasOwnProperty; module2.exports = XMLStringifier = (function() { @@ -66855,7 +67995,7 @@ var require_XMLWriterBase = __commonJS({ return r6; }; XMLWriterBase2.prototype.element = function(node, options, level) { - var att, child2, childNodeCount, firstChildNode, i6, j6, len, len1, name, prettySuppressed, r6, ref, ref1, ref2; + var att, child2, childNodeCount, firstChildNode, i6, j7, len, len1, name, prettySuppressed, r6, ref, ref1, ref2; level || (level = 0); prettySuppressed = false; r6 = ""; @@ -66906,8 +68046,8 @@ var require_XMLWriterBase = __commonJS({ r6 += ">" + this.endline(node, options, level); options.state = WriterState.InsideTag; ref2 = node.children; - for (j6 = 0, len1 = ref2.length; j6 < len1; j6++) { - child2 = ref2[j6]; + for (j7 = 0, len1 = ref2.length; j7 < len1; j7++) { + child2 = ref2[j7]; r6 += this.writeChildNode(child2, options, level + 1); } options.state = WriterState.CloseTag; @@ -67329,10 +68469,10 @@ var require_XMLDocument = __commonJS({ XMLDocument2.prototype.createRange = function() { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; - XMLDocument2.prototype.createNodeIterator = function(root, whatToShow, filter2) { + XMLDocument2.prototype.createNodeIterator = function(root, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; - XMLDocument2.prototype.createTreeWalker = function(root, whatToShow, filter2) { + XMLDocument2.prototype.createTreeWalker = function(root, whatToShow, filter) { throw new Error("This DOM method is not implemented." + this.debugInfo()); }; return XMLDocument2; @@ -67830,8 +68970,8 @@ var require_XMLStreamWriter = __commonJS({ WriterState = require_WriterState(); module2.exports = XMLStreamWriter = (function(superClass) { extend(XMLStreamWriter2, superClass); - function XMLStreamWriter2(stream3, options) { - this.stream = stream3; + function XMLStreamWriter2(stream2, options) { + this.stream = stream2; XMLStreamWriter2.__super__.constructor.call(this, options); } XMLStreamWriter2.prototype.endline = function(node, options, level) { @@ -67842,17 +68982,17 @@ var require_XMLStreamWriter = __commonJS({ } }; XMLStreamWriter2.prototype.document = function(doc, options) { - var child2, i6, j6, k6, len, len1, ref, ref1, results; + var child2, i6, j7, k7, len, len1, ref, ref1, results; ref = doc.children; - for (i6 = j6 = 0, len = ref.length; j6 < len; i6 = ++j6) { + for (i6 = j7 = 0, len = ref.length; j7 < len; i6 = ++j7) { child2 = ref[i6]; child2.isLastRootNode = i6 === doc.children.length - 1; } options = this.filterOptions(options); ref1 = doc.children; results = []; - for (k6 = 0, len1 = ref1.length; k6 < len1; k6++) { - child2 = ref1[k6]; + for (k7 = 0, len1 = ref1.length; k7 < len1; k7++) { + child2 = ref1[k7]; results.push(this.writeChildNode(child2, options, 0)); } return results; @@ -67870,7 +69010,7 @@ var require_XMLStreamWriter = __commonJS({ return this.stream.write(XMLStreamWriter2.__super__.declaration.call(this, node, options, level)); }; XMLStreamWriter2.prototype.docType = function(node, options, level) { - var child2, j6, len, ref; + var child2, j7, len, ref; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; @@ -67886,8 +69026,8 @@ var require_XMLStreamWriter = __commonJS({ this.stream.write(this.endline(node, options, level)); options.state = WriterState.InsideTag; ref = node.children; - for (j6 = 0, len = ref.length; j6 < len; j6++) { - child2 = ref[j6]; + for (j7 = 0, len = ref.length; j7 < len; j7++) { + child2 = ref[j7]; this.writeChildNode(child2, options, level + 1); } options.state = WriterState.CloseTag; @@ -67900,7 +69040,7 @@ var require_XMLStreamWriter = __commonJS({ return this.closeNode(node, options, level); }; XMLStreamWriter2.prototype.element = function(node, options, level) { - var att, child2, childNodeCount, firstChildNode, j6, len, name, prettySuppressed, ref, ref1; + var att, child2, childNodeCount, firstChildNode, j7, len, name, prettySuppressed, ref, ref1; level || (level = 0); this.openNode(node, options, level); options.state = WriterState.OpenTag; @@ -67938,8 +69078,8 @@ var require_XMLStreamWriter = __commonJS({ this.stream.write(">" + this.endline(node, options, level)); options.state = WriterState.InsideTag; ref1 = node.children; - for (j6 = 0, len = ref1.length; j6 < len; j6++) { - child2 = ref1[j6]; + for (j7 = 0, len = ref1.length; j7 < len; j7++) { + child2 = ref1[j7]; this.writeChildNode(child2, options, level + 1); } options.state = WriterState.CloseTag; @@ -68021,8 +69161,8 @@ var require_lib3 = __commonJS({ module2.exports.stringWriter = function(options) { return new XMLStringWriter(options); }; - module2.exports.streamWriter = function(stream3, options) { - return new XMLStreamWriter(stream3, options); + module2.exports.streamWriter = function(stream2, options) { + return new XMLStreamWriter(stream2, options); }; module2.exports.implementation = new XMLDOMImplementation(); module2.exports.nodeType = NodeType; @@ -68037,9 +69177,9 @@ var require_builder = __commonJS({ "use strict"; (function() { "use strict"; - var builder, defaults3, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; + var builder, defaults2, escapeCDATA, requiresCDATA, wrapCDATA, hasProp = {}.hasOwnProperty; builder = require_lib3(); - defaults3 = require_defaults().defaults; + defaults2 = require_defaults().defaults; requiresCDATA = function(entry) { return typeof entry === "string" && (entry.indexOf("&") >= 0 || entry.indexOf(">") >= 0 || entry.indexOf("<") >= 0); }; @@ -68053,7 +69193,7 @@ var require_builder = __commonJS({ function Builder(opts) { var key, ref, value; this.options = {}; - ref = defaults3["0.2"]; + ref = defaults2["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; @@ -68069,7 +69209,7 @@ var require_builder = __commonJS({ var attrkey, charkey, render, rootElement, rootName; attrkey = this.options.attrkey; charkey = this.options.charkey; - if (Object.keys(rootObj).length === 1 && this.options.rootName === defaults3["0.2"].rootName) { + if (Object.keys(rootObj).length === 1 && this.options.rootName === defaults2["0.2"].rootName) { rootName = Object.keys(rootObj)[0]; rootObj = rootObj[rootName]; } else { @@ -68233,10 +69373,10 @@ var require_sax = __commonJS({ } if (!Object.create) { Object.create = function(o6) { - function F3() { + function F4() { } - F3.prototype = o6; - var newf = new F3(); + F4.prototype = o6; + var newf = new F4(); return newf; }; } @@ -68306,14 +69446,14 @@ var require_sax = __commonJS({ flushBuffers(this); } }; - var Stream2; + var Stream; try { - Stream2 = require("stream").Stream; + Stream = require("stream").Stream; } catch (ex) { - Stream2 = function() { + Stream = function() { }; } - if (!Stream2) Stream2 = function() { + if (!Stream) Stream = function() { }; var streamWraps = sax.EVENTS.filter(function(ev) { return ev !== "error" && ev !== "end"; @@ -68325,38 +69465,38 @@ var require_sax = __commonJS({ if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt); } - Stream2.apply(this); + Stream.apply(this); this._parser = new SAXParser(strict, opt); this.writable = true; this.readable = true; - var me = this; + var me2 = this; this._parser.onend = function() { - me.emit("end"); + me2.emit("end"); }; this._parser.onerror = function(er) { - me.emit("error", er); - me._parser.error = null; + me2.emit("error", er); + me2._parser.error = null; }; this._decoder = null; streamWraps.forEach(function(ev) { - Object.defineProperty(me, "on" + ev, { + Object.defineProperty(me2, "on" + ev, { get: function() { - return me._parser["on" + ev]; + return me2._parser["on" + ev]; }, set: function(h6) { if (!h6) { - me.removeAllListeners(ev); - me._parser["on" + ev] = h6; + me2.removeAllListeners(ev); + me2._parser["on" + ev] = h6; return h6; } - me.on(ev, h6); + me2.on(ev, h6); }, enumerable: true, configurable: false }); }); } - SAXStream.prototype = Object.create(Stream2.prototype, { + SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } @@ -68381,15 +69521,15 @@ var require_sax = __commonJS({ return true; }; SAXStream.prototype.on = function(ev, handler2) { - var me = this; - if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) { - me._parser["on" + ev] = function() { + var me2 = this; + if (!me2._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) { + me2._parser["on" + ev] = function() { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); args.splice(0, 0, ev); - me.emit.apply(me, args); + me2.emit.apply(me2, args); }; } - return Stream2.prototype.on.call(me, ev, handler2); + return Stream.prototype.on.call(me2, ev, handler2); }; var CDATA = "[CDATA["; var DOCTYPE = "DOCTYPE"; @@ -68974,15 +70114,15 @@ var require_sax = __commonJS({ var tag = parser2.tag = parser2.tags.pop(); parser2.tagName = parser2.tag.name; emitNode(parser2, "onclosetag", parser2.tagName); - var x7 = {}; + var x8 = {}; for (var i6 in tag.ns) { - x7[i6] = tag.ns[i6]; + x8[i6] = tag.ns[i6]; } var parent = parser2.tags[parser2.tags.length - 1] || parser2; if (parser2.opt.xmlns && tag.ns !== parent.ns) { Object.keys(tag.ns).forEach(function(p6) { - var n6 = tag.ns[p6]; - emitNode(parser2, "onclosenamespace", { prefix: p6, uri: n6 }); + var n12 = tag.ns[p6]; + emitNode(parser2, "onclosenamespace", { prefix: p6, uri: n12 }); }); } } @@ -69566,7 +70706,7 @@ var require_sax = __commonJS({ (function() { var stringFromCharCode = String.fromCharCode; var floor = Math.floor; - var fromCodePoint = function() { + var fromCodePoint2 = function() { var MAX_SIZE = 16384; var codeUnits = []; var highSurrogate; @@ -69602,12 +70742,12 @@ var require_sax = __commonJS({ }; if (Object.defineProperty) { Object.defineProperty(String, "fromCodePoint", { - value: fromCodePoint, + value: fromCodePoint2, configurable: true, writable: true }); } else { - String.fromCodePoint = fromCodePoint; + String.fromCodePoint = fromCodePoint2; } })(); } @@ -69671,9 +70811,9 @@ var require_parser3 = __commonJS({ "use strict"; (function() { "use strict"; - var bom, defaults3, events2, isEmpty, processItem, processors, sax, setImmediate2, bind2 = function(fn, me) { + var bom, defaults2, events2, isEmpty, processItem, processors, sax, setImmediate2, bind2 = function(fn, me2) { return function() { - return fn.apply(me, arguments); + return fn.apply(me2, arguments); }; }, extend = function(child2, parent) { for (var key in parent) { @@ -69692,7 +70832,7 @@ var require_parser3 = __commonJS({ bom = require_bom(); processors = require_processors(); setImmediate2 = require("timers").setImmediate; - defaults3 = require_defaults().defaults; + defaults2 = require_defaults().defaults; isEmpty = function(thing) { return typeof thing === "object" && thing != null && Object.keys(thing).length === 0; }; @@ -69717,7 +70857,7 @@ var require_parser3 = __commonJS({ return new exports2.Parser(opts); } this.options = {}; - ref = defaults3["0.2"]; + ref = defaults2["0.2"]; for (key in ref) { if (!hasProp.call(ref, key)) continue; value = ref[key]; @@ -70054,7 +71194,7 @@ var require_xml2js = __commonJS({ "use strict"; (function() { "use strict"; - var builder, defaults3, parser2, processors, extend = function(child2, parent) { + var builder, defaults2, parser2, processors, extend = function(child2, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child2[key] = parent[key]; } @@ -70066,11 +71206,11 @@ var require_xml2js = __commonJS({ child2.__super__ = parent.prototype; return child2; }, hasProp = {}.hasOwnProperty; - defaults3 = require_defaults(); + defaults2 = require_defaults(); builder = require_builder(); parser2 = require_parser3(); processors = require_processors(); - exports2.defaults = defaults3.defaults; + exports2.defaults = defaults2.defaults; exports2.processors = processors; exports2.ValidationError = (function(superClass) { extend(ValidationError, superClass); @@ -70098,13 +71238,13 @@ var require_parse_attribs = __commonJS({ obj2["charset"] = obj2[GLYPH_DESIGNER_ERROR]; delete obj2[GLYPH_DESIGNER_ERROR]; } - for (var k6 in obj2) { - if (k6 === "face" || k6 === "charset") + for (var k7 in obj2) { + if (k7 === "face" || k7 === "charset") continue; - else if (k6 === "padding" || k6 === "spacing") - obj2[k6] = parseIntList(obj2[k6]); + else if (k7 === "padding" || k7 === "spacing") + obj2[k7] = parseIntList(obj2[k7]); else - obj2[k6] = parseInt(obj2[k6], 10); + obj2[k7] = parseInt(obj2[k7], 10); } return obj2; }; @@ -70319,7 +71459,7 @@ var require_simpleXmlToJson_min = __commonJS({ } var t12 = (e7) => { if (!e7) return null; - const n7 = {}; + const n13 = {}; switch (e7.type) { case "ELEMENT": { let a7 = {}; @@ -70328,21 +71468,21 @@ var require_simpleXmlToJson_min = __commonJS({ const t13 = r6(e7.value.children); a7 = Object.assign(a7, t13); } - n7[e7.value.type] = a7; + n13[e7.value.type] = a7; break; } case "ATTRIBUTE": { const t13 = e7.value; - n7[t13.name] = t13.value; + n13[t13.name] = t13.value; break; } case "CONTENT": return { content: e7.value }; } - return n7; + return n13; }; - var r6 = (e7) => e7 && Array.isArray(e7) && 0 !== e7.length ? n6(e7) ? { content: e7[0].value } : { children: e7.map(t12) } : null; - var n6 = (e7) => e7 && Array.isArray(e7) && 1 === e7.length && "CONTENT" === e7[0].type; + var r6 = (e7) => e7 && Array.isArray(e7) && 0 !== e7.length ? n12(e7) ? { content: e7[0].value } : { children: e7.map(t12) } : null; + var n12 = (e7) => e7 && Array.isArray(e7) && 1 === e7.length && "CONTENT" === e7[0].type; var s6 = (e7) => { if (e7 && Array.isArray(e7)) { return e7.map(t12).reduce(((e8, t13) => Object.assign(e8, t13)), {}); @@ -70355,7 +71495,7 @@ var require_simpleXmlToJson_min = __commonJS({ var l6 = c7("EOF"); var E3 = (e7) => " " === e7 || "\n" === e7 || "\r" === e7 || " " === e7; var o6 = (e7) => e7.replace(/'/g, "'"); - var T2 = { createLexer: function(e7) { + var T3 = { createLexer: function(e7) { let t13 = null, r7 = ((e8) => { let t14 = 0; for (; t14 < e8.length && E3(e8[t14]); ) t14++; @@ -70370,8 +71510,8 @@ var require_simpleXmlToJson_min = __commonJS({ } return t15; })(e8, t14); - })(e7), n7 = []; - const s7 = () => e7[r7], a7 = () => t13 !== l6 && r7 < e7.length, u7 = (e8) => '"' === e8 || "'" === e8, T3 = () => { + })(e7), n13 = []; + const s7 = () => e7[r7], a7 = () => t13 !== l6 && r7 < e7.length, u7 = (e8) => '"' === e8 || "'" === e8, T4 = () => { for (; a7() && E3(e7[r7]); ) r7++; }, i7 = (t14) => { if (a7()) { @@ -70390,27 +71530,27 @@ var require_simpleXmlToJson_min = __commonJS({ } return p7(!!t14); }, p7 = (t14) => { - const n8 = t14 ? /[^>=<]/u : /[a-zA-Z0-9_:-]/; + const n14 = t14 ? /[^>=<]/u : /[a-zA-Z0-9_:-]/; let s8 = r7; - for (; a7() && e7[r7].match(n8); ) r7++; + for (; a7() && e7[r7].match(n14); ) r7++; return o6(e7.substring(s8, r7)); - }, N3 = () => { + }, N4 = () => { const E4 = r7; - T3(); + T4(); const f7 = r7 - E4; if (a7()) if (t13 && "OPEN_BRACKET" === t13.type) { - T3(); + T4(); const e8 = i7(false); - t13 = c7("ELEMENT_TYPE", e8), n7.push(e8); + t13 = c7("ELEMENT_TYPE", e8), n13.push(e8); } else if (t13 && "ASSIGN" === t13.type) { a7() && u7(s7()) && r7++; - const n8 = e7[r7 - 1]; + const n14 = e7[r7 - 1]; let l7 = r7; - for (; a7() && s7() !== n8; ) r7++; + for (; a7() && s7() !== n14; ) r7++; const E5 = o6(e7.substring(l7, r7)); r7++, t13 = c7("ATTRIB_VALUE", E5); } else { - T3(); + T4(); let u8 = i7(true); switch (u8) { case "=": @@ -70419,18 +71559,18 @@ var require_simpleXmlToJson_min = __commonJS({ case "" !== e7[r7]; ) r7++; - t13 = c7("CLOSE_ELEMENT", e7.substring(s8, r7)), r7++, n7.pop(); + t13 = c7("CLOSE_ELEMENT", e7.substring(s8, r7)), r7++, n13.pop(); break; } case "/>": { - const e8 = n7.pop(); + const e8 = n13.pop(); t13 = c7("CLOSE_ELEMENT", e8); break; } case " | 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 () {\n super()\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 super()\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 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 super()\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 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 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 return true\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')\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 constructor (extensions) {\n this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')\n this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')\n }\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\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 this.#inflate = createInflateRaw({ windowBits })\n this.#inflate[kBuffer] = []\n this.#inflate[kLength] = 0\n\n this.#inflate.on('data', (data) => {\n this.#inflate[kBuffer].push(data)\n this.#inflate[kLength] += data.length\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 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')\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 #byteOffset = 0\n #loop = false\n\n #state = parserStates.INFO\n\n #info = {}\n #fragments = []\n\n /** @type {Map} */\n #extensions\n\n constructor (ws, extensions) {\n super()\n\n this.ws = ws\n this.#extensions = extensions == null ? new Map() : extensions\n\n if (this.#extensions.has('permessage-deflate')) {\n this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions))\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 /**\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 } 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 } 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\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 > 2 ** 31 - 1) {\n failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')\n return\n }\n\n const lower = buffer.readUInt32BE(4)\n\n this.#info.payloadLength = (upper << 8) + lower\n this.#state = parserStates.READ_DATA\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.#fragments.push(body)\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 const fullMessage = Buffer.concat(this.#fragments)\n websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage)\n this.#fragments.length = 0\n }\n\n this.#state = parserStates.INFO\n } else {\n this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {\n if (error) {\n closeWebSocketConnection(this.ws, 1007, error.message, error.message.length)\n return\n }\n\n this.#fragments.push(data)\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, Buffer.concat(this.#fragments))\n\n this.#loop = true\n this.#state = parserStates.INFO\n this.#fragments.length = 0\n this.run(callback)\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 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 parser = new ByteParser(this, parsedExtensions)\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","export const getHttpHandlerExtensionConfiguration = (runtimeConfig) => {\n return {\n setHttpHandler(handler) {\n runtimeConfig.httpHandler = handler;\n },\n httpHandler() {\n return runtimeConfig.httpHandler;\n },\n updateHttpClientConfig(key, value) {\n runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);\n },\n httpHandlerConfigs() {\n return runtimeConfig.httpHandler.httpHandlerConfigs();\n },\n };\n};\nexport const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {\n return {\n httpHandler: httpHandlerExtensionConfiguration.httpHandler(),\n };\n};\n","export * from \"./httpExtensionConfiguration\";\n","export {};\n","export var HttpAuthLocation;\n(function (HttpAuthLocation) {\n HttpAuthLocation[\"HEADER\"] = \"header\";\n HttpAuthLocation[\"QUERY\"] = \"query\";\n})(HttpAuthLocation || (HttpAuthLocation = {}));\n","export var HttpApiKeyAuthLocation;\n(function (HttpApiKeyAuthLocation) {\n HttpApiKeyAuthLocation[\"HEADER\"] = \"header\";\n HttpApiKeyAuthLocation[\"QUERY\"] = \"query\";\n})(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./auth\";\nexport * from \"./HttpApiKeyAuth\";\nexport * from \"./HttpAuthScheme\";\nexport * from \"./HttpAuthSchemeProvider\";\nexport * from \"./HttpSigner\";\nexport * from \"./IdentityProviderConfig\";\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./config\";\nexport * from \"./manager\";\nexport * from \"./pool\";\n","export {};\n","export {};\n","export var EndpointURLScheme;\n(function (EndpointURLScheme) {\n EndpointURLScheme[\"HTTP\"] = \"http\";\n EndpointURLScheme[\"HTTPS\"] = \"https\";\n})(EndpointURLScheme || (EndpointURLScheme = {}));\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./EndpointRuleObject\";\nexport * from \"./ErrorRuleObject\";\nexport * from \"./RuleSetObject\";\nexport * from \"./shared\";\nexport * from \"./TreeRuleObject\";\n","export {};\n","export var AlgorithmId;\n(function (AlgorithmId) {\n AlgorithmId[\"MD5\"] = \"md5\";\n AlgorithmId[\"CRC32\"] = \"crc32\";\n AlgorithmId[\"CRC32C\"] = \"crc32c\";\n AlgorithmId[\"SHA1\"] = \"sha1\";\n AlgorithmId[\"SHA256\"] = \"sha256\";\n})(AlgorithmId || (AlgorithmId = {}));\nexport const getChecksumConfiguration = (runtimeConfig) => {\n const checksumAlgorithms = [];\n if (runtimeConfig.sha256 !== undefined) {\n checksumAlgorithms.push({\n algorithmId: () => AlgorithmId.SHA256,\n checksumConstructor: () => runtimeConfig.sha256,\n });\n }\n if (runtimeConfig.md5 != undefined) {\n checksumAlgorithms.push({\n algorithmId: () => AlgorithmId.MD5,\n checksumConstructor: () => runtimeConfig.md5,\n });\n }\n return {\n addChecksumAlgorithm(algo) {\n checksumAlgorithms.push(algo);\n },\n checksumAlgorithms() {\n return checksumAlgorithms;\n },\n };\n};\nexport const resolveChecksumRuntimeConfig = (clientConfig) => {\n const runtimeConfig = {};\n clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {\n runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();\n });\n return runtimeConfig;\n};\n","import { getChecksumConfiguration, resolveChecksumRuntimeConfig } from \"./checksum\";\nexport const getDefaultClientConfiguration = (runtimeConfig) => {\n return getChecksumConfiguration(runtimeConfig);\n};\nexport const resolveDefaultRuntimeConfig = (config) => {\n return resolveChecksumRuntimeConfig(config);\n};\n","export {};\n","export * from \"./defaultClientConfiguration\";\nexport * from \"./defaultExtensionConfiguration\";\nexport { AlgorithmId } from \"./checksum\";\n","export {};\n","export var FieldPosition;\n(function (FieldPosition) {\n FieldPosition[FieldPosition[\"HEADER\"] = 0] = \"HEADER\";\n FieldPosition[FieldPosition[\"TRAILER\"] = 1] = \"TRAILER\";\n})(FieldPosition || (FieldPosition = {}));\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./apiKeyIdentity\";\nexport * from \"./awsCredentialIdentity\";\nexport * from \"./identity\";\nexport * from \"./tokenIdentity\";\n","export {};\n","export const SMITHY_CONTEXT_KEY = \"__smithy_context\";\n","export {};\n","export var IniSectionType;\n(function (IniSectionType) {\n IniSectionType[\"PROFILE\"] = \"profile\";\n IniSectionType[\"SSO_SESSION\"] = \"sso-session\";\n IniSectionType[\"SERVICES\"] = \"services\";\n})(IniSectionType || (IniSectionType = {}));\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export var RequestHandlerProtocol;\n(function (RequestHandlerProtocol) {\n RequestHandlerProtocol[\"HTTP_0_9\"] = \"http/0.9\";\n RequestHandlerProtocol[\"HTTP_1_0\"] = \"http/1.0\";\n RequestHandlerProtocol[\"TDS_8_0\"] = \"tds/8.0\";\n})(RequestHandlerProtocol || (RequestHandlerProtocol = {}));\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./abort\";\nexport * from \"./auth\";\nexport * from \"./blob/blob-payload-input-types\";\nexport * from \"./checksum\";\nexport * from \"./client\";\nexport * from \"./command\";\nexport * from \"./connection\";\nexport * from \"./crypto\";\nexport * from \"./encode\";\nexport * from \"./endpoint\";\nexport * from \"./endpoints\";\nexport * from \"./eventStream\";\nexport * from \"./extensions\";\nexport * from \"./feature-ids\";\nexport * from \"./http\";\nexport * from \"./http/httpHandlerInitialization\";\nexport * from \"./identity\";\nexport * from \"./logger\";\nexport * from \"./middleware\";\nexport * from \"./pagination\";\nexport * from \"./profile\";\nexport * from \"./response\";\nexport * from \"./retry\";\nexport * from \"./schema/schema\";\nexport * from \"./schema/traits\";\nexport * from \"./schema/schema-deprecated\";\nexport * from \"./schema/sentinels\";\nexport * from \"./schema/static-schemas\";\nexport * from \"./serde\";\nexport * from \"./shapes\";\nexport * from \"./signature\";\nexport * from \"./stream\";\nexport * from \"./streaming-payload/streaming-blob-common-types\";\nexport * from \"./streaming-payload/streaming-blob-payload-input-types\";\nexport * from \"./streaming-payload/streaming-blob-payload-output-types\";\nexport * from \"./transfer\";\nexport * from \"./transform/client-payload-blob-type-narrow\";\nexport * from \"./transform/mutable\";\nexport * from \"./transform/no-undefined\";\nexport * from \"./transform/type-transform\";\nexport * from \"./uri\";\nexport * from \"./util\";\nexport * from \"./waiter\";\n","import { FieldPosition } from \"@smithy/types\";\nexport class Field {\n name;\n kind;\n values;\n constructor({ name, kind = FieldPosition.HEADER, values = [] }) {\n this.name = name;\n this.kind = kind;\n this.values = values;\n }\n add(value) {\n this.values.push(value);\n }\n set(values) {\n this.values = values;\n }\n remove(value) {\n this.values = this.values.filter((v) => v !== value);\n }\n toString() {\n return this.values.map((v) => (v.includes(\",\") || v.includes(\" \") ? `\"${v}\"` : v)).join(\", \");\n }\n get() {\n return this.values;\n }\n}\n","export class Fields {\n entries = {};\n encoding;\n constructor({ fields = [], encoding = \"utf-8\" }) {\n fields.forEach(this.setField.bind(this));\n this.encoding = encoding;\n }\n setField(field) {\n this.entries[field.name.toLowerCase()] = field;\n }\n getField(name) {\n return this.entries[name.toLowerCase()];\n }\n removeField(name) {\n delete this.entries[name.toLowerCase()];\n }\n getByType(kind) {\n return Object.values(this.entries).filter((field) => field.kind === kind);\n }\n}\n","export {};\n","export class HttpRequest {\n method;\n protocol;\n hostname;\n port;\n path;\n query;\n headers;\n username;\n password;\n fragment;\n body;\n constructor(options) {\n this.method = options.method || \"GET\";\n this.hostname = options.hostname || \"localhost\";\n this.port = options.port;\n this.query = options.query || {};\n this.headers = options.headers || {};\n this.body = options.body;\n this.protocol = options.protocol\n ? options.protocol.slice(-1) !== \":\"\n ? `${options.protocol}:`\n : options.protocol\n : \"https:\";\n this.path = options.path ? (options.path.charAt(0) !== \"/\" ? `/${options.path}` : options.path) : \"/\";\n this.username = options.username;\n this.password = options.password;\n this.fragment = options.fragment;\n }\n static clone(request) {\n const cloned = new HttpRequest({\n ...request,\n headers: { ...request.headers },\n });\n if (cloned.query) {\n cloned.query = cloneQuery(cloned.query);\n }\n return cloned;\n }\n static isInstance(request) {\n if (!request) {\n return false;\n }\n const req = request;\n return (\"method\" in req &&\n \"protocol\" in req &&\n \"hostname\" in req &&\n \"path\" in req &&\n typeof req[\"query\"] === \"object\" &&\n typeof req[\"headers\"] === \"object\");\n }\n clone() {\n return HttpRequest.clone(this);\n }\n}\nfunction cloneQuery(query) {\n return Object.keys(query).reduce((carry, paramName) => {\n const param = query[paramName];\n return {\n ...carry,\n [paramName]: Array.isArray(param) ? [...param] : param,\n };\n }, {});\n}\n","export class HttpResponse {\n statusCode;\n reason;\n headers;\n body;\n constructor(options) {\n this.statusCode = options.statusCode;\n this.reason = options.reason;\n this.headers = options.headers || {};\n this.body = options.body;\n }\n static isInstance(response) {\n if (!response)\n return false;\n const resp = response;\n return typeof resp.statusCode === \"number\" && typeof resp.headers === \"object\";\n }\n}\n","export function isValidHostname(hostname) {\n const hostPattern = /^[a-z0-9][a-z0-9\\.\\-]*[a-z0-9]$/;\n return hostPattern.test(hostname);\n}\n","export {};\n","export * from \"./extensions\";\nexport * from \"./Field\";\nexport * from \"./Fields\";\nexport * from \"./httpHandler\";\nexport * from \"./httpRequest\";\nexport * from \"./httpResponse\";\nexport * from \"./isValidHostname\";\nexport * from \"./types\";\n","export const state = {\n warningEmitted: false,\n};\nexport const emitWarningIfUnsupportedVersion = (version) => {\n if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf(\".\"))) < 20) {\n state.warningEmitted = true;\n process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will\nno longer support Node.js ${version} in January 2026.\n\nTo continue receiving updates to AWS services, bug fixes, and security\nupdates please upgrade to a supported Node.js LTS version.\n\nMore information can be found at: https://a.co/c895JFp`);\n }\n};\n","export function setCredentialFeature(credentials, feature, value) {\n if (!credentials.$source) {\n credentials.$source = {};\n }\n credentials.$source[feature] = value;\n return credentials;\n}\n","export function setFeature(context, feature, value) {\n if (!context.__aws_sdk_context) {\n context.__aws_sdk_context = {\n features: {},\n };\n }\n else if (!context.__aws_sdk_context.features) {\n context.__aws_sdk_context.features = {};\n }\n context.__aws_sdk_context.features[feature] = value;\n}\n","export function setTokenFeature(token, feature, value) {\n if (!token.$source) {\n token.$source = {};\n }\n token.$source[feature] = value;\n return token;\n}\n","export * from \"./emitWarningIfUnsupportedVersion\";\nexport * from \"./setCredentialFeature\";\nexport * from \"./setFeature\";\nexport * from \"./setTokenFeature\";\n","import { HttpResponse } from \"@smithy/protocol-http\";\nexport const getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined;\n","export const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);\n","import { getSkewCorrectedDate } from \"./getSkewCorrectedDate\";\nexport const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000;\n","import { isClockSkewed } from \"./isClockSkewed\";\nexport const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {\n const clockTimeInMs = Date.parse(clockTime);\n if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {\n return clockTimeInMs - Date.now();\n }\n return currentSystemClockOffset;\n};\n","export * from \"./getDateHeader\";\nexport * from \"./getSkewCorrectedDate\";\nexport * from \"./getUpdatedSystemClockOffset\";\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { getDateHeader, getSkewCorrectedDate, getUpdatedSystemClockOffset } from \"../utils\";\nconst throwSigningPropertyError = (name, property) => {\n if (!property) {\n throw new Error(`Property \\`${name}\\` is not resolved for AWS SDK SigV4Auth`);\n }\n return property;\n};\nexport const validateSigningProperties = async (signingProperties) => {\n const context = throwSigningPropertyError(\"context\", signingProperties.context);\n const config = throwSigningPropertyError(\"config\", signingProperties.config);\n const authScheme = context.endpointV2?.properties?.authSchemes?.[0];\n const signerFunction = throwSigningPropertyError(\"signer\", config.signer);\n const signer = await signerFunction(authScheme);\n const signingRegion = signingProperties?.signingRegion;\n const signingRegionSet = signingProperties?.signingRegionSet;\n const signingName = signingProperties?.signingName;\n return {\n config,\n signer,\n signingRegion,\n signingRegionSet,\n signingName,\n };\n};\nexport class AwsSdkSigV4Signer {\n async sign(httpRequest, identity, signingProperties) {\n if (!HttpRequest.isInstance(httpRequest)) {\n throw new Error(\"The request is not an instance of `HttpRequest` and cannot be signed\");\n }\n const validatedProps = await validateSigningProperties(signingProperties);\n const { config, signer } = validatedProps;\n let { signingRegion, signingName } = validatedProps;\n const handlerExecutionContext = signingProperties.context;\n if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {\n const [first, second] = handlerExecutionContext.authSchemes;\n if (first?.name === \"sigv4a\" && second?.name === \"sigv4\") {\n signingRegion = second?.signingRegion ?? signingRegion;\n signingName = second?.signingName ?? signingName;\n }\n }\n const signedRequest = await signer.sign(httpRequest, {\n signingDate: getSkewCorrectedDate(config.systemClockOffset),\n signingRegion: signingRegion,\n signingService: signingName,\n });\n return signedRequest;\n }\n errorHandler(signingProperties) {\n return (error) => {\n const serverTime = error.ServerTime ?? getDateHeader(error.$response);\n if (serverTime) {\n const config = throwSigningPropertyError(\"config\", signingProperties.config);\n const initialSystemClockOffset = config.systemClockOffset;\n config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);\n const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;\n if (clockSkewCorrected && error.$metadata) {\n error.$metadata.clockSkewCorrected = true;\n }\n }\n throw error;\n };\n }\n successHandler(httpResponse, signingProperties) {\n const dateHeader = getDateHeader(httpResponse);\n if (dateHeader) {\n const config = throwSigningPropertyError(\"config\", signingProperties.config);\n config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);\n }\n }\n}\nexport const AWSSDKSigV4Signer = AwsSdkSigV4Signer;\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { getSkewCorrectedDate } from \"../utils\";\nimport { AwsSdkSigV4Signer, validateSigningProperties } from \"./AwsSdkSigV4Signer\";\nexport class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer {\n async sign(httpRequest, identity, signingProperties) {\n if (!HttpRequest.isInstance(httpRequest)) {\n throw new Error(\"The request is not an instance of `HttpRequest` and cannot be signed\");\n }\n const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);\n const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.();\n const multiRegionOverride = (configResolvedSigningRegionSet ??\n signingRegionSet ?? [signingRegion]).join(\",\");\n const signedRequest = await signer.sign(httpRequest, {\n signingDate: getSkewCorrectedDate(config.systemClockOffset),\n signingRegion: multiRegionOverride,\n signingService: signingName,\n });\n return signedRequest;\n }\n}\n","export const getArrayForCommaSeparatedString = (str) => typeof str === \"string\" && str.length > 0 ? str.split(\",\").map((item) => item.trim()) : [];\n","export const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\\s-]/g, \"_\").toUpperCase()}`;\n","import { getArrayForCommaSeparatedString } from \"../utils/getArrayForCommaSeparatedString\";\nimport { getBearerTokenEnvKey } from \"../utils/getBearerTokenEnvKey\";\nconst NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = \"AWS_AUTH_SCHEME_PREFERENCE\";\nconst NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = \"auth_scheme_preference\";\nexport const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {\n environmentVariableSelector: (env, options) => {\n if (options?.signingName) {\n const bearerTokenKey = getBearerTokenEnvKey(options.signingName);\n if (bearerTokenKey in env)\n return [\"httpBearerAuth\"];\n }\n if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env))\n return undefined;\n return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);\n },\n configFileSelector: (profile) => {\n if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))\n return undefined;\n return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);\n },\n default: [],\n};\n","import { SMITHY_CONTEXT_KEY } from \"@smithy/types\";\nexport const getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {});\n","import { SMITHY_CONTEXT_KEY } from \"@smithy/types\";\nexport const getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {});\n","export const normalizeProvider = (input) => {\n if (typeof input === \"function\")\n return input;\n const promisified = Promise.resolve(input);\n return () => promisified;\n};\n","export * from \"./getSmithyContext\";\nexport * from \"./normalizeProvider\";\n","export const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {\n if (!authSchemePreference || authSchemePreference.length === 0) {\n return candidateAuthOptions;\n }\n const preferredAuthOptions = [];\n for (const preferredSchemeName of authSchemePreference) {\n for (const candidateAuthOption of candidateAuthOptions) {\n const candidateAuthSchemeName = candidateAuthOption.schemeId.split(\"#\")[1];\n if (candidateAuthSchemeName === preferredSchemeName) {\n preferredAuthOptions.push(candidateAuthOption);\n }\n }\n }\n for (const candidateAuthOption of candidateAuthOptions) {\n if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {\n preferredAuthOptions.push(candidateAuthOption);\n }\n }\n return preferredAuthOptions;\n};\n","import { getSmithyContext } from \"@smithy/util-middleware\";\nimport { resolveAuthOptions } from \"./resolveAuthOptions\";\nfunction convertHttpAuthSchemesToMap(httpAuthSchemes) {\n const map = new Map();\n for (const scheme of httpAuthSchemes) {\n map.set(scheme.schemeId, scheme);\n }\n return map;\n}\nexport const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {\n const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));\n const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];\n const resolvedOptions = resolveAuthOptions(options, authSchemePreference);\n const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);\n const smithyContext = getSmithyContext(context);\n const failureReasons = [];\n for (const option of resolvedOptions) {\n const scheme = authSchemes.get(option.schemeId);\n if (!scheme) {\n failureReasons.push(`HttpAuthScheme \\`${option.schemeId}\\` was not enabled for this service.`);\n continue;\n }\n const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));\n if (!identityProvider) {\n failureReasons.push(`HttpAuthScheme \\`${option.schemeId}\\` did not have an IdentityProvider configured.`);\n continue;\n }\n const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {};\n option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);\n option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);\n smithyContext.selectedHttpAuthScheme = {\n httpAuthOption: option,\n identity: await identityProvider(option.identityProperties),\n signer: scheme.signer,\n };\n break;\n }\n if (!smithyContext.selectedHttpAuthScheme) {\n throw new Error(failureReasons.join(\"\\n\"));\n }\n return next(args);\n};\n","import { httpAuthSchemeMiddleware } from \"./httpAuthSchemeMiddleware\";\nexport const httpAuthSchemeEndpointRuleSetMiddlewareOptions = {\n step: \"serialize\",\n tags: [\"HTTP_AUTH_SCHEME\"],\n name: \"httpAuthSchemeMiddleware\",\n override: true,\n relation: \"before\",\n toMiddleware: \"endpointV2Middleware\",\n};\nexport const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {\n httpAuthSchemeParametersProvider,\n identityProviderConfigProvider,\n }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);\n },\n});\n","import { HttpResponse } from \"@smithy/protocol-http\";\nexport const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => {\n const { response } = await next(args);\n try {\n const parsed = await deserializer(response, options);\n return {\n response,\n output: parsed,\n };\n }\n catch (error) {\n Object.defineProperty(error, \"$response\", {\n value: response,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n if (!(\"$metadata\" in error)) {\n const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;\n try {\n error.message += \"\\n \" + hint;\n }\n catch (e) {\n if (!context.logger || context.logger?.constructor?.name === \"NoOpLogger\") {\n console.warn(hint);\n }\n else {\n context.logger?.warn?.(hint);\n }\n }\n if (typeof error.$responseBodyText !== \"undefined\") {\n if (error.$response) {\n error.$response.body = error.$responseBodyText;\n }\n }\n try {\n if (HttpResponse.isInstance(response)) {\n const { headers = {} } = response;\n const headerEntries = Object.entries(headers);\n error.$metadata = {\n httpStatusCode: response.statusCode,\n requestId: findHeader(/^x-[\\w-]+-request-?id$/, headerEntries),\n extendedRequestId: findHeader(/^x-[\\w-]+-id-2$/, headerEntries),\n cfId: findHeader(/^x-[\\w-]+-cf-id$/, headerEntries),\n };\n }\n }\n catch (e) {\n }\n }\n throw error;\n }\n};\nconst findHeader = (pattern, headers) => {\n return (headers.find(([k]) => {\n return k.match(pattern);\n }) || [void 0, void 1])[1];\n};\n","export const serializerMiddleware = (options, serializer) => (next, context) => async (args) => {\n const endpointConfig = options;\n const endpoint = context.endpointV2?.url && endpointConfig.urlParser\n ? async () => endpointConfig.urlParser(context.endpointV2.url)\n : endpointConfig.endpoint;\n if (!endpoint) {\n throw new Error(\"No valid endpoint provider available.\");\n }\n const request = await serializer(args.input, { ...options, endpoint });\n return next({\n ...args,\n request,\n });\n};\n","import { deserializerMiddleware } from \"./deserializerMiddleware\";\nimport { serializerMiddleware } from \"./serializerMiddleware\";\nexport const deserializerMiddlewareOption = {\n name: \"deserializerMiddleware\",\n step: \"deserialize\",\n tags: [\"DESERIALIZER\"],\n override: true,\n};\nexport const serializerMiddlewareOption = {\n name: \"serializerMiddleware\",\n step: \"serialize\",\n tags: [\"SERIALIZER\"],\n override: true,\n};\nexport function getSerdePlugin(config, serializer, deserializer) {\n return {\n applyToStack: (commandStack) => {\n commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);\n commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);\n },\n };\n}\n","export * from \"./deserializerMiddleware\";\nexport * from \"./serdePlugin\";\nexport * from \"./serializerMiddleware\";\n","import { serializerMiddlewareOption } from \"@smithy/middleware-serde\";\nimport { httpAuthSchemeMiddleware } from \"./httpAuthSchemeMiddleware\";\nexport const httpAuthSchemeMiddlewareOptions = {\n step: \"serialize\",\n tags: [\"HTTP_AUTH_SCHEME\"],\n name: \"httpAuthSchemeMiddleware\",\n override: true,\n relation: \"before\",\n toMiddleware: serializerMiddlewareOption.name,\n};\nexport const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {\n httpAuthSchemeParametersProvider,\n identityProviderConfigProvider,\n }), httpAuthSchemeMiddlewareOptions);\n },\n});\n","export * from \"./httpAuthSchemeMiddleware\";\nexport * from \"./getHttpAuthSchemeEndpointRuleSetPlugin\";\nexport * from \"./getHttpAuthSchemePlugin\";\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { getSmithyContext } from \"@smithy/util-middleware\";\nconst defaultErrorHandler = (signingProperties) => (error) => {\n throw error;\n};\nconst defaultSuccessHandler = (httpResponse, signingProperties) => { };\nexport const httpSigningMiddleware = (config) => (next, context) => async (args) => {\n if (!HttpRequest.isInstance(args.request)) {\n return next(args);\n }\n const smithyContext = getSmithyContext(context);\n const scheme = smithyContext.selectedHttpAuthScheme;\n if (!scheme) {\n throw new Error(`No HttpAuthScheme was selected: unable to sign request`);\n }\n const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme;\n const output = await next({\n ...args,\n request: await signer.sign(args.request, identity, signingProperties),\n }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));\n (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);\n return output;\n};\n","import { httpSigningMiddleware } from \"./httpSigningMiddleware\";\nexport const httpSigningMiddlewareOptions = {\n step: \"finalizeRequest\",\n tags: [\"HTTP_SIGNING\"],\n name: \"httpSigningMiddleware\",\n aliases: [\"apiKeyMiddleware\", \"tokenMiddleware\", \"awsAuthMiddleware\"],\n override: true,\n relation: \"after\",\n toMiddleware: \"retryMiddleware\",\n};\nexport const getHttpSigningPlugin = (config) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);\n },\n});\n","export * from \"./httpSigningMiddleware\";\nexport * from \"./getHttpSigningMiddleware\";\n","export const normalizeProvider = (input) => {\n if (typeof input === \"function\")\n return input;\n const promisified = Promise.resolve(input);\n return () => promisified;\n};\n","const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => {\n let command = new CommandCtor(input);\n command = withCommand(command) ?? command;\n return await client.send(command, ...args);\n};\nexport function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {\n return async function* paginateOperation(config, input, ...additionalArguments) {\n const _input = input;\n let token = config.startingToken ?? _input[inputTokenName];\n let hasNext = true;\n let page;\n while (hasNext) {\n _input[inputTokenName] = token;\n if (pageSizeTokenName) {\n _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize;\n }\n if (config.client instanceof ClientCtor) {\n page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments);\n }\n else {\n throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);\n }\n yield page;\n const prevToken = token;\n token = get(page, outputTokenName);\n hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));\n }\n return undefined;\n };\n}\nconst get = (fromObject, path) => {\n let cursor = fromObject;\n const pathComponents = path.split(\".\");\n for (const step of pathComponents) {\n if (!cursor || typeof cursor !== \"object\") {\n return undefined;\n }\n cursor = cursor[step];\n }\n return cursor;\n};\n","export const isArrayBuffer = (arg) => (typeof ArrayBuffer === \"function\" && arg instanceof ArrayBuffer) ||\n Object.prototype.toString.call(arg) === \"[object ArrayBuffer]\";\n","import { isArrayBuffer } from \"@smithy/is-array-buffer\";\nimport { Buffer } from \"buffer\";\nexport const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {\n if (!isArrayBuffer(input)) {\n throw new TypeError(`The \"input\" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);\n }\n return Buffer.from(input, offset, length);\n};\nexport const fromString = (input, encoding) => {\n if (typeof input !== \"string\") {\n throw new TypeError(`The \"input\" argument must be of type string. Received type ${typeof input} (${input})`);\n }\n return encoding ? Buffer.from(input, encoding) : Buffer.from(input);\n};\n","import { fromString } from \"@smithy/util-buffer-from\";\nconst BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;\nexport const fromBase64 = (input) => {\n if ((input.length * 3) % 4 !== 0) {\n throw new TypeError(`Incorrect padding on base64 string.`);\n }\n if (!BASE64_REGEX.exec(input)) {\n throw new TypeError(`Invalid base64 string.`);\n }\n const buffer = fromString(input, \"base64\");\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n};\n","import { fromString } from \"@smithy/util-buffer-from\";\nexport const fromUtf8 = (input) => {\n const buf = fromString(input, \"utf8\");\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n};\n","import { fromUtf8 } from \"./fromUtf8\";\nexport const toUint8Array = (data) => {\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n};\n","import { fromArrayBuffer } from \"@smithy/util-buffer-from\";\nexport const toUtf8 = (input) => {\n if (typeof input === \"string\") {\n return input;\n }\n if (typeof input !== \"object\" || typeof input.byteOffset !== \"number\" || typeof input.byteLength !== \"number\") {\n throw new Error(\"@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.\");\n }\n return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString(\"utf8\");\n};\n","export * from \"./fromUtf8\";\nexport * from \"./toUint8Array\";\nexport * from \"./toUtf8\";\n","import { fromArrayBuffer } from \"@smithy/util-buffer-from\";\nimport { fromUtf8 } from \"@smithy/util-utf8\";\nexport const toBase64 = (_input) => {\n let input;\n if (typeof _input === \"string\") {\n input = fromUtf8(_input);\n }\n else {\n input = _input;\n }\n if (typeof input !== \"object\" || typeof input.byteOffset !== \"number\" || typeof input.byteLength !== \"number\") {\n throw new Error(\"@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.\");\n }\n return fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString(\"base64\");\n};\n","export * from \"./fromBase64\";\nexport * from \"./toBase64\";\n","import { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nexport class Uint8ArrayBlobAdapter extends Uint8Array {\n static fromString(source, encoding = \"utf-8\") {\n if (typeof source === \"string\") {\n if (encoding === \"base64\") {\n return Uint8ArrayBlobAdapter.mutate(fromBase64(source));\n }\n return Uint8ArrayBlobAdapter.mutate(fromUtf8(source));\n }\n throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);\n }\n static mutate(source) {\n Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype);\n return source;\n }\n transformToString(encoding = \"utf-8\") {\n if (encoding === \"base64\") {\n return toBase64(this);\n }\n return toUtf8(this);\n }\n}\n","import { toBase64 } from \"@smithy/util-base64\";\nimport { Duplex } from \"stream\";\nexport class ChecksumStream extends Duplex {\n expectedChecksum;\n checksumSourceLocation;\n checksum;\n source;\n base64Encoder;\n constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) {\n super();\n if (typeof source.pipe === \"function\") {\n this.source = source;\n }\n else {\n throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);\n }\n this.base64Encoder = base64Encoder ?? toBase64;\n this.expectedChecksum = expectedChecksum;\n this.checksum = checksum;\n this.checksumSourceLocation = checksumSourceLocation;\n this.source.pipe(this);\n }\n _read(size) { }\n _write(chunk, encoding, callback) {\n try {\n this.checksum.update(chunk);\n this.push(chunk);\n }\n catch (e) {\n return callback(e);\n }\n return callback();\n }\n async _final(callback) {\n try {\n const digest = await this.checksum.digest();\n const received = this.base64Encoder(digest);\n if (this.expectedChecksum !== received) {\n return callback(new Error(`Checksum mismatch: expected \"${this.expectedChecksum}\" but received \"${received}\"` +\n ` in response header \"${this.checksumSourceLocation}\".`));\n }\n }\n catch (e) {\n return callback(e);\n }\n this.push(null);\n return callback();\n }\n}\n","export const isReadableStream = (stream) => typeof ReadableStream === \"function\" &&\n (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream);\nexport const isBlob = (blob) => {\n return typeof Blob === \"function\" && (blob?.constructor?.name === Blob.name || blob instanceof Blob);\n};\n","const ReadableStreamRef = typeof ReadableStream === \"function\" ? ReadableStream : function () { };\nexport class ChecksumStream extends ReadableStreamRef {\n}\n","import { toBase64 } from \"@smithy/util-base64\";\nimport { isReadableStream } from \"../stream-type-check\";\nimport { ChecksumStream } from \"./ChecksumStream.browser\";\nexport const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => {\n if (!isReadableStream(source)) {\n throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`);\n }\n const encoder = base64Encoder ?? toBase64;\n if (typeof TransformStream !== \"function\") {\n throw new Error(\"@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.\");\n }\n const transform = new TransformStream({\n start() { },\n async transform(chunk, controller) {\n checksum.update(chunk);\n controller.enqueue(chunk);\n },\n async flush(controller) {\n const digest = await checksum.digest();\n const received = encoder(digest);\n if (expectedChecksum !== received) {\n const error = new Error(`Checksum mismatch: expected \"${expectedChecksum}\" but received \"${received}\"` +\n ` in response header \"${checksumSourceLocation}\".`);\n controller.error(error);\n }\n else {\n controller.terminate();\n }\n },\n });\n source.pipeThrough(transform);\n const readable = transform.readable;\n Object.setPrototypeOf(readable, ChecksumStream.prototype);\n return readable;\n};\n","import { isReadableStream } from \"../stream-type-check\";\nimport { ChecksumStream } from \"./ChecksumStream\";\nimport { createChecksumStream as createChecksumStreamWeb } from \"./createChecksumStream.browser\";\nexport function createChecksumStream(init) {\n if (typeof ReadableStream === \"function\" && isReadableStream(init.source)) {\n return createChecksumStreamWeb(init);\n }\n return new ChecksumStream(init);\n}\n","export class ByteArrayCollector {\n allocByteArray;\n byteLength = 0;\n byteArrays = [];\n constructor(allocByteArray) {\n this.allocByteArray = allocByteArray;\n }\n push(byteArray) {\n this.byteArrays.push(byteArray);\n this.byteLength += byteArray.byteLength;\n }\n flush() {\n if (this.byteArrays.length === 1) {\n const bytes = this.byteArrays[0];\n this.reset();\n return bytes;\n }\n const aggregation = this.allocByteArray(this.byteLength);\n let cursor = 0;\n for (let i = 0; i < this.byteArrays.length; ++i) {\n const bytes = this.byteArrays[i];\n aggregation.set(bytes, cursor);\n cursor += bytes.byteLength;\n }\n this.reset();\n return aggregation;\n }\n reset() {\n this.byteArrays = [];\n this.byteLength = 0;\n }\n}\n","import { ByteArrayCollector } from \"./ByteArrayCollector\";\nexport function createBufferedReadableStream(upstream, size, logger) {\n const reader = upstream.getReader();\n let streamBufferingLoggedWarning = false;\n let bytesSeen = 0;\n const buffers = [\"\", new ByteArrayCollector((size) => new Uint8Array(size))];\n let mode = -1;\n const pull = async (controller) => {\n const { value, done } = await reader.read();\n const chunk = value;\n if (done) {\n if (mode !== -1) {\n const remainder = flush(buffers, mode);\n if (sizeOf(remainder) > 0) {\n controller.enqueue(remainder);\n }\n }\n controller.close();\n }\n else {\n const chunkMode = modeOf(chunk, false);\n if (mode !== chunkMode) {\n if (mode >= 0) {\n controller.enqueue(flush(buffers, mode));\n }\n mode = chunkMode;\n }\n if (mode === -1) {\n controller.enqueue(chunk);\n return;\n }\n const chunkSize = sizeOf(chunk);\n bytesSeen += chunkSize;\n const bufferSize = sizeOf(buffers[mode]);\n if (chunkSize >= size && bufferSize === 0) {\n controller.enqueue(chunk);\n }\n else {\n const newSize = merge(buffers, mode, chunk);\n if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {\n streamBufferingLoggedWarning = true;\n logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);\n }\n if (newSize >= size) {\n controller.enqueue(flush(buffers, mode));\n }\n else {\n await pull(controller);\n }\n }\n }\n };\n return new ReadableStream({\n pull,\n });\n}\nexport const createBufferedReadable = createBufferedReadableStream;\nexport function merge(buffers, mode, chunk) {\n switch (mode) {\n case 0:\n buffers[0] += chunk;\n return sizeOf(buffers[0]);\n case 1:\n case 2:\n buffers[mode].push(chunk);\n return sizeOf(buffers[mode]);\n }\n}\nexport function flush(buffers, mode) {\n switch (mode) {\n case 0:\n const s = buffers[0];\n buffers[0] = \"\";\n return s;\n case 1:\n case 2:\n return buffers[mode].flush();\n }\n throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`);\n}\nexport function sizeOf(chunk) {\n return chunk?.byteLength ?? chunk?.length ?? 0;\n}\nexport function modeOf(chunk, allowBuffer = true) {\n if (allowBuffer && typeof Buffer !== \"undefined\" && chunk instanceof Buffer) {\n return 2;\n }\n if (chunk instanceof Uint8Array) {\n return 1;\n }\n if (typeof chunk === \"string\") {\n return 0;\n }\n return -1;\n}\n","import { Readable } from \"node:stream\";\nimport { ByteArrayCollector } from \"./ByteArrayCollector\";\nimport { createBufferedReadableStream, flush, merge, modeOf, sizeOf } from \"./createBufferedReadableStream\";\nimport { isReadableStream } from \"./stream-type-check\";\nexport function createBufferedReadable(upstream, size, logger) {\n if (isReadableStream(upstream)) {\n return createBufferedReadableStream(upstream, size, logger);\n }\n const downstream = new Readable({ read() { } });\n let streamBufferingLoggedWarning = false;\n let bytesSeen = 0;\n const buffers = [\n \"\",\n new ByteArrayCollector((size) => new Uint8Array(size)),\n new ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))),\n ];\n let mode = -1;\n upstream.on(\"data\", (chunk) => {\n const chunkMode = modeOf(chunk, true);\n if (mode !== chunkMode) {\n if (mode >= 0) {\n downstream.push(flush(buffers, mode));\n }\n mode = chunkMode;\n }\n if (mode === -1) {\n downstream.push(chunk);\n return;\n }\n const chunkSize = sizeOf(chunk);\n bytesSeen += chunkSize;\n const bufferSize = sizeOf(buffers[mode]);\n if (chunkSize >= size && bufferSize === 0) {\n downstream.push(chunk);\n }\n else {\n const newSize = merge(buffers, mode, chunk);\n if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {\n streamBufferingLoggedWarning = true;\n logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);\n }\n if (newSize >= size) {\n downstream.push(flush(buffers, mode));\n }\n }\n });\n upstream.on(\"end\", () => {\n if (mode !== -1) {\n const remainder = flush(buffers, mode);\n if (sizeOf(remainder) > 0) {\n downstream.push(remainder);\n }\n }\n downstream.push(null);\n });\n return downstream;\n}\n","export const getAwsChunkedEncodingStream = (readableStream, options) => {\n const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;\n const checksumRequired = base64Encoder !== undefined &&\n bodyLengthChecker !== undefined &&\n checksumAlgorithmFn !== undefined &&\n checksumLocationName !== undefined &&\n streamHasher !== undefined;\n const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined;\n const reader = readableStream.getReader();\n return new ReadableStream({\n async pull(controller) {\n const { value, done } = await reader.read();\n if (done) {\n controller.enqueue(`0\\r\\n`);\n if (checksumRequired) {\n const checksum = base64Encoder(await digest);\n controller.enqueue(`${checksumLocationName}:${checksum}\\r\\n`);\n controller.enqueue(`\\r\\n`);\n }\n controller.close();\n }\n else {\n controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\\r\\n${value}\\r\\n`);\n }\n },\n });\n};\n","import { Readable } from \"node:stream\";\nimport { getAwsChunkedEncodingStream as getAwsChunkedEncodingStreamBrowser } from \"./getAwsChunkedEncodingStream.browser\";\nimport { isReadableStream } from \"./stream-type-check\";\nexport function getAwsChunkedEncodingStream(stream, options) {\n const readable = stream;\n const readableStream = stream;\n if (isReadableStream(readableStream)) {\n return getAwsChunkedEncodingStreamBrowser(readableStream, options);\n }\n const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;\n const checksumRequired = base64Encoder !== undefined &&\n checksumAlgorithmFn !== undefined &&\n checksumLocationName !== undefined &&\n streamHasher !== undefined;\n const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readable) : undefined;\n const awsChunkedEncodingStream = new Readable({\n read: () => { },\n });\n readable.on(\"data\", (data) => {\n const length = bodyLengthChecker(data) || 0;\n if (length === 0) {\n return;\n }\n awsChunkedEncodingStream.push(`${length.toString(16)}\\r\\n`);\n awsChunkedEncodingStream.push(data);\n awsChunkedEncodingStream.push(\"\\r\\n\");\n });\n readable.on(\"end\", async () => {\n awsChunkedEncodingStream.push(`0\\r\\n`);\n if (checksumRequired) {\n const checksum = base64Encoder(await digest);\n awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\\r\\n`);\n awsChunkedEncodingStream.push(`\\r\\n`);\n }\n awsChunkedEncodingStream.push(null);\n });\n return awsChunkedEncodingStream;\n}\n","export async function headStream(stream, bytes) {\n let byteLengthCounter = 0;\n const chunks = [];\n const reader = stream.getReader();\n let isDone = false;\n while (!isDone) {\n const { done, value } = await reader.read();\n if (value) {\n chunks.push(value);\n byteLengthCounter += value?.byteLength ?? 0;\n }\n if (byteLengthCounter >= bytes) {\n break;\n }\n isDone = done;\n }\n reader.releaseLock();\n const collected = new Uint8Array(Math.min(bytes, byteLengthCounter));\n let offset = 0;\n for (const chunk of chunks) {\n if (chunk.byteLength > collected.byteLength - offset) {\n collected.set(chunk.subarray(0, collected.byteLength - offset), offset);\n break;\n }\n else {\n collected.set(chunk, offset);\n }\n offset += chunk.length;\n }\n return collected;\n}\n","import { Writable } from \"stream\";\nimport { headStream as headWebStream } from \"./headStream.browser\";\nimport { isReadableStream } from \"./stream-type-check\";\nexport const headStream = (stream, bytes) => {\n if (isReadableStream(stream)) {\n return headWebStream(stream, bytes);\n }\n return new Promise((resolve, reject) => {\n const collector = new Collector();\n collector.limit = bytes;\n stream.pipe(collector);\n stream.on(\"error\", (err) => {\n collector.end();\n reject(err);\n });\n collector.on(\"error\", reject);\n collector.on(\"finish\", function () {\n const bytes = new Uint8Array(Buffer.concat(this.buffers));\n resolve(bytes);\n });\n });\n};\nclass Collector extends Writable {\n buffers = [];\n limit = Infinity;\n bytesBuffered = 0;\n _write(chunk, encoding, callback) {\n this.buffers.push(chunk);\n this.bytesBuffered += chunk.byteLength ?? 0;\n if (this.bytesBuffered >= this.limit) {\n const excess = this.bytesBuffered - this.limit;\n const tailBuffer = this.buffers[this.buffers.length - 1];\n this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess);\n this.emit(\"finish\");\n }\n callback();\n }\n}\n","export const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);\nconst hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;\n","import { escapeUri } from \"./escape-uri\";\nexport const escapeUriPath = (uri) => uri.split(\"/\").map(escapeUri).join(\"/\");\n","export * from \"./escape-uri\";\nexport * from \"./escape-uri-path\";\n","import { escapeUri } from \"@smithy/util-uri-escape\";\nexport function buildQueryString(query) {\n const parts = [];\n for (let key of Object.keys(query).sort()) {\n const value = query[key];\n key = escapeUri(key);\n if (Array.isArray(value)) {\n for (let i = 0, iLen = value.length; i < iLen; i++) {\n parts.push(`${key}=${escapeUri(value[i])}`);\n }\n }\n else {\n let qsEntry = key;\n if (value || typeof value === \"string\") {\n qsEntry += `=${escapeUri(value)}`;\n }\n parts.push(qsEntry);\n }\n }\n return parts.join(\"&\");\n}\n","export const NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"EPIPE\", \"ETIMEDOUT\"];\n","const getTransformedHeaders = (headers) => {\n const transformedHeaders = {};\n for (const name of Object.keys(headers)) {\n const headerValues = headers[name];\n transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(\",\") : headerValues;\n }\n return transformedHeaders;\n};\nexport { getTransformedHeaders };\n","export const timing = {\n setTimeout: (cb, ms) => setTimeout(cb, ms),\n clearTimeout: (timeoutId) => clearTimeout(timeoutId),\n};\n","import { timing } from \"./timing\";\nconst DEFER_EVENT_LISTENER_TIME = 1000;\nexport const setConnectionTimeout = (request, reject, timeoutInMs = 0) => {\n if (!timeoutInMs) {\n return -1;\n }\n const registerTimeout = (offset) => {\n const timeoutId = timing.setTimeout(() => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {\n name: \"TimeoutError\",\n }));\n }, timeoutInMs - offset);\n const doWithSocket = (socket) => {\n if (socket?.connecting) {\n socket.on(\"connect\", () => {\n timing.clearTimeout(timeoutId);\n });\n }\n else {\n timing.clearTimeout(timeoutId);\n }\n };\n if (request.socket) {\n doWithSocket(request.socket);\n }\n else {\n request.on(\"socket\", doWithSocket);\n }\n };\n if (timeoutInMs < 2000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n","import { timing } from \"./timing\";\nexport const setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => {\n if (timeoutInMs) {\n return timing.setTimeout(() => {\n let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? \"ERROR\" : \"WARN\"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;\n if (throwOnRequestTimeout) {\n const error = Object.assign(new Error(msg), {\n name: \"TimeoutError\",\n code: \"ETIMEDOUT\",\n });\n req.destroy(error);\n reject(error);\n }\n else {\n msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;\n logger?.warn?.(msg);\n }\n }, timeoutInMs);\n }\n return -1;\n};\n","import { timing } from \"./timing\";\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nexport const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME) => {\n if (keepAlive !== true) {\n return -1;\n }\n const registerListener = () => {\n if (request.socket) {\n request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n }\n else {\n request.on(\"socket\", (socket) => {\n socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);\n });\n }\n };\n if (deferTimeMs === 0) {\n registerListener();\n return 0;\n }\n return timing.setTimeout(registerListener, deferTimeMs);\n};\n","import { timing } from \"./timing\";\nconst DEFER_EVENT_LISTENER_TIME = 3000;\nexport const setSocketTimeout = (request, reject, timeoutInMs = 0) => {\n const registerTimeout = (offset) => {\n const timeout = timeoutInMs - offset;\n const onTimeout = () => {\n request.destroy();\n reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: \"TimeoutError\" }));\n };\n if (request.socket) {\n request.socket.setTimeout(timeout, onTimeout);\n request.on(\"close\", () => request.socket?.removeListener(\"timeout\", onTimeout));\n }\n else {\n request.setTimeout(timeout, onTimeout);\n }\n };\n if (0 < timeoutInMs && timeoutInMs < 6000) {\n registerTimeout(0);\n return 0;\n }\n return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);\n};\n","import { Readable } from \"stream\";\nimport { timing } from \"./timing\";\nconst MIN_WAIT_TIME = 6_000;\nexport async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {\n const headers = request.headers ?? {};\n const expect = headers.Expect || headers.expect;\n let timeoutId = -1;\n let sendBody = true;\n if (!externalAgent && expect === \"100-continue\") {\n sendBody = await Promise.race([\n new Promise((resolve) => {\n timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));\n }),\n new Promise((resolve) => {\n httpRequest.on(\"continue\", () => {\n timing.clearTimeout(timeoutId);\n resolve(true);\n });\n httpRequest.on(\"response\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n httpRequest.on(\"error\", () => {\n timing.clearTimeout(timeoutId);\n resolve(false);\n });\n }),\n ]);\n }\n if (sendBody) {\n writeBody(httpRequest, request.body);\n }\n}\nfunction writeBody(httpRequest, body) {\n if (body instanceof Readable) {\n body.pipe(httpRequest);\n return;\n }\n if (body) {\n if (Buffer.isBuffer(body) || typeof body === \"string\") {\n httpRequest.end(body);\n return;\n }\n const uint8 = body;\n if (typeof uint8 === \"object\" &&\n uint8.buffer &&\n typeof uint8.byteOffset === \"number\" &&\n typeof uint8.byteLength === \"number\") {\n httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));\n return;\n }\n httpRequest.end(Buffer.from(body));\n return;\n }\n httpRequest.end();\n}\n","import { HttpResponse } from \"@smithy/protocol-http\";\nimport { buildQueryString } from \"@smithy/querystring-builder\";\nimport { Agent as hAgent, request as hRequest } from \"http\";\nimport { Agent as hsAgent, request as hsRequest } from \"https\";\nimport { NODEJS_TIMEOUT_ERROR_CODES } from \"./constants\";\nimport { getTransformedHeaders } from \"./get-transformed-headers\";\nimport { setConnectionTimeout } from \"./set-connection-timeout\";\nimport { setRequestTimeout } from \"./set-request-timeout\";\nimport { setSocketKeepAlive } from \"./set-socket-keep-alive\";\nimport { setSocketTimeout } from \"./set-socket-timeout\";\nimport { timing } from \"./timing\";\nimport { writeRequestBody } from \"./write-request-body\";\nexport const DEFAULT_REQUEST_TIMEOUT = 0;\nexport class NodeHttpHandler {\n config;\n configProvider;\n socketWarningTimestamp = 0;\n externalAgent = false;\n metadata = { handlerProtocol: \"http/1.1\" };\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttpHandler(instanceOrOptions);\n }\n static checkSocketUsage(agent, socketWarningTimestamp, logger = console) {\n const { sockets, requests, maxSockets } = agent;\n if (typeof maxSockets !== \"number\" || maxSockets === Infinity) {\n return socketWarningTimestamp;\n }\n const interval = 15_000;\n if (Date.now() - interval < socketWarningTimestamp) {\n return socketWarningTimestamp;\n }\n if (sockets && requests) {\n for (const origin in sockets) {\n const socketsInUse = sockets[origin]?.length ?? 0;\n const requestsEnqueued = requests[origin]?.length ?? 0;\n if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {\n logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.\nSee https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html\nor increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`);\n return Date.now();\n }\n }\n }\n return socketWarningTimestamp;\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((_options) => {\n resolve(this.resolveDefaultConfig(_options));\n })\n .catch(reject);\n }\n else {\n resolve(this.resolveDefaultConfig(options));\n }\n });\n }\n resolveDefaultConfig(options) {\n const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, } = options || {};\n const keepAlive = true;\n const maxSockets = 50;\n return {\n connectionTimeout,\n requestTimeout,\n socketTimeout,\n socketAcquisitionWarningTimeout,\n throwOnRequestTimeout,\n httpAgent: (() => {\n if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpAgent;\n }\n return new hAgent({ keepAlive, maxSockets, ...httpAgent });\n })(),\n httpsAgent: (() => {\n if (httpsAgent instanceof hsAgent || typeof httpsAgent?.destroy === \"function\") {\n this.externalAgent = true;\n return httpsAgent;\n }\n return new hsAgent({ keepAlive, maxSockets, ...httpsAgent });\n })(),\n logger: console,\n };\n }\n destroy() {\n this.config?.httpAgent?.destroy();\n this.config?.httpsAgent?.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n return new Promise((_resolve, _reject) => {\n const config = this.config;\n let writeRequestBodyPromise = undefined;\n const timeouts = [];\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n timeouts.forEach(timing.clearTimeout);\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n timeouts.forEach(timing.clearTimeout);\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n reject(abortError);\n return;\n }\n const isSSL = request.protocol === \"https:\";\n const headers = request.headers ?? {};\n const expectContinue = (headers.Expect ?? headers.expect) === \"100-continue\";\n let agent = isSSL ? config.httpsAgent : config.httpAgent;\n if (expectContinue && !this.externalAgent) {\n agent = new (isSSL ? hsAgent : hAgent)({\n keepAlive: false,\n maxSockets: Infinity,\n });\n }\n timeouts.push(timing.setTimeout(() => {\n this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger);\n }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000)));\n const queryString = buildQueryString(request.query || {});\n let auth = undefined;\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}`;\n }\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let hostname = request.hostname ?? \"\";\n if (hostname[0] === \"[\" && hostname.endsWith(\"]\")) {\n hostname = request.hostname.slice(1, -1);\n }\n else {\n hostname = request.hostname;\n }\n const nodeHttpsOptions = {\n headers: request.headers,\n host: hostname,\n method: request.method,\n path,\n port: request.port,\n agent,\n auth,\n };\n const requestFunc = isSSL ? hsRequest : hRequest;\n const req = requestFunc(nodeHttpsOptions, (res) => {\n const httpResponse = new HttpResponse({\n statusCode: res.statusCode || -1,\n reason: res.statusMessage,\n headers: getTransformedHeaders(res.headers),\n body: res,\n });\n resolve({ response: httpResponse });\n });\n req.on(\"error\", (err) => {\n if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {\n reject(Object.assign(err, { name: \"TimeoutError\" }));\n }\n else {\n reject(err);\n }\n });\n if (abortSignal) {\n const onAbort = () => {\n req.destroy();\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;\n timeouts.push(setConnectionTimeout(req, reject, config.connectionTimeout));\n timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console));\n timeouts.push(setSocketTimeout(req, reject, config.socketTimeout));\n const httpAgent = nodeHttpsOptions.agent;\n if (typeof httpAgent === \"object\" && \"keepAlive\" in httpAgent) {\n timeouts.push(setSocketKeepAlive(req, {\n keepAlive: httpAgent.keepAlive,\n keepAliveMsecs: httpAgent.keepAliveMsecs,\n }));\n }\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => {\n timeouts.forEach(timing.clearTimeout);\n return _reject(e);\n });\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n","import { HttpResponse } from \"@smithy/protocol-http\";\nimport { buildQueryString } from \"@smithy/querystring-builder\";\nimport { constants } from \"http2\";\nimport { getTransformedHeaders } from \"./get-transformed-headers\";\nimport { NodeHttp2ConnectionManager } from \"./node-http2-connection-manager\";\nimport { writeRequestBody } from \"./write-request-body\";\nexport class NodeHttp2Handler {\n config;\n configProvider;\n metadata = { handlerProtocol: \"h2\" };\n connectionManager = new NodeHttp2ConnectionManager({});\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new NodeHttp2Handler(instanceOrOptions);\n }\n constructor(options) {\n this.configProvider = new Promise((resolve, reject) => {\n if (typeof options === \"function\") {\n options()\n .then((opts) => {\n resolve(opts || {});\n })\n .catch(reject);\n }\n else {\n resolve(options || {});\n }\n });\n }\n destroy() {\n this.connectionManager.destroy();\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false);\n if (this.config.maxConcurrentStreams) {\n this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams);\n }\n }\n const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config;\n const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout;\n return new Promise((_resolve, _reject) => {\n let fulfilled = false;\n let writeRequestBodyPromise = undefined;\n const resolve = async (arg) => {\n await writeRequestBodyPromise;\n _resolve(arg);\n };\n const reject = async (arg) => {\n await writeRequestBodyPromise;\n _reject(arg);\n };\n if (abortSignal?.aborted) {\n fulfilled = true;\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n reject(abortError);\n return;\n }\n const { hostname, method, port, protocol, query } = request;\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : \"\"}`;\n const requestContext = { destination: new URL(authority) };\n const session = this.connectionManager.lease(requestContext, {\n requestTimeout: this.config?.sessionTimeout,\n disableConcurrentStreams: disableConcurrentStreams || false,\n });\n const rejectWithDestroy = (err) => {\n if (disableConcurrentStreams) {\n this.destroySession(session);\n }\n fulfilled = true;\n reject(err);\n };\n const queryString = buildQueryString(query || {});\n let path = request.path;\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n const req = session.request({\n ...request.headers,\n [constants.HTTP2_HEADER_PATH]: path,\n [constants.HTTP2_HEADER_METHOD]: method,\n });\n session.ref();\n req.on(\"response\", (headers) => {\n const httpResponse = new HttpResponse({\n statusCode: headers[\":status\"] || -1,\n headers: getTransformedHeaders(headers),\n body: req,\n });\n fulfilled = true;\n resolve({ response: httpResponse });\n if (disableConcurrentStreams) {\n session.close();\n this.connectionManager.deleteSession(authority, session);\n }\n });\n if (effectiveRequestTimeout) {\n req.setTimeout(effectiveRequestTimeout, () => {\n req.close();\n const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`);\n timeoutError.name = \"TimeoutError\";\n rejectWithDestroy(timeoutError);\n });\n }\n if (abortSignal) {\n const onAbort = () => {\n req.close();\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n rejectWithDestroy(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n req.once(\"close\", () => signal.removeEventListener(\"abort\", onAbort));\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }\n req.on(\"frameError\", (type, code, id) => {\n rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));\n });\n req.on(\"error\", rejectWithDestroy);\n req.on(\"aborted\", () => {\n rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`));\n });\n req.on(\"close\", () => {\n session.unref();\n if (disableConcurrentStreams) {\n session.destroy();\n }\n if (!fulfilled) {\n rejectWithDestroy(new Error(\"Unexpected error: http2 request did not get a response\"));\n }\n });\n writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout);\n });\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n return {\n ...config,\n [key]: value,\n };\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n destroySession(session) {\n if (!session.destroyed) {\n session.destroy();\n }\n }\n}\n","import { Writable } from \"stream\";\nexport class Collector extends Writable {\n bufferedBytes = [];\n _write(chunk, encoding, callback) {\n this.bufferedBytes.push(chunk);\n callback();\n }\n}\n","import { Collector } from \"./collector\";\nexport const streamCollector = (stream) => {\n if (isReadableStreamInstance(stream)) {\n return collectReadableStream(stream);\n }\n return new Promise((resolve, reject) => {\n const collector = new Collector();\n stream.pipe(collector);\n stream.on(\"error\", (err) => {\n collector.end();\n reject(err);\n });\n collector.on(\"error\", reject);\n collector.on(\"finish\", function () {\n const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));\n resolve(bytes);\n });\n });\n};\nconst isReadableStreamInstance = (stream) => typeof ReadableStream === \"function\" && stream instanceof ReadableStream;\nasync function collectReadableStream(stream) {\n const chunks = [];\n const reader = stream.getReader();\n let isDone = false;\n let length = 0;\n while (!isDone) {\n const { done, value } = await reader.read();\n if (value) {\n chunks.push(value);\n length += value.length;\n }\n isDone = done;\n }\n const collected = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n collected.set(chunk, offset);\n offset += chunk.length;\n }\n return collected;\n}\n","export * from \"./node-http-handler\";\nexport * from \"./node-http2-handler\";\nexport * from \"./stream-collector\";\n","import { HttpResponse } from \"@smithy/protocol-http\";\nimport { buildQueryString } from \"@smithy/querystring-builder\";\nimport { createRequest } from \"./create-request\";\nimport { requestTimeout as requestTimeoutFn } from \"./request-timeout\";\nexport const keepAliveSupport = {\n supported: undefined,\n};\nexport class FetchHttpHandler {\n config;\n configProvider;\n static create(instanceOrOptions) {\n if (typeof instanceOrOptions?.handle === \"function\") {\n return instanceOrOptions;\n }\n return new FetchHttpHandler(instanceOrOptions);\n }\n constructor(options) {\n if (typeof options === \"function\") {\n this.configProvider = options().then((opts) => opts || {});\n }\n else {\n this.config = options ?? {};\n this.configProvider = Promise.resolve(this.config);\n }\n if (keepAliveSupport.supported === undefined) {\n keepAliveSupport.supported = Boolean(typeof Request !== \"undefined\" && \"keepalive\" in createRequest(\"https://[::1]\"));\n }\n }\n destroy() {\n }\n async handle(request, { abortSignal, requestTimeout } = {}) {\n if (!this.config) {\n this.config = await this.configProvider;\n }\n const requestTimeoutInMs = requestTimeout ?? this.config.requestTimeout;\n const keepAlive = this.config.keepAlive === true;\n const credentials = this.config.credentials;\n if (abortSignal?.aborted) {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n return Promise.reject(abortError);\n }\n let path = request.path;\n const queryString = buildQueryString(request.query || {});\n if (queryString) {\n path += `?${queryString}`;\n }\n if (request.fragment) {\n path += `#${request.fragment}`;\n }\n let auth = \"\";\n if (request.username != null || request.password != null) {\n const username = request.username ?? \"\";\n const password = request.password ?? \"\";\n auth = `${username}:${password}@`;\n }\n const { port, method } = request;\n const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : \"\"}${path}`;\n const body = method === \"GET\" || method === \"HEAD\" ? undefined : request.body;\n const requestOptions = {\n body,\n headers: new Headers(request.headers),\n method: method,\n credentials,\n };\n if (this.config?.cache) {\n requestOptions.cache = this.config.cache;\n }\n if (body) {\n requestOptions.duplex = \"half\";\n }\n if (typeof AbortController !== \"undefined\") {\n requestOptions.signal = abortSignal;\n }\n if (keepAliveSupport.supported) {\n requestOptions.keepalive = keepAlive;\n }\n if (typeof this.config.requestInit === \"function\") {\n Object.assign(requestOptions, this.config.requestInit(request));\n }\n let removeSignalEventListener = () => { };\n const fetchRequest = createRequest(url, requestOptions);\n const raceOfPromises = [\n fetch(fetchRequest).then((response) => {\n const fetchHeaders = response.headers;\n const transformedHeaders = {};\n for (const pair of fetchHeaders.entries()) {\n transformedHeaders[pair[0]] = pair[1];\n }\n const hasReadableStream = response.body != undefined;\n if (!hasReadableStream) {\n return response.blob().then((body) => ({\n response: new HttpResponse({\n headers: transformedHeaders,\n reason: response.statusText,\n statusCode: response.status,\n body,\n }),\n }));\n }\n return {\n response: new HttpResponse({\n headers: transformedHeaders,\n reason: response.statusText,\n statusCode: response.status,\n body: response.body,\n }),\n };\n }),\n requestTimeoutFn(requestTimeoutInMs),\n ];\n if (abortSignal) {\n raceOfPromises.push(new Promise((resolve, reject) => {\n const onAbort = () => {\n const abortError = new Error(\"Request aborted\");\n abortError.name = \"AbortError\";\n reject(abortError);\n };\n if (typeof abortSignal.addEventListener === \"function\") {\n const signal = abortSignal;\n signal.addEventListener(\"abort\", onAbort, { once: true });\n removeSignalEventListener = () => signal.removeEventListener(\"abort\", onAbort);\n }\n else {\n abortSignal.onabort = onAbort;\n }\n }));\n }\n return Promise.race(raceOfPromises).finally(removeSignalEventListener);\n }\n updateHttpClientConfig(key, value) {\n this.config = undefined;\n this.configProvider = this.configProvider.then((config) => {\n config[key] = value;\n return config;\n });\n }\n httpHandlerConfigs() {\n return this.config ?? {};\n }\n}\n","import { fromBase64 } from \"@smithy/util-base64\";\nexport const streamCollector = async (stream) => {\n if ((typeof Blob === \"function\" && stream instanceof Blob) || stream.constructor?.name === \"Blob\") {\n if (Blob.prototype.arrayBuffer !== undefined) {\n return new Uint8Array(await stream.arrayBuffer());\n }\n return collectBlob(stream);\n }\n return collectStream(stream);\n};\nasync function collectBlob(blob) {\n const base64 = await readToBase64(blob);\n const arrayBuffer = fromBase64(base64);\n return new Uint8Array(arrayBuffer);\n}\nasync function collectStream(stream) {\n const chunks = [];\n const reader = stream.getReader();\n let isDone = false;\n let length = 0;\n while (!isDone) {\n const { done, value } = await reader.read();\n if (value) {\n chunks.push(value);\n length += value.length;\n }\n isDone = done;\n }\n const collected = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n collected.set(chunk, offset);\n offset += chunk.length;\n }\n return collected;\n}\nfunction readToBase64(blob) {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n if (reader.readyState !== 2) {\n return reject(new Error(\"Reader aborted too early\"));\n }\n const result = (reader.result ?? \"\");\n const commaIndex = result.indexOf(\",\");\n const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;\n resolve(result.substring(dataOffset));\n };\n reader.onabort = () => reject(new Error(\"Read aborted\"));\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(blob);\n });\n}\n","export * from \"./fetch-http-handler\";\nexport * from \"./stream-collector\";\n","const SHORT_TO_HEX = {};\nconst HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\nexport function fromHex(encoded) {\n if (encoded.length % 2 !== 0) {\n throw new Error(\"Hex encoded strings must have an even number length\");\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n}\nexport function toHex(bytes) {\n let out = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n}\n","import { streamCollector } from \"@smithy/fetch-http-handler\";\nimport { toBase64 } from \"@smithy/util-base64\";\nimport { toHex } from \"@smithy/util-hex-encoding\";\nimport { toUtf8 } from \"@smithy/util-utf8\";\nimport { isReadableStream } from \"./stream-type-check\";\nconst ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = \"The stream has already been transformed.\";\nexport const sdkStreamMixin = (stream) => {\n if (!isBlobInstance(stream) && !isReadableStream(stream)) {\n const name = stream?.__proto__?.constructor?.name || stream;\n throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);\n }\n let transformed = false;\n const transformToByteArray = async () => {\n if (transformed) {\n throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);\n }\n transformed = true;\n return await streamCollector(stream);\n };\n const blobToWebStream = (blob) => {\n if (typeof blob.stream !== \"function\") {\n throw new Error(\"Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\\n\" +\n \"If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body\");\n }\n return blob.stream();\n };\n return Object.assign(stream, {\n transformToByteArray: transformToByteArray,\n transformToString: async (encoding) => {\n const buf = await transformToByteArray();\n if (encoding === \"base64\") {\n return toBase64(buf);\n }\n else if (encoding === \"hex\") {\n return toHex(buf);\n }\n else if (encoding === undefined || encoding === \"utf8\" || encoding === \"utf-8\") {\n return toUtf8(buf);\n }\n else if (typeof TextDecoder === \"function\") {\n return new TextDecoder(encoding).decode(buf);\n }\n else {\n throw new Error(\"TextDecoder is not available, please make sure polyfill is provided.\");\n }\n },\n transformToWebStream: () => {\n if (transformed) {\n throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);\n }\n transformed = true;\n if (isBlobInstance(stream)) {\n return blobToWebStream(stream);\n }\n else if (isReadableStream(stream)) {\n return stream;\n }\n else {\n throw new Error(`Cannot transform payload to web stream, got ${stream}`);\n }\n },\n });\n};\nconst isBlobInstance = (stream) => typeof Blob === \"function\" && stream instanceof Blob;\n","import { streamCollector } from \"@smithy/node-http-handler\";\nimport { fromArrayBuffer } from \"@smithy/util-buffer-from\";\nimport { Readable } from \"stream\";\nimport { sdkStreamMixin as sdkStreamMixinReadableStream } from \"./sdk-stream-mixin.browser\";\nconst ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = \"The stream has already been transformed.\";\nexport const sdkStreamMixin = (stream) => {\n if (!(stream instanceof Readable)) {\n try {\n return sdkStreamMixinReadableStream(stream);\n }\n catch (e) {\n const name = stream?.__proto__?.constructor?.name || stream;\n throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);\n }\n }\n let transformed = false;\n const transformToByteArray = async () => {\n if (transformed) {\n throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);\n }\n transformed = true;\n return await streamCollector(stream);\n };\n return Object.assign(stream, {\n transformToByteArray,\n transformToString: async (encoding) => {\n const buf = await transformToByteArray();\n if (encoding === undefined || Buffer.isEncoding(encoding)) {\n return fromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);\n }\n else {\n const decoder = new TextDecoder(encoding);\n return decoder.decode(buf);\n }\n },\n transformToWebStream: () => {\n if (transformed) {\n throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);\n }\n if (stream.readableFlowing !== null) {\n throw new Error(\"The stream has been consumed by other callbacks.\");\n }\n if (typeof Readable.toWeb !== \"function\") {\n throw new Error(\"Readable.toWeb() is not supported. Please ensure a polyfill is available.\");\n }\n transformed = true;\n return Readable.toWeb(stream);\n },\n });\n};\n","export async function splitStream(stream) {\n if (typeof stream.stream === \"function\") {\n stream = stream.stream();\n }\n const readableStream = stream;\n return readableStream.tee();\n}\n","import { PassThrough } from \"stream\";\nimport { splitStream as splitWebStream } from \"./splitStream.browser\";\nimport { isBlob, isReadableStream } from \"./stream-type-check\";\nexport async function splitStream(stream) {\n if (isReadableStream(stream) || isBlob(stream)) {\n return splitWebStream(stream);\n }\n const stream1 = new PassThrough();\n const stream2 = new PassThrough();\n stream.pipe(stream1);\n stream.pipe(stream2);\n return [stream1, stream2];\n}\n","export * from \"./blob/Uint8ArrayBlobAdapter\";\nexport * from \"./checksum/ChecksumStream\";\nexport * from \"./checksum/createChecksumStream\";\nexport * from \"./createBufferedReadable\";\nexport * from \"./getAwsChunkedEncodingStream\";\nexport * from \"./headStream\";\nexport * from \"./sdk-stream-mixin\";\nexport * from \"./splitStream\";\nexport { isReadableStream, isBlob } from \"./stream-type-check\";\n","import { Uint8ArrayBlobAdapter } from \"@smithy/util-stream\";\nexport const collectBody = async (streamBody = new Uint8Array(), context) => {\n if (streamBody instanceof Uint8Array) {\n return Uint8ArrayBlobAdapter.mutate(streamBody);\n }\n if (!streamBody) {\n return Uint8ArrayBlobAdapter.mutate(new Uint8Array());\n }\n const fromContext = context.streamCollector(streamBody);\n return Uint8ArrayBlobAdapter.mutate(await fromContext);\n};\n","export function extendedEncodeURIComponent(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\n","export const deref = (schemaRef) => {\n if (typeof schemaRef === \"function\") {\n return schemaRef();\n }\n return schemaRef;\n};\n","export const operation = (namespace, name, traits, input, output) => ({\n name,\n namespace,\n traits,\n input,\n output,\n});\n","import { HttpResponse } from \"@smithy/protocol-http\";\nimport { getSmithyContext } from \"@smithy/util-middleware\";\nimport { operation } from \"../schemas/operation\";\nexport const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => {\n const { response } = await next(args);\n const { operationSchema } = getSmithyContext(context);\n const [, ns, n, t, i, o] = operationSchema ?? [];\n try {\n const parsed = await config.protocol.deserializeResponse(operation(ns, n, t, i, o), {\n ...config,\n ...context,\n }, response);\n return {\n response,\n output: parsed,\n };\n }\n catch (error) {\n Object.defineProperty(error, \"$response\", {\n value: response,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n if (!(\"$metadata\" in error)) {\n const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;\n try {\n error.message += \"\\n \" + hint;\n }\n catch (e) {\n if (!context.logger || context.logger?.constructor?.name === \"NoOpLogger\") {\n console.warn(hint);\n }\n else {\n context.logger?.warn?.(hint);\n }\n }\n if (typeof error.$responseBodyText !== \"undefined\") {\n if (error.$response) {\n error.$response.body = error.$responseBodyText;\n }\n }\n try {\n if (HttpResponse.isInstance(response)) {\n const { headers = {} } = response;\n const headerEntries = Object.entries(headers);\n error.$metadata = {\n httpStatusCode: response.statusCode,\n requestId: findHeader(/^x-[\\w-]+-request-?id$/, headerEntries),\n extendedRequestId: findHeader(/^x-[\\w-]+-id-2$/, headerEntries),\n cfId: findHeader(/^x-[\\w-]+-cf-id$/, headerEntries),\n };\n }\n }\n catch (e) {\n }\n }\n throw error;\n }\n};\nconst findHeader = (pattern, headers) => {\n return (headers.find(([k]) => {\n return k.match(pattern);\n }) || [void 0, void 1])[1];\n};\n","import { getSmithyContext } from \"@smithy/util-middleware\";\nimport { operation } from \"../schemas/operation\";\nexport const schemaSerializationMiddleware = (config) => (next, context) => async (args) => {\n const { operationSchema } = getSmithyContext(context);\n const [, ns, n, t, i, o] = operationSchema ?? [];\n const endpoint = context.endpointV2?.url && config.urlParser\n ? async () => config.urlParser(context.endpointV2.url)\n : config.endpoint;\n const request = await config.protocol.serializeRequest(operation(ns, n, t, i, o), args.input, {\n ...config,\n ...context,\n endpoint,\n });\n return next({\n ...args,\n request,\n });\n};\n","import { schemaDeserializationMiddleware } from \"./schemaDeserializationMiddleware\";\nimport { schemaSerializationMiddleware } from \"./schemaSerializationMiddleware\";\nexport const deserializerMiddlewareOption = {\n name: \"deserializerMiddleware\",\n step: \"deserialize\",\n tags: [\"DESERIALIZER\"],\n override: true,\n};\nexport const serializerMiddlewareOption = {\n name: \"serializerMiddleware\",\n step: \"serialize\",\n tags: [\"SERIALIZER\"],\n override: true,\n};\nexport function getSchemaSerdePlugin(config) {\n return {\n applyToStack: (commandStack) => {\n commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption);\n commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption);\n config.protocol.setSerdeContext(config);\n },\n };\n}\n","export class Schema {\n name;\n namespace;\n traits;\n static assign(instance, values) {\n const schema = Object.assign(instance, values);\n return schema;\n }\n static [Symbol.hasInstance](lhs) {\n const isPrototype = this.prototype.isPrototypeOf(lhs);\n if (!isPrototype && typeof lhs === \"object\" && lhs !== null) {\n const list = lhs;\n return list.symbol === this.symbol;\n }\n return isPrototype;\n }\n getName() {\n return this.namespace + \"#\" + this.name;\n }\n}\n","import { Schema } from \"./Schema\";\nexport class ListSchema extends Schema {\n static symbol = Symbol.for(\"@smithy/lis\");\n name;\n traits;\n valueSchema;\n symbol = ListSchema.symbol;\n}\nexport const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), {\n name,\n namespace,\n traits,\n valueSchema,\n});\n","import { Schema } from \"./Schema\";\nexport class MapSchema extends Schema {\n static symbol = Symbol.for(\"@smithy/map\");\n name;\n traits;\n keySchema;\n valueSchema;\n symbol = MapSchema.symbol;\n}\nexport const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), {\n name,\n namespace,\n traits,\n keySchema,\n valueSchema,\n});\n","import { Schema } from \"./Schema\";\nexport class OperationSchema extends Schema {\n static symbol = Symbol.for(\"@smithy/ope\");\n name;\n traits;\n input;\n output;\n symbol = OperationSchema.symbol;\n}\nexport const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), {\n name,\n namespace,\n traits,\n input,\n output,\n});\n","import { Schema } from \"./Schema\";\nexport class StructureSchema extends Schema {\n static symbol = Symbol.for(\"@smithy/str\");\n name;\n traits;\n memberNames;\n memberList;\n symbol = StructureSchema.symbol;\n}\nexport const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), {\n name,\n namespace,\n traits,\n memberNames,\n memberList,\n});\n","import { Schema } from \"./Schema\";\nimport { StructureSchema } from \"./StructureSchema\";\nexport class ErrorSchema extends StructureSchema {\n static symbol = Symbol.for(\"@smithy/err\");\n ctor;\n symbol = ErrorSchema.symbol;\n}\nexport const error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), {\n name,\n namespace,\n traits,\n memberNames,\n memberList,\n ctor: null,\n});\n","export function translateTraits(indicator) {\n if (typeof indicator === \"object\") {\n return indicator;\n }\n indicator = indicator | 0;\n const traits = {};\n let i = 0;\n for (const trait of [\n \"httpLabel\",\n \"idempotent\",\n \"idempotencyToken\",\n \"sensitive\",\n \"httpPayload\",\n \"httpResponseCode\",\n \"httpQueryParams\",\n ]) {\n if (((indicator >> i++) & 1) === 1) {\n traits[trait] = 1;\n }\n }\n return traits;\n}\n","import { deref } from \"../deref\";\nimport { translateTraits } from \"./translateTraits\";\nconst anno = {\n it: Symbol.for(\"@smithy/nor-struct-it\"),\n};\nexport class NormalizedSchema {\n ref;\n memberName;\n static symbol = Symbol.for(\"@smithy/nor\");\n symbol = NormalizedSchema.symbol;\n name;\n schema;\n _isMemberSchema;\n traits;\n memberTraits;\n normalizedTraits;\n constructor(ref, memberName) {\n this.ref = ref;\n this.memberName = memberName;\n const traitStack = [];\n let _ref = ref;\n let schema = ref;\n this._isMemberSchema = false;\n while (isMemberSchema(_ref)) {\n traitStack.push(_ref[1]);\n _ref = _ref[0];\n schema = deref(_ref);\n this._isMemberSchema = true;\n }\n if (traitStack.length > 0) {\n this.memberTraits = {};\n for (let i = traitStack.length - 1; i >= 0; --i) {\n const traitSet = traitStack[i];\n Object.assign(this.memberTraits, translateTraits(traitSet));\n }\n }\n else {\n this.memberTraits = 0;\n }\n if (schema instanceof NormalizedSchema) {\n const computedMemberTraits = this.memberTraits;\n Object.assign(this, schema);\n this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits());\n this.normalizedTraits = void 0;\n this.memberName = memberName ?? schema.memberName;\n return;\n }\n this.schema = deref(schema);\n if (isStaticSchema(this.schema)) {\n this.name = `${this.schema[1]}#${this.schema[2]}`;\n this.traits = this.schema[3];\n }\n else {\n this.name = this.memberName ?? String(schema);\n this.traits = 0;\n }\n if (this._isMemberSchema && !memberName) {\n throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`);\n }\n }\n static [Symbol.hasInstance](lhs) {\n const isPrototype = this.prototype.isPrototypeOf(lhs);\n if (!isPrototype && typeof lhs === \"object\" && lhs !== null) {\n const ns = lhs;\n return ns.symbol === this.symbol;\n }\n return isPrototype;\n }\n static of(ref) {\n const sc = deref(ref);\n if (sc instanceof NormalizedSchema) {\n return sc;\n }\n if (isMemberSchema(sc)) {\n const [ns, traits] = sc;\n if (ns instanceof NormalizedSchema) {\n Object.assign(ns.getMergedTraits(), translateTraits(traits));\n return ns;\n }\n throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`);\n }\n return new NormalizedSchema(sc);\n }\n getSchema() {\n const sc = this.schema;\n if (sc[0] === 0) {\n return sc[4];\n }\n return sc;\n }\n getName(withNamespace = false) {\n const { name } = this;\n const short = !withNamespace && name && name.includes(\"#\");\n return short ? name.split(\"#\")[1] : name || undefined;\n }\n getMemberName() {\n return this.memberName;\n }\n isMemberSchema() {\n return this._isMemberSchema;\n }\n isListSchema() {\n const sc = this.getSchema();\n return typeof sc === \"number\"\n ? sc >= 64 && sc < 128\n : sc[0] === 1;\n }\n isMapSchema() {\n const sc = this.getSchema();\n return typeof sc === \"number\"\n ? sc >= 128 && sc <= 0b1111_1111\n : sc[0] === 2;\n }\n isStructSchema() {\n const sc = this.getSchema();\n const id = sc[0];\n return (id === 3 ||\n id === -3 ||\n id === 4);\n }\n isUnionSchema() {\n const sc = this.getSchema();\n return sc[0] === 4;\n }\n isBlobSchema() {\n const sc = this.getSchema();\n return sc === 21 || sc === 42;\n }\n isTimestampSchema() {\n const sc = this.getSchema();\n return (typeof sc === \"number\" &&\n sc >= 4 &&\n sc <= 7);\n }\n isUnitSchema() {\n return this.getSchema() === \"unit\";\n }\n isDocumentSchema() {\n return this.getSchema() === 15;\n }\n isStringSchema() {\n return this.getSchema() === 0;\n }\n isBooleanSchema() {\n return this.getSchema() === 2;\n }\n isNumericSchema() {\n return this.getSchema() === 1;\n }\n isBigIntegerSchema() {\n return this.getSchema() === 17;\n }\n isBigDecimalSchema() {\n return this.getSchema() === 19;\n }\n isStreaming() {\n const { streaming } = this.getMergedTraits();\n return !!streaming || this.getSchema() === 42;\n }\n isIdempotencyToken() {\n return !!this.getMergedTraits().idempotencyToken;\n }\n getMergedTraits() {\n return (this.normalizedTraits ??\n (this.normalizedTraits = {\n ...this.getOwnTraits(),\n ...this.getMemberTraits(),\n }));\n }\n getMemberTraits() {\n return translateTraits(this.memberTraits);\n }\n getOwnTraits() {\n return translateTraits(this.traits);\n }\n getKeySchema() {\n const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()];\n if (!isDoc && !isMap) {\n throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`);\n }\n const schema = this.getSchema();\n const memberSchema = isDoc\n ? 15\n : schema[4] ?? 0;\n return member([memberSchema, 0], \"key\");\n }\n getValueSchema() {\n const sc = this.getSchema();\n const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()];\n const memberSchema = typeof sc === \"number\"\n ? 0b0011_1111 & sc\n : sc && typeof sc === \"object\" && (isMap || isList)\n ? sc[3 + sc[0]]\n : isDoc\n ? 15\n : void 0;\n if (memberSchema != null) {\n return member([memberSchema, 0], isMap ? \"value\" : \"member\");\n }\n throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`);\n }\n getMemberSchema(memberName) {\n const struct = this.getSchema();\n if (this.isStructSchema() && struct[4].includes(memberName)) {\n const i = struct[4].indexOf(memberName);\n const memberSchema = struct[5][i];\n return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName);\n }\n if (this.isDocumentSchema()) {\n return member([15, 0], memberName);\n }\n throw new Error(`@smithy/core/schema - ${this.getName(true)} has no no member=${memberName}.`);\n }\n getMemberSchemas() {\n const buffer = {};\n try {\n for (const [k, v] of this.structIterator()) {\n buffer[k] = v;\n }\n }\n catch (ignored) { }\n return buffer;\n }\n getEventStreamMember() {\n if (this.isStructSchema()) {\n for (const [memberName, memberSchema] of this.structIterator()) {\n if (memberSchema.isStreaming() && memberSchema.isStructSchema()) {\n return memberName;\n }\n }\n }\n return \"\";\n }\n *structIterator() {\n if (this.isUnitSchema()) {\n return;\n }\n if (!this.isStructSchema()) {\n throw new Error(\"@smithy/core/schema - cannot iterate non-struct schema.\");\n }\n const struct = this.getSchema();\n const z = struct[4].length;\n let it = struct[anno.it];\n if (it && z === it.length) {\n yield* it;\n return;\n }\n it = Array(z);\n for (let i = 0; i < z; ++i) {\n const k = struct[4][i];\n const v = member([struct[5][i], 0], k);\n yield (it[i] = [k, v]);\n }\n struct[anno.it] = it;\n }\n}\nfunction member(memberSchema, memberName) {\n if (memberSchema instanceof NormalizedSchema) {\n return Object.assign(memberSchema, {\n memberName,\n _isMemberSchema: true,\n });\n }\n const internalCtorAccess = NormalizedSchema;\n return new internalCtorAccess(memberSchema, memberName);\n}\nconst isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2;\nexport const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5;\n","import { Schema } from \"./Schema\";\nexport class SimpleSchema extends Schema {\n static symbol = Symbol.for(\"@smithy/sim\");\n name;\n schemaRef;\n traits;\n symbol = SimpleSchema.symbol;\n}\nexport const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), {\n name,\n namespace,\n traits,\n schemaRef,\n});\nexport const simAdapter = (namespace, name, traits, schemaRef) => Schema.assign(new SimpleSchema(), {\n name,\n namespace,\n traits,\n schemaRef,\n});\n","export const SCHEMA = {\n BLOB: 0b0001_0101,\n STREAMING_BLOB: 0b0010_1010,\n BOOLEAN: 0b0000_0010,\n STRING: 0b0000_0000,\n NUMERIC: 0b0000_0001,\n BIG_INTEGER: 0b0001_0001,\n BIG_DECIMAL: 0b0001_0011,\n DOCUMENT: 0b0000_1111,\n TIMESTAMP_DEFAULT: 0b0000_0100,\n TIMESTAMP_DATE_TIME: 0b0000_0101,\n TIMESTAMP_HTTP_DATE: 0b0000_0110,\n TIMESTAMP_EPOCH_SECONDS: 0b0000_0111,\n LIST_MODIFIER: 0b0100_0000,\n MAP_MODIFIER: 0b1000_0000,\n};\n","export class TypeRegistry {\n namespace;\n schemas;\n exceptions;\n static registries = new Map();\n constructor(namespace, schemas = new Map(), exceptions = new Map()) {\n this.namespace = namespace;\n this.schemas = schemas;\n this.exceptions = exceptions;\n }\n static for(namespace) {\n if (!TypeRegistry.registries.has(namespace)) {\n TypeRegistry.registries.set(namespace, new TypeRegistry(namespace));\n }\n return TypeRegistry.registries.get(namespace);\n }\n register(shapeId, schema) {\n const qualifiedName = this.normalizeShapeId(shapeId);\n const registry = TypeRegistry.for(qualifiedName.split(\"#\")[0]);\n registry.schemas.set(qualifiedName, schema);\n }\n getSchema(shapeId) {\n const id = this.normalizeShapeId(shapeId);\n if (!this.schemas.has(id)) {\n throw new Error(`@smithy/core/schema - schema not found for ${id}`);\n }\n return this.schemas.get(id);\n }\n registerError(es, ctor) {\n const $error = es;\n const registry = TypeRegistry.for($error[1]);\n registry.schemas.set($error[1] + \"#\" + $error[2], $error);\n registry.exceptions.set($error, ctor);\n }\n getErrorCtor(es) {\n const $error = es;\n const registry = TypeRegistry.for($error[1]);\n return registry.exceptions.get($error);\n }\n getBaseException() {\n for (const exceptionKey of this.exceptions.keys()) {\n if (Array.isArray(exceptionKey)) {\n const [, ns, name] = exceptionKey;\n const id = ns + \"#\" + name;\n if (id.startsWith(\"smithy.ts.sdk.synthetic.\") && id.endsWith(\"ServiceException\")) {\n return exceptionKey;\n }\n }\n }\n return undefined;\n }\n find(predicate) {\n return [...this.schemas.values()].find(predicate);\n }\n clear() {\n this.schemas.clear();\n this.exceptions.clear();\n }\n normalizeShapeId(shapeId) {\n if (shapeId.includes(\"#\")) {\n return shapeId;\n }\n return this.namespace + \"#\" + shapeId;\n }\n}\n","export * from \"./deref\";\nexport * from \"./middleware/getSchemaSerdePlugin\";\nexport * from \"./schemas/ListSchema\";\nexport * from \"./schemas/MapSchema\";\nexport * from \"./schemas/OperationSchema\";\nexport * from \"./schemas/operation\";\nexport * from \"./schemas/ErrorSchema\";\nexport * from \"./schemas/NormalizedSchema\";\nexport * from \"./schemas/Schema\";\nexport * from \"./schemas/SimpleSchema\";\nexport * from \"./schemas/StructureSchema\";\nexport * from \"./schemas/sentinels\";\nexport * from \"./schemas/translateTraits\";\nexport * from \"./TypeRegistry\";\n","export const copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source;\n","export const parseBoolean = (value) => {\n switch (value) {\n case \"true\":\n return true;\n case \"false\":\n return false;\n default:\n throw new Error(`Unable to parse boolean value \"${value}\"`);\n }\n};\nexport const expectBoolean = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value === \"number\") {\n if (value === 0 || value === 1) {\n logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));\n }\n if (value === 0) {\n return false;\n }\n if (value === 1) {\n return true;\n }\n }\n if (typeof value === \"string\") {\n const lower = value.toLowerCase();\n if (lower === \"false\" || lower === \"true\") {\n logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));\n }\n if (lower === \"false\") {\n return false;\n }\n if (lower === \"true\") {\n return true;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);\n};\nexport const expectNumber = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\") {\n const parsed = parseFloat(value);\n if (!Number.isNaN(parsed)) {\n if (String(parsed) !== String(value)) {\n logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));\n }\n return parsed;\n }\n }\n if (typeof value === \"number\") {\n return value;\n }\n throw new TypeError(`Expected number, got ${typeof value}: ${value}`);\n};\nconst MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));\nexport const expectFloat32 = (value) => {\n const expected = expectNumber(value);\n if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {\n if (Math.abs(expected) > MAX_FLOAT) {\n throw new TypeError(`Expected 32-bit float, got ${value}`);\n }\n }\n return expected;\n};\nexport const expectLong = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (Number.isInteger(value) && !Number.isNaN(value)) {\n return value;\n }\n throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);\n};\nexport const expectInt = expectLong;\nexport const expectInt32 = (value) => expectSizedInt(value, 32);\nexport const expectShort = (value) => expectSizedInt(value, 16);\nexport const expectByte = (value) => expectSizedInt(value, 8);\nconst expectSizedInt = (value, size) => {\n const expected = expectLong(value);\n if (expected !== undefined && castInt(expected, size) !== expected) {\n throw new TypeError(`Expected ${size}-bit integer, got ${value}`);\n }\n return expected;\n};\nconst castInt = (value, size) => {\n switch (size) {\n case 32:\n return Int32Array.of(value)[0];\n case 16:\n return Int16Array.of(value)[0];\n case 8:\n return Int8Array.of(value)[0];\n }\n};\nexport const expectNonNull = (value, location) => {\n if (value === null || value === undefined) {\n if (location) {\n throw new TypeError(`Expected a non-null value for ${location}`);\n }\n throw new TypeError(\"Expected a non-null value\");\n }\n return value;\n};\nexport const expectObject = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value === \"object\" && !Array.isArray(value)) {\n return value;\n }\n const receivedType = Array.isArray(value) ? \"array\" : typeof value;\n throw new TypeError(`Expected object, got ${receivedType}: ${value}`);\n};\nexport const expectString = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if ([\"boolean\", \"number\", \"bigint\"].includes(typeof value)) {\n logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));\n return String(value);\n }\n throw new TypeError(`Expected string, got ${typeof value}: ${value}`);\n};\nexport const expectUnion = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n const asObject = expectObject(value);\n const setKeys = Object.entries(asObject)\n .filter(([, v]) => v != null)\n .map(([k]) => k);\n if (setKeys.length === 0) {\n throw new TypeError(`Unions must have exactly one non-null member. None were found.`);\n }\n if (setKeys.length > 1) {\n throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);\n }\n return asObject;\n};\nexport const strictParseDouble = (value) => {\n if (typeof value == \"string\") {\n return expectNumber(parseNumber(value));\n }\n return expectNumber(value);\n};\nexport const strictParseFloat = strictParseDouble;\nexport const strictParseFloat32 = (value) => {\n if (typeof value == \"string\") {\n return expectFloat32(parseNumber(value));\n }\n return expectFloat32(value);\n};\nconst NUMBER_REGEX = /(-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)|(-?Infinity)|(NaN)/g;\nconst parseNumber = (value) => {\n const matches = value.match(NUMBER_REGEX);\n if (matches === null || matches[0].length !== value.length) {\n throw new TypeError(`Expected real number, got implicit NaN`);\n }\n return parseFloat(value);\n};\nexport const limitedParseDouble = (value) => {\n if (typeof value == \"string\") {\n return parseFloatString(value);\n }\n return expectNumber(value);\n};\nexport const handleFloat = limitedParseDouble;\nexport const limitedParseFloat = limitedParseDouble;\nexport const limitedParseFloat32 = (value) => {\n if (typeof value == \"string\") {\n return parseFloatString(value);\n }\n return expectFloat32(value);\n};\nconst parseFloatString = (value) => {\n switch (value) {\n case \"NaN\":\n return NaN;\n case \"Infinity\":\n return Infinity;\n case \"-Infinity\":\n return -Infinity;\n default:\n throw new Error(`Unable to parse float value: ${value}`);\n }\n};\nexport const strictParseLong = (value) => {\n if (typeof value === \"string\") {\n return expectLong(parseNumber(value));\n }\n return expectLong(value);\n};\nexport const strictParseInt = strictParseLong;\nexport const strictParseInt32 = (value) => {\n if (typeof value === \"string\") {\n return expectInt32(parseNumber(value));\n }\n return expectInt32(value);\n};\nexport const strictParseShort = (value) => {\n if (typeof value === \"string\") {\n return expectShort(parseNumber(value));\n }\n return expectShort(value);\n};\nexport const strictParseByte = (value) => {\n if (typeof value === \"string\") {\n return expectByte(parseNumber(value));\n }\n return expectByte(value);\n};\nconst stackTraceWarning = (message) => {\n return String(new TypeError(message).stack || message)\n .split(\"\\n\")\n .slice(0, 5)\n .filter((s) => !s.includes(\"stackTraceWarning\"))\n .join(\"\\n\");\n};\nexport const logger = {\n warn: console.warn,\n};\n","import { strictParseByte, strictParseDouble, strictParseFloat32, strictParseShort } from \"./parse-utils\";\nconst DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nexport function dateToUtcString(date) {\n const year = date.getUTCFullYear();\n const month = date.getUTCMonth();\n const dayOfWeek = date.getUTCDay();\n const dayOfMonthInt = date.getUTCDate();\n const hoursInt = date.getUTCHours();\n const minutesInt = date.getUTCMinutes();\n const secondsInt = date.getUTCSeconds();\n const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;\n const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;\n const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;\n const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;\n return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;\n}\nconst RFC3339 = new RegExp(/^(\\d{4})-(\\d{2})-(\\d{2})[tT](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?[zZ]$/);\nexport const parseRfc3339DateTime = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"RFC-3339 date-times must be expressed as strings\");\n }\n const match = RFC3339.exec(value);\n if (!match) {\n throw new TypeError(\"Invalid RFC-3339 date-time value\");\n }\n const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match;\n const year = strictParseShort(stripLeadingZeroes(yearStr));\n const month = parseDateValue(monthStr, \"month\", 1, 12);\n const day = parseDateValue(dayStr, \"day\", 1, 31);\n return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });\n};\nconst RFC3339_WITH_OFFSET = new RegExp(/^(\\d{4})-(\\d{2})-(\\d{2})[tT](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?(([-+]\\d{2}\\:\\d{2})|[zZ])$/);\nexport const parseRfc3339DateTimeWithOffset = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"RFC-3339 date-times must be expressed as strings\");\n }\n const match = RFC3339_WITH_OFFSET.exec(value);\n if (!match) {\n throw new TypeError(\"Invalid RFC-3339 date-time value\");\n }\n const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match;\n const year = strictParseShort(stripLeadingZeroes(yearStr));\n const month = parseDateValue(monthStr, \"month\", 1, 12);\n const day = parseDateValue(dayStr, \"day\", 1, 31);\n const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });\n if (offsetStr.toUpperCase() != \"Z\") {\n date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));\n }\n return date;\n};\nconst IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\\d{4}) (\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))? GMT$/);\nconst RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\\d{2}) (\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))? GMT$/);\nconst ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\\d{2}) (\\d{1,2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))? (\\d{4})$/);\nexport const parseRfc7231DateTime = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"RFC-7231 date-times must be expressed as strings\");\n }\n let match = IMF_FIXDATE.exec(value);\n if (match) {\n const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match;\n return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, \"day\", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });\n }\n match = RFC_850_DATE.exec(value);\n if (match) {\n const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match;\n return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, \"day\", 1, 31), {\n hours,\n minutes,\n seconds,\n fractionalMilliseconds,\n }));\n }\n match = ASC_TIME.exec(value);\n if (match) {\n const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match;\n return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), \"day\", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });\n }\n throw new TypeError(\"Invalid RFC-7231 date-time value\");\n};\nexport const parseEpochTimestamp = (value) => {\n if (value === null || value === undefined) {\n return undefined;\n }\n let valueAsDouble;\n if (typeof value === \"number\") {\n valueAsDouble = value;\n }\n else if (typeof value === \"string\") {\n valueAsDouble = strictParseDouble(value);\n }\n else if (typeof value === \"object\" && value.tag === 1) {\n valueAsDouble = value.value;\n }\n else {\n throw new TypeError(\"Epoch timestamps must be expressed as floating point numbers or their string representation\");\n }\n if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {\n throw new TypeError(\"Epoch timestamps must be valid, non-Infinite, non-NaN numerics\");\n }\n return new Date(Math.round(valueAsDouble * 1000));\n};\nconst buildDate = (year, month, day, time) => {\n const adjustedMonth = month - 1;\n validateDayOfMonth(year, adjustedMonth, day);\n return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, \"hour\", 0, 23), parseDateValue(time.minutes, \"minute\", 0, 59), parseDateValue(time.seconds, \"seconds\", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));\n};\nconst parseTwoDigitYear = (value) => {\n const thisYear = new Date().getUTCFullYear();\n const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value));\n if (valueInThisCentury < thisYear) {\n return valueInThisCentury + 100;\n }\n return valueInThisCentury;\n};\nconst FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000;\nconst adjustRfc850Year = (input) => {\n if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) {\n return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));\n }\n return input;\n};\nconst parseMonthByShortName = (value) => {\n const monthIdx = MONTHS.indexOf(value);\n if (monthIdx < 0) {\n throw new TypeError(`Invalid month: ${value}`);\n }\n return monthIdx + 1;\n};\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst validateDayOfMonth = (year, month, day) => {\n let maxDays = DAYS_IN_MONTH[month];\n if (month === 1 && isLeapYear(year)) {\n maxDays = 29;\n }\n if (day > maxDays) {\n throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);\n }\n};\nconst isLeapYear = (year) => {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n};\nconst parseDateValue = (value, type, lower, upper) => {\n const dateVal = strictParseByte(stripLeadingZeroes(value));\n if (dateVal < lower || dateVal > upper) {\n throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);\n }\n return dateVal;\n};\nconst parseMilliseconds = (value) => {\n if (value === null || value === undefined) {\n return 0;\n }\n return strictParseFloat32(\"0.\" + value) * 1000;\n};\nconst parseOffsetToMilliseconds = (value) => {\n const directionStr = value[0];\n let direction = 1;\n if (directionStr == \"+\") {\n direction = 1;\n }\n else if (directionStr == \"-\") {\n direction = -1;\n }\n else {\n throw new TypeError(`Offset direction, ${directionStr}, must be \"+\" or \"-\"`);\n }\n const hour = Number(value.substring(1, 3));\n const minute = Number(value.substring(4, 6));\n return direction * (hour * 60 + minute) * 60 * 1000;\n};\nconst stripLeadingZeroes = (value) => {\n let idx = 0;\n while (idx < value.length - 1 && value.charAt(idx) === \"0\") {\n idx++;\n }\n if (idx === 0) {\n return value;\n }\n return value.slice(idx);\n};\n","import crypto from \"crypto\";\nexport const randomUUID = crypto.randomUUID.bind(crypto);\n","import { randomUUID } from \"./randomUUID\";\nconst decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nexport const v4 = () => {\n if (randomUUID) {\n return randomUUID();\n }\n const rnds = new Uint8Array(16);\n crypto.getRandomValues(rnds);\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n return (decimalToHex[rnds[0]] +\n decimalToHex[rnds[1]] +\n decimalToHex[rnds[2]] +\n decimalToHex[rnds[3]] +\n \"-\" +\n decimalToHex[rnds[4]] +\n decimalToHex[rnds[5]] +\n \"-\" +\n decimalToHex[rnds[6]] +\n decimalToHex[rnds[7]] +\n \"-\" +\n decimalToHex[rnds[8]] +\n decimalToHex[rnds[9]] +\n \"-\" +\n decimalToHex[rnds[10]] +\n decimalToHex[rnds[11]] +\n decimalToHex[rnds[12]] +\n decimalToHex[rnds[13]] +\n decimalToHex[rnds[14]] +\n decimalToHex[rnds[15]]);\n};\n","export * from \"./v4\";\n","import { v4 as generateIdempotencyToken } from \"@smithy/uuid\";\nexport { generateIdempotencyToken };\n","export const LazyJsonString = function LazyJsonString(val) {\n const str = Object.assign(new String(val), {\n deserializeJSON() {\n return JSON.parse(String(val));\n },\n toString() {\n return String(val);\n },\n toJSON() {\n return String(val);\n },\n });\n return str;\n};\nLazyJsonString.from = (object) => {\n if (object && typeof object === \"object\" && (object instanceof LazyJsonString || \"deserializeJSON\" in object)) {\n return object;\n }\n else if (typeof object === \"string\" || Object.getPrototypeOf(object) === String.prototype) {\n return LazyJsonString(String(object));\n }\n return LazyJsonString(JSON.stringify(object));\n};\nLazyJsonString.fromObject = LazyJsonString.from;\n","export function quoteHeader(part) {\n if (part.includes(\",\") || part.includes('\"')) {\n part = `\"${part.replace(/\"/g, '\\\\\"')}\"`;\n }\n return part;\n}\n","const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`;\nconst mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`;\nconst time = `(\\\\d?\\\\d):(\\\\d{2}):(\\\\d{2})(?:\\\\.(\\\\d+))?`;\nconst date = `(\\\\d?\\\\d)`;\nconst year = `(\\\\d{4})`;\nconst RFC3339_WITH_OFFSET = new RegExp(/^(\\d{4})-(\\d\\d)-(\\d\\d)[tT](\\d\\d):(\\d\\d):(\\d\\d)(\\.(\\d+))?(([-+]\\d\\d:\\d\\d)|[zZ])$/);\nconst IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`);\nconst RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\\\d\\\\d) ${time} GMT$`);\nconst ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\\\d\\\\d) ${time} ${year}$`);\nconst months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nexport const _parseEpochTimestamp = (value) => {\n if (value == null) {\n return void 0;\n }\n let num = NaN;\n if (typeof value === \"number\") {\n num = value;\n }\n else if (typeof value === \"string\") {\n if (!/^-?\\d*\\.?\\d+$/.test(value)) {\n throw new TypeError(`parseEpochTimestamp - numeric string invalid.`);\n }\n num = Number.parseFloat(value);\n }\n else if (typeof value === \"object\" && value.tag === 1) {\n num = value.value;\n }\n if (isNaN(num) || Math.abs(num) === Infinity) {\n throw new TypeError(\"Epoch timestamps must be valid finite numbers.\");\n }\n return new Date(Math.round(num * 1000));\n};\nexport const _parseRfc3339DateTimeWithOffset = (value) => {\n if (value == null) {\n return void 0;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"RFC3339 timestamps must be strings\");\n }\n const matches = RFC3339_WITH_OFFSET.exec(value);\n if (!matches) {\n throw new TypeError(`Invalid RFC3339 timestamp format ${value}`);\n }\n const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches;\n range(monthStr, 1, 12);\n range(dayStr, 1, 31);\n range(hours, 0, 23);\n range(minutes, 0, 59);\n range(seconds, 0, 60);\n const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0));\n date.setUTCFullYear(Number(yearStr));\n if (offsetStr.toUpperCase() != \"Z\") {\n const [, sign, offsetH, offsetM] = /([+-])(\\d\\d):(\\d\\d)/.exec(offsetStr) || [void 0, \"+\", 0, 0];\n const scalar = sign === \"-\" ? 1 : -1;\n date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000));\n }\n return date;\n};\nexport const _parseRfc7231DateTime = (value) => {\n if (value == null) {\n return void 0;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"RFC7231 timestamps must be strings.\");\n }\n let day;\n let month;\n let year;\n let hour;\n let minute;\n let second;\n let fraction;\n let matches;\n if ((matches = IMF_FIXDATE.exec(value))) {\n [, day, month, year, hour, minute, second, fraction] = matches;\n }\n else if ((matches = RFC_850_DATE.exec(value))) {\n [, day, month, year, hour, minute, second, fraction] = matches;\n year = (Number(year) + 1900).toString();\n }\n else if ((matches = ASC_TIME.exec(value))) {\n [, month, day, hour, minute, second, fraction, year] = matches;\n }\n if (year && second) {\n const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0);\n range(day, 1, 31);\n range(hour, 0, 23);\n range(minute, 0, 59);\n range(second, 0, 60);\n const date = new Date(timestamp);\n date.setUTCFullYear(Number(year));\n return date;\n }\n throw new TypeError(`Invalid RFC7231 date-time value ${value}.`);\n};\nfunction range(v, min, max) {\n const _v = Number(v);\n if (_v < min || _v > max) {\n throw new Error(`Value ${_v} out of range [${min}, ${max}]`);\n }\n}\n","export function splitEvery(value, delimiter, numDelimiters) {\n if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) {\n throw new Error(\"Invalid number of delimiters (\" + numDelimiters + \") for splitEvery.\");\n }\n const segments = value.split(delimiter);\n if (numDelimiters === 1) {\n return segments;\n }\n const compoundSegments = [];\n let currentSegment = \"\";\n for (let i = 0; i < segments.length; i++) {\n if (currentSegment === \"\") {\n currentSegment = segments[i];\n }\n else {\n currentSegment += delimiter + segments[i];\n }\n if ((i + 1) % numDelimiters === 0) {\n compoundSegments.push(currentSegment);\n currentSegment = \"\";\n }\n }\n if (currentSegment !== \"\") {\n compoundSegments.push(currentSegment);\n }\n return compoundSegments;\n}\n","export const splitHeader = (value) => {\n const z = value.length;\n const values = [];\n let withinQuotes = false;\n let prevChar = undefined;\n let anchor = 0;\n for (let i = 0; i < z; ++i) {\n const char = value[i];\n switch (char) {\n case `\"`:\n if (prevChar !== \"\\\\\") {\n withinQuotes = !withinQuotes;\n }\n break;\n case \",\":\n if (!withinQuotes) {\n values.push(value.slice(anchor, i));\n anchor = i + 1;\n }\n break;\n default:\n }\n prevChar = char;\n }\n values.push(value.slice(anchor));\n return values.map((v) => {\n v = v.trim();\n const z = v.length;\n if (z < 2) {\n return v;\n }\n if (v[0] === `\"` && v[z - 1] === `\"`) {\n v = v.slice(1, z - 1);\n }\n return v.replace(/\\\\\"/g, '\"');\n });\n};\n","const format = /^-?\\d*(\\.\\d+)?$/;\nexport class NumericValue {\n string;\n type;\n constructor(string, type) {\n this.string = string;\n this.type = type;\n if (!format.test(string)) {\n throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point \".\", and an optional negation prefix \"-\".`);\n }\n }\n toString() {\n return this.string;\n }\n static [Symbol.hasInstance](object) {\n if (!object || typeof object !== \"object\") {\n return false;\n }\n const _nv = object;\n return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === \"bigDecimal\" && format.test(_nv.string));\n }\n}\nexport function nv(input) {\n return new NumericValue(String(input), \"bigDecimal\");\n}\n","export * from \"./copyDocumentWithTransform\";\nexport * from \"./date-utils\";\nexport * from \"./generateIdempotencyToken\";\nexport * from \"./lazy-json\";\nexport * from \"./parse-utils\";\nexport * from \"./quote-header\";\nexport * from \"./schema-serde-lib/schema-date-utils\";\nexport * from \"./split-every\";\nexport * from \"./split-header\";\nexport * from \"./value/NumericValue\";\n","export class SerdeContext {\n serdeContext;\n setSerdeContext(serdeContext) {\n this.serdeContext = serdeContext;\n }\n}\n","import { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nexport class EventStreamSerde {\n marshaller;\n serializer;\n deserializer;\n serdeContext;\n defaultContentType;\n constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) {\n this.marshaller = marshaller;\n this.serializer = serializer;\n this.deserializer = deserializer;\n this.serdeContext = serdeContext;\n this.defaultContentType = defaultContentType;\n }\n async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = requestSchema.getEventStreamMember();\n const unionSchema = requestSchema.getMemberSchema(eventStreamMember);\n const serializer = this.serializer;\n const defaultContentType = this.defaultContentType;\n const initialRequestMarker = Symbol(\"initialRequestMarker\");\n const eventStreamIterable = {\n async *[Symbol.asyncIterator]() {\n if (initialRequest) {\n const headers = {\n \":event-type\": { type: \"string\", value: \"initial-request\" },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: defaultContentType },\n };\n serializer.write(requestSchema, initialRequest);\n const body = serializer.flush();\n yield {\n [initialRequestMarker]: true,\n headers,\n body,\n };\n }\n for await (const page of eventStream) {\n yield page;\n }\n },\n };\n return marshaller.serialize(eventStreamIterable, (event) => {\n if (event[initialRequestMarker]) {\n return {\n headers: event.headers,\n body: event.body,\n };\n }\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event);\n const headers = {\n \":event-type\": { type: \"string\", value: eventType },\n \":message-type\": { type: \"string\", value: \"event\" },\n \":content-type\": { type: \"string\", value: explicitPayloadContentType ?? defaultContentType },\n ...additionalHeaders,\n };\n return {\n headers,\n body,\n };\n });\n }\n async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {\n const marshaller = this.marshaller;\n const eventStreamMember = responseSchema.getEventStreamMember();\n const unionSchema = responseSchema.getMemberSchema(eventStreamMember);\n const memberSchemas = unionSchema.getMemberSchemas();\n const initialResponseMarker = Symbol(\"initialResponseMarker\");\n const asyncIterable = marshaller.deserialize(response.body, async (event) => {\n const unionMember = Object.keys(event).find((key) => {\n return key !== \"__type\";\n }) ?? \"\";\n const body = event[unionMember].body;\n if (unionMember === \"initial-response\") {\n const dataObject = await this.deserializer.read(responseSchema, body);\n delete dataObject[eventStreamMember];\n return {\n [initialResponseMarker]: true,\n ...dataObject,\n };\n }\n else if (unionMember in memberSchemas) {\n const eventStreamSchema = memberSchemas[unionMember];\n if (eventStreamSchema.isStructSchema()) {\n const out = {};\n let hasBindings = false;\n for (const [name, member] of eventStreamSchema.structIterator()) {\n const { eventHeader, eventPayload } = member.getMergedTraits();\n hasBindings = hasBindings || Boolean(eventHeader || eventPayload);\n if (eventPayload) {\n if (member.isBlobSchema()) {\n out[name] = body;\n }\n else if (member.isStringSchema()) {\n out[name] = (this.serdeContext?.utf8Encoder ?? toUtf8)(body);\n }\n else if (member.isStructSchema()) {\n out[name] = await this.deserializer.read(member, body);\n }\n }\n else if (eventHeader) {\n const value = event[unionMember].headers[name]?.value;\n if (value != null) {\n if (member.isNumericSchema()) {\n if (value && typeof value === \"object\" && \"bytes\" in value) {\n out[name] = BigInt(value.toString());\n }\n else {\n out[name] = Number(value);\n }\n }\n else {\n out[name] = value;\n }\n }\n }\n }\n if (hasBindings) {\n return {\n [unionMember]: out,\n };\n }\n if (body.byteLength === 0) {\n return {\n [unionMember]: {},\n };\n }\n }\n return {\n [unionMember]: await this.deserializer.read(eventStreamSchema, body),\n };\n }\n else {\n return {\n $unknown: event,\n };\n }\n });\n const asyncIterator = asyncIterable[Symbol.asyncIterator]();\n const firstEvent = await asyncIterator.next();\n if (firstEvent.done) {\n return asyncIterable;\n }\n if (firstEvent.value?.[initialResponseMarker]) {\n if (!responseSchema) {\n throw new Error(\"@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.\");\n }\n for (const [key, value] of Object.entries(firstEvent.value)) {\n initialResponseContainer[key] = value;\n }\n }\n return {\n async *[Symbol.asyncIterator]() {\n if (!firstEvent?.value?.[initialResponseMarker]) {\n yield firstEvent.value;\n }\n while (true) {\n const { done, value } = await asyncIterator.next();\n if (done) {\n break;\n }\n yield value;\n }\n },\n };\n }\n writeEventBody(unionMember, unionSchema, event) {\n const serializer = this.serializer;\n let eventType = unionMember;\n let explicitPayloadMember = null;\n let explicitPayloadContentType;\n const isKnownSchema = (() => {\n const struct = unionSchema.getSchema();\n return struct[4].includes(unionMember);\n })();\n const additionalHeaders = {};\n if (!isKnownSchema) {\n const [type, value] = event[unionMember];\n eventType = type;\n serializer.write(15, value);\n }\n else {\n const eventSchema = unionSchema.getMemberSchema(unionMember);\n if (eventSchema.isStructSchema()) {\n for (const [memberName, memberSchema] of eventSchema.structIterator()) {\n const { eventHeader, eventPayload } = memberSchema.getMergedTraits();\n if (eventPayload) {\n explicitPayloadMember = memberName;\n }\n else if (eventHeader) {\n const value = event[unionMember][memberName];\n let type = \"binary\";\n if (memberSchema.isNumericSchema()) {\n if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) {\n type = \"integer\";\n }\n else {\n type = \"long\";\n }\n }\n else if (memberSchema.isTimestampSchema()) {\n type = \"timestamp\";\n }\n else if (memberSchema.isStringSchema()) {\n type = \"string\";\n }\n else if (memberSchema.isBooleanSchema()) {\n type = \"boolean\";\n }\n if (value != null) {\n additionalHeaders[memberName] = {\n type,\n value,\n };\n delete event[unionMember][memberName];\n }\n }\n }\n if (explicitPayloadMember !== null) {\n const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember);\n if (payloadSchema.isBlobSchema()) {\n explicitPayloadContentType = \"application/octet-stream\";\n }\n else if (payloadSchema.isStringSchema()) {\n explicitPayloadContentType = \"text/plain\";\n }\n serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]);\n }\n else {\n serializer.write(eventSchema, event[unionMember]);\n }\n }\n else {\n throw new Error(\"@smithy/core/event-streams - non-struct member not supported in event stream union.\");\n }\n }\n const messageSerialization = serializer.flush();\n const body = typeof messageSerialization === \"string\"\n ? (this.serdeContext?.utf8Decoder ?? fromUtf8)(messageSerialization)\n : messageSerialization;\n return {\n body,\n eventType,\n explicitPayloadContentType,\n additionalHeaders,\n };\n }\n}\n","export * from \"./EventStreamSerde\";\n","import { NormalizedSchema, translateTraits } from \"@smithy/core/schema\";\nimport { HttpRequest, HttpResponse } from \"@smithy/protocol-http\";\nimport { SerdeContext } from \"./SerdeContext\";\nexport class HttpProtocol extends SerdeContext {\n options;\n constructor(options) {\n super();\n this.options = options;\n }\n getRequestType() {\n return HttpRequest;\n }\n getResponseType() {\n return HttpResponse;\n }\n setSerdeContext(serdeContext) {\n this.serdeContext = serdeContext;\n this.serializer.setSerdeContext(serdeContext);\n this.deserializer.setSerdeContext(serdeContext);\n if (this.getPayloadCodec()) {\n this.getPayloadCodec().setSerdeContext(serdeContext);\n }\n }\n updateServiceEndpoint(request, endpoint) {\n if (\"url\" in endpoint) {\n request.protocol = endpoint.url.protocol;\n request.hostname = endpoint.url.hostname;\n request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined;\n request.path = endpoint.url.pathname;\n request.fragment = endpoint.url.hash || void 0;\n request.username = endpoint.url.username || void 0;\n request.password = endpoint.url.password || void 0;\n if (!request.query) {\n request.query = {};\n }\n for (const [k, v] of endpoint.url.searchParams.entries()) {\n request.query[k] = v;\n }\n return request;\n }\n else {\n request.protocol = endpoint.protocol;\n request.hostname = endpoint.hostname;\n request.port = endpoint.port ? Number(endpoint.port) : undefined;\n request.path = endpoint.path;\n request.query = {\n ...endpoint.query,\n };\n return request;\n }\n }\n setHostPrefix(request, operationSchema, input) {\n if (this.serdeContext?.disableHostPrefix) {\n return;\n }\n const inputNs = NormalizedSchema.of(operationSchema.input);\n const opTraits = translateTraits(operationSchema.traits ?? {});\n if (opTraits.endpoint) {\n let hostPrefix = opTraits.endpoint?.[0];\n if (typeof hostPrefix === \"string\") {\n const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel);\n for (const [name] of hostLabelInputs) {\n const replacement = input[name];\n if (typeof replacement !== \"string\") {\n throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);\n }\n hostPrefix = hostPrefix.replace(`{${name}}`, replacement);\n }\n request.hostname = hostPrefix + request.hostname;\n }\n }\n }\n deserializeMetadata(output) {\n return {\n httpStatusCode: output.statusCode,\n requestId: output.headers[\"x-amzn-requestid\"] ?? output.headers[\"x-amzn-request-id\"] ?? output.headers[\"x-amz-request-id\"],\n extendedRequestId: output.headers[\"x-amz-id-2\"],\n cfId: output.headers[\"x-amz-cf-id\"],\n };\n }\n async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {\n const eventStreamSerde = await this.loadEventStreamCapability();\n return eventStreamSerde.serializeEventStream({\n eventStream,\n requestSchema,\n initialRequest,\n });\n }\n async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {\n const eventStreamSerde = await this.loadEventStreamCapability();\n return eventStreamSerde.deserializeEventStream({\n response,\n responseSchema,\n initialResponseContainer,\n });\n }\n async loadEventStreamCapability() {\n const { EventStreamSerde } = await import(\"@smithy/core/event-streams\");\n return new EventStreamSerde({\n marshaller: this.getEventStreamMarshaller(),\n serializer: this.serializer,\n deserializer: this.deserializer,\n serdeContext: this.serdeContext,\n defaultContentType: this.getDefaultContentType(),\n });\n }\n getDefaultContentType() {\n throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`);\n }\n async deserializeHttpMessage(schema, context, response, arg4, arg5) {\n void schema;\n void context;\n void response;\n void arg4;\n void arg5;\n return [];\n }\n getEventStreamMarshaller() {\n const context = this.serdeContext;\n if (!context.eventStreamMarshaller) {\n throw new Error(\"@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.\");\n }\n return context.eventStreamMarshaller;\n }\n}\n","import { NormalizedSchema, translateTraits } from \"@smithy/core/schema\";\nimport { splitEvery, splitHeader } from \"@smithy/core/serde\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nimport { sdkStreamMixin } from \"@smithy/util-stream\";\nimport { collectBody } from \"./collect-stream-body\";\nimport { extendedEncodeURIComponent } from \"./extended-encode-uri-component\";\nimport { HttpProtocol } from \"./HttpProtocol\";\nexport class HttpBindingProtocol extends HttpProtocol {\n async serializeRequest(operationSchema, _input, context) {\n const input = {\n ...(_input ?? {}),\n };\n const serializer = this.serializer;\n const query = {};\n const headers = {};\n const endpoint = await context.endpoint();\n const ns = NormalizedSchema.of(operationSchema?.input);\n const schema = ns.getSchema();\n let hasNonHttpBindingMember = false;\n let payload;\n const request = new HttpRequest({\n protocol: \"\",\n hostname: \"\",\n port: undefined,\n path: \"\",\n fragment: undefined,\n query: query,\n headers: headers,\n body: undefined,\n });\n if (endpoint) {\n this.updateServiceEndpoint(request, endpoint);\n this.setHostPrefix(request, operationSchema, input);\n const opTraits = translateTraits(operationSchema.traits);\n if (opTraits.http) {\n request.method = opTraits.http[0];\n const [path, search] = opTraits.http[1].split(\"?\");\n if (request.path == \"/\") {\n request.path = path;\n }\n else {\n request.path += path;\n }\n const traitSearchParams = new URLSearchParams(search ?? \"\");\n Object.assign(query, Object.fromEntries(traitSearchParams));\n }\n }\n for (const [memberName, memberNs] of ns.structIterator()) {\n const memberTraits = memberNs.getMergedTraits() ?? {};\n const inputMemberValue = input[memberName];\n if (inputMemberValue == null && !memberNs.isIdempotencyToken()) {\n if (memberTraits.httpLabel) {\n if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) {\n throw new Error(`No value provided for input HTTP label: ${memberName}.`);\n }\n }\n continue;\n }\n if (memberTraits.httpPayload) {\n const isStreaming = memberNs.isStreaming();\n if (isStreaming) {\n const isEventStream = memberNs.isStructSchema();\n if (isEventStream) {\n if (input[memberName]) {\n payload = await this.serializeEventStream({\n eventStream: input[memberName],\n requestSchema: ns,\n });\n }\n }\n else {\n payload = inputMemberValue;\n }\n }\n else {\n serializer.write(memberNs, inputMemberValue);\n payload = serializer.flush();\n }\n delete input[memberName];\n }\n else if (memberTraits.httpLabel) {\n serializer.write(memberNs, inputMemberValue);\n const replacement = serializer.flush();\n if (request.path.includes(`{${memberName}+}`)) {\n request.path = request.path.replace(`{${memberName}+}`, replacement.split(\"/\").map(extendedEncodeURIComponent).join(\"/\"));\n }\n else if (request.path.includes(`{${memberName}}`)) {\n request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement));\n }\n delete input[memberName];\n }\n else if (memberTraits.httpHeader) {\n serializer.write(memberNs, inputMemberValue);\n headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush());\n delete input[memberName];\n }\n else if (typeof memberTraits.httpPrefixHeaders === \"string\") {\n for (const [key, val] of Object.entries(inputMemberValue)) {\n const amalgam = memberTraits.httpPrefixHeaders + key;\n serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val);\n headers[amalgam.toLowerCase()] = serializer.flush();\n }\n delete input[memberName];\n }\n else if (memberTraits.httpQuery || memberTraits.httpQueryParams) {\n this.serializeQuery(memberNs, inputMemberValue, query);\n delete input[memberName];\n }\n else {\n hasNonHttpBindingMember = true;\n }\n }\n if (hasNonHttpBindingMember && input) {\n serializer.write(schema, input);\n payload = serializer.flush();\n }\n request.headers = headers;\n request.query = query;\n request.body = payload;\n return request;\n }\n serializeQuery(ns, data, query) {\n const serializer = this.serializer;\n const traits = ns.getMergedTraits();\n if (traits.httpQueryParams) {\n for (const [key, val] of Object.entries(data)) {\n if (!(key in query)) {\n const valueSchema = ns.getValueSchema();\n Object.assign(valueSchema.getMergedTraits(), {\n ...traits,\n httpQuery: key,\n httpQueryParams: undefined,\n });\n this.serializeQuery(valueSchema, val, query);\n }\n }\n return;\n }\n if (ns.isListSchema()) {\n const sparse = !!ns.getMergedTraits().sparse;\n const buffer = [];\n for (const item of data) {\n serializer.write([ns.getValueSchema(), traits], item);\n const serializable = serializer.flush();\n if (sparse || serializable !== undefined) {\n buffer.push(serializable);\n }\n }\n query[traits.httpQuery] = buffer;\n }\n else {\n serializer.write([ns, traits], data);\n query[traits.httpQuery] = serializer.flush();\n }\n }\n async deserializeResponse(operationSchema, context, response) {\n const deserializer = this.deserializer;\n const ns = NormalizedSchema.of(operationSchema.output);\n const dataObject = {};\n if (response.statusCode >= 300) {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n Object.assign(dataObject, await deserializer.read(15, bytes));\n }\n await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));\n throw new Error(\"@smithy/core/protocols - HTTP Protocol error handler failed to throw.\");\n }\n for (const header in response.headers) {\n const value = response.headers[header];\n delete response.headers[header];\n response.headers[header.toLowerCase()] = value;\n }\n const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject);\n if (nonHttpBindingMembers.length) {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n const dataFromBody = await deserializer.read(ns, bytes);\n for (const member of nonHttpBindingMembers) {\n dataObject[member] = dataFromBody[member];\n }\n }\n }\n else if (nonHttpBindingMembers.discardResponseBody) {\n await collectBody(response.body, context);\n }\n dataObject.$metadata = this.deserializeMetadata(response);\n return dataObject;\n }\n async deserializeHttpMessage(schema, context, response, arg4, arg5) {\n let dataObject;\n if (arg4 instanceof Set) {\n dataObject = arg5;\n }\n else {\n dataObject = arg4;\n }\n let discardResponseBody = true;\n const deserializer = this.deserializer;\n const ns = NormalizedSchema.of(schema);\n const nonHttpBindingMembers = [];\n for (const [memberName, memberSchema] of ns.structIterator()) {\n const memberTraits = memberSchema.getMemberTraits();\n if (memberTraits.httpPayload) {\n discardResponseBody = false;\n const isStreaming = memberSchema.isStreaming();\n if (isStreaming) {\n const isEventStream = memberSchema.isStructSchema();\n if (isEventStream) {\n dataObject[memberName] = await this.deserializeEventStream({\n response,\n responseSchema: ns,\n });\n }\n else {\n dataObject[memberName] = sdkStreamMixin(response.body);\n }\n }\n else if (response.body) {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n dataObject[memberName] = await deserializer.read(memberSchema, bytes);\n }\n }\n }\n else if (memberTraits.httpHeader) {\n const key = String(memberTraits.httpHeader).toLowerCase();\n const value = response.headers[key];\n if (null != value) {\n if (memberSchema.isListSchema()) {\n const headerListValueSchema = memberSchema.getValueSchema();\n headerListValueSchema.getMergedTraits().httpHeader = key;\n let sections;\n if (headerListValueSchema.isTimestampSchema() &&\n headerListValueSchema.getSchema() === 4) {\n sections = splitEvery(value, \",\", 2);\n }\n else {\n sections = splitHeader(value);\n }\n const list = [];\n for (const section of sections) {\n list.push(await deserializer.read(headerListValueSchema, section.trim()));\n }\n dataObject[memberName] = list;\n }\n else {\n dataObject[memberName] = await deserializer.read(memberSchema, value);\n }\n }\n }\n else if (memberTraits.httpPrefixHeaders !== undefined) {\n dataObject[memberName] = {};\n for (const [header, value] of Object.entries(response.headers)) {\n if (header.startsWith(memberTraits.httpPrefixHeaders)) {\n const valueSchema = memberSchema.getValueSchema();\n valueSchema.getMergedTraits().httpHeader = header;\n dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value);\n }\n }\n }\n else if (memberTraits.httpResponseCode) {\n dataObject[memberName] = response.statusCode;\n }\n else {\n nonHttpBindingMembers.push(memberName);\n }\n }\n nonHttpBindingMembers.discardResponseBody = discardResponseBody;\n return nonHttpBindingMembers;\n }\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nimport { collectBody } from \"./collect-stream-body\";\nimport { HttpProtocol } from \"./HttpProtocol\";\nexport class RpcProtocol extends HttpProtocol {\n async serializeRequest(operationSchema, input, context) {\n const serializer = this.serializer;\n const query = {};\n const headers = {};\n const endpoint = await context.endpoint();\n const ns = NormalizedSchema.of(operationSchema?.input);\n const schema = ns.getSchema();\n let payload;\n const request = new HttpRequest({\n protocol: \"\",\n hostname: \"\",\n port: undefined,\n path: \"/\",\n fragment: undefined,\n query: query,\n headers: headers,\n body: undefined,\n });\n if (endpoint) {\n this.updateServiceEndpoint(request, endpoint);\n this.setHostPrefix(request, operationSchema, input);\n }\n const _input = {\n ...input,\n };\n if (input) {\n const eventStreamMember = ns.getEventStreamMember();\n if (eventStreamMember) {\n if (_input[eventStreamMember]) {\n const initialRequest = {};\n for (const [memberName, memberSchema] of ns.structIterator()) {\n if (memberName !== eventStreamMember && _input[memberName]) {\n serializer.write(memberSchema, _input[memberName]);\n initialRequest[memberName] = serializer.flush();\n }\n }\n payload = await this.serializeEventStream({\n eventStream: _input[eventStreamMember],\n requestSchema: ns,\n initialRequest,\n });\n }\n }\n else {\n serializer.write(schema, _input);\n payload = serializer.flush();\n }\n }\n request.headers = headers;\n request.query = query;\n request.body = payload;\n request.method = \"POST\";\n return request;\n }\n async deserializeResponse(operationSchema, context, response) {\n const deserializer = this.deserializer;\n const ns = NormalizedSchema.of(operationSchema.output);\n const dataObject = {};\n if (response.statusCode >= 300) {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n Object.assign(dataObject, await deserializer.read(15, bytes));\n }\n await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));\n throw new Error(\"@smithy/core/protocols - RPC Protocol error handler failed to throw.\");\n }\n for (const header in response.headers) {\n const value = response.headers[header];\n delete response.headers[header];\n response.headers[header.toLowerCase()] = value;\n }\n const eventStreamMember = ns.getEventStreamMember();\n if (eventStreamMember) {\n dataObject[eventStreamMember] = await this.deserializeEventStream({\n response,\n responseSchema: ns,\n initialResponseContainer: dataObject,\n });\n }\n else {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n Object.assign(dataObject, await deserializer.read(ns, bytes));\n }\n }\n dataObject.$metadata = this.deserializeMetadata(response);\n return dataObject;\n }\n}\n","import { extendedEncodeURIComponent } from \"./extended-encode-uri-component\";\nexport const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {\n if (input != null && input[memberName] !== undefined) {\n const labelValue = labelValueProvider();\n if (labelValue.length <= 0) {\n throw new Error(\"Empty value provided for input HTTP label: \" + memberName + \".\");\n }\n resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel\n ? labelValue\n .split(\"/\")\n .map((segment) => extendedEncodeURIComponent(segment))\n .join(\"/\")\n : extendedEncodeURIComponent(labelValue));\n }\n else {\n throw new Error(\"No value provided for input HTTP label: \" + memberName + \".\");\n }\n return resolvedPath;\n};\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { resolvedPath } from \"./resolve-path\";\nexport function requestBuilder(input, context) {\n return new RequestBuilder(input, context);\n}\nexport class RequestBuilder {\n input;\n context;\n query = {};\n method = \"\";\n headers = {};\n path = \"\";\n body = null;\n hostname = \"\";\n resolvePathStack = [];\n constructor(input, context) {\n this.input = input;\n this.context = context;\n }\n async build() {\n const { hostname, protocol = \"https\", port, path: basePath } = await this.context.endpoint();\n this.path = basePath;\n for (const resolvePath of this.resolvePathStack) {\n resolvePath(this.path);\n }\n return new HttpRequest({\n protocol,\n hostname: this.hostname || hostname,\n port,\n method: this.method,\n path: this.path,\n query: this.query,\n body: this.body,\n headers: this.headers,\n });\n }\n hn(hostname) {\n this.hostname = hostname;\n return this;\n }\n bp(uriLabel) {\n this.resolvePathStack.push((basePath) => {\n this.path = `${basePath?.endsWith(\"/\") ? basePath.slice(0, -1) : basePath || \"\"}` + uriLabel;\n });\n return this;\n }\n p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {\n this.resolvePathStack.push((path) => {\n this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);\n });\n return this;\n }\n h(headers) {\n this.headers = headers;\n return this;\n }\n q(query) {\n this.query = query;\n return this;\n }\n b(body) {\n this.body = body;\n return this;\n }\n m(method) {\n this.method = method;\n return this;\n }\n}\n","export function determineTimestampFormat(ns, settings) {\n if (settings.timestampFormat.useTrait) {\n if (ns.isTimestampSchema() &&\n (ns.getSchema() === 5 ||\n ns.getSchema() === 6 ||\n ns.getSchema() === 7)) {\n return ns.getSchema();\n }\n }\n const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits();\n const bindingFormat = settings.httpBindings\n ? typeof httpPrefixHeaders === \"string\" || Boolean(httpHeader)\n ? 6\n : Boolean(httpQuery) || Boolean(httpLabel)\n ? 5\n : undefined\n : undefined;\n return bindingFormat ?? settings.timestampFormat.default;\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nimport { _parseEpochTimestamp, _parseRfc3339DateTimeWithOffset, _parseRfc7231DateTime, LazyJsonString, NumericValue, splitHeader, } from \"@smithy/core/serde\";\nimport { fromBase64 } from \"@smithy/util-base64\";\nimport { toUtf8 } from \"@smithy/util-utf8\";\nimport { SerdeContext } from \"../SerdeContext\";\nimport { determineTimestampFormat } from \"./determineTimestampFormat\";\nexport class FromStringShapeDeserializer extends SerdeContext {\n settings;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n read(_schema, data) {\n const ns = NormalizedSchema.of(_schema);\n if (ns.isListSchema()) {\n return splitHeader(data).map((item) => this.read(ns.getValueSchema(), item));\n }\n if (ns.isBlobSchema()) {\n return (this.serdeContext?.base64Decoder ?? fromBase64)(data);\n }\n if (ns.isTimestampSchema()) {\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n return _parseRfc3339DateTimeWithOffset(data);\n case 6:\n return _parseRfc7231DateTime(data);\n case 7:\n return _parseEpochTimestamp(data);\n default:\n console.warn(\"Missing timestamp format, parsing value with Date constructor:\", data);\n return new Date(data);\n }\n }\n if (ns.isStringSchema()) {\n const mediaType = ns.getMergedTraits().mediaType;\n let intermediateValue = data;\n if (mediaType) {\n if (ns.getMergedTraits().httpHeader) {\n intermediateValue = this.base64ToUtf8(intermediateValue);\n }\n const isJson = mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n if (isJson) {\n intermediateValue = LazyJsonString.from(intermediateValue);\n }\n return intermediateValue;\n }\n }\n if (ns.isNumericSchema()) {\n return Number(data);\n }\n if (ns.isBigIntegerSchema()) {\n return BigInt(data);\n }\n if (ns.isBigDecimalSchema()) {\n return new NumericValue(data, \"bigDecimal\");\n }\n if (ns.isBooleanSchema()) {\n return String(data).toLowerCase() === \"true\";\n }\n return data;\n }\n base64ToUtf8(base64String) {\n return (this.serdeContext?.utf8Encoder ?? toUtf8)((this.serdeContext?.base64Decoder ?? fromBase64)(base64String));\n }\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nimport { SerdeContext } from \"../SerdeContext\";\nimport { FromStringShapeDeserializer } from \"./FromStringShapeDeserializer\";\nexport class HttpInterceptingShapeDeserializer extends SerdeContext {\n codecDeserializer;\n stringDeserializer;\n constructor(codecDeserializer, codecSettings) {\n super();\n this.codecDeserializer = codecDeserializer;\n this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);\n }\n setSerdeContext(serdeContext) {\n this.stringDeserializer.setSerdeContext(serdeContext);\n this.codecDeserializer.setSerdeContext(serdeContext);\n this.serdeContext = serdeContext;\n }\n read(schema, data) {\n const ns = NormalizedSchema.of(schema);\n const traits = ns.getMergedTraits();\n const toString = this.serdeContext?.utf8Encoder ?? toUtf8;\n if (traits.httpHeader || traits.httpResponseCode) {\n return this.stringDeserializer.read(ns, toString(data));\n }\n if (traits.httpPayload) {\n if (ns.isBlobSchema()) {\n const toBytes = this.serdeContext?.utf8Decoder ?? fromUtf8;\n if (typeof data === \"string\") {\n return toBytes(data);\n }\n return data;\n }\n else if (ns.isStringSchema()) {\n if (\"byteLength\" in data) {\n return toString(data);\n }\n return data;\n }\n }\n return this.codecDeserializer.read(ns, data);\n }\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nimport { dateToUtcString, generateIdempotencyToken, LazyJsonString, quoteHeader } from \"@smithy/core/serde\";\nimport { toBase64 } from \"@smithy/util-base64\";\nimport { SerdeContext } from \"../SerdeContext\";\nimport { determineTimestampFormat } from \"./determineTimestampFormat\";\nexport class ToStringShapeSerializer extends SerdeContext {\n settings;\n stringBuffer = \"\";\n constructor(settings) {\n super();\n this.settings = settings;\n }\n write(schema, value) {\n const ns = NormalizedSchema.of(schema);\n switch (typeof value) {\n case \"object\":\n if (value === null) {\n this.stringBuffer = \"null\";\n return;\n }\n if (ns.isTimestampSchema()) {\n if (!(value instanceof Date)) {\n throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`);\n }\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n this.stringBuffer = value.toISOString().replace(\".000Z\", \"Z\");\n break;\n case 6:\n this.stringBuffer = dateToUtcString(value);\n break;\n case 7:\n this.stringBuffer = String(value.getTime() / 1000);\n break;\n default:\n console.warn(\"Missing timestamp format, using epoch seconds\", value);\n this.stringBuffer = String(value.getTime() / 1000);\n }\n return;\n }\n if (ns.isBlobSchema() && \"byteLength\" in value) {\n this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(value);\n return;\n }\n if (ns.isListSchema() && Array.isArray(value)) {\n let buffer = \"\";\n for (const item of value) {\n this.write([ns.getValueSchema(), ns.getMergedTraits()], item);\n const headerItem = this.flush();\n const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem);\n if (buffer !== \"\") {\n buffer += \", \";\n }\n buffer += serialized;\n }\n this.stringBuffer = buffer;\n return;\n }\n this.stringBuffer = JSON.stringify(value, null, 2);\n break;\n case \"string\":\n const mediaType = ns.getMergedTraits().mediaType;\n let intermediateValue = value;\n if (mediaType) {\n const isJson = mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n if (isJson) {\n intermediateValue = LazyJsonString.from(intermediateValue);\n }\n if (ns.getMergedTraits().httpHeader) {\n this.stringBuffer = (this.serdeContext?.base64Encoder ?? toBase64)(intermediateValue.toString());\n return;\n }\n }\n this.stringBuffer = value;\n break;\n default:\n if (ns.isIdempotencyToken()) {\n this.stringBuffer = generateIdempotencyToken();\n }\n else {\n this.stringBuffer = String(value);\n }\n }\n }\n flush() {\n const buffer = this.stringBuffer;\n this.stringBuffer = \"\";\n return buffer;\n }\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nimport { ToStringShapeSerializer } from \"./ToStringShapeSerializer\";\nexport class HttpInterceptingShapeSerializer {\n codecSerializer;\n stringSerializer;\n buffer;\n constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) {\n this.codecSerializer = codecSerializer;\n this.stringSerializer = stringSerializer;\n }\n setSerdeContext(serdeContext) {\n this.codecSerializer.setSerdeContext(serdeContext);\n this.stringSerializer.setSerdeContext(serdeContext);\n }\n write(schema, value) {\n const ns = NormalizedSchema.of(schema);\n const traits = ns.getMergedTraits();\n if (traits.httpHeader || traits.httpLabel || traits.httpQuery) {\n this.stringSerializer.write(ns, value);\n this.buffer = this.stringSerializer.flush();\n return;\n }\n return this.codecSerializer.write(ns, value);\n }\n flush() {\n if (this.buffer !== undefined) {\n const buffer = this.buffer;\n this.buffer = undefined;\n return buffer;\n }\n return this.codecSerializer.flush();\n }\n}\n","export * from \"./collect-stream-body\";\nexport * from \"./extended-encode-uri-component\";\nexport * from \"./HttpBindingProtocol\";\nexport * from \"./HttpProtocol\";\nexport * from \"./RpcProtocol\";\nexport * from \"./requestBuilder\";\nexport * from \"./resolve-path\";\nexport * from \"./serde/FromStringShapeDeserializer\";\nexport * from \"./serde/HttpInterceptingShapeDeserializer\";\nexport * from \"./serde/HttpInterceptingShapeSerializer\";\nexport * from \"./serde/ToStringShapeSerializer\";\nexport * from \"./serde/determineTimestampFormat\";\nexport * from \"./SerdeContext\";\n","export { requestBuilder } from \"@smithy/core/protocols\";\n","export function setFeature(context, feature, value) {\n if (!context.__smithy_context) {\n context.__smithy_context = {\n features: {},\n };\n }\n else if (!context.__smithy_context.features) {\n context.__smithy_context.features = {};\n }\n context.__smithy_context.features[feature] = value;\n}\n","export class DefaultIdentityProviderConfig {\n authSchemes = new Map();\n constructor(config) {\n for (const [key, value] of Object.entries(config)) {\n if (value !== undefined) {\n this.authSchemes.set(key, value);\n }\n }\n }\n getIdentityProvider(schemeId) {\n return this.authSchemes.get(schemeId);\n }\n}\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { HttpApiKeyAuthLocation } from \"@smithy/types\";\nexport class HttpApiKeyAuthSigner {\n async sign(httpRequest, identity, signingProperties) {\n if (!signingProperties) {\n throw new Error(\"request could not be signed with `apiKey` since the `name` and `in` signer properties are missing\");\n }\n if (!signingProperties.name) {\n throw new Error(\"request could not be signed with `apiKey` since the `name` signer property is missing\");\n }\n if (!signingProperties.in) {\n throw new Error(\"request could not be signed with `apiKey` since the `in` signer property is missing\");\n }\n if (!identity.apiKey) {\n throw new Error(\"request could not be signed with `apiKey` since the `apiKey` is not defined\");\n }\n const clonedRequest = HttpRequest.clone(httpRequest);\n if (signingProperties.in === HttpApiKeyAuthLocation.QUERY) {\n clonedRequest.query[signingProperties.name] = identity.apiKey;\n }\n else if (signingProperties.in === HttpApiKeyAuthLocation.HEADER) {\n clonedRequest.headers[signingProperties.name] = signingProperties.scheme\n ? `${signingProperties.scheme} ${identity.apiKey}`\n : identity.apiKey;\n }\n else {\n throw new Error(\"request can only be signed with `apiKey` locations `query` or `header`, \" +\n \"but found: `\" +\n signingProperties.in +\n \"`\");\n }\n return clonedRequest;\n }\n}\n","import { HttpRequest } from \"@smithy/protocol-http\";\nexport class HttpBearerAuthSigner {\n async sign(httpRequest, identity, signingProperties) {\n const clonedRequest = HttpRequest.clone(httpRequest);\n if (!identity.token) {\n throw new Error(\"request could not be signed with `token` since the `token` is not defined\");\n }\n clonedRequest.headers[\"Authorization\"] = `Bearer ${identity.token}`;\n return clonedRequest;\n }\n}\n","export class NoAuthSigner {\n async sign(httpRequest, identity, signingProperties) {\n return httpRequest;\n }\n}\n","export * from \"./httpApiKeyAuth\";\nexport * from \"./httpBearerAuth\";\nexport * from \"./noAuth\";\n","export const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) {\n return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;\n};\nexport const EXPIRATION_MS = 300_000;\nexport const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);\nexport const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined;\nexport const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {\n if (provider === undefined) {\n return undefined;\n }\n const normalizedProvider = typeof provider !== \"function\" ? async () => Promise.resolve(provider) : provider;\n let resolved;\n let pending;\n let hasResult;\n let isConstant = false;\n const coalesceProvider = async (options) => {\n if (!pending) {\n pending = normalizedProvider(options);\n }\n try {\n resolved = await pending;\n hasResult = true;\n isConstant = false;\n }\n finally {\n pending = undefined;\n }\n return resolved;\n };\n if (isExpired === undefined) {\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider(options);\n }\n return resolved;\n };\n }\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider(options);\n }\n if (isConstant) {\n return resolved;\n }\n if (!requiresRefresh(resolved)) {\n isConstant = true;\n return resolved;\n }\n if (isExpired(resolved)) {\n await coalesceProvider(options);\n return resolved;\n }\n return resolved;\n };\n};\n","export * from \"./DefaultIdentityProviderConfig\";\nexport * from \"./httpAuthSchemes\";\nexport * from \"./memoizeIdentityProvider\";\n","export * from \"./getSmithyContext\";\nexport * from \"./middleware-http-auth-scheme\";\nexport * from \"./middleware-http-signing\";\nexport * from \"./normalizeProvider\";\nexport { createPaginator } from \"./pagination/createPaginator\";\nexport * from \"./request-builder/requestBuilder\";\nexport * from \"./setFeature\";\nexport * from \"./util-identity-and-auth\";\n","export class ProviderError extends Error {\n name = \"ProviderError\";\n tryNextLink;\n constructor(message, options = true) {\n let logger;\n let tryNextLink = true;\n if (typeof options === \"boolean\") {\n logger = undefined;\n tryNextLink = options;\n }\n else if (options != null && typeof options === \"object\") {\n logger = options.logger;\n tryNextLink = options.tryNextLink ?? true;\n }\n super(message);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, ProviderError.prototype);\n logger?.debug?.(`@smithy/property-provider ${tryNextLink ? \"->\" : \"(!)\"} ${message}`);\n }\n static from(error, options = true) {\n return Object.assign(new this(error.message, options), error);\n }\n}\n","import { ProviderError } from \"./ProviderError\";\nexport class CredentialsProviderError extends ProviderError {\n name = \"CredentialsProviderError\";\n constructor(message, options = true) {\n super(message, options);\n Object.setPrototypeOf(this, CredentialsProviderError.prototype);\n }\n}\n","import { ProviderError } from \"./ProviderError\";\nexport class TokenProviderError extends ProviderError {\n name = \"TokenProviderError\";\n constructor(message, options = true) {\n super(message, options);\n Object.setPrototypeOf(this, TokenProviderError.prototype);\n }\n}\n","import { ProviderError } from \"./ProviderError\";\nexport const chain = (...providers) => async () => {\n if (providers.length === 0) {\n throw new ProviderError(\"No providers in chain\");\n }\n let lastProviderError;\n for (const provider of providers) {\n try {\n const credentials = await provider();\n return credentials;\n }\n catch (err) {\n lastProviderError = err;\n if (err?.tryNextLink) {\n continue;\n }\n throw err;\n }\n }\n throw lastProviderError;\n};\n","export const fromStatic = (staticValue) => () => Promise.resolve(staticValue);\n","export const memoize = (provider, isExpired, requiresRefresh) => {\n let resolved;\n let pending;\n let hasResult;\n let isConstant = false;\n const coalesceProvider = async () => {\n if (!pending) {\n pending = provider();\n }\n try {\n resolved = await pending;\n hasResult = true;\n isConstant = false;\n }\n finally {\n pending = undefined;\n }\n return resolved;\n };\n if (isExpired === undefined) {\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider();\n }\n return resolved;\n };\n }\n return async (options) => {\n if (!hasResult || options?.forceRefresh) {\n resolved = await coalesceProvider();\n }\n if (isConstant) {\n return resolved;\n }\n if (requiresRefresh && !requiresRefresh(resolved)) {\n isConstant = true;\n return resolved;\n }\n if (isExpired(resolved)) {\n await coalesceProvider();\n return resolved;\n }\n return resolved;\n };\n};\n","export * from \"./CredentialsProviderError\";\nexport * from \"./ProviderError\";\nexport * from \"./TokenProviderError\";\nexport * from \"./chain\";\nexport * from \"./fromStatic\";\nexport * from \"./memoize\";\n","import { normalizeProvider } from \"@smithy/core\";\nimport { ProviderError } from \"@smithy/property-provider\";\nexport const resolveAwsSdkSigV4AConfig = (config) => {\n config.sigv4aSigningRegionSet = normalizeProvider(config.sigv4aSigningRegionSet);\n return config;\n};\nexport const NODE_SIGV4A_CONFIG_OPTIONS = {\n environmentVariableSelector(env) {\n if (env.AWS_SIGV4A_SIGNING_REGION_SET) {\n return env.AWS_SIGV4A_SIGNING_REGION_SET.split(\",\").map((_) => _.trim());\n }\n throw new ProviderError(\"AWS_SIGV4A_SIGNING_REGION_SET not set in env.\", {\n tryNextLink: true,\n });\n },\n configFileSelector(profile) {\n if (profile.sigv4a_signing_region_set) {\n return (profile.sigv4a_signing_region_set ?? \"\").split(\",\").map((_) => _.trim());\n }\n throw new ProviderError(\"sigv4a_signing_region_set not set in profile.\", {\n tryNextLink: true,\n });\n },\n default: undefined,\n};\n","export const ALGORITHM_QUERY_PARAM = \"X-Amz-Algorithm\";\nexport const CREDENTIAL_QUERY_PARAM = \"X-Amz-Credential\";\nexport const AMZ_DATE_QUERY_PARAM = \"X-Amz-Date\";\nexport const SIGNED_HEADERS_QUERY_PARAM = \"X-Amz-SignedHeaders\";\nexport const EXPIRES_QUERY_PARAM = \"X-Amz-Expires\";\nexport const SIGNATURE_QUERY_PARAM = \"X-Amz-Signature\";\nexport const TOKEN_QUERY_PARAM = \"X-Amz-Security-Token\";\nexport const REGION_SET_PARAM = \"X-Amz-Region-Set\";\nexport const AUTH_HEADER = \"authorization\";\nexport const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();\nexport const DATE_HEADER = \"date\";\nexport const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];\nexport const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();\nexport const SHA256_HEADER = \"x-amz-content-sha256\";\nexport const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();\nexport const HOST_HEADER = \"host\";\nexport const ALWAYS_UNSIGNABLE_HEADERS = {\n authorization: true,\n \"cache-control\": true,\n connection: true,\n expect: true,\n from: true,\n \"keep-alive\": true,\n \"max-forwards\": true,\n pragma: true,\n referer: true,\n te: true,\n trailer: true,\n \"transfer-encoding\": true,\n upgrade: true,\n \"user-agent\": true,\n \"x-amzn-trace-id\": true,\n};\nexport const PROXY_HEADER_PATTERN = /^proxy-/;\nexport const SEC_HEADER_PATTERN = /^sec-/;\nexport const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];\nexport const ALGORITHM_IDENTIFIER = \"AWS4-HMAC-SHA256\";\nexport const ALGORITHM_IDENTIFIER_V4A = \"AWS4-ECDSA-P256-SHA256\";\nexport const EVENT_ALGORITHM_IDENTIFIER = \"AWS4-HMAC-SHA256-PAYLOAD\";\nexport const UNSIGNED_PAYLOAD = \"UNSIGNED-PAYLOAD\";\nexport const MAX_CACHE_SIZE = 50;\nexport const KEY_TYPE_IDENTIFIER = \"aws4_request\";\nexport const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;\n","import { toHex } from \"@smithy/util-hex-encoding\";\nimport { toUint8Array } from \"@smithy/util-utf8\";\nimport { KEY_TYPE_IDENTIFIER, MAX_CACHE_SIZE } from \"./constants\";\nconst signingKeyCache = {};\nconst cacheQueue = [];\nexport const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;\nexport const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {\n const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);\n const cacheKey = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`;\n if (cacheKey in signingKeyCache) {\n return signingKeyCache[cacheKey];\n }\n cacheQueue.push(cacheKey);\n while (cacheQueue.length > MAX_CACHE_SIZE) {\n delete signingKeyCache[cacheQueue.shift()];\n }\n let key = `AWS4${credentials.secretAccessKey}`;\n for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {\n key = await hmac(sha256Constructor, key, signable);\n }\n return (signingKeyCache[cacheKey] = key);\n};\nexport const clearCredentialCache = () => {\n cacheQueue.length = 0;\n Object.keys(signingKeyCache).forEach((cacheKey) => {\n delete signingKeyCache[cacheKey];\n });\n};\nconst hmac = (ctor, secret, data) => {\n const hash = new ctor(secret);\n hash.update(toUint8Array(data));\n return hash.digest();\n};\n","import { ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN } from \"./constants\";\nexport const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {\n const canonical = {};\n for (const headerName of Object.keys(headers).sort()) {\n if (headers[headerName] == undefined) {\n continue;\n }\n const canonicalHeaderName = headerName.toLowerCase();\n if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS ||\n unsignableHeaders?.has(canonicalHeaderName) ||\n PROXY_HEADER_PATTERN.test(canonicalHeaderName) ||\n SEC_HEADER_PATTERN.test(canonicalHeaderName)) {\n if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) {\n continue;\n }\n }\n canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\\s+/g, \" \");\n }\n return canonical;\n};\n","import { isArrayBuffer } from \"@smithy/is-array-buffer\";\nimport { toHex } from \"@smithy/util-hex-encoding\";\nimport { toUint8Array } from \"@smithy/util-utf8\";\nimport { SHA256_HEADER, UNSIGNED_PAYLOAD } from \"./constants\";\nexport const getPayloadHash = async ({ headers, body }, hashConstructor) => {\n for (const headerName of Object.keys(headers)) {\n if (headerName.toLowerCase() === SHA256_HEADER) {\n return headers[headerName];\n }\n }\n if (body == undefined) {\n return \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\";\n }\n else if (typeof body === \"string\" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {\n const hashCtor = new hashConstructor();\n hashCtor.update(toUint8Array(body));\n return toHex(await hashCtor.digest());\n }\n return UNSIGNED_PAYLOAD;\n};\n","import { fromHex, toHex } from \"@smithy/util-hex-encoding\";\nimport { fromUtf8 } from \"@smithy/util-utf8\";\nexport class HeaderFormatter {\n format(headers) {\n const chunks = [];\n for (const headerName of Object.keys(headers)) {\n const bytes = fromUtf8(headerName);\n chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));\n }\n const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));\n let position = 0;\n for (const chunk of chunks) {\n out.set(chunk, position);\n position += chunk.byteLength;\n }\n return out;\n }\n formatHeaderValue(header) {\n switch (header.type) {\n case \"boolean\":\n return Uint8Array.from([header.value ? 0 : 1]);\n case \"byte\":\n return Uint8Array.from([2, header.value]);\n case \"short\":\n const shortView = new DataView(new ArrayBuffer(3));\n shortView.setUint8(0, 3);\n shortView.setInt16(1, header.value, false);\n return new Uint8Array(shortView.buffer);\n case \"integer\":\n const intView = new DataView(new ArrayBuffer(5));\n intView.setUint8(0, 4);\n intView.setInt32(1, header.value, false);\n return new Uint8Array(intView.buffer);\n case \"long\":\n const longBytes = new Uint8Array(9);\n longBytes[0] = 5;\n longBytes.set(header.value.bytes, 1);\n return longBytes;\n case \"binary\":\n const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));\n binView.setUint8(0, 6);\n binView.setUint16(1, header.value.byteLength, false);\n const binBytes = new Uint8Array(binView.buffer);\n binBytes.set(header.value, 3);\n return binBytes;\n case \"string\":\n const utf8Bytes = fromUtf8(header.value);\n const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));\n strView.setUint8(0, 7);\n strView.setUint16(1, utf8Bytes.byteLength, false);\n const strBytes = new Uint8Array(strView.buffer);\n strBytes.set(utf8Bytes, 3);\n return strBytes;\n case \"timestamp\":\n const tsBytes = new Uint8Array(9);\n tsBytes[0] = 8;\n tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);\n return tsBytes;\n case \"uuid\":\n if (!UUID_PATTERN.test(header.value)) {\n throw new Error(`Invalid UUID received: ${header.value}`);\n }\n const uuidBytes = new Uint8Array(17);\n uuidBytes[0] = 9;\n uuidBytes.set(fromHex(header.value.replace(/\\-/g, \"\")), 1);\n return uuidBytes;\n }\n }\n}\nvar HEADER_VALUE_TYPE;\n(function (HEADER_VALUE_TYPE) {\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"boolTrue\"] = 0] = \"boolTrue\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"boolFalse\"] = 1] = \"boolFalse\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"byte\"] = 2] = \"byte\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"short\"] = 3] = \"short\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"integer\"] = 4] = \"integer\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"long\"] = 5] = \"long\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"byteArray\"] = 6] = \"byteArray\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"string\"] = 7] = \"string\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"timestamp\"] = 8] = \"timestamp\";\n HEADER_VALUE_TYPE[HEADER_VALUE_TYPE[\"uuid\"] = 9] = \"uuid\";\n})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));\nconst UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;\nexport class Int64 {\n bytes;\n constructor(bytes) {\n this.bytes = bytes;\n if (bytes.byteLength !== 8) {\n throw new Error(\"Int64 buffers must be exactly 8 bytes\");\n }\n }\n static fromNumber(number) {\n if (number > 9_223_372_036_854_775_807 || number < -9_223_372_036_854_775_808) {\n throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);\n }\n const bytes = new Uint8Array(8);\n for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) {\n bytes[i] = remaining;\n }\n if (number < 0) {\n negate(bytes);\n }\n return new Int64(bytes);\n }\n valueOf() {\n const bytes = this.bytes.slice(0);\n const negative = bytes[0] & 0b10000000;\n if (negative) {\n negate(bytes);\n }\n return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);\n }\n toString() {\n return String(this.valueOf());\n }\n}\nfunction negate(bytes) {\n for (let i = 0; i < 8; i++) {\n bytes[i] ^= 0xff;\n }\n for (let i = 7; i > -1; i--) {\n bytes[i]++;\n if (bytes[i] !== 0)\n break;\n }\n}\n","export const hasHeader = (soughtHeader, headers) => {\n soughtHeader = soughtHeader.toLowerCase();\n for (const headerName of Object.keys(headers)) {\n if (soughtHeader === headerName.toLowerCase()) {\n return true;\n }\n }\n return false;\n};\nexport const getHeaderValue = (soughtHeader, headers) => {\n soughtHeader = soughtHeader.toLowerCase();\n for (const headerName of Object.keys(headers)) {\n if (soughtHeader === headerName.toLowerCase()) {\n return headers[headerName];\n }\n }\n return undefined;\n};\nexport const deleteHeader = (soughtHeader, headers) => {\n soughtHeader = soughtHeader.toLowerCase();\n for (const headerName of Object.keys(headers)) {\n if (soughtHeader === headerName.toLowerCase()) {\n delete headers[headerName];\n }\n }\n};\n","import { HttpRequest } from \"@smithy/protocol-http\";\nexport const moveHeadersToQuery = (request, options = {}) => {\n const { headers, query = {} } = HttpRequest.clone(request);\n for (const name of Object.keys(headers)) {\n const lname = name.toLowerCase();\n if ((lname.slice(0, 6) === \"x-amz-\" && !options.unhoistableHeaders?.has(lname)) ||\n options.hoistableHeaders?.has(lname)) {\n query[name] = headers[name];\n delete headers[name];\n }\n }\n return {\n ...request,\n headers,\n query,\n };\n};\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { GENERATED_HEADERS } from \"./constants\";\nexport const prepareRequest = (request) => {\n request = HttpRequest.clone(request);\n for (const headerName of Object.keys(request.headers)) {\n if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {\n delete request.headers[headerName];\n }\n }\n return request;\n};\n","import { escapeUri } from \"@smithy/util-uri-escape\";\nimport { SIGNATURE_HEADER } from \"./constants\";\nexport const getCanonicalQuery = ({ query = {} }) => {\n const keys = [];\n const serialized = {};\n for (const key of Object.keys(query)) {\n if (key.toLowerCase() === SIGNATURE_HEADER) {\n continue;\n }\n const encodedKey = escapeUri(key);\n keys.push(encodedKey);\n const value = query[key];\n if (typeof value === \"string\") {\n serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`;\n }\n else if (Array.isArray(value)) {\n serialized[encodedKey] = value\n .slice(0)\n .reduce((encoded, value) => encoded.concat([`${encodedKey}=${escapeUri(value)}`]), [])\n .sort()\n .join(\"&\");\n }\n }\n return keys\n .sort()\n .map((key) => serialized[key])\n .filter((serialized) => serialized)\n .join(\"&\");\n};\n","export const iso8601 = (time) => toDate(time)\n .toISOString()\n .replace(/\\.\\d{3}Z$/, \"Z\");\nexport const toDate = (time) => {\n if (typeof time === \"number\") {\n return new Date(time * 1000);\n }\n if (typeof time === \"string\") {\n if (Number(time)) {\n return new Date(Number(time) * 1000);\n }\n return new Date(time);\n }\n return time;\n};\n","import { toHex } from \"@smithy/util-hex-encoding\";\nimport { normalizeProvider } from \"@smithy/util-middleware\";\nimport { escapeUri } from \"@smithy/util-uri-escape\";\nimport { toUint8Array } from \"@smithy/util-utf8\";\nimport { getCanonicalQuery } from \"./getCanonicalQuery\";\nimport { iso8601 } from \"./utilDate\";\nexport class SignatureV4Base {\n service;\n regionProvider;\n credentialProvider;\n sha256;\n uriEscapePath;\n applyChecksum;\n constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) {\n this.service = service;\n this.sha256 = sha256;\n this.uriEscapePath = uriEscapePath;\n this.applyChecksum = typeof applyChecksum === \"boolean\" ? applyChecksum : true;\n this.regionProvider = normalizeProvider(region);\n this.credentialProvider = normalizeProvider(credentials);\n }\n createCanonicalRequest(request, canonicalHeaders, payloadHash) {\n const sortedHeaders = Object.keys(canonicalHeaders).sort();\n return `${request.method}\n${this.getCanonicalPath(request)}\n${getCanonicalQuery(request)}\n${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join(\"\\n\")}\n\n${sortedHeaders.join(\";\")}\n${payloadHash}`;\n }\n async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {\n const hash = new this.sha256();\n hash.update(toUint8Array(canonicalRequest));\n const hashedRequest = await hash.digest();\n return `${algorithmIdentifier}\n${longDate}\n${credentialScope}\n${toHex(hashedRequest)}`;\n }\n getCanonicalPath({ path }) {\n if (this.uriEscapePath) {\n const normalizedPathSegments = [];\n for (const pathSegment of path.split(\"/\")) {\n if (pathSegment?.length === 0)\n continue;\n if (pathSegment === \".\")\n continue;\n if (pathSegment === \"..\") {\n normalizedPathSegments.pop();\n }\n else {\n normalizedPathSegments.push(pathSegment);\n }\n }\n const normalizedPath = `${path?.startsWith(\"/\") ? \"/\" : \"\"}${normalizedPathSegments.join(\"/\")}${normalizedPathSegments.length > 0 && path?.endsWith(\"/\") ? \"/\" : \"\"}`;\n const doubleEncoded = escapeUri(normalizedPath);\n return doubleEncoded.replace(/%2F/g, \"/\");\n }\n return path;\n }\n validateResolvedCredentials(credentials) {\n if (typeof credentials !== \"object\" ||\n typeof credentials.accessKeyId !== \"string\" ||\n typeof credentials.secretAccessKey !== \"string\") {\n throw new Error(\"Resolved credential object is not valid\");\n }\n }\n formatDate(now) {\n const longDate = iso8601(now).replace(/[\\-:]/g, \"\");\n return {\n longDate,\n shortDate: longDate.slice(0, 8),\n };\n }\n getCanonicalHeaderList(headers) {\n return Object.keys(headers).sort().join(\";\");\n }\n}\n","import { toHex } from \"@smithy/util-hex-encoding\";\nimport { toUint8Array } from \"@smithy/util-utf8\";\nimport { ALGORITHM_IDENTIFIER, ALGORITHM_QUERY_PARAM, AMZ_DATE_HEADER, AMZ_DATE_QUERY_PARAM, AUTH_HEADER, CREDENTIAL_QUERY_PARAM, EVENT_ALGORITHM_IDENTIFIER, EXPIRES_QUERY_PARAM, MAX_PRESIGNED_TTL, SHA256_HEADER, SIGNATURE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, TOKEN_HEADER, TOKEN_QUERY_PARAM, } from \"./constants\";\nimport { createScope, getSigningKey } from \"./credentialDerivation\";\nimport { getCanonicalHeaders } from \"./getCanonicalHeaders\";\nimport { getPayloadHash } from \"./getPayloadHash\";\nimport { HeaderFormatter } from \"./HeaderFormatter\";\nimport { hasHeader } from \"./headerUtil\";\nimport { moveHeadersToQuery } from \"./moveHeadersToQuery\";\nimport { prepareRequest } from \"./prepareRequest\";\nimport { SignatureV4Base } from \"./SignatureV4Base\";\nexport class SignatureV4 extends SignatureV4Base {\n headerFormatter = new HeaderFormatter();\n constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) {\n super({\n applyChecksum,\n credentials,\n region,\n service,\n sha256,\n uriEscapePath,\n });\n }\n async presign(originalRequest, options = {}) {\n const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options;\n const credentials = await this.credentialProvider();\n this.validateResolvedCredentials(credentials);\n const region = signingRegion ?? (await this.regionProvider());\n const { longDate, shortDate } = this.formatDate(signingDate);\n if (expiresIn > MAX_PRESIGNED_TTL) {\n return Promise.reject(\"Signature version 4 presigned URLs\" + \" must have an expiration date less than one week in\" + \" the future\");\n }\n const scope = createScope(shortDate, region, signingService ?? this.service);\n const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });\n if (credentials.sessionToken) {\n request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;\n }\n request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;\n request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;\n request.query[AMZ_DATE_QUERY_PARAM] = longDate;\n request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);\n const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);\n request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);\n request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));\n return request;\n }\n async sign(toSign, options) {\n if (typeof toSign === \"string\") {\n return this.signString(toSign, options);\n }\n else if (toSign.headers && toSign.payload) {\n return this.signEvent(toSign, options);\n }\n else if (toSign.message) {\n return this.signMessage(toSign, options);\n }\n else {\n return this.signRequest(toSign, options);\n }\n }\n async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) {\n const region = signingRegion ?? (await this.regionProvider());\n const { shortDate, longDate } = this.formatDate(signingDate);\n const scope = createScope(shortDate, region, signingService ?? this.service);\n const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);\n const hash = new this.sha256();\n hash.update(headers);\n const hashedHeaders = toHex(await hash.digest());\n const stringToSign = [\n EVENT_ALGORITHM_IDENTIFIER,\n longDate,\n scope,\n priorSignature,\n hashedHeaders,\n hashedPayload,\n ].join(\"\\n\");\n return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });\n }\n async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) {\n const promise = this.signEvent({\n headers: this.headerFormatter.format(signableMessage.message.headers),\n payload: signableMessage.message.body,\n }, {\n signingDate,\n signingRegion,\n signingService,\n priorSignature: signableMessage.priorSignature,\n });\n return promise.then((signature) => {\n return { message: signableMessage.message, signature };\n });\n }\n async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) {\n const credentials = await this.credentialProvider();\n this.validateResolvedCredentials(credentials);\n const region = signingRegion ?? (await this.regionProvider());\n const { shortDate } = this.formatDate(signingDate);\n const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));\n hash.update(toUint8Array(stringToSign));\n return toHex(await hash.digest());\n }\n async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) {\n const credentials = await this.credentialProvider();\n this.validateResolvedCredentials(credentials);\n const region = signingRegion ?? (await this.regionProvider());\n const request = prepareRequest(requestToSign);\n const { longDate, shortDate } = this.formatDate(signingDate);\n const scope = createScope(shortDate, region, signingService ?? this.service);\n request.headers[AMZ_DATE_HEADER] = longDate;\n if (credentials.sessionToken) {\n request.headers[TOKEN_HEADER] = credentials.sessionToken;\n }\n const payloadHash = await getPayloadHash(request, this.sha256);\n if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {\n request.headers[SHA256_HEADER] = payloadHash;\n }\n const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);\n const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash));\n request.headers[AUTH_HEADER] =\n `${ALGORITHM_IDENTIFIER} ` +\n `Credential=${credentials.accessKeyId}/${scope}, ` +\n `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` +\n `Signature=${signature}`;\n return request;\n }\n async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {\n const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER);\n const hash = new this.sha256(await keyPromise);\n hash.update(toUint8Array(stringToSign));\n return toHex(await hash.digest());\n }\n getSigningKey(credentials, region, shortDate, service) {\n return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);\n }\n}\n","export const signatureV4aContainer = {\n SignatureV4a: null,\n};\n","export * from \"./SignatureV4\";\nexport * from \"./constants\";\nexport { getCanonicalHeaders } from \"./getCanonicalHeaders\";\nexport { getCanonicalQuery } from \"./getCanonicalQuery\";\nexport { getPayloadHash } from \"./getPayloadHash\";\nexport { moveHeadersToQuery } from \"./moveHeadersToQuery\";\nexport { prepareRequest } from \"./prepareRequest\";\nexport * from \"./credentialDerivation\";\nexport { SignatureV4Base } from \"./SignatureV4Base\";\nexport { hasHeader } from \"./headerUtil\";\nexport * from \"./signature-v4a-container\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { doesIdentityRequireRefresh, isIdentityExpired, memoizeIdentityProvider, normalizeProvider, } from \"@smithy/core\";\nimport { SignatureV4 } from \"@smithy/signature-v4\";\nexport const resolveAwsSdkSigV4Config = (config) => {\n let inputCredentials = config.credentials;\n let isUserSupplied = !!config.credentials;\n let resolvedCredentials = undefined;\n Object.defineProperty(config, \"credentials\", {\n set(credentials) {\n if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) {\n isUserSupplied = true;\n }\n inputCredentials = credentials;\n const memoizedProvider = normalizeCredentialProvider(config, {\n credentials: inputCredentials,\n credentialDefaultProvider: config.credentialDefaultProvider,\n });\n const boundProvider = bindCallerConfig(config, memoizedProvider);\n if (isUserSupplied && !boundProvider.attributed) {\n const isCredentialObject = typeof inputCredentials === \"object\" && inputCredentials !== null;\n resolvedCredentials = async (options) => {\n const creds = await boundProvider(options);\n const attributedCreds = creds;\n if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) {\n return setCredentialFeature(attributedCreds, \"CREDENTIALS_CODE\", \"e\");\n }\n return attributedCreds;\n };\n resolvedCredentials.memoized = boundProvider.memoized;\n resolvedCredentials.configBound = boundProvider.configBound;\n resolvedCredentials.attributed = true;\n }\n else {\n resolvedCredentials = boundProvider;\n }\n },\n get() {\n return resolvedCredentials;\n },\n enumerable: true,\n configurable: true,\n });\n config.credentials = inputCredentials;\n const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config;\n let signer;\n if (config.signer) {\n signer = normalizeProvider(config.signer);\n }\n else if (config.regionInfoProvider) {\n signer = () => normalizeProvider(config.region)()\n .then(async (region) => [\n (await config.regionInfoProvider(region, {\n useFipsEndpoint: await config.useFipsEndpoint(),\n useDualstackEndpoint: await config.useDualstackEndpoint(),\n })) || {},\n region,\n ])\n .then(([regionInfo, region]) => {\n const { signingRegion, signingService } = regionInfo;\n config.signingRegion = config.signingRegion || signingRegion || region;\n config.signingName = config.signingName || signingService || config.serviceId;\n const params = {\n ...config,\n credentials: config.credentials,\n region: config.signingRegion,\n service: config.signingName,\n sha256,\n uriEscapePath: signingEscapePath,\n };\n const SignerCtor = config.signerConstructor || SignatureV4;\n return new SignerCtor(params);\n });\n }\n else {\n signer = async (authScheme) => {\n authScheme = Object.assign({}, {\n name: \"sigv4\",\n signingName: config.signingName || config.defaultSigningName,\n signingRegion: await normalizeProvider(config.region)(),\n properties: {},\n }, authScheme);\n const signingRegion = authScheme.signingRegion;\n const signingService = authScheme.signingName;\n config.signingRegion = config.signingRegion || signingRegion;\n config.signingName = config.signingName || signingService || config.serviceId;\n const params = {\n ...config,\n credentials: config.credentials,\n region: config.signingRegion,\n service: config.signingName,\n sha256,\n uriEscapePath: signingEscapePath,\n };\n const SignerCtor = config.signerConstructor || SignatureV4;\n return new SignerCtor(params);\n };\n }\n const resolvedConfig = Object.assign(config, {\n systemClockOffset,\n signingEscapePath,\n signer,\n });\n return resolvedConfig;\n};\nexport const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;\nfunction normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) {\n let credentialsProvider;\n if (credentials) {\n if (!credentials?.memoized) {\n credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh);\n }\n else {\n credentialsProvider = credentials;\n }\n }\n else {\n if (credentialDefaultProvider) {\n credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config, {\n parentClientConfig: config,\n })));\n }\n else {\n credentialsProvider = async () => {\n throw new Error(\"@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.\");\n };\n }\n }\n credentialsProvider.memoized = true;\n return credentialsProvider;\n}\nfunction bindCallerConfig(config, credentialsProvider) {\n if (credentialsProvider.configBound) {\n return credentialsProvider;\n }\n const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });\n fn.memoized = credentialsProvider.memoized;\n fn.configBound = true;\n return fn;\n}\n","export { AwsSdkSigV4Signer, AWSSDKSigV4Signer, validateSigningProperties } from \"./AwsSdkSigV4Signer\";\nexport { AwsSdkSigV4ASigner } from \"./AwsSdkSigV4ASigner\";\nexport * from \"./NODE_AUTH_SCHEME_PREFERENCE_OPTIONS\";\nexport * from \"./resolveAwsSdkSigV4AConfig\";\nexport * from \"./resolveAwsSdkSigV4Config\";\n","export * from \"./aws_sdk\";\nexport * from \"./utils/getBearerTokenEnvKey\";\n","const getAllAliases = (name, aliases) => {\n const _aliases = [];\n if (name) {\n _aliases.push(name);\n }\n if (aliases) {\n for (const alias of aliases) {\n _aliases.push(alias);\n }\n }\n return _aliases;\n};\nconst getMiddlewareNameWithAliases = (name, aliases) => {\n return `${name || \"anonymous\"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(\",\")})` : \"\"}`;\n};\nexport const constructStack = () => {\n let absoluteEntries = [];\n let relativeEntries = [];\n let identifyOnResolve = false;\n const entriesNameSet = new Set();\n const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] ||\n priorityWeights[b.priority || \"normal\"] - priorityWeights[a.priority || \"normal\"]);\n const removeByName = (toRemove) => {\n let isRemoved = false;\n const filterCb = (entry) => {\n const aliases = getAllAliases(entry.name, entry.aliases);\n if (aliases.includes(toRemove)) {\n isRemoved = true;\n for (const alias of aliases) {\n entriesNameSet.delete(alias);\n }\n return false;\n }\n return true;\n };\n absoluteEntries = absoluteEntries.filter(filterCb);\n relativeEntries = relativeEntries.filter(filterCb);\n return isRemoved;\n };\n const removeByReference = (toRemove) => {\n let isRemoved = false;\n const filterCb = (entry) => {\n if (entry.middleware === toRemove) {\n isRemoved = true;\n for (const alias of getAllAliases(entry.name, entry.aliases)) {\n entriesNameSet.delete(alias);\n }\n return false;\n }\n return true;\n };\n absoluteEntries = absoluteEntries.filter(filterCb);\n relativeEntries = relativeEntries.filter(filterCb);\n return isRemoved;\n };\n const cloneTo = (toStack) => {\n absoluteEntries.forEach((entry) => {\n toStack.add(entry.middleware, { ...entry });\n });\n relativeEntries.forEach((entry) => {\n toStack.addRelativeTo(entry.middleware, { ...entry });\n });\n toStack.identifyOnResolve?.(stack.identifyOnResolve());\n return toStack;\n };\n const expandRelativeMiddlewareList = (from) => {\n const expandedMiddlewareList = [];\n from.before.forEach((entry) => {\n if (entry.before.length === 0 && entry.after.length === 0) {\n expandedMiddlewareList.push(entry);\n }\n else {\n expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));\n }\n });\n expandedMiddlewareList.push(from);\n from.after.reverse().forEach((entry) => {\n if (entry.before.length === 0 && entry.after.length === 0) {\n expandedMiddlewareList.push(entry);\n }\n else {\n expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));\n }\n });\n return expandedMiddlewareList;\n };\n const getMiddlewareList = (debug = false) => {\n const normalizedAbsoluteEntries = [];\n const normalizedRelativeEntries = [];\n const normalizedEntriesNameMap = {};\n absoluteEntries.forEach((entry) => {\n const normalizedEntry = {\n ...entry,\n before: [],\n after: [],\n };\n for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {\n normalizedEntriesNameMap[alias] = normalizedEntry;\n }\n normalizedAbsoluteEntries.push(normalizedEntry);\n });\n relativeEntries.forEach((entry) => {\n const normalizedEntry = {\n ...entry,\n before: [],\n after: [],\n };\n for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {\n normalizedEntriesNameMap[alias] = normalizedEntry;\n }\n normalizedRelativeEntries.push(normalizedEntry);\n });\n normalizedRelativeEntries.forEach((entry) => {\n if (entry.toMiddleware) {\n const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];\n if (toMiddleware === undefined) {\n if (debug) {\n return;\n }\n throw new Error(`${entry.toMiddleware} is not found when adding ` +\n `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` +\n `middleware ${entry.relation} ${entry.toMiddleware}`);\n }\n if (entry.relation === \"after\") {\n toMiddleware.after.push(entry);\n }\n if (entry.relation === \"before\") {\n toMiddleware.before.push(entry);\n }\n }\n });\n const mainChain = sort(normalizedAbsoluteEntries)\n .map(expandRelativeMiddlewareList)\n .reduce((wholeList, expandedMiddlewareList) => {\n wholeList.push(...expandedMiddlewareList);\n return wholeList;\n }, []);\n return mainChain;\n };\n const stack = {\n add: (middleware, options = {}) => {\n const { name, override, aliases: _aliases } = options;\n const entry = {\n step: \"initialize\",\n priority: \"normal\",\n middleware,\n ...options,\n };\n const aliases = getAllAliases(name, _aliases);\n if (aliases.length > 0) {\n if (aliases.some((alias) => entriesNameSet.has(alias))) {\n if (!override)\n throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);\n for (const alias of aliases) {\n const toOverrideIndex = absoluteEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias));\n if (toOverrideIndex === -1) {\n continue;\n }\n const toOverride = absoluteEntries[toOverrideIndex];\n if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {\n throw new Error(`\"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}\" middleware with ` +\n `${toOverride.priority} priority in ${toOverride.step} step cannot ` +\n `be overridden by \"${getMiddlewareNameWithAliases(name, _aliases)}\" middleware with ` +\n `${entry.priority} priority in ${entry.step} step.`);\n }\n absoluteEntries.splice(toOverrideIndex, 1);\n }\n }\n for (const alias of aliases) {\n entriesNameSet.add(alias);\n }\n }\n absoluteEntries.push(entry);\n },\n addRelativeTo: (middleware, options) => {\n const { name, override, aliases: _aliases } = options;\n const entry = {\n middleware,\n ...options,\n };\n const aliases = getAllAliases(name, _aliases);\n if (aliases.length > 0) {\n if (aliases.some((alias) => entriesNameSet.has(alias))) {\n if (!override)\n throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);\n for (const alias of aliases) {\n const toOverrideIndex = relativeEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias));\n if (toOverrideIndex === -1) {\n continue;\n }\n const toOverride = relativeEntries[toOverrideIndex];\n if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {\n throw new Error(`\"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}\" middleware ` +\n `${toOverride.relation} \"${toOverride.toMiddleware}\" middleware cannot be overridden ` +\n `by \"${getMiddlewareNameWithAliases(name, _aliases)}\" middleware ${entry.relation} ` +\n `\"${entry.toMiddleware}\" middleware.`);\n }\n relativeEntries.splice(toOverrideIndex, 1);\n }\n }\n for (const alias of aliases) {\n entriesNameSet.add(alias);\n }\n }\n relativeEntries.push(entry);\n },\n clone: () => cloneTo(constructStack()),\n use: (plugin) => {\n plugin.applyToStack(stack);\n },\n remove: (toRemove) => {\n if (typeof toRemove === \"string\")\n return removeByName(toRemove);\n else\n return removeByReference(toRemove);\n },\n removeByTag: (toRemove) => {\n let isRemoved = false;\n const filterCb = (entry) => {\n const { tags, name, aliases: _aliases } = entry;\n if (tags && tags.includes(toRemove)) {\n const aliases = getAllAliases(name, _aliases);\n for (const alias of aliases) {\n entriesNameSet.delete(alias);\n }\n isRemoved = true;\n return false;\n }\n return true;\n };\n absoluteEntries = absoluteEntries.filter(filterCb);\n relativeEntries = relativeEntries.filter(filterCb);\n return isRemoved;\n },\n concat: (from) => {\n const cloned = cloneTo(constructStack());\n cloned.use(from);\n cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));\n return cloned;\n },\n applyToStack: cloneTo,\n identify: () => {\n return getMiddlewareList(true).map((mw) => {\n const step = mw.step ??\n mw.relation +\n \" \" +\n mw.toMiddleware;\n return getMiddlewareNameWithAliases(mw.name, mw.aliases) + \" - \" + step;\n });\n },\n identifyOnResolve(toggle) {\n if (typeof toggle === \"boolean\")\n identifyOnResolve = toggle;\n return identifyOnResolve;\n },\n resolve: (handler, context) => {\n for (const middleware of getMiddlewareList()\n .map((entry) => entry.middleware)\n .reverse()) {\n handler = middleware(handler, context);\n }\n if (identifyOnResolve) {\n console.log(stack.identify());\n }\n return handler;\n },\n };\n return stack;\n};\nconst stepWeights = {\n initialize: 5,\n serialize: 4,\n build: 3,\n finalizeRequest: 2,\n deserialize: 1,\n};\nconst priorityWeights = {\n high: 3,\n normal: 2,\n low: 1,\n};\n","export * from \"./MiddlewareStack\";\n","import { constructStack } from \"@smithy/middleware-stack\";\nexport class Client {\n config;\n middlewareStack = constructStack();\n initConfig;\n handlers;\n constructor(config) {\n this.config = config;\n const { protocol, protocolSettings } = config;\n if (protocolSettings) {\n if (typeof protocol === \"function\") {\n config.protocol = new protocol(protocolSettings);\n }\n }\n }\n send(command, optionsOrCb, cb) {\n const options = typeof optionsOrCb !== \"function\" ? optionsOrCb : undefined;\n const callback = typeof optionsOrCb === \"function\" ? optionsOrCb : cb;\n const useHandlerCache = options === undefined && this.config.cacheMiddleware === true;\n let handler;\n if (useHandlerCache) {\n if (!this.handlers) {\n this.handlers = new WeakMap();\n }\n const handlers = this.handlers;\n if (handlers.has(command.constructor)) {\n handler = handlers.get(command.constructor);\n }\n else {\n handler = command.resolveMiddleware(this.middlewareStack, this.config, options);\n handlers.set(command.constructor, handler);\n }\n }\n else {\n delete this.handlers;\n handler = command.resolveMiddleware(this.middlewareStack, this.config, options);\n }\n if (callback) {\n handler(command)\n .then((result) => callback(null, result.output), (err) => callback(err))\n .catch(() => { });\n }\n else {\n return handler(command).then((result) => result.output);\n }\n }\n destroy() {\n this.config?.requestHandler?.destroy?.();\n delete this.handlers;\n }\n}\n","export { collectBody } from \"@smithy/core/protocols\";\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nconst SENSITIVE_STRING = \"***SensitiveInformation***\";\nexport function schemaLogFilter(schema, data) {\n if (data == null) {\n return data;\n }\n const ns = NormalizedSchema.of(schema);\n if (ns.getMergedTraits().sensitive) {\n return SENSITIVE_STRING;\n }\n if (ns.isListSchema()) {\n const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;\n if (isSensitive) {\n return SENSITIVE_STRING;\n }\n }\n else if (ns.isMapSchema()) {\n const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;\n if (isSensitive) {\n return SENSITIVE_STRING;\n }\n }\n else if (ns.isStructSchema() && typeof data === \"object\") {\n const object = data;\n const newObject = {};\n for (const [member, memberNs] of ns.structIterator()) {\n if (object[member] != null) {\n newObject[member] = schemaLogFilter(memberNs, object[member]);\n }\n }\n return newObject;\n }\n return data;\n}\n","import { constructStack } from \"@smithy/middleware-stack\";\nimport { SMITHY_CONTEXT_KEY } from \"@smithy/types\";\nimport { schemaLogFilter } from \"./schemaLogFilter\";\nexport class Command {\n middlewareStack = constructStack();\n schema;\n static classBuilder() {\n return new ClassBuilder();\n }\n resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) {\n for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {\n this.middlewareStack.use(mw);\n }\n const stack = clientStack.concat(this.middlewareStack);\n const { logger } = configuration;\n const handlerExecutionContext = {\n logger,\n clientName,\n commandName,\n inputFilterSensitiveLog,\n outputFilterSensitiveLog,\n [SMITHY_CONTEXT_KEY]: {\n commandInstance: this,\n ...smithyContext,\n },\n ...additionalContext,\n };\n const { requestHandler } = configuration;\n return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);\n }\n}\nclass ClassBuilder {\n _init = () => { };\n _ep = {};\n _middlewareFn = () => [];\n _commandName = \"\";\n _clientName = \"\";\n _additionalContext = {};\n _smithyContext = {};\n _inputFilterSensitiveLog = undefined;\n _outputFilterSensitiveLog = undefined;\n _serializer = null;\n _deserializer = null;\n _operationSchema;\n init(cb) {\n this._init = cb;\n }\n ep(endpointParameterInstructions) {\n this._ep = endpointParameterInstructions;\n return this;\n }\n m(middlewareSupplier) {\n this._middlewareFn = middlewareSupplier;\n return this;\n }\n s(service, operation, smithyContext = {}) {\n this._smithyContext = {\n service,\n operation,\n ...smithyContext,\n };\n return this;\n }\n c(additionalContext = {}) {\n this._additionalContext = additionalContext;\n return this;\n }\n n(clientName, commandName) {\n this._clientName = clientName;\n this._commandName = commandName;\n return this;\n }\n f(inputFilter = (_) => _, outputFilter = (_) => _) {\n this._inputFilterSensitiveLog = inputFilter;\n this._outputFilterSensitiveLog = outputFilter;\n return this;\n }\n ser(serializer) {\n this._serializer = serializer;\n return this;\n }\n de(deserializer) {\n this._deserializer = deserializer;\n return this;\n }\n sc(operation) {\n this._operationSchema = operation;\n this._smithyContext.operationSchema = operation;\n return this;\n }\n build() {\n const closure = this;\n let CommandRef;\n return (CommandRef = class extends Command {\n input;\n static getEndpointParameterInstructions() {\n return closure._ep;\n }\n constructor(...[input]) {\n super();\n this.input = input ?? {};\n closure._init(this);\n this.schema = closure._operationSchema;\n }\n resolveMiddleware(stack, configuration, options) {\n const op = closure._operationSchema;\n const input = op?.[4] ?? op?.input;\n const output = op?.[5] ?? op?.output;\n return this.resolveMiddlewareWithContext(stack, configuration, options, {\n CommandCtor: CommandRef,\n middlewareFn: closure._middlewareFn,\n clientName: closure._clientName,\n commandName: closure._commandName,\n inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _),\n outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _),\n smithyContext: closure._smithyContext,\n additionalContext: closure._additionalContext,\n });\n }\n serialize = closure._serializer;\n deserialize = closure._deserializer;\n });\n }\n}\n","export const SENSITIVE_STRING = \"***SensitiveInformation***\";\n","export const createAggregatedClient = (commands, Client) => {\n for (const command of Object.keys(commands)) {\n const CommandCtor = commands[command];\n const methodImpl = async function (args, optionsOrCb, cb) {\n const command = new CommandCtor(args);\n if (typeof optionsOrCb === \"function\") {\n this.send(command, optionsOrCb);\n }\n else if (typeof cb === \"function\") {\n if (typeof optionsOrCb !== \"object\")\n throw new Error(`Expected http options but got ${typeof optionsOrCb}`);\n this.send(command, optionsOrCb || {}, cb);\n }\n else {\n return this.send(command, optionsOrCb);\n }\n };\n const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, \"\");\n Client.prototype[methodName] = methodImpl;\n }\n};\n","export class ServiceException extends Error {\n $fault;\n $response;\n $retryable;\n $metadata;\n constructor(options) {\n super(options.message);\n Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);\n this.name = options.name;\n this.$fault = options.$fault;\n this.$metadata = options.$metadata;\n }\n static isInstance(value) {\n if (!value)\n return false;\n const candidate = value;\n return (ServiceException.prototype.isPrototypeOf(candidate) ||\n (Boolean(candidate.$fault) &&\n Boolean(candidate.$metadata) &&\n (candidate.$fault === \"client\" || candidate.$fault === \"server\")));\n }\n static [Symbol.hasInstance](instance) {\n if (!instance)\n return false;\n const candidate = instance;\n if (this === ServiceException) {\n return ServiceException.isInstance(instance);\n }\n if (ServiceException.isInstance(instance)) {\n if (candidate.name && this.name) {\n return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;\n }\n return this.prototype.isPrototypeOf(instance);\n }\n return false;\n }\n}\nexport const decorateServiceException = (exception, additions = {}) => {\n Object.entries(additions)\n .filter(([, v]) => v !== undefined)\n .forEach(([k, v]) => {\n if (exception[k] == undefined || exception[k] === \"\") {\n exception[k] = v;\n }\n });\n const message = exception.message || exception.Message || \"UnknownError\";\n exception.message = message;\n delete exception.Message;\n return exception;\n};\n","import { decorateServiceException } from \"./exceptions\";\nexport const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {\n const $metadata = deserializeMetadata(output);\n const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + \"\" : undefined;\n const response = new exceptionCtor({\n name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || \"UnknownError\",\n $fault: \"client\",\n $metadata,\n });\n throw decorateServiceException(response, parsedBody);\n};\nexport const withBaseException = (ExceptionCtor) => {\n return ({ output, parsedBody, errorCode }) => {\n throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });\n };\n};\nconst deserializeMetadata = (output) => ({\n httpStatusCode: output.statusCode,\n requestId: output.headers[\"x-amzn-requestid\"] ?? output.headers[\"x-amzn-request-id\"] ?? output.headers[\"x-amz-request-id\"],\n extendedRequestId: output.headers[\"x-amz-id-2\"],\n cfId: output.headers[\"x-amz-cf-id\"],\n});\n","export const loadConfigsForDefaultMode = (mode) => {\n switch (mode) {\n case \"standard\":\n return {\n retryMode: \"standard\",\n connectionTimeout: 3100,\n };\n case \"in-region\":\n return {\n retryMode: \"standard\",\n connectionTimeout: 1100,\n };\n case \"cross-region\":\n return {\n retryMode: \"standard\",\n connectionTimeout: 3100,\n };\n case \"mobile\":\n return {\n retryMode: \"standard\",\n connectionTimeout: 30000,\n };\n default:\n return {};\n }\n};\n","let warningEmitted = false;\nexport const emitWarningIfUnsupportedVersion = (version) => {\n if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf(\".\"))) < 16) {\n warningEmitted = true;\n }\n};\n","export { extendedEncodeURIComponent } from \"@smithy/core/protocols\";\n","import { AlgorithmId } from \"@smithy/types\";\nexport { AlgorithmId };\nexport const getChecksumConfiguration = (runtimeConfig) => {\n const checksumAlgorithms = [];\n for (const id in AlgorithmId) {\n const algorithmId = AlgorithmId[id];\n if (runtimeConfig[algorithmId] === undefined) {\n continue;\n }\n checksumAlgorithms.push({\n algorithmId: () => algorithmId,\n checksumConstructor: () => runtimeConfig[algorithmId],\n });\n }\n return {\n addChecksumAlgorithm(algo) {\n checksumAlgorithms.push(algo);\n },\n checksumAlgorithms() {\n return checksumAlgorithms;\n },\n };\n};\nexport const resolveChecksumRuntimeConfig = (clientConfig) => {\n const runtimeConfig = {};\n clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {\n runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();\n });\n return runtimeConfig;\n};\n","export const getRetryConfiguration = (runtimeConfig) => {\n return {\n setRetryStrategy(retryStrategy) {\n runtimeConfig.retryStrategy = retryStrategy;\n },\n retryStrategy() {\n return runtimeConfig.retryStrategy;\n },\n };\n};\nexport const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {\n const runtimeConfig = {};\n runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();\n return runtimeConfig;\n};\n","import { getChecksumConfiguration, resolveChecksumRuntimeConfig } from \"./checksum\";\nimport { getRetryConfiguration, resolveRetryRuntimeConfig } from \"./retry\";\nexport const getDefaultExtensionConfiguration = (runtimeConfig) => {\n return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));\n};\nexport const getDefaultClientConfiguration = getDefaultExtensionConfiguration;\nexport const resolveDefaultRuntimeConfig = (config) => {\n return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config));\n};\n","export * from \"./defaultExtensionConfiguration\";\n","export const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];\n","export const getValueFromTextNode = (obj) => {\n const textNodeName = \"#text\";\n for (const key in obj) {\n if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {\n obj[key] = obj[key][textNodeName];\n }\n else if (typeof obj[key] === \"object\" && obj[key] !== null) {\n obj[key] = getValueFromTextNode(obj[key]);\n }\n }\n return obj;\n};\n","export const isSerializableHeaderValue = (value) => {\n return value != null;\n};\n","export class NoOpLogger {\n trace() { }\n debug() { }\n info() { }\n warn() { }\n error() { }\n}\n","export function map(arg0, arg1, arg2) {\n let target;\n let filter;\n let instructions;\n if (typeof arg1 === \"undefined\" && typeof arg2 === \"undefined\") {\n target = {};\n instructions = arg0;\n }\n else {\n target = arg0;\n if (typeof arg1 === \"function\") {\n filter = arg1;\n instructions = arg2;\n return mapWithFilter(target, filter, instructions);\n }\n else {\n instructions = arg1;\n }\n }\n for (const key of Object.keys(instructions)) {\n if (!Array.isArray(instructions[key])) {\n target[key] = instructions[key];\n continue;\n }\n applyInstruction(target, null, instructions, key);\n }\n return target;\n}\nexport const convertMap = (target) => {\n const output = {};\n for (const [k, v] of Object.entries(target || {})) {\n output[k] = [, v];\n }\n return output;\n};\nexport const take = (source, instructions) => {\n const out = {};\n for (const key in instructions) {\n applyInstruction(out, source, instructions, key);\n }\n return out;\n};\nconst mapWithFilter = (target, filter, instructions) => {\n return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {\n if (Array.isArray(value)) {\n _instructions[key] = value;\n }\n else {\n if (typeof value === \"function\") {\n _instructions[key] = [filter, value()];\n }\n else {\n _instructions[key] = [filter, value];\n }\n }\n return _instructions;\n }, {}));\n};\nconst applyInstruction = (target, source, instructions, targetKey) => {\n if (source !== null) {\n let instruction = instructions[targetKey];\n if (typeof instruction === \"function\") {\n instruction = [, instruction];\n }\n const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;\n if ((typeof filter === \"function\" && filter(source[sourceKey])) || (typeof filter !== \"function\" && !!filter)) {\n target[targetKey] = valueFn(source[sourceKey]);\n }\n return;\n }\n let [filter, value] = instructions[targetKey];\n if (typeof value === \"function\") {\n let _value;\n const defaultFilterPassed = filter === undefined && (_value = value()) != null;\n const customFilterPassed = (typeof filter === \"function\" && !!filter(void 0)) || (typeof filter !== \"function\" && !!filter);\n if (defaultFilterPassed) {\n target[targetKey] = _value;\n }\n else if (customFilterPassed) {\n target[targetKey] = value();\n }\n }\n else {\n const defaultFilterPassed = filter === undefined && value != null;\n const customFilterPassed = (typeof filter === \"function\" && !!filter(value)) || (typeof filter !== \"function\" && !!filter);\n if (defaultFilterPassed || customFilterPassed) {\n target[targetKey] = value;\n }\n }\n};\nconst nonNullish = (_) => _ != null;\nconst pass = (_) => _;\n","export { resolvedPath } from \"@smithy/core/protocols\";\n","export const serializeFloat = (value) => {\n if (value !== value) {\n return \"NaN\";\n }\n switch (value) {\n case Infinity:\n return \"Infinity\";\n case -Infinity:\n return \"-Infinity\";\n default:\n return value;\n }\n};\nexport const serializeDateTime = (date) => date.toISOString().replace(\".000Z\", \"Z\");\n","export const _json = (obj) => {\n if (obj == null) {\n return {};\n }\n if (Array.isArray(obj)) {\n return obj.filter((_) => _ != null).map(_json);\n }\n if (typeof obj === \"object\") {\n const target = {};\n for (const key of Object.keys(obj)) {\n if (obj[key] == null) {\n continue;\n }\n target[key] = _json(obj[key]);\n }\n return target;\n }\n return obj;\n};\n","export * from \"./client\";\nexport * from \"./collect-stream-body\";\nexport * from \"./command\";\nexport * from \"./constants\";\nexport * from \"./create-aggregated-client\";\nexport * from \"./default-error-handler\";\nexport * from \"./defaults-mode\";\nexport * from \"./emitWarningIfUnsupportedVersion\";\nexport * from \"./exceptions\";\nexport * from \"./extended-encode-uri-component\";\nexport * from \"./extensions\";\nexport * from \"./get-array-if-single-item\";\nexport * from \"./get-value-from-text-node\";\nexport * from \"./is-serializable-header-value\";\nexport * from \"./NoOpLogger\";\nexport * from \"./object-mapping\";\nexport * from \"./resolve-path\";\nexport * from \"./ser-utils\";\nexport * from \"./serde-json\";\nexport * from \"@smithy/core/serde\";\n","import { NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { decorateServiceException } from \"@smithy/smithy-client\";\nexport class ProtocolLib {\n queryCompat;\n constructor(queryCompat = false) {\n this.queryCompat = queryCompat;\n }\n resolveRestContentType(defaultContentType, inputSchema) {\n const members = inputSchema.getMemberSchemas();\n const httpPayloadMember = Object.values(members).find((m) => {\n return !!m.getMergedTraits().httpPayload;\n });\n if (httpPayloadMember) {\n const mediaType = httpPayloadMember.getMergedTraits().mediaType;\n if (mediaType) {\n return mediaType;\n }\n else if (httpPayloadMember.isStringSchema()) {\n return \"text/plain\";\n }\n else if (httpPayloadMember.isBlobSchema()) {\n return \"application/octet-stream\";\n }\n else {\n return defaultContentType;\n }\n }\n else if (!inputSchema.isUnitSchema()) {\n const hasBody = Object.values(members).find((m) => {\n const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits();\n const noPrefixHeaders = httpPrefixHeaders === void 0;\n return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders;\n });\n if (hasBody) {\n return defaultContentType;\n }\n }\n }\n async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) {\n let namespace = defaultNamespace;\n let errorName = errorIdentifier;\n if (errorIdentifier.includes(\"#\")) {\n [namespace, errorName] = errorIdentifier.split(\"#\");\n }\n const errorMetadata = {\n $metadata: metadata,\n $fault: response.statusCode < 500 ? \"client\" : \"server\",\n };\n const registry = TypeRegistry.for(namespace);\n try {\n const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier);\n return { errorSchema, errorMetadata };\n }\n catch (e) {\n dataObject.message = dataObject.message ?? dataObject.Message ?? \"UnknownError\";\n const synthetic = TypeRegistry.for(\"smithy.ts.sdk.synthetic.\" + namespace);\n const baseExceptionSchema = synthetic.getBaseException();\n if (baseExceptionSchema) {\n const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error;\n throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject);\n }\n throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject);\n }\n }\n decorateServiceException(exception, additions = {}) {\n if (this.queryCompat) {\n const msg = exception.Message ?? additions.Message;\n const error = decorateServiceException(exception, additions);\n if (msg) {\n error.message = msg;\n }\n error.Error = {\n ...error.Error,\n Type: error.Error.Type,\n Code: error.Error.Code,\n Message: error.Error.message ?? error.Error.Message ?? msg,\n };\n const reqId = error.$metadata.requestId;\n if (reqId) {\n error.RequestId = reqId;\n }\n return error;\n }\n return decorateServiceException(exception, additions);\n }\n setQueryCompatError(output, response) {\n const queryErrorHeader = response.headers?.[\"x-amzn-query-error\"];\n if (output !== undefined && queryErrorHeader != null) {\n const [Code, Type] = queryErrorHeader.split(\";\");\n const entries = Object.entries(output);\n const Error = {\n Code,\n Type,\n };\n Object.assign(output, Error);\n for (const [k, v] of entries) {\n Error[k === \"message\" ? \"Message\" : k] = v;\n }\n delete Error.__type;\n output.Error = Error;\n }\n }\n queryCompatOutput(queryCompatErrorData, errorData) {\n if (queryCompatErrorData.Error) {\n errorData.Error = queryCompatErrorData.Error;\n }\n if (queryCompatErrorData.Type) {\n errorData.Type = queryCompatErrorData.Type;\n }\n if (queryCompatErrorData.Code) {\n errorData.Code = queryCompatErrorData.Code;\n }\n }\n findQueryCompatibleError(registry, errorName) {\n try {\n return registry.getSchema(errorName);\n }\n catch (e) {\n return registry.find((schema) => NormalizedSchema.of(schema).getMergedTraits().awsQueryError?.[0] === errorName);\n }\n }\n}\n","import { loadSmithyRpcV2CborErrorCode, SmithyRpcV2CborProtocol } from \"@smithy/core/cbor\";\nimport { NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { ProtocolLib } from \"../ProtocolLib\";\nexport class AwsSmithyRpcV2CborProtocol extends SmithyRpcV2CborProtocol {\n awsQueryCompatible;\n mixin;\n constructor({ defaultNamespace, awsQueryCompatible, }) {\n super({ defaultNamespace });\n this.awsQueryCompatible = !!awsQueryCompatible;\n this.mixin = new ProtocolLib(this.awsQueryCompatible);\n }\n async serializeRequest(operationSchema, input, context) {\n const request = await super.serializeRequest(operationSchema, input, context);\n if (this.awsQueryCompatible) {\n request.headers[\"x-amzn-query-mode\"] = \"true\";\n }\n return request;\n }\n async handleError(operationSchema, context, response, dataObject, metadata) {\n if (this.awsQueryCompatible) {\n this.mixin.setQueryCompatError(dataObject, response);\n }\n const errorName = (() => {\n const compatHeader = response.headers[\"x-amzn-query-error\"];\n if (compatHeader && this.awsQueryCompatible) {\n return compatHeader.split(\";\")[0];\n }\n return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? \"Unknown\";\n })();\n const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined);\n const ns = NormalizedSchema.of(errorSchema);\n const message = dataObject.message ?? dataObject.Message ?? \"Unknown\";\n const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error;\n const exception = new ErrorCtor(message);\n const output = {};\n for (const [name, member] of ns.structIterator()) {\n if (dataObject[name] != null) {\n output[name] = this.deserializer.readValue(member, dataObject[name]);\n }\n }\n if (this.awsQueryCompatible) {\n this.mixin.queryCompatOutput(dataObject, output);\n }\n throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {\n $fault: ns.getMergedTraits().error,\n message,\n }, output), dataObject);\n }\n}\n","export const _toStr = (val) => {\n if (val == null) {\n return val;\n }\n if (typeof val === \"number\" || typeof val === \"bigint\") {\n const warning = new Error(`Received number ${val} where a string was expected.`);\n warning.name = \"Warning\";\n console.warn(warning);\n return String(val);\n }\n if (typeof val === \"boolean\") {\n const warning = new Error(`Received boolean ${val} where a string was expected.`);\n warning.name = \"Warning\";\n console.warn(warning);\n return String(val);\n }\n return val;\n};\nexport const _toBool = (val) => {\n if (val == null) {\n return val;\n }\n if (typeof val === \"number\") {\n }\n if (typeof val === \"string\") {\n const lowercase = val.toLowerCase();\n if (val !== \"\" && lowercase !== \"false\" && lowercase !== \"true\") {\n const warning = new Error(`Received string \"${val}\" where a boolean was expected.`);\n warning.name = \"Warning\";\n console.warn(warning);\n }\n return val !== \"\" && lowercase !== \"false\";\n }\n return val;\n};\nexport const _toNum = (val) => {\n if (val == null) {\n return val;\n }\n if (typeof val === \"boolean\") {\n }\n if (typeof val === \"string\") {\n const num = Number(val);\n if (num.toString() !== val) {\n const warning = new Error(`Received string \"${val}\" where a number was expected.`);\n warning.name = \"Warning\";\n console.warn(warning);\n return val;\n }\n return num;\n }\n return val;\n};\n","export class SerdeContextConfig {\n serdeContext;\n setSerdeContext(serdeContext) {\n this.serdeContext = serdeContext;\n }\n}\n","import { NormalizedSchema } from \"@smithy/core/schema\";\nexport function* serializingStructIterator(ns, sourceObject) {\n if (ns.isUnitSchema()) {\n return;\n }\n const struct = ns.getSchema();\n for (let i = 0; i < struct[4].length; ++i) {\n const key = struct[4][i];\n const memberSchema = struct[5][i];\n const memberNs = new NormalizedSchema([memberSchema, 0], key);\n if (!(key in sourceObject) && !memberNs.isIdempotencyToken()) {\n continue;\n }\n yield [key, memberNs];\n }\n}\nexport function* deserializingStructIterator(ns, sourceObject, nameTrait) {\n if (ns.isUnitSchema()) {\n return;\n }\n const struct = ns.getSchema();\n let keysRemaining = Object.keys(sourceObject).filter((k) => k !== \"__type\").length;\n for (let i = 0; i < struct[4].length; ++i) {\n if (keysRemaining === 0) {\n break;\n }\n const key = struct[4][i];\n const memberSchema = struct[5][i];\n const memberNs = new NormalizedSchema([memberSchema, 0], key);\n let serializationKey = key;\n if (nameTrait) {\n serializationKey = memberNs.getMergedTraits()[nameTrait] ?? key;\n }\n if (!(serializationKey in sourceObject)) {\n continue;\n }\n yield [key, memberNs];\n keysRemaining -= 1;\n }\n}\n","export class UnionSerde {\n from;\n to;\n keys;\n constructor(from, to) {\n this.from = from;\n this.to = to;\n this.keys = new Set(Object.keys(this.from).filter((k) => k !== \"__type\"));\n }\n mark(key) {\n this.keys.delete(key);\n }\n hasUnknown() {\n return this.keys.size === 1 && Object.keys(this.to).length === 0;\n }\n writeUnknown() {\n if (this.hasUnknown()) {\n const k = this.keys.values().next().value;\n const v = this.from[k];\n this.to.$unknown = [k, v];\n }\n }\n}\n","import { NumericValue } from \"@smithy/core/serde\";\nexport function jsonReviver(key, value, context) {\n if (context?.source) {\n const numericString = context.source;\n if (typeof value === \"number\") {\n if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) {\n const isFractional = numericString.includes(\".\");\n if (isFractional) {\n return new NumericValue(numericString, \"bigDecimal\");\n }\n else {\n return BigInt(numericString);\n }\n }\n }\n }\n return value;\n}\n","import { collectBody } from \"@smithy/smithy-client\";\nimport { toUtf8 } from \"@smithy/util-utf8\";\nexport const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? toUtf8)(body));\n","import { collectBodyString } from \"../common\";\nexport const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {\n if (encoded.length) {\n try {\n return JSON.parse(encoded);\n }\n catch (e) {\n if (e?.name === \"SyntaxError\") {\n Object.defineProperty(e, \"$responseBodyText\", {\n value: encoded,\n });\n }\n throw e;\n }\n }\n return {};\n});\nexport const parseJsonErrorBody = async (errorBody, context) => {\n const value = await parseJsonBody(errorBody, context);\n value.message = value.message ?? value.Message;\n return value;\n};\nexport const loadRestJsonErrorCode = (output, data) => {\n const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase());\n const sanitizeErrorCode = (rawValue) => {\n let cleanValue = rawValue;\n if (typeof cleanValue === \"number\") {\n cleanValue = cleanValue.toString();\n }\n if (cleanValue.indexOf(\",\") >= 0) {\n cleanValue = cleanValue.split(\",\")[0];\n }\n if (cleanValue.indexOf(\":\") >= 0) {\n cleanValue = cleanValue.split(\":\")[0];\n }\n if (cleanValue.indexOf(\"#\") >= 0) {\n cleanValue = cleanValue.split(\"#\")[1];\n }\n return cleanValue;\n };\n const headerKey = findKey(output.headers, \"x-amzn-errortype\");\n if (headerKey !== undefined) {\n return sanitizeErrorCode(output.headers[headerKey]);\n }\n if (data && typeof data === \"object\") {\n const codeKey = findKey(data, \"code\");\n if (codeKey && data[codeKey] !== undefined) {\n return sanitizeErrorCode(data[codeKey]);\n }\n if (data[\"__type\"] !== undefined) {\n return sanitizeErrorCode(data[\"__type\"]);\n }\n }\n};\n","import { determineTimestampFormat } from \"@smithy/core/protocols\";\nimport { NormalizedSchema } from \"@smithy/core/schema\";\nimport { LazyJsonString, NumericValue, parseEpochTimestamp, parseRfc3339DateTimeWithOffset, parseRfc7231DateTime, } from \"@smithy/core/serde\";\nimport { fromBase64 } from \"@smithy/util-base64\";\nimport { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { deserializingStructIterator } from \"../structIterator\";\nimport { UnionSerde } from \"../UnionSerde\";\nimport { jsonReviver } from \"./jsonReviver\";\nimport { parseJsonBody } from \"./parseJsonBody\";\nexport class JsonShapeDeserializer extends SerdeContextConfig {\n settings;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n async read(schema, data) {\n return this._read(schema, typeof data === \"string\" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext));\n }\n readObject(schema, data) {\n return this._read(schema, data);\n }\n _read(schema, value) {\n const isObject = value !== null && typeof value === \"object\";\n const ns = NormalizedSchema.of(schema);\n if (isObject) {\n if (ns.isStructSchema()) {\n const record = value;\n const union = ns.isUnionSchema();\n const out = {};\n let nameMap = void 0;\n const { jsonName } = this.settings;\n if (jsonName) {\n nameMap = {};\n }\n let unionSerde;\n if (union) {\n unionSerde = new UnionSerde(record, out);\n }\n for (const [memberName, memberSchema] of deserializingStructIterator(ns, record, jsonName ? \"jsonName\" : false)) {\n let fromKey = memberName;\n if (jsonName) {\n fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey;\n nameMap[fromKey] = memberName;\n }\n if (union) {\n unionSerde.mark(fromKey);\n }\n if (record[fromKey] != null) {\n out[memberName] = this._read(memberSchema, record[fromKey]);\n }\n }\n if (union) {\n unionSerde.writeUnknown();\n }\n else if (typeof record.__type === \"string\") {\n for (const [k, v] of Object.entries(record)) {\n const t = jsonName ? nameMap[k] ?? k : k;\n if (!(t in out)) {\n out[t] = v;\n }\n }\n }\n return out;\n }\n if (Array.isArray(value) && ns.isListSchema()) {\n const listMember = ns.getValueSchema();\n const out = [];\n const sparse = !!ns.getMergedTraits().sparse;\n for (const item of value) {\n if (sparse || item != null) {\n out.push(this._read(listMember, item));\n }\n }\n return out;\n }\n if (ns.isMapSchema()) {\n const mapMember = ns.getValueSchema();\n const out = {};\n const sparse = !!ns.getMergedTraits().sparse;\n for (const [_k, _v] of Object.entries(value)) {\n if (sparse || _v != null) {\n out[_k] = this._read(mapMember, _v);\n }\n }\n return out;\n }\n }\n if (ns.isBlobSchema() && typeof value === \"string\") {\n return fromBase64(value);\n }\n const mediaType = ns.getMergedTraits().mediaType;\n if (ns.isStringSchema() && typeof value === \"string\" && mediaType) {\n const isJson = mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n if (isJson) {\n return LazyJsonString.from(value);\n }\n return value;\n }\n if (ns.isTimestampSchema() && value != null) {\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n return parseRfc3339DateTimeWithOffset(value);\n case 6:\n return parseRfc7231DateTime(value);\n case 7:\n return parseEpochTimestamp(value);\n default:\n console.warn(\"Missing timestamp format, parsing value with Date constructor:\", value);\n return new Date(value);\n }\n }\n if (ns.isBigIntegerSchema() && (typeof value === \"number\" || typeof value === \"string\")) {\n return BigInt(value);\n }\n if (ns.isBigDecimalSchema() && value != undefined) {\n if (value instanceof NumericValue) {\n return value;\n }\n const untyped = value;\n if (untyped.type === \"bigDecimal\" && \"string\" in untyped) {\n return new NumericValue(untyped.string, untyped.type);\n }\n return new NumericValue(String(value), \"bigDecimal\");\n }\n if (ns.isNumericSchema() && typeof value === \"string\") {\n switch (value) {\n case \"Infinity\":\n return Infinity;\n case \"-Infinity\":\n return -Infinity;\n case \"NaN\":\n return NaN;\n }\n return value;\n }\n if (ns.isDocumentSchema()) {\n if (isObject) {\n const out = Array.isArray(value) ? [] : {};\n for (const [k, v] of Object.entries(value)) {\n if (v instanceof NumericValue) {\n out[k] = v;\n }\n else {\n out[k] = this._read(ns, v);\n }\n }\n return out;\n }\n else {\n return structuredClone(value);\n }\n }\n return value;\n }\n}\n","import { NumericValue } from \"@smithy/core/serde\";\nconst NUMERIC_CONTROL_CHAR = String.fromCharCode(925);\nexport class JsonReplacer {\n values = new Map();\n counter = 0;\n stage = 0;\n createReplacer() {\n if (this.stage === 1) {\n throw new Error(\"@aws-sdk/core/protocols - JsonReplacer already created.\");\n }\n if (this.stage === 2) {\n throw new Error(\"@aws-sdk/core/protocols - JsonReplacer exhausted.\");\n }\n this.stage = 1;\n return (key, value) => {\n if (value instanceof NumericValue) {\n const v = `${NUMERIC_CONTROL_CHAR + \"nv\" + this.counter++}_` + value.string;\n this.values.set(`\"${v}\"`, value.string);\n return v;\n }\n if (typeof value === \"bigint\") {\n const s = value.toString();\n const v = `${NUMERIC_CONTROL_CHAR + \"b\" + this.counter++}_` + s;\n this.values.set(`\"${v}\"`, s);\n return v;\n }\n return value;\n };\n }\n replaceInJson(json) {\n if (this.stage === 0) {\n throw new Error(\"@aws-sdk/core/protocols - JsonReplacer not created yet.\");\n }\n if (this.stage === 2) {\n throw new Error(\"@aws-sdk/core/protocols - JsonReplacer exhausted.\");\n }\n this.stage = 2;\n if (this.counter === 0) {\n return json;\n }\n for (const [key, value] of this.values) {\n json = json.replace(key, value);\n }\n return json;\n }\n}\n","import { determineTimestampFormat } from \"@smithy/core/protocols\";\nimport { NormalizedSchema } from \"@smithy/core/schema\";\nimport { dateToUtcString, generateIdempotencyToken, LazyJsonString, NumericValue } from \"@smithy/core/serde\";\nimport { toBase64 } from \"@smithy/util-base64\";\nimport { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { serializingStructIterator } from \"../structIterator\";\nimport { JsonReplacer } from \"./jsonReplacer\";\nexport class JsonShapeSerializer extends SerdeContextConfig {\n settings;\n buffer;\n useReplacer = false;\n rootSchema;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n write(schema, value) {\n this.rootSchema = NormalizedSchema.of(schema);\n this.buffer = this._write(this.rootSchema, value);\n }\n writeDiscriminatedDocument(schema, value) {\n this.write(schema, value);\n if (typeof this.buffer === \"object\") {\n this.buffer.__type = NormalizedSchema.of(schema).getName(true);\n }\n }\n flush() {\n const { rootSchema, useReplacer } = this;\n this.rootSchema = undefined;\n this.useReplacer = false;\n if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) {\n if (!useReplacer) {\n return JSON.stringify(this.buffer);\n }\n const replacer = new JsonReplacer();\n return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0));\n }\n return this.buffer;\n }\n _write(schema, value, container) {\n const isObject = value !== null && typeof value === \"object\";\n const ns = NormalizedSchema.of(schema);\n if (isObject) {\n if (ns.isStructSchema()) {\n const record = value;\n const out = {};\n const { jsonName } = this.settings;\n let nameMap = void 0;\n if (jsonName) {\n nameMap = {};\n }\n for (const [memberName, memberSchema] of serializingStructIterator(ns, record)) {\n const serializableValue = this._write(memberSchema, record[memberName], ns);\n if (serializableValue !== undefined) {\n let targetKey = memberName;\n if (jsonName) {\n targetKey = memberSchema.getMergedTraits().jsonName ?? memberName;\n nameMap[memberName] = targetKey;\n }\n out[targetKey] = serializableValue;\n }\n }\n if (ns.isUnionSchema() && Object.keys(out).length === 0) {\n const { $unknown } = record;\n if (Array.isArray($unknown)) {\n const [k, v] = $unknown;\n out[k] = this._write(15, v);\n }\n }\n else if (typeof record.__type === \"string\") {\n for (const [k, v] of Object.entries(record)) {\n const targetKey = jsonName ? nameMap[k] ?? k : k;\n if (!(targetKey in out)) {\n out[targetKey] = this._write(15, v);\n }\n }\n }\n return out;\n }\n if (Array.isArray(value) && ns.isListSchema()) {\n const listMember = ns.getValueSchema();\n const out = [];\n const sparse = !!ns.getMergedTraits().sparse;\n for (const item of value) {\n if (sparse || item != null) {\n out.push(this._write(listMember, item));\n }\n }\n return out;\n }\n if (ns.isMapSchema()) {\n const mapMember = ns.getValueSchema();\n const out = {};\n const sparse = !!ns.getMergedTraits().sparse;\n for (const [_k, _v] of Object.entries(value)) {\n if (sparse || _v != null) {\n out[_k] = this._write(mapMember, _v);\n }\n }\n return out;\n }\n if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) {\n if (ns === this.rootSchema) {\n return value;\n }\n return (this.serdeContext?.base64Encoder ?? toBase64)(value);\n }\n if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) {\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n return value.toISOString().replace(\".000Z\", \"Z\");\n case 6:\n return dateToUtcString(value);\n case 7:\n return value.getTime() / 1000;\n default:\n console.warn(\"Missing timestamp format, using epoch seconds\", value);\n return value.getTime() / 1000;\n }\n }\n if (value instanceof NumericValue) {\n this.useReplacer = true;\n }\n }\n if (value === null && container?.isStructSchema()) {\n return void 0;\n }\n if (ns.isStringSchema()) {\n if (typeof value === \"undefined\" && ns.isIdempotencyToken()) {\n return generateIdempotencyToken();\n }\n const mediaType = ns.getMergedTraits().mediaType;\n if (value != null && mediaType) {\n const isJson = mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n if (isJson) {\n return LazyJsonString.from(value);\n }\n }\n return value;\n }\n if (typeof value === \"number\" && ns.isNumericSchema()) {\n if (Math.abs(value) === Infinity || isNaN(value)) {\n return String(value);\n }\n return value;\n }\n if (typeof value === \"string\" && ns.isBlobSchema()) {\n if (ns === this.rootSchema) {\n return value;\n }\n return (this.serdeContext?.base64Encoder ?? toBase64)(value);\n }\n if (typeof value === \"bigint\") {\n this.useReplacer = true;\n }\n if (ns.isDocumentSchema()) {\n if (isObject) {\n const out = Array.isArray(value) ? [] : {};\n for (const [k, v] of Object.entries(value)) {\n if (v instanceof NumericValue) {\n this.useReplacer = true;\n out[k] = v;\n }\n else {\n out[k] = this._write(ns, v);\n }\n }\n return out;\n }\n else {\n return structuredClone(value);\n }\n }\n return value;\n }\n}\n","import { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { JsonShapeDeserializer } from \"./JsonShapeDeserializer\";\nimport { JsonShapeSerializer } from \"./JsonShapeSerializer\";\nexport class JsonCodec extends SerdeContextConfig {\n settings;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n createSerializer() {\n const serializer = new JsonShapeSerializer(this.settings);\n serializer.setSerdeContext(this.serdeContext);\n return serializer;\n }\n createDeserializer() {\n const deserializer = new JsonShapeDeserializer(this.settings);\n deserializer.setSerdeContext(this.serdeContext);\n return deserializer;\n }\n}\n","import { RpcProtocol } from \"@smithy/core/protocols\";\nimport { deref, NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { ProtocolLib } from \"../ProtocolLib\";\nimport { JsonCodec } from \"./JsonCodec\";\nimport { loadRestJsonErrorCode } from \"./parseJsonBody\";\nexport class AwsJsonRpcProtocol extends RpcProtocol {\n serializer;\n deserializer;\n serviceTarget;\n codec;\n mixin;\n awsQueryCompatible;\n constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec, }) {\n super({\n defaultNamespace,\n });\n this.serviceTarget = serviceTarget;\n this.codec =\n jsonCodec ??\n new JsonCodec({\n timestampFormat: {\n useTrait: true,\n default: 7,\n },\n jsonName: false,\n });\n this.serializer = this.codec.createSerializer();\n this.deserializer = this.codec.createDeserializer();\n this.awsQueryCompatible = !!awsQueryCompatible;\n this.mixin = new ProtocolLib(this.awsQueryCompatible);\n }\n async serializeRequest(operationSchema, input, context) {\n const request = await super.serializeRequest(operationSchema, input, context);\n if (!request.path.endsWith(\"/\")) {\n request.path += \"/\";\n }\n Object.assign(request.headers, {\n \"content-type\": `application/x-amz-json-${this.getJsonRpcVersion()}`,\n \"x-amz-target\": `${this.serviceTarget}.${operationSchema.name}`,\n });\n if (this.awsQueryCompatible) {\n request.headers[\"x-amzn-query-mode\"] = \"true\";\n }\n if (deref(operationSchema.input) === \"unit\" || !request.body) {\n request.body = \"{}\";\n }\n return request;\n }\n getPayloadCodec() {\n return this.codec;\n }\n async handleError(operationSchema, context, response, dataObject, metadata) {\n if (this.awsQueryCompatible) {\n this.mixin.setQueryCompatError(dataObject, response);\n }\n const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? \"Unknown\";\n const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : undefined);\n const ns = NormalizedSchema.of(errorSchema);\n const message = dataObject.message ?? dataObject.Message ?? \"Unknown\";\n const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error;\n const exception = new ErrorCtor(message);\n const output = {};\n for (const [name, member] of ns.structIterator()) {\n if (dataObject[name] != null) {\n output[name] = this.codec.createDeserializer().readObject(member, dataObject[name]);\n }\n }\n if (this.awsQueryCompatible) {\n this.mixin.queryCompatOutput(dataObject, output);\n }\n throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {\n $fault: ns.getMergedTraits().error,\n message,\n }, output), dataObject);\n }\n}\n","import { AwsJsonRpcProtocol } from \"./AwsJsonRpcProtocol\";\nexport class AwsJson1_0Protocol extends AwsJsonRpcProtocol {\n constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec, }) {\n super({\n defaultNamespace,\n serviceTarget,\n awsQueryCompatible,\n jsonCodec,\n });\n }\n getShapeId() {\n return \"aws.protocols#awsJson1_0\";\n }\n getJsonRpcVersion() {\n return \"1.0\";\n }\n getDefaultContentType() {\n return \"application/x-amz-json-1.0\";\n }\n}\n","import { AwsJsonRpcProtocol } from \"./AwsJsonRpcProtocol\";\nexport class AwsJson1_1Protocol extends AwsJsonRpcProtocol {\n constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, jsonCodec, }) {\n super({\n defaultNamespace,\n serviceTarget,\n awsQueryCompatible,\n jsonCodec,\n });\n }\n getShapeId() {\n return \"aws.protocols#awsJson1_1\";\n }\n getJsonRpcVersion() {\n return \"1.1\";\n }\n getDefaultContentType() {\n return \"application/x-amz-json-1.1\";\n }\n}\n","import { HttpBindingProtocol, HttpInterceptingShapeDeserializer, HttpInterceptingShapeSerializer, } from \"@smithy/core/protocols\";\nimport { NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { ProtocolLib } from \"../ProtocolLib\";\nimport { JsonCodec } from \"./JsonCodec\";\nimport { loadRestJsonErrorCode } from \"./parseJsonBody\";\nexport class AwsRestJsonProtocol extends HttpBindingProtocol {\n serializer;\n deserializer;\n codec;\n mixin = new ProtocolLib();\n constructor({ defaultNamespace }) {\n super({\n defaultNamespace,\n });\n const settings = {\n timestampFormat: {\n useTrait: true,\n default: 7,\n },\n httpBindings: true,\n jsonName: true,\n };\n this.codec = new JsonCodec(settings);\n this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);\n this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings);\n }\n getShapeId() {\n return \"aws.protocols#restJson1\";\n }\n getPayloadCodec() {\n return this.codec;\n }\n setSerdeContext(serdeContext) {\n this.codec.setSerdeContext(serdeContext);\n super.setSerdeContext(serdeContext);\n }\n async serializeRequest(operationSchema, input, context) {\n const request = await super.serializeRequest(operationSchema, input, context);\n const inputSchema = NormalizedSchema.of(operationSchema.input);\n if (!request.headers[\"content-type\"]) {\n const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);\n if (contentType) {\n request.headers[\"content-type\"] = contentType;\n }\n }\n if (request.body == null && request.headers[\"content-type\"] === this.getDefaultContentType()) {\n request.body = \"{}\";\n }\n return request;\n }\n async deserializeResponse(operationSchema, context, response) {\n const output = await super.deserializeResponse(operationSchema, context, response);\n const outputSchema = NormalizedSchema.of(operationSchema.output);\n for (const [name, member] of outputSchema.structIterator()) {\n if (member.getMemberTraits().httpPayload && !(name in output)) {\n output[name] = null;\n }\n }\n return output;\n }\n async handleError(operationSchema, context, response, dataObject, metadata) {\n const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? \"Unknown\";\n const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata);\n const ns = NormalizedSchema.of(errorSchema);\n const message = dataObject.message ?? dataObject.Message ?? \"Unknown\";\n const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error;\n const exception = new ErrorCtor(message);\n await this.deserializeHttpMessage(errorSchema, context, response, dataObject);\n const output = {};\n for (const [name, member] of ns.structIterator()) {\n const target = member.getMergedTraits().jsonName ?? name;\n output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]);\n }\n throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {\n $fault: ns.getMergedTraits().error,\n message,\n }, output), dataObject);\n }\n getDefaultContentType() {\n return \"application/json\";\n }\n}\n","import { expectUnion } from \"@smithy/smithy-client\";\nexport const awsExpectUnion = (value) => {\n if (value == null) {\n return undefined;\n }\n if (typeof value === \"object\" && \"__type\" in value) {\n delete value.__type;\n }\n return expectUnion(value);\n};\n","export function escapeAttribute(value) {\n return value.replace(/&/g, \"&\").replace(//g, \">\").replace(/\"/g, \""\");\n}\n","export function escapeElement(value) {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n .replace(//g, \">\")\n .replace(/\\r/g, \" \")\n .replace(/\\n/g, \" \")\n .replace(/\\u0085/g, \"…\")\n .replace(/\\u2028/, \"
\");\n}\n","import { escapeElement } from \"./escape-element\";\nexport class XmlText {\n value;\n constructor(value) {\n this.value = value;\n }\n toString() {\n return escapeElement(\"\" + this.value);\n }\n}\n","import { escapeAttribute } from \"./escape-attribute\";\nimport { XmlText } from \"./XmlText\";\nexport class XmlNode {\n name;\n children;\n attributes = {};\n static of(name, childText, withName) {\n const node = new XmlNode(name);\n if (childText !== undefined) {\n node.addChildNode(new XmlText(childText));\n }\n if (withName !== undefined) {\n node.withName(withName);\n }\n return node;\n }\n constructor(name, children = []) {\n this.name = name;\n this.children = children;\n }\n withName(name) {\n this.name = name;\n return this;\n }\n addAttribute(name, value) {\n this.attributes[name] = value;\n return this;\n }\n addChildNode(child) {\n this.children.push(child);\n return this;\n }\n removeAttribute(name) {\n delete this.attributes[name];\n return this;\n }\n n(name) {\n this.name = name;\n return this;\n }\n c(child) {\n this.children.push(child);\n return this;\n }\n a(name, value) {\n if (value != null) {\n this.attributes[name] = value;\n }\n return this;\n }\n cc(input, field, withName = field) {\n if (input[field] != null) {\n const node = XmlNode.of(field, input[field]).withName(withName);\n this.c(node);\n }\n }\n l(input, listName, memberName, valueProvider) {\n if (input[listName] != null) {\n const nodes = valueProvider();\n nodes.map((node) => {\n node.withName(memberName);\n this.c(node);\n });\n }\n }\n lc(input, listName, memberName, valueProvider) {\n if (input[listName] != null) {\n const nodes = valueProvider();\n const containerNode = new XmlNode(memberName);\n nodes.map((node) => {\n containerNode.c(node);\n });\n this.c(containerNode);\n }\n }\n toString() {\n const hasChildren = Boolean(this.children.length);\n let xmlText = `<${this.name}`;\n const attributes = this.attributes;\n for (const attributeName of Object.keys(attributes)) {\n const attribute = attributes[attributeName];\n if (attribute != null) {\n xmlText += ` ${attributeName}=\"${escapeAttribute(\"\" + attribute)}\"`;\n }\n }\n return (xmlText += !hasChildren ? \"/>\" : `>${this.children.map((c) => c.toString()).join(\"\")}`);\n }\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\n/**\n * Copy all the properties of a into b.\n * @param {*} target\n * @param {*} a\n */\nexport function merge(target, a, arrayMode) {\n if (a) {\n const keys = Object.keys(a); // will return an array of own properties\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n if (arrayMode === 'strict') {\n target[keys[i]] = [ a[keys[i]] ];\n } else {\n target[keys[i]] = a[keys[i]];\n }\n }\n }\n}\n/* exports.merge =function (b,a){\n return Object.assign(b,a);\n} */\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n// const fakeCall = function(a) {return a;};\n// const fakeCallNoReturn = function() {};","'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 (!attrNames.hasOwnProperty(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","\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 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};\n \nexport const buildOptions = function(options) {\n return Object.assign({}, defaultOptions, options);\n};\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[\":@\"] = {}; //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\n//TODO: handle comments\nexport default function readDocType(xmlData, i){\n \n const entities = {};\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 { \n i = i+9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for(;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\nconst skipWhitespace = (data, index) => {\n while (index < data.length && /\\s/.test(data[index])) {\n index++;\n }\n return index;\n};\n\nfunction 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 \n // \n // \n // \n // \n \n // Skip leading whitespace after [ , '+', '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(options.leadingZeros && !eAdjacentToLeadingZeros){ //accept with leading zeros\n //remove leading 0s\n trimmedStr = (notation[1] || \"\") + notation[3];\n return Number(trimmedStr);\n }else return str;\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}","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///@ts-check\n\nimport {getAllMatches, isExist} from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport readDocType from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\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\nexport default class OrderedObjParser{\n constructor(options){\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.docTypeEntities = {};\n this.lastEntities = {\n \"apos\" : { regex: /&(apos|#39|#x27);/g, val : \"'\"},\n \"gt\" : { regex: /&(gt|#62|#x3E);/g, val : \">\"},\n \"lt\" : { regex: /&(lt|#60|#x3C);/g, val : \"<\"},\n \"quot\" : { regex: /&(quot|#34|#x22);/g, val : \"\\\"\"},\n };\n this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : \"&\"};\n this.htmlEntities = {\n \"space\": { regex: /&(nbsp|#160);/g, val: \" \" },\n // \"lt\" : { regex: /&(lt|#60);/g, val: \"<\" },\n // \"gt\" : { regex: /&(gt|#62);/g, val: \">\" },\n // \"amp\" : { regex: /&(amp|#38);/g, val: \"&\" },\n // \"quot\" : { regex: /&(quot|#34);/g, val: \"\\\"\" },\n // \"apos\" : { regex: /&(apos|#39);/g, val: \"'\" },\n \"cent\" : { regex: /&(cent|#162);/g, val: \"¢\" },\n \"pound\" : { regex: /&(pound|#163);/g, val: \"£\" },\n \"yen\" : { regex: /&(yen|#165);/g, val: \"¥\" },\n \"euro\" : { regex: /&(euro|#8364);/g, val: \"€\" },\n \"copyright\" : { regex: /&(copy|#169);/g, val: \"©\" },\n \"reg\" : { regex: /&(reg|#174);/g, val: \"®\" },\n \"inr\" : { regex: /&(inr|#8377);/g, val: \"₹\" },\n \"num_dec\": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 10)) },\n \"num_hex\": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCodePoint(Number.parseInt(str, 16)) },\n };\n this.addExternalEntities = addExternalEntities;\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 }\n\n}\n\nfunction addExternalEntities(externalEntities){\n const entKeys = Object.keys(externalEntities);\n for (let i = 0; i < entKeys.length; i++) {\n const ent = entKeys[i];\n this.lastEntities[ent] = {\n regex: new RegExp(\"&\"+ent+\";\",\"g\"),\n val : externalEntities[ent]\n }\n }\n}\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string} 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 if (val !== undefined) {\n if (this.options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if(val.length > 0){\n if(!escapeEntities) val = this.replaceEntitiesValue(val);\n \n const newval = this.options.tagValueProcessor(tagName, val, jPath, 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(this.options.trimValues){\n return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);\n }else{\n const trimmedVal = val.trim();\n if(trimmedVal === val){\n return parseValue(val, this.options.parseTagValue, this.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) {\n if (this.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 for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n if (this.ignoreAttributesFn(attrName, jPath)) {\n continue\n }\n let oldVal = matches[i][4];\n let aName = this.options.attributeNamePrefix + attrName;\n if (attrName.length) {\n if (this.options.transformAttributeName) {\n aName = this.options.transformAttributeName(aName);\n }\n if(aName === \"__proto__\") aName = \"#__proto__\";\n if (oldVal !== undefined) {\n if (this.options.trimValues) {\n oldVal = oldVal.trim();\n }\n oldVal = this.replaceEntitiesValue(oldVal);\n const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);\n if(newVal === null || newVal === undefined){\n //don't parse\n attrs[aName] = oldVal;\n }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){\n //overwrite\n attrs[aName] = newVal;\n }else{\n //parse\n attrs[aName] = parseValue(\n oldVal,\n this.options.parseAttributeValue,\n this.options.numberParseOptions\n );\n }\n } else if (this.options.allowBooleanAttributes) {\n attrs[aName] = true;\n }\n }\n }\n if (!Object.keys(attrs).length) {\n return;\n }\n if (this.options.attributesGroupName) {\n const attrCollection = {};\n attrCollection[this.options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs\n }\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 let jPath = \"\";\n for(let i=0; i< xmlData.length; 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 if( xmlData[i+1] === '/') {//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(this.options.removeNSPrefix){\n const colonIndex = tagName.indexOf(\":\");\n if(colonIndex !== -1){\n tagName = tagName.substr(colonIndex+1);\n }\n }\n\n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n if(currentNode){\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = jPath.substring(jPath.lastIndexOf(\".\")+1);\n if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n let propIndex = 0\n if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){\n propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)\n this.tagsNodeStack.pop();\n }else{\n propIndex = jPath.lastIndexOf(\".\");\n }\n jPath = jPath.substring(0, propIndex);\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if( xmlData[i+1] === '?') {\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, jPath);\n if( (this.options.ignoreDeclaration && tagData.tagName === \"?xml\") || this.options.ignorePiTags){\n\n }else{\n \n const childNode = new xmlNode(tagData.tagName);\n childNode.add(this.options.textNodeName, \"\");\n \n if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);\n }\n this.addChild(currentNode, childNode, jPath, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if(xmlData.substr(i + 1, 3) === '!--') {\n const endIndex = findClosingIndex(xmlData, \"-->\", i+4, \"Comment is not closed.\")\n if(this.options.commentPropName){\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, jPath);\n\n currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);\n }\n i = endIndex;\n } else if( xmlData.substr(i + 1, 2) === '!D') {\n const result = readDocType(xmlData, i);\n this.docTypeEntities = result.entities;\n i = result.i;\n }else if(xmlData.substr(i + 1, 2) === '![') {\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, jPath);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);\n if(val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if(this.options.cdataPropName){\n currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);\n }else{\n currentNode.add(this.options.textNodeName, val);\n }\n \n i = closeIndex + 2;\n }else {//Opening tag\n let result = readTagExp(xmlData,i, this.options.removeNSPrefix);\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 if (this.options.transformTagName) {\n tagName = this.options.transformTagName(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, jPath, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){\n currentNode = this.tagsNodeStack.pop();\n jPath = jPath.substring(0, jPath.lastIndexOf(\".\"));\n }\n if(tagName !== xmlObj.tagname){\n jPath += jPath ? \".\" + tagName : tagName;\n }\n const startIndex = i;\n if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {\n let tagContent = \"\";\n //self-closing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n i = result.closeIndex;\n }\n //unpaired tag\n else if(this.options.unpairedTags.indexOf(tagName) !== -1){\n \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(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n if(tagContent) {\n tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);\n }\n \n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n childNode.add(this.options.textNodeName, tagContent);\n \n this.addChild(currentNode, childNode, jPath, startIndex);\n }else{\n //selfClosing tag\n if(tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1){\n if(tagName[tagName.length - 1] === \"/\"){ //remove trailing '/'\n tagName = tagName.substr(0, tagName.length - 1);\n jPath = jPath.substr(0, jPath.length - 1);\n tagExp = tagName;\n }else{\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n \n if(this.options.transformTagName) {\n tagName = this.options.transformTagName(tagName);\n }\n\n const childNode = new xmlNode(tagName);\n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath, startIndex);\n jPath = jPath.substr(0, jPath.lastIndexOf(\".\"));\n }\n //opening tag\n else{\n const childNode = new xmlNode( tagName);\n this.tagsNodeStack.push(currentNode);\n \n if(tagName !== tagExp && attrExpPresent){\n childNode[\":@\"] = this.buildAttributesMap(tagExp, jPath, tagName);\n }\n this.addChild(currentNode, childNode, jPath, 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, jPath, startIndex){\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n const result = this.options.updateTag(childNode.tagname, jPath, childNode[\":@\"])\n if(result === false){\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\nconst replaceEntitiesValue = function(val){\n\n if(this.options.processEntities){\n for(let entityName in this.docTypeEntities){\n const entity = this.docTypeEntities[entityName];\n val = val.replace( entity.regx, entity.val);\n }\n for(let entityName in this.lastEntities){\n const entity = this.lastEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n if(this.options.htmlEntities){\n for(let entityName in this.htmlEntities){\n const entity = this.htmlEntities[entityName];\n val = val.replace( entity.regex, entity.val);\n }\n }\n val = val.replace( this.ampEntity.regex, this.ampEntity.val);\n }\n return val;\n}\nfunction saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if(isLeafNode === undefined) isLeafNode = currentNode.child.length === 0\n \n textData = this.parseTextData(textData,\n currentNode.tagname,\n jPath,\n false,\n currentNode[\":@\"] ? Object.keys(currentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n currentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n//TODO: use jPath to simplify the logic\n/**\n * \n * @param {string[]} stopNodes \n * @param {string} jPath\n * @param {string} currentTagName \n */\nfunction isItStopNode(stopNodes, jPath, currentTagName){\n const allNodesExp = \"*.\" + currentTagName;\n for (const stopNodePath in stopNodes) {\n const stopNodeExp = stopNodes[stopNodePath];\n if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;\n }\n return false;\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 let attrBoundary;\n let tagExp = \"\";\n for (let index = i; index < xmlData.length; index++) {\n let ch = xmlData[index];\n if (attrBoundary) {\n if (ch === attrBoundary) attrBoundary = \"\";//reset\n } else if (ch === '\"' || ch === \"'\") {\n attrBoundary = ch;\n } else if (ch === closingChar[0]) {\n if(closingChar[1]){\n if(xmlData[index + 1] === closingChar[1]){\n return {\n data: tagExp,\n index: index\n }\n }\n }else{\n return {\n data: tagExp,\n index: index\n }\n }\n } else if (ch === '\\t') {\n ch = \" \"\n }\n tagExp += ch;\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 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 for (; i < xmlData.length; i++) {\n if( xmlData[i] === \"<\"){ \n if (xmlData[i+1] === \"/\") {//close tag\n const closeIndex = findClosingIndex(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(xmlData[i+1] === '?') { \n const closeIndex = findClosingIndex(xmlData, \"?>\", i+1, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 3) === '!--') { \n const closeIndex = findClosingIndex(xmlData, \"-->\", i+3, \"StopNode is not closed.\")\n i=closeIndex;\n } else if(xmlData.substr(i + 1, 2) === '![') { \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","'use strict';\n\nimport XmlNode from './xmlNode.js';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @returns \n */\nexport default function prettify(node, options){\n return compress( node, options);\n}\n\n/**\n * \n * @param {array} arr \n * @param {object} options \n * @param {string} jPath \n * @returns object\n */\nfunction compress(arr, options, jPath){\n let text;\n const compressedObj = {};\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n let newJpath = \"\";\n if(jPath === undefined) newJpath = property;\n else newJpath = jPath + \".\" + property;\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, newJpath);\n const isLeaf = isLeafTag(val, options);\n if (tagObj[METADATA_SYMBOL] !== undefined) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n if(tagObj[\":@\"]){\n assignAttributes( val, tagObj[\":@\"], newJpath, 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(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(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 if (options.isArray(property, newJpath, isLeaf )) {\n compressedObj[property] = [val];\n }else{\n compressedObj[property] = val;\n }\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 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, jpath, 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];\n if (options.isArray(atrrName, jpath + \".\" + atrrName, 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}\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|Buffer} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData,validationOption){\n if(typeof xmlData === \"string\"){\n }else if( xmlData.toString){\n xmlData = xmlData.toString();\n }else{\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\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);\n orderedObjParser.addExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options);\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}\n","'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};","import { XMLParser } from \"fast-xml-parser\";\nconst parser = new XMLParser({\n attributeNamePrefix: \"\",\n htmlEntities: true,\n ignoreAttributes: false,\n ignoreDeclaration: true,\n parseTagValue: false,\n trimValues: false,\n tagValueProcessor: (_, val) => (val.trim() === \"\" && val.includes(\"\\n\") ? \"\" : undefined),\n});\nparser.addEntity(\"#xD\", \"\\r\");\nparser.addEntity(\"#10\", \"\\n\");\nexport function parseXML(xmlString) {\n return parser.parse(xmlString, true);\n}\n","export * from \"./XmlNode\";\nexport * from \"./XmlText\";\nexport { parseXML } from \"./xml-parser\";\n","import { parseXML } from \"@aws-sdk/xml-builder\";\nimport { FromStringShapeDeserializer } from \"@smithy/core/protocols\";\nimport { NormalizedSchema } from \"@smithy/core/schema\";\nimport { getValueFromTextNode } from \"@smithy/smithy-client\";\nimport { toUtf8 } from \"@smithy/util-utf8\";\nimport { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { UnionSerde } from \"../UnionSerde\";\nexport class XmlShapeDeserializer extends SerdeContextConfig {\n settings;\n stringDeserializer;\n constructor(settings) {\n super();\n this.settings = settings;\n this.stringDeserializer = new FromStringShapeDeserializer(settings);\n }\n setSerdeContext(serdeContext) {\n this.serdeContext = serdeContext;\n this.stringDeserializer.setSerdeContext(serdeContext);\n }\n read(schema, bytes, key) {\n const ns = NormalizedSchema.of(schema);\n const memberSchemas = ns.getMemberSchemas();\n const isEventPayload = ns.isStructSchema() &&\n ns.isMemberSchema() &&\n !!Object.values(memberSchemas).find((memberNs) => {\n return !!memberNs.getMemberTraits().eventPayload;\n });\n if (isEventPayload) {\n const output = {};\n const memberName = Object.keys(memberSchemas)[0];\n const eventMemberSchema = memberSchemas[memberName];\n if (eventMemberSchema.isBlobSchema()) {\n output[memberName] = bytes;\n }\n else {\n output[memberName] = this.read(memberSchemas[memberName], bytes);\n }\n return output;\n }\n const xmlString = (this.serdeContext?.utf8Encoder ?? toUtf8)(bytes);\n const parsedObject = this.parseXml(xmlString);\n return this.readSchema(schema, key ? parsedObject[key] : parsedObject);\n }\n readSchema(_schema, value) {\n const ns = NormalizedSchema.of(_schema);\n if (ns.isUnitSchema()) {\n return;\n }\n const traits = ns.getMergedTraits();\n if (ns.isListSchema() && !Array.isArray(value)) {\n return this.readSchema(ns, [value]);\n }\n if (value == null) {\n return value;\n }\n if (typeof value === \"object\") {\n const sparse = !!traits.sparse;\n const flat = !!traits.xmlFlattened;\n if (ns.isListSchema()) {\n const listValue = ns.getValueSchema();\n const buffer = [];\n const sourceKey = listValue.getMergedTraits().xmlName ?? \"member\";\n const source = flat ? value : (value[0] ?? value)[sourceKey];\n const sourceArray = Array.isArray(source) ? source : [source];\n for (const v of sourceArray) {\n if (v != null || sparse) {\n buffer.push(this.readSchema(listValue, v));\n }\n }\n return buffer;\n }\n const buffer = {};\n if (ns.isMapSchema()) {\n const keyNs = ns.getKeySchema();\n const memberNs = ns.getValueSchema();\n let entries;\n if (flat) {\n entries = Array.isArray(value) ? value : [value];\n }\n else {\n entries = Array.isArray(value.entry) ? value.entry : [value.entry];\n }\n const keyProperty = keyNs.getMergedTraits().xmlName ?? \"key\";\n const valueProperty = memberNs.getMergedTraits().xmlName ?? \"value\";\n for (const entry of entries) {\n const key = entry[keyProperty];\n const value = entry[valueProperty];\n if (value != null || sparse) {\n buffer[key] = this.readSchema(memberNs, value);\n }\n }\n return buffer;\n }\n if (ns.isStructSchema()) {\n const union = ns.isUnionSchema();\n let unionSerde;\n if (union) {\n unionSerde = new UnionSerde(value, buffer);\n }\n for (const [memberName, memberSchema] of ns.structIterator()) {\n const memberTraits = memberSchema.getMergedTraits();\n const xmlObjectKey = !memberTraits.httpPayload\n ? memberSchema.getMemberTraits().xmlName ?? memberName\n : memberTraits.xmlName ?? memberSchema.getName();\n if (union) {\n unionSerde.mark(xmlObjectKey);\n }\n if (value[xmlObjectKey] != null) {\n buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]);\n }\n }\n if (union) {\n unionSerde.writeUnknown();\n }\n return buffer;\n }\n if (ns.isDocumentSchema()) {\n return value;\n }\n throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`);\n }\n if (ns.isListSchema()) {\n return [];\n }\n if (ns.isMapSchema() || ns.isStructSchema()) {\n return {};\n }\n return this.stringDeserializer.read(ns, value);\n }\n parseXml(xml) {\n if (xml.length) {\n let parsedObj;\n try {\n parsedObj = parseXML(xml);\n }\n catch (e) {\n if (e && typeof e === \"object\") {\n Object.defineProperty(e, \"$responseBodyText\", {\n value: xml,\n });\n }\n throw e;\n }\n const textNodeName = \"#text\";\n const key = Object.keys(parsedObj)[0];\n const parsedObjToReturn = parsedObj[key];\n if (parsedObjToReturn[textNodeName]) {\n parsedObjToReturn[key] = parsedObjToReturn[textNodeName];\n delete parsedObjToReturn[textNodeName];\n }\n return getValueFromTextNode(parsedObjToReturn);\n }\n return {};\n }\n}\n","import { determineTimestampFormat, extendedEncodeURIComponent } from \"@smithy/core/protocols\";\nimport { NormalizedSchema } from \"@smithy/core/schema\";\nimport { generateIdempotencyToken, NumericValue } from \"@smithy/core/serde\";\nimport { dateToUtcString } from \"@smithy/smithy-client\";\nimport { toBase64 } from \"@smithy/util-base64\";\nimport { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { serializingStructIterator } from \"../structIterator\";\nexport class QueryShapeSerializer extends SerdeContextConfig {\n settings;\n buffer;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n write(schema, value, prefix = \"\") {\n if (this.buffer === undefined) {\n this.buffer = \"\";\n }\n const ns = NormalizedSchema.of(schema);\n if (prefix && !prefix.endsWith(\".\")) {\n prefix += \".\";\n }\n if (ns.isBlobSchema()) {\n if (typeof value === \"string\" || value instanceof Uint8Array) {\n this.writeKey(prefix);\n this.writeValue((this.serdeContext?.base64Encoder ?? toBase64)(value));\n }\n }\n else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) {\n if (value != null) {\n this.writeKey(prefix);\n this.writeValue(String(value));\n }\n else if (ns.isIdempotencyToken()) {\n this.writeKey(prefix);\n this.writeValue(generateIdempotencyToken());\n }\n }\n else if (ns.isBigIntegerSchema()) {\n if (value != null) {\n this.writeKey(prefix);\n this.writeValue(String(value));\n }\n }\n else if (ns.isBigDecimalSchema()) {\n if (value != null) {\n this.writeKey(prefix);\n this.writeValue(value instanceof NumericValue ? value.string : String(value));\n }\n }\n else if (ns.isTimestampSchema()) {\n if (value instanceof Date) {\n this.writeKey(prefix);\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n this.writeValue(value.toISOString().replace(\".000Z\", \"Z\"));\n break;\n case 6:\n this.writeValue(dateToUtcString(value));\n break;\n case 7:\n this.writeValue(String(value.getTime() / 1000));\n break;\n }\n }\n }\n else if (ns.isDocumentSchema()) {\n if (Array.isArray(value)) {\n this.write(64 | 15, value, prefix);\n }\n else if (value instanceof Date) {\n this.write(4, value, prefix);\n }\n else if (value instanceof Uint8Array) {\n this.write(21, value, prefix);\n }\n else if (value && typeof value === \"object\") {\n this.write(128 | 15, value, prefix);\n }\n else {\n this.writeKey(prefix);\n this.writeValue(String(value));\n }\n }\n else if (ns.isListSchema()) {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n if (this.settings.serializeEmptyLists) {\n this.writeKey(prefix);\n this.writeValue(\"\");\n }\n }\n else {\n const member = ns.getValueSchema();\n const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened;\n let i = 1;\n for (const item of value) {\n if (item == null) {\n continue;\n }\n const suffix = this.getKey(\"member\", member.getMergedTraits().xmlName);\n const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`;\n this.write(member, item, key);\n ++i;\n }\n }\n }\n }\n else if (ns.isMapSchema()) {\n if (value && typeof value === \"object\") {\n const keySchema = ns.getKeySchema();\n const memberSchema = ns.getValueSchema();\n const flat = ns.getMergedTraits().xmlFlattened;\n let i = 1;\n for (const [k, v] of Object.entries(value)) {\n if (v == null) {\n continue;\n }\n const keySuffix = this.getKey(\"key\", keySchema.getMergedTraits().xmlName);\n const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`;\n const valueSuffix = this.getKey(\"value\", memberSchema.getMergedTraits().xmlName);\n const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`;\n this.write(keySchema, k, key);\n this.write(memberSchema, v, valueKey);\n ++i;\n }\n }\n }\n else if (ns.isStructSchema()) {\n if (value && typeof value === \"object\") {\n let didWriteMember = false;\n for (const [memberName, member] of serializingStructIterator(ns, value)) {\n if (value[memberName] == null && !member.isIdempotencyToken()) {\n continue;\n }\n const suffix = this.getKey(memberName, member.getMergedTraits().xmlName);\n const key = `${prefix}${suffix}`;\n this.write(member, value[memberName], key);\n didWriteMember = true;\n }\n if (!didWriteMember && ns.isUnionSchema()) {\n const { $unknown } = value;\n if (Array.isArray($unknown)) {\n const [k, v] = $unknown;\n const key = `${prefix}${k}`;\n this.write(15, v, key);\n }\n }\n }\n }\n else if (ns.isUnitSchema()) {\n }\n else {\n throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`);\n }\n }\n flush() {\n if (this.buffer === undefined) {\n throw new Error(\"@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.\");\n }\n const str = this.buffer;\n delete this.buffer;\n return str;\n }\n getKey(memberName, xmlName) {\n const key = xmlName ?? memberName;\n if (this.settings.capitalizeKeys) {\n return key[0].toUpperCase() + key.slice(1);\n }\n return key;\n }\n writeKey(key) {\n if (key.endsWith(\".\")) {\n key = key.slice(0, key.length - 1);\n }\n this.buffer += `&${extendedEncodeURIComponent(key)}=`;\n }\n writeValue(value) {\n this.buffer += extendedEncodeURIComponent(value);\n }\n}\n","import { collectBody, RpcProtocol } from \"@smithy/core/protocols\";\nimport { deref, NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { ProtocolLib } from \"../ProtocolLib\";\nimport { XmlShapeDeserializer } from \"../xml/XmlShapeDeserializer\";\nimport { QueryShapeSerializer } from \"./QueryShapeSerializer\";\nexport class AwsQueryProtocol extends RpcProtocol {\n options;\n serializer;\n deserializer;\n mixin = new ProtocolLib();\n constructor(options) {\n super({\n defaultNamespace: options.defaultNamespace,\n });\n this.options = options;\n const settings = {\n timestampFormat: {\n useTrait: true,\n default: 5,\n },\n httpBindings: false,\n xmlNamespace: options.xmlNamespace,\n serviceNamespace: options.defaultNamespace,\n serializeEmptyLists: true,\n };\n this.serializer = new QueryShapeSerializer(settings);\n this.deserializer = new XmlShapeDeserializer(settings);\n }\n getShapeId() {\n return \"aws.protocols#awsQuery\";\n }\n setSerdeContext(serdeContext) {\n this.serializer.setSerdeContext(serdeContext);\n this.deserializer.setSerdeContext(serdeContext);\n }\n getPayloadCodec() {\n throw new Error(\"AWSQuery protocol has no payload codec.\");\n }\n async serializeRequest(operationSchema, input, context) {\n const request = await super.serializeRequest(operationSchema, input, context);\n if (!request.path.endsWith(\"/\")) {\n request.path += \"/\";\n }\n Object.assign(request.headers, {\n \"content-type\": `application/x-www-form-urlencoded`,\n });\n if (deref(operationSchema.input) === \"unit\" || !request.body) {\n request.body = \"\";\n }\n const action = operationSchema.name.split(\"#\")[1] ?? operationSchema.name;\n request.body = `Action=${action}&Version=${this.options.version}` + request.body;\n if (request.body.endsWith(\"&\")) {\n request.body = request.body.slice(-1);\n }\n return request;\n }\n async deserializeResponse(operationSchema, context, response) {\n const deserializer = this.deserializer;\n const ns = NormalizedSchema.of(operationSchema.output);\n const dataObject = {};\n if (response.statusCode >= 300) {\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n Object.assign(dataObject, await deserializer.read(15, bytes));\n }\n await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));\n }\n for (const header in response.headers) {\n const value = response.headers[header];\n delete response.headers[header];\n response.headers[header.toLowerCase()] = value;\n }\n const shortName = operationSchema.name.split(\"#\")[1] ?? operationSchema.name;\n const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + \"Result\" : undefined;\n const bytes = await collectBody(response.body, context);\n if (bytes.byteLength > 0) {\n Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey));\n }\n const output = {\n $metadata: this.deserializeMetadata(response),\n ...dataObject,\n };\n return output;\n }\n useNestedResult() {\n return true;\n }\n async handleError(operationSchema, context, response, dataObject, metadata) {\n const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? \"Unknown\";\n const errorData = this.loadQueryError(dataObject);\n const message = this.loadQueryErrorMessage(dataObject);\n errorData.message = message;\n errorData.Error = {\n Type: errorData.Type,\n Code: errorData.Code,\n Message: message,\n };\n const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError);\n const ns = NormalizedSchema.of(errorSchema);\n const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error;\n const exception = new ErrorCtor(message);\n const output = {\n Type: errorData.Error.Type,\n Code: errorData.Error.Code,\n Error: errorData.Error,\n };\n for (const [name, member] of ns.structIterator()) {\n const target = member.getMergedTraits().xmlName ?? name;\n const value = errorData[target] ?? dataObject[target];\n output[name] = this.deserializer.readSchema(member, value);\n }\n throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {\n $fault: ns.getMergedTraits().error,\n message,\n }, output), dataObject);\n }\n loadQueryErrorCode(output, data) {\n const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code;\n if (code !== undefined) {\n return code;\n }\n if (output.statusCode == 404) {\n return \"NotFound\";\n }\n }\n loadQueryError(data) {\n return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error;\n }\n loadQueryErrorMessage(data) {\n const errorData = this.loadQueryError(data);\n return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? \"Unknown\";\n }\n getDefaultContentType() {\n return \"application/x-www-form-urlencoded\";\n }\n}\n","import { AwsQueryProtocol } from \"./AwsQueryProtocol\";\nexport class AwsEc2QueryProtocol extends AwsQueryProtocol {\n options;\n constructor(options) {\n super(options);\n this.options = options;\n const ec2Settings = {\n capitalizeKeys: true,\n flattenLists: true,\n serializeEmptyLists: false,\n };\n Object.assign(this.serializer.settings, ec2Settings);\n }\n useNestedResult() {\n return false;\n }\n}\n","import { parseXML } from \"@aws-sdk/xml-builder\";\nimport { getValueFromTextNode } from \"@smithy/smithy-client\";\nimport { collectBodyString } from \"../common\";\nexport const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {\n if (encoded.length) {\n let parsedObj;\n try {\n parsedObj = parseXML(encoded);\n }\n catch (e) {\n if (e && typeof e === \"object\") {\n Object.defineProperty(e, \"$responseBodyText\", {\n value: encoded,\n });\n }\n throw e;\n }\n const textNodeName = \"#text\";\n const key = Object.keys(parsedObj)[0];\n const parsedObjToReturn = parsedObj[key];\n if (parsedObjToReturn[textNodeName]) {\n parsedObjToReturn[key] = parsedObjToReturn[textNodeName];\n delete parsedObjToReturn[textNodeName];\n }\n return getValueFromTextNode(parsedObjToReturn);\n }\n return {};\n});\nexport const parseXmlErrorBody = async (errorBody, context) => {\n const value = await parseXmlBody(errorBody, context);\n if (value.Error) {\n value.Error.message = value.Error.message ?? value.Error.Message;\n }\n return value;\n};\nexport const loadRestXmlErrorCode = (output, data) => {\n if (data?.Error?.Code !== undefined) {\n return data.Error.Code;\n }\n if (data?.Code !== undefined) {\n return data.Code;\n }\n if (output.statusCode == 404) {\n return \"NotFound\";\n }\n};\n","import { XmlNode, XmlText } from \"@aws-sdk/xml-builder\";\nimport { determineTimestampFormat } from \"@smithy/core/protocols\";\nimport { NormalizedSchema } from \"@smithy/core/schema\";\nimport { generateIdempotencyToken, NumericValue } from \"@smithy/core/serde\";\nimport { dateToUtcString } from \"@smithy/smithy-client\";\nimport { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { serializingStructIterator } from \"../structIterator\";\nexport class XmlShapeSerializer extends SerdeContextConfig {\n settings;\n stringBuffer;\n byteBuffer;\n buffer;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n write(schema, value) {\n const ns = NormalizedSchema.of(schema);\n if (ns.isStringSchema() && typeof value === \"string\") {\n this.stringBuffer = value;\n }\n else if (ns.isBlobSchema()) {\n this.byteBuffer =\n \"byteLength\" in value\n ? value\n : (this.serdeContext?.base64Decoder ?? fromBase64)(value);\n }\n else {\n this.buffer = this.writeStruct(ns, value, undefined);\n const traits = ns.getMergedTraits();\n if (traits.httpPayload && !traits.xmlName) {\n this.buffer.withName(ns.getName());\n }\n }\n }\n flush() {\n if (this.byteBuffer !== undefined) {\n const bytes = this.byteBuffer;\n delete this.byteBuffer;\n return bytes;\n }\n if (this.stringBuffer !== undefined) {\n const str = this.stringBuffer;\n delete this.stringBuffer;\n return str;\n }\n const buffer = this.buffer;\n if (this.settings.xmlNamespace) {\n if (!buffer?.attributes?.[\"xmlns\"]) {\n buffer.addAttribute(\"xmlns\", this.settings.xmlNamespace);\n }\n }\n delete this.buffer;\n return buffer.toString();\n }\n writeStruct(ns, value, parentXmlns) {\n const traits = ns.getMergedTraits();\n const name = ns.isMemberSchema() && !traits.httpPayload\n ? ns.getMemberTraits().xmlName ?? ns.getMemberName()\n : traits.xmlName ?? ns.getName();\n if (!name || !ns.isStructSchema()) {\n throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`);\n }\n const structXmlNode = XmlNode.of(name);\n const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);\n for (const [memberName, memberSchema] of serializingStructIterator(ns, value)) {\n const val = value[memberName];\n if (val != null || memberSchema.isIdempotencyToken()) {\n if (memberSchema.getMergedTraits().xmlAttribute) {\n structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val));\n continue;\n }\n if (memberSchema.isListSchema()) {\n this.writeList(memberSchema, val, structXmlNode, xmlns);\n }\n else if (memberSchema.isMapSchema()) {\n this.writeMap(memberSchema, val, structXmlNode, xmlns);\n }\n else if (memberSchema.isStructSchema()) {\n structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns));\n }\n else {\n const memberNode = XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName());\n this.writeSimpleInto(memberSchema, val, memberNode, xmlns);\n structXmlNode.addChildNode(memberNode);\n }\n }\n }\n const { $unknown } = value;\n if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) {\n const [k, v] = $unknown;\n const node = XmlNode.of(k);\n if (typeof v !== \"string\") {\n if (value instanceof XmlNode || value instanceof XmlText) {\n structXmlNode.addChildNode(value);\n }\n else {\n throw new Error(`@aws-sdk - $unknown union member in XML requires ` +\n `value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`);\n }\n }\n this.writeSimpleInto(0, v, node, xmlns);\n structXmlNode.addChildNode(node);\n }\n if (xmlns) {\n structXmlNode.addAttribute(xmlnsAttr, xmlns);\n }\n return structXmlNode;\n }\n writeList(listMember, array, container, parentXmlns) {\n if (!listMember.isMemberSchema()) {\n throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`);\n }\n const listTraits = listMember.getMergedTraits();\n const listValueSchema = listMember.getValueSchema();\n const listValueTraits = listValueSchema.getMergedTraits();\n const sparse = !!listValueTraits.sparse;\n const flat = !!listTraits.xmlFlattened;\n const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns);\n const writeItem = (container, value) => {\n if (listValueSchema.isListSchema()) {\n this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns);\n }\n else if (listValueSchema.isMapSchema()) {\n this.writeMap(listValueSchema, value, container, xmlns);\n }\n else if (listValueSchema.isStructSchema()) {\n const struct = this.writeStruct(listValueSchema, value, xmlns);\n container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? \"member\"));\n }\n else {\n const listItemNode = XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? \"member\");\n this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns);\n container.addChildNode(listItemNode);\n }\n };\n if (flat) {\n for (const value of array) {\n if (sparse || value != null) {\n writeItem(container, value);\n }\n }\n }\n else {\n const listNode = XmlNode.of(listTraits.xmlName ?? listMember.getMemberName());\n if (xmlns) {\n listNode.addAttribute(xmlnsAttr, xmlns);\n }\n for (const value of array) {\n if (sparse || value != null) {\n writeItem(listNode, value);\n }\n }\n container.addChildNode(listNode);\n }\n }\n writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) {\n if (!mapMember.isMemberSchema()) {\n throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`);\n }\n const mapTraits = mapMember.getMergedTraits();\n const mapKeySchema = mapMember.getKeySchema();\n const mapKeyTraits = mapKeySchema.getMergedTraits();\n const keyTag = mapKeyTraits.xmlName ?? \"key\";\n const mapValueSchema = mapMember.getValueSchema();\n const mapValueTraits = mapValueSchema.getMergedTraits();\n const valueTag = mapValueTraits.xmlName ?? \"value\";\n const sparse = !!mapValueTraits.sparse;\n const flat = !!mapTraits.xmlFlattened;\n const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns);\n const addKeyValue = (entry, key, val) => {\n const keyNode = XmlNode.of(keyTag, key);\n const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns);\n if (keyXmlns) {\n keyNode.addAttribute(keyXmlnsAttr, keyXmlns);\n }\n entry.addChildNode(keyNode);\n let valueNode = XmlNode.of(valueTag);\n if (mapValueSchema.isListSchema()) {\n this.writeList(mapValueSchema, val, valueNode, xmlns);\n }\n else if (mapValueSchema.isMapSchema()) {\n this.writeMap(mapValueSchema, val, valueNode, xmlns, true);\n }\n else if (mapValueSchema.isStructSchema()) {\n valueNode = this.writeStruct(mapValueSchema, val, xmlns);\n }\n else {\n this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns);\n }\n entry.addChildNode(valueNode);\n };\n if (flat) {\n for (const [key, val] of Object.entries(map)) {\n if (sparse || val != null) {\n const entry = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName());\n addKeyValue(entry, key, val);\n container.addChildNode(entry);\n }\n }\n }\n else {\n let mapNode;\n if (!containerIsMap) {\n mapNode = XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName());\n if (xmlns) {\n mapNode.addAttribute(xmlnsAttr, xmlns);\n }\n container.addChildNode(mapNode);\n }\n for (const [key, val] of Object.entries(map)) {\n if (sparse || val != null) {\n const entry = XmlNode.of(\"entry\");\n addKeyValue(entry, key, val);\n (containerIsMap ? container : mapNode).addChildNode(entry);\n }\n }\n }\n }\n writeSimple(_schema, value) {\n if (null === value) {\n throw new Error(\"@aws-sdk/core/protocols - (XML serializer) cannot write null value.\");\n }\n const ns = NormalizedSchema.of(_schema);\n let nodeContents = null;\n if (value && typeof value === \"object\") {\n if (ns.isBlobSchema()) {\n nodeContents = (this.serdeContext?.base64Encoder ?? toBase64)(value);\n }\n else if (ns.isTimestampSchema() && value instanceof Date) {\n const format = determineTimestampFormat(ns, this.settings);\n switch (format) {\n case 5:\n nodeContents = value.toISOString().replace(\".000Z\", \"Z\");\n break;\n case 6:\n nodeContents = dateToUtcString(value);\n break;\n case 7:\n nodeContents = String(value.getTime() / 1000);\n break;\n default:\n console.warn(\"Missing timestamp format, using http date\", value);\n nodeContents = dateToUtcString(value);\n break;\n }\n }\n else if (ns.isBigDecimalSchema() && value) {\n if (value instanceof NumericValue) {\n return value.string;\n }\n return String(value);\n }\n else if (ns.isMapSchema() || ns.isListSchema()) {\n throw new Error(\"@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.\");\n }\n else {\n throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`);\n }\n }\n if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) {\n nodeContents = String(value);\n }\n if (ns.isStringSchema()) {\n if (value === undefined && ns.isIdempotencyToken()) {\n nodeContents = generateIdempotencyToken();\n }\n else {\n nodeContents = String(value);\n }\n }\n if (nodeContents === null) {\n throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`);\n }\n return nodeContents;\n }\n writeSimpleInto(_schema, value, into, parentXmlns) {\n const nodeContents = this.writeSimple(_schema, value);\n const ns = NormalizedSchema.of(_schema);\n const content = new XmlText(nodeContents);\n const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns);\n if (xmlns) {\n into.addAttribute(xmlnsAttr, xmlns);\n }\n into.addChildNode(content);\n }\n getXmlnsAttribute(ns, parentXmlns) {\n const traits = ns.getMergedTraits();\n const [prefix, xmlns] = traits.xmlNamespace ?? [];\n if (xmlns && xmlns !== parentXmlns) {\n return [prefix ? `xmlns:${prefix}` : \"xmlns\", xmlns];\n }\n return [void 0, void 0];\n }\n}\n","import { SerdeContextConfig } from \"../ConfigurableSerdeContext\";\nimport { XmlShapeDeserializer } from \"./XmlShapeDeserializer\";\nimport { XmlShapeSerializer } from \"./XmlShapeSerializer\";\nexport class XmlCodec extends SerdeContextConfig {\n settings;\n constructor(settings) {\n super();\n this.settings = settings;\n }\n createSerializer() {\n const serializer = new XmlShapeSerializer(this.settings);\n serializer.setSerdeContext(this.serdeContext);\n return serializer;\n }\n createDeserializer() {\n const deserializer = new XmlShapeDeserializer(this.settings);\n deserializer.setSerdeContext(this.serdeContext);\n return deserializer;\n }\n}\n","import { HttpBindingProtocol, HttpInterceptingShapeDeserializer, HttpInterceptingShapeSerializer, } from \"@smithy/core/protocols\";\nimport { NormalizedSchema, TypeRegistry } from \"@smithy/core/schema\";\nimport { ProtocolLib } from \"../ProtocolLib\";\nimport { loadRestXmlErrorCode } from \"./parseXmlBody\";\nimport { XmlCodec } from \"./XmlCodec\";\nexport class AwsRestXmlProtocol extends HttpBindingProtocol {\n codec;\n serializer;\n deserializer;\n mixin = new ProtocolLib();\n constructor(options) {\n super(options);\n const settings = {\n timestampFormat: {\n useTrait: true,\n default: 5,\n },\n httpBindings: true,\n xmlNamespace: options.xmlNamespace,\n serviceNamespace: options.defaultNamespace,\n };\n this.codec = new XmlCodec(settings);\n this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings);\n this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings);\n }\n getPayloadCodec() {\n return this.codec;\n }\n getShapeId() {\n return \"aws.protocols#restXml\";\n }\n async serializeRequest(operationSchema, input, context) {\n const request = await super.serializeRequest(operationSchema, input, context);\n const inputSchema = NormalizedSchema.of(operationSchema.input);\n if (!request.headers[\"content-type\"]) {\n const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema);\n if (contentType) {\n request.headers[\"content-type\"] = contentType;\n }\n }\n if (typeof request.body === \"string\" &&\n request.headers[\"content-type\"] === this.getDefaultContentType() &&\n !request.body.startsWith(\"' + request.body;\n }\n return request;\n }\n async deserializeResponse(operationSchema, context, response) {\n return super.deserializeResponse(operationSchema, context, response);\n }\n async handleError(operationSchema, context, response, dataObject, metadata) {\n const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? \"Unknown\";\n const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata);\n const ns = NormalizedSchema.of(errorSchema);\n const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? \"Unknown\";\n const ErrorCtor = TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error;\n const exception = new ErrorCtor(message);\n await this.deserializeHttpMessage(errorSchema, context, response, dataObject);\n const output = {};\n for (const [name, member] of ns.structIterator()) {\n const target = member.getMergedTraits().xmlName ?? name;\n const value = dataObject.Error?.[target] ?? dataObject[target];\n output[name] = this.codec.createDeserializer().readSchema(member, value);\n }\n throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, {\n $fault: ns.getMergedTraits().error,\n message,\n }, output), dataObject);\n }\n getDefaultContentType() {\n return \"application/xml\";\n }\n hasUnstructuredPayloadBinding(ns) {\n for (const [, member] of ns.structIterator()) {\n if (member.getMergedTraits().httpPayload) {\n return !(member.isStructSchema() || member.isMapSchema() || member.isListSchema());\n }\n }\n return false;\n }\n}\n","export * from \"./cbor/AwsSmithyRpcV2CborProtocol\";\nexport * from \"./coercing-serializers\";\nexport * from \"./json/AwsJson1_0Protocol\";\nexport * from \"./json/AwsJson1_1Protocol\";\nexport * from \"./json/AwsJsonRpcProtocol\";\nexport * from \"./json/AwsRestJsonProtocol\";\nexport * from \"./json/JsonCodec\";\nexport * from \"./json/JsonShapeDeserializer\";\nexport * from \"./json/JsonShapeSerializer\";\nexport * from \"./json/awsExpectUnion\";\nexport * from \"./json/parseJsonBody\";\nexport * from \"./query/AwsEc2QueryProtocol\";\nexport * from \"./query/AwsQueryProtocol\";\nexport * from \"./xml/AwsRestXmlProtocol\";\nexport * from \"./xml/XmlCodec\";\nexport * from \"./xml/XmlShapeDeserializer\";\nexport * from \"./xml/XmlShapeSerializer\";\nexport * from \"./xml/parseXmlBody\";\n","export * from \"./submodules/client/index\";\nexport * from \"./submodules/httpAuthSchemes/index\";\nexport * from \"./submodules/protocols/index\";\n","import { HttpRequest } from \"@smithy/protocol-http\";\nexport function resolveHostHeaderConfig(input) {\n return input;\n}\nexport const hostHeaderMiddleware = (options) => (next) => async (args) => {\n if (!HttpRequest.isInstance(args.request))\n return next(args);\n const { request } = args;\n const { handlerProtocol = \"\" } = options.requestHandler.metadata || {};\n if (handlerProtocol.indexOf(\"h2\") >= 0 && !request.headers[\":authority\"]) {\n delete request.headers[\"host\"];\n request.headers[\":authority\"] = request.hostname + (request.port ? \":\" + request.port : \"\");\n }\n else if (!request.headers[\"host\"]) {\n let host = request.hostname;\n if (request.port != null)\n host += `:${request.port}`;\n request.headers[\"host\"] = host;\n }\n return next(args);\n};\nexport const hostHeaderMiddlewareOptions = {\n name: \"hostHeaderMiddleware\",\n step: \"build\",\n priority: \"low\",\n tags: [\"HOST\"],\n override: true,\n};\nexport const getHostHeaderPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);\n },\n});\n","export const loggerMiddleware = () => (next, context) => async (args) => {\n try {\n const response = await next(args);\n const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context;\n const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;\n const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;\n const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;\n const { $metadata, ...outputWithoutMetadata } = response.output;\n logger?.info?.({\n clientName,\n commandName,\n input: inputFilterSensitiveLog(args.input),\n output: outputFilterSensitiveLog(outputWithoutMetadata),\n metadata: $metadata,\n });\n return response;\n }\n catch (error) {\n const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context;\n const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;\n const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;\n logger?.error?.({\n clientName,\n commandName,\n input: inputFilterSensitiveLog(args.input),\n error,\n metadata: error.$metadata,\n });\n throw error;\n }\n};\nexport const loggerMiddlewareOptions = {\n name: \"loggerMiddleware\",\n tags: [\"LOGGER\"],\n step: \"initialize\",\n override: true,\n};\nexport const getLoggerPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);\n },\n});\n","export * from \"./loggerMiddleware\";\n","export const recursionDetectionMiddlewareOptions = {\n step: \"build\",\n tags: [\"RECURSION_DETECTION\"],\n name: \"recursionDetectionMiddleware\",\n override: true,\n priority: \"low\",\n};\n","const PROTECTED_KEYS = {\n REQUEST_ID: Symbol.for(\"_AWS_LAMBDA_REQUEST_ID\"),\n X_RAY_TRACE_ID: Symbol.for(\"_AWS_LAMBDA_X_RAY_TRACE_ID\"),\n TENANT_ID: Symbol.for(\"_AWS_LAMBDA_TENANT_ID\"),\n};\nconst NO_GLOBAL_AWS_LAMBDA = [\"true\", \"1\"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? \"\");\nif (!NO_GLOBAL_AWS_LAMBDA) {\n globalThis.awslambda = globalThis.awslambda || {};\n}\nclass InvokeStoreBase {\n static PROTECTED_KEYS = PROTECTED_KEYS;\n isProtectedKey(key) {\n return Object.values(PROTECTED_KEYS).includes(key);\n }\n getRequestId() {\n return this.get(PROTECTED_KEYS.REQUEST_ID) ?? \"-\";\n }\n getXRayTraceId() {\n return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID);\n }\n getTenantId() {\n return this.get(PROTECTED_KEYS.TENANT_ID);\n }\n}\nclass InvokeStoreSingle extends InvokeStoreBase {\n currentContext;\n getContext() {\n return this.currentContext;\n }\n hasContext() {\n return this.currentContext !== undefined;\n }\n get(key) {\n return this.currentContext?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n this.currentContext = this.currentContext || {};\n this.currentContext[key] = value;\n }\n run(context, fn) {\n this.currentContext = context;\n return fn();\n }\n}\nclass InvokeStoreMulti extends InvokeStoreBase {\n als;\n static async create() {\n const instance = new InvokeStoreMulti();\n const asyncHooks = await import('node:async_hooks');\n instance.als = new asyncHooks.AsyncLocalStorage();\n return instance;\n }\n getContext() {\n return this.als.getStore();\n }\n hasContext() {\n return this.als.getStore() !== undefined;\n }\n get(key) {\n return this.als.getStore()?.[key];\n }\n set(key, value) {\n if (this.isProtectedKey(key)) {\n throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`);\n }\n const store = this.als.getStore();\n if (!store) {\n throw new Error(\"No context available\");\n }\n store[key] = value;\n }\n run(context, fn) {\n return this.als.run(context, fn);\n }\n}\nvar InvokeStore;\n(function (InvokeStore) {\n let instance = null;\n async function getInstanceAsync() {\n if (!instance) {\n instance = (async () => {\n const isMulti = \"AWS_LAMBDA_MAX_CONCURRENCY\" in process.env;\n const newInstance = isMulti\n ? await InvokeStoreMulti.create()\n : new InvokeStoreSingle();\n if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) {\n return globalThis.awslambda.InvokeStore;\n }\n else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) {\n globalThis.awslambda.InvokeStore = newInstance;\n return newInstance;\n }\n else {\n return newInstance;\n }\n })();\n }\n return instance;\n }\n InvokeStore.getInstanceAsync = getInstanceAsync;\n InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === \"1\"\n ? {\n reset: () => {\n instance = null;\n if (globalThis.awslambda?.InvokeStore) {\n delete globalThis.awslambda.InvokeStore;\n }\n globalThis.awslambda = {};\n },\n }\n : undefined;\n})(InvokeStore || (InvokeStore = {}));\n\nexport { InvokeStore, InvokeStoreBase };\n","import { InvokeStore } from \"@aws/lambda-invoke-store\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nconst TRACE_ID_HEADER_NAME = \"X-Amzn-Trace-Id\";\nconst ENV_LAMBDA_FUNCTION_NAME = \"AWS_LAMBDA_FUNCTION_NAME\";\nconst ENV_TRACE_ID = \"_X_AMZN_TRACE_ID\";\nexport const recursionDetectionMiddleware = () => (next) => async (args) => {\n const { request } = args;\n if (!HttpRequest.isInstance(request)) {\n return next(args);\n }\n const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ??\n TRACE_ID_HEADER_NAME;\n if (request.headers.hasOwnProperty(traceIdHeader)) {\n return next(args);\n }\n const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];\n const traceIdFromEnv = process.env[ENV_TRACE_ID];\n const invokeStore = await InvokeStore.getInstanceAsync();\n const traceIdFromInvokeStore = invokeStore?.getXRayTraceId();\n const traceId = traceIdFromInvokeStore ?? traceIdFromEnv;\n const nonEmptyString = (str) => typeof str === \"string\" && str.length > 0;\n if (nonEmptyString(functionName) && nonEmptyString(traceId)) {\n request.headers[TRACE_ID_HEADER_NAME] = traceId;\n }\n return next({\n ...args,\n request,\n });\n};\n","import { recursionDetectionMiddlewareOptions } from \"./configuration\";\nimport { recursionDetectionMiddleware } from \"./recursionDetectionMiddleware\";\nexport const getRecursionDetectionPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.add(recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions);\n },\n});\n","export * from \"./getRecursionDetectionPlugin\";\nexport * from \"./recursionDetectionMiddleware\";\n","export const booleanSelector = (obj, key, type) => {\n if (!(key in obj))\n return undefined;\n if (obj[key] === \"true\")\n return true;\n if (obj[key] === \"false\")\n return false;\n throw new Error(`Cannot load ${type} \"${key}\". Expected \"true\" or \"false\", got ${obj[key]}.`);\n};\n","export const numberSelector = (obj, key, type) => {\n if (!(key in obj))\n return undefined;\n const numberValue = parseInt(obj[key], 10);\n if (Number.isNaN(numberValue)) {\n throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`);\n }\n return numberValue;\n};\n","export var SelectorType;\n(function (SelectorType) {\n SelectorType[\"ENV\"] = \"env\";\n SelectorType[\"CONFIG\"] = \"shared config entry\";\n})(SelectorType || (SelectorType = {}));\n","export * from \"./booleanSelector\";\nexport * from \"./numberSelector\";\nexport * from \"./types\";\n","import { normalizeProvider } from \"@smithy/core\";\nexport const DEFAULT_UA_APP_ID = undefined;\nfunction isValidUserAgentAppId(appId) {\n if (appId === undefined) {\n return true;\n }\n return typeof appId === \"string\" && appId.length <= 50;\n}\nexport function resolveUserAgentConfig(input) {\n const normalizedAppIdProvider = normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID);\n const { customUserAgent } = input;\n return Object.assign(input, {\n customUserAgent: typeof customUserAgent === \"string\" ? [[customUserAgent]] : customUserAgent,\n userAgentAppId: async () => {\n const appId = await normalizedAppIdProvider();\n if (!isValidUserAgentAppId(appId)) {\n const logger = input.logger?.constructor?.name === \"NoOpLogger\" || !input.logger ? console : input.logger;\n if (typeof appId !== \"string\") {\n logger?.warn(\"userAgentAppId must be a string or undefined.\");\n }\n else if (appId.length > 50) {\n logger?.warn(\"The provided userAgentAppId exceeds the maximum length of 50 characters.\");\n }\n }\n return appId;\n },\n });\n}\n","export class EndpointCache {\n capacity;\n data = new Map();\n parameters = [];\n constructor({ size, params }) {\n this.capacity = size ?? 50;\n if (params) {\n this.parameters = params;\n }\n }\n get(endpointParams, resolver) {\n const key = this.hash(endpointParams);\n if (key === false) {\n return resolver();\n }\n if (!this.data.has(key)) {\n if (this.data.size > this.capacity + 10) {\n const keys = this.data.keys();\n let i = 0;\n while (true) {\n const { value, done } = keys.next();\n this.data.delete(value);\n if (done || ++i > 10) {\n break;\n }\n }\n }\n this.data.set(key, resolver());\n }\n return this.data.get(key);\n }\n size() {\n return this.data.size;\n }\n hash(endpointParams) {\n let buffer = \"\";\n const { parameters } = this;\n if (parameters.length === 0) {\n return false;\n }\n for (const param of parameters) {\n const val = String(endpointParams[param] ?? \"\");\n if (val.includes(\"|;\")) {\n return false;\n }\n buffer += val + \"|;\";\n }\n return buffer;\n }\n}\n","const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]\\\\d|\\\\d)){3}$`);\nexport const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith(\"[\") && value.endsWith(\"]\"));\n","const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);\nexport const isValidHostLabel = (value, allowSubDomains = false) => {\n if (!allowSubDomains) {\n return VALID_HOST_LABEL_REGEX.test(value);\n }\n const labels = value.split(\".\");\n for (const label of labels) {\n if (!isValidHostLabel(label)) {\n return false;\n }\n }\n return true;\n};\n","export const customEndpointFunctions = {};\n","export const debugId = \"endpoints\";\n","export function toDebugString(input) {\n if (typeof input !== \"object\" || input == null) {\n return input;\n }\n if (\"ref\" in input) {\n return `$${toDebugString(input.ref)}`;\n }\n if (\"fn\" in input) {\n return `${input.fn}(${(input.argv || []).map(toDebugString).join(\", \")})`;\n }\n return JSON.stringify(input, null, 2);\n}\n","export * from \"./debugId\";\nexport * from \"./toDebugString\";\n","export class EndpointError extends Error {\n constructor(message) {\n super(message);\n this.name = \"EndpointError\";\n }\n}\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./EndpointError\";\nexport * from \"./EndpointFunctions\";\nexport * from \"./EndpointRuleObject\";\nexport * from \"./ErrorRuleObject\";\nexport * from \"./RuleSetObject\";\nexport * from \"./TreeRuleObject\";\nexport * from \"./shared\";\n","export const booleanEquals = (value1, value2) => value1 === value2;\n","import { EndpointError } from \"../types\";\nexport const getAttrPathList = (path) => {\n const parts = path.split(\".\");\n const pathList = [];\n for (const part of parts) {\n const squareBracketIndex = part.indexOf(\"[\");\n if (squareBracketIndex !== -1) {\n if (part.indexOf(\"]\") !== part.length - 1) {\n throw new EndpointError(`Path: '${path}' does not end with ']'`);\n }\n const arrayIndex = part.slice(squareBracketIndex + 1, -1);\n if (Number.isNaN(parseInt(arrayIndex))) {\n throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`);\n }\n if (squareBracketIndex !== 0) {\n pathList.push(part.slice(0, squareBracketIndex));\n }\n pathList.push(arrayIndex);\n }\n else {\n pathList.push(part);\n }\n }\n return pathList;\n};\n","import { EndpointError } from \"../types\";\nimport { getAttrPathList } from \"./getAttrPathList\";\nexport const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => {\n if (typeof acc !== \"object\") {\n throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`);\n }\n else if (Array.isArray(acc)) {\n return acc[parseInt(index)];\n }\n return acc[index];\n}, value);\n","export const isSet = (value) => value != null;\n","export const not = (value) => !value;\n","import { EndpointURLScheme } from \"@smithy/types\";\nimport { isIpAddress } from \"./isIpAddress\";\nconst DEFAULT_PORTS = {\n [EndpointURLScheme.HTTP]: 80,\n [EndpointURLScheme.HTTPS]: 443,\n};\nexport const parseURL = (value) => {\n const whatwgURL = (() => {\n try {\n if (value instanceof URL) {\n return value;\n }\n if (typeof value === \"object\" && \"hostname\" in value) {\n const { hostname, port, protocol = \"\", path = \"\", query = {} } = value;\n const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : \"\"}${path}`);\n url.search = Object.entries(query)\n .map(([k, v]) => `${k}=${v}`)\n .join(\"&\");\n return url;\n }\n return new URL(value);\n }\n catch (error) {\n return null;\n }\n })();\n if (!whatwgURL) {\n console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);\n return null;\n }\n const urlString = whatwgURL.href;\n const { host, hostname, pathname, protocol, search } = whatwgURL;\n if (search) {\n return null;\n }\n const scheme = protocol.slice(0, -1);\n if (!Object.values(EndpointURLScheme).includes(scheme)) {\n return null;\n }\n const isIp = isIpAddress(hostname);\n const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) ||\n (typeof value === \"string\" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`));\n const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;\n return {\n scheme,\n authority,\n path: pathname,\n normalizedPath: pathname.endsWith(\"/\") ? pathname : `${pathname}/`,\n isIp,\n };\n};\n","export const stringEquals = (value1, value2) => value1 === value2;\n","export const substring = (input, start, stop, reverse) => {\n if (start >= stop || input.length < stop) {\n return null;\n }\n if (!reverse) {\n return input.substring(start, stop);\n }\n return input.substring(input.length - stop, input.length - start);\n};\n","export const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n","export * from \"./booleanEquals\";\nexport * from \"./getAttr\";\nexport * from \"./isSet\";\nexport * from \"./isValidHostLabel\";\nexport * from \"./not\";\nexport * from \"./parseURL\";\nexport * from \"./stringEquals\";\nexport * from \"./substring\";\nexport * from \"./uriEncode\";\n","import { booleanEquals, getAttr, isSet, isValidHostLabel, not, parseURL, stringEquals, substring, uriEncode, } from \"../lib\";\nexport const endpointFunctions = {\n booleanEquals,\n getAttr,\n isSet,\n isValidHostLabel,\n not,\n parseURL,\n stringEquals,\n substring,\n uriEncode,\n};\n","import { getAttr } from \"../lib\";\nexport const evaluateTemplate = (template, options) => {\n const evaluatedTemplateArr = [];\n const templateContext = {\n ...options.endpointParams,\n ...options.referenceRecord,\n };\n let currentIndex = 0;\n while (currentIndex < template.length) {\n const openingBraceIndex = template.indexOf(\"{\", currentIndex);\n if (openingBraceIndex === -1) {\n evaluatedTemplateArr.push(template.slice(currentIndex));\n break;\n }\n evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));\n const closingBraceIndex = template.indexOf(\"}\", openingBraceIndex);\n if (closingBraceIndex === -1) {\n evaluatedTemplateArr.push(template.slice(openingBraceIndex));\n break;\n }\n if (template[openingBraceIndex + 1] === \"{\" && template[closingBraceIndex + 1] === \"}\") {\n evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));\n currentIndex = closingBraceIndex + 2;\n }\n const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);\n if (parameterName.includes(\"#\")) {\n const [refName, attrName] = parameterName.split(\"#\");\n evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));\n }\n else {\n evaluatedTemplateArr.push(templateContext[parameterName]);\n }\n currentIndex = closingBraceIndex + 1;\n }\n return evaluatedTemplateArr.join(\"\");\n};\n","export const getReferenceValue = ({ ref }, options) => {\n const referenceRecord = {\n ...options.endpointParams,\n ...options.referenceRecord,\n };\n return referenceRecord[ref];\n};\n","import { EndpointError } from \"../types\";\nimport { customEndpointFunctions } from \"./customEndpointFunctions\";\nimport { endpointFunctions } from \"./endpointFunctions\";\nimport { evaluateTemplate } from \"./evaluateTemplate\";\nimport { getReferenceValue } from \"./getReferenceValue\";\nexport const evaluateExpression = (obj, keyName, options) => {\n if (typeof obj === \"string\") {\n return evaluateTemplate(obj, options);\n }\n else if (obj[\"fn\"]) {\n return group.callFunction(obj, options);\n }\n else if (obj[\"ref\"]) {\n return getReferenceValue(obj, options);\n }\n throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);\n};\nexport const callFunction = ({ fn, argv }, options) => {\n const evaluatedArgs = argv.map((arg) => [\"boolean\", \"number\"].includes(typeof arg) ? arg : group.evaluateExpression(arg, \"arg\", options));\n const fnSegments = fn.split(\".\");\n if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {\n return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);\n }\n return endpointFunctions[fn](...evaluatedArgs);\n};\nexport const group = {\n evaluateExpression,\n callFunction,\n};\n","export { callFunction } from \"./evaluateExpression\";\n","import { debugId, toDebugString } from \"../debug\";\nimport { EndpointError } from \"../types\";\nimport { callFunction } from \"./callFunction\";\nexport const evaluateCondition = ({ assign, ...fnArgs }, options) => {\n if (assign && assign in options.referenceRecord) {\n throw new EndpointError(`'${assign}' is already defined in Reference Record.`);\n }\n const value = callFunction(fnArgs, options);\n options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);\n return {\n result: value === \"\" ? true : !!value,\n ...(assign != null && { toAssign: { name: assign, value } }),\n };\n};\n","import { debugId, toDebugString } from \"../debug\";\nimport { evaluateCondition } from \"./evaluateCondition\";\nexport const evaluateConditions = (conditions = [], options) => {\n const conditionsReferenceRecord = {};\n for (const condition of conditions) {\n const { result, toAssign } = evaluateCondition(condition, {\n ...options,\n referenceRecord: {\n ...options.referenceRecord,\n ...conditionsReferenceRecord,\n },\n });\n if (!result) {\n return { result };\n }\n if (toAssign) {\n conditionsReferenceRecord[toAssign.name] = toAssign.value;\n options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);\n }\n }\n return { result: true, referenceRecord: conditionsReferenceRecord };\n};\n","import { EndpointError } from \"../types\";\nimport { evaluateExpression } from \"./evaluateExpression\";\nexport const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({\n ...acc,\n [headerKey]: headerVal.map((headerValEntry) => {\n const processedExpr = evaluateExpression(headerValEntry, \"Header value entry\", options);\n if (typeof processedExpr !== \"string\") {\n throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);\n }\n return processedExpr;\n }),\n}), {});\n","import { EndpointError } from \"../types\";\nimport { evaluateTemplate } from \"./evaluateTemplate\";\nexport const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({\n ...acc,\n [propertyKey]: group.getEndpointProperty(propertyVal, options),\n}), {});\nexport const getEndpointProperty = (property, options) => {\n if (Array.isArray(property)) {\n return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));\n }\n switch (typeof property) {\n case \"string\":\n return evaluateTemplate(property, options);\n case \"object\":\n if (property === null) {\n throw new EndpointError(`Unexpected endpoint property: ${property}`);\n }\n return group.getEndpointProperties(property, options);\n case \"boolean\":\n return property;\n default:\n throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`);\n }\n};\nexport const group = {\n getEndpointProperty,\n getEndpointProperties,\n};\n","import { EndpointError } from \"../types\";\nimport { evaluateExpression } from \"./evaluateExpression\";\nexport const getEndpointUrl = (endpointUrl, options) => {\n const expression = evaluateExpression(endpointUrl, \"Endpoint URL\", options);\n if (typeof expression === \"string\") {\n try {\n return new URL(expression);\n }\n catch (error) {\n console.error(`Failed to construct URL with ${expression}`, error);\n throw error;\n }\n }\n throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`);\n};\n","import { debugId, toDebugString } from \"../debug\";\nimport { evaluateConditions } from \"./evaluateConditions\";\nimport { getEndpointHeaders } from \"./getEndpointHeaders\";\nimport { getEndpointProperties } from \"./getEndpointProperties\";\nimport { getEndpointUrl } from \"./getEndpointUrl\";\nexport const evaluateEndpointRule = (endpointRule, options) => {\n const { conditions, endpoint } = endpointRule;\n const { result, referenceRecord } = evaluateConditions(conditions, options);\n if (!result) {\n return;\n }\n const endpointRuleOptions = {\n ...options,\n referenceRecord: { ...options.referenceRecord, ...referenceRecord },\n };\n const { url, properties, headers } = endpoint;\n options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);\n return {\n ...(headers != undefined && {\n headers: getEndpointHeaders(headers, endpointRuleOptions),\n }),\n ...(properties != undefined && {\n properties: getEndpointProperties(properties, endpointRuleOptions),\n }),\n url: getEndpointUrl(url, endpointRuleOptions),\n };\n};\n","import { EndpointError } from \"../types\";\nimport { evaluateConditions } from \"./evaluateConditions\";\nimport { evaluateExpression } from \"./evaluateExpression\";\nexport const evaluateErrorRule = (errorRule, options) => {\n const { conditions, error } = errorRule;\n const { result, referenceRecord } = evaluateConditions(conditions, options);\n if (!result) {\n return;\n }\n throw new EndpointError(evaluateExpression(error, \"Error\", {\n ...options,\n referenceRecord: { ...options.referenceRecord, ...referenceRecord },\n }));\n};\n","import { EndpointError } from \"../types\";\nimport { evaluateConditions } from \"./evaluateConditions\";\nimport { evaluateEndpointRule } from \"./evaluateEndpointRule\";\nimport { evaluateErrorRule } from \"./evaluateErrorRule\";\nexport const evaluateRules = (rules, options) => {\n for (const rule of rules) {\n if (rule.type === \"endpoint\") {\n const endpointOrUndefined = evaluateEndpointRule(rule, options);\n if (endpointOrUndefined) {\n return endpointOrUndefined;\n }\n }\n else if (rule.type === \"error\") {\n evaluateErrorRule(rule, options);\n }\n else if (rule.type === \"tree\") {\n const endpointOrUndefined = group.evaluateTreeRule(rule, options);\n if (endpointOrUndefined) {\n return endpointOrUndefined;\n }\n }\n else {\n throw new EndpointError(`Unknown endpoint rule: ${rule}`);\n }\n }\n throw new EndpointError(`Rules evaluation failed`);\n};\nexport const evaluateTreeRule = (treeRule, options) => {\n const { conditions, rules } = treeRule;\n const { result, referenceRecord } = evaluateConditions(conditions, options);\n if (!result) {\n return;\n }\n return group.evaluateRules(rules, {\n ...options,\n referenceRecord: { ...options.referenceRecord, ...referenceRecord },\n });\n};\nexport const group = {\n evaluateRules,\n evaluateTreeRule,\n};\n","export * from \"./customEndpointFunctions\";\nexport * from \"./evaluateRules\";\n","import { debugId, toDebugString } from \"./debug\";\nimport { EndpointError } from \"./types\";\nimport { evaluateRules } from \"./utils\";\nexport const resolveEndpoint = (ruleSetObject, options) => {\n const { endpointParams, logger } = options;\n const { parameters, rules } = ruleSetObject;\n options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);\n const paramsWithDefault = Object.entries(parameters)\n .filter(([, v]) => v.default != null)\n .map(([k, v]) => [k, v.default]);\n if (paramsWithDefault.length > 0) {\n for (const [paramKey, paramDefaultValue] of paramsWithDefault) {\n endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;\n }\n }\n const requiredParams = Object.entries(parameters)\n .filter(([, v]) => v.required)\n .map(([k]) => k);\n for (const requiredParam of requiredParams) {\n if (endpointParams[requiredParam] == null) {\n throw new EndpointError(`Missing required parameter: '${requiredParam}'`);\n }\n }\n const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} });\n options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);\n return endpoint;\n};\n","export * from \"./cache/EndpointCache\";\nexport * from \"./lib/isIpAddress\";\nexport * from \"./lib/isValidHostLabel\";\nexport * from \"./utils/customEndpointFunctions\";\nexport * from \"./resolveEndpoint\";\nexport * from \"./types\";\n","export { isIpAddress } from \"@smithy/util-endpoints\";\n","import { isValidHostLabel } from \"@smithy/util-endpoints\";\nimport { isIpAddress } from \"../isIpAddress\";\nexport const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => {\n if (allowSubDomains) {\n for (const label of value.split(\".\")) {\n if (!isVirtualHostableS3Bucket(label)) {\n return false;\n }\n }\n return true;\n }\n if (!isValidHostLabel(value)) {\n return false;\n }\n if (value.length < 3 || value.length > 63) {\n return false;\n }\n if (value !== value.toLowerCase()) {\n return false;\n }\n if (isIpAddress(value)) {\n return false;\n }\n return true;\n};\n","const ARN_DELIMITER = \":\";\nconst RESOURCE_DELIMITER = \"/\";\nexport const parseArn = (value) => {\n const segments = value.split(ARN_DELIMITER);\n if (segments.length < 6)\n return null;\n const [arn, partition, service, region, accountId, ...resourcePath] = segments;\n if (arn !== \"arn\" || partition === \"\" || service === \"\" || resourcePath.join(ARN_DELIMITER) === \"\")\n return null;\n const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();\n return {\n partition,\n service,\n region,\n accountId,\n resourceId,\n };\n};\n","{\n \"partitions\": [{\n \"id\": \"aws\",\n \"outputs\": {\n \"dnsSuffix\": \"amazonaws.com\",\n \"dualStackDnsSuffix\": \"api.aws\",\n \"implicitGlobalRegion\": \"us-east-1\",\n \"name\": \"aws\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^(us|eu|ap|sa|ca|me|af|il|mx)\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"af-south-1\": {\n \"description\": \"Africa (Cape Town)\"\n },\n \"ap-east-1\": {\n \"description\": \"Asia Pacific (Hong Kong)\"\n },\n \"ap-east-2\": {\n \"description\": \"Asia Pacific (Taipei)\"\n },\n \"ap-northeast-1\": {\n \"description\": \"Asia Pacific (Tokyo)\"\n },\n \"ap-northeast-2\": {\n \"description\": \"Asia Pacific (Seoul)\"\n },\n \"ap-northeast-3\": {\n \"description\": \"Asia Pacific (Osaka)\"\n },\n \"ap-south-1\": {\n \"description\": \"Asia Pacific (Mumbai)\"\n },\n \"ap-south-2\": {\n \"description\": \"Asia Pacific (Hyderabad)\"\n },\n \"ap-southeast-1\": {\n \"description\": \"Asia Pacific (Singapore)\"\n },\n \"ap-southeast-2\": {\n \"description\": \"Asia Pacific (Sydney)\"\n },\n \"ap-southeast-3\": {\n \"description\": \"Asia Pacific (Jakarta)\"\n },\n \"ap-southeast-4\": {\n \"description\": \"Asia Pacific (Melbourne)\"\n },\n \"ap-southeast-5\": {\n \"description\": \"Asia Pacific (Malaysia)\"\n },\n \"ap-southeast-6\": {\n \"description\": \"Asia Pacific (New Zealand)\"\n },\n \"ap-southeast-7\": {\n \"description\": \"Asia Pacific (Thailand)\"\n },\n \"aws-global\": {\n \"description\": \"aws global region\"\n },\n \"ca-central-1\": {\n \"description\": \"Canada (Central)\"\n },\n \"ca-west-1\": {\n \"description\": \"Canada West (Calgary)\"\n },\n \"eu-central-1\": {\n \"description\": \"Europe (Frankfurt)\"\n },\n \"eu-central-2\": {\n \"description\": \"Europe (Zurich)\"\n },\n \"eu-north-1\": {\n \"description\": \"Europe (Stockholm)\"\n },\n \"eu-south-1\": {\n \"description\": \"Europe (Milan)\"\n },\n \"eu-south-2\": {\n \"description\": \"Europe (Spain)\"\n },\n \"eu-west-1\": {\n \"description\": \"Europe (Ireland)\"\n },\n \"eu-west-2\": {\n \"description\": \"Europe (London)\"\n },\n \"eu-west-3\": {\n \"description\": \"Europe (Paris)\"\n },\n \"il-central-1\": {\n \"description\": \"Israel (Tel Aviv)\"\n },\n \"me-central-1\": {\n \"description\": \"Middle East (UAE)\"\n },\n \"me-south-1\": {\n \"description\": \"Middle East (Bahrain)\"\n },\n \"mx-central-1\": {\n \"description\": \"Mexico (Central)\"\n },\n \"sa-east-1\": {\n \"description\": \"South America (Sao Paulo)\"\n },\n \"us-east-1\": {\n \"description\": \"US East (N. Virginia)\"\n },\n \"us-east-2\": {\n \"description\": \"US East (Ohio)\"\n },\n \"us-west-1\": {\n \"description\": \"US West (N. California)\"\n },\n \"us-west-2\": {\n \"description\": \"US West (Oregon)\"\n }\n }\n }, {\n \"id\": \"aws-cn\",\n \"outputs\": {\n \"dnsSuffix\": \"amazonaws.com.cn\",\n \"dualStackDnsSuffix\": \"api.amazonwebservices.com.cn\",\n \"implicitGlobalRegion\": \"cn-northwest-1\",\n \"name\": \"aws-cn\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^cn\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-cn-global\": {\n \"description\": \"aws-cn global region\"\n },\n \"cn-north-1\": {\n \"description\": \"China (Beijing)\"\n },\n \"cn-northwest-1\": {\n \"description\": \"China (Ningxia)\"\n }\n }\n }, {\n \"id\": \"aws-eusc\",\n \"outputs\": {\n \"dnsSuffix\": \"amazonaws.eu\",\n \"dualStackDnsSuffix\": \"api.amazonwebservices.eu\",\n \"implicitGlobalRegion\": \"eusc-de-east-1\",\n \"name\": \"aws-eusc\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^eusc\\\\-(de)\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"eusc-de-east-1\": {\n \"description\": \"AWS European Sovereign Cloud (Germany)\"\n }\n }\n }, {\n \"id\": \"aws-iso\",\n \"outputs\": {\n \"dnsSuffix\": \"c2s.ic.gov\",\n \"dualStackDnsSuffix\": \"api.aws.ic.gov\",\n \"implicitGlobalRegion\": \"us-iso-east-1\",\n \"name\": \"aws-iso\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^us\\\\-iso\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-iso-global\": {\n \"description\": \"aws-iso global region\"\n },\n \"us-iso-east-1\": {\n \"description\": \"US ISO East\"\n },\n \"us-iso-west-1\": {\n \"description\": \"US ISO WEST\"\n }\n }\n }, {\n \"id\": \"aws-iso-b\",\n \"outputs\": {\n \"dnsSuffix\": \"sc2s.sgov.gov\",\n \"dualStackDnsSuffix\": \"api.aws.scloud\",\n \"implicitGlobalRegion\": \"us-isob-east-1\",\n \"name\": \"aws-iso-b\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^us\\\\-isob\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-iso-b-global\": {\n \"description\": \"aws-iso-b global region\"\n },\n \"us-isob-east-1\": {\n \"description\": \"US ISOB East (Ohio)\"\n },\n \"us-isob-west-1\": {\n \"description\": \"US ISOB West\"\n }\n }\n }, {\n \"id\": \"aws-iso-e\",\n \"outputs\": {\n \"dnsSuffix\": \"cloud.adc-e.uk\",\n \"dualStackDnsSuffix\": \"api.cloud-aws.adc-e.uk\",\n \"implicitGlobalRegion\": \"eu-isoe-west-1\",\n \"name\": \"aws-iso-e\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^eu\\\\-isoe\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-iso-e-global\": {\n \"description\": \"aws-iso-e global region\"\n },\n \"eu-isoe-west-1\": {\n \"description\": \"EU ISOE West\"\n }\n }\n }, {\n \"id\": \"aws-iso-f\",\n \"outputs\": {\n \"dnsSuffix\": \"csp.hci.ic.gov\",\n \"dualStackDnsSuffix\": \"api.aws.hci.ic.gov\",\n \"implicitGlobalRegion\": \"us-isof-south-1\",\n \"name\": \"aws-iso-f\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^us\\\\-isof\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-iso-f-global\": {\n \"description\": \"aws-iso-f global region\"\n },\n \"us-isof-east-1\": {\n \"description\": \"US ISOF EAST\"\n },\n \"us-isof-south-1\": {\n \"description\": \"US ISOF SOUTH\"\n }\n }\n }, {\n \"id\": \"aws-us-gov\",\n \"outputs\": {\n \"dnsSuffix\": \"amazonaws.com\",\n \"dualStackDnsSuffix\": \"api.aws\",\n \"implicitGlobalRegion\": \"us-gov-west-1\",\n \"name\": \"aws-us-gov\",\n \"supportsDualStack\": true,\n \"supportsFIPS\": true\n },\n \"regionRegex\": \"^us\\\\-gov\\\\-\\\\w+\\\\-\\\\d+$\",\n \"regions\": {\n \"aws-us-gov-global\": {\n \"description\": \"aws-us-gov global region\"\n },\n \"us-gov-east-1\": {\n \"description\": \"AWS GovCloud (US-East)\"\n },\n \"us-gov-west-1\": {\n \"description\": \"AWS GovCloud (US-West)\"\n }\n }\n }],\n \"version\": \"1.1\"\n}\n","import partitionsInfo from \"./partitions.json\";\nlet selectedPartitionsInfo = partitionsInfo;\nlet selectedUserAgentPrefix = \"\";\nexport const partition = (value) => {\n const { partitions } = selectedPartitionsInfo;\n for (const partition of partitions) {\n const { regions, outputs } = partition;\n for (const [region, regionData] of Object.entries(regions)) {\n if (region === value) {\n return {\n ...outputs,\n ...regionData,\n };\n }\n }\n }\n for (const partition of partitions) {\n const { regionRegex, outputs } = partition;\n if (new RegExp(regionRegex).test(value)) {\n return {\n ...outputs,\n };\n }\n }\n const DEFAULT_PARTITION = partitions.find((partition) => partition.id === \"aws\");\n if (!DEFAULT_PARTITION) {\n throw new Error(\"Provided region was not found in the partition array or regex,\" +\n \" and default partition with id 'aws' doesn't exist.\");\n }\n return {\n ...DEFAULT_PARTITION.outputs,\n };\n};\nexport const setPartitionInfo = (partitionsInfo, userAgentPrefix = \"\") => {\n selectedPartitionsInfo = partitionsInfo;\n selectedUserAgentPrefix = userAgentPrefix;\n};\nexport const useDefaultPartitionInfo = () => {\n setPartitionInfo(partitionsInfo, \"\");\n};\nexport const getUserAgentPrefix = () => selectedUserAgentPrefix;\n","import { customEndpointFunctions } from \"@smithy/util-endpoints\";\nimport { isVirtualHostableS3Bucket } from \"./lib/aws/isVirtualHostableS3Bucket\";\nimport { parseArn } from \"./lib/aws/parseArn\";\nimport { partition } from \"./lib/aws/partition\";\nexport const awsEndpointFunctions = {\n isVirtualHostableS3Bucket: isVirtualHostableS3Bucket,\n parseArn: parseArn,\n partition: partition,\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n","export function parseQueryString(querystring) {\n const query = {};\n querystring = querystring.replace(/^\\?/, \"\");\n if (querystring) {\n for (const pair of querystring.split(\"&\")) {\n let [key, value = null] = pair.split(\"=\");\n key = decodeURIComponent(key);\n if (value) {\n value = decodeURIComponent(value);\n }\n if (!(key in query)) {\n query[key] = value;\n }\n else if (Array.isArray(query[key])) {\n query[key].push(value);\n }\n else {\n query[key] = [query[key], value];\n }\n }\n }\n return query;\n}\n","import { parseQueryString } from \"@smithy/querystring-parser\";\nexport const parseUrl = (url) => {\n if (typeof url === \"string\") {\n return parseUrl(new URL(url));\n }\n const { hostname, pathname, port, protocol, search } = url;\n let query;\n if (search) {\n query = parseQueryString(search);\n }\n return {\n hostname,\n port: port ? parseInt(port) : undefined,\n protocol,\n path: pathname,\n query,\n };\n};\n","import { parseUrl } from \"@smithy/url-parser\";\nexport const resolveDefaultAwsRegionalEndpointsConfig = (input) => {\n if (typeof input.endpointProvider !== \"function\") {\n throw new Error(\"@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.\");\n }\n const { endpoint } = input;\n if (endpoint === undefined) {\n input.endpoint = async () => {\n return toEndpointV1(input.endpointProvider({\n Region: typeof input.region === \"function\" ? await input.region() : input.region,\n UseDualStack: typeof input.useDualstackEndpoint === \"function\"\n ? await input.useDualstackEndpoint()\n : input.useDualstackEndpoint,\n UseFIPS: typeof input.useFipsEndpoint === \"function\" ? await input.useFipsEndpoint() : input.useFipsEndpoint,\n Endpoint: undefined,\n }, { logger: input.logger }));\n };\n }\n return input;\n};\nexport const toEndpointV1 = (endpoint) => parseUrl(endpoint.url);\n","export { resolveEndpoint } from \"@smithy/util-endpoints\";\n","export { EndpointError } from \"@smithy/util-endpoints\";\n","export {};\n","export {};\n","export {};\n","export {};\n","export {};\n","export * from \"./EndpointError\";\nexport * from \"./EndpointRuleObject\";\nexport * from \"./ErrorRuleObject\";\nexport * from \"./RuleSetObject\";\nexport * from \"./TreeRuleObject\";\nexport * from \"./shared\";\n","export * from \"./aws\";\nexport * from \"./lib/aws/partition\";\nexport * from \"./lib/isIpAddress\";\nexport * from \"./resolveDefaultAwsRegionalEndpointsConfig\";\nexport * from \"./resolveEndpoint\";\nexport * from \"./types\";\n","import { setFeature } from \"@aws-sdk/core\";\nconst ACCOUNT_ID_ENDPOINT_REGEX = /\\d{12}\\.ddb/;\nexport async function checkFeatures(context, config, args) {\n const request = args.request;\n if (request?.headers?.[\"smithy-protocol\"] === \"rpc-v2-cbor\") {\n setFeature(context, \"PROTOCOL_RPC_V2_CBOR\", \"M\");\n }\n if (typeof config.retryStrategy === \"function\") {\n const retryStrategy = await config.retryStrategy();\n if (typeof retryStrategy.acquireInitialRetryToken === \"function\") {\n if (retryStrategy.constructor?.name?.includes(\"Adaptive\")) {\n setFeature(context, \"RETRY_MODE_ADAPTIVE\", \"F\");\n }\n else {\n setFeature(context, \"RETRY_MODE_STANDARD\", \"E\");\n }\n }\n else {\n setFeature(context, \"RETRY_MODE_LEGACY\", \"D\");\n }\n }\n if (typeof config.accountIdEndpointMode === \"function\") {\n const endpointV2 = context.endpointV2;\n if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {\n setFeature(context, \"ACCOUNT_ID_ENDPOINT\", \"O\");\n }\n switch (await config.accountIdEndpointMode?.()) {\n case \"disabled\":\n setFeature(context, \"ACCOUNT_ID_MODE_DISABLED\", \"Q\");\n break;\n case \"preferred\":\n setFeature(context, \"ACCOUNT_ID_MODE_PREFERRED\", \"P\");\n break;\n case \"required\":\n setFeature(context, \"ACCOUNT_ID_MODE_REQUIRED\", \"R\");\n break;\n }\n }\n const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity;\n if (identity?.$source) {\n const credentials = identity;\n if (credentials.accountId) {\n setFeature(context, \"RESOLVED_ACCOUNT_ID\", \"T\");\n }\n for (const [key, value] of Object.entries(credentials.$source ?? {})) {\n setFeature(context, key, value);\n }\n }\n}\n","export const USER_AGENT = \"user-agent\";\nexport const X_AMZ_USER_AGENT = \"x-amz-user-agent\";\nexport const SPACE = \" \";\nexport const UA_NAME_SEPARATOR = \"/\";\nexport const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\\-.^_`|~\\w]/g;\nexport const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\\-.^_`|~\\w#]/g;\nexport const UA_ESCAPE_CHAR = \"-\";\n","const BYTE_LIMIT = 1024;\nexport function encodeFeatures(features) {\n let buffer = \"\";\n for (const key in features) {\n const val = features[key];\n if (buffer.length + val.length + 1 <= BYTE_LIMIT) {\n if (buffer.length) {\n buffer += \",\" + val;\n }\n else {\n buffer += val;\n }\n continue;\n }\n break;\n }\n return buffer;\n}\n","import { getUserAgentPrefix } from \"@aws-sdk/util-endpoints\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nimport { checkFeatures } from \"./check-features\";\nimport { SPACE, UA_ESCAPE_CHAR, UA_NAME_ESCAPE_REGEX, UA_NAME_SEPARATOR, UA_VALUE_ESCAPE_REGEX, USER_AGENT, X_AMZ_USER_AGENT, } from \"./constants\";\nimport { encodeFeatures } from \"./encode-features\";\nexport const userAgentMiddleware = (options) => (next, context) => async (args) => {\n const { request } = args;\n if (!HttpRequest.isInstance(request)) {\n return next(args);\n }\n const { headers } = request;\n const userAgent = context?.userAgent?.map(escapeUserAgent) || [];\n const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);\n await checkFeatures(context, options, args);\n const awsContext = context;\n defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);\n const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];\n const appId = await options.userAgentAppId();\n if (appId) {\n defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`]));\n }\n const prefix = getUserAgentPrefix();\n const sdkUserAgentValue = (prefix ? [prefix] : [])\n .concat([...defaultUserAgent, ...userAgent, ...customUserAgent])\n .join(SPACE);\n const normalUAValue = [\n ...defaultUserAgent.filter((section) => section.startsWith(\"aws-sdk-\")),\n ...customUserAgent,\n ].join(SPACE);\n if (options.runtime !== \"browser\") {\n if (normalUAValue) {\n headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT]\n ? `${headers[USER_AGENT]} ${normalUAValue}`\n : normalUAValue;\n }\n headers[USER_AGENT] = sdkUserAgentValue;\n }\n else {\n headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;\n }\n return next({\n ...args,\n request,\n });\n};\nconst escapeUserAgent = (userAgentPair) => {\n const name = userAgentPair[0]\n .split(UA_NAME_SEPARATOR)\n .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR))\n .join(UA_NAME_SEPARATOR);\n const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);\n const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);\n const prefix = name.substring(0, prefixSeparatorIndex);\n let uaName = name.substring(prefixSeparatorIndex + 1);\n if (prefix === \"api\") {\n uaName = uaName.toLowerCase();\n }\n return [prefix, uaName, version]\n .filter((item) => item && item.length > 0)\n .reduce((acc, item, index) => {\n switch (index) {\n case 0:\n return item;\n case 1:\n return `${acc}/${item}`;\n default:\n return `${acc}#${item}`;\n }\n }, \"\");\n};\nexport const getUserAgentMiddlewareOptions = {\n name: \"getUserAgentMiddleware\",\n step: \"build\",\n priority: \"low\",\n tags: [\"SET_USER_AGENT\", \"USER_AGENT\"],\n override: true,\n};\nexport const getUserAgentPlugin = (config) => ({\n applyToStack: (clientStack) => {\n clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);\n },\n});\n","export * from \"./configurations\";\nexport * from \"./user-agent-middleware\";\n","import { booleanSelector, SelectorType } from \"@smithy/util-config-provider\";\nexport const ENV_USE_DUALSTACK_ENDPOINT = \"AWS_USE_DUALSTACK_ENDPOINT\";\nexport const CONFIG_USE_DUALSTACK_ENDPOINT = \"use_dualstack_endpoint\";\nexport const DEFAULT_USE_DUALSTACK_ENDPOINT = false;\nexport const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, SelectorType.ENV),\n configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, SelectorType.CONFIG),\n default: false,\n};\n","import { booleanSelector, SelectorType } from \"@smithy/util-config-provider\";\nexport const ENV_USE_FIPS_ENDPOINT = \"AWS_USE_FIPS_ENDPOINT\";\nexport const CONFIG_USE_FIPS_ENDPOINT = \"use_fips_endpoint\";\nexport const DEFAULT_USE_FIPS_ENDPOINT = false;\nexport const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => booleanSelector(env, ENV_USE_FIPS_ENDPOINT, SelectorType.ENV),\n configFileSelector: (profile) => booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, SelectorType.CONFIG),\n default: false,\n};\n","import { normalizeProvider } from \"@smithy/util-middleware\";\nexport const resolveCustomEndpointsConfig = (input) => {\n const { tls, endpoint, urlParser, useDualstackEndpoint } = input;\n return Object.assign(input, {\n tls: tls ?? true,\n endpoint: normalizeProvider(typeof endpoint === \"string\" ? urlParser(endpoint) : endpoint),\n isCustomEndpoint: true,\n useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),\n });\n};\n","import { normalizeProvider } from \"@smithy/util-middleware\";\nimport { getEndpointFromRegion } from \"./utils/getEndpointFromRegion\";\nexport const resolveEndpointsConfig = (input) => {\n const useDualstackEndpoint = normalizeProvider(input.useDualstackEndpoint ?? false);\n const { endpoint, useFipsEndpoint, urlParser, tls } = input;\n return Object.assign(input, {\n tls: tls ?? true,\n endpoint: endpoint\n ? normalizeProvider(typeof endpoint === \"string\" ? urlParser(endpoint) : endpoint)\n : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),\n isCustomEndpoint: !!endpoint,\n useDualstackEndpoint,\n });\n};\n","export * from \"./NodeUseDualstackEndpointConfigOptions\";\nexport * from \"./NodeUseFipsEndpointConfigOptions\";\nexport * from \"./resolveCustomEndpointsConfig\";\nexport * from \"./resolveEndpointsConfig\";\n","export const REGION_ENV_NAME = \"AWS_REGION\";\nexport const REGION_INI_NAME = \"region\";\nexport const NODE_REGION_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[REGION_ENV_NAME],\n configFileSelector: (profile) => profile[REGION_INI_NAME],\n default: () => {\n throw new Error(\"Region is missing\");\n },\n};\nexport const NODE_REGION_CONFIG_FILE_OPTIONS = {\n preferredFile: \"credentials\",\n};\n","import { isValidHostLabel } from \"@smithy/util-endpoints\";\nconst validRegions = new Set();\nexport const checkRegion = (region, check = isValidHostLabel) => {\n if (!validRegions.has(region) && !check(region)) {\n if (region === \"*\") {\n console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of \"*\". See \"sigv4a\" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`);\n }\n else {\n throw new Error(`Region not accepted: region=\"${region}\" is not a valid hostname component.`);\n }\n }\n else {\n validRegions.add(region);\n }\n};\n","export const isFipsRegion = (region) => typeof region === \"string\" && (region.startsWith(\"fips-\") || region.endsWith(\"-fips\"));\n","import { isFipsRegion } from \"./isFipsRegion\";\nexport const getRealRegion = (region) => isFipsRegion(region)\n ? [\"fips-aws-global\", \"aws-fips\"].includes(region)\n ? \"us-east-1\"\n : region.replace(/fips-(dkr-|prod-)?|-fips/, \"\")\n : region;\n","import { checkRegion } from \"./checkRegion\";\nimport { getRealRegion } from \"./getRealRegion\";\nimport { isFipsRegion } from \"./isFipsRegion\";\nexport const resolveRegionConfig = (input) => {\n const { region, useFipsEndpoint } = input;\n if (!region) {\n throw new Error(\"Region is missing\");\n }\n return Object.assign(input, {\n region: async () => {\n const providedRegion = typeof region === \"function\" ? await region() : region;\n const realRegion = getRealRegion(providedRegion);\n checkRegion(realRegion);\n return realRegion;\n },\n useFipsEndpoint: async () => {\n const providedRegion = typeof region === \"string\" ? region : await region();\n if (isFipsRegion(providedRegion)) {\n return true;\n }\n return typeof useFipsEndpoint !== \"function\" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();\n },\n });\n};\n","export * from \"./config\";\nexport * from \"./resolveRegionConfig\";\n","export {};\n","export {};\n","import { getHostnameFromVariants } from \"./getHostnameFromVariants\";\nimport { getResolvedHostname } from \"./getResolvedHostname\";\nimport { getResolvedPartition } from \"./getResolvedPartition\";\nimport { getResolvedSigningRegion } from \"./getResolvedSigningRegion\";\nexport const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => {\n const partition = getResolvedPartition(region, { partitionHash });\n const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region;\n const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint };\n const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions);\n const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions);\n const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname });\n if (hostname === undefined) {\n throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`);\n }\n const signingRegion = getResolvedSigningRegion(hostname, {\n signingRegion: regionHash[resolvedRegion]?.signingRegion,\n regionRegex: partitionHash[partition].regionRegex,\n useFipsEndpoint,\n });\n return {\n partition,\n signingService,\n hostname,\n ...(signingRegion && { signingRegion }),\n ...(regionHash[resolvedRegion]?.signingService && {\n signingService: regionHash[resolvedRegion].signingService,\n }),\n };\n};\n","export * from \"./PartitionHash\";\nexport * from \"./RegionHash\";\nexport * from \"./getRegionInfo\";\n","export * from \"./endpointsConfig\";\nexport * from \"./regionConfig\";\nexport * from \"./regionInfo\";\n","import { HttpRequest } from \"@smithy/protocol-http\";\nconst CONTENT_LENGTH_HEADER = \"content-length\";\nexport function contentLengthMiddleware(bodyLengthChecker) {\n return (next) => async (args) => {\n const request = args.request;\n if (HttpRequest.isInstance(request)) {\n const { body, headers } = request;\n if (body &&\n Object.keys(headers)\n .map((str) => str.toLowerCase())\n .indexOf(CONTENT_LENGTH_HEADER) === -1) {\n try {\n const length = bodyLengthChecker(body);\n request.headers = {\n ...request.headers,\n [CONTENT_LENGTH_HEADER]: String(length),\n };\n }\n catch (error) {\n }\n }\n }\n return next({\n ...args,\n request,\n });\n };\n}\nexport const contentLengthMiddlewareOptions = {\n step: \"build\",\n tags: [\"SET_CONTENT_LENGTH\", \"CONTENT_LENGTH\"],\n name: \"contentLengthMiddleware\",\n override: true,\n};\nexport const getContentLengthPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);\n },\n});\n","export const resolveParamsForS3 = async (endpointParams) => {\n const bucket = endpointParams?.Bucket || \"\";\n if (typeof endpointParams.Bucket === \"string\") {\n endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent(\"#\")).replace(/\\?/g, encodeURIComponent(\"?\"));\n }\n if (isArnBucketName(bucket)) {\n if (endpointParams.ForcePathStyle === true) {\n throw new Error(\"Path-style addressing cannot be used with ARN buckets\");\n }\n }\n else if (!isDnsCompatibleBucketName(bucket) ||\n (bucket.indexOf(\".\") !== -1 && !String(endpointParams.Endpoint).startsWith(\"http:\")) ||\n bucket.toLowerCase() !== bucket ||\n bucket.length < 3) {\n endpointParams.ForcePathStyle = true;\n }\n if (endpointParams.DisableMultiRegionAccessPoints) {\n endpointParams.disableMultiRegionAccessPoints = true;\n endpointParams.DisableMRAP = true;\n }\n return endpointParams;\n};\nconst DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\\.\\-]{1,61}[a-z0-9]$/;\nconst IP_ADDRESS_PATTERN = /(\\d+\\.){3}\\d+/;\nconst DOTS_PATTERN = /\\.\\./;\nexport const DOT_PATTERN = /\\./;\nexport const S3_HOSTNAME_PATTERN = /^(.+\\.)?s3(-fips)?(\\.dualstack)?[.-]([a-z0-9-]+)\\./;\nexport const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);\nexport const isArnBucketName = (bucketName) => {\n const [arn, partition, service, , , bucket] = bucketName.split(\":\");\n const isArn = arn === \"arn\" && bucketName.split(\":\").length >= 6;\n const isValidArn = Boolean(isArn && partition && service && bucket);\n if (isArn && !isValidArn) {\n throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);\n }\n return isValidArn;\n};\n","export * from \"./s3\";\n","export const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config, isClientContextParam = false) => {\n const configProvider = async () => {\n let configValue;\n if (isClientContextParam) {\n const clientContextParams = config.clientContextParams;\n const nestedValue = clientContextParams?.[configKey];\n configValue = nestedValue ?? config[configKey] ?? config[canonicalEndpointParamKey];\n }\n else {\n configValue = config[configKey] ?? config[canonicalEndpointParamKey];\n }\n if (typeof configValue === \"function\") {\n return configValue();\n }\n return configValue;\n };\n if (configKey === \"credentialScope\" || canonicalEndpointParamKey === \"CredentialScope\") {\n return async () => {\n const credentials = typeof config.credentials === \"function\" ? await config.credentials() : config.credentials;\n const configValue = credentials?.credentialScope ?? credentials?.CredentialScope;\n return configValue;\n };\n }\n if (configKey === \"accountId\" || canonicalEndpointParamKey === \"AccountId\") {\n return async () => {\n const credentials = typeof config.credentials === \"function\" ? await config.credentials() : config.credentials;\n const configValue = credentials?.accountId ?? credentials?.AccountId;\n return configValue;\n };\n }\n if (configKey === \"endpoint\" || canonicalEndpointParamKey === \"endpoint\") {\n return async () => {\n if (config.isCustomEndpoint === false) {\n return undefined;\n }\n const endpoint = await configProvider();\n if (endpoint && typeof endpoint === \"object\") {\n if (\"url\" in endpoint) {\n return endpoint.url.href;\n }\n if (\"hostname\" in endpoint) {\n const { protocol, hostname, port, path } = endpoint;\n return `${protocol}//${hostname}${port ? \":\" + port : \"\"}${path}`;\n }\n }\n return endpoint;\n };\n }\n return configProvider;\n};\n","export function getSelectorName(functionString) {\n try {\n const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));\n constants.delete(\"CONFIG\");\n constants.delete(\"CONFIG_PREFIX_SEPARATOR\");\n constants.delete(\"ENV\");\n return [...constants].join(\", \");\n }\n catch (e) {\n return functionString;\n }\n}\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getSelectorName } from \"./getSelectorName\";\nexport const fromEnv = (envVarSelector, options) => async () => {\n try {\n const config = envVarSelector(process.env, options);\n if (config === undefined) {\n throw new Error();\n }\n return config;\n }\n catch (e) {\n throw new CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger });\n }\n};\n","import { homedir } from \"os\";\nimport { sep } from \"path\";\nconst homeDirCache = {};\nconst getHomeDirCacheKey = () => {\n if (process && process.geteuid) {\n return `${process.geteuid()}`;\n }\n return \"DEFAULT\";\n};\nexport const getHomeDir = () => {\n const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${sep}` } = process.env;\n if (HOME)\n return HOME;\n if (USERPROFILE)\n return USERPROFILE;\n if (HOMEPATH)\n return `${HOMEDRIVE}${HOMEPATH}`;\n const homeDirCacheKey = getHomeDirCacheKey();\n if (!homeDirCache[homeDirCacheKey])\n homeDirCache[homeDirCacheKey] = homedir();\n return homeDirCache[homeDirCacheKey];\n};\n","export const ENV_PROFILE = \"AWS_PROFILE\";\nexport const DEFAULT_PROFILE = \"default\";\nexport const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE;\n","import { createHash } from \"crypto\";\nimport { join } from \"path\";\nimport { getHomeDir } from \"./getHomeDir\";\nexport const getSSOTokenFilepath = (id) => {\n const hasher = createHash(\"sha1\");\n const cacheName = hasher.update(id).digest(\"hex\");\n return join(getHomeDir(), \".aws\", \"sso\", \"cache\", `${cacheName}.json`);\n};\n","import { readFile } from \"fs/promises\";\nimport { getSSOTokenFilepath } from \"./getSSOTokenFilepath\";\nexport const tokenIntercept = {};\nexport const getSSOTokenFromFile = async (id) => {\n if (tokenIntercept[id]) {\n return tokenIntercept[id];\n }\n const ssoTokenFilepath = getSSOTokenFilepath(id);\n const ssoTokenText = await readFile(ssoTokenFilepath, \"utf8\");\n return JSON.parse(ssoTokenText);\n};\n","export const CONFIG_PREFIX_SEPARATOR = \".\";\n","import { IniSectionType } from \"@smithy/types\";\nimport { CONFIG_PREFIX_SEPARATOR } from \"./constants\";\nexport const getConfigData = (data) => Object.entries(data)\n .filter(([key]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n if (indexOfSeparator === -1) {\n return false;\n }\n return Object.values(IniSectionType).includes(key.substring(0, indexOfSeparator));\n})\n .reduce((acc, [key, value]) => {\n const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);\n const updatedKey = key.substring(0, indexOfSeparator) === IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;\n acc[updatedKey] = value;\n return acc;\n}, {\n ...(data.default && { default: data.default }),\n});\n","import { join } from \"path\";\nimport { getHomeDir } from \"./getHomeDir\";\nexport const ENV_CONFIG_PATH = \"AWS_CONFIG_FILE\";\nexport const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || join(getHomeDir(), \".aws\", \"config\");\n","import { join } from \"path\";\nimport { getHomeDir } from \"./getHomeDir\";\nexport const ENV_CREDENTIALS_PATH = \"AWS_SHARED_CREDENTIALS_FILE\";\nexport const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || join(getHomeDir(), \".aws\", \"credentials\");\n","import { IniSectionType } from \"@smithy/types\";\nimport { CONFIG_PREFIX_SEPARATOR } from \"./constants\";\nconst prefixKeyRegex = /^([\\w-]+)\\s([\"'])?([\\w-@\\+\\.%:/]+)\\2$/;\nconst profileNameBlockList = [\"__proto__\", \"profile __proto__\"];\nexport const parseIni = (iniData) => {\n const map = {};\n let currentSection;\n let currentSubSection;\n for (const iniLine of iniData.split(/\\r?\\n/)) {\n const trimmedLine = iniLine.split(/(^|\\s)[;#]/)[0].trim();\n const isSection = trimmedLine[0] === \"[\" && trimmedLine[trimmedLine.length - 1] === \"]\";\n if (isSection) {\n currentSection = undefined;\n currentSubSection = undefined;\n const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);\n const matches = prefixKeyRegex.exec(sectionName);\n if (matches) {\n const [, prefix, , name] = matches;\n if (Object.values(IniSectionType).includes(prefix)) {\n currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR);\n }\n }\n else {\n currentSection = sectionName;\n }\n if (profileNameBlockList.includes(sectionName)) {\n throw new Error(`Found invalid profile name \"${sectionName}\"`);\n }\n }\n else if (currentSection) {\n const indexOfEqualsSign = trimmedLine.indexOf(\"=\");\n if (![0, -1].includes(indexOfEqualsSign)) {\n const [name, value] = [\n trimmedLine.substring(0, indexOfEqualsSign).trim(),\n trimmedLine.substring(indexOfEqualsSign + 1).trim(),\n ];\n if (value === \"\") {\n currentSubSection = name;\n }\n else {\n if (currentSubSection && iniLine.trimStart() === iniLine) {\n currentSubSection = undefined;\n }\n map[currentSection] = map[currentSection] || {};\n const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;\n map[currentSection][key] = value;\n }\n }\n }\n }\n return map;\n};\n","import { readFile as fsReadFile } from \"node:fs/promises\";\nexport const filePromises = {};\nexport const fileIntercept = {};\nexport const readFile = (path, options) => {\n if (fileIntercept[path] !== undefined) {\n return fileIntercept[path];\n }\n if (!filePromises[path] || options?.ignoreCache) {\n filePromises[path] = fsReadFile(path, \"utf8\");\n }\n return filePromises[path];\n};\n","import { join } from \"path\";\nimport { getConfigData } from \"./getConfigData\";\nimport { getConfigFilepath } from \"./getConfigFilepath\";\nimport { getCredentialsFilepath } from \"./getCredentialsFilepath\";\nimport { getHomeDir } from \"./getHomeDir\";\nimport { parseIni } from \"./parseIni\";\nimport { readFile } from \"./readFile\";\nconst swallowError = () => ({});\nexport { CONFIG_PREFIX_SEPARATOR } from \"./constants\";\nexport const loadSharedConfigFiles = async (init = {}) => {\n const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init;\n const homeDir = getHomeDir();\n const relativeHomeDirPrefix = \"~/\";\n let resolvedFilepath = filepath;\n if (filepath.startsWith(relativeHomeDirPrefix)) {\n resolvedFilepath = join(homeDir, filepath.slice(2));\n }\n let resolvedConfigFilepath = configFilepath;\n if (configFilepath.startsWith(relativeHomeDirPrefix)) {\n resolvedConfigFilepath = join(homeDir, configFilepath.slice(2));\n }\n const parsedFiles = await Promise.all([\n readFile(resolvedConfigFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .then(getConfigData)\n .catch(swallowError),\n readFile(resolvedFilepath, {\n ignoreCache: init.ignoreCache,\n })\n .then(parseIni)\n .catch(swallowError),\n ]);\n return {\n configFile: parsedFiles[0],\n credentialsFile: parsedFiles[1],\n };\n};\n","import { IniSectionType } from \"@smithy/types\";\nimport { CONFIG_PREFIX_SEPARATOR } from \"./loadSharedConfigFiles\";\nexport const getSsoSessionData = (data) => Object.entries(data)\n .filter(([key]) => key.startsWith(IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR))\n .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {});\n","import { getConfigFilepath } from \"./getConfigFilepath\";\nimport { getSsoSessionData } from \"./getSsoSessionData\";\nimport { parseIni } from \"./parseIni\";\nimport { readFile } from \"./readFile\";\nconst swallowError = () => ({});\nexport const loadSsoSessionData = async (init = {}) => readFile(init.configFilepath ?? getConfigFilepath())\n .then(parseIni)\n .then(getSsoSessionData)\n .catch(swallowError);\n","export const mergeConfigFiles = (...files) => {\n const merged = {};\n for (const file of files) {\n for (const [key, values] of Object.entries(file)) {\n if (merged[key] !== undefined) {\n Object.assign(merged[key], values);\n }\n else {\n merged[key] = values;\n }\n }\n }\n return merged;\n};\n","import { loadSharedConfigFiles } from \"./loadSharedConfigFiles\";\nimport { mergeConfigFiles } from \"./mergeConfigFiles\";\nexport const parseKnownFiles = async (init) => {\n const parsedFiles = await loadSharedConfigFiles(init);\n return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);\n};\n","import { tokenIntercept } from \"./getSSOTokenFromFile\";\nimport { fileIntercept } from \"./readFile\";\nexport const externalDataInterceptor = {\n getFileRecord() {\n return fileIntercept;\n },\n interceptFile(path, contents) {\n fileIntercept[path] = Promise.resolve(contents);\n },\n getTokenRecord() {\n return tokenIntercept;\n },\n interceptToken(id, contents) {\n tokenIntercept[id] = contents;\n },\n};\n","export {};\n","export * from \"./getHomeDir\";\nexport * from \"./getProfileName\";\nexport * from \"./getSSOTokenFilepath\";\nexport { getSSOTokenFromFile } from \"./getSSOTokenFromFile\";\nexport * from \"./loadSharedConfigFiles\";\nexport * from \"./loadSsoSessionData\";\nexport * from \"./parseKnownFiles\";\nexport { externalDataInterceptor } from \"./externalDataInterceptor\";\nexport * from \"./types\";\nexport { readFile } from \"./readFile\";\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getProfileName, loadSharedConfigFiles } from \"@smithy/shared-ini-file-loader\";\nimport { getSelectorName } from \"./getSelectorName\";\nexport const fromSharedConfigFiles = (configSelector, { preferredFile = \"config\", ...init } = {}) => async () => {\n const profile = getProfileName(init);\n const { configFile, credentialsFile } = await loadSharedConfigFiles(init);\n const profileFromCredentials = credentialsFile[profile] || {};\n const profileFromConfig = configFile[profile] || {};\n const mergedProfile = preferredFile === \"config\"\n ? { ...profileFromCredentials, ...profileFromConfig }\n : { ...profileFromConfig, ...profileFromCredentials };\n try {\n const cfgFile = preferredFile === \"config\" ? configFile : credentialsFile;\n const configValue = configSelector(mergedProfile, cfgFile);\n if (configValue === undefined) {\n throw new Error();\n }\n return configValue;\n }\n catch (e) {\n throw new CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger });\n }\n};\n","import { fromStatic as convertToProvider } from \"@smithy/property-provider\";\nconst isFunction = (func) => typeof func === \"function\";\nexport const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : convertToProvider(defaultValue);\n","import { chain, memoize } from \"@smithy/property-provider\";\nimport { fromEnv } from \"./fromEnv\";\nimport { fromSharedConfigFiles } from \"./fromSharedConfigFiles\";\nimport { fromStatic } from \"./fromStatic\";\nexport const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {\n const { signingName, logger } = configuration;\n const envOptions = { signingName, logger };\n return memoize(chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue)));\n};\n","export * from \"./configLoader\";\n","import { CONFIG_PREFIX_SEPARATOR } from \"@smithy/shared-ini-file-loader\";\nconst ENV_ENDPOINT_URL = \"AWS_ENDPOINT_URL\";\nconst CONFIG_ENDPOINT_URL = \"endpoint_url\";\nexport const getEndpointUrlConfig = (serviceId) => ({\n environmentVariableSelector: (env) => {\n const serviceSuffixParts = serviceId.split(\" \").map((w) => w.toUpperCase());\n const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join(\"_\")];\n if (serviceEndpointUrl)\n return serviceEndpointUrl;\n const endpointUrl = env[ENV_ENDPOINT_URL];\n if (endpointUrl)\n return endpointUrl;\n return undefined;\n },\n configFileSelector: (profile, config) => {\n if (config && profile.services) {\n const servicesSection = config[[\"services\", profile.services].join(CONFIG_PREFIX_SEPARATOR)];\n if (servicesSection) {\n const servicePrefixParts = serviceId.split(\" \").map((w) => w.toLowerCase());\n const endpointUrl = servicesSection[[servicePrefixParts.join(\"_\"), CONFIG_ENDPOINT_URL].join(CONFIG_PREFIX_SEPARATOR)];\n if (endpointUrl)\n return endpointUrl;\n }\n }\n const endpointUrl = profile[CONFIG_ENDPOINT_URL];\n if (endpointUrl)\n return endpointUrl;\n return undefined;\n },\n default: undefined,\n});\n","import { loadConfig } from \"@smithy/node-config-provider\";\nimport { getEndpointUrlConfig } from \"./getEndpointUrlConfig\";\nexport const getEndpointFromConfig = async (serviceId) => loadConfig(getEndpointUrlConfig(serviceId ?? \"\"))();\n","import { parseUrl } from \"@smithy/url-parser\";\nexport const toEndpointV1 = (endpoint) => {\n if (typeof endpoint === \"object\") {\n if (\"url\" in endpoint) {\n return parseUrl(endpoint.url);\n }\n return endpoint;\n }\n return parseUrl(endpoint);\n};\n","import { resolveParamsForS3 } from \"../service-customizations\";\nimport { createConfigValueProvider } from \"./createConfigValueProvider\";\nimport { getEndpointFromConfig } from \"./getEndpointFromConfig\";\nimport { toEndpointV1 } from \"./toEndpointV1\";\nexport const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => {\n if (!clientConfig.isCustomEndpoint) {\n let endpointFromConfig;\n if (clientConfig.serviceConfiguredEndpoint) {\n endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();\n }\n else {\n endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId);\n }\n if (endpointFromConfig) {\n clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));\n clientConfig.isCustomEndpoint = true;\n }\n }\n const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);\n if (typeof clientConfig.endpointProvider !== \"function\") {\n throw new Error(\"config.endpointProvider is not set.\");\n }\n const endpoint = clientConfig.endpointProvider(endpointParams, context);\n return endpoint;\n};\nexport const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {\n const endpointParams = {};\n const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};\n for (const [name, instruction] of Object.entries(instructions)) {\n switch (instruction.type) {\n case \"staticContextParams\":\n endpointParams[name] = instruction.value;\n break;\n case \"contextParams\":\n endpointParams[name] = commandInput[instruction.name];\n break;\n case \"clientContextParams\":\n case \"builtInParams\":\n endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== \"builtInParams\")();\n break;\n case \"operationContextParams\":\n endpointParams[name] = instruction.get(commandInput);\n break;\n default:\n throw new Error(\"Unrecognized endpoint parameter instruction: \" + JSON.stringify(instruction));\n }\n }\n if (Object.keys(instructions).length === 0) {\n Object.assign(endpointParams, clientConfig);\n }\n if (String(clientConfig.serviceId).toLowerCase() === \"s3\") {\n await resolveParamsForS3(endpointParams);\n }\n return endpointParams;\n};\n","export * from \"./getEndpointFromInstructions\";\nexport * from \"./toEndpointV1\";\n","import { setFeature } from \"@smithy/core\";\nimport { getSmithyContext } from \"@smithy/util-middleware\";\nimport { getEndpointFromInstructions } from \"./adaptors/getEndpointFromInstructions\";\nexport const endpointMiddleware = ({ config, instructions, }) => {\n return (next, context) => async (args) => {\n if (config.isCustomEndpoint) {\n setFeature(context, \"ENDPOINT_OVERRIDE\", \"N\");\n }\n const endpoint = await getEndpointFromInstructions(args.input, {\n getEndpointParameterInstructions() {\n return instructions;\n },\n }, { ...config }, context);\n context.endpointV2 = endpoint;\n context.authSchemes = endpoint.properties?.authSchemes;\n const authScheme = context.authSchemes?.[0];\n if (authScheme) {\n context[\"signing_region\"] = authScheme.signingRegion;\n context[\"signing_service\"] = authScheme.signingName;\n const smithyContext = getSmithyContext(context);\n const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;\n if (httpAuthOption) {\n httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {\n signing_region: authScheme.signingRegion,\n signingRegion: authScheme.signingRegion,\n signing_service: authScheme.signingName,\n signingName: authScheme.signingName,\n signingRegionSet: authScheme.signingRegionSet,\n }, authScheme.properties);\n }\n }\n return next({\n ...args,\n });\n };\n};\n","import { serializerMiddlewareOption } from \"@smithy/middleware-serde\";\nimport { endpointMiddleware } from \"./endpointMiddleware\";\nexport const endpointMiddlewareOptions = {\n step: \"serialize\",\n tags: [\"ENDPOINT_PARAMETERS\", \"ENDPOINT_V2\", \"ENDPOINT\"],\n name: \"endpointV2Middleware\",\n override: true,\n relation: \"before\",\n toMiddleware: serializerMiddlewareOption.name,\n};\nexport const getEndpointPlugin = (config, instructions) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(endpointMiddleware({\n config,\n instructions,\n }), endpointMiddlewareOptions);\n },\n});\n","import { normalizeProvider } from \"@smithy/util-middleware\";\nimport { getEndpointFromConfig } from \"./adaptors/getEndpointFromConfig\";\nimport { toEndpointV1 } from \"./adaptors/toEndpointV1\";\nexport const resolveEndpointConfig = (input) => {\n const tls = input.tls ?? true;\n const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;\n const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : undefined;\n const isCustomEndpoint = !!endpoint;\n const resolvedConfig = Object.assign(input, {\n endpoint: customEndpointProvider,\n tls,\n isCustomEndpoint,\n useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),\n useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false),\n });\n let configuredEndpointPromise = undefined;\n resolvedConfig.serviceConfiguredEndpoint = async () => {\n if (input.serviceId && !configuredEndpointPromise) {\n configuredEndpointPromise = getEndpointFromConfig(input.serviceId);\n }\n return configuredEndpointPromise;\n };\n return resolvedConfig;\n};\n","export const resolveEndpointRequiredConfig = (input) => {\n const { endpoint } = input;\n if (endpoint === undefined) {\n input.endpoint = async () => {\n throw new Error(\"@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.\");\n };\n }\n return input;\n};\n","export {};\n","export * from \"./adaptors\";\nexport * from \"./endpointMiddleware\";\nexport * from \"./getEndpointPlugin\";\nexport * from \"./resolveEndpointConfig\";\nexport * from \"./resolveEndpointRequiredConfig\";\nexport * from \"./types\";\n","export var RETRY_MODES;\n(function (RETRY_MODES) {\n RETRY_MODES[\"STANDARD\"] = \"standard\";\n RETRY_MODES[\"ADAPTIVE\"] = \"adaptive\";\n})(RETRY_MODES || (RETRY_MODES = {}));\nexport const DEFAULT_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;\n","export const CLOCK_SKEW_ERROR_CODES = [\n \"AuthFailure\",\n \"InvalidSignatureException\",\n \"RequestExpired\",\n \"RequestInTheFuture\",\n \"RequestTimeTooSkewed\",\n \"SignatureDoesNotMatch\",\n];\nexport const THROTTLING_ERROR_CODES = [\n \"BandwidthLimitExceeded\",\n \"EC2ThrottledException\",\n \"LimitExceededException\",\n \"PriorRequestNotComplete\",\n \"ProvisionedThroughputExceededException\",\n \"RequestLimitExceeded\",\n \"RequestThrottled\",\n \"RequestThrottledException\",\n \"SlowDown\",\n \"ThrottledException\",\n \"Throttling\",\n \"ThrottlingException\",\n \"TooManyRequestsException\",\n \"TransactionInProgressException\",\n];\nexport const TRANSIENT_ERROR_CODES = [\"TimeoutError\", \"RequestTimeout\", \"RequestTimeoutException\"];\nexport const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];\nexport const NODEJS_TIMEOUT_ERROR_CODES = [\"ECONNRESET\", \"ECONNREFUSED\", \"EPIPE\", \"ETIMEDOUT\"];\nexport const NODEJS_NETWORK_ERROR_CODES = [\"EHOSTUNREACH\", \"ENETUNREACH\", \"ENOTFOUND\"];\n","import { CLOCK_SKEW_ERROR_CODES, NODEJS_NETWORK_ERROR_CODES, NODEJS_TIMEOUT_ERROR_CODES, THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, } from \"./constants\";\nexport const isRetryableByTrait = (error) => error?.$retryable !== undefined;\nexport const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name);\nexport const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected;\nexport const isBrowserNetworkError = (error) => {\n const errorMessages = new Set([\n \"Failed to fetch\",\n \"NetworkError when attempting to fetch resource\",\n \"The Internet connection appears to be offline\",\n \"Load failed\",\n \"Network request failed\",\n ]);\n const isValid = error && error instanceof TypeError;\n if (!isValid) {\n return false;\n }\n return errorMessages.has(error.message);\n};\nexport const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 ||\n THROTTLING_ERROR_CODES.includes(error.name) ||\n error.$retryable?.throttling == true;\nexport const isTransientError = (error, depth = 0) => isRetryableByTrait(error) ||\n isClockSkewCorrectedError(error) ||\n TRANSIENT_ERROR_CODES.includes(error.name) ||\n NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || \"\") ||\n NODEJS_NETWORK_ERROR_CODES.includes(error?.code || \"\") ||\n TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) ||\n isBrowserNetworkError(error) ||\n (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1));\nexport const isServerError = (error) => {\n if (error.$metadata?.httpStatusCode !== undefined) {\n const statusCode = error.$metadata.httpStatusCode;\n if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) {\n return true;\n }\n return false;\n }\n return false;\n};\n","import { isThrottlingError } from \"@smithy/service-error-classification\";\nexport class DefaultRateLimiter {\n static setTimeoutFn = setTimeout;\n beta;\n minCapacity;\n minFillRate;\n scaleConstant;\n smooth;\n currentCapacity = 0;\n enabled = false;\n lastMaxRate = 0;\n measuredTxRate = 0;\n requestCount = 0;\n fillRate;\n lastThrottleTime;\n lastTimestamp = 0;\n lastTxRateBucket;\n maxCapacity;\n timeWindow = 0;\n constructor(options) {\n this.beta = options?.beta ?? 0.7;\n this.minCapacity = options?.minCapacity ?? 1;\n this.minFillRate = options?.minFillRate ?? 0.5;\n this.scaleConstant = options?.scaleConstant ?? 0.4;\n this.smooth = options?.smooth ?? 0.8;\n const currentTimeInSeconds = this.getCurrentTimeInSeconds();\n this.lastThrottleTime = currentTimeInSeconds;\n this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());\n this.fillRate = this.minFillRate;\n this.maxCapacity = this.minCapacity;\n }\n getCurrentTimeInSeconds() {\n return Date.now() / 1000;\n }\n async getSendToken() {\n return this.acquireTokenBucket(1);\n }\n async acquireTokenBucket(amount) {\n if (!this.enabled) {\n return;\n }\n this.refillTokenBucket();\n if (amount > this.currentCapacity) {\n const delay = ((amount - this.currentCapacity) / this.fillRate) * 1000;\n await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay));\n }\n this.currentCapacity = this.currentCapacity - amount;\n }\n refillTokenBucket() {\n const timestamp = this.getCurrentTimeInSeconds();\n if (!this.lastTimestamp) {\n this.lastTimestamp = timestamp;\n return;\n }\n const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;\n this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);\n this.lastTimestamp = timestamp;\n }\n updateClientSendingRate(response) {\n let calculatedRate;\n this.updateMeasuredRate();\n if (isThrottlingError(response)) {\n const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);\n this.lastMaxRate = rateToUse;\n this.calculateTimeWindow();\n this.lastThrottleTime = this.getCurrentTimeInSeconds();\n calculatedRate = this.cubicThrottle(rateToUse);\n this.enableTokenBucket();\n }\n else {\n this.calculateTimeWindow();\n calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());\n }\n const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);\n this.updateTokenBucketRate(newRate);\n }\n calculateTimeWindow() {\n this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3));\n }\n cubicThrottle(rateToUse) {\n return this.getPrecise(rateToUse * this.beta);\n }\n cubicSuccess(timestamp) {\n return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);\n }\n enableTokenBucket() {\n this.enabled = true;\n }\n updateTokenBucketRate(newRate) {\n this.refillTokenBucket();\n this.fillRate = Math.max(newRate, this.minFillRate);\n this.maxCapacity = Math.max(newRate, this.minCapacity);\n this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);\n }\n updateMeasuredRate() {\n const t = this.getCurrentTimeInSeconds();\n const timeBucket = Math.floor(t * 2) / 2;\n this.requestCount++;\n if (timeBucket > this.lastTxRateBucket) {\n const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);\n this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));\n this.requestCount = 0;\n this.lastTxRateBucket = timeBucket;\n }\n }\n getPrecise(num) {\n return parseFloat(num.toFixed(8));\n }\n}\n","export const DEFAULT_RETRY_DELAY_BASE = 100;\nexport const MAXIMUM_RETRY_DELAY = 20 * 1000;\nexport const THROTTLING_RETRY_DELAY_BASE = 500;\nexport const INITIAL_RETRY_TOKENS = 500;\nexport const RETRY_COST = 5;\nexport const TIMEOUT_RETRY_COST = 10;\nexport const NO_RETRY_INCREMENT = 1;\nexport const INVOCATION_ID_HEADER = \"amz-sdk-invocation-id\";\nexport const REQUEST_HEADER = \"amz-sdk-request\";\n","import { DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY } from \"./constants\";\nexport const getDefaultRetryBackoffStrategy = () => {\n let delayBase = DEFAULT_RETRY_DELAY_BASE;\n const computeNextBackoffDelay = (attempts) => {\n return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));\n };\n const setDelayBase = (delay) => {\n delayBase = delay;\n };\n return {\n computeNextBackoffDelay,\n setDelayBase,\n };\n};\n","import { MAXIMUM_RETRY_DELAY } from \"./constants\";\nexport const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost, }) => {\n const getRetryCount = () => retryCount;\n const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);\n const getRetryCost = () => retryCost;\n return {\n getRetryCount,\n getRetryDelay,\n getRetryCost,\n };\n};\n","import { DEFAULT_MAX_ATTEMPTS, RETRY_MODES } from \"./config\";\nimport { DEFAULT_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, NO_RETRY_INCREMENT, RETRY_COST, THROTTLING_RETRY_DELAY_BASE, TIMEOUT_RETRY_COST, } from \"./constants\";\nimport { getDefaultRetryBackoffStrategy } from \"./defaultRetryBackoffStrategy\";\nimport { createDefaultRetryToken } from \"./defaultRetryToken\";\nexport class StandardRetryStrategy {\n maxAttempts;\n mode = RETRY_MODES.STANDARD;\n capacity = INITIAL_RETRY_TOKENS;\n retryBackoffStrategy = getDefaultRetryBackoffStrategy();\n maxAttemptsProvider;\n constructor(maxAttempts) {\n this.maxAttempts = maxAttempts;\n this.maxAttemptsProvider = typeof maxAttempts === \"function\" ? maxAttempts : async () => maxAttempts;\n }\n async acquireInitialRetryToken(retryTokenScope) {\n return createDefaultRetryToken({\n retryDelay: DEFAULT_RETRY_DELAY_BASE,\n retryCount: 0,\n });\n }\n async refreshRetryTokenForRetry(token, errorInfo) {\n const maxAttempts = await this.getMaxAttempts();\n if (this.shouldRetry(token, errorInfo, maxAttempts)) {\n const errorType = errorInfo.errorType;\n this.retryBackoffStrategy.setDelayBase(errorType === \"THROTTLING\" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);\n const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());\n const retryDelay = errorInfo.retryAfterHint\n ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType)\n : delayFromErrorType;\n const capacityCost = this.getCapacityCost(errorType);\n this.capacity -= capacityCost;\n return createDefaultRetryToken({\n retryDelay,\n retryCount: token.getRetryCount() + 1,\n retryCost: capacityCost,\n });\n }\n throw new Error(\"No retry token available\");\n }\n recordSuccess(token) {\n this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));\n }\n getCapacity() {\n return this.capacity;\n }\n async getMaxAttempts() {\n try {\n return await this.maxAttemptsProvider();\n }\n catch (error) {\n console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);\n return DEFAULT_MAX_ATTEMPTS;\n }\n }\n shouldRetry(tokenToRenew, errorInfo, maxAttempts) {\n const attempts = tokenToRenew.getRetryCount() + 1;\n return (attempts < maxAttempts &&\n this.capacity >= this.getCapacityCost(errorInfo.errorType) &&\n this.isRetryableError(errorInfo.errorType));\n }\n getCapacityCost(errorType) {\n return errorType === \"TRANSIENT\" ? TIMEOUT_RETRY_COST : RETRY_COST;\n }\n isRetryableError(errorType) {\n return errorType === \"THROTTLING\" || errorType === \"TRANSIENT\";\n }\n}\n","import { RETRY_MODES } from \"./config\";\nimport { DefaultRateLimiter } from \"./DefaultRateLimiter\";\nimport { StandardRetryStrategy } from \"./StandardRetryStrategy\";\nexport class AdaptiveRetryStrategy {\n maxAttemptsProvider;\n rateLimiter;\n standardRetryStrategy;\n mode = RETRY_MODES.ADAPTIVE;\n constructor(maxAttemptsProvider, options) {\n this.maxAttemptsProvider = maxAttemptsProvider;\n const { rateLimiter } = options ?? {};\n this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();\n this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);\n }\n async acquireInitialRetryToken(retryTokenScope) {\n await this.rateLimiter.getSendToken();\n return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);\n }\n async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {\n this.rateLimiter.updateClientSendingRate(errorInfo);\n return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);\n }\n recordSuccess(token) {\n this.rateLimiter.updateClientSendingRate({});\n this.standardRetryStrategy.recordSuccess(token);\n }\n}\n","import { DEFAULT_RETRY_DELAY_BASE } from \"./constants\";\nimport { StandardRetryStrategy } from \"./StandardRetryStrategy\";\nexport class ConfiguredRetryStrategy extends StandardRetryStrategy {\n computeNextBackoffDelay;\n constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) {\n super(typeof maxAttempts === \"function\" ? maxAttempts : async () => maxAttempts);\n if (typeof computeNextBackoffDelay === \"number\") {\n this.computeNextBackoffDelay = () => computeNextBackoffDelay;\n }\n else {\n this.computeNextBackoffDelay = computeNextBackoffDelay;\n }\n }\n async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {\n const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo);\n token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount());\n return token;\n }\n}\n","export {};\n","export * from \"./AdaptiveRetryStrategy\";\nexport * from \"./ConfiguredRetryStrategy\";\nexport * from \"./DefaultRateLimiter\";\nexport * from \"./StandardRetryStrategy\";\nexport * from \"./config\";\nexport * from \"./constants\";\nexport * from \"./types\";\n","import { MAXIMUM_RETRY_DELAY } from \"@smithy/util-retry\";\nexport const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));\n","import { isClockSkewError, isRetryableByTrait, isThrottlingError, isTransientError, } from \"@smithy/service-error-classification\";\nexport const defaultRetryDecider = (error) => {\n if (!error) {\n return false;\n }\n return isRetryableByTrait(error) || isClockSkewError(error) || isThrottlingError(error) || isTransientError(error);\n};\n","export const asSdkError = (error) => {\n if (error instanceof Error)\n return error;\n if (error instanceof Object)\n return Object.assign(new Error(), error);\n if (typeof error === \"string\")\n return new Error(error);\n return new Error(`AWS SDK error wrapper for ${error}`);\n};\n","import { HttpRequest, HttpResponse } from \"@smithy/protocol-http\";\nimport { isThrottlingError } from \"@smithy/service-error-classification\";\nimport { DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, INVOCATION_ID_HEADER, REQUEST_HEADER, RETRY_MODES, THROTTLING_RETRY_DELAY_BASE, } from \"@smithy/util-retry\";\nimport { v4 } from \"@smithy/uuid\";\nimport { getDefaultRetryQuota } from \"./defaultRetryQuota\";\nimport { defaultDelayDecider } from \"./delayDecider\";\nimport { defaultRetryDecider } from \"./retryDecider\";\nimport { asSdkError } from \"./util\";\nexport class StandardRetryStrategy {\n maxAttemptsProvider;\n retryDecider;\n delayDecider;\n retryQuota;\n mode = RETRY_MODES.STANDARD;\n constructor(maxAttemptsProvider, options) {\n this.maxAttemptsProvider = maxAttemptsProvider;\n this.retryDecider = options?.retryDecider ?? defaultRetryDecider;\n this.delayDecider = options?.delayDecider ?? defaultDelayDecider;\n this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(INITIAL_RETRY_TOKENS);\n }\n shouldRetry(error, attempts, maxAttempts) {\n return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error);\n }\n async getMaxAttempts() {\n let maxAttempts;\n try {\n maxAttempts = await this.maxAttemptsProvider();\n }\n catch (error) {\n maxAttempts = DEFAULT_MAX_ATTEMPTS;\n }\n return maxAttempts;\n }\n async retry(next, args, options) {\n let retryTokenAmount;\n let attempts = 0;\n let totalDelay = 0;\n const maxAttempts = await this.getMaxAttempts();\n const { request } = args;\n if (HttpRequest.isInstance(request)) {\n request.headers[INVOCATION_ID_HEADER] = v4();\n }\n while (true) {\n try {\n if (HttpRequest.isInstance(request)) {\n request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;\n }\n if (options?.beforeRequest) {\n await options.beforeRequest();\n }\n const { response, output } = await next(args);\n if (options?.afterRequest) {\n options.afterRequest(response);\n }\n this.retryQuota.releaseRetryTokens(retryTokenAmount);\n output.$metadata.attempts = attempts + 1;\n output.$metadata.totalRetryDelay = totalDelay;\n return { response, output };\n }\n catch (e) {\n const err = asSdkError(e);\n attempts++;\n if (this.shouldRetry(err, attempts, maxAttempts)) {\n retryTokenAmount = this.retryQuota.retrieveRetryTokens(err);\n const delayFromDecider = this.delayDecider(isThrottlingError(err) ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE, attempts);\n const delayFromResponse = getDelayFromRetryAfterHeader(err.$response);\n const delay = Math.max(delayFromResponse || 0, delayFromDecider);\n totalDelay += delay;\n await new Promise((resolve) => setTimeout(resolve, delay));\n continue;\n }\n if (!err.$metadata) {\n err.$metadata = {};\n }\n err.$metadata.attempts = attempts;\n err.$metadata.totalRetryDelay = totalDelay;\n throw err;\n }\n }\n }\n}\nconst getDelayFromRetryAfterHeader = (response) => {\n if (!HttpResponse.isInstance(response))\n return;\n const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === \"retry-after\");\n if (!retryAfterHeaderName)\n return;\n const retryAfter = response.headers[retryAfterHeaderName];\n const retryAfterSeconds = Number(retryAfter);\n if (!Number.isNaN(retryAfterSeconds))\n return retryAfterSeconds * 1000;\n const retryAfterDate = new Date(retryAfter);\n return retryAfterDate.getTime() - Date.now();\n};\n","import { DefaultRateLimiter, RETRY_MODES } from \"@smithy/util-retry\";\nimport { StandardRetryStrategy } from \"./StandardRetryStrategy\";\nexport class AdaptiveRetryStrategy extends StandardRetryStrategy {\n rateLimiter;\n constructor(maxAttemptsProvider, options) {\n const { rateLimiter, ...superOptions } = options ?? {};\n super(maxAttemptsProvider, superOptions);\n this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();\n this.mode = RETRY_MODES.ADAPTIVE;\n }\n async retry(next, args) {\n return super.retry(next, args, {\n beforeRequest: async () => {\n return this.rateLimiter.getSendToken();\n },\n afterRequest: (response) => {\n this.rateLimiter.updateClientSendingRate(response);\n },\n });\n }\n}\n","import { normalizeProvider } from \"@smithy/util-middleware\";\nimport { AdaptiveRetryStrategy, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE, RETRY_MODES, StandardRetryStrategy, } from \"@smithy/util-retry\";\nexport const ENV_MAX_ATTEMPTS = \"AWS_MAX_ATTEMPTS\";\nexport const CONFIG_MAX_ATTEMPTS = \"max_attempts\";\nexport const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => {\n const value = env[ENV_MAX_ATTEMPTS];\n if (!value)\n return undefined;\n const maxAttempt = parseInt(value);\n if (Number.isNaN(maxAttempt)) {\n throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got \"${value}\"`);\n }\n return maxAttempt;\n },\n configFileSelector: (profile) => {\n const value = profile[CONFIG_MAX_ATTEMPTS];\n if (!value)\n return undefined;\n const maxAttempt = parseInt(value);\n if (Number.isNaN(maxAttempt)) {\n throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got \"${value}\"`);\n }\n return maxAttempt;\n },\n default: DEFAULT_MAX_ATTEMPTS,\n};\nexport const resolveRetryConfig = (input) => {\n const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;\n const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS);\n return Object.assign(input, {\n maxAttempts,\n retryStrategy: async () => {\n if (retryStrategy) {\n return retryStrategy;\n }\n const retryMode = await normalizeProvider(_retryMode)();\n if (retryMode === RETRY_MODES.ADAPTIVE) {\n return new AdaptiveRetryStrategy(maxAttempts);\n }\n return new StandardRetryStrategy(maxAttempts);\n },\n });\n};\nexport const ENV_RETRY_MODE = \"AWS_RETRY_MODE\";\nexport const CONFIG_RETRY_MODE = \"retry_mode\";\nexport const NODE_RETRY_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_RETRY_MODE],\n configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],\n default: DEFAULT_RETRY_MODE,\n};\n","import { HttpRequest } from \"@smithy/protocol-http\";\nimport { INVOCATION_ID_HEADER, REQUEST_HEADER } from \"@smithy/util-retry\";\nexport const omitRetryHeadersMiddleware = () => (next) => async (args) => {\n const { request } = args;\n if (HttpRequest.isInstance(request)) {\n delete request.headers[INVOCATION_ID_HEADER];\n delete request.headers[REQUEST_HEADER];\n }\n return next(args);\n};\nexport const omitRetryHeadersMiddlewareOptions = {\n name: \"omitRetryHeadersMiddleware\",\n tags: [\"RETRY\", \"HEADERS\", \"OMIT_RETRY_HEADERS\"],\n relation: \"before\",\n toMiddleware: \"awsAuthMiddleware\",\n override: true,\n};\nexport const getOmitRetryHeadersPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);\n },\n});\n","import { Readable } from \"stream\";\nexport const isStreamingPayload = (request) => request?.body instanceof Readable ||\n (typeof ReadableStream !== \"undefined\" && request?.body instanceof ReadableStream);\n","import { HttpRequest, HttpResponse } from \"@smithy/protocol-http\";\nimport { isServerError, isThrottlingError, isTransientError } from \"@smithy/service-error-classification\";\nimport { NoOpLogger } from \"@smithy/smithy-client\";\nimport { INVOCATION_ID_HEADER, REQUEST_HEADER } from \"@smithy/util-retry\";\nimport { v4 } from \"@smithy/uuid\";\nimport { isStreamingPayload } from \"./isStreamingPayload/isStreamingPayload\";\nimport { asSdkError } from \"./util\";\nexport const retryMiddleware = (options) => (next, context) => async (args) => {\n let retryStrategy = await options.retryStrategy();\n const maxAttempts = await options.maxAttempts();\n if (isRetryStrategyV2(retryStrategy)) {\n retryStrategy = retryStrategy;\n let retryToken = await retryStrategy.acquireInitialRetryToken(context[\"partition_id\"]);\n let lastError = new Error();\n let attempts = 0;\n let totalRetryDelay = 0;\n const { request } = args;\n const isRequest = HttpRequest.isInstance(request);\n if (isRequest) {\n request.headers[INVOCATION_ID_HEADER] = v4();\n }\n while (true) {\n try {\n if (isRequest) {\n request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;\n }\n const { response, output } = await next(args);\n retryStrategy.recordSuccess(retryToken);\n output.$metadata.attempts = attempts + 1;\n output.$metadata.totalRetryDelay = totalRetryDelay;\n return { response, output };\n }\n catch (e) {\n const retryErrorInfo = getRetryErrorInfo(e);\n lastError = asSdkError(e);\n if (isRequest && isStreamingPayload(request)) {\n (context.logger instanceof NoOpLogger ? console : context.logger)?.warn(\"An error was encountered in a non-retryable streaming request.\");\n throw lastError;\n }\n try {\n retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);\n }\n catch (refreshError) {\n if (!lastError.$metadata) {\n lastError.$metadata = {};\n }\n lastError.$metadata.attempts = attempts + 1;\n lastError.$metadata.totalRetryDelay = totalRetryDelay;\n throw lastError;\n }\n attempts = retryToken.getRetryCount();\n const delay = retryToken.getRetryDelay();\n totalRetryDelay += delay;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n else {\n retryStrategy = retryStrategy;\n if (retryStrategy?.mode)\n context.userAgent = [...(context.userAgent || []), [\"cfg/retry-mode\", retryStrategy.mode]];\n return retryStrategy.retry(next, args);\n }\n};\nconst isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== \"undefined\" &&\n typeof retryStrategy.refreshRetryTokenForRetry !== \"undefined\" &&\n typeof retryStrategy.recordSuccess !== \"undefined\";\nconst getRetryErrorInfo = (error) => {\n const errorInfo = {\n error,\n errorType: getRetryErrorType(error),\n };\n const retryAfterHint = getRetryAfterHint(error.$response);\n if (retryAfterHint) {\n errorInfo.retryAfterHint = retryAfterHint;\n }\n return errorInfo;\n};\nconst getRetryErrorType = (error) => {\n if (isThrottlingError(error))\n return \"THROTTLING\";\n if (isTransientError(error))\n return \"TRANSIENT\";\n if (isServerError(error))\n return \"SERVER_ERROR\";\n return \"CLIENT_ERROR\";\n};\nexport const retryMiddlewareOptions = {\n name: \"retryMiddleware\",\n tags: [\"RETRY\"],\n step: \"finalizeRequest\",\n priority: \"high\",\n override: true,\n};\nexport const getRetryPlugin = (options) => ({\n applyToStack: (clientStack) => {\n clientStack.add(retryMiddleware(options), retryMiddlewareOptions);\n },\n});\nexport const getRetryAfterHint = (response) => {\n if (!HttpResponse.isInstance(response))\n return;\n const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === \"retry-after\");\n if (!retryAfterHeaderName)\n return;\n const retryAfter = response.headers[retryAfterHeaderName];\n const retryAfterSeconds = Number(retryAfter);\n if (!Number.isNaN(retryAfterSeconds))\n return new Date(retryAfterSeconds * 1000);\n const retryAfterDate = new Date(retryAfter);\n return retryAfterDate;\n};\n","export * from \"./AdaptiveRetryStrategy\";\nexport * from \"./StandardRetryStrategy\";\nexport * from \"./configurations\";\nexport * from \"./delayDecider\";\nexport * from \"./omitRetryHeadersMiddleware\";\nexport * from \"./retryDecider\";\nexport * from \"./retryMiddleware\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n","export * from \"./fromEnv\";\n","import { ProviderError } from \"@smithy/property-provider\";\nimport { Buffer } from \"buffer\";\nimport { request } from \"http\";\nexport function httpRequest(options) {\n return new Promise((resolve, reject) => {\n const req = request({\n method: \"GET\",\n ...options,\n hostname: options.hostname?.replace(/^\\[(.+)\\]$/, \"$1\"),\n });\n req.on(\"error\", (err) => {\n reject(Object.assign(new ProviderError(\"Unable to connect to instance metadata service\"), err));\n req.destroy();\n });\n req.on(\"timeout\", () => {\n reject(new ProviderError(\"TimeoutError from instance metadata service\"));\n req.destroy();\n });\n req.on(\"response\", (res) => {\n const { statusCode = 400 } = res;\n if (statusCode < 200 || 300 <= statusCode) {\n reject(Object.assign(new ProviderError(\"Error response received from instance metadata service\"), { statusCode }));\n req.destroy();\n }\n const chunks = [];\n res.on(\"data\", (chunk) => {\n chunks.push(chunk);\n });\n res.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n req.destroy();\n });\n });\n req.end();\n });\n}\n","export const isImdsCredentials = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.AccessKeyId === \"string\" &&\n typeof arg.SecretAccessKey === \"string\" &&\n typeof arg.Token === \"string\" &&\n typeof arg.Expiration === \"string\";\nexport const fromImdsCredentials = (creds) => ({\n accessKeyId: creds.AccessKeyId,\n secretAccessKey: creds.SecretAccessKey,\n sessionToken: creds.Token,\n expiration: new Date(creds.Expiration),\n ...(creds.AccountId && { accountId: creds.AccountId }),\n});\n","export const DEFAULT_TIMEOUT = 1000;\nexport const DEFAULT_MAX_RETRIES = 0;\nexport const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout });\n","export const retry = (toRetry, maxRetries) => {\n let promise = toRetry();\n for (let i = 0; i < maxRetries; i++) {\n promise = promise.catch(toRetry);\n }\n return promise;\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { parse } from \"url\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { retry } from \"./remoteProvider/retry\";\nexport const ENV_CMDS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nexport const ENV_CMDS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nexport const ENV_CMDS_AUTH_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromContainerMetadata = (init = {}) => {\n const { timeout, maxRetries } = providerConfigFromInit(init);\n return () => retry(async () => {\n const requestOptions = await getCmdsUri({ logger: init.logger });\n const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));\n if (!isImdsCredentials(credsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credsResponse);\n }, maxRetries);\n};\nconst requestFromEcsImds = async (timeout, options) => {\n if (process.env[ENV_CMDS_AUTH_TOKEN]) {\n options.headers = {\n ...options.headers,\n Authorization: process.env[ENV_CMDS_AUTH_TOKEN],\n };\n }\n const buffer = await httpRequest({\n ...options,\n timeout,\n });\n return buffer.toString();\n};\nconst CMDS_IP = \"169.254.170.2\";\nconst GREENGRASS_HOSTS = {\n localhost: true,\n \"127.0.0.1\": true,\n};\nconst GREENGRASS_PROTOCOLS = {\n \"http:\": true,\n \"https:\": true,\n};\nconst getCmdsUri = async ({ logger }) => {\n if (process.env[ENV_CMDS_RELATIVE_URI]) {\n return {\n hostname: CMDS_IP,\n path: process.env[ENV_CMDS_RELATIVE_URI],\n };\n }\n if (process.env[ENV_CMDS_FULL_URI]) {\n const parsed = parse(process.env[ENV_CMDS_FULL_URI]);\n if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {\n throw new CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {\n tryNextLink: false,\n logger,\n });\n }\n if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {\n throw new CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {\n tryNextLink: false,\n logger,\n });\n }\n return {\n ...parsed,\n port: parsed.port ? parseInt(parsed.port, 10) : undefined,\n };\n }\n throw new CredentialsProviderError(\"The container metadata credential provider cannot be used unless\" +\n ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` +\n \" variable is set\", {\n tryNextLink: false,\n logger,\n });\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nexport class InstanceMetadataV1FallbackError extends CredentialsProviderError {\n tryNextLink;\n name = \"InstanceMetadataV1FallbackError\";\n constructor(message, tryNextLink = true) {\n super(message, tryNextLink);\n this.tryNextLink = tryNextLink;\n Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype);\n }\n}\n","export var Endpoint;\n(function (Endpoint) {\n Endpoint[\"IPv4\"] = \"http://169.254.169.254\";\n Endpoint[\"IPv6\"] = \"http://[fd00:ec2::254]\";\n})(Endpoint || (Endpoint = {}));\n","export const ENV_ENDPOINT_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT\";\nexport const CONFIG_ENDPOINT_NAME = \"ec2_metadata_service_endpoint\";\nexport const ENDPOINT_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],\n default: undefined,\n};\n","export var EndpointMode;\n(function (EndpointMode) {\n EndpointMode[\"IPv4\"] = \"IPv4\";\n EndpointMode[\"IPv6\"] = \"IPv6\";\n})(EndpointMode || (EndpointMode = {}));\n","import { EndpointMode } from \"./EndpointMode\";\nexport const ENV_ENDPOINT_MODE_NAME = \"AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE\";\nexport const CONFIG_ENDPOINT_MODE_NAME = \"ec2_metadata_service_endpoint_mode\";\nexport const ENDPOINT_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME],\n configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],\n default: EndpointMode.IPv4,\n};\n","import { loadConfig } from \"@smithy/node-config-provider\";\nimport { parseUrl } from \"@smithy/url-parser\";\nimport { Endpoint as InstanceMetadataEndpoint } from \"../config/Endpoint\";\nimport { ENDPOINT_CONFIG_OPTIONS } from \"../config/EndpointConfigOptions\";\nimport { EndpointMode } from \"../config/EndpointMode\";\nimport { ENDPOINT_MODE_CONFIG_OPTIONS, } from \"../config/EndpointModeConfigOptions\";\nexport const getInstanceMetadataEndpoint = async () => parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig()));\nconst getFromEndpointConfig = async () => loadConfig(ENDPOINT_CONFIG_OPTIONS)();\nconst getFromEndpointModeConfig = async () => {\n const endpointMode = await loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)();\n switch (endpointMode) {\n case EndpointMode.IPv4:\n return InstanceMetadataEndpoint.IPv4;\n case EndpointMode.IPv6:\n return InstanceMetadataEndpoint.IPv6;\n default:\n throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`);\n }\n};\n","const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;\nconst STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;\nconst STATIC_STABILITY_DOC_URL = \"https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html\";\nexport const getExtendedInstanceMetadataCredentials = (credentials, logger) => {\n const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS +\n Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);\n const newExpiration = new Date(Date.now() + refreshInterval * 1000);\n logger.warn(\"Attempting credential expiration extension due to a credential service availability issue. A refresh of these \" +\n `credentials will be attempted after ${new Date(newExpiration)}.\\nFor more information, please visit: ` +\n STATIC_STABILITY_DOC_URL);\n const originalExpiration = credentials.originalExpiration ?? credentials.expiration;\n return {\n ...credentials,\n ...(originalExpiration ? { originalExpiration } : {}),\n expiration: newExpiration,\n };\n};\n","import { getExtendedInstanceMetadataCredentials } from \"./getExtendedInstanceMetadataCredentials\";\nexport const staticStabilityProvider = (provider, options = {}) => {\n const logger = options?.logger || console;\n let pastCredentials;\n return async () => {\n let credentials;\n try {\n credentials = await provider();\n if (credentials.expiration && credentials.expiration.getTime() < Date.now()) {\n credentials = getExtendedInstanceMetadataCredentials(credentials, logger);\n }\n }\n catch (e) {\n if (pastCredentials) {\n logger.warn(\"Credential renew failed: \", e);\n credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger);\n }\n else {\n throw e;\n }\n }\n pastCredentials = credentials;\n return credentials;\n };\n};\n","import { loadConfig } from \"@smithy/node-config-provider\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { InstanceMetadataV1FallbackError } from \"./error/InstanceMetadataV1FallbackError\";\nimport { httpRequest } from \"./remoteProvider/httpRequest\";\nimport { fromImdsCredentials, isImdsCredentials } from \"./remoteProvider/ImdsCredentials\";\nimport { providerConfigFromInit } from \"./remoteProvider/RemoteProviderInit\";\nimport { retry } from \"./remoteProvider/retry\";\nimport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nimport { staticStabilityProvider } from \"./utils/staticStabilityProvider\";\nconst IMDS_PATH = \"/latest/meta-data/iam/security-credentials/\";\nconst IMDS_TOKEN_PATH = \"/latest/api/token\";\nconst AWS_EC2_METADATA_V1_DISABLED = \"AWS_EC2_METADATA_V1_DISABLED\";\nconst PROFILE_AWS_EC2_METADATA_V1_DISABLED = \"ec2_metadata_v1_disabled\";\nconst X_AWS_EC2_METADATA_TOKEN = \"x-aws-ec2-metadata-token\";\nexport const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger });\nconst getInstanceMetadataProvider = (init = {}) => {\n let disableFetchToken = false;\n const { logger, profile } = init;\n const { timeout, maxRetries } = providerConfigFromInit(init);\n const getCredentials = async (maxRetries, options) => {\n const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null;\n if (isImdsV1Fallback) {\n let fallbackBlockedFromProfile = false;\n let fallbackBlockedFromProcessEnv = false;\n const configValue = await loadConfig({\n environmentVariableSelector: (env) => {\n const envValue = env[AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProcessEnv = !!envValue && envValue !== \"false\";\n if (envValue === undefined) {\n throw new CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger });\n }\n return fallbackBlockedFromProcessEnv;\n },\n configFileSelector: (profile) => {\n const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED];\n fallbackBlockedFromProfile = !!profileValue && profileValue !== \"false\";\n return fallbackBlockedFromProfile;\n },\n default: false,\n }, {\n profile,\n })();\n if (init.ec2MetadataV1Disabled || configValue) {\n const causes = [];\n if (init.ec2MetadataV1Disabled)\n causes.push(\"credential provider initialization (runtime option ec2MetadataV1Disabled)\");\n if (fallbackBlockedFromProfile)\n causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);\n if (fallbackBlockedFromProcessEnv)\n causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);\n throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(\", \")}].`);\n }\n }\n const imdsProfile = (await retry(async () => {\n let profile;\n try {\n profile = await getProfile(options);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return profile;\n }, maxRetries)).trim();\n return retry(async () => {\n let creds;\n try {\n creds = await getCredentialsFromProfile(imdsProfile, options, init);\n }\n catch (err) {\n if (err.statusCode === 401) {\n disableFetchToken = false;\n }\n throw err;\n }\n return creds;\n }, maxRetries);\n };\n return async () => {\n const endpoint = await getInstanceMetadataEndpoint();\n if (disableFetchToken) {\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (no token fetch)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n else {\n let token;\n try {\n token = (await getMetadataToken({ ...endpoint, timeout })).toString();\n }\n catch (error) {\n if (error?.statusCode === 400) {\n throw Object.assign(error, {\n message: \"EC2 Metadata token request returned error\",\n });\n }\n else if (error.message === \"TimeoutError\" || [403, 404, 405].includes(error.statusCode)) {\n disableFetchToken = true;\n }\n logger?.debug(\"AWS SDK Instance Metadata\", \"using v1 fallback (initial)\");\n return getCredentials(maxRetries, { ...endpoint, timeout });\n }\n return getCredentials(maxRetries, {\n ...endpoint,\n headers: {\n [X_AWS_EC2_METADATA_TOKEN]: token,\n },\n timeout,\n });\n }\n };\n};\nconst getMetadataToken = async (options) => httpRequest({\n ...options,\n path: IMDS_TOKEN_PATH,\n method: \"PUT\",\n headers: {\n \"x-aws-ec2-metadata-token-ttl-seconds\": \"21600\",\n },\n});\nconst getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString();\nconst getCredentialsFromProfile = async (profile, options, init) => {\n const credentialsResponse = JSON.parse((await httpRequest({\n ...options,\n path: IMDS_PATH + profile,\n })).toString());\n if (!isImdsCredentials(credentialsResponse)) {\n throw new CredentialsProviderError(\"Invalid response received from instance metadata service.\", {\n logger: init.logger,\n });\n }\n return fromImdsCredentials(credentialsResponse);\n};\n","export {};\n","export * from \"./fromContainerMetadata\";\nexport * from \"./fromInstanceMetadata\";\nexport * from \"./remoteProvider/RemoteProviderInit\";\nexport * from \"./types\";\nexport { httpRequest } from \"./remoteProvider/httpRequest\";\nexport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nexport { Endpoint } from \"./config/Endpoint\";\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nconst LOOPBACK_CIDR_IPv4 = \"127.0.0.0/8\";\nconst LOOPBACK_CIDR_IPv6 = \"::1/128\";\nconst ECS_CONTAINER_HOST = \"169.254.170.2\";\nconst EKS_CONTAINER_HOST_IPv4 = \"169.254.170.23\";\nconst EKS_CONTAINER_HOST_IPv6 = \"[fd00:ec2::23]\";\nexport const checkUrl = (url, logger) => {\n if (url.protocol === \"https:\") {\n return;\n }\n if (url.hostname === ECS_CONTAINER_HOST ||\n url.hostname === EKS_CONTAINER_HOST_IPv4 ||\n url.hostname === EKS_CONTAINER_HOST_IPv6) {\n return;\n }\n if (url.hostname.includes(\"[\")) {\n if (url.hostname === \"[::1]\" || url.hostname === \"[0000:0000:0000:0000:0000:0000:0000:0001]\") {\n return;\n }\n }\n else {\n if (url.hostname === \"localhost\") {\n return;\n }\n const ipComponents = url.hostname.split(\".\");\n const inRange = (component) => {\n const num = parseInt(component, 10);\n return 0 <= num && num <= 255;\n };\n if (ipComponents[0] === \"127\" &&\n inRange(ipComponents[1]) &&\n inRange(ipComponents[2]) &&\n inRange(ipComponents[3]) &&\n ipComponents.length === 4) {\n return;\n }\n }\n throw new CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:\n - loopback CIDR 127.0.0.0/8 or [::1/128]\n - ECS container host 169.254.170.2\n - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger });\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nimport { parseRfc3339DateTime } from \"@smithy/smithy-client\";\nimport { sdkStreamMixin } from \"@smithy/util-stream\";\nexport function createGetRequest(url) {\n return new HttpRequest({\n protocol: url.protocol,\n hostname: url.hostname,\n port: Number(url.port),\n path: url.pathname,\n query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => {\n acc[k] = v;\n return acc;\n }, {}),\n fragment: url.hash,\n });\n}\nexport async function getCredentials(response, logger) {\n const stream = sdkStreamMixin(response.body);\n const str = await stream.transformToString();\n if (response.statusCode === 200) {\n const parsed = JSON.parse(str);\n if (typeof parsed.AccessKeyId !== \"string\" ||\n typeof parsed.SecretAccessKey !== \"string\" ||\n typeof parsed.Token !== \"string\" ||\n typeof parsed.Expiration !== \"string\") {\n throw new CredentialsProviderError(\"HTTP credential provider response not of the required format, an object matching: \" +\n \"{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }\", { logger });\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.Token,\n expiration: parseRfc3339DateTime(parsed.Expiration),\n };\n }\n if (response.statusCode >= 400 && response.statusCode < 500) {\n let parsedBody = {};\n try {\n parsedBody = JSON.parse(str);\n }\n catch (e) { }\n throw Object.assign(new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), {\n Code: parsedBody.Code,\n Message: parsedBody.Message,\n });\n }\n throw new CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger });\n}\n","export const retryWrapper = (toRetry, maxRetries, delayMs) => {\n return async () => {\n for (let i = 0; i < maxRetries; ++i) {\n try {\n return await toRetry();\n }\n catch (e) {\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n return await toRetry();\n };\n};\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { NodeHttpHandler } from \"@smithy/node-http-handler\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport fs from \"fs/promises\";\nimport { checkUrl } from \"./checkUrl\";\nimport { createGetRequest, getCredentials } from \"./requestHelpers\";\nimport { retryWrapper } from \"./retry-wrapper\";\nconst AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = \"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\";\nconst DEFAULT_LINK_LOCAL_HOST = \"http://169.254.170.2\";\nconst AWS_CONTAINER_CREDENTIALS_FULL_URI = \"AWS_CONTAINER_CREDENTIALS_FULL_URI\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\";\nconst AWS_CONTAINER_AUTHORIZATION_TOKEN = \"AWS_CONTAINER_AUTHORIZATION_TOKEN\";\nexport const fromHttp = (options = {}) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-http - fromHttp\");\n let host;\n const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];\n const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];\n const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];\n const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];\n const warn = options.logger?.constructor?.name === \"NoOpLogger\" || !options.logger?.warn\n ? console.warn\n : options.logger.warn.bind(options.logger);\n if (relative && full) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.\");\n warn(\"awsContainerCredentialsFullUri will take precedence.\");\n }\n if (token && tokenFile) {\n warn(\"@aws-sdk/credential-provider-http: \" +\n \"you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.\");\n warn(\"awsContainerAuthorizationToken will take precedence.\");\n }\n if (full) {\n host = full;\n }\n else if (relative) {\n host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;\n }\n else {\n throw new CredentialsProviderError(`No HTTP credential provider host provided.\nSet AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });\n }\n const url = new URL(host);\n checkUrl(url, options.logger);\n const requestHandler = NodeHttpHandler.create({\n requestTimeout: options.timeout ?? 1000,\n connectionTimeout: options.timeout ?? 1000,\n });\n return retryWrapper(async () => {\n const request = createGetRequest(url);\n if (token) {\n request.headers.Authorization = token;\n }\n else if (tokenFile) {\n request.headers.Authorization = (await fs.readFile(tokenFile)).toString();\n }\n try {\n const result = await requestHandler.handle(request);\n return getCredentials(result.response).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_HTTP\", \"z\"));\n }\n catch (e) {\n throw new CredentialsProviderError(String(e), { logger: options.logger });\n }\n }, options.maxRetries ?? 3, options.timeout ?? 1000);\n};\n","export { fromHttp } from \"./fromHttp/fromHttp\";\n","export const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n","import { setTokenFeature } from \"@aws-sdk/core/client\";\nimport { getBearerTokenEnvKey } from \"@aws-sdk/core/httpAuthSchemes\";\nimport { TokenProviderError } from \"@smithy/property-provider\";\nexport const fromEnvSigningName = ({ logger, signingName } = {}) => async () => {\n logger?.debug?.(\"@aws-sdk/token-providers - fromEnvSigningName\");\n if (!signingName) {\n throw new TokenProviderError(\"Please pass 'signingName' to compute environment variable key\", { logger });\n }\n const bearerTokenKey = getBearerTokenEnvKey(signingName);\n if (!(bearerTokenKey in process.env)) {\n throw new TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger });\n }\n const token = { token: process.env[bearerTokenKey] };\n setTokenFeature(token, \"BEARER_SERVICE_ENV_VARS\", \"3\");\n return token;\n};\n","export const EXPIRE_WINDOW_MS = 5 * 60 * 1000;\nexport const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;\n","import { resolveAwsSdkSigV4Config, } from \"@aws-sdk/core\";\nimport { getSmithyContext, normalizeProvider } from \"@smithy/util-middleware\";\nexport const defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: (await normalizeProvider(config.region)()) ||\n (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sso-oauth\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nexport const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateToken\": {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nexport const resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n","export const resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"sso-oauth\",\n });\n};\nexport const commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n","{\n \"name\": \"@aws-sdk/nested-clients\",\n \"version\": \"3.974.0\",\n \"description\": \"Nested clients for AWS SDK packages.\",\n \"main\": \"./dist-cjs/index.js\",\n \"module\": \"./dist-es/index.js\",\n \"types\": \"./dist-types/index.d.ts\",\n \"scripts\": {\n \"build\": \"yarn lint && concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs\",\n \"build:cjs\": \"node ../../scripts/compilation/inline nested-clients\",\n \"build:es\": \"tsc -p tsconfig.es.json\",\n \"build:include:deps\": \"yarn g:turbo run build -F=\\\"$npm_package_name\\\"\",\n \"build:types\": \"tsc -p tsconfig.types.json\",\n \"build:types:downlevel\": \"downlevel-dts dist-types dist-types/ts3.4\",\n \"clean\": \"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo\",\n \"lint\": \"node ../../scripts/validation/submodules-linter.js --pkg nested-clients\",\n \"test\": \"yarn g:vitest run\",\n \"test:watch\": \"yarn g:vitest watch\"\n },\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"sideEffects\": false,\n \"author\": {\n \"name\": \"AWS SDK for JavaScript Team\",\n \"url\": \"https://aws.amazon.com/javascript/\"\n },\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@aws-crypto/sha256-browser\": \"5.2.0\",\n \"@aws-crypto/sha256-js\": \"5.2.0\",\n \"@aws-sdk/core\": \"^3.973.0\",\n \"@aws-sdk/middleware-host-header\": \"^3.972.1\",\n \"@aws-sdk/middleware-logger\": \"^3.972.1\",\n \"@aws-sdk/middleware-recursion-detection\": \"^3.972.1\",\n \"@aws-sdk/middleware-user-agent\": \"^3.972.1\",\n \"@aws-sdk/region-config-resolver\": \"^3.972.1\",\n \"@aws-sdk/types\": \"^3.973.0\",\n \"@aws-sdk/util-endpoints\": \"3.972.0\",\n \"@aws-sdk/util-user-agent-browser\": \"^3.972.1\",\n \"@aws-sdk/util-user-agent-node\": \"^3.972.1\",\n \"@smithy/config-resolver\": \"^4.4.6\",\n \"@smithy/core\": \"^3.21.0\",\n \"@smithy/fetch-http-handler\": \"^5.3.9\",\n \"@smithy/hash-node\": \"^4.2.8\",\n \"@smithy/invalid-dependency\": \"^4.2.8\",\n \"@smithy/middleware-content-length\": \"^4.2.8\",\n \"@smithy/middleware-endpoint\": \"^4.4.10\",\n \"@smithy/middleware-retry\": \"^4.4.26\",\n \"@smithy/middleware-serde\": \"^4.2.9\",\n \"@smithy/middleware-stack\": \"^4.2.8\",\n \"@smithy/node-config-provider\": \"^4.3.8\",\n \"@smithy/node-http-handler\": \"^4.4.8\",\n \"@smithy/protocol-http\": \"^5.3.8\",\n \"@smithy/smithy-client\": \"^4.10.11\",\n \"@smithy/types\": \"^4.12.0\",\n \"@smithy/url-parser\": \"^4.2.8\",\n \"@smithy/util-base64\": \"^4.3.0\",\n \"@smithy/util-body-length-browser\": \"^4.2.0\",\n \"@smithy/util-body-length-node\": \"^4.2.1\",\n \"@smithy/util-defaults-mode-browser\": \"^4.3.25\",\n \"@smithy/util-defaults-mode-node\": \"^4.2.28\",\n \"@smithy/util-endpoints\": \"^3.2.8\",\n \"@smithy/util-middleware\": \"^4.2.8\",\n \"@smithy/util-retry\": \"^4.2.8\",\n \"@smithy/util-utf8\": \"^4.2.0\",\n \"tslib\": \"^2.6.2\"\n },\n \"devDependencies\": {\n \"concurrently\": \"7.0.0\",\n \"downlevel-dts\": \"0.10.1\",\n \"premove\": \"4.0.0\",\n \"typescript\": \"~5.8.3\"\n },\n \"typesVersions\": {\n \"<4.0\": {\n \"dist-types/*\": [\n \"dist-types/ts3.4/*\"\n ]\n }\n },\n \"files\": [\n \"./signin.d.ts\",\n \"./signin.js\",\n \"./sso-oidc.d.ts\",\n \"./sso-oidc.js\",\n \"./sts.d.ts\",\n \"./sts.js\",\n \"dist-*/**\"\n ],\n \"browser\": {\n \"./dist-es/submodules/signin/runtimeConfig\": \"./dist-es/submodules/signin/runtimeConfig.browser\",\n \"./dist-es/submodules/sso-oidc/runtimeConfig\": \"./dist-es/submodules/sso-oidc/runtimeConfig.browser\",\n \"./dist-es/submodules/sts/runtimeConfig\": \"./dist-es/submodules/sts/runtimeConfig.browser\"\n },\n \"react-native\": {},\n \"homepage\": \"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/aws/aws-sdk-js-v3.git\",\n \"directory\": \"packages/nested-clients\"\n },\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \"./sso-oidc\": {\n \"types\": \"./dist-types/submodules/sso-oidc/index.d.ts\",\n \"module\": \"./dist-es/submodules/sso-oidc/index.js\",\n \"node\": \"./dist-cjs/submodules/sso-oidc/index.js\",\n \"import\": \"./dist-es/submodules/sso-oidc/index.js\",\n \"require\": \"./dist-cjs/submodules/sso-oidc/index.js\"\n },\n \"./sts\": {\n \"types\": \"./dist-types/submodules/sts/index.d.ts\",\n \"module\": \"./dist-es/submodules/sts/index.js\",\n \"node\": \"./dist-cjs/submodules/sts/index.js\",\n \"import\": \"./dist-es/submodules/sts/index.js\",\n \"require\": \"./dist-cjs/submodules/sts/index.js\"\n },\n \"./signin\": {\n \"types\": \"./dist-types/submodules/signin/index.d.ts\",\n \"module\": \"./dist-es/submodules/signin/index.js\",\n \"node\": \"./dist-cjs/submodules/signin/index.js\",\n \"import\": \"./dist-es/submodules/signin/index.js\",\n \"require\": \"./dist-cjs/submodules/signin/index.js\"\n }\n }\n}\n","export const crtAvailability = {\n isCrtAvailable: false,\n};\n","import { crtAvailability } from \"./crt-availability\";\nexport const isCrtAvailable = () => {\n if (crtAvailability.isCrtAvailable) {\n return [\"md/crt-avail\"];\n }\n return null;\n};\n","import { platform, release } from \"os\";\nimport { env, versions } from \"process\";\nimport { isCrtAvailable } from \"./is-crt-available\";\nexport { crtAvailability } from \"./crt-availability\";\nexport const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => {\n return async (config) => {\n const sections = [\n [\"aws-sdk-js\", clientVersion],\n [\"ua\", \"2.1\"],\n [`os/${platform()}`, release()],\n [\"lang/js\"],\n [\"md/nodejs\", `${versions.node}`],\n ];\n const crtAvailable = isCrtAvailable();\n if (crtAvailable) {\n sections.push(crtAvailable);\n }\n if (serviceId) {\n sections.push([`api/${serviceId}`, clientVersion]);\n }\n if (env.AWS_EXECUTION_ENV) {\n sections.push([`exec-env/${env.AWS_EXECUTION_ENV}`]);\n }\n const appId = await config?.userAgentAppId?.();\n const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];\n return resolvedUserAgent;\n };\n};\nexport const defaultUserAgent = createDefaultUserAgentProvider;\n","import { DEFAULT_UA_APP_ID } from \"@aws-sdk/middleware-user-agent\";\nexport const UA_APP_ID_ENV_NAME = \"AWS_SDK_UA_APP_ID\";\nexport const UA_APP_ID_INI_NAME = \"sdk_ua_app_id\";\nconst UA_APP_ID_INI_NAME_DEPRECATED = \"sdk-ua-app-id\";\nexport const NODE_APP_ID_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME],\n configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED],\n default: DEFAULT_UA_APP_ID,\n};\n","export * from \"./defaultUserAgent\";\nexport * from \"./nodeAppIdConfigOptions\";\n","import { fromArrayBuffer, fromString } from \"@smithy/util-buffer-from\";\nimport { toUint8Array } from \"@smithy/util-utf8\";\nimport { Buffer } from \"buffer\";\nimport { createHash, createHmac } from \"crypto\";\nexport class Hash {\n algorithmIdentifier;\n secret;\n hash;\n constructor(algorithmIdentifier, secret) {\n this.algorithmIdentifier = algorithmIdentifier;\n this.secret = secret;\n this.reset();\n }\n update(toHash, encoding) {\n this.hash.update(toUint8Array(castSourceData(toHash, encoding)));\n }\n digest() {\n return Promise.resolve(this.hash.digest());\n }\n reset() {\n this.hash = this.secret\n ? createHmac(this.algorithmIdentifier, castSourceData(this.secret))\n : createHash(this.algorithmIdentifier);\n }\n}\nfunction castSourceData(toCast, encoding) {\n if (Buffer.isBuffer(toCast)) {\n return toCast;\n }\n if (typeof toCast === \"string\") {\n return fromString(toCast, encoding);\n }\n if (ArrayBuffer.isView(toCast)) {\n return fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength);\n }\n return fromArrayBuffer(toCast);\n}\n","import { fstatSync, lstatSync, ReadStream } from \"node:fs\";\nexport const calculateBodyLength = (body) => {\n if (!body) {\n return 0;\n }\n if (typeof body === \"string\") {\n return Buffer.byteLength(body);\n }\n else if (typeof body.byteLength === \"number\") {\n return body.byteLength;\n }\n else if (typeof body.size === \"number\") {\n return body.size;\n }\n else if (typeof body.start === \"number\" && typeof body.end === \"number\") {\n return body.end + 1 - body.start;\n }\n else if (body instanceof ReadStream) {\n if (body.path != null) {\n return lstatSync(body.path).size;\n }\n else if (typeof body.fd === \"number\") {\n return fstatSync(body.fd).size;\n }\n }\n throw new Error(`Body Length computation failed for ${body}`);\n};\n","export * from \"./calculateBodyLength\";\n","export const AWS_EXECUTION_ENV = \"AWS_EXECUTION_ENV\";\nexport const AWS_REGION_ENV = \"AWS_REGION\";\nexport const AWS_DEFAULT_REGION_ENV = \"AWS_DEFAULT_REGION\";\nexport const ENV_IMDS_DISABLED = \"AWS_EC2_METADATA_DISABLED\";\nexport const DEFAULTS_MODE_OPTIONS = [\"in-region\", \"cross-region\", \"mobile\", \"standard\", \"legacy\"];\nexport const IMDS_REGION_PATH = \"/latest/meta-data/placement/region\";\n","const AWS_DEFAULTS_MODE_ENV = \"AWS_DEFAULTS_MODE\";\nconst AWS_DEFAULTS_MODE_CONFIG = \"defaults_mode\";\nexport const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {\n environmentVariableSelector: (env) => {\n return env[AWS_DEFAULTS_MODE_ENV];\n },\n configFileSelector: (profile) => {\n return profile[AWS_DEFAULTS_MODE_CONFIG];\n },\n default: \"legacy\",\n};\n","import { NODE_REGION_CONFIG_OPTIONS } from \"@smithy/config-resolver\";\nimport { loadConfig } from \"@smithy/node-config-provider\";\nimport { memoize } from \"@smithy/property-provider\";\nimport { AWS_DEFAULT_REGION_ENV, AWS_EXECUTION_ENV, AWS_REGION_ENV, DEFAULTS_MODE_OPTIONS, ENV_IMDS_DISABLED, IMDS_REGION_PATH, } from \"./constants\";\nimport { NODE_DEFAULTS_MODE_CONFIG_OPTIONS } from \"./defaultsModeConfig\";\nexport const resolveDefaultsModeConfig = ({ region = loadConfig(NODE_REGION_CONFIG_OPTIONS), defaultsMode = loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => memoize(async () => {\n const mode = typeof defaultsMode === \"function\" ? await defaultsMode() : defaultsMode;\n switch (mode?.toLowerCase()) {\n case \"auto\":\n return resolveNodeDefaultsModeAuto(region);\n case \"in-region\":\n case \"cross-region\":\n case \"mobile\":\n case \"standard\":\n case \"legacy\":\n return Promise.resolve(mode?.toLocaleLowerCase());\n case undefined:\n return Promise.resolve(\"legacy\");\n default:\n throw new Error(`Invalid parameter for \"defaultsMode\", expect ${DEFAULTS_MODE_OPTIONS.join(\", \")}, got ${mode}`);\n }\n});\nconst resolveNodeDefaultsModeAuto = async (clientRegion) => {\n if (clientRegion) {\n const resolvedRegion = typeof clientRegion === \"function\" ? await clientRegion() : clientRegion;\n const inferredRegion = await inferPhysicalRegion();\n if (!inferredRegion) {\n return \"standard\";\n }\n if (resolvedRegion === inferredRegion) {\n return \"in-region\";\n }\n else {\n return \"cross-region\";\n }\n }\n return \"standard\";\n};\nconst inferPhysicalRegion = async () => {\n if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {\n return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];\n }\n if (!process.env[ENV_IMDS_DISABLED]) {\n try {\n const { getInstanceMetadataEndpoint, httpRequest } = await import(\"@smithy/credential-provider-imds\");\n const endpoint = await getInstanceMetadataEndpoint();\n return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString();\n }\n catch (e) {\n }\n }\n};\n","export * from \"./resolveDefaultsModeConfig\";\n","const u = \"required\", v = \"fn\", w = \"argv\", x = \"ref\";\nconst a = true, b = \"isSet\", c = \"booleanEquals\", d = \"error\", e = \"endpoint\", f = \"tree\", g = \"PartitionResult\", h = \"getAttr\", i = { [u]: false, \"type\": \"string\" }, j = { [u]: true, \"default\": false, \"type\": \"boolean\" }, k = { [x]: \"Endpoint\" }, l = { [v]: c, [w]: [{ [x]: \"UseFIPS\" }, true] }, m = { [v]: c, [w]: [{ [x]: \"UseDualStack\" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, \"supportsFIPS\"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, \"supportsDualStack\"] }] }, r = [l], s = [m], t = [{ [x]: \"Region\" }];\nconst _data = { version: \"1.0\", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: \"Invalid Configuration: FIPS and custom endpoint are not supported\", type: d }, { conditions: s, error: \"Invalid Configuration: Dualstack and custom endpoint are not supported\", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: \"aws.partition\", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: \"https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS and DualStack are enabled, but this partition does not support one or both\", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: \"stringEquals\", [w]: [{ [v]: h, [w]: [p, \"name\"] }, \"aws-us-gov\"] }], endpoint: { url: \"https://oidc.{Region}.amazonaws.com\", properties: n, headers: n }, type: e }, { endpoint: { url: \"https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS is enabled but this partition does not support FIPS\", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: \"https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"DualStack is enabled but this partition does not support DualStack\", type: d }], type: f }, { endpoint: { url: \"https://oidc.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: \"Invalid Configuration: Missing Region\", type: d }] };\nexport const ruleSet = _data;\n","import { awsEndpointFunctions } from \"@aws-sdk/util-endpoints\";\nimport { customEndpointFunctions, EndpointCache, resolveEndpoint } from \"@smithy/util-endpoints\";\nimport { ruleSet } from \"./ruleset\";\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nexport const defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n","import { AwsSdkSigV4Signer } from \"@aws-sdk/core\";\nimport { AwsRestJsonProtocol } from \"@aws-sdk/core/protocols\";\nimport { NoAuthSigner } from \"@smithy/core\";\nimport { NoOpLogger } from \"@smithy/smithy-client\";\nimport { parseUrl } from \"@smithy/url-parser\";\nimport { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nimport { defaultSSOOIDCHttpAuthSchemeProvider } from \"./auth/httpAuthSchemeProvider\";\nimport { defaultEndpointResolver } from \"./endpoint/endpointResolver\";\nexport const getRuntimeConfig = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.ssooidc\",\n version: \"2019-06-10\",\n serviceTarget: \"AWSSSOOIDCService\",\n },\n serviceId: config?.serviceId ?? \"SSO OIDC\",\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n","import packageInfo from \"../../../package.json\";\nimport { emitWarningIfUnsupportedVersion as awsCheckVersion, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } from \"@aws-sdk/core\";\nimport { createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS } from \"@aws-sdk/util-user-agent-node\";\nimport { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, } from \"@smithy/config-resolver\";\nimport { Hash } from \"@smithy/hash-node\";\nimport { NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS } from \"@smithy/middleware-retry\";\nimport { loadConfig as loadNodeConfig } from \"@smithy/node-config-provider\";\nimport { NodeHttpHandler as RequestHandler, streamCollector } from \"@smithy/node-http-handler\";\nimport { emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode } from \"@smithy/smithy-client\";\nimport { calculateBodyLength } from \"@smithy/util-body-length-node\";\nimport { resolveDefaultsModeConfig } from \"@smithy/util-defaults-mode-node\";\nimport { DEFAULT_RETRY_MODE } from \"@smithy/util-retry\";\nimport { getRuntimeConfig as getSharedRuntimeConfig } from \"./runtimeConfig.shared\";\nexport const getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getSharedRuntimeConfig(config);\n awsCheckVersion(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadNodeConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ??\n createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadNodeConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ??\n loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: RequestHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadNodeConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n sha256: config?.sha256 ?? Hash.bind(null, \"sha256\"),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadNodeConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n","export const getAwsRegionExtensionConfiguration = (runtimeConfig) => {\n return {\n setRegion(region) {\n runtimeConfig.region = region;\n },\n region() {\n return runtimeConfig.region;\n },\n };\n};\nexport const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {\n return {\n region: awsRegionExtensionConfiguration.region(),\n };\n};\n","export { REGION_ENV_NAME, REGION_INI_NAME, NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS, } from \"@smithy/config-resolver\";\nexport { resolveRegionConfig } from \"@smithy/config-resolver\";\n","import { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS } from \"@smithy/config-resolver\";\nimport { loadConfig } from \"@smithy/node-config-provider\";\nexport function stsRegionDefaultResolver(loaderConfig = {}) {\n return loadConfig({\n ...NODE_REGION_CONFIG_OPTIONS,\n async default() {\n if (!warning.silence) {\n console.warn(\"@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.\");\n }\n return \"us-east-1\";\n },\n }, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig });\n}\nexport const warning = {\n silence: false,\n};\n","export * from \"./extensions\";\nexport * from \"./regionConfig/awsRegionConfig\";\nexport * from \"./regionConfig/stsRegionDefaultResolver\";\n","export const getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nexport const resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n","import { getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, } from \"@aws-sdk/region-config-resolver\";\nimport { getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig } from \"@smithy/protocol-http\";\nimport { getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig } from \"@smithy/smithy-client\";\nimport { getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig } from \"./auth/httpAuthExtensionConfiguration\";\nexport const resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n","import { getHostHeaderPlugin, resolveHostHeaderConfig, } from \"@aws-sdk/middleware-host-header\";\nimport { getLoggerPlugin } from \"@aws-sdk/middleware-logger\";\nimport { getRecursionDetectionPlugin } from \"@aws-sdk/middleware-recursion-detection\";\nimport { getUserAgentPlugin, resolveUserAgentConfig, } from \"@aws-sdk/middleware-user-agent\";\nimport { resolveRegionConfig } from \"@smithy/config-resolver\";\nimport { DefaultIdentityProviderConfig, getHttpAuthSchemeEndpointRuleSetPlugin, getHttpSigningPlugin, } from \"@smithy/core\";\nimport { getSchemaSerdePlugin } from \"@smithy/core/schema\";\nimport { getContentLengthPlugin } from \"@smithy/middleware-content-length\";\nimport { resolveEndpointConfig, } from \"@smithy/middleware-endpoint\";\nimport { getRetryPlugin, resolveRetryConfig, } from \"@smithy/middleware-retry\";\nimport { Client as __Client, } from \"@smithy/smithy-client\";\nimport { defaultSSOOIDCHttpAuthSchemeParametersProvider, resolveHttpAuthSchemeConfig, } from \"./auth/httpAuthSchemeProvider\";\nimport { resolveClientEndpointParameters, } from \"./endpoint/EndpointParameters\";\nimport { getRuntimeConfig as __getRuntimeConfig } from \"./runtimeConfig\";\nimport { resolveRuntimeExtensions } from \"./runtimeExtensions\";\nexport { __Client };\nexport class SSOOIDCClient extends __Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = __getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n","import { ServiceException as __ServiceException, } from \"@smithy/smithy-client\";\nexport { __ServiceException };\nexport class SSOOIDCServiceException extends __ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOOIDCServiceException.prototype);\n }\n}\n","import { SSOOIDCServiceException as __BaseException } from \"./SSOOIDCServiceException\";\nexport class AccessDeniedException extends __BaseException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nexport class AuthorizationPendingException extends __BaseException {\n name = \"AuthorizationPendingException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"AuthorizationPendingException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AuthorizationPendingException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class ExpiredTokenException extends __BaseException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class InternalServerException extends __BaseException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class InvalidClientException extends __BaseException {\n name = \"InvalidClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class InvalidGrantException extends __BaseException {\n name = \"InvalidGrantException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidGrantException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidGrantException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class InvalidRequestException extends __BaseException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n error;\n reason;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n this.error = opts.error;\n this.reason = opts.reason;\n this.error_description = opts.error_description;\n }\n}\nexport class InvalidScopeException extends __BaseException {\n name = \"InvalidScopeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"InvalidScopeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidScopeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class SlowDownException extends __BaseException {\n name = \"SlowDownException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"SlowDownException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, SlowDownException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class UnauthorizedClientException extends __BaseException {\n name = \"UnauthorizedClientException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnauthorizedClientException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedClientException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\nexport class UnsupportedGrantTypeException extends __BaseException {\n name = \"UnsupportedGrantTypeException\";\n $fault = \"client\";\n error;\n error_description;\n constructor(opts) {\n super({\n name: \"UnsupportedGrantTypeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype);\n this.error = opts.error;\n this.error_description = opts.error_description;\n }\n}\n","const _ADE = \"AccessDeniedException\";\nconst _APE = \"AuthorizationPendingException\";\nconst _AT = \"AccessToken\";\nconst _CS = \"ClientSecret\";\nconst _CT = \"CreateToken\";\nconst _CTR = \"CreateTokenRequest\";\nconst _CTRr = \"CreateTokenResponse\";\nconst _CV = \"CodeVerifier\";\nconst _ETE = \"ExpiredTokenException\";\nconst _ICE = \"InvalidClientException\";\nconst _IGE = \"InvalidGrantException\";\nconst _IRE = \"InvalidRequestException\";\nconst _ISE = \"InternalServerException\";\nconst _ISEn = \"InvalidScopeException\";\nconst _IT = \"IdToken\";\nconst _RT = \"RefreshToken\";\nconst _SDE = \"SlowDownException\";\nconst _UCE = \"UnauthorizedClientException\";\nconst _UGTE = \"UnsupportedGrantTypeException\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cS = \"clientSecret\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _dC = \"deviceCode\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _ed = \"error_description\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _r = \"reason\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"scope\";\nconst _se = \"server\";\nconst _sm = \"smithy.ts.sdk.synthetic.com.amazonaws.ssooidc\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.ssooidc\";\nimport { TypeRegistry } from \"@smithy/core/schema\";\nimport { AccessDeniedException, AuthorizationPendingException, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException, } from \"../models/errors\";\nimport { SSOOIDCServiceException } from \"../models/SSOOIDCServiceException\";\nvar AccessToken = [0, n0, _AT, 8, 0];\nvar ClientSecret = [0, n0, _CS, 8, 0];\nvar CodeVerifier = [0, n0, _CV, 8, 0];\nvar IdToken = [0, n0, _IT, 8, 0];\nvar RefreshToken = [0, n0, _RT, 8, 0];\nexport var AccessDeniedException$ = [\n -3,\n n0,\n _ADE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0],\n];\nTypeRegistry.for(n0).registerError(AccessDeniedException$, AccessDeniedException);\nexport var AuthorizationPendingException$ = [\n -3,\n n0,\n _APE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0],\n];\nTypeRegistry.for(n0).registerError(AuthorizationPendingException$, AuthorizationPendingException);\nexport var CreateTokenRequest$ = [\n 3,\n n0,\n _CTR,\n 0,\n [_cI, _cS, _gT, _dC, _co, _rT, _s, _rU, _cV],\n [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]],\n 3,\n];\nexport var CreateTokenResponse$ = [\n 3,\n n0,\n _CTRr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]],\n];\nexport var ExpiredTokenException$ = [-3, n0, _ETE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(ExpiredTokenException$, ExpiredTokenException);\nexport var InternalServerException$ = [-3, n0, _ISE, { [_e]: _se, [_hE]: 500 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(InternalServerException$, InternalServerException);\nexport var InvalidClientException$ = [-3, n0, _ICE, { [_e]: _c, [_hE]: 401 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(InvalidClientException$, InvalidClientException);\nexport var InvalidGrantException$ = [-3, n0, _IGE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(InvalidGrantException$, InvalidGrantException);\nexport var InvalidRequestException$ = [\n -3,\n n0,\n _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _r, _ed],\n [0, 0, 0],\n];\nTypeRegistry.for(n0).registerError(InvalidRequestException$, InvalidRequestException);\nexport var InvalidScopeException$ = [-3, n0, _ISEn, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(InvalidScopeException$, InvalidScopeException);\nexport var SlowDownException$ = [-3, n0, _SDE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]];\nTypeRegistry.for(n0).registerError(SlowDownException$, SlowDownException);\nexport var UnauthorizedClientException$ = [\n -3,\n n0,\n _UCE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0],\n];\nTypeRegistry.for(n0).registerError(UnauthorizedClientException$, UnauthorizedClientException);\nexport var UnsupportedGrantTypeException$ = [\n -3,\n n0,\n _UGTE,\n { [_e]: _c, [_hE]: 400 },\n [_e, _ed],\n [0, 0],\n];\nTypeRegistry.for(n0).registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException);\nexport var SSOOIDCServiceException$ = [-3, _sm, \"SSOOIDCServiceException\", 0, [], []];\nTypeRegistry.for(_sm).registerError(SSOOIDCServiceException$, SSOOIDCServiceException);\nvar Scopes = 64 | 0;\nexport var CreateToken$ = [\n 9,\n n0,\n _CT,\n { [_h]: [\"POST\", \"/token\", 200] },\n () => CreateTokenRequest$,\n () => CreateTokenResponse$,\n];\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { CreateToken$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class CreateTokenCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"AWSSSOOIDCService\", \"CreateToken\", {})\n .n(\"SSOOIDCClient\", \"CreateTokenCommand\")\n .sc(CreateToken$)\n .build() {\n}\n","import { createAggregatedClient } from \"@smithy/smithy-client\";\nimport { CreateTokenCommand } from \"./commands/CreateTokenCommand\";\nimport { SSOOIDCClient } from \"./SSOOIDCClient\";\nconst commands = {\n CreateTokenCommand,\n};\nexport class SSOOIDC extends SSOOIDCClient {\n}\ncreateAggregatedClient(commands, SSOOIDC);\n","export * from \"./CreateTokenCommand\";\n","export const AccessDeniedExceptionReason = {\n KMS_ACCESS_DENIED: \"KMS_AccessDeniedException\",\n};\nexport const InvalidRequestExceptionReason = {\n KMS_DISABLED_KEY: \"KMS_DisabledException\",\n KMS_INVALID_KEY_USAGE: \"KMS_InvalidKeyUsageException\",\n KMS_INVALID_STATE: \"KMS_InvalidStateException\",\n KMS_KEY_NOT_FOUND: \"KMS_NotFoundException\",\n};\n","export {};\n","export * from \"./SSOOIDCClient\";\nexport * from \"./SSOOIDC\";\nexport * from \"./commands\";\nexport * from \"./schemas/schemas_0\";\nexport * from \"./models/enums\";\nexport * from \"./models/errors\";\nexport * from \"./models/models_0\";\nexport { SSOOIDCServiceException } from \"./models/SSOOIDCServiceException\";\n","export const getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {\n const { SSOOIDCClient } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];\n const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, {\n region: ssoRegion ?? init.clientConfig?.region,\n logger: coalesce(\"logger\"),\n userAgentAppId: coalesce(\"userAgentAppId\"),\n }));\n return ssoOidcClient;\n};\n","import { getSsoOidcClient } from \"./getSsoOidcClient\";\nexport const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {\n const { CreateTokenCommand } = await import(\"@aws-sdk/nested-clients/sso-oidc\");\n const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);\n return ssoOidcClient.send(new CreateTokenCommand({\n clientId: ssoToken.clientId,\n clientSecret: ssoToken.clientSecret,\n refreshToken: ssoToken.refreshToken,\n grantType: \"refresh_token\",\n }));\n};\n","import { TokenProviderError } from \"@smithy/property-provider\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenExpiry = (token) => {\n if (token.expiration && token.expiration.getTime() < Date.now()) {\n throw new TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);\n }\n};\n","import { TokenProviderError } from \"@smithy/property-provider\";\nimport { REFRESH_MESSAGE } from \"./constants\";\nexport const validateTokenKey = (key, value, forRefresh = false) => {\n if (typeof value === \"undefined\") {\n throw new TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? \". Cannot refresh\" : \"\"}. ${REFRESH_MESSAGE}`, false);\n }\n};\n","import { getSSOTokenFilepath } from \"@smithy/shared-ini-file-loader\";\nimport { promises as fsPromises } from \"fs\";\nconst { writeFile } = fsPromises;\nexport const writeSSOTokenToFile = (id, ssoToken) => {\n const tokenFilepath = getSSOTokenFilepath(id);\n const tokenString = JSON.stringify(ssoToken, null, 2);\n return writeFile(tokenFilepath, tokenString);\n};\n","import { TokenProviderError } from \"@smithy/property-provider\";\nimport { getProfileName, getSSOTokenFromFile, loadSsoSessionData, parseKnownFiles, } from \"@smithy/shared-ini-file-loader\";\nimport { EXPIRE_WINDOW_MS, REFRESH_MESSAGE } from \"./constants\";\nimport { getNewSsoOidcToken } from \"./getNewSsoOidcToken\";\nimport { validateTokenExpiry } from \"./validateTokenExpiry\";\nimport { validateTokenKey } from \"./validateTokenKey\";\nimport { writeSSOTokenToFile } from \"./writeSSOTokenToFile\";\nconst lastRefreshAttemptTime = new Date(0);\nexport const fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/token-providers - fromSso\");\n const profiles = await parseKnownFiles(init);\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile) {\n throw new TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);\n }\n else if (!profile[\"sso_session\"]) {\n throw new TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);\n }\n const ssoSessionName = profile[\"sso_session\"];\n const ssoSessions = await loadSsoSessionData(init);\n const ssoSession = ssoSessions[ssoSessionName];\n if (!ssoSession) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);\n }\n for (const ssoSessionRequiredKey of [\"sso_start_url\", \"sso_region\"]) {\n if (!ssoSession[ssoSessionRequiredKey]) {\n throw new TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);\n }\n }\n const ssoStartUrl = ssoSession[\"sso_start_url\"];\n const ssoRegion = ssoSession[\"sso_region\"];\n let ssoToken;\n try {\n ssoToken = await getSSOTokenFromFile(ssoSessionName);\n }\n catch (e) {\n throw new TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);\n }\n validateTokenKey(\"accessToken\", ssoToken.accessToken);\n validateTokenKey(\"expiresAt\", ssoToken.expiresAt);\n const { accessToken, expiresAt } = ssoToken;\n const existingToken = { token: accessToken, expiration: new Date(expiresAt) };\n if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {\n return existingToken;\n }\n if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n validateTokenKey(\"clientId\", ssoToken.clientId, true);\n validateTokenKey(\"clientSecret\", ssoToken.clientSecret, true);\n validateTokenKey(\"refreshToken\", ssoToken.refreshToken, true);\n try {\n lastRefreshAttemptTime.setTime(Date.now());\n const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);\n validateTokenKey(\"accessToken\", newSsoOidcToken.accessToken);\n validateTokenKey(\"expiresIn\", newSsoOidcToken.expiresIn);\n const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000);\n try {\n await writeSSOTokenToFile(ssoSessionName, {\n ...ssoToken,\n accessToken: newSsoOidcToken.accessToken,\n expiresAt: newTokenExpiration.toISOString(),\n refreshToken: newSsoOidcToken.refreshToken,\n });\n }\n catch (error) {\n }\n return {\n token: newSsoOidcToken.accessToken,\n expiration: newTokenExpiration,\n };\n }\n catch (error) {\n validateTokenExpiry(existingToken);\n return existingToken;\n }\n};\n","import { TokenProviderError } from \"@smithy/property-provider\";\nexport const fromStatic = ({ token, logger }) => async () => {\n logger?.debug(\"@aws-sdk/token-providers - fromStatic\");\n if (!token || !token.token) {\n throw new TokenProviderError(`Please pass a valid token to fromStatic`, false);\n }\n return token;\n};\n","import { chain, memoize, TokenProviderError } from \"@smithy/property-provider\";\nimport { fromSso } from \"./fromSso\";\nexport const nodeProvider = (init = {}) => memoize(chain(fromSso(init), async () => {\n throw new TokenProviderError(\"Could not load token from any providers\", false);\n}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined);\n","export * from \"./fromEnvSigningName\";\nexport * from \"./fromSso\";\nexport * from \"./fromStatic\";\nexport * from \"./nodeProvider\";\n","import { resolveAwsSdkSigV4Config, } from \"@aws-sdk/core\";\nimport { getSmithyContext, normalizeProvider } from \"@smithy/util-middleware\";\nexport const defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: await normalizeProvider(config.region)() || (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"awsssoportal\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nexport const defaultSSOHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"GetRoleCredentials\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n ;\n case \"ListAccountRoles\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n ;\n case \"ListAccounts\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n ;\n case \"Logout\":\n {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n ;\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nexport const resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n","export const resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"awsssoportal\",\n });\n};\nexport const commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n","{\n \"name\": \"@aws-sdk/client-sso\",\n \"description\": \"AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native\",\n \"version\": \"3.974.0\",\n \"scripts\": {\n \"build\": \"concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs\",\n \"build:cjs\": \"node ../../scripts/compilation/inline client-sso\",\n \"build:es\": \"tsc -p tsconfig.es.json\",\n \"build:include:deps\": \"yarn g:turbo run build -F=\\\"$npm_package_name\\\"\",\n \"build:types\": \"tsc -p tsconfig.types.json\",\n \"build:types:downlevel\": \"downlevel-dts dist-types dist-types/ts3.4\",\n \"clean\": \"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo\",\n \"extract:docs\": \"api-extractor run --local\",\n \"generate:client\": \"node ../../scripts/generate-clients/single-service --solo sso\",\n \"test:index\": \"tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs\"\n },\n \"main\": \"./dist-cjs/index.js\",\n \"types\": \"./dist-types/index.d.ts\",\n \"module\": \"./dist-es/index.js\",\n \"sideEffects\": false,\n \"dependencies\": {\n \"@aws-crypto/sha256-browser\": \"5.2.0\",\n \"@aws-crypto/sha256-js\": \"5.2.0\",\n \"@aws-sdk/core\": \"^3.973.0\",\n \"@aws-sdk/middleware-host-header\": \"^3.972.1\",\n \"@aws-sdk/middleware-logger\": \"^3.972.1\",\n \"@aws-sdk/middleware-recursion-detection\": \"^3.972.1\",\n \"@aws-sdk/middleware-user-agent\": \"^3.972.1\",\n \"@aws-sdk/region-config-resolver\": \"^3.972.1\",\n \"@aws-sdk/types\": \"^3.973.0\",\n \"@aws-sdk/util-endpoints\": \"3.972.0\",\n \"@aws-sdk/util-user-agent-browser\": \"^3.972.1\",\n \"@aws-sdk/util-user-agent-node\": \"^3.972.1\",\n \"@smithy/config-resolver\": \"^4.4.6\",\n \"@smithy/core\": \"^3.21.0\",\n \"@smithy/fetch-http-handler\": \"^5.3.9\",\n \"@smithy/hash-node\": \"^4.2.8\",\n \"@smithy/invalid-dependency\": \"^4.2.8\",\n \"@smithy/middleware-content-length\": \"^4.2.8\",\n \"@smithy/middleware-endpoint\": \"^4.4.10\",\n \"@smithy/middleware-retry\": \"^4.4.26\",\n \"@smithy/middleware-serde\": \"^4.2.9\",\n \"@smithy/middleware-stack\": \"^4.2.8\",\n \"@smithy/node-config-provider\": \"^4.3.8\",\n \"@smithy/node-http-handler\": \"^4.4.8\",\n \"@smithy/protocol-http\": \"^5.3.8\",\n \"@smithy/smithy-client\": \"^4.10.11\",\n \"@smithy/types\": \"^4.12.0\",\n \"@smithy/url-parser\": \"^4.2.8\",\n \"@smithy/util-base64\": \"^4.3.0\",\n \"@smithy/util-body-length-browser\": \"^4.2.0\",\n \"@smithy/util-body-length-node\": \"^4.2.1\",\n \"@smithy/util-defaults-mode-browser\": \"^4.3.25\",\n \"@smithy/util-defaults-mode-node\": \"^4.2.28\",\n \"@smithy/util-endpoints\": \"^3.2.8\",\n \"@smithy/util-middleware\": \"^4.2.8\",\n \"@smithy/util-retry\": \"^4.2.8\",\n \"@smithy/util-utf8\": \"^4.2.0\",\n \"tslib\": \"^2.6.2\"\n },\n \"devDependencies\": {\n \"@tsconfig/node20\": \"20.1.8\",\n \"@types/node\": \"^20.14.8\",\n \"concurrently\": \"7.0.0\",\n \"downlevel-dts\": \"0.10.1\",\n \"premove\": \"4.0.0\",\n \"typescript\": \"~5.8.3\"\n },\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"typesVersions\": {\n \"<4.0\": {\n \"dist-types/*\": [\n \"dist-types/ts3.4/*\"\n ]\n }\n },\n \"files\": [\n \"dist-*/**\"\n ],\n \"author\": {\n \"name\": \"AWS SDK for JavaScript Team\",\n \"url\": \"https://aws.amazon.com/javascript/\"\n },\n \"license\": \"Apache-2.0\",\n \"browser\": {\n \"./dist-es/runtimeConfig\": \"./dist-es/runtimeConfig.browser\"\n },\n \"react-native\": {\n \"./dist-es/runtimeConfig\": \"./dist-es/runtimeConfig.native\"\n },\n \"homepage\": \"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/aws/aws-sdk-js-v3.git\",\n \"directory\": \"clients/client-sso\"\n }\n}\n","const u = \"required\", v = \"fn\", w = \"argv\", x = \"ref\";\nconst a = true, b = \"isSet\", c = \"booleanEquals\", d = \"error\", e = \"endpoint\", f = \"tree\", g = \"PartitionResult\", h = \"getAttr\", i = { [u]: false, \"type\": \"string\" }, j = { [u]: true, \"default\": false, \"type\": \"boolean\" }, k = { [x]: \"Endpoint\" }, l = { [v]: c, [w]: [{ [x]: \"UseFIPS\" }, true] }, m = { [v]: c, [w]: [{ [x]: \"UseDualStack\" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, \"supportsFIPS\"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, \"supportsDualStack\"] }] }, r = [l], s = [m], t = [{ [x]: \"Region\" }];\nconst _data = { version: \"1.0\", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: \"Invalid Configuration: FIPS and custom endpoint are not supported\", type: d }, { conditions: s, error: \"Invalid Configuration: Dualstack and custom endpoint are not supported\", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: \"aws.partition\", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: \"https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS and DualStack are enabled, but this partition does not support one or both\", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: \"stringEquals\", [w]: [{ [v]: h, [w]: [p, \"name\"] }, \"aws-us-gov\"] }], endpoint: { url: \"https://portal.sso.{Region}.amazonaws.com\", properties: n, headers: n }, type: e }, { endpoint: { url: \"https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS is enabled but this partition does not support FIPS\", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: \"https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"DualStack is enabled but this partition does not support DualStack\", type: d }], type: f }, { endpoint: { url: \"https://portal.sso.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: \"Invalid Configuration: Missing Region\", type: d }] };\nexport const ruleSet = _data;\n","import { awsEndpointFunctions } from \"@aws-sdk/util-endpoints\";\nimport { customEndpointFunctions, EndpointCache, resolveEndpoint } from \"@smithy/util-endpoints\";\nimport { ruleSet } from \"./ruleset\";\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nexport const defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n","import { AwsSdkSigV4Signer } from \"@aws-sdk/core\";\nimport { AwsRestJsonProtocol } from \"@aws-sdk/core/protocols\";\nimport { NoAuthSigner } from \"@smithy/core\";\nimport { NoOpLogger } from \"@smithy/smithy-client\";\nimport { parseUrl } from \"@smithy/url-parser\";\nimport { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nimport { defaultSSOHttpAuthSchemeProvider } from \"./auth/httpAuthSchemeProvider\";\nimport { defaultEndpointResolver } from \"./endpoint/endpointResolver\";\nexport const getRuntimeConfig = (config) => {\n return {\n apiVersion: \"2019-06-10\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sso\",\n version: \"2019-06-10\",\n serviceTarget: \"SWBPortalService\",\n },\n serviceId: config?.serviceId ?? \"SSO\",\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n","import packageInfo from \"../package.json\";\nimport { emitWarningIfUnsupportedVersion as awsCheckVersion, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } from \"@aws-sdk/core\";\nimport { createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS } from \"@aws-sdk/util-user-agent-node\";\nimport { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, } from \"@smithy/config-resolver\";\nimport { Hash } from \"@smithy/hash-node\";\nimport { NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS } from \"@smithy/middleware-retry\";\nimport { loadConfig as loadNodeConfig } from \"@smithy/node-config-provider\";\nimport { NodeHttpHandler as RequestHandler, streamCollector } from \"@smithy/node-http-handler\";\nimport { emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode } from \"@smithy/smithy-client\";\nimport { calculateBodyLength } from \"@smithy/util-body-length-node\";\nimport { resolveDefaultsModeConfig } from \"@smithy/util-defaults-mode-node\";\nimport { DEFAULT_RETRY_MODE } from \"@smithy/util-retry\";\nimport { getRuntimeConfig as getSharedRuntimeConfig } from \"./runtimeConfig.shared\";\nexport const getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getSharedRuntimeConfig(config);\n awsCheckVersion(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadNodeConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadNodeConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ?? loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: RequestHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadNodeConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n sha256: config?.sha256 ?? Hash.bind(null, \"sha256\"),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadNodeConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n","export const getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nexport const resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n","import { getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, } from \"@aws-sdk/region-config-resolver\";\nimport { getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig } from \"@smithy/protocol-http\";\nimport { getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig } from \"@smithy/smithy-client\";\nimport { getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig } from \"./auth/httpAuthExtensionConfiguration\";\nexport const resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n","import { getHostHeaderPlugin, resolveHostHeaderConfig, } from \"@aws-sdk/middleware-host-header\";\nimport { getLoggerPlugin } from \"@aws-sdk/middleware-logger\";\nimport { getRecursionDetectionPlugin } from \"@aws-sdk/middleware-recursion-detection\";\nimport { getUserAgentPlugin, resolveUserAgentConfig, } from \"@aws-sdk/middleware-user-agent\";\nimport { resolveRegionConfig } from \"@smithy/config-resolver\";\nimport { DefaultIdentityProviderConfig, getHttpAuthSchemeEndpointRuleSetPlugin, getHttpSigningPlugin, } from \"@smithy/core\";\nimport { getSchemaSerdePlugin } from \"@smithy/core/schema\";\nimport { getContentLengthPlugin } from \"@smithy/middleware-content-length\";\nimport { resolveEndpointConfig, } from \"@smithy/middleware-endpoint\";\nimport { getRetryPlugin, resolveRetryConfig, } from \"@smithy/middleware-retry\";\nimport { Client as __Client, } from \"@smithy/smithy-client\";\nimport { defaultSSOHttpAuthSchemeParametersProvider, resolveHttpAuthSchemeConfig, } from \"./auth/httpAuthSchemeProvider\";\nimport { resolveClientEndpointParameters, } from \"./endpoint/EndpointParameters\";\nimport { getRuntimeConfig as __getRuntimeConfig } from \"./runtimeConfig\";\nimport { resolveRuntimeExtensions } from \"./runtimeExtensions\";\nexport { __Client };\nexport class SSOClient extends __Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = __getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n","import { ServiceException as __ServiceException, } from \"@smithy/smithy-client\";\nexport { __ServiceException };\nexport class SSOServiceException extends __ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SSOServiceException.prototype);\n }\n}\n","import { SSOServiceException as __BaseException } from \"./SSOServiceException\";\nexport class InvalidRequestException extends __BaseException {\n name = \"InvalidRequestException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidRequestException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidRequestException.prototype);\n }\n}\nexport class ResourceNotFoundException extends __BaseException {\n name = \"ResourceNotFoundException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ResourceNotFoundException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ResourceNotFoundException.prototype);\n }\n}\nexport class TooManyRequestsException extends __BaseException {\n name = \"TooManyRequestsException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"TooManyRequestsException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsException.prototype);\n }\n}\nexport class UnauthorizedException extends __BaseException {\n name = \"UnauthorizedException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"UnauthorizedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, UnauthorizedException.prototype);\n }\n}\n","const _AI = \"AccountInfo\";\nconst _ALT = \"AccountListType\";\nconst _ATT = \"AccessTokenType\";\nconst _GRC = \"GetRoleCredentials\";\nconst _GRCR = \"GetRoleCredentialsRequest\";\nconst _GRCRe = \"GetRoleCredentialsResponse\";\nconst _IRE = \"InvalidRequestException\";\nconst _L = \"Logout\";\nconst _LA = \"ListAccounts\";\nconst _LAR = \"ListAccountsRequest\";\nconst _LARR = \"ListAccountRolesRequest\";\nconst _LARRi = \"ListAccountRolesResponse\";\nconst _LARi = \"ListAccountsResponse\";\nconst _LARis = \"ListAccountRoles\";\nconst _LR = \"LogoutRequest\";\nconst _RC = \"RoleCredentials\";\nconst _RI = \"RoleInfo\";\nconst _RLT = \"RoleListType\";\nconst _RNFE = \"ResourceNotFoundException\";\nconst _SAKT = \"SecretAccessKeyType\";\nconst _STT = \"SessionTokenType\";\nconst _TMRE = \"TooManyRequestsException\";\nconst _UE = \"UnauthorizedException\";\nconst _aI = \"accountId\";\nconst _aKI = \"accessKeyId\";\nconst _aL = \"accountList\";\nconst _aN = \"accountName\";\nconst _aT = \"accessToken\";\nconst _ai = \"account_id\";\nconst _c = \"client\";\nconst _e = \"error\";\nconst _eA = \"emailAddress\";\nconst _ex = \"expiration\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _hH = \"httpHeader\";\nconst _hQ = \"httpQuery\";\nconst _m = \"message\";\nconst _mR = \"maxResults\";\nconst _mr = \"max_result\";\nconst _nT = \"nextToken\";\nconst _nt = \"next_token\";\nconst _rC = \"roleCredentials\";\nconst _rL = \"roleList\";\nconst _rN = \"roleName\";\nconst _rn = \"role_name\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sso\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _xasbt = \"x-amz-sso_bearer_token\";\nconst n0 = \"com.amazonaws.sso\";\nimport { TypeRegistry } from \"@smithy/core/schema\";\nimport { InvalidRequestException, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException, } from \"../models/errors\";\nimport { SSOServiceException } from \"../models/SSOServiceException\";\nvar AccessTokenType = [0, n0, _ATT, 8, 0];\nvar SecretAccessKeyType = [0, n0, _SAKT, 8, 0];\nvar SessionTokenType = [0, n0, _STT, 8, 0];\nexport var AccountInfo$ = [3, n0, _AI,\n 0,\n [_aI, _aN, _eA],\n [0, 0, 0]\n];\nexport var GetRoleCredentialsRequest$ = [3, n0, _GRCR,\n 0,\n [_rN, _aI, _aT],\n [[0, { [_hQ]: _rn }], [0, { [_hQ]: _ai }], [() => AccessTokenType, { [_hH]: _xasbt }]], 3\n];\nexport var GetRoleCredentialsResponse$ = [3, n0, _GRCRe,\n 0,\n [_rC],\n [[() => RoleCredentials$, 0]]\n];\nexport var InvalidRequestException$ = [-3, n0, _IRE,\n { [_e]: _c, [_hE]: 400 },\n [_m],\n [0]\n];\nTypeRegistry.for(n0).registerError(InvalidRequestException$, InvalidRequestException);\nexport var ListAccountRolesRequest$ = [3, n0, _LARR,\n 0,\n [_aT, _aI, _nT, _mR],\n [[() => AccessTokenType, { [_hH]: _xasbt }], [0, { [_hQ]: _ai }], [0, { [_hQ]: _nt }], [1, { [_hQ]: _mr }]], 2\n];\nexport var ListAccountRolesResponse$ = [3, n0, _LARRi,\n 0,\n [_nT, _rL],\n [0, () => RoleListType]\n];\nexport var ListAccountsRequest$ = [3, n0, _LAR,\n 0,\n [_aT, _nT, _mR],\n [[() => AccessTokenType, { [_hH]: _xasbt }], [0, { [_hQ]: _nt }], [1, { [_hQ]: _mr }]], 1\n];\nexport var ListAccountsResponse$ = [3, n0, _LARi,\n 0,\n [_nT, _aL],\n [0, () => AccountListType]\n];\nexport var LogoutRequest$ = [3, n0, _LR,\n 0,\n [_aT],\n [[() => AccessTokenType, { [_hH]: _xasbt }]], 1\n];\nexport var ResourceNotFoundException$ = [-3, n0, _RNFE,\n { [_e]: _c, [_hE]: 404 },\n [_m],\n [0]\n];\nTypeRegistry.for(n0).registerError(ResourceNotFoundException$, ResourceNotFoundException);\nexport var RoleCredentials$ = [3, n0, _RC,\n 0,\n [_aKI, _sAK, _sT, _ex],\n [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1]\n];\nexport var RoleInfo$ = [3, n0, _RI,\n 0,\n [_rN, _aI],\n [0, 0]\n];\nexport var TooManyRequestsException$ = [-3, n0, _TMRE,\n { [_e]: _c, [_hE]: 429 },\n [_m],\n [0]\n];\nTypeRegistry.for(n0).registerError(TooManyRequestsException$, TooManyRequestsException);\nexport var UnauthorizedException$ = [-3, n0, _UE,\n { [_e]: _c, [_hE]: 401 },\n [_m],\n [0]\n];\nTypeRegistry.for(n0).registerError(UnauthorizedException$, UnauthorizedException);\nvar __Unit = \"unit\";\nexport var SSOServiceException$ = [-3, _s, \"SSOServiceException\", 0, [], []];\nTypeRegistry.for(_s).registerError(SSOServiceException$, SSOServiceException);\nvar AccountListType = [1, n0, _ALT,\n 0, () => AccountInfo$\n];\nvar RoleListType = [1, n0, _RLT,\n 0, () => RoleInfo$\n];\nexport var GetRoleCredentials$ = [9, n0, _GRC,\n { [_h]: [\"GET\", \"/federation/credentials\", 200] }, () => GetRoleCredentialsRequest$, () => GetRoleCredentialsResponse$\n];\nexport var ListAccountRoles$ = [9, n0, _LARis,\n { [_h]: [\"GET\", \"/assignment/roles\", 200] }, () => ListAccountRolesRequest$, () => ListAccountRolesResponse$\n];\nexport var ListAccounts$ = [9, n0, _LA,\n { [_h]: [\"GET\", \"/assignment/accounts\", 200] }, () => ListAccountsRequest$, () => ListAccountsResponse$\n];\nexport var Logout$ = [9, n0, _L,\n { [_h]: [\"POST\", \"/logout\", 200] }, () => LogoutRequest$, () => __Unit\n];\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { GetRoleCredentials$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class GetRoleCredentialsCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"SWBPortalService\", \"GetRoleCredentials\", {})\n .n(\"SSOClient\", \"GetRoleCredentialsCommand\")\n .sc(GetRoleCredentials$)\n .build() {\n}\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { ListAccountRoles$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class ListAccountRolesCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"SWBPortalService\", \"ListAccountRoles\", {})\n .n(\"SSOClient\", \"ListAccountRolesCommand\")\n .sc(ListAccountRoles$)\n .build() {\n}\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { ListAccounts$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class ListAccountsCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"SWBPortalService\", \"ListAccounts\", {})\n .n(\"SSOClient\", \"ListAccountsCommand\")\n .sc(ListAccounts$)\n .build() {\n}\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { Logout$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class LogoutCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"SWBPortalService\", \"Logout\", {})\n .n(\"SSOClient\", \"LogoutCommand\")\n .sc(Logout$)\n .build() {\n}\n","import { createAggregatedClient } from \"@smithy/smithy-client\";\nimport { GetRoleCredentialsCommand, } from \"./commands/GetRoleCredentialsCommand\";\nimport { ListAccountRolesCommand, } from \"./commands/ListAccountRolesCommand\";\nimport { ListAccountsCommand, } from \"./commands/ListAccountsCommand\";\nimport { LogoutCommand } from \"./commands/LogoutCommand\";\nimport { SSOClient } from \"./SSOClient\";\nconst commands = {\n GetRoleCredentialsCommand,\n ListAccountRolesCommand,\n ListAccountsCommand,\n LogoutCommand,\n};\nexport class SSO extends SSOClient {\n}\ncreateAggregatedClient(commands, SSO);\n","export * from \"./GetRoleCredentialsCommand\";\nexport * from \"./ListAccountRolesCommand\";\nexport * from \"./ListAccountsCommand\";\nexport * from \"./LogoutCommand\";\n","export {};\n","import { createPaginator } from \"@smithy/core\";\nimport { ListAccountRolesCommand, } from \"../commands/ListAccountRolesCommand\";\nimport { SSOClient } from \"../SSOClient\";\nexport const paginateListAccountRoles = createPaginator(SSOClient, ListAccountRolesCommand, \"nextToken\", \"nextToken\", \"maxResults\");\n","import { createPaginator } from \"@smithy/core\";\nimport { ListAccountsCommand, } from \"../commands/ListAccountsCommand\";\nimport { SSOClient } from \"../SSOClient\";\nexport const paginateListAccounts = createPaginator(SSOClient, ListAccountsCommand, \"nextToken\", \"nextToken\", \"maxResults\");\n","export * from \"./Interfaces\";\nexport * from \"./ListAccountRolesPaginator\";\nexport * from \"./ListAccountsPaginator\";\n","export {};\n","export * from \"./SSOClient\";\nexport * from \"./SSO\";\nexport * from \"./commands\";\nexport * from \"./schemas/schemas_0\";\nexport * from \"./pagination\";\nexport * from \"./models/errors\";\nexport * from \"./models/models_0\";\nexport { SSOServiceException } from \"./models/SSOServiceException\";\n","import { GetRoleCredentialsCommand, SSOClient } from \"@aws-sdk/client-sso\";\nexport { GetRoleCredentialsCommand, SSOClient };\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromSso as getSsoTokenProvider } from \"@aws-sdk/token-providers\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getSSOTokenFromFile } from \"@smithy/shared-ini-file-loader\";\nconst SHOULD_FAIL_CREDENTIAL_CHAIN = false;\nexport const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => {\n let token;\n const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;\n if (ssoSession) {\n try {\n const _token = await getSsoTokenProvider({\n profile,\n filepath,\n configFilepath,\n ignoreCache,\n })();\n token = {\n accessToken: _token.token,\n expiresAt: new Date(_token.expiration).toISOString(),\n };\n }\n catch (e) {\n throw new CredentialsProviderError(e.message, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n else {\n try {\n token = await getSSOTokenFromFile(ssoStartUrl);\n }\n catch (e) {\n throw new CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n }\n if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {\n throw new CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { accessToken } = token;\n const { SSOClient, GetRoleCredentialsCommand } = await import(\"./loadSso\");\n const sso = ssoClient ||\n new SSOClient(Object.assign({}, clientConfig ?? {}, {\n logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger,\n region: clientConfig?.region ?? ssoRegion,\n userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId,\n }));\n let ssoResp;\n try {\n ssoResp = await sso.send(new GetRoleCredentialsCommand({\n accountId: ssoAccountId,\n roleName: ssoRoleName,\n accessToken,\n }));\n }\n catch (e) {\n throw new CredentialsProviderError(e, {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp;\n if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {\n throw new CredentialsProviderError(\"SSO returns an invalid temporary credential.\", {\n tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,\n logger,\n });\n }\n const credentials = {\n accessKeyId,\n secretAccessKey,\n sessionToken,\n expiration: new Date(expiration),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n if (ssoSession) {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO\", \"s\");\n }\n else {\n setCredentialFeature(credentials, \"CREDENTIALS_SSO_LEGACY\", \"u\");\n }\n return credentials;\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const validateSsoProfile = (profile, logger) => {\n const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;\n if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {\n throw new CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters \"sso_account_id\", ` +\n `\"sso_region\", \"sso_role_name\", \"sso_start_url\". Got ${Object.keys(profile).join(\", \")}\\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger });\n }\n return profile;\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getProfileName, loadSsoSessionData, parseKnownFiles } from \"@smithy/shared-ini-file-loader\";\nimport { isSsoProfile } from \"./isSsoProfile\";\nimport { resolveSSOCredentials } from \"./resolveSSOCredentials\";\nimport { validateSsoProfile } from \"./validateSsoProfile\";\nexport const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-sso - fromSSO\");\n const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;\n const { ssoClient } = init;\n const profileName = getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n });\n if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {\n const profiles = await parseKnownFiles(init);\n const profile = profiles[profileName];\n if (!profile) {\n throw new CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger });\n }\n if (!isSsoProfile(profile)) {\n throw new CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {\n logger: init.logger,\n });\n }\n if (profile?.sso_session) {\n const ssoSessions = await loadSsoSessionData(init);\n const session = ssoSessions[profile.sso_session];\n const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;\n if (ssoRegion && ssoRegion !== session.sso_region) {\n throw new CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {\n throw new CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {\n tryNextLink: false,\n logger: init.logger,\n });\n }\n profile.sso_region = session.sso_region;\n profile.sso_start_url = session.sso_start_url;\n }\n const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger);\n return resolveSSOCredentials({\n ssoStartUrl: sso_start_url,\n ssoSession: sso_session,\n ssoAccountId: sso_account_id,\n ssoRegion: sso_region,\n ssoRoleName: sso_role_name,\n ssoClient: ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {\n throw new CredentialsProviderError(\"Incomplete configuration. The fromSSO() argument hash must include \" +\n '\"ssoStartUrl\", \"ssoAccountId\", \"ssoRegion\", \"ssoRoleName\"', { tryNextLink: false, logger: init.logger });\n }\n else {\n return resolveSSOCredentials({\n ssoStartUrl,\n ssoSession,\n ssoAccountId,\n ssoRegion,\n ssoRoleName,\n ssoClient,\n clientConfig: init.clientConfig,\n parentClientConfig: init.parentClientConfig,\n callerClientConfig: init.callerClientConfig,\n profile: profileName,\n filepath: init.filepath,\n configFilepath: init.configFilepath,\n ignoreCache: init.ignoreCache,\n logger: init.logger,\n });\n }\n};\n","export {};\n","export * from \"./fromSSO\";\nexport * from \"./isSsoProfile\";\nexport * from \"./types\";\nexport * from \"./validateSsoProfile\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { chain, CredentialsProviderError } from \"@smithy/property-provider\";\nexport const resolveCredentialSource = (credentialSource, profileName, logger) => {\n const sourceProvidersMap = {\n EcsContainer: async (options) => {\n const { fromHttp } = await import(\"@aws-sdk/credential-provider-http\");\n const { fromContainerMetadata } = await import(\"@smithy/credential-provider-imds\");\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is EcsContainer\");\n return async () => chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);\n },\n Ec2InstanceMetadata: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata\");\n const { fromInstanceMetadata } = await import(\"@smithy/credential-provider-imds\");\n return async () => fromInstanceMetadata(options)().then(setNamedProvider);\n },\n Environment: async (options) => {\n logger?.debug(\"@aws-sdk/credential-provider-ini - credential_source is Environment\");\n const { fromEnv } = await import(\"@aws-sdk/credential-provider-env\");\n return async () => fromEnv(options)().then(setNamedProvider);\n },\n };\n if (credentialSource in sourceProvidersMap) {\n return sourceProvidersMap[credentialSource];\n }\n else {\n throw new CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` +\n `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger });\n }\n};\nconst setNamedProvider = (creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_NAMED_PROVIDER\", \"p\");\n","import { resolveAwsSdkSigV4Config, } from \"@aws-sdk/core\";\nimport { getSmithyContext, normalizeProvider } from \"@smithy/util-middleware\";\nimport { STSClient } from \"../STSClient\";\nexport const defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: (await normalizeProvider(config.region)()) ||\n (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"sts\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nexport const defaultSTSHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"AssumeRoleWithWebIdentity\": {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nexport const resolveStsAuthConfig = (input) => Object.assign(input, {\n stsClientCtor: STSClient,\n});\nexport const resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveStsAuthConfig(config);\n const config_1 = resolveAwsSdkSigV4Config(config_0);\n return Object.assign(config_1, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n","export const resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n useGlobalEndpoint: options.useGlobalEndpoint ?? false,\n defaultSigningName: \"sts\",\n });\n};\nexport const commonParams = {\n UseGlobalEndpoint: { type: \"builtInParams\", name: \"useGlobalEndpoint\" },\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n","const F = \"required\", G = \"type\", H = \"fn\", I = \"argv\", J = \"ref\";\nconst a = false, b = true, c = \"booleanEquals\", d = \"stringEquals\", e = \"sigv4\", f = \"sts\", g = \"us-east-1\", h = \"endpoint\", i = \"https://sts.{Region}.{PartitionResult#dnsSuffix}\", j = \"tree\", k = \"error\", l = \"getAttr\", m = { [F]: false, [G]: \"string\" }, n = { [F]: true, \"default\": false, [G]: \"boolean\" }, o = { [J]: \"Endpoint\" }, p = { [H]: \"isSet\", [I]: [{ [J]: \"Region\" }] }, q = { [J]: \"Region\" }, r = { [H]: \"aws.partition\", [I]: [q], \"assign\": \"PartitionResult\" }, s = { [J]: \"UseFIPS\" }, t = { [J]: \"UseDualStack\" }, u = { \"url\": \"https://sts.amazonaws.com\", \"properties\": { \"authSchemes\": [{ \"name\": e, \"signingName\": f, \"signingRegion\": g }] }, \"headers\": {} }, v = {}, w = { \"conditions\": [{ [H]: d, [I]: [q, \"aws-global\"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: \"PartitionResult\" }, \"supportsFIPS\"] }, A = { [J]: \"PartitionResult\" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, \"supportsDualStack\"] }] }, C = [{ [H]: \"isSet\", [I]: [o] }], D = [x], E = [y];\nconst _data = { version: \"1.0\", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: \"UseGlobalEndpoint\" }, b] }, { [H]: \"not\", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, \"ap-northeast-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"ap-south-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"ap-southeast-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"ap-southeast-2\"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, \"ca-central-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"eu-central-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"eu-north-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"eu-west-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"eu-west-2\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"eu-west-3\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"sa-east-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"us-east-2\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"us-west-1\"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, \"us-west-2\"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: \"{Region}\" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: \"Invalid Configuration: FIPS and custom endpoint are not supported\", [G]: k }, { conditions: E, error: \"Invalid Configuration: Dualstack and custom endpoint are not supported\", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: \"https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: v, headers: v }, [G]: h }], [G]: j }, { error: \"FIPS and DualStack are enabled, but this partition does not support one or both\", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, \"name\"] }, \"aws-us-gov\"] }], endpoint: { url: \"https://sts.{Region}.amazonaws.com\", properties: v, headers: v }, [G]: h }, { endpoint: { url: \"https://sts-fips.{Region}.{PartitionResult#dnsSuffix}\", properties: v, headers: v }, [G]: h }], [G]: j }, { error: \"FIPS is enabled but this partition does not support FIPS\", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: \"https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: v, headers: v }, [G]: h }], [G]: j }, { error: \"DualStack is enabled but this partition does not support DualStack\", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: \"Invalid Configuration: Missing Region\", [G]: k }] };\nexport const ruleSet = _data;\n","import { awsEndpointFunctions } from \"@aws-sdk/util-endpoints\";\nimport { customEndpointFunctions, EndpointCache, resolveEndpoint } from \"@smithy/util-endpoints\";\nimport { ruleSet } from \"./ruleset\";\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\", \"UseGlobalEndpoint\"],\n});\nexport const defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n","import { AwsSdkSigV4Signer } from \"@aws-sdk/core\";\nimport { AwsQueryProtocol } from \"@aws-sdk/core/protocols\";\nimport { NoAuthSigner } from \"@smithy/core\";\nimport { NoOpLogger } from \"@smithy/smithy-client\";\nimport { parseUrl } from \"@smithy/url-parser\";\nimport { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nimport { defaultSTSHttpAuthSchemeProvider } from \"./auth/httpAuthSchemeProvider\";\nimport { defaultEndpointResolver } from \"./endpoint/endpointResolver\";\nexport const getRuntimeConfig = (config) => {\n return {\n apiVersion: \"2011-06-15\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsQueryProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.sts\",\n xmlNamespace: \"https://sts.amazonaws.com/doc/2011-06-15/\",\n version: \"2011-06-15\",\n serviceTarget: \"AWSSecurityTokenServiceV20110615\",\n },\n serviceId: config?.serviceId ?? \"STS\",\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n","import packageInfo from \"../../../package.json\";\nimport { AwsSdkSigV4Signer, emitWarningIfUnsupportedVersion as awsCheckVersion, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, } from \"@aws-sdk/core\";\nimport { createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS } from \"@aws-sdk/util-user-agent-node\";\nimport { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, } from \"@smithy/config-resolver\";\nimport { NoAuthSigner } from \"@smithy/core\";\nimport { Hash } from \"@smithy/hash-node\";\nimport { NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS } from \"@smithy/middleware-retry\";\nimport { loadConfig as loadNodeConfig } from \"@smithy/node-config-provider\";\nimport { NodeHttpHandler as RequestHandler, streamCollector } from \"@smithy/node-http-handler\";\nimport { emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode } from \"@smithy/smithy-client\";\nimport { calculateBodyLength } from \"@smithy/util-body-length-node\";\nimport { resolveDefaultsModeConfig } from \"@smithy/util-defaults-mode-node\";\nimport { DEFAULT_RETRY_MODE } from \"@smithy/util-retry\";\nimport { getRuntimeConfig as getSharedRuntimeConfig } from \"./runtimeConfig.shared\";\nexport const getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getSharedRuntimeConfig(config);\n awsCheckVersion(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadNodeConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ??\n createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\") ||\n (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n maxAttempts: config?.maxAttempts ?? loadNodeConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ??\n loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: RequestHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadNodeConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n sha256: config?.sha256 ?? Hash.bind(null, \"sha256\"),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadNodeConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n","export const getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nexport const resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n","import { getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, } from \"@aws-sdk/region-config-resolver\";\nimport { getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig } from \"@smithy/protocol-http\";\nimport { getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig } from \"@smithy/smithy-client\";\nimport { getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig } from \"./auth/httpAuthExtensionConfiguration\";\nexport const resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n","import { getHostHeaderPlugin, resolveHostHeaderConfig, } from \"@aws-sdk/middleware-host-header\";\nimport { getLoggerPlugin } from \"@aws-sdk/middleware-logger\";\nimport { getRecursionDetectionPlugin } from \"@aws-sdk/middleware-recursion-detection\";\nimport { getUserAgentPlugin, resolveUserAgentConfig, } from \"@aws-sdk/middleware-user-agent\";\nimport { resolveRegionConfig } from \"@smithy/config-resolver\";\nimport { DefaultIdentityProviderConfig, getHttpAuthSchemeEndpointRuleSetPlugin, getHttpSigningPlugin, } from \"@smithy/core\";\nimport { getSchemaSerdePlugin } from \"@smithy/core/schema\";\nimport { getContentLengthPlugin } from \"@smithy/middleware-content-length\";\nimport { resolveEndpointConfig, } from \"@smithy/middleware-endpoint\";\nimport { getRetryPlugin, resolveRetryConfig, } from \"@smithy/middleware-retry\";\nimport { Client as __Client, } from \"@smithy/smithy-client\";\nimport { defaultSTSHttpAuthSchemeParametersProvider, resolveHttpAuthSchemeConfig, } from \"./auth/httpAuthSchemeProvider\";\nimport { resolveClientEndpointParameters, } from \"./endpoint/EndpointParameters\";\nimport { getRuntimeConfig as __getRuntimeConfig } from \"./runtimeConfig\";\nimport { resolveRuntimeExtensions } from \"./runtimeExtensions\";\nexport { __Client };\nexport class STSClient extends __Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = __getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n","import { ServiceException as __ServiceException, } from \"@smithy/smithy-client\";\nexport { __ServiceException };\nexport class STSServiceException extends __ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, STSServiceException.prototype);\n }\n}\n","import { STSServiceException as __BaseException } from \"./STSServiceException\";\nexport class ExpiredTokenException extends __BaseException {\n name = \"ExpiredTokenException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"ExpiredTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ExpiredTokenException.prototype);\n }\n}\nexport class MalformedPolicyDocumentException extends __BaseException {\n name = \"MalformedPolicyDocumentException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"MalformedPolicyDocumentException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype);\n }\n}\nexport class PackedPolicyTooLargeException extends __BaseException {\n name = \"PackedPolicyTooLargeException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"PackedPolicyTooLargeException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype);\n }\n}\nexport class RegionDisabledException extends __BaseException {\n name = \"RegionDisabledException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"RegionDisabledException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, RegionDisabledException.prototype);\n }\n}\nexport class IDPRejectedClaimException extends __BaseException {\n name = \"IDPRejectedClaimException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"IDPRejectedClaimException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, IDPRejectedClaimException.prototype);\n }\n}\nexport class InvalidIdentityTokenException extends __BaseException {\n name = \"InvalidIdentityTokenException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"InvalidIdentityTokenException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype);\n }\n}\nexport class IDPCommunicationErrorException extends __BaseException {\n name = \"IDPCommunicationErrorException\";\n $fault = \"client\";\n constructor(opts) {\n super({\n name: \"IDPCommunicationErrorException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype);\n }\n}\n","const _A = \"Arn\";\nconst _AKI = \"AccessKeyId\";\nconst _AR = \"AssumeRole\";\nconst _ARI = \"AssumedRoleId\";\nconst _ARR = \"AssumeRoleRequest\";\nconst _ARRs = \"AssumeRoleResponse\";\nconst _ARU = \"AssumedRoleUser\";\nconst _ARWWI = \"AssumeRoleWithWebIdentity\";\nconst _ARWWIR = \"AssumeRoleWithWebIdentityRequest\";\nconst _ARWWIRs = \"AssumeRoleWithWebIdentityResponse\";\nconst _Au = \"Audience\";\nconst _C = \"Credentials\";\nconst _CA = \"ContextAssertion\";\nconst _DS = \"DurationSeconds\";\nconst _E = \"Expiration\";\nconst _EI = \"ExternalId\";\nconst _ETE = \"ExpiredTokenException\";\nconst _IDPCEE = \"IDPCommunicationErrorException\";\nconst _IDPRCE = \"IDPRejectedClaimException\";\nconst _IITE = \"InvalidIdentityTokenException\";\nconst _K = \"Key\";\nconst _MPDE = \"MalformedPolicyDocumentException\";\nconst _P = \"Policy\";\nconst _PA = \"PolicyArns\";\nconst _PAr = \"ProviderArn\";\nconst _PC = \"ProvidedContexts\";\nconst _PCLT = \"ProvidedContextsListType\";\nconst _PCr = \"ProvidedContext\";\nconst _PDT = \"PolicyDescriptorType\";\nconst _PI = \"ProviderId\";\nconst _PPS = \"PackedPolicySize\";\nconst _PPTLE = \"PackedPolicyTooLargeException\";\nconst _Pr = \"Provider\";\nconst _RA = \"RoleArn\";\nconst _RDE = \"RegionDisabledException\";\nconst _RSN = \"RoleSessionName\";\nconst _SAK = \"SecretAccessKey\";\nconst _SFWIT = \"SubjectFromWebIdentityToken\";\nconst _SI = \"SourceIdentity\";\nconst _SN = \"SerialNumber\";\nconst _ST = \"SessionToken\";\nconst _T = \"Tags\";\nconst _TC = \"TokenCode\";\nconst _TTK = \"TransitiveTagKeys\";\nconst _Ta = \"Tag\";\nconst _V = \"Value\";\nconst _WIT = \"WebIdentityToken\";\nconst _a = \"arn\";\nconst _aKST = \"accessKeySecretType\";\nconst _aQE = \"awsQueryError\";\nconst _c = \"client\";\nconst _cTT = \"clientTokenType\";\nconst _e = \"error\";\nconst _hE = \"httpError\";\nconst _m = \"message\";\nconst _pDLT = \"policyDescriptorListType\";\nconst _s = \"smithy.ts.sdk.synthetic.com.amazonaws.sts\";\nconst _tLT = \"tagListType\";\nconst n0 = \"com.amazonaws.sts\";\nimport { TypeRegistry } from \"@smithy/core/schema\";\nimport { ExpiredTokenException, IDPCommunicationErrorException, IDPRejectedClaimException, InvalidIdentityTokenException, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, } from \"../models/errors\";\nimport { STSServiceException } from \"../models/STSServiceException\";\nvar accessKeySecretType = [0, n0, _aKST, 8, 0];\nvar clientTokenType = [0, n0, _cTT, 8, 0];\nexport var AssumedRoleUser$ = [3, n0, _ARU, 0, [_ARI, _A], [0, 0], 2];\nexport var AssumeRoleRequest$ = [\n 3,\n n0,\n _ARR,\n 0,\n [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC],\n [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType],\n 2,\n];\nexport var AssumeRoleResponse$ = [\n 3,\n n0,\n _ARRs,\n 0,\n [_C, _ARU, _PPS, _SI],\n [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0],\n];\nexport var AssumeRoleWithWebIdentityRequest$ = [\n 3,\n n0,\n _ARWWIR,\n 0,\n [_RA, _RSN, _WIT, _PI, _PA, _P, _DS],\n [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1],\n 3,\n];\nexport var AssumeRoleWithWebIdentityResponse$ = [\n 3,\n n0,\n _ARWWIRs,\n 0,\n [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI],\n [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0],\n];\nexport var Credentials$ = [\n 3,\n n0,\n _C,\n 0,\n [_AKI, _SAK, _ST, _E],\n [0, [() => accessKeySecretType, 0], 0, 4],\n 4,\n];\nexport var ExpiredTokenException$ = [\n -3,\n n0,\n _ETE,\n { [_aQE]: [`ExpiredTokenException`, 400], [_e]: _c, [_hE]: 400 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(ExpiredTokenException$, ExpiredTokenException);\nexport var IDPCommunicationErrorException$ = [\n -3,\n n0,\n _IDPCEE,\n { [_aQE]: [`IDPCommunicationError`, 400], [_e]: _c, [_hE]: 400 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException);\nexport var IDPRejectedClaimException$ = [\n -3,\n n0,\n _IDPRCE,\n { [_aQE]: [`IDPRejectedClaim`, 403], [_e]: _c, [_hE]: 403 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(IDPRejectedClaimException$, IDPRejectedClaimException);\nexport var InvalidIdentityTokenException$ = [\n -3,\n n0,\n _IITE,\n { [_aQE]: [`InvalidIdentityToken`, 400], [_e]: _c, [_hE]: 400 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException);\nexport var MalformedPolicyDocumentException$ = [\n -3,\n n0,\n _MPDE,\n { [_aQE]: [`MalformedPolicyDocument`, 400], [_e]: _c, [_hE]: 400 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException);\nexport var PackedPolicyTooLargeException$ = [\n -3,\n n0,\n _PPTLE,\n { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e]: _c, [_hE]: 400 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException);\nexport var PolicyDescriptorType$ = [3, n0, _PDT, 0, [_a], [0]];\nexport var ProvidedContext$ = [3, n0, _PCr, 0, [_PAr, _CA], [0, 0]];\nexport var RegionDisabledException$ = [\n -3,\n n0,\n _RDE,\n { [_aQE]: [`RegionDisabledException`, 403], [_e]: _c, [_hE]: 403 },\n [_m],\n [0],\n];\nTypeRegistry.for(n0).registerError(RegionDisabledException$, RegionDisabledException);\nexport var Tag$ = [3, n0, _Ta, 0, [_K, _V], [0, 0], 2];\nexport var STSServiceException$ = [-3, _s, \"STSServiceException\", 0, [], []];\nTypeRegistry.for(_s).registerError(STSServiceException$, STSServiceException);\nvar policyDescriptorListType = [1, n0, _pDLT, 0, () => PolicyDescriptorType$];\nvar ProvidedContextsListType = [1, n0, _PCLT, 0, () => ProvidedContext$];\nvar tagKeyListType = 64 | 0;\nvar tagListType = [1, n0, _tLT, 0, () => Tag$];\nexport var AssumeRole$ = [9, n0, _AR, 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$];\nexport var AssumeRoleWithWebIdentity$ = [\n 9,\n n0,\n _ARWWI,\n 0,\n () => AssumeRoleWithWebIdentityRequest$,\n () => AssumeRoleWithWebIdentityResponse$,\n];\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { AssumeRole$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class AssumeRoleCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"AWSSecurityTokenServiceV20110615\", \"AssumeRole\", {})\n .n(\"STSClient\", \"AssumeRoleCommand\")\n .sc(AssumeRole$)\n .build() {\n}\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { AssumeRoleWithWebIdentity$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class AssumeRoleWithWebIdentityCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"AWSSecurityTokenServiceV20110615\", \"AssumeRoleWithWebIdentity\", {})\n .n(\"STSClient\", \"AssumeRoleWithWebIdentityCommand\")\n .sc(AssumeRoleWithWebIdentity$)\n .build() {\n}\n","import { createAggregatedClient } from \"@smithy/smithy-client\";\nimport { AssumeRoleCommand } from \"./commands/AssumeRoleCommand\";\nimport { AssumeRoleWithWebIdentityCommand, } from \"./commands/AssumeRoleWithWebIdentityCommand\";\nimport { STSClient } from \"./STSClient\";\nconst commands = {\n AssumeRoleCommand,\n AssumeRoleWithWebIdentityCommand,\n};\nexport class STS extends STSClient {\n}\ncreateAggregatedClient(commands, STS);\n","export * from \"./AssumeRoleCommand\";\nexport * from \"./AssumeRoleWithWebIdentityCommand\";\n","export {};\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { stsRegionDefaultResolver } from \"@aws-sdk/region-config-resolver\";\nimport { AssumeRoleCommand } from \"./commands/AssumeRoleCommand\";\nimport { AssumeRoleWithWebIdentityCommand, } from \"./commands/AssumeRoleWithWebIdentityCommand\";\nconst getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {\n if (typeof assumedRoleUser?.Arn === \"string\") {\n const arnComponents = assumedRoleUser.Arn.split(\":\");\n if (arnComponents.length > 4 && arnComponents[4] !== \"\") {\n return arnComponents[4];\n }\n }\n return undefined;\n};\nconst resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => {\n const region = typeof _region === \"function\" ? await _region() : _region;\n const parentRegion = typeof _parentRegion === \"function\" ? await _parentRegion() : _parentRegion;\n let stsDefaultRegion = \"\";\n const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await stsRegionDefaultResolver(loaderConfig)());\n credentialProviderLogger?.debug?.(\"@aws-sdk/client-sts::resolveRegion\", \"accepting first of:\", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`);\n return resolvedRegion;\n};\nexport const getDefaultRoleAssumer = (stsOptions, STSClient) => {\n let stsClient;\n let closureSourceCreds;\n return async (sourceCreds, params) => {\n closureSourceCreds = sourceCreds;\n if (!stsClient) {\n const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions;\n const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {\n logger,\n profile,\n });\n const isCompatibleRequestHandler = !isH2(requestHandler);\n stsClient = new STSClient({\n ...stsOptions,\n userAgentAppId,\n profile,\n credentialDefaultProvider: () => async () => closureSourceCreds,\n region: resolvedRegion,\n requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,\n logger: logger,\n });\n }\n const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);\n }\n const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);\n const credentials = {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_STS_ASSUME_ROLE\", \"i\");\n return credentials;\n };\n};\nexport const getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient) => {\n let stsClient;\n return async (params) => {\n if (!stsClient) {\n const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions;\n const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {\n logger,\n profile,\n });\n const isCompatibleRequestHandler = !isH2(requestHandler);\n stsClient = new STSClient({\n ...stsOptions,\n userAgentAppId,\n profile,\n region: resolvedRegion,\n requestHandler: isCompatibleRequestHandler ? requestHandler : undefined,\n logger: logger,\n });\n }\n const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));\n if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {\n throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);\n }\n const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);\n const credentials = {\n accessKeyId: Credentials.AccessKeyId,\n secretAccessKey: Credentials.SecretAccessKey,\n sessionToken: Credentials.SessionToken,\n expiration: Credentials.Expiration,\n ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }),\n ...(accountId && { accountId }),\n };\n if (accountId) {\n setCredentialFeature(credentials, \"RESOLVED_ACCOUNT_ID\", \"T\");\n }\n setCredentialFeature(credentials, \"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID\", \"k\");\n return credentials;\n };\n};\nexport const decorateDefaultCredentialProvider = (provider) => (input) => provider({\n roleAssumer: getDefaultRoleAssumer(input, input.stsClientCtor),\n roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input, input.stsClientCtor),\n ...input,\n});\nconst isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n};\n","import { getDefaultRoleAssumer as StsGetDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity as StsGetDefaultRoleAssumerWithWebIdentity, } from \"./defaultStsRoleAssumers\";\nimport { STSClient } from \"./STSClient\";\nconst getCustomizableStsClientCtor = (baseCtor, customizations) => {\n if (!customizations)\n return baseCtor;\n else\n return class CustomizableSTSClient extends baseCtor {\n constructor(config) {\n super(config);\n for (const customization of customizations) {\n this.middlewareStack.use(customization);\n }\n }\n };\n};\nexport const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => StsGetDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));\nexport const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => StsGetDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));\nexport const decorateDefaultCredentialProvider = (provider) => (input) => provider({\n roleAssumer: getDefaultRoleAssumer(input),\n roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input),\n ...input,\n});\n","export * from \"./STSClient\";\nexport * from \"./STS\";\nexport * from \"./commands\";\nexport * from \"./schemas/schemas_0\";\nexport * from \"./models/errors\";\nexport * from \"./models/models_0\";\nexport * from \"./defaultRoleAssumers\";\nexport { STSServiceException } from \"./models/STSServiceException\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getProfileName } from \"@smithy/shared-ini-file-loader\";\nimport { resolveCredentialSource } from \"./resolveCredentialSource\";\nexport const isAssumeRoleProfile = (arg, { profile = \"default\", logger } = {}) => {\n return (Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.external_id) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.mfa_serial) > -1 &&\n (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger })));\n};\nconst isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => {\n const withSourceProfile = typeof arg.source_profile === \"string\" && typeof arg.credential_source === \"undefined\";\n if (withSourceProfile) {\n logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);\n }\n return withSourceProfile;\n};\nconst isCredentialSourceProfile = (arg, { profile, logger }) => {\n const withProviderProfile = typeof arg.credential_source === \"string\" && typeof arg.source_profile === \"undefined\";\n if (withProviderProfile) {\n logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);\n }\n return withProviderProfile;\n};\nexport const resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData) => {\n options.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)\");\n const profileData = profiles[profileName];\n const { source_profile, region } = profileData;\n if (!options.roleAssumer) {\n const { getDefaultRoleAssumer } = await import(\"@aws-sdk/nested-clients/sts\");\n options.roleAssumer = getDefaultRoleAssumer({\n ...options.clientConfig,\n credentialProviderLogger: options.logger,\n parentClientConfig: {\n ...callerClientConfig,\n ...options?.parentClientConfig,\n region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region,\n },\n }, options.clientPlugins);\n }\n if (source_profile && source_profile in visitedProfiles) {\n throw new CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` +\n ` ${getProfileName(options)}. Profiles visited: ` +\n Object.keys(visitedProfiles).join(\", \"), { logger: options.logger });\n }\n options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`);\n const sourceCredsProvider = source_profile\n ? resolveProfileData(source_profile, profiles, options, callerClientConfig, {\n ...visitedProfiles,\n [source_profile]: true,\n }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {}))\n : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();\n if (isCredentialSourceWithoutRoleArn(profileData)) {\n return sourceCredsProvider.then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n else {\n const params = {\n RoleArn: profileData.role_arn,\n RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,\n ExternalId: profileData.external_id,\n DurationSeconds: parseInt(profileData.duration_seconds || \"3600\", 10),\n };\n const { mfa_serial } = profileData;\n if (mfa_serial) {\n if (!options.mfaCodeProvider) {\n throw new CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false });\n }\n params.SerialNumber = mfa_serial;\n params.TokenCode = await options.mfaCodeProvider(mfa_serial);\n }\n const sourceCreds = await sourceCredsProvider;\n return options.roleAssumer(sourceCreds, params).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SOURCE_PROFILE\", \"o\"));\n }\n};\nconst isCredentialSourceWithoutRoleArn = (section) => {\n return !section.role_arn && !!section.credential_source;\n};\n","import { resolveAwsSdkSigV4Config, } from \"@aws-sdk/core\";\nimport { getSmithyContext, normalizeProvider } from \"@smithy/util-middleware\";\nexport const defaultSigninHttpAuthSchemeParametersProvider = async (config, context, input) => {\n return {\n operation: getSmithyContext(context).operation,\n region: (await normalizeProvider(config.region)()) ||\n (() => {\n throw new Error(\"expected `region` to be configured for `aws.auth#sigv4`\");\n })(),\n };\n};\nfunction createAwsAuthSigv4HttpAuthOption(authParameters) {\n return {\n schemeId: \"aws.auth#sigv4\",\n signingProperties: {\n name: \"signin\",\n region: authParameters.region,\n },\n propertiesExtractor: (config, context) => ({\n signingProperties: {\n config,\n context,\n },\n }),\n };\n}\nfunction createSmithyApiNoAuthHttpAuthOption(authParameters) {\n return {\n schemeId: \"smithy.api#noAuth\",\n };\n}\nexport const defaultSigninHttpAuthSchemeProvider = (authParameters) => {\n const options = [];\n switch (authParameters.operation) {\n case \"CreateOAuth2Token\": {\n options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));\n break;\n }\n default: {\n options.push(createAwsAuthSigv4HttpAuthOption(authParameters));\n }\n }\n return options;\n};\nexport const resolveHttpAuthSchemeConfig = (config) => {\n const config_0 = resolveAwsSdkSigV4Config(config);\n return Object.assign(config_0, {\n authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),\n });\n};\n","export const resolveClientEndpointParameters = (options) => {\n return Object.assign(options, {\n useDualstackEndpoint: options.useDualstackEndpoint ?? false,\n useFipsEndpoint: options.useFipsEndpoint ?? false,\n defaultSigningName: \"signin\",\n });\n};\nexport const commonParams = {\n UseFIPS: { type: \"builtInParams\", name: \"useFipsEndpoint\" },\n Endpoint: { type: \"builtInParams\", name: \"endpoint\" },\n Region: { type: \"builtInParams\", name: \"region\" },\n UseDualStack: { type: \"builtInParams\", name: \"useDualstackEndpoint\" },\n};\n","const u = \"required\", v = \"fn\", w = \"argv\", x = \"ref\";\nconst a = true, b = \"isSet\", c = \"booleanEquals\", d = \"error\", e = \"endpoint\", f = \"tree\", g = \"PartitionResult\", h = \"stringEquals\", i = { [u]: true, \"default\": false, \"type\": \"boolean\" }, j = { [u]: false, \"type\": \"string\" }, k = { [x]: \"Endpoint\" }, l = { [v]: c, [w]: [{ [x]: \"UseFIPS\" }, true] }, m = { [v]: c, [w]: [{ [x]: \"UseDualStack\" }, true] }, n = {}, o = { [v]: \"getAttr\", [w]: [{ [x]: g }, \"name\"] }, p = { [v]: c, [w]: [{ [x]: \"UseFIPS\" }, false] }, q = { [v]: c, [w]: [{ [x]: \"UseDualStack\" }, false] }, r = { [v]: \"getAttr\", [w]: [{ [x]: g }, \"supportsFIPS\"] }, s = { [v]: c, [w]: [true, { [v]: \"getAttr\", [w]: [{ [x]: g }, \"supportsDualStack\"] }] }, t = [{ [x]: \"Region\" }];\nconst _data = { version: \"1.0\", parameters: { UseDualStack: i, UseFIPS: i, Endpoint: j, Region: j }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: [l], error: \"Invalid Configuration: FIPS and custom endpoint are not supported\", type: d }, { rules: [{ conditions: [m], error: \"Invalid Configuration: Dualstack and custom endpoint are not supported\", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: \"aws.partition\", [w]: t, assign: g }], rules: [{ conditions: [{ [v]: h, [w]: [o, \"aws\"] }, p, q], endpoint: { url: \"https://{Region}.signin.aws.amazon.com\", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, \"aws-cn\"] }, p, q], endpoint: { url: \"https://{Region}.signin.amazonaws.cn\", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, \"aws-us-gov\"] }, p, q], endpoint: { url: \"https://{Region}.signin.amazonaws-us-gov.com\", properties: n, headers: n }, type: e }, { conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, r] }, s], rules: [{ endpoint: { url: \"https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS and DualStack are enabled, but this partition does not support one or both\", type: d }], type: f }, { conditions: [l, q], rules: [{ conditions: [{ [v]: c, [w]: [r, a] }], rules: [{ endpoint: { url: \"https://signin-fips.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"FIPS is enabled but this partition does not support FIPS\", type: d }], type: f }, { conditions: [p, m], rules: [{ conditions: [s], rules: [{ endpoint: { url: \"https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}\", properties: n, headers: n }, type: e }], type: f }, { error: \"DualStack is enabled but this partition does not support DualStack\", type: d }], type: f }, { endpoint: { url: \"https://signin.{Region}.{PartitionResult#dnsSuffix}\", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: \"Invalid Configuration: Missing Region\", type: d }], type: f }] };\nexport const ruleSet = _data;\n","import { awsEndpointFunctions } from \"@aws-sdk/util-endpoints\";\nimport { customEndpointFunctions, EndpointCache, resolveEndpoint } from \"@smithy/util-endpoints\";\nimport { ruleSet } from \"./ruleset\";\nconst cache = new EndpointCache({\n size: 50,\n params: [\"Endpoint\", \"Region\", \"UseDualStack\", \"UseFIPS\"],\n});\nexport const defaultEndpointResolver = (endpointParams, context = {}) => {\n return cache.get(endpointParams, () => resolveEndpoint(ruleSet, {\n endpointParams: endpointParams,\n logger: context.logger,\n }));\n};\ncustomEndpointFunctions.aws = awsEndpointFunctions;\n","import { AwsSdkSigV4Signer } from \"@aws-sdk/core\";\nimport { AwsRestJsonProtocol } from \"@aws-sdk/core/protocols\";\nimport { NoAuthSigner } from \"@smithy/core\";\nimport { NoOpLogger } from \"@smithy/smithy-client\";\nimport { parseUrl } from \"@smithy/url-parser\";\nimport { fromBase64, toBase64 } from \"@smithy/util-base64\";\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\";\nimport { defaultSigninHttpAuthSchemeProvider } from \"./auth/httpAuthSchemeProvider\";\nimport { defaultEndpointResolver } from \"./endpoint/endpointResolver\";\nexport const getRuntimeConfig = (config) => {\n return {\n apiVersion: \"2023-01-01\",\n base64Decoder: config?.base64Decoder ?? fromBase64,\n base64Encoder: config?.base64Encoder ?? toBase64,\n disableHostPrefix: config?.disableHostPrefix ?? false,\n endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,\n extensions: config?.extensions ?? [],\n httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider,\n httpAuthSchemes: config?.httpAuthSchemes ?? [\n {\n schemeId: \"aws.auth#sigv4\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"aws.auth#sigv4\"),\n signer: new AwsSdkSigV4Signer(),\n },\n {\n schemeId: \"smithy.api#noAuth\",\n identityProvider: (ipc) => ipc.getIdentityProvider(\"smithy.api#noAuth\") || (async () => ({})),\n signer: new NoAuthSigner(),\n },\n ],\n logger: config?.logger ?? new NoOpLogger(),\n protocol: config?.protocol ?? AwsRestJsonProtocol,\n protocolSettings: config?.protocolSettings ?? {\n defaultNamespace: \"com.amazonaws.signin\",\n version: \"2023-01-01\",\n serviceTarget: \"Signin\",\n },\n serviceId: config?.serviceId ?? \"Signin\",\n urlParser: config?.urlParser ?? parseUrl,\n utf8Decoder: config?.utf8Decoder ?? fromUtf8,\n utf8Encoder: config?.utf8Encoder ?? toUtf8,\n };\n};\n","import packageInfo from \"../../../package.json\";\nimport { emitWarningIfUnsupportedVersion as awsCheckVersion, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS } from \"@aws-sdk/core\";\nimport { createDefaultUserAgentProvider, NODE_APP_ID_CONFIG_OPTIONS } from \"@aws-sdk/util-user-agent-node\";\nimport { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS, NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, } from \"@smithy/config-resolver\";\nimport { Hash } from \"@smithy/hash-node\";\nimport { NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS } from \"@smithy/middleware-retry\";\nimport { loadConfig as loadNodeConfig } from \"@smithy/node-config-provider\";\nimport { NodeHttpHandler as RequestHandler, streamCollector } from \"@smithy/node-http-handler\";\nimport { emitWarningIfUnsupportedVersion, loadConfigsForDefaultMode } from \"@smithy/smithy-client\";\nimport { calculateBodyLength } from \"@smithy/util-body-length-node\";\nimport { resolveDefaultsModeConfig } from \"@smithy/util-defaults-mode-node\";\nimport { DEFAULT_RETRY_MODE } from \"@smithy/util-retry\";\nimport { getRuntimeConfig as getSharedRuntimeConfig } from \"./runtimeConfig.shared\";\nexport const getRuntimeConfig = (config) => {\n emitWarningIfUnsupportedVersion(process.version);\n const defaultsMode = resolveDefaultsModeConfig(config);\n const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);\n const clientSharedValues = getSharedRuntimeConfig(config);\n awsCheckVersion(process.version);\n const loaderConfig = {\n profile: config?.profile,\n logger: clientSharedValues.logger,\n };\n return {\n ...clientSharedValues,\n ...config,\n runtime: \"node\",\n defaultsMode,\n authSchemePreference: config?.authSchemePreference ?? loadNodeConfig(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),\n bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,\n defaultUserAgentProvider: config?.defaultUserAgentProvider ??\n createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }),\n maxAttempts: config?.maxAttempts ?? loadNodeConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),\n region: config?.region ??\n loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, { ...NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),\n requestHandler: RequestHandler.create(config?.requestHandler ?? defaultConfigProvider),\n retryMode: config?.retryMode ??\n loadNodeConfig({\n ...NODE_RETRY_MODE_CONFIG_OPTIONS,\n default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,\n }, config),\n sha256: config?.sha256 ?? Hash.bind(null, \"sha256\"),\n streamCollector: config?.streamCollector ?? streamCollector,\n useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),\n userAgentAppId: config?.userAgentAppId ?? loadNodeConfig(NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),\n };\n};\n","export const getHttpAuthExtensionConfiguration = (runtimeConfig) => {\n const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;\n let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;\n let _credentials = runtimeConfig.credentials;\n return {\n setHttpAuthScheme(httpAuthScheme) {\n const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);\n if (index === -1) {\n _httpAuthSchemes.push(httpAuthScheme);\n }\n else {\n _httpAuthSchemes.splice(index, 1, httpAuthScheme);\n }\n },\n httpAuthSchemes() {\n return _httpAuthSchemes;\n },\n setHttpAuthSchemeProvider(httpAuthSchemeProvider) {\n _httpAuthSchemeProvider = httpAuthSchemeProvider;\n },\n httpAuthSchemeProvider() {\n return _httpAuthSchemeProvider;\n },\n setCredentials(credentials) {\n _credentials = credentials;\n },\n credentials() {\n return _credentials;\n },\n };\n};\nexport const resolveHttpAuthRuntimeConfig = (config) => {\n return {\n httpAuthSchemes: config.httpAuthSchemes(),\n httpAuthSchemeProvider: config.httpAuthSchemeProvider(),\n credentials: config.credentials(),\n };\n};\n","import { getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration, } from \"@aws-sdk/region-config-resolver\";\nimport { getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig } from \"@smithy/protocol-http\";\nimport { getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig } from \"@smithy/smithy-client\";\nimport { getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig } from \"./auth/httpAuthExtensionConfiguration\";\nexport const resolveRuntimeExtensions = (runtimeConfig, extensions) => {\n const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));\n extensions.forEach((extension) => extension.configure(extensionConfiguration));\n return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));\n};\n","import { getHostHeaderPlugin, resolveHostHeaderConfig, } from \"@aws-sdk/middleware-host-header\";\nimport { getLoggerPlugin } from \"@aws-sdk/middleware-logger\";\nimport { getRecursionDetectionPlugin } from \"@aws-sdk/middleware-recursion-detection\";\nimport { getUserAgentPlugin, resolveUserAgentConfig, } from \"@aws-sdk/middleware-user-agent\";\nimport { resolveRegionConfig } from \"@smithy/config-resolver\";\nimport { DefaultIdentityProviderConfig, getHttpAuthSchemeEndpointRuleSetPlugin, getHttpSigningPlugin, } from \"@smithy/core\";\nimport { getSchemaSerdePlugin } from \"@smithy/core/schema\";\nimport { getContentLengthPlugin } from \"@smithy/middleware-content-length\";\nimport { resolveEndpointConfig, } from \"@smithy/middleware-endpoint\";\nimport { getRetryPlugin, resolveRetryConfig, } from \"@smithy/middleware-retry\";\nimport { Client as __Client, } from \"@smithy/smithy-client\";\nimport { defaultSigninHttpAuthSchemeParametersProvider, resolveHttpAuthSchemeConfig, } from \"./auth/httpAuthSchemeProvider\";\nimport { resolveClientEndpointParameters, } from \"./endpoint/EndpointParameters\";\nimport { getRuntimeConfig as __getRuntimeConfig } from \"./runtimeConfig\";\nimport { resolveRuntimeExtensions } from \"./runtimeExtensions\";\nexport { __Client };\nexport class SigninClient extends __Client {\n config;\n constructor(...[configuration]) {\n const _config_0 = __getRuntimeConfig(configuration || {});\n super(_config_0);\n this.initConfig = _config_0;\n const _config_1 = resolveClientEndpointParameters(_config_0);\n const _config_2 = resolveUserAgentConfig(_config_1);\n const _config_3 = resolveRetryConfig(_config_2);\n const _config_4 = resolveRegionConfig(_config_3);\n const _config_5 = resolveHostHeaderConfig(_config_4);\n const _config_6 = resolveEndpointConfig(_config_5);\n const _config_7 = resolveHttpAuthSchemeConfig(_config_6);\n const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []);\n this.config = _config_8;\n this.middlewareStack.use(getSchemaSerdePlugin(this.config));\n this.middlewareStack.use(getUserAgentPlugin(this.config));\n this.middlewareStack.use(getRetryPlugin(this.config));\n this.middlewareStack.use(getContentLengthPlugin(this.config));\n this.middlewareStack.use(getHostHeaderPlugin(this.config));\n this.middlewareStack.use(getLoggerPlugin(this.config));\n this.middlewareStack.use(getRecursionDetectionPlugin(this.config));\n this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {\n httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider,\n identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({\n \"aws.auth#sigv4\": config.credentials,\n }),\n }));\n this.middlewareStack.use(getHttpSigningPlugin(this.config));\n }\n destroy() {\n super.destroy();\n }\n}\n","import { ServiceException as __ServiceException, } from \"@smithy/smithy-client\";\nexport { __ServiceException };\nexport class SigninServiceException extends __ServiceException {\n constructor(options) {\n super(options);\n Object.setPrototypeOf(this, SigninServiceException.prototype);\n }\n}\n","import { SigninServiceException as __BaseException } from \"./SigninServiceException\";\nexport class AccessDeniedException extends __BaseException {\n name = \"AccessDeniedException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"AccessDeniedException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, AccessDeniedException.prototype);\n this.error = opts.error;\n }\n}\nexport class InternalServerException extends __BaseException {\n name = \"InternalServerException\";\n $fault = \"server\";\n error;\n constructor(opts) {\n super({\n name: \"InternalServerException\",\n $fault: \"server\",\n ...opts,\n });\n Object.setPrototypeOf(this, InternalServerException.prototype);\n this.error = opts.error;\n }\n}\nexport class TooManyRequestsError extends __BaseException {\n name = \"TooManyRequestsError\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"TooManyRequestsError\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n this.error = opts.error;\n }\n}\nexport class ValidationException extends __BaseException {\n name = \"ValidationException\";\n $fault = \"client\";\n error;\n constructor(opts) {\n super({\n name: \"ValidationException\",\n $fault: \"client\",\n ...opts,\n });\n Object.setPrototypeOf(this, ValidationException.prototype);\n this.error = opts.error;\n }\n}\n","const _ADE = \"AccessDeniedException\";\nconst _AT = \"AccessToken\";\nconst _COAT = \"CreateOAuth2Token\";\nconst _COATR = \"CreateOAuth2TokenRequest\";\nconst _COATRB = \"CreateOAuth2TokenRequestBody\";\nconst _COATRBr = \"CreateOAuth2TokenResponseBody\";\nconst _COATRr = \"CreateOAuth2TokenResponse\";\nconst _ISE = \"InternalServerException\";\nconst _RT = \"RefreshToken\";\nconst _TMRE = \"TooManyRequestsError\";\nconst _VE = \"ValidationException\";\nconst _aKI = \"accessKeyId\";\nconst _aT = \"accessToken\";\nconst _c = \"client\";\nconst _cI = \"clientId\";\nconst _cV = \"codeVerifier\";\nconst _co = \"code\";\nconst _e = \"error\";\nconst _eI = \"expiresIn\";\nconst _gT = \"grantType\";\nconst _h = \"http\";\nconst _hE = \"httpError\";\nconst _iT = \"idToken\";\nconst _jN = \"jsonName\";\nconst _m = \"message\";\nconst _rT = \"refreshToken\";\nconst _rU = \"redirectUri\";\nconst _s = \"server\";\nconst _sAK = \"secretAccessKey\";\nconst _sT = \"sessionToken\";\nconst _sm = \"smithy.ts.sdk.synthetic.com.amazonaws.signin\";\nconst _tI = \"tokenInput\";\nconst _tO = \"tokenOutput\";\nconst _tT = \"tokenType\";\nconst n0 = \"com.amazonaws.signin\";\nimport { TypeRegistry } from \"@smithy/core/schema\";\nimport { AccessDeniedException, InternalServerException, TooManyRequestsError, ValidationException, } from \"../models/errors\";\nimport { SigninServiceException } from \"../models/SigninServiceException\";\nvar RefreshToken = [0, n0, _RT, 8, 0];\nexport var AccessDeniedException$ = [-3, n0, _ADE, { [_e]: _c }, [_e, _m], [0, 0], 2];\nTypeRegistry.for(n0).registerError(AccessDeniedException$, AccessDeniedException);\nexport var AccessToken$ = [\n 3,\n n0,\n _AT,\n 8,\n [_aKI, _sAK, _sT],\n [\n [0, { [_jN]: _aKI }],\n [0, { [_jN]: _sAK }],\n [0, { [_jN]: _sT }],\n ],\n 3,\n];\nexport var CreateOAuth2TokenRequest$ = [\n 3,\n n0,\n _COATR,\n 0,\n [_tI],\n [[() => CreateOAuth2TokenRequestBody$, 16]],\n 1,\n];\nexport var CreateOAuth2TokenRequestBody$ = [\n 3,\n n0,\n _COATRB,\n 0,\n [_cI, _gT, _co, _rU, _cV, _rT],\n [\n [0, { [_jN]: _cI }],\n [0, { [_jN]: _gT }],\n 0,\n [0, { [_jN]: _rU }],\n [0, { [_jN]: _cV }],\n [() => RefreshToken, { [_jN]: _rT }],\n ],\n 2,\n];\nexport var CreateOAuth2TokenResponse$ = [\n 3,\n n0,\n _COATRr,\n 0,\n [_tO],\n [[() => CreateOAuth2TokenResponseBody$, 16]],\n 1,\n];\nexport var CreateOAuth2TokenResponseBody$ = [\n 3,\n n0,\n _COATRBr,\n 0,\n [_aT, _tT, _eI, _rT, _iT],\n [\n [() => AccessToken$, { [_jN]: _aT }],\n [0, { [_jN]: _tT }],\n [1, { [_jN]: _eI }],\n [() => RefreshToken, { [_jN]: _rT }],\n [0, { [_jN]: _iT }],\n ],\n 4,\n];\nexport var InternalServerException$ = [-3, n0, _ISE, { [_e]: _s, [_hE]: 500 }, [_e, _m], [0, 0], 2];\nTypeRegistry.for(n0).registerError(InternalServerException$, InternalServerException);\nexport var TooManyRequestsError$ = [-3, n0, _TMRE, { [_e]: _c, [_hE]: 429 }, [_e, _m], [0, 0], 2];\nTypeRegistry.for(n0).registerError(TooManyRequestsError$, TooManyRequestsError);\nexport var ValidationException$ = [-3, n0, _VE, { [_e]: _c, [_hE]: 400 }, [_e, _m], [0, 0], 2];\nTypeRegistry.for(n0).registerError(ValidationException$, ValidationException);\nexport var SigninServiceException$ = [-3, _sm, \"SigninServiceException\", 0, [], []];\nTypeRegistry.for(_sm).registerError(SigninServiceException$, SigninServiceException);\nexport var CreateOAuth2Token$ = [\n 9,\n n0,\n _COAT,\n { [_h]: [\"POST\", \"/v1/token\", 200] },\n () => CreateOAuth2TokenRequest$,\n () => CreateOAuth2TokenResponse$,\n];\n","import { getEndpointPlugin } from \"@smithy/middleware-endpoint\";\nimport { Command as $Command } from \"@smithy/smithy-client\";\nimport { commonParams } from \"../endpoint/EndpointParameters\";\nimport { CreateOAuth2Token$ } from \"../schemas/schemas_0\";\nexport { $Command };\nexport class CreateOAuth2TokenCommand extends $Command\n .classBuilder()\n .ep(commonParams)\n .m(function (Command, cs, config, o) {\n return [getEndpointPlugin(config, Command.getEndpointParameterInstructions())];\n})\n .s(\"Signin\", \"CreateOAuth2Token\", {})\n .n(\"SigninClient\", \"CreateOAuth2TokenCommand\")\n .sc(CreateOAuth2Token$)\n .build() {\n}\n","import { createAggregatedClient } from \"@smithy/smithy-client\";\nimport { CreateOAuth2TokenCommand, } from \"./commands/CreateOAuth2TokenCommand\";\nimport { SigninClient } from \"./SigninClient\";\nconst commands = {\n CreateOAuth2TokenCommand,\n};\nexport class Signin extends SigninClient {\n}\ncreateAggregatedClient(commands, Signin);\n","export * from \"./CreateOAuth2TokenCommand\";\n","export const OAuth2ErrorCode = {\n AUTHCODE_EXPIRED: \"AUTHCODE_EXPIRED\",\n INSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n INVALID_REQUEST: \"INVALID_REQUEST\",\n SERVER_ERROR: \"server_error\",\n TOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n USER_CREDENTIALS_CHANGED: \"USER_CREDENTIALS_CHANGED\",\n};\n","export {};\n","export * from \"./SigninClient\";\nexport * from \"./Signin\";\nexport * from \"./commands\";\nexport * from \"./schemas/schemas_0\";\nexport * from \"./models/enums\";\nexport * from \"./models/errors\";\nexport * from \"./models/models_0\";\nexport { SigninServiceException } from \"./models/SigninServiceException\";\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { HttpRequest } from \"@smithy/protocol-http\";\nimport { readFile } from \"@smithy/shared-ini-file-loader\";\nimport { createHash, createPrivateKey, createPublicKey, sign } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nexport class LoginCredentialsFetcher {\n profileData;\n init;\n callerClientConfig;\n static REFRESH_THRESHOLD = 5 * 60 * 1000;\n constructor(profileData, init, callerClientConfig) {\n this.profileData = profileData;\n this.init = init;\n this.callerClientConfig = callerClientConfig;\n }\n async loadCredentials() {\n const token = await this.loadToken();\n if (!token) {\n throw new CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger });\n }\n const accessToken = token.accessToken;\n const now = Date.now();\n const expiryTime = new Date(accessToken.expiresAt).getTime();\n const timeUntilExpiry = expiryTime - now;\n if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) {\n return this.refresh(token);\n }\n return {\n accessKeyId: accessToken.accessKeyId,\n secretAccessKey: accessToken.secretAccessKey,\n sessionToken: accessToken.sessionToken,\n accountId: accessToken.accountId,\n expiration: new Date(accessToken.expiresAt),\n };\n }\n get logger() {\n return this.init?.logger;\n }\n get loginSession() {\n return this.profileData.login_session;\n }\n async refresh(token) {\n const { SigninClient, CreateOAuth2TokenCommand } = await import(\"@aws-sdk/nested-clients/signin\");\n const { logger, userAgentAppId } = this.callerClientConfig ?? {};\n const isH2 = (requestHandler) => {\n return requestHandler?.metadata?.handlerProtocol === \"h2\";\n };\n const requestHandler = isH2(this.callerClientConfig?.requestHandler)\n ? undefined\n : this.callerClientConfig?.requestHandler;\n const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION;\n const client = new SigninClient({\n credentials: {\n accessKeyId: \"\",\n secretAccessKey: \"\",\n },\n region,\n requestHandler,\n logger,\n userAgentAppId,\n ...this.init?.clientConfig,\n });\n this.createDPoPInterceptor(client.middlewareStack);\n const commandInput = {\n tokenInput: {\n clientId: token.clientId,\n refreshToken: token.refreshToken,\n grantType: \"refresh_token\",\n },\n };\n try {\n const response = await client.send(new CreateOAuth2TokenCommand(commandInput));\n const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {};\n const { refreshToken, expiresIn } = response.tokenOutput ?? {};\n if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) {\n throw new CredentialsProviderError(\"Token refresh response missing required fields\", {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n const expiresInMs = (expiresIn ?? 900) * 1000;\n const expiration = new Date(Date.now() + expiresInMs);\n const updatedToken = {\n ...token,\n accessToken: {\n ...token.accessToken,\n accessKeyId: accessKeyId,\n secretAccessKey: secretAccessKey,\n sessionToken: sessionToken,\n expiresAt: expiration.toISOString(),\n },\n refreshToken: refreshToken,\n };\n await this.saveToken(updatedToken);\n const newAccessToken = updatedToken.accessToken;\n return {\n accessKeyId: newAccessToken.accessKeyId,\n secretAccessKey: newAccessToken.secretAccessKey,\n sessionToken: newAccessToken.sessionToken,\n accountId: newAccessToken.accountId,\n expiration,\n };\n }\n catch (error) {\n if (error.name === \"AccessDeniedException\") {\n const errorType = error.error;\n let message;\n switch (errorType) {\n case \"TOKEN_EXPIRED\":\n message = \"Your session has expired. Please reauthenticate.\";\n break;\n case \"USER_CREDENTIALS_CHANGED\":\n message =\n \"Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.\";\n break;\n case \"INSUFFICIENT_PERMISSIONS\":\n message =\n \"Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.\";\n break;\n default:\n message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \\`aws login\\``;\n }\n throw new CredentialsProviderError(message, { logger: this.logger, tryNextLink: false });\n }\n throw new CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger });\n }\n }\n async loadToken() {\n const tokenFilePath = this.getTokenFilePath();\n try {\n let tokenData;\n try {\n tokenData = await readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache });\n }\n catch {\n tokenData = await fs.readFile(tokenFilePath, \"utf8\");\n }\n const token = JSON.parse(tokenData);\n const missingFields = [\"accessToken\", \"clientId\", \"refreshToken\", \"dpopKey\"].filter((k) => !token[k]);\n if (!token.accessToken?.accountId) {\n missingFields.push(\"accountId\");\n }\n if (missingFields.length > 0) {\n throw new CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(\", \")}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n return token;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, {\n logger: this.logger,\n tryNextLink: false,\n });\n }\n }\n async saveToken(token) {\n const tokenFilePath = this.getTokenFilePath();\n const directory = dirname(tokenFilePath);\n try {\n await fs.mkdir(directory, { recursive: true });\n }\n catch (error) {\n }\n await fs.writeFile(tokenFilePath, JSON.stringify(token, null, 2), \"utf8\");\n }\n getTokenFilePath() {\n const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? join(homedir(), \".aws\", \"login\", \"cache\");\n const loginSessionBytes = Buffer.from(this.loginSession, \"utf8\");\n const loginSessionSha256 = createHash(\"sha256\").update(loginSessionBytes).digest(\"hex\");\n return join(directory, `${loginSessionSha256}.json`);\n }\n derToRawSignature(derSignature) {\n let offset = 2;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const rLength = derSignature[offset++];\n let r = derSignature.subarray(offset, offset + rLength);\n offset += rLength;\n if (derSignature[offset] !== 0x02) {\n throw new Error(\"Invalid DER signature\");\n }\n offset++;\n const sLength = derSignature[offset++];\n let s = derSignature.subarray(offset, offset + sLength);\n r = r[0] === 0x00 ? r.subarray(1) : r;\n s = s[0] === 0x00 ? s.subarray(1) : s;\n const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]);\n const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]);\n return Buffer.concat([rPadded, sPadded]);\n }\n createDPoPInterceptor(middlewareStack) {\n middlewareStack.add((next) => async (args) => {\n if (HttpRequest.isInstance(args.request)) {\n const request = args.request;\n const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : \"\"}${request.path}`;\n const dpop = await this.generateDpop(request.method, actualEndpoint);\n request.headers = {\n ...request.headers,\n DPoP: dpop,\n };\n }\n return next(args);\n }, {\n step: \"finalizeRequest\",\n name: \"dpopInterceptor\",\n override: true,\n });\n }\n async generateDpop(method = \"POST\", endpoint) {\n const token = await this.loadToken();\n try {\n const privateKey = createPrivateKey({\n key: token.dpopKey,\n format: \"pem\",\n type: \"sec1\",\n });\n const publicKey = createPublicKey(privateKey);\n const publicDer = publicKey.export({ format: \"der\", type: \"spki\" });\n let pointStart = -1;\n for (let i = 0; i < publicDer.length; i++) {\n if (publicDer[i] === 0x04) {\n pointStart = i;\n break;\n }\n }\n const x = publicDer.slice(pointStart + 1, pointStart + 33);\n const y = publicDer.slice(pointStart + 33, pointStart + 65);\n const header = {\n alg: \"ES256\",\n typ: \"dpop+jwt\",\n jwk: {\n kty: \"EC\",\n crv: \"P-256\",\n x: x.toString(\"base64url\"),\n y: y.toString(\"base64url\"),\n },\n };\n const payload = {\n jti: crypto.randomUUID(),\n htm: method,\n htu: endpoint,\n iat: Math.floor(Date.now() / 1000),\n };\n const headerB64 = Buffer.from(JSON.stringify(header)).toString(\"base64url\");\n const payloadB64 = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n const message = `${headerB64}.${payloadB64}`;\n const asn1Signature = sign(\"sha256\", Buffer.from(message), privateKey);\n const rawSignature = this.derToRawSignature(asn1Signature);\n const signatureB64 = rawSignature.toString(\"base64url\");\n return `${message}.${signatureB64}`;\n }\n catch (error) {\n throw new CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false });\n }\n }\n}\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { getProfileName, parseKnownFiles } from \"@smithy/shared-ini-file-loader\";\nimport { LoginCredentialsFetcher } from \"./LoginCredentialsFetcher\";\nexport const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => {\n init?.logger?.debug?.(\"@aws-sdk/credential-providers - fromLoginCredentials\");\n const profiles = await parseKnownFiles(init || {});\n const profileName = getProfileName({\n profile: init?.profile ?? callerClientConfig?.profile,\n });\n const profile = profiles[profileName];\n if (!profile?.login_session) {\n throw new CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, {\n tryNextLink: true,\n logger: init?.logger,\n });\n }\n const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig);\n const credentials = await fetcher.loadCredentials();\n return setCredentialFeature(credentials, \"CREDENTIALS_LOGIN\", \"AD\");\n};\n","export {};\n","export * from \"./fromLoginCredentials\";\nexport * from \"./types\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { fromLoginCredentials } from \"@aws-sdk/credential-provider-login\";\nexport const isLoginProfile = (data) => {\n return Boolean(data && data.login_session);\n};\nexport const resolveLoginCredentials = async (profileName, options, callerClientConfig) => {\n const credentials = await fromLoginCredentials({\n ...options,\n profile: profileName,\n })({ callerClientConfig });\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE_LOGIN\", \"AC\");\n};\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const getValidatedProcessCredentials = (profileName, data, profiles) => {\n if (data.Version !== 1) {\n throw Error(`Profile ${profileName} credential_process did not return Version 1.`);\n }\n if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) {\n throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);\n }\n if (data.Expiration) {\n const currentTime = new Date();\n const expireTime = new Date(data.Expiration);\n if (expireTime < currentTime) {\n throw Error(`Profile ${profileName} credential_process returned expired credentials.`);\n }\n }\n let accountId = data.AccountId;\n if (!accountId && profiles?.[profileName]?.aws_account_id) {\n accountId = profiles[profileName].aws_account_id;\n }\n const credentials = {\n accessKeyId: data.AccessKeyId,\n secretAccessKey: data.SecretAccessKey,\n ...(data.SessionToken && { sessionToken: data.SessionToken }),\n ...(data.Expiration && { expiration: new Date(data.Expiration) }),\n ...(data.CredentialScope && { credentialScope: data.CredentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_PROCESS\", \"w\");\n return credentials;\n};\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { externalDataInterceptor } from \"@smithy/shared-ini-file-loader\";\nimport { exec } from \"child_process\";\nimport { promisify } from \"util\";\nimport { getValidatedProcessCredentials } from \"./getValidatedProcessCredentials\";\nexport const resolveProcessCredentials = async (profileName, profiles, logger) => {\n const profile = profiles[profileName];\n if (profiles[profileName]) {\n const credentialProcess = profile[\"credential_process\"];\n if (credentialProcess !== undefined) {\n const execPromise = promisify(externalDataInterceptor?.getTokenRecord?.().exec ?? exec);\n try {\n const { stdout } = await execPromise(credentialProcess);\n let data;\n try {\n data = JSON.parse(stdout.trim());\n }\n catch {\n throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);\n }\n return getValidatedProcessCredentials(profileName, data, profiles);\n }\n catch (error) {\n throw new CredentialsProviderError(error.message, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger });\n }\n }\n else {\n throw new CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {\n logger,\n });\n }\n};\n","import { getProfileName, parseKnownFiles } from \"@smithy/shared-ini-file-loader\";\nimport { resolveProcessCredentials } from \"./resolveProcessCredentials\";\nexport const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-process - fromProcess\");\n const profiles = await parseKnownFiles(init);\n return resolveProcessCredentials(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init.logger);\n};\n","export * from \"./fromProcess\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isProcessProfile = (arg) => Boolean(arg) && typeof arg === \"object\" && typeof arg.credential_process === \"string\";\nexport const resolveProcessCredentials = async (options, profile) => import(\"@aws-sdk/credential-provider-process\").then(({ fromProcess }) => fromProcess({\n ...options,\n profile,\n})().then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_PROCESS\", \"v\")));\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => {\n const { fromSSO } = await import(\"@aws-sdk/credential-provider-sso\");\n return fromSSO({\n profile,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n clientConfig: options.clientConfig,\n })({\n callerClientConfig,\n }).then((creds) => {\n if (profileData.sso_session) {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO\", \"r\");\n }\n else {\n return setCredentialFeature(creds, \"CREDENTIALS_PROFILE_SSO_LEGACY\", \"t\");\n }\n });\n};\nexport const isSsoProfile = (arg) => arg &&\n (typeof arg.sso_start_url === \"string\" ||\n typeof arg.sso_account_id === \"string\" ||\n typeof arg.sso_session === \"string\" ||\n typeof arg.sso_region === \"string\" ||\n typeof arg.sso_role_name === \"string\");\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isStaticCredsProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.aws_access_key_id === \"string\" &&\n typeof arg.aws_secret_access_key === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_session_token) > -1 &&\n [\"undefined\", \"string\"].indexOf(typeof arg.aws_account_id) > -1;\nexport const resolveStaticCredentials = async (profile, options) => {\n options?.logger?.debug(\"@aws-sdk/credential-provider-ini - resolveStaticCredentials\");\n const credentials = {\n accessKeyId: profile.aws_access_key_id,\n secretAccessKey: profile.aws_secret_access_key,\n sessionToken: profile.aws_session_token,\n ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }),\n ...(profile.aws_account_id && { accountId: profile.aws_account_id }),\n };\n return setCredentialFeature(credentials, \"CREDENTIALS_PROFILE\", \"n\");\n};\n","export const fromWebToken = (init) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromWebToken\");\n const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init;\n let { roleAssumerWithWebIdentity } = init;\n if (!roleAssumerWithWebIdentity) {\n const { getDefaultRoleAssumerWithWebIdentity } = await import(\"@aws-sdk/nested-clients/sts\");\n roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({\n ...init.clientConfig,\n credentialProviderLogger: init.logger,\n parentClientConfig: {\n ...awsIdentityProperties?.callerClientConfig,\n ...init.parentClientConfig,\n },\n }, init.clientPlugins);\n }\n return roleAssumerWithWebIdentity({\n RoleArn: roleArn,\n RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,\n WebIdentityToken: webIdentityToken,\n ProviderId: providerId,\n PolicyArns: policyArns,\n Policy: policy,\n DurationSeconds: durationSeconds,\n });\n};\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { externalDataInterceptor } from \"@smithy/shared-ini-file-loader\";\nimport { readFileSync } from \"fs\";\nimport { fromWebToken } from \"./fromWebToken\";\nconst ENV_TOKEN_FILE = \"AWS_WEB_IDENTITY_TOKEN_FILE\";\nconst ENV_ROLE_ARN = \"AWS_ROLE_ARN\";\nconst ENV_ROLE_SESSION_NAME = \"AWS_ROLE_SESSION_NAME\";\nexport const fromTokenFile = (init = {}) => async (awsIdentityProperties) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-web-identity - fromTokenFile\");\n const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];\n const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];\n const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME];\n if (!webIdentityTokenFile || !roleArn) {\n throw new CredentialsProviderError(\"Web identity configuration not specified\", {\n logger: init.logger,\n });\n }\n const credentials = await fromWebToken({\n ...init,\n webIdentityToken: externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ??\n readFileSync(webIdentityTokenFile, { encoding: \"ascii\" }),\n roleArn,\n roleSessionName,\n })(awsIdentityProperties);\n if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN\", \"h\");\n }\n return credentials;\n};\n","export * from \"./fromTokenFile\";\nexport * from \"./fromWebToken\";\n","import { setCredentialFeature } from \"@aws-sdk/core/client\";\nexport const isWebIdentityProfile = (arg) => Boolean(arg) &&\n typeof arg === \"object\" &&\n typeof arg.web_identity_token_file === \"string\" &&\n typeof arg.role_arn === \"string\" &&\n [\"undefined\", \"string\"].indexOf(typeof arg.role_session_name) > -1;\nexport const resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => import(\"@aws-sdk/credential-provider-web-identity\").then(({ fromTokenFile }) => fromTokenFile({\n webIdentityTokenFile: profile.web_identity_token_file,\n roleArn: profile.role_arn,\n roleSessionName: profile.role_session_name,\n roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,\n logger: options.logger,\n parentClientConfig: options.parentClientConfig,\n})({\n callerClientConfig,\n}).then((creds) => setCredentialFeature(creds, \"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN\", \"q\")));\n","import { CredentialsProviderError } from \"@smithy/property-provider\";\nimport { isAssumeRoleProfile, resolveAssumeRoleCredentials } from \"./resolveAssumeRoleCredentials\";\nimport { isLoginProfile, resolveLoginCredentials } from \"./resolveLoginCredentials\";\nimport { isProcessProfile, resolveProcessCredentials } from \"./resolveProcessCredentials\";\nimport { isSsoProfile, resolveSsoCredentials } from \"./resolveSsoCredentials\";\nimport { isStaticCredsProfile, resolveStaticCredentials } from \"./resolveStaticCredentials\";\nimport { isWebIdentityProfile, resolveWebIdentityCredentials } from \"./resolveWebIdentityCredentials\";\nexport const resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {\n const data = profiles[profileName];\n if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {\n return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData);\n }\n if (isStaticCredsProfile(data)) {\n return resolveStaticCredentials(data, options);\n }\n if (isWebIdentityProfile(data)) {\n return resolveWebIdentityCredentials(data, options, callerClientConfig);\n }\n if (isProcessProfile(data)) {\n return resolveProcessCredentials(options, profileName);\n }\n if (isSsoProfile(data)) {\n return await resolveSsoCredentials(profileName, data, options, callerClientConfig);\n }\n if (isLoginProfile(data)) {\n return resolveLoginCredentials(profileName, options, callerClientConfig);\n }\n throw new CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger });\n};\n","import { getProfileName, parseKnownFiles } from \"@smithy/shared-ini-file-loader\";\nimport { resolveProfileData } from \"./resolveProfileData\";\nexport const fromIni = (init = {}) => async ({ callerClientConfig } = {}) => {\n init.logger?.debug(\"@aws-sdk/credential-provider-ini - fromIni\");\n const profiles = await parseKnownFiles(init);\n return resolveProfileData(getProfileName({\n profile: init.profile ?? callerClientConfig?.profile,\n }), profiles, init, callerClientConfig);\n};\n","export * from \"./fromIni\";\n","var isES5 = (function(){\n \"use strict\";\n return this === undefined;\n})();\n\nif (isES5) {\n module.exports = {\n freeze: Object.freeze,\n defineProperty: Object.defineProperty,\n getDescriptor: Object.getOwnPropertyDescriptor,\n keys: Object.keys,\n names: Object.getOwnPropertyNames,\n getPrototypeOf: Object.getPrototypeOf,\n isArray: Array.isArray,\n isES5: isES5,\n propertyIsWritable: function(obj, prop) {\n var descriptor = Object.getOwnPropertyDescriptor(obj, prop);\n return !!(!descriptor || descriptor.writable || descriptor.set);\n }\n };\n} else {\n var has = {}.hasOwnProperty;\n var str = {}.toString;\n var proto = {}.constructor.prototype;\n\n var ObjectKeys = function (o) {\n var ret = [];\n for (var key in o) {\n if (has.call(o, key)) {\n ret.push(key);\n }\n }\n return ret;\n };\n\n var ObjectGetDescriptor = function(o, key) {\n return {value: o[key]};\n };\n\n var ObjectDefineProperty = function (o, key, desc) {\n o[key] = desc.value;\n return o;\n };\n\n var ObjectFreeze = function (obj) {\n return obj;\n };\n\n var ObjectGetPrototypeOf = function (obj) {\n try {\n return Object(obj).constructor.prototype;\n }\n catch (e) {\n return proto;\n }\n };\n\n var ArrayIsArray = function (obj) {\n try {\n return str.call(obj) === \"[object Array]\";\n }\n catch(e) {\n return false;\n }\n };\n\n module.exports = {\n isArray: ArrayIsArray,\n keys: ObjectKeys,\n names: ObjectKeys,\n defineProperty: ObjectDefineProperty,\n getDescriptor: ObjectGetDescriptor,\n freeze: ObjectFreeze,\n getPrototypeOf: ObjectGetPrototypeOf,\n isES5: isES5,\n propertyIsWritable: function() {\n return true;\n }\n };\n}\n","\"use strict\";\nvar es5 = require(\"./es5\");\nvar canEvaluate = typeof navigator == \"undefined\";\n\nvar errorObj = {e: {}};\nvar tryCatchTarget;\nvar globalObject = typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window :\n typeof global !== \"undefined\" ? global :\n this !== undefined ? this : null;\n\nfunction tryCatcher() {\n try {\n var target = tryCatchTarget;\n tryCatchTarget = null;\n return target.apply(this, arguments);\n } catch (e) {\n errorObj.e = e;\n return errorObj;\n }\n}\nfunction tryCatch(fn) {\n tryCatchTarget = fn;\n return tryCatcher;\n}\n\nvar inherits = function(Child, Parent) {\n var hasProp = {}.hasOwnProperty;\n\n function T() {\n this.constructor = Child;\n this.constructor$ = Parent;\n for (var propertyName in Parent.prototype) {\n if (hasProp.call(Parent.prototype, propertyName) &&\n propertyName.charAt(propertyName.length-1) !== \"$\"\n ) {\n this[propertyName + \"$\"] = Parent.prototype[propertyName];\n }\n }\n }\n T.prototype = Parent.prototype;\n Child.prototype = new T();\n return Child.prototype;\n};\n\n\nfunction isPrimitive(val) {\n return val == null || val === true || val === false ||\n typeof val === \"string\" || typeof val === \"number\";\n\n}\n\nfunction isObject(value) {\n return typeof value === \"function\" ||\n typeof value === \"object\" && value !== null;\n}\n\nfunction maybeWrapAsError(maybeError) {\n if (!isPrimitive(maybeError)) return maybeError;\n\n return new Error(safeToString(maybeError));\n}\n\nfunction withAppended(target, appendee) {\n var len = target.length;\n var ret = new Array(len + 1);\n var i;\n for (i = 0; i < len; ++i) {\n ret[i] = target[i];\n }\n ret[i] = appendee;\n return ret;\n}\n\nfunction getDataPropertyOrDefault(obj, key, defaultValue) {\n if (es5.isES5) {\n var desc = Object.getOwnPropertyDescriptor(obj, key);\n\n if (desc != null) {\n return desc.get == null && desc.set == null\n ? desc.value\n : defaultValue;\n }\n } else {\n return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;\n }\n}\n\nfunction notEnumerableProp(obj, name, value) {\n if (isPrimitive(obj)) return obj;\n var descriptor = {\n value: value,\n configurable: true,\n enumerable: false,\n writable: true\n };\n es5.defineProperty(obj, name, descriptor);\n return obj;\n}\n\nfunction thrower(r) {\n throw r;\n}\n\nvar inheritedDataKeys = (function() {\n var excludedPrototypes = [\n Array.prototype,\n Object.prototype,\n Function.prototype\n ];\n\n var isExcludedProto = function(val) {\n for (var i = 0; i < excludedPrototypes.length; ++i) {\n if (excludedPrototypes[i] === val) {\n return true;\n }\n }\n return false;\n };\n\n if (es5.isES5) {\n var getKeys = Object.getOwnPropertyNames;\n return function(obj) {\n var ret = [];\n var visitedKeys = Object.create(null);\n while (obj != null && !isExcludedProto(obj)) {\n var keys;\n try {\n keys = getKeys(obj);\n } catch (e) {\n return ret;\n }\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n if (visitedKeys[key]) continue;\n visitedKeys[key] = true;\n var desc = Object.getOwnPropertyDescriptor(obj, key);\n if (desc != null && desc.get == null && desc.set == null) {\n ret.push(key);\n }\n }\n obj = es5.getPrototypeOf(obj);\n }\n return ret;\n };\n } else {\n var hasProp = {}.hasOwnProperty;\n return function(obj) {\n if (isExcludedProto(obj)) return [];\n var ret = [];\n\n /*jshint forin:false */\n enumeration: for (var key in obj) {\n if (hasProp.call(obj, key)) {\n ret.push(key);\n } else {\n for (var i = 0; i < excludedPrototypes.length; ++i) {\n if (hasProp.call(excludedPrototypes[i], key)) {\n continue enumeration;\n }\n }\n ret.push(key);\n }\n }\n return ret;\n };\n }\n\n})();\n\nvar thisAssignmentPattern = /this\\s*\\.\\s*\\S+\\s*=/;\nfunction isClass(fn) {\n try {\n if (typeof fn === \"function\") {\n var keys = es5.names(fn.prototype);\n\n var hasMethods = es5.isES5 && keys.length > 1;\n var hasMethodsOtherThanConstructor = keys.length > 0 &&\n !(keys.length === 1 && keys[0] === \"constructor\");\n var hasThisAssignmentAndStaticMethods =\n thisAssignmentPattern.test(fn + \"\") && es5.names(fn).length > 0;\n\n if (hasMethods || hasMethodsOtherThanConstructor ||\n hasThisAssignmentAndStaticMethods) {\n return true;\n }\n }\n return false;\n } catch (e) {\n return false;\n }\n}\n\nfunction toFastProperties(obj) {\n /*jshint -W027,-W055,-W031*/\n function FakeConstructor() {}\n FakeConstructor.prototype = obj;\n var receiver = new FakeConstructor();\n function ic() {\n return typeof receiver.foo;\n }\n ic();\n ic();\n return obj;\n eval(obj);\n}\n\nvar rident = /^[a-z$_][a-z$_0-9]*$/i;\nfunction isIdentifier(str) {\n return rident.test(str);\n}\n\nfunction filledRange(count, prefix, suffix) {\n var ret = new Array(count);\n for(var i = 0; i < count; ++i) {\n ret[i] = prefix + i + suffix;\n }\n return ret;\n}\n\nfunction safeToString(obj) {\n try {\n return obj + \"\";\n } catch (e) {\n return \"[no string representation]\";\n }\n}\n\nfunction isError(obj) {\n return obj instanceof Error ||\n (obj !== null &&\n typeof obj === \"object\" &&\n typeof obj.message === \"string\" &&\n typeof obj.name === \"string\");\n}\n\nfunction markAsOriginatingFromRejection(e) {\n try {\n notEnumerableProp(e, \"isOperational\", true);\n }\n catch(ignore) {}\n}\n\nfunction originatesFromRejection(e) {\n if (e == null) return false;\n return ((e instanceof Error[\"__BluebirdErrorTypes__\"].OperationalError) ||\n e[\"isOperational\"] === true);\n}\n\nfunction canAttachTrace(obj) {\n return isError(obj) && es5.propertyIsWritable(obj, \"stack\");\n}\n\nvar ensureErrorObject = (function() {\n if (!(\"stack\" in new Error())) {\n return function(value) {\n if (canAttachTrace(value)) return value;\n try {throw new Error(safeToString(value));}\n catch(err) {return err;}\n };\n } else {\n return function(value) {\n if (canAttachTrace(value)) return value;\n return new Error(safeToString(value));\n };\n }\n})();\n\nfunction classString(obj) {\n return {}.toString.call(obj);\n}\n\nfunction copyDescriptors(from, to, filter) {\n var keys = es5.names(from);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n if (filter(key)) {\n try {\n es5.defineProperty(to, key, es5.getDescriptor(from, key));\n } catch (ignore) {}\n }\n }\n}\n\nvar asArray = function(v) {\n if (es5.isArray(v)) {\n return v;\n }\n return null;\n};\n\nif (typeof Symbol !== \"undefined\" && Symbol.iterator) {\n var ArrayFrom = typeof Array.from === \"function\" ? function(v) {\n return Array.from(v);\n } : function(v) {\n var ret = [];\n var it = v[Symbol.iterator]();\n var itResult;\n while (!((itResult = it.next()).done)) {\n ret.push(itResult.value);\n }\n return ret;\n };\n\n asArray = function(v) {\n if (es5.isArray(v)) {\n return v;\n } else if (v != null && typeof v[Symbol.iterator] === \"function\") {\n return ArrayFrom(v);\n }\n return null;\n };\n}\n\nvar isNode = typeof process !== \"undefined\" &&\n classString(process).toLowerCase() === \"[object process]\";\n\nvar hasEnvVariables = typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\";\n\nfunction env(key) {\n return hasEnvVariables ? process.env[key] : undefined;\n}\n\nfunction getNativePromise() {\n if (typeof Promise === \"function\") {\n try {\n var promise = new Promise(function(){});\n if (classString(promise) === \"[object Promise]\") {\n return Promise;\n }\n } catch (e) {}\n }\n}\n\nvar reflectHandler;\nfunction contextBind(ctx, cb) {\n if (ctx === null ||\n typeof cb !== \"function\" ||\n cb === reflectHandler) {\n return cb;\n }\n\n if (ctx.domain !== null) {\n cb = ctx.domain.bind(cb);\n }\n\n var async = ctx.async;\n if (async !== null) {\n var old = cb;\n cb = function() {\n var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];};\n args[0] = old;\n args[1] = this;\n return async.runInAsyncScope.apply(async, args);\n };\n }\n return cb;\n}\n\nvar ret = {\n setReflectHandler: function(fn) {\n reflectHandler = fn;\n },\n isClass: isClass,\n isIdentifier: isIdentifier,\n inheritedDataKeys: inheritedDataKeys,\n getDataPropertyOrDefault: getDataPropertyOrDefault,\n thrower: thrower,\n isArray: es5.isArray,\n asArray: asArray,\n notEnumerableProp: notEnumerableProp,\n isPrimitive: isPrimitive,\n isObject: isObject,\n isError: isError,\n canEvaluate: canEvaluate,\n errorObj: errorObj,\n tryCatch: tryCatch,\n inherits: inherits,\n withAppended: withAppended,\n maybeWrapAsError: maybeWrapAsError,\n toFastProperties: toFastProperties,\n filledRange: filledRange,\n toString: safeToString,\n canAttachTrace: canAttachTrace,\n ensureErrorObject: ensureErrorObject,\n originatesFromRejection: originatesFromRejection,\n markAsOriginatingFromRejection: markAsOriginatingFromRejection,\n classString: classString,\n copyDescriptors: copyDescriptors,\n isNode: isNode,\n hasEnvVariables: hasEnvVariables,\n env: env,\n global: globalObject,\n getNativePromise: getNativePromise,\n contextBind: contextBind\n};\nret.isRecentNode = ret.isNode && (function() {\n var version;\n if (process.versions && process.versions.node) {\n version = process.versions.node.split(\".\").map(Number);\n } else if (process.version) {\n version = process.version.split(\".\").map(Number);\n }\n return (version[0] === 0 && version[1] > 10) || (version[0] > 0);\n})();\nret.nodeSupportsAsyncResource = ret.isNode && (function() {\n var supportsAsync = false;\n try {\n var res = require(\"async_hooks\").AsyncResource;\n supportsAsync = typeof res.prototype.runInAsyncScope === \"function\";\n } catch (e) {\n supportsAsync = false;\n }\n return supportsAsync;\n})();\n\nif (ret.isNode) ret.toFastProperties(process);\n\ntry {throw new Error(); } catch (e) {ret.lastLineError = e;}\nmodule.exports = ret;\n","\"use strict\";\nvar util = require(\"./util\");\nvar schedule;\nvar noAsyncScheduler = function() {\n throw new Error(\"No async scheduler available\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n};\nvar NativePromise = util.getNativePromise();\nif (util.isNode && typeof MutationObserver === \"undefined\") {\n var GlobalSetImmediate = global.setImmediate;\n var ProcessNextTick = process.nextTick;\n schedule = util.isRecentNode\n ? function(fn) { GlobalSetImmediate.call(global, fn); }\n : function(fn) { ProcessNextTick.call(process, fn); };\n} else if (typeof NativePromise === \"function\" &&\n typeof NativePromise.resolve === \"function\") {\n var nativePromise = NativePromise.resolve();\n schedule = function(fn) {\n nativePromise.then(fn);\n };\n} else if ((typeof MutationObserver !== \"undefined\") &&\n !(typeof window !== \"undefined\" &&\n window.navigator &&\n (window.navigator.standalone || window.cordova)) &&\n (\"classList\" in document.documentElement)) {\n schedule = (function() {\n var div = document.createElement(\"div\");\n var opts = {attributes: true};\n var toggleScheduled = false;\n var div2 = document.createElement(\"div\");\n var o2 = new MutationObserver(function() {\n div.classList.toggle(\"foo\");\n toggleScheduled = false;\n });\n o2.observe(div2, opts);\n\n var scheduleToggle = function() {\n if (toggleScheduled) return;\n toggleScheduled = true;\n div2.classList.toggle(\"foo\");\n };\n\n return function schedule(fn) {\n var o = new MutationObserver(function() {\n o.disconnect();\n fn();\n });\n o.observe(div, opts);\n scheduleToggle();\n };\n })();\n} else if (typeof setImmediate !== \"undefined\") {\n schedule = function (fn) {\n setImmediate(fn);\n };\n} else if (typeof setTimeout !== \"undefined\") {\n schedule = function (fn) {\n setTimeout(fn, 0);\n };\n} else {\n schedule = noAsyncScheduler;\n}\nmodule.exports = schedule;\n","\"use strict\";\nfunction arrayMove(src, srcIndex, dst, dstIndex, len) {\n for (var j = 0; j < len; ++j) {\n dst[j + dstIndex] = src[j + srcIndex];\n src[j + srcIndex] = void 0;\n }\n}\n\nfunction Queue(capacity) {\n this._capacity = capacity;\n this._length = 0;\n this._front = 0;\n}\n\nQueue.prototype._willBeOverCapacity = function (size) {\n return this._capacity < size;\n};\n\nQueue.prototype._pushOne = function (arg) {\n var length = this.length();\n this._checkCapacity(length + 1);\n var i = (this._front + length) & (this._capacity - 1);\n this[i] = arg;\n this._length = length + 1;\n};\n\nQueue.prototype.push = function (fn, receiver, arg) {\n var length = this.length() + 3;\n if (this._willBeOverCapacity(length)) {\n this._pushOne(fn);\n this._pushOne(receiver);\n this._pushOne(arg);\n return;\n }\n var j = this._front + length - 3;\n this._checkCapacity(length);\n var wrapMask = this._capacity - 1;\n this[(j + 0) & wrapMask] = fn;\n this[(j + 1) & wrapMask] = receiver;\n this[(j + 2) & wrapMask] = arg;\n this._length = length;\n};\n\nQueue.prototype.shift = function () {\n var front = this._front,\n ret = this[front];\n\n this[front] = undefined;\n this._front = (front + 1) & (this._capacity - 1);\n this._length--;\n return ret;\n};\n\nQueue.prototype.length = function () {\n return this._length;\n};\n\nQueue.prototype._checkCapacity = function (size) {\n if (this._capacity < size) {\n this._resizeTo(this._capacity << 1);\n }\n};\n\nQueue.prototype._resizeTo = function (capacity) {\n var oldCapacity = this._capacity;\n this._capacity = capacity;\n var front = this._front;\n var length = this._length;\n var moveItemsCount = (front + length) & (oldCapacity - 1);\n arrayMove(this, 0, this, oldCapacity, moveItemsCount);\n};\n\nmodule.exports = Queue;\n","\"use strict\";\nvar firstLineError;\ntry {throw new Error(); } catch (e) {firstLineError = e;}\nvar schedule = require(\"./schedule\");\nvar Queue = require(\"./queue\");\n\nfunction Async() {\n this._customScheduler = false;\n this._isTickUsed = false;\n this._lateQueue = new Queue(16);\n this._normalQueue = new Queue(16);\n this._haveDrainedQueues = false;\n var self = this;\n this.drainQueues = function () {\n self._drainQueues();\n };\n this._schedule = schedule;\n}\n\nAsync.prototype.setScheduler = function(fn) {\n var prev = this._schedule;\n this._schedule = fn;\n this._customScheduler = true;\n return prev;\n};\n\nAsync.prototype.hasCustomScheduler = function() {\n return this._customScheduler;\n};\n\nAsync.prototype.haveItemsQueued = function () {\n return this._isTickUsed || this._haveDrainedQueues;\n};\n\n\nAsync.prototype.fatalError = function(e, isNode) {\n if (isNode) {\n process.stderr.write(\"Fatal \" + (e instanceof Error ? e.stack : e) +\n \"\\n\");\n process.exit(2);\n } else {\n this.throwLater(e);\n }\n};\n\nAsync.prototype.throwLater = function(fn, arg) {\n if (arguments.length === 1) {\n arg = fn;\n fn = function () { throw arg; };\n }\n if (typeof setTimeout !== \"undefined\") {\n setTimeout(function() {\n fn(arg);\n }, 0);\n } else try {\n this._schedule(function() {\n fn(arg);\n });\n } catch (e) {\n throw new Error(\"No async scheduler available\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n};\n\nfunction AsyncInvokeLater(fn, receiver, arg) {\n this._lateQueue.push(fn, receiver, arg);\n this._queueTick();\n}\n\nfunction AsyncInvoke(fn, receiver, arg) {\n this._normalQueue.push(fn, receiver, arg);\n this._queueTick();\n}\n\nfunction AsyncSettlePromises(promise) {\n this._normalQueue._pushOne(promise);\n this._queueTick();\n}\n\nAsync.prototype.invokeLater = AsyncInvokeLater;\nAsync.prototype.invoke = AsyncInvoke;\nAsync.prototype.settlePromises = AsyncSettlePromises;\n\n\nfunction _drainQueue(queue) {\n while (queue.length() > 0) {\n _drainQueueStep(queue);\n }\n}\n\nfunction _drainQueueStep(queue) {\n var fn = queue.shift();\n if (typeof fn !== \"function\") {\n fn._settlePromises();\n } else {\n var receiver = queue.shift();\n var arg = queue.shift();\n fn.call(receiver, arg);\n }\n}\n\nAsync.prototype._drainQueues = function () {\n _drainQueue(this._normalQueue);\n this._reset();\n this._haveDrainedQueues = true;\n _drainQueue(this._lateQueue);\n};\n\nAsync.prototype._queueTick = function () {\n if (!this._isTickUsed) {\n this._isTickUsed = true;\n this._schedule(this.drainQueues);\n }\n};\n\nAsync.prototype._reset = function () {\n this._isTickUsed = false;\n};\n\nmodule.exports = Async;\nmodule.exports.firstLineError = firstLineError;\n","\"use strict\";\nvar es5 = require(\"./es5\");\nvar Objectfreeze = es5.freeze;\nvar util = require(\"./util\");\nvar inherits = util.inherits;\nvar notEnumerableProp = util.notEnumerableProp;\n\nfunction subError(nameProperty, defaultMessage) {\n function SubError(message) {\n if (!(this instanceof SubError)) return new SubError(message);\n notEnumerableProp(this, \"message\",\n typeof message === \"string\" ? message : defaultMessage);\n notEnumerableProp(this, \"name\", nameProperty);\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n Error.call(this);\n }\n }\n inherits(SubError, Error);\n return SubError;\n}\n\nvar _TypeError, _RangeError;\nvar Warning = subError(\"Warning\", \"warning\");\nvar CancellationError = subError(\"CancellationError\", \"cancellation error\");\nvar TimeoutError = subError(\"TimeoutError\", \"timeout error\");\nvar AggregateError = subError(\"AggregateError\", \"aggregate error\");\ntry {\n _TypeError = TypeError;\n _RangeError = RangeError;\n} catch(e) {\n _TypeError = subError(\"TypeError\", \"type error\");\n _RangeError = subError(\"RangeError\", \"range error\");\n}\n\nvar methods = (\"join pop push shift unshift slice filter forEach some \" +\n \"every map indexOf lastIndexOf reduce reduceRight sort reverse\").split(\" \");\n\nfor (var i = 0; i < methods.length; ++i) {\n if (typeof Array.prototype[methods[i]] === \"function\") {\n AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];\n }\n}\n\nes5.defineProperty(AggregateError.prototype, \"length\", {\n value: 0,\n configurable: false,\n writable: true,\n enumerable: true\n});\nAggregateError.prototype[\"isOperational\"] = true;\nvar level = 0;\nAggregateError.prototype.toString = function() {\n var indent = Array(level * 4 + 1).join(\" \");\n var ret = \"\\n\" + indent + \"AggregateError of:\" + \"\\n\";\n level++;\n indent = Array(level * 4 + 1).join(\" \");\n for (var i = 0; i < this.length; ++i) {\n var str = this[i] === this ? \"[Circular AggregateError]\" : this[i] + \"\";\n var lines = str.split(\"\\n\");\n for (var j = 0; j < lines.length; ++j) {\n lines[j] = indent + lines[j];\n }\n str = lines.join(\"\\n\");\n ret += str + \"\\n\";\n }\n level--;\n return ret;\n};\n\nfunction OperationalError(message) {\n if (!(this instanceof OperationalError))\n return new OperationalError(message);\n notEnumerableProp(this, \"name\", \"OperationalError\");\n notEnumerableProp(this, \"message\", message);\n this.cause = message;\n this[\"isOperational\"] = true;\n\n if (message instanceof Error) {\n notEnumerableProp(this, \"message\", message.message);\n notEnumerableProp(this, \"stack\", message.stack);\n } else if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n}\ninherits(OperationalError, Error);\n\nvar errorTypes = Error[\"__BluebirdErrorTypes__\"];\nif (!errorTypes) {\n errorTypes = Objectfreeze({\n CancellationError: CancellationError,\n TimeoutError: TimeoutError,\n OperationalError: OperationalError,\n RejectionError: OperationalError,\n AggregateError: AggregateError\n });\n es5.defineProperty(Error, \"__BluebirdErrorTypes__\", {\n value: errorTypes,\n writable: false,\n enumerable: false,\n configurable: false\n });\n}\n\nmodule.exports = {\n Error: Error,\n TypeError: _TypeError,\n RangeError: _RangeError,\n CancellationError: errorTypes.CancellationError,\n OperationalError: errorTypes.OperationalError,\n TimeoutError: errorTypes.TimeoutError,\n AggregateError: errorTypes.AggregateError,\n Warning: Warning\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL) {\nvar util = require(\"./util\");\nvar errorObj = util.errorObj;\nvar isObject = util.isObject;\n\nfunction tryConvertToPromise(obj, context) {\n if (isObject(obj)) {\n if (obj instanceof Promise) return obj;\n var then = getThen(obj);\n if (then === errorObj) {\n if (context) context._pushContext();\n var ret = Promise.reject(then.e);\n if (context) context._popContext();\n return ret;\n } else if (typeof then === \"function\") {\n if (isAnyBluebirdPromise(obj)) {\n var ret = new Promise(INTERNAL);\n obj._then(\n ret._fulfill,\n ret._reject,\n undefined,\n ret,\n null\n );\n return ret;\n }\n return doThenable(obj, then, context);\n }\n }\n return obj;\n}\n\nfunction doGetThen(obj) {\n return obj.then;\n}\n\nfunction getThen(obj) {\n try {\n return doGetThen(obj);\n } catch (e) {\n errorObj.e = e;\n return errorObj;\n }\n}\n\nvar hasProp = {}.hasOwnProperty;\nfunction isAnyBluebirdPromise(obj) {\n try {\n return hasProp.call(obj, \"_promise0\");\n } catch (e) {\n return false;\n }\n}\n\nfunction doThenable(x, then, context) {\n var promise = new Promise(INTERNAL);\n var ret = promise;\n if (context) context._pushContext();\n promise._captureStackTrace();\n if (context) context._popContext();\n var synchronous = true;\n var result = util.tryCatch(then).call(x, resolve, reject);\n synchronous = false;\n\n if (promise && result === errorObj) {\n promise._rejectCallback(result.e, true, true);\n promise = null;\n }\n\n function resolve(value) {\n if (!promise) return;\n promise._resolveCallback(value);\n promise = null;\n }\n\n function reject(reason) {\n if (!promise) return;\n promise._rejectCallback(reason, synchronous, true);\n promise = null;\n }\n return ret;\n}\n\nreturn tryConvertToPromise;\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL, tryConvertToPromise,\n apiRejection, Proxyable) {\nvar util = require(\"./util\");\nvar isArray = util.isArray;\n\nfunction toResolutionValue(val) {\n switch(val) {\n case -2: return [];\n case -3: return {};\n case -6: return new Map();\n }\n}\n\nfunction PromiseArray(values) {\n var promise = this._promise = new Promise(INTERNAL);\n if (values instanceof Promise) {\n promise._propagateFrom(values, 3);\n values.suppressUnhandledRejections();\n }\n promise._setOnCancel(this);\n this._values = values;\n this._length = 0;\n this._totalResolved = 0;\n this._init(undefined, -2);\n}\nutil.inherits(PromiseArray, Proxyable);\n\nPromiseArray.prototype.length = function () {\n return this._length;\n};\n\nPromiseArray.prototype.promise = function () {\n return this._promise;\n};\n\nPromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {\n var values = tryConvertToPromise(this._values, this._promise);\n if (values instanceof Promise) {\n values = values._target();\n var bitField = values._bitField;\n ;\n this._values = values;\n\n if (((bitField & 50397184) === 0)) {\n this._promise._setAsyncGuaranteed();\n return values._then(\n init,\n this._reject,\n undefined,\n this,\n resolveValueIfEmpty\n );\n } else if (((bitField & 33554432) !== 0)) {\n values = values._value();\n } else if (((bitField & 16777216) !== 0)) {\n return this._reject(values._reason());\n } else {\n return this._cancel();\n }\n }\n values = util.asArray(values);\n if (values === null) {\n var err = apiRejection(\n \"expecting an array or an iterable object but got \" + util.classString(values)).reason();\n this._promise._rejectCallback(err, false);\n return;\n }\n\n if (values.length === 0) {\n if (resolveValueIfEmpty === -5) {\n this._resolveEmptyArray();\n }\n else {\n this._resolve(toResolutionValue(resolveValueIfEmpty));\n }\n return;\n }\n this._iterate(values);\n};\n\nPromiseArray.prototype._iterate = function(values) {\n var len = this.getActualLength(values.length);\n this._length = len;\n this._values = this.shouldCopyValues() ? new Array(len) : this._values;\n var result = this._promise;\n var isResolved = false;\n var bitField = null;\n for (var i = 0; i < len; ++i) {\n var maybePromise = tryConvertToPromise(values[i], result);\n\n if (maybePromise instanceof Promise) {\n maybePromise = maybePromise._target();\n bitField = maybePromise._bitField;\n } else {\n bitField = null;\n }\n\n if (isResolved) {\n if (bitField !== null) {\n maybePromise.suppressUnhandledRejections();\n }\n } else if (bitField !== null) {\n if (((bitField & 50397184) === 0)) {\n maybePromise._proxy(this, i);\n this._values[i] = maybePromise;\n } else if (((bitField & 33554432) !== 0)) {\n isResolved = this._promiseFulfilled(maybePromise._value(), i);\n } else if (((bitField & 16777216) !== 0)) {\n isResolved = this._promiseRejected(maybePromise._reason(), i);\n } else {\n isResolved = this._promiseCancelled(i);\n }\n } else {\n isResolved = this._promiseFulfilled(maybePromise, i);\n }\n }\n if (!isResolved) result._setAsyncGuaranteed();\n};\n\nPromiseArray.prototype._isResolved = function () {\n return this._values === null;\n};\n\nPromiseArray.prototype._resolve = function (value) {\n this._values = null;\n this._promise._fulfill(value);\n};\n\nPromiseArray.prototype._cancel = function() {\n if (this._isResolved() || !this._promise._isCancellable()) return;\n this._values = null;\n this._promise._cancel();\n};\n\nPromiseArray.prototype._reject = function (reason) {\n this._values = null;\n this._promise._rejectCallback(reason, false);\n};\n\nPromiseArray.prototype._promiseFulfilled = function (value, index) {\n this._values[index] = value;\n var totalResolved = ++this._totalResolved;\n if (totalResolved >= this._length) {\n this._resolve(this._values);\n return true;\n }\n return false;\n};\n\nPromiseArray.prototype._promiseCancelled = function() {\n this._cancel();\n return true;\n};\n\nPromiseArray.prototype._promiseRejected = function (reason) {\n this._totalResolved++;\n this._reject(reason);\n return true;\n};\n\nPromiseArray.prototype._resultCancelled = function() {\n if (this._isResolved()) return;\n var values = this._values;\n this._cancel();\n if (values instanceof Promise) {\n values.cancel();\n } else {\n for (var i = 0; i < values.length; ++i) {\n if (values[i] instanceof Promise) {\n values[i].cancel();\n }\n }\n }\n};\n\nPromiseArray.prototype.shouldCopyValues = function () {\n return true;\n};\n\nPromiseArray.prototype.getActualLength = function (len) {\n return len;\n};\n\nreturn PromiseArray;\n};\n","\"use strict\";\nmodule.exports = function(Promise) {\nvar longStackTraces = false;\nvar contextStack = [];\n\nPromise.prototype._promiseCreated = function() {};\nPromise.prototype._pushContext = function() {};\nPromise.prototype._popContext = function() {return null;};\nPromise._peekContext = Promise.prototype._peekContext = function() {};\n\nfunction Context() {\n this._trace = new Context.CapturedTrace(peekContext());\n}\nContext.prototype._pushContext = function () {\n if (this._trace !== undefined) {\n this._trace._promiseCreated = null;\n contextStack.push(this._trace);\n }\n};\n\nContext.prototype._popContext = function () {\n if (this._trace !== undefined) {\n var trace = contextStack.pop();\n var ret = trace._promiseCreated;\n trace._promiseCreated = null;\n return ret;\n }\n return null;\n};\n\nfunction createContext() {\n if (longStackTraces) return new Context();\n}\n\nfunction peekContext() {\n var lastIndex = contextStack.length - 1;\n if (lastIndex >= 0) {\n return contextStack[lastIndex];\n }\n return undefined;\n}\nContext.CapturedTrace = null;\nContext.create = createContext;\nContext.deactivateLongStackTraces = function() {};\nContext.activateLongStackTraces = function() {\n var Promise_pushContext = Promise.prototype._pushContext;\n var Promise_popContext = Promise.prototype._popContext;\n var Promise_PeekContext = Promise._peekContext;\n var Promise_peekContext = Promise.prototype._peekContext;\n var Promise_promiseCreated = Promise.prototype._promiseCreated;\n Context.deactivateLongStackTraces = function() {\n Promise.prototype._pushContext = Promise_pushContext;\n Promise.prototype._popContext = Promise_popContext;\n Promise._peekContext = Promise_PeekContext;\n Promise.prototype._peekContext = Promise_peekContext;\n Promise.prototype._promiseCreated = Promise_promiseCreated;\n longStackTraces = false;\n };\n longStackTraces = true;\n Promise.prototype._pushContext = Context.prototype._pushContext;\n Promise.prototype._popContext = Context.prototype._popContext;\n Promise._peekContext = Promise.prototype._peekContext = peekContext;\n Promise.prototype._promiseCreated = function() {\n var ctx = this._peekContext();\n if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;\n };\n};\nreturn Context;\n};\n","\"use strict\";\nmodule.exports = function(Promise, Context,\n enableAsyncHooks, disableAsyncHooks) {\nvar async = Promise._async;\nvar Warning = require(\"./errors\").Warning;\nvar util = require(\"./util\");\nvar es5 = require(\"./es5\");\nvar canAttachTrace = util.canAttachTrace;\nvar unhandledRejectionHandled;\nvar possiblyUnhandledRejection;\nvar bluebirdFramePattern =\n /[\\\\\\/]bluebird[\\\\\\/]js[\\\\\\/](release|debug|instrumented)/;\nvar nodeFramePattern = /\\((?:timers\\.js):\\d+:\\d+\\)/;\nvar parseLinePattern = /[\\/<\\(](.+?):(\\d+):(\\d+)\\)?\\s*$/;\nvar stackFramePattern = null;\nvar formatStack = null;\nvar indentStackFrames = false;\nvar printWarning;\nvar debugging = !!(util.env(\"BLUEBIRD_DEBUG\") != 0 &&\n (false ||\n util.env(\"BLUEBIRD_DEBUG\") ||\n util.env(\"NODE_ENV\") === \"development\"));\n\nvar warnings = !!(util.env(\"BLUEBIRD_WARNINGS\") != 0 &&\n (debugging || util.env(\"BLUEBIRD_WARNINGS\")));\n\nvar longStackTraces = !!(util.env(\"BLUEBIRD_LONG_STACK_TRACES\") != 0 &&\n (debugging || util.env(\"BLUEBIRD_LONG_STACK_TRACES\")));\n\nvar wForgottenReturn = util.env(\"BLUEBIRD_W_FORGOTTEN_RETURN\") != 0 &&\n (warnings || !!util.env(\"BLUEBIRD_W_FORGOTTEN_RETURN\"));\n\nvar deferUnhandledRejectionCheck;\n(function() {\n var promises = [];\n\n function unhandledRejectionCheck() {\n for (var i = 0; i < promises.length; ++i) {\n promises[i]._notifyUnhandledRejection();\n }\n unhandledRejectionClear();\n }\n\n function unhandledRejectionClear() {\n promises.length = 0;\n }\n\n deferUnhandledRejectionCheck = function(promise) {\n promises.push(promise);\n setTimeout(unhandledRejectionCheck, 1);\n };\n\n es5.defineProperty(Promise, \"_unhandledRejectionCheck\", {\n value: unhandledRejectionCheck\n });\n es5.defineProperty(Promise, \"_unhandledRejectionClear\", {\n value: unhandledRejectionClear\n });\n})();\n\nPromise.prototype.suppressUnhandledRejections = function() {\n var target = this._target();\n target._bitField = ((target._bitField & (~1048576)) |\n 524288);\n};\n\nPromise.prototype._ensurePossibleRejectionHandled = function () {\n if ((this._bitField & 524288) !== 0) return;\n this._setRejectionIsUnhandled();\n deferUnhandledRejectionCheck(this);\n};\n\nPromise.prototype._notifyUnhandledRejectionIsHandled = function () {\n fireRejectionEvent(\"rejectionHandled\",\n unhandledRejectionHandled, undefined, this);\n};\n\nPromise.prototype._setReturnedNonUndefined = function() {\n this._bitField = this._bitField | 268435456;\n};\n\nPromise.prototype._returnedNonUndefined = function() {\n return (this._bitField & 268435456) !== 0;\n};\n\nPromise.prototype._notifyUnhandledRejection = function () {\n if (this._isRejectionUnhandled()) {\n var reason = this._settledValue();\n this._setUnhandledRejectionIsNotified();\n fireRejectionEvent(\"unhandledRejection\",\n possiblyUnhandledRejection, reason, this);\n }\n};\n\nPromise.prototype._setUnhandledRejectionIsNotified = function () {\n this._bitField = this._bitField | 262144;\n};\n\nPromise.prototype._unsetUnhandledRejectionIsNotified = function () {\n this._bitField = this._bitField & (~262144);\n};\n\nPromise.prototype._isUnhandledRejectionNotified = function () {\n return (this._bitField & 262144) > 0;\n};\n\nPromise.prototype._setRejectionIsUnhandled = function () {\n this._bitField = this._bitField | 1048576;\n};\n\nPromise.prototype._unsetRejectionIsUnhandled = function () {\n this._bitField = this._bitField & (~1048576);\n if (this._isUnhandledRejectionNotified()) {\n this._unsetUnhandledRejectionIsNotified();\n this._notifyUnhandledRejectionIsHandled();\n }\n};\n\nPromise.prototype._isRejectionUnhandled = function () {\n return (this._bitField & 1048576) > 0;\n};\n\nPromise.prototype._warn = function(message, shouldUseOwnTrace, promise) {\n return warn(message, shouldUseOwnTrace, promise || this);\n};\n\nPromise.onPossiblyUnhandledRejection = function (fn) {\n var context = Promise._getContext();\n possiblyUnhandledRejection = util.contextBind(context, fn);\n};\n\nPromise.onUnhandledRejectionHandled = function (fn) {\n var context = Promise._getContext();\n unhandledRejectionHandled = util.contextBind(context, fn);\n};\n\nvar disableLongStackTraces = function() {};\nPromise.longStackTraces = function () {\n if (async.haveItemsQueued() && !config.longStackTraces) {\n throw new Error(\"cannot enable long stack traces after promises have been created\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n if (!config.longStackTraces && longStackTracesIsSupported()) {\n var Promise_captureStackTrace = Promise.prototype._captureStackTrace;\n var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;\n var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;\n config.longStackTraces = true;\n disableLongStackTraces = function() {\n if (async.haveItemsQueued() && !config.longStackTraces) {\n throw new Error(\"cannot enable long stack traces after promises have been created\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n Promise.prototype._captureStackTrace = Promise_captureStackTrace;\n Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;\n Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;\n Context.deactivateLongStackTraces();\n config.longStackTraces = false;\n };\n Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;\n Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;\n Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;\n Context.activateLongStackTraces();\n }\n};\n\nPromise.hasLongStackTraces = function () {\n return config.longStackTraces && longStackTracesIsSupported();\n};\n\n\nvar legacyHandlers = {\n unhandledrejection: {\n before: function() {\n var ret = util.global.onunhandledrejection;\n util.global.onunhandledrejection = null;\n return ret;\n },\n after: function(fn) {\n util.global.onunhandledrejection = fn;\n }\n },\n rejectionhandled: {\n before: function() {\n var ret = util.global.onrejectionhandled;\n util.global.onrejectionhandled = null;\n return ret;\n },\n after: function(fn) {\n util.global.onrejectionhandled = fn;\n }\n }\n};\n\nvar fireDomEvent = (function() {\n var dispatch = function(legacy, e) {\n if (legacy) {\n var fn;\n try {\n fn = legacy.before();\n return !util.global.dispatchEvent(e);\n } finally {\n legacy.after(fn);\n }\n } else {\n return !util.global.dispatchEvent(e);\n }\n };\n try {\n if (typeof CustomEvent === \"function\") {\n var event = new CustomEvent(\"CustomEvent\");\n util.global.dispatchEvent(event);\n return function(name, event) {\n name = name.toLowerCase();\n var eventData = {\n detail: event,\n cancelable: true\n };\n var domEvent = new CustomEvent(name, eventData);\n es5.defineProperty(\n domEvent, \"promise\", {value: event.promise});\n es5.defineProperty(\n domEvent, \"reason\", {value: event.reason});\n\n return dispatch(legacyHandlers[name], domEvent);\n };\n } else if (typeof Event === \"function\") {\n var event = new Event(\"CustomEvent\");\n util.global.dispatchEvent(event);\n return function(name, event) {\n name = name.toLowerCase();\n var domEvent = new Event(name, {\n cancelable: true\n });\n domEvent.detail = event;\n es5.defineProperty(domEvent, \"promise\", {value: event.promise});\n es5.defineProperty(domEvent, \"reason\", {value: event.reason});\n return dispatch(legacyHandlers[name], domEvent);\n };\n } else {\n var event = document.createEvent(\"CustomEvent\");\n event.initCustomEvent(\"testingtheevent\", false, true, {});\n util.global.dispatchEvent(event);\n return function(name, event) {\n name = name.toLowerCase();\n var domEvent = document.createEvent(\"CustomEvent\");\n domEvent.initCustomEvent(name, false, true,\n event);\n return dispatch(legacyHandlers[name], domEvent);\n };\n }\n } catch (e) {}\n return function() {\n return false;\n };\n})();\n\nvar fireGlobalEvent = (function() {\n if (util.isNode) {\n return function() {\n return process.emit.apply(process, arguments);\n };\n } else {\n if (!util.global) {\n return function() {\n return false;\n };\n }\n return function(name) {\n var methodName = \"on\" + name.toLowerCase();\n var method = util.global[methodName];\n if (!method) return false;\n method.apply(util.global, [].slice.call(arguments, 1));\n return true;\n };\n }\n})();\n\nfunction generatePromiseLifecycleEventObject(name, promise) {\n return {promise: promise};\n}\n\nvar eventToObjectGenerator = {\n promiseCreated: generatePromiseLifecycleEventObject,\n promiseFulfilled: generatePromiseLifecycleEventObject,\n promiseRejected: generatePromiseLifecycleEventObject,\n promiseResolved: generatePromiseLifecycleEventObject,\n promiseCancelled: generatePromiseLifecycleEventObject,\n promiseChained: function(name, promise, child) {\n return {promise: promise, child: child};\n },\n warning: function(name, warning) {\n return {warning: warning};\n },\n unhandledRejection: function (name, reason, promise) {\n return {reason: reason, promise: promise};\n },\n rejectionHandled: generatePromiseLifecycleEventObject\n};\n\nvar activeFireEvent = function (name) {\n var globalEventFired = false;\n try {\n globalEventFired = fireGlobalEvent.apply(null, arguments);\n } catch (e) {\n async.throwLater(e);\n globalEventFired = true;\n }\n\n var domEventFired = false;\n try {\n domEventFired = fireDomEvent(name,\n eventToObjectGenerator[name].apply(null, arguments));\n } catch (e) {\n async.throwLater(e);\n domEventFired = true;\n }\n\n return domEventFired || globalEventFired;\n};\n\nPromise.config = function(opts) {\n opts = Object(opts);\n if (\"longStackTraces\" in opts) {\n if (opts.longStackTraces) {\n Promise.longStackTraces();\n } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {\n disableLongStackTraces();\n }\n }\n if (\"warnings\" in opts) {\n var warningsOption = opts.warnings;\n config.warnings = !!warningsOption;\n wForgottenReturn = config.warnings;\n\n if (util.isObject(warningsOption)) {\n if (\"wForgottenReturn\" in warningsOption) {\n wForgottenReturn = !!warningsOption.wForgottenReturn;\n }\n }\n }\n if (\"cancellation\" in opts && opts.cancellation && !config.cancellation) {\n if (async.haveItemsQueued()) {\n throw new Error(\n \"cannot enable cancellation after promises are in use\");\n }\n Promise.prototype._clearCancellationData =\n cancellationClearCancellationData;\n Promise.prototype._propagateFrom = cancellationPropagateFrom;\n Promise.prototype._onCancel = cancellationOnCancel;\n Promise.prototype._setOnCancel = cancellationSetOnCancel;\n Promise.prototype._attachCancellationCallback =\n cancellationAttachCancellationCallback;\n Promise.prototype._execute = cancellationExecute;\n propagateFromFunction = cancellationPropagateFrom;\n config.cancellation = true;\n }\n if (\"monitoring\" in opts) {\n if (opts.monitoring && !config.monitoring) {\n config.monitoring = true;\n Promise.prototype._fireEvent = activeFireEvent;\n } else if (!opts.monitoring && config.monitoring) {\n config.monitoring = false;\n Promise.prototype._fireEvent = defaultFireEvent;\n }\n }\n if (\"asyncHooks\" in opts && util.nodeSupportsAsyncResource) {\n var prev = config.asyncHooks;\n var cur = !!opts.asyncHooks;\n if (prev !== cur) {\n config.asyncHooks = cur;\n if (cur) {\n enableAsyncHooks();\n } else {\n disableAsyncHooks();\n }\n }\n }\n return Promise;\n};\n\nfunction defaultFireEvent() { return false; }\n\nPromise.prototype._fireEvent = defaultFireEvent;\nPromise.prototype._execute = function(executor, resolve, reject) {\n try {\n executor(resolve, reject);\n } catch (e) {\n return e;\n }\n};\nPromise.prototype._onCancel = function () {};\nPromise.prototype._setOnCancel = function (handler) { ; };\nPromise.prototype._attachCancellationCallback = function(onCancel) {\n ;\n};\nPromise.prototype._captureStackTrace = function () {};\nPromise.prototype._attachExtraTrace = function () {};\nPromise.prototype._dereferenceTrace = function () {};\nPromise.prototype._clearCancellationData = function() {};\nPromise.prototype._propagateFrom = function (parent, flags) {\n ;\n ;\n};\n\nfunction cancellationExecute(executor, resolve, reject) {\n var promise = this;\n try {\n executor(resolve, reject, function(onCancel) {\n if (typeof onCancel !== \"function\") {\n throw new TypeError(\"onCancel must be a function, got: \" +\n util.toString(onCancel));\n }\n promise._attachCancellationCallback(onCancel);\n });\n } catch (e) {\n return e;\n }\n}\n\nfunction cancellationAttachCancellationCallback(onCancel) {\n if (!this._isCancellable()) return this;\n\n var previousOnCancel = this._onCancel();\n if (previousOnCancel !== undefined) {\n if (util.isArray(previousOnCancel)) {\n previousOnCancel.push(onCancel);\n } else {\n this._setOnCancel([previousOnCancel, onCancel]);\n }\n } else {\n this._setOnCancel(onCancel);\n }\n}\n\nfunction cancellationOnCancel() {\n return this._onCancelField;\n}\n\nfunction cancellationSetOnCancel(onCancel) {\n this._onCancelField = onCancel;\n}\n\nfunction cancellationClearCancellationData() {\n this._cancellationParent = undefined;\n this._onCancelField = undefined;\n}\n\nfunction cancellationPropagateFrom(parent, flags) {\n if ((flags & 1) !== 0) {\n this._cancellationParent = parent;\n var branchesRemainingToCancel = parent._branchesRemainingToCancel;\n if (branchesRemainingToCancel === undefined) {\n branchesRemainingToCancel = 0;\n }\n parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;\n }\n if ((flags & 2) !== 0 && parent._isBound()) {\n this._setBoundTo(parent._boundTo);\n }\n}\n\nfunction bindingPropagateFrom(parent, flags) {\n if ((flags & 2) !== 0 && parent._isBound()) {\n this._setBoundTo(parent._boundTo);\n }\n}\nvar propagateFromFunction = bindingPropagateFrom;\n\nfunction boundValueFunction() {\n var ret = this._boundTo;\n if (ret !== undefined) {\n if (ret instanceof Promise) {\n if (ret.isFulfilled()) {\n return ret.value();\n } else {\n return undefined;\n }\n }\n }\n return ret;\n}\n\nfunction longStackTracesCaptureStackTrace() {\n this._trace = new CapturedTrace(this._peekContext());\n}\n\nfunction longStackTracesAttachExtraTrace(error, ignoreSelf) {\n if (canAttachTrace(error)) {\n var trace = this._trace;\n if (trace !== undefined) {\n if (ignoreSelf) trace = trace._parent;\n }\n if (trace !== undefined) {\n trace.attachExtraTrace(error);\n } else if (!error.__stackCleaned__) {\n var parsed = parseStackAndMessage(error);\n util.notEnumerableProp(error, \"stack\",\n parsed.message + \"\\n\" + parsed.stack.join(\"\\n\"));\n util.notEnumerableProp(error, \"__stackCleaned__\", true);\n }\n }\n}\n\nfunction longStackTracesDereferenceTrace() {\n this._trace = undefined;\n}\n\nfunction checkForgottenReturns(returnValue, promiseCreated, name, promise,\n parent) {\n if (returnValue === undefined && promiseCreated !== null &&\n wForgottenReturn) {\n if (parent !== undefined && parent._returnedNonUndefined()) return;\n if ((promise._bitField & 65535) === 0) return;\n\n if (name) name = name + \" \";\n var handlerLine = \"\";\n var creatorLine = \"\";\n if (promiseCreated._trace) {\n var traceLines = promiseCreated._trace.stack.split(\"\\n\");\n var stack = cleanStack(traceLines);\n for (var i = stack.length - 1; i >= 0; --i) {\n var line = stack[i];\n if (!nodeFramePattern.test(line)) {\n var lineMatches = line.match(parseLinePattern);\n if (lineMatches) {\n handlerLine = \"at \" + lineMatches[1] +\n \":\" + lineMatches[2] + \":\" + lineMatches[3] + \" \";\n }\n break;\n }\n }\n\n if (stack.length > 0) {\n var firstUserLine = stack[0];\n for (var i = 0; i < traceLines.length; ++i) {\n\n if (traceLines[i] === firstUserLine) {\n if (i > 0) {\n creatorLine = \"\\n\" + traceLines[i - 1];\n }\n break;\n }\n }\n\n }\n }\n var msg = \"a promise was created in a \" + name +\n \"handler \" + handlerLine + \"but was not returned from it, \" +\n \"see http://goo.gl/rRqMUw\" +\n creatorLine;\n promise._warn(msg, true, promiseCreated);\n }\n}\n\nfunction deprecated(name, replacement) {\n var message = name +\n \" is deprecated and will be removed in a future version.\";\n if (replacement) message += \" Use \" + replacement + \" instead.\";\n return warn(message);\n}\n\nfunction warn(message, shouldUseOwnTrace, promise) {\n if (!config.warnings) return;\n var warning = new Warning(message);\n var ctx;\n if (shouldUseOwnTrace) {\n promise._attachExtraTrace(warning);\n } else if (config.longStackTraces && (ctx = Promise._peekContext())) {\n ctx.attachExtraTrace(warning);\n } else {\n var parsed = parseStackAndMessage(warning);\n warning.stack = parsed.message + \"\\n\" + parsed.stack.join(\"\\n\");\n }\n\n if (!activeFireEvent(\"warning\", warning)) {\n formatAndLogError(warning, \"\", true);\n }\n}\n\nfunction reconstructStack(message, stacks) {\n for (var i = 0; i < stacks.length - 1; ++i) {\n stacks[i].push(\"From previous event:\");\n stacks[i] = stacks[i].join(\"\\n\");\n }\n if (i < stacks.length) {\n stacks[i] = stacks[i].join(\"\\n\");\n }\n return message + \"\\n\" + stacks.join(\"\\n\");\n}\n\nfunction removeDuplicateOrEmptyJumps(stacks) {\n for (var i = 0; i < stacks.length; ++i) {\n if (stacks[i].length === 0 ||\n ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {\n stacks.splice(i, 1);\n i--;\n }\n }\n}\n\nfunction removeCommonRoots(stacks) {\n var current = stacks[0];\n for (var i = 1; i < stacks.length; ++i) {\n var prev = stacks[i];\n var currentLastIndex = current.length - 1;\n var currentLastLine = current[currentLastIndex];\n var commonRootMeetPoint = -1;\n\n for (var j = prev.length - 1; j >= 0; --j) {\n if (prev[j] === currentLastLine) {\n commonRootMeetPoint = j;\n break;\n }\n }\n\n for (var j = commonRootMeetPoint; j >= 0; --j) {\n var line = prev[j];\n if (current[currentLastIndex] === line) {\n current.pop();\n currentLastIndex--;\n } else {\n break;\n }\n }\n current = prev;\n }\n}\n\nfunction cleanStack(stack) {\n var ret = [];\n for (var i = 0; i < stack.length; ++i) {\n var line = stack[i];\n var isTraceLine = \" (No stack trace)\" === line ||\n stackFramePattern.test(line);\n var isInternalFrame = isTraceLine && shouldIgnore(line);\n if (isTraceLine && !isInternalFrame) {\n if (indentStackFrames && line.charAt(0) !== \" \") {\n line = \" \" + line;\n }\n ret.push(line);\n }\n }\n return ret;\n}\n\nfunction stackFramesAsArray(error) {\n var stack = error.stack.replace(/\\s+$/g, \"\").split(\"\\n\");\n for (var i = 0; i < stack.length; ++i) {\n var line = stack[i];\n if (\" (No stack trace)\" === line || stackFramePattern.test(line)) {\n break;\n }\n }\n if (i > 0 && error.name != \"SyntaxError\") {\n stack = stack.slice(i);\n }\n return stack;\n}\n\nfunction parseStackAndMessage(error) {\n var stack = error.stack;\n var message = error.toString();\n stack = typeof stack === \"string\" && stack.length > 0\n ? stackFramesAsArray(error) : [\" (No stack trace)\"];\n return {\n message: message,\n stack: error.name == \"SyntaxError\" ? stack : cleanStack(stack)\n };\n}\n\nfunction formatAndLogError(error, title, isSoft) {\n if (typeof console !== \"undefined\") {\n var message;\n if (util.isObject(error)) {\n var stack = error.stack;\n message = title + formatStack(stack, error);\n } else {\n message = title + String(error);\n }\n if (typeof printWarning === \"function\") {\n printWarning(message, isSoft);\n } else if (typeof console.log === \"function\" ||\n typeof console.log === \"object\") {\n console.log(message);\n }\n }\n}\n\nfunction fireRejectionEvent(name, localHandler, reason, promise) {\n var localEventFired = false;\n try {\n if (typeof localHandler === \"function\") {\n localEventFired = true;\n if (name === \"rejectionHandled\") {\n localHandler(promise);\n } else {\n localHandler(reason, promise);\n }\n }\n } catch (e) {\n async.throwLater(e);\n }\n\n if (name === \"unhandledRejection\") {\n if (!activeFireEvent(name, reason, promise) && !localEventFired) {\n formatAndLogError(reason, \"Unhandled rejection \");\n }\n } else {\n activeFireEvent(name, promise);\n }\n}\n\nfunction formatNonError(obj) {\n var str;\n if (typeof obj === \"function\") {\n str = \"[function \" +\n (obj.name || \"anonymous\") +\n \"]\";\n } else {\n str = obj && typeof obj.toString === \"function\"\n ? obj.toString() : util.toString(obj);\n var ruselessToString = /\\[object [a-zA-Z0-9$_]+\\]/;\n if (ruselessToString.test(str)) {\n try {\n var newStr = JSON.stringify(obj);\n str = newStr;\n }\n catch(e) {\n\n }\n }\n if (str.length === 0) {\n str = \"(empty array)\";\n }\n }\n return (\"(<\" + snip(str) + \">, no stack trace)\");\n}\n\nfunction snip(str) {\n var maxChars = 41;\n if (str.length < maxChars) {\n return str;\n }\n return str.substr(0, maxChars - 3) + \"...\";\n}\n\nfunction longStackTracesIsSupported() {\n return typeof captureStackTrace === \"function\";\n}\n\nvar shouldIgnore = function() { return false; };\nvar parseLineInfoRegex = /[\\/<\\(]([^:\\/]+):(\\d+):(?:\\d+)\\)?\\s*$/;\nfunction parseLineInfo(line) {\n var matches = line.match(parseLineInfoRegex);\n if (matches) {\n return {\n fileName: matches[1],\n line: parseInt(matches[2], 10)\n };\n }\n}\n\nfunction setBounds(firstLineError, lastLineError) {\n if (!longStackTracesIsSupported()) return;\n var firstStackLines = (firstLineError.stack || \"\").split(\"\\n\");\n var lastStackLines = (lastLineError.stack || \"\").split(\"\\n\");\n var firstIndex = -1;\n var lastIndex = -1;\n var firstFileName;\n var lastFileName;\n for (var i = 0; i < firstStackLines.length; ++i) {\n var result = parseLineInfo(firstStackLines[i]);\n if (result) {\n firstFileName = result.fileName;\n firstIndex = result.line;\n break;\n }\n }\n for (var i = 0; i < lastStackLines.length; ++i) {\n var result = parseLineInfo(lastStackLines[i]);\n if (result) {\n lastFileName = result.fileName;\n lastIndex = result.line;\n break;\n }\n }\n if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||\n firstFileName !== lastFileName || firstIndex >= lastIndex) {\n return;\n }\n\n shouldIgnore = function(line) {\n if (bluebirdFramePattern.test(line)) return true;\n var info = parseLineInfo(line);\n if (info) {\n if (info.fileName === firstFileName &&\n (firstIndex <= info.line && info.line <= lastIndex)) {\n return true;\n }\n }\n return false;\n };\n}\n\nfunction CapturedTrace(parent) {\n this._parent = parent;\n this._promisesCreated = 0;\n var length = this._length = 1 + (parent === undefined ? 0 : parent._length);\n captureStackTrace(this, CapturedTrace);\n if (length > 32) this.uncycle();\n}\nutil.inherits(CapturedTrace, Error);\nContext.CapturedTrace = CapturedTrace;\n\nCapturedTrace.prototype.uncycle = function() {\n var length = this._length;\n if (length < 2) return;\n var nodes = [];\n var stackToIndex = {};\n\n for (var i = 0, node = this; node !== undefined; ++i) {\n nodes.push(node);\n node = node._parent;\n }\n length = this._length = i;\n for (var i = length - 1; i >= 0; --i) {\n var stack = nodes[i].stack;\n if (stackToIndex[stack] === undefined) {\n stackToIndex[stack] = i;\n }\n }\n for (var i = 0; i < length; ++i) {\n var currentStack = nodes[i].stack;\n var index = stackToIndex[currentStack];\n if (index !== undefined && index !== i) {\n if (index > 0) {\n nodes[index - 1]._parent = undefined;\n nodes[index - 1]._length = 1;\n }\n nodes[i]._parent = undefined;\n nodes[i]._length = 1;\n var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;\n\n if (index < length - 1) {\n cycleEdgeNode._parent = nodes[index + 1];\n cycleEdgeNode._parent.uncycle();\n cycleEdgeNode._length =\n cycleEdgeNode._parent._length + 1;\n } else {\n cycleEdgeNode._parent = undefined;\n cycleEdgeNode._length = 1;\n }\n var currentChildLength = cycleEdgeNode._length + 1;\n for (var j = i - 2; j >= 0; --j) {\n nodes[j]._length = currentChildLength;\n currentChildLength++;\n }\n return;\n }\n }\n};\n\nCapturedTrace.prototype.attachExtraTrace = function(error) {\n if (error.__stackCleaned__) return;\n this.uncycle();\n var parsed = parseStackAndMessage(error);\n var message = parsed.message;\n var stacks = [parsed.stack];\n\n var trace = this;\n while (trace !== undefined) {\n stacks.push(cleanStack(trace.stack.split(\"\\n\")));\n trace = trace._parent;\n }\n removeCommonRoots(stacks);\n removeDuplicateOrEmptyJumps(stacks);\n util.notEnumerableProp(error, \"stack\", reconstructStack(message, stacks));\n util.notEnumerableProp(error, \"__stackCleaned__\", true);\n};\n\nvar captureStackTrace = (function stackDetection() {\n var v8stackFramePattern = /^\\s*at\\s*/;\n var v8stackFormatter = function(stack, error) {\n if (typeof stack === \"string\") return stack;\n\n if (error.name !== undefined &&\n error.message !== undefined) {\n return error.toString();\n }\n return formatNonError(error);\n };\n\n if (typeof Error.stackTraceLimit === \"number\" &&\n typeof Error.captureStackTrace === \"function\") {\n Error.stackTraceLimit += 6;\n stackFramePattern = v8stackFramePattern;\n formatStack = v8stackFormatter;\n var captureStackTrace = Error.captureStackTrace;\n\n shouldIgnore = function(line) {\n return bluebirdFramePattern.test(line);\n };\n return function(receiver, ignoreUntil) {\n Error.stackTraceLimit += 6;\n captureStackTrace(receiver, ignoreUntil);\n Error.stackTraceLimit -= 6;\n };\n }\n var err = new Error();\n\n if (typeof err.stack === \"string\" &&\n err.stack.split(\"\\n\")[0].indexOf(\"stackDetection@\") >= 0) {\n stackFramePattern = /@/;\n formatStack = v8stackFormatter;\n indentStackFrames = true;\n return function captureStackTrace(o) {\n o.stack = new Error().stack;\n };\n }\n\n var hasStackAfterThrow;\n try { throw new Error(); }\n catch(e) {\n hasStackAfterThrow = (\"stack\" in e);\n }\n if (!(\"stack\" in err) && hasStackAfterThrow &&\n typeof Error.stackTraceLimit === \"number\") {\n stackFramePattern = v8stackFramePattern;\n formatStack = v8stackFormatter;\n return function captureStackTrace(o) {\n Error.stackTraceLimit += 6;\n try { throw new Error(); }\n catch(e) { o.stack = e.stack; }\n Error.stackTraceLimit -= 6;\n };\n }\n\n formatStack = function(stack, error) {\n if (typeof stack === \"string\") return stack;\n\n if ((typeof error === \"object\" ||\n typeof error === \"function\") &&\n error.name !== undefined &&\n error.message !== undefined) {\n return error.toString();\n }\n return formatNonError(error);\n };\n\n return null;\n\n})([]);\n\nif (typeof console !== \"undefined\" && typeof console.warn !== \"undefined\") {\n printWarning = function (message) {\n console.warn(message);\n };\n if (util.isNode && process.stderr.isTTY) {\n printWarning = function(message, isSoft) {\n var color = isSoft ? \"\\u001b[33m\" : \"\\u001b[31m\";\n console.warn(color + message + \"\\u001b[0m\\n\");\n };\n } else if (!util.isNode && typeof (new Error().stack) === \"string\") {\n printWarning = function(message, isSoft) {\n console.warn(\"%c\" + message,\n isSoft ? \"color: darkorange\" : \"color: red\");\n };\n }\n}\n\nvar config = {\n warnings: warnings,\n longStackTraces: false,\n cancellation: false,\n monitoring: false,\n asyncHooks: false\n};\n\nif (longStackTraces) Promise.longStackTraces();\n\nreturn {\n asyncHooks: function() {\n return config.asyncHooks;\n },\n longStackTraces: function() {\n return config.longStackTraces;\n },\n warnings: function() {\n return config.warnings;\n },\n cancellation: function() {\n return config.cancellation;\n },\n monitoring: function() {\n return config.monitoring;\n },\n propagateFromFunction: function() {\n return propagateFromFunction;\n },\n boundValueFunction: function() {\n return boundValueFunction;\n },\n checkForgottenReturns: checkForgottenReturns,\n setBounds: setBounds,\n warn: warn,\n deprecated: deprecated,\n CapturedTrace: CapturedTrace,\n fireDomEvent: fireDomEvent,\n fireGlobalEvent: fireGlobalEvent\n};\n};\n","\"use strict\";\nmodule.exports = function(NEXT_FILTER) {\nvar util = require(\"./util\");\nvar getKeys = require(\"./es5\").keys;\nvar tryCatch = util.tryCatch;\nvar errorObj = util.errorObj;\n\nfunction catchFilter(instances, cb, promise) {\n return function(e) {\n var boundTo = promise._boundValue();\n predicateLoop: for (var i = 0; i < instances.length; ++i) {\n var item = instances[i];\n\n if (item === Error ||\n (item != null && item.prototype instanceof Error)) {\n if (e instanceof item) {\n return tryCatch(cb).call(boundTo, e);\n }\n } else if (typeof item === \"function\") {\n var matchesPredicate = tryCatch(item).call(boundTo, e);\n if (matchesPredicate === errorObj) {\n return matchesPredicate;\n } else if (matchesPredicate) {\n return tryCatch(cb).call(boundTo, e);\n }\n } else if (util.isObject(e)) {\n var keys = getKeys(item);\n for (var j = 0; j < keys.length; ++j) {\n var key = keys[j];\n if (item[key] != e[key]) {\n continue predicateLoop;\n }\n }\n return tryCatch(cb).call(boundTo, e);\n }\n }\n return NEXT_FILTER;\n };\n}\n\nreturn catchFilter;\n};\n","\"use strict\";\nmodule.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {\nvar util = require(\"./util\");\nvar CancellationError = Promise.CancellationError;\nvar errorObj = util.errorObj;\nvar catchFilter = require(\"./catch_filter\")(NEXT_FILTER);\n\nfunction PassThroughHandlerContext(promise, type, handler) {\n this.promise = promise;\n this.type = type;\n this.handler = handler;\n this.called = false;\n this.cancelPromise = null;\n}\n\nPassThroughHandlerContext.prototype.isFinallyHandler = function() {\n return this.type === 0;\n};\n\nfunction FinallyHandlerCancelReaction(finallyHandler) {\n this.finallyHandler = finallyHandler;\n}\n\nFinallyHandlerCancelReaction.prototype._resultCancelled = function() {\n checkCancel(this.finallyHandler);\n};\n\nfunction checkCancel(ctx, reason) {\n if (ctx.cancelPromise != null) {\n if (arguments.length > 1) {\n ctx.cancelPromise._reject(reason);\n } else {\n ctx.cancelPromise._cancel();\n }\n ctx.cancelPromise = null;\n return true;\n }\n return false;\n}\n\nfunction succeed() {\n return finallyHandler.call(this, this.promise._target()._settledValue());\n}\nfunction fail(reason) {\n if (checkCancel(this, reason)) return;\n errorObj.e = reason;\n return errorObj;\n}\nfunction finallyHandler(reasonOrValue) {\n var promise = this.promise;\n var handler = this.handler;\n\n if (!this.called) {\n this.called = true;\n var ret = this.isFinallyHandler()\n ? handler.call(promise._boundValue())\n : handler.call(promise._boundValue(), reasonOrValue);\n if (ret === NEXT_FILTER) {\n return ret;\n } else if (ret !== undefined) {\n promise._setReturnedNonUndefined();\n var maybePromise = tryConvertToPromise(ret, promise);\n if (maybePromise instanceof Promise) {\n if (this.cancelPromise != null) {\n if (maybePromise._isCancelled()) {\n var reason =\n new CancellationError(\"late cancellation observer\");\n promise._attachExtraTrace(reason);\n errorObj.e = reason;\n return errorObj;\n } else if (maybePromise.isPending()) {\n maybePromise._attachCancellationCallback(\n new FinallyHandlerCancelReaction(this));\n }\n }\n return maybePromise._then(\n succeed, fail, undefined, this, undefined);\n }\n }\n }\n\n if (promise.isRejected()) {\n checkCancel(this);\n errorObj.e = reasonOrValue;\n return errorObj;\n } else {\n checkCancel(this);\n return reasonOrValue;\n }\n}\n\nPromise.prototype._passThrough = function(handler, type, success, fail) {\n if (typeof handler !== \"function\") return this.then();\n return this._then(success,\n fail,\n undefined,\n new PassThroughHandlerContext(this, type, handler),\n undefined);\n};\n\nPromise.prototype.lastly =\nPromise.prototype[\"finally\"] = function (handler) {\n return this._passThrough(handler,\n 0,\n finallyHandler,\n finallyHandler);\n};\n\n\nPromise.prototype.tap = function (handler) {\n return this._passThrough(handler, 1, finallyHandler);\n};\n\nPromise.prototype.tapCatch = function (handlerOrPredicate) {\n var len = arguments.length;\n if(len === 1) {\n return this._passThrough(handlerOrPredicate,\n 1,\n undefined,\n finallyHandler);\n } else {\n var catchInstances = new Array(len - 1),\n j = 0, i;\n for (i = 0; i < len - 1; ++i) {\n var item = arguments[i];\n if (util.isObject(item)) {\n catchInstances[j++] = item;\n } else {\n return Promise.reject(new TypeError(\n \"tapCatch statement predicate: \"\n + \"expecting an object but got \" + util.classString(item)\n ));\n }\n }\n catchInstances.length = j;\n var handler = arguments[i];\n return this._passThrough(catchFilter(catchInstances, handler, this),\n 1,\n undefined,\n finallyHandler);\n }\n\n};\n\nreturn PassThroughHandlerContext;\n};\n","\"use strict\";\nvar util = require(\"./util\");\nvar maybeWrapAsError = util.maybeWrapAsError;\nvar errors = require(\"./errors\");\nvar OperationalError = errors.OperationalError;\nvar es5 = require(\"./es5\");\n\nfunction isUntypedError(obj) {\n return obj instanceof Error &&\n es5.getPrototypeOf(obj) === Error.prototype;\n}\n\nvar rErrorKey = /^(?:name|message|stack|cause)$/;\nfunction wrapAsOperationalError(obj) {\n var ret;\n if (isUntypedError(obj)) {\n ret = new OperationalError(obj);\n ret.name = obj.name;\n ret.message = obj.message;\n ret.stack = obj.stack;\n var keys = es5.keys(obj);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n if (!rErrorKey.test(key)) {\n ret[key] = obj[key];\n }\n }\n return ret;\n }\n util.markAsOriginatingFromRejection(obj);\n return obj;\n}\n\nfunction nodebackForPromise(promise, multiArgs) {\n return function(err, value) {\n if (promise === null) return;\n if (err) {\n var wrapped = wrapAsOperationalError(maybeWrapAsError(err));\n promise._attachExtraTrace(wrapped);\n promise._reject(wrapped);\n } else if (!multiArgs) {\n promise._fulfill(value);\n } else {\n var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};\n promise._fulfill(args);\n }\n promise = null;\n };\n}\n\nmodule.exports = nodebackForPromise;\n","\"use strict\";\nmodule.exports =\nfunction(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {\nvar util = require(\"./util\");\nvar tryCatch = util.tryCatch;\n\nPromise.method = function (fn) {\n if (typeof fn !== \"function\") {\n throw new Promise.TypeError(\"expecting a function but got \" + util.classString(fn));\n }\n return function () {\n var ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n ret._pushContext();\n var value = tryCatch(fn).apply(this, arguments);\n var promiseCreated = ret._popContext();\n debug.checkForgottenReturns(\n value, promiseCreated, \"Promise.method\", ret);\n ret._resolveFromSyncValue(value);\n return ret;\n };\n};\n\nPromise.attempt = Promise[\"try\"] = function (fn) {\n if (typeof fn !== \"function\") {\n return apiRejection(\"expecting a function but got \" + util.classString(fn));\n }\n var ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n ret._pushContext();\n var value;\n if (arguments.length > 1) {\n debug.deprecated(\"calling Promise.try with more than 1 argument\");\n var arg = arguments[1];\n var ctx = arguments[2];\n value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)\n : tryCatch(fn).call(ctx, arg);\n } else {\n value = tryCatch(fn)();\n }\n var promiseCreated = ret._popContext();\n debug.checkForgottenReturns(\n value, promiseCreated, \"Promise.try\", ret);\n ret._resolveFromSyncValue(value);\n return ret;\n};\n\nPromise.prototype._resolveFromSyncValue = function (value) {\n if (value === util.errorObj) {\n this._rejectCallback(value.e, false);\n } else {\n this._resolveCallback(value, true);\n }\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {\nvar calledBind = false;\nvar rejectThis = function(_, e) {\n this._reject(e);\n};\n\nvar targetRejected = function(e, context) {\n context.promiseRejectionQueued = true;\n context.bindingPromise._then(rejectThis, rejectThis, null, this, e);\n};\n\nvar bindingResolved = function(thisArg, context) {\n if (((this._bitField & 50397184) === 0)) {\n this._resolveCallback(context.target);\n }\n};\n\nvar bindingRejected = function(e, context) {\n if (!context.promiseRejectionQueued) this._reject(e);\n};\n\nPromise.prototype.bind = function (thisArg) {\n if (!calledBind) {\n calledBind = true;\n Promise.prototype._propagateFrom = debug.propagateFromFunction();\n Promise.prototype._boundValue = debug.boundValueFunction();\n }\n var maybePromise = tryConvertToPromise(thisArg);\n var ret = new Promise(INTERNAL);\n ret._propagateFrom(this, 1);\n var target = this._target();\n ret._setBoundTo(maybePromise);\n if (maybePromise instanceof Promise) {\n var context = {\n promiseRejectionQueued: false,\n promise: ret,\n target: target,\n bindingPromise: maybePromise\n };\n target._then(INTERNAL, targetRejected, undefined, ret, context);\n maybePromise._then(\n bindingResolved, bindingRejected, undefined, ret, context);\n ret._setOnCancel(maybePromise);\n } else {\n ret._resolveCallback(target);\n }\n return ret;\n};\n\nPromise.prototype._setBoundTo = function (obj) {\n if (obj !== undefined) {\n this._bitField = this._bitField | 2097152;\n this._boundTo = obj;\n } else {\n this._bitField = this._bitField & (~2097152);\n }\n};\n\nPromise.prototype._isBound = function () {\n return (this._bitField & 2097152) === 2097152;\n};\n\nPromise.bind = function (thisArg, value) {\n return Promise.resolve(value).bind(thisArg);\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise, PromiseArray, apiRejection, debug) {\nvar util = require(\"./util\");\nvar tryCatch = util.tryCatch;\nvar errorObj = util.errorObj;\nvar async = Promise._async;\n\nPromise.prototype[\"break\"] = Promise.prototype.cancel = function() {\n if (!debug.cancellation()) return this._warn(\"cancellation is disabled\");\n\n var promise = this;\n var child = promise;\n while (promise._isCancellable()) {\n if (!promise._cancelBy(child)) {\n if (child._isFollowing()) {\n child._followee().cancel();\n } else {\n child._cancelBranched();\n }\n break;\n }\n\n var parent = promise._cancellationParent;\n if (parent == null || !parent._isCancellable()) {\n if (promise._isFollowing()) {\n promise._followee().cancel();\n } else {\n promise._cancelBranched();\n }\n break;\n } else {\n if (promise._isFollowing()) promise._followee().cancel();\n promise._setWillBeCancelled();\n child = promise;\n promise = parent;\n }\n }\n};\n\nPromise.prototype._branchHasCancelled = function() {\n this._branchesRemainingToCancel--;\n};\n\nPromise.prototype._enoughBranchesHaveCancelled = function() {\n return this._branchesRemainingToCancel === undefined ||\n this._branchesRemainingToCancel <= 0;\n};\n\nPromise.prototype._cancelBy = function(canceller) {\n if (canceller === this) {\n this._branchesRemainingToCancel = 0;\n this._invokeOnCancel();\n return true;\n } else {\n this._branchHasCancelled();\n if (this._enoughBranchesHaveCancelled()) {\n this._invokeOnCancel();\n return true;\n }\n }\n return false;\n};\n\nPromise.prototype._cancelBranched = function() {\n if (this._enoughBranchesHaveCancelled()) {\n this._cancel();\n }\n};\n\nPromise.prototype._cancel = function() {\n if (!this._isCancellable()) return;\n this._setCancelled();\n async.invoke(this._cancelPromises, this, undefined);\n};\n\nPromise.prototype._cancelPromises = function() {\n if (this._length() > 0) this._settlePromises();\n};\n\nPromise.prototype._unsetOnCancel = function() {\n this._onCancelField = undefined;\n};\n\nPromise.prototype._isCancellable = function() {\n return this.isPending() && !this._isCancelled();\n};\n\nPromise.prototype.isCancellable = function() {\n return this.isPending() && !this.isCancelled();\n};\n\nPromise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {\n if (util.isArray(onCancelCallback)) {\n for (var i = 0; i < onCancelCallback.length; ++i) {\n this._doInvokeOnCancel(onCancelCallback[i], internalOnly);\n }\n } else if (onCancelCallback !== undefined) {\n if (typeof onCancelCallback === \"function\") {\n if (!internalOnly) {\n var e = tryCatch(onCancelCallback).call(this._boundValue());\n if (e === errorObj) {\n this._attachExtraTrace(e.e);\n async.throwLater(e.e);\n }\n }\n } else {\n onCancelCallback._resultCancelled(this);\n }\n }\n};\n\nPromise.prototype._invokeOnCancel = function() {\n var onCancelCallback = this._onCancel();\n this._unsetOnCancel();\n async.invoke(this._doInvokeOnCancel, this, onCancelCallback);\n};\n\nPromise.prototype._invokeInternalOnCancel = function() {\n if (this._isCancellable()) {\n this._doInvokeOnCancel(this._onCancel(), true);\n this._unsetOnCancel();\n }\n};\n\nPromise.prototype._resultCancelled = function() {\n this.cancel();\n};\n\n};\n","\"use strict\";\nmodule.exports = function(Promise) {\nfunction returner() {\n return this.value;\n}\nfunction thrower() {\n throw this.reason;\n}\n\nPromise.prototype[\"return\"] =\nPromise.prototype.thenReturn = function (value) {\n if (value instanceof Promise) value.suppressUnhandledRejections();\n return this._then(\n returner, undefined, undefined, {value: value}, undefined);\n};\n\nPromise.prototype[\"throw\"] =\nPromise.prototype.thenThrow = function (reason) {\n return this._then(\n thrower, undefined, undefined, {reason: reason}, undefined);\n};\n\nPromise.prototype.catchThrow = function (reason) {\n if (arguments.length <= 1) {\n return this._then(\n undefined, thrower, undefined, {reason: reason}, undefined);\n } else {\n var _reason = arguments[1];\n var handler = function() {throw _reason;};\n return this.caught(reason, handler);\n }\n};\n\nPromise.prototype.catchReturn = function (value) {\n if (arguments.length <= 1) {\n if (value instanceof Promise) value.suppressUnhandledRejections();\n return this._then(\n undefined, returner, undefined, {value: value}, undefined);\n } else {\n var _value = arguments[1];\n if (_value instanceof Promise) _value.suppressUnhandledRejections();\n var handler = function() {return _value;};\n return this.caught(value, handler);\n }\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise) {\nfunction PromiseInspection(promise) {\n if (promise !== undefined) {\n promise = promise._target();\n this._bitField = promise._bitField;\n this._settledValueField = promise._isFateSealed()\n ? promise._settledValue() : undefined;\n }\n else {\n this._bitField = 0;\n this._settledValueField = undefined;\n }\n}\n\nPromiseInspection.prototype._settledValue = function() {\n return this._settledValueField;\n};\n\nvar value = PromiseInspection.prototype.value = function () {\n if (!this.isFulfilled()) {\n throw new TypeError(\"cannot get fulfillment value of a non-fulfilled promise\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n return this._settledValue();\n};\n\nvar reason = PromiseInspection.prototype.error =\nPromiseInspection.prototype.reason = function () {\n if (!this.isRejected()) {\n throw new TypeError(\"cannot get rejection reason of a non-rejected promise\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n return this._settledValue();\n};\n\nvar isFulfilled = PromiseInspection.prototype.isFulfilled = function() {\n return (this._bitField & 33554432) !== 0;\n};\n\nvar isRejected = PromiseInspection.prototype.isRejected = function () {\n return (this._bitField & 16777216) !== 0;\n};\n\nvar isPending = PromiseInspection.prototype.isPending = function () {\n return (this._bitField & 50397184) === 0;\n};\n\nvar isResolved = PromiseInspection.prototype.isResolved = function () {\n return (this._bitField & 50331648) !== 0;\n};\n\nPromiseInspection.prototype.isCancelled = function() {\n return (this._bitField & 8454144) !== 0;\n};\n\nPromise.prototype.__isCancelled = function() {\n return (this._bitField & 65536) === 65536;\n};\n\nPromise.prototype._isCancelled = function() {\n return this._target().__isCancelled();\n};\n\nPromise.prototype.isCancelled = function() {\n return (this._target()._bitField & 8454144) !== 0;\n};\n\nPromise.prototype.isPending = function() {\n return isPending.call(this._target());\n};\n\nPromise.prototype.isRejected = function() {\n return isRejected.call(this._target());\n};\n\nPromise.prototype.isFulfilled = function() {\n return isFulfilled.call(this._target());\n};\n\nPromise.prototype.isResolved = function() {\n return isResolved.call(this._target());\n};\n\nPromise.prototype.value = function() {\n return value.call(this._target());\n};\n\nPromise.prototype.reason = function() {\n var target = this._target();\n target._unsetRejectionIsUnhandled();\n return reason.call(target);\n};\n\nPromise.prototype._value = function() {\n return this._settledValue();\n};\n\nPromise.prototype._reason = function() {\n this._unsetRejectionIsUnhandled();\n return this._settledValue();\n};\n\nPromise.PromiseInspection = PromiseInspection;\n};\n","\"use strict\";\nmodule.exports =\nfunction(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {\nvar util = require(\"./util\");\nvar canEvaluate = util.canEvaluate;\nvar tryCatch = util.tryCatch;\nvar errorObj = util.errorObj;\nvar reject;\n\nif (!false) {\nif (canEvaluate) {\n var thenCallback = function(i) {\n return new Function(\"value\", \"holder\", \" \\n\\\n 'use strict'; \\n\\\n holder.pIndex = value; \\n\\\n holder.checkFulfillment(this); \\n\\\n \".replace(/Index/g, i));\n };\n\n var promiseSetter = function(i) {\n return new Function(\"promise\", \"holder\", \" \\n\\\n 'use strict'; \\n\\\n holder.pIndex = promise; \\n\\\n \".replace(/Index/g, i));\n };\n\n var generateHolderClass = function(total) {\n var props = new Array(total);\n for (var i = 0; i < props.length; ++i) {\n props[i] = \"this.p\" + (i+1);\n }\n var assignment = props.join(\" = \") + \" = null;\";\n var cancellationCode= \"var promise;\\n\" + props.map(function(prop) {\n return \" \\n\\\n promise = \" + prop + \"; \\n\\\n if (promise instanceof Promise) { \\n\\\n promise.cancel(); \\n\\\n } \\n\\\n \";\n }).join(\"\\n\");\n var passedArguments = props.join(\", \");\n var name = \"Holder$\" + total;\n\n\n var code = \"return function(tryCatch, errorObj, Promise, async) { \\n\\\n 'use strict'; \\n\\\n function [TheName](fn) { \\n\\\n [TheProperties] \\n\\\n this.fn = fn; \\n\\\n this.asyncNeeded = true; \\n\\\n this.now = 0; \\n\\\n } \\n\\\n \\n\\\n [TheName].prototype._callFunction = function(promise) { \\n\\\n promise._pushContext(); \\n\\\n var ret = tryCatch(this.fn)([ThePassedArguments]); \\n\\\n promise._popContext(); \\n\\\n if (ret === errorObj) { \\n\\\n promise._rejectCallback(ret.e, false); \\n\\\n } else { \\n\\\n promise._resolveCallback(ret); \\n\\\n } \\n\\\n }; \\n\\\n \\n\\\n [TheName].prototype.checkFulfillment = function(promise) { \\n\\\n var now = ++this.now; \\n\\\n if (now === [TheTotal]) { \\n\\\n if (this.asyncNeeded) { \\n\\\n async.invoke(this._callFunction, this, promise); \\n\\\n } else { \\n\\\n this._callFunction(promise); \\n\\\n } \\n\\\n \\n\\\n } \\n\\\n }; \\n\\\n \\n\\\n [TheName].prototype._resultCancelled = function() { \\n\\\n [CancellationCode] \\n\\\n }; \\n\\\n \\n\\\n return [TheName]; \\n\\\n }(tryCatch, errorObj, Promise, async); \\n\\\n \";\n\n code = code.replace(/\\[TheName\\]/g, name)\n .replace(/\\[TheTotal\\]/g, total)\n .replace(/\\[ThePassedArguments\\]/g, passedArguments)\n .replace(/\\[TheProperties\\]/g, assignment)\n .replace(/\\[CancellationCode\\]/g, cancellationCode);\n\n return new Function(\"tryCatch\", \"errorObj\", \"Promise\", \"async\", code)\n (tryCatch, errorObj, Promise, async);\n };\n\n var holderClasses = [];\n var thenCallbacks = [];\n var promiseSetters = [];\n\n for (var i = 0; i < 8; ++i) {\n holderClasses.push(generateHolderClass(i + 1));\n thenCallbacks.push(thenCallback(i + 1));\n promiseSetters.push(promiseSetter(i + 1));\n }\n\n reject = function (reason) {\n this._reject(reason);\n };\n}}\n\nPromise.join = function () {\n var last = arguments.length - 1;\n var fn;\n if (last > 0 && typeof arguments[last] === \"function\") {\n fn = arguments[last];\n if (!false) {\n if (last <= 8 && canEvaluate) {\n var ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n var HolderClass = holderClasses[last - 1];\n var holder = new HolderClass(fn);\n var callbacks = thenCallbacks;\n\n for (var i = 0; i < last; ++i) {\n var maybePromise = tryConvertToPromise(arguments[i], ret);\n if (maybePromise instanceof Promise) {\n maybePromise = maybePromise._target();\n var bitField = maybePromise._bitField;\n ;\n if (((bitField & 50397184) === 0)) {\n maybePromise._then(callbacks[i], reject,\n undefined, ret, holder);\n promiseSetters[i](maybePromise, holder);\n holder.asyncNeeded = false;\n } else if (((bitField & 33554432) !== 0)) {\n callbacks[i].call(ret,\n maybePromise._value(), holder);\n } else if (((bitField & 16777216) !== 0)) {\n ret._reject(maybePromise._reason());\n } else {\n ret._cancel();\n }\n } else {\n callbacks[i].call(ret, maybePromise, holder);\n }\n }\n\n if (!ret._isFateSealed()) {\n if (holder.asyncNeeded) {\n var context = Promise._getContext();\n holder.fn = util.contextBind(context, holder.fn);\n }\n ret._setAsyncGuaranteed();\n ret._setOnCancel(holder);\n }\n return ret;\n }\n }\n }\n var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i ];};\n if (fn) args.pop();\n var ret = new PromiseArray(args).promise();\n return fn !== undefined ? ret.spread(fn) : ret;\n};\n\n};\n","\"use strict\";\nvar cr = Object.create;\nif (cr) {\n var callerCache = cr(null);\n var getterCache = cr(null);\n callerCache[\" size\"] = getterCache[\" size\"] = 0;\n}\n\nmodule.exports = function(Promise) {\nvar util = require(\"./util\");\nvar canEvaluate = util.canEvaluate;\nvar isIdentifier = util.isIdentifier;\n\nvar getMethodCaller;\nvar getGetter;\nif (!false) {\nvar makeMethodCaller = function (methodName) {\n return new Function(\"ensureMethod\", \" \\n\\\n return function(obj) { \\n\\\n 'use strict' \\n\\\n var len = this.length; \\n\\\n ensureMethod(obj, 'methodName'); \\n\\\n switch(len) { \\n\\\n case 1: return obj.methodName(this[0]); \\n\\\n case 2: return obj.methodName(this[0], this[1]); \\n\\\n case 3: return obj.methodName(this[0], this[1], this[2]); \\n\\\n case 0: return obj.methodName(); \\n\\\n default: \\n\\\n return obj.methodName.apply(obj, this); \\n\\\n } \\n\\\n }; \\n\\\n \".replace(/methodName/g, methodName))(ensureMethod);\n};\n\nvar makeGetter = function (propertyName) {\n return new Function(\"obj\", \" \\n\\\n 'use strict'; \\n\\\n return obj.propertyName; \\n\\\n \".replace(\"propertyName\", propertyName));\n};\n\nvar getCompiled = function(name, compiler, cache) {\n var ret = cache[name];\n if (typeof ret !== \"function\") {\n if (!isIdentifier(name)) {\n return null;\n }\n ret = compiler(name);\n cache[name] = ret;\n cache[\" size\"]++;\n if (cache[\" size\"] > 512) {\n var keys = Object.keys(cache);\n for (var i = 0; i < 256; ++i) delete cache[keys[i]];\n cache[\" size\"] = keys.length - 256;\n }\n }\n return ret;\n};\n\ngetMethodCaller = function(name) {\n return getCompiled(name, makeMethodCaller, callerCache);\n};\n\ngetGetter = function(name) {\n return getCompiled(name, makeGetter, getterCache);\n};\n}\n\nfunction ensureMethod(obj, methodName) {\n var fn;\n if (obj != null) fn = obj[methodName];\n if (typeof fn !== \"function\") {\n var message = \"Object \" + util.classString(obj) + \" has no method '\" +\n util.toString(methodName) + \"'\";\n throw new Promise.TypeError(message);\n }\n return fn;\n}\n\nfunction caller(obj) {\n var methodName = this.pop();\n var fn = ensureMethod(obj, methodName);\n return fn.apply(obj, this);\n}\nPromise.prototype.call = function (methodName) {\n var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};\n if (!false) {\n if (canEvaluate) {\n var maybeCaller = getMethodCaller(methodName);\n if (maybeCaller !== null) {\n return this._then(\n maybeCaller, undefined, undefined, args, undefined);\n }\n }\n }\n args.push(methodName);\n return this._then(caller, undefined, undefined, args, undefined);\n};\n\nfunction namedGetter(obj) {\n return obj[this];\n}\nfunction indexedGetter(obj) {\n var index = +this;\n if (index < 0) index = Math.max(0, index + obj.length);\n return obj[index];\n}\nPromise.prototype.get = function (propertyName) {\n var isIndex = (typeof propertyName === \"number\");\n var getter;\n if (!isIndex) {\n if (canEvaluate) {\n var maybeGetter = getGetter(propertyName);\n getter = maybeGetter !== null ? maybeGetter : namedGetter;\n } else {\n getter = namedGetter;\n }\n } else {\n getter = indexedGetter;\n }\n return this._then(getter, undefined, undefined, propertyName, undefined);\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise,\n apiRejection,\n INTERNAL,\n tryConvertToPromise,\n Proxyable,\n debug) {\nvar errors = require(\"./errors\");\nvar TypeError = errors.TypeError;\nvar util = require(\"./util\");\nvar errorObj = util.errorObj;\nvar tryCatch = util.tryCatch;\nvar yieldHandlers = [];\n\nfunction promiseFromYieldHandler(value, yieldHandlers, traceParent) {\n for (var i = 0; i < yieldHandlers.length; ++i) {\n traceParent._pushContext();\n var result = tryCatch(yieldHandlers[i])(value);\n traceParent._popContext();\n if (result === errorObj) {\n traceParent._pushContext();\n var ret = Promise.reject(errorObj.e);\n traceParent._popContext();\n return ret;\n }\n var maybePromise = tryConvertToPromise(result, traceParent);\n if (maybePromise instanceof Promise) return maybePromise;\n }\n return null;\n}\n\nfunction PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {\n if (debug.cancellation()) {\n var internal = new Promise(INTERNAL);\n var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);\n this._promise = internal.lastly(function() {\n return _finallyPromise;\n });\n internal._captureStackTrace();\n internal._setOnCancel(this);\n } else {\n var promise = this._promise = new Promise(INTERNAL);\n promise._captureStackTrace();\n }\n this._stack = stack;\n this._generatorFunction = generatorFunction;\n this._receiver = receiver;\n this._generator = undefined;\n this._yieldHandlers = typeof yieldHandler === \"function\"\n ? [yieldHandler].concat(yieldHandlers)\n : yieldHandlers;\n this._yieldedPromise = null;\n this._cancellationPhase = false;\n}\nutil.inherits(PromiseSpawn, Proxyable);\n\nPromiseSpawn.prototype._isResolved = function() {\n return this._promise === null;\n};\n\nPromiseSpawn.prototype._cleanup = function() {\n this._promise = this._generator = null;\n if (debug.cancellation() && this._finallyPromise !== null) {\n this._finallyPromise._fulfill();\n this._finallyPromise = null;\n }\n};\n\nPromiseSpawn.prototype._promiseCancelled = function() {\n if (this._isResolved()) return;\n var implementsReturn = typeof this._generator[\"return\"] !== \"undefined\";\n\n var result;\n if (!implementsReturn) {\n var reason = new Promise.CancellationError(\n \"generator .return() sentinel\");\n Promise.coroutine.returnSentinel = reason;\n this._promise._attachExtraTrace(reason);\n this._promise._pushContext();\n result = tryCatch(this._generator[\"throw\"]).call(this._generator,\n reason);\n this._promise._popContext();\n } else {\n this._promise._pushContext();\n result = tryCatch(this._generator[\"return\"]).call(this._generator,\n undefined);\n this._promise._popContext();\n }\n this._cancellationPhase = true;\n this._yieldedPromise = null;\n this._continue(result);\n};\n\nPromiseSpawn.prototype._promiseFulfilled = function(value) {\n this._yieldedPromise = null;\n this._promise._pushContext();\n var result = tryCatch(this._generator.next).call(this._generator, value);\n this._promise._popContext();\n this._continue(result);\n};\n\nPromiseSpawn.prototype._promiseRejected = function(reason) {\n this._yieldedPromise = null;\n this._promise._attachExtraTrace(reason);\n this._promise._pushContext();\n var result = tryCatch(this._generator[\"throw\"])\n .call(this._generator, reason);\n this._promise._popContext();\n this._continue(result);\n};\n\nPromiseSpawn.prototype._resultCancelled = function() {\n if (this._yieldedPromise instanceof Promise) {\n var promise = this._yieldedPromise;\n this._yieldedPromise = null;\n promise.cancel();\n }\n};\n\nPromiseSpawn.prototype.promise = function () {\n return this._promise;\n};\n\nPromiseSpawn.prototype._run = function () {\n this._generator = this._generatorFunction.call(this._receiver);\n this._receiver =\n this._generatorFunction = undefined;\n this._promiseFulfilled(undefined);\n};\n\nPromiseSpawn.prototype._continue = function (result) {\n var promise = this._promise;\n if (result === errorObj) {\n this._cleanup();\n if (this._cancellationPhase) {\n return promise.cancel();\n } else {\n return promise._rejectCallback(result.e, false);\n }\n }\n\n var value = result.value;\n if (result.done === true) {\n this._cleanup();\n if (this._cancellationPhase) {\n return promise.cancel();\n } else {\n return promise._resolveCallback(value);\n }\n } else {\n var maybePromise = tryConvertToPromise(value, this._promise);\n if (!(maybePromise instanceof Promise)) {\n maybePromise =\n promiseFromYieldHandler(maybePromise,\n this._yieldHandlers,\n this._promise);\n if (maybePromise === null) {\n this._promiseRejected(\n new TypeError(\n \"A value %s was yielded that could not be treated as a promise\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\\u000a\".replace(\"%s\", String(value)) +\n \"From coroutine:\\u000a\" +\n this._stack.split(\"\\n\").slice(1, -7).join(\"\\n\")\n )\n );\n return;\n }\n }\n maybePromise = maybePromise._target();\n var bitField = maybePromise._bitField;\n ;\n if (((bitField & 50397184) === 0)) {\n this._yieldedPromise = maybePromise;\n maybePromise._proxy(this, null);\n } else if (((bitField & 33554432) !== 0)) {\n Promise._async.invoke(\n this._promiseFulfilled, this, maybePromise._value()\n );\n } else if (((bitField & 16777216) !== 0)) {\n Promise._async.invoke(\n this._promiseRejected, this, maybePromise._reason()\n );\n } else {\n this._promiseCancelled();\n }\n }\n};\n\nPromise.coroutine = function (generatorFunction, options) {\n if (typeof generatorFunction !== \"function\") {\n throw new TypeError(\"generatorFunction must be a function\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n var yieldHandler = Object(options).yieldHandler;\n var PromiseSpawn$ = PromiseSpawn;\n var stack = new Error().stack;\n return function () {\n var generator = generatorFunction.apply(this, arguments);\n var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,\n stack);\n var ret = spawn.promise();\n spawn._generator = generator;\n spawn._promiseFulfilled(undefined);\n return ret;\n };\n};\n\nPromise.coroutine.addYieldHandler = function(fn) {\n if (typeof fn !== \"function\") {\n throw new TypeError(\"expecting a function but got \" + util.classString(fn));\n }\n yieldHandlers.push(fn);\n};\n\nPromise.spawn = function (generatorFunction) {\n debug.deprecated(\"Promise.spawn()\", \"Promise.coroutine()\");\n if (typeof generatorFunction !== \"function\") {\n return apiRejection(\"generatorFunction must be a function\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n var spawn = new PromiseSpawn(generatorFunction, this);\n var ret = spawn.promise();\n spawn._run(Promise.spawn);\n return ret;\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise,\n PromiseArray,\n apiRejection,\n tryConvertToPromise,\n INTERNAL,\n debug) {\nvar util = require(\"./util\");\nvar tryCatch = util.tryCatch;\nvar errorObj = util.errorObj;\nvar async = Promise._async;\n\nfunction MappingPromiseArray(promises, fn, limit, _filter) {\n this.constructor$(promises);\n this._promise._captureStackTrace();\n var context = Promise._getContext();\n this._callback = util.contextBind(context, fn);\n this._preservedValues = _filter === INTERNAL\n ? new Array(this.length())\n : null;\n this._limit = limit;\n this._inFlight = 0;\n this._queue = [];\n async.invoke(this._asyncInit, this, undefined);\n if (util.isArray(promises)) {\n for (var i = 0; i < promises.length; ++i) {\n var maybePromise = promises[i];\n if (maybePromise instanceof Promise) {\n maybePromise.suppressUnhandledRejections();\n }\n }\n }\n}\nutil.inherits(MappingPromiseArray, PromiseArray);\n\nMappingPromiseArray.prototype._asyncInit = function() {\n this._init$(undefined, -2);\n};\n\nMappingPromiseArray.prototype._init = function () {};\n\nMappingPromiseArray.prototype._promiseFulfilled = function (value, index) {\n var values = this._values;\n var length = this.length();\n var preservedValues = this._preservedValues;\n var limit = this._limit;\n\n if (index < 0) {\n index = (index * -1) - 1;\n values[index] = value;\n if (limit >= 1) {\n this._inFlight--;\n this._drainQueue();\n if (this._isResolved()) return true;\n }\n } else {\n if (limit >= 1 && this._inFlight >= limit) {\n values[index] = value;\n this._queue.push(index);\n return false;\n }\n if (preservedValues !== null) preservedValues[index] = value;\n\n var promise = this._promise;\n var callback = this._callback;\n var receiver = promise._boundValue();\n promise._pushContext();\n var ret = tryCatch(callback).call(receiver, value, index, length);\n var promiseCreated = promise._popContext();\n debug.checkForgottenReturns(\n ret,\n promiseCreated,\n preservedValues !== null ? \"Promise.filter\" : \"Promise.map\",\n promise\n );\n if (ret === errorObj) {\n this._reject(ret.e);\n return true;\n }\n\n var maybePromise = tryConvertToPromise(ret, this._promise);\n if (maybePromise instanceof Promise) {\n maybePromise = maybePromise._target();\n var bitField = maybePromise._bitField;\n ;\n if (((bitField & 50397184) === 0)) {\n if (limit >= 1) this._inFlight++;\n values[index] = maybePromise;\n maybePromise._proxy(this, (index + 1) * -1);\n return false;\n } else if (((bitField & 33554432) !== 0)) {\n ret = maybePromise._value();\n } else if (((bitField & 16777216) !== 0)) {\n this._reject(maybePromise._reason());\n return true;\n } else {\n this._cancel();\n return true;\n }\n }\n values[index] = ret;\n }\n var totalResolved = ++this._totalResolved;\n if (totalResolved >= length) {\n if (preservedValues !== null) {\n this._filter(values, preservedValues);\n } else {\n this._resolve(values);\n }\n return true;\n }\n return false;\n};\n\nMappingPromiseArray.prototype._drainQueue = function () {\n var queue = this._queue;\n var limit = this._limit;\n var values = this._values;\n while (queue.length > 0 && this._inFlight < limit) {\n if (this._isResolved()) return;\n var index = queue.pop();\n this._promiseFulfilled(values[index], index);\n }\n};\n\nMappingPromiseArray.prototype._filter = function (booleans, values) {\n var len = values.length;\n var ret = new Array(len);\n var j = 0;\n for (var i = 0; i < len; ++i) {\n if (booleans[i]) ret[j++] = values[i];\n }\n ret.length = j;\n this._resolve(ret);\n};\n\nMappingPromiseArray.prototype.preservedValues = function () {\n return this._preservedValues;\n};\n\nfunction map(promises, fn, options, _filter) {\n if (typeof fn !== \"function\") {\n return apiRejection(\"expecting a function but got \" + util.classString(fn));\n }\n\n var limit = 0;\n if (options !== undefined) {\n if (typeof options === \"object\" && options !== null) {\n if (typeof options.concurrency !== \"number\") {\n return Promise.reject(\n new TypeError(\"'concurrency' must be a number but it is \" +\n util.classString(options.concurrency)));\n }\n limit = options.concurrency;\n } else {\n return Promise.reject(new TypeError(\n \"options argument must be an object but it is \" +\n util.classString(options)));\n }\n }\n limit = typeof limit === \"number\" &&\n isFinite(limit) && limit >= 1 ? limit : 0;\n return new MappingPromiseArray(promises, fn, limit, _filter).promise();\n}\n\nPromise.prototype.map = function (fn, options) {\n return map(this, fn, options, null);\n};\n\nPromise.map = function (promises, fn, options, _filter) {\n return map(promises, fn, options, _filter);\n};\n\n\n};\n","\"use strict\";\nmodule.exports = function(Promise) {\nvar util = require(\"./util\");\nvar async = Promise._async;\nvar tryCatch = util.tryCatch;\nvar errorObj = util.errorObj;\n\nfunction spreadAdapter(val, nodeback) {\n var promise = this;\n if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);\n var ret =\n tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));\n if (ret === errorObj) {\n async.throwLater(ret.e);\n }\n}\n\nfunction successAdapter(val, nodeback) {\n var promise = this;\n var receiver = promise._boundValue();\n var ret = val === undefined\n ? tryCatch(nodeback).call(receiver, null)\n : tryCatch(nodeback).call(receiver, null, val);\n if (ret === errorObj) {\n async.throwLater(ret.e);\n }\n}\nfunction errorAdapter(reason, nodeback) {\n var promise = this;\n if (!reason) {\n var newReason = new Error(reason + \"\");\n newReason.cause = reason;\n reason = newReason;\n }\n var ret = tryCatch(nodeback).call(promise._boundValue(), reason);\n if (ret === errorObj) {\n async.throwLater(ret.e);\n }\n}\n\nPromise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,\n options) {\n if (typeof nodeback == \"function\") {\n var adapter = successAdapter;\n if (options !== undefined && Object(options).spread) {\n adapter = spreadAdapter;\n }\n this._then(\n adapter,\n errorAdapter,\n undefined,\n this,\n nodeback\n );\n }\n return this;\n};\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL) {\nvar THIS = {};\nvar util = require(\"./util\");\nvar nodebackForPromise = require(\"./nodeback\");\nvar withAppended = util.withAppended;\nvar maybeWrapAsError = util.maybeWrapAsError;\nvar canEvaluate = util.canEvaluate;\nvar TypeError = require(\"./errors\").TypeError;\nvar defaultSuffix = \"Async\";\nvar defaultPromisified = {__isPromisified__: true};\nvar noCopyProps = [\n \"arity\", \"length\",\n \"name\",\n \"arguments\",\n \"caller\",\n \"callee\",\n \"prototype\",\n \"__isPromisified__\"\n];\nvar noCopyPropsPattern = new RegExp(\"^(?:\" + noCopyProps.join(\"|\") + \")$\");\n\nvar defaultFilter = function(name) {\n return util.isIdentifier(name) &&\n name.charAt(0) !== \"_\" &&\n name !== \"constructor\";\n};\n\nfunction propsFilter(key) {\n return !noCopyPropsPattern.test(key);\n}\n\nfunction isPromisified(fn) {\n try {\n return fn.__isPromisified__ === true;\n }\n catch (e) {\n return false;\n }\n}\n\nfunction hasPromisified(obj, key, suffix) {\n var val = util.getDataPropertyOrDefault(obj, key + suffix,\n defaultPromisified);\n return val ? isPromisified(val) : false;\n}\nfunction checkValid(ret, suffix, suffixRegexp) {\n for (var i = 0; i < ret.length; i += 2) {\n var key = ret[i];\n if (suffixRegexp.test(key)) {\n var keyWithoutAsyncSuffix = key.replace(suffixRegexp, \"\");\n for (var j = 0; j < ret.length; j += 2) {\n if (ret[j] === keyWithoutAsyncSuffix) {\n throw new TypeError(\"Cannot promisify an API that has normal methods with '%s'-suffix\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\"\n .replace(\"%s\", suffix));\n }\n }\n }\n }\n}\n\nfunction promisifiableMethods(obj, suffix, suffixRegexp, filter) {\n var keys = util.inheritedDataKeys(obj);\n var ret = [];\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n var value = obj[key];\n var passesDefaultFilter = filter === defaultFilter\n ? true : defaultFilter(key, value, obj);\n if (typeof value === \"function\" &&\n !isPromisified(value) &&\n !hasPromisified(obj, key, suffix) &&\n filter(key, value, obj, passesDefaultFilter)) {\n ret.push(key, value);\n }\n }\n checkValid(ret, suffix, suffixRegexp);\n return ret;\n}\n\nvar escapeIdentRegex = function(str) {\n return str.replace(/([$])/, \"\\\\$\");\n};\n\nvar makeNodePromisifiedEval;\nif (!false) {\nvar switchCaseArgumentOrder = function(likelyArgumentCount) {\n var ret = [likelyArgumentCount];\n var min = Math.max(0, likelyArgumentCount - 1 - 3);\n for(var i = likelyArgumentCount - 1; i >= min; --i) {\n ret.push(i);\n }\n for(var i = likelyArgumentCount + 1; i <= 3; ++i) {\n ret.push(i);\n }\n return ret;\n};\n\nvar argumentSequence = function(argumentCount) {\n return util.filledRange(argumentCount, \"_arg\", \"\");\n};\n\nvar parameterDeclaration = function(parameterCount) {\n return util.filledRange(\n Math.max(parameterCount, 3), \"_arg\", \"\");\n};\n\nvar parameterCount = function(fn) {\n if (typeof fn.length === \"number\") {\n return Math.max(Math.min(fn.length, 1023 + 1), 0);\n }\n return 0;\n};\n\nmakeNodePromisifiedEval =\nfunction(callback, receiver, originalName, fn, _, multiArgs) {\n var newParameterCount = Math.max(0, parameterCount(fn) - 1);\n var argumentOrder = switchCaseArgumentOrder(newParameterCount);\n var shouldProxyThis = typeof callback === \"string\" || receiver === THIS;\n\n function generateCallForArgumentCount(count) {\n var args = argumentSequence(count).join(\", \");\n var comma = count > 0 ? \", \" : \"\";\n var ret;\n if (shouldProxyThis) {\n ret = \"ret = callback.call(this, {{args}}, nodeback); break;\\n\";\n } else {\n ret = receiver === undefined\n ? \"ret = callback({{args}}, nodeback); break;\\n\"\n : \"ret = callback.call(receiver, {{args}}, nodeback); break;\\n\";\n }\n return ret.replace(\"{{args}}\", args).replace(\", \", comma);\n }\n\n function generateArgumentSwitchCase() {\n var ret = \"\";\n for (var i = 0; i < argumentOrder.length; ++i) {\n ret += \"case \" + argumentOrder[i] +\":\" +\n generateCallForArgumentCount(argumentOrder[i]);\n }\n\n ret += \" \\n\\\n default: \\n\\\n var args = new Array(len + 1); \\n\\\n var i = 0; \\n\\\n for (var i = 0; i < len; ++i) { \\n\\\n args[i] = arguments[i]; \\n\\\n } \\n\\\n args[i] = nodeback; \\n\\\n [CodeForCall] \\n\\\n break; \\n\\\n \".replace(\"[CodeForCall]\", (shouldProxyThis\n ? \"ret = callback.apply(this, args);\\n\"\n : \"ret = callback.apply(receiver, args);\\n\"));\n return ret;\n }\n\n var getFunctionCode = typeof callback === \"string\"\n ? (\"this != null ? this['\"+callback+\"'] : fn\")\n : \"fn\";\n var body = \"'use strict'; \\n\\\n var ret = function (Parameters) { \\n\\\n 'use strict'; \\n\\\n var len = arguments.length; \\n\\\n var promise = new Promise(INTERNAL); \\n\\\n promise._captureStackTrace(); \\n\\\n var nodeback = nodebackForPromise(promise, \" + multiArgs + \"); \\n\\\n var ret; \\n\\\n var callback = tryCatch([GetFunctionCode]); \\n\\\n switch(len) { \\n\\\n [CodeForSwitchCase] \\n\\\n } \\n\\\n if (ret === errorObj) { \\n\\\n promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\\n\\\n } \\n\\\n if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \\n\\\n return promise; \\n\\\n }; \\n\\\n notEnumerableProp(ret, '__isPromisified__', true); \\n\\\n return ret; \\n\\\n \".replace(\"[CodeForSwitchCase]\", generateArgumentSwitchCase())\n .replace(\"[GetFunctionCode]\", getFunctionCode);\n body = body.replace(\"Parameters\", parameterDeclaration(newParameterCount));\n return new Function(\"Promise\",\n \"fn\",\n \"receiver\",\n \"withAppended\",\n \"maybeWrapAsError\",\n \"nodebackForPromise\",\n \"tryCatch\",\n \"errorObj\",\n \"notEnumerableProp\",\n \"INTERNAL\",\n body)(\n Promise,\n fn,\n receiver,\n withAppended,\n maybeWrapAsError,\n nodebackForPromise,\n util.tryCatch,\n util.errorObj,\n util.notEnumerableProp,\n INTERNAL);\n};\n}\n\nfunction makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {\n var defaultThis = (function() {return this;})();\n var method = callback;\n if (typeof method === \"string\") {\n callback = fn;\n }\n function promisified() {\n var _receiver = receiver;\n if (receiver === THIS) _receiver = this;\n var promise = new Promise(INTERNAL);\n promise._captureStackTrace();\n var cb = typeof method === \"string\" && this !== defaultThis\n ? this[method] : callback;\n var fn = nodebackForPromise(promise, multiArgs);\n try {\n cb.apply(_receiver, withAppended(arguments, fn));\n } catch(e) {\n promise._rejectCallback(maybeWrapAsError(e), true, true);\n }\n if (!promise._isFateSealed()) promise._setAsyncGuaranteed();\n return promise;\n }\n util.notEnumerableProp(promisified, \"__isPromisified__\", true);\n return promisified;\n}\n\nvar makeNodePromisified = canEvaluate\n ? makeNodePromisifiedEval\n : makeNodePromisifiedClosure;\n\nfunction promisifyAll(obj, suffix, filter, promisifier, multiArgs) {\n var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + \"$\");\n var methods =\n promisifiableMethods(obj, suffix, suffixRegexp, filter);\n\n for (var i = 0, len = methods.length; i < len; i+= 2) {\n var key = methods[i];\n var fn = methods[i+1];\n var promisifiedKey = key + suffix;\n if (promisifier === makeNodePromisified) {\n obj[promisifiedKey] =\n makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);\n } else {\n var promisified = promisifier(fn, function() {\n return makeNodePromisified(key, THIS, key,\n fn, suffix, multiArgs);\n });\n util.notEnumerableProp(promisified, \"__isPromisified__\", true);\n obj[promisifiedKey] = promisified;\n }\n }\n util.toFastProperties(obj);\n return obj;\n}\n\nfunction promisify(callback, receiver, multiArgs) {\n return makeNodePromisified(callback, receiver, undefined,\n callback, null, multiArgs);\n}\n\nPromise.promisify = function (fn, options) {\n if (typeof fn !== \"function\") {\n throw new TypeError(\"expecting a function but got \" + util.classString(fn));\n }\n if (isPromisified(fn)) {\n return fn;\n }\n options = Object(options);\n var receiver = options.context === undefined ? THIS : options.context;\n var multiArgs = !!options.multiArgs;\n var ret = promisify(fn, receiver, multiArgs);\n util.copyDescriptors(fn, ret, propsFilter);\n return ret;\n};\n\nPromise.promisifyAll = function (target, options) {\n if (typeof target !== \"function\" && typeof target !== \"object\") {\n throw new TypeError(\"the target of promisifyAll must be an object or a function\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n options = Object(options);\n var multiArgs = !!options.multiArgs;\n var suffix = options.suffix;\n if (typeof suffix !== \"string\") suffix = defaultSuffix;\n var filter = options.filter;\n if (typeof filter !== \"function\") filter = defaultFilter;\n var promisifier = options.promisifier;\n if (typeof promisifier !== \"function\") promisifier = makeNodePromisified;\n\n if (!util.isIdentifier(suffix)) {\n throw new RangeError(\"suffix must be a valid identifier\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n\n var keys = util.inheritedDataKeys(target);\n for (var i = 0; i < keys.length; ++i) {\n var value = target[keys[i]];\n if (keys[i] !== \"constructor\" &&\n util.isClass(value)) {\n promisifyAll(value.prototype, suffix, filter, promisifier,\n multiArgs);\n promisifyAll(value, suffix, filter, promisifier, multiArgs);\n }\n }\n\n return promisifyAll(target, suffix, filter, promisifier, multiArgs);\n};\n};\n\n","\"use strict\";\nmodule.exports = function(\n Promise, PromiseArray, tryConvertToPromise, apiRejection) {\nvar util = require(\"./util\");\nvar isObject = util.isObject;\nvar es5 = require(\"./es5\");\nvar Es6Map;\nif (typeof Map === \"function\") Es6Map = Map;\n\nvar mapToEntries = (function() {\n var index = 0;\n var size = 0;\n\n function extractEntry(value, key) {\n this[index] = value;\n this[index + size] = key;\n index++;\n }\n\n return function mapToEntries(map) {\n size = map.size;\n index = 0;\n var ret = new Array(map.size * 2);\n map.forEach(extractEntry, ret);\n return ret;\n };\n})();\n\nvar entriesToMap = function(entries) {\n var ret = new Es6Map();\n var length = entries.length / 2 | 0;\n for (var i = 0; i < length; ++i) {\n var key = entries[length + i];\n var value = entries[i];\n ret.set(key, value);\n }\n return ret;\n};\n\nfunction PropertiesPromiseArray(obj) {\n var isMap = false;\n var entries;\n if (Es6Map !== undefined && obj instanceof Es6Map) {\n entries = mapToEntries(obj);\n isMap = true;\n } else {\n var keys = es5.keys(obj);\n var len = keys.length;\n entries = new Array(len * 2);\n for (var i = 0; i < len; ++i) {\n var key = keys[i];\n entries[i] = obj[key];\n entries[i + len] = key;\n }\n }\n this.constructor$(entries);\n this._isMap = isMap;\n this._init$(undefined, isMap ? -6 : -3);\n}\nutil.inherits(PropertiesPromiseArray, PromiseArray);\n\nPropertiesPromiseArray.prototype._init = function () {};\n\nPropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {\n this._values[index] = value;\n var totalResolved = ++this._totalResolved;\n if (totalResolved >= this._length) {\n var val;\n if (this._isMap) {\n val = entriesToMap(this._values);\n } else {\n val = {};\n var keyOffset = this.length();\n for (var i = 0, len = this.length(); i < len; ++i) {\n val[this._values[i + keyOffset]] = this._values[i];\n }\n }\n this._resolve(val);\n return true;\n }\n return false;\n};\n\nPropertiesPromiseArray.prototype.shouldCopyValues = function () {\n return false;\n};\n\nPropertiesPromiseArray.prototype.getActualLength = function (len) {\n return len >> 1;\n};\n\nfunction props(promises) {\n var ret;\n var castValue = tryConvertToPromise(promises);\n\n if (!isObject(castValue)) {\n return apiRejection(\"cannot await properties of a non-object\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n } else if (castValue instanceof Promise) {\n ret = castValue._then(\n Promise.props, undefined, undefined, undefined, undefined);\n } else {\n ret = new PropertiesPromiseArray(castValue).promise();\n }\n\n if (castValue instanceof Promise) {\n ret._propagateFrom(castValue, 2);\n }\n return ret;\n}\n\nPromise.prototype.props = function () {\n return props(this);\n};\n\nPromise.props = function (promises) {\n return props(promises);\n};\n};\n","\"use strict\";\nmodule.exports = function(\n Promise, INTERNAL, tryConvertToPromise, apiRejection) {\nvar util = require(\"./util\");\n\nvar raceLater = function (promise) {\n return promise.then(function(array) {\n return race(array, promise);\n });\n};\n\nfunction race(promises, parent) {\n var maybePromise = tryConvertToPromise(promises);\n\n if (maybePromise instanceof Promise) {\n return raceLater(maybePromise);\n } else {\n promises = util.asArray(promises);\n if (promises === null)\n return apiRejection(\"expecting an array or an iterable object but got \" + util.classString(promises));\n }\n\n var ret = new Promise(INTERNAL);\n if (parent !== undefined) {\n ret._propagateFrom(parent, 3);\n }\n var fulfill = ret._fulfill;\n var reject = ret._reject;\n for (var i = 0, len = promises.length; i < len; ++i) {\n var val = promises[i];\n\n if (val === undefined && !(i in promises)) {\n continue;\n }\n\n Promise.cast(val)._then(fulfill, reject, undefined, ret, null);\n }\n return ret;\n}\n\nPromise.race = function (promises) {\n return race(promises, undefined);\n};\n\nPromise.prototype.race = function () {\n return race(this, undefined);\n};\n\n};\n","\"use strict\";\nmodule.exports = function(Promise,\n PromiseArray,\n apiRejection,\n tryConvertToPromise,\n INTERNAL,\n debug) {\nvar util = require(\"./util\");\nvar tryCatch = util.tryCatch;\n\nfunction ReductionPromiseArray(promises, fn, initialValue, _each) {\n this.constructor$(promises);\n var context = Promise._getContext();\n this._fn = util.contextBind(context, fn);\n if (initialValue !== undefined) {\n initialValue = Promise.resolve(initialValue);\n initialValue._attachCancellationCallback(this);\n }\n this._initialValue = initialValue;\n this._currentCancellable = null;\n if(_each === INTERNAL) {\n this._eachValues = Array(this._length);\n } else if (_each === 0) {\n this._eachValues = null;\n } else {\n this._eachValues = undefined;\n }\n this._promise._captureStackTrace();\n this._init$(undefined, -5);\n}\nutil.inherits(ReductionPromiseArray, PromiseArray);\n\nReductionPromiseArray.prototype._gotAccum = function(accum) {\n if (this._eachValues !== undefined &&\n this._eachValues !== null &&\n accum !== INTERNAL) {\n this._eachValues.push(accum);\n }\n};\n\nReductionPromiseArray.prototype._eachComplete = function(value) {\n if (this._eachValues !== null) {\n this._eachValues.push(value);\n }\n return this._eachValues;\n};\n\nReductionPromiseArray.prototype._init = function() {};\n\nReductionPromiseArray.prototype._resolveEmptyArray = function() {\n this._resolve(this._eachValues !== undefined ? this._eachValues\n : this._initialValue);\n};\n\nReductionPromiseArray.prototype.shouldCopyValues = function () {\n return false;\n};\n\nReductionPromiseArray.prototype._resolve = function(value) {\n this._promise._resolveCallback(value);\n this._values = null;\n};\n\nReductionPromiseArray.prototype._resultCancelled = function(sender) {\n if (sender === this._initialValue) return this._cancel();\n if (this._isResolved()) return;\n this._resultCancelled$();\n if (this._currentCancellable instanceof Promise) {\n this._currentCancellable.cancel();\n }\n if (this._initialValue instanceof Promise) {\n this._initialValue.cancel();\n }\n};\n\nReductionPromiseArray.prototype._iterate = function (values) {\n this._values = values;\n var value;\n var i;\n var length = values.length;\n if (this._initialValue !== undefined) {\n value = this._initialValue;\n i = 0;\n } else {\n value = Promise.resolve(values[0]);\n i = 1;\n }\n\n this._currentCancellable = value;\n\n for (var j = i; j < length; ++j) {\n var maybePromise = values[j];\n if (maybePromise instanceof Promise) {\n maybePromise.suppressUnhandledRejections();\n }\n }\n\n if (!value.isRejected()) {\n for (; i < length; ++i) {\n var ctx = {\n accum: null,\n value: values[i],\n index: i,\n length: length,\n array: this\n };\n\n value = value._then(gotAccum, undefined, undefined, ctx, undefined);\n\n if ((i & 127) === 0) {\n value._setNoAsyncGuarantee();\n }\n }\n }\n\n if (this._eachValues !== undefined) {\n value = value\n ._then(this._eachComplete, undefined, undefined, this, undefined);\n }\n value._then(completed, completed, undefined, value, this);\n};\n\nPromise.prototype.reduce = function (fn, initialValue) {\n return reduce(this, fn, initialValue, null);\n};\n\nPromise.reduce = function (promises, fn, initialValue, _each) {\n return reduce(promises, fn, initialValue, _each);\n};\n\nfunction completed(valueOrReason, array) {\n if (this.isFulfilled()) {\n array._resolve(valueOrReason);\n } else {\n array._reject(valueOrReason);\n }\n}\n\nfunction reduce(promises, fn, initialValue, _each) {\n if (typeof fn !== \"function\") {\n return apiRejection(\"expecting a function but got \" + util.classString(fn));\n }\n var array = new ReductionPromiseArray(promises, fn, initialValue, _each);\n return array.promise();\n}\n\nfunction gotAccum(accum) {\n this.accum = accum;\n this.array._gotAccum(accum);\n var value = tryConvertToPromise(this.value, this.array._promise);\n if (value instanceof Promise) {\n this.array._currentCancellable = value;\n return value._then(gotValue, undefined, undefined, this, undefined);\n } else {\n return gotValue.call(this, value);\n }\n}\n\nfunction gotValue(value) {\n var array = this.array;\n var promise = array._promise;\n var fn = tryCatch(array._fn);\n promise._pushContext();\n var ret;\n if (array._eachValues !== undefined) {\n ret = fn.call(promise._boundValue(), value, this.index, this.length);\n } else {\n ret = fn.call(promise._boundValue(),\n this.accum, value, this.index, this.length);\n }\n if (ret instanceof Promise) {\n array._currentCancellable = ret;\n }\n var promiseCreated = promise._popContext();\n debug.checkForgottenReturns(\n ret,\n promiseCreated,\n array._eachValues !== undefined ? \"Promise.each\" : \"Promise.reduce\",\n promise\n );\n return ret;\n}\n};\n","\"use strict\";\nmodule.exports =\n function(Promise, PromiseArray, debug) {\nvar PromiseInspection = Promise.PromiseInspection;\nvar util = require(\"./util\");\n\nfunction SettledPromiseArray(values) {\n this.constructor$(values);\n}\nutil.inherits(SettledPromiseArray, PromiseArray);\n\nSettledPromiseArray.prototype._promiseResolved = function (index, inspection) {\n this._values[index] = inspection;\n var totalResolved = ++this._totalResolved;\n if (totalResolved >= this._length) {\n this._resolve(this._values);\n return true;\n }\n return false;\n};\n\nSettledPromiseArray.prototype._promiseFulfilled = function (value, index) {\n var ret = new PromiseInspection();\n ret._bitField = 33554432;\n ret._settledValueField = value;\n return this._promiseResolved(index, ret);\n};\nSettledPromiseArray.prototype._promiseRejected = function (reason, index) {\n var ret = new PromiseInspection();\n ret._bitField = 16777216;\n ret._settledValueField = reason;\n return this._promiseResolved(index, ret);\n};\n\nPromise.settle = function (promises) {\n debug.deprecated(\".settle()\", \".reflect()\");\n return new SettledPromiseArray(promises).promise();\n};\n\nPromise.allSettled = function (promises) {\n return new SettledPromiseArray(promises).promise();\n};\n\nPromise.prototype.settle = function () {\n return Promise.settle(this);\n};\n};\n","\"use strict\";\nmodule.exports =\nfunction(Promise, PromiseArray, apiRejection) {\nvar util = require(\"./util\");\nvar RangeError = require(\"./errors\").RangeError;\nvar AggregateError = require(\"./errors\").AggregateError;\nvar isArray = util.isArray;\nvar CANCELLATION = {};\n\n\nfunction SomePromiseArray(values) {\n this.constructor$(values);\n this._howMany = 0;\n this._unwrap = false;\n this._initialized = false;\n}\nutil.inherits(SomePromiseArray, PromiseArray);\n\nSomePromiseArray.prototype._init = function () {\n if (!this._initialized) {\n return;\n }\n if (this._howMany === 0) {\n this._resolve([]);\n return;\n }\n this._init$(undefined, -5);\n var isArrayResolved = isArray(this._values);\n if (!this._isResolved() &&\n isArrayResolved &&\n this._howMany > this._canPossiblyFulfill()) {\n this._reject(this._getRangeError(this.length()));\n }\n};\n\nSomePromiseArray.prototype.init = function () {\n this._initialized = true;\n this._init();\n};\n\nSomePromiseArray.prototype.setUnwrap = function () {\n this._unwrap = true;\n};\n\nSomePromiseArray.prototype.howMany = function () {\n return this._howMany;\n};\n\nSomePromiseArray.prototype.setHowMany = function (count) {\n this._howMany = count;\n};\n\nSomePromiseArray.prototype._promiseFulfilled = function (value) {\n this._addFulfilled(value);\n if (this._fulfilled() === this.howMany()) {\n this._values.length = this.howMany();\n if (this.howMany() === 1 && this._unwrap) {\n this._resolve(this._values[0]);\n } else {\n this._resolve(this._values);\n }\n return true;\n }\n return false;\n\n};\nSomePromiseArray.prototype._promiseRejected = function (reason) {\n this._addRejected(reason);\n return this._checkOutcome();\n};\n\nSomePromiseArray.prototype._promiseCancelled = function () {\n if (this._values instanceof Promise || this._values == null) {\n return this._cancel();\n }\n this._addRejected(CANCELLATION);\n return this._checkOutcome();\n};\n\nSomePromiseArray.prototype._checkOutcome = function() {\n if (this.howMany() > this._canPossiblyFulfill()) {\n var e = new AggregateError();\n for (var i = this.length(); i < this._values.length; ++i) {\n if (this._values[i] !== CANCELLATION) {\n e.push(this._values[i]);\n }\n }\n if (e.length > 0) {\n this._reject(e);\n } else {\n this._cancel();\n }\n return true;\n }\n return false;\n};\n\nSomePromiseArray.prototype._fulfilled = function () {\n return this._totalResolved;\n};\n\nSomePromiseArray.prototype._rejected = function () {\n return this._values.length - this.length();\n};\n\nSomePromiseArray.prototype._addRejected = function (reason) {\n this._values.push(reason);\n};\n\nSomePromiseArray.prototype._addFulfilled = function (value) {\n this._values[this._totalResolved++] = value;\n};\n\nSomePromiseArray.prototype._canPossiblyFulfill = function () {\n return this.length() - this._rejected();\n};\n\nSomePromiseArray.prototype._getRangeError = function (count) {\n var message = \"Input array must contain at least \" +\n this._howMany + \" items but contains only \" + count + \" items\";\n return new RangeError(message);\n};\n\nSomePromiseArray.prototype._resolveEmptyArray = function () {\n this._reject(this._getRangeError(0));\n};\n\nfunction some(promises, howMany) {\n if ((howMany | 0) !== howMany || howMany < 0) {\n return apiRejection(\"expecting a positive integer\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n var ret = new SomePromiseArray(promises);\n var promise = ret.promise();\n ret.setHowMany(howMany);\n ret.init();\n return promise;\n}\n\nPromise.some = function (promises, howMany) {\n return some(promises, howMany);\n};\n\nPromise.prototype.some = function (howMany) {\n return some(this, howMany);\n};\n\nPromise._SomePromiseArray = SomePromiseArray;\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL, debug) {\nvar util = require(\"./util\");\nvar TimeoutError = Promise.TimeoutError;\n\nfunction HandleWrapper(handle) {\n this.handle = handle;\n}\n\nHandleWrapper.prototype._resultCancelled = function() {\n clearTimeout(this.handle);\n};\n\nvar afterValue = function(value) { return delay(+this).thenReturn(value); };\nvar delay = Promise.delay = function (ms, value) {\n var ret;\n var handle;\n if (value !== undefined) {\n ret = Promise.resolve(value)\n ._then(afterValue, null, null, ms, undefined);\n if (debug.cancellation() && value instanceof Promise) {\n ret._setOnCancel(value);\n }\n } else {\n ret = new Promise(INTERNAL);\n handle = setTimeout(function() { ret._fulfill(); }, +ms);\n if (debug.cancellation()) {\n ret._setOnCancel(new HandleWrapper(handle));\n }\n ret._captureStackTrace();\n }\n ret._setAsyncGuaranteed();\n return ret;\n};\n\nPromise.prototype.delay = function (ms) {\n return delay(ms, this);\n};\n\nvar afterTimeout = function (promise, message, parent) {\n var err;\n if (typeof message !== \"string\") {\n if (message instanceof Error) {\n err = message;\n } else {\n err = new TimeoutError(\"operation timed out\");\n }\n } else {\n err = new TimeoutError(message);\n }\n util.markAsOriginatingFromRejection(err);\n promise._attachExtraTrace(err);\n promise._reject(err);\n\n if (parent != null) {\n parent.cancel();\n }\n};\n\nfunction successClear(value) {\n clearTimeout(this.handle);\n return value;\n}\n\nfunction failureClear(reason) {\n clearTimeout(this.handle);\n throw reason;\n}\n\nPromise.prototype.timeout = function (ms, message) {\n ms = +ms;\n var ret, parent;\n\n var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {\n if (ret.isPending()) {\n afterTimeout(ret, message, parent);\n }\n }, ms));\n\n if (debug.cancellation()) {\n parent = this.then();\n ret = parent._then(successClear, failureClear,\n undefined, handleWrapper, undefined);\n ret._setOnCancel(handleWrapper);\n } else {\n ret = this._then(successClear, failureClear,\n undefined, handleWrapper, undefined);\n }\n\n return ret;\n};\n\n};\n","\"use strict\";\nmodule.exports = function (Promise, apiRejection, tryConvertToPromise,\n createContext, INTERNAL, debug) {\n var util = require(\"./util\");\n var TypeError = require(\"./errors\").TypeError;\n var inherits = require(\"./util\").inherits;\n var errorObj = util.errorObj;\n var tryCatch = util.tryCatch;\n var NULL = {};\n\n function thrower(e) {\n setTimeout(function(){throw e;}, 0);\n }\n\n function castPreservingDisposable(thenable) {\n var maybePromise = tryConvertToPromise(thenable);\n if (maybePromise !== thenable &&\n typeof thenable._isDisposable === \"function\" &&\n typeof thenable._getDisposer === \"function\" &&\n thenable._isDisposable()) {\n maybePromise._setDisposable(thenable._getDisposer());\n }\n return maybePromise;\n }\n function dispose(resources, inspection) {\n var i = 0;\n var len = resources.length;\n var ret = new Promise(INTERNAL);\n function iterator() {\n if (i >= len) return ret._fulfill();\n var maybePromise = castPreservingDisposable(resources[i++]);\n if (maybePromise instanceof Promise &&\n maybePromise._isDisposable()) {\n try {\n maybePromise = tryConvertToPromise(\n maybePromise._getDisposer().tryDispose(inspection),\n resources.promise);\n } catch (e) {\n return thrower(e);\n }\n if (maybePromise instanceof Promise) {\n return maybePromise._then(iterator, thrower,\n null, null, null);\n }\n }\n iterator();\n }\n iterator();\n return ret;\n }\n\n function Disposer(data, promise, context) {\n this._data = data;\n this._promise = promise;\n this._context = context;\n }\n\n Disposer.prototype.data = function () {\n return this._data;\n };\n\n Disposer.prototype.promise = function () {\n return this._promise;\n };\n\n Disposer.prototype.resource = function () {\n if (this.promise().isFulfilled()) {\n return this.promise().value();\n }\n return NULL;\n };\n\n Disposer.prototype.tryDispose = function(inspection) {\n var resource = this.resource();\n var context = this._context;\n if (context !== undefined) context._pushContext();\n var ret = resource !== NULL\n ? this.doDispose(resource, inspection) : null;\n if (context !== undefined) context._popContext();\n this._promise._unsetDisposable();\n this._data = null;\n return ret;\n };\n\n Disposer.isDisposer = function (d) {\n return (d != null &&\n typeof d.resource === \"function\" &&\n typeof d.tryDispose === \"function\");\n };\n\n function FunctionDisposer(fn, promise, context) {\n this.constructor$(fn, promise, context);\n }\n inherits(FunctionDisposer, Disposer);\n\n FunctionDisposer.prototype.doDispose = function (resource, inspection) {\n var fn = this.data();\n return fn.call(resource, resource, inspection);\n };\n\n function maybeUnwrapDisposer(value) {\n if (Disposer.isDisposer(value)) {\n this.resources[this.index]._setDisposable(value);\n return value.promise();\n }\n return value;\n }\n\n function ResourceList(length) {\n this.length = length;\n this.promise = null;\n this[length-1] = null;\n }\n\n ResourceList.prototype._resultCancelled = function() {\n var len = this.length;\n for (var i = 0; i < len; ++i) {\n var item = this[i];\n if (item instanceof Promise) {\n item.cancel();\n }\n }\n };\n\n Promise.using = function () {\n var len = arguments.length;\n if (len < 2) return apiRejection(\n \"you must pass at least 2 arguments to Promise.using\");\n var fn = arguments[len - 1];\n if (typeof fn !== \"function\") {\n return apiRejection(\"expecting a function but got \" + util.classString(fn));\n }\n var input;\n var spreadArgs = true;\n if (len === 2 && Array.isArray(arguments[0])) {\n input = arguments[0];\n len = input.length;\n spreadArgs = false;\n } else {\n input = arguments;\n len--;\n }\n var resources = new ResourceList(len);\n for (var i = 0; i < len; ++i) {\n var resource = input[i];\n if (Disposer.isDisposer(resource)) {\n var disposer = resource;\n resource = resource.promise();\n resource._setDisposable(disposer);\n } else {\n var maybePromise = tryConvertToPromise(resource);\n if (maybePromise instanceof Promise) {\n resource =\n maybePromise._then(maybeUnwrapDisposer, null, null, {\n resources: resources,\n index: i\n }, undefined);\n }\n }\n resources[i] = resource;\n }\n\n var reflectedResources = new Array(resources.length);\n for (var i = 0; i < reflectedResources.length; ++i) {\n reflectedResources[i] = Promise.resolve(resources[i]).reflect();\n }\n\n var resultPromise = Promise.all(reflectedResources)\n .then(function(inspections) {\n for (var i = 0; i < inspections.length; ++i) {\n var inspection = inspections[i];\n if (inspection.isRejected()) {\n errorObj.e = inspection.error();\n return errorObj;\n } else if (!inspection.isFulfilled()) {\n resultPromise.cancel();\n return;\n }\n inspections[i] = inspection.value();\n }\n promise._pushContext();\n\n fn = tryCatch(fn);\n var ret = spreadArgs\n ? fn.apply(undefined, inspections) : fn(inspections);\n var promiseCreated = promise._popContext();\n debug.checkForgottenReturns(\n ret, promiseCreated, \"Promise.using\", promise);\n return ret;\n });\n\n var promise = resultPromise.lastly(function() {\n var inspection = new Promise.PromiseInspection(resultPromise);\n return dispose(resources, inspection);\n });\n resources.promise = promise;\n promise._setOnCancel(resources);\n return promise;\n };\n\n Promise.prototype._setDisposable = function (disposer) {\n this._bitField = this._bitField | 131072;\n this._disposer = disposer;\n };\n\n Promise.prototype._isDisposable = function () {\n return (this._bitField & 131072) > 0;\n };\n\n Promise.prototype._getDisposer = function () {\n return this._disposer;\n };\n\n Promise.prototype._unsetDisposable = function () {\n this._bitField = this._bitField & (~131072);\n this._disposer = undefined;\n };\n\n Promise.prototype.disposer = function (fn) {\n if (typeof fn === \"function\") {\n return new FunctionDisposer(fn, this, createContext());\n }\n throw new TypeError();\n };\n\n};\n","\"use strict\";\nmodule.exports = function(Promise) {\nvar SomePromiseArray = Promise._SomePromiseArray;\nfunction any(promises) {\n var ret = new SomePromiseArray(promises);\n var promise = ret.promise();\n ret.setHowMany(1);\n ret.setUnwrap();\n ret.init();\n return promise;\n}\n\nPromise.any = function (promises) {\n return any(promises);\n};\n\nPromise.prototype.any = function () {\n return any(this);\n};\n\n};\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL) {\nvar PromiseReduce = Promise.reduce;\nvar PromiseAll = Promise.all;\n\nfunction promiseAllThis() {\n return PromiseAll(this);\n}\n\nfunction PromiseMapSeries(promises, fn) {\n return PromiseReduce(promises, fn, INTERNAL, INTERNAL);\n}\n\nPromise.prototype.each = function (fn) {\n return PromiseReduce(this, fn, INTERNAL, 0)\n ._then(promiseAllThis, undefined, undefined, this, undefined);\n};\n\nPromise.prototype.mapSeries = function (fn) {\n return PromiseReduce(this, fn, INTERNAL, INTERNAL);\n};\n\nPromise.each = function (promises, fn) {\n return PromiseReduce(promises, fn, INTERNAL, 0)\n ._then(promiseAllThis, undefined, undefined, promises, undefined);\n};\n\nPromise.mapSeries = PromiseMapSeries;\n};\n\n","\"use strict\";\nmodule.exports = function(Promise, INTERNAL) {\nvar PromiseMap = Promise.map;\n\nPromise.prototype.filter = function (fn, options) {\n return PromiseMap(this, fn, options, INTERNAL);\n};\n\nPromise.filter = function (promises, fn, options) {\n return PromiseMap(promises, fn, options, INTERNAL);\n};\n};\n","\"use strict\";\nmodule.exports = function() {\nvar makeSelfResolutionError = function () {\n return new TypeError(\"circular promise resolution chain\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n};\nvar reflectHandler = function() {\n return new Promise.PromiseInspection(this._target());\n};\nvar apiRejection = function(msg) {\n return Promise.reject(new TypeError(msg));\n};\nfunction Proxyable() {}\nvar UNDEFINED_BINDING = {};\nvar util = require(\"./util\");\nutil.setReflectHandler(reflectHandler);\n\nvar getDomain = function() {\n var domain = process.domain;\n if (domain === undefined) {\n return null;\n }\n return domain;\n};\nvar getContextDefault = function() {\n return null;\n};\nvar getContextDomain = function() {\n return {\n domain: getDomain(),\n async: null\n };\n};\nvar AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?\n require(\"async_hooks\").AsyncResource : null;\nvar getContextAsyncHooks = function() {\n return {\n domain: getDomain(),\n async: new AsyncResource(\"Bluebird::Promise\")\n };\n};\nvar getContext = util.isNode ? getContextDomain : getContextDefault;\nutil.notEnumerableProp(Promise, \"_getContext\", getContext);\nvar enableAsyncHooks = function() {\n getContext = getContextAsyncHooks;\n util.notEnumerableProp(Promise, \"_getContext\", getContextAsyncHooks);\n};\nvar disableAsyncHooks = function() {\n getContext = getContextDomain;\n util.notEnumerableProp(Promise, \"_getContext\", getContextDomain);\n};\n\nvar es5 = require(\"./es5\");\nvar Async = require(\"./async\");\nvar async = new Async();\nes5.defineProperty(Promise, \"_async\", {value: async});\nvar errors = require(\"./errors\");\nvar TypeError = Promise.TypeError = errors.TypeError;\nPromise.RangeError = errors.RangeError;\nvar CancellationError = Promise.CancellationError = errors.CancellationError;\nPromise.TimeoutError = errors.TimeoutError;\nPromise.OperationalError = errors.OperationalError;\nPromise.RejectionError = errors.OperationalError;\nPromise.AggregateError = errors.AggregateError;\nvar INTERNAL = function(){};\nvar APPLY = {};\nvar NEXT_FILTER = {};\nvar tryConvertToPromise = require(\"./thenables\")(Promise, INTERNAL);\nvar PromiseArray =\n require(\"./promise_array\")(Promise, INTERNAL,\n tryConvertToPromise, apiRejection, Proxyable);\nvar Context = require(\"./context\")(Promise);\n /*jshint unused:false*/\nvar createContext = Context.create;\n\nvar debug = require(\"./debuggability\")(Promise, Context,\n enableAsyncHooks, disableAsyncHooks);\nvar CapturedTrace = debug.CapturedTrace;\nvar PassThroughHandlerContext =\n require(\"./finally\")(Promise, tryConvertToPromise, NEXT_FILTER);\nvar catchFilter = require(\"./catch_filter\")(NEXT_FILTER);\nvar nodebackForPromise = require(\"./nodeback\");\nvar errorObj = util.errorObj;\nvar tryCatch = util.tryCatch;\nfunction check(self, executor) {\n if (self == null || self.constructor !== Promise) {\n throw new TypeError(\"the promise constructor cannot be invoked directly\\u000a\\u000a See http://goo.gl/MqrFmX\\u000a\");\n }\n if (typeof executor !== \"function\") {\n throw new TypeError(\"expecting a function but got \" + util.classString(executor));\n }\n\n}\n\nfunction Promise(executor) {\n if (executor !== INTERNAL) {\n check(this, executor);\n }\n this._bitField = 0;\n this._fulfillmentHandler0 = undefined;\n this._rejectionHandler0 = undefined;\n this._promise0 = undefined;\n this._receiver0 = undefined;\n this._resolveFromExecutor(executor);\n this._promiseCreated();\n this._fireEvent(\"promiseCreated\", this);\n}\n\nPromise.prototype.toString = function () {\n return \"[object Promise]\";\n};\n\nPromise.prototype.caught = Promise.prototype[\"catch\"] = function (fn) {\n var len = arguments.length;\n if (len > 1) {\n var catchInstances = new Array(len - 1),\n j = 0, i;\n for (i = 0; i < len - 1; ++i) {\n var item = arguments[i];\n if (util.isObject(item)) {\n catchInstances[j++] = item;\n } else {\n return apiRejection(\"Catch statement predicate: \" +\n \"expecting an object but got \" + util.classString(item));\n }\n }\n catchInstances.length = j;\n fn = arguments[i];\n\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The last argument to .catch() \" +\n \"must be a function, got \" + util.toString(fn));\n }\n return this.then(undefined, catchFilter(catchInstances, fn, this));\n }\n return this.then(undefined, fn);\n};\n\nPromise.prototype.reflect = function () {\n return this._then(reflectHandler,\n reflectHandler, undefined, this, undefined);\n};\n\nPromise.prototype.then = function (didFulfill, didReject) {\n if (debug.warnings() && arguments.length > 0 &&\n typeof didFulfill !== \"function\" &&\n typeof didReject !== \"function\") {\n var msg = \".then() only accepts functions but was passed: \" +\n util.classString(didFulfill);\n if (arguments.length > 1) {\n msg += \", \" + util.classString(didReject);\n }\n this._warn(msg);\n }\n return this._then(didFulfill, didReject, undefined, undefined, undefined);\n};\n\nPromise.prototype.done = function (didFulfill, didReject) {\n var promise =\n this._then(didFulfill, didReject, undefined, undefined, undefined);\n promise._setIsFinal();\n};\n\nPromise.prototype.spread = function (fn) {\n if (typeof fn !== \"function\") {\n return apiRejection(\"expecting a function but got \" + util.classString(fn));\n }\n return this.all()._then(fn, undefined, undefined, APPLY, undefined);\n};\n\nPromise.prototype.toJSON = function () {\n var ret = {\n isFulfilled: false,\n isRejected: false,\n fulfillmentValue: undefined,\n rejectionReason: undefined\n };\n if (this.isFulfilled()) {\n ret.fulfillmentValue = this.value();\n ret.isFulfilled = true;\n } else if (this.isRejected()) {\n ret.rejectionReason = this.reason();\n ret.isRejected = true;\n }\n return ret;\n};\n\nPromise.prototype.all = function () {\n if (arguments.length > 0) {\n this._warn(\".all() was passed arguments but it does not take any\");\n }\n return new PromiseArray(this).promise();\n};\n\nPromise.prototype.error = function (fn) {\n return this.caught(util.originatesFromRejection, fn);\n};\n\nPromise.getNewLibraryCopy = module.exports;\n\nPromise.is = function (val) {\n return val instanceof Promise;\n};\n\nPromise.fromNode = Promise.fromCallback = function(fn) {\n var ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs\n : false;\n var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));\n if (result === errorObj) {\n ret._rejectCallback(result.e, true);\n }\n if (!ret._isFateSealed()) ret._setAsyncGuaranteed();\n return ret;\n};\n\nPromise.all = function (promises) {\n return new PromiseArray(promises).promise();\n};\n\nPromise.cast = function (obj) {\n var ret = tryConvertToPromise(obj);\n if (!(ret instanceof Promise)) {\n ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n ret._setFulfilled();\n ret._rejectionHandler0 = obj;\n }\n return ret;\n};\n\nPromise.resolve = Promise.fulfilled = Promise.cast;\n\nPromise.reject = Promise.rejected = function (reason) {\n var ret = new Promise(INTERNAL);\n ret._captureStackTrace();\n ret._rejectCallback(reason, true);\n return ret;\n};\n\nPromise.setScheduler = function(fn) {\n if (typeof fn !== \"function\") {\n throw new TypeError(\"expecting a function but got \" + util.classString(fn));\n }\n return async.setScheduler(fn);\n};\n\nPromise.prototype._then = function (\n didFulfill,\n didReject,\n _, receiver,\n internalData\n) {\n var haveInternalData = internalData !== undefined;\n var promise = haveInternalData ? internalData : new Promise(INTERNAL);\n var target = this._target();\n var bitField = target._bitField;\n\n if (!haveInternalData) {\n promise._propagateFrom(this, 3);\n promise._captureStackTrace();\n if (receiver === undefined &&\n ((this._bitField & 2097152) !== 0)) {\n if (!((bitField & 50397184) === 0)) {\n receiver = this._boundValue();\n } else {\n receiver = target === this ? undefined : this._boundTo;\n }\n }\n this._fireEvent(\"promiseChained\", this, promise);\n }\n\n var context = getContext();\n if (!((bitField & 50397184) === 0)) {\n var handler, value, settler = target._settlePromiseCtx;\n if (((bitField & 33554432) !== 0)) {\n value = target._rejectionHandler0;\n handler = didFulfill;\n } else if (((bitField & 16777216) !== 0)) {\n value = target._fulfillmentHandler0;\n handler = didReject;\n target._unsetRejectionIsUnhandled();\n } else {\n settler = target._settlePromiseLateCancellationObserver;\n value = new CancellationError(\"late cancellation observer\");\n target._attachExtraTrace(value);\n handler = didReject;\n }\n\n async.invoke(settler, target, {\n handler: util.contextBind(context, handler),\n promise: promise,\n receiver: receiver,\n value: value\n });\n } else {\n target._addCallbacks(didFulfill, didReject, promise,\n receiver, context);\n }\n\n return promise;\n};\n\nPromise.prototype._length = function () {\n return this._bitField & 65535;\n};\n\nPromise.prototype._isFateSealed = function () {\n return (this._bitField & 117506048) !== 0;\n};\n\nPromise.prototype._isFollowing = function () {\n return (this._bitField & 67108864) === 67108864;\n};\n\nPromise.prototype._setLength = function (len) {\n this._bitField = (this._bitField & -65536) |\n (len & 65535);\n};\n\nPromise.prototype._setFulfilled = function () {\n this._bitField = this._bitField | 33554432;\n this._fireEvent(\"promiseFulfilled\", this);\n};\n\nPromise.prototype._setRejected = function () {\n this._bitField = this._bitField | 16777216;\n this._fireEvent(\"promiseRejected\", this);\n};\n\nPromise.prototype._setFollowing = function () {\n this._bitField = this._bitField | 67108864;\n this._fireEvent(\"promiseResolved\", this);\n};\n\nPromise.prototype._setIsFinal = function () {\n this._bitField = this._bitField | 4194304;\n};\n\nPromise.prototype._isFinal = function () {\n return (this._bitField & 4194304) > 0;\n};\n\nPromise.prototype._unsetCancelled = function() {\n this._bitField = this._bitField & (~65536);\n};\n\nPromise.prototype._setCancelled = function() {\n this._bitField = this._bitField | 65536;\n this._fireEvent(\"promiseCancelled\", this);\n};\n\nPromise.prototype._setWillBeCancelled = function() {\n this._bitField = this._bitField | 8388608;\n};\n\nPromise.prototype._setAsyncGuaranteed = function() {\n if (async.hasCustomScheduler()) return;\n var bitField = this._bitField;\n this._bitField = bitField |\n (((bitField & 536870912) >> 2) ^\n 134217728);\n};\n\nPromise.prototype._setNoAsyncGuarantee = function() {\n this._bitField = (this._bitField | 536870912) &\n (~134217728);\n};\n\nPromise.prototype._receiverAt = function (index) {\n var ret = index === 0 ? this._receiver0 : this[\n index * 4 - 4 + 3];\n if (ret === UNDEFINED_BINDING) {\n return undefined;\n } else if (ret === undefined && this._isBound()) {\n return this._boundValue();\n }\n return ret;\n};\n\nPromise.prototype._promiseAt = function (index) {\n return this[\n index * 4 - 4 + 2];\n};\n\nPromise.prototype._fulfillmentHandlerAt = function (index) {\n return this[\n index * 4 - 4 + 0];\n};\n\nPromise.prototype._rejectionHandlerAt = function (index) {\n return this[\n index * 4 - 4 + 1];\n};\n\nPromise.prototype._boundValue = function() {};\n\nPromise.prototype._migrateCallback0 = function (follower) {\n var bitField = follower._bitField;\n var fulfill = follower._fulfillmentHandler0;\n var reject = follower._rejectionHandler0;\n var promise = follower._promise0;\n var receiver = follower._receiverAt(0);\n if (receiver === undefined) receiver = UNDEFINED_BINDING;\n this._addCallbacks(fulfill, reject, promise, receiver, null);\n};\n\nPromise.prototype._migrateCallbackAt = function (follower, index) {\n var fulfill = follower._fulfillmentHandlerAt(index);\n var reject = follower._rejectionHandlerAt(index);\n var promise = follower._promiseAt(index);\n var receiver = follower._receiverAt(index);\n if (receiver === undefined) receiver = UNDEFINED_BINDING;\n this._addCallbacks(fulfill, reject, promise, receiver, null);\n};\n\nPromise.prototype._addCallbacks = function (\n fulfill,\n reject,\n promise,\n receiver,\n context\n) {\n var index = this._length();\n\n if (index >= 65535 - 4) {\n index = 0;\n this._setLength(0);\n }\n\n if (index === 0) {\n this._promise0 = promise;\n this._receiver0 = receiver;\n if (typeof fulfill === \"function\") {\n this._fulfillmentHandler0 = util.contextBind(context, fulfill);\n }\n if (typeof reject === \"function\") {\n this._rejectionHandler0 = util.contextBind(context, reject);\n }\n } else {\n var base = index * 4 - 4;\n this[base + 2] = promise;\n this[base + 3] = receiver;\n if (typeof fulfill === \"function\") {\n this[base + 0] =\n util.contextBind(context, fulfill);\n }\n if (typeof reject === \"function\") {\n this[base + 1] =\n util.contextBind(context, reject);\n }\n }\n this._setLength(index + 1);\n return index;\n};\n\nPromise.prototype._proxy = function (proxyable, arg) {\n this._addCallbacks(undefined, undefined, arg, proxyable, null);\n};\n\nPromise.prototype._resolveCallback = function(value, shouldBind) {\n if (((this._bitField & 117506048) !== 0)) return;\n if (value === this)\n return this._rejectCallback(makeSelfResolutionError(), false);\n var maybePromise = tryConvertToPromise(value, this);\n if (!(maybePromise instanceof Promise)) return this._fulfill(value);\n\n if (shouldBind) this._propagateFrom(maybePromise, 2);\n\n\n var promise = maybePromise._target();\n\n if (promise === this) {\n this._reject(makeSelfResolutionError());\n return;\n }\n\n var bitField = promise._bitField;\n if (((bitField & 50397184) === 0)) {\n var len = this._length();\n if (len > 0) promise._migrateCallback0(this);\n for (var i = 1; i < len; ++i) {\n promise._migrateCallbackAt(this, i);\n }\n this._setFollowing();\n this._setLength(0);\n this._setFollowee(maybePromise);\n } else if (((bitField & 33554432) !== 0)) {\n this._fulfill(promise._value());\n } else if (((bitField & 16777216) !== 0)) {\n this._reject(promise._reason());\n } else {\n var reason = new CancellationError(\"late cancellation observer\");\n promise._attachExtraTrace(reason);\n this._reject(reason);\n }\n};\n\nPromise.prototype._rejectCallback =\nfunction(reason, synchronous, ignoreNonErrorWarnings) {\n var trace = util.ensureErrorObject(reason);\n var hasStack = trace === reason;\n if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {\n var message = \"a promise was rejected with a non-error: \" +\n util.classString(reason);\n this._warn(message, true);\n }\n this._attachExtraTrace(trace, synchronous ? hasStack : false);\n this._reject(reason);\n};\n\nPromise.prototype._resolveFromExecutor = function (executor) {\n if (executor === INTERNAL) return;\n var promise = this;\n this._captureStackTrace();\n this._pushContext();\n var synchronous = true;\n var r = this._execute(executor, function(value) {\n promise._resolveCallback(value);\n }, function (reason) {\n promise._rejectCallback(reason, synchronous);\n });\n synchronous = false;\n this._popContext();\n\n if (r !== undefined) {\n promise._rejectCallback(r, true);\n }\n};\n\nPromise.prototype._settlePromiseFromHandler = function (\n handler, receiver, value, promise\n) {\n var bitField = promise._bitField;\n if (((bitField & 65536) !== 0)) return;\n promise._pushContext();\n var x;\n if (receiver === APPLY) {\n if (!value || typeof value.length !== \"number\") {\n x = errorObj;\n x.e = new TypeError(\"cannot .spread() a non-array: \" +\n util.classString(value));\n } else {\n x = tryCatch(handler).apply(this._boundValue(), value);\n }\n } else {\n x = tryCatch(handler).call(receiver, value);\n }\n var promiseCreated = promise._popContext();\n bitField = promise._bitField;\n if (((bitField & 65536) !== 0)) return;\n\n if (x === NEXT_FILTER) {\n promise._reject(value);\n } else if (x === errorObj) {\n promise._rejectCallback(x.e, false);\n } else {\n debug.checkForgottenReturns(x, promiseCreated, \"\", promise, this);\n promise._resolveCallback(x);\n }\n};\n\nPromise.prototype._target = function() {\n var ret = this;\n while (ret._isFollowing()) ret = ret._followee();\n return ret;\n};\n\nPromise.prototype._followee = function() {\n return this._rejectionHandler0;\n};\n\nPromise.prototype._setFollowee = function(promise) {\n this._rejectionHandler0 = promise;\n};\n\nPromise.prototype._settlePromise = function(promise, handler, receiver, value) {\n var isPromise = promise instanceof Promise;\n var bitField = this._bitField;\n var asyncGuaranteed = ((bitField & 134217728) !== 0);\n if (((bitField & 65536) !== 0)) {\n if (isPromise) promise._invokeInternalOnCancel();\n\n if (receiver instanceof PassThroughHandlerContext &&\n receiver.isFinallyHandler()) {\n receiver.cancelPromise = promise;\n if (tryCatch(handler).call(receiver, value) === errorObj) {\n promise._reject(errorObj.e);\n }\n } else if (handler === reflectHandler) {\n promise._fulfill(reflectHandler.call(receiver));\n } else if (receiver instanceof Proxyable) {\n receiver._promiseCancelled(promise);\n } else if (isPromise || promise instanceof PromiseArray) {\n promise._cancel();\n } else {\n receiver.cancel();\n }\n } else if (typeof handler === \"function\") {\n if (!isPromise) {\n handler.call(receiver, value, promise);\n } else {\n if (asyncGuaranteed) promise._setAsyncGuaranteed();\n this._settlePromiseFromHandler(handler, receiver, value, promise);\n }\n } else if (receiver instanceof Proxyable) {\n if (!receiver._isResolved()) {\n if (((bitField & 33554432) !== 0)) {\n receiver._promiseFulfilled(value, promise);\n } else {\n receiver._promiseRejected(value, promise);\n }\n }\n } else if (isPromise) {\n if (asyncGuaranteed) promise._setAsyncGuaranteed();\n if (((bitField & 33554432) !== 0)) {\n promise._fulfill(value);\n } else {\n promise._reject(value);\n }\n }\n};\n\nPromise.prototype._settlePromiseLateCancellationObserver = function(ctx) {\n var handler = ctx.handler;\n var promise = ctx.promise;\n var receiver = ctx.receiver;\n var value = ctx.value;\n if (typeof handler === \"function\") {\n if (!(promise instanceof Promise)) {\n handler.call(receiver, value, promise);\n } else {\n this._settlePromiseFromHandler(handler, receiver, value, promise);\n }\n } else if (promise instanceof Promise) {\n promise._reject(value);\n }\n};\n\nPromise.prototype._settlePromiseCtx = function(ctx) {\n this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);\n};\n\nPromise.prototype._settlePromise0 = function(handler, value, bitField) {\n var promise = this._promise0;\n var receiver = this._receiverAt(0);\n this._promise0 = undefined;\n this._receiver0 = undefined;\n this._settlePromise(promise, handler, receiver, value);\n};\n\nPromise.prototype._clearCallbackDataAtIndex = function(index) {\n var base = index * 4 - 4;\n this[base + 2] =\n this[base + 3] =\n this[base + 0] =\n this[base + 1] = undefined;\n};\n\nPromise.prototype._fulfill = function (value) {\n var bitField = this._bitField;\n if (((bitField & 117506048) >>> 16)) return;\n if (value === this) {\n var err = makeSelfResolutionError();\n this._attachExtraTrace(err);\n return this._reject(err);\n }\n this._setFulfilled();\n this._rejectionHandler0 = value;\n\n if ((bitField & 65535) > 0) {\n if (((bitField & 134217728) !== 0)) {\n this._settlePromises();\n } else {\n async.settlePromises(this);\n }\n this._dereferenceTrace();\n }\n};\n\nPromise.prototype._reject = function (reason) {\n var bitField = this._bitField;\n if (((bitField & 117506048) >>> 16)) return;\n this._setRejected();\n this._fulfillmentHandler0 = reason;\n\n if (this._isFinal()) {\n return async.fatalError(reason, util.isNode);\n }\n\n if ((bitField & 65535) > 0) {\n async.settlePromises(this);\n } else {\n this._ensurePossibleRejectionHandled();\n }\n};\n\nPromise.prototype._fulfillPromises = function (len, value) {\n for (var i = 1; i < len; i++) {\n var handler = this._fulfillmentHandlerAt(i);\n var promise = this._promiseAt(i);\n var receiver = this._receiverAt(i);\n this._clearCallbackDataAtIndex(i);\n this._settlePromise(promise, handler, receiver, value);\n }\n};\n\nPromise.prototype._rejectPromises = function (len, reason) {\n for (var i = 1; i < len; i++) {\n var handler = this._rejectionHandlerAt(i);\n var promise = this._promiseAt(i);\n var receiver = this._receiverAt(i);\n this._clearCallbackDataAtIndex(i);\n this._settlePromise(promise, handler, receiver, reason);\n }\n};\n\nPromise.prototype._settlePromises = function () {\n var bitField = this._bitField;\n var len = (bitField & 65535);\n\n if (len > 0) {\n if (((bitField & 16842752) !== 0)) {\n var reason = this._fulfillmentHandler0;\n this._settlePromise0(this._rejectionHandler0, reason, bitField);\n this._rejectPromises(len, reason);\n } else {\n var value = this._rejectionHandler0;\n this._settlePromise0(this._fulfillmentHandler0, value, bitField);\n this._fulfillPromises(len, value);\n }\n this._setLength(0);\n }\n this._clearCancellationData();\n};\n\nPromise.prototype._settledValue = function() {\n var bitField = this._bitField;\n if (((bitField & 33554432) !== 0)) {\n return this._rejectionHandler0;\n } else if (((bitField & 16777216) !== 0)) {\n return this._fulfillmentHandler0;\n }\n};\n\nif (typeof Symbol !== \"undefined\" && Symbol.toStringTag) {\n es5.defineProperty(Promise.prototype, Symbol.toStringTag, {\n get: function () {\n return \"Object\";\n }\n });\n}\n\nfunction deferResolve(v) {this.promise._resolveCallback(v);}\nfunction deferReject(v) {this.promise._rejectCallback(v, false);}\n\nPromise.defer = Promise.pending = function() {\n debug.deprecated(\"Promise.defer\", \"new Promise\");\n var promise = new Promise(INTERNAL);\n return {\n promise: promise,\n resolve: deferResolve,\n reject: deferReject\n };\n};\n\nutil.notEnumerableProp(Promise,\n \"_makeSelfResolutionError\",\n makeSelfResolutionError);\n\nrequire(\"./method\")(Promise, INTERNAL, tryConvertToPromise, apiRejection,\n debug);\nrequire(\"./bind\")(Promise, INTERNAL, tryConvertToPromise, debug);\nrequire(\"./cancel\")(Promise, PromiseArray, apiRejection, debug);\nrequire(\"./direct_resolve\")(Promise);\nrequire(\"./synchronous_inspection\")(Promise);\nrequire(\"./join\")(\n Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);\nPromise.Promise = Promise;\nPromise.version = \"3.7.2\";\nrequire('./call_get.js')(Promise);\nrequire('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);\nrequire('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);\nrequire('./nodeify.js')(Promise);\nrequire('./promisify.js')(Promise, INTERNAL);\nrequire('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);\nrequire('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);\nrequire('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);\nrequire('./settle.js')(Promise, PromiseArray, debug);\nrequire('./some.js')(Promise, PromiseArray, apiRejection);\nrequire('./timers.js')(Promise, INTERNAL, debug);\nrequire('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);\nrequire('./any.js')(Promise);\nrequire('./each.js')(Promise, INTERNAL);\nrequire('./filter.js')(Promise, INTERNAL);\n \n util.toFastProperties(Promise); \n util.toFastProperties(Promise.prototype); \n function fillTypes(value) { \n var p = new Promise(INTERNAL); \n p._fulfillmentHandler0 = value; \n p._rejectionHandler0 = value; \n p._promise0 = value; \n p._receiver0 = value; \n } \n // Complete slack tracking, opt out of field-type tracking and \n // stabilize map \n fillTypes({a: 1}); \n fillTypes({b: 2}); \n fillTypes({c: 3}); \n fillTypes(1); \n fillTypes(function(){}); \n fillTypes(undefined); \n fillTypes(false); \n fillTypes(new Promise(INTERNAL)); \n debug.setBounds(Async.firstLineError, util.lastLineError); \n return Promise; \n\n};\n","\"use strict\";\nvar old;\nif (typeof Promise !== \"undefined\") old = Promise;\nfunction noConflict() {\n try { if (Promise === bluebird) Promise = old; }\n catch (e) {}\n return bluebird;\n}\nvar bluebird = require(\"./promise\")();\nbluebird.noConflict = noConflict;\nmodule.exports = bluebird;\n","// (c) Dean McNamee , 2013.\n//\n// https://github.com/deanm/omggif\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n//\n// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,\n// including animation and compression. It does not rely on any specific\n// underlying system, so should run in the browser, Node, or Plask.\n\n\"use strict\";\n\nfunction GifWriter(buf, width, height, gopts) {\n var p = 0;\n\n var gopts = gopts === undefined ? { } : gopts;\n var loop_count = gopts.loop === undefined ? null : gopts.loop;\n var global_palette = gopts.palette === undefined ? null : gopts.palette;\n\n if (width <= 0 || height <= 0 || width > 65535 || height > 65535)\n throw new Error(\"Width/Height invalid.\");\n\n function check_palette_and_num_colors(palette) {\n var num_colors = palette.length;\n if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) {\n throw new Error(\n \"Invalid code/color length, must be power of 2 and 2 .. 256.\");\n }\n return num_colors;\n }\n\n // - Header.\n buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF\n buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a\n\n // Handling of Global Color Table (palette) and background index.\n var gp_num_colors_pow2 = 0;\n var background = 0;\n if (global_palette !== null) {\n var gp_num_colors = check_palette_and_num_colors(global_palette);\n while (gp_num_colors >>= 1) ++gp_num_colors_pow2;\n gp_num_colors = 1 << gp_num_colors_pow2;\n --gp_num_colors_pow2;\n if (gopts.background !== undefined) {\n background = gopts.background;\n if (background >= gp_num_colors)\n throw new Error(\"Background index out of range.\");\n // The GIF spec states that a background index of 0 should be ignored, so\n // this is probably a mistake and you really want to set it to another\n // slot in the palette. But actually in the end most browsers, etc end\n // up ignoring this almost completely (including for dispose background).\n if (background === 0)\n throw new Error(\"Background index explicitly passed as 0.\");\n }\n }\n\n // - Logical Screen Descriptor.\n // NOTE(deanm): w/h apparently ignored by implementations, but set anyway.\n buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff;\n buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff;\n // NOTE: Indicates 0-bpp original color resolution (unused?).\n buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag.\n gp_num_colors_pow2; // NOTE: No sort flag (unused?).\n buf[p++] = background; // Background Color Index.\n buf[p++] = 0; // Pixel aspect ratio (unused?).\n\n // - Global Color Table\n if (global_palette !== null) {\n for (var i = 0, il = global_palette.length; i < il; ++i) {\n var rgb = global_palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n if (loop_count !== null) { // Netscape block for looping.\n if (loop_count < 0 || loop_count > 65535)\n throw new Error(\"Loop count invalid.\")\n // Extension code, label, and length.\n buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b;\n // NETSCAPE2.0\n buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53;\n buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45;\n buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30;\n // Sub-block\n buf[p++] = 0x03; buf[p++] = 0x01;\n buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff;\n buf[p++] = 0x00; // Terminator.\n }\n\n\n var ended = false;\n\n this.addFrame = function(x, y, w, h, indexed_pixels, opts) {\n if (ended === true) { --p; ended = false; } // Un-end.\n\n opts = opts === undefined ? { } : opts;\n\n // TODO(deanm): Bounds check x, y. Do they need to be within the virtual\n // canvas width/height, I imagine?\n if (x < 0 || y < 0 || x > 65535 || y > 65535)\n throw new Error(\"x/y invalid.\")\n\n if (w <= 0 || h <= 0 || w > 65535 || h > 65535)\n throw new Error(\"Width/Height invalid.\")\n\n if (indexed_pixels.length < w * h)\n throw new Error(\"Not enough pixels for the frame size.\");\n\n var using_local_palette = true;\n var palette = opts.palette;\n if (palette === undefined || palette === null) {\n using_local_palette = false;\n palette = global_palette;\n }\n\n if (palette === undefined || palette === null)\n throw new Error(\"Must supply either a local or global palette.\");\n\n var num_colors = check_palette_and_num_colors(palette);\n\n // Compute the min_code_size (power of 2), destroying num_colors.\n var min_code_size = 0;\n while (num_colors >>= 1) ++min_code_size;\n num_colors = 1 << min_code_size; // Now we can easily get it back.\n\n var delay = opts.delay === undefined ? 0 : opts.delay;\n\n // From the spec:\n // 0 - No disposal specified. The decoder is\n // not required to take any action.\n // 1 - Do not dispose. The graphic is to be left\n // in place.\n // 2 - Restore to background color. The area used by the\n // graphic must be restored to the background color.\n // 3 - Restore to previous. The decoder is required to\n // restore the area overwritten by the graphic with\n // what was there prior to rendering the graphic.\n // 4-7 - To be defined.\n // NOTE(deanm): Dispose background doesn't really work, apparently most\n // browsers ignore the background palette index and clear to transparency.\n var disposal = opts.disposal === undefined ? 0 : opts.disposal;\n if (disposal < 0 || disposal > 3) // 4-7 is reserved.\n throw new Error(\"Disposal out of range.\");\n\n var use_transparency = false;\n var transparent_index = 0;\n if (opts.transparent !== undefined && opts.transparent !== null) {\n use_transparency = true;\n transparent_index = opts.transparent;\n if (transparent_index < 0 || transparent_index >= num_colors)\n throw new Error(\"Transparent color index.\");\n }\n\n if (disposal !== 0 || use_transparency || delay !== 0) {\n // - Graphics Control Extension\n buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label.\n buf[p++] = 4; // Byte size.\n\n buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0);\n buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff;\n buf[p++] = transparent_index; // Transparent color index.\n buf[p++] = 0; // Block Terminator.\n }\n\n // - Image Descriptor\n buf[p++] = 0x2c; // Image Seperator.\n buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left.\n buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top.\n buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff;\n buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff;\n // NOTE: No sort flag (unused?).\n // TODO(deanm): Support interlace.\n buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0;\n\n // - Local Color Table\n if (using_local_palette === true) {\n for (var i = 0, il = palette.length; i < il; ++i) {\n var rgb = palette[i];\n buf[p++] = rgb >> 16 & 0xff;\n buf[p++] = rgb >> 8 & 0xff;\n buf[p++] = rgb & 0xff;\n }\n }\n\n p = GifWriterOutputLZWCodeStream(\n buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels);\n\n return p;\n };\n\n this.end = function() {\n if (ended === false) {\n buf[p++] = 0x3b; // Trailer.\n ended = true;\n }\n return p;\n };\n\n this.getOutputBuffer = function() { return buf; };\n this.setOutputBuffer = function(v) { buf = v; };\n this.getOutputBufferPosition = function() { return p; };\n this.setOutputBufferPosition = function(v) { p = v; };\n}\n\n// Main compression routine, palette indexes -> LZW code stream.\n// |index_stream| must have at least one entry.\nfunction GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) {\n buf[p++] = min_code_size;\n var cur_subblock = p++; // Pointing at the length field.\n\n var clear_code = 1 << min_code_size;\n var code_mask = clear_code - 1;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n var cur_shift = 0;\n // We have at most 12-bit codes, so we should have to hold a max of 19\n // bits here (and then we would write out).\n var cur = 0;\n\n function emit_bytes_to_buffer(bit_block_size) {\n while (cur_shift >= bit_block_size) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n }\n\n function emit_code(c) {\n cur |= c << cur_shift;\n cur_shift += cur_code_size;\n emit_bytes_to_buffer(8);\n }\n\n // I am not an expert on the topic, and I don't want to write a thesis.\n // However, it is good to outline here the basic algorithm and the few data\n // structures and optimizations here that make this implementation fast.\n // The basic idea behind LZW is to build a table of previously seen runs\n // addressed by a short id (herein called output code). All data is\n // referenced by a code, which represents one or more values from the\n // original input stream. All input bytes can be referenced as the same\n // value as an output code. So if you didn't want any compression, you\n // could more or less just output the original bytes as codes (there are\n // some details to this, but it is the idea). In order to achieve\n // compression, values greater then the input range (codes can be up to\n // 12-bit while input only 8-bit) represent a sequence of previously seen\n // inputs. The decompressor is able to build the same mapping while\n // decoding, so there is always a shared common knowledge between the\n // encoding and decoder, which is also important for \"timing\" aspects like\n // how to handle variable bit width code encoding.\n //\n // One obvious but very important consequence of the table system is there\n // is always a unique id (at most 12-bits) to map the runs. 'A' might be\n // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship\n // can be used for an effecient lookup strategy for the code mapping. We\n // need to know if a run has been seen before, and be able to map that run\n // to the output code. Since we start with known unique ids (input bytes),\n // and then from those build more unique ids (table entries), we can\n // continue this chain (almost like a linked list) to always have small\n // integer values that represent the current byte chains in the encoder.\n // This means instead of tracking the input bytes (AAAABCD) to know our\n // current state, we can track the table entry for AAAABC (it is guaranteed\n // to exist by the nature of the algorithm) and the next character D.\n // Therefor the tuple of (table_entry, byte) is guaranteed to also be\n // unique. This allows us to create a simple lookup key for mapping input\n // sequences to codes (table indices) without having to store or search\n // any of the code sequences. So if 'AAAA' has a table entry of 12, the\n // tuple of ('AAAA', K) for any input byte K will be unique, and can be our\n // key. This leads to a integer value at most 20-bits, which can always\n // fit in an SMI value and be used as a fast sparse array / object key.\n\n // Output code for the current contents of the index buffer.\n var ib_code = index_stream[0] & code_mask; // Load first input index.\n var code_table = { }; // Key'd on our 20-bit \"tuple\".\n\n emit_code(clear_code); // Spec says first code should be a clear code.\n\n // First index already loaded, process the rest of the stream.\n for (var i = 1, il = index_stream.length; i < il; ++i) {\n var k = index_stream[i] & code_mask;\n var cur_key = ib_code << 8 | k; // (prev, k) unique tuple.\n var cur_code = code_table[cur_key]; // buffer + k.\n\n // Check if we have to create a new code table entry.\n if (cur_code === undefined) { // We don't have buffer + k.\n // Emit index buffer (without k).\n // This is an inline version of emit_code, because this is the core\n // writing routine of the compressor (and V8 cannot inline emit_code\n // because it is a closure here in a different context). Additionally\n // we can call emit_byte_to_buffer less often, because we can have\n // 30-bits (from our 31-bit signed SMI), and we know our codes will only\n // be 12-bits, so can safely have 18-bits there without overflow.\n // emit_code(ib_code);\n cur |= ib_code << cur_shift;\n cur_shift += cur_code_size;\n while (cur_shift >= 8) {\n buf[p++] = cur & 0xff;\n cur >>= 8; cur_shift -= 8;\n if (p === cur_subblock + 256) { // Finished a subblock.\n buf[cur_subblock] = 255;\n cur_subblock = p++;\n }\n }\n\n if (next_code === 4096) { // Table full, need a clear.\n emit_code(clear_code);\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_table = { };\n } else { // Table not full, insert a new entry.\n // Increase our variable bit code sizes if necessary. This is a bit\n // tricky as it is based on \"timing\" between the encoding and\n // decoder. From the encoders perspective this should happen after\n // we've already emitted the index buffer and are about to create the\n // first table entry that would overflow our current code bit size.\n if (next_code >= (1 << cur_code_size)) ++cur_code_size;\n code_table[cur_key] = next_code++; // Insert into code table.\n }\n\n ib_code = k; // Index buffer to single input k.\n } else {\n ib_code = cur_code; // Index buffer to sequence in code table.\n }\n }\n\n emit_code(ib_code); // There will still be something in the index buffer.\n emit_code(eoi_code); // End Of Information.\n\n // Flush / finalize the sub-blocks stream to the buffer.\n emit_bytes_to_buffer(1);\n\n // Finish the sub-blocks, writing out any unfinished lengths and\n // terminating with a sub-block of length 0. If we have already started\n // but not yet used a sub-block it can just become the terminator.\n if (cur_subblock + 1 === p) { // Started but unused.\n buf[cur_subblock] = 0;\n } else { // Started and used, write length and additional terminator block.\n buf[cur_subblock] = p - cur_subblock - 1;\n buf[p++] = 0;\n }\n return p;\n}\n\nfunction GifReader(buf) {\n var p = 0;\n\n // - Header (GIF87a or GIF89a).\n if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 ||\n buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) {\n throw new Error(\"Invalid GIF 87a/89a header.\");\n }\n\n // - Logical Screen Descriptor.\n var width = buf[p++] | buf[p++] << 8;\n var height = buf[p++] | buf[p++] << 8;\n var pf0 = buf[p++]; // .\n var global_palette_flag = pf0 >> 7;\n var num_global_colors_pow2 = pf0 & 0x7;\n var num_global_colors = 1 << (num_global_colors_pow2 + 1);\n var background = buf[p++];\n buf[p++]; // Pixel aspect ratio (unused?).\n\n var global_palette_offset = null;\n var global_palette_size = null;\n\n if (global_palette_flag) {\n global_palette_offset = p;\n global_palette_size = num_global_colors;\n p += num_global_colors * 3; // Seek past palette.\n }\n\n var no_eof = true;\n\n var frames = [ ];\n\n var delay = 0;\n var transparent_index = null;\n var disposal = 0; // 0 - No disposal specified.\n var loop_count = null;\n\n this.width = width;\n this.height = height;\n\n while (no_eof && p < buf.length) {\n switch (buf[p++]) {\n case 0x21: // Graphics Control Extension Block\n switch (buf[p++]) {\n case 0xff: // Application specific block\n // Try if it's a Netscape block (with animation loop counter).\n if (buf[p ] !== 0x0b || // 21 FF already read, check block size.\n // NETSCAPE2.0\n buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 &&\n buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 &&\n buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 &&\n buf[p+10] == 0x2e && buf[p+11] == 0x30 &&\n // Sub-block\n buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) {\n p += 14;\n loop_count = buf[p++] | buf[p++] << 8;\n p++; // Skip terminator.\n } else { // We don't know what it is, just try to get past it.\n p += 12;\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n }\n break;\n\n case 0xf9: // Graphics Control Extension\n if (buf[p++] !== 0x4 || buf[p+4] !== 0)\n throw new Error(\"Invalid graphics extension block.\");\n var pf1 = buf[p++];\n delay = buf[p++] | buf[p++] << 8;\n transparent_index = buf[p++];\n if ((pf1 & 1) === 0) transparent_index = null;\n disposal = pf1 >> 2 & 0x7;\n p++; // Skip terminator.\n break;\n\n case 0xfe: // Comment Extension.\n while (true) { // Seek through subblocks.\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n // console.log(buf.slice(p, p+block_size).toString('ascii'));\n p += block_size;\n }\n break;\n\n default:\n throw new Error(\n \"Unknown graphic control label: 0x\" + buf[p-1].toString(16));\n }\n break;\n\n case 0x2c: // Image Descriptor.\n var x = buf[p++] | buf[p++] << 8;\n var y = buf[p++] | buf[p++] << 8;\n var w = buf[p++] | buf[p++] << 8;\n var h = buf[p++] | buf[p++] << 8;\n var pf2 = buf[p++];\n var local_palette_flag = pf2 >> 7;\n var interlace_flag = pf2 >> 6 & 1;\n var num_local_colors_pow2 = pf2 & 0x7;\n var num_local_colors = 1 << (num_local_colors_pow2 + 1);\n var palette_offset = global_palette_offset;\n var palette_size = global_palette_size;\n var has_local_palette = false;\n if (local_palette_flag) {\n var has_local_palette = true;\n palette_offset = p; // Override with local palette.\n palette_size = num_local_colors;\n p += num_local_colors * 3; // Seek past palette.\n }\n\n var data_offset = p;\n\n p++; // codesize\n while (true) {\n var block_size = buf[p++];\n // Bad block size (ex: undefined from an out of bounds read).\n if (!(block_size >= 0)) throw Error(\"Invalid block size\");\n if (block_size === 0) break; // 0 size is terminator\n p += block_size;\n }\n\n frames.push({x: x, y: y, width: w, height: h,\n has_local_palette: has_local_palette,\n palette_offset: palette_offset,\n palette_size: palette_size,\n data_offset: data_offset,\n data_length: p - data_offset,\n transparent_index: transparent_index,\n interlaced: !!interlace_flag,\n delay: delay,\n disposal: disposal});\n break;\n\n case 0x3b: // Trailer Marker (end of file).\n no_eof = false;\n break;\n\n default:\n throw new Error(\"Unknown gif block: 0x\" + buf[p-1].toString(16));\n break;\n }\n }\n\n this.numFrames = function() {\n return frames.length;\n };\n\n this.loopCount = function() {\n return loop_count;\n };\n\n this.frameInfo = function(frame_num) {\n if (frame_num < 0 || frame_num >= frames.length)\n throw new Error(\"Frame index out of range.\");\n return frames[frame_num];\n }\n\n this.decodeAndBlitFrameBGRA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = b;\n pixels[op++] = g;\n pixels[op++] = r;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n\n // I will go to copy and paste hell one day...\n this.decodeAndBlitFrameRGBA = function(frame_num, pixels) {\n var frame = this.frameInfo(frame_num);\n var num_pixels = frame.width * frame.height;\n var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.\n GifReaderLZWOutputIndexStream(\n buf, frame.data_offset, index_stream, num_pixels);\n var palette_offset = frame.palette_offset;\n\n // NOTE(deanm): It seems to be much faster to compare index to 256 than\n // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in\n // the profile, not sure if it's related to using a Uint8Array.\n var trans = frame.transparent_index;\n if (trans === null) trans = 256;\n\n // We are possibly just blitting to a portion of the entire frame.\n // That is a subrect within the framerect, so the additional pixels\n // must be skipped over after we finished a scanline.\n var framewidth = frame.width;\n var framestride = width - framewidth;\n var xleft = framewidth; // Number of subrect pixels left in scanline.\n\n // Output indicies of the top left and bottom right corners of the subrect.\n var opbeg = ((frame.y * width) + frame.x) * 4;\n var opend = ((frame.y + frame.height) * width + frame.x) * 4;\n var op = opbeg;\n\n var scanstride = framestride * 4;\n\n // Use scanstride to skip past the rows when interlacing. This is skipping\n // 7 rows for the first two passes, then 3 then 1.\n if (frame.interlaced === true) {\n scanstride += width * 4 * 7; // Pass 1.\n }\n\n var interlaceskip = 8; // Tracking the row interval in the current pass.\n\n for (var i = 0, il = index_stream.length; i < il; ++i) {\n var index = index_stream[i];\n\n if (xleft === 0) { // Beginning of new scan line\n op += scanstride;\n xleft = framewidth;\n if (op >= opend) { // Catch the wrap to switch passes when interlacing.\n scanstride = framestride * 4 + width * 4 * (interlaceskip-1);\n // interlaceskip / 2 * 4 is interlaceskip << 1.\n op = opbeg + (framewidth + framestride) * (interlaceskip << 1);\n interlaceskip >>= 1;\n }\n }\n\n if (index === trans) {\n op += 4;\n } else {\n var r = buf[palette_offset + index * 3];\n var g = buf[palette_offset + index * 3 + 1];\n var b = buf[palette_offset + index * 3 + 2];\n pixels[op++] = r;\n pixels[op++] = g;\n pixels[op++] = b;\n pixels[op++] = 255;\n }\n --xleft;\n }\n };\n}\n\nfunction GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) {\n var min_code_size = code_stream[p++];\n\n var clear_code = 1 << min_code_size;\n var eoi_code = clear_code + 1;\n var next_code = eoi_code + 1;\n\n var cur_code_size = min_code_size + 1; // Number of bits per code.\n // NOTE: This shares the same name as the encoder, but has a different\n // meaning here. Here this masks each code coming from the code stream.\n var code_mask = (1 << cur_code_size) - 1;\n var cur_shift = 0;\n var cur = 0;\n\n var op = 0; // Output pointer.\n\n var subblock_size = code_stream[p++];\n\n // TODO(deanm): Would using a TypedArray be any faster? At least it would\n // solve the fast mode / backing store uncertainty.\n // var code_table = Array(4096);\n var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.\n\n var prev_code = null; // Track code-1.\n\n while (true) {\n // Read up to two bytes, making sure we always 12-bits for max sized code.\n while (cur_shift < 16) {\n if (subblock_size === 0) break; // No more data to be read.\n\n cur |= code_stream[p++] << cur_shift;\n cur_shift += 8;\n\n if (subblock_size === 1) { // Never let it get to 0 to hold logic above.\n subblock_size = code_stream[p++]; // Next subblock.\n } else {\n --subblock_size;\n }\n }\n\n // TODO(deanm): We should never really get here, we should have received\n // and EOI.\n if (cur_shift < cur_code_size)\n break;\n\n var code = cur & code_mask;\n cur >>= cur_code_size;\n cur_shift -= cur_code_size;\n\n // TODO(deanm): Maybe should check that the first code was a clear code,\n // at least this is what you're supposed to do. But actually our encoder\n // now doesn't emit a clear code first anyway.\n if (code === clear_code) {\n // We don't actually have to clear the table. This could be a good idea\n // for greater error checking, but we don't really do any anyway. We\n // will just track it with next_code and overwrite old entries.\n\n next_code = eoi_code + 1;\n cur_code_size = min_code_size + 1;\n code_mask = (1 << cur_code_size) - 1;\n\n // Don't update prev_code ?\n prev_code = null;\n continue;\n } else if (code === eoi_code) {\n break;\n }\n\n // We have a similar situation as the decoder, where we want to store\n // variable length entries (code table entries), but we want to do in a\n // faster manner than an array of arrays. The code below stores sort of a\n // linked list within the code table, and then \"chases\" through it to\n // construct the dictionary entries. When a new entry is created, just the\n // last byte is stored, and the rest (prefix) of the entry is only\n // referenced by its table entry. Then the code chases through the\n // prefixes until it reaches a single byte code. We have to chase twice,\n // first to compute the length, and then to actually copy the data to the\n // output (backwards, since we know the length). The alternative would be\n // storing something in an intermediate stack, but that doesn't make any\n // more sense. I implemented an approach where it also stored the length\n // in the code table, although it's a bit tricky because you run out of\n // bits (12 + 12 + 8), but I didn't measure much improvements (the table\n // entries are generally not the long). Even when I created benchmarks for\n // very long table entries the complexity did not seem worth it.\n // The code table stores the prefix entry in 12 bits and then the suffix\n // byte in 8 bits, so each entry is 20 bits.\n\n var chase_code = code < next_code ? code : prev_code;\n\n // Chase what we will output, either {CODE} or {CODE-1}.\n var chase_length = 0;\n var chase = chase_code;\n while (chase > clear_code) {\n chase = code_table[chase] >> 8;\n ++chase_length;\n }\n\n var k = chase;\n\n var op_end = op + chase_length + (chase_code !== code ? 1 : 0);\n if (op_end > output_length) {\n console.log(\"Warning, gif stream longer than expected.\");\n return;\n }\n\n // Already have the first byte from the chase, might as well write it fast.\n output[op++] = k;\n\n op += chase_length;\n var b = op; // Track pointer, writing backwards.\n\n if (chase_code !== code) // The case of emitting {CODE-1} + k.\n output[op++] = k;\n\n chase = chase_code;\n while (chase_length--) {\n chase = code_table[chase];\n output[--b] = chase & 0xff; // Write backwards.\n chase >>= 8; // Pull down to the prefix code.\n }\n\n if (prev_code !== null && next_code < 4096) {\n code_table[next_code++] = prev_code << 8 | k;\n // TODO(deanm): Figure out this clearing vs code growth logic better. I\n // have an feeling that it should just happen somewhere else, for now it\n // is awkward between when we grow past the max and then hit a clear code.\n // For now just check if we hit the max 12-bits (then a clear code should\n // follow, also of course encoded in 12-bits).\n if (next_code >= code_mask+1 && cur_code_size < 12) {\n ++cur_code_size;\n code_mask = code_mask << 1 | 1;\n }\n }\n\n prev_code = code;\n }\n\n if (op !== output_length) {\n console.log(\"Warning, gif stream shorter than expected.\");\n }\n\n return output;\n}\n\n// CommonJS.\ntry { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {}\n","'use strict';\n\n/** @class BitmapImage */\n\nclass BitmapImage {\n\n /**\n * BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties:\n * \n * Property | Description\n * --- | ---\n * bitmap.width | width of image in pixels\n * bitmap.height | height of image in pixels\n * bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel\n *\n * Its constructor supports the following signatures:\n *\n * * new BitmapImage(bitmap: { width: number, height: number, data: Buffer })\n * * new BitmapImage(bitmapImage: BitmapImage)\n * * new BitmapImage(width: number, height: number, buffer: Buffer)\n * * new BitmapImage(width: number, height: number, backgroundRGBA?: number)\n * \n * When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other.\n *\n * `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque.\n */\n\n constructor(...args) {\n // don't confirm the number of args, because a subclass may have\n // additional args and pass them all to the superclass\n if (args.length === 0) {\n throw new Error(\"constructor requires parameters\");\n }\n const firstArg = args[0];\n if (firstArg !== null && typeof firstArg === 'object') {\n if (firstArg instanceof BitmapImage) {\n // copy a provided BitmapImage\n const sourceBitmap = firstArg.bitmap;\n this.bitmap = {\n width: sourceBitmap.width,\n height: sourceBitmap.height,\n data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4)\n };\n sourceBitmap.data.copy(this.bitmap.data);\n }\n else if (firstArg.width && firstArg.height && firstArg.data) {\n // share a provided bitmap\n this.bitmap = firstArg;\n }\n else {\n throw new Error(\"unrecognized constructor parameters\");\n }\n }\n else if (typeof firstArg === 'number' && typeof args[1] === 'number')\n {\n const width = firstArg;\n const height = args[1];\n const thirdArg = args[2];\n this.bitmap = { width, height };\n\n if (Buffer.isBuffer(thirdArg)) {\n this.bitmap.data = thirdArg;\n }\n else {\n this.bitmap.data = new Buffer(width * height * 4);\n if (typeof thirdArg === 'number') {\n this.fillRGBA(thirdArg);\n }\n }\n }\n else {\n throw new Error(\"unrecognized constructor parameters\");\n }\n }\n\n /**\n * Copy a square portion of this image into another image. \n * \n * @param {BitmapImage} toImage Image into which to copy the square\n * @param {number} toX x-coord in toImage of upper-left corner of receiving square\n * @param {number} toY y-coord in toImage of upper-left corner of receiving square\n * @param {number} fromX x-coord in this image of upper-left corner of source square\n * @param {number} fromY y-coord in this image of upper-left corner of source square\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) {\n if (fromX + fromWidth > this.bitmap.width) {\n throw new Error(\"copy exceeds width of source bitmap\");\n }\n if (toX + fromWidth > toImage.bitmap.width) {\n throw new Error(\"copy exceeds width of target bitmap\");\n }\n if (fromY + fromHeight > this.bitmap.height) {\n throw new Error(\"copy exceeds height of source bitmap\");\n }\n if (toY + fromHeight > toImage.bitmap.height) {\n throw new Erro(\"copy exceeds height of target bitmap\");\n }\n \n const sourceBuf = this.bitmap.data;\n const targetBuf = toImage.bitmap.data;\n const sourceByteWidth = this.bitmap.width * 4;\n const targetByteWidth = toImage.bitmap.width * 4;\n const copyByteWidth = fromWidth * 4;\n let si = fromY * sourceByteWidth + fromX * 4;\n let ti = toY * targetByteWidth + toX * 4;\n\n while (--fromHeight >= 0) {\n sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth);\n si += sourceByteWidth;\n ti += targetByteWidth;\n }\n return this;\n }\n\n /**\n * Fills the image with a single color.\n * \n * @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque.\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n fillRGBA(rgba) {\n const buf = this.bitmap.data;\n const bufByteWidth = this.bitmap.height * 4;\n \n let bi = 0;\n while (bi < bufByteWidth) {\n buf.writeUInt32BE(rgba, bi);\n bi += 4;\n }\n while (bi < buf.length) {\n buf.copy(buf, bi, 0, bufByteWidth);\n bi += bufByteWidth;\n }\n return this;\n }\n\n /**\n * Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs.\n * \n * @param {number} x x-coord of pixel\n * @param {number} y y-coord of pixel\n * @return {number} RGBA of pixel in 0xRRGGBBAA form\n */\n\n getRGBA(x, y) {\n const bi = (y * this.bitmap.width + x) * 4;\n return this.bitmap.data.readUInt32BE(bi);\n }\n\n /**\n * Gets a set of all RGBA colors found within the image.\n * \n * @return {Set} Set of all RGBA colors that the image contains.\n */\n\n getRGBASet() {\n const rgbaSet = new Set();\n const buf = this.bitmap.data;\n for (let bi = 0; bi < buf.length; bi += 4) {\n rgbaSet.add(buf.readUInt32BE(bi, true));\n }\n return rgbaSet;\n }\n\n /**\n * Converts the image to greyscale using inferred Adobe metrics.\n * \n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n greyscale() {\n const buf = this.bitmap.data;\n this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => {\n const grey = Math.round(\n 0.299 * buf[idx] +\n 0.587 * buf[idx + 1] +\n 0.114 * buf[idx + 2]\n );\n buf[idx] = grey;\n buf[idx + 1] = grey;\n buf[idx + 2] = grey;\n });\n return this;\n }\n\n /**\n * Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image.\n * \n * @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image.\n * @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image.\n * @param {number} width The width of the new image after reframing\n * @param {number} height The height of the new image after reframing\n * @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop).\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n reframe(xOffset, yOffset, width, height, fillRGBA) {\n const cropX = (xOffset < 0 ? 0 : xOffset);\n const cropY = (yOffset < 0 ? 0 : yOffset);\n const cropWidth = (width + cropX > this.bitmap.width ?\n this.bitmap.width - cropX : width);\n const cropHeight = (height + cropY > this.bitmap.height ?\n this.bitmap.height - cropY : height);\n const newX = (xOffset < 0 ? -xOffset : 0);\n const newY = (yOffset < 0 ? -yOffset : 0);\n\n let image;\n if (fillRGBA === undefined) {\n if (cropX !== xOffset || cropY != yOffset ||\n cropWidth !== width || cropHeight !== height)\n {\n throw new GifError(`fillRGBA required for this reframing`);\n }\n image = new BitmapImage(width, height);\n }\n else {\n image = new BitmapImage(width, height, fillRGBA);\n }\n this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight);\n this.bitmap = image.bitmap;\n return this;\n }\n\n /**\n * Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels.\n * \n * @param {number} factor The factor by which to scale up the image. Must be an integer >= 1.\n * @return {BitmapImage} The present image to allow for chaining.\n */\n\n scale(factor) {\n if (factor === 1) {\n return;\n }\n if (!Number.isInteger(factor) || factor < 1) {\n throw new Error(\"the scale must be an integer >= 1\");\n }\n const sourceWidth = this.bitmap.width;\n const sourceHeight = this.bitmap.height;\n const destByteWidth = sourceWidth * factor * 4;\n const sourceBuf = this.bitmap.data;\n const destBuf = new Buffer(sourceHeight * destByteWidth * factor);\n let sourceIndex = 0;\n let priorDestRowIndex;\n let destIndex = 0;\n for (let y = 0; y < sourceHeight; ++y) {\n priorDestRowIndex = destIndex;\n for (let x = 0; x < sourceWidth; ++x) {\n const color = sourceBuf.readUInt32BE(sourceIndex, true);\n for (let cx = 0; cx < factor; ++cx) {\n destBuf.writeUInt32BE(color, destIndex);\n destIndex += 4;\n }\n sourceIndex += 4;\n }\n for (let cy = 1; cy < factor; ++cy) {\n destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex);\n destIndex += destByteWidth;\n priorDestRowIndex += destByteWidth;\n }\n }\n this.bitmap = {\n width: sourceWidth * factor,\n height: sourceHeight * factor,\n data: destBuf\n };\n return this;\n }\n\n /**\n * Scans all coordinates of the image, handing each in turn to the provided handler function.\n *\n * @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`.\n * @see scanAllIndexes\n */\n\n scanAllCoords(scanHandler) {\n const width = this.bitmap.width;\n const bufferLength = this.bitmap.data.length;\n let x = 0;\n let y = 0;\n\n for (let bi = 0; bi < bufferLength; bi += 4) {\n scanHandler(x, y, bi);\n if (++x === width) {\n x = 0;\n ++y;\n }\n }\n }\n\n /**\n * Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates.\n *\n * @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`.\n * @see scanAllCoords\n */\n\n scanAllIndexes(scanHandler) {\n const bufferLength = this.bitmap.data.length;\n for (let bi = 0; bi < bufferLength; bi += 4) {\n scanHandler(bi);\n }\n }\n}\n\nmodule.exports = BitmapImage;\n","'use strict';\n\n/** @class Gif */\n\nclass Gif {\n\n // width - width of GIF in pixels\n // height - height of GIF in pixels\n // loops - 0 = unending; (n > 0) = iterate n times\n // usesTransparency - whether any frames have transparent pixels\n // colorScope - scope of color tables in GIF\n // frames - array of frames\n // buffer - GIF-formatted data\n\n /**\n * Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class.\n * \n * Property | Description\n * --- | ---\n * width | width of the GIF at its widest\n * height | height of the GIF at its highest\n * loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely\n * usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel\n * colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2).\n * frames | a array of GifFrame instances, one for each frame of the GIF\n * buffer | a Buffer holding the encoding's byte data\n * \n * Its constructor should only ever be called by the GIF encoder or decoder.\n *\n * @param {Buffer} buffer A Buffer containing the encoded bytes\n * @param {GifFrame[]} frames Array of frames found in the encoding\n * @param {object} spec Properties of the encoding as listed above\n */\n\n constructor(buffer, frames, spec) {\n this.width = spec.width;\n this.height = spec.height;\n this.loops = spec.loops;\n this.usesTransparency = spec.usesTransparency;\n this.colorScope = spec.colorScope;\n this.frames = frames;\n this.buffer = buffer;\n }\n}\n\nGif.GlobalColorsPreferred = 0;\nGif.GlobalColorsOnly = 1;\nGif.LocalColorsOnly = 2;\n\n/** @class GifError */\n\nclass GifError extends Error {\n\n /**\n * GifError is a class representing a GIF-related error\n * \n * @param {string|Error} messageOrError\n */\n\n constructor(messageOrError) {\n super(messageOrError);\n if (messageOrError instanceof Error) {\n this.stack = 'Gif' + messageOrError.stack;\n }\n }\n}\n\nexports.Gif = Gif;\nexports.GifError = GifError;\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nimport * as constants from './constants';\nimport * as conversion from './conversion';\nimport * as distance from './distance';\nimport * as palette from './palette';\nimport * as image from './image';\nimport * as quality from './quality';\nimport * as utils from './utils';\n\nexport {\n buildPalette,\n buildPaletteSync,\n applyPalette,\n applyPaletteSync,\n} from './basicAPI';\n\nexport type {\n ImageQuantization,\n PaletteQuantization,\n ColorDistanceFormula,\n} from './basicAPI';\n\nexport { constants, conversion, distance, palette, image, quality, utils };\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * constants.ts - part of Image Quantization Library\n */\nimport * as bt709 from './bt709';\n\nexport { bt709 };\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * constants.ts - part of Image Quantization Library\n */\n\n/**\n * sRGB (based on ITU-R Recommendation BT.709)\n * http://en.wikipedia.org/wiki/SRGB\n */\nexport enum Y {\n RED = 0.2126,\n GREEN = 0.7152,\n BLUE = 0.0722,\n WHITE = 1,\n}\n\nexport enum x {\n RED = 0.64,\n GREEN = 0.3,\n BLUE = 0.15,\n WHITE = 0.3127,\n}\n\nexport enum y {\n RED = 0.33,\n GREEN = 0.6,\n BLUE = 0.06,\n WHITE = 0.329,\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nexport { rgb2xyz } from './rgb2xyz';\nexport { rgb2hsl } from './rgb2hsl';\nexport { rgb2lab } from './rgb2lab';\nexport { lab2xyz } from './lab2xyz';\nexport { lab2rgb } from './lab2rgb';\nexport { xyz2lab } from './xyz2lab';\nexport { xyz2rgb } from './xyz2rgb';\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2xyz.ts - part of Image Quantization Library\n */\nfunction correctGamma(n: number) {\n return n > 0.04045 ? ((n + 0.055) / 1.055) ** 2.4 : n / 12.92;\n}\n\nexport function rgb2xyz(r: number, g: number, b: number) {\n // gamma correction, see https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation\n r = correctGamma(r / 255);\n g = correctGamma(g / 255);\n b = correctGamma(b / 255);\n\n // Observer. = 2°, Illuminant = D65\n return {\n x: r * 0.4124 + g * 0.3576 + b * 0.1805,\n y: r * 0.2126 + g * 0.7152 + b * 0.0722,\n z: r * 0.0193 + g * 0.1192 + b * 0.9505,\n };\n}\n","export function degrees2radians(n: number) {\n return n * (Math.PI / 180);\n}\n\nexport function max3(a: number, b: number, c: number) {\n let m = a;\n if (m < b) m = b;\n if (m < c) m = c;\n return m;\n}\n\nexport function min3(a: number, b: number, c: number) {\n let m = a;\n if (m > b) m = b;\n if (m > c) m = c;\n return m;\n}\n\nexport function intInRange(value: number, low: number, high: number) {\n if (value > high) value = high;\n if (value < low) value = low;\n return value | 0;\n}\n\nexport function inRange0to255Rounded(n: number) {\n n = Math.round(n);\n if (n > 255) n = 255;\n else if (n < 0) n = 0;\n return n;\n}\n\nexport function inRange0to255(n: number) {\n if (n > 255) n = 255;\n else if (n < 0) n = 0;\n return n;\n}\n\nexport function stableSort(\n arrayToSort: T[],\n callback: (a: T, b: T) => number,\n) {\n const type = typeof arrayToSort[0];\n let sorted: T[];\n\n if (type === 'number' || type === 'string') {\n const ord = Object.create(null);\n for (let i = 0, l = arrayToSort.length; i < l; i++) {\n const val = arrayToSort[i] as unknown as string;\n if (ord[val] || ord[val] === 0) continue;\n ord[val] = i;\n }\n\n sorted = arrayToSort.sort((a, b) => callback(a, b) || ord[a] - ord[b]);\n } else {\n const ord2 = arrayToSort.slice(0);\n sorted = arrayToSort.sort(\n (a, b) => callback(a, b) || ord2.indexOf(a) - ord2.indexOf(b),\n );\n }\n\n return sorted;\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2hsl.ts - part of Image Quantization Library\n */\nimport { min3, max3 } from '../utils/arithmetic';\n\n/**\n * Calculate HSL from RGB\n * Hue is in degrees [0..360]\n * Lightness: [0..1]\n * Saturation: [0..1]\n * http://web.archive.org/web/20060914040436/http://local.wasp.uwa.edu.au/~pbourke/colour/hsl/\n */\nexport function rgb2hsl(r: number, g: number, b: number) {\n const min = min3(r, g, b);\n const max = max3(r, g, b);\n const delta = max - min;\n const l = (min + max) / 510;\n\n let s = 0;\n if (l > 0 && l < 1) s = delta / (l < 0.5 ? max + min : 510 - max - min);\n\n let h = 0;\n if (delta > 0) {\n if (max === r) {\n h = (g - b) / delta;\n } else if (max === g) {\n h = 2 + (b - r) / delta;\n } else {\n h = 4 + (r - g) / delta;\n }\n\n h *= 60;\n if (h < 0) h += 360;\n }\n return { h, s, l };\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * xyz2lab.ts - part of Image Quantization Library\n */\nconst refX = 0.95047; // ref_X = 95.047 Observer= 2°, Illuminant= D65\nconst refY = 1.0; // ref_Y = 100.000\nconst refZ = 1.08883; // ref_Z = 108.883\n\nfunction pivot(n: number) {\n return n > 0.008856 ? n ** (1 / 3) : 7.787 * n + 16 / 116;\n}\n\nexport function xyz2lab(x: number, y: number, z: number) {\n x = pivot(x / refX);\n y = pivot(y / refY);\n z = pivot(z / refZ);\n\n if (116 * y - 16 < 0) throw new Error('xxx');\n return {\n L: Math.max(0, 116 * y - 16),\n a: 500 * (x - y),\n b: 200 * (y - z),\n };\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgb2lab.ts - part of Image Quantization Library\n */\nimport { rgb2xyz } from './rgb2xyz';\nimport { xyz2lab } from './xyz2lab';\n\nexport function rgb2lab(r: number, g: number, b: number) {\n const xyz = rgb2xyz(r, g, b);\n return xyz2lab(xyz.x, xyz.y, xyz.z);\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * lab2xyz.ts - part of Image Quantization Library\n */\nconst refX = 0.95047; // ref_X = 95.047 Observer= 2°, Illuminant = D65\nconst refY = 1.0; // ref_Y = 100.000\nconst refZ = 1.08883; // ref_Z = 108.883\n\nfunction pivot(n: number) {\n return n > 0.206893034 ? n ** 3 : (n - 16 / 116) / 7.787;\n}\n\nexport function lab2xyz(L: number, a: number, b: number) {\n const y = (L + 16) / 116;\n const x = a / 500 + y;\n const z = y - b / 200;\n\n return {\n x: refX * pivot(x),\n y: refY * pivot(y),\n z: refZ * pivot(z),\n };\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * xyz2rgb.ts - part of Image Quantization Library\n */\nimport { inRange0to255Rounded } from '../utils/arithmetic';\n\n// gamma correction, see https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation\nfunction correctGamma(n: number) {\n return n > 0.0031308 ? 1.055 * n ** (1 / 2.4) - 0.055 : 12.92 * n;\n}\n\nexport function xyz2rgb(x: number, y: number, z: number) {\n // Observer. = 2°, Illuminant = D65\n const r = correctGamma(x * 3.2406 + y * -1.5372 + z * -0.4986);\n const g = correctGamma(x * -0.9689 + y * 1.8758 + z * 0.0415);\n const b = correctGamma(x * 0.0557 + y * -0.204 + z * 1.057);\n\n return {\n r: inRange0to255Rounded(r * 255),\n g: inRange0to255Rounded(g * 255),\n b: inRange0to255Rounded(b * 255),\n };\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * lab2rgb.ts - part of Image Quantization Library\n */\nimport { lab2xyz } from './lab2xyz';\nimport { xyz2rgb } from './xyz2rgb';\n\nexport function lab2rgb(L: number, a: number, b: number) {\n const xyz = lab2xyz(L, a, b);\n return xyz2rgb(xyz.x, xyz.y, xyz.z);\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nexport { AbstractDistanceCalculator } from './distanceCalculator';\nexport { CIE94Textiles, CIE94GraphicArts } from './cie94';\nexport { CIEDE2000 } from './ciede2000';\nexport { CMetric } from './cmetric';\nexport {\n AbstractEuclidean,\n Euclidean,\n EuclideanBT709NoAlpha,\n EuclideanBT709,\n} from './euclidean';\nexport {\n AbstractManhattan,\n Manhattan,\n ManhattanBT709,\n ManhattanNommyde,\n} from './manhattan';\nexport { PNGQuant } from './pngQuant';\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * common.ts - part of Image Quantization Library\n */\nimport { PointRGBA } from '../utils/point';\n\nexport abstract class AbstractDistanceCalculator {\n protected _maxDistance!: number;\n protected _whitePoint!: {\n r: number;\n g: number;\n b: number;\n a: number;\n };\n\n constructor() {\n this._setDefaults();\n\n // set default maximal color component deltas (255 - 0 = 255)\n this.setWhitePoint(255, 255, 255, 255);\n }\n\n setWhitePoint(r: number, g: number, b: number, a: number) {\n this._whitePoint = {\n r: r > 0 ? 255 / r : 0,\n g: g > 0 ? 255 / g : 0,\n b: b > 0 ? 255 / b : 0,\n a: a > 0 ? 255 / a : 0,\n };\n this._maxDistance = this.calculateRaw(r, g, b, a, 0, 0, 0, 0);\n }\n\n calculateNormalized(colorA: PointRGBA, colorB: PointRGBA) {\n return (\n this.calculateRaw(\n colorA.r,\n colorA.g,\n colorA.b,\n colorA.a,\n colorB.r,\n colorB.g,\n colorB.b,\n colorB.a,\n ) / this._maxDistance\n );\n }\n\n /**\n * Calculate raw distance (non-normalized)\n */\n abstract calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ): number;\n\n protected abstract _setDefaults(): void;\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * cie94.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\nimport { rgb2lab } from '../conversion/rgb2lab';\nimport { inRange0to255 } from '../utils/arithmetic';\n\n/**\n * CIE94 method of delta-e\n * http://en.wikipedia.org/wiki/Color_difference#CIE94\n */\nexport abstract class AbstractCIE94 extends AbstractDistanceCalculator {\n /**\n * Weight in distance: 0.25\n * Max DeltaE: 100\n * Max DeltaA: 255\n */\n declare protected _kA: number;\n declare protected _Kl: number;\n declare protected _K1: number;\n declare protected _K2: number;\n\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n const lab1 = rgb2lab(\n inRange0to255(r1 * this._whitePoint.r),\n inRange0to255(g1 * this._whitePoint.g),\n inRange0to255(b1 * this._whitePoint.b),\n );\n const lab2 = rgb2lab(\n inRange0to255(r2 * this._whitePoint.r),\n inRange0to255(g2 * this._whitePoint.g),\n inRange0to255(b2 * this._whitePoint.b),\n );\n\n const dL = lab1.L - lab2.L;\n const dA = lab1.a - lab2.a;\n const dB = lab1.b - lab2.b;\n const c1 = Math.sqrt(lab1.a * lab1.a + lab1.b * lab1.b);\n const c2 = Math.sqrt(lab2.a * lab2.a + lab2.b * lab2.b);\n const dC = c1 - c2;\n\n let deltaH = dA * dA + dB * dB - dC * dC;\n deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH);\n\n const dAlpha = (a2 - a1) * this._whitePoint.a * this._kA;\n\n // TODO: add alpha channel support\n return Math.sqrt(\n (dL / this._Kl) ** 2 +\n (dC / (1.0 + this._K1 * c1)) ** 2 +\n (deltaH / (1.0 + this._K2 * c1)) ** 2 +\n dAlpha ** 2,\n );\n }\n}\n\nexport class CIE94Textiles extends AbstractCIE94 {\n protected _setDefaults() {\n this._Kl = 2.0;\n this._K1 = 0.048;\n this._K2 = 0.014;\n this._kA = (0.25 * 50) / 255;\n }\n}\n\nexport class CIE94GraphicArts extends AbstractCIE94 {\n protected _setDefaults() {\n this._Kl = 1.0;\n this._K1 = 0.045;\n this._K2 = 0.015;\n this._kA = (0.25 * 100) / 255;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ciede2000.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\nimport { rgb2lab } from '../conversion/rgb2lab';\nimport { degrees2radians, inRange0to255 } from '../utils/arithmetic';\n\n/**\n * CIEDE2000 algorithm - Adapted from Sharma et al's MATLAB implementation at\n * http://www.ece.rochester.edu/~gsharma/ciede2000/\n */\nexport class CIEDE2000 extends AbstractDistanceCalculator {\n /**\n * Weight in distance: 0.25\n * Max DeltaE: 100\n * Max DeltaA: 255\n */\n private static readonly _kA = (0.25 * 100) / 255;\n private static readonly _pow25to7 = 25 ** 7;\n private static readonly _deg360InRad = degrees2radians(360);\n private static readonly _deg180InRad = degrees2radians(180);\n private static readonly _deg30InRad = degrees2radians(30);\n private static readonly _deg6InRad = degrees2radians(6);\n private static readonly _deg63InRad = degrees2radians(63);\n private static readonly _deg275InRad = degrees2radians(275);\n private static readonly _deg25InRad = degrees2radians(25);\n\n protected _setDefaults() {}\n\n private static _calculatehp(b: number, ap: number) {\n const hp = Math.atan2(b, ap);\n if (hp >= 0) return hp;\n return hp + CIEDE2000._deg360InRad;\n }\n\n private static _calculateRT(ahp: number, aCp: number) {\n const aCp_to_7 = aCp ** 7.0;\n const R_C = 2.0 * Math.sqrt(aCp_to_7 / (aCp_to_7 + CIEDE2000._pow25to7)); // 25^7\n const delta_theta =\n CIEDE2000._deg30InRad *\n Math.exp(\n -(((ahp - CIEDE2000._deg275InRad) / CIEDE2000._deg25InRad) ** 2.0),\n );\n return -Math.sin(2.0 * delta_theta) * R_C;\n }\n\n private static _calculateT(ahp: number) {\n return (\n 1.0 -\n 0.17 * Math.cos(ahp - CIEDE2000._deg30InRad) +\n 0.24 * Math.cos(ahp * 2.0) +\n 0.32 * Math.cos(ahp * 3.0 + CIEDE2000._deg6InRad) -\n 0.2 * Math.cos(ahp * 4.0 - CIEDE2000._deg63InRad)\n );\n }\n\n private static _calculate_ahp(\n C1pC2p: number,\n h_bar: number,\n h1p: number,\n h2p: number,\n ) {\n const hpSum = h1p + h2p;\n if (C1pC2p === 0) return hpSum;\n if (h_bar <= CIEDE2000._deg180InRad) return hpSum / 2.0;\n if (hpSum < CIEDE2000._deg360InRad) {\n return (hpSum + CIEDE2000._deg360InRad) / 2.0;\n }\n return (hpSum - CIEDE2000._deg360InRad) / 2.0;\n }\n\n private static _calculate_dHp(\n C1pC2p: number,\n h_bar: number,\n h2p: number,\n h1p: number,\n ) {\n let dhp;\n if (C1pC2p === 0) {\n dhp = 0;\n } else if (h_bar <= CIEDE2000._deg180InRad) {\n dhp = h2p - h1p;\n } else if (h2p <= h1p) {\n dhp = h2p - h1p + CIEDE2000._deg360InRad;\n } else {\n dhp = h2p - h1p - CIEDE2000._deg360InRad;\n }\n return 2.0 * Math.sqrt(C1pC2p) * Math.sin(dhp / 2.0);\n }\n\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n const lab1 = rgb2lab(\n inRange0to255(r1 * this._whitePoint.r),\n inRange0to255(g1 * this._whitePoint.g),\n inRange0to255(b1 * this._whitePoint.b),\n );\n const lab2 = rgb2lab(\n inRange0to255(r2 * this._whitePoint.r),\n inRange0to255(g2 * this._whitePoint.g),\n inRange0to255(b2 * this._whitePoint.b),\n );\n const dA = (a2 - a1) * this._whitePoint.a * CIEDE2000._kA;\n const dE2 = this.calculateRawInLab(lab1, lab2);\n\n return Math.sqrt(dE2 + dA * dA);\n }\n\n calculateRawInLab(\n Lab1: { L: number; a: number; b: number },\n Lab2: { L: number; a: number; b: number },\n ) {\n // Get L,a,b values for color 1\n const L1 = Lab1.L;\n const a1 = Lab1.a;\n const b1 = Lab1.b;\n\n // Get L,a,b values for color 2\n const L2 = Lab2.L;\n const a2 = Lab2.a;\n const b2 = Lab2.b;\n\n // Calculate Cprime1, Cprime2, Cabbar\n const C1 = Math.sqrt(a1 * a1 + b1 * b1);\n const C2 = Math.sqrt(a2 * a2 + b2 * b2);\n const pow_a_C1_C2_to_7 = ((C1 + C2) / 2.0) ** 7.0;\n\n const G =\n 0.5 *\n (1.0 -\n Math.sqrt(pow_a_C1_C2_to_7 / (pow_a_C1_C2_to_7 + CIEDE2000._pow25to7))); // 25^7\n const a1p = (1.0 + G) * a1;\n const a2p = (1.0 + G) * a2;\n\n const C1p = Math.sqrt(a1p * a1p + b1 * b1);\n const C2p = Math.sqrt(a2p * a2p + b2 * b2);\n const C1pC2p = C1p * C2p;\n\n // Angles in Degree.\n const h1p = CIEDE2000._calculatehp(b1, a1p);\n const h2p = CIEDE2000._calculatehp(b2, a2p);\n const h_bar = Math.abs(h1p - h2p);\n const dLp = L2 - L1;\n const dCp = C2p - C1p;\n const dHp = CIEDE2000._calculate_dHp(C1pC2p, h_bar, h2p, h1p);\n const ahp = CIEDE2000._calculate_ahp(C1pC2p, h_bar, h1p, h2p);\n\n const T = CIEDE2000._calculateT(ahp);\n\n const aCp = (C1p + C2p) / 2.0;\n const aLp_minus_50_square = ((L1 + L2) / 2.0 - 50.0) ** 2.0;\n const S_L =\n 1.0 +\n (0.015 * aLp_minus_50_square) / Math.sqrt(20.0 + aLp_minus_50_square);\n const S_C = 1.0 + 0.045 * aCp;\n const S_H = 1.0 + 0.015 * T * aCp;\n\n const R_T = CIEDE2000._calculateRT(ahp, aCp);\n\n const dLpSL = dLp / S_L; // S_L * kL, where kL is 1.0\n const dCpSC = dCp / S_C; // S_C * kC, where kC is 1.0\n const dHpSH = dHp / S_H; // S_H * kH, where kH is 1.0\n\n return dLpSL ** 2 + dCpSC ** 2 + dHpSH ** 2 + R_T * dCpSC * dHpSH;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * cmetric.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\n\n/**\n * TODO: Name it: http://www.compuphase.com/cmetric.htm\n */\nexport class CMetric extends AbstractDistanceCalculator {\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n const rmean = ((r1 + r2) / 2) * this._whitePoint.r;\n const r = (r1 - r2) * this._whitePoint.r;\n const g = (g1 - g2) * this._whitePoint.g;\n const b = (b1 - b2) * this._whitePoint.b;\n const dE =\n (((512 + rmean) * r * r) >> 8) +\n 4 * g * g +\n (((767 - rmean) * b * b) >> 8);\n const dA = (a2 - a1) * this._whitePoint.a;\n\n return Math.sqrt(dE + dA * dA);\n }\n\n protected _setDefaults() {}\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * euclidean.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\nimport { Y } from '../constants/bt709';\n\n/**\n * Euclidean color distance\n */\nexport abstract class AbstractEuclidean extends AbstractDistanceCalculator {\n declare protected _kR: number;\n declare protected _kG: number;\n declare protected _kB: number;\n declare protected _kA: number;\n\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n const dR = r2 - r1;\n const dG = g2 - g1;\n const dB = b2 - b1;\n const dA = a2 - a1;\n return Math.sqrt(\n this._kR * dR * dR +\n this._kG * dG * dG +\n this._kB * dB * dB +\n this._kA * dA * dA,\n );\n }\n}\n\nexport class Euclidean extends AbstractEuclidean {\n protected _setDefaults() {\n this._kR = 1;\n this._kG = 1;\n this._kB = 1;\n this._kA = 1;\n }\n}\n\n/**\n * Euclidean color distance (RGBQuant modification w Alpha)\n */\nexport class EuclideanBT709 extends AbstractEuclidean {\n protected _setDefaults() {\n this._kR = Y.RED;\n this._kG = Y.GREEN;\n this._kB = Y.BLUE;\n // TODO: what is the best coefficient below?\n this._kA = 1;\n }\n}\n\n/**\n * Euclidean color distance (RGBQuant modification w/o Alpha)\n */\nexport class EuclideanBT709NoAlpha extends AbstractEuclidean {\n protected _setDefaults() {\n this._kR = Y.RED;\n this._kG = Y.GREEN;\n this._kB = Y.BLUE;\n this._kA = 0;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * manhattanNeuQuant.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\nimport { Y } from '../constants/bt709';\n\n/**\n * Manhattan distance (NeuQuant modification) - w/o sRGB coefficients\n */\nexport abstract class AbstractManhattan extends AbstractDistanceCalculator {\n declare protected _kR: number;\n declare protected _kG: number;\n declare protected _kB: number;\n declare protected _kA: number;\n\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n let dR = r2 - r1;\n let dG = g2 - g1;\n let dB = b2 - b1;\n let dA = a2 - a1;\n if (dR < 0) dR = 0 - dR;\n if (dG < 0) dG = 0 - dG;\n if (dB < 0) dB = 0 - dB;\n if (dA < 0) dA = 0 - dA;\n\n return this._kR * dR + this._kG * dG + this._kB * dB + this._kA * dA;\n }\n}\n\nexport class Manhattan extends AbstractManhattan {\n protected _setDefaults() {\n this._kR = 1;\n this._kG = 1;\n this._kB = 1;\n this._kA = 1;\n }\n}\n\n/**\n * Manhattan distance (Nommyde modification)\n * https://github.com/igor-bezkrovny/image-quantization/issues/4#issuecomment-235155320\n */\nexport class ManhattanNommyde extends AbstractManhattan {\n protected _setDefaults() {\n this._kR = 0.4984;\n this._kG = 0.8625;\n this._kB = 0.2979;\n // TODO: what is the best coefficient below?\n this._kA = 1;\n }\n}\n\n/**\n * Manhattan distance (sRGB coefficients)\n */\nexport class ManhattanBT709 extends AbstractManhattan {\n protected _setDefaults() {\n this._kR = Y.RED;\n this._kG = Y.GREEN;\n this._kB = Y.BLUE;\n // TODO: what is the best coefficient below?\n this._kA = 1;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * pngQuant.ts - part of Image Quantization Library\n */\nimport { AbstractDistanceCalculator } from './distanceCalculator';\n\n/**\n * TODO: check quality of this distance equation\n * TODO: ask author for usage rights\n * taken from:\n * {@link http://stackoverflow.com/questions/4754506/color-similarity-distance-in-rgba-color-space/8796867#8796867}\n * {@link https://github.com/pornel/pngquant/blob/cc39b47799a7ff2ef17b529f9415ff6e6b213b8f/lib/pam.h#L148}\n */\nexport class PNGQuant extends AbstractDistanceCalculator {\n /**\n * Author's comments\n * px_b.rgb = px.rgb + 0*(1-px.a) // blend px on black\n * px_b.a = px.a + 1*(1-px.a)\n * px_w.rgb = px.rgb + 1*(1-px.a) // blend px on white\n * px_w.a = px.a + 1*(1-px.a)\n *\n * px_b.rgb = px.rgb // difference same as in opaque RGB\n * px_b.a = 1\n * px_w.rgb = px.rgb - px.a // difference simplifies to formula below\n * px_w.a = 1\n *\n * (px.rgb - px.a) - (py.rgb - py.a)\n * (px.rgb - py.rgb) + (py.a - px.a)\n *\n */\n calculateRaw(\n r1: number,\n g1: number,\n b1: number,\n a1: number,\n r2: number,\n g2: number,\n b2: number,\n a2: number,\n ) {\n const alphas = (a2 - a1) * this._whitePoint.a;\n return (\n this._colordifferenceCh(\n r1 * this._whitePoint.r,\n r2 * this._whitePoint.r,\n alphas,\n ) +\n this._colordifferenceCh(\n g1 * this._whitePoint.g,\n g2 * this._whitePoint.g,\n alphas,\n ) +\n this._colordifferenceCh(\n b1 * this._whitePoint.b,\n b2 * this._whitePoint.b,\n alphas,\n )\n );\n }\n\n private _colordifferenceCh(x: number, y: number, alphas: number) {\n // maximum of channel blended on white, and blended on black\n // premultiplied alpha and backgrounds 0/1 shorten the formula\n const black = x - y;\n const white = black + alphas;\n\n return black * black + white * white;\n }\n\n protected _setDefaults() {}\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nexport { AbstractPaletteQuantizer } from './paletteQuantizer';\nexport { NeuQuant } from './neuquant/neuquant';\nexport { NeuQuantFloat } from './neuquant/neuquantFloat';\nexport { RGBQuant } from './rgbquant/rgbquant';\nexport { ColorHistogram } from './rgbquant/colorHistogram';\nexport { WuQuant, WuColorCube } from './wu/wuQuant';\nexport { PaletteQuantizerYieldValue } from './paletteQuantizerYieldValue';\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * common.ts - part of Image Quantization Library\n */\nimport { PointContainer } from '../utils/pointContainer';\nimport { PaletteQuantizerYieldValue } from './paletteQuantizerYieldValue';\n\nexport abstract class AbstractPaletteQuantizer {\n abstract sample(pointContainer: PointContainer): void;\n abstract quantize(): IterableIterator;\n\n quantizeSync() {\n for (const value of this.quantize()) {\n if (value.palette) {\n return value.palette;\n }\n }\n\n throw new Error('unreachable');\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * point.ts - part of Image Quantization Library\n */\nimport { Y } from '../constants/bt709';\n\nexport interface PointRGBA {\n r: number;\n g: number;\n b: number;\n a: number;\n}\n\n/**\n * v8 optimized class\n * 1) \"constructor\" should have initialization with worst types\n * 2) \"set\" should have |0 / >>> 0\n */\nexport class Point implements PointRGBA {\n r: number;\n g: number;\n b: number;\n a: number;\n uint32: number;\n rgba: number[]; // TODO: better name is quadruplet or quad may be?\n // Lab : { L : number; a : number; b : number };\n\n static createByQuadruplet(quadruplet: number[]) {\n const point = new Point();\n\n point.r = quadruplet[0] | 0;\n point.g = quadruplet[1] | 0;\n point.b = quadruplet[2] | 0;\n point.a = quadruplet[3] | 0;\n point._loadUINT32();\n point._loadQuadruplet();\n // point._loadLab();\n return point;\n }\n\n static createByRGBA(red: number, green: number, blue: number, alpha: number) {\n const point = new Point();\n\n point.r = red | 0;\n point.g = green | 0;\n point.b = blue | 0;\n point.a = alpha | 0;\n point._loadUINT32();\n point._loadQuadruplet();\n // point._loadLab();\n return point;\n }\n\n static createByUint32(uint32: number) {\n const point = new Point();\n\n point.uint32 = uint32 >>> 0;\n point._loadRGBA();\n point._loadQuadruplet();\n // point._loadLab();\n return point;\n }\n\n constructor() {\n this.uint32 = -1 >>> 0;\n this.r = this.g = this.b = this.a = 0;\n this.rgba = new Array(4);\n this.rgba[0] = 0;\n this.rgba[1] = 0;\n this.rgba[2] = 0;\n this.rgba[3] = 0;\n /*\n this.Lab = {\n L : 0.0,\n a : 0.0,\n b : 0.0\n };\n */\n }\n\n from(point: Point) {\n this.r = point.r;\n this.g = point.g;\n this.b = point.b;\n this.a = point.a;\n this.uint32 = point.uint32;\n this.rgba[0] = point.r;\n this.rgba[1] = point.g;\n this.rgba[2] = point.b;\n this.rgba[3] = point.a;\n\n /*\n this.Lab.L = point.Lab.L;\n this.Lab.a = point.Lab.a;\n this.Lab.b = point.Lab.b;\n */\n }\n\n /*\n * TODO:\n Luminance from RGB:\n\n Luminance (standard for certain colour spaces): (0.2126*R + 0.7152*G + 0.0722*B) [1]\n Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B) [2]\n Luminance (perceived option 2, slower to calculate): sqrt( 0.241*R^2 + 0.691*G^2 + 0.068*B^2 ) ? sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 ) (thanks to @MatthewHerbst) [http://alienryderflex.com/hsp.html]\n */\n getLuminosity(useAlphaChannel: boolean) {\n let r = this.r;\n let g = this.g;\n let b = this.b;\n\n if (useAlphaChannel) {\n r = Math.min(255, 255 - this.a + (this.a * r) / 255);\n g = Math.min(255, 255 - this.a + (this.a * g) / 255);\n b = Math.min(255, 255 - this.a + (this.a * b) / 255);\n }\n\n // var luma = this.r * Point._RED_COEFFICIENT + this.g * Point._GREEN_COEFFICIENT + this.b * Point._BLUE_COEFFICIENT;\n\n /*\n if(useAlphaChannel) {\n luma = (luma * (255 - this.a)) / 255;\n }\n */\n\n return r * Y.RED + g * Y.GREEN + b * Y.BLUE;\n }\n\n private _loadUINT32() {\n this.uint32 =\n ((this.a << 24) | (this.b << 16) | (this.g << 8) | this.r) >>> 0;\n }\n\n private _loadRGBA() {\n this.r = this.uint32 & 0xff;\n this.g = (this.uint32 >>> 8) & 0xff;\n this.b = (this.uint32 >>> 16) & 0xff;\n this.a = (this.uint32 >>> 24) & 0xff;\n }\n\n private _loadQuadruplet() {\n this.rgba[0] = this.r;\n this.rgba[1] = this.g;\n this.rgba[2] = this.b;\n this.rgba[3] = this.a;\n\n /*\n var xyz = rgb2xyz(this.r, this.g, this.b);\n var lab = xyz2lab(xyz.x, xyz.y, xyz.z);\n this.lab.l = lab.l;\n this.lab.a = lab.a;\n this.lab.b = lab.b;\n */\n }\n\n /*\n private _loadLab() : void {\n var Lab = Color.Conversion.rgb2lab(this.r, this.g, this.b);\n this.Lab.L = Lab.L;\n this.Lab.a = Lab.a;\n this.Lab.b = Lab.b;\n }\n */\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * pointContainer.ts - part of Image Quantization Library\n */\nimport { Point } from './point';\n\n/**\n * v8 optimizations done.\n * fromXXX methods are static to move out polymorphic code from class instance itself.\n */\nexport class PointContainer {\n private readonly _pointArray: Point[];\n private _width: number;\n private _height: number;\n\n constructor() {\n this._width = 0;\n this._height = 0;\n this._pointArray = [];\n }\n\n getWidth() {\n return this._width;\n }\n\n getHeight() {\n return this._height;\n }\n\n setWidth(width: number) {\n this._width = width;\n }\n\n setHeight(height: number) {\n this._height = height;\n }\n\n getPointArray() {\n return this._pointArray;\n }\n\n clone() {\n const clone = new PointContainer();\n clone._width = this._width;\n clone._height = this._height;\n\n for (let i = 0, l = this._pointArray.length; i < l; i++) {\n clone._pointArray[i] = Point.createByUint32(\n this._pointArray[i].uint32 | 0,\n ); // \"| 0\" is added for v8 optimization\n }\n\n return clone;\n }\n\n toUint32Array() {\n const l = this._pointArray.length;\n const uint32Array = new Uint32Array(l);\n\n for (let i = 0; i < l; i++) {\n uint32Array[i] = this._pointArray[i].uint32;\n }\n\n return uint32Array;\n }\n\n toUint8Array() {\n return new Uint8Array(this.toUint32Array().buffer);\n }\n\n static fromHTMLImageElement(img: HTMLImageElement) {\n const width = img.naturalWidth;\n const height = img.naturalHeight;\n\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0, width, height, 0, 0, width, height);\n\n return PointContainer.fromHTMLCanvasElement(canvas);\n }\n\n static fromHTMLCanvasElement(canvas: HTMLCanvasElement) {\n const width = canvas.width;\n const height = canvas.height;\n\n const ctx = canvas.getContext('2d')!;\n const imgData = ctx.getImageData(0, 0, width, height);\n\n return PointContainer.fromImageData(imgData);\n }\n\n static fromImageData(imageData: ImageData) {\n const width = imageData.width;\n const height = imageData.height;\n\n return PointContainer.fromUint8Array(imageData.data, width, height);\n }\n\n static fromUint8Array(\n uint8Array: number[] | Uint8Array | Uint8ClampedArray,\n width: number,\n height: number,\n ) {\n switch (Object.prototype.toString.call(uint8Array)) {\n case '[object Uint8ClampedArray]':\n case '[object Uint8Array]':\n break;\n\n default:\n uint8Array = new Uint8Array(uint8Array);\n }\n\n const uint32Array = new Uint32Array((uint8Array as Uint8Array).buffer);\n return PointContainer.fromUint32Array(uint32Array, width, height);\n }\n\n static fromUint32Array(\n uint32Array: Uint32Array,\n width: number,\n height: number,\n ) {\n const container = new PointContainer();\n\n container._width = width;\n container._height = height;\n\n for (let i = 0, l = uint32Array.length; i < l; i++) {\n container._pointArray[i] = Point.createByUint32(uint32Array[i] | 0); // \"| 0\" is added for v8 optimization\n }\n\n return container;\n }\n\n static fromBuffer(buffer: Buffer, width: number, height: number) {\n const uint32Array = new Uint32Array(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength / Uint32Array.BYTES_PER_ELEMENT,\n );\n return PointContainer.fromUint32Array(uint32Array, width, height);\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * palette.ts - part of Image Quantization Library\n */\n\nimport { Point } from './point';\nimport { PointContainer } from './pointContainer';\nimport { AbstractDistanceCalculator } from '../distance/distanceCalculator';\nimport { rgb2hsl } from '../conversion/rgb2hsl';\n\n// TODO: make paletteArray via pointContainer, so, export will be available via pointContainer.exportXXX\n\nconst hueGroups = 10;\n\nexport function hueGroup(hue: number, segmentsNumber: number) {\n const maxHue = 360;\n const seg = maxHue / segmentsNumber;\n const half = seg / 2;\n\n for (let i = 1, mid = seg - half; i < segmentsNumber; i++, mid += seg) {\n if (hue >= mid && hue < mid + seg) return i;\n }\n return 0;\n}\n\nexport class Palette {\n private readonly _pointContainer: PointContainer;\n private readonly _pointArray: Point[] = [];\n private _i32idx: { [key: string]: number } = {};\n\n constructor() {\n this._pointContainer = new PointContainer();\n this._pointContainer.setHeight(1);\n this._pointArray = this._pointContainer.getPointArray();\n }\n\n add(color: Point) {\n this._pointArray.push(color);\n this._pointContainer.setWidth(this._pointArray.length);\n }\n\n has(color: Point) {\n for (let i = this._pointArray.length - 1; i >= 0; i--) {\n if (color.uint32 === this._pointArray[i].uint32) return true;\n }\n\n return false;\n }\n\n // TOTRY: use HUSL - http://boronine.com/husl/ http://www.husl-colors.org/ https://github.com/husl-colors/husl\n getNearestColor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n color: Point,\n ) {\n return this._pointArray[\n this._getNearestIndex(colorDistanceCalculator, color) | 0\n ];\n }\n\n getPointContainer() {\n return this._pointContainer;\n }\n\n // TOTRY: use HUSL - http://boronine.com/husl/\n /*\n public nearestIndexByUint32(i32) {\n var idx : number = this._nearestPointFromCache(\"\" + i32);\n if (idx >= 0) return idx;\n\n var min = 1000,\n rgb = [\n (i32 & 0xff),\n (i32 >>> 8) & 0xff,\n (i32 >>> 16) & 0xff,\n (i32 >>> 24) & 0xff\n ],\n len = this._pointArray.length;\n\n idx = 0;\n for (var i = 0; i < len; i++) {\n var dist = Utils.distEuclidean(rgb, this._pointArray[i].rgba);\n\n if (dist < min) {\n min = dist;\n idx = i;\n }\n }\n\n this._i32idx[i32] = idx;\n return idx;\n }\n */\n\n private _nearestPointFromCache(key: string) {\n return typeof this._i32idx[key] === 'number' ? this._i32idx[key] : -1;\n }\n\n private _getNearestIndex(\n colorDistanceCalculator: AbstractDistanceCalculator,\n point: Point,\n ) {\n let idx = this._nearestPointFromCache('' + point.uint32);\n if (idx >= 0) return idx;\n\n let minimalDistance = Number.MAX_VALUE;\n\n idx = 0;\n for (let i = 0, l = this._pointArray.length; i < l; i++) {\n const p = this._pointArray[i];\n const distance = colorDistanceCalculator.calculateRaw(\n point.r,\n point.g,\n point.b,\n point.a,\n p.r,\n p.g,\n p.b,\n p.a,\n );\n\n if (distance < minimalDistance) {\n minimalDistance = distance;\n idx = i;\n }\n }\n\n this._i32idx[point.uint32] = idx;\n return idx;\n }\n\n /*\n public reduce(histogram : ColorHistogram, colors : number) {\n if (this._pointArray.length > colors) {\n var idxi32 = histogram.getImportanceSortedColorsIDXI32();\n\n // quantize histogram to existing palette\n var keep = [], uniqueColors = 0, idx, pruned = false;\n\n for (var i = 0, len = idxi32.length; i < len; i++) {\n // palette length reached, unset all remaining colors (sparse palette)\n if (uniqueColors >= colors) {\n this.prunePal(keep);\n pruned = true;\n break;\n } else {\n idx = this.nearestIndexByUint32(idxi32[i]);\n if (keep.indexOf(idx) < 0) {\n keep.push(idx);\n uniqueColors++;\n }\n }\n }\n\n if (!pruned) {\n this.prunePal(keep);\n }\n }\n }\n\n // TODO: check usage, not tested!\n public prunePal(keep : number[]) {\n var colors = this._pointArray.length;\n for (var colorIndex = colors - 1; colorIndex >= 0; colorIndex--) {\n if (keep.indexOf(colorIndex) < 0) {\n\n if(colorIndex + 1 < colors) {\n this._pointArray[ colorIndex ] = this._pointArray [ colors - 1 ];\n }\n --colors;\n //this._pointArray[colorIndex] = null;\n }\n }\n console.log(\"colors pruned: \" + (this._pointArray.length - colors));\n this._pointArray.length = colors;\n this._i32idx = {};\n }\n */\n\n // TODO: group very low lum and very high lum colors\n // TODO: pass custom sort order\n // TODO: sort criteria function should be placed to HueStats class\n sort() {\n this._i32idx = {};\n this._pointArray.sort((a: Point, b: Point) => {\n const hslA = rgb2hsl(a.r, a.g, a.b);\n const hslB = rgb2hsl(b.r, b.g, b.b);\n\n // sort all grays + whites together\n const hueA =\n a.r === a.g && a.g === a.b ? 0 : 1 + hueGroup(hslA.h, hueGroups);\n const hueB =\n b.r === b.g && b.g === b.b ? 0 : 1 + hueGroup(hslB.h, hueGroups);\n /*\n var hueA = (a.r === a.g && a.g === a.b) ? 0 : 1 + Utils.hueGroup(hslA.h, hueGroups);\n var hueB = (b.r === b.g && b.g === b.b) ? 0 : 1 + Utils.hueGroup(hslB.h, hueGroups);\n */\n\n const hueDiff = hueB - hueA;\n if (hueDiff) return -hueDiff;\n\n /*\n var lumDiff = Utils.lumGroup(+hslB.l.toFixed(2)) - Utils.lumGroup(+hslA.l.toFixed(2));\n if (lumDiff) return -lumDiff;\n */\n const lA = a.getLuminosity(true);\n const lB = b.getLuminosity(true);\n\n if (lB - lA !== 0) return lB - lA;\n\n const satDiff = ((hslB.s * 100) | 0) - ((hslA.s * 100) | 0);\n if (satDiff) return -satDiff;\n\n return 0;\n });\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nimport * as arithmetic from './arithmetic';\nimport { HueStatistics } from './hueStatistics';\nimport { Palette } from './palette';\nimport { Point } from './point';\nimport { PointContainer } from './pointContainer';\nimport { ProgressTracker } from './progressTracker';\n\nexport {\n Point,\n PointContainer,\n Palette,\n HueStatistics,\n ProgressTracker,\n arithmetic,\n};\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * hueStatistics.ts - part of Image Quantization Library\n */\nimport { rgb2hsl } from '../conversion/rgb2hsl';\nimport { hueGroup } from './palette';\n\nclass HueGroup {\n num = 0;\n cols: number[] = [];\n}\n\nexport class HueStatistics {\n private _numGroups: number;\n private _minCols: number;\n private _stats: HueGroup[];\n private _groupsFull: number;\n\n constructor(numGroups: number, minCols: number) {\n this._numGroups = numGroups;\n this._minCols = minCols;\n this._stats = [];\n\n for (let i = 0; i <= numGroups; i++) {\n this._stats[i] = new HueGroup();\n }\n\n this._groupsFull = 0;\n }\n\n check(i32: number) {\n if (this._groupsFull === this._numGroups + 1) {\n this.check = () => {};\n }\n\n const r = i32 & 0xff;\n const g = (i32 >>> 8) & 0xff;\n const b = (i32 >>> 16) & 0xff;\n const hg =\n r === g && g === b\n ? 0\n : 1 + hueGroup(rgb2hsl(r, g, b).h, this._numGroups);\n const gr = this._stats[hg];\n const min = this._minCols;\n\n gr.num++;\n\n if (gr.num > min) {\n return;\n }\n if (gr.num === min) {\n this._groupsFull++;\n }\n\n if (gr.num <= min) {\n this._stats[hg].cols.push(i32);\n }\n }\n\n injectIntoDictionary(histG: Record) {\n for (let i = 0; i <= this._numGroups; i++) {\n if (this._stats[i].num <= this._minCols) {\n this._stats[i].cols.forEach((col: number) => {\n if (!histG[col]) {\n histG[col] = 1;\n } else {\n histG[col]++;\n }\n });\n }\n }\n }\n\n injectIntoArray(histG: string[]) {\n for (let i = 0; i <= this._numGroups; i++) {\n if (this._stats[i].num <= this._minCols) {\n this._stats[i].cols.forEach((col: unknown) => {\n if (histG.indexOf(col as string) === -1) {\n histG.push(col as string);\n }\n });\n }\n }\n }\n}\n","export class ProgressTracker {\n static readonly steps = 100;\n\n progress: number;\n\n private _step: number;\n private _range: number;\n private _last: number;\n private _progressRange: number;\n\n constructor(valueRange: number, progressRange: number) {\n this._range = valueRange;\n this._progressRange = progressRange;\n this._step = Math.max(1, (this._range / (ProgressTracker.steps + 1)) | 0);\n this._last = -this._step;\n this.progress = 0;\n }\n\n shouldNotify(current: number) {\n if (current - this._last >= this._step) {\n this._last = current;\n this.progress = Math.min(\n (this._progressRange * this._last) / this._range,\n this._progressRange,\n );\n return true;\n }\n\n return false;\n }\n}\n","/*\n * NeuQuant Neural-Net Quantization Algorithm\n * ------------------------------------------\n *\n * Copyright (c) 1994 Anthony Dekker\n *\n * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See\n * \"Kohonen neural networks for optimal colour quantization\" in \"Network:\n * Computation in Neural Systems\" Vol. 5 (1994) pp 351-367. for a discussion of\n * the algorithm.\n *\n * Any party obtaining a copy of these files from the author, directly or\n * indirectly, is granted, free of charge, a full and unrestricted irrevocable,\n * world-wide, paid up, royalty-free, nonexclusive right and license to deal in\n * this software and documentation files (the \"Software\"), including without\n * limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and/or sell copies of the Software, and to permit persons who\n * receive copies from any such party to do so, with the only requirement being\n * that this copyright notice remain intact.\n */\n\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * neuquant.ts - part of Image Quantization Library\n */\n\nimport { Palette } from '../../utils/palette';\nimport { Point } from '../../utils/point';\nimport { PointContainer } from '../../utils/pointContainer';\nimport { AbstractDistanceCalculator } from '../../distance/distanceCalculator';\nimport { AbstractPaletteQuantizer } from '../paletteQuantizer';\nimport { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue';\nimport { ProgressTracker } from '../../utils';\n\n// bias for colour values\nconst networkBiasShift = 3;\n\nclass Neuron {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(defaultValue: number) {\n this.r = this.g = this.b = this.a = defaultValue;\n }\n\n /**\n * There is a fix in original NEUQUANT by Anthony Dekker (http://members.ozemail.com.au/~dekker/NEUQUANT.HTML)\n * @example\n * r = Math.min(255, (neuron.r + (1 << (networkBiasShift - 1))) >> networkBiasShift);\n */\n toPoint() {\n return Point.createByRGBA(\n this.r >> networkBiasShift,\n this.g >> networkBiasShift,\n this.b >> networkBiasShift,\n this.a >> networkBiasShift,\n );\n }\n\n subtract(r: number, g: number, b: number, a: number) {\n this.r -= r | 0;\n this.g -= g | 0;\n this.b -= b | 0;\n this.a -= a | 0;\n }\n\n /*\n public subtract(r : number, g : number, b : number, a : number) : void {\n this.r = (-r + this.r) | 0;\n this.g = (-g + this.g) | 0;\n this.b = (-b + this.b) | 0;\n this.a = (-a + this.a) | 0;\n\n this.r -= r;\n this.g -= g;\n this.b -= b;\n this.a -= a;\n\n this.r -= r | 0;\n this.g -= g | 0;\n this.b -= b | 0;\n this.a -= a | 0;\n }\n */\n}\n\nexport class NeuQuant extends AbstractPaletteQuantizer {\n /*\n four primes near 500 - assume no image has a length so large\n that it is divisible by all four primes\n */\n private static readonly _prime1 = 499;\n private static readonly _prime2 = 491;\n private static readonly _prime3 = 487;\n private static readonly _prime4 = 503;\n private static readonly _minpicturebytes = NeuQuant._prime4;\n\n // no. of learning cycles\n private static readonly _nCycles = 100;\n\n // defs for freq and bias\n private static readonly _initialBiasShift = 16;\n\n // bias for fractions\n private static readonly _initialBias = 1 << NeuQuant._initialBiasShift;\n private static readonly _gammaShift = 10;\n\n // gamma = 1024\n // TODO: why gamma is never used?\n // private static _gamma : number = (1 << NeuQuant._gammaShift);\n private static readonly _betaShift = 10;\n private static readonly _beta = NeuQuant._initialBias >> NeuQuant._betaShift;\n\n // beta = 1/1024\n private static readonly _betaGamma =\n NeuQuant._initialBias << (NeuQuant._gammaShift - NeuQuant._betaShift);\n\n /*\n * for 256 cols, radius starts\n */\n private static readonly _radiusBiasShift = 6;\n\n // at 32.0 biased by 6 bits\n private static readonly _radiusBias = 1 << NeuQuant._radiusBiasShift;\n\n // and decreases by a factor of 1/30 each cycle\n private static readonly _radiusDecrease = 30;\n\n /* defs for decreasing alpha factor */\n\n // alpha starts at 1.0\n private static readonly _alphaBiasShift = 10;\n\n // biased by 10 bits\n private static readonly _initAlpha = 1 << NeuQuant._alphaBiasShift;\n\n /* radBias and alphaRadBias used for radpower calculation */\n private static readonly _radBiasShift = 8;\n private static readonly _radBias = 1 << NeuQuant._radBiasShift;\n private static readonly _alphaRadBiasShift =\n NeuQuant._alphaBiasShift + NeuQuant._radBiasShift;\n private static readonly _alphaRadBias = 1 << NeuQuant._alphaRadBiasShift;\n\n private _pointArray: Point[];\n private readonly _networkSize: number;\n private _network!: Neuron[];\n\n /** sampling factor 1..30 */\n private readonly _sampleFactor!: number;\n private _radPower!: number[];\n\n // bias and freq arrays for learning\n private _freq!: number[];\n\n /* for network lookup - really 256 */\n private _bias!: number[];\n private readonly _distance: AbstractDistanceCalculator;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n colors = 256,\n ) {\n super();\n this._distance = colorDistanceCalculator;\n this._pointArray = [];\n this._sampleFactor = 1;\n this._networkSize = colors;\n\n this._distance.setWhitePoint(\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n );\n }\n\n sample(pointContainer: PointContainer) {\n this._pointArray = this._pointArray.concat(pointContainer.getPointArray());\n }\n\n *quantize(): IterableIterator {\n this._init();\n\n yield* this._learn();\n\n yield {\n palette: this._buildPalette(),\n progress: 100,\n };\n }\n\n private _init() {\n this._freq = [];\n this._bias = [];\n this._radPower = [];\n this._network = [];\n for (let i = 0; i < this._networkSize; i++) {\n this._network[i] = new Neuron(\n ((i << (networkBiasShift + 8)) / this._networkSize) | 0,\n );\n\n // 1/this._networkSize\n this._freq[i] = (NeuQuant._initialBias / this._networkSize) | 0;\n this._bias[i] = 0;\n }\n }\n\n /**\n * Main Learning Loop\n */\n private *_learn() {\n let sampleFactor = this._sampleFactor;\n const pointsNumber = this._pointArray.length;\n if (pointsNumber < NeuQuant._minpicturebytes) sampleFactor = 1;\n\n const alphadec = (30 + (sampleFactor - 1) / 3) | 0;\n const pointsToSample = (pointsNumber / sampleFactor) | 0;\n\n let delta = (pointsToSample / NeuQuant._nCycles) | 0;\n let alpha = NeuQuant._initAlpha;\n let radius = (this._networkSize >> 3) * NeuQuant._radiusBias;\n\n let rad = radius >> NeuQuant._radiusBiasShift;\n if (rad <= 1) rad = 0;\n\n for (let i = 0; i < rad; i++) {\n this._radPower[i] =\n (alpha * (((rad * rad - i * i) * NeuQuant._radBias) / (rad * rad))) >>>\n 0;\n }\n\n let step;\n if (pointsNumber < NeuQuant._minpicturebytes) {\n step = 1;\n } else if (pointsNumber % NeuQuant._prime1 !== 0) {\n step = NeuQuant._prime1;\n } else if (pointsNumber % NeuQuant._prime2 !== 0) {\n step = NeuQuant._prime2;\n } else if (pointsNumber % NeuQuant._prime3 !== 0) {\n step = NeuQuant._prime3;\n } else {\n step = NeuQuant._prime4;\n }\n\n const tracker = new ProgressTracker(pointsToSample, 99);\n for (let i = 0, pointIndex = 0; i < pointsToSample; ) {\n if (tracker.shouldNotify(i)) {\n yield {\n progress: tracker.progress,\n };\n }\n\n const point = this._pointArray[pointIndex];\n const b = point.b << networkBiasShift;\n const g = point.g << networkBiasShift;\n const r = point.r << networkBiasShift;\n const a = point.a << networkBiasShift;\n const neuronIndex = this._contest(b, g, r, a);\n\n this._alterSingle(alpha, neuronIndex, b, g, r, a);\n if (rad !== 0) this._alterNeighbour(rad, neuronIndex, b, g, r, a);\n\n /* alter neighbours */\n pointIndex += step;\n if (pointIndex >= pointsNumber) pointIndex -= pointsNumber;\n i++;\n\n if (delta === 0) delta = 1;\n\n if (i % delta === 0) {\n alpha -= (alpha / alphadec) | 0;\n radius -= (radius / NeuQuant._radiusDecrease) | 0;\n rad = radius >> NeuQuant._radiusBiasShift;\n\n if (rad <= 1) rad = 0;\n for (let j = 0; j < rad; j++) {\n this._radPower[j] =\n (alpha *\n (((rad * rad - j * j) * NeuQuant._radBias) / (rad * rad))) >>>\n 0;\n }\n }\n }\n }\n\n private _buildPalette() {\n const palette = new Palette();\n\n this._network.forEach((neuron) => {\n palette.add(neuron.toPoint());\n });\n\n palette.sort();\n return palette;\n }\n\n /**\n * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]\n */\n private _alterNeighbour(\n rad: number,\n i: number,\n b: number,\n g: number,\n r: number,\n al: number,\n ) {\n let lo = i - rad;\n if (lo < -1) lo = -1;\n\n let hi = i + rad;\n if (hi > this._networkSize) hi = this._networkSize;\n\n let j = i + 1;\n let k = i - 1;\n let m = 1;\n\n while (j < hi || k > lo) {\n const a = this._radPower[m++] / NeuQuant._alphaRadBias;\n if (j < hi) {\n const p = this._network[j++];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n\n if (k > lo) {\n const p = this._network[k--];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n }\n }\n\n /**\n * Move neuron i towards biased (b,g,r) by factor alpha\n */\n private _alterSingle(\n alpha: number,\n i: number,\n b: number,\n g: number,\n r: number,\n a: number,\n ) {\n alpha /= NeuQuant._initAlpha;\n\n /* alter hit neuron */\n const n = this._network[i];\n n.subtract(\n alpha * (n.r - r),\n alpha * (n.g - g),\n alpha * (n.b - b),\n alpha * (n.a - a),\n );\n }\n\n /**\n * Search for biased BGR values\n * description:\n * finds closest neuron (min dist) and updates freq\n * finds best neuron (min dist-bias) and returns position\n * for frequently chosen neurons, freq[i] is high and bias[i] is negative\n * bias[i] = _gamma*((1/this._networkSize)-freq[i])\n *\n * Original distance equation:\n * dist = abs(dR) + abs(dG) + abs(dB)\n */\n private _contest(b: number, g: number, r: number, a: number) {\n const multiplier = (255 * 4) << networkBiasShift;\n\n let bestd = ~(1 << 31);\n let bestbiasd = bestd;\n let bestpos = -1;\n let bestbiaspos = bestpos;\n\n for (let i = 0; i < this._networkSize; i++) {\n const n = this._network[i];\n const dist =\n (this._distance.calculateNormalized(n, { r, g, b, a }) * multiplier) |\n 0;\n\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n const biasdist =\n dist -\n (this._bias[i] >> (NeuQuant._initialBiasShift - networkBiasShift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n const betafreq = this._freq[i] >> NeuQuant._betaShift;\n this._freq[i] -= betafreq;\n this._bias[i] += betafreq << NeuQuant._gammaShift;\n }\n this._freq[bestpos] += NeuQuant._beta;\n this._bias[bestpos] -= NeuQuant._betaGamma;\n return bestbiaspos;\n }\n}\n","/*\n * NeuQuantFloat Neural-Net Quantization Algorithm\n * ------------------------------------------\n *\n * Copyright (c) 1994 Anthony Dekker\n *\n * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. See\n * \"Kohonen neural networks for optimal colour quantization\" in \"Network:\n * Computation in Neural Systems\" Vol. 5 (1994) pp 351-367. for a discussion of\n * the algorithm.\n *\n * Any party obtaining a copy of these files from the author, directly or\n * indirectly, is granted, free of charge, a full and unrestricted irrevocable,\n * world-wide, paid up, royalty-free, nonexclusive right and license to deal in\n * this software and documentation files (the \"Software\"), including without\n * limitation the rights to use, copy, modify, merge, publish, distribute,\n * sublicense, and/or sell copies of the Software, and to permit persons who\n * receive copies from any such party to do so, with the only requirement being\n * that this copyright notice remain intact.\n */\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * neuquant.ts - part of Image Quantization Library\n */\nimport { Palette } from '../../utils/palette';\nimport { Point } from '../../utils/point';\nimport { PointContainer } from '../../utils/pointContainer';\nimport { AbstractDistanceCalculator } from '../../distance/distanceCalculator';\nimport { AbstractPaletteQuantizer } from '../paletteQuantizer';\nimport { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue';\nimport { ProgressTracker } from '../../utils';\n\n// bias for colour values\nconst networkBiasShift = 3;\n\nclass NeuronFloat {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(defaultValue: number) {\n this.r = this.g = this.b = this.a = defaultValue;\n }\n\n /**\n * There is a fix in original NEUQUANT by Anthony Dekker (http://members.ozemail.com.au/~dekker/NEUQUANT.HTML)\n * @example\n * r = Math.min(255, (neuron.r + (1 << (networkBiasShift - 1))) >> networkBiasShift);\n */\n toPoint() {\n return Point.createByRGBA(\n this.r >> networkBiasShift,\n this.g >> networkBiasShift,\n this.b >> networkBiasShift,\n this.a >> networkBiasShift,\n );\n }\n\n subtract(r: number, g: number, b: number, a: number) {\n this.r -= r;\n this.g -= g;\n this.b -= b;\n this.a -= a;\n }\n}\n\nexport class NeuQuantFloat extends AbstractPaletteQuantizer {\n /*\n four primes near 500 - assume no image has a length so large\n that it is divisible by all four primes\n */\n private static readonly _prime1 = 499;\n private static readonly _prime2 = 491;\n private static readonly _prime3 = 487;\n private static readonly _prime4 = 503;\n private static readonly _minpicturebytes = NeuQuantFloat._prime4;\n\n // no. of learning cycles\n private static readonly _nCycles = 100;\n\n // defs for freq and bias\n private static readonly _initialBiasShift = 16;\n\n // bias for fractions\n private static readonly _initialBias = 1 << NeuQuantFloat._initialBiasShift;\n private static readonly _gammaShift = 10;\n\n // gamma = 1024\n // TODO: why gamma is never used?\n // private static _gamma : number = (1 << NeuQuantFloat._gammaShift);\n private static readonly _betaShift = 10;\n private static readonly _beta =\n NeuQuantFloat._initialBias >> NeuQuantFloat._betaShift;\n\n // beta = 1/1024\n private static readonly _betaGamma =\n NeuQuantFloat._initialBias <<\n (NeuQuantFloat._gammaShift - NeuQuantFloat._betaShift);\n\n /*\n * for 256 cols, radius starts\n */\n private static readonly _radiusBiasShift = 6;\n\n // at 32.0 biased by 6 bits\n private static readonly _radiusBias = 1 << NeuQuantFloat._radiusBiasShift;\n\n // and decreases by a factor of 1/30 each cycle\n private static readonly _radiusDecrease = 30;\n\n /* defs for decreasing alpha factor */\n\n // alpha starts at 1.0\n private static readonly _alphaBiasShift = 10;\n\n // biased by 10 bits\n private static readonly _initAlpha = 1 << NeuQuantFloat._alphaBiasShift;\n\n /* radBias and alphaRadBias used for radpower calculation */\n private static readonly _radBiasShift = 8;\n private static readonly _radBias = 1 << NeuQuantFloat._radBiasShift;\n private static readonly _alphaRadBiasShift =\n NeuQuantFloat._alphaBiasShift + NeuQuantFloat._radBiasShift;\n private static readonly _alphaRadBias = 1 << NeuQuantFloat._alphaRadBiasShift;\n\n private _pointArray!: Point[];\n private readonly _networkSize!: number;\n private _network!: NeuronFloat[];\n\n /** sampling factor 1..30 */\n private readonly _sampleFactor!: number;\n private _radPower!: number[];\n\n // bias and freq arrays for learning\n private _freq!: number[];\n\n /* for network lookup - really 256 */\n private _bias!: number[];\n private readonly _distance: AbstractDistanceCalculator;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n colors = 256,\n ) {\n super();\n this._distance = colorDistanceCalculator;\n this._pointArray = [];\n this._sampleFactor = 1;\n this._networkSize = colors;\n\n this._distance.setWhitePoint(\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n 255 << networkBiasShift,\n );\n }\n\n sample(pointContainer: PointContainer) {\n this._pointArray = this._pointArray.concat(pointContainer.getPointArray());\n }\n\n *quantize() {\n this._init();\n yield* this._learn();\n\n yield {\n palette: this._buildPalette(),\n progress: 100,\n };\n }\n\n private _init() {\n this._freq = [];\n this._bias = [];\n this._radPower = [];\n this._network = [];\n for (let i = 0; i < this._networkSize; i++) {\n this._network[i] = new NeuronFloat(\n (i << (networkBiasShift + 8)) / this._networkSize,\n );\n\n // 1/this._networkSize\n this._freq[i] = NeuQuantFloat._initialBias / this._networkSize;\n this._bias[i] = 0;\n }\n }\n\n /**\n * Main Learning Loop\n */\n private *_learn(): IterableIterator {\n let sampleFactor = this._sampleFactor;\n\n const pointsNumber = this._pointArray.length;\n if (pointsNumber < NeuQuantFloat._minpicturebytes) sampleFactor = 1;\n\n const alphadec = 30 + (sampleFactor - 1) / 3;\n const pointsToSample = pointsNumber / sampleFactor;\n\n let delta = (pointsToSample / NeuQuantFloat._nCycles) | 0;\n let alpha = NeuQuantFloat._initAlpha;\n let radius = (this._networkSize >> 3) * NeuQuantFloat._radiusBias;\n\n let rad = radius >> NeuQuantFloat._radiusBiasShift;\n if (rad <= 1) rad = 0;\n\n for (let i = 0; i < rad; i++) {\n this._radPower[i] =\n alpha * (((rad * rad - i * i) * NeuQuantFloat._radBias) / (rad * rad));\n }\n\n let step;\n if (pointsNumber < NeuQuantFloat._minpicturebytes) {\n step = 1;\n } else if (pointsNumber % NeuQuantFloat._prime1 !== 0) {\n step = NeuQuantFloat._prime1;\n } else if (pointsNumber % NeuQuantFloat._prime2 !== 0) {\n step = NeuQuantFloat._prime2;\n } else if (pointsNumber % NeuQuantFloat._prime3 !== 0) {\n step = NeuQuantFloat._prime3;\n } else {\n step = NeuQuantFloat._prime4;\n }\n\n const tracker = new ProgressTracker(pointsToSample, 99);\n for (let i = 0, pointIndex = 0; i < pointsToSample; ) {\n if (tracker.shouldNotify(i)) {\n yield {\n progress: tracker.progress,\n };\n }\n\n const point = this._pointArray[pointIndex];\n const b = point.b << networkBiasShift;\n const g = point.g << networkBiasShift;\n const r = point.r << networkBiasShift;\n const a = point.a << networkBiasShift;\n const neuronIndex = this._contest(b, g, r, a);\n\n this._alterSingle(alpha, neuronIndex, b, g, r, a);\n if (rad !== 0) this._alterNeighbour(rad, neuronIndex, b, g, r, a);\n\n /* alter neighbours */\n pointIndex += step;\n if (pointIndex >= pointsNumber) pointIndex -= pointsNumber;\n i++;\n\n if (delta === 0) delta = 1;\n\n if (i % delta === 0) {\n alpha -= alpha / alphadec;\n radius -= radius / NeuQuantFloat._radiusDecrease;\n rad = radius >> NeuQuantFloat._radiusBiasShift;\n\n if (rad <= 1) rad = 0;\n for (let j = 0; j < rad; j++) {\n this._radPower[j] =\n alpha *\n (((rad * rad - j * j) * NeuQuantFloat._radBias) / (rad * rad));\n }\n }\n }\n }\n\n private _buildPalette() {\n const palette = new Palette();\n\n this._network.forEach((neuron) => {\n palette.add(neuron.toPoint());\n });\n\n palette.sort();\n return palette;\n }\n\n /**\n * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]\n */\n private _alterNeighbour(\n rad: number,\n i: number,\n b: number,\n g: number,\n r: number,\n al: number,\n ) {\n let lo = i - rad;\n if (lo < -1) lo = -1;\n\n let hi = i + rad;\n if (hi > this._networkSize) hi = this._networkSize;\n\n let j = i + 1;\n let k = i - 1;\n let m = 1;\n\n while (j < hi || k > lo) {\n const a = this._radPower[m++] / NeuQuantFloat._alphaRadBias;\n if (j < hi) {\n const p = this._network[j++];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n\n if (k > lo) {\n const p = this._network[k--];\n p.subtract(a * (p.r - r), a * (p.g - g), a * (p.b - b), a * (p.a - al));\n }\n }\n }\n\n /**\n * Move neuron i towards biased (b,g,r) by factor alpha\n */\n private _alterSingle(\n alpha: number,\n i: number,\n b: number,\n g: number,\n r: number,\n a: number,\n ) {\n alpha /= NeuQuantFloat._initAlpha;\n\n /* alter hit neuron */\n const n = this._network[i];\n n.subtract(\n alpha * (n.r - r),\n alpha * (n.g - g),\n alpha * (n.b - b),\n alpha * (n.a - a),\n );\n }\n\n /**\n * Search for biased BGR values\n * description:\n * finds closest neuron (min dist) and updates freq\n * finds best neuron (min dist-bias) and returns position\n * for frequently chosen neurons, freq[i] is high and bias[i] is negative\n * bias[i] = _gamma*((1/this._networkSize)-freq[i])\n *\n * Original distance equation:\n * dist = abs(dR) + abs(dG) + abs(dB)\n */\n private _contest(b: number, g: number, r: number, al: number) {\n const multiplier = (255 * 4) << networkBiasShift;\n\n let bestd = ~(1 << 31);\n let bestbiasd = bestd;\n let bestpos = -1;\n let bestbiaspos = bestpos;\n\n for (let i = 0; i < this._networkSize; i++) {\n const n = this._network[i];\n const dist =\n this._distance.calculateNormalized(n, { r, g, b, a: al }) * multiplier;\n\n if (dist < bestd) {\n bestd = dist;\n bestpos = i;\n }\n\n const biasdist =\n dist -\n (this._bias[i] >> (NeuQuantFloat._initialBiasShift - networkBiasShift));\n if (biasdist < bestbiasd) {\n bestbiasd = biasdist;\n bestbiaspos = i;\n }\n const betafreq = this._freq[i] >> NeuQuantFloat._betaShift;\n this._freq[i] -= betafreq;\n this._bias[i] += betafreq << NeuQuantFloat._gammaShift;\n }\n this._freq[bestpos] += NeuQuantFloat._beta;\n this._bias[bestpos] -= NeuQuantFloat._betaGamma;\n return bestbiaspos;\n }\n}\n","/*\n * Copyright (c) 2015, Leon Sorokin\n * All rights reserved. (MIT Licensed)\n *\n * ColorHistogram.js - an image quantization lib\n */\n\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * colorHistogram.ts - part of Image Quantization Library\n */\nimport { HueStatistics } from '../../utils/hueStatistics';\nimport { PointContainer } from '../../utils/pointContainer';\nimport { stableSort } from '../../utils/arithmetic';\n\ninterface Box {\n x: number;\n y: number;\n h: number;\n w: number;\n}\n\nexport class ColorHistogram {\n private static _boxSize = [64, 64];\n private static _boxPixels = 2;\n private static _hueGroups = 10;\n\n // 1 = by global population, 2 = subregion population threshold\n private _method: number;\n\n // HueStatistics instance\n private _hueStats: HueStatistics;\n\n private _histogram: { [color: string]: number };\n\n // # of highest-frequency colors to start with for palette reduction\n private _initColors: number;\n\n // if > 0, enables hues stats and min-color retention per group\n private _minHueCols: number;\n\n constructor(method: number, colors: number) {\n // 1 = by global population, 2 = subregion population threshold\n this._method = method;\n\n // if > 0, enables hues stats and min-color retention per group\n this._minHueCols = colors << 2; // opts.minHueCols || 0;\n\n // # of highest-frequency colors to start with for palette reduction\n this._initColors = colors << 2;\n\n // HueStatistics instance\n this._hueStats = new HueStatistics(\n ColorHistogram._hueGroups,\n this._minHueCols,\n );\n\n this._histogram = Object.create(null);\n }\n\n sample(pointContainer: PointContainer) {\n switch (this._method) {\n case 1:\n this._colorStats1D(pointContainer);\n break;\n case 2:\n this._colorStats2D(pointContainer);\n break;\n }\n }\n\n getImportanceSortedColorsIDXI32() {\n // TODO: fix typing issue in stableSort func\n const sorted = stableSort(\n Object.keys(this._histogram),\n (a, b) => this._histogram[b] - this._histogram[a],\n );\n if (sorted.length === 0) {\n return [];\n }\n\n let idxi32;\n switch (this._method) {\n case 1:\n const initialColorsLimit = Math.min(sorted.length, this._initColors);\n const last = sorted[initialColorsLimit - 1];\n const freq = this._histogram[last];\n\n idxi32 = sorted.slice(0, initialColorsLimit);\n\n // add any cut off colors with same freq as last\n let pos = initialColorsLimit;\n const len = sorted.length;\n while (pos < len && this._histogram[sorted[pos]] === freq) {\n idxi32.push(sorted[pos++]);\n }\n\n // inject min huegroup colors\n this._hueStats.injectIntoArray(idxi32);\n break;\n\n case 2:\n idxi32 = sorted;\n break;\n\n default:\n // TODO: rethink errors\n throw new Error('Incorrect method');\n }\n\n // int32-ify values\n return idxi32.map((v) => +v);\n }\n\n // global top-population\n private _colorStats1D(pointContainer: PointContainer) {\n const histG = this._histogram;\n const pointArray = pointContainer.getPointArray();\n const len = pointArray.length;\n\n for (let i = 0; i < len; i++) {\n const col = pointArray[i].uint32;\n\n // collect hue stats\n this._hueStats.check(col);\n\n if (col in histG) {\n histG[col]++;\n } else {\n histG[col] = 1;\n }\n }\n }\n\n // population threshold within subregions\n // FIXME: this can over-reduce (few/no colors same?), need a way to keep\n // important colors that dont ever reach local thresholds (gradients?)\n private _colorStats2D(pointContainer: PointContainer) {\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const pointArray = pointContainer.getPointArray();\n\n const boxW = ColorHistogram._boxSize[0];\n const boxH = ColorHistogram._boxSize[1];\n const area = boxW * boxH;\n const boxes = this._makeBoxes(width, height, boxW, boxH);\n const histG = this._histogram;\n\n boxes.forEach((box) => {\n let effc = Math.round((box.w * box.h) / area) * ColorHistogram._boxPixels;\n if (effc < 2) effc = 2;\n\n const histL: Record = {};\n this._iterateBox(box, width, (i) => {\n const col = pointArray[i].uint32;\n\n // collect hue stats\n this._hueStats.check(col);\n\n if (col in histG) {\n histG[col]++;\n } else if (col in histL) {\n if (++histL[col] >= effc) {\n histG[col] = histL[col];\n }\n } else {\n histL[col] = 1;\n }\n });\n });\n\n // inject min huegroup colors\n this._hueStats.injectIntoDictionary(histG);\n }\n\n // iterates @bbox within a parent rect of width @wid; calls @fn, passing index within parent\n private _iterateBox(bbox: Box, wid: number, fn: (i: number) => void) {\n const b = bbox;\n const i0 = b.y * wid + b.x;\n const i1 = (b.y + b.h - 1) * wid + (b.x + b.w - 1);\n const incr = wid - b.w + 1;\n\n let cnt = 0;\n let i = i0;\n\n do {\n fn.call(this, i);\n i += ++cnt % b.w === 0 ? incr : 1;\n } while (i <= i1);\n }\n\n /**\n * partitions a rectangle of width x height into\n * array of boxes stepX x stepY (or less)\n */\n private _makeBoxes(\n width: number,\n height: number,\n stepX: number,\n stepY: number,\n ) {\n const wrem = width % stepX;\n const hrem = height % stepY;\n const xend = width - wrem;\n const yend = height - hrem;\n const boxesArray = [];\n\n for (let y = 0; y < height; y += stepY) {\n for (let x = 0; x < width; x += stepX) {\n boxesArray.push({\n x,\n y,\n w: x === xend ? wrem : stepX,\n h: y === yend ? hrem : stepY,\n });\n }\n }\n\n return boxesArray;\n }\n}\n","/*\n * Copyright (c) 2015, Leon Sorokin\n * All rights reserved. (MIT Licensed)\n *\n * RGBQuant.js - an image quantization lib\n */\n\n/**\n * @preserve TypeScript port:\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * rgbquant.ts - part of Image Quantization Library\n */\n\nimport { Palette } from '../../utils/palette';\nimport { Point } from '../../utils/point';\nimport { PointContainer } from '../../utils/pointContainer';\nimport { AbstractDistanceCalculator } from '../../distance/distanceCalculator';\nimport { ColorHistogram } from './colorHistogram';\nimport { AbstractPaletteQuantizer } from '../paletteQuantizer';\nimport { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue';\nimport { stableSort } from '../../utils/arithmetic';\nimport { ProgressTracker } from '../../utils';\n\nclass RemovedColor {\n readonly index: number;\n readonly color: Point;\n readonly distance: number;\n\n constructor(index: number, color: Point, distance: number) {\n this.index = index;\n this.color = color;\n this.distance = distance;\n }\n}\n\n// TODO: make input/output image and input/output palettes with instances of class Point only!\nexport class RGBQuant extends AbstractPaletteQuantizer {\n // desired final palette size\n private readonly _colors: number;\n\n // color-distance threshold for initial reduction pass\n private readonly _initialDistance: number;\n\n // subsequent passes threshold\n private readonly _distanceIncrement: number;\n\n // accumulated histogram\n private readonly _histogram: ColorHistogram;\n private readonly _distance: AbstractDistanceCalculator;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n colors = 256,\n method = 2,\n ) {\n super();\n this._distance = colorDistanceCalculator;\n // desired final palette size\n this._colors = colors;\n\n // histogram to accumulate\n this._histogram = new ColorHistogram(method, colors);\n\n this._initialDistance = 0.01;\n this._distanceIncrement = 0.005;\n }\n\n // gathers histogram info\n sample(image: PointContainer) {\n /*\n var pointArray = image.getPointArray(), max = [0, 0, 0, 0], min = [255, 255, 255, 255];\n\n for (var i = 0, l = pointArray.length; i < l; i++) {\n var color = pointArray[i];\n for (var componentIndex = 0; componentIndex < 4; componentIndex++) {\n if (max[componentIndex] < color.rgba[componentIndex]) max[componentIndex] = color.rgba[componentIndex];\n if (min[componentIndex] > color.rgba[componentIndex]) min[componentIndex] = color.rgba[componentIndex];\n }\n }\n var rd = max[0] - min[0], gd = max[1] - min[1], bd = max[2] - min[2], ad = max[3] - min[3];\n this._distance.setWhitePoint(rd, gd, bd, ad);\n\n this._initialDistance = (Math.sqrt(rd * rd + gd * gd + bd * bd + ad * ad) / Math.sqrt(255 * 255 + 255 * 255 + 255 * 255)) * 0.01;\n */\n\n this._histogram.sample(image);\n }\n\n // reduces histogram to palette, remaps & memoizes reduced colors\n *quantize() {\n const idxi32 = this._histogram.getImportanceSortedColorsIDXI32();\n if (idxi32.length === 0) {\n throw new Error('No colors in image');\n }\n\n yield* this._buildPalette(idxi32);\n }\n\n // reduces similar colors from an importance-sorted Uint32 rgba array\n private *_buildPalette(\n idxi32: number[],\n ): IterableIterator {\n // reduce histogram to create initial palette\n // build full rgb palette\n const palette = new Palette();\n const colorArray = palette.getPointContainer().getPointArray();\n const usageArray = new Array(idxi32.length);\n\n for (let i = 0; i < idxi32.length; i++) {\n colorArray.push(Point.createByUint32(idxi32[i]));\n usageArray[i] = 1;\n }\n\n const len = colorArray.length;\n const memDist = [];\n\n let palLen = len;\n let thold = this._initialDistance;\n\n // palette already at or below desired length\n const tracker = new ProgressTracker(palLen - this._colors, 99);\n while (palLen > this._colors) {\n memDist.length = 0;\n\n // iterate palette\n for (let i = 0; i < len; i++) {\n if (tracker.shouldNotify(len - palLen)) {\n yield {\n progress: tracker.progress,\n };\n }\n\n if (usageArray[i] === 0) continue;\n const pxi = colorArray[i];\n // if (!pxi) continue;\n\n for (let j = i + 1; j < len; j++) {\n if (usageArray[j] === 0) continue;\n const pxj = colorArray[j];\n // if (!pxj) continue;\n\n const dist = this._distance.calculateNormalized(pxi, pxj);\n if (dist < thold) {\n // store index,rgb,dist\n memDist.push(new RemovedColor(j, pxj, dist));\n usageArray[j] = 0;\n palLen--;\n }\n }\n }\n // palette reduction pass\n // console.log(\"palette length: \" + palLen);\n\n // if palette is still much larger than target, increment by larger initDist\n thold +=\n palLen > this._colors * 3\n ? this._initialDistance\n : this._distanceIncrement;\n }\n\n // if palette is over-reduced, re-add removed colors with largest distances from last round\n if (palLen < this._colors) {\n // sort descending\n stableSort(memDist, (a, b) => b.distance - a.distance);\n\n let k = 0;\n while (palLen < this._colors && k < memDist.length) {\n const removedColor = memDist[k];\n // re-inject rgb into final palette\n usageArray[removedColor.index] = 1;\n palLen++;\n k++;\n }\n }\n\n let colors = colorArray.length;\n for (let colorIndex = colors - 1; colorIndex >= 0; colorIndex--) {\n if (usageArray[colorIndex] === 0) {\n if (colorIndex !== colors - 1) {\n colorArray[colorIndex] = colorArray[colors - 1];\n }\n --colors;\n }\n }\n colorArray.length = colors;\n\n palette.sort();\n\n yield {\n palette,\n progress: 100,\n };\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * wuQuant.ts - part of Image Quantization Library\n */\nimport { Palette } from '../../utils/palette';\nimport { Point } from '../../utils/point';\nimport { PointContainer } from '../../utils/pointContainer';\nimport { AbstractDistanceCalculator } from '../../distance/distanceCalculator';\nimport { AbstractPaletteQuantizer } from '../paletteQuantizer';\nimport { PaletteQuantizerYieldValue } from '../paletteQuantizerYieldValue';\nimport { ProgressTracker } from '../../utils';\n\nfunction createArray1D(dimension1: number) {\n const a = [];\n for (let k = 0; k < dimension1; k++) {\n a[k] = 0;\n }\n return a;\n}\n\nfunction createArray4D(\n dimension1: number,\n dimension2: number,\n dimension3: number,\n dimension4: number,\n): number[][][][] {\n const a = new Array(dimension1);\n for (let i = 0; i < dimension1; i++) {\n a[i] = new Array(dimension2);\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = new Array(dimension3);\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = new Array(dimension4);\n for (let l = 0; l < dimension4; l++) {\n a[i][j][k][l] = 0;\n }\n }\n }\n }\n return a;\n}\n\nfunction createArray3D(\n dimension1: number,\n dimension2: number,\n dimension3: number,\n): number[][][] {\n const a = new Array(dimension1);\n for (let i = 0; i < dimension1; i++) {\n a[i] = new Array(dimension2);\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = new Array(dimension3);\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = 0;\n }\n }\n }\n return a;\n}\n\nfunction fillArray3D(\n a: T[][][],\n dimension1: number,\n dimension2: number,\n dimension3: number,\n value: T,\n) {\n for (let i = 0; i < dimension1; i++) {\n a[i] = [];\n for (let j = 0; j < dimension2; j++) {\n a[i][j] = [];\n for (let k = 0; k < dimension3; k++) {\n a[i][j][k] = value;\n }\n }\n }\n}\n\nfunction fillArray1D(a: T[], dimension1: number, value: T) {\n for (let i = 0; i < dimension1; i++) {\n a[i] = value;\n }\n}\n\nexport class WuColorCube {\n redMinimum!: number;\n redMaximum!: number;\n greenMinimum!: number;\n greenMaximum!: number;\n blueMinimum!: number;\n blueMaximum!: number;\n volume!: number;\n alphaMinimum!: number;\n alphaMaximum!: number;\n}\n\nexport class WuQuant extends AbstractPaletteQuantizer {\n private static readonly _alpha = 3;\n private static readonly _red = 2;\n private static readonly _green = 1;\n private static readonly _blue = 0;\n\n private _reds!: number[];\n private _greens!: number[];\n private _blues!: number[];\n private _alphas!: number[];\n private _sums!: number[];\n\n private _weights!: number[][][][];\n private _momentsRed!: number[][][][];\n private _momentsGreen!: number[][][][];\n private _momentsBlue!: number[][][][];\n private _momentsAlpha!: number[][][][];\n private _moments!: number[][][][];\n private _table!: number[];\n private _pixels!: Point[];\n\n private _cubes!: WuColorCube[];\n private _colors!: number;\n\n private _significantBitsPerChannel!: number;\n private _maxSideIndex!: number;\n private _alphaMaxSideIndex!: number;\n private _sideSize!: number;\n private _alphaSideSize!: number;\n\n private readonly _distance: AbstractDistanceCalculator;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n colors = 256,\n significantBitsPerChannel = 5,\n ) {\n super();\n this._distance = colorDistanceCalculator;\n this._setQuality(significantBitsPerChannel);\n this._initialize(colors);\n }\n\n sample(image: PointContainer) {\n const pointArray = image.getPointArray();\n\n for (let i = 0, l = pointArray.length; i < l; i++) {\n this._addColor(pointArray[i]);\n }\n\n this._pixels = this._pixels.concat(pointArray);\n }\n\n *quantize() {\n yield* this._preparePalette();\n\n const palette = new Palette();\n\n // generates palette\n for (let paletteIndex = 0; paletteIndex < this._colors; paletteIndex++) {\n if (this._sums[paletteIndex] > 0) {\n const sum = this._sums[paletteIndex];\n const r = this._reds[paletteIndex] / sum;\n const g = this._greens[paletteIndex] / sum;\n const b = this._blues[paletteIndex] / sum;\n const a = this._alphas[paletteIndex] / sum;\n\n const color = Point.createByRGBA(r | 0, g | 0, b | 0, a | 0);\n palette.add(color);\n }\n }\n\n palette.sort();\n\n yield {\n palette,\n progress: 100,\n };\n }\n\n private *_preparePalette() {\n // preprocess the colors\n yield* this._calculateMoments();\n\n let next = 0;\n const volumeVariance = createArray1D(this._colors);\n\n // processes the cubes\n for (let cubeIndex = 1; cubeIndex < this._colors; ++cubeIndex) {\n // if cut is possible; make it\n if (this._cut(this._cubes[next], this._cubes[cubeIndex])) {\n volumeVariance[next] =\n this._cubes[next].volume > 1\n ? this._calculateVariance(this._cubes[next])\n : 0.0;\n volumeVariance[cubeIndex] =\n this._cubes[cubeIndex].volume > 1\n ? this._calculateVariance(this._cubes[cubeIndex])\n : 0.0;\n } else {\n // the cut was not possible, revert the index\n volumeVariance[next] = 0.0;\n cubeIndex--;\n }\n\n next = 0;\n let temp = volumeVariance[0];\n\n for (let index = 1; index <= cubeIndex; ++index) {\n if (volumeVariance[index] > temp) {\n temp = volumeVariance[index];\n next = index;\n }\n }\n\n if (temp <= 0.0) {\n this._colors = cubeIndex + 1;\n break;\n }\n }\n\n const lookupRed = [];\n const lookupGreen = [];\n const lookupBlue = [];\n const lookupAlpha = [];\n\n // precalculates lookup tables\n for (let k = 0; k < this._colors; ++k) {\n const weight = WuQuant._volume(this._cubes[k], this._weights);\n\n if (weight > 0) {\n lookupRed[k] =\n (WuQuant._volume(this._cubes[k], this._momentsRed) / weight) | 0;\n lookupGreen[k] =\n (WuQuant._volume(this._cubes[k], this._momentsGreen) / weight) | 0;\n lookupBlue[k] =\n (WuQuant._volume(this._cubes[k], this._momentsBlue) / weight) | 0;\n lookupAlpha[k] =\n (WuQuant._volume(this._cubes[k], this._momentsAlpha) / weight) | 0;\n } else {\n lookupRed[k] = 0;\n lookupGreen[k] = 0;\n lookupBlue[k] = 0;\n lookupAlpha[k] = 0;\n }\n }\n\n this._reds = createArray1D(this._colors + 1);\n this._greens = createArray1D(this._colors + 1);\n this._blues = createArray1D(this._colors + 1);\n this._alphas = createArray1D(this._colors + 1);\n this._sums = createArray1D(this._colors + 1);\n\n // scans and adds colors\n for (let index = 0, l = this._pixels.length; index < l; index++) {\n const color = this._pixels[index];\n\n const match = -1;\n\n let bestMatch = match;\n let bestDistance = Number.MAX_VALUE;\n\n for (let lookup = 0; lookup < this._colors; lookup++) {\n const foundRed = lookupRed[lookup];\n const foundGreen = lookupGreen[lookup];\n const foundBlue = lookupBlue[lookup];\n const foundAlpha = lookupAlpha[lookup];\n\n const distance = this._distance.calculateRaw(\n foundRed,\n foundGreen,\n foundBlue,\n foundAlpha,\n color.r,\n color.g,\n color.b,\n color.a,\n );\n\n if (distance < bestDistance) {\n bestDistance = distance;\n bestMatch = lookup;\n }\n }\n\n this._reds[bestMatch] += color.r;\n this._greens[bestMatch] += color.g;\n this._blues[bestMatch] += color.b;\n this._alphas[bestMatch] += color.a;\n this._sums[bestMatch]++;\n }\n }\n\n private _addColor(color: Point) {\n const bitsToRemove = 8 - this._significantBitsPerChannel;\n const indexRed = (color.r >> bitsToRemove) + 1;\n const indexGreen = (color.g >> bitsToRemove) + 1;\n const indexBlue = (color.b >> bitsToRemove) + 1;\n const indexAlpha = (color.a >> bitsToRemove) + 1;\n\n // if(color.a > 10) {\n this._weights[indexAlpha][indexRed][indexGreen][indexBlue]++;\n this._momentsRed[indexAlpha][indexRed][indexGreen][indexBlue] += color.r;\n this._momentsGreen[indexAlpha][indexRed][indexGreen][indexBlue] += color.g;\n this._momentsBlue[indexAlpha][indexRed][indexGreen][indexBlue] += color.b;\n this._momentsAlpha[indexAlpha][indexRed][indexGreen][indexBlue] += color.a;\n this._moments[indexAlpha][indexRed][indexGreen][indexBlue] +=\n this._table[color.r] +\n this._table[color.g] +\n this._table[color.b] +\n this._table[color.a];\n // }\n }\n\n /**\n * Converts the histogram to a series of _moments.\n */\n private *_calculateMoments(): IterableIterator {\n const area: number[] = [];\n const areaRed: number[] = [];\n const areaGreen: number[] = [];\n const areaBlue: number[] = [];\n const areaAlpha: number[] = [];\n const area2: number[] = [];\n\n const xarea = createArray3D(this._sideSize, this._sideSize, this._sideSize);\n const xareaRed = createArray3D(\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n const xareaGreen = createArray3D(\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n const xareaBlue = createArray3D(\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n const xareaAlpha = createArray3D(\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n const xarea2 = createArray3D(\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n\n let trackerProgress = 0;\n const tracker = new ProgressTracker(\n this._alphaMaxSideIndex * this._maxSideIndex,\n 99,\n );\n\n for (\n let alphaIndex = 1;\n alphaIndex <= this._alphaMaxSideIndex;\n ++alphaIndex\n ) {\n fillArray3D(\n xarea,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n fillArray3D(\n xareaRed,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n fillArray3D(\n xareaGreen,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n fillArray3D(\n xareaBlue,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n fillArray3D(\n xareaAlpha,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n fillArray3D(\n xarea2,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n 0,\n );\n\n for (\n let redIndex = 1;\n redIndex <= this._maxSideIndex;\n ++redIndex, ++trackerProgress\n ) {\n if (tracker.shouldNotify(trackerProgress)) {\n yield {\n progress: tracker.progress,\n };\n }\n\n fillArray1D(area, this._sideSize, 0);\n fillArray1D(areaRed, this._sideSize, 0);\n fillArray1D(areaGreen, this._sideSize, 0);\n fillArray1D(areaBlue, this._sideSize, 0);\n fillArray1D(areaAlpha, this._sideSize, 0);\n fillArray1D(area2, this._sideSize, 0);\n\n for (\n let greenIndex = 1;\n greenIndex <= this._maxSideIndex;\n ++greenIndex\n ) {\n let line = 0;\n let lineRed = 0;\n let lineGreen = 0;\n let lineBlue = 0;\n let lineAlpha = 0;\n let line2 = 0.0;\n\n for (\n let blueIndex = 1;\n blueIndex <= this._maxSideIndex;\n ++blueIndex\n ) {\n line += this._weights[alphaIndex][redIndex][greenIndex][blueIndex];\n lineRed +=\n this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex];\n lineGreen +=\n this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex];\n lineBlue +=\n this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex];\n lineAlpha +=\n this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex];\n line2 += this._moments[alphaIndex][redIndex][greenIndex][blueIndex];\n\n area[blueIndex] += line;\n areaRed[blueIndex] += lineRed;\n areaGreen[blueIndex] += lineGreen;\n areaBlue[blueIndex] += lineBlue;\n areaAlpha[blueIndex] += lineAlpha;\n area2[blueIndex] += line2;\n\n xarea[redIndex][greenIndex][blueIndex] =\n xarea[redIndex - 1][greenIndex][blueIndex] + area[blueIndex];\n xareaRed[redIndex][greenIndex][blueIndex] =\n xareaRed[redIndex - 1][greenIndex][blueIndex] +\n areaRed[blueIndex];\n xareaGreen[redIndex][greenIndex][blueIndex] =\n xareaGreen[redIndex - 1][greenIndex][blueIndex] +\n areaGreen[blueIndex];\n xareaBlue[redIndex][greenIndex][blueIndex] =\n xareaBlue[redIndex - 1][greenIndex][blueIndex] +\n areaBlue[blueIndex];\n xareaAlpha[redIndex][greenIndex][blueIndex] =\n xareaAlpha[redIndex - 1][greenIndex][blueIndex] +\n areaAlpha[blueIndex];\n xarea2[redIndex][greenIndex][blueIndex] =\n xarea2[redIndex - 1][greenIndex][blueIndex] + area2[blueIndex];\n\n this._weights[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._weights[alphaIndex - 1][redIndex][greenIndex][blueIndex] +\n xarea[redIndex][greenIndex][blueIndex];\n this._momentsRed[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._momentsRed[alphaIndex - 1][redIndex][greenIndex][\n blueIndex\n ] + xareaRed[redIndex][greenIndex][blueIndex];\n this._momentsGreen[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._momentsGreen[alphaIndex - 1][redIndex][greenIndex][\n blueIndex\n ] + xareaGreen[redIndex][greenIndex][blueIndex];\n this._momentsBlue[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._momentsBlue[alphaIndex - 1][redIndex][greenIndex][\n blueIndex\n ] + xareaBlue[redIndex][greenIndex][blueIndex];\n this._momentsAlpha[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._momentsAlpha[alphaIndex - 1][redIndex][greenIndex][\n blueIndex\n ] + xareaAlpha[redIndex][greenIndex][blueIndex];\n this._moments[alphaIndex][redIndex][greenIndex][blueIndex] =\n this._moments[alphaIndex - 1][redIndex][greenIndex][blueIndex] +\n xarea2[redIndex][greenIndex][blueIndex];\n }\n }\n }\n }\n }\n\n /**\n * Computes the volume of the cube in a specific moment.\n */\n private static _volumeFloat(cube: WuColorCube, moment: number[][][][]) {\n return (\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ])\n );\n }\n\n /**\n * Computes the volume of the cube in a specific moment.\n */\n private static _volume(cube: WuColorCube, moment: number[][][][]) {\n return WuQuant._volumeFloat(cube, moment) | 0;\n }\n\n /**\n * Splits the cube in given position][and color direction.\n */\n private static _top(\n cube: WuColorCube,\n direction: number,\n position: number,\n moment: number[][][][],\n ) {\n let result;\n switch (direction) {\n case WuQuant._alpha:\n result =\n moment[position][cube.redMaximum][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[position][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n moment[position][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[position][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (moment[position][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[position][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] -\n moment[position][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[position][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ]);\n break;\n\n case WuQuant._red:\n result =\n moment[cube.alphaMaximum][position][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMaximum][position][cube.greenMinimum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][position][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][position][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (moment[cube.alphaMaximum][position][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMaximum][position][cube.greenMinimum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][position][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][position][cube.greenMinimum][\n cube.blueMinimum\n ]);\n break;\n\n case WuQuant._green:\n result =\n moment[cube.alphaMaximum][cube.redMaximum][position][\n cube.blueMaximum\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][position][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMaximum][position][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][position][\n cube.blueMaximum\n ] -\n (moment[cube.alphaMaximum][cube.redMaximum][position][\n cube.blueMinimum\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][position][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMaximum][position][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][position][\n cube.blueMinimum\n ]);\n break;\n\n case WuQuant._blue:\n result =\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][\n position\n ] -\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n position\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n position\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n position\n ] -\n (moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n position\n ] -\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n position\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n position\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n position\n ]);\n break;\n default:\n throw new Error('impossible');\n }\n\n return result | 0;\n }\n\n /**\n * Splits the cube in a given color direction at its minimum.\n */\n private static _bottom(\n cube: WuColorCube,\n direction: number,\n moment: number[][][][],\n ) {\n switch (direction) {\n case WuQuant._alpha:\n return (\n -moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ])\n );\n\n case WuQuant._red:\n return (\n -moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (-moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ])\n );\n\n case WuQuant._green:\n return (\n -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMaximum\n ] -\n (-moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ])\n );\n\n case WuQuant._blue:\n return (\n -moment[cube.alphaMaximum][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMaximum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMaximum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ] -\n (-moment[cube.alphaMinimum][cube.redMaximum][cube.greenMaximum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMaximum][cube.greenMinimum][\n cube.blueMinimum\n ] +\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMaximum][\n cube.blueMinimum\n ] -\n moment[cube.alphaMinimum][cube.redMinimum][cube.greenMinimum][\n cube.blueMinimum\n ])\n );\n\n default:\n // TODO: why here is return 0, and in this._top there is no default at all (now it is throw error)?\n return 0;\n }\n }\n\n /**\n * Calculates statistical variance for a given cube.\n */\n private _calculateVariance(cube: WuColorCube) {\n const volumeRed = WuQuant._volume(cube, this._momentsRed);\n const volumeGreen = WuQuant._volume(cube, this._momentsGreen);\n const volumeBlue = WuQuant._volume(cube, this._momentsBlue);\n const volumeAlpha = WuQuant._volume(cube, this._momentsAlpha);\n const volumeMoment = WuQuant._volumeFloat(cube, this._moments);\n const volumeWeight = WuQuant._volume(cube, this._weights);\n const distance =\n volumeRed * volumeRed +\n volumeGreen * volumeGreen +\n volumeBlue * volumeBlue +\n volumeAlpha * volumeAlpha;\n\n return volumeMoment - distance / volumeWeight;\n }\n\n /**\n * Finds the optimal (maximal) position for the cut.\n */\n private _maximize(\n cube: WuColorCube,\n direction: number,\n first: number,\n last: number,\n wholeRed: number,\n wholeGreen: number,\n wholeBlue: number,\n wholeAlpha: number,\n wholeWeight: number,\n ) {\n const bottomRed = WuQuant._bottom(cube, direction, this._momentsRed) | 0;\n const bottomGreen =\n WuQuant._bottom(cube, direction, this._momentsGreen) | 0;\n const bottomBlue = WuQuant._bottom(cube, direction, this._momentsBlue) | 0;\n const bottomAlpha =\n WuQuant._bottom(cube, direction, this._momentsAlpha) | 0;\n const bottomWeight = WuQuant._bottom(cube, direction, this._weights) | 0;\n\n let result = 0.0;\n let cutPosition = -1;\n\n for (let position = first; position < last; ++position) {\n // determines the cube cut at a certain position\n let halfRed =\n bottomRed + WuQuant._top(cube, direction, position, this._momentsRed);\n let halfGreen =\n bottomGreen +\n WuQuant._top(cube, direction, position, this._momentsGreen);\n let halfBlue =\n bottomBlue + WuQuant._top(cube, direction, position, this._momentsBlue);\n let halfAlpha =\n bottomAlpha +\n WuQuant._top(cube, direction, position, this._momentsAlpha);\n let halfWeight =\n bottomWeight + WuQuant._top(cube, direction, position, this._weights);\n\n // the cube cannot be cut at bottom (this would lead to empty cube)\n if (halfWeight !== 0) {\n let halfDistance =\n halfRed * halfRed +\n halfGreen * halfGreen +\n halfBlue * halfBlue +\n halfAlpha * halfAlpha;\n let temp = halfDistance / halfWeight;\n\n halfRed = wholeRed - halfRed;\n halfGreen = wholeGreen - halfGreen;\n halfBlue = wholeBlue - halfBlue;\n halfAlpha = wholeAlpha - halfAlpha;\n halfWeight = wholeWeight - halfWeight;\n\n if (halfWeight !== 0) {\n halfDistance =\n halfRed * halfRed +\n halfGreen * halfGreen +\n halfBlue * halfBlue +\n halfAlpha * halfAlpha;\n temp += halfDistance / halfWeight;\n\n if (temp > result) {\n result = temp;\n cutPosition = position;\n }\n }\n }\n }\n\n return { max: result, position: cutPosition };\n }\n\n // Cuts a cube with another one.\n private _cut(first: WuColorCube, second: WuColorCube) {\n let direction;\n\n const wholeRed = WuQuant._volume(first, this._momentsRed);\n const wholeGreen = WuQuant._volume(first, this._momentsGreen);\n const wholeBlue = WuQuant._volume(first, this._momentsBlue);\n const wholeAlpha = WuQuant._volume(first, this._momentsAlpha);\n const wholeWeight = WuQuant._volume(first, this._weights);\n\n const red = this._maximize(\n first,\n WuQuant._red,\n first.redMinimum + 1,\n first.redMaximum,\n wholeRed,\n wholeGreen,\n wholeBlue,\n wholeAlpha,\n wholeWeight,\n );\n const green = this._maximize(\n first,\n WuQuant._green,\n first.greenMinimum + 1,\n first.greenMaximum,\n wholeRed,\n wholeGreen,\n wholeBlue,\n wholeAlpha,\n wholeWeight,\n );\n const blue = this._maximize(\n first,\n WuQuant._blue,\n first.blueMinimum + 1,\n first.blueMaximum,\n wholeRed,\n wholeGreen,\n wholeBlue,\n wholeAlpha,\n wholeWeight,\n );\n const alpha = this._maximize(\n first,\n WuQuant._alpha,\n first.alphaMinimum + 1,\n first.alphaMaximum,\n wholeRed,\n wholeGreen,\n wholeBlue,\n wholeAlpha,\n wholeWeight,\n );\n\n if (\n alpha.max >= red.max &&\n alpha.max >= green.max &&\n alpha.max >= blue.max\n ) {\n direction = WuQuant._alpha;\n\n // cannot split empty cube\n if (alpha.position < 0) return false;\n } else if (\n red.max >= alpha.max &&\n red.max >= green.max &&\n red.max >= blue.max\n ) {\n direction = WuQuant._red;\n } else if (\n green.max >= alpha.max &&\n green.max >= red.max &&\n green.max >= blue.max\n ) {\n direction = WuQuant._green;\n } else {\n direction = WuQuant._blue;\n }\n\n second.redMaximum = first.redMaximum;\n second.greenMaximum = first.greenMaximum;\n second.blueMaximum = first.blueMaximum;\n second.alphaMaximum = first.alphaMaximum;\n\n // cuts in a certain direction\n switch (direction) {\n case WuQuant._red:\n second.redMinimum = first.redMaximum = red.position;\n second.greenMinimum = first.greenMinimum;\n second.blueMinimum = first.blueMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n\n case WuQuant._green:\n second.greenMinimum = first.greenMaximum = green.position;\n second.redMinimum = first.redMinimum;\n second.blueMinimum = first.blueMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n\n case WuQuant._blue:\n second.blueMinimum = first.blueMaximum = blue.position;\n second.redMinimum = first.redMinimum;\n second.greenMinimum = first.greenMinimum;\n second.alphaMinimum = first.alphaMinimum;\n break;\n\n case WuQuant._alpha:\n second.alphaMinimum = first.alphaMaximum = alpha.position;\n second.blueMinimum = first.blueMinimum;\n second.redMinimum = first.redMinimum;\n second.greenMinimum = first.greenMinimum;\n break;\n }\n\n // determines the volumes after cut\n first.volume =\n (first.redMaximum - first.redMinimum) *\n (first.greenMaximum - first.greenMinimum) *\n (first.blueMaximum - first.blueMinimum) *\n (first.alphaMaximum - first.alphaMinimum);\n second.volume =\n (second.redMaximum - second.redMinimum) *\n (second.greenMaximum - second.greenMinimum) *\n (second.blueMaximum - second.blueMinimum) *\n (second.alphaMaximum - second.alphaMinimum);\n\n // the cut was successful\n return true;\n }\n\n private _initialize(colors: number) {\n this._colors = colors;\n\n // creates all the _cubes\n this._cubes = [];\n\n // initializes all the _cubes\n for (let cubeIndex = 0; cubeIndex < colors; cubeIndex++) {\n this._cubes[cubeIndex] = new WuColorCube();\n }\n\n // resets the reference minimums\n this._cubes[0].redMinimum = 0;\n this._cubes[0].greenMinimum = 0;\n this._cubes[0].blueMinimum = 0;\n this._cubes[0].alphaMinimum = 0;\n\n // resets the reference maximums\n this._cubes[0].redMaximum = this._maxSideIndex;\n this._cubes[0].greenMaximum = this._maxSideIndex;\n this._cubes[0].blueMaximum = this._maxSideIndex;\n this._cubes[0].alphaMaximum = this._alphaMaxSideIndex;\n\n this._weights = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n this._momentsRed = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n this._momentsGreen = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n this._momentsBlue = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n this._momentsAlpha = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n this._moments = createArray4D(\n this._alphaSideSize,\n this._sideSize,\n this._sideSize,\n this._sideSize,\n );\n\n this._table = [];\n for (let tableIndex = 0; tableIndex < 256; ++tableIndex) {\n this._table[tableIndex] = tableIndex * tableIndex;\n }\n\n this._pixels = [];\n }\n\n private _setQuality(significantBitsPerChannel = 5) {\n this._significantBitsPerChannel = significantBitsPerChannel;\n this._maxSideIndex = 1 << this._significantBitsPerChannel;\n this._alphaMaxSideIndex = this._maxSideIndex;\n\n this._sideSize = this._maxSideIndex + 1;\n this._alphaSideSize = this._alphaMaxSideIndex + 1;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\n\nexport { AbstractImageQuantizer } from './imageQuantizer';\nexport { ImageQuantizerYieldValue } from './imageQuantizerYieldValue';\nexport { NearestColor } from './nearestColor';\nexport { ErrorDiffusionArray, ErrorDiffusionArrayKernel } from './array';\nexport { ErrorDiffusionRiemersma } from './riemersma';\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * common.ts - part of Image Quantization Library\n */\nimport { PointContainer } from '../utils/pointContainer';\nimport { Palette } from '../utils/palette';\nimport { ImageQuantizerYieldValue } from './imageQuantizerYieldValue';\n\nexport abstract class AbstractImageQuantizer {\n abstract quantize(\n pointContainer: PointContainer,\n palette: Palette,\n ): IterableIterator;\n\n quantizeSync(pointContainer: PointContainer, palette: Palette) {\n for (const value of this.quantize(pointContainer, palette)) {\n if (value.pointContainer) {\n return value.pointContainer;\n }\n }\n\n throw new Error('unreachable');\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * nearestColor.ts - part of Image Quantization Library\n */\nimport { AbstractImageQuantizer } from './imageQuantizer';\nimport { AbstractDistanceCalculator } from '../distance/distanceCalculator';\nimport { PointContainer } from '../utils/pointContainer';\nimport { Palette } from '../utils/palette';\nimport { ImageQuantizerYieldValue } from './imageQuantizerYieldValue';\nimport { ProgressTracker } from '../utils/progressTracker';\n\nexport class NearestColor extends AbstractImageQuantizer {\n private _distance: AbstractDistanceCalculator;\n\n constructor(colorDistanceCalculator: AbstractDistanceCalculator) {\n super();\n this._distance = colorDistanceCalculator;\n }\n\n /**\n * Mutates pointContainer\n */\n *quantize(\n pointContainer: PointContainer,\n palette: Palette,\n ): IterableIterator {\n const pointArray = pointContainer.getPointArray();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n\n const tracker = new ProgressTracker(height, 99);\n for (let y = 0; y < height; y++) {\n if (tracker.shouldNotify(y)) {\n yield {\n progress: tracker.progress,\n };\n }\n for (let x = 0, idx = y * width; x < width; x++, idx++) {\n // Image pixel\n const point = pointArray[idx];\n // Reduced pixel\n point.from(palette.getNearestColor(this._distance, point));\n }\n }\n\n yield {\n pointContainer,\n progress: 100,\n };\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ditherErrorDiffusionArray.ts - part of Image Quantization Library\n */\nimport { AbstractImageQuantizer } from './imageQuantizer';\nimport { AbstractDistanceCalculator } from '../distance/distanceCalculator';\nimport { PointContainer } from '../utils/pointContainer';\nimport { Palette } from '../utils/palette';\nimport { Point } from '../utils/point';\nimport { inRange0to255Rounded } from '../utils/arithmetic';\nimport { ImageQuantizerYieldValue } from './imageQuantizerYieldValue';\nimport { ProgressTracker } from '../utils/progressTracker';\n\n// TODO: is it the best name for this enum \"kernel\"?\nexport enum ErrorDiffusionArrayKernel {\n FloydSteinberg = 0,\n FalseFloydSteinberg,\n Stucki,\n Atkinson,\n Jarvis,\n Burkes,\n Sierra,\n TwoSierra,\n SierraLite,\n}\n\n// http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code/\nexport class ErrorDiffusionArray extends AbstractImageQuantizer {\n private _minColorDistance: number;\n private _serpentine: boolean;\n private _kernel!: number[][];\n /** true = GIMP, false = XNVIEW */\n private _calculateErrorLikeGIMP: boolean;\n\n private _distance: AbstractDistanceCalculator;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n kernel: ErrorDiffusionArrayKernel,\n serpentine = true,\n minimumColorDistanceToDither = 0,\n calculateErrorLikeGIMP = false,\n ) {\n super();\n this._setKernel(kernel);\n\n this._distance = colorDistanceCalculator;\n this._minColorDistance = minimumColorDistanceToDither;\n this._serpentine = serpentine;\n this._calculateErrorLikeGIMP = calculateErrorLikeGIMP;\n }\n\n /**\n * adapted from http://jsbin.com/iXofIji/2/edit by PAEz\n * fixed version. it doesn't use image pixels as error storage, also it doesn't have 0.3 + 0.3 + 0.3 + 0.3 = 0 error\n * Mutates pointContainer\n */\n *quantize(\n pointContainer: PointContainer,\n palette: Palette,\n ): IterableIterator {\n const pointArray = pointContainer.getPointArray();\n const originalPoint = new Point();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const errorLines: number[][][] = [];\n\n let dir = 1;\n let maxErrorLines = 1;\n\n // initial error lines (number is taken from dithering kernel)\n for (const kernel of this._kernel) {\n const kernelErrorLines = kernel[2] + 1;\n if (maxErrorLines < kernelErrorLines) maxErrorLines = kernelErrorLines;\n }\n for (let i = 0; i < maxErrorLines; i++) {\n this._fillErrorLine((errorLines[i] = []), width);\n }\n\n const tracker = new ProgressTracker(height, 99);\n for (let y = 0; y < height; y++) {\n if (tracker.shouldNotify(y)) {\n yield {\n progress: tracker.progress,\n };\n }\n\n // always serpentine\n if (this._serpentine) dir *= -1;\n\n const lni = y * width;\n const xStart = dir === 1 ? 0 : width - 1;\n const xEnd = dir === 1 ? width : -1;\n\n // cyclic shift with erasing\n this._fillErrorLine(errorLines[0], width);\n // TODO: why it is needed to cast types here?\n errorLines.push(errorLines.shift() as number[][]);\n\n const errorLine = errorLines[0];\n for (\n let x = xStart, idx = lni + xStart;\n x !== xEnd;\n x += dir, idx += dir\n ) {\n // Image pixel\n const point = pointArray[idx];\n // originalPoint = new Utils.Point(),\n const error = errorLine[x];\n\n originalPoint.from(point);\n\n const correctedPoint = Point.createByRGBA(\n inRange0to255Rounded(point.r + error[0]),\n inRange0to255Rounded(point.g + error[1]),\n inRange0to255Rounded(point.b + error[2]),\n inRange0to255Rounded(point.a + error[3]),\n );\n\n // Reduced pixel\n const palettePoint = palette.getNearestColor(\n this._distance,\n correctedPoint,\n );\n point.from(palettePoint);\n\n // dithering strength\n if (this._minColorDistance) {\n const dist = this._distance.calculateNormalized(\n originalPoint,\n palettePoint,\n );\n if (dist < this._minColorDistance) continue;\n }\n\n // Component distance\n let er;\n let eg;\n let eb;\n let ea;\n if (this._calculateErrorLikeGIMP) {\n er = correctedPoint.r - palettePoint.r;\n eg = correctedPoint.g - palettePoint.g;\n eb = correctedPoint.b - palettePoint.b;\n ea = correctedPoint.a - palettePoint.a;\n } else {\n er = originalPoint.r - palettePoint.r;\n eg = originalPoint.g - palettePoint.g;\n eb = originalPoint.b - palettePoint.b;\n ea = originalPoint.a - palettePoint.a;\n }\n\n const dStart = dir === 1 ? 0 : this._kernel.length - 1;\n const dEnd = dir === 1 ? this._kernel.length : -1;\n\n for (let i = dStart; i !== dEnd; i += dir) {\n const x1 = this._kernel[i][1] * dir;\n const y1 = this._kernel[i][2];\n\n if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) {\n const d = this._kernel[i][0];\n const e = errorLines[y1][x1 + x];\n\n e[0] += er * d;\n e[1] += eg * d;\n e[2] += eb * d;\n e[3] += ea * d;\n }\n }\n }\n }\n\n yield {\n pointContainer,\n progress: 100,\n };\n }\n\n private _fillErrorLine(errorLine: number[][], width: number) {\n // shrink\n if (errorLine.length > width) {\n errorLine.length = width;\n }\n\n // reuse existing arrays\n const l = errorLine.length;\n for (let i = 0; i < l; i++) {\n const error = errorLine[i];\n error[0] = error[1] = error[2] = error[3] = 0;\n }\n\n // create missing arrays\n for (let i = l; i < width; i++) {\n errorLine[i] = [0.0, 0.0, 0.0, 0.0];\n }\n }\n\n private _setKernel(kernel: ErrorDiffusionArrayKernel) {\n switch (kernel) {\n case ErrorDiffusionArrayKernel.FloydSteinberg:\n this._kernel = [\n [7 / 16, 1, 0],\n [3 / 16, -1, 1],\n [5 / 16, 0, 1],\n [1 / 16, 1, 1],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.FalseFloydSteinberg:\n this._kernel = [\n [3 / 8, 1, 0],\n [3 / 8, 0, 1],\n [2 / 8, 1, 1],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.Stucki:\n this._kernel = [\n [8 / 42, 1, 0],\n [4 / 42, 2, 0],\n [2 / 42, -2, 1],\n [4 / 42, -1, 1],\n [8 / 42, 0, 1],\n [4 / 42, 1, 1],\n [2 / 42, 2, 1],\n [1 / 42, -2, 2],\n [2 / 42, -1, 2],\n [4 / 42, 0, 2],\n [2 / 42, 1, 2],\n [1 / 42, 2, 2],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.Atkinson:\n this._kernel = [\n [1 / 8, 1, 0],\n [1 / 8, 2, 0],\n [1 / 8, -1, 1],\n [1 / 8, 0, 1],\n [1 / 8, 1, 1],\n [1 / 8, 0, 2],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.Jarvis:\n this._kernel = [\n // Jarvis, Judice, and Ninke / JJN?\n [7 / 48, 1, 0],\n [5 / 48, 2, 0],\n [3 / 48, -2, 1],\n [5 / 48, -1, 1],\n [7 / 48, 0, 1],\n [5 / 48, 1, 1],\n [3 / 48, 2, 1],\n [1 / 48, -2, 2],\n [3 / 48, -1, 2],\n [5 / 48, 0, 2],\n [3 / 48, 1, 2],\n [1 / 48, 2, 2],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.Burkes:\n this._kernel = [\n [8 / 32, 1, 0],\n [4 / 32, 2, 0],\n [2 / 32, -2, 1],\n [4 / 32, -1, 1],\n [8 / 32, 0, 1],\n [4 / 32, 1, 1],\n [2 / 32, 2, 1],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.Sierra:\n this._kernel = [\n [5 / 32, 1, 0],\n [3 / 32, 2, 0],\n [2 / 32, -2, 1],\n [4 / 32, -1, 1],\n [5 / 32, 0, 1],\n [4 / 32, 1, 1],\n [2 / 32, 2, 1],\n [2 / 32, -1, 2],\n [3 / 32, 0, 2],\n [2 / 32, 1, 2],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.TwoSierra:\n this._kernel = [\n [4 / 16, 1, 0],\n [3 / 16, 2, 0],\n [1 / 16, -2, 1],\n [2 / 16, -1, 1],\n [3 / 16, 0, 1],\n [2 / 16, 1, 1],\n [1 / 16, 2, 1],\n ];\n break;\n\n case ErrorDiffusionArrayKernel.SierraLite:\n this._kernel = [\n [2 / 4, 1, 0],\n [1 / 4, -1, 1],\n [1 / 4, 0, 1],\n ];\n break;\n\n default:\n throw new Error(`ErrorDiffusionArray: unknown kernel = ${kernel}`);\n }\n }\n}\n","import { ProgressTracker } from '../../utils/progressTracker';\nimport { ImageQuantizerYieldValue } from '../imageQuantizerYieldValue';\n\nenum Direction {\n NONE = 0,\n UP,\n LEFT,\n RIGHT,\n DOWN,\n}\n\ninterface Data {\n x: number;\n y: number;\n width: number;\n height: number;\n level: number;\n index: number;\n tracker: ProgressTracker;\n callback(x: number, y: number): void;\n}\n\nexport function* hilbertCurve(\n width: number,\n height: number,\n callback: (x: number, y: number) => void,\n) {\n const maxBound = Math.max(width, height);\n const level = Math.floor(Math.log(maxBound) / Math.log(2) + 1);\n const tracker = new ProgressTracker(width * height, 99);\n const data = {\n width,\n height,\n level,\n callback,\n tracker,\n index: 0,\n x: 0,\n y: 0,\n };\n yield* walkHilbert(data, Direction.UP);\n visit(data, Direction.NONE);\n}\n\nfunction* walkHilbert(\n data: Data,\n direction: Direction,\n): IterableIterator {\n if (data.level < 1) return;\n\n if (data.tracker.shouldNotify(data.index)) {\n yield { progress: data.tracker.progress };\n }\n data.level--;\n switch (direction) {\n case Direction.LEFT:\n yield* walkHilbert(data, Direction.UP);\n visit(data, Direction.RIGHT);\n yield* walkHilbert(data, Direction.LEFT);\n visit(data, Direction.DOWN);\n yield* walkHilbert(data, Direction.LEFT);\n visit(data, Direction.LEFT);\n yield* walkHilbert(data, Direction.DOWN);\n break;\n\n case Direction.RIGHT:\n yield* walkHilbert(data, Direction.DOWN);\n visit(data, Direction.LEFT);\n yield* walkHilbert(data, Direction.RIGHT);\n visit(data, Direction.UP);\n yield* walkHilbert(data, Direction.RIGHT);\n visit(data, Direction.RIGHT);\n yield* walkHilbert(data, Direction.UP);\n break;\n\n case Direction.UP:\n yield* walkHilbert(data, Direction.LEFT);\n visit(data, Direction.DOWN);\n yield* walkHilbert(data, Direction.UP);\n visit(data, Direction.RIGHT);\n yield* walkHilbert(data, Direction.UP);\n visit(data, Direction.UP);\n yield* walkHilbert(data, Direction.RIGHT);\n break;\n\n case Direction.DOWN:\n yield* walkHilbert(data, Direction.RIGHT);\n visit(data, Direction.UP);\n yield* walkHilbert(data, Direction.DOWN);\n visit(data, Direction.LEFT);\n yield* walkHilbert(data, Direction.DOWN);\n visit(data, Direction.DOWN);\n yield* walkHilbert(data, Direction.LEFT);\n break;\n\n default:\n break;\n }\n data.level++;\n}\n\nfunction visit(data: Data, direction: Direction) {\n if (\n data.x >= 0 &&\n data.x < data.width &&\n data.y >= 0 &&\n data.y < data.height\n ) {\n data.callback(data.x, data.y);\n data.index++;\n }\n switch (direction) {\n case Direction.LEFT:\n data.x--;\n break;\n case Direction.RIGHT:\n data.x++;\n break;\n case Direction.UP:\n data.y--;\n break;\n case Direction.DOWN:\n data.y++;\n break;\n }\n}\n","/**\n * @preserve\n * MIT License\n *\n * Copyright 2015-2018 Igor Bezkrovnyi\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * riemersma.ts - part of Image Quantization Library\n */\nimport { AbstractImageQuantizer } from './imageQuantizer';\nimport { hilbertCurve } from './spaceFillingCurves/hilbertCurve';\nimport { AbstractDistanceCalculator } from '../distance/distanceCalculator';\nimport { PointContainer } from '../utils/pointContainer';\nimport { Palette } from '../utils/palette';\nimport { Point } from '../utils/point';\nimport { inRange0to255Rounded } from '../utils/arithmetic';\n\nexport class ErrorDiffusionRiemersma extends AbstractImageQuantizer {\n private _distance: AbstractDistanceCalculator;\n private _weights: number[];\n private _errorQueueSize: number;\n\n constructor(\n colorDistanceCalculator: AbstractDistanceCalculator,\n errorQueueSize = 16,\n errorPropagation = 1,\n ) {\n super();\n this._distance = colorDistanceCalculator;\n this._errorQueueSize = errorQueueSize;\n this._weights = ErrorDiffusionRiemersma._createWeights(\n errorPropagation,\n errorQueueSize,\n );\n }\n\n /**\n * Mutates pointContainer\n */\n *quantize(pointContainer: PointContainer, palette: Palette) {\n const pointArray = pointContainer.getPointArray();\n const width = pointContainer.getWidth();\n const height = pointContainer.getHeight();\n const errorQueue: Array<{\n r: number;\n g: number;\n b: number;\n a: number;\n }> = [];\n\n let head = 0;\n\n for (let i = 0; i < this._errorQueueSize; i++) {\n errorQueue[i] = { r: 0, g: 0, b: 0, a: 0 };\n }\n\n yield* hilbertCurve(width, height, (x, y) => {\n const p = pointArray[x + y * width];\n let { r, g, b, a } = p;\n for (let i = 0; i < this._errorQueueSize; i++) {\n const weight = this._weights[i];\n const e = errorQueue[(i + head) % this._errorQueueSize];\n\n r += e.r * weight;\n g += e.g * weight;\n b += e.b * weight;\n a += e.a * weight;\n }\n\n const correctedPoint = Point.createByRGBA(\n inRange0to255Rounded(r),\n inRange0to255Rounded(g),\n inRange0to255Rounded(b),\n inRange0to255Rounded(a),\n );\n\n const quantizedPoint = palette.getNearestColor(\n this._distance,\n correctedPoint,\n );\n\n // update head and calculate tail\n head = (head + 1) % this._errorQueueSize;\n const tail = (head + this._errorQueueSize - 1) % this._errorQueueSize;\n\n // update error with new value\n errorQueue[tail].r = p.r - quantizedPoint.r;\n errorQueue[tail].g = p.g - quantizedPoint.g;\n errorQueue[tail].b = p.b - quantizedPoint.b;\n errorQueue[tail].a = p.a - quantizedPoint.a;\n\n // update point\n p.from(quantizedPoint);\n });\n\n yield {\n pointContainer,\n progress: 100,\n };\n }\n\n private static _createWeights(\n errorPropagation: number,\n errorQueueSize: number,\n ) {\n const weights = [];\n\n const multiplier = Math.exp(\n Math.log(errorQueueSize) / (errorQueueSize - 1),\n );\n for (let i = 0, next = 1; i < errorQueueSize; i++) {\n weights[i] = (((next + 0.5) | 0) / errorQueueSize) * errorPropagation;\n next *= multiplier;\n }\n\n return weights;\n }\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * iq.ts - Image Quantization Library\n */\nexport { ssim } from './ssim';\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * ssim.ts - part of Image Quantization Library\n */\nimport { PointContainer } from '../utils/pointContainer';\nimport { Y } from '../constants/bt709';\n\n// based on https://github.com/rhys-e/structural-similarity\n// http://en.wikipedia.org/wiki/Structural_similarity\nconst K1 = 0.01;\nconst K2 = 0.03;\n\nexport function ssim(image1: PointContainer, image2: PointContainer) {\n if (\n image1.getHeight() !== image2.getHeight() ||\n image1.getWidth() !== image2.getWidth()\n ) {\n throw new Error('Images have different sizes!');\n }\n\n const bitsPerComponent = 8;\n const L = (1 << bitsPerComponent) - 1;\n const c1 = (K1 * L) ** 2;\n const c2 = (K2 * L) ** 2;\n\n let numWindows = 0;\n let mssim = 0.0;\n\n // calculate ssim for each window\n iterate(\n image1,\n image2,\n (lumaValues1, lumaValues2, averageLumaValue1, averageLumaValue2) => {\n // calculate variance and covariance\n let sigxy = 0.0;\n let sigsqx = 0.0;\n let sigsqy = 0.0;\n\n for (let i = 0; i < lumaValues1.length; i++) {\n sigsqx += (lumaValues1[i] - averageLumaValue1) ** 2;\n sigsqy += (lumaValues2[i] - averageLumaValue2) ** 2;\n\n sigxy +=\n (lumaValues1[i] - averageLumaValue1) *\n (lumaValues2[i] - averageLumaValue2);\n }\n\n const numPixelsInWin = lumaValues1.length - 1;\n sigsqx /= numPixelsInWin;\n sigsqy /= numPixelsInWin;\n sigxy /= numPixelsInWin;\n\n // perform ssim calculation on window\n const numerator =\n (2 * averageLumaValue1 * averageLumaValue2 + c1) * (2 * sigxy + c2);\n const denominator =\n (averageLumaValue1 ** 2 + averageLumaValue2 ** 2 + c1) *\n (sigsqx + sigsqy + c2);\n const ssim = numerator / denominator;\n\n mssim += ssim;\n numWindows++;\n },\n );\n return mssim / numWindows;\n}\n\nfunction iterate(\n image1: PointContainer,\n image2: PointContainer,\n callback: (\n lumaValues1: number[],\n lumaValues2: number[],\n averageLumaValue1: number,\n averageLumaValue2: number,\n ) => void,\n) {\n const windowSize = 8;\n const width = image1.getWidth();\n const height = image1.getHeight();\n\n for (let y = 0; y < height; y += windowSize) {\n for (let x = 0; x < width; x += windowSize) {\n // avoid out-of-width/height\n const windowWidth = Math.min(windowSize, width - x);\n const windowHeight = Math.min(windowSize, height - y);\n\n const lumaValues1 = calculateLumaValuesForWindow(\n image1,\n x,\n y,\n windowWidth,\n windowHeight,\n );\n const lumaValues2 = calculateLumaValuesForWindow(\n image2,\n x,\n y,\n windowWidth,\n windowHeight,\n );\n const averageLuma1 = calculateAverageLuma(lumaValues1);\n const averageLuma2 = calculateAverageLuma(lumaValues2);\n\n callback(lumaValues1, lumaValues2, averageLuma1, averageLuma2);\n }\n }\n}\n\nfunction calculateLumaValuesForWindow(\n image: PointContainer,\n x: number,\n y: number,\n width: number,\n height: number,\n) {\n const pointArray = image.getPointArray();\n const lumaValues = [];\n\n let counter = 0;\n\n for (let j = y; j < y + height; j++) {\n const offset = j * image.getWidth();\n for (let i = x; i < x + width; i++) {\n const point = pointArray[offset + i];\n lumaValues[counter] =\n point.r * Y.RED + point.g * Y.GREEN + point.b * Y.BLUE;\n counter++;\n }\n }\n\n return lumaValues;\n}\n\nfunction calculateAverageLuma(lumaValues: number[]) {\n let sumLuma = 0.0;\n for (const luma of lumaValues) {\n sumLuma += luma;\n }\n\n return sumLuma / lumaValues.length;\n}\n","/**\n * @preserve\n * Copyright 2015-2018 Igor Bezkrovnyi\n * All rights reserved. (MIT Licensed)\n *\n * helper.ts - part of Image Quantization Library\n */\nimport * as distance from './distance';\nimport * as image from './image';\nimport * as palette from './palette';\nimport { AbstractDistanceCalculator } from './distance/distanceCalculator';\nimport { PointContainer } from './utils/pointContainer';\nimport { Palette } from './utils/palette';\n\nconst setImmediateImpl =\n typeof setImmediate === 'function'\n ? setImmediate\n : typeof process !== 'undefined' && typeof process?.nextTick === 'function'\n ? (callback: () => void) => process.nextTick(callback)\n : (callback: () => void) => setTimeout(callback, 0);\n\nexport type ColorDistanceFormula =\n | 'cie94-textiles'\n | 'cie94-graphic-arts'\n | 'ciede2000'\n | 'color-metric'\n | 'euclidean'\n | 'euclidean-bt709-noalpha'\n | 'euclidean-bt709'\n | 'manhattan'\n | 'manhattan-bt709'\n | 'manhattan-nommyde'\n | 'pngquant';\n\nexport type PaletteQuantization =\n | 'neuquant'\n | 'neuquant-float'\n | 'rgbquant'\n | 'wuquant';\n\nexport type ImageQuantization =\n | 'nearest'\n | 'riemersma'\n | 'floyd-steinberg'\n | 'false-floyd-steinberg'\n | 'stucki'\n | 'atkinson'\n | 'jarvis'\n | 'burkes'\n | 'sierra'\n | 'two-sierra'\n | 'sierra-lite';\n\nexport interface ProgressOptions {\n onProgress?: (progress: number) => void;\n}\n\nexport interface ApplyPaletteOptions {\n colorDistanceFormula?: ColorDistanceFormula;\n imageQuantization?: ImageQuantization;\n}\n\nexport interface BuildPaletteOptions {\n colorDistanceFormula?: ColorDistanceFormula;\n paletteQuantization?: PaletteQuantization;\n colors?: number;\n}\n\nexport function buildPaletteSync(\n images: PointContainer[],\n {\n colorDistanceFormula,\n paletteQuantization,\n colors,\n }: BuildPaletteOptions = {},\n) {\n const distanceCalculator =\n colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const paletteQuantizer = paletteQuantizationToPaletteQuantizer(\n distanceCalculator,\n paletteQuantization,\n colors,\n );\n images.forEach((image) => paletteQuantizer.sample(image));\n return paletteQuantizer.quantizeSync();\n}\n\nexport async function buildPalette(\n images: PointContainer[],\n {\n colorDistanceFormula,\n paletteQuantization,\n colors,\n onProgress,\n }: BuildPaletteOptions & ProgressOptions = {},\n) {\n return new Promise((resolve, reject) => {\n const distanceCalculator =\n colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const paletteQuantizer = paletteQuantizationToPaletteQuantizer(\n distanceCalculator,\n paletteQuantization,\n colors,\n );\n images.forEach((image) => paletteQuantizer.sample(image));\n\n let palette: Palette;\n const iterator = paletteQuantizer.quantize();\n const next = () => {\n try {\n const result = iterator.next();\n if (result.done) {\n resolve(palette);\n } else {\n if (result.value.palette) palette = result.value.palette;\n if (onProgress) onProgress(result.value.progress);\n setImmediateImpl(next);\n }\n } catch (error) {\n reject(error);\n }\n };\n setImmediateImpl(next);\n });\n}\n\nexport function applyPaletteSync(\n image: PointContainer,\n palette: Palette,\n { colorDistanceFormula, imageQuantization }: ApplyPaletteOptions = {},\n) {\n const distanceCalculator =\n colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const imageQuantizer = imageQuantizationToImageQuantizer(\n distanceCalculator,\n imageQuantization,\n );\n return imageQuantizer.quantizeSync(image, palette);\n}\n\nexport async function applyPalette(\n image: PointContainer,\n palette: Palette,\n {\n colorDistanceFormula,\n imageQuantization,\n onProgress,\n }: ApplyPaletteOptions & ProgressOptions = {},\n) {\n return new Promise((resolve, reject) => {\n const distanceCalculator =\n colorDistanceFormulaToColorDistance(colorDistanceFormula);\n const imageQuantizer = imageQuantizationToImageQuantizer(\n distanceCalculator,\n imageQuantization,\n );\n\n let outPointContainer: PointContainer;\n const iterator = imageQuantizer.quantize(image, palette);\n const next = () => {\n try {\n const result = iterator.next();\n if (result.done) {\n resolve(outPointContainer);\n } else {\n if (result.value.pointContainer) {\n outPointContainer = result.value.pointContainer;\n }\n if (onProgress) onProgress(result.value.progress);\n setImmediateImpl(next);\n }\n } catch (error) {\n reject(error);\n }\n };\n setImmediateImpl(next);\n });\n}\n\nfunction colorDistanceFormulaToColorDistance(\n colorDistanceFormula: ColorDistanceFormula = 'euclidean-bt709',\n) {\n switch (colorDistanceFormula) {\n case 'cie94-graphic-arts':\n return new distance.CIE94GraphicArts();\n case 'cie94-textiles':\n return new distance.CIE94Textiles();\n case 'ciede2000':\n return new distance.CIEDE2000();\n case 'color-metric':\n return new distance.CMetric();\n case 'euclidean':\n return new distance.Euclidean();\n case 'euclidean-bt709':\n return new distance.EuclideanBT709();\n case 'euclidean-bt709-noalpha':\n return new distance.EuclideanBT709NoAlpha();\n case 'manhattan':\n return new distance.Manhattan();\n case 'manhattan-bt709':\n return new distance.ManhattanBT709();\n case 'manhattan-nommyde':\n return new distance.ManhattanNommyde();\n case 'pngquant':\n return new distance.PNGQuant();\n default:\n throw new Error(`Unknown colorDistanceFormula ${colorDistanceFormula}`);\n }\n}\n\nfunction imageQuantizationToImageQuantizer(\n distanceCalculator: AbstractDistanceCalculator,\n imageQuantization: ImageQuantization = 'floyd-steinberg',\n) {\n switch (imageQuantization) {\n case 'nearest':\n return new image.NearestColor(distanceCalculator);\n case 'riemersma':\n return new image.ErrorDiffusionRiemersma(distanceCalculator);\n case 'floyd-steinberg':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.FloydSteinberg,\n );\n case 'false-floyd-steinberg':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.FalseFloydSteinberg,\n );\n case 'stucki':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.Stucki,\n );\n case 'atkinson':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.Atkinson,\n );\n case 'jarvis':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.Jarvis,\n );\n case 'burkes':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.Burkes,\n );\n case 'sierra':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.Sierra,\n );\n case 'two-sierra':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.TwoSierra,\n );\n case 'sierra-lite':\n return new image.ErrorDiffusionArray(\n distanceCalculator,\n image.ErrorDiffusionArrayKernel.SierraLite,\n );\n default:\n throw new Error(`Unknown imageQuantization ${imageQuantization}`);\n }\n}\n\nfunction paletteQuantizationToPaletteQuantizer(\n distanceCalculator: AbstractDistanceCalculator,\n paletteQuantization: PaletteQuantization = 'wuquant',\n colors = 256,\n) {\n switch (paletteQuantization) {\n case 'neuquant':\n return new palette.NeuQuant(distanceCalculator, colors);\n case 'rgbquant':\n return new palette.RGBQuant(distanceCalculator, colors);\n case 'wuquant':\n return new palette.WuQuant(distanceCalculator, colors);\n case 'neuquant-float':\n return new palette.NeuQuantFloat(distanceCalculator, colors);\n default:\n throw new Error(`Unknown paletteQuantization ${paletteQuantization}`);\n }\n}\n","'use strict';\n\nconst BitmapImage = require('./bitmapimage');\nconst { GifError } = require('./gif');\n\n/** @class GifFrame */\n\nclass GifFrame extends BitmapImage {\n\n // xOffset - x offset of bitmap on GIF (defaults to 0)\n // yOffset - y offset of bitmap on GIF (defaults to 0)\n // disposalMethod - pixel disposal method when handling partial images\n // delayCentisecs - duration of frame in hundredths of a second\n // interlaced - whether the image is interlaced (defaults to false)\n\n /**\n * GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame.\n * \n * Property | Description\n * --- | ---\n * xOffset | x-coord of position within GIF at which to render the image (defaults to 0)\n * yOffset | y-coord of position within GIF at which to render the image (defaults to 0)\n * disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color)\n * delayCentisecs | duration of the frame in hundreths of a second\n * interlaced | boolean indicating whether the frame renders interlaced\n * \n * Its constructor supports the following signatures:\n * \n * * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?)\n * * new GifFrame(bitmapImage: BitmapImage, options?)\n * * new GifFrame(width: number, height: number, buffer: Buffer, options?)\n * * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?)\n * * new GifFrame(frame: GifFrame)\n * \n * See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional.\n * \n * Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other.\n */\n\n constructor(...args) {\n super(...args);\n if (args[0] instanceof GifFrame) {\n // copy a provided GifFrame\n const source = args[0];\n this.xOffset = source.xOffset;\n this.yOffset = source.yOffset;\n this.disposalMethod = source.disposalMethod;\n this.delayCentisecs = source.delayCentisecs;\n this.interlaced = source.interlaced;\n }\n else {\n const lastArg = args[args.length - 1];\n let options = {};\n if (typeof lastArg === 'object' && !(lastArg instanceof BitmapImage)) {\n options = lastArg;\n }\n this.xOffset = options.xOffset || 0;\n this.yOffset = options.yOffset || 0;\n this.disposalMethod = (options.disposalMethod !== undefined ?\n options.disposalMethod : GifFrame.DisposeToBackgroundColor);\n this.delayCentisecs = options.delayCentisecs || 8;\n this.interlaced = options.interlaced || false;\n }\n }\n\n /**\n * Get a summary of the colors found within the frame. The return value is an object of the following form:\n * \n * Property | Description\n * --- | ---\n * colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent.\n * usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00.\n * indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency.\n * \n * @return {object} An object representing a color palette as described above.\n */\n\n getPalette() {\n // returns with colors sorted low to high\n const colorSet = new Set();\n const buf = this.bitmap.data;\n let i = 0;\n let usesTransparency = false;\n while (i < buf.length) {\n if (buf[i + 3] === 0) {\n usesTransparency = true;\n }\n else {\n // can eliminate the bitshift by starting one byte prior\n const color = (buf.readUInt32BE(i, true) >> 8) & 0xFFFFFF;\n colorSet.add(color);\n }\n i += 4; // skip alpha\n }\n const colors = new Array(colorSet.size);\n const iter = colorSet.values();\n for (i = 0; i < colors.length; ++i) {\n colors[i] = iter.next().value;\n }\n colors.sort((a, b) => (a - b));\n let indexCount = colors.length;\n if (usesTransparency) {\n ++indexCount;\n }\n return { colors, usesTransparency, indexCount };\n }\n}\n\nGifFrame.DisposeToAnything = 0;\nGifFrame.DisposeNothing = 1;\nGifFrame.DisposeToBackgroundColor = 2;\nGifFrame.DisposeToPrevious = 3;\n\nexports.GifFrame = GifFrame;\n","'use strict';\n\n/** @namespace GifUtil */\n\nconst fs = require('fs');\nconst ImageQ = require('image-q');\n\nconst BitmapImage = require('./bitmapimage');\nconst { GifFrame } = require('./gifframe');\nconst { GifError } = require('./gif');\nconst { GifCodec } = require('./gifcodec');\n\nconst INVALID_SUFFIXES = ['.jpg', '.jpeg', '.png', '.bmp'];\n\nconst defaultCodec = new GifCodec();\n\n/**\n * cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once.\n * \n * @function cloneFrames\n * @memberof GifUtil\n * @param {GifFrame[]} frames An array of GifFrame instances to clone\n * @return {GifFrame[]} An array of GifFrame clones of the provided frames.\n */\n\nexports.cloneFrames = function (frames) {\n let clones = [];\n frames.forEach(frame => {\n\n clones.push(new GifFrame(frame));\n });\n return clones;\n}\n\n/**\n * getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames.\n * \n * `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency.\n * \n * @function getColorInfo\n * @memberof GifUtil\n * @param {GifFrame[]} frames Frames to examine for color and transparency.\n * @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default.\n * @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF.\n * @throws {GifError} When any frame requires more than 256 color indexes.\n */\n\nexports.getColorInfo = function (frames, maxGlobalIndex) {\n let usesTransparency = false;\n const palettes = [];\n for (let i = 0; i < frames.length; ++i) {\n let palette = frames[i].getPalette();\n if (palette.usesTransparency) {\n usesTransparency = true;\n }\n if (palette.indexCount > 256) {\n throw new GifError(`Frame ${i} uses more than 256 color indexes`);\n }\n palettes.push(palette);\n }\n if (maxGlobalIndex === 0) {\n return { usesTransparency, palettes };\n }\n\n const globalColorSet = new Set();\n palettes.forEach(palette => {\n\n palette.colors.forEach(color => {\n\n globalColorSet.add(color);\n });\n });\n let indexCount = globalColorSet.size;\n if (usesTransparency) {\n // odd that GIF requires a color table entry at transparent index\n ++indexCount;\n }\n if (maxGlobalIndex && indexCount > maxGlobalIndex) {\n return { usesTransparency, palettes };\n }\n \n const colors = new Array(globalColorSet.size);\n const iter = globalColorSet.values();\n for (let i = 0; i < colors.length; ++i) {\n colors[i] = iter.next().value;\n }\n colors.sort((a, b) => (a - b));\n return { colors, indexCount, usesTransparency, palettes };\n};\n\n/**\n * copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp.\n *\n * @function copyAsJimp\n * @memberof GifUtil\n * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.\n * @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.\n * @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy.\n */\n \nexports.copyAsJimp = function (jimp, bitmapImageToCopy) {\n return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy));\n};\n\n/**\n * getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame.\n * \n * @function getMaxDimensions\n * @memberof GifUtil\n * @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions.\n * @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames.\n */\n\nexports.getMaxDimensions = function (frames) {\n let maxWidth = 0, maxHeight = 0;\n frames.forEach(frame => {\n const width = frame.xOffset + frame.bitmap.width;\n if (width > maxWidth) {\n maxWidth = width;\n }\n const height = frame.yOffset + frame.bitmap.height;\n if (height > maxHeight) {\n maxHeight = height;\n }\n });\n return { maxWidth, maxHeight };\n};\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * The method may increase the number of colors if there are fewer than the provided maximum.\n * \n * @function quantizeDekker\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. }\n */\n\nexports.quantizeDekker = function (imageOrImages, maxColorIndexes, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n _quantize(imageOrImages, 'NeuQuantFloat', maxColorIndexes, 0, dither);\n}\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * @function quantizeSorokin\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'.\n * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.\n */\n\nexports.quantizeSorokin = function (imageOrImages, maxColorIndexes, histogram, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n histogram = histogram || 'min-pop';\n let histogramID;\n switch (histogram) {\n case 'min-pop':\n histogramID = 2;\n break;\n\n case 'top-pop':\n histogramID = 1;\n break\n\n default:\n throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`);\n }\n _quantize(imageOrImages, 'RGBQuant', maxColorIndexes, histogramID, dither);\n}\n\n/**\n * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu.\n * \n * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values.\n * \n * The method may increase the number of colors if there are fewer than the provided maximum.\n * \n * @function quantizeWu\n * @memberof GifUtil\n * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame.\n * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256.\n * @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5.\n * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`.\n */\n\nexports.quantizeWu = function (imageOrImages, maxColorIndexes, significantBits, dither) {\n maxColorIndexes = maxColorIndexes || 256;\n significantBits = significantBits || 5;\n if (significantBits < 1 || significantBits > 8) {\n throw new Error(\"Invalid quantization quality\");\n }\n _quantize(imageOrImages, 'WuQuant', maxColorIndexes, significantBits, dither);\n}\n\n/**\n * read() decodes an encoded GIF, whether provided as a filename or as a byte buffer.\n * \n * @function read\n * @memberof GifUtil\n * @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse.\n * @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF.\n */\n\nexports.read = function (source, decoder) {\n decoder = decoder || defaultCodec;\n if (Buffer.isBuffer(source)) {\n return decoder.decodeGif(source);\n }\n return _readBinary(source)\n .then(buffer => {\n\n return decoder.decodeGif(buffer);\n });\n};\n\n/**\n * shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp.\n *\n * @function shareAsJimp\n * @memberof GifUtil\n * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp.\n * @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp.\n * @return {object} An new instance of Jimp that shares the image in bitmapImageToShare.\n */\n \nexports.shareAsJimp = function (jimp, bitmapImageToShare) {\n const jimpImage = new jimp(bitmapImageToShare.bitmap.width,\n bitmapImageToShare.bitmap.height, 0);\n jimpImage.bitmap.data = bitmapImageToShare.bitmap.data;\n return jimpImage;\n};\n\n/**\n * write() encodes a GIF and saves it as a file.\n * \n * @function write\n * @memberof GifUtil\n * @param {string} path Filename to write GIF out as. Will overwrite an existing file.\n * @param {GifFrame[]} frames Array of frames to be written into GIF.\n * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred.\n * @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n */\n\nexports.write = function (path, frames, spec, encoder) {\n encoder = encoder || defaultCodec;\n const matches = path.match(/\\.[a-zA-Z]+$/); // prevent accidents\n if (matches !== null &&\n INVALID_SUFFIXES.includes(matches[0].toLowerCase()))\n {\n throw new Error(`GIF '${path}' has an unexpected suffix`);\n }\n\n return encoder.encodeGif(frames, spec)\n .then(gif => {\n\n return _writeBinary(path, gif.buffer)\n .then(() => {\n\n return gif;\n });\n });\n};\n\nfunction _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) {\n const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages];\n const ditherAlgs = [\n 'FloydSteinberg',\n 'FalseFloydSteinberg',\n 'Stucki',\n 'Atkinson',\n 'Jarvis',\n 'Burkes',\n 'Sierra',\n 'TwoSierra',\n 'SierraLite'\n ];\n\n if (dither) {\n if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) {\n throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`);\n }\n if (dither.serpentine === undefined) {\n dither.serpentine = true;\n }\n if (dither.minimumColorDistanceToDither === undefined) {\n dither.minimumColorDistanceToDither = 0;\n }\n if (dither.calculateErrorLikeGIMP === undefined) {\n dither.calculateErrorLikeGIMP = false;\n }\n }\n\n const distCalculator = new ImageQ.distance.Euclidean();\n const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier);\n let imageMaker;\n if (dither) {\n imageMaker = new ImageQ.image.ErrorDiffusionArray(\n distCalculator,\n ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm],\n dither.serpentine,\n dither.minimumColorDistanceToDither,\n dither.calculateErrorLikeGIMP\n );\n }\n else {\n imageMaker = new ImageQ.image.NearestColor(distCalculator);\n }\n\n const inputContainers = [];\n images.forEach(image => {\n\n const imageBuf = image.bitmap.data;\n const inputBuf = new ArrayBuffer(imageBuf.length);\n const inputArray = new Uint32Array(inputBuf);\n for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {\n inputArray[ai] = imageBuf.readUInt32LE(bi, true);\n }\n const inputContainer = ImageQ.utils.PointContainer.fromUint32Array(\n inputArray, image.bitmap.width, image.bitmap.height);\n quantizer.sample(inputContainer);\n inputContainers.push(inputContainer);\n });\n \n const limitedPalette = quantizer.quantizeSync();\n\n for (let i = 0; i < images.length; ++i) {\n const imageBuf = images[i].bitmap.data;\n const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette);\n const outputArray = outputContainer.toUint32Array();\n for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) {\n imageBuf.writeUInt32LE(outputArray[ai], bi);\n }\n }\n}\n\nfunction _readBinary(path) {\n // TBD: add support for URLs\n return new Promise((resolve, reject) => {\n\n fs.readFile(path, (err, buffer) => {\n\n if (err) {\n return reject(err);\n }\n return resolve(buffer);\n });\n });\n}\n\nfunction _writeBinary(path, buffer) {\n // TBD: add support for URLs\n return new Promise((resolve, reject) => {\n\n fs.writeFile(path, buffer, err => {\n \n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n}\n","'use strict';\n\nconst Omggif = require('omggif');\nconst { Gif, GifError } = require('./gif');\n\n// allow circular dependency with GifUtil\nfunction GifUtil() {\n const data = require('./gifutil');\n\n GifUtil = function () {\n return data;\n };\n\n return data;\n}\n\nconst { GifFrame } = require('./gifframe');\n\nconst PER_GIF_OVERHEAD = 200; // these are guesses at upper limits\nconst PER_FRAME_OVERHEAD = 100;\n\n// Note: I experimented with accepting a global color table when encoding and returning the global color table when decoding. Doing this properly greatly increased the complexity of the code and the amount of clock cycles required. The main issue is that each frame can specify any color of the global color table to be transparent within the frame, while this GIF library strives to hide GIF formatting details from its clients. E.g. it's possible to have 256 colors in the global color table and different transparencies in each frame, requiring clients to either provide per-frame transparency indexes, or for arcane reasons that won't be apparent to client developers, encode some GIFs with local color tables that previously decoded with global tables.\n\n/** @class GifCodec */\n\nclass GifCodec\n{\n // _transparentRGBA - RGB given to transparent pixels (alpha=0) on decode; defaults to null indicating 0x000000, which is fastest\n\n /**\n * GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing.\n * \n * Instances of this class are stateless and can be shared across multiple encodings and decodings.\n * \n * Its constructor takes one option argument:\n * \n * @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000.\n */\n\n constructor(options = {}) {\n this._transparentRGB = null; // 0x000000\n if (typeof options.transparentRGB === 'number' &&\n options.transparentRGB !== 0)\n {\n this._transparentRGBA = options.transparentRGB * 256;\n }\n this._testInitialBufferSize = 0; // assume no buffer scaling test\n }\n\n /**\n * Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option.\n * \n * @param {Buffer} buffer Bytes of an encoded GIF to decode.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.\n */\n\n decodeGif(buffer) {\n try {\n let reader;\n try {\n reader = new Omggif.GifReader(buffer);\n }\n catch (err) {\n throw new GifError(err);\n }\n const frameCount = reader.numFrames();\n const frames = [];\n const spec = {\n width: reader.width,\n height: reader.height,\n loops: reader.loopCount()\n };\n\n spec.usesTransparency = false;\n for (let i = 0; i < frameCount; ++i) {\n const frameInfo =\n this._decodeFrame(reader, i, spec.usesTransparency);\n frames.push(frameInfo.frame);\n if (frameInfo.usesTransparency) {\n spec.usesTransparency = true;\n }\n }\n return Promise.resolve(new Gif(buffer, frames, spec));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n\n /**\n * Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque.\n * \n * @param {GifFrame[]} frames Array of frames to encode\n * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred.\n * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF.\n * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs.\n */\n\n encodeGif(frames, spec = {}) {\n try {\n if (frames === null || frames.length === 0) {\n throw new GifError(\"there are no frames\");\n }\n const dims = GifUtil().getMaxDimensions(frames);\n\n spec = Object.assign({}, spec); // don't munge caller's spec\n spec.width = dims.maxWidth;\n spec.height = dims.maxHeight;\n if (spec.loops === undefined) {\n spec.loops = 0;\n }\n spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred;\n\n return Promise.resolve(this._encodeGif(frames, spec));\n }\n catch (err) {\n return Promise.reject(err);\n }\n }\n\n _decodeFrame(reader, frameIndex, alreadyUsedTransparency) {\n let info, buffer;\n try {\n info = reader.frameInfo(frameIndex);\n buffer = new Buffer(reader.width * reader.height * 4);\n reader.decodeAndBlitFrameRGBA(frameIndex, buffer);\n if (info.width !== reader.width || info.height !== reader.height) {\n if (info.y) {\n // skip unused rows\n buffer = buffer.slice(info.y * reader.width * 4);\n }\n if (reader.width > info.width) {\n // skip scanstride\n for (let ii = 0; ii < info.height; ++ii) {\n buffer.copy(buffer, ii * info.width * 4,\n (info.x + ii * reader.width) * 4,\n (info.x + ii * reader.width) * 4 + info.width * 4);\n }\n }\n // trim buffer to size\n buffer = buffer.slice(0, info.width * info.height * 4);\n }\n }\n catch (err) {\n throw new GifError(err);\n }\n\n let usesTransparency = false;\n if (this._transparentRGBA === null) {\n if (!alreadyUsedTransparency) {\n for (let i = 3; i < buffer.length; i += 4) {\n if (buffer[i] === 0) {\n usesTransparency = true;\n i = buffer.length;\n }\n }\n }\n }\n else {\n for (let i = 3; i < buffer.length; i += 4) {\n if (buffer[i] === 0) {\n buffer.writeUInt32BE(this._transparentRGBA, i - 3);\n usesTransparency = true; // GIF might encode unused index\n }\n }\n }\n\n const frame = new GifFrame(info.width, info.height, buffer, {\n xOffset: info.x,\n yOffset: info.y,\n disposalMethod: info.disposal,\n interlaced: info.interlaced,\n delayCentisecs: info.delay\n });\n return { frame, usesTransparency };\n }\n\n _encodeGif(frames, spec) {\n let colorInfo;\n if (spec.colorScope === Gif.LocalColorsOnly) {\n colorInfo = GifUtil().getColorInfo(frames, 0);\n }\n else {\n colorInfo = GifUtil().getColorInfo(frames, 256);\n if (!colorInfo.colors) { // if global palette impossible\n if (spec.colorScope === Gif.GlobalColorsOnly) {\n throw new GifError(\n \"Too many color indexes for global color table\");\n }\n spec.colorScope = Gif.LocalColorsOnly\n }\n }\n spec.usesTransparency = colorInfo.usesTransparency;\n\n const localPalettes = colorInfo.palettes;\n if (spec.colorScope === Gif.LocalColorsOnly) {\n const localSizeEst = 2000; //this._getSizeEstimateLocal(localPalettes, frames);\n return _encodeLocal(frames, spec, localSizeEst, localPalettes);\n }\n\n const globalSizeEst = 2000; //this._getSizeEstimateGlobal(colorInfo, frames);\n return _encodeGlobal(frames, spec, globalSizeEst, colorInfo);\n }\n\n _getSizeEstimateGlobal(globalPalette, frames) {\n if (this._testInitialBufferSize > 0) {\n return this._testInitialBufferSize;\n }\n let sizeEst = PER_GIF_OVERHEAD + 3*256 /* max palette size*/;\n const pixelBitWidth = _getPixelBitWidth(globalPalette);\n frames.forEach(frame => {\n sizeEst += _getFrameSizeEst(frame, pixelBitWidth);\n });\n return sizeEst; // should be the upper limit\n }\n\n _getSizeEstimateLocal(palettes, frames) {\n if (this._testInitialBufferSize > 0) {\n return this._testInitialBufferSize;\n }\n let sizeEst = PER_GIF_OVERHEAD;\n for (let i = 0; i < frames.length; ++i ) {\n const palette = palettes[i];\n const pixelBitWidth = _getPixelBitWidth(palette);\n sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth);\n }\n return sizeEst; // should be the upper limit\n }\n}\nexports.GifCodec = GifCodec;\n\nfunction _colorLookupLinear(colors, color) {\n const index = colors.indexOf(color);\n return (index === -1 ? null : index);\n}\n\nfunction _colorLookupBinary(colors, color) {\n // adapted from https://stackoverflow.com/a/10264318/650894\n var lo = 0, hi = colors.length - 1, mid;\n while (lo <= hi) {\n mid = Math.floor((lo + hi)/2);\n if (colors[mid] > color)\n hi = mid - 1;\n else if (colors[mid] < color)\n lo = mid + 1;\n else\n return mid;\n }\n return null;\n}\n\nfunction _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) {\n // would be inefficient for frames to lookup colors in extended palette \n const extendedGlobalPalette = {\n colors: globalPalette.colors.slice(),\n usesTransparency: globalPalette.usesTransparency\n };\n _extendPaletteToPowerOf2(extendedGlobalPalette);\n const options = {\n palette: extendedGlobalPalette.colors,\n loop: spec.loops\n };\n let buffer = new Buffer(bufferSizeEst);\n let gifWriter;\n try {\n gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,\n options);\n }\n catch (err) {\n throw new GifError(err);\n }\n for (let i = 0; i < frames.length; ++i) {\n buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false);\n }\n return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);\n}\n\nfunction _encodeLocal(frames, spec, bufferSizeEst, localPalettes) {\n const options = {\n loop: spec.loops\n };\n let buffer = new Buffer(bufferSizeEst);\n let gifWriter;\n try {\n gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height,\n options);\n } \n catch (err) {\n throw new GifError(err);\n }\n for (let i = 0; i < frames.length; ++i) {\n buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true);\n }\n return new Gif(buffer.slice(0, gifWriter.end()), frames, spec);\n}\n\nfunction _extendPaletteToPowerOf2(palette) {\n const colors = palette.colors;\n if (palette.usesTransparency) {\n colors.push(0);\n }\n const colorCount = colors.length;\n let powerOf2 = 2;\n while (colorCount > powerOf2) {\n powerOf2 <<= 1;\n }\n colors.length = powerOf2;\n colors.fill(0, colorCount);\n}\n\nfunction _getFrameSizeEst(frame, pixelBitWidth) {\n let byteLength = frame.bitmap.width * frame.bitmap.height;\n byteLength = Math.ceil(byteLength * pixelBitWidth / 8);\n byteLength += Math.ceil(byteLength / 255); // add block size bytes\n // assume maximum palete size because it might get extended for power of 2\n return (PER_FRAME_OVERHEAD + byteLength + 3 * 256 /* largest palette */);\n}\n\nfunction _getIndexedImage(frameIndex, frame, palette) {\n const colors = palette.colors;\n const colorToIndexFunc = (colors.length <= 8 ? // guess at the break-even\n _colorLookupLinear : _colorLookupBinary);\n const colorBuffer = frame.bitmap.data;\n const indexBuffer = new Buffer(colorBuffer.length/4);\n let transparentIndex = colors.length;\n let i = 0, j = 0;\n\n while (i < colorBuffer.length) {\n if (colorBuffer[i + 3] !== 0) {\n const color = (colorBuffer.readUInt32BE(i, true) >> 8) & 0xFFFFFF;\n // caller guarantees that the color will be in the palette\n indexBuffer[j] = colorToIndexFunc(colors, color);\n }\n else {\n indexBuffer[j] = transparentIndex;\n }\n i += 4; // skip alpha\n ++j;\n }\n\n if (palette.usesTransparency) {\n if (transparentIndex === 256) {\n throw new GifError(`Frame ${frameIndex} already has 256 colors` +\n `and so can't use transparency`);\n }\n }\n else {\n transparentIndex = null;\n }\n\n return { buffer: indexBuffer, transparentIndex };\n}\n\nfunction _getPixelBitWidth(palette) {\n let indexCount = palette.indexCount;\n let pixelBitWidth = 0;\n --indexCount; // start at maximum index\n while (indexCount) {\n ++pixelBitWidth;\n indexCount >>= 1;\n }\n return (pixelBitWidth > 0 ? pixelBitWidth : 1);\n}\n\nfunction _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) {\n if (frame.interlaced) {\n throw new GifError(\"writing interlaced GIFs is not supported\");\n }\n const frameInfo = _getIndexedImage(frameIndex, frame, palette);\n const options = {\n delay: frame.delayCentisecs,\n disposal: frame.disposalMethod,\n transparent: frameInfo.transparentIndex\n };\n if (isLocalPalette) {\n _extendPaletteToPowerOf2(palette); // ok 'cause palette never used again\n options.palette = palette.colors;\n }\n try {\n let buffer = gifWriter.getOutputBuffer();\n let startOfFrame = gifWriter.getOutputBufferPosition();\n let endOfFrame;\n let tryAgain = true;\n\n while (tryAgain) {\n endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset,\n frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options);\n tryAgain = false;\n if (endOfFrame >= buffer.length - 1) {\n const biggerBuffer = new Buffer(buffer.length * 1.5);\n buffer.copy(biggerBuffer);\n gifWriter.setOutputBuffer(biggerBuffer);\n gifWriter.setOutputBufferPosition(startOfFrame);\n buffer = biggerBuffer;\n tryAgain = true;\n }\n }\n return buffer;\n }\n catch (err) {\n throw new GifError(err);\n }\n}\n","'use strict';\n\nconst BitmapImage = require('./bitmapimage');\nconst { Gif, GifError } = require('./gif');\nconst { GifCodec } = require('./gifcodec');\nconst { GifFrame } = require('./gifframe');\nconst GifUtil = require('./gifutil');\n\nmodule.exports = {\n BitmapImage,\n Gif,\n GifCodec,\n GifFrame,\n GifUtil,\n GifError\n};\n","/*\n Copyright (c) 2008, Adobe Systems Incorporated\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without \n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the \n documentation and/or other materials provided with the distribution.\n \n * Neither the name of Adobe Systems Incorporated nor the names of its \n contributors may be used to endorse or promote products derived from \n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR \n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\nJPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009\n\nBasic GUI blocking jpeg encoder\n*/\n\nvar btoa = btoa || function(buf) {\n return Buffer.from(buf).toString('base64');\n};\n\nfunction JPEGEncoder(quality) {\n var self = this;\n\tvar fround = Math.round;\n\tvar ffloor = Math.floor;\n\tvar YTable = new Array(64);\n\tvar UVTable = new Array(64);\n\tvar fdtbl_Y = new Array(64);\n\tvar fdtbl_UV = new Array(64);\n\tvar YDC_HT;\n\tvar UVDC_HT;\n\tvar YAC_HT;\n\tvar UVAC_HT;\n\t\n\tvar bitcode = new Array(65535);\n\tvar category = new Array(65535);\n\tvar outputfDCTQuant = new Array(64);\n\tvar DU = new Array(64);\n\tvar byteout = [];\n\tvar bytenew = 0;\n\tvar bytepos = 7;\n\t\n\tvar YDU = new Array(64);\n\tvar UDU = new Array(64);\n\tvar VDU = new Array(64);\n\tvar clt = new Array(256);\n\tvar RGB_YUV_TABLE = new Array(2048);\n\tvar currentQuality;\n\t\n\tvar ZigZag = [\n\t\t\t 0, 1, 5, 6,14,15,27,28,\n\t\t\t 2, 4, 7,13,16,26,29,42,\n\t\t\t 3, 8,12,17,25,30,41,43,\n\t\t\t 9,11,18,24,31,40,44,53,\n\t\t\t10,19,23,32,39,45,52,54,\n\t\t\t20,22,33,38,46,51,55,60,\n\t\t\t21,34,37,47,50,56,59,61,\n\t\t\t35,36,48,49,57,58,62,63\n\t\t];\n\t\n\tvar std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];\n\tvar std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];\n\tvar std_ac_luminance_values = [\n\t\t\t0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,\n\t\t\t0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,\n\t\t\t0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,\n\t\t\t0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,\n\t\t\t0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,\n\t\t\t0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,\n\t\t\t0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,\n\t\t\t0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,\n\t\t\t0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,\n\t\t\t0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,\n\t\t\t0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,\n\t\t\t0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,\n\t\t\t0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,\n\t\t\t0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,\n\t\t\t0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,\n\t\t\t0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,\n\t\t\t0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,\n\t\t\t0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,\n\t\t\t0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,\n\t\t\t0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tvar std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];\n\tvar std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];\n\tvar std_ac_chrominance_values = [\n\t\t\t0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,\n\t\t\t0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,\n\t\t\t0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,\n\t\t\t0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,\n\t\t\t0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,\n\t\t\t0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,\n\t\t\t0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,\n\t\t\t0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,\n\t\t\t0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,\n\t\t\t0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,\n\t\t\t0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,\n\t\t\t0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,\n\t\t\t0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,\n\t\t\t0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,\n\t\t\t0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,\n\t\t\t0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,\n\t\t\t0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,\n\t\t\t0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,\n\t\t\t0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,\n\t\t\t0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tfunction initQuantTables(sf){\n\t\t\tvar YQT = [\n\t\t\t\t16, 11, 10, 16, 24, 40, 51, 61,\n\t\t\t\t12, 12, 14, 19, 26, 58, 60, 55,\n\t\t\t\t14, 13, 16, 24, 40, 57, 69, 56,\n\t\t\t\t14, 17, 22, 29, 51, 87, 80, 62,\n\t\t\t\t18, 22, 37, 56, 68,109,103, 77,\n\t\t\t\t24, 35, 55, 64, 81,104,113, 92,\n\t\t\t\t49, 64, 78, 87,103,121,120,101,\n\t\t\t\t72, 92, 95, 98,112,100,103, 99\n\t\t\t];\n\t\t\t\n\t\t\tfor (var i = 0; i < 64; i++) {\n\t\t\t\tvar t = ffloor((YQT[i]*sf+50)/100);\n\t\t\t\tif (t < 1) {\n\t\t\t\t\tt = 1;\n\t\t\t\t} else if (t > 255) {\n\t\t\t\t\tt = 255;\n\t\t\t\t}\n\t\t\t\tYTable[ZigZag[i]] = t;\n\t\t\t}\n\t\t\tvar UVQT = [\n\t\t\t\t17, 18, 24, 47, 99, 99, 99, 99,\n\t\t\t\t18, 21, 26, 66, 99, 99, 99, 99,\n\t\t\t\t24, 26, 56, 99, 99, 99, 99, 99,\n\t\t\t\t47, 66, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99\n\t\t\t];\n\t\t\tfor (var j = 0; j < 64; j++) {\n\t\t\t\tvar u = ffloor((UVQT[j]*sf+50)/100);\n\t\t\t\tif (u < 1) {\n\t\t\t\t\tu = 1;\n\t\t\t\t} else if (u > 255) {\n\t\t\t\t\tu = 255;\n\t\t\t\t}\n\t\t\t\tUVTable[ZigZag[j]] = u;\n\t\t\t}\n\t\t\tvar aasf = [\n\t\t\t\t1.0, 1.387039845, 1.306562965, 1.175875602,\n\t\t\t\t1.0, 0.785694958, 0.541196100, 0.275899379\n\t\t\t];\n\t\t\tvar k = 0;\n\t\t\tfor (var row = 0; row < 8; row++)\n\t\t\t{\n\t\t\t\tfor (var col = 0; col < 8; col++)\n\t\t\t\t{\n\t\t\t\t\tfdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tfdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction computeHuffmanTbl(nrcodes, std_table){\n\t\t\tvar codevalue = 0;\n\t\t\tvar pos_in_table = 0;\n\t\t\tvar HT = new Array();\n\t\t\tfor (var k = 1; k <= 16; k++) {\n\t\t\t\tfor (var j = 1; j <= nrcodes[k]; j++) {\n\t\t\t\t\tHT[std_table[pos_in_table]] = [];\n\t\t\t\t\tHT[std_table[pos_in_table]][0] = codevalue;\n\t\t\t\t\tHT[std_table[pos_in_table]][1] = k;\n\t\t\t\t\tpos_in_table++;\n\t\t\t\t\tcodevalue++;\n\t\t\t\t}\n\t\t\t\tcodevalue*=2;\n\t\t\t}\n\t\t\treturn HT;\n\t\t}\n\t\t\n\t\tfunction initHuffmanTbl()\n\t\t{\n\t\t\tYDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);\n\t\t\tUVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);\n\t\t\tYAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);\n\t\t\tUVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);\n\t\t}\n\t\n\t\tfunction initCategoryNumber()\n\t\t{\n\t\t\tvar nrlower = 1;\n\t\t\tvar nrupper = 2;\n\t\t\tfor (var cat = 1; cat <= 15; cat++) {\n\t\t\t\t//Positive numbers\n\t\t\t\tfor (var nr = nrlower; nr>0] \t= 38470 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+ 512)>>0] \t= 7471 * i + 0x8000;\n\t\t\t\tRGB_YUV_TABLE[(i+ 768)>>0] \t= -11059 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1024)>>0] \t= -21709 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1280)>>0] \t= 32768 * i + 0x807FFF;\n\t\t\t\tRGB_YUV_TABLE[(i+1536)>>0] \t= -27439 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1792)>>0] \t= - 5329 * i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// IO functions\n\t\tfunction writeBits(bs)\n\t\t{\n\t\t\tvar value = bs[0];\n\t\t\tvar posval = bs[1]-1;\n\t\t\twhile ( posval >= 0 ) {\n\t\t\t\tif (value & (1 << posval) ) {\n\t\t\t\t\tbytenew |= (1 << bytepos);\n\t\t\t\t}\n\t\t\t\tposval--;\n\t\t\t\tbytepos--;\n\t\t\t\tif (bytepos < 0) {\n\t\t\t\t\tif (bytenew == 0xFF) {\n\t\t\t\t\t\twriteByte(0xFF);\n\t\t\t\t\t\twriteByte(0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twriteByte(bytenew);\n\t\t\t\t\t}\n\t\t\t\t\tbytepos=7;\n\t\t\t\t\tbytenew=0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeByte(value)\n\t\t{\n\t\t\t//byteout.push(clt[value]); // write char directly instead of converting later\n byteout.push(value);\n\t\t}\n\t\n\t\tfunction writeWord(value)\n\t\t{\n\t\t\twriteByte((value>>8)&0xFF);\n\t\t\twriteByte((value )&0xFF);\n\t\t}\n\t\t\n\t\t// DCT & quantization core\n\t\tfunction fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}\n\t\t\n\t\tfunction writeAPP0()\n\t\t{\n\t\t\twriteWord(0xFFE0); // marker\n\t\t\twriteWord(16); // length\n\t\t\twriteByte(0x4A); // J\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0x49); // I\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0); // = \"JFIF\",'\\0'\n\t\t\twriteByte(1); // versionhi\n\t\t\twriteByte(1); // versionlo\n\t\t\twriteByte(0); // xyunits\n\t\t\twriteWord(1); // xdensity\n\t\t\twriteWord(1); // ydensity\n\t\t\twriteByte(0); // thumbnwidth\n\t\t\twriteByte(0); // thumbnheight\n\t\t}\n\n\t\tfunction writeAPP1(exifBuffer) {\n\t\t\tif (!exifBuffer) return;\n\n\t\t\twriteWord(0xFFE1); // APP1 marker\n\n\t\t\tif (exifBuffer[0] === 0x45 &&\n\t\t\t\t\texifBuffer[1] === 0x78 &&\n\t\t\t\t\texifBuffer[2] === 0x69 &&\n\t\t\t\t\texifBuffer[3] === 0x66) {\n\t\t\t\t// Buffer already starts with EXIF, just use it directly\n\t\t\t\twriteWord(exifBuffer.length + 2); // length is buffer + length itself!\n\t\t\t} else {\n\t\t\t\t// Buffer doesn't start with EXIF, write it for them\n\t\t\t\twriteWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\\0 + length itself!\n\t\t\t\twriteByte(0x45); // E\n\t\t\t\twriteByte(0x78); // X\n\t\t\t\twriteByte(0x69); // I\n\t\t\t\twriteByte(0x66); // F\n\t\t\t\twriteByte(0); // = \"EXIF\",'\\0'\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < exifBuffer.length; i++) {\n\t\t\t\twriteByte(exifBuffer[i]);\n\t\t\t}\n\t\t}\n\n\t\tfunction writeSOF0(width, height)\n\t\t{\n\t\t\twriteWord(0xFFC0); // marker\n\t\t\twriteWord(17); // length, truecolor YUV JPG\n\t\t\twriteByte(8); // precision\n\t\t\twriteWord(height);\n\t\t\twriteWord(width);\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0x11); // HVY\n\t\t\twriteByte(0); // QTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HVU\n\t\t\twriteByte(1); // QTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HVV\n\t\t\twriteByte(1); // QTV\n\t\t}\n\t\n\t\tfunction writeDQT()\n\t\t{\n\t\t\twriteWord(0xFFDB); // marker\n\t\t\twriteWord(132);\t // length\n\t\t\twriteByte(0);\n\t\t\tfor (var i=0; i<64; i++) {\n\t\t\t\twriteByte(YTable[i]);\n\t\t\t}\n\t\t\twriteByte(1);\n\t\t\tfor (var j=0; j<64; j++) {\n\t\t\t\twriteByte(UVTable[j]);\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeDHT()\n\t\t{\n\t\t\twriteWord(0xFFC4); // marker\n\t\t\twriteWord(0x01A2); // length\n\t\n\t\t\twriteByte(0); // HTYDCinfo\n\t\t\tfor (var i=0; i<16; i++) {\n\t\t\t\twriteByte(std_dc_luminance_nrcodes[i+1]);\n\t\t\t}\n\t\t\tfor (var j=0; j<=11; j++) {\n\t\t\t\twriteByte(std_dc_luminance_values[j]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x10); // HTYACinfo\n\t\t\tfor (var k=0; k<16; k++) {\n\t\t\t\twriteByte(std_ac_luminance_nrcodes[k+1]);\n\t\t\t}\n\t\t\tfor (var l=0; l<=161; l++) {\n\t\t\t\twriteByte(std_ac_luminance_values[l]);\n\t\t\t}\n\t\n\t\t\twriteByte(1); // HTUDCinfo\n\t\t\tfor (var m=0; m<16; m++) {\n\t\t\t\twriteByte(std_dc_chrominance_nrcodes[m+1]);\n\t\t\t}\n\t\t\tfor (var n=0; n<=11; n++) {\n\t\t\t\twriteByte(std_dc_chrominance_values[n]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x11); // HTUACinfo\n\t\t\tfor (var o=0; o<16; o++) {\n\t\t\t\twriteByte(std_ac_chrominance_nrcodes[o+1]);\n\t\t\t}\n\t\t\tfor (var p=0; p<=161; p++) {\n\t\t\t\twriteByte(std_ac_chrominance_values[p]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction writeCOM(comments)\n\t\t{\n\t\t\tif (typeof comments === \"undefined\" || comments.constructor !== Array) return;\n\t\t\tcomments.forEach(e => {\n\t\t\t\tif (typeof e !== \"string\") return;\n\t\t\t\twriteWord(0xFFFE); // marker\n\t\t\t\tvar l = e.length;\n\t\t\t\twriteWord(l + 2); // length itself as well\n\t\t\t\tvar i;\n\t\t\t\tfor (i = 0; i < l; i++)\n\t\t\t\t\twriteByte(e.charCodeAt(i));\n\t\t\t});\n\t\t}\n\t\n\t\tfunction writeSOS()\n\t\t{\n\t\t\twriteWord(0xFFDA); // marker\n\t\t\twriteWord(12); // length\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0); // HTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HTV\n\t\t\twriteByte(0); // Ss\n\t\t\twriteByte(0x3f); // Se\n\t\t\twriteByte(0); // Bf\n\t\t}\n\t\t\n\t\tfunction processDU(CDU, fdtbl, DC, HTDC, HTAC){\n\t\t\tvar EOB = HTAC[0x00];\n\t\t\tvar M16zeroes = HTAC[0xF0];\n\t\t\tvar pos;\n\t\t\tvar I16 = 16;\n\t\t\tvar I63 = 63;\n\t\t\tvar I64 = 64;\n\t\t\tvar DU_DCT = fDCTQuant(CDU, fdtbl);\n\t\t\t//ZigZag reorder\n\t\t\tfor (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};\n\t\t\t//end0pos = first element in reverse order !=0\n\t\t\tif ( end0pos == 0) {\n\t\t\t\twriteBits(EOB);\n\t\t\t\treturn DC;\n\t\t\t}\n\t\t\tvar i = 1;\n\t\t\tvar lng;\n\t\t\twhile ( i <= end0pos ) {\n\t\t\t\tvar startpos = i;\n\t\t\t\tfor (; (DU[i]==0) && (i<=end0pos); ++i) {}\n\t\t\t\tvar nrzeroes = i-startpos;\n\t\t\t\tif ( nrzeroes >= I16 ) {\n\t\t\t\t\tlng = nrzeroes>>4;\n\t\t\t\t\tfor (var nrmarker=1; nrmarker <= lng; ++nrmarker)\n\t\t\t\t\t\twriteBits(M16zeroes);\n\t\t\t\t\tnrzeroes = nrzeroes&0xF;\n\t\t\t\t}\n\t\t\t\tpos = 32767+DU[i];\n\t\t\t\twriteBits(HTAC[(nrzeroes<<4)+category[pos]]);\n\t\t\t\twriteBits(bitcode[pos]);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif ( end0pos != I63 ) {\n\t\t\t\twriteBits(EOB);\n\t\t\t}\n\t\t\treturn DC;\n\t\t}\n\n\t\tfunction initCharLookupTable(){\n\t\t\tvar sfcc = String.fromCharCode;\n\t\t\tfor(var i=0; i < 256; i++){ ///// ACHTUNG // 255\n\t\t\t\tclt[i] = sfcc(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.encode = function(image,quality) // image data object\n\t\t{\n\t\t\tvar time_start = new Date().getTime();\n\t\t\t\n\t\t\tif(quality) setQuality(quality);\n\t\t\t\n\t\t\t// Initialize bit writer\n\t\t\tbyteout = new Array();\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\n\t\t\t// Add JPEG headers\n\t\t\twriteWord(0xFFD8); // SOI\n\t\t\twriteAPP0();\n\t\t\twriteCOM(image.comments);\n\t\t\twriteAPP1(image.exifBuffer);\n\t\t\twriteDQT();\n\t\t\twriteSOF0(image.width,image.height);\n\t\t\twriteDHT();\n\t\t\twriteSOS();\n\n\t\n\t\t\t// Encode 8x8 macroblocks\n\t\t\tvar DCY=0;\n\t\t\tvar DCU=0;\n\t\t\tvar DCV=0;\n\t\t\t\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\t\t\n\t\t\t\n\t\t\tthis.encode.displayName = \"_encode_\";\n\n\t\t\tvar imageData = image.data;\n\t\t\tvar width = image.width;\n\t\t\tvar height = image.height;\n\n\t\t\tvar quadWidth = width*4;\n\t\t\tvar tripleWidth = width*3;\n\t\t\t\n\t\t\tvar x, y = 0;\n\t\t\tvar r, g, b;\n\t\t\tvar start,p, col,row,pos;\n\t\t\twhile(y < height){\n\t\t\t\tx = 0;\n\t\t\t\twhile(x < quadWidth){\n\t\t\t\tstart = quadWidth * y + x;\n\t\t\t\tp = start;\n\t\t\t\tcol = -1;\n\t\t\t\trow = 0;\n\t\t\t\t\n\t\t\t\tfor(pos=0; pos < 64; pos++){\n\t\t\t\t\trow = pos >> 3;// /8\n\t\t\t\t\tcol = ( pos & 7 ) * 4; // %8\n\t\t\t\t\tp = start + ( row * quadWidth ) + col;\t\t\n\t\t\t\t\t\n\t\t\t\t\tif(y+row >= height){ // padding bottom\n\t\t\t\t\t\tp-= (quadWidth*(y+1+row-height));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(x+col >= quadWidth){ // padding right\t\n\t\t\t\t\t\tp-= ((x+col) - quadWidth +4)\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tr = imageData[ p++ ];\n\t\t\t\t\tg = imageData[ p++ ];\n\t\t\t\t\tb = imageData[ p++ ];\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t/* // calculate YUV values dynamically\n\t\t\t\t\tYDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80\n\t\t\t\t\tUDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));\n\t\t\t\t\tVDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));\n\t\t\t\t\t*/\n\t\t\t\t\t\n\t\t\t\t\t// use lookup table (slightly faster)\n\t\t\t\t\tYDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;\n\t\t\t\t\tUDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;\n\t\t\t\t\tVDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n\t\t\t\tDCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n\t\t\t\tDCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n\t\t\t\tx+=32;\n\t\t\t\t}\n\t\t\t\ty+=8;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t////////////////////////////////////////////////////////////////\n\t\n\t\t\t// Do the bit alignment of the EOI marker\n\t\t\tif ( bytepos >= 0 ) {\n\t\t\t\tvar fillbits = [];\n\t\t\t\tfillbits[1] = bytepos+1;\n\t\t\t\tfillbits[0] = (1<<(bytepos+1))-1;\n\t\t\t\twriteBits(fillbits);\n\t\t\t}\n\t\n\t\t\twriteWord(0xFFD9); //EOI\n\n\t\t\tif (typeof module === 'undefined') return new Uint8Array(byteout);\n return Buffer.from(byteout);\n\n\t\t\tvar jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));\n\t\t\t\n\t\t\tbyteout = [];\n\t\t\t\n\t\t\t// benchmarking\n\t\t\tvar duration = new Date().getTime() - time_start;\n \t\t//console.log('Encoding time: '+ duration + 'ms');\n \t\t//\n\t\t\t\n\t\t\treturn jpegDataUri\t\t\t\n\t}\n\t\n\tfunction setQuality(quality){\n\t\tif (quality <= 0) {\n\t\t\tquality = 1;\n\t\t}\n\t\tif (quality > 100) {\n\t\t\tquality = 100;\n\t\t}\n\t\t\n\t\tif(currentQuality == quality) return // don't recalc if unchanged\n\t\t\n\t\tvar sf = 0;\n\t\tif (quality < 50) {\n\t\t\tsf = Math.floor(5000 / quality);\n\t\t} else {\n\t\t\tsf = Math.floor(200 - quality*2);\n\t\t}\n\t\t\n\t\tinitQuantTables(sf);\n\t\tcurrentQuality = quality;\n\t\t//console.log('Quality set to: '+quality +'%');\n\t}\n\t\n\tfunction init(){\n\t\tvar time_start = new Date().getTime();\n\t\tif(!quality) quality = 50;\n\t\t// Create tables\n\t\tinitCharLookupTable()\n\t\tinitHuffmanTbl();\n\t\tinitCategoryNumber();\n\t\tinitRGBYUVTable();\n\t\t\n\t\tsetQuality(quality);\n\t\tvar duration = new Date().getTime() - time_start;\n \t//console.log('Initialization '+ duration + 'ms');\n\t}\n\t\n\tinit();\n\t\n};\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = encode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].encode = encode;\n}\n\nfunction encode(imgData, qu) {\n if (typeof qu === 'undefined') qu = 50;\n var encoder = new JPEGEncoder(qu);\n\tvar data = encoder.encode(imgData, qu);\n return {\n data: data,\n width: imgData.width,\n height: imgData.height,\n };\n}\n\n// helper function to get the imageData of an existing image on the current page.\nfunction getImageDataFromImage(idOrElement){\n\tvar theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;\n\tvar cvs = document.createElement('canvas');\n\tcvs.width = theImg.width;\n\tcvs.height = theImg.height;\n\tvar ctx = cvs.getContext(\"2d\");\n\tctx.drawImage(theImg,0,0);\n\t\n\treturn (ctx.getImageData(0, 0, cvs.width, cvs.height));\n}\n","/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\n/*\n Copyright 2011 notmasteryet\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// - The JPEG specification can be found in the ITU CCITT Recommendation T.81\n// (www.w3.org/Graphics/JPEG/itu-t81.pdf)\n// - The JFIF specification can be found in the JPEG File Interchange Format\n// (www.w3.org/Graphics/JPEG/jfif3.pdf)\n// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters\n// in PostScript Level 2, Technical Note #5116\n// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)\n\nvar JpegImage = (function jpegImage() {\n \"use strict\";\n var dctZigZag = new Int32Array([\n 0,\n 1, 8,\n 16, 9, 2,\n 3, 10, 17, 24,\n 32, 25, 18, 11, 4,\n 5, 12, 19, 26, 33, 40,\n 48, 41, 34, 27, 20, 13, 6,\n 7, 14, 21, 28, 35, 42, 49, 56,\n 57, 50, 43, 36, 29, 22, 15,\n 23, 30, 37, 44, 51, 58,\n 59, 52, 45, 38, 31,\n 39, 46, 53, 60,\n 61, 54, 47,\n 55, 62,\n 63\n ]);\n\n var dctCos1 = 4017 // cos(pi/16)\n var dctSin1 = 799 // sin(pi/16)\n var dctCos3 = 3406 // cos(3*pi/16)\n var dctSin3 = 2276 // sin(3*pi/16)\n var dctCos6 = 1567 // cos(6*pi/16)\n var dctSin6 = 3784 // sin(6*pi/16)\n var dctSqrt2 = 5793 // sqrt(2)\n var dctSqrt1d2 = 2896 // sqrt(2) / 2\n\n function constructor() {\n }\n\n function buildHuffmanTable(codeLengths, values) {\n var k = 0, code = [], i, j, length = 16;\n while (length > 0 && !codeLengths[length - 1])\n length--;\n code.push({children: [], index: 0});\n var p = code[0], q;\n for (i = 0; i < length; i++) {\n for (j = 0; j < codeLengths[i]; j++) {\n p = code.pop();\n p.children[p.index] = values[k];\n while (p.index > 0) {\n if (code.length === 0)\n throw new Error('Could not recreate Huffman Table');\n p = code.pop();\n }\n p.index++;\n code.push(p);\n while (code.length <= i) {\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n k++;\n }\n if (i + 1 < length) {\n // p here points to last code\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n }\n return code[0].children;\n }\n\n function decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successivePrev, successive, opts) {\n var precision = frame.precision;\n var samplesPerLine = frame.samplesPerLine;\n var scanLines = frame.scanLines;\n var mcusPerLine = frame.mcusPerLine;\n var progressive = frame.progressive;\n var maxH = frame.maxH, maxV = frame.maxV;\n\n var startOffset = offset, bitsData = 0, bitsCount = 0;\n function readBit() {\n if (bitsCount > 0) {\n bitsCount--;\n return (bitsData >> bitsCount) & 1;\n }\n bitsData = data[offset++];\n if (bitsData == 0xFF) {\n var nextByte = data[offset++];\n if (nextByte) {\n throw new Error(\"unexpected marker: \" + ((bitsData << 8) | nextByte).toString(16));\n }\n // unstuff 0\n }\n bitsCount = 7;\n return bitsData >>> 7;\n }\n function decodeHuffman(tree) {\n var node = tree, bit;\n while ((bit = readBit()) !== null) {\n node = node[bit];\n if (typeof node === 'number')\n return node;\n if (typeof node !== 'object')\n throw new Error(\"invalid huffman sequence\");\n }\n return null;\n }\n function receive(length) {\n var n = 0;\n while (length > 0) {\n var bit = readBit();\n if (bit === null) return;\n n = (n << 1) | bit;\n length--;\n }\n return n;\n }\n function receiveAndExtend(length) {\n var n = receive(length);\n if (n >= 1 << (length - 1))\n return n;\n return n + (-1 << length) + 1;\n }\n function decodeBaseline(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : receiveAndExtend(t);\n zz[0]= (component.pred += diff);\n var k = 1;\n while (k < 64) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15)\n break;\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s);\n k++;\n }\n }\n function decodeDCFirst(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);\n zz[0] = (component.pred += diff);\n }\n function decodeDCSuccessive(component, zz) {\n zz[0] |= readBit() << successive;\n }\n var eobrun = 0;\n function decodeACFirst(component, zz) {\n if (eobrun > 0) {\n eobrun--;\n return;\n }\n var k = spectralStart, e = spectralEnd;\n while (k <= e) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r) - 1;\n break;\n }\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s) * (1 << successive);\n k++;\n }\n }\n var successiveACState = 0, successiveACNextValue;\n function decodeACSuccessive(component, zz) {\n var k = spectralStart, e = spectralEnd, r = 0;\n while (k <= e) {\n var z = dctZigZag[k];\n var direction = zz[z] < 0 ? -1 : 1;\n switch (successiveACState) {\n case 0: // initial state\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r);\n successiveACState = 4;\n } else {\n r = 16;\n successiveACState = 1;\n }\n } else {\n if (s !== 1)\n throw new Error(\"invalid ACn encoding\");\n successiveACNextValue = receiveAndExtend(s);\n successiveACState = r ? 2 : 3;\n }\n continue;\n case 1: // skipping r zero items\n case 2:\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n r--;\n if (r === 0)\n successiveACState = successiveACState == 2 ? 3 : 0;\n }\n break;\n case 3: // set value for a zero item\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n zz[z] = successiveACNextValue << successive;\n successiveACState = 0;\n }\n break;\n case 4: // eob\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n break;\n }\n k++;\n }\n if (successiveACState === 4) {\n eobrun--;\n if (eobrun === 0)\n successiveACState = 0;\n }\n }\n function decodeMcu(component, decode, mcu, row, col) {\n var mcuRow = (mcu / mcusPerLine) | 0;\n var mcuCol = mcu % mcusPerLine;\n var blockRow = mcuRow * component.v + row;\n var blockCol = mcuCol * component.h + col;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n function decodeBlock(component, decode, mcu) {\n var blockRow = (mcu / component.blocksPerLine) | 0;\n var blockCol = mcu % component.blocksPerLine;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n\n var componentsLength = components.length;\n var component, i, j, k, n;\n var decodeFn;\n if (progressive) {\n if (spectralStart === 0)\n decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;\n else\n decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;\n } else {\n decodeFn = decodeBaseline;\n }\n\n var mcu = 0, marker;\n var mcuExpected;\n if (componentsLength == 1) {\n mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;\n } else {\n mcuExpected = mcusPerLine * frame.mcusPerColumn;\n }\n if (!resetInterval) resetInterval = mcuExpected;\n\n var h, v;\n while (mcu < mcuExpected) {\n // reset interval stuff\n for (i = 0; i < componentsLength; i++)\n components[i].pred = 0;\n eobrun = 0;\n\n if (componentsLength == 1) {\n component = components[0];\n for (n = 0; n < resetInterval; n++) {\n decodeBlock(component, decodeFn, mcu);\n mcu++;\n }\n } else {\n for (n = 0; n < resetInterval; n++) {\n for (i = 0; i < componentsLength; i++) {\n component = components[i];\n h = component.h;\n v = component.v;\n for (j = 0; j < v; j++) {\n for (k = 0; k < h; k++) {\n decodeMcu(component, decodeFn, mcu, j, k);\n }\n }\n }\n mcu++;\n\n // If we've reached our expected MCU's, stop decoding\n if (mcu === mcuExpected) break;\n }\n }\n\n if (mcu === mcuExpected) {\n // Skip trailing bytes at the end of the scan - until we reach the next marker\n do {\n if (data[offset] === 0xFF) {\n if (data[offset + 1] !== 0x00) {\n break;\n }\n }\n offset += 1;\n } while (offset < data.length - 2);\n }\n\n // find marker\n bitsCount = 0;\n marker = (data[offset] << 8) | data[offset + 1];\n if (marker < 0xFF00) {\n throw new Error(\"marker was not found\");\n }\n\n if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx\n offset += 2;\n }\n else\n break;\n }\n\n return offset - startOffset;\n }\n\n function buildComponentData(frame, component) {\n var lines = [];\n var blocksPerLine = component.blocksPerLine;\n var blocksPerColumn = component.blocksPerColumn;\n var samplesPerLine = blocksPerLine << 3;\n // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.\n var R = new Int32Array(64), r = new Uint8Array(64);\n\n // A port of poppler's IDCT method which in turn is taken from:\n // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,\n // \"Practical Fast 1-D DCT Algorithms with 11 Multiplications\",\n // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,\n // 988-991.\n function quantizeAndInverse(zz, dataOut, dataIn) {\n var qt = component.quantizationTable;\n var v0, v1, v2, v3, v4, v5, v6, v7, t;\n var p = dataIn;\n var i;\n\n // dequant\n for (i = 0; i < 64; i++)\n p[i] = zz[i] * qt[i];\n\n // inverse DCT on rows\n for (i = 0; i < 8; ++i) {\n var row = 8 * i;\n\n // check for all-zero AC coefficients\n if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&\n p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&\n p[7 + row] == 0) {\n t = (dctSqrt2 * p[0 + row] + 512) >> 10;\n p[0 + row] = t;\n p[1 + row] = t;\n p[2 + row] = t;\n p[3 + row] = t;\n p[4 + row] = t;\n p[5 + row] = t;\n p[6 + row] = t;\n p[7 + row] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;\n v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;\n v2 = p[2 + row];\n v3 = p[6 + row];\n v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;\n v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;\n v5 = p[3 + row] << 4;\n v6 = p[5 + row] << 4;\n\n // stage 3\n t = (v0 - v1+ 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0 + row] = v0 + v7;\n p[7 + row] = v0 - v7;\n p[1 + row] = v1 + v6;\n p[6 + row] = v1 - v6;\n p[2 + row] = v2 + v5;\n p[5 + row] = v2 - v5;\n p[3 + row] = v3 + v4;\n p[4 + row] = v3 - v4;\n }\n\n // inverse DCT on columns\n for (i = 0; i < 8; ++i) {\n var col = i;\n\n // check for all-zero AC coefficients\n if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&\n p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&\n p[7*8 + col] == 0) {\n t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;\n p[0*8 + col] = t;\n p[1*8 + col] = t;\n p[2*8 + col] = t;\n p[3*8 + col] = t;\n p[4*8 + col] = t;\n p[5*8 + col] = t;\n p[6*8 + col] = t;\n p[7*8 + col] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;\n v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;\n v2 = p[2*8 + col];\n v3 = p[6*8 + col];\n v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;\n v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;\n v5 = p[3*8 + col];\n v6 = p[5*8 + col];\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0*8 + col] = v0 + v7;\n p[7*8 + col] = v0 - v7;\n p[1*8 + col] = v1 + v6;\n p[6*8 + col] = v1 - v6;\n p[2*8 + col] = v2 + v5;\n p[5*8 + col] = v2 - v5;\n p[3*8 + col] = v3 + v4;\n p[4*8 + col] = v3 - v4;\n }\n\n // convert to 8-bit integers\n for (i = 0; i < 64; ++i) {\n var sample = 128 + ((p[i] + 8) >> 4);\n dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;\n }\n }\n\n requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);\n\n var i, j;\n for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {\n var scanLine = blockRow << 3;\n for (i = 0; i < 8; i++)\n lines.push(new Uint8Array(samplesPerLine));\n for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {\n quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);\n\n var offset = 0, sample = blockCol << 3;\n for (j = 0; j < 8; j++) {\n var line = lines[scanLine + j];\n for (i = 0; i < 8; i++)\n line[sample + i] = r[offset++];\n }\n }\n }\n return lines;\n }\n\n function clampTo8bit(a) {\n return a < 0 ? 0 : a > 255 ? 255 : a;\n }\n\n constructor.prototype = {\n load: function load(path) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", path, true);\n xhr.responseType = \"arraybuffer\";\n xhr.onload = (function() {\n // TODO catch parse error\n var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);\n this.parse(data);\n if (this.onload)\n this.onload();\n }).bind(this);\n xhr.send(null);\n },\n parse: function parse(data) {\n var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;\n var offset = 0, length = data.length;\n function readUint16() {\n var value = (data[offset] << 8) | data[offset + 1];\n offset += 2;\n return value;\n }\n function readDataBlock() {\n var length = readUint16();\n var array = data.subarray(offset, offset + length - 2);\n offset += array.length;\n return array;\n }\n function prepareComponents(frame) {\n // According to the JPEG standard, the sampling factor must be between 1 and 4\n // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146\n var maxH = 1, maxV = 1;\n var component, componentId;\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n if (maxH < component.h) maxH = component.h;\n if (maxV < component.v) maxV = component.v;\n }\n }\n var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);\n var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);\n var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);\n var blocksPerLineForMcu = mcusPerLine * component.h;\n var blocksPerColumnForMcu = mcusPerColumn * component.v;\n var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;\n var blocks = [];\n\n // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)\n requestMemoryAllocation(blocksToAllocate * 256);\n\n for (var i = 0; i < blocksPerColumnForMcu; i++) {\n var row = [];\n for (var j = 0; j < blocksPerLineForMcu; j++)\n row.push(new Int32Array(64));\n blocks.push(row);\n }\n component.blocksPerLine = blocksPerLine;\n component.blocksPerColumn = blocksPerColumn;\n component.blocks = blocks;\n }\n }\n frame.maxH = maxH;\n frame.maxV = maxV;\n frame.mcusPerLine = mcusPerLine;\n frame.mcusPerColumn = mcusPerColumn;\n }\n var jfif = null;\n var adobe = null;\n var pixels = null;\n var frame, resetInterval;\n var quantizationTables = [], frames = [];\n var huffmanTablesAC = [], huffmanTablesDC = [];\n var fileMarker = readUint16();\n var malformedDataOffset = -1;\n this.comments = [];\n if (fileMarker != 0xFFD8) { // SOI (Start of Image)\n throw new Error(\"SOI not found\");\n }\n\n fileMarker = readUint16();\n while (fileMarker != 0xFFD9) { // EOI (End of image)\n var i, j, l;\n switch(fileMarker) {\n case 0xFF00: break;\n case 0xFFE0: // APP0 (Application Specific)\n case 0xFFE1: // APP1\n case 0xFFE2: // APP2\n case 0xFFE3: // APP3\n case 0xFFE4: // APP4\n case 0xFFE5: // APP5\n case 0xFFE6: // APP6\n case 0xFFE7: // APP7\n case 0xFFE8: // APP8\n case 0xFFE9: // APP9\n case 0xFFEA: // APP10\n case 0xFFEB: // APP11\n case 0xFFEC: // APP12\n case 0xFFED: // APP13\n case 0xFFEE: // APP14\n case 0xFFEF: // APP15\n case 0xFFFE: // COM (Comment)\n var appData = readDataBlock();\n\n if (fileMarker === 0xFFFE) {\n var comment = String.fromCharCode.apply(null, appData);\n this.comments.push(comment);\n }\n\n if (fileMarker === 0xFFE0) {\n if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&\n appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\\x00'\n jfif = {\n version: { major: appData[5], minor: appData[6] },\n densityUnits: appData[7],\n xDensity: (appData[8] << 8) | appData[9],\n yDensity: (appData[10] << 8) | appData[11],\n thumbWidth: appData[12],\n thumbHeight: appData[13],\n thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])\n };\n }\n }\n // TODO APP1 - Exif\n if (fileMarker === 0xFFE1) {\n if (appData[0] === 0x45 &&\n appData[1] === 0x78 &&\n appData[2] === 0x69 &&\n appData[3] === 0x66 &&\n appData[4] === 0) { // 'EXIF\\x00'\n this.exifBuffer = appData.subarray(5, appData.length);\n }\n }\n\n if (fileMarker === 0xFFEE) {\n if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&\n appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\\x00'\n adobe = {\n version: appData[6],\n flags0: (appData[7] << 8) | appData[8],\n flags1: (appData[9] << 8) | appData[10],\n transformCode: appData[11]\n };\n }\n }\n break;\n\n case 0xFFDB: // DQT (Define Quantization Tables)\n var quantizationTablesLength = readUint16();\n var quantizationTablesEnd = quantizationTablesLength + offset - 2;\n while (offset < quantizationTablesEnd) {\n var quantizationTableSpec = data[offset++];\n requestMemoryAllocation(64 * 4);\n var tableData = new Int32Array(64);\n if ((quantizationTableSpec >> 4) === 0) { // 8 bit values\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = data[offset++];\n }\n } else if ((quantizationTableSpec >> 4) === 1) { //16 bit\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = readUint16();\n }\n } else\n throw new Error(\"DQT: invalid table spec\");\n quantizationTables[quantizationTableSpec & 15] = tableData;\n }\n break;\n\n case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)\n case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)\n case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)\n readUint16(); // skip data length\n frame = {};\n frame.extended = (fileMarker === 0xFFC1);\n frame.progressive = (fileMarker === 0xFFC2);\n frame.precision = data[offset++];\n frame.scanLines = readUint16();\n frame.samplesPerLine = readUint16();\n frame.components = {};\n frame.componentsOrder = [];\n\n var pixelsInFrame = frame.scanLines * frame.samplesPerLine;\n if (pixelsInFrame > maxResolutionInPixels) {\n var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);\n throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);\n }\n\n var componentsCount = data[offset++], componentId;\n var maxH = 0, maxV = 0;\n for (i = 0; i < componentsCount; i++) {\n componentId = data[offset];\n var h = data[offset + 1] >> 4;\n var v = data[offset + 1] & 15;\n var qId = data[offset + 2];\n\n if ( h <= 0 || v <= 0 ) {\n throw new Error('Invalid sampling factor, expected values above 0');\n }\n\n frame.componentsOrder.push(componentId);\n frame.components[componentId] = {\n h: h,\n v: v,\n quantizationIdx: qId\n };\n offset += 3;\n }\n prepareComponents(frame);\n frames.push(frame);\n break;\n\n case 0xFFC4: // DHT (Define Huffman Tables)\n var huffmanLength = readUint16();\n for (i = 2; i < huffmanLength;) {\n var huffmanTableSpec = data[offset++];\n var codeLengths = new Uint8Array(16);\n var codeLengthSum = 0;\n for (j = 0; j < 16; j++, offset++) {\n codeLengthSum += (codeLengths[j] = data[offset]);\n }\n requestMemoryAllocation(16 + codeLengthSum);\n var huffmanValues = new Uint8Array(codeLengthSum);\n for (j = 0; j < codeLengthSum; j++, offset++)\n huffmanValues[j] = data[offset];\n i += 17 + codeLengthSum;\n\n ((huffmanTableSpec >> 4) === 0 ?\n huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =\n buildHuffmanTable(codeLengths, huffmanValues);\n }\n break;\n\n case 0xFFDD: // DRI (Define Restart Interval)\n readUint16(); // skip data length\n resetInterval = readUint16();\n break;\n\n case 0xFFDC: // Number of Lines marker\n readUint16() // skip data length\n readUint16() // Ignore this data since it represents the image height\n break;\n \n case 0xFFDA: // SOS (Start of Scan)\n var scanLength = readUint16();\n var selectorsCount = data[offset++];\n var components = [], component;\n for (i = 0; i < selectorsCount; i++) {\n component = frame.components[data[offset++]];\n var tableSpec = data[offset++];\n component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];\n component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];\n components.push(component);\n }\n var spectralStart = data[offset++];\n var spectralEnd = data[offset++];\n var successiveApproximation = data[offset++];\n var processed = decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successiveApproximation >> 4, successiveApproximation & 15, this.opts);\n offset += processed;\n break;\n\n case 0xFFFF: // Fill bytes\n if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.\n offset--;\n }\n break;\n default:\n if (data[offset - 3] == 0xFF &&\n data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {\n // could be incorrect encoding -- last 0xFF byte of the previous\n // block was eaten by the encoder\n offset -= 3;\n break;\n }\n else if (fileMarker === 0xE0 || fileMarker == 0xE1) {\n // Recover from malformed APP1 markers popular in some phone models.\n // See https://github.com/eugeneware/jpeg-js/issues/82\n if (malformedDataOffset !== -1) {\n throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);\n }\n malformedDataOffset = offset - 1;\n const nextOffset = readUint16();\n if (data[offset + nextOffset - 2] === 0xFF) {\n offset += nextOffset - 2;\n break;\n }\n }\n throw new Error(\"unknown JPEG marker \" + fileMarker.toString(16));\n }\n fileMarker = readUint16();\n }\n if (frames.length != 1)\n throw new Error(\"only single frame JPEGs supported\");\n\n // set each frame's components quantization table\n for (var i = 0; i < frames.length; i++) {\n var cp = frames[i].components;\n for (var j in cp) {\n cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];\n delete cp[j].quantizationIdx;\n }\n }\n\n this.width = frame.samplesPerLine;\n this.height = frame.scanLines;\n this.jfif = jfif;\n this.adobe = adobe;\n this.components = [];\n for (var i = 0; i < frame.componentsOrder.length; i++) {\n var component = frame.components[frame.componentsOrder[i]];\n this.components.push({\n lines: buildComponentData(frame, component),\n scaleX: component.h / frame.maxH,\n scaleY: component.v / frame.maxV\n });\n }\n },\n getData: function getData(width, height) {\n var scaleX = this.width / width, scaleY = this.height / height;\n\n var component1, component2, component3, component4;\n var component1Line, component2Line, component3Line, component4Line;\n var x, y;\n var offset = 0;\n var Y, Cb, Cr, K, C, M, Ye, R, G, B;\n var colorTransform;\n var dataLength = width * height * this.components.length;\n requestMemoryAllocation(dataLength);\n var data = new Uint8Array(dataLength);\n switch (this.components.length) {\n case 1:\n component1 = this.components[0];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n\n data[offset++] = Y;\n }\n }\n break;\n case 2:\n // PDF might compress two component data in custom colorspace\n component1 = this.components[0];\n component2 = this.components[1];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n data[offset++] = Y;\n Y = component2Line[0 | (x * component2.scaleX * scaleX)];\n data[offset++] = Y;\n }\n }\n break;\n case 3:\n // The default transform for three components is true\n colorTransform = true;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n R = component1Line[0 | (x * component1.scaleX * scaleX)];\n G = component2Line[0 | (x * component2.scaleX * scaleX)];\n B = component3Line[0 | (x * component3.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n\n R = clampTo8bit(Y + 1.402 * (Cr - 128));\n G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n B = clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n\n data[offset++] = R;\n data[offset++] = G;\n data[offset++] = B;\n }\n }\n break;\n case 4:\n if (!this.adobe)\n throw new Error('Unsupported color mode (4 components)');\n // The default transform for four components is false\n colorTransform = false;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n component4 = this.components[3];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n C = component1Line[0 | (x * component1.scaleX * scaleX)];\n M = component2Line[0 | (x * component2.scaleX * scaleX)];\n Ye = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n\n C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));\n M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n data[offset++] = 255-C;\n data[offset++] = 255-M;\n data[offset++] = 255-Ye;\n data[offset++] = 255-K;\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n return data;\n },\n copyToImageData: function copyToImageData(imageData, formatAsRGBA) {\n var width = imageData.width, height = imageData.height;\n var imageDataArray = imageData.data;\n var data = this.getData(width, height);\n var i = 0, j = 0, x, y;\n var Y, K, C, M, R, G, B;\n switch (this.components.length) {\n case 1:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n Y = data[i++];\n\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 3:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n R = data[i++];\n G = data[i++];\n B = data[i++];\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 4:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n C = data[i++];\n M = data[i++];\n Y = data[i++];\n K = data[i++];\n\n R = 255 - clampTo8bit(C * (1 - K / 255) + K);\n G = 255 - clampTo8bit(M * (1 - K / 255) + K);\n B = 255 - clampTo8bit(Y * (1 - K / 255) + K);\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n }\n };\n\n\n // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.\n var totalBytesAllocated = 0;\n var maxMemoryUsageBytes = 0;\n function requestMemoryAllocation(increaseAmount = 0) {\n var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;\n if (totalMemoryImpactBytes > maxMemoryUsageBytes) {\n var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);\n throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);\n }\n\n totalBytesAllocated = totalMemoryImpactBytes;\n }\n\n constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {\n totalBytesAllocated = 0;\n maxMemoryUsageBytes = maxMemoryUsageBytes_;\n };\n\n constructor.getBytesAllocated = function () {\n return totalBytesAllocated;\n };\n\n constructor.requestMemoryAllocation = requestMemoryAllocation;\n\n return constructor;\n})();\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = decode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].decode = decode;\n}\n\nfunction decode(jpegData, userOpts = {}) {\n var defaultOpts = {\n // \"undefined\" means \"Choose whether to transform colors based on the image’s color model.\"\n colorTransform: undefined,\n useTArray: false,\n formatAsRGBA: true,\n tolerantDecoding: true,\n maxResolutionInMP: 100, // Don't decode more than 100 megapixels\n maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB\n };\n\n var opts = {...defaultOpts, ...userOpts};\n var arr = new Uint8Array(jpegData);\n var decoder = new JpegImage();\n decoder.opts = opts;\n // If this constructor ever supports async decoding this will need to be done differently.\n // Until then, treating as singleton limit is fine.\n JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);\n decoder.parse(arr);\n\n var channels = (opts.formatAsRGBA) ? 4 : 3;\n var bytesNeeded = decoder.width * decoder.height * channels;\n try {\n JpegImage.requestMemoryAllocation(bytesNeeded);\n var image = {\n width: decoder.width,\n height: decoder.height,\n exifBuffer: decoder.exifBuffer,\n data: opts.useTArray ?\n new Uint8Array(bytesNeeded) :\n Buffer.alloc(bytesNeeded)\n };\n if(decoder.comments.length > 0) {\n image[\"comments\"] = decoder.comments;\n }\n } catch (err) {\n if (err instanceof RangeError) {\n throw new Error(\"Could not allocate enough memory for the image. \" +\n \"Required: \" + bytesNeeded);\n } \n \n if (err instanceof ReferenceError) {\n if (err.message === \"Buffer is not defined\") {\n throw new Error(\"Buffer is not globally defined in this environment. \" +\n \"Consider setting useTArray to true\");\n }\n }\n throw err;\n }\n\n decoder.copyToImageData(image, opts.formatAsRGBA);\n\n return image;\n}\n","var encode = require('./lib/encoder'),\n decode = require('./lib/decoder');\n\nmodule.exports = {\n encode: encode,\n decode: decode\n};\n","\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\n\nlet ChunkStream = (module.exports = function () {\n Stream.call(this);\n\n this._buffers = [];\n this._buffered = 0;\n\n this._reads = [];\n this._paused = false;\n\n this._encoding = \"utf8\";\n this.writable = true;\n});\nutil.inherits(ChunkStream, Stream);\n\nChunkStream.prototype.read = function (length, callback) {\n this._reads.push({\n length: Math.abs(length), // if length < 0 then at most this length\n allowLess: length < 0,\n func: callback,\n });\n\n process.nextTick(\n function () {\n this._process();\n\n // its paused and there is not enought data then ask for more\n if (this._paused && this._reads && this._reads.length > 0) {\n this._paused = false;\n\n this.emit(\"drain\");\n }\n }.bind(this)\n );\n};\n\nChunkStream.prototype.write = function (data, encoding) {\n if (!this.writable) {\n this.emit(\"error\", new Error(\"Stream not writable\"));\n return false;\n }\n\n let dataBuffer;\n if (Buffer.isBuffer(data)) {\n dataBuffer = data;\n } else {\n dataBuffer = Buffer.from(data, encoding || this._encoding);\n }\n\n this._buffers.push(dataBuffer);\n this._buffered += dataBuffer.length;\n\n this._process();\n\n // ok if there are no more read requests\n if (this._reads && this._reads.length === 0) {\n this._paused = true;\n }\n\n return this.writable && !this._paused;\n};\n\nChunkStream.prototype.end = function (data, encoding) {\n if (data) {\n this.write(data, encoding);\n }\n\n this.writable = false;\n\n // already destroyed\n if (!this._buffers) {\n return;\n }\n\n // enqueue or handle end\n if (this._buffers.length === 0) {\n this._end();\n } else {\n this._buffers.push(null);\n this._process();\n }\n};\n\nChunkStream.prototype.destroySoon = ChunkStream.prototype.end;\n\nChunkStream.prototype._end = function () {\n if (this._reads.length > 0) {\n this.emit(\"error\", new Error(\"Unexpected end of input\"));\n }\n\n this.destroy();\n};\n\nChunkStream.prototype.destroy = function () {\n if (!this._buffers) {\n return;\n }\n\n this.writable = false;\n this._reads = null;\n this._buffers = null;\n\n this.emit(\"close\");\n};\n\nChunkStream.prototype._processReadAllowingLess = function (read) {\n // ok there is any data so that we can satisfy this request\n this._reads.shift(); // == read\n\n // first we need to peek into first buffer\n let smallerBuf = this._buffers[0];\n\n // ok there is more data than we need\n if (smallerBuf.length > read.length) {\n this._buffered -= read.length;\n this._buffers[0] = smallerBuf.slice(read.length);\n\n read.func.call(this, smallerBuf.slice(0, read.length));\n } else {\n // ok this is less than maximum length so use it all\n this._buffered -= smallerBuf.length;\n this._buffers.shift(); // == smallerBuf\n\n read.func.call(this, smallerBuf);\n }\n};\n\nChunkStream.prototype._processRead = function (read) {\n this._reads.shift(); // == read\n\n let pos = 0;\n let count = 0;\n let data = Buffer.alloc(read.length);\n\n // create buffer for all data\n while (pos < read.length) {\n let buf = this._buffers[count++];\n let len = Math.min(buf.length, read.length - pos);\n\n buf.copy(data, pos, 0, len);\n pos += len;\n\n // last buffer wasn't used all so just slice it and leave\n if (len !== buf.length) {\n this._buffers[--count] = buf.slice(len);\n }\n }\n\n // remove all used buffers\n if (count > 0) {\n this._buffers.splice(0, count);\n }\n\n this._buffered -= read.length;\n\n read.func.call(this, data);\n};\n\nChunkStream.prototype._process = function () {\n try {\n // as long as there is any data and read requests\n while (this._buffered > 0 && this._reads && this._reads.length > 0) {\n let read = this._reads[0];\n\n // read any data (but no more than length)\n if (read.allowLess) {\n this._processReadAllowingLess(read);\n } else if (this._buffered >= read.length) {\n // ok we can meet some expectations\n\n this._processRead(read);\n } else {\n // not enought data to satisfy first request in queue\n // so we need to wait for more\n break;\n }\n }\n\n if (this._buffers && !this.writable) {\n this._end();\n }\n } catch (ex) {\n this.emit(\"error\", ex);\n }\n};\n","\"use strict\";\n\n// Adam 7\n// 0 1 2 3 4 5 6 7\n// 0 x 6 4 6 x 6 4 6\n// 1 7 7 7 7 7 7 7 7\n// 2 5 6 5 6 5 6 5 6\n// 3 7 7 7 7 7 7 7 7\n// 4 3 6 4 6 3 6 4 6\n// 5 7 7 7 7 7 7 7 7\n// 6 5 6 5 6 5 6 5 6\n// 7 7 7 7 7 7 7 7 7\n\nlet imagePasses = [\n {\n // pass 1 - 1px\n x: [0],\n y: [0],\n },\n {\n // pass 2 - 1px\n x: [4],\n y: [0],\n },\n {\n // pass 3 - 2px\n x: [0, 4],\n y: [4],\n },\n {\n // pass 4 - 4px\n x: [2, 6],\n y: [0, 4],\n },\n {\n // pass 5 - 8px\n x: [0, 2, 4, 6],\n y: [2, 6],\n },\n {\n // pass 6 - 16px\n x: [1, 3, 5, 7],\n y: [0, 2, 4, 6],\n },\n {\n // pass 7 - 32px\n x: [0, 1, 2, 3, 4, 5, 6, 7],\n y: [1, 3, 5, 7],\n },\n];\n\nexports.getImagePasses = function (width, height) {\n let images = [];\n let xLeftOver = width % 8;\n let yLeftOver = height % 8;\n let xRepeats = (width - xLeftOver) / 8;\n let yRepeats = (height - yLeftOver) / 8;\n for (let i = 0; i < imagePasses.length; i++) {\n let pass = imagePasses[i];\n let passWidth = xRepeats * pass.x.length;\n let passHeight = yRepeats * pass.y.length;\n for (let j = 0; j < pass.x.length; j++) {\n if (pass.x[j] < xLeftOver) {\n passWidth++;\n } else {\n break;\n }\n }\n for (let j = 0; j < pass.y.length; j++) {\n if (pass.y[j] < yLeftOver) {\n passHeight++;\n } else {\n break;\n }\n }\n if (passWidth > 0 && passHeight > 0) {\n images.push({ width: passWidth, height: passHeight, index: i });\n }\n }\n return images;\n};\n\nexports.getInterlaceIterator = function (width) {\n return function (x, y, pass) {\n let outerXLeftOver = x % imagePasses[pass].x.length;\n let outerX =\n ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 +\n imagePasses[pass].x[outerXLeftOver];\n let outerYLeftOver = y % imagePasses[pass].y.length;\n let outerY =\n ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 +\n imagePasses[pass].y[outerYLeftOver];\n return outerX * 4 + outerY * width * 4;\n };\n};\n","\"use strict\";\n\nmodule.exports = function paethPredictor(left, above, upLeft) {\n let paeth = left + above - upLeft;\n let pLeft = Math.abs(paeth - left);\n let pAbove = Math.abs(paeth - above);\n let pUpLeft = Math.abs(paeth - upLeft);\n\n if (pLeft <= pAbove && pLeft <= pUpLeft) {\n return left;\n }\n if (pAbove <= pUpLeft) {\n return above;\n }\n return upLeft;\n};\n","\"use strict\";\n\nlet interlaceUtils = require(\"./interlace\");\nlet paethPredictor = require(\"./paeth-predictor\");\n\nfunction getByteWidth(width, bpp, depth) {\n let byteWidth = width * bpp;\n if (depth !== 8) {\n byteWidth = Math.ceil(byteWidth / (8 / depth));\n }\n return byteWidth;\n}\n\nlet Filter = (module.exports = function (bitmapInfo, dependencies) {\n let width = bitmapInfo.width;\n let height = bitmapInfo.height;\n let interlace = bitmapInfo.interlace;\n let bpp = bitmapInfo.bpp;\n let depth = bitmapInfo.depth;\n\n this.read = dependencies.read;\n this.write = dependencies.write;\n this.complete = dependencies.complete;\n\n this._imageIndex = 0;\n this._images = [];\n if (interlace) {\n let passes = interlaceUtils.getImagePasses(width, height);\n for (let i = 0; i < passes.length; i++) {\n this._images.push({\n byteWidth: getByteWidth(passes[i].width, bpp, depth),\n height: passes[i].height,\n lineIndex: 0,\n });\n }\n } else {\n this._images.push({\n byteWidth: getByteWidth(width, bpp, depth),\n height: height,\n lineIndex: 0,\n });\n }\n\n // when filtering the line we look at the pixel to the left\n // the spec also says it is done on a byte level regardless of the number of pixels\n // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back\n // a pixel rather than just a different byte part. However if we are sub byte, we ignore.\n if (depth === 8) {\n this._xComparison = bpp;\n } else if (depth === 16) {\n this._xComparison = bpp * 2;\n } else {\n this._xComparison = 1;\n }\n});\n\nFilter.prototype.start = function () {\n this.read(\n this._images[this._imageIndex].byteWidth + 1,\n this._reverseFilterLine.bind(this)\n );\n};\n\nFilter.prototype._unFilterType1 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n unfilteredLine[x] = rawByte + f1Left;\n }\n};\n\nFilter.prototype._unFilterType2 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f2Up = lastLine ? lastLine[x] : 0;\n unfilteredLine[x] = rawByte + f2Up;\n }\n};\n\nFilter.prototype._unFilterType3 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f3Up = lastLine ? lastLine[x] : 0;\n let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n let f3Add = Math.floor((f3Left + f3Up) / 2);\n unfilteredLine[x] = rawByte + f3Add;\n }\n};\n\nFilter.prototype._unFilterType4 = function (\n rawData,\n unfilteredLine,\n byteWidth\n) {\n let xComparison = this._xComparison;\n let xBiggerThan = xComparison - 1;\n let lastLine = this._lastLine;\n\n for (let x = 0; x < byteWidth; x++) {\n let rawByte = rawData[1 + x];\n let f4Up = lastLine ? lastLine[x] : 0;\n let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;\n let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;\n let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);\n unfilteredLine[x] = rawByte + f4Add;\n }\n};\n\nFilter.prototype._reverseFilterLine = function (rawData) {\n let filter = rawData[0];\n let unfilteredLine;\n let currentImage = this._images[this._imageIndex];\n let byteWidth = currentImage.byteWidth;\n\n if (filter === 0) {\n unfilteredLine = rawData.slice(1, byteWidth + 1);\n } else {\n unfilteredLine = Buffer.alloc(byteWidth);\n\n switch (filter) {\n case 1:\n this._unFilterType1(rawData, unfilteredLine, byteWidth);\n break;\n case 2:\n this._unFilterType2(rawData, unfilteredLine, byteWidth);\n break;\n case 3:\n this._unFilterType3(rawData, unfilteredLine, byteWidth);\n break;\n case 4:\n this._unFilterType4(rawData, unfilteredLine, byteWidth);\n break;\n default:\n throw new Error(\"Unrecognised filter type - \" + filter);\n }\n }\n\n this.write(unfilteredLine);\n\n currentImage.lineIndex++;\n if (currentImage.lineIndex >= currentImage.height) {\n this._lastLine = null;\n this._imageIndex++;\n currentImage = this._images[this._imageIndex];\n } else {\n this._lastLine = unfilteredLine;\n }\n\n if (currentImage) {\n // read, using the byte width that may be from the new current image\n this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));\n } else {\n this._lastLine = null;\n this.complete();\n }\n};\n","\"use strict\";\n\nlet util = require(\"util\");\nlet ChunkStream = require(\"./chunkstream\");\nlet Filter = require(\"./filter-parse\");\n\nlet FilterAsync = (module.exports = function (bitmapInfo) {\n ChunkStream.call(this);\n\n let buffers = [];\n let that = this;\n this._filter = new Filter(bitmapInfo, {\n read: this.read.bind(this),\n write: function (buffer) {\n buffers.push(buffer);\n },\n complete: function () {\n that.emit(\"complete\", Buffer.concat(buffers));\n },\n });\n\n this._filter.start();\n});\nutil.inherits(FilterAsync, ChunkStream);\n","\"use strict\";\n\nmodule.exports = {\n PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],\n\n TYPE_IHDR: 0x49484452,\n TYPE_IEND: 0x49454e44,\n TYPE_IDAT: 0x49444154,\n TYPE_PLTE: 0x504c5445,\n TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase\n TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase\n\n // color-type bits\n COLORTYPE_GRAYSCALE: 0,\n COLORTYPE_PALETTE: 1,\n COLORTYPE_COLOR: 2,\n COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha\n\n // color-type combinations\n COLORTYPE_PALETTE_COLOR: 3,\n COLORTYPE_COLOR_ALPHA: 6,\n\n COLORTYPE_TO_BPP_MAP: {\n 0: 1,\n 2: 3,\n 3: 1,\n 4: 2,\n 6: 4,\n },\n\n GAMMA_DIVISION: 100000,\n};\n","\"use strict\";\n\nlet crcTable = [];\n\n(function () {\n for (let i = 0; i < 256; i++) {\n let currentCrc = i;\n for (let j = 0; j < 8; j++) {\n if (currentCrc & 1) {\n currentCrc = 0xedb88320 ^ (currentCrc >>> 1);\n } else {\n currentCrc = currentCrc >>> 1;\n }\n }\n crcTable[i] = currentCrc;\n }\n})();\n\nlet CrcCalculator = (module.exports = function () {\n this._crc = -1;\n});\n\nCrcCalculator.prototype.write = function (data) {\n for (let i = 0; i < data.length; i++) {\n this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);\n }\n return true;\n};\n\nCrcCalculator.prototype.crc32 = function () {\n return this._crc ^ -1;\n};\n\nCrcCalculator.crc32 = function (buf) {\n let crc = -1;\n for (let i = 0; i < buf.length; i++) {\n crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);\n }\n return crc ^ -1;\n};\n","\"use strict\";\n\nlet constants = require(\"./constants\");\nlet CrcCalculator = require(\"./crc\");\n\nlet Parser = (module.exports = function (options, dependencies) {\n this._options = options;\n options.checkCRC = options.checkCRC !== false;\n\n this._hasIHDR = false;\n this._hasIEND = false;\n this._emittedHeadersFinished = false;\n\n // input flags/metadata\n this._palette = [];\n this._colorType = 0;\n\n this._chunks = {};\n this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);\n this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);\n this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);\n this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);\n this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);\n this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);\n\n this.read = dependencies.read;\n this.error = dependencies.error;\n this.metadata = dependencies.metadata;\n this.gamma = dependencies.gamma;\n this.transColor = dependencies.transColor;\n this.palette = dependencies.palette;\n this.parsed = dependencies.parsed;\n this.inflateData = dependencies.inflateData;\n this.finished = dependencies.finished;\n this.simpleTransparency = dependencies.simpleTransparency;\n this.headersFinished = dependencies.headersFinished || function () {};\n});\n\nParser.prototype.start = function () {\n this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));\n};\n\nParser.prototype._parseSignature = function (data) {\n let signature = constants.PNG_SIGNATURE;\n\n for (let i = 0; i < signature.length; i++) {\n if (data[i] !== signature[i]) {\n this.error(new Error(\"Invalid file signature\"));\n return;\n }\n }\n this.read(8, this._parseChunkBegin.bind(this));\n};\n\nParser.prototype._parseChunkBegin = function (data) {\n // chunk content length\n let length = data.readUInt32BE(0);\n\n // chunk type\n let type = data.readUInt32BE(4);\n let name = \"\";\n for (let i = 4; i < 8; i++) {\n name += String.fromCharCode(data[i]);\n }\n\n //console.log('chunk ', name, length);\n\n // chunk flags\n let ancillary = Boolean(data[4] & 0x20); // or critical\n // priv = Boolean(data[5] & 0x20), // or public\n // safeToCopy = Boolean(data[7] & 0x20); // or unsafe\n\n if (!this._hasIHDR && type !== constants.TYPE_IHDR) {\n this.error(new Error(\"Expected IHDR on beggining\"));\n return;\n }\n\n this._crc = new CrcCalculator();\n this._crc.write(Buffer.from(name));\n\n if (this._chunks[type]) {\n return this._chunks[type](length);\n }\n\n if (!ancillary) {\n this.error(new Error(\"Unsupported critical chunk type \" + name));\n return;\n }\n\n this.read(length + 4, this._skipChunk.bind(this));\n};\n\nParser.prototype._skipChunk = function (/*data*/) {\n this.read(8, this._parseChunkBegin.bind(this));\n};\n\nParser.prototype._handleChunkEnd = function () {\n this.read(4, this._parseChunkEnd.bind(this));\n};\n\nParser.prototype._parseChunkEnd = function (data) {\n let fileCrc = data.readInt32BE(0);\n let calcCrc = this._crc.crc32();\n\n // check CRC\n if (this._options.checkCRC && calcCrc !== fileCrc) {\n this.error(new Error(\"Crc error - \" + fileCrc + \" - \" + calcCrc));\n return;\n }\n\n if (!this._hasIEND) {\n this.read(8, this._parseChunkBegin.bind(this));\n }\n};\n\nParser.prototype._handleIHDR = function (length) {\n this.read(length, this._parseIHDR.bind(this));\n};\nParser.prototype._parseIHDR = function (data) {\n this._crc.write(data);\n\n let width = data.readUInt32BE(0);\n let height = data.readUInt32BE(4);\n let depth = data[8];\n let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha\n let compr = data[10];\n let filter = data[11];\n let interlace = data[12];\n\n // console.log(' width', width, 'height', height,\n // 'depth', depth, 'colorType', colorType,\n // 'compr', compr, 'filter', filter, 'interlace', interlace\n // );\n\n if (\n depth !== 8 &&\n depth !== 4 &&\n depth !== 2 &&\n depth !== 1 &&\n depth !== 16\n ) {\n this.error(new Error(\"Unsupported bit depth \" + depth));\n return;\n }\n if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {\n this.error(new Error(\"Unsupported color type\"));\n return;\n }\n if (compr !== 0) {\n this.error(new Error(\"Unsupported compression method\"));\n return;\n }\n if (filter !== 0) {\n this.error(new Error(\"Unsupported filter method\"));\n return;\n }\n if (interlace !== 0 && interlace !== 1) {\n this.error(new Error(\"Unsupported interlace method\"));\n return;\n }\n\n this._colorType = colorType;\n\n let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];\n\n this._hasIHDR = true;\n\n this.metadata({\n width: width,\n height: height,\n depth: depth,\n interlace: Boolean(interlace),\n palette: Boolean(colorType & constants.COLORTYPE_PALETTE),\n color: Boolean(colorType & constants.COLORTYPE_COLOR),\n alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),\n bpp: bpp,\n colorType: colorType,\n });\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handlePLTE = function (length) {\n this.read(length, this._parsePLTE.bind(this));\n};\nParser.prototype._parsePLTE = function (data) {\n this._crc.write(data);\n\n let entries = Math.floor(data.length / 3);\n // console.log('Palette:', entries);\n\n for (let i = 0; i < entries; i++) {\n this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]);\n }\n\n this.palette(this._palette);\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleTRNS = function (length) {\n this.simpleTransparency();\n this.read(length, this._parseTRNS.bind(this));\n};\nParser.prototype._parseTRNS = function (data) {\n this._crc.write(data);\n\n // palette\n if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {\n if (this._palette.length === 0) {\n this.error(new Error(\"Transparency chunk must be after palette\"));\n return;\n }\n if (data.length > this._palette.length) {\n this.error(new Error(\"More transparent colors than palette size\"));\n return;\n }\n for (let i = 0; i < data.length; i++) {\n this._palette[i][3] = data[i];\n }\n this.palette(this._palette);\n }\n\n // for colorType 0 (grayscale) and 2 (rgb)\n // there might be one gray/color defined as transparent\n if (this._colorType === constants.COLORTYPE_GRAYSCALE) {\n // grey, 2 bytes\n this.transColor([data.readUInt16BE(0)]);\n }\n if (this._colorType === constants.COLORTYPE_COLOR) {\n this.transColor([\n data.readUInt16BE(0),\n data.readUInt16BE(2),\n data.readUInt16BE(4),\n ]);\n }\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleGAMA = function (length) {\n this.read(length, this._parseGAMA.bind(this));\n};\nParser.prototype._parseGAMA = function (data) {\n this._crc.write(data);\n this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);\n\n this._handleChunkEnd();\n};\n\nParser.prototype._handleIDAT = function (length) {\n if (!this._emittedHeadersFinished) {\n this._emittedHeadersFinished = true;\n this.headersFinished();\n }\n this.read(-length, this._parseIDAT.bind(this, length));\n};\nParser.prototype._parseIDAT = function (length, data) {\n this._crc.write(data);\n\n if (\n this._colorType === constants.COLORTYPE_PALETTE_COLOR &&\n this._palette.length === 0\n ) {\n throw new Error(\"Expected palette not found\");\n }\n\n this.inflateData(data);\n let leftOverLength = length - data.length;\n\n if (leftOverLength > 0) {\n this._handleIDAT(leftOverLength);\n } else {\n this._handleChunkEnd();\n }\n};\n\nParser.prototype._handleIEND = function (length) {\n this.read(length, this._parseIEND.bind(this));\n};\nParser.prototype._parseIEND = function (data) {\n this._crc.write(data);\n\n this._hasIEND = true;\n this._handleChunkEnd();\n\n if (this.finished) {\n this.finished();\n }\n};\n","\"use strict\";\n\nlet interlaceUtils = require(\"./interlace\");\n\nlet pixelBppMapper = [\n // 0 - dummy entry\n function () {},\n\n // 1 - L\n // 0: 0, 1: 0, 2: 0, 3: 0xff\n function (pxData, data, pxPos, rawPos) {\n if (rawPos === data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n let pixel = data[rawPos];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = 0xff;\n },\n\n // 2 - LA\n // 0: 0, 1: 0, 2: 0, 3: 1\n function (pxData, data, pxPos, rawPos) {\n if (rawPos + 1 >= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n let pixel = data[rawPos];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = data[rawPos + 1];\n },\n\n // 3 - RGB\n // 0: 0, 1: 1, 2: 2, 3: 0xff\n function (pxData, data, pxPos, rawPos) {\n if (rawPos + 2 >= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n pxData[pxPos] = data[rawPos];\n pxData[pxPos + 1] = data[rawPos + 1];\n pxData[pxPos + 2] = data[rawPos + 2];\n pxData[pxPos + 3] = 0xff;\n },\n\n // 4 - RGBA\n // 0: 0, 1: 1, 2: 2, 3: 3\n function (pxData, data, pxPos, rawPos) {\n if (rawPos + 3 >= data.length) {\n throw new Error(\"Ran out of data\");\n }\n\n pxData[pxPos] = data[rawPos];\n pxData[pxPos + 1] = data[rawPos + 1];\n pxData[pxPos + 2] = data[rawPos + 2];\n pxData[pxPos + 3] = data[rawPos + 3];\n },\n];\n\nlet pixelBppCustomMapper = [\n // 0 - dummy entry\n function () {},\n\n // 1 - L\n // 0: 0, 1: 0, 2: 0, 3: 0xff\n function (pxData, pixelData, pxPos, maxBit) {\n let pixel = pixelData[0];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = maxBit;\n },\n\n // 2 - LA\n // 0: 0, 1: 0, 2: 0, 3: 1\n function (pxData, pixelData, pxPos) {\n let pixel = pixelData[0];\n pxData[pxPos] = pixel;\n pxData[pxPos + 1] = pixel;\n pxData[pxPos + 2] = pixel;\n pxData[pxPos + 3] = pixelData[1];\n },\n\n // 3 - RGB\n // 0: 0, 1: 1, 2: 2, 3: 0xff\n function (pxData, pixelData, pxPos, maxBit) {\n pxData[pxPos] = pixelData[0];\n pxData[pxPos + 1] = pixelData[1];\n pxData[pxPos + 2] = pixelData[2];\n pxData[pxPos + 3] = maxBit;\n },\n\n // 4 - RGBA\n // 0: 0, 1: 1, 2: 2, 3: 3\n function (pxData, pixelData, pxPos) {\n pxData[pxPos] = pixelData[0];\n pxData[pxPos + 1] = pixelData[1];\n pxData[pxPos + 2] = pixelData[2];\n pxData[pxPos + 3] = pixelData[3];\n },\n];\n\nfunction bitRetriever(data, depth) {\n let leftOver = [];\n let i = 0;\n\n function split() {\n if (i === data.length) {\n throw new Error(\"Ran out of data\");\n }\n let byte = data[i];\n i++;\n let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;\n switch (depth) {\n default:\n throw new Error(\"unrecognised depth\");\n case 16:\n byte2 = data[i];\n i++;\n leftOver.push((byte << 8) + byte2);\n break;\n case 4:\n byte2 = byte & 0x0f;\n byte1 = byte >> 4;\n leftOver.push(byte1, byte2);\n break;\n case 2:\n byte4 = byte & 3;\n byte3 = (byte >> 2) & 3;\n byte2 = (byte >> 4) & 3;\n byte1 = (byte >> 6) & 3;\n leftOver.push(byte1, byte2, byte3, byte4);\n break;\n case 1:\n byte8 = byte & 1;\n byte7 = (byte >> 1) & 1;\n byte6 = (byte >> 2) & 1;\n byte5 = (byte >> 3) & 1;\n byte4 = (byte >> 4) & 1;\n byte3 = (byte >> 5) & 1;\n byte2 = (byte >> 6) & 1;\n byte1 = (byte >> 7) & 1;\n leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);\n break;\n }\n }\n\n return {\n get: function (count) {\n while (leftOver.length < count) {\n split();\n }\n let returner = leftOver.slice(0, count);\n leftOver = leftOver.slice(count);\n return returner;\n },\n resetAfterLine: function () {\n leftOver.length = 0;\n },\n end: function () {\n if (i !== data.length) {\n throw new Error(\"extra data found\");\n }\n },\n };\n}\n\nfunction mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {\n // eslint-disable-line max-params\n let imageWidth = image.width;\n let imageHeight = image.height;\n let imagePass = image.index;\n for (let y = 0; y < imageHeight; y++) {\n for (let x = 0; x < imageWidth; x++) {\n let pxPos = getPxPos(x, y, imagePass);\n pixelBppMapper[bpp](pxData, data, pxPos, rawPos);\n rawPos += bpp; //eslint-disable-line no-param-reassign\n }\n }\n return rawPos;\n}\n\nfunction mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {\n // eslint-disable-line max-params\n let imageWidth = image.width;\n let imageHeight = image.height;\n let imagePass = image.index;\n for (let y = 0; y < imageHeight; y++) {\n for (let x = 0; x < imageWidth; x++) {\n let pixelData = bits.get(bpp);\n let pxPos = getPxPos(x, y, imagePass);\n pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);\n }\n bits.resetAfterLine();\n }\n}\n\nexports.dataToBitMap = function (data, bitmapInfo) {\n let width = bitmapInfo.width;\n let height = bitmapInfo.height;\n let depth = bitmapInfo.depth;\n let bpp = bitmapInfo.bpp;\n let interlace = bitmapInfo.interlace;\n let bits;\n\n if (depth !== 8) {\n bits = bitRetriever(data, depth);\n }\n let pxData;\n if (depth <= 8) {\n pxData = Buffer.alloc(width * height * 4);\n } else {\n pxData = new Uint16Array(width * height * 4);\n }\n let maxBit = Math.pow(2, depth) - 1;\n let rawPos = 0;\n let images;\n let getPxPos;\n\n if (interlace) {\n images = interlaceUtils.getImagePasses(width, height);\n getPxPos = interlaceUtils.getInterlaceIterator(width, height);\n } else {\n let nonInterlacedPxPos = 0;\n getPxPos = function () {\n let returner = nonInterlacedPxPos;\n nonInterlacedPxPos += 4;\n return returner;\n };\n images = [{ width: width, height: height }];\n }\n\n for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {\n if (depth === 8) {\n rawPos = mapImage8Bit(\n images[imageIndex],\n pxData,\n getPxPos,\n bpp,\n data,\n rawPos\n );\n } else {\n mapImageCustomBit(\n images[imageIndex],\n pxData,\n getPxPos,\n bpp,\n bits,\n maxBit\n );\n }\n }\n if (depth === 8) {\n if (rawPos !== data.length) {\n throw new Error(\"extra data found\");\n }\n } else {\n bits.end();\n }\n\n return pxData;\n};\n","\"use strict\";\n\nfunction dePalette(indata, outdata, width, height, palette) {\n let pxPos = 0;\n // use values from palette\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let color = palette[indata[pxPos]];\n\n if (!color) {\n throw new Error(\"index \" + indata[pxPos] + \" not in palette\");\n }\n\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = color[i];\n }\n pxPos += 4;\n }\n }\n}\n\nfunction replaceTransparentColor(indata, outdata, width, height, transColor) {\n let pxPos = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let makeTrans = false;\n\n if (transColor.length === 1) {\n if (transColor[0] === indata[pxPos]) {\n makeTrans = true;\n }\n } else if (\n transColor[0] === indata[pxPos] &&\n transColor[1] === indata[pxPos + 1] &&\n transColor[2] === indata[pxPos + 2]\n ) {\n makeTrans = true;\n }\n if (makeTrans) {\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = 0;\n }\n }\n pxPos += 4;\n }\n }\n}\n\nfunction scaleDepth(indata, outdata, width, height, depth) {\n let maxOutSample = 255;\n let maxInSample = Math.pow(2, depth) - 1;\n let pxPos = 0;\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n for (let i = 0; i < 4; i++) {\n outdata[pxPos + i] = Math.floor(\n (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5\n );\n }\n pxPos += 4;\n }\n }\n}\n\nmodule.exports = function (indata, imageData, skipRescale = false) {\n let depth = imageData.depth;\n let width = imageData.width;\n let height = imageData.height;\n let colorType = imageData.colorType;\n let transColor = imageData.transColor;\n let palette = imageData.palette;\n\n let outdata = indata; // only different for 16 bits\n\n if (colorType === 3) {\n // paletted\n dePalette(indata, outdata, width, height, palette);\n } else {\n if (transColor) {\n replaceTransparentColor(indata, outdata, width, height, transColor);\n }\n // if it needs scaling\n if (depth !== 8 && !skipRescale) {\n // if we need to change the buffer size\n if (depth === 16) {\n outdata = Buffer.alloc(width * height * 4);\n }\n scaleDepth(indata, outdata, width, height, depth);\n }\n }\n return outdata;\n};\n","\"use strict\";\n\nlet util = require(\"util\");\nlet zlib = require(\"zlib\");\nlet ChunkStream = require(\"./chunkstream\");\nlet FilterAsync = require(\"./filter-parse-async\");\nlet Parser = require(\"./parser\");\nlet bitmapper = require(\"./bitmapper\");\nlet formatNormaliser = require(\"./format-normaliser\");\n\nlet ParserAsync = (module.exports = function (options) {\n ChunkStream.call(this);\n\n this._parser = new Parser(options, {\n read: this.read.bind(this),\n error: this._handleError.bind(this),\n metadata: this._handleMetaData.bind(this),\n gamma: this.emit.bind(this, \"gamma\"),\n palette: this._handlePalette.bind(this),\n transColor: this._handleTransColor.bind(this),\n finished: this._finished.bind(this),\n inflateData: this._inflateData.bind(this),\n simpleTransparency: this._simpleTransparency.bind(this),\n headersFinished: this._headersFinished.bind(this),\n });\n this._options = options;\n this.writable = true;\n\n this._parser.start();\n});\nutil.inherits(ParserAsync, ChunkStream);\n\nParserAsync.prototype._handleError = function (err) {\n this.emit(\"error\", err);\n\n this.writable = false;\n\n this.destroy();\n\n if (this._inflate && this._inflate.destroy) {\n this._inflate.destroy();\n }\n\n if (this._filter) {\n this._filter.destroy();\n // For backward compatibility with Node 7 and below.\n // Suppress errors due to _inflate calling write() even after\n // it's destroy()'ed.\n this._filter.on(\"error\", function () {});\n }\n\n this.errord = true;\n};\n\nParserAsync.prototype._inflateData = function (data) {\n if (!this._inflate) {\n if (this._bitmapInfo.interlace) {\n this._inflate = zlib.createInflate();\n\n this._inflate.on(\"error\", this.emit.bind(this, \"error\"));\n this._filter.on(\"complete\", this._complete.bind(this));\n\n this._inflate.pipe(this._filter);\n } else {\n let rowSize =\n ((this._bitmapInfo.width *\n this._bitmapInfo.bpp *\n this._bitmapInfo.depth +\n 7) >>\n 3) +\n 1;\n let imageSize = rowSize * this._bitmapInfo.height;\n let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);\n\n this._inflate = zlib.createInflate({ chunkSize: chunkSize });\n let leftToInflate = imageSize;\n\n let emitError = this.emit.bind(this, \"error\");\n this._inflate.on(\"error\", function (err) {\n if (!leftToInflate) {\n return;\n }\n\n emitError(err);\n });\n this._filter.on(\"complete\", this._complete.bind(this));\n\n let filterWrite = this._filter.write.bind(this._filter);\n this._inflate.on(\"data\", function (chunk) {\n if (!leftToInflate) {\n return;\n }\n\n if (chunk.length > leftToInflate) {\n chunk = chunk.slice(0, leftToInflate);\n }\n\n leftToInflate -= chunk.length;\n\n filterWrite(chunk);\n });\n\n this._inflate.on(\"end\", this._filter.end.bind(this._filter));\n }\n }\n this._inflate.write(data);\n};\n\nParserAsync.prototype._handleMetaData = function (metaData) {\n this._metaData = metaData;\n this._bitmapInfo = Object.create(metaData);\n\n this._filter = new FilterAsync(this._bitmapInfo);\n};\n\nParserAsync.prototype._handleTransColor = function (transColor) {\n this._bitmapInfo.transColor = transColor;\n};\n\nParserAsync.prototype._handlePalette = function (palette) {\n this._bitmapInfo.palette = palette;\n};\n\nParserAsync.prototype._simpleTransparency = function () {\n this._metaData.alpha = true;\n};\n\nParserAsync.prototype._headersFinished = function () {\n // Up until this point, we don't know if we have a tRNS chunk (alpha)\n // so we can't emit metadata any earlier\n this.emit(\"metadata\", this._metaData);\n};\n\nParserAsync.prototype._finished = function () {\n if (this.errord) {\n return;\n }\n\n if (!this._inflate) {\n this.emit(\"error\", \"No Inflate block\");\n } else {\n // no more data to inflate\n this._inflate.end();\n }\n};\n\nParserAsync.prototype._complete = function (filteredData) {\n if (this.errord) {\n return;\n }\n\n let normalisedBitmapData;\n\n try {\n let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);\n\n normalisedBitmapData = formatNormaliser(\n bitmapData,\n this._bitmapInfo,\n this._options.skipRescale\n );\n bitmapData = null;\n } catch (ex) {\n this._handleError(ex);\n return;\n }\n\n this.emit(\"parsed\", normalisedBitmapData);\n};\n","\"use strict\";\n\nlet constants = require(\"./constants\");\n\nmodule.exports = function (dataIn, width, height, options) {\n let outHasAlpha =\n [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(\n options.colorType\n ) !== -1;\n if (options.colorType === options.inputColorType) {\n let bigEndian = (function () {\n let buffer = new ArrayBuffer(2);\n new DataView(buffer).setInt16(0, 256, true /* littleEndian */);\n // Int16Array uses the platform's endianness.\n return new Int16Array(buffer)[0] !== 256;\n })();\n // If no need to convert to grayscale and alpha is present/absent in both, take a fast route\n if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {\n return dataIn;\n }\n }\n\n // map to a UInt16 array if data is 16bit, fix endianness below\n let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);\n\n let maxValue = 255;\n let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];\n if (inBpp === 4 && !options.inputHasAlpha) {\n inBpp = 3;\n }\n let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];\n if (options.bitDepth === 16) {\n maxValue = 65535;\n outBpp *= 2;\n }\n let outData = Buffer.alloc(width * height * outBpp);\n\n let inIndex = 0;\n let outIndex = 0;\n\n let bgColor = options.bgColor || {};\n if (bgColor.red === undefined) {\n bgColor.red = maxValue;\n }\n if (bgColor.green === undefined) {\n bgColor.green = maxValue;\n }\n if (bgColor.blue === undefined) {\n bgColor.blue = maxValue;\n }\n\n function getRGBA() {\n let red;\n let green;\n let blue;\n let alpha = maxValue;\n switch (options.inputColorType) {\n case constants.COLORTYPE_COLOR_ALPHA:\n alpha = data[inIndex + 3];\n red = data[inIndex];\n green = data[inIndex + 1];\n blue = data[inIndex + 2];\n break;\n case constants.COLORTYPE_COLOR:\n red = data[inIndex];\n green = data[inIndex + 1];\n blue = data[inIndex + 2];\n break;\n case constants.COLORTYPE_ALPHA:\n alpha = data[inIndex + 1];\n red = data[inIndex];\n green = red;\n blue = red;\n break;\n case constants.COLORTYPE_GRAYSCALE:\n red = data[inIndex];\n green = red;\n blue = red;\n break;\n default:\n throw new Error(\n \"input color type:\" +\n options.inputColorType +\n \" is not supported at present\"\n );\n }\n\n if (options.inputHasAlpha) {\n if (!outHasAlpha) {\n alpha /= maxValue;\n red = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),\n maxValue\n );\n green = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),\n maxValue\n );\n blue = Math.min(\n Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),\n maxValue\n );\n }\n }\n return { red: red, green: green, blue: blue, alpha: alpha };\n }\n\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n let rgba = getRGBA(data, inIndex);\n\n switch (options.colorType) {\n case constants.COLORTYPE_COLOR_ALPHA:\n case constants.COLORTYPE_COLOR:\n if (options.bitDepth === 8) {\n outData[outIndex] = rgba.red;\n outData[outIndex + 1] = rgba.green;\n outData[outIndex + 2] = rgba.blue;\n if (outHasAlpha) {\n outData[outIndex + 3] = rgba.alpha;\n }\n } else {\n outData.writeUInt16BE(rgba.red, outIndex);\n outData.writeUInt16BE(rgba.green, outIndex + 2);\n outData.writeUInt16BE(rgba.blue, outIndex + 4);\n if (outHasAlpha) {\n outData.writeUInt16BE(rgba.alpha, outIndex + 6);\n }\n }\n break;\n case constants.COLORTYPE_ALPHA:\n case constants.COLORTYPE_GRAYSCALE: {\n // Convert to grayscale and alpha\n let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;\n if (options.bitDepth === 8) {\n outData[outIndex] = grayscale;\n if (outHasAlpha) {\n outData[outIndex + 1] = rgba.alpha;\n }\n } else {\n outData.writeUInt16BE(grayscale, outIndex);\n if (outHasAlpha) {\n outData.writeUInt16BE(rgba.alpha, outIndex + 2);\n }\n }\n break;\n }\n default:\n throw new Error(\"unrecognised color Type \" + options.colorType);\n }\n\n inIndex += inBpp;\n outIndex += outBpp;\n }\n }\n\n return outData;\n};\n","\"use strict\";\n\nlet paethPredictor = require(\"./paeth-predictor\");\n\nfunction filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {\n for (let x = 0; x < byteWidth; x++) {\n rawData[rawPos + x] = pxData[pxPos + x];\n }\n}\n\nfunction filterSumNone(pxData, pxPos, byteWidth) {\n let sum = 0;\n let length = pxPos + byteWidth;\n\n for (let i = pxPos; i < length; i++) {\n sum += Math.abs(pxData[i]);\n }\n return sum;\n}\n\nfunction filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let val = pxData[pxPos + x] - left;\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumSub(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let val = pxData[pxPos + x] - left;\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {\n for (let x = 0; x < byteWidth; x++) {\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - up;\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumUp(pxData, pxPos, byteWidth) {\n let sum = 0;\n let length = pxPos + byteWidth;\n for (let x = pxPos; x < length; x++) {\n let up = pxPos > 0 ? pxData[x - byteWidth] : 0;\n let val = pxData[x] - up;\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - ((left + up) >> 1);\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumAvg(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let val = pxData[pxPos + x] - ((left + up) >> 1);\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nfunction filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let upleft =\n pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;\n let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);\n\n rawData[rawPos + x] = val;\n }\n}\n\nfunction filterSumPaeth(pxData, pxPos, byteWidth, bpp) {\n let sum = 0;\n for (let x = 0; x < byteWidth; x++) {\n let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;\n let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;\n let upleft =\n pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;\n let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);\n\n sum += Math.abs(val);\n }\n\n return sum;\n}\n\nlet filters = {\n 0: filterNone,\n 1: filterSub,\n 2: filterUp,\n 3: filterAvg,\n 4: filterPaeth,\n};\n\nlet filterSums = {\n 0: filterSumNone,\n 1: filterSumSub,\n 2: filterSumUp,\n 3: filterSumAvg,\n 4: filterSumPaeth,\n};\n\nmodule.exports = function (pxData, width, height, options, bpp) {\n let filterTypes;\n if (!(\"filterType\" in options) || options.filterType === -1) {\n filterTypes = [0, 1, 2, 3, 4];\n } else if (typeof options.filterType === \"number\") {\n filterTypes = [options.filterType];\n } else {\n throw new Error(\"unrecognised filter types\");\n }\n\n if (options.bitDepth === 16) {\n bpp *= 2;\n }\n let byteWidth = width * bpp;\n let rawPos = 0;\n let pxPos = 0;\n let rawData = Buffer.alloc((byteWidth + 1) * height);\n\n let sel = filterTypes[0];\n\n for (let y = 0; y < height; y++) {\n if (filterTypes.length > 1) {\n // find best filter for this line (with lowest sum of values)\n let min = Infinity;\n\n for (let i = 0; i < filterTypes.length; i++) {\n let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);\n if (sum < min) {\n sel = filterTypes[i];\n min = sum;\n }\n }\n }\n\n rawData[rawPos] = sel;\n rawPos++;\n filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);\n rawPos += byteWidth;\n pxPos += byteWidth;\n }\n return rawData;\n};\n","\"use strict\";\n\nlet constants = require(\"./constants\");\nlet CrcStream = require(\"./crc\");\nlet bitPacker = require(\"./bitpacker\");\nlet filter = require(\"./filter-pack\");\nlet zlib = require(\"zlib\");\n\nlet Packer = (module.exports = function (options) {\n this._options = options;\n\n options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;\n options.deflateLevel =\n options.deflateLevel != null ? options.deflateLevel : 9;\n options.deflateStrategy =\n options.deflateStrategy != null ? options.deflateStrategy : 3;\n options.inputHasAlpha =\n options.inputHasAlpha != null ? options.inputHasAlpha : true;\n options.deflateFactory = options.deflateFactory || zlib.createDeflate;\n options.bitDepth = options.bitDepth || 8;\n // This is outputColorType\n options.colorType =\n typeof options.colorType === \"number\"\n ? options.colorType\n : constants.COLORTYPE_COLOR_ALPHA;\n options.inputColorType =\n typeof options.inputColorType === \"number\"\n ? options.inputColorType\n : constants.COLORTYPE_COLOR_ALPHA;\n\n if (\n [\n constants.COLORTYPE_GRAYSCALE,\n constants.COLORTYPE_COLOR,\n constants.COLORTYPE_COLOR_ALPHA,\n constants.COLORTYPE_ALPHA,\n ].indexOf(options.colorType) === -1\n ) {\n throw new Error(\n \"option color type:\" + options.colorType + \" is not supported at present\"\n );\n }\n if (\n [\n constants.COLORTYPE_GRAYSCALE,\n constants.COLORTYPE_COLOR,\n constants.COLORTYPE_COLOR_ALPHA,\n constants.COLORTYPE_ALPHA,\n ].indexOf(options.inputColorType) === -1\n ) {\n throw new Error(\n \"option input color type:\" +\n options.inputColorType +\n \" is not supported at present\"\n );\n }\n if (options.bitDepth !== 8 && options.bitDepth !== 16) {\n throw new Error(\n \"option bit depth:\" + options.bitDepth + \" is not supported at present\"\n );\n }\n});\n\nPacker.prototype.getDeflateOptions = function () {\n return {\n chunkSize: this._options.deflateChunkSize,\n level: this._options.deflateLevel,\n strategy: this._options.deflateStrategy,\n };\n};\n\nPacker.prototype.createDeflate = function () {\n return this._options.deflateFactory(this.getDeflateOptions());\n};\n\nPacker.prototype.filterData = function (data, width, height) {\n // convert to correct format for filtering (e.g. right bpp and bit depth)\n let packedData = bitPacker(data, width, height, this._options);\n\n // filter pixel data\n let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];\n let filteredData = filter(packedData, width, height, this._options, bpp);\n return filteredData;\n};\n\nPacker.prototype._packChunk = function (type, data) {\n let len = data ? data.length : 0;\n let buf = Buffer.alloc(len + 12);\n\n buf.writeUInt32BE(len, 0);\n buf.writeUInt32BE(type, 4);\n\n if (data) {\n data.copy(buf, 8);\n }\n\n buf.writeInt32BE(\n CrcStream.crc32(buf.slice(4, buf.length - 4)),\n buf.length - 4\n );\n return buf;\n};\n\nPacker.prototype.packGAMA = function (gamma) {\n let buf = Buffer.alloc(4);\n buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);\n return this._packChunk(constants.TYPE_gAMA, buf);\n};\n\nPacker.prototype.packIHDR = function (width, height) {\n let buf = Buffer.alloc(13);\n buf.writeUInt32BE(width, 0);\n buf.writeUInt32BE(height, 4);\n buf[8] = this._options.bitDepth; // Bit depth\n buf[9] = this._options.colorType; // colorType\n buf[10] = 0; // compression\n buf[11] = 0; // filter\n buf[12] = 0; // interlace\n\n return this._packChunk(constants.TYPE_IHDR, buf);\n};\n\nPacker.prototype.packIDAT = function (data) {\n return this._packChunk(constants.TYPE_IDAT, data);\n};\n\nPacker.prototype.packIEND = function () {\n return this._packChunk(constants.TYPE_IEND, null);\n};\n","\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\nlet constants = require(\"./constants\");\nlet Packer = require(\"./packer\");\n\nlet PackerAsync = (module.exports = function (opt) {\n Stream.call(this);\n\n let options = opt || {};\n\n this._packer = new Packer(options);\n this._deflate = this._packer.createDeflate();\n\n this.readable = true;\n});\nutil.inherits(PackerAsync, Stream);\n\nPackerAsync.prototype.pack = function (data, width, height, gamma) {\n // Signature\n this.emit(\"data\", Buffer.from(constants.PNG_SIGNATURE));\n this.emit(\"data\", this._packer.packIHDR(width, height));\n\n if (gamma) {\n this.emit(\"data\", this._packer.packGAMA(gamma));\n }\n\n let filteredData = this._packer.filterData(data, width, height);\n\n // compress it\n this._deflate.on(\"error\", this.emit.bind(this, \"error\"));\n\n this._deflate.on(\n \"data\",\n function (compressedData) {\n this.emit(\"data\", this._packer.packIDAT(compressedData));\n }.bind(this)\n );\n\n this._deflate.on(\n \"end\",\n function () {\n this.emit(\"data\", this._packer.packIEND());\n this.emit(\"end\");\n }.bind(this)\n );\n\n this._deflate.end(filteredData);\n};\n","\"use strict\";\n\nlet assert = require(\"assert\").ok;\nlet zlib = require(\"zlib\");\nlet util = require(\"util\");\n\nlet kMaxLength = require(\"buffer\").kMaxLength;\n\nfunction Inflate(opts) {\n if (!(this instanceof Inflate)) {\n return new Inflate(opts);\n }\n\n if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {\n opts.chunkSize = zlib.Z_MIN_CHUNK;\n }\n\n zlib.Inflate.call(this, opts);\n\n // Node 8 --> 9 compatibility check\n this._offset = this._offset === undefined ? this._outOffset : this._offset;\n this._buffer = this._buffer || this._outBuffer;\n\n if (opts && opts.maxLength != null) {\n this._maxLength = opts.maxLength;\n }\n}\n\nfunction createInflate(opts) {\n return new Inflate(opts);\n}\n\nfunction _close(engine, callback) {\n if (callback) {\n process.nextTick(callback);\n }\n\n // Caller may invoke .close after a zlib error (which will null _handle).\n if (!engine._handle) {\n return;\n }\n\n engine._handle.close();\n engine._handle = null;\n}\n\nInflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) {\n if (typeof asyncCb === \"function\") {\n return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);\n }\n\n let self = this;\n\n let availInBefore = chunk && chunk.length;\n let availOutBefore = this._chunkSize - this._offset;\n let leftToInflate = this._maxLength;\n let inOff = 0;\n\n let buffers = [];\n let nread = 0;\n\n let error;\n this.on(\"error\", function (err) {\n error = err;\n });\n\n function handleChunk(availInAfter, availOutAfter) {\n if (self._hadError) {\n return;\n }\n\n let have = availOutBefore - availOutAfter;\n assert(have >= 0, \"have should not go down\");\n\n if (have > 0) {\n let out = self._buffer.slice(self._offset, self._offset + have);\n self._offset += have;\n\n if (out.length > leftToInflate) {\n out = out.slice(0, leftToInflate);\n }\n\n buffers.push(out);\n nread += out.length;\n leftToInflate -= out.length;\n\n if (leftToInflate === 0) {\n return false;\n }\n }\n\n if (availOutAfter === 0 || self._offset >= self._chunkSize) {\n availOutBefore = self._chunkSize;\n self._offset = 0;\n self._buffer = Buffer.allocUnsafe(self._chunkSize);\n }\n\n if (availOutAfter === 0) {\n inOff += availInBefore - availInAfter;\n availInBefore = availInAfter;\n\n return true;\n }\n\n return false;\n }\n\n assert(this._handle, \"zlib binding closed\");\n let res;\n do {\n res = this._handle.writeSync(\n flushFlag,\n chunk, // in\n inOff, // in_off\n availInBefore, // in_len\n this._buffer, // out\n this._offset, //out_off\n availOutBefore\n ); // out_len\n // Node 8 --> 9 compatibility check\n res = res || this._writeState;\n } while (!this._hadError && handleChunk(res[0], res[1]));\n\n if (this._hadError) {\n throw error;\n }\n\n if (nread >= kMaxLength) {\n _close(this);\n throw new RangeError(\n \"Cannot create final Buffer. It would be larger than 0x\" +\n kMaxLength.toString(16) +\n \" bytes\"\n );\n }\n\n let buf = Buffer.concat(buffers, nread);\n _close(this);\n\n return buf;\n};\n\nutil.inherits(Inflate, zlib.Inflate);\n\nfunction zlibBufferSync(engine, buffer) {\n if (typeof buffer === \"string\") {\n buffer = Buffer.from(buffer);\n }\n if (!(buffer instanceof Buffer)) {\n throw new TypeError(\"Not a string or buffer\");\n }\n\n let flushFlag = engine._finishFlushFlag;\n if (flushFlag == null) {\n flushFlag = zlib.Z_FINISH;\n }\n\n return engine._processChunk(buffer, flushFlag);\n}\n\nfunction inflateSync(buffer, opts) {\n return zlibBufferSync(new Inflate(opts), buffer);\n}\n\nmodule.exports = exports = inflateSync;\nexports.Inflate = Inflate;\nexports.createInflate = createInflate;\nexports.inflateSync = inflateSync;\n","\"use strict\";\n\nlet SyncReader = (module.exports = function (buffer) {\n this._buffer = buffer;\n this._reads = [];\n});\n\nSyncReader.prototype.read = function (length, callback) {\n this._reads.push({\n length: Math.abs(length), // if length < 0 then at most this length\n allowLess: length < 0,\n func: callback,\n });\n};\n\nSyncReader.prototype.process = function () {\n // as long as there is any data and read requests\n while (this._reads.length > 0 && this._buffer.length) {\n let read = this._reads[0];\n\n if (\n this._buffer.length &&\n (this._buffer.length >= read.length || read.allowLess)\n ) {\n // ok there is any data so that we can satisfy this request\n this._reads.shift(); // == read\n\n let buf = this._buffer;\n\n this._buffer = buf.slice(read.length);\n\n read.func.call(this, buf.slice(0, read.length));\n } else {\n break;\n }\n }\n\n if (this._reads.length > 0) {\n throw new Error(\"There are some read requests waitng on finished stream\");\n }\n\n if (this._buffer.length > 0) {\n throw new Error(\"unrecognised content at end of stream\");\n }\n};\n","\"use strict\";\n\nlet SyncReader = require(\"./sync-reader\");\nlet Filter = require(\"./filter-parse\");\n\nexports.process = function (inBuffer, bitmapInfo) {\n let outBuffers = [];\n let reader = new SyncReader(inBuffer);\n let filter = new Filter(bitmapInfo, {\n read: reader.read.bind(reader),\n write: function (bufferPart) {\n outBuffers.push(bufferPart);\n },\n complete: function () {},\n });\n\n filter.start();\n reader.process();\n\n return Buffer.concat(outBuffers);\n};\n","\"use strict\";\n\nlet hasSyncZlib = true;\nlet zlib = require(\"zlib\");\nlet inflateSync = require(\"./sync-inflate\");\nif (!zlib.deflateSync) {\n hasSyncZlib = false;\n}\nlet SyncReader = require(\"./sync-reader\");\nlet FilterSync = require(\"./filter-parse-sync\");\nlet Parser = require(\"./parser\");\nlet bitmapper = require(\"./bitmapper\");\nlet formatNormaliser = require(\"./format-normaliser\");\n\nmodule.exports = function (buffer, options) {\n if (!hasSyncZlib) {\n throw new Error(\n \"To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0\"\n );\n }\n\n let err;\n function handleError(_err_) {\n err = _err_;\n }\n\n let metaData;\n function handleMetaData(_metaData_) {\n metaData = _metaData_;\n }\n\n function handleTransColor(transColor) {\n metaData.transColor = transColor;\n }\n\n function handlePalette(palette) {\n metaData.palette = palette;\n }\n\n function handleSimpleTransparency() {\n metaData.alpha = true;\n }\n\n let gamma;\n function handleGamma(_gamma_) {\n gamma = _gamma_;\n }\n\n let inflateDataList = [];\n function handleInflateData(inflatedData) {\n inflateDataList.push(inflatedData);\n }\n\n let reader = new SyncReader(buffer);\n\n let parser = new Parser(options, {\n read: reader.read.bind(reader),\n error: handleError,\n metadata: handleMetaData,\n gamma: handleGamma,\n palette: handlePalette,\n transColor: handleTransColor,\n inflateData: handleInflateData,\n simpleTransparency: handleSimpleTransparency,\n });\n\n parser.start();\n reader.process();\n\n if (err) {\n throw err;\n }\n\n //join together the inflate datas\n let inflateData = Buffer.concat(inflateDataList);\n inflateDataList.length = 0;\n\n let inflatedData;\n if (metaData.interlace) {\n inflatedData = zlib.inflateSync(inflateData);\n } else {\n let rowSize =\n ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;\n let imageSize = rowSize * metaData.height;\n inflatedData = inflateSync(inflateData, {\n chunkSize: imageSize,\n maxLength: imageSize,\n });\n }\n inflateData = null;\n\n if (!inflatedData || !inflatedData.length) {\n throw new Error(\"bad png - invalid inflate data response\");\n }\n\n let unfilteredData = FilterSync.process(inflatedData, metaData);\n inflateData = null;\n\n let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);\n unfilteredData = null;\n\n let normalisedBitmapData = formatNormaliser(\n bitmapData,\n metaData,\n options.skipRescale\n );\n\n metaData.data = normalisedBitmapData;\n metaData.gamma = gamma || 0;\n\n return metaData;\n};\n","\"use strict\";\n\nlet hasSyncZlib = true;\nlet zlib = require(\"zlib\");\nif (!zlib.deflateSync) {\n hasSyncZlib = false;\n}\nlet constants = require(\"./constants\");\nlet Packer = require(\"./packer\");\n\nmodule.exports = function (metaData, opt) {\n if (!hasSyncZlib) {\n throw new Error(\n \"To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0\"\n );\n }\n\n let options = opt || {};\n\n let packer = new Packer(options);\n\n let chunks = [];\n\n // Signature\n chunks.push(Buffer.from(constants.PNG_SIGNATURE));\n\n // Header\n chunks.push(packer.packIHDR(metaData.width, metaData.height));\n\n if (metaData.gamma) {\n chunks.push(packer.packGAMA(metaData.gamma));\n }\n\n let filteredData = packer.filterData(\n metaData.data,\n metaData.width,\n metaData.height\n );\n\n // compress it\n let compressedData = zlib.deflateSync(\n filteredData,\n packer.getDeflateOptions()\n );\n filteredData = null;\n\n if (!compressedData || !compressedData.length) {\n throw new Error(\"bad png - invalid compressed data response\");\n }\n chunks.push(packer.packIDAT(compressedData));\n\n // End\n chunks.push(packer.packIEND());\n\n return Buffer.concat(chunks);\n};\n","\"use strict\";\n\nlet parse = require(\"./parser-sync\");\nlet pack = require(\"./packer-sync\");\n\nexports.read = function (buffer, options) {\n return parse(buffer, options || {});\n};\n\nexports.write = function (png, options) {\n return pack(png, options);\n};\n","\"use strict\";\n\nlet util = require(\"util\");\nlet Stream = require(\"stream\");\nlet Parser = require(\"./parser-async\");\nlet Packer = require(\"./packer-async\");\nlet PNGSync = require(\"./png-sync\");\n\nlet PNG = (exports.PNG = function (options) {\n Stream.call(this);\n\n options = options || {}; // eslint-disable-line no-param-reassign\n\n // coerce pixel dimensions to integers (also coerces undefined -> 0):\n this.width = options.width | 0;\n this.height = options.height | 0;\n\n this.data =\n this.width > 0 && this.height > 0\n ? Buffer.alloc(4 * this.width * this.height)\n : null;\n\n if (options.fill && this.data) {\n this.data.fill(0);\n }\n\n this.gamma = 0;\n this.readable = this.writable = true;\n\n this._parser = new Parser(options);\n\n this._parser.on(\"error\", this.emit.bind(this, \"error\"));\n this._parser.on(\"close\", this._handleClose.bind(this));\n this._parser.on(\"metadata\", this._metadata.bind(this));\n this._parser.on(\"gamma\", this._gamma.bind(this));\n this._parser.on(\n \"parsed\",\n function (data) {\n this.data = data;\n this.emit(\"parsed\", data);\n }.bind(this)\n );\n\n this._packer = new Packer(options);\n this._packer.on(\"data\", this.emit.bind(this, \"data\"));\n this._packer.on(\"end\", this.emit.bind(this, \"end\"));\n this._parser.on(\"close\", this._handleClose.bind(this));\n this._packer.on(\"error\", this.emit.bind(this, \"error\"));\n});\nutil.inherits(PNG, Stream);\n\nPNG.sync = PNGSync;\n\nPNG.prototype.pack = function () {\n if (!this.data || !this.data.length) {\n this.emit(\"error\", \"No data provided\");\n return this;\n }\n\n process.nextTick(\n function () {\n this._packer.pack(this.data, this.width, this.height, this.gamma);\n }.bind(this)\n );\n\n return this;\n};\n\nPNG.prototype.parse = function (data, callback) {\n if (callback) {\n let onParsed, onError;\n\n onParsed = function (parsedData) {\n this.removeListener(\"error\", onError);\n\n this.data = parsedData;\n callback(null, this);\n }.bind(this);\n\n onError = function (err) {\n this.removeListener(\"parsed\", onParsed);\n\n callback(err, null);\n }.bind(this);\n\n this.once(\"parsed\", onParsed);\n this.once(\"error\", onError);\n }\n\n this.end(data);\n return this;\n};\n\nPNG.prototype.write = function (data) {\n this._parser.write(data);\n return true;\n};\n\nPNG.prototype.end = function (data) {\n this._parser.end(data);\n};\n\nPNG.prototype._metadata = function (metadata) {\n this.width = metadata.width;\n this.height = metadata.height;\n\n this.emit(\"metadata\", metadata);\n};\n\nPNG.prototype._gamma = function (gamma) {\n this.gamma = gamma;\n};\n\nPNG.prototype._handleClose = function () {\n if (!this._parser.writable && !this._packer.readable) {\n this.emit(\"close\");\n }\n};\n\nPNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) {\n // eslint-disable-line max-params\n // coerce pixel dimensions to integers (also coerces undefined -> 0):\n /* eslint-disable no-param-reassign */\n srcX |= 0;\n srcY |= 0;\n width |= 0;\n height |= 0;\n deltaX |= 0;\n deltaY |= 0;\n /* eslint-enable no-param-reassign */\n\n if (\n srcX > src.width ||\n srcY > src.height ||\n srcX + width > src.width ||\n srcY + height > src.height\n ) {\n throw new Error(\"bitblt reading outside image\");\n }\n\n if (\n deltaX > dst.width ||\n deltaY > dst.height ||\n deltaX + width > dst.width ||\n deltaY + height > dst.height\n ) {\n throw new Error(\"bitblt writing outside image\");\n }\n\n for (let y = 0; y < height; y++) {\n src.data.copy(\n dst.data,\n ((deltaY + y) * dst.width + deltaX) << 2,\n ((srcY + y) * src.width + srcX) << 2,\n ((srcY + y) * src.width + srcX + width) << 2\n );\n }\n};\n\nPNG.prototype.bitblt = function (\n dst,\n srcX,\n srcY,\n width,\n height,\n deltaX,\n deltaY\n) {\n // eslint-disable-line max-params\n\n PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);\n return this;\n};\n\nPNG.adjustGamma = function (src) {\n if (src.gamma) {\n for (let y = 0; y < src.height; y++) {\n for (let x = 0; x < src.width; x++) {\n let idx = (src.width * y + x) << 2;\n\n for (let i = 0; i < 3; i++) {\n let sample = src.data[idx + i] / 255;\n sample = Math.pow(sample, 1 / 2.2 / src.gamma);\n src.data[idx + i] = Math.round(sample * 255);\n }\n }\n }\n src.gamma = 0;\n }\n};\n\nPNG.prototype.adjustGamma = function () {\n PNG.adjustGamma(this);\n};\n","'use strict';\n\n\nvar TYPED_OK = (typeof Uint8Array !== 'undefined') &&\n (typeof Uint16Array !== 'undefined') &&\n (typeof Int32Array !== 'undefined');\n\nfunction _has(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexports.assign = function (obj /*from1, from2, from3, ...*/) {\n var sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n var source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (var p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// reduce buffer size, avoiding mem copy\nexports.shrinkBuf = function (buf, size) {\n if (buf.length === size) { return buf; }\n if (buf.subarray) { return buf.subarray(0, size); }\n buf.length = size;\n return buf;\n};\n\n\nvar fnTyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n if (src.subarray && dest.subarray) {\n dest.set(src.subarray(src_offs, src_offs + len), dest_offs);\n return;\n }\n // Fallback to ordinary array\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n var i, l, len, pos, chunk, result;\n\n // calculate data length\n len = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n result = new Uint8Array(len);\n pos = 0;\n for (i = 0, l = chunks.length; i < l; i++) {\n chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n }\n};\n\nvar fnUntyped = {\n arraySet: function (dest, src, src_offs, len, dest_offs) {\n for (var i = 0; i < len; i++) {\n dest[dest_offs + i] = src[src_offs + i];\n }\n },\n // Join array of chunks to single array.\n flattenChunks: function (chunks) {\n return [].concat.apply([], chunks);\n }\n};\n\n\n// Enable/Disable typed arrays use, for testing\n//\nexports.setTyped = function (on) {\n if (on) {\n exports.Buf8 = Uint8Array;\n exports.Buf16 = Uint16Array;\n exports.Buf32 = Int32Array;\n exports.assign(exports, fnTyped);\n } else {\n exports.Buf8 = Array;\n exports.Buf16 = Array;\n exports.Buf32 = Array;\n exports.assign(exports, fnUntyped);\n }\n};\n\nexports.setTyped(TYPED_OK);\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\nvar utils = require('../utils/common');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//var Z_FILTERED = 1;\n//var Z_HUFFMAN_ONLY = 2;\n//var Z_RLE = 3;\nvar Z_FIXED = 4;\n//var Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nvar Z_BINARY = 0;\nvar Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nvar STORED_BLOCK = 0;\nvar STATIC_TREES = 1;\nvar DYN_TREES = 2;\n/* The three kinds of block type */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nvar D_CODES = 30;\n/* number of distance codes */\n\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nvar MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nvar END_BLOCK = 256;\n/* end of block literal code */\n\nvar REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nvar REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nvar REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nvar extra_lbits = /* extra bits for each length code */\n [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];\n\nvar extra_dbits = /* extra bits for each distance code */\n [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];\n\nvar extra_blbits = /* extra bits for each bit length code */\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];\n\nvar bl_order =\n [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nvar DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nvar static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nvar static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nvar _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nvar _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nvar base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nvar base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nvar static_l_desc;\nvar static_d_desc;\nvar static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nfunction d_code(dist) {\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n}\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nfunction put_short(s, w) {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n}\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nfunction send_bits(s, value, length) {\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n}\n\n\nfunction send_code(s, c, tree) {\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n}\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nfunction bi_reverse(code, len) {\n var res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nfunction bi_flush(s) {\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n}\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nfunction gen_bitlen(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var max_code = desc.max_code;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var extra = desc.stat_desc.extra_bits;\n var base = desc.stat_desc.extra_base;\n var max_length = desc.stat_desc.max_length;\n var h; /* heap index */\n var n, m; /* iterate over the tree elements */\n var bits; /* bit length */\n var xbits; /* extra bits */\n var f; /* frequency */\n var overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n}\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nfunction gen_codes(tree, max_code, bl_count)\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n var code = 0; /* running code value */\n var bits; /* bit index */\n var n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n}\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nfunction init_block(s) {\n var n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n}\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nfunction bi_windup(s)\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nfunction copy_block(s, buf, len, header)\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);\n s.pending += len;\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nfunction smaller(tree, n, m, depth) {\n var _n2 = n * 2;\n var _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n}\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nfunction pqdownheap(s, tree, k)\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n var v = s.heap[k];\n var j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n}\n\n\n// inlined manually\n// var SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nfunction compress_block(s, ltree, dtree)\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n var dist; /* distance of matched string */\n var lc; /* match length or unmatched char (if dist == 0) */\n var lx = 0; /* running index in l_buf */\n var code; /* the code to send */\n var extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n}\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nfunction build_tree(s, desc)\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n var tree = desc.dyn_tree;\n var stree = desc.stat_desc.static_tree;\n var has_stree = desc.stat_desc.has_stree;\n var elems = desc.stat_desc.elems;\n var n, m; /* iterate over heap elements */\n var max_code = -1; /* largest code with non zero frequency */\n var node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n}\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nfunction scan_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nfunction send_tree(s, tree, max_code)\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n var n; /* iterates over all tree elements */\n var prevlen = -1; /* last emitted length */\n var curlen; /* length of current code */\n\n var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n var count = 0; /* repeat count of the current code */\n var max_count = 7; /* max repeat count */\n var min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n}\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nfunction build_bl_tree(s) {\n var max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n}\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nfunction send_all_trees(s, lcodes, dcodes, blcodes)\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n var rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nfunction detect_data_type(s) {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n var black_mask = 0xf3ffc07f;\n var n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n}\n\n\nvar static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nfunction _tr_init(s)\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n}\n\n\n/* ===========================================================================\n * Send a stored block\n */\nfunction _tr_stored_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n}\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nfunction _tr_align(s) {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n}\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nfunction _tr_flush_block(s, buf, stored_len, last)\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n var opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n var max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nfunction _tr_tally(s, dist, lc)\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //var out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n}\n\nexports._tr_init = _tr_init;\nexports._tr_stored_block = _tr_stored_block;\nexports._tr_flush_block = _tr_flush_block;\nexports._tr_tally = _tr_tally;\nexports._tr_align = _tr_align;\n","'use strict';\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction adler32(adler, buf, len, pos) {\n var s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n}\n\n\nmodule.exports = adler32;\n","'use strict';\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable,\n end = pos + len;\n\n crc ^= -1;\n\n for (var i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n\nmodule.exports = crc32;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar trees = require('./trees');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar msg = require('./messages');\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\nvar Z_NO_FLUSH = 0;\nvar Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\nvar Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\n//var Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\n//var Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\n//var Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n\n/* compression levels */\n//var Z_NO_COMPRESSION = 0;\n//var Z_BEST_SPEED = 1;\n//var Z_BEST_COMPRESSION = 9;\nvar Z_DEFAULT_COMPRESSION = -1;\n\n\nvar Z_FILTERED = 1;\nvar Z_HUFFMAN_ONLY = 2;\nvar Z_RLE = 3;\nvar Z_FIXED = 4;\nvar Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\n//var Z_BINARY = 0;\n//var Z_TEXT = 1;\n//var Z_ASCII = 1; // = Z_TEXT\nvar Z_UNKNOWN = 2;\n\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n/*============================================================================*/\n\n\nvar MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_MEM_LEVEL = 8;\n\n\nvar LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nvar LITERALS = 256;\n/* number of literal bytes 0..255 */\nvar L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nvar D_CODES = 30;\n/* number of distance codes */\nvar BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nvar HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nvar MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nvar MIN_MATCH = 3;\nvar MAX_MATCH = 258;\nvar MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nvar PRESET_DICT = 0x20;\n\nvar INIT_STATE = 42;\nvar EXTRA_STATE = 69;\nvar NAME_STATE = 73;\nvar COMMENT_STATE = 91;\nvar HCRC_STATE = 103;\nvar BUSY_STATE = 113;\nvar FINISH_STATE = 666;\n\nvar BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nvar BS_BLOCK_DONE = 2; /* block flush performed */\nvar BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nvar BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nvar OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nfunction err(strm, errorCode) {\n strm.msg = msg[errorCode];\n return errorCode;\n}\n\nfunction rank(f) {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n}\n\nfunction zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nfunction flush_pending(strm) {\n var s = strm.state;\n\n //_tr_flush_bits(s);\n var len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n}\n\n\nfunction flush_block_only(s, last) {\n trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n}\n\n\nfunction put_byte(s, b) {\n s.pending_buf[s.pending++] = b;\n}\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nfunction putShortMSB(s, b) {\n// put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n}\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nfunction read_buf(strm, buf, start, size) {\n var len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n utils.arraySet(buf, strm.input, strm.next_in, len, start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n}\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nfunction longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nfunction fill_window(s) {\n var _w_size = s.w_size;\n var p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n utils.arraySet(s.window, s.window, _w_size, _w_size, 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// var curr = s.strstart + s.lookahead;\n// var init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nfunction deflate_stored(s, flush) {\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n var max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n var max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nfunction deflate_fast(s, flush) {\n var hash_head; /* head of the hash chain */\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nfunction deflate_slow(s, flush) {\n var hash_head; /* head of hash chain */\n var bflush; /* set if current block must be flushed */\n\n var max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n}\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nfunction deflate_rle(s, flush) {\n var bflush; /* set if current block must be flushed */\n var prev; /* byte at distance one to match */\n var scan, strend; /* scan goes up to strend for length of run */\n\n var _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nfunction deflate_huff(s, flush) {\n var bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = trees._tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n}\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nvar configuration_table;\n\nconfiguration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nfunction lm_init(s) {\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n}\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);\n this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);\n this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new utils.Buf16(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nfunction deflateResetKeep(strm) {\n var s;\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n trees._tr_init(s);\n return Z_OK;\n}\n\n\nfunction deflateReset(strm) {\n var ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n}\n\n\nfunction deflateSetHeader(strm, head) {\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n}\n\n\nfunction deflateInit2(strm, level, method, windowBits, memLevel, strategy) {\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n var wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n var s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new utils.Buf8(s.w_size * 2);\n s.head = new utils.Buf16(s.hash_size);\n s.prev = new utils.Buf16(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new utils.Buf8(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n}\n\nfunction deflateInit(strm, level) {\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n}\n\n\nfunction deflate(strm, flush) {\n var old_flush, s;\n var beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n var level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n trees._tr_align(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n trees._tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n}\n\nfunction deflateEnd(strm) {\n var status;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n}\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nfunction deflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var s;\n var str, n;\n var wrap;\n var avail;\n var next;\n var input;\n var tmpDict;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n s = strm.state;\n wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n tmpDict = new utils.Buf8(s.w_size);\n utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n avail = strm.avail_in;\n next = strm.next_in;\n input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n str = s.strstart;\n n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n}\n\n\nexports.deflateInit = deflateInit;\nexports.deflateInit2 = deflateInit2;\nexports.deflateReset = deflateReset;\nexports.deflateResetKeep = deflateResetKeep;\nexports.deflateSetHeader = deflateSetHeader;\nexports.deflate = deflate;\nexports.deflateEnd = deflateEnd;\nexports.deflateSetDictionary = deflateSetDictionary;\nexports.deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nexports.deflateBound = deflateBound;\nexports.deflateCopy = deflateCopy;\nexports.deflateParams = deflateParams;\nexports.deflatePending = deflatePending;\nexports.deflatePrime = deflatePrime;\nexports.deflateTune = deflateTune;\n*/\n","// String encode/decode helpers\n'use strict';\n\n\nvar utils = require('./common');\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nvar STR_APPLY_OK = true;\nvar STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new utils.Buf8(256);\nfor (var q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nexports.string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new utils.Buf8(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper (used in 2 places)\nfunction buf2binstring(buf, len) {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {\n return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));\n }\n }\n\n var result = '';\n for (var i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n}\n\n\n// Convert byte array to binary string\nexports.buf2binstring = function (buf) {\n return buf2binstring(buf, buf.length);\n};\n\n\n// Convert binary string (typed, when possible)\nexports.binstring2buf = function (str) {\n var buf = new utils.Buf8(str.length);\n for (var i = 0, len = buf.length; i < len; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n};\n\n\n// convert array to string\nexports.buf2string = function (buf, max) {\n var i, out, c, c_len;\n var len = max || buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nexports.utf8border = function (buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nmodule.exports = ZStream;\n","'use strict';\n\n\nvar zlib_deflate = require('./zlib/deflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\n\nvar toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nvar Z_NO_FLUSH = 0;\nvar Z_FINISH = 4;\n\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_SYNC_FLUSH = 2;\n\nvar Z_DEFAULT_COMPRESSION = -1;\n\nvar Z_DEFAULT_STRATEGY = 0;\n\nvar Z_DEFLATED = 8;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array|Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Deflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n if (!(this instanceof Deflate)) return new Deflate(options);\n\n this.options = utils.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_deflate.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n if (opt.header) {\n zlib_deflate.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n var dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = zlib_deflate.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK) {\n throw new Error(msg[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the compression context.\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * array format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var status, _mode;\n\n if (this.ended) { return false; }\n\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n status = zlib_deflate.deflate(strm, _mode); /* no bad return value */\n\n if (status !== Z_STREAM_END && status !== Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {\n if (this.options.to === 'string') {\n this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);\n\n // Finalize on the last chunk.\n if (_mode === Z_FINISH) {\n status = zlib_deflate.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === Z_SYNC_FLUSH) {\n this.onEnd(Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be \"binary string\"\n * (each char code [0..255])\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate(input, options) {\n var deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || msg[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate(input, options);\n}\n\n\nexports.Deflate = Deflate;\nexports.deflate = deflate;\nexports.deflateRaw = deflateRaw;\nexports.gzip = gzip;\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nmodule.exports = function inflate_fast(strm, start) {\n var state;\n var _in; /* local strm.input */\n var last; /* have enough input while in < last */\n var _out; /* local strm.output */\n var beg; /* inflate()'s initial strm.output */\n var end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n var dmax; /* maximum distance from zlib header */\n//#endif\n var wsize; /* window size or zero if not using window */\n var whave; /* valid bytes in the window */\n var wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n var s_window; /* allocated sliding window, if wsize != 0 */\n var hold; /* local strm.hold */\n var bits; /* local strm.bits */\n var lcode; /* local strm.lencode */\n var dcode; /* local strm.distcode */\n var lmask; /* mask for first level of length codes */\n var dmask; /* mask for first level of distance codes */\n var here; /* retrieved table entry */\n var op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n var len; /* match length, unused bytes */\n var dist; /* match distance */\n var from; /* where to copy match from */\n var from_source;\n\n\n var input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\n\nvar MAXBITS = 15;\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\nvar lbase = [ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n];\n\nvar lext = [ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n];\n\nvar dbase = [ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n];\n\nvar dext = [ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n];\n\nmodule.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)\n{\n var bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n var len = 0; /* a code's length in bits */\n var sym = 0; /* index of code symbols */\n var min = 0, max = 0; /* minimum and maximum code lengths */\n var root = 0; /* number of index bits for root table */\n var curr = 0; /* number of index bits for current table */\n var drop = 0; /* code bits to drop for sub-table */\n var left = 0; /* number of prefix codes available */\n var used = 0; /* code entries in table used */\n var huff = 0; /* Huffman code */\n var incr; /* for incrementing code, index */\n var fill; /* index for replicating entries */\n var low; /* low bits for current root entry */\n var mask; /* mask for low root bits */\n var next; /* next available space in table */\n var base = null; /* base value table to use */\n var base_index = 0;\n// var shoextra; /* extra bits table to use */\n var end; /* use base and extra for symbol > end */\n var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n var extra = null;\n var extra_index = 0;\n\n var here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar utils = require('../utils/common');\nvar adler32 = require('./adler32');\nvar crc32 = require('./crc32');\nvar inflate_fast = require('./inffast');\nvar inflate_table = require('./inftrees');\n\nvar CODES = 0;\nvar LENS = 1;\nvar DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n/* Allowed flush values; see deflate() and inflate() below for details */\n//var Z_NO_FLUSH = 0;\n//var Z_PARTIAL_FLUSH = 1;\n//var Z_SYNC_FLUSH = 2;\n//var Z_FULL_FLUSH = 3;\nvar Z_FINISH = 4;\nvar Z_BLOCK = 5;\nvar Z_TREES = 6;\n\n\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\nvar Z_OK = 0;\nvar Z_STREAM_END = 1;\nvar Z_NEED_DICT = 2;\n//var Z_ERRNO = -1;\nvar Z_STREAM_ERROR = -2;\nvar Z_DATA_ERROR = -3;\nvar Z_MEM_ERROR = -4;\nvar Z_BUF_ERROR = -5;\n//var Z_VERSION_ERROR = -6;\n\n/* The deflate compression method */\nvar Z_DEFLATED = 8;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nvar HEAD = 1; /* i: waiting for magic header */\nvar FLAGS = 2; /* i: waiting for method and flags (gzip) */\nvar TIME = 3; /* i: waiting for modification time (gzip) */\nvar OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nvar EXLEN = 5; /* i: waiting for extra length (gzip) */\nvar EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nvar NAME = 7; /* i: waiting for end of file name (gzip) */\nvar COMMENT = 8; /* i: waiting for end of comment (gzip) */\nvar HCRC = 9; /* i: waiting for header crc (gzip) */\nvar DICTID = 10; /* i: waiting for dictionary check value */\nvar DICT = 11; /* waiting for inflateSetDictionary() call */\nvar TYPE = 12; /* i: waiting for type bits, including last-flag bit */\nvar TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nvar STORED = 14; /* i: waiting for stored size (length and complement) */\nvar COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nvar COPY = 16; /* i/o: waiting for input or output to copy stored block */\nvar TABLE = 17; /* i: waiting for dynamic block table lengths */\nvar LENLENS = 18; /* i: waiting for code length code lengths */\nvar CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nvar LEN_ = 20; /* i: same as LEN below, but only first time in */\nvar LEN = 21; /* i: waiting for length/lit/eob code */\nvar LENEXT = 22; /* i: waiting for length extra bits */\nvar DIST = 23; /* i: waiting for distance code */\nvar DISTEXT = 24; /* i: waiting for distance extra bits */\nvar MATCH = 25; /* o: waiting for output space to copy string */\nvar LIT = 26; /* o: waiting for output space to write literal */\nvar CHECK = 27; /* i: waiting for 32-bit check value */\nvar LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nvar DONE = 29; /* finished check, done -- remain here until reset */\nvar BAD = 30; /* got a data error -- remain here until reset */\nvar MEM = 31; /* got an inflate() memory error -- remain here until reset */\nvar SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nvar ENOUGH_LENS = 852;\nvar ENOUGH_DISTS = 592;\n//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nvar MAX_WBITS = 15;\n/* 32K LZ77 window */\nvar DEF_WBITS = MAX_WBITS;\n\n\nfunction zswap32(q) {\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n}\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new utils.Buf16(320); /* temporary storage for code lengths */\n this.work = new utils.Buf16(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\nfunction inflateResetKeep(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);\n state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nfunction inflateReset(strm) {\n var state;\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n}\n\nfunction inflateReset2(strm, windowBits) {\n var wrap;\n var state;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n}\n\nfunction inflateInit2(strm, windowBits) {\n var ret;\n var state;\n\n if (!strm) { return Z_STREAM_ERROR; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n}\n\nfunction inflateInit(strm) {\n return inflateInit2(strm, DEF_WBITS);\n}\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nvar virgin = true;\n\nvar lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\nfunction fixedtables(state) {\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n var sym;\n\n lenfix = new utils.Buf32(512);\n distfix = new utils.Buf32(32);\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n}\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nfunction updatewindow(strm, src, end, copy) {\n var dist;\n var state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new utils.Buf8(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n utils.arraySet(state.window, src, end - copy, dist, state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n utils.arraySet(state.window, src, end - copy, copy, 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n}\n\nfunction inflate(strm, flush) {\n var state;\n var input, output; // input/output buffers\n var next; /* next input INDEX */\n var put; /* next output INDEX */\n var have, left; /* available input and output */\n var hold; /* bit buffer */\n var bits; /* bits in bit buffer */\n var _in, _out; /* save starting available input and output */\n var copy; /* number of stored or match bytes to copy */\n var from; /* where to copy match bytes from */\n var from_source;\n var here = 0; /* current decoding table entry */\n var here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //var last; /* parent table entry */\n var last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n var len; /* length to copy for repeats, bits to drop */\n var ret; /* return code */\n var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */\n var opts;\n\n var n; // temporary var for NEED_BITS\n\n var order = /* permutation of code lengths */\n [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n state.dmax = 1 << len;\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Array(state.head.extra_len);\n }\n utils.arraySet(\n state.head.extra,\n input,\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n copy,\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n utils.arraySet(output, input, next, copy, put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inflate_fast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n}\n\nfunction inflateEnd(strm) {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR;\n }\n\n var state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK;\n}\n\nfunction inflateGetHeader(strm, head) {\n var state;\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK;\n}\n\nfunction inflateSetDictionary(strm, dictionary) {\n var dictLength = dictionary.length;\n\n var state;\n var dictid;\n var ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nexports.inflateReset = inflateReset;\nexports.inflateReset2 = inflateReset2;\nexports.inflateResetKeep = inflateResetKeep;\nexports.inflateInit = inflateInit;\nexports.inflateInit2 = inflateInit2;\nexports.inflate = inflate;\nexports.inflateEnd = inflateEnd;\nexports.inflateGetHeader = inflateGetHeader;\nexports.inflateSetDictionary = inflateSetDictionary;\nexports.inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nexports.inflateCopy = inflateCopy;\nexports.inflateGetDictionary = inflateGetDictionary;\nexports.inflateMark = inflateMark;\nexports.inflatePrime = inflatePrime;\nexports.inflateSync = inflateSync;\nexports.inflateSyncPoint = inflateSyncPoint;\nexports.inflateUndermine = inflateUndermine;\n*/\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nmodule.exports = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n //Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n","'use strict';\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nmodule.exports = GZheader;\n","'use strict';\n\n\nvar zlib_inflate = require('./zlib/inflate');\nvar utils = require('./utils/common');\nvar strings = require('./utils/strings');\nvar c = require('./zlib/constants');\nvar msg = require('./zlib/messages');\nvar ZStream = require('./zlib/zstream');\nvar GZheader = require('./zlib/gzheader');\n\nvar toString = Object.prototype.toString;\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you\n * push a chunk with explicit flush (call [[Inflate#push]] with\n * `Z_SYNC_FLUSH` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * var inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n if (!(this instanceof Inflate)) return new Inflate(options);\n\n this.options = utils.assign({\n chunkSize: 16384,\n windowBits: 0,\n to: ''\n }, options || {});\n\n var opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new ZStream();\n this.strm.avail_out = 0;\n\n var status = zlib_inflate.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n\n this.header = new GZheader();\n\n zlib_inflate.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== c.Z_OK) {\n throw new Error(msg[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, mode]) -> Boolean\n * - data (Uint8Array|Array|ArrayBuffer|String): input data\n * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. The last data block must have\n * mode Z_FINISH (or `true`). That will flush internal pending buffers and call\n * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you\n * can use mode Z_SYNC_FLUSH, keeping the decompression context.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * We strongly recommend to use `Uint8Array` on input for best speed (output\n * format is detected automatically). Also, don't skip last param and always\n * use the same type in your code (boolean or number). That will improve JS speed.\n *\n * For regular `Array`-s make sure all elements are [0..255].\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, mode) {\n var strm = this.strm;\n var chunkSize = this.options.chunkSize;\n var dictionary = this.options.dictionary;\n var status, _mode;\n var next_out_utf8, tail, utf8str;\n\n // Flag to properly process Z_BUF_ERROR on testing inflate call\n // when we check that all output data was flushed.\n var allowBufError = false;\n\n if (this.ended) { return false; }\n _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);\n\n // Convert data if needed\n if (typeof data === 'string') {\n // Only binary strings can be decompressed on practice\n strm.input = strings.binstring2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n do {\n if (strm.avail_out === 0) {\n strm.output = new utils.Buf8(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */\n\n if (status === c.Z_NEED_DICT && dictionary) {\n status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);\n }\n\n if (status === c.Z_BUF_ERROR && allowBufError === true) {\n status = c.Z_OK;\n allowBufError = false;\n }\n\n if (status !== c.Z_STREAM_END && status !== c.Z_OK) {\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {\n\n if (this.options.to === 'string') {\n\n next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n tail = strm.next_out - next_out_utf8;\n utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }\n\n this.onData(utf8str);\n\n } else {\n this.onData(utils.shrinkBuf(strm.output, strm.next_out));\n }\n }\n }\n\n // When no more input data, we should check that internal inflate buffers\n // are flushed. The only way to do it when avail_out = 0 - run one more\n // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.\n // Here we set flag to process this error properly.\n //\n // NOTE. Deflate does not return error in this case and does not needs such\n // logic.\n if (strm.avail_in === 0 && strm.avail_out === 0) {\n allowBufError = true;\n }\n\n } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);\n\n if (status === c.Z_STREAM_END) {\n _mode = c.Z_FINISH;\n }\n\n // Finalize on the last chunk.\n if (_mode === c.Z_FINISH) {\n status = zlib_inflate.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === c.Z_OK;\n }\n\n // callback interim results if Z_SYNC_FLUSH.\n if (_mode === c.Z_SYNC_FLUSH) {\n this.onEnd(c.Z_OK);\n strm.avail_out = 0;\n return true;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|Array|String): output data. Type of array depends\n * on js engine support. When string output requested, each chunk\n * will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)\n * or if an error happened. By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === c.Z_OK) {\n if (this.options.to === 'string') {\n // Glue & convert here, until we teach pako to send\n // utf8 aligned strings to onData\n this.result = this.chunks.join('');\n } else {\n this.result = utils.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * var pako = require('pako')\n * , input = pako.deflate([1,2,3,4,5,6,7,8,9])\n * , output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate(input, options) {\n var inflator = new Inflate(options);\n\n inflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) { throw inflator.msg || msg[inflator.err]; }\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|Array|String\n * - data (Uint8Array|Array|String): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nexports.Inflate = Inflate;\nexports.inflate = inflate;\nexports.inflateRaw = inflateRaw;\nexports.ungzip = inflate;\n","// Top level file is just a mixin of submodules & constants\n'use strict';\n\nvar assign = require('./lib/utils/common').assign;\n\nvar deflate = require('./lib/deflate');\nvar inflate = require('./lib/inflate');\nvar constants = require('./lib/zlib/constants');\n\nvar pako = {};\n\nassign(pako, deflate, inflate, constants);\n\nmodule.exports = pako;\n","\r\n\r\n\r\n\r\n;(function(){\r\n\tvar UTIF = {};\r\n\t\r\n\t// Make available for import by `require()`\r\n\tif (typeof module == \"object\") {module.exports = UTIF;}\r\n\telse {self.UTIF = UTIF;}\r\n\t\r\n\tvar pako = (typeof require === \"function\") ? require(\"pako\") : self.pako;\r\n\t\r\n\tfunction log() { if (typeof process==\"undefined\" || process.env.NODE_ENV==\"development\") console.log.apply(console, arguments); }\r\n\t\r\n\t(function(UTIF, pako){\r\n\t\t\r\n\t// Following lines add a JPEG decoder to UTIF.JpegDecoder\r\n\t(function(){\"use strict\";var W=function a1(){function W(p){this.message=\"JPEG error: \"+p}W.prototype=new Error;W.prototype.name=\"JpegError\";W.constructor=W;return W}(),ak=function ag(){var p=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,ac=799,ah=3406,ao=2276,ar=1567,ai=3784,s=5793,ad=2896;function ak(Q){if(Q==null)Q={};if(Q.w==null)Q.w=-1;this.V=Q.n;this.N=Q.w}function a5(Q,h){var f=0,G=[],n,E,a=16,F;while(a>0&&!Q[a-1]){a--}G.push({children:[],index:0});var C=G[0];for(n=0;n0){C=G.pop()}C.index++;G.push(C);while(G.length<=n){G.push(F={children:[],index:0});C.children[C.index]=F.children;C=F}f++}if(n+10){V--;return J>>V&1}J=Q[h++];if(J===255){var I=Q[h++];if(I){if(I===220&&d){h+=2;var l=Z(Q,h);h+=2;if(l>0&&l!==f.s){throw new DNLMarkerError(\"Found DNL marker (0xFFDC) while parsing scan data\",l)}}else if(I===217){if(d){var M=q*8;\r\n\tif(M>0&&M>>7}function u(I){var l=I;while(!0){l=l[Y()];switch(typeof l){case\"number\":return l;case\"object\":continue}throw new W(\"invalid huffman sequence\")}}function m(I){var e=0;while(I>0){e=e<<1|Y();I--}return e}function j(I){if(I===1){return Y()===1?1:-1}var e=m(I);if(e>=1<>4;if(i===0){if(A<15){break}N+=16;continue}N+=A;var o=p[N];X.D[I+o]=j(i);N++}}function $(X,I){var l=u(X.J),M=l===0?0:j(l)<0){r--;return}var N=E,l=a;while(N<=l){var M=u(X.i),S=M&15,i=M>>4;if(S===0){if(i<15){r=m(i)+(1<>4;if(S===0){if(M<15){r=m(M)+(1<0){for(O=0;O0?\"unexpected\":\"excessive\";h=k.offset}if(k.M>=65488&&k.M<=65495){h+=2}else{break}}return h-z}function al(Q,h,f){var G=Q.$,n=Q.D,E,a,C,F,d,T,U,z,J,V,Y,u,m,j,v,$,b;if(!G){throw new W(\"missing required Quantization Table.\")}for(var r=0;r<64;r+=8){J=n[h+r];V=n[h+r+1];Y=n[h+r+2];u=n[h+r+3];m=n[h+r+4];j=n[h+r+5];v=n[h+r+6];$=n[h+r+7];J*=G[r];if((V|Y|u|m|j|v|$)===0){b=s*J+512>>10;f[r]=b;f[r+1]=b;f[r+2]=b;f[r+3]=b;f[r+4]=b;f[r+5]=b;f[r+6]=b;f[r+7]=b;continue}V*=G[r+1];Y*=G[r+2];u*=G[r+3];m*=G[r+4];j*=G[r+5];v*=G[r+6];$*=G[r+7];E=s*J+128>>8;a=s*m+128>>8;C=Y;F=v;d=ad*(V-$)+128>>8;z=ad*(V+$)+128>>8;\r\n\tT=u<<4;U=j<<4;E=E+a+1>>1;a=E-a;b=C*ai+F*ar+128>>8;C=C*ar-F*ai+128>>8;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;b=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;f[r]=E+z;f[r+7]=E-z;f[r+1]=a+U;f[r+6]=a-U;f[r+2]=C+T;f[r+5]=C-T;f[r+3]=F+d;f[r+4]=F-d}for(var P=0;P<8;++P){J=f[P];V=f[P+8];Y=f[P+16];u=f[P+24];m=f[P+32];j=f[P+40];v=f[P+48];$=f[P+56];if((V|Y|u|m|j|v|$)===0){b=s*J+8192>>14;if(b<-2040){b=0}else if(b>=2024){b=255}else{b=b+2056>>4}n[h+P]=b;n[h+P+8]=b;n[h+P+16]=b;n[h+P+24]=b;n[h+P+32]=b;n[h+P+40]=b;n[h+P+48]=b;n[h+P+56]=b;continue}E=s*J+2048>>12;a=s*m+2048>>12;C=Y;F=v;d=ad*(V-$)+2048>>12;z=ad*(V+$)+2048>>12;T=u;U=j;E=(E+a+1>>1)+4112;a=E-a;b=C*ai+F*ar+2048>>12;C=C*ar-F*ai+2048>>12;F=b;d=d+U+1>>1;U=d-U;z=z+T+1>>1;T=z-T;E=E+F+1>>1;F=E-F;a=a+C+1>>1;C=a-C;b=d*ao+z*ah+2048>>12;d=d*ah-z*ao+2048>>12;z=b;\r\n\tb=T*ac+U*t+2048>>12;T=T*t-U*ac+2048>>12;U=b;J=E+z;$=E-z;V=a+U;v=a-U;Y=C+T;j=C-T;u=F+d;m=F-d;if(J<16){J=0}else if(J>=4080){J=255}else{J>>=4}if(V<16){V=0}else if(V>=4080){V=255}else{V>>=4}if(Y<16){Y=0}else if(Y>=4080){Y=255}else{Y>>=4}if(u<16){u=0}else if(u>=4080){u=255}else{u>>=4}if(m<16){m=0}else if(m>=4080){m=255}else{m>>=4}if(j<16){j=0}else if(j>=4080){j=255}else{j>>=4}if(v<16){v=0}else if(v>=4080){v=255}else{v>>=4}if($<16){$=0}else if($>=4080){$=255}else{$>>=4}n[h+P]=J;\r\n\tn[h+P+8]=V;n[h+P+16]=Y;n[h+P+24]=u;n[h+P+32]=m;n[h+P+40]=j;n[h+P+48]=v;n[h+P+56]=$}}function a0(Q,h){var f=h.P,G=h.c,n=new Int16Array(64);for(var E=0;E=G){return null}var E=Z(Q,h);if(E>=65472&&E<=65534){return{u:null,M:E,offset:h}}var a=Z(Q,n);while(!(a>=65472&&a<=65534)){if(++n>=G){return null}a=Z(Q,n)}return{u:E.toString(16),M:a,offset:n}}ak.prototype={parse(Q,h){if(h==null)h={};\r\n\tvar f=h.F,E=0,a=null,C=null,F,d,T=0;function G(){var o=Z(Q,E);E+=2;var B=E+o-2,V=an(Q,B,E);if(V&&V.u){B=V.offset}var ab=Q.subarray(E,B);E+=ab.length;return ab}function n(F){var o=Math.ceil(F.o/8/F.X),B=Math.ceil(F.s/8/F.B);for(var Y=0;Y>4===0){for(u=0;u<64;u++){b=p[u];P[b]=Q[E++]}}else if(r>>4===1){for(u=0;u<64;u++){b=p[u];P[b]=Z(Q,E);E+=2}}else{throw new W(\"DQT - invalid table spec\")}U[r&15]=P}break;case 65472:case 65473:case 65474:if(F){throw new W(\"Only single frame JPEGs supported\")}E+=2;F={};F.G=V===65473;F.Z=V===65474;F.precision=Q[E++];var D=Z(Q,E),a4,q=0,H=0;E+=2;F.s=f||D;F.o=Z(Q,E);E+=2;F.W=[];F._={};var a8=Q[E++];for(Y=0;Y>4,y=Q[E+1]&15;if(q>4===0?J:z)[_&15]=a5(N,K)}break;case 65501:E+=2;d=Z(Q,E);E+=2;break;case 65498:var x=++T===1&&!f,R;E+=2;var k=Q[E++],g=[];for(Y=0;Y>4];R.i=z[a6&15];g.push(R)}var I=Q[E++],l=Q[E++],M=Q[E++];try{var S=a7(Q,E,F,g,d,I,l,M>>4,M&15,x);E+=S}catch(ex){if(ex instanceof DNLMarkerError){return this.parse(Q,{F:ex.s})}else if(ex instanceof EOIMarkerError){break markerLoop}throw ex}break;case 65500:E+=4;break;case 65535:if(Q[E]!==255){E--}break;default:var i=an(Q,E-2,E-3);if(i&&i.u){E=i.offset;break}if(E>=Q.length-1){break markerLoop}throw new W(\"JpegImage.parse - unknown marker: \"+V.toString(16))}V=Z(Q,E);E+=2}this.width=F.o;this.height=F.s;this.g=a;this.b=C;this.W=[];for(Y=0;Y>8)+P[J+1]}}}return v},get f(){if(this.b){return!!this.b.a}if(this.p===3){if(this.N===0){return!1}else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66){return!1}return!0}if(this.N===1){return!0}return!1},z:function aj(Q){var h,f,G;\r\n\tfor(var n=0,E=Q.length;n4){throw new W(\"Unsupported color mode\")}var E=this.Y(h,f,n);if(this.p===1&&G){var a=E.length,C=new Uint8ClampedArray(a*3),F=0;for(var d=0;d>24}function Z(p,t){return p[t]<<8|p[t+1]}function am(p,t){return(p[t]<<24|p[t+1]<<16|p[t+2]<<8|p[t+3])>>>0}UTIF.JpegDecoder=ak}());\r\n\t\r\n\t//UTIF.JpegDecoder = PDFJS.JpegImage;\r\n\t\r\n\t\r\n\tUTIF.encodeImage = function(rgba, w, h, metadata)\r\n\t{\r\n\t\tvar idf = { \"t256\":[w], \"t257\":[h], \"t258\":[8,8,8,8], \"t259\":[1], \"t262\":[2], \"t273\":[1000], // strips offset\r\n\t\t\t\t\t\"t277\":[4], \"t278\":[h], /* rows per strip */ \"t279\":[w*h*4], // strip byte counts\r\n\t\t\t\t\t\"t282\":[[72,1]], \"t283\":[[72,1]], \"t284\":[1], \"t286\":[[0,1]], \"t287\":[[0,1]], \"t296\":[1], \"t305\": [\"Photopea (UTIF.js)\"], \"t338\":[1]\r\n\t\t\t};\r\n\t\tif (metadata) for (var i in metadata) idf[i] = metadata[i];\r\n\t\t\r\n\t\tvar prfx = new Uint8Array(UTIF.encode([idf]));\r\n\t\tvar img = new Uint8Array(rgba);\r\n\t\tvar data = new Uint8Array(1000+w*h*4);\r\n\t\tfor(var i=0; i probably not an image\r\n\t\timg.isLE = id==\"II\";\r\n\t\timg.width = img[\"t256\"][0]; //delete img[\"t256\"];\r\n\t\timg.height = img[\"t257\"][0]; //delete img[\"t257\"];\r\n\t\r\n\t\tvar cmpr = img[\"t259\"] ? img[\"t259\"][0] : 1; //delete img[\"t259\"];\r\n\t\tvar fo = img[\"t266\"] ? img[\"t266\"][0] : 1; //delete img[\"t266\"];\r\n\t\tif(img[\"t284\"] && img[\"t284\"][0]==2) log(\"PlanarConfiguration 2 should not be used!\");\r\n\t\tif(cmpr==7 && img[\"t258\"] && img[\"t258\"].length>3) img[\"t258\"]=img[\"t258\"].slice(0,3);\r\n\t\r\n\t\tvar spp = img[\"t277\"]?img[\"t277\"][0]:1;\r\n\t\tvar bps = img[\"t258\"]?img[\"t258\"][0]:1;\r\n\t\tvar bipp = bps*spp; // bits per pixel\r\n\t\t/*\r\n\t\tvar bipp; // bits per pixel\r\n\t\tif(img[\"t258\"]) bipp = Math.min(32,img[\"t258\"][0])*img[\"t258\"].length;\r\n\t\telse bipp = (img[\"t277\"]?img[\"t277\"][0]:1); \r\n\t\t*/\r\n\t\t// Some .NEF files have t258==14, even though they use 16 bits per pixel\r\n\t\tif(cmpr==1 && img[\"t279\"]!=null && img[\"t278\"] && img[\"t262\"][0]==32803) {\r\n\t\t\tbipp = Math.round((img[\"t279\"][0]*8)/(img.width*img[\"t278\"][0]));\r\n\t\t}\r\n\t\tif(img[\"t50885\"] && img[\"t50885\"][0]==4) bipp = img[\"t258\"][0]*3; // RAW_CANON_40D_SRAW_V103.CR2\r\n\t\tvar bipl = Math.ceil(img.width*bipp/8)*8;\r\n\t\tvar soff = img[\"t273\"]; if(soff==null || img[\"t322\"]) soff = img[\"t324\"];\r\n\t\tvar bcnt = img[\"t279\"]; if(cmpr==1 && soff.length==1) bcnt = [img.height*(bipl>>>3)]; if(bcnt==null || img[\"t322\"]) bcnt = img[\"t325\"];\r\n\t\t//bcnt[0] = Math.min(bcnt[0], data.length); // Hasselblad, \"RAW_HASSELBLAD_H3D39II.3FR\"\r\n\t\tvar bytes = new Uint8Array(img.height*(bipl>>>3)), bilen = 0;\r\n\t\r\n\t\tif(img[\"t322\"]!=null) // tiled\r\n\t\t{\r\n\t\t\tvar tw = img[\"t322\"][0], th = img[\"t323\"][0];\r\n\t\t\tvar tx = Math.floor((img.width + tw - 1) / tw);\r\n\t\t\tvar ty = Math.floor((img.height + th - 1) / th);\r\n\t\t\tvar tbuff = new Uint8Array(Math.ceil(tw*th*bipp/8)|0);\r\n\t\t\tconsole.log(\"====\", tx,ty);\r\n\t\t\tfor(var y=0; y>>3, bpl = Math.ceil(bps*noc*w/8);\r\n\t\t\r\n\t\t// convert to Little Endian /*\r\n\t\tif(bps==16 && !img.isLE && img[\"t33422\"]==null) // not DNG\r\n\t\t\tfor(var y=0; y>>8)&255; \r\n\t\t\t\t}\r\n\t\t\t\telse if(noc==3) for(var j= 3; j> 3 ^ 0x3ff0;\r\n\t\t\t\t\t\t\treturn (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~((-1) << bits);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t// Raw Format 6\r\n\t\t\t\t\tfunction getBufferDataRW6(i) {\r\n\t\t\t\t\t\treturn buffer[vpos + 15 - i];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfunction readPageRW6() {\r\n\t\t\t\t\t\tbytes[0] = (getBufferDataRW6(0) << 6) | (getBufferDataRW6(1) >> 2); // 14 bit\r\n\t\t\t\t\t\tbytes[1] = (((getBufferDataRW6(1) & 0x3) << 12) | (getBufferDataRW6(2) << 4) | (getBufferDataRW6(3) >> 4)) & 0x3fff;\r\n\t\t\t\t\t\tbytes[2] = (getBufferDataRW6(3) >> 2) & 0x3;\r\n\t\t\t\t\t\tbytes[3] = ((getBufferDataRW6(3) & 0x3) << 8) | getBufferDataRW6(4);\r\n\t\t\t\t\t\tbytes[4] = (getBufferDataRW6(5) << 2) | (getBufferDataRW6(6) >> 6);\r\n\t\t\t\t\t\tbytes[5] = ((getBufferDataRW6(6) & 0x3f) << 4) | (getBufferDataRW6(7) >> 4);\r\n\t\t\t\t\t\tbytes[6] = (getBufferDataRW6(7) >> 2) & 0x3;\r\n\t\t\t\t\t\tbytes[7] = ((getBufferDataRW6(7) & 0x3) << 8) | getBufferDataRW6(8);\r\n\t\t\t\t\t\tbytes[8] = ((getBufferDataRW6(9) << 2) & 0x3fc) | (getBufferDataRW6(10) >> 6);\r\n\t\t\t\t\t\tbytes[9] = ((getBufferDataRW6(10) << 4) | (getBufferDataRW6(11) >> 4)) & 0x3ff;\r\n\t\t\t\t\t\tbytes[10] = (getBufferDataRW6(11) >> 2) & 0x3;\r\n\t\t\t\t\t\tbytes[11] = ((getBufferDataRW6(11) & 0x3) << 8) | getBufferDataRW6(12);\r\n\t\t\t\t\t\tbytes[12] = (((getBufferDataRW6(13) << 2) & 0x3fc) | getBufferDataRW6(14) >> 6) & 0x3ff;\r\n\t\t\t\t\t\tbytes[13] = ((getBufferDataRW6(14) << 4) | (getBufferDataRW6(15) >> 4)) & 0x3ff;\r\n\t\t\t\t\t\tvpos += 16;\r\n\t\t\t\t\t\tbyte = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfunction readPageRw6_bps12() {\r\n\t\t\t\t\t\tbytes[0] = (getBufferDataRW6(0) << 4) | (getBufferDataRW6(1) >> 4);\r\n\t\t\t\t\t\tbytes[1] = (((getBufferDataRW6(1) & 0xf) << 8) | (getBufferDataRW6(2))) & 0xfff;\r\n\t\t\t\t\t\tbytes[2] = (getBufferDataRW6(3) >> 6) & 0x3;\r\n\t\t\t\t\t\tbytes[3] = ((getBufferDataRW6(3) & 0x3f) << 2) | (getBufferDataRW6(4) >> 6);\r\n\t\t\t\t\t\tbytes[4] = ((getBufferDataRW6(4) & 0x3f) << 2) | (getBufferDataRW6(5) >> 6);\r\n\t\t\t\t\t\tbytes[5] = ((getBufferDataRW6(5) & 0x3f) << 2) | (getBufferDataRW6(6) >> 6);\r\n\t\t\t\t\t\tbytes[6] = (getBufferDataRW6(6) >> 4) & 0x3;\r\n\t\t\t\t\t\tbytes[7] = ((getBufferDataRW6(6) & 0xf) << 4) | (getBufferDataRW6(7) >> 4);\r\n\t\t\t\t\t\tbytes[8] = ((getBufferDataRW6(7) & 0xf) << 4) | (getBufferDataRW6(8) >> 4);\r\n\t\t\t\t\t\tbytes[9] = ((getBufferDataRW6(8) & 0xf) << 4) | (getBufferDataRW6(9) >> 4);\r\n\t\t\t\t\t\tbytes[10] = (getBufferDataRW6(9) >> 2) & 0x3;\r\n\t\t\t\t\t\tbytes[11] = ((getBufferDataRW6(9) & 0x3) << 6) | (getBufferDataRW6(10) >> 2);\r\n\t\t\t\t\t\tbytes[12] = ((getBufferDataRW6(10) & 0x3) << 6) | (getBufferDataRW6(11) >> 2);\r\n\t\t\t\t\t\tbytes[13] = ((getBufferDataRW6(11) & 0x3) << 6) | (getBufferDataRW6(12) >> 2);\r\n\t\t\t\t\t\tbytes[14] = getBufferDataRW6(12) & 0x3;\r\n\t\t\t\t\t\tbytes[15] = getBufferDataRW6(13);\r\n\t\t\t\t\t\tbytes[16] = getBufferDataRW6(14);\r\n\t\t\t\t\t\tbytes[17] = getBufferDataRW6(15);\r\n\t\r\n\t\t\t\t\t\tvpos += 16;\r\n\t\t\t\t\t\tbyte = 0; \r\n\t\t\t\t\t}\r\n\t\t\t\t\t// Main loop\r\n\t\t\t\t\tfunction resetPredNonzeros(){\r\n\t\t\t\t\t\tpred[0]=0; pred[1]=0;\r\n\t\t\t\t\t\tnonz[0]=0; nonz[1]=0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (RW2_Format == 7) {\r\n\t\t\t\t\t\tthrow RW2_Format;\r\n\t\r\n\t\t\t\t\t\t// Skatch of version 7 \r\n\t\t\t\t\t\t/*\r\n\t\t\t\t\t\tvar pixels_per_block = bitsPerSample == 14 ? 9 : 10;\r\n\t\t\t\t\t\t\trowbytes = 0|(rawWidth / pixels_per_block * 16);\r\n\t\t\t\t\t\tfor (row = 0; row < rawHeight - 15; row += 16) {\r\n\t\t\t\t\t\t\tvar rowstoread = Math.min(16, rawHeight - row);\r\n\t\t\t\t\t\t\tvar readlen = rowbytes*rowstoread;\r\n\t\t\t\t\t\t\tbuffer = new Uint8Array(image.slice(bidx, bidx+readlen));\r\n\t\t\t\t\t\t\tvpos = 0;\r\n\t\t\t\t\t\t\tbidx += readlen; \r\n\t\t\t\t\t\t\ti = 0;\r\n\t\t\t\t\t\t\tfor (crow = 0; crow < rowstoread; crow++) {\r\n\t\t\t\t\t\t\t\tidx = (row + crow) * rawWidth;\r\n\t\t\t\t\t\t\t\tfor (col = 0; col <= rawWidth - pixels_per_block; col += pixels_per_block) {\r\n\t\t\t\t\t\t\t\t\tfor(j=0; j < pixels_per_block; j++) bytes[j] = buffer[i++];\r\n\t\t\t\t\t\t\t\t\tif (bitsPerSample == 12) {\r\n\t\t\t\t\t\t\t\t\t\tresult[idx ] = ((bytes[1] & 0xF) << 8) + bytes[0];\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 1] = 16 * bytes[2] + (bytes[1] >> 4);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 2] = ((bytes[4] & 0xF) << 8) + bytes[3];\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 3] = 16 * bytes[5] + (bytes[4] >> 4);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 4] = ((bytes[7] & 0xF) << 8) + bytes[6];\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 5] = 16 * bytes[8] + (bytes[7] >> 4);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 6] = ((bytes[10] & 0xF) << 8) + bytes[9];\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 7] = 16 * bytes[11] + (bytes[10] >> 4);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 8] = ((bytes[13] & 0xF) << 8) + bytes[12];\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 9] = 16 * bytes[14] + (bytes[13] >> 4);\r\n\t\t\t\t\t\t\t\t\t} else if (bitsPerSample == 14) {\r\n\t\t\t\t\t\t\t\t\t\tresult[idx] = bytes[0] + ((bytes[1] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 1] = (bytes[1] >> 6) + 4 * (bytes[2]) + ((bytes[3] & 0xF) << 10);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 2] = (bytes[3] >> 4) + 16 * (bytes[4]) + ((bytes[5] & 3) << 12);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 3] = ((bytes[5] & 0xFC) >> 2) + (bytes[6] << 6);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 4] = bytes[7] + ((bytes[8] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 5] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 0xF) << 10);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 6] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 7] = ((bytes[12] & 0xFC) >> 2) + (bytes[13] << 6);\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + 8] = bytes[14] + ((bytes[15] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t} \r\n\t\t\t\t\telse if(RW2_Format == 6) {\r\n\t\t\t\t\t\tvar is12bit = bitsPerSample == 12,\r\n\t\t\t\t\t\t\treadPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6,\r\n\t\t\t\t\t\t\tpixelsPerBlock = is12bit ? 14 : 11,\r\n\t\t\t\t\t\t\tpixelbase0 = is12bit ? 0x80 : 0x200,\r\n\t\t\t\t\t\t\tpixelbase_compare = is12bit ? 0x800 : 0x2000,\r\n\t\t\t\t\t\t\tspix_compare = is12bit ? 0x3fff : 0xffff,\r\n\t\t\t\t\t\t\tpixel_mask = is12bit ? 0xfff : 0x3fff,\r\n\t\t\t\t\t\t\tblocksperrow = rawWidth / pixelsPerBlock, \r\n\t\t\t\t\t\t\trowbytes = blocksperrow * 16,\r\n\t\t\t\t\t\t\tbufferSize = is12bit ? 18 : 14;\r\n\t\r\n\t\t\t\t\t\tfor (row = 0; row < rawHeight - 15; row += 16) {\r\n\t\t\t\t\t\t\tvar rowstoread = Math.min(16, rawHeight - row);\r\n\t\t\t\t\t\t\tvar readlen = rowbytes*rowstoread;\r\n\t\t\t\t\t\t\tbuffer = new Uint8Array(img_buffer, off+bidx, readlen);//new Uint8Array(image.slice(bidx, bidx+readlen));\r\n\t\t\t\t\t\t\tvpos = 0;\r\n\t\t\t\t\t\t\tbidx += readlen; \r\n\t\t\t\t\t\t\tfor (crow = 0, col = 0; crow < rowstoread; crow++, col = 0) {\r\n\t\t\t\t\t\t\t\tidx = (row + crow) * rawWidth;\r\n\t\t\t\t\t\t\t\tfor (var rblock = 0; rblock < blocksperrow; rblock++) {\r\n\t\t\t\t\t\t\t\t\treadPageRw6Fn();\r\n\t\t\t\t\t\t\t\t\tresetPredNonzeros();\r\n\t\t\t\t\t\t\t\t\tsh=0; pixel_base=0;\r\n\t\t\t\t\t\t\t\t\tfor (i = 0; i < pixelsPerBlock; i++){\r\n\t\t\t\t\t\t\t\t\t\tisOdd = i & 1;\r\n\t\t\t\t\t\t\t\t\t\tif (i % 3 == 2) {\r\n\t\t\t\t\t\t\t\t\t\t\tvar base = byte < bufferSize ? bytes[byte++] : 0;\r\n\t\t\t\t\t\t\t\t\t\t\tif (base == 3) base = 4;\r\n\t\t\t\t\t\t\t\t\t\t\tpixel_base = pixelbase0 << base;\r\n\t\t\t\t\t\t\t\t\t\t\tsh = 1 << base;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tvar epixel = byte < bufferSize ? bytes[byte++] : 0;\r\n\t\t\t\t\t\t\t\t\t\tif (pred[isOdd]) {\r\n\t\t\t\t\t\t\t\t\t\t\tepixel *= sh;\r\n\t\t\t\t\t\t\t\t\t\t\tif (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base)\r\n\t\t\t\t\t\t\t\t\t\t\t\tepixel += nonz[isOdd] - pixel_base;\r\n\t\t\t\t\t\t\t\t\t\t\tnonz[isOdd] = epixel;\r\n\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\tpred[isOdd] = epixel;\r\n\t\t\t\t\t\t\t\t\t\t\tif (epixel)\r\n\t\t\t\t\t\t\t\t\t\t\t\tnonz[isOdd] = epixel;\r\n\t\t\t\t\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\t\t\t\t\tepixel = nonz[isOdd];\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\tresult[idx + col++] = (epixel - 0xf) <= spix_compare ? (epixel - 0xf) & spix_compare : ((epixel + 0x7ffffff1) >> 0x1f) & pixel_mask;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} \r\n\t\t\t\t\telse if (RW2_Format == 5) { \r\n\t\t\t\t\t\tvar blockSize = bitsPerSample == 12 ? 10 : 9;\r\n\t\t\t\t\t\tfor (row = 0; row < rawHeight; row++) {\r\n\t\t\t\t\t\t\tfor (col = 0; col < rawWidth; col+=blockSize) {\r\n\t\t\t\t\t\t\t\tgetDataRaw(0);\r\n\t\t\t\t\t\t\t\t// Tuhle podminku pouziva i RW2_Format 7 \r\n\t\t\t\t\t\t\t\tif (bitsPerSample == 12) {\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[1] & 0xF) << 8) + bytes[0];\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = 16 * bytes[2] + (bytes[1] >> 4);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[4] & 0xF) << 8) + bytes[3];\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = 16 * bytes[5] + (bytes[4] >> 4);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[7] & 0xF) << 8) + bytes[6];\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = 16 * bytes[8] + (bytes[7] >> 4);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[10] & 0xF) << 8) + bytes[9];\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = 16 * bytes[11] + (bytes[10] >> 4);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[13] & 0xF) << 8) + bytes[12];\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = 16 * bytes[14] + (bytes[13] >> 4);\r\n\t\t\t\t\t\t\t\t} else if (bitsPerSample == 14) {\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = bytes[0] + ((bytes[1] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = (bytes[1] >> 6) + 4 * (bytes[2]) + ((bytes[3] & 0xF) << 10);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = (bytes[3] >> 4) + 16 * (bytes[4]) + ((bytes[5] & 3) << 12);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[5] & 0xFC) >> 2) + (bytes[6] << 6);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = bytes[7] + ((bytes[8] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 0xF) << 10);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = ((bytes[12] & 0xFC) >> 2) + (bytes[13] << 6);\r\n\t\t\t\t\t\t\t\t\tresult[idx++] = bytes[14] + ((bytes[15] & 0x3F) << 8);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//console.log(result[1000000 - 1])\r\n\t\t\t\t\t} else if(RW2_Format == 4) {\r\n\t\t\t\t\t\tfor (row = 0; row < rawHeight; row++){\r\n\t\t\t\t\t\t\tfor(col = 0; col < rawWidth; col++){\r\n\t\t\t\t\t\t\t\ti = col % 14;\r\n\t\t\t\t\t\t\t\tisOdd = i & 1;\r\n\t\t\t\t\t\t\t\tif (i==0) resetPredNonzeros();\r\n\t\t\t\t\t\t\t\tif (i%3 == 2) \r\n\t\t\t\t\t\t\t\t\tsh = 4 >> (3 - getDataRaw(2));\r\n\t\t\t\t\t\t\t\tif (nonz[isOdd]) {\r\n\t\t\t\t\t\t\t\t\tj = getDataRaw(8);\r\n\t\t\t\t\t\t\t\t\tif(j != 0){\r\n\t\t\t\t\t\t\t\t\t\tpred[isOdd] -= 0x80 << sh;\r\n\t\t\t\t\t\t\t\t\t\tif (pred[isOdd] < 0 || sh == 4) \r\n\t\t\t\t\t\t\t\t\t\t\tpred[isOdd] &= ~((-1) << sh);\r\n\t\t\t\t\t\t\t\t\t\tpred[isOdd] += j << sh;\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\tnonz[isOdd] = getDataRaw(8);\r\n\t\t\t\t\t\t\t\t\tif(nonz[isOdd] || i > 11)\r\n\t\t\t\t\t\t\t\t\t\tpred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tresult[idx++] = pred[col & 1];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} \r\n\t\t\t\t\telse throw RW2_Format;\r\n\t\t\t\t}\r\n\t\r\n\t\r\n\tUTIF.decode._decodeVC5 = function(){var x=[1,0,1,0,2,2,1,1,3,7,1,2,5,25,1,3,6,48,1,4,6,54,1,5,7,111,1,8,7,99,1,6,7,105,12,0,7,107,1,7,8,209,20,0,8,212,1,9,8,220,1,10,9,393,1,11,9,394,32,0,9,416,1,12,9,427,1,13,10,887,1,18,10,784,1,14,10,790,1,15,10,835,60,0,10,852,1,16,10,885,1,17,11,1571,1,19,11,1668,1,20,11,1669,100,0,11,1707,1,21,11,1772,1,22,12,3547,1,29,12,3164,1,24,12,3166,1,25,12,3140,1,23,12,3413,1,26,12,3537,1,27,12,3539,1,28,13,7093,1,35,13,6283,1,30,13,6331,1,31,13,6335,180,0,13,6824,1,32,13,7072,1,33,13,7077,320,0,13,7076,1,34,14,12565,1,36,14,12661,1,37,14,12669,1,38,14,13651,1,39,14,14184,1,40,15,28295,1,46,15,28371,1,47,15,25320,1,42,15,25336,1,43,15,25128,1,41,15,27300,1,44,15,28293,1,45,16,50259,1,48,16,50643,1,49,16,50675,1,50,16,56740,1,53,16,56584,1,51,16,56588,1,52,17,113483,1,61,17,113482,1,60,17,101285,1,55,17,101349,1,56,17,109205,1,57,17,109207,1,58,17,100516,1,54,17,113171,1,59,18,202568,1,62,18,202696,1,63,18,218408,1,64,18,218412,1,65,18,226340,1,66,18,226356,1,67,18,226358,1,68,19,402068,1,69,19,405138,1,70,19,405394,1,71,19,436818,1,72,19,436826,1,73,19,452714,1,75,19,452718,1,76,19,452682,1,74,20,804138,1,77,20,810279,1,78,20,810790,1,79,20,873638,1,80,20,873654,1,81,20,905366,1,82,20,905430,1,83,20,905438,1,84,21,1608278,1,85,21,1620557,1,86,21,1621582,1,87,21,1621583,1,88,21,1747310,1,89,21,1810734,1,90,21,1810735,1,91,21,1810863,1,92,21,1810879,1,93,22,3621725,1,99,22,3621757,1,100,22,3241112,1,94,22,3494556,1,95,22,3494557,1,96,22,3494622,1,97,22,3494623,1,98,23,6482227,1,102,23,6433117,1,101,23,6989117,1,103,23,6989119,1,105,23,6989118,1,104,23,7243449,1,106,23,7243512,1,107,24,13978233,1,111,24,12964453,1,109,24,12866232,1,108,24,14486897,1,113,24,13978232,1,110,24,14486896,1,112,24,14487026,1,114,24,14487027,1,115,25,25732598,1,225,25,25732597,1,189,25,25732596,1,188,25,25732595,1,203,25,25732594,1,202,25,25732593,1,197,25,25732592,1,207,25,25732591,1,169,25,25732590,1,223,25,25732589,1,159,25,25732522,1,235,25,25732579,1,152,25,25732575,1,192,25,25732489,1,179,25,25732573,1,201,25,25732472,1,172,25,25732576,1,149,25,25732488,1,178,25,25732566,1,120,25,25732571,1,219,25,25732577,1,150,25,25732487,1,127,25,25732506,1,211,25,25732548,1,125,25,25732588,1,158,25,25732486,1,247,25,25732467,1,238,25,25732508,1,163,25,25732552,1,228,25,25732603,1,183,25,25732513,1,217,25,25732587,1,168,25,25732520,1,122,25,25732484,1,128,25,25732562,1,249,25,25732505,1,187,25,25732504,1,186,25,25732483,1,136,25,25928905,1,181,25,25732560,1,255,25,25732500,1,230,25,25732482,1,135,25,25732555,1,233,25,25732568,1,222,25,25732583,1,145,25,25732481,1,134,25,25732586,1,167,25,25732521,1,248,25,25732518,1,209,25,25732480,1,243,25,25732512,1,216,25,25732509,1,164,25,25732547,1,140,25,25732479,1,157,25,25732544,1,239,25,25732574,1,191,25,25732564,1,251,25,25732478,1,156,25,25732546,1,139,25,25732498,1,242,25,25732557,1,133,25,25732477,1,162,25,25732515,1,213,25,25732584,1,165,25,25732514,1,212,25,25732476,1,227,25,25732494,1,198,25,25732531,1,236,25,25732530,1,234,25,25732529,1,117,25,25732528,1,215,25,25732527,1,124,25,25732526,1,123,25,25732525,1,254,25,25732524,1,253,25,25732523,1,148,25,25732570,1,218,25,25732580,1,146,25,25732581,1,147,25,25732569,1,224,25,25732533,1,143,25,25732540,1,184,25,25732541,1,185,25,25732585,1,166,25,25732556,1,132,25,25732485,1,129,25,25732563,1,250,25,25732578,1,151,25,25732501,1,119,25,25732502,1,193,25,25732536,1,176,25,25732496,1,245,25,25732553,1,229,25,25732516,1,206,25,25732582,1,144,25,25732517,1,208,25,25732558,1,137,25,25732543,1,241,25,25732466,1,237,25,25732507,1,190,25,25732542,1,240,25,25732551,1,131,25,25732554,1,232,25,25732565,1,252,25,25732475,1,171,25,25732493,1,205,25,25732492,1,204,25,25732491,1,118,25,25732490,1,214,25,25928904,1,180,25,25732549,1,126,25,25732602,1,182,25,25732539,1,175,25,25732545,1,141,25,25732559,1,138,25,25732537,1,177,25,25732534,1,153,25,25732503,1,194,25,25732606,1,160,25,25732567,1,121,25,25732538,1,174,25,25732497,1,246,25,25732550,1,130,25,25732572,1,200,25,25732474,1,170,25,25732511,1,221,25,25732601,1,196,25,25732532,1,142,25,25732519,1,210,25,25732495,1,199,25,25732605,1,155,25,25732535,1,154,25,25732499,1,244,25,25732510,1,220,25,25732600,1,195,25,25732607,1,161,25,25732604,1,231,25,25732473,1,173,25,25732599,1,226,26,51465122,1,116,26,51465123,0,1],o,C,k,P=[3,3,3,3,2,2,2,1,1,1],V=24576,ar=16384,H=8192,az=ar|H;\r\n\tfunction d(t){var E=t[1],h=t[0][E>>>3]>>>7-(E&7)&1;t[1]++;return h}function ag(t,E){if(o==null){o={};\r\n\tfor(var h=0;h>>1}return t}function A(t,E){return t>>E}function O(t,E,h,L,g,n){E[h]=A(A(11*t[g]-4*t[g+n]+t[g+n+n]+4,3)+t[L],1);\r\n\tE[h+n]=A(A(5*t[g]+4*t[g+n]-t[g+n+n]+4,3)-t[L],1)}function J(t,E,h,L,g,n){var W=t[g-n]-t[g+n],j=t[g],$=t[L];\r\n\tE[h]=A(A(W+4,3)+j+$,1);E[h+n]=A(A(-W+4,3)+j-$,1)}function y(t,E,h,L,g,n){E[h]=A(A(5*t[g]+4*t[g-n]-t[g-n-n]+4,3)+t[L],1);\r\n\tE[h+n]=A(A(11*t[g]-4*t[g-n]+t[g-n-n]+4,3)-t[L],1)}function q(t){t=t<0?0:t>4095?4095:t;t=k[t]>>>2;return t}function av(t,E,h,L,g,n){L=new Uint16Array(L.buffer);\r\n\tvar W=Date.now(),j=UTIF._binBE,$=E+h,r,u,X,I,ax,a3,R,ai,aa,ap,ah,ae,aD,al,i,aE,T,B;E+=4;var a5=n[0]==1;\r\n\twhile(E<$){var S=j.readShort(t,E),s=j.readUshort(t,E+2);E+=4;if(S==12)r=s;else if(S==20)u=s;else if(S==21)X=s;\r\n\telse if(S==48)I=s;else if(S==53)ax=s;else if(S==35)a3=s;else if(S==62)R=s;else if(S==101)ai=s;else if(S==109)aa=s;\r\n\telse if(S==84)ap=s;else if(S==106)ah=s;else if(S==107)ae=s;else if(S==108)aD=s;else if(S==102)al=s;else if(S==104)i=s;\r\n\telse if(S==105)aE=s;else{var F=S<0?-S:S,D=F&65280,_=0;if(F&az){if(F&H){_=s&65535;_+=(F&255)<<16}else{_=s&65535}}if((F&V)==V){if(T==null){T=[];\r\n\tfor(var M=0;M<4;M++)T[M]=new Int16Array((u>>>1)*(X>>>1));B=new Int16Array((u>>>1)*(X>>>1));C=new Int16Array(1024);\r\n\tfor(var M=0;M<1024;M++){var aG=M-512,p=Math.abs(aG),r=Math.floor(768*p*p*p/(255*255*255))+p;C[M]=Math.sign(aG)*r}k=new Uint16Array(4096);\r\n\tvar aA=(1<<16)-1;for(var M=0;M<4096;M++){var at=M,a1=aA*(Math.pow(113,at/4095)-1)/112;k[M]=Math.min(a1,aA)}}var w=T[R],v=m(u,1+P[I]),N=m(X,1+P[I]);\r\n\tif(I==0){for(var b=0;b>>1)+G]=t[c]<<8|t[c+1]}}else{var a7=[t,E*8],a4=[],ay=0,aw=v*N,f=[0,0],Q=0,s=0;\r\n\twhile(ay0){a4[ay++]=s;Q--}}var l=(I-1)%3,aF=l!=1?v:0,a2=l!=0?N:0;\r\n\tfor(var b=0;b>>1)+aF,au=b*v;for(var G=0;G>>1,an=v*2,a9=N*2;\r\n\tfor(var b=0;b>14-K*2&3;var a6=aC[aB];if(a6!=0)for(var b=0;b>>1)*(u>>>1)+(G>>>1),z=a8[c],ao=ab[c]-2048,ak=aq[c]-2048,ad=as[c]-2048,aj=(ao<<1)+z,a0=(ak<<1)+z,aH=z+ad,am=z-ad;\r\n\tif(a5){L[U]=q(aH);L[U+1]=q(a0);L[U+u]=q(aj);L[U+u+1]=q(am)}else{L[U]=q(aj);L[U+1]=q(aH);L[U+u]=q(am);\r\n\tL[U+u+1]=q(a0)}}}E+=_*4}else if(F==16388){E+=_*4}else if(D==8192||D==8448||D==9216){}else throw F.toString(16)}}console.log(Date.now()-W)}return av}()\r\n\t\r\n\t\r\n\t\r\n\tUTIF.decode._decodeLogLuv32 = function(img, data, off, len, tgt, toff) {\r\n\t\tvar w = img.width, qw=w*4;\r\n\t\tvar io = 0, out = new Uint8Array(qw);\r\n\t\t\r\n\t\twhile(io>> (tab[i] >>> 8);\r\n\t\t\t\tfor(var c=0; c>>4); tgt[toff+i+1]=(b0<<4)|(b2>>>4); tgt[toff+i+2]=(b2<<4)|(b1>>>4); }\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tvar pix = new Uint16Array(16);\r\n\t\tvar row, col, val, max, min, imax, imin, sh, bit, i, dp;\r\n\t\t\r\n\t\tvar data = new Uint8Array(raw_width+1);\r\n\t\tfor (row=0; row < height; row++) {\r\n\t\t\t//fread (data, 1, raw_width, ifp);\r\n\t\t\tfor(var j=0; j>> 11);\r\n\t\t\t\timax = 0x0f & (val >>> 22);\r\n\t\t\t\timin = 0x0f & (val >>> 26);\r\n\t\t\t\tfor (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);\r\n\t\t\t\tfor (bit=30, i=0; i < 16; i++)\r\n\t\t\t\t\tif (i == imax) pix[i] = max;\r\n\t\t\t\t\telse if (i == imin) pix[i] = min;\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tpix[i] = ((bin.readUshort(data, dp+(bit >> 3)) >>> (bit & 7) & 0x7f) << sh) + min;\r\n\t\t\t\t\t\tif (pix[i] > 0x7ff) pix[i] = 0x7ff;\r\n\t\t\t\t\t\tbit += 7;\r\n\t\t\t\t\t}\r\n\t\t\t\tfor (i=0; i < 16; i++, col+=2) {\r\n\t\t\t\t\t//RAW(row,col) = curve[pix[i] << 1] >> 2;\r\n\t\t\t\t\tvar clr = pix[i]<<1; //clr = 0xffff;\r\n\t\t\t\t\tUTIF.decode._putsF(tgt, (row*raw_width+col)*tiff_bps, clr<<(16-tiff_bps));\r\n\t\t\t\t}\r\n\t\t\t\tcol -= col & 1 ? 1:31;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeNikon = function(img,imgs, data, off, src_length, tgt, toff)\r\n\t{\r\n\t\tvar nikon_tree = [\r\n\t\t[ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 12-bit lossy */\r\n\t\t 5,4,3,6,2,7,1,0,8,9,11,10,12 ],\r\n\t\t[ 0, 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 12-bit lossy after split */\r\n\t\t 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 ],\r\n\t\t[ 0, 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */\r\n\t\t 5,4,6,3,7,2,8,1,9,0,10,11,12 ],\r\n\t\t[ 0, 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,\t/* 14-bit lossy */\r\n\t\t 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 ],\r\n\t\t[ 0, 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,\t/* 14-bit lossy after split */\r\n\t\t 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 ],\r\n\t\t[ 0, 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,\t/* 14-bit lossless */\r\n\t\t 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 ] ];\r\n\t\t \r\n\t\tvar raw_width = img[\"t256\"][0], height=img[\"t257\"][0], tiff_bps=img[\"t258\"][0];\r\n\t\t\r\n\t\tvar tree = 0, split = 0;\r\n\t\tvar make_decoder = UTIF.decode._make_decoder;\r\n\t\tvar getbithuff = UTIF.decode._getbithuff;\r\n\t\t\r\n\t\tvar mn = imgs[0].exifIFD.makerNote, md = mn[\"t150\"]?mn[\"t150\"]:mn[\"t140\"], mdo=0; //console.log(mn,md);\r\n\t\t//console.log(md[0].toString(16), md[1].toString(16), tiff_bps);\r\n\t\tvar ver0 = md[mdo++], ver1 = md[mdo++];\r\n\t\tif (ver0 == 0x49 || ver1 == 0x58) mdo+=2110;\r\n\t\tif (ver0 == 0x46) tree = 2;\r\n\t\tif (tiff_bps == 14) tree += 3;\r\n\t\t\r\n\t\tvar vpred = [[0,0],[0,0]], bin=(img.isLE ? UTIF._binLE : UTIF._binBE);\r\n\t\tfor(var i=0; i<2; i++) for(var j=0; j<2; j++) { vpred[i][j] = bin.readShort(md,mdo); mdo+=2; } // not sure here ... [i][j] or [j][i]\r\n\t\t//console.log(vpred);\r\n\t\t\r\n\t\t\r\n\t\tvar max = 1 << tiff_bps & 0x7fff, step=0;\r\n\t\tvar csize = bin.readShort(md,mdo); mdo+=2;\r\n\t\tif (csize > 1) step = Math.floor(max / (csize-1));\r\n\t\tif (ver0 == 0x44 && ver1 == 0x20 && step > 0) split = bin.readShort(md,562);\r\n\t\t\r\n\t\t\r\n\t\tvar i;\r\n\t\tvar row, col;\r\n\t\tvar len, shl, diff;\r\n\t\tvar min_v = 0;\r\n\t\tvar hpred = [0,0];\r\n\t\tvar huff = make_decoder(nikon_tree[tree]);\r\n\t\t\r\n\t\t//var g_input_offset=0, bitbuf=0, vbits=0, reset=0;\r\n\t\tvar prm = [off,0,0,0];\r\n\t\t//console.log(split); split = 170;\r\n\t\t\r\n\t\tfor (min_v=row=0; row < height; row++) {\r\n\t\t\tif (split && row == split) {\r\n\t\t\t\t//free (huff);\r\n\t\t\t\thuff = make_decoder (nikon_tree[tree+1]);\r\n\t\t\t\t//max_v += (min_v = 16) << 1;\r\n\t\t\t}\r\n\t\t\tfor (col=0; col < raw_width; col++) {\r\n\t\t\t\ti = getbithuff(data,prm,huff[0],huff);\r\n\t\t\t\tlen = i & 15;\r\n\t\t\t\tshl = i >>> 4;\r\n\t\t\t\tdiff = (((getbithuff(data,prm,len-shl,0) << 1) + 1) << shl) >>> 1;\r\n\t\t\t\tif ((diff & (1 << (len-1))) == 0)\r\n\t\t\t\t\tdiff -= (1 << len) - (shl==0?1:0);\r\n\t\t\t\tif (col < 2) hpred[col] = vpred[row & 1][col] += diff;\r\n\t\t\t\telse hpred[col & 1] += diff;\r\n\t\t\t\t\r\n\t\t\t\tvar clr = Math.min(Math.max(hpred[col & 1],0),(1<>>3); dt[o]|=val>>>16; dt[o+1]|=val>>>8; dt[o+2]|=val; }\r\n\t\r\n\t\r\n\tUTIF.decode._getbithuff = function(data,prm,nbits, huff) {\r\n\t\tvar zero_after_ff = 0;\r\n\t\tvar get_byte = UTIF.decode._get_byte;\r\n\t\tvar c;\r\n\t \r\n\t\tvar off=prm[0], bitbuf=prm[1], vbits=prm[2], reset=prm[3];\r\n\t\r\n\t\t//if (nbits > 25) return 0;\r\n\t\t//if (nbits < 0) return bitbuf = vbits = reset = 0;\r\n\t\tif (nbits == 0 || vbits < 0) return 0; \r\n\t\twhile (!reset && vbits < nbits && (c = data[off++]) != -1 &&\r\n\t\t\t!(reset = zero_after_ff && c == 0xff && data[off++])) {\r\n\t\t\t//console.log(\"byte read into c\");\r\n\t\t\tbitbuf = (bitbuf << 8) + c;\r\n\t\t\tvbits += 8;\r\n\t\t} \r\n\t\tc = (bitbuf << (32-vbits)) >>> (32-nbits);\r\n\t\tif (huff) {\r\n\t\t\tvbits -= huff[c+1] >>> 8; //console.log(c, huff[c]>>8);\r\n\t\t\tc = huff[c+1]&255;\r\n\t\t} else\r\n\t\t\tvbits -= nbits;\r\n\t\tif (vbits < 0) throw \"e\";\r\n\t \r\n\t\tprm[0]=off; prm[1]=bitbuf; prm[2]=vbits; prm[3]=reset;\r\n\t \r\n\t\treturn c;\r\n\t}\r\n\t\r\n\tUTIF.decode._make_decoder = function(source) {\r\n\t\tvar max, len, h, i, j;\r\n\t\tvar huff = [];\r\n\t\r\n\t\tfor (max=16; max!=0 && !source[max]; max--);\r\n\t\tvar si=17;\r\n\t\t\r\n\t\thuff[0] = max;\r\n\t\tfor (h=len=1; len <= max; len++)\r\n\t\t\tfor (i=0; i < source[len]; i++, ++si)\r\n\t\t\t\tfor (j=0; j < 1 << (max-len); j++)\r\n\t\t\t\t\tif (h <= 1 << max)\r\n\t\t\t\t\t\thuff[h++] = (len << 8) | source[si];\r\n\t\treturn huff;\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeNewJPEG = function(img, data, off, len, tgt, toff)\r\n\t{\r\n\t\tlen = Math.min(len, data.length-off);\r\n\t\tvar tables = img[\"t347\"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);\r\n\t\t\r\n\t\tif (tables) {\r\n\t\t\tvar SOI = 216, EOI = 217, boff = 0;\r\n\t\t\tfor (var i=0; i<(tlen-1); i++)\r\n\t\t\t{\r\n\t\t\t\t// Skip EOI marker from JPEGTables\r\n\t\t\t\tif (tables[i]==255 && tables[i+1]==EOI) break;\r\n\t\t\t\tbuff[boff++] = tables[i];\r\n\t\t\t}\r\n\t\r\n\t\t\t// Skip SOI marker from data\r\n\t\t\tvar byte1 = data[off], byte2 = data[off + 1];\r\n\t\t\tif (byte1!=255 || byte2!=SOI)\r\n\t\t\t{\r\n\t\t\t\tbuff[boff++] = byte1;\r\n\t\t\t\tbuff[boff++] = byte2;\r\n\t\t\t}\r\n\t\t\tfor (var i=2; i>>8); }\r\n\t\t\t\telse for(var i=0; i>>8); tgt[toff+(i<<1)+1] = (out[i]&255); }\r\n\t\t\t}\r\n\t\t\telse if(bps==14 || bps==12 || bps==10) { // 4 * 14 == 56 == 7 * 8\r\n\t\t\t\tvar rst = 16-bps;\r\n\t\t\t\tfor(var i=0; i 1);\r\n\t\t}\r\n\t\r\n\t\tif(!isTiled)\r\n\t\t{\r\n\t\t\tif(data[off]==255 && data[off+1]==SOI) return { jpegOffset: off };\r\n\t\t\tif(jpgIchgFmt!=null)\r\n\t\t\t{\r\n\t\t\t\tif(data[off+jifoff]==255 && data[off+jifoff+1]==SOI) joff = off+jifoff;\r\n\t\t\t\telse log(\"JPEGInterchangeFormat does not point to SOI\");\r\n\t\r\n\t\t\t\tif(jpgIchgFmtLen==null) log(\"JPEGInterchangeFormatLength field is missing\");\r\n\t\t\t\telse if(jifoff >= soff || (jifoff+jiflen) <= soff) log(\"JPEGInterchangeFormatLength field value is invalid\");\r\n\t\r\n\t\t\t\tif(joff != null) return { jpegOffset: joff };\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tif(ycbcrss!=null) { ssx = ycbcrss[0]; ssy = ycbcrss[1]; }\r\n\t\r\n\t\tif(jpgIchgFmt!=null)\r\n\t\t\tif(jpgIchgFmtLen!=null)\r\n\t\t\t\tif(jiflen >= 2 && (jifoff+jiflen) <= soff)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(data[off+jifoff+jiflen-2]==255 && data[off+jifoff+jiflen-1]==SOI) tables = new Uint8Array(jiflen-2);\r\n\t\t\t\t\telse tables = new Uint8Array(jiflen);\r\n\t\r\n\t\t\t\t\tfor(i=0; i offset to first strip or tile\");\r\n\t\r\n\t\tif(tables == null)\r\n\t\t{\r\n\t\t\tvar ooff = 0, out = [];\r\n\t\t\tout[ooff++] = 255; out[ooff++] = SOI;\r\n\t\r\n\t\t\tvar qtables = img[\"t519\"];\r\n\t\t\tif(qtables==null) throw new Error(\"JPEGQTables tag is missing\");\r\n\t\t\tfor(i=0; i>> 8); out[ooff++] = nc & 255;\r\n\t\t\t\t\tout[ooff++] = (i | (k << 4));\r\n\t\t\t\t\tfor(j=0; j<16; j++) out[ooff++] = data[off+htables[i]+j];\r\n\t\t\t\t\tfor(j=0; j>> 8) & 255; out[ooff++] = img.height & 255;\r\n\t\t\tout[ooff++] = (img.width >>> 8) & 255; out[ooff++] = img.width & 255;\r\n\t\t\tout[ooff++] = spp;\r\n\t\t\tif(spp==1) { out[ooff++] = 1; out[ooff++] = 17; out[ooff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\tout[ooff++] = i + 1;\r\n\t\t\t\tout[ooff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));\r\n\t\t\t\tout[ooff++] = i;\r\n\t\t\t}\r\n\t\r\n\t\t\tif(jpgresint!=null && jpgresint[0]!=0)\r\n\t\t\t{\r\n\t\t\t\tout[ooff++] = 255; out[ooff++] = DRI; out[ooff++] = 0; out[ooff++] = 4;\r\n\t\t\t\tout[ooff++] = (jpgresint[0] >>> 8) & 255;\r\n\t\t\t\tout[ooff++] = jpgresint[0] & 255;\r\n\t\t\t}\r\n\t\r\n\t\t\ttables = new Uint8Array(out);\r\n\t\t}\r\n\t\r\n\t\tvar sofpos = -1;\r\n\t\ti = 0;\r\n\t\twhile(i < (tables.length - 1)) {\r\n\t\t\tif(tables[i]==255 && tables[i+1]==SOF0) { sofpos = i; break; }\r\n\t\t\ti++;\r\n\t\t}\r\n\t\r\n\t\tif(sofpos == -1)\r\n\t\t{\r\n\t\t\tvar tmptab = new Uint8Array(tables.length + 10 + 3*spp);\r\n\t\t\ttmptab.set(tables);\r\n\t\t\tvar tmpoff = tables.length;\r\n\t\t\tsofpos = tables.length;\r\n\t\t\ttables = tmptab;\r\n\t\r\n\t\t\ttables[tmpoff++] = 255; tables[tmpoff++] = SOF0;\r\n\t\t\ttables[tmpoff++] = 0; tables[tmpoff++] = 8 + 3*spp; tables[tmpoff++] = 8;\r\n\t\t\ttables[tmpoff++] = (img.height >>> 8) & 255; tables[tmpoff++] = img.height & 255;\r\n\t\t\ttables[tmpoff++] = (img.width >>> 8) & 255; tables[tmpoff++] = img.width & 255;\r\n\t\t\ttables[tmpoff++] = spp;\r\n\t\t\tif(spp==1) { tables[tmpoff++] = 1; tables[tmpoff++] = 17; tables[tmpoff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\ttables[tmpoff++] = i + 1;\r\n\t\t\t\ttables[tmpoff++] = (i != 0) ? 17 : (((ssx & 15) << 4) | (ssy & 15));\r\n\t\t\t\ttables[tmpoff++] = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t\tif(data[soff]==255 && data[soff+1]==SOS)\r\n\t\t{\r\n\t\t\tvar soslen = (data[soff+2]<<8) | data[soff+3];\r\n\t\t\tsosMarker = new Uint8Array(soslen+2);\r\n\t\t\tsosMarker[0] = data[soff]; sosMarker[1] = data[soff+1]; sosMarker[2] = data[soff+2]; sosMarker[3] = data[soff+3];\r\n\t\t\tfor(i=0; i<(soslen-2); i++) sosMarker[i+4] = data[soff+i+4];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsosMarker = new Uint8Array(2 + 6 + 2*spp);\r\n\t\t\tvar sosoff = 0;\r\n\t\t\tsosMarker[sosoff++] = 255; sosMarker[sosoff++] = SOS;\r\n\t\t\tsosMarker[sosoff++] = 0; sosMarker[sosoff++] = 6 + 2*spp; sosMarker[sosoff++] = spp;\r\n\t\t\tif(spp==1) { sosMarker[sosoff++] = 1; sosMarker[sosoff++] = 0; }\r\n\t\t\telse for(i=0; i<3; i++)\r\n\t\t\t{\r\n\t\t\t\tsosMarker[sosoff++] = i+1; sosMarker[sosoff++] = (i << 4) | i;\r\n\t\t\t}\r\n\t\t\tsosMarker[sosoff++] = 0; sosMarker[sosoff++] = 63; sosMarker[sosoff++] = 0;\r\n\t\t}\r\n\t\r\n\t\treturn { jpegOffset: off, tables: tables, sosMarker: sosMarker, sofPosition: sofpos };\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeOldJPEG = function(img, data, off, len, tgt, toff)\r\n\t{\r\n\t\tvar i, dlen, tlen, buff, buffoff;\r\n\t\tvar jpegData = UTIF.decode._decodeOldJPEGInit(img, data, off, len);\r\n\t\r\n\t\tif(jpegData.jpegOffset!=null)\r\n\t\t{\r\n\t\t\tdlen = off+len-jpegData.jpegOffset;\r\n\t\t\tbuff = new Uint8Array(dlen);\r\n\t\t\tfor(i=0; i>> 8) & 255; buff[jpegData.sofPosition+6] = img.height & 255;\r\n\t\t\tbuff[jpegData.sofPosition+7] = (img.width >>> 8) & 255; buff[jpegData.sofPosition+8] = img.width & 255;\r\n\t\r\n\t\t\tif(data[off]!=255 || data[off+1]!=SOS)\r\n\t\t\t{\r\n\t\t\t\tbuff.set(jpegData.sosMarker, buffoff);\r\n\t\t\t\tbuffoff += sosMarker.length;\r\n\t\t\t}\r\n\t\t\tfor(i=0; i=0 && n<128) for(var i=0; i< n+1; i++) { ta[toff]=sa[off]; toff++; off++; }\r\n\t\t\tif(n>=-127 && n<0) { for(var i=0; i<-n+1; i++) { ta[toff]=sa[off]; toff++; } off++; }\r\n\t\t}\r\n\t\treturn toff;\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeThunder = function(data, off, len, tgt, toff)\r\n\t{\r\n\t\tvar d2 = [ 0, 1, 0, -1 ], d3 = [ 0, 1, 2, 3, 0, -3, -2, -1 ];\r\n\t\tvar lim = off+len, qoff = toff*2, px = 0;\r\n\t\twhile(off>>6), n = (b&63); off++;\r\n\t\t\tif(msk==3) { px=(n&15); tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; }\r\n\t\t\tif(msk==0) for(var i=0; i>>1] |= (px<<(4*(1-qoff&1))); qoff++; }\r\n\t\t\tif(msk==2) for(var i=0; i<2; i++) { var d=(n>>>(3*(1-i)))&7; if(d!=4) { px+=d3[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }\r\n\t\t\tif(msk==1) for(var i=0; i<3; i++) { var d=(n>>>(2*(2-i)))&3; if(d!=2) { px+=d2[d]; tgt[qoff>>>1] |= (px<<(4*(1-qoff&1))); qoff++; } }\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._dmap = { \"1\":0,\"011\":1,\"000011\":2,\"0000011\":3, \"010\":-1,\"000010\":-2,\"0000010\":-3 };\r\n\tUTIF.decode._lens = ( function()\r\n\t{\r\n\t\tvar addKeys = function(lens, arr, i0, inc) { for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\t\tif(mode==\"H\")\r\n\t\t\t{\r\n\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=\"\"; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(wrd==\"0001\") { wrd=\"\"; U._addNtimes(line,b2-a0,clr); a0=b2; }\r\n\t\t\t\tif(wrd==\"001\" ) { wrd=\"\"; mode=\"H\"; toRead=2; }\r\n\t\t\t\tif(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=\"\"; clr=1-clr; }\r\n\t\t\t}\r\n\t\t\tif(line.length==w && mode==\"\")\r\n\t\t\t{\r\n\t\t\t\tU._writeBits(line, tgt, toff*8+y*bipl);\r\n\t\t\t\tclr=0; y++; a0=0;\r\n\t\t\t\tpline=U._makeDiff(line); line=[];\r\n\t\t\t}\r\n\t\t\t//if(wrd.length>150) { log(wrd); break; throw \"e\"; }\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._findDiff = function(line, x, clr) { for(var i=0; i=x && line[i+1]==clr) return line[i]; }\r\n\t\r\n\tUTIF.decode._makeDiff = function(line)\r\n\t{\r\n\t\tvar out = []; if(line[0]==1) out.push(0,1);\r\n\t\tfor(var i=1; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\t\t\r\n\t\t\tlen = U._lens[clr][wrd];\r\n\t\t\tif(len!=null) {\r\n\t\t\t\tU._addNtimes(line,len,clr); wrd=\"\";\r\n\t\t\t\tif(len<64) clr = 1-clr; \r\n\t\t\t\tif(line.length==w) { U._writeBits(line, tgt, toff*8+y*bipl); line=[]; y++; clr=0; if((boff&7)!=0) boff+=8-(boff&7); if(len>=64) boff+=8; }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeG3 = function(data, off, slen, tgt, toff, w, fo, twoDim)\r\n\t{\r\n\t\tvar U = UTIF.decode, boff=off<<3, len=0, wrd=\"\";\r\n\t\tvar line=[], pline=[]; for(var i=0; i>>3)>>3]>>>(7-(boff&7)))&1;\r\n\t\t\tif(fo==2) bit = (data[boff>>>3]>>>( (boff&7)))&1;\r\n\t\t\tboff++; wrd+=bit;\r\n\t\r\n\t\t\tif(is1D)\r\n\t\t\t{\r\n\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); clr=1-clr; len=0; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(mode==\"H\")\r\n\t\t\t\t{\r\n\t\t\t\t\tif(U._lens[clr][wrd]!=null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar dl=U._lens[clr][wrd]; wrd=\"\"; len+=dl;\r\n\t\t\t\t\t\tif(dl<64) { U._addNtimes(line,len,clr); a0+=len; clr=1-clr; len=0; toRead--; if(toRead==0) mode=\"\"; }\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif(wrd==\"0001\") { wrd=\"\"; U._addNtimes(line,b2-a0,clr); a0=b2; }\r\n\t\t\t\t\tif(wrd==\"001\" ) { wrd=\"\"; mode=\"H\"; toRead=2; }\r\n\t\t\t\t\tif(U._dmap[wrd]!=null) { a1 = b1+U._dmap[wrd]; U._addNtimes(line, a1-a0, clr); a0=a1; wrd=\"\"; clr=1-clr; }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(wrd.endsWith(\"000000000001\")) // needed for some files\r\n\t\t\t{\r\n\t\t\t\tif(y>=0) U._writeBits(line, tgt, toff*8+y*bipl);\r\n\t\t\t\tif(twoDim) {\r\n\t\t\t\t\tif(fo==1) is1D = ((data[boff>>>3]>>>(7-(boff&7)))&1)==1;\r\n\t\t\t\t\tif(fo==2) is1D = ((data[boff>>>3]>>>( (boff&7)))&1)==1;\r\n\t\t\t\t\tboff++;\r\n\t\t\t\t}\r\n\t\t\t\t//log(\"EOL\",y, \"next 1D:\", is1D);\r\n\t\t\t\twrd=\"\"; clr=0; y++; a0=0;\r\n\t\t\t\tpline=U._makeDiff(line); line=[];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(line.length==w) U._writeBits(line, tgt, toff*8+y*bipl);\r\n\t}\r\n\t\r\n\tUTIF.decode._addNtimes = function(arr, n, val) { for(var i=0; i>>3] |= (bits[i]<<(7-((boff+i)&7)));\r\n\t}\r\n\t\r\n\tUTIF.decode._decodeLZW=UTIF.decode._decodeLZW=function(){var e,U,Z,u,K=0,V=0,g=0,N=0,O=function(){var S=e>>>3,A=U[S]<<16|U[S+1]<<8|U[S+2],j=A>>>24-(e&7)-V&(1<>>----------------\");\r\n\t\tfor(var i=0; idata.buffer.byteLength) num=data.buffer.byteLength-no; arr = new Uint8Array(data.buffer, no, num); }\r\n\t\t\tif(type== 2) { var o0 = (num<5 ? offset-4 : voff), c=data[o0], len=Math.max(0, Math.min(num-1,data.length-o0));\r\n\t\t\t\t\t\t\tif(c<128 || len==0) arr.push( bin.readASCII(data, o0, len) );\r\n\t\t\t\t\t\t\telse arr = new Uint8Array(data.buffer, o0, len); }\r\n\t\t\tif(type== 3) { for(var j=0; j4) { bin.writeUint(data, offset, eoff); toff=eoff; }\r\n\t\r\n\t\t\tif (type== 1 || type==7) { for(var i=0; i4) { dlen += (dlen&1); eoff += dlen; }\r\n\t\t\toffset += 4;\r\n\t\t}\r\n\t\treturn [offset, eoff];\r\n\t}\r\n\t\r\n\tUTIF.toRGBA8 = function(out, scl)\r\n\t{\r\n\t\tfunction gamma(x) { return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055; }\r\n\t\t\r\n\t\t\r\n\t\tvar w = out.width, h = out.height, area = w*h, qarea = area*4, data = out.data;\r\n\t\tvar img = new Uint8Array(area*4);\r\n\t\t//console.log(out);\r\n\t\t// 0: WhiteIsZero, 1: BlackIsZero, 2: RGB, 3: Palette color, 4: Transparency mask, 5: CMYK\r\n\t\tvar intp = (out[\"t262\"] ? out[\"t262\"][0]: 2), bps = (out[\"t258\"]?Math.min(32,out[\"t258\"][0]):1);\r\n\t\tif(out[\"t262\"]==null && bps==1) intp=0;\r\n\t\t\r\n\t\tvar smpls = out[\"t277\"]?out[\"t277\"][0] : (out[\"t258\"]?out[\"t258\"].length : [1,1,3,1,1,4,3][intp]);\r\n\t\tvar sfmt = out[\"t339\"]?out[\"t339\"][0] : null; if(intp==1 && bps==32 && sfmt!=3) throw \"e\"; // sample format\r\n\t\tvar bpl = Math.ceil(smpls*bps*w/8);\r\n\t\t\r\n\t\t//log(\"interpretation: \", intp, \"smpls\", smpls, \"bps\", bps, \"sample format\",sfmt, out);\r\n\t\t\r\n\t\tif(false) {}\r\n\t\telse if(intp==0)\r\n\t\t{\r\n\t\t\tscl = 1/256; // \"Photopeatest.tif\"\r\n\t\t\tfor(var y=0; y>3)])>>(7- (i&7)))& 1; img[qi]=img[qi+1]=img[qi+2]=( 1-px)*255; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 4) for(var i=0; i>1)])>>(4-4*(i&1)))&15; img[qi]=img[qi+1]=img[qi+2]=(15-px)* 17; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 8) for(var i=0; i>3)])>>(7- (i&7)))&1; img[qi]=img[qi+1]=img[qi+2]=(px)*255; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 2) for(var i=0; i>2)])>>(6-2*(i&3)))&3; img[qi]=img[qi+1]=img[qi+2]=(px)* 85; img[qi+3]=255; }\r\n\t\t\t\tif(bps== 8) for(var i=0; i>>2)+i, px=f32[o]; img[qi]=img[qi+1]=img[qi+2]= ~~(0.5+255*px); img[qi+3]=255; }\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(intp==2)\r\n\t\t{\r\n\t\t\tif(bps== 8) \r\n\t\t\t{\r\n\t\t\t\tif(smpls==1) for(var i=0; i=4) for(var i=0; i1 && out[\"t338\"] && out[\"t338\"][0]!=0;\r\n\t\t\t\r\n\t\t\tfor(var y=0; y>>3)]>>>(7- (x&7)))& 1;\r\n\t\t\t\t\telse if(bps==2) mi=(data[dof+(x>>>2)]>>>(6-2*(x&3)))& 3;\r\n\t\t\t\t\telse if(bps==4) mi=(data[dof+(x>>>1)]>>>(4-4*(x&1)))&15;\r\n\t\t\t\t\telse if(bps==8) mi= data[dof+x*smpls]; \r\n\t\t\t\t\telse throw bps;\r\n\t\t\t\t\timg[qi]=(map[mi]>>8); img[qi+1]=(map[cn+mi]>>8); img[qi+2]=(map[cn+cn+mi]>>8); img[qi+3]=nexta ? data[dof+x*smpls+1] : 255; \r\n\t\t\t\t}\r\n\t\t}\r\n\t\telse if(intp==5) \r\n\t\t{\r\n\t\t\tvar gotAlpha = smpls>4 ? 1 : 0;\r\n\t\t\tfor(var i=0; i>>1);\r\n\t\t\t\t\tvar Y = data[si+(j&1)], Cb=data[si+2]-128, Cr=data[si+3]-128;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar r = Y + ( (Cr >> 2) + (Cr >> 3) + (Cr >> 5) ) ;\r\n\t\t\t\t\tvar g = Y - ( (Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ( (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5)) ;\r\n\t\t\t\t\tvar b = Y + ( Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)) ;\r\n\t\t\t\t\t\r\n\t\t\t\t\timg[qi ]=Math.max(0,Math.min(255,r));\r\n\t\t\t\t\timg[qi+1]=Math.max(0,Math.min(255,g));\r\n\t\t\t\t\timg[qi+2]=Math.max(0,Math.min(255,b));\r\n\t\t\t\t\timg[qi+3]=255;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(intp==32845) {\r\n\t\t\t\r\n\t\t\tfor(var y=0; yma) { ma=ar; page=img; }\r\n\t\t}\r\n\t\tUTIF.decodeImage(buff, page, ifds);\r\n\t\tvar rgba = UTIF.toRGBA8(page), w=page.width, h=page.height;\r\n\t\t\r\n\t\tvar cnv = document.createElement(\"canvas\"); cnv.width=w; cnv.height=h;\r\n\t\tvar ctx = cnv.getContext(\"2d\");\r\n\t\tvar imgd = new ImageData(new Uint8ClampedArray(rgba.buffer),w,h);\r\n\t\tctx.putImageData(imgd,0,0);\r\n\t\treturn cnv.toDataURL();\r\n\t}\r\n\t\r\n\t\r\n\tUTIF._binBE =\r\n\t{\r\n\t\tnextZero : function(data, o) { while(data[o]!=0) o++; return o; },\r\n\t\treadUshort : function(buff, p) { return (buff[p]<< 8) | buff[p+1]; },\r\n\t\treadShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+1]; a[1]=buff[p+0];\t\t\t\t\t\t\t return UTIF._binBE. i16[0]; },\r\n\t\treadInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE. i32[0]; },\r\n\t\treadUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+3]; a[1]=buff[p+2]; a[2]=buff[p+1]; a[3]=buff[p+0]; return UTIF._binBE.ui32[0]; },\r\n\t\treadASCII : function(buff, p, l) { var s = \"\"; for(var i=0; i> 8)&255; buff[p+1] = n&255; },\r\n\t\twriteInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+3]=a[0]; buff[p+2]=a[1]; buff[p+1]=a[2]; buff[p+0]=a[3]; },\r\n\t\twriteUint : function(buff, p, n) { buff[p] = (n>>24)&255; buff[p+1] = (n>>16)&255; buff[p+2] = (n>>8)&255; buff[p+3] = (n>>0)&255; },\r\n\t\twriteASCII : function(buff, p, s) { for(var i = 0; i < s.length; i++) buff[p+i] = s.charCodeAt(i); },\r\n\t\twriteDouble: function(buff, p, n)\r\n\t\t{\r\n\t\t\tUTIF._binBE.fl64[0] = n;\r\n\t\t\tfor (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];\r\n\t\t}\r\n\t}\r\n\tUTIF._binBE.ui8 = new Uint8Array (8);\r\n\tUTIF._binBE.i16 = new Int16Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.i32 = new Int32Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.ui32 = new Uint32Array (UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);\r\n\tUTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);\r\n\t\r\n\tUTIF._binLE =\r\n\t{\r\n\t\tnextZero : UTIF._binBE.nextZero,\r\n\t\treadUshort : function(buff, p) { return (buff[p+1]<< 8) | buff[p]; },\r\n\t\treadShort : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1];\t\t\t\t\t\t\t return UTIF._binBE. i16[0]; },\r\n\t\treadInt : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE. i32[0]; },\r\n\t\treadUint : function(buff, p) { var a=UTIF._binBE.ui8; a[0]=buff[p+0]; a[1]=buff[p+1]; a[2]=buff[p+2]; a[3]=buff[p+3]; return UTIF._binBE.ui32[0]; },\r\n\t\treadASCII : UTIF._binBE.readASCII,\r\n\t\treadFloat : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<4;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl32[0]; },\r\n\t\treadDouble : function(buff, p) { var a=UTIF._binBE.ui8; for(var i=0;i<8;i++) a[i]=buff[p+ i]; return UTIF._binBE.fl64[0]; },\r\n\t\t\r\n\t\twriteUshort: function(buff, p, n) { buff[p] = (n)&255; buff[p+1] = (n>>8)&255; },\r\n\t\twriteInt : function(buff, p, n) { var a=UTIF._binBE.ui8; UTIF._binBE.i32[0]=n; buff[p+0]=a[0]; buff[p+1]=a[1]; buff[p+2]=a[2]; buff[p+3]=a[3]; },\r\n\t\twriteUint : function(buff, p, n) { buff[p] = (n>>>0)&255; buff[p+1] = (n>>>8)&255; buff[p+2] = (n>>>16)&255; buff[p+3] = (n>>>24)&255; },\r\n\t\twriteASCII : UTIF._binBE.writeASCII\r\n\t}\r\n\tUTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff)\r\n\t{\r\n\t\t//log(\"copyTile\", tw, th, w, h, xoff, yoff);\r\n\t\tvar xlim = Math.min(tw, w-xoff);\r\n\t\tvar ylim = Math.min(th, h-yoff);\r\n\t\tfor(var y=0; y>--s&1;\r\n\tY=I[Y+F]}E[w]=Y}}function z(h,V,I,f){if(h[V+3]!=255)return 0;if(I==0)return V;for(var w=0;w<2;w++){if(h[V+w]==0){h[V+w]=h.length;\r\n\th.push(0,0,f,255)}var x=z(h,h[V+w],I-1,f+1);if(x!=0)return x}return 0}function i(h){var V=h.b,I=h.f;\r\n\twhile(V<25&&h.a>(V.b-=h)&65535>>16-h}function g(h,V){var I=h[0],f=0,w=255,x=0;if(V.b<16)i(V);var T=V.f>>V.b-8&255;\r\n\tf=h[1][T];w=I[f+3];V.b-=I[f+2];while(w==255){x=V.f>>--V.b&1;f=I[f+x];w=I[f+3]}return w}function P(h,V){if(h<32768>>16-V)h+=-(1<>4,J&15]}}else if(Y==65476){var a3=O+F-2;while(O>>4];x[v[0]]=v.slice(1)}I=l();O+=2;break}else if(Y==65501){w=m()}else{O+=F-2}}var a4=f>8?Uint16Array:Uint8Array,$=new a4(s*_*E),M={b:0,f:0,c:I==8,a:O,data:b,d:b.length,e:w};\r\n\tif(M.c)a1($,_*E,M,G[0],s);else{var c=[],p=0,D=0;for(var t=0;tp)p=S;\r\n\tif(K>D)D=K;c.push(S*K)}if(p!=1||D!=1){if(E!=3||c[1]!=1||c[2]!=1)throw\"e\";if(p!=2||D!=1&&D!=2)throw\"e\";\r\n\tvar u=[],Z=0;for(var t=0;t>>1)*B+(S>>>1))*Z,y=(K&1)*2+(S&1);\r\n\t$[q]=n[k+y];$[q+1]=n[k+4];$[q+2]=n[k+5]}else for(var S=0;S<_;S++){var q=(K*_+S)*E,k=(K*B+(S>>>1))*Z,y=S&1;\r\n\t$[q]=n[k+y];$[q+1]=n[k+2];$[q+2]=n[k+3]}}}else{X($,_*E,M,G,E,s);if(w==0)j($,I,_,s,0,E,E,f);else{var U=Math.floor(w/_);\r\n\tfor(var K=0;K>>1);else if(V==6)Q=h[J]+(r-h[J-G]>>>1);else if(V==7)Q=r+h[J]>>>1;else throw V;\r\n\th[a]+=Q}}}}return C}();\r\n\t\r\n\t\r\n\t(function(){var G=0,F=1,i=2,b=3,J=4,N=5,E=6,s=7,c=8,T=9,a3=10,f=11,q=12,M=13,m=14,x=15,L=16,$=17,p=18;\r\n\tfunction a5(t){var Z=UTIF._binBE.readUshort,u={b:Z(t,0),i:t[2],C:t[3],u:t[4],q:Z(t,5),k:Z(t,7),e:Z(t,9),l:Z(t,11),s:t[13],d:Z(t,14)};\r\n\tif(u.b!=18771||u.i>1||u.q<6||u.q%6||u.e<768||u.e%24||u.l!=768||u.k=u.l||u.s>16||u.s!=u.k/u.l||u.s!=Math.ceil(u.e/u.l)||u.d!=u.q/6||u.u!=12&&u.u!=14&&u.u!=16||u.C!=16&&u.C!=0){throw\"Invalid data\"}if(u.i==0){throw\"Not implemented. We need this file!\"}u.h=u.C==16;\r\n\tu.m=(u.h?u.l*2/3:u.l>>>1)|0;u.A=u.m+2;u.f=64;u.g=(1<>>6);for(var e=0;e<3;e++){for(var Q=0;\r\n\tQ<41;Q++){Z[e][Q]=[u,1]}}return Z}function a4(t){for(var Z=-1,u=0;!u;Z++){u=t[t.j]>>>7-t.a&1;t.a++;t.a&=7;\r\n\tif(!t.a)t.j++}return Z}function K(t,Z){var u=0,e=8-t.a,Q=t.j,V=t.a;if(Z){if(Z>=e){do{u<<=e;Z-=e;u|=t[t.j]&(1<=8)}if(Z){u<<=Z;e-=Z;u|=t[t.j]>>>e&(1<n&&C>>2;if(o){w[X]=h;return}l=Z.t*Z.c[t.g+Y-H]+Z.c[t.g+g-Y]}else{h=Y>g&&Y>P||Y>>2:A+v>>>1;\r\n\tl=Z.t*Z.c[t.g+Y-g]+Z.c[t.g+g-A]}R=y(l);var W=a4(u);if(W>>1):a>>>1;\r\n\tO[R][0]+=y(a);if(O[R][1]==t.f){O[R][0]>>>=1;O[R][1]>>>=1}O[R][1]++;h=l<0?h-a:h+a;if(t.i){if(h<0)h+=Z.w;\r\n\telse if(h>t.g)h-=Z.w}w[X]=h>=0?Math.min(h,t.g):0}function U(t,Z,u){var e=t[0].length;for(var Q=Z;Q<=u;\r\n\tQ++){t[Q][0]=t[Q-1][1];t[Q][e-1]=t[Q-1][e-2]}}function B(t){U(t,s,q);U(t,i,J);U(t,x,$)}function _(t,Z,u,e,Q,V,O,o,X,k,j,I,a){var l=0,R=1,w=QJ;\r\n\twhile(R8){r(t,Z,u,e,Q,R,o[X]);r(t,Z,u,e,V,R,o[X]);R+=2}}B(e)}function a8(t,Z,u,e,Q,V){_(t,Z,u,e,i,s,Q,V,0,0,1,0,8);\r\n\t_(t,Z,u,e,c,x,Q,V,1,0,1,0,8);_(t,Z,u,e,b,T,Q,V,2,1,0,3,0);_(t,Z,u,e,a3,L,Q,V,0,0,0,3,2);_(t,Z,u,e,J,f,Q,V,1,0,0,3,2);\r\n\t_(t,Z,u,e,q,$,Q,V,2,1,0,3,0)}function a9(t,Z,u,e,Q,V){var O=V.length,o=t.l;if(Q+1==t.s)o=t.e-Q*t.l;var X=6*t.e*e+Q*t.l;\r\n\tfor(var k=0;k<6;k++){for(var j=0;j>>1)}else if(I==2){a=x+(k>>>1)}else{a=s+k}var l=t.h?(j*2/3&2147483646|j%3&1)+(j%3>>>1):j>>>1;\r\n\tZ[X+j]=u[a][l+1]}X+=t.e}}UTIF._decompressRAF=function(t,Z){var u=a5(t),e=a7(t,u),Q=a2(u),V=new Int16Array(u.e*u.q);\r\n\tif(Z==null){Z=u.h?[[1,1,0,1,1,2],[1,1,2,1,1,0],[2,0,1,0,2,1],[1,1,2,1,1,0],[1,1,0,1,1,2],[0,2,1,2,0,1]]:[[0,1],[3,2]]}var O=[[G,b],[F,J],[N,f],[E,q],[M,L],[m,$]],o=[];\r\n\tfor(var X=0;X */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AnsiStringType = exports.StringType = exports.BufferType = exports.Uint8ArrayType = exports.IgnoreType = exports.Float80_LE = exports.Float80_BE = exports.Float64_LE = exports.Float64_BE = exports.Float32_LE = exports.Float32_BE = exports.Float16_LE = exports.Float16_BE = exports.INT64_BE = exports.UINT64_BE = exports.INT64_LE = exports.UINT64_LE = exports.INT32_LE = exports.INT32_BE = exports.INT24_BE = exports.INT24_LE = exports.INT16_LE = exports.INT16_BE = exports.INT8 = exports.UINT32_BE = exports.UINT32_LE = exports.UINT24_BE = exports.UINT24_LE = exports.UINT16_BE = exports.UINT16_LE = exports.UINT8 = void 0;\nconst ieee754 = require(\"ieee754\");\n// Primitive types\nfunction dv(array) {\n return new DataView(array.buffer, array.byteOffset);\n}\n/**\n * 8-bit unsigned integer\n */\nexports.UINT8 = {\n len: 1,\n get(array, offset) {\n return dv(array).getUint8(offset);\n },\n put(array, offset, value) {\n dv(array).setUint8(offset, value);\n return offset + 1;\n }\n};\n/**\n * 16-bit unsigned integer, Little Endian byte order\n */\nexports.UINT16_LE = {\n len: 2,\n get(array, offset) {\n return dv(array).getUint16(offset, true);\n },\n put(array, offset, value) {\n dv(array).setUint16(offset, value, true);\n return offset + 2;\n }\n};\n/**\n * 16-bit unsigned integer, Big Endian byte order\n */\nexports.UINT16_BE = {\n len: 2,\n get(array, offset) {\n return dv(array).getUint16(offset);\n },\n put(array, offset, value) {\n dv(array).setUint16(offset, value);\n return offset + 2;\n }\n};\n/**\n * 24-bit unsigned integer, Little Endian byte order\n */\nexports.UINT24_LE = {\n len: 3,\n get(array, offset) {\n const dataView = dv(array);\n return dataView.getUint8(offset) + (dataView.getUint16(offset + 1, true) << 8);\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint8(offset, value & 0xff);\n dataView.setUint16(offset + 1, value >> 8, true);\n return offset + 3;\n }\n};\n/**\n * 24-bit unsigned integer, Big Endian byte order\n */\nexports.UINT24_BE = {\n len: 3,\n get(array, offset) {\n const dataView = dv(array);\n return (dataView.getUint16(offset) << 8) + dataView.getUint8(offset + 2);\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint16(offset, value >> 8);\n dataView.setUint8(offset + 2, value & 0xff);\n return offset + 3;\n }\n};\n/**\n * 32-bit unsigned integer, Little Endian byte order\n */\nexports.UINT32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getUint32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setUint32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * 32-bit unsigned integer, Big Endian byte order\n */\nexports.UINT32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getUint32(offset);\n },\n put(array, offset, value) {\n dv(array).setUint32(offset, value);\n return offset + 4;\n }\n};\n/**\n * 8-bit signed integer\n */\nexports.INT8 = {\n len: 1,\n get(array, offset) {\n return dv(array).getInt8(offset);\n },\n put(array, offset, value) {\n dv(array).setInt8(offset, value);\n return offset + 1;\n }\n};\n/**\n * 16-bit signed integer, Big Endian byte order\n */\nexports.INT16_BE = {\n len: 2,\n get(array, offset) {\n return dv(array).getInt16(offset);\n },\n put(array, offset, value) {\n dv(array).setInt16(offset, value);\n return offset + 2;\n }\n};\n/**\n * 16-bit signed integer, Little Endian byte order\n */\nexports.INT16_LE = {\n len: 2,\n get(array, offset) {\n return dv(array).getInt16(offset, true);\n },\n put(array, offset, value) {\n dv(array).setInt16(offset, value, true);\n return offset + 2;\n }\n};\n/**\n * 24-bit signed integer, Little Endian byte order\n */\nexports.INT24_LE = {\n len: 3,\n get(array, offset) {\n const unsigned = exports.UINT24_LE.get(array, offset);\n return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned;\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint8(offset, value & 0xff);\n dataView.setUint16(offset + 1, value >> 8, true);\n return offset + 3;\n }\n};\n/**\n * 24-bit signed integer, Big Endian byte order\n */\nexports.INT24_BE = {\n len: 3,\n get(array, offset) {\n const unsigned = exports.UINT24_BE.get(array, offset);\n return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned;\n },\n put(array, offset, value) {\n const dataView = dv(array);\n dataView.setUint16(offset, value >> 8);\n dataView.setUint8(offset + 2, value & 0xff);\n return offset + 3;\n }\n};\n/**\n * 32-bit signed integer, Big Endian byte order\n */\nexports.INT32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getInt32(offset);\n },\n put(array, offset, value) {\n dv(array).setInt32(offset, value);\n return offset + 4;\n }\n};\n/**\n * 32-bit signed integer, Big Endian byte order\n */\nexports.INT32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getInt32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setInt32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * 64-bit unsigned integer, Little Endian byte order\n */\nexports.UINT64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigUint64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setBigUint64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * 64-bit signed integer, Little Endian byte order\n */\nexports.INT64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigInt64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setBigInt64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * 64-bit unsigned integer, Big Endian byte order\n */\nexports.UINT64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigUint64(offset);\n },\n put(array, offset, value) {\n dv(array).setBigUint64(offset, value);\n return offset + 8;\n }\n};\n/**\n * 64-bit signed integer, Big Endian byte order\n */\nexports.INT64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getBigInt64(offset);\n },\n put(array, offset, value) {\n dv(array).setBigInt64(offset, value);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 16-bit (half precision) float, big endian\n */\nexports.Float16_BE = {\n len: 2,\n get(dataView, offset) {\n return ieee754.read(dataView, offset, false, 10, this.len);\n },\n put(dataView, offset, value) {\n ieee754.write(dataView, value, offset, false, 10, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 16-bit (half precision) float, little endian\n */\nexports.Float16_LE = {\n len: 2,\n get(array, offset) {\n return ieee754.read(array, offset, true, 10, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, true, 10, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 32-bit (single precision) float, big endian\n */\nexports.Float32_BE = {\n len: 4,\n get(array, offset) {\n return dv(array).getFloat32(offset);\n },\n put(array, offset, value) {\n dv(array).setFloat32(offset, value);\n return offset + 4;\n }\n};\n/**\n * IEEE 754 32-bit (single precision) float, little endian\n */\nexports.Float32_LE = {\n len: 4,\n get(array, offset) {\n return dv(array).getFloat32(offset, true);\n },\n put(array, offset, value) {\n dv(array).setFloat32(offset, value, true);\n return offset + 4;\n }\n};\n/**\n * IEEE 754 64-bit (double precision) float, big endian\n */\nexports.Float64_BE = {\n len: 8,\n get(array, offset) {\n return dv(array).getFloat64(offset);\n },\n put(array, offset, value) {\n dv(array).setFloat64(offset, value);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 64-bit (double precision) float, little endian\n */\nexports.Float64_LE = {\n len: 8,\n get(array, offset) {\n return dv(array).getFloat64(offset, true);\n },\n put(array, offset, value) {\n dv(array).setFloat64(offset, value, true);\n return offset + 8;\n }\n};\n/**\n * IEEE 754 80-bit (extended precision) float, big endian\n */\nexports.Float80_BE = {\n len: 10,\n get(array, offset) {\n return ieee754.read(array, offset, false, 63, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, false, 63, this.len);\n return offset + this.len;\n }\n};\n/**\n * IEEE 754 80-bit (extended precision) float, little endian\n */\nexports.Float80_LE = {\n len: 10,\n get(array, offset) {\n return ieee754.read(array, offset, true, 63, this.len);\n },\n put(array, offset, value) {\n ieee754.write(array, value, offset, true, 63, this.len);\n return offset + this.len;\n }\n};\n/**\n * Ignore a given number of bytes\n */\nclass IgnoreType {\n /**\n * @param len number of bytes to ignore\n */\n constructor(len) {\n this.len = len;\n }\n // ToDo: don't read, but skip data\n get(array, off) {\n }\n}\nexports.IgnoreType = IgnoreType;\nclass Uint8ArrayType {\n constructor(len) {\n this.len = len;\n }\n get(array, offset) {\n return array.subarray(offset, offset + this.len);\n }\n}\nexports.Uint8ArrayType = Uint8ArrayType;\nclass BufferType {\n constructor(len) {\n this.len = len;\n }\n get(uint8Array, off) {\n return Buffer.from(uint8Array.subarray(off, off + this.len));\n }\n}\nexports.BufferType = BufferType;\n/**\n * Consume a fixed number of bytes from the stream and return a string with a specified encoding.\n */\nclass StringType {\n constructor(len, encoding) {\n this.len = len;\n this.encoding = encoding;\n }\n get(uint8Array, offset) {\n return Buffer.from(uint8Array).toString(this.encoding, offset, offset + this.len);\n }\n}\nexports.StringType = StringType;\n/**\n * ANSI Latin 1 String\n * Using windows-1252 / ISO 8859-1 decoding\n */\nclass AnsiStringType {\n constructor(len) {\n this.len = len;\n }\n static decode(buffer, offset, until) {\n let str = '';\n for (let i = offset; i < until; ++i) {\n str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i]));\n }\n return str;\n }\n static inRange(a, min, max) {\n return min <= a && a <= max;\n }\n static codePointToString(cp) {\n if (cp <= 0xFFFF) {\n return String.fromCharCode(cp);\n }\n else {\n cp -= 0x10000;\n return String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00);\n }\n }\n static singleByteDecoder(bite) {\n if (AnsiStringType.inRange(bite, 0x00, 0x7F)) {\n return bite;\n }\n const codePoint = AnsiStringType.windows1252[bite - 0x80];\n if (codePoint === null) {\n throw Error('invaliding encoding');\n }\n return codePoint;\n }\n get(buffer, offset = 0) {\n return AnsiStringType.decode(buffer, offset, offset + this.len);\n }\n}\nexports.AnsiStringType = AnsiStringType;\nAnsiStringType.windows1252 = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352,\n 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732,\n 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168,\n 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184,\n 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200,\n 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216,\n 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,\n 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,\n 248, 249, 250, 251, 252, 253, 254, 255];\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.EndOfStreamError = exports.defaultMessages = void 0;\r\nexports.defaultMessages = 'End-Of-Stream';\r\n/**\r\n * Thrown on read operation of the end of file or stream has been reached\r\n */\r\nclass EndOfStreamError extends Error {\r\n constructor() {\r\n super(exports.defaultMessages);\r\n }\r\n}\r\nexports.EndOfStreamError = EndOfStreamError;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.Deferred = void 0;\r\nclass Deferred {\r\n constructor() {\r\n this.resolve = () => null;\r\n this.reject = () => null;\r\n this.promise = new Promise((resolve, reject) => {\r\n this.reject = reject;\r\n this.resolve = resolve;\r\n });\r\n }\r\n}\r\nexports.Deferred = Deferred;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.StreamReader = exports.EndOfStreamError = void 0;\r\nconst EndOfFileStream_1 = require(\"./EndOfFileStream\");\r\nconst Deferred_1 = require(\"./Deferred\");\r\nvar EndOfFileStream_2 = require(\"./EndOfFileStream\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return EndOfFileStream_2.EndOfStreamError; } });\r\nconst maxStreamReadSize = 1 * 1024 * 1024; // Maximum request length on read-stream operation\r\nclass StreamReader {\r\n constructor(s) {\r\n this.s = s;\r\n /**\r\n * Deferred used for postponed read request (as not data is yet available to read)\r\n */\r\n this.deferred = null;\r\n this.endOfStream = false;\r\n /**\r\n * Store peeked data\r\n * @type {Array}\r\n */\r\n this.peekQueue = [];\r\n if (!s.read || !s.once) {\r\n throw new Error('Expected an instance of stream.Readable');\r\n }\r\n this.s.once('end', () => this.reject(new EndOfFileStream_1.EndOfStreamError()));\r\n this.s.once('error', err => this.reject(err));\r\n this.s.once('close', () => this.reject(new Error('Stream closed')));\r\n }\r\n /**\r\n * Read ahead (peek) from stream. Subsequent read or peeks will return the same data\r\n * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset - Offset target\r\n * @param length - Number of bytes to read\r\n * @returns Number of bytes peeked\r\n */\r\n async peek(uint8Array, offset, length) {\r\n const bytesRead = await this.read(uint8Array, offset, length);\r\n this.peekQueue.push(uint8Array.subarray(offset, offset + bytesRead)); // Put read data back to peek buffer\r\n return bytesRead;\r\n }\r\n /**\r\n * Read chunk from stream\r\n * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset - Offset target\r\n * @param length - Number of bytes to read\r\n * @returns Number of bytes read\r\n */\r\n async read(buffer, offset, length) {\r\n if (length === 0) {\r\n return 0;\r\n }\r\n if (this.peekQueue.length === 0 && this.endOfStream) {\r\n throw new EndOfFileStream_1.EndOfStreamError();\r\n }\r\n let remaining = length;\r\n let bytesRead = 0;\r\n // consume peeked data first\r\n while (this.peekQueue.length > 0 && remaining > 0) {\r\n const peekData = this.peekQueue.pop(); // Front of queue\r\n if (!peekData)\r\n throw new Error('peekData should be defined');\r\n const lenCopy = Math.min(peekData.length, remaining);\r\n buffer.set(peekData.subarray(0, lenCopy), offset + bytesRead);\r\n bytesRead += lenCopy;\r\n remaining -= lenCopy;\r\n if (lenCopy < peekData.length) {\r\n // remainder back to queue\r\n this.peekQueue.push(peekData.subarray(lenCopy));\r\n }\r\n }\r\n // continue reading from stream if required\r\n while (remaining > 0 && !this.endOfStream) {\r\n const reqLen = Math.min(remaining, maxStreamReadSize);\r\n const chunkLen = await this.readFromStream(buffer, offset + bytesRead, reqLen);\r\n bytesRead += chunkLen;\r\n if (chunkLen < reqLen)\r\n break;\r\n remaining -= chunkLen;\r\n }\r\n return bytesRead;\r\n }\r\n /**\r\n * Read chunk from stream\r\n * @param buffer Target Uint8Array (or Buffer) to store data read from stream in\r\n * @param offset Offset target\r\n * @param length Number of bytes to read\r\n * @returns Number of bytes read\r\n */\r\n async readFromStream(buffer, offset, length) {\r\n const readBuffer = this.s.read(length);\r\n if (readBuffer) {\r\n buffer.set(readBuffer, offset);\r\n return readBuffer.length;\r\n }\r\n else {\r\n const request = {\r\n buffer,\r\n offset,\r\n length,\r\n deferred: new Deferred_1.Deferred()\r\n };\r\n this.deferred = request.deferred;\r\n this.s.once('readable', () => {\r\n this.readDeferred(request);\r\n });\r\n return request.deferred.promise;\r\n }\r\n }\r\n /**\r\n * Process deferred read request\r\n * @param request Deferred read request\r\n */\r\n readDeferred(request) {\r\n const readBuffer = this.s.read(request.length);\r\n if (readBuffer) {\r\n request.buffer.set(readBuffer, request.offset);\r\n request.deferred.resolve(readBuffer.length);\r\n this.deferred = null;\r\n }\r\n else {\r\n this.s.once('readable', () => {\r\n this.readDeferred(request);\r\n });\r\n }\r\n }\r\n reject(err) {\r\n this.endOfStream = true;\r\n if (this.deferred) {\r\n this.deferred.reject(err);\r\n this.deferred = null;\r\n }\r\n }\r\n}\r\nexports.StreamReader = StreamReader;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.StreamReader = exports.EndOfStreamError = void 0;\r\nvar EndOfFileStream_1 = require(\"./EndOfFileStream\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return EndOfFileStream_1.EndOfStreamError; } });\r\nvar StreamReader_1 = require(\"./StreamReader\");\r\nObject.defineProperty(exports, \"StreamReader\", { enumerable: true, get: function () { return StreamReader_1.StreamReader; } });\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.AbstractTokenizer = void 0;\r\nconst peek_readable_1 = require(\"peek-readable\");\r\n/**\r\n * Core tokenizer\r\n */\r\nclass AbstractTokenizer {\r\n constructor(fileInfo) {\r\n /**\r\n * Tokenizer-stream position\r\n */\r\n this.position = 0;\r\n this.numBuffer = new Uint8Array(8);\r\n this.fileInfo = fileInfo ? fileInfo : {};\r\n }\r\n /**\r\n * Read a token from the tokenizer-stream\r\n * @param token - The token to read\r\n * @param position - If provided, the desired position in the tokenizer-stream\r\n * @returns Promise with token data\r\n */\r\n async readToken(token, position = this.position) {\r\n const uint8Array = Buffer.alloc(token.len);\r\n const len = await this.readBuffer(uint8Array, { position });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(uint8Array, 0);\r\n }\r\n /**\r\n * Peek a token from the tokenizer-stream.\r\n * @param token - Token to peek from the tokenizer-stream.\r\n * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position.\r\n * @returns Promise with token data\r\n */\r\n async peekToken(token, position = this.position) {\r\n const uint8Array = Buffer.alloc(token.len);\r\n const len = await this.peekBuffer(uint8Array, { position });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(uint8Array, 0);\r\n }\r\n /**\r\n * Read a numeric token from the stream\r\n * @param token - Numeric token\r\n * @returns Promise with number\r\n */\r\n async readNumber(token) {\r\n const len = await this.readBuffer(this.numBuffer, { length: token.len });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(this.numBuffer, 0);\r\n }\r\n /**\r\n * Read a numeric token from the stream\r\n * @param token - Numeric token\r\n * @returns Promise with number\r\n */\r\n async peekNumber(token) {\r\n const len = await this.peekBuffer(this.numBuffer, { length: token.len });\r\n if (len < token.len)\r\n throw new peek_readable_1.EndOfStreamError();\r\n return token.get(this.numBuffer, 0);\r\n }\r\n /**\r\n * Ignore number of bytes, advances the pointer in under tokenizer-stream.\r\n * @param length - Number of bytes to ignore\r\n * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available\r\n */\r\n async ignore(length) {\r\n if (this.fileInfo.size !== undefined) {\r\n const bytesLeft = this.fileInfo.size - this.position;\r\n if (length > bytesLeft) {\r\n this.position += bytesLeft;\r\n return bytesLeft;\r\n }\r\n }\r\n this.position += length;\r\n return length;\r\n }\r\n async close() {\r\n // empty\r\n }\r\n normalizeOptions(uint8Array, options) {\r\n if (options && options.position !== undefined && options.position < this.position) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n if (options) {\r\n return {\r\n mayBeLess: options.mayBeLess === true,\r\n offset: options.offset ? options.offset : 0,\r\n length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)),\r\n position: options.position ? options.position : this.position\r\n };\r\n }\r\n return {\r\n mayBeLess: false,\r\n offset: 0,\r\n length: uint8Array.length,\r\n position: this.position\r\n };\r\n }\r\n}\r\nexports.AbstractTokenizer = AbstractTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.ReadStreamTokenizer = void 0;\r\nconst AbstractTokenizer_1 = require(\"./AbstractTokenizer\");\r\nconst peek_readable_1 = require(\"peek-readable\");\r\nconst maxBufferSize = 256000;\r\nclass ReadStreamTokenizer extends AbstractTokenizer_1.AbstractTokenizer {\r\n constructor(stream, fileInfo) {\r\n super(fileInfo);\r\n this.streamReader = new peek_readable_1.StreamReader(stream);\r\n }\r\n /**\r\n * Get file information, an HTTP-client may implement this doing a HEAD request\r\n * @return Promise with file information\r\n */\r\n async getFileInfo() {\r\n return this.fileInfo;\r\n }\r\n /**\r\n * Read buffer from tokenizer\r\n * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream\r\n * @param options - Read behaviour options\r\n * @returns Promise with number of bytes read\r\n */\r\n async readBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const skipBytes = normOptions.position - this.position;\r\n if (skipBytes > 0) {\r\n await this.ignore(skipBytes);\r\n return this.readBuffer(uint8Array, options);\r\n }\r\n else if (skipBytes < 0) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n if (normOptions.length === 0) {\r\n return 0;\r\n }\r\n const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length);\r\n this.position += bytesRead;\r\n if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return bytesRead;\r\n }\r\n /**\r\n * Peek (read ahead) buffer from tokenizer\r\n * @param uint8Array - Uint8Array (or Buffer) to write data to\r\n * @param options - Read behaviour options\r\n * @returns Promise with number of bytes peeked\r\n */\r\n async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n let bytesRead = 0;\r\n if (normOptions.position) {\r\n const skipBytes = normOptions.position - this.position;\r\n if (skipBytes > 0) {\r\n const skipBuffer = new Uint8Array(normOptions.length + skipBytes);\r\n bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess });\r\n uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset);\r\n return bytesRead - skipBytes;\r\n }\r\n else if (skipBytes < 0) {\r\n throw new Error('Cannot peek from a negative offset in a stream');\r\n }\r\n }\r\n if (normOptions.length > 0) {\r\n try {\r\n bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length);\r\n }\r\n catch (err) {\r\n if (options && options.mayBeLess && err instanceof peek_readable_1.EndOfStreamError) {\r\n return 0;\r\n }\r\n throw err;\r\n }\r\n if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n }\r\n return bytesRead;\r\n }\r\n async ignore(length) {\r\n // debug(`ignore ${this.position}...${this.position + length - 1}`);\r\n const bufSize = Math.min(maxBufferSize, length);\r\n const buf = new Uint8Array(bufSize);\r\n let totBytesRead = 0;\r\n while (totBytesRead < length) {\r\n const remaining = length - totBytesRead;\r\n const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) });\r\n if (bytesRead < 0) {\r\n return bytesRead;\r\n }\r\n totBytesRead += bytesRead;\r\n }\r\n return totBytesRead;\r\n }\r\n}\r\nexports.ReadStreamTokenizer = ReadStreamTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.BufferTokenizer = void 0;\r\nconst peek_readable_1 = require(\"peek-readable\");\r\nconst AbstractTokenizer_1 = require(\"./AbstractTokenizer\");\r\nclass BufferTokenizer extends AbstractTokenizer_1.AbstractTokenizer {\r\n /**\r\n * Construct BufferTokenizer\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param fileInfo - Pass additional file information to the tokenizer\r\n */\r\n constructor(uint8Array, fileInfo) {\r\n super(fileInfo);\r\n this.uint8Array = uint8Array;\r\n this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length;\r\n }\r\n /**\r\n * Read buffer from tokenizer\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param options - Read behaviour options\r\n * @returns {Promise}\r\n */\r\n async readBuffer(uint8Array, options) {\r\n if (options && options.position) {\r\n if (options.position < this.position) {\r\n throw new Error('`options.position` must be equal or greater than `tokenizer.position`');\r\n }\r\n this.position = options.position;\r\n }\r\n const bytesRead = await this.peekBuffer(uint8Array, options);\r\n this.position += bytesRead;\r\n return bytesRead;\r\n }\r\n /**\r\n * Peek (read ahead) buffer from tokenizer\r\n * @param uint8Array\r\n * @param options - Read behaviour options\r\n * @returns {Promise}\r\n */\r\n async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length);\r\n if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n else {\r\n uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset);\r\n return bytes2read;\r\n }\r\n }\r\n async close() {\r\n // empty\r\n }\r\n}\r\nexports.BufferTokenizer = BufferTokenizer;\r\n","\"use strict\";\r\nObject.defineProperty(exports, \"__esModule\", { value: true });\r\nexports.fromBuffer = exports.fromStream = exports.EndOfStreamError = void 0;\r\nconst ReadStreamTokenizer_1 = require(\"./ReadStreamTokenizer\");\r\nconst BufferTokenizer_1 = require(\"./BufferTokenizer\");\r\nvar peek_readable_1 = require(\"peek-readable\");\r\nObject.defineProperty(exports, \"EndOfStreamError\", { enumerable: true, get: function () { return peek_readable_1.EndOfStreamError; } });\r\n/**\r\n * Construct ReadStreamTokenizer from given Stream.\r\n * Will set fileSize, if provided given Stream has set the .path property/\r\n * @param stream - Read from Node.js Stream.Readable\r\n * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.\r\n * @returns ReadStreamTokenizer\r\n */\r\nfunction fromStream(stream, fileInfo) {\r\n fileInfo = fileInfo ? fileInfo : {};\r\n return new ReadStreamTokenizer_1.ReadStreamTokenizer(stream, fileInfo);\r\n}\r\nexports.fromStream = fromStream;\r\n/**\r\n * Construct ReadStreamTokenizer from given Buffer.\r\n * @param uint8Array - Uint8Array to tokenize\r\n * @param fileInfo - Pass additional file information to the tokenizer\r\n * @returns BufferTokenizer\r\n */\r\nfunction fromBuffer(uint8Array, fileInfo) {\r\n return new BufferTokenizer_1.BufferTokenizer(uint8Array, fileInfo);\r\n}\r\nexports.fromBuffer = fromBuffer;\r\n","'use strict';\n\nexports.stringToBytes = string => [...string].map(character => character.charCodeAt(0));\n\n/**\nChecks whether the TAR checksum is valid.\n\n@param {Buffer} buffer - The TAR header `[offset ... offset + 512]`.\n@param {number} offset - TAR header offset.\n@returns {boolean} `true` if the TAR checksum is valid, otherwise `false`.\n*/\nexports.tarHeaderChecksumMatches = (buffer, offset = 0) => {\n\tconst readSum = parseInt(buffer.toString('utf8', 148, 154).replace(/\\0.*$/, '').trim(), 8); // Read sum in header\n\tif (isNaN(readSum)) {\n\t\treturn false;\n\t}\n\n\tlet sum = 8 * 0x20; // Initialize signed bit sum\n\n\tfor (let i = offset; i < offset + 148; i++) {\n\t\tsum += buffer[i];\n\t}\n\n\tfor (let i = offset + 156; i < offset + 512; i++) {\n\t\tsum += buffer[i];\n\t}\n\n\treturn readSum === sum;\n};\n\n/**\nID3 UINT32 sync-safe tokenizer token.\n28 bits (representing up to 256MB) integer, the msb is 0 to avoid \"false syncsignals\".\n*/\nexports.uint32SyncSafeToken = {\n\tget: (buffer, offset) => {\n\t\treturn (buffer[offset + 3] & 0x7F) | ((buffer[offset + 2]) << 7) | ((buffer[offset + 1]) << 14) | ((buffer[offset]) << 21);\n\t},\n\tlen: 4\n};\n","'use strict';\n\nmodule.exports = {\n\textensions: [\n\t\t'jpg',\n\t\t'png',\n\t\t'apng',\n\t\t'gif',\n\t\t'webp',\n\t\t'flif',\n\t\t'xcf',\n\t\t'cr2',\n\t\t'cr3',\n\t\t'orf',\n\t\t'arw',\n\t\t'dng',\n\t\t'nef',\n\t\t'rw2',\n\t\t'raf',\n\t\t'tif',\n\t\t'bmp',\n\t\t'icns',\n\t\t'jxr',\n\t\t'psd',\n\t\t'indd',\n\t\t'zip',\n\t\t'tar',\n\t\t'rar',\n\t\t'gz',\n\t\t'bz2',\n\t\t'7z',\n\t\t'dmg',\n\t\t'mp4',\n\t\t'mid',\n\t\t'mkv',\n\t\t'webm',\n\t\t'mov',\n\t\t'avi',\n\t\t'mpg',\n\t\t'mp2',\n\t\t'mp3',\n\t\t'm4a',\n\t\t'oga',\n\t\t'ogg',\n\t\t'ogv',\n\t\t'opus',\n\t\t'flac',\n\t\t'wav',\n\t\t'spx',\n\t\t'amr',\n\t\t'pdf',\n\t\t'epub',\n\t\t'exe',\n\t\t'swf',\n\t\t'rtf',\n\t\t'wasm',\n\t\t'woff',\n\t\t'woff2',\n\t\t'eot',\n\t\t'ttf',\n\t\t'otf',\n\t\t'ico',\n\t\t'flv',\n\t\t'ps',\n\t\t'xz',\n\t\t'sqlite',\n\t\t'nes',\n\t\t'crx',\n\t\t'xpi',\n\t\t'cab',\n\t\t'deb',\n\t\t'ar',\n\t\t'rpm',\n\t\t'Z',\n\t\t'lz',\n\t\t'cfb',\n\t\t'mxf',\n\t\t'mts',\n\t\t'blend',\n\t\t'bpg',\n\t\t'docx',\n\t\t'pptx',\n\t\t'xlsx',\n\t\t'3gp',\n\t\t'3g2',\n\t\t'jp2',\n\t\t'jpm',\n\t\t'jpx',\n\t\t'mj2',\n\t\t'aif',\n\t\t'qcp',\n\t\t'odt',\n\t\t'ods',\n\t\t'odp',\n\t\t'xml',\n\t\t'mobi',\n\t\t'heic',\n\t\t'cur',\n\t\t'ktx',\n\t\t'ape',\n\t\t'wv',\n\t\t'dcm',\n\t\t'ics',\n\t\t'glb',\n\t\t'pcap',\n\t\t'dsf',\n\t\t'lnk',\n\t\t'alias',\n\t\t'voc',\n\t\t'ac3',\n\t\t'm4v',\n\t\t'm4p',\n\t\t'm4b',\n\t\t'f4v',\n\t\t'f4p',\n\t\t'f4b',\n\t\t'f4a',\n\t\t'mie',\n\t\t'asf',\n\t\t'ogm',\n\t\t'ogx',\n\t\t'mpc',\n\t\t'arrow',\n\t\t'shp',\n\t\t'aac',\n\t\t'mp1',\n\t\t'it',\n\t\t's3m',\n\t\t'xm',\n\t\t'ai',\n\t\t'skp',\n\t\t'avif',\n\t\t'eps',\n\t\t'lzh',\n\t\t'pgp',\n\t\t'asar',\n\t\t'stl',\n\t\t'chm',\n\t\t'3mf',\n\t\t'zst',\n\t\t'jxl',\n\t\t'vcf'\n\t],\n\tmimeTypes: [\n\t\t'image/jpeg',\n\t\t'image/png',\n\t\t'image/gif',\n\t\t'image/webp',\n\t\t'image/flif',\n\t\t'image/x-xcf',\n\t\t'image/x-canon-cr2',\n\t\t'image/x-canon-cr3',\n\t\t'image/tiff',\n\t\t'image/bmp',\n\t\t'image/vnd.ms-photo',\n\t\t'image/vnd.adobe.photoshop',\n\t\t'application/x-indesign',\n\t\t'application/epub+zip',\n\t\t'application/x-xpinstall',\n\t\t'application/vnd.oasis.opendocument.text',\n\t\t'application/vnd.oasis.opendocument.spreadsheet',\n\t\t'application/vnd.oasis.opendocument.presentation',\n\t\t'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\t\t'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n\t\t'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\t\t'application/zip',\n\t\t'application/x-tar',\n\t\t'application/x-rar-compressed',\n\t\t'application/gzip',\n\t\t'application/x-bzip2',\n\t\t'application/x-7z-compressed',\n\t\t'application/x-apple-diskimage',\n\t\t'application/x-apache-arrow',\n\t\t'video/mp4',\n\t\t'audio/midi',\n\t\t'video/x-matroska',\n\t\t'video/webm',\n\t\t'video/quicktime',\n\t\t'video/vnd.avi',\n\t\t'audio/vnd.wave',\n\t\t'audio/qcelp',\n\t\t'audio/x-ms-asf',\n\t\t'video/x-ms-asf',\n\t\t'application/vnd.ms-asf',\n\t\t'video/mpeg',\n\t\t'video/3gpp',\n\t\t'audio/mpeg',\n\t\t'audio/mp4', // RFC 4337\n\t\t'audio/opus',\n\t\t'video/ogg',\n\t\t'audio/ogg',\n\t\t'application/ogg',\n\t\t'audio/x-flac',\n\t\t'audio/ape',\n\t\t'audio/wavpack',\n\t\t'audio/amr',\n\t\t'application/pdf',\n\t\t'application/x-msdownload',\n\t\t'application/x-shockwave-flash',\n\t\t'application/rtf',\n\t\t'application/wasm',\n\t\t'font/woff',\n\t\t'font/woff2',\n\t\t'application/vnd.ms-fontobject',\n\t\t'font/ttf',\n\t\t'font/otf',\n\t\t'image/x-icon',\n\t\t'video/x-flv',\n\t\t'application/postscript',\n\t\t'application/eps',\n\t\t'application/x-xz',\n\t\t'application/x-sqlite3',\n\t\t'application/x-nintendo-nes-rom',\n\t\t'application/x-google-chrome-extension',\n\t\t'application/vnd.ms-cab-compressed',\n\t\t'application/x-deb',\n\t\t'application/x-unix-archive',\n\t\t'application/x-rpm',\n\t\t'application/x-compress',\n\t\t'application/x-lzip',\n\t\t'application/x-cfb',\n\t\t'application/x-mie',\n\t\t'application/mxf',\n\t\t'video/mp2t',\n\t\t'application/x-blender',\n\t\t'image/bpg',\n\t\t'image/jp2',\n\t\t'image/jpx',\n\t\t'image/jpm',\n\t\t'image/mj2',\n\t\t'audio/aiff',\n\t\t'application/xml',\n\t\t'application/x-mobipocket-ebook',\n\t\t'image/heif',\n\t\t'image/heif-sequence',\n\t\t'image/heic',\n\t\t'image/heic-sequence',\n\t\t'image/icns',\n\t\t'image/ktx',\n\t\t'application/dicom',\n\t\t'audio/x-musepack',\n\t\t'text/calendar',\n\t\t'text/vcard',\n\t\t'model/gltf-binary',\n\t\t'application/vnd.tcpdump.pcap',\n\t\t'audio/x-dsf', // Non-standard\n\t\t'application/x.ms.shortcut', // Invented by us\n\t\t'application/x.apple.alias', // Invented by us\n\t\t'audio/x-voc',\n\t\t'audio/vnd.dolby.dd-raw',\n\t\t'audio/x-m4a',\n\t\t'image/apng',\n\t\t'image/x-olympus-orf',\n\t\t'image/x-sony-arw',\n\t\t'image/x-adobe-dng',\n\t\t'image/x-nikon-nef',\n\t\t'image/x-panasonic-rw2',\n\t\t'image/x-fujifilm-raf',\n\t\t'video/x-m4v',\n\t\t'video/3gpp2',\n\t\t'application/x-esri-shape',\n\t\t'audio/aac',\n\t\t'audio/x-it',\n\t\t'audio/x-s3m',\n\t\t'audio/x-xm',\n\t\t'video/MP1S',\n\t\t'video/MP2P',\n\t\t'application/vnd.sketchup.skp',\n\t\t'image/avif',\n\t\t'application/x-lzh-compressed',\n\t\t'application/pgp-encrypted',\n\t\t'application/x-asar',\n\t\t'model/stl',\n\t\t'application/vnd.ms-htmlhelp',\n\t\t'model/3mf',\n\t\t'image/jxl',\n\t\t'application/zstd'\n\t]\n};\n","'use strict';\nconst Token = require('token-types');\nconst strtok3 = require('strtok3/lib/core');\nconst {\n\tstringToBytes,\n\ttarHeaderChecksumMatches,\n\tuint32SyncSafeToken\n} = require('./util');\nconst supported = require('./supported');\n\nconst minimumBytes = 4100; // A fair amount of file-types are detectable within this range\n\nasync function fromStream(stream) {\n\tconst tokenizer = await strtok3.fromStream(stream);\n\ttry {\n\t\treturn await fromTokenizer(tokenizer);\n\t} finally {\n\t\tawait tokenizer.close();\n\t}\n}\n\nasync function fromBuffer(input) {\n\tif (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {\n\t\tthrow new TypeError(`Expected the \\`input\\` argument to be of type \\`Uint8Array\\` or \\`Buffer\\` or \\`ArrayBuffer\\`, got \\`${typeof input}\\``);\n\t}\n\n\tconst buffer = input instanceof Buffer ? input : Buffer.from(input);\n\n\tif (!(buffer && buffer.length > 1)) {\n\t\treturn;\n\t}\n\n\tconst tokenizer = strtok3.fromBuffer(buffer);\n\treturn fromTokenizer(tokenizer);\n}\n\nfunction _check(buffer, headers, options) {\n\toptions = {\n\t\toffset: 0,\n\t\t...options\n\t};\n\n\tfor (const [index, header] of headers.entries()) {\n\t\t// If a bitmask is set\n\t\tif (options.mask) {\n\t\t\t// If header doesn't equal `buf` with bits masked off\n\t\t\tif (header !== (options.mask[index] & buffer[index + options.offset])) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (header !== buffer[index + options.offset]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nasync function fromTokenizer(tokenizer) {\n\ttry {\n\t\treturn _fromTokenizer(tokenizer);\n\t} catch (error) {\n\t\tif (!(error instanceof strtok3.EndOfStreamError)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nasync function _fromTokenizer(tokenizer) {\n\tlet buffer = Buffer.alloc(minimumBytes);\n\tconst bytesRead = 12;\n\tconst check = (header, options) => _check(buffer, header, options);\n\tconst checkString = (header, options) => check(stringToBytes(header), options);\n\n\t// Keep reading until EOF if the file size is unknown.\n\tif (!tokenizer.fileInfo.size) {\n\t\ttokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER;\n\t}\n\n\tawait tokenizer.peekBuffer(buffer, {length: bytesRead, mayBeLess: true});\n\n\t// -- 2-byte signatures --\n\n\tif (check([0x42, 0x4D])) {\n\t\treturn {\n\t\t\text: 'bmp',\n\t\t\tmime: 'image/bmp'\n\t\t};\n\t}\n\n\tif (check([0x0B, 0x77])) {\n\t\treturn {\n\t\t\text: 'ac3',\n\t\t\tmime: 'audio/vnd.dolby.dd-raw'\n\t\t};\n\t}\n\n\tif (check([0x78, 0x01])) {\n\t\treturn {\n\t\t\text: 'dmg',\n\t\t\tmime: 'application/x-apple-diskimage'\n\t\t};\n\t}\n\n\tif (check([0x4D, 0x5A])) {\n\t\treturn {\n\t\t\text: 'exe',\n\t\t\tmime: 'application/x-msdownload'\n\t\t};\n\t}\n\n\tif (check([0x25, 0x21])) {\n\t\tawait tokenizer.peekBuffer(buffer, {length: 24, mayBeLess: true});\n\n\t\tif (checkString('PS-Adobe-', {offset: 2}) &&\n\t\t\tcheckString(' EPSF-', {offset: 14})) {\n\t\t\treturn {\n\t\t\t\text: 'eps',\n\t\t\t\tmime: 'application/eps'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'ps',\n\t\t\tmime: 'application/postscript'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x1F, 0xA0]) ||\n\t\tcheck([0x1F, 0x9D])\n\t) {\n\t\treturn {\n\t\t\text: 'Z',\n\t\t\tmime: 'application/x-compress'\n\t\t};\n\t}\n\n\t// -- 3-byte signatures --\n\n\tif (check([0xFF, 0xD8, 0xFF])) {\n\t\treturn {\n\t\t\text: 'jpg',\n\t\t\tmime: 'image/jpeg'\n\t\t};\n\t}\n\n\tif (check([0x49, 0x49, 0xBC])) {\n\t\treturn {\n\t\t\text: 'jxr',\n\t\t\tmime: 'image/vnd.ms-photo'\n\t\t};\n\t}\n\n\tif (check([0x1F, 0x8B, 0x8])) {\n\t\treturn {\n\t\t\text: 'gz',\n\t\t\tmime: 'application/gzip'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x5A, 0x68])) {\n\t\treturn {\n\t\t\text: 'bz2',\n\t\t\tmime: 'application/x-bzip2'\n\t\t};\n\t}\n\n\tif (checkString('ID3')) {\n\t\tawait tokenizer.ignore(6); // Skip ID3 header until the header size\n\t\tconst id3HeaderLen = await tokenizer.readToken(uint32SyncSafeToken);\n\t\tif (tokenizer.position + id3HeaderLen > tokenizer.fileInfo.size) {\n\t\t\t// Guess file type based on ID3 header for backward compatibility\n\t\t\treturn {\n\t\t\t\text: 'mp3',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\tawait tokenizer.ignore(id3HeaderLen);\n\t\treturn fromTokenizer(tokenizer); // Skip ID3 header, recursion\n\t}\n\n\t// Musepack, SV7\n\tif (checkString('MP+')) {\n\t\treturn {\n\t\t\text: 'mpc',\n\t\t\tmime: 'audio/x-musepack'\n\t\t};\n\t}\n\n\tif (\n\t\t(buffer[0] === 0x43 || buffer[0] === 0x46) &&\n\t\tcheck([0x57, 0x53], {offset: 1})\n\t) {\n\t\treturn {\n\t\t\text: 'swf',\n\t\t\tmime: 'application/x-shockwave-flash'\n\t\t};\n\t}\n\n\t// -- 4-byte signatures --\n\n\tif (check([0x47, 0x49, 0x46])) {\n\t\treturn {\n\t\t\text: 'gif',\n\t\t\tmime: 'image/gif'\n\t\t};\n\t}\n\n\tif (checkString('FLIF')) {\n\t\treturn {\n\t\t\text: 'flif',\n\t\t\tmime: 'image/flif'\n\t\t};\n\t}\n\n\tif (checkString('8BPS')) {\n\t\treturn {\n\t\t\text: 'psd',\n\t\t\tmime: 'image/vnd.adobe.photoshop'\n\t\t};\n\t}\n\n\tif (checkString('WEBP', {offset: 8})) {\n\t\treturn {\n\t\t\text: 'webp',\n\t\t\tmime: 'image/webp'\n\t\t};\n\t}\n\n\t// Musepack, SV8\n\tif (checkString('MPCK')) {\n\t\treturn {\n\t\t\text: 'mpc',\n\t\t\tmime: 'audio/x-musepack'\n\t\t};\n\t}\n\n\tif (checkString('FORM')) {\n\t\treturn {\n\t\t\text: 'aif',\n\t\t\tmime: 'audio/aiff'\n\t\t};\n\t}\n\n\tif (checkString('icns', {offset: 0})) {\n\t\treturn {\n\t\t\text: 'icns',\n\t\t\tmime: 'image/icns'\n\t\t};\n\t}\n\n\t// Zip-based file formats\n\t// Need to be before the `zip` check\n\tif (check([0x50, 0x4B, 0x3, 0x4])) { // Local file header signature\n\t\ttry {\n\t\t\twhile (tokenizer.position + 30 < tokenizer.fileInfo.size) {\n\t\t\t\tawait tokenizer.readBuffer(buffer, {length: 30});\n\n\t\t\t\t// https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers\n\t\t\t\tconst zipHeader = {\n\t\t\t\t\tcompressedSize: buffer.readUInt32LE(18),\n\t\t\t\t\tuncompressedSize: buffer.readUInt32LE(22),\n\t\t\t\t\tfilenameLength: buffer.readUInt16LE(26),\n\t\t\t\t\textraFieldLength: buffer.readUInt16LE(28)\n\t\t\t\t};\n\n\t\t\t\tzipHeader.filename = await tokenizer.readToken(new Token.StringType(zipHeader.filenameLength, 'utf-8'));\n\t\t\t\tawait tokenizer.ignore(zipHeader.extraFieldLength);\n\n\t\t\t\t// Assumes signed `.xpi` from addons.mozilla.org\n\t\t\t\tif (zipHeader.filename === 'META-INF/mozilla.rsa') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'xpi',\n\t\t\t\t\t\tmime: 'application/x-xpinstall'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.endsWith('.rels') || zipHeader.filename.endsWith('.xml')) {\n\t\t\t\t\tconst type = zipHeader.filename.split('/')[0];\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase '_rels':\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'word':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'docx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'ppt':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'pptx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'xl':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'xlsx',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.startsWith('xl/')) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'xlsx',\n\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (zipHeader.filename.startsWith('3D/') && zipHeader.filename.endsWith('.model')) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: '3mf',\n\t\t\t\t\t\tmime: 'model/3mf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// The docx, xlsx and pptx file types extend the Office Open XML file format:\n\t\t\t\t// https://en.wikipedia.org/wiki/Office_Open_XML_file_formats\n\t\t\t\t// We look for:\n\t\t\t\t// - one entry named '[Content_Types].xml' or '_rels/.rels',\n\t\t\t\t// - one entry indicating specific type of file.\n\t\t\t\t// MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.\n\t\t\t\tif (zipHeader.filename === 'mimetype' && zipHeader.compressedSize === zipHeader.uncompressedSize) {\n\t\t\t\t\tconst mimeType = await tokenizer.readToken(new Token.StringType(zipHeader.compressedSize, 'utf-8'));\n\n\t\t\t\t\tswitch (mimeType) {\n\t\t\t\t\t\tcase 'application/epub+zip':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'epub',\n\t\t\t\t\t\t\t\tmime: 'application/epub+zip'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.text':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'odt',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.text'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.spreadsheet':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'ods',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.spreadsheet'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tcase 'application/vnd.oasis.opendocument.presentation':\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\text: 'odp',\n\t\t\t\t\t\t\t\tmime: 'application/vnd.oasis.opendocument.presentation'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Try to find next header manually when current one is corrupted\n\t\t\t\tif (zipHeader.compressedSize === 0) {\n\t\t\t\t\tlet nextHeaderIndex = -1;\n\n\t\t\t\t\twhile (nextHeaderIndex < 0 && (tokenizer.position < tokenizer.fileInfo.size)) {\n\t\t\t\t\t\tawait tokenizer.peekBuffer(buffer, {mayBeLess: true});\n\n\t\t\t\t\t\tnextHeaderIndex = buffer.indexOf('504B0304', 0, 'hex');\n\t\t\t\t\t\t// Move position to the next header if found, skip the whole buffer otherwise\n\t\t\t\t\t\tawait tokenizer.ignore(nextHeaderIndex >= 0 ? nextHeaderIndex : buffer.length);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tawait tokenizer.ignore(zipHeader.compressedSize);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof strtok3.EndOfStreamError)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\text: 'zip',\n\t\t\tmime: 'application/zip'\n\t\t};\n\t}\n\n\tif (checkString('OggS')) {\n\t\t// This is an OGG container\n\t\tawait tokenizer.ignore(28);\n\t\tconst type = Buffer.alloc(8);\n\t\tawait tokenizer.readBuffer(type);\n\n\t\t// Needs to be before `ogg` check\n\t\tif (_check(type, [0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64])) {\n\t\t\treturn {\n\t\t\t\text: 'opus',\n\t\t\t\tmime: 'audio/opus'\n\t\t\t};\n\t\t}\n\n\t\t// If ' theora' in header.\n\t\tif (_check(type, [0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61])) {\n\t\t\treturn {\n\t\t\t\text: 'ogv',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01video' in header.\n\t\tif (_check(type, [0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00])) {\n\t\t\treturn {\n\t\t\t\text: 'ogm',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If ' FLAC' in header https://xiph.org/flac/faq.html\n\t\tif (_check(type, [0x7F, 0x46, 0x4C, 0x41, 0x43])) {\n\t\t\treturn {\n\t\t\t\text: 'oga',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// 'Speex ' in header https://en.wikipedia.org/wiki/Speex\n\t\tif (_check(type, [0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20])) {\n\t\t\treturn {\n\t\t\t\text: 'spx',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01vorbis' in header\n\t\tif (_check(type, [0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73])) {\n\t\t\treturn {\n\t\t\t\text: 'ogg',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// Default OGG container https://www.iana.org/assignments/media-types/application/ogg\n\t\treturn {\n\t\t\text: 'ogx',\n\t\t\tmime: 'application/ogg'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x50, 0x4B]) &&\n\t\t(buffer[2] === 0x3 || buffer[2] === 0x5 || buffer[2] === 0x7) &&\n\t\t(buffer[3] === 0x4 || buffer[3] === 0x6 || buffer[3] === 0x8)\n\t) {\n\t\treturn {\n\t\t\text: 'zip',\n\t\t\tmime: 'application/zip'\n\t\t};\n\t}\n\n\t//\n\n\t// File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)\n\t// It's not required to be first, but it's recommended to be. Almost all ISO base media files start with `ftyp` box.\n\t// `ftyp` box must contain a brand major identifier, which must consist of ISO 8859-1 printable characters.\n\t// Here we check for 8859-1 printable characters (for simplicity, it's a mask which also catches one non-printable character).\n\tif (\n\t\tcheckString('ftyp', {offset: 4}) &&\n\t\t(buffer[8] & 0x60) !== 0x00 // Brand major, first character ASCII?\n\t) {\n\t\t// They all can have MIME `video/mp4` except `application/mp4` special-case which is hard to detect.\n\t\t// For some cases, we're specific, everything else falls to `video/mp4` with `mp4` extension.\n\t\tconst brandMajor = buffer.toString('binary', 8, 12).replace('\\0', ' ').trim();\n\t\tswitch (brandMajor) {\n\t\t\tcase 'avif':\n\t\t\t\treturn {ext: 'avif', mime: 'image/avif'};\n\t\t\tcase 'mif1':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heif'};\n\t\t\tcase 'msf1':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heif-sequence'};\n\t\t\tcase 'heic':\n\t\t\tcase 'heix':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heic'};\n\t\t\tcase 'hevc':\n\t\t\tcase 'hevx':\n\t\t\t\treturn {ext: 'heic', mime: 'image/heic-sequence'};\n\t\t\tcase 'qt':\n\t\t\t\treturn {ext: 'mov', mime: 'video/quicktime'};\n\t\t\tcase 'M4V':\n\t\t\tcase 'M4VH':\n\t\t\tcase 'M4VP':\n\t\t\t\treturn {ext: 'm4v', mime: 'video/x-m4v'};\n\t\t\tcase 'M4P':\n\t\t\t\treturn {ext: 'm4p', mime: 'video/mp4'};\n\t\t\tcase 'M4B':\n\t\t\t\treturn {ext: 'm4b', mime: 'audio/mp4'};\n\t\t\tcase 'M4A':\n\t\t\t\treturn {ext: 'm4a', mime: 'audio/x-m4a'};\n\t\t\tcase 'F4V':\n\t\t\t\treturn {ext: 'f4v', mime: 'video/mp4'};\n\t\t\tcase 'F4P':\n\t\t\t\treturn {ext: 'f4p', mime: 'video/mp4'};\n\t\t\tcase 'F4A':\n\t\t\t\treturn {ext: 'f4a', mime: 'audio/mp4'};\n\t\t\tcase 'F4B':\n\t\t\t\treturn {ext: 'f4b', mime: 'audio/mp4'};\n\t\t\tcase 'crx':\n\t\t\t\treturn {ext: 'cr3', mime: 'image/x-canon-cr3'};\n\t\t\tdefault:\n\t\t\t\tif (brandMajor.startsWith('3g')) {\n\t\t\t\t\tif (brandMajor.startsWith('3g2')) {\n\t\t\t\t\t\treturn {ext: '3g2', mime: 'video/3gpp2'};\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {ext: '3gp', mime: 'video/3gpp'};\n\t\t\t\t}\n\n\t\t\t\treturn {ext: 'mp4', mime: 'video/mp4'};\n\t\t}\n\t}\n\n\tif (checkString('MThd')) {\n\t\treturn {\n\t\t\text: 'mid',\n\t\t\tmime: 'audio/midi'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('wOFF') &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheckString('OTTO', {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff',\n\t\t\tmime: 'font/woff'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('wOF2') &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheckString('OTTO', {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff2',\n\t\t\tmime: 'font/woff2'\n\t\t};\n\t}\n\n\tif (check([0xD4, 0xC3, 0xB2, 0xA1]) || check([0xA1, 0xB2, 0xC3, 0xD4])) {\n\t\treturn {\n\t\t\text: 'pcap',\n\t\t\tmime: 'application/vnd.tcpdump.pcap'\n\t\t};\n\t}\n\n\t// Sony DSD Stream File (DSF)\n\tif (checkString('DSD ')) {\n\t\treturn {\n\t\t\text: 'dsf',\n\t\t\tmime: 'audio/x-dsf' // Non-standard\n\t\t};\n\t}\n\n\tif (checkString('LZIP')) {\n\t\treturn {\n\t\t\text: 'lz',\n\t\t\tmime: 'application/x-lzip'\n\t\t};\n\t}\n\n\tif (checkString('fLaC')) {\n\t\treturn {\n\t\t\text: 'flac',\n\t\t\tmime: 'audio/x-flac'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x50, 0x47, 0xFB])) {\n\t\treturn {\n\t\t\text: 'bpg',\n\t\t\tmime: 'image/bpg'\n\t\t};\n\t}\n\n\tif (checkString('wvpk')) {\n\t\treturn {\n\t\t\text: 'wv',\n\t\t\tmime: 'audio/wavpack'\n\t\t};\n\t}\n\n\tif (checkString('%PDF')) {\n\t\tawait tokenizer.ignore(1350);\n\t\tconst maxBufferSize = 10 * 1024 * 1024;\n\t\tconst buffer = Buffer.alloc(Math.min(maxBufferSize, tokenizer.fileInfo.size));\n\t\tawait tokenizer.readBuffer(buffer, {mayBeLess: true});\n\n\t\t// Check if this is an Adobe Illustrator file\n\t\tif (buffer.includes(Buffer.from('AIPrivateData'))) {\n\t\t\treturn {\n\t\t\t\text: 'ai',\n\t\t\t\tmime: 'application/postscript'\n\t\t\t};\n\t\t}\n\n\t\t// Assume this is just a normal PDF\n\t\treturn {\n\t\t\text: 'pdf',\n\t\t\tmime: 'application/pdf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x61, 0x73, 0x6D])) {\n\t\treturn {\n\t\t\text: 'wasm',\n\t\t\tmime: 'application/wasm'\n\t\t};\n\t}\n\n\t// TIFF, little-endian type\n\tif (check([0x49, 0x49, 0x2A, 0x0])) {\n\t\tif (checkString('CR', {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'cr2',\n\t\t\t\tmime: 'image/x-canon-cr2'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x1C, 0x00, 0xFE, 0x00], {offset: 8}) || check([0x1F, 0x00, 0x0B, 0x00], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'nef',\n\t\t\t\tmime: 'image/x-nikon-nef'\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcheck([0x08, 0x00, 0x00, 0x00], {offset: 4}) &&\n\t\t\t(check([0x2D, 0x00, 0xFE, 0x00], {offset: 8}) ||\n\t\t\t\tcheck([0x27, 0x00, 0xFE, 0x00], {offset: 8}))\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'dng',\n\t\t\t\tmime: 'image/x-adobe-dng'\n\t\t\t};\n\t\t}\n\n\t\tbuffer = Buffer.alloc(24);\n\t\tawait tokenizer.peekBuffer(buffer);\n\t\tif (\n\t\t\t(check([0x10, 0xFB, 0x86, 0x01], {offset: 4}) || check([0x08, 0x00, 0x00, 0x00], {offset: 4})) &&\n\t\t\t// This pattern differentiates ARW from other TIFF-ish file types:\n\t\t\tcheck([0x00, 0xFE, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x01], {offset: 9})\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'arw',\n\t\t\t\tmime: 'image/x-sony-arw'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'tif',\n\t\t\tmime: 'image/tiff'\n\t\t};\n\t}\n\n\t// TIFF, big-endian type\n\tif (check([0x4D, 0x4D, 0x0, 0x2A])) {\n\t\treturn {\n\t\t\text: 'tif',\n\t\t\tmime: 'image/tiff'\n\t\t};\n\t}\n\n\tif (checkString('MAC ')) {\n\t\treturn {\n\t\t\text: 'ape',\n\t\t\tmime: 'audio/ape'\n\t\t};\n\t}\n\n\t// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska\n\tif (check([0x1A, 0x45, 0xDF, 0xA3])) { // Root element: EBML\n\t\tasync function readField() {\n\t\t\tconst msb = await tokenizer.peekNumber(Token.UINT8);\n\t\t\tlet mask = 0x80;\n\t\t\tlet ic = 0; // 0 = A, 1 = B, 2 = C, 3 = D\n\n\t\t\twhile ((msb & mask) === 0 && mask !== 0) {\n\t\t\t\t++ic;\n\t\t\t\tmask >>= 1;\n\t\t\t}\n\n\t\t\tconst id = Buffer.alloc(ic + 1);\n\t\t\tawait tokenizer.readBuffer(id);\n\t\t\treturn id;\n\t\t}\n\n\t\tasync function readElement() {\n\t\t\tconst id = await readField();\n\t\t\tconst lenField = await readField();\n\t\t\tlenField[0] ^= 0x80 >> (lenField.length - 1);\n\t\t\tconst nrLen = Math.min(6, lenField.length); // JavaScript can max read 6 bytes integer\n\t\t\treturn {\n\t\t\t\tid: id.readUIntBE(0, id.length),\n\t\t\t\tlen: lenField.readUIntBE(lenField.length - nrLen, nrLen)\n\t\t\t};\n\t\t}\n\n\t\tasync function readChildren(level, children) {\n\t\t\twhile (children > 0) {\n\t\t\t\tconst e = await readElement();\n\t\t\t\tif (e.id === 0x4282) {\n\t\t\t\t\treturn tokenizer.readToken(new Token.StringType(e.len, 'utf-8')); // Return DocType\n\t\t\t\t}\n\n\t\t\t\tawait tokenizer.ignore(e.len); // ignore payload\n\t\t\t\t--children;\n\t\t\t}\n\t\t}\n\n\t\tconst re = await readElement();\n\t\tconst docType = await readChildren(1, re.len);\n\n\t\tswitch (docType) {\n\t\t\tcase 'webm':\n\t\t\t\treturn {\n\t\t\t\t\text: 'webm',\n\t\t\t\t\tmime: 'video/webm'\n\t\t\t\t};\n\n\t\t\tcase 'matroska':\n\t\t\t\treturn {\n\t\t\t\t\text: 'mkv',\n\t\t\t\t\tmime: 'video/x-matroska'\n\t\t\t\t};\n\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\t// RIFF file format which might be AVI, WAV, QCP, etc\n\tif (check([0x52, 0x49, 0x46, 0x46])) {\n\t\tif (check([0x41, 0x56, 0x49], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'avi',\n\t\t\t\tmime: 'video/vnd.avi'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'wav',\n\t\t\t\tmime: 'audio/vnd.wave'\n\t\t\t};\n\t\t}\n\n\t\t// QLCM, QCP file\n\t\tif (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'qcp',\n\t\t\t\tmime: 'audio/qcelp'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (checkString('SQLi')) {\n\t\treturn {\n\t\t\text: 'sqlite',\n\t\t\tmime: 'application/x-sqlite3'\n\t\t};\n\t}\n\n\tif (check([0x4E, 0x45, 0x53, 0x1A])) {\n\t\treturn {\n\t\t\text: 'nes',\n\t\t\tmime: 'application/x-nintendo-nes-rom'\n\t\t};\n\t}\n\n\tif (checkString('Cr24')) {\n\t\treturn {\n\t\t\text: 'crx',\n\t\t\tmime: 'application/x-google-chrome-extension'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('MSCF') ||\n\t\tcheckString('ISc(')\n\t) {\n\t\treturn {\n\t\t\text: 'cab',\n\t\t\tmime: 'application/vnd.ms-cab-compressed'\n\t\t};\n\t}\n\n\tif (check([0xED, 0xAB, 0xEE, 0xDB])) {\n\t\treturn {\n\t\t\text: 'rpm',\n\t\t\tmime: 'application/x-rpm'\n\t\t};\n\t}\n\n\tif (check([0xC5, 0xD0, 0xD3, 0xC6])) {\n\t\treturn {\n\t\t\text: 'eps',\n\t\t\tmime: 'application/eps'\n\t\t};\n\t}\n\n\tif (check([0x28, 0xB5, 0x2F, 0xFD])) {\n\t\treturn {\n\t\t\text: 'zst',\n\t\t\tmime: 'application/zstd'\n\t\t};\n\t}\n\n\t// -- 5-byte signatures --\n\n\tif (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {\n\t\treturn {\n\t\t\text: 'otf',\n\t\t\tmime: 'font/otf'\n\t\t};\n\t}\n\n\tif (checkString('#!AMR')) {\n\t\treturn {\n\t\t\text: 'amr',\n\t\t\tmime: 'audio/amr'\n\t\t};\n\t}\n\n\tif (checkString('{\\\\rtf')) {\n\t\treturn {\n\t\t\text: 'rtf',\n\t\t\tmime: 'application/rtf'\n\t\t};\n\t}\n\n\tif (check([0x46, 0x4C, 0x56, 0x01])) {\n\t\treturn {\n\t\t\text: 'flv',\n\t\t\tmime: 'video/x-flv'\n\t\t};\n\t}\n\n\tif (checkString('IMPM')) {\n\t\treturn {\n\t\t\text: 'it',\n\t\t\tmime: 'audio/x-it'\n\t\t};\n\t}\n\n\tif (\n\t\tcheckString('-lh0-', {offset: 2}) ||\n\t\tcheckString('-lh1-', {offset: 2}) ||\n\t\tcheckString('-lh2-', {offset: 2}) ||\n\t\tcheckString('-lh3-', {offset: 2}) ||\n\t\tcheckString('-lh4-', {offset: 2}) ||\n\t\tcheckString('-lh5-', {offset: 2}) ||\n\t\tcheckString('-lh6-', {offset: 2}) ||\n\t\tcheckString('-lh7-', {offset: 2}) ||\n\t\tcheckString('-lzs-', {offset: 2}) ||\n\t\tcheckString('-lz4-', {offset: 2}) ||\n\t\tcheckString('-lz5-', {offset: 2}) ||\n\t\tcheckString('-lhd-', {offset: 2})\n\t) {\n\t\treturn {\n\t\t\text: 'lzh',\n\t\t\tmime: 'application/x-lzh-compressed'\n\t\t};\n\t}\n\n\t// MPEG program stream (PS or MPEG-PS)\n\tif (check([0x00, 0x00, 0x01, 0xBA])) {\n\t\t// MPEG-PS, MPEG-1 Part 1\n\t\tif (check([0x21], {offset: 4, mask: [0xF1]})) {\n\t\t\treturn {\n\t\t\t\text: 'mpg', // May also be .ps, .mpeg\n\t\t\t\tmime: 'video/MP1S'\n\t\t\t};\n\t\t}\n\n\t\t// MPEG-PS, MPEG-2 Part 1\n\t\tif (check([0x44], {offset: 4, mask: [0xC4]})) {\n\t\t\treturn {\n\t\t\t\text: 'mpg', // May also be .mpg, .m2p, .vob or .sub\n\t\t\t\tmime: 'video/MP2P'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (checkString('ITSF')) {\n\t\treturn {\n\t\t\text: 'chm',\n\t\t\tmime: 'application/vnd.ms-htmlhelp'\n\t\t};\n\t}\n\n\t// -- 6-byte signatures --\n\n\tif (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {\n\t\treturn {\n\t\t\text: 'xz',\n\t\t\tmime: 'application/x-xz'\n\t\t};\n\t}\n\n\tif (checkString('')) {\n\t\tawait tokenizer.ignore(8);\n\t\tconst str = await tokenizer.readToken(new Token.StringType(13, 'ascii'));\n\t\tif (str === 'debian-binary') {\n\t\t\treturn {\n\t\t\t\text: 'deb',\n\t\t\t\tmime: 'application/x-deb'\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\text: 'ar',\n\t\t\tmime: 'application/x-unix-archive'\n\t\t};\n\t}\n\n\t// -- 8-byte signatures --\n\n\tif (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {\n\t\t// APNG format (https://wiki.mozilla.org/APNG_Specification)\n\t\t// 1. Find the first IDAT (image data) chunk (49 44 41 54)\n\t\t// 2. Check if there is an \"acTL\" chunk before the IDAT one (61 63 54 4C)\n\n\t\t// Offset calculated as follows:\n\t\t// - 8 bytes: PNG signature\n\t\t// - 4 (length) + 4 (chunk type) + 13 (chunk data) + 4 (CRC): IHDR chunk\n\n\t\tawait tokenizer.ignore(8); // ignore PNG signature\n\n\t\tasync function readChunkHeader() {\n\t\t\treturn {\n\t\t\t\tlength: await tokenizer.readToken(Token.INT32_BE),\n\t\t\t\ttype: await tokenizer.readToken(new Token.StringType(4, 'binary'))\n\t\t\t};\n\t\t}\n\n\t\tdo {\n\t\t\tconst chunk = await readChunkHeader();\n\t\t\tif (chunk.length < 0) {\n\t\t\t\treturn; // Invalid chunk length\n\t\t\t}\n\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase 'IDAT':\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'png',\n\t\t\t\t\t\tmime: 'image/png'\n\t\t\t\t\t};\n\t\t\t\tcase 'acTL':\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'apng',\n\t\t\t\t\t\tmime: 'image/apng'\n\t\t\t\t\t};\n\t\t\t\tdefault:\n\t\t\t\t\tawait tokenizer.ignore(chunk.length + 4); // Ignore chunk-data + CRC\n\t\t\t}\n\t\t} while (tokenizer.position + 8 < tokenizer.fileInfo.size);\n\n\t\treturn {\n\t\t\text: 'png',\n\t\t\tmime: 'image/png'\n\t\t};\n\t}\n\n\tif (check([0x41, 0x52, 0x52, 0x4F, 0x57, 0x31, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'arrow',\n\t\t\tmime: 'application/x-apache-arrow'\n\t\t};\n\t}\n\n\tif (check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'glb',\n\t\t\tmime: 'model/gltf-binary'\n\t\t};\n\t}\n\n\t// `mov` format variants\n\tif (\n\t\tcheck([0x66, 0x72, 0x65, 0x65], {offset: 4}) || // `free`\n\t\tcheck([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // `mdat` MJPEG\n\t\tcheck([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) || // `moov`\n\t\tcheck([0x77, 0x69, 0x64, 0x65], {offset: 4}) // `wide`\n\t) {\n\t\treturn {\n\t\t\text: 'mov',\n\t\t\tmime: 'video/quicktime'\n\t\t};\n\t}\n\n\t// -- 9-byte signatures --\n\n\tif (check([0x49, 0x49, 0x52, 0x4F, 0x08, 0x00, 0x00, 0x00, 0x18])) {\n\t\treturn {\n\t\t\text: 'orf',\n\t\t\tmime: 'image/x-olympus-orf'\n\t\t};\n\t}\n\n\tif (checkString('gimp xcf ')) {\n\t\treturn {\n\t\t\text: 'xcf',\n\t\t\tmime: 'image/x-xcf'\n\t\t};\n\t}\n\n\t// -- 12-byte signatures --\n\n\tif (check([0x49, 0x49, 0x55, 0x00, 0x18, 0x00, 0x00, 0x00, 0x88, 0xE7, 0x74, 0xD8])) {\n\t\treturn {\n\t\t\text: 'rw2',\n\t\t\tmime: 'image/x-panasonic-rw2'\n\t\t};\n\t}\n\n\t// ASF_Header_Object first 80 bytes\n\tif (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {\n\t\tasync function readHeader() {\n\t\t\tconst guid = Buffer.alloc(16);\n\t\t\tawait tokenizer.readBuffer(guid);\n\t\t\treturn {\n\t\t\t\tid: guid,\n\t\t\t\tsize: Number(await tokenizer.readToken(Token.UINT64_LE))\n\t\t\t};\n\t\t}\n\n\t\tawait tokenizer.ignore(30);\n\t\t// Search for header should be in first 1KB of file.\n\t\twhile (tokenizer.position + 24 < tokenizer.fileInfo.size) {\n\t\t\tconst header = await readHeader();\n\t\t\tlet payload = header.size - 24;\n\t\t\tif (_check(header.id, [0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65])) {\n\t\t\t\t// Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)\n\t\t\t\tconst typeId = Buffer.alloc(16);\n\t\t\t\tpayload -= await tokenizer.readBuffer(typeId);\n\n\t\t\t\tif (_check(typeId, [0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {\n\t\t\t\t\t// Found audio:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asf',\n\t\t\t\t\t\tmime: 'audio/x-ms-asf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (_check(typeId, [0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B])) {\n\t\t\t\t\t// Found video:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asf',\n\t\t\t\t\t\tmime: 'video/x-ms-asf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tawait tokenizer.ignore(payload);\n\t\t}\n\n\t\t// Default to ASF generic extension\n\t\treturn {\n\t\t\text: 'asf',\n\t\t\tmime: 'application/vnd.ms-asf'\n\t\t};\n\t}\n\n\tif (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {\n\t\treturn {\n\t\t\text: 'ktx',\n\t\t\tmime: 'image/ktx'\n\t\t};\n\t}\n\n\tif ((check([0x7E, 0x10, 0x04]) || check([0x7E, 0x18, 0x04])) && check([0x30, 0x4D, 0x49, 0x45], {offset: 4})) {\n\t\treturn {\n\t\t\text: 'mie',\n\t\t\tmime: 'application/x-mie'\n\t\t};\n\t}\n\n\tif (check([0x27, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], {offset: 2})) {\n\t\treturn {\n\t\t\text: 'shp',\n\t\t\tmime: 'application/x-esri-shape'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {\n\t\t// JPEG-2000 family\n\n\t\tawait tokenizer.ignore(20);\n\t\tconst type = await tokenizer.readToken(new Token.StringType(4, 'ascii'));\n\t\tswitch (type) {\n\t\t\tcase 'jp2 ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jp2',\n\t\t\t\t\tmime: 'image/jp2'\n\t\t\t\t};\n\t\t\tcase 'jpx ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jpx',\n\t\t\t\t\tmime: 'image/jpx'\n\t\t\t\t};\n\t\t\tcase 'jpm ':\n\t\t\t\treturn {\n\t\t\t\t\text: 'jpm',\n\t\t\t\t\tmime: 'image/jpm'\n\t\t\t\t};\n\t\t\tcase 'mjp2':\n\t\t\t\treturn {\n\t\t\t\t\text: 'mj2',\n\t\t\t\t\tmime: 'image/mj2'\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tif (\n\t\tcheck([0xFF, 0x0A]) ||\n\t\tcheck([0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A])\n\t) {\n\t\treturn {\n\t\t\text: 'jxl',\n\t\t\tmime: 'image/jxl'\n\t\t};\n\t}\n\n\t// -- Unsafe signatures --\n\n\tif (\n\t\tcheck([0x0, 0x0, 0x1, 0xBA]) ||\n\t\tcheck([0x0, 0x0, 0x1, 0xB3])\n\t) {\n\t\treturn {\n\t\t\text: 'mpg',\n\t\t\tmime: 'video/mpeg'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x01, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'ttf',\n\t\t\tmime: 'font/ttf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x01, 0x00])) {\n\t\treturn {\n\t\t\text: 'ico',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x02, 0x00])) {\n\t\treturn {\n\t\t\text: 'cur',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {\n\t\t// Detected Microsoft Compound File Binary File (MS-CFB) Format.\n\t\treturn {\n\t\t\text: 'cfb',\n\t\t\tmime: 'application/x-cfb'\n\t\t};\n\t}\n\n\t// Increase sample size from 12 to 256.\n\tawait tokenizer.peekBuffer(buffer, {length: Math.min(256, tokenizer.fileInfo.size), mayBeLess: true});\n\n\t// -- 15-byte signatures --\n\n\tif (checkString('BEGIN:')) {\n\t\tif (checkString('VCARD', {offset: 6})) {\n\t\t\treturn {\n\t\t\t\text: 'vcf',\n\t\t\t\tmime: 'text/vcard'\n\t\t\t};\n\t\t}\n\n\t\tif (checkString('VCALENDAR', {offset: 6})) {\n\t\t\treturn {\n\t\t\t\text: 'ics',\n\t\t\t\tmime: 'text/calendar'\n\t\t\t};\n\t\t}\n\t}\n\n\t// `raf` is here just to keep all the raw image detectors together.\n\tif (checkString('FUJIFILMCCD-RAW')) {\n\t\treturn {\n\t\t\text: 'raf',\n\t\t\tmime: 'image/x-fujifilm-raf'\n\t\t};\n\t}\n\n\tif (checkString('Extended Module:')) {\n\t\treturn {\n\t\t\text: 'xm',\n\t\t\tmime: 'audio/x-xm'\n\t\t};\n\t}\n\n\tif (checkString('Creative Voice File')) {\n\t\treturn {\n\t\t\text: 'voc',\n\t\t\tmime: 'audio/x-voc'\n\t\t};\n\t}\n\n\tif (check([0x04, 0x00, 0x00, 0x00]) && buffer.length >= 16) { // Rough & quick check Pickle/ASAR\n\t\tconst jsonSize = buffer.readUInt32LE(12);\n\t\tif (jsonSize > 12 && buffer.length >= jsonSize + 16) {\n\t\t\ttry {\n\t\t\t\tconst header = buffer.slice(16, jsonSize + 16).toString();\n\t\t\t\tconst json = JSON.parse(header);\n\t\t\t\t// Check if Pickle is ASAR\n\t\t\t\tif (json.files) { // Final check, assuring Pickle/ASAR format\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'asar',\n\t\t\t\t\t\tmime: 'application/x-asar'\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch (_) {\n\t\t\t}\n\t\t}\n\t}\n\n\tif (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {\n\t\treturn {\n\t\t\text: 'mxf',\n\t\t\tmime: 'application/mxf'\n\t\t};\n\t}\n\n\tif (checkString('SCRM', {offset: 44})) {\n\t\treturn {\n\t\t\text: 's3m',\n\t\t\tmime: 'audio/x-s3m'\n\t\t};\n\t}\n\n\tif (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) {\n\t\treturn {\n\t\t\text: 'mts',\n\t\t\tmime: 'video/mp2t'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {\n\t\treturn {\n\t\t\text: 'mobi',\n\t\t\tmime: 'application/x-mobipocket-ebook'\n\t\t};\n\t}\n\n\tif (check([0x44, 0x49, 0x43, 0x4D], {offset: 128})) {\n\t\treturn {\n\t\t\text: 'dcm',\n\t\t\tmime: 'application/dicom'\n\t\t};\n\t}\n\n\tif (check([0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46])) {\n\t\treturn {\n\t\t\text: 'lnk',\n\t\t\tmime: 'application/x.ms.shortcut' // Invented by us\n\t\t};\n\t}\n\n\tif (check([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x6D, 0x61, 0x72, 0x6B, 0x00, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'alias',\n\t\t\tmime: 'application/x.apple.alias' // Invented by us\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x4C, 0x50], {offset: 34}) &&\n\t\t(\n\t\t\tcheck([0x00, 0x00, 0x01], {offset: 8}) ||\n\t\t\tcheck([0x01, 0x00, 0x02], {offset: 8}) ||\n\t\t\tcheck([0x02, 0x00, 0x02], {offset: 8})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'eot',\n\t\t\tmime: 'application/vnd.ms-fontobject'\n\t\t};\n\t}\n\n\tif (check([0x06, 0x06, 0xED, 0xF5, 0xD8, 0x1D, 0x46, 0xE5, 0xBD, 0x31, 0xEF, 0xE7, 0xFE, 0x74, 0xB7, 0x1D])) {\n\t\treturn {\n\t\t\text: 'indd',\n\t\t\tmime: 'application/x-indesign'\n\t\t};\n\t}\n\n\t// Increase sample size from 256 to 512\n\tawait tokenizer.peekBuffer(buffer, {length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true});\n\n\t// Requires a buffer size of 512 bytes\n\tif (tarHeaderChecksumMatches(buffer)) {\n\t\treturn {\n\t\t\text: 'tar',\n\t\t\tmime: 'application/x-tar'\n\t\t};\n\t}\n\n\tif (check([0xFF, 0xFE, 0xFF, 0x0E, 0x53, 0x00, 0x6B, 0x00, 0x65, 0x00, 0x74, 0x00, 0x63, 0x00, 0x68, 0x00, 0x55, 0x00, 0x70, 0x00, 0x20, 0x00, 0x4D, 0x00, 0x6F, 0x00, 0x64, 0x00, 0x65, 0x00, 0x6C, 0x00])) {\n\t\treturn {\n\t\t\text: 'skp',\n\t\t\tmime: 'application/vnd.sketchup.skp'\n\t\t};\n\t}\n\n\tif (checkString('-----BEGIN PGP MESSAGE-----')) {\n\t\treturn {\n\t\t\text: 'pgp',\n\t\t\tmime: 'application/pgp-encrypted'\n\t\t};\n\t}\n\n\t// Check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE)\n\tif (buffer.length >= 2 && check([0xFF, 0xE0], {offset: 0, mask: [0xFF, 0xE0]})) {\n\t\tif (check([0x10], {offset: 1, mask: [0x16]})) {\n\t\t\t// Check for (ADTS) MPEG-2\n\t\t\tif (check([0x08], {offset: 1, mask: [0x08]})) {\n\t\t\t\treturn {\n\t\t\t\t\text: 'aac',\n\t\t\t\t\tmime: 'audio/aac'\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Must be (ADTS) MPEG-4\n\t\t\treturn {\n\t\t\t\text: 'aac',\n\t\t\t\tmime: 'audio/aac'\n\t\t\t};\n\t\t}\n\n\t\t// MPEG 1 or 2 Layer 3 header\n\t\t// Check for MPEG layer 3\n\t\tif (check([0x02], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp3',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\t// Check for MPEG layer 2\n\t\tif (check([0x04], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp2',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\t// Check for MPEG layer 1\n\t\tif (check([0x06], {offset: 1, mask: [0x06]})) {\n\t\t\treturn {\n\t\t\t\text: 'mp1',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\t}\n}\n\nconst stream = readableStream => new Promise((resolve, reject) => {\n\t// Using `eval` to work around issues when bundling with Webpack\n\tconst stream = eval('require')('stream'); // eslint-disable-line no-eval\n\n\treadableStream.on('error', reject);\n\treadableStream.once('readable', async () => {\n\t\t// Set up output stream\n\t\tconst pass = new stream.PassThrough();\n\t\tlet outputStream;\n\t\tif (stream.pipeline) {\n\t\t\toutputStream = stream.pipeline(readableStream, pass, () => {\n\t\t\t});\n\t\t} else {\n\t\t\toutputStream = readableStream.pipe(pass);\n\t\t}\n\n\t\t// Read the input stream and detect the filetype\n\t\tconst chunk = readableStream.read(minimumBytes) || readableStream.read() || Buffer.alloc(0);\n\t\ttry {\n\t\t\tconst fileType = await fromBuffer(chunk);\n\t\t\tpass.fileType = fileType;\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\n\t\tresolve(outputStream);\n\t});\n});\n\nconst fileType = {\n\tfromStream,\n\tfromTokenizer,\n\tfromBuffer,\n\tstream\n};\n\nObject.defineProperty(fileType, 'extensions', {\n\tget() {\n\t\treturn new Set(supported.extensions);\n\t}\n});\n\nObject.defineProperty(fileType, 'mimeTypes', {\n\tget() {\n\t\treturn new Set(supported.mimeTypes);\n\t}\n});\n\nmodule.exports = fileType;\n","'use strict';\n\n/**\n * @param typeMap [Object] Map of MIME type -> Array[extensions]\n * @param ...\n */\nfunction Mime() {\n this._types = Object.create(null);\n this._extensions = Object.create(null);\n\n for (let i = 0; i < arguments.length; i++) {\n this.define(arguments[i]);\n }\n\n this.define = this.define.bind(this);\n this.getType = this.getType.bind(this);\n this.getExtension = this.getExtension.bind(this);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * If a type declares an extension that has already been defined, an error will\n * be thrown. To suppress this error and force the extension to be associated\n * with the new type, pass `force`=true. Alternatively, you may prefix the\n * extension with \"*\" to map the type to extension, without mapping the\n * extension to the type.\n *\n * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});\n *\n *\n * @param map (Object) type definitions\n * @param force (Boolean) if true, force overriding of existing definitions\n */\nMime.prototype.define = function(typeMap, force) {\n for (let type in typeMap) {\n let extensions = typeMap[type].map(function(t) {\n return t.toLowerCase();\n });\n type = type.toLowerCase();\n\n for (let i = 0; i < extensions.length; i++) {\n const ext = extensions[i];\n\n // '*' prefix = not the preferred type for this extension. So fixup the\n // extension, and skip it.\n if (ext[0] === '*') {\n continue;\n }\n\n if (!force && (ext in this._types)) {\n throw new Error(\n 'Attempt to change mapping for \"' + ext +\n '\" extension from \"' + this._types[ext] + '\" to \"' + type +\n '\". Pass `force=true` to allow this, otherwise remove \"' + ext +\n '\" from the list of extensions for \"' + type + '\".'\n );\n }\n\n this._types[ext] = type;\n }\n\n // Use first extension as default\n if (force || !this._extensions[type]) {\n const ext = extensions[0];\n this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);\n }\n }\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.getType = function(path) {\n path = String(path);\n let last = path.replace(/^.*[/\\\\]/, '').toLowerCase();\n let ext = last.replace(/^.*\\./, '').toLowerCase();\n\n let hasPath = last.length < path.length;\n let hasDot = ext.length < last.length - 1;\n\n return (hasDot || !hasPath) && this._types[ext] || null;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.getExtension = function(type) {\n type = /^\\s*([^;\\s]*)/.test(type) && RegExp.$1;\n return type && this._extensions[type.toLowerCase()] || null;\n};\n\nmodule.exports = Mime;\n","module.exports = {\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]};","'use strict';\n\nlet Mime = require('./Mime');\nmodule.exports = new Mime(require('./types/standard'));\n","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nmodule.exports = {\n\tparseSections: function(stream, iterator) {\n\t\tvar len, markerType;\n\t\tstream.setBigEndian(true);\n\t\t//stop reading the stream at the SOS (Start of Stream) marker,\n\t\t//because its length is not stored in the header so we can't\n\t\t//know where to jump to. The only marker after that is just EOI (End Of Image) anyway\n\t\twhile(stream.remainingLength() > 0 && markerType !== 0xDA) {\n\t\t\tif(stream.nextUInt8() !== 0xFF) {\n\t\t\t\tthrow new Error('Invalid JPEG section offset');\n\t\t\t}\n\t\t\tmarkerType = stream.nextUInt8();\n\t\t\t//don't read size from markers that have no datas\n\t\t\tif((markerType >= 0xD0 && markerType <= 0xD9) || markerType === 0xDA) {\n\t\t\t\tlen = 0;\n\t\t\t} else {\n\t\t\t\tlen = stream.nextUInt16() - 2;\n\t\t\t}\n\t\t\titerator(markerType, stream.branch(0, len));\n\t\t\tstream.skip(len);\n\t\t}\n\t},\n\t//stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator\n\tgetSizeFromSOFSection: function(stream) {\n\t\tstream.skip(1);\n\t\treturn {\n\t\t\theight: stream.nextUInt16(),\n\t\t\twidth: stream.nextUInt16()\n\t\t};\n\t},\n\tgetSectionName: function(markerType) {\n\t\tvar name, index;\n\t\tswitch(markerType) {\n\t\t\tcase 0xD8: name = 'SOI'; break;\n\t\t\tcase 0xC4: name = 'DHT'; break;\n\t\t\tcase 0xDB: name = 'DQT'; break;\n\t\t\tcase 0xDD: name = 'DRI'; break;\n\t\t\tcase 0xDA: name = 'SOS'; break;\n\t\t\tcase 0xFE: name = 'COM'; break;\n\t\t\tcase 0xD9: name = 'EOI'; break;\n\t\t\tdefault:\n\t\t\t\tif(markerType >= 0xE0 && markerType <= 0xEF) {\n\t\t\t\t\tname = 'APP';\n\t\t\t\t\tindex = markerType - 0xE0;\n\t\t\t\t}\n\t\t\t\telse if(markerType >= 0xC0 && markerType <= 0xCF && markerType !== 0xC4 && markerType !== 0xC8 && markerType !== 0xCC) {\n\t\t\t\t\tname = 'SOF';\n\t\t\t\t\tindex = markerType - 0xC0;\n\t\t\t\t}\n\t\t\t\telse if(markerType >= 0xD0 && markerType <= 0xD7) {\n\t\t\t\t\tname = 'RST';\n\t\t\t\t\tindex = markerType - 0xD0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t\tvar nameStruct = {\n\t\t\tname: name\n\t\t};\n\t\tif(typeof index === 'number') {\n\t\t\tnameStruct.index = index;\n\t\t}\n\t\treturn nameStruct;\n\t}\n};","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nfunction readExifValue(format, stream) {\n\tswitch(format) {\n\t\tcase 1: return stream.nextUInt8();\n\t\tcase 3: return stream.nextUInt16();\n\t\tcase 4: return stream.nextUInt32();\n\t\tcase 5: return [stream.nextUInt32(), stream.nextUInt32()];\n\t\tcase 6: return stream.nextInt8();\n\t\tcase 8: return stream.nextUInt16();\n\t\tcase 9: return stream.nextUInt32();\n\t\tcase 10: return [stream.nextInt32(), stream.nextInt32()];\n\t\tcase 11: return stream.nextFloat();\n\t\tcase 12: return stream.nextDouble();\n\t\tdefault: throw new Error('Invalid format while decoding: ' + format);\n\t}\n}\n\nfunction getBytesPerComponent(format) {\n\tswitch(format) {\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 6:\n\t\tcase 7:\n\t\t\treturn 1;\n\t\tcase 3:\n\t\tcase 8:\n\t\t\treturn 2;\n\t\tcase 4:\n\t\tcase 9:\n\t\tcase 11:\n\t\t\treturn 4;\n\t\tcase 5:\n\t\tcase 10:\n\t\tcase 12:\n\t\t\treturn 8;\n\t\tdefault:\n\t\t\treturn 0;\n\t}\n}\n\nfunction readExifTag(tiffMarker, stream) {\n\tvar tagType = stream.nextUInt16(),\n\t\tformat = stream.nextUInt16(),\n\t\tbytesPerComponent = getBytesPerComponent(format),\n\t\tcomponents = stream.nextUInt32(),\n\t\tvalueBytes = bytesPerComponent * components,\n\t\tvalues,\n\t\tvalue,\n\t\tc;\n\n\t/* if the value is bigger then 4 bytes, the value is in the data section of the IFD\n\tand the value present in the tag is the offset starting from the tiff header. So we replace the stream\n\twith a stream that is located at the given offset in the data section. s*/\n\tif(valueBytes > 4) {\n\t\tstream = tiffMarker.openWithOffset(stream.nextUInt32());\n\t}\n\t//we don't want to read strings as arrays\n\tif(format === 2) {\n\t\tvalues = stream.nextString(components);\n\t\t//cut off \\0 characters\n\t\tvar lastNull = values.indexOf('\\0');\n\t\tif(lastNull !== -1) {\n\t\t\tvalues = values.substr(0, lastNull);\n\t\t}\n\t}\n\telse if(format === 7) {\n\t\tvalues = stream.nextBuffer(components);\n\t}\n\telse if(format !== 0) {\n\t\tvalues = [];\n\t\tfor(c = 0; c < components; ++c) {\n\t\t\tvalues.push(readExifValue(format, stream));\n\t\t}\n\t}\n\t//since our stream is a stateful object, we need to skip remaining bytes\n\t//so our offset stays correct\n\tif(valueBytes < 4) {\n\t\tstream.skip(4 - valueBytes);\n\t}\n\n\treturn [tagType, values, format];\n}\n\nfunction readIFDSection(tiffMarker, stream, iterator) {\n\tvar numberOfEntries = stream.nextUInt16(), tag, i;\n\tfor(i = 0; i < numberOfEntries; ++i) {\n\t\ttag = readExifTag(tiffMarker, stream);\n\t\titerator(tag[0], tag[1], tag[2]);\n\t}\n}\n\nfunction readHeader(stream) {\n\tvar exifHeader = stream.nextString(6);\n\tif(exifHeader !== 'Exif\\0\\0') {\n\t\tthrow new Error('Invalid EXIF header');\n\t}\n\n\tvar tiffMarker = stream.mark();\n\tvar tiffHeader = stream.nextUInt16();\n\tif(tiffHeader === 0x4949) {\n\t\tstream.setBigEndian(false);\n\t} else if(tiffHeader === 0x4D4D) {\n\t\tstream.setBigEndian(true);\n\t} else {\n\t\tthrow new Error('Invalid TIFF header');\n\t}\n\tif(stream.nextUInt16() !== 0x002A) {\n\t\tthrow new Error('Invalid TIFF data');\n\t}\n\treturn tiffMarker;\n}\n\nmodule.exports = {\n\tIFD0: 1,\n\tIFD1: 2,\n\tGPSIFD: 3,\n\tSubIFD: 4,\n\tInteropIFD: 5,\n\tparseTags: function(stream, iterator) {\n\t\tvar tiffMarker;\n\t\ttry {\n\t\t\ttiffMarker = readHeader(stream);\n\t\t} catch(e) {\n\t\t\treturn false;\t//ignore APP1 sections with invalid headers\n\t\t}\n\t\tvar subIfdOffset, gpsOffset, interopOffset;\n\t\tvar ifd0Stream = tiffMarker.openWithOffset(stream.nextUInt32()),\n\t\t\tIFD0 = this.IFD0;\n\t\treadIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) {\n\t\t\tswitch(tagType) {\n\t\t\t\tcase 0x8825: gpsOffset = value[0]; break;\n\t\t\t\tcase 0x8769: subIfdOffset = value[0]; break;\n\t\t\t\tdefault: iterator(IFD0, tagType, value, format); break;\n\t\t\t}\n\t\t});\n\t\tvar ifd1Offset = ifd0Stream.nextUInt32();\n\t\tif(ifd1Offset !== 0) {\n\t\t\tvar ifd1Stream = tiffMarker.openWithOffset(ifd1Offset);\n\t\t\treadIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1));\n\t\t}\n\n\t\tif(gpsOffset) {\n\t\t\tvar gpsStream = tiffMarker.openWithOffset(gpsOffset);\n\t\t\treadIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD));\n\t\t}\n\n\t\tif(subIfdOffset) {\n\t\t\tvar subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD;\n\t\t\treadIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) {\n\t\t\t\tif(tagType === 0xA005) {\n\t\t\t\t\tinteropOffset = value[0];\n\t\t\t\t} else {\n\t\t\t\t\titerator(InteropIFD, tagType, value, format);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif(interopOffset) {\n\t\t\tvar interopStream = tiffMarker.openWithOffset(interopOffset);\n\t\t\treadIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD));\n\t\t}\n\t\treturn true;\n\t}\n};","function parseNumber(s) {\n\treturn parseInt(s, 10);\n}\n\n//in seconds\nvar hours = 3600;\nvar minutes = 60;\n\n//take date (year, month, day) and time (hour, minutes, seconds) digits in UTC\n//and return a timestamp in seconds\nfunction parseDateTimeParts(dateParts, timeParts) {\n\tdateParts = dateParts.map(parseNumber);\n\ttimeParts = timeParts.map(parseNumber);\n\tvar year = dateParts[0];\n\tvar month = dateParts[1] - 1;\n\tvar day = dateParts[2];\n\tvar hours = timeParts[0];\n\tvar minutes = timeParts[1];\n\tvar seconds = timeParts[2];\n\tvar date = Date.UTC(year, month, day, hours, minutes, seconds, 0);\n\tvar timestamp = date / 1000;\n\treturn timestamp;\n}\n\n//parse date with \"2004-09-04T23:39:06-08:00\" format,\n//one of the formats supported by ISO 8601, and\n//convert to utc timestamp in seconds\nfunction parseDateWithTimezoneFormat(dateTimeStr) {\n\n\tvar dateParts = dateTimeStr.substr(0, 10).split('-');\n\tvar timeParts = dateTimeStr.substr(11, 8).split(':');\n\tvar timezoneStr = dateTimeStr.substr(19, 6);\n\tvar timezoneParts = timezoneStr.split(':').map(parseNumber);\n\tvar timezoneOffset = (timezoneParts[0] * hours) +\n\t\t(timezoneParts[1] * minutes);\n\n\tvar timestamp = parseDateTimeParts(dateParts, timeParts);\n\t//minus because the timezoneOffset describes\n\t//how much the described time is ahead of UTC\n\ttimestamp -= timezoneOffset;\n\n\tif(typeof timestamp === 'number' && !isNaN(timestamp)) {\n\t\treturn timestamp;\n\t}\n}\n\n//parse date with \"YYYY:MM:DD hh:mm:ss\" format, convert to utc timestamp in seconds\nfunction parseDateWithSpecFormat(dateTimeStr) {\n\tvar parts = dateTimeStr.split(' '),\n\t\tdateParts = parts[0].split(':'),\n\t\ttimeParts = parts[1].split(':');\n\n\tvar timestamp = parseDateTimeParts(dateParts, timeParts);\n\n\tif(typeof timestamp === 'number' && !isNaN(timestamp)) {\n\t\treturn timestamp;\n\t}\n}\n\nfunction parseExifDate(dateTimeStr) {\n\t//some easy checks to determine two common date formats\n\n\t//is the date in the standard \"YYYY:MM:DD hh:mm:ss\" format?\n\tvar isSpecFormat = dateTimeStr.length === 19 &&\n\t\tdateTimeStr.charAt(4) === ':';\n\t//is the date in the non-standard format,\n\t//\"2004-09-04T23:39:06-08:00\" to include a timezone?\n\tvar isTimezoneFormat = dateTimeStr.length === 25 &&\n\t\tdateTimeStr.charAt(10) === 'T';\n\tvar timestamp;\n\n\tif(isTimezoneFormat) {\n\t\treturn parseDateWithTimezoneFormat(dateTimeStr);\n\t}\n\telse if(isSpecFormat) {\n\t\treturn parseDateWithSpecFormat(dateTimeStr);\n\t}\n}\n\nmodule.exports = {\n\tparseDateWithSpecFormat: parseDateWithSpecFormat,\n\tparseDateWithTimezoneFormat: parseDateWithTimezoneFormat,\n\tparseExifDate: parseExifDate\n};\n","var exif = require('./exif');\nvar date = require('./date');\n\nvar degreeTags = [{\n\tsection: exif.GPSIFD,\n\ttype: 0x0002,\n\tname: 'GPSLatitude',\n\trefType: 0x0001,\n\trefName: 'GPSLatitudeRef',\n\tposVal: 'N'\n},\n{\n\tsection: exif.GPSIFD,\n\ttype: 0x0004,\n\tname: 'GPSLongitude',\n\trefType: 0x0003,\n\trefName: 'GPSLongitudeRef',\n\tposVal: 'E'\n}];\nvar dateTags = [{\n\tsection: exif.SubIFD,\n\ttype: 0x0132,\n\tname: 'ModifyDate'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x9003,\n\tname: 'DateTimeOriginal'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x9004,\n\tname: 'CreateDate'\n},\n{\n\tsection: exif.SubIFD,\n\ttype: 0x0132,\n\tname : 'ModifyDate',\n}];\n\nmodule.exports = {\n\tcastDegreeValues: function(getTagValue, setTagValue) {\n\t\tdegreeTags.forEach(function(t) {\n\t\t\tvar degreeVal = getTagValue(t);\n\t\t\tif(degreeVal) {\n\t\t\t\tvar degreeRef = getTagValue({section: t.section, type: t.refType, name: t.refName});\n\t\t\t\tvar degreeNumRef = degreeRef === t.posVal ? 1 : -1;\n\t\t\t\tvar degree = (degreeVal[0] + (degreeVal[1] / 60) + (degreeVal[2] / 3600)) * degreeNumRef;\n\t\t\t\tsetTagValue(t, degree);\n\t\t\t}\n\t\t});\n\t},\n\tcastDateValues: function(getTagValue, setTagValue) {\n\t\tdateTags.forEach(function(t) {\n\t\t\tvar dateStrVal = getTagValue(t);\n\t\t\tif(dateStrVal) {\n\t\t\t\t//some easy checks to determine two common date formats\n\t\t\t\tvar timestamp = date.parseExifDate(dateStrVal);\n\t\t\t\tif(typeof timestamp !== 'undefined') {\n\t\t\t\t\tsetTagValue(t, timestamp);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t},\n\tsimplifyValue: function(values, format) {\n\t\tif(Array.isArray(values)) {\n\t\t\tvalues = values.map(function(value) {\n\t\t\t\tif(format === 10 || format === 5) {\n\t\t\t\t\treturn value[0] / value[1];\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t});\n\t\t\tif(values.length === 1) {\n\t\t\t\tvalues = values[0];\n\t\t\t}\n\t\t}\n\t\treturn values;\n\t}\n};\n","module.exports = {\n\texif : {\n\t\t0x0001 : \"InteropIndex\",\n\t\t0x0002 : \"InteropVersion\",\n\t\t0x000B : \"ProcessingSoftware\",\n\t\t0x00FE : \"SubfileType\",\n\t\t0x00FF : \"OldSubfileType\",\n\t\t0x0100 : \"ImageWidth\",\n\t\t0x0101 : \"ImageHeight\",\n\t\t0x0102 : \"BitsPerSample\",\n\t\t0x0103 : \"Compression\",\n\t\t0x0106 : \"PhotometricInterpretation\",\n\t\t0x0107 : \"Thresholding\",\n\t\t0x0108 : \"CellWidth\",\n\t\t0x0109 : \"CellLength\",\n\t\t0x010A : \"FillOrder\",\n\t\t0x010D : \"DocumentName\",\n\t\t0x010E : \"ImageDescription\",\n\t\t0x010F : \"Make\",\n\t\t0x0110 : \"Model\",\n\t\t0x0111 : \"StripOffsets\",\n\t\t0x0112 : \"Orientation\",\n\t\t0x0115 : \"SamplesPerPixel\",\n\t\t0x0116 : \"RowsPerStrip\",\n\t\t0x0117 : \"StripByteCounts\",\n\t\t0x0118 : \"MinSampleValue\",\n\t\t0x0119 : \"MaxSampleValue\",\n\t\t0x011A : \"XResolution\",\n\t\t0x011B : \"YResolution\",\n\t\t0x011C : \"PlanarConfiguration\",\n\t\t0x011D : \"PageName\",\n\t\t0x011E : \"XPosition\",\n\t\t0x011F : \"YPosition\",\n\t\t0x0120 : \"FreeOffsets\",\n\t\t0x0121 : \"FreeByteCounts\",\n\t\t0x0122 : \"GrayResponseUnit\",\n\t\t0x0123 : \"GrayResponseCurve\",\n\t\t0x0124 : \"T4Options\",\n\t\t0x0125 : \"T6Options\",\n\t\t0x0128 : \"ResolutionUnit\",\n\t\t0x0129 : \"PageNumber\",\n\t\t0x012C : \"ColorResponseUnit\",\n\t\t0x012D : \"TransferFunction\",\n\t\t0x0131 : \"Software\",\n\t\t0x0132 : \"ModifyDate\",\n\t\t0x013B : \"Artist\",\n\t\t0x013C : \"HostComputer\",\n\t\t0x013D : \"Predictor\",\n\t\t0x013E : \"WhitePoint\",\n\t\t0x013F : \"PrimaryChromaticities\",\n\t\t0x0140 : \"ColorMap\",\n\t\t0x0141 : \"HalftoneHints\",\n\t\t0x0142 : \"TileWidth\",\n\t\t0x0143 : \"TileLength\",\n\t\t0x0144 : \"TileOffsets\",\n\t\t0x0145 : \"TileByteCounts\",\n\t\t0x0146 : \"BadFaxLines\",\n\t\t0x0147 : \"CleanFaxData\",\n\t\t0x0148 : \"ConsecutiveBadFaxLines\",\n\t\t0x014A : \"SubIFD\",\n\t\t0x014C : \"InkSet\",\n\t\t0x014D : \"InkNames\",\n\t\t0x014E : \"NumberofInks\",\n\t\t0x0150 : \"DotRange\",\n\t\t0x0151 : \"TargetPrinter\",\n\t\t0x0152 : \"ExtraSamples\",\n\t\t0x0153 : \"SampleFormat\",\n\t\t0x0154 : \"SMinSampleValue\",\n\t\t0x0155 : \"SMaxSampleValue\",\n\t\t0x0156 : \"TransferRange\",\n\t\t0x0157 : \"ClipPath\",\n\t\t0x0158 : \"XClipPathUnits\",\n\t\t0x0159 : \"YClipPathUnits\",\n\t\t0x015A : \"Indexed\",\n\t\t0x015B : \"JPEGTables\",\n\t\t0x015F : \"OPIProxy\",\n\t\t0x0190 : \"GlobalParametersIFD\",\n\t\t0x0191 : \"ProfileType\",\n\t\t0x0192 : \"FaxProfile\",\n\t\t0x0193 : \"CodingMethods\",\n\t\t0x0194 : \"VersionYear\",\n\t\t0x0195 : \"ModeNumber\",\n\t\t0x01B1 : \"Decode\",\n\t\t0x01B2 : \"DefaultImageColor\",\n\t\t0x01B3 : \"T82Options\",\n\t\t0x01B5 : \"JPEGTables\",\n\t\t0x0200 : \"JPEGProc\",\n\t\t0x0201 : \"ThumbnailOffset\",\n\t\t0x0202 : \"ThumbnailLength\",\n\t\t0x0203 : \"JPEGRestartInterval\",\n\t\t0x0205 : \"JPEGLosslessPredictors\",\n\t\t0x0206 : \"JPEGPointTransforms\",\n\t\t0x0207 : \"JPEGQTables\",\n\t\t0x0208 : \"JPEGDCTables\",\n\t\t0x0209 : \"JPEGACTables\",\n\t\t0x0211 : \"YCbCrCoefficients\",\n\t\t0x0212 : \"YCbCrSubSampling\",\n\t\t0x0213 : \"YCbCrPositioning\",\n\t\t0x0214 : \"ReferenceBlackWhite\",\n\t\t0x022F : \"StripRowCounts\",\n\t\t0x02BC : \"ApplicationNotes\",\n\t\t0x03E7 : \"USPTOMiscellaneous\",\n\t\t0x1000 : \"RelatedImageFileFormat\",\n\t\t0x1001 : \"RelatedImageWidth\",\n\t\t0x1002 : \"RelatedImageHeight\",\n\t\t0x4746 : \"Rating\",\n\t\t0x4747 : \"XP_DIP_XML\",\n\t\t0x4748 : \"StitchInfo\",\n\t\t0x4749 : \"RatingPercent\",\n\t\t0x800D : \"ImageID\",\n\t\t0x80A3 : \"WangTag1\",\n\t\t0x80A4 : \"WangAnnotation\",\n\t\t0x80A5 : \"WangTag3\",\n\t\t0x80A6 : \"WangTag4\",\n\t\t0x80E3 : \"Matteing\",\n\t\t0x80E4 : \"DataType\",\n\t\t0x80E5 : \"ImageDepth\",\n\t\t0x80E6 : \"TileDepth\",\n\t\t0x827D : \"Model2\",\n\t\t0x828D : \"CFARepeatPatternDim\",\n\t\t0x828E : \"CFAPattern2\",\n\t\t0x828F : \"BatteryLevel\",\n\t\t0x8290 : \"KodakIFD\",\n\t\t0x8298 : \"Copyright\",\n\t\t0x829A : \"ExposureTime\",\n\t\t0x829D : \"FNumber\",\n\t\t0x82A5 : \"MDFileTag\",\n\t\t0x82A6 : \"MDScalePixel\",\n\t\t0x82A7 : \"MDColorTable\",\n\t\t0x82A8 : \"MDLabName\",\n\t\t0x82A9 : \"MDSampleInfo\",\n\t\t0x82AA : \"MDPrepDate\",\n\t\t0x82AB : \"MDPrepTime\",\n\t\t0x82AC : \"MDFileUnits\",\n\t\t0x830E : \"PixelScale\",\n\t\t0x8335 : \"AdventScale\",\n\t\t0x8336 : \"AdventRevision\",\n\t\t0x835C : \"UIC1Tag\",\n\t\t0x835D : \"UIC2Tag\",\n\t\t0x835E : \"UIC3Tag\",\n\t\t0x835F : \"UIC4Tag\",\n\t\t0x83BB : \"IPTC-NAA\",\n\t\t0x847E : \"IntergraphPacketData\",\n\t\t0x847F : \"IntergraphFlagRegisters\",\n\t\t0x8480 : \"IntergraphMatrix\",\n\t\t0x8481 : \"INGRReserved\",\n\t\t0x8482 : \"ModelTiePoint\",\n\t\t0x84E0 : \"Site\",\n\t\t0x84E1 : \"ColorSequence\",\n\t\t0x84E2 : \"IT8Header\",\n\t\t0x84E3 : \"RasterPadding\",\n\t\t0x84E4 : \"BitsPerRunLength\",\n\t\t0x84E5 : \"BitsPerExtendedRunLength\",\n\t\t0x84E6 : \"ColorTable\",\n\t\t0x84E7 : \"ImageColorIndicator\",\n\t\t0x84E8 : \"BackgroundColorIndicator\",\n\t\t0x84E9 : \"ImageColorValue\",\n\t\t0x84EA : \"BackgroundColorValue\",\n\t\t0x84EB : \"PixelIntensityRange\",\n\t\t0x84EC : \"TransparencyIndicator\",\n\t\t0x84ED : \"ColorCharacterization\",\n\t\t0x84EE : \"HCUsage\",\n\t\t0x84EF : \"TrapIndicator\",\n\t\t0x84F0 : \"CMYKEquivalent\",\n\t\t0x8546 : \"SEMInfo\",\n\t\t0x8568 : \"AFCP_IPTC\",\n\t\t0x85B8 : \"PixelMagicJBIGOptions\",\n\t\t0x85D8 : \"ModelTransform\",\n\t\t0x8602 : \"WB_GRGBLevels\",\n\t\t0x8606 : \"LeafData\",\n\t\t0x8649 : \"PhotoshopSettings\",\n\t\t0x8769 : \"ExifOffset\",\n\t\t0x8773 : \"ICC_Profile\",\n\t\t0x877F : \"TIFF_FXExtensions\",\n\t\t0x8780 : \"MultiProfiles\",\n\t\t0x8781 : \"SharedData\",\n\t\t0x8782 : \"T88Options\",\n\t\t0x87AC : \"ImageLayer\",\n\t\t0x87AF : \"GeoTiffDirectory\",\n\t\t0x87B0 : \"GeoTiffDoubleParams\",\n\t\t0x87B1 : \"GeoTiffAsciiParams\",\n\t\t0x8822 : \"ExposureProgram\",\n\t\t0x8824 : \"SpectralSensitivity\",\n\t\t0x8825 : \"GPSInfo\",\n\t\t0x8827 : \"ISO\",\n\t\t0x8828 : \"Opto-ElectricConvFactor\",\n\t\t0x8829 : \"Interlace\",\n\t\t0x882A : \"TimeZoneOffset\",\n\t\t0x882B : \"SelfTimerMode\",\n\t\t0x8830 : \"SensitivityType\",\n\t\t0x8831 : \"StandardOutputSensitivity\",\n\t\t0x8832 : \"RecommendedExposureIndex\",\n\t\t0x8833 : \"ISOSpeed\",\n\t\t0x8834 : \"ISOSpeedLatitudeyyy\",\n\t\t0x8835 : \"ISOSpeedLatitudezzz\",\n\t\t0x885C : \"FaxRecvParams\",\n\t\t0x885D : \"FaxSubAddress\",\n\t\t0x885E : \"FaxRecvTime\",\n\t\t0x888A : \"LeafSubIFD\",\n\t\t0x9000 : \"ExifVersion\",\n\t\t0x9003 : \"DateTimeOriginal\",\n\t\t0x9004 : \"CreateDate\",\n\t\t0x9101 : \"ComponentsConfiguration\",\n\t\t0x9102 : \"CompressedBitsPerPixel\",\n\t\t0x9201 : \"ShutterSpeedValue\",\n\t\t0x9202 : \"ApertureValue\",\n\t\t0x9203 : \"BrightnessValue\",\n\t\t0x9204 : \"ExposureCompensation\",\n\t\t0x9205 : \"MaxApertureValue\",\n\t\t0x9206 : \"SubjectDistance\",\n\t\t0x9207 : \"MeteringMode\",\n\t\t0x9208 : \"LightSource\",\n\t\t0x9209 : \"Flash\",\n\t\t0x920A : \"FocalLength\",\n\t\t0x920B : \"FlashEnergy\",\n\t\t0x920C : \"SpatialFrequencyResponse\",\n\t\t0x920D : \"Noise\",\n\t\t0x920E : \"FocalPlaneXResolution\",\n\t\t0x920F : \"FocalPlaneYResolution\",\n\t\t0x9210 : \"FocalPlaneResolutionUnit\",\n\t\t0x9211 : \"ImageNumber\",\n\t\t0x9212 : \"SecurityClassification\",\n\t\t0x9213 : \"ImageHistory\",\n\t\t0x9214 : \"SubjectArea\",\n\t\t0x9215 : \"ExposureIndex\",\n\t\t0x9216 : \"TIFF-EPStandardID\",\n\t\t0x9217 : \"SensingMethod\",\n\t\t0x923A : \"CIP3DataFile\",\n\t\t0x923B : \"CIP3Sheet\",\n\t\t0x923C : \"CIP3Side\",\n\t\t0x923F : \"StoNits\",\n\t\t0x927C : \"MakerNote\",\n\t\t0x9286 : \"UserComment\",\n\t\t0x9290 : \"SubSecTime\",\n\t\t0x9291 : \"SubSecTimeOriginal\",\n\t\t0x9292 : \"SubSecTimeDigitized\",\n\t\t0x932F : \"MSDocumentText\",\n\t\t0x9330 : \"MSPropertySetStorage\",\n\t\t0x9331 : \"MSDocumentTextPosition\",\n\t\t0x935C : \"ImageSourceData\",\n\t\t0x9C9B : \"XPTitle\",\n\t\t0x9C9C : \"XPComment\",\n\t\t0x9C9D : \"XPAuthor\",\n\t\t0x9C9E : \"XPKeywords\",\n\t\t0x9C9F : \"XPSubject\",\n\t\t0xA000 : \"FlashpixVersion\",\n\t\t0xA001 : \"ColorSpace\",\n\t\t0xA002 : \"ExifImageWidth\",\n\t\t0xA003 : \"ExifImageHeight\",\n\t\t0xA004 : \"RelatedSoundFile\",\n\t\t0xA005 : \"InteropOffset\",\n\t\t0xA20B : \"FlashEnergy\",\n\t\t0xA20C : \"SpatialFrequencyResponse\",\n\t\t0xA20D : \"Noise\",\n\t\t0xA20E : \"FocalPlaneXResolution\",\n\t\t0xA20F : \"FocalPlaneYResolution\",\n\t\t0xA210 : \"FocalPlaneResolutionUnit\",\n\t\t0xA211 : \"ImageNumber\",\n\t\t0xA212 : \"SecurityClassification\",\n\t\t0xA213 : \"ImageHistory\",\n\t\t0xA214 : \"SubjectLocation\",\n\t\t0xA215 : \"ExposureIndex\",\n\t\t0xA216 : \"TIFF-EPStandardID\",\n\t\t0xA217 : \"SensingMethod\",\n\t\t0xA300 : \"FileSource\",\n\t\t0xA301 : \"SceneType\",\n\t\t0xA302 : \"CFAPattern\",\n\t\t0xA401 : \"CustomRendered\",\n\t\t0xA402 : \"ExposureMode\",\n\t\t0xA403 : \"WhiteBalance\",\n\t\t0xA404 : \"DigitalZoomRatio\",\n\t\t0xA405 : \"FocalLengthIn35mmFormat\",\n\t\t0xA406 : \"SceneCaptureType\",\n\t\t0xA407 : \"GainControl\",\n\t\t0xA408 : \"Contrast\",\n\t\t0xA409 : \"Saturation\",\n\t\t0xA40A : \"Sharpness\",\n\t\t0xA40B : \"DeviceSettingDescription\",\n\t\t0xA40C : \"SubjectDistanceRange\",\n\t\t0xA420 : \"ImageUniqueID\",\n\t\t0xA430 : \"OwnerName\",\n\t\t0xA431 : \"SerialNumber\",\n\t\t0xA432 : \"LensInfo\",\n\t\t0xA433 : \"LensMake\",\n\t\t0xA434 : \"LensModel\",\n\t\t0xA435 : \"LensSerialNumber\",\n\t\t0xA480 : \"GDALMetadata\",\n\t\t0xA481 : \"GDALNoData\",\n\t\t0xA500 : \"Gamma\",\n\t\t0xAFC0 : \"ExpandSoftware\",\n\t\t0xAFC1 : \"ExpandLens\",\n\t\t0xAFC2 : \"ExpandFilm\",\n\t\t0xAFC3 : \"ExpandFilterLens\",\n\t\t0xAFC4 : \"ExpandScanner\",\n\t\t0xAFC5 : \"ExpandFlashLamp\",\n\t\t0xBC01 : \"PixelFormat\",\n\t\t0xBC02 : \"Transformation\",\n\t\t0xBC03 : \"Uncompressed\",\n\t\t0xBC04 : \"ImageType\",\n\t\t0xBC80 : \"ImageWidth\",\n\t\t0xBC81 : \"ImageHeight\",\n\t\t0xBC82 : \"WidthResolution\",\n\t\t0xBC83 : \"HeightResolution\",\n\t\t0xBCC0 : \"ImageOffset\",\n\t\t0xBCC1 : \"ImageByteCount\",\n\t\t0xBCC2 : \"AlphaOffset\",\n\t\t0xBCC3 : \"AlphaByteCount\",\n\t\t0xBCC4 : \"ImageDataDiscard\",\n\t\t0xBCC5 : \"AlphaDataDiscard\",\n\t\t0xC427 : \"OceScanjobDesc\",\n\t\t0xC428 : \"OceApplicationSelector\",\n\t\t0xC429 : \"OceIDNumber\",\n\t\t0xC42A : \"OceImageLogic\",\n\t\t0xC44F : \"Annotations\",\n\t\t0xC4A5 : \"PrintIM\",\n\t\t0xC580 : \"USPTOOriginalContentType\",\n\t\t0xC612 : \"DNGVersion\",\n\t\t0xC613 : \"DNGBackwardVersion\",\n\t\t0xC614 : \"UniqueCameraModel\",\n\t\t0xC615 : \"LocalizedCameraModel\",\n\t\t0xC616 : \"CFAPlaneColor\",\n\t\t0xC617 : \"CFALayout\",\n\t\t0xC618 : \"LinearizationTable\",\n\t\t0xC619 : \"BlackLevelRepeatDim\",\n\t\t0xC61A : \"BlackLevel\",\n\t\t0xC61B : \"BlackLevelDeltaH\",\n\t\t0xC61C : \"BlackLevelDeltaV\",\n\t\t0xC61D : \"WhiteLevel\",\n\t\t0xC61E : \"DefaultScale\",\n\t\t0xC61F : \"DefaultCropOrigin\",\n\t\t0xC620 : \"DefaultCropSize\",\n\t\t0xC621 : \"ColorMatrix1\",\n\t\t0xC622 : \"ColorMatrix2\",\n\t\t0xC623 : \"CameraCalibration1\",\n\t\t0xC624 : \"CameraCalibration2\",\n\t\t0xC625 : \"ReductionMatrix1\",\n\t\t0xC626 : \"ReductionMatrix2\",\n\t\t0xC627 : \"AnalogBalance\",\n\t\t0xC628 : \"AsShotNeutral\",\n\t\t0xC629 : \"AsShotWhiteXY\",\n\t\t0xC62A : \"BaselineExposure\",\n\t\t0xC62B : \"BaselineNoise\",\n\t\t0xC62C : \"BaselineSharpness\",\n\t\t0xC62D : \"BayerGreenSplit\",\n\t\t0xC62E : \"LinearResponseLimit\",\n\t\t0xC62F : \"CameraSerialNumber\",\n\t\t0xC630 : \"DNGLensInfo\",\n\t\t0xC631 : \"ChromaBlurRadius\",\n\t\t0xC632 : \"AntiAliasStrength\",\n\t\t0xC633 : \"ShadowScale\",\n\t\t0xC634 : \"DNGPrivateData\",\n\t\t0xC635 : \"MakerNoteSafety\",\n\t\t0xC640 : \"RawImageSegmentation\",\n\t\t0xC65A : \"CalibrationIlluminant1\",\n\t\t0xC65B : \"CalibrationIlluminant2\",\n\t\t0xC65C : \"BestQualityScale\",\n\t\t0xC65D : \"RawDataUniqueID\",\n\t\t0xC660 : \"AliasLayerMetadata\",\n\t\t0xC68B : \"OriginalRawFileName\",\n\t\t0xC68C : \"OriginalRawFileData\",\n\t\t0xC68D : \"ActiveArea\",\n\t\t0xC68E : \"MaskedAreas\",\n\t\t0xC68F : \"AsShotICCProfile\",\n\t\t0xC690 : \"AsShotPreProfileMatrix\",\n\t\t0xC691 : \"CurrentICCProfile\",\n\t\t0xC692 : \"CurrentPreProfileMatrix\",\n\t\t0xC6BF : \"ColorimetricReference\",\n\t\t0xC6D2 : \"PanasonicTitle\",\n\t\t0xC6D3 : \"PanasonicTitle2\",\n\t\t0xC6F3 : \"CameraCalibrationSig\",\n\t\t0xC6F4 : \"ProfileCalibrationSig\",\n\t\t0xC6F5 : \"ProfileIFD\",\n\t\t0xC6F6 : \"AsShotProfileName\",\n\t\t0xC6F7 : \"NoiseReductionApplied\",\n\t\t0xC6F8 : \"ProfileName\",\n\t\t0xC6F9 : \"ProfileHueSatMapDims\",\n\t\t0xC6FA : \"ProfileHueSatMapData1\",\n\t\t0xC6FB : \"ProfileHueSatMapData2\",\n\t\t0xC6FC : \"ProfileToneCurve\",\n\t\t0xC6FD : \"ProfileEmbedPolicy\",\n\t\t0xC6FE : \"ProfileCopyright\",\n\t\t0xC714 : \"ForwardMatrix1\",\n\t\t0xC715 : \"ForwardMatrix2\",\n\t\t0xC716 : \"PreviewApplicationName\",\n\t\t0xC717 : \"PreviewApplicationVersion\",\n\t\t0xC718 : \"PreviewSettingsName\",\n\t\t0xC719 : \"PreviewSettingsDigest\",\n\t\t0xC71A : \"PreviewColorSpace\",\n\t\t0xC71B : \"PreviewDateTime\",\n\t\t0xC71C : \"RawImageDigest\",\n\t\t0xC71D : \"OriginalRawFileDigest\",\n\t\t0xC71E : \"SubTileBlockSize\",\n\t\t0xC71F : \"RowInterleaveFactor\",\n\t\t0xC725 : \"ProfileLookTableDims\",\n\t\t0xC726 : \"ProfileLookTableData\",\n\t\t0xC740 : \"OpcodeList1\",\n\t\t0xC741 : \"OpcodeList2\",\n\t\t0xC74E : \"OpcodeList3\",\n\t\t0xC761 : \"NoiseProfile\",\n\t\t0xC763 : \"TimeCodes\",\n\t\t0xC764 : \"FrameRate\",\n\t\t0xC772 : \"TStop\",\n\t\t0xC789 : \"ReelName\",\n\t\t0xC791 : \"OriginalDefaultFinalSize\",\n\t\t0xC792 : \"OriginalBestQualitySize\",\n\t\t0xC793 : \"OriginalDefaultCropSize\",\n\t\t0xC7A1 : \"CameraLabel\",\n\t\t0xC7A3 : \"ProfileHueSatMapEncoding\",\n\t\t0xC7A4 : \"ProfileLookTableEncoding\",\n\t\t0xC7A5 : \"BaselineExposureOffset\",\n\t\t0xC7A6 : \"DefaultBlackRender\",\n\t\t0xC7A7 : \"NewRawImageDigest\",\n\t\t0xC7A8 : \"RawToPreviewGain\",\n\t\t0xC7B5 : \"DefaultUserCrop\",\n\t\t0xEA1C : \"Padding\",\n\t\t0xEA1D : \"OffsetSchema\",\n\t\t0xFDE8 : \"OwnerName\",\n\t\t0xFDE9 : \"SerialNumber\",\n\t\t0xFDEA : \"Lens\",\n\t\t0xFE00 : \"KDC_IFD\",\n\t\t0xFE4C : \"RawFile\",\n\t\t0xFE4D : \"Converter\",\n\t\t0xFE4E : \"WhiteBalance\",\n\t\t0xFE51 : \"Exposure\",\n\t\t0xFE52 : \"Shadows\",\n\t\t0xFE53 : \"Brightness\",\n\t\t0xFE54 : \"Contrast\",\n\t\t0xFE55 : \"Saturation\",\n\t\t0xFE56 : \"Sharpness\",\n\t\t0xFE57 : \"Smoothness\",\n\t\t0xFE58 : \"MoireFilter\"\n\t\t\n\t},\n\tgps : {\t\n\t\t0x0000 : 'GPSVersionID',\n\t\t0x0001 : 'GPSLatitudeRef',\n\t\t0x0002 : 'GPSLatitude',\n\t\t0x0003 : 'GPSLongitudeRef',\n\t\t0x0004 : 'GPSLongitude',\n\t\t0x0005 : 'GPSAltitudeRef',\n\t\t0x0006 : 'GPSAltitude',\n\t\t0x0007 : 'GPSTimeStamp',\n\t\t0x0008 : 'GPSSatellites',\n\t\t0x0009 : 'GPSStatus',\n\t\t0x000A : 'GPSMeasureMode',\n\t\t0x000B : 'GPSDOP',\n\t\t0x000C : 'GPSSpeedRef',\n\t\t0x000D : 'GPSSpeed',\n\t\t0x000E : 'GPSTrackRef',\n\t\t0x000F : 'GPSTrack',\n\t\t0x0010 : 'GPSImgDirectionRef',\n\t\t0x0011 : 'GPSImgDirection',\n\t\t0x0012 : 'GPSMapDatum',\n\t\t0x0013 : 'GPSDestLatitudeRef',\n\t\t0x0014 : 'GPSDestLatitude',\n\t\t0x0015 : 'GPSDestLongitudeRef',\n\t\t0x0016 : 'GPSDestLongitude',\n\t\t0x0017 : 'GPSDestBearingRef',\n\t\t0x0018 : 'GPSDestBearing',\n\t\t0x0019 : 'GPSDestDistanceRef',\n\t\t0x001A : 'GPSDestDistance',\n\t\t0x001B : 'GPSProcessingMethod',\n\t\t0x001C : 'GPSAreaInformation',\n\t\t0x001D : 'GPSDateStamp',\n\t\t0x001E : 'GPSDifferential',\n\t\t0x001F : 'GPSHPositioningError'\n\t}\n};","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nvar jpeg = require('./jpeg'),\n\texif = require('./exif'),\n\tsimplify = require('./simplify');\n\nfunction ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) {\n\tthis.startMarker = startMarker;\n\tthis.tags = tags;\n\tthis.imageSize = imageSize;\n\tthis.thumbnailOffset = thumbnailOffset;\n\tthis.thumbnailLength = thumbnailLength;\n\tthis.thumbnailType = thumbnailType;\n\tthis.app1Offset = app1Offset;\n}\n\nExifResult.prototype = {\n\thasThumbnail: function(mime) {\n\t\tif(!this.thumbnailOffset || !this.thumbnailLength) {\n\t\t\treturn false;\n\t\t}\n\t\tif(typeof mime !== 'string') {\n\t\t\treturn true;\n\t\t}\n\t\tif(mime.toLowerCase().trim() === 'image/jpeg') {\n\t\t\treturn this.thumbnailType === 6;\n\t\t}\n\t\tif(mime.toLowerCase().trim() === 'image/tiff') {\n\t\t\treturn this.thumbnailType === 1;\n\t\t}\n\t\treturn false;\n\t},\n\tgetThumbnailOffset: function() {\n\t\treturn this.app1Offset + 6 + this.thumbnailOffset;\n\t},\n\tgetThumbnailLength: function() {\n\t\treturn this.thumbnailLength;\n\t},\n\tgetThumbnailBuffer: function() {\n\t\treturn this._getThumbnailStream().nextBuffer(this.thumbnailLength);\n\t},\n\t_getThumbnailStream: function() {\n\t\treturn this.startMarker.openWithOffset(this.getThumbnailOffset());\n\t},\n\tgetImageSize: function() {\n\t\treturn this.imageSize;\n\t},\n\tgetThumbnailSize: function() {\n\t\tvar stream = this._getThumbnailStream(), size;\n\t\tjpeg.parseSections(stream, function(sectionType, sectionStream) {\n\t\t\tif(jpeg.getSectionName(sectionType).name === 'SOF') {\n\t\t\t\tsize = jpeg.getSizeFromSOFSection(sectionStream);\n\t\t\t}\n\t\t});\n\t\treturn size;\n\t}\n};\n\nfunction Parser(stream) {\n\tthis.stream = stream;\n\tthis.flags = {\n\t\treadBinaryTags: false,\n\t\tresolveTagNames: true,\n\t\tsimplifyValues: true,\n\t\timageSize: true,\n\t\thidePointers: true,\n\t\treturnTags: true\n\t};\n}\n\nParser.prototype = {\n\tenableBinaryFields: function(enable) {\n\t\tthis.flags.readBinaryTags = !!enable;\n\t\treturn this;\n\t},\n\tenablePointers: function(enable) {\n\t\tthis.flags.hidePointers = !enable;\n\t\treturn this;\n\t},\n\tenableTagNames: function(enable) {\n\t\tthis.flags.resolveTagNames = !!enable;\n\t\treturn this;\n\t},\n\tenableImageSize: function(enable) {\n\t\tthis.flags.imageSize = !!enable;\n\t\treturn this;\n\t},\n\tenableReturnTags: function(enable) {\n\t\tthis.flags.returnTags = !!enable;\n\t\treturn this;\n\t},\n\tenableSimpleValues: function(enable) {\n\t\tthis.flags.simplifyValues = !!enable;\n\t\treturn this;\n\t},\n\tparse: function() {\n\t\tvar start = this.stream.mark(),\n\t\t\tstream = start.openWithOffset(0),\n\t\t\tflags = this.flags,\n\t\t\ttags,\n\t\t\timageSize,\n\t\t\tthumbnailOffset,\n\t\t\tthumbnailLength,\n\t\t\tthumbnailType,\n\t\t\tapp1Offset,\n\t\t\ttagNames,\n\t\t\tgetTagValue, setTagValue;\n\t\tif(flags.resolveTagNames) {\n\t\t\ttagNames = require('./exif-tags');\n\t\t}\n\t\tif(flags.resolveTagNames) {\n\t\t\ttags = {};\n\t\t\tgetTagValue = function(t) {\n\t\t\t\treturn tags[t.name];\n\t\t\t};\n\t\t\tsetTagValue = function(t, value) {\n\t\t\t\ttags[t.name] = value;\n\t\t\t};\n\t\t} else {\n\t\t\ttags = [];\n\t\t\tgetTagValue = function(t) {\n\t\t\t\tvar i;\n\t\t\t\tfor(i = 0; i < tags.length; ++i) {\n\t\t\t\t\tif(tags[i].type === t.type && tags[i].section === t.section) {\n\t\t\t\t\t\treturn tags.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tsetTagValue = function(t, value) {\n\t\t\t\tvar i;\n\t\t\t\tfor(i = 0; i < tags.length; ++i) {\n\t\t\t\t\tif(tags[i].type === t.type && tags[i].section === t.section) {\n\t\t\t\t\t\ttags.value = value;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\n\t\tjpeg.parseSections(stream, function(sectionType, sectionStream) {\n\t\t\tvar validExifHeaders, sectionOffset = sectionStream.offsetFrom(start);\n\t\t\tif(sectionType === 0xE1) {\n\t\t\t\tvalidExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) {\n\t\t\t\t\t//ignore binary fields if disabled\n\t\t\t\t\tif(!flags.readBinaryTags && format === 7) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(tagType === 0x0201) {\n\t\t\t\t\t\tthumbnailOffset = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t} else if(tagType === 0x0202) {\n\t\t\t\t\t\tthumbnailLength = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t} else if(tagType === 0x0103) {\n\t\t\t\t\t\tthumbnailType = value[0];\n\t\t\t\t\t\tif(flags.hidePointers) {return;}\n\t\t\t\t\t}\n\t\t\t\t\t//if flag is set to not store tags, return here after storing pointers\n\t\t\t\t\tif(!flags.returnTags) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(flags.simplifyValues) {\n\t\t\t\t\t\tvalue = simplify.simplifyValue(value, format);\n\t\t\t\t\t}\n\t\t\t\t\tif(flags.resolveTagNames) {\n\t\t\t\t\t\tvar sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif;\n\t\t\t\t\t\tvar name = sectionTagNames[tagType];\n\t\t\t\t\t\tif(!name) {\n\t\t\t\t\t\t\tname = tagNames.exif[tagType];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!tags.hasOwnProperty(name)) {\n\t\t\t\t\t\t\ttags[name] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttags.push({\n\t\t\t\t\t\t\tsection: ifdSection,\n\t\t\t\t\t\t\ttype: tagType,\n\t\t\t\t\t\t\tvalue: value\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif(validExifHeaders) {\n\t\t\t\t\tapp1Offset = sectionOffset;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') {\n\t\t\t\timageSize = jpeg.getSizeFromSOFSection(sectionStream);\n\t\t\t}\n\t\t});\n\n\t\tif(flags.simplifyValues) {\n\t\t\tsimplify.castDegreeValues(getTagValue, setTagValue);\n\t\t\tsimplify.castDateValues(getTagValue, setTagValue);\n\t\t}\n\n\t\treturn new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset);\n\t}\n};\n\n\n\nmodule.exports = Parser;\n","/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */\n\nfunction DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) {\n\tthis.global = global;\n\toffset = offset || 0;\n\tlength = length || (arrayBuffer.byteLength - offset);\n\tthis.arrayBuffer = arrayBuffer.slice(offset, offset + length);\n\tthis.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength);\n\tthis.setBigEndian(bigEndian);\n\tthis.offset = 0;\n\tthis.parentOffset = (parentOffset || 0) + offset;\n}\n\nDOMBufferStream.prototype = {\n\tsetBigEndian: function(bigEndian) {\n\t\tthis.littleEndian = !bigEndian;\n\t},\n\tnextUInt8: function() {\n\t\tvar value = this.view.getUint8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextInt8: function() {\n\t\tvar value = this.view.getInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextUInt16: function() {\n\t\tvar value = this.view.getUint16(this.offset, this.littleEndian);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextUInt32: function() {\n\t\tvar value = this.view.getUint32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextInt16: function() {\n\t\tvar value = this.view.getInt16(this.offset, this.littleEndian);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextInt32: function() {\n\t\tvar value = this.view.getInt32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextFloat: function() {\n\t\tvar value = this.view.getFloat32(this.offset, this.littleEndian);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextDouble: function() {\n\t\tvar value = this.view.getFloat64(this.offset, this.littleEndian);\n\t\tthis.offset += 8;\n\t\treturn value;\n\t},\n\tnextBuffer: function(length) {\n\t\t//this won't work in IE10\n\t\tvar value = this.arrayBuffer.slice(this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tremainingLength: function() {\n\t\treturn this.arrayBuffer.byteLength - this.offset;\n\t},\n\tnextString: function(length) {\n\t\tvar value = this.arrayBuffer.slice(this.offset, this.offset + length);\n\t\tvalue = String.fromCharCode.apply(null, new this.global.Uint8Array(value));\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tmark: function() {\n\t\tvar self = this;\n\t\treturn {\n\t\t\topenWithOffset: function(offset) {\n\t\t\t\toffset = (offset || 0) + this.offset;\n\t\t\t\treturn new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset);\n\t\t\t},\n\t\t\toffset: this.offset,\n\t\t\tgetParentOffset: function() {\n\t\t\t\treturn self.parentOffset;\n\t\t\t}\n\t\t};\n\t},\n\toffsetFrom: function(marker) {\n\t\treturn this.parentOffset + this.offset - (marker.offset + marker.getParentOffset());\n\t},\n\tskip: function(amount) {\n\t\tthis.offset += amount;\n\t},\n\tbranch: function(offset, length) {\n\t\tlength = typeof length === 'number' ? length : this.arrayBuffer.byteLength - (this.offset + offset);\n\t\treturn new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset);\n\t}\n};\n\nmodule.exports = DOMBufferStream;\n","function BufferStream(buffer, offset, length, bigEndian) {\n\tthis.buffer = buffer;\n\tthis.offset = offset || 0;\n\tlength = typeof length === 'number' ? length : buffer.length;\n\tthis.endPosition = this.offset + length;\n\tthis.setBigEndian(bigEndian);\n}\n\nBufferStream.prototype = {\n\tsetBigEndian: function(bigEndian) {\n\t\tthis.bigEndian = !!bigEndian;\n\t},\n\tnextUInt8: function() {\n\t\tvar value = this.buffer.readUInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextInt8: function() {\n\t\tvar value = this.buffer.readInt8(this.offset);\n\t\tthis.offset += 1;\n\t\treturn value;\n\t},\n\tnextUInt16: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextUInt32: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextInt16: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);\n\t\tthis.offset += 2;\n\t\treturn value;\n\t},\n\tnextInt32: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextFloat: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);\n\t\tthis.offset += 4;\n\t\treturn value;\n\t},\n\tnextDouble: function() {\n\t\tvar value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);\n\t\tthis.offset += 8;\n\t\treturn value;\n\t},\n\tnextBuffer: function(length) {\n\t\tvar value = this.buffer.slice(this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tremainingLength: function() {\n\t\treturn this.endPosition - this.offset;\n\t},\n\tnextString: function(length) {\n\t\tvar value = this.buffer.toString('utf8', this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn value;\n\t},\n\tmark: function() {\n\t\tvar self = this;\n\t\treturn {\n\t\t\topenWithOffset: function(offset) {\n\t\t\t\toffset = (offset || 0) + this.offset;\n\t\t\t\treturn new BufferStream(self.buffer, offset, self.endPosition - offset, self.bigEndian);\n\t\t\t},\n\t\t\toffset: this.offset\n\t\t};\n\t},\n\toffsetFrom: function(marker) {\n\t\treturn this.offset - marker.offset;\n\t},\n\tskip: function(amount) {\n\t\tthis.offset += amount;\n\t},\n\tbranch: function(offset, length) {\n\t\tlength = typeof length === 'number' ? length : this.endPosition - (this.offset + offset);\n\t\treturn new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian);\n\t}\n};\n\nmodule.exports = BufferStream;\n","var Parser = require('./lib/parser');\n\nfunction getGlobal() {\n\treturn (1,eval)('this');\n}\n\nmodule.exports = {\n\tcreate: function(buffer, global) {\n\t\tglobal = global || getGlobal();\n\t\tif(buffer instanceof global.ArrayBuffer) {\n\t\t\tvar DOMBufferStream = require('./lib/dom-bufferstream');\n\t\t\treturn new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global));\n\t\t} else {\n\t\t\tvar NodeBufferStream = require('./lib/bufferstream');\n\t\t\treturn new Parser(new NodeBufferStream(buffer, 0, buffer.length, true));\n\t\t}\n\t}\n};\n","'use strict';\n\n/**\n * Converter\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n * @constructor\n */\nfunction Converter(srcAlphabet, dstAlphabet) {\n if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {\n throw new Error('Bad alphabet');\n }\n this.srcAlphabet = srcAlphabet;\n this.dstAlphabet = dstAlphabet;\n}\n\n/**\n * Convert number from source alphabet to destination alphabet\n *\n * @param {string|Array} number - number represented as a string or array of points\n *\n * @returns {string|Array}\n */\nConverter.prototype.convert = function(number) {\n var i, divide, newlen,\n numberMap = {},\n fromBase = this.srcAlphabet.length,\n toBase = this.dstAlphabet.length,\n length = number.length,\n result = typeof number === 'string' ? '' : [];\n\n if (!this.isValid(number)) {\n throw new Error('Number \"' + number + '\" contains of non-alphabetic digits (' + this.srcAlphabet + ')');\n }\n\n if (this.srcAlphabet === this.dstAlphabet) {\n return number;\n }\n\n for (i = 0; i < length; i++) {\n numberMap[i] = this.srcAlphabet.indexOf(number[i]);\n }\n do {\n divide = 0;\n newlen = 0;\n for (i = 0; i < length; i++) {\n divide = divide * fromBase + numberMap[i];\n if (divide >= toBase) {\n numberMap[newlen++] = parseInt(divide / toBase, 10);\n divide = divide % toBase;\n } else if (newlen > 0) {\n numberMap[newlen++] = 0;\n }\n }\n length = newlen;\n result = this.dstAlphabet.slice(divide, divide + 1).concat(result);\n } while (newlen !== 0);\n\n return result;\n};\n\n/**\n * Valid number with source alphabet\n *\n * @param {number} number\n *\n * @returns {boolean}\n */\nConverter.prototype.isValid = function(number) {\n var i = 0;\n for (; i < number.length; ++i) {\n if (this.srcAlphabet.indexOf(number[i]) === -1) {\n return false;\n }\n }\n return true;\n};\n\nmodule.exports = Converter;","var Converter = require('./src/converter');\n\n/**\n * Function get source and destination alphabet and return convert function\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n *\n * @returns {function(number|Array)}\n */\nfunction anyBase(srcAlphabet, dstAlphabet) {\n var converter = new Converter(srcAlphabet, dstAlphabet);\n /**\n * Convert function\n *\n * @param {string|Array} number\n *\n * @return {string|Array} number\n */\n return function (number) {\n return converter.convert(number);\n }\n};\n\nanyBase.BIN = '01';\nanyBase.OCT = '01234567';\nanyBase.DEC = '0123456789';\nanyBase.HEX = '0123456789abcdef';\n\nmodule.exports = anyBase;","module.exports = function parseBMFontAscii(data) {\n if (!data)\n throw new Error('no data provided')\n data = data.toString().trim()\n\n var output = {\n pages: [],\n chars: [],\n kernings: []\n }\n\n var lines = data.split(/\\r\\n?|\\n/g)\n\n if (lines.length === 0)\n throw new Error('no data in BMFont file')\n\n for (var i = 0; i < lines.length; i++) {\n var lineData = splitLine(lines[i], i)\n if (!lineData) //skip empty lines\n continue\n\n if (lineData.key === 'page') {\n if (typeof lineData.data.id !== 'number')\n throw new Error('malformed file at line ' + i + ' -- needs page id=N')\n if (typeof lineData.data.file !== 'string')\n throw new Error('malformed file at line ' + i + ' -- needs page file=\"path\"')\n output.pages[lineData.data.id] = lineData.data.file\n } else if (lineData.key === 'chars' || lineData.key === 'kernings') {\n //... do nothing for these two ...\n } else if (lineData.key === 'char') {\n output.chars.push(lineData.data)\n } else if (lineData.key === 'kerning') {\n output.kernings.push(lineData.data)\n } else {\n output[lineData.key] = lineData.data\n }\n }\n\n return output\n}\n\nfunction splitLine(line, idx) {\n line = line.replace(/\\t+/g, ' ').trim()\n if (!line)\n return null\n\n var space = line.indexOf(' ')\n if (space === -1) \n throw new Error(\"no named row at line \" + idx)\n\n var key = line.substring(0, space)\n\n line = line.substring(space + 1)\n //clear \"letter\" field as it is non-standard and\n //requires additional complexity to parse \" / = symbols\n line = line.replace(/letter=[\\'\\\"]\\S+[\\'\\\"]/gi, '') \n line = line.split(\"=\")\n line = line.map(function(str) {\n return str.trim().match((/(\".*?\"|[^\"\\s]+)+(?=\\s*|\\s*$)/g))\n })\n\n var data = []\n for (var i = 0; i < line.length; i++) {\n var dt = line[i]\n if (i === 0) {\n data.push({\n key: dt[0],\n data: \"\"\n })\n } else if (i === line.length - 1) {\n data[data.length - 1].data = parseData(dt[0])\n } else {\n data[data.length - 1].data = parseData(dt[0])\n data.push({\n key: dt[1],\n data: \"\"\n })\n }\n }\n\n var out = {\n key: key,\n data: {}\n }\n\n data.forEach(function(v) {\n out.data[v.key] = v.data;\n })\n\n return out\n}\n\nfunction parseData(data) {\n if (!data || data.length === 0)\n return \"\"\n\n if (data.indexOf('\"') === 0 || data.indexOf(\"'\") === 0)\n return data.substring(1, data.length - 1)\n if (data.indexOf(',') !== -1)\n return parseIntList(data)\n return parseInt(data, 10)\n}\n\nfunction parseIntList(data) {\n return data.split(',').map(function(val) {\n return parseInt(val, 10)\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++, //