Compare commits

...

38 Commits

Author SHA1 Message Date
Michael B. Gale b24bd4a46f Don't fail post start-proxy action if killing the proxy process fails
Otherwise logs won't get uploaded as artifact, even in debug mode
2025-04-25 16:53:21 +01:00
Michael B. Gale 6e35f86a20 Add proxy_binary input to start-proxy Action
This allows a custom binary to be used. Mainly for testing.
2025-04-25 16:53:09 +01:00
Michael B. Gale f843d94177 Merge pull request #2869 from github/mbg/proxy/use-2.21.1-artifacts
Use proxy artifacts for `v2.21.1`
2025-04-25 16:50:50 +01:00
Michael B. Gale 2264a4ecc1 Merge branch 'main' into mbg/proxy/use-2.21.1-artifacts 2025-04-25 14:25:57 +01:00
Michael B. Gale d3b65fcaf0 Merge pull request #2870 from github/mbg/ci/retire-ubuntu-20.04
Remove ubuntu-20.04 and add ubuntu-24.04
2025-04-25 14:25:40 +01:00
Michael B. Gale eea52ddc4e Remove ubuntu-20.04 and add ubuntu-24.04 2025-04-25 13:03:25 +01:00
Michael B. Gale 6ef9b921b1 Use proxy artifacts for v2.21.1 2025-04-24 18:20:31 +01:00
Ian Lynagh 4ffa2364a0 Merge pull request #2867 from github/mergeback/v3.28.16-to-main-28deaeda
Mergeback v3.28.16 refs/heads/releases/v3 into main
2025-04-23 13:34:31 +01:00
github-actions[bot] 7e00290d34 Update checked-in dependencies 2025-04-23 12:17:11 +00:00
github-actions[bot] 259434501f Update changelog and version after v3.28.16 2025-04-23 12:10:49 +00:00
Ian Lynagh 28deaeda66 Merge pull request #2865 from github/update-v3.28.16-2a8cbadc0
Merge main into releases/v3
2025-04-23 13:10:18 +01:00
github-actions[bot] 03c5d71c11 Update changelog for v3.28.16 2025-04-23 10:40:48 +00:00
Ian Lynagh 2a8cbadc02 Merge pull request #2863 from github/update-bundle/codeql-bundle-v2.21.1
Update default bundle to 2.21.1
2025-04-22 12:30:12 +01:00
github-actions[bot] f76eaf51a6 Add changelog note 2025-04-16 16:54:18 +00:00
github-actions[bot] e63b3f5166 Update default bundle to codeql-bundle-v2.21.1 2025-04-16 16:54:11 +00:00
Andrew Eisenberg 4c3e536282 Merge pull request #2853 from github/dependabot/npm_and_yarn/npm-7d84c66b66
build(deps-dev): bump the npm group with 3 updates
2025-04-10 16:31:21 -07:00
Nick Fyson 56dd02f26d Merge pull request #2852 from github/dependabot/github_actions/actions-4575878e06
build(deps): bump actions/create-github-app-token from 1.12.0 to 2.0.2 in the actions group
2025-04-09 17:18:03 +01:00
Nick Fyson 192406dd84 Merge branch 'main' into dependabot/github_actions/actions-4575878e06 2025-04-09 16:59:59 +01:00
Nick Fyson c7dbb2084e Merge pull request #2857 from github/nickfyson/address-vulns
move use of input variables into env vars
2025-04-09 16:05:04 +01:00
nickfyson 9a45cd8c50 move use of input variables into env vars 2025-04-09 14:13:35 +01:00
Andrew Eisenberg d26c46acea Merge pull request #2855 from github/mergeback/v3.28.15-to-main-45775bd8
Mergeback v3.28.15 refs/heads/releases/v3 into main
2025-04-07 14:48:19 -07:00
github-actions[bot] 51c83e1588 Update checked-in dependencies 2025-04-07 21:34:58 +00:00
github-actions[bot] 8774e3f945 Update changelog and version after v3.28.15 2025-04-07 21:32:19 +00:00
Andrew Eisenberg 45775bd823 Merge pull request #2854 from github/update-v3.28.15-a35ae8c38
Merge main into releases/v3
2025-04-07 14:31:50 -07:00
Andrew Eisenberg dd78aab407 Update CHANGELOG.md with bug fix details 2025-04-07 14:15:05 -07:00
github-actions[bot] e40af59174 Update changelog for v3.28.15 2025-04-07 21:05:03 +00:00
Chuan-kai Lin a35ae8c380 Merge pull request #2843 from github/cklin/diff-informed-compat
Set checkPresence in diff-range data extension
2025-04-07 13:29:16 -07:00
github-actions[bot] 5bddbeb2bf Update checked-in dependencies 2025-04-07 17:59:50 +00:00
dependabot[bot] c7102cdca1 build(deps-dev): bump the npm group with 3 updates
Bumps the npm group with 3 updates: [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js), [nock](https://github.com/nock/nock) and [typescript](https://github.com/microsoft/TypeScript).


Updates `@eslint/js` from 9.23.0 to 9.24.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/commits/v9.24.0/packages/js)

Updates `nock` from 14.0.2 to 14.0.3
- [Release notes](https://github.com/nock/nock/releases)
- [Changelog](https://github.com/nock/nock/blob/main/CHANGELOG.md)
- [Commits](https://github.com/nock/nock/compare/v14.0.2...v14.0.3)

Updates `typescript` from 5.8.2 to 5.8.3
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release-publish.yml)
- [Commits](https://github.com/microsoft/TypeScript/commits)

---
updated-dependencies:
- dependency-name: "@eslint/js"
  dependency-version: 9.24.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm
- dependency-name: nock
  dependency-version: 14.0.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm
- dependency-name: typescript
  dependency-version: 5.8.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-07 17:59:17 +00:00
dependabot[bot] a1ca4846bc build(deps): bump actions/create-github-app-token in the actions group
Bumps the actions group with 1 update: [actions/create-github-app-token](https://github.com/actions/create-github-app-token).


Updates `actions/create-github-app-token` from 1.12.0 to 2.0.2
- [Release notes](https://github.com/actions/create-github-app-token/releases)
- [Commits](https://github.com/actions/create-github-app-token/compare/v1.12.0...v2.0.2)

---
updated-dependencies:
- dependency-name: actions/create-github-app-token
  dependency-version: 2.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-07 17:53:11 +00:00
Andrew Eisenberg bb59df6c17 Merge pull request #2842 from github/henrymercer/zip64
Raise the file limit for debug artifacts by producing zip64 files where necessary
2025-04-07 10:50:46 -07:00
Arthur Baars 4b508f5964 Merge pull request #2845 from github/mergeback/v3.28.14-to-main-fc7e4a0f
Mergeback v3.28.14 refs/heads/releases/v3 into main
2025-04-07 13:04:29 +02:00
github-actions[bot] ca00afb5f1 Update checked-in dependencies 2025-04-07 09:33:21 +00:00
github-actions[bot] 2969c78ce0 Update changelog and version after v3.28.14 2025-04-07 09:27:28 +00:00
Andrew Eisenberg a8be43c24e Don't throw error for ENOENT 2025-04-04 13:42:00 -07:00
Chuan-kai Lin 94102d99b0 Set checkPresence in diff-range data extension
This commit updates the diff-range data extension to use the new
checkPresence field being introduced in CodeQL CLI 2.21.0, so that
diff-informed analysis no longer fails when a query pack does not have
the restrictAlertsTo extensible predicate.
2025-04-04 08:41:50 -07:00
github-actions[bot] fd8685f16e Update checked-in dependencies 2025-04-04 13:46:53 +00:00
Henry Mercer 56feaac968 Raise file limit in debug artifacts by using zip64 2025-04-04 14:40:53 +01:00
128 changed files with 978 additions and 4396 deletions
+12 -9
View File
@@ -29,24 +29,27 @@ runs:
- id: get-url
name: Determine URL
shell: bash
env:
VERSION: ${{ inputs.version }}
USE_ALL_PLATFORM_BUNDLE: ${{ inputs.use-all-platform-bundle }}
run: |
set -e # Fail this Action if `gh release list` fails.
if [[ ${{ inputs.version }} == "linked" ]]; then
if [[ "$VERSION" == "linked" ]]; then
echo "tools-url=linked" >> "$GITHUB_OUTPUT"
exit 0
elif [[ ${{ inputs.version }} == "default" ]]; then
elif [[ "$VERSION" == "default" ]]; then
echo "tools-url=" >> "$GITHUB_OUTPUT"
exit 0
fi
if [[ ${{ inputs.version }} == "nightly-latest" && "$RUNNER_OS" != "Windows" ]]; then
if [[ "$VERSION" == "nightly-latest" && "$RUNNER_OS" != "Windows" ]]; then
extension="tar.zst"
else
extension="tar.gz"
fi
if [[ ${{ inputs.use-all-platform-bundle }} == "true" ]]; then
if [[ "$USE_ALL_PLATFORM_BUNDLE" == "true" ]]; then
artifact_name="codeql-bundle.$extension"
elif [[ "$RUNNER_OS" == "Linux" ]]; then
artifact_name="codeql-bundle-linux64.$extension"
@@ -59,14 +62,14 @@ runs:
exit 1
fi
if [[ ${{ inputs.version }} == "nightly-latest" ]]; then
if [[ "$VERSION" == "nightly-latest" ]]; then
tag=`gh release list --repo dsp-testing/codeql-cli-nightlies -L 1 | cut -f 3`
echo "tools-url=https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/$tag/$artifact_name" >> $GITHUB_OUTPUT
elif [[ ${{ inputs.version }} == *"nightly"* ]]; then
version=`echo ${{ inputs.version }} | sed -e 's/^.*\-//'`
elif [[ "$VERSION" == *"nightly"* ]]; then
version=`echo "$VERSION" | sed -e 's/^.*\-//'`
echo "tools-url=https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/codeql-bundle-$version/$artifact_name" >> $GITHUB_OUTPUT
elif [[ ${{ inputs.version }} == *"stable"* ]]; then
version=`echo ${{ inputs.version }} | sed -e 's/^.*\-//'`
elif [[ "$VERSION" == *"stable"* ]]; then
version=`echo "$VERSION" | sed -e 's/^.*\-//'`
echo "tools-url=https://github.com/github/codeql-action/releases/download/codeql-bundle-$version/$artifact_name" >> $GITHUB_OUTPUT
else
echo "::error::Unrecognized version specified!"
+5 -2
View File
@@ -18,8 +18,11 @@ runs:
using: "composite"
steps:
- id: branches
env:
MAJOR_VERSION: ${{ inputs.major_version }}
LATEST_TAG: ${{ inputs.latest_tag }}
run: |
python ${{ github.action_path }}/release-branches.py \
--major-version ${{ inputs.major_version }} \
--latest-tag ${{ inputs.latest_tag }}
--major-version "$MAJOR_VERSION" \
--latest-tag "$LATEST_TAG"
shell: bash
+1 -1
View File
@@ -75,7 +75,7 @@ jobs:
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04,ubuntu-22.04,windows-2019,windows-2022,macos-13,macos-14]
os: [ubuntu-22.04,ubuntu-24.04,windows-2019,windows-2022,macos-13,macos-14]
tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }}
runs-on: ${{ matrix.os }}
+1 -1
View File
@@ -168,7 +168,7 @@ jobs:
--draft
- name: Generate token
uses: actions/create-github-app-token@v1.12.0
uses: actions/create-github-app-token@v2.0.2
id: app-token
with:
app-id: ${{ vars.AUTOMATION_APP_ID }}
+1 -1
View File
@@ -124,7 +124,7 @@ jobs:
pull-requests: write # needed to create pull request
steps:
- name: Generate token
uses: actions/create-github-app-token@v1.12.0
uses: actions/create-github-app-token@v2.0.2
id: app-token
with:
app-id: ${{ vars.AUTOMATION_APP_ID }}
+12
View File
@@ -2,6 +2,18 @@
See the [releases page](https://github.com/github/codeql-action/releases) for the relevant changes to the CodeQL CLI and language packs.
## [UNRELEASED]
No user facing changes.
## 3.28.16 - 23 Apr 2025
- Update default CodeQL bundle version to 2.21.1. [#2863](https://github.com/github/codeql-action/pull/2863)
## 3.28.15 - 07 Apr 2025
- Fix bug where the action would fail if it tried to produce a debug artifact with more than 65535 files. [#2842](https://github.com/github/codeql-action/pull/2842)
## 3.28.14 - 07 Apr 2025
- Update default CodeQL bundle version to 2.21.0. [#2838](https://github.com/github/codeql-action/pull/2838)
+1
View File
@@ -358,6 +358,7 @@ extensions:
- addsTo:
pack: codeql/util
extensible: restrictAlertsTo
checkPresence: false
data:
`;
let data = ranges
+1 -1
View File
File diff suppressed because one or more lines are too long
+15 -4
View File
@@ -46,7 +46,7 @@ const path = __importStar(require("path"));
const artifact = __importStar(require("@actions/artifact"));
const artifactLegacy = __importStar(require("@actions/artifact-legacy"));
const core = __importStar(require("@actions/core"));
const adm_zip_1 = __importDefault(require("adm-zip"));
const archiver_1 = __importDefault(require("archiver"));
const del_1 = __importDefault(require("del"));
const actions_util_1 = require("./actions-util");
const analyze_1 = require("./analyze");
@@ -250,9 +250,20 @@ async function createPartialDatabaseBundle(config, language) {
if (fs.existsSync(databaseBundlePath)) {
await (0, del_1.default)(databaseBundlePath, { force: true });
}
const zip = new adm_zip_1.default();
zip.addLocalFolder(databasePath);
zip.writeZip(databaseBundlePath);
const output = fs.createWriteStream(databaseBundlePath);
const zip = (0, archiver_1.default)("zip");
zip.on("error", (err) => {
throw err;
});
zip.on("warning", (err) => {
// Ignore ENOENT warnings. There's nothing anyone can do about it.
if (err.code !== "ENOENT") {
throw err;
}
});
zip.pipe(output);
zip.directory(databasePath, false);
await zip.finalize();
return databaseBundlePath;
}
/**
File diff suppressed because one or more lines are too long
+4 -4
View File
@@ -1,6 +1,6 @@
{
"bundleVersion": "codeql-bundle-v2.21.0",
"cliVersion": "2.21.0",
"priorBundleVersion": "codeql-bundle-v2.20.7",
"priorCliVersion": "2.20.7"
"bundleVersion": "codeql-bundle-v2.21.1",
"cliVersion": "2.21.1",
"priorBundleVersion": "codeql-bundle-v2.21.0",
"priorCliVersion": "2.21.0"
}
+1 -2
View File
@@ -96,8 +96,7 @@ exports.featureConfig = {
[Feature.DiffInformedQueries]: {
defaultValue: false,
envVar: "CODEQL_ACTION_DIFF_INFORMED_QUERIES",
minimumVersion: undefined,
toolsFeature: tools_features_1.ToolsFeature.DatabaseInterpretResultsSupportsSarifRunProperty,
minimumVersion: "2.21.0",
},
[Feature.DisableCsharpBuildless]: {
defaultValue: false,
File diff suppressed because one or more lines are too long
+6 -1
View File
@@ -53,7 +53,12 @@ async function runWrapper() {
// Kill the running proxy
const pid = core.getState("proxy-process-pid");
if (pid) {
process.kill(Number(pid));
try {
process.kill(Number(pid));
}
catch (error) {
logger.error(`Failed to kill proxy process: ${(0, util_1.getErrorMessage)(error)}`);
}
}
const config = await configUtils.getConfig(actionsUtil.getTemporaryDirectory(), logger);
if ((config && config.debugMode) || core.isDebug()) {
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"start-proxy-action-post.js","sourceRoot":"","sources":["../src/start-proxy-action-post.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;GAIG;AACH,oDAAsC;AAEtC,4DAA8C;AAC9C,6CAAgD;AAChD,4DAA8C;AAC9C,uDAA8D;AAC9D,uCAA6C;AAC7C,iCAAoE;AAEpE,KAAK,UAAU,UAAU;IACvB,MAAM,MAAM,GAAG,IAAA,0BAAgB,GAAE,CAAC;IAElC,IAAI,CAAC;QACH,4CAA4C;QAC5C,WAAW,CAAC,aAAa,EAAE,CAAC;QAE5B,yBAAyB;QACzB,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC;QAC/C,IAAI,GAAG,EAAE,CAAC;YACR,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5B,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,SAAS,CACxC,WAAW,CAAC,qBAAqB,EAAE,EACnC,MAAM,CACP,CAAC;QAEF,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;YACnD,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;YACpD,MAAM,CAAC,IAAI,CACT,wEAAwE,CACzE,CAAC;YACF,IAAI,MAAM,EAAE,aAAa,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC7C,MAAM,CAAC,OAAO,CACZ,qFAAqF,CACtF,CAAC;gBACF,OAAO;YACT,CAAC;YACD,MAAM,aAAa,GAAG,MAAM,IAAA,6BAAgB,GAAE,CAAC;YAC/C,IAAA,gCAAyB,EAAC,aAAa,EAAE,MAAM,CAAC,CAAC;YAEjD,MAAM,gBAAgB,GAAG,MAAM,IAAA,2CAAyB,EACtD,MAAM,EACN,aAAa,CAAC,IAAI,CACnB,CAAC;YAEF,MAAM,gBAAgB,CAAC,cAAc,CACnC,gBAAgB,EAChB,CAAC,WAAW,CAAC,EACb,WAAW,CAAC,qBAAqB,EAAE,EACnC;gBACE,wFAAwF;gBACxF,aAAa,EAAE,CAAC;aACjB,CACF,CAAC;QACJ,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,gEAAgE;QAChE,MAAM,CAAC,OAAO,CACZ,wCAAwC,IAAA,sBAAe,EAAC,KAAK,CAAC,EAAE,CACjE,CAAC;IACJ,CAAC;AACH,CAAC;AAED,KAAK,UAAU,EAAE,CAAC"}
{"version":3,"file":"start-proxy-action-post.js","sourceRoot":"","sources":["../src/start-proxy-action-post.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;GAIG;AACH,oDAAsC;AAEtC,4DAA8C;AAC9C,6CAAgD;AAChD,4DAA8C;AAC9C,uDAA8D;AAC9D,uCAA6C;AAC7C,iCAAoE;AAEpE,KAAK,UAAU,UAAU;IACvB,MAAM,MAAM,GAAG,IAAA,0BAAgB,GAAE,CAAC;IAElC,IAAI,CAAC;QACH,4CAA4C;QAC5C,WAAW,CAAC,aAAa,EAAE,CAAC;QAE5B,yBAAyB;QACzB,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC;QAC/C,IAAI,GAAG,EAAE,CAAC;YACR,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC5B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,iCAAiC,IAAA,sBAAe,EAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,SAAS,CACxC,WAAW,CAAC,qBAAqB,EAAE,EACnC,MAAM,CACP,CAAC;QAEF,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;YACnD,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;YACpD,MAAM,CAAC,IAAI,CACT,wEAAwE,CACzE,CAAC;YACF,IAAI,MAAM,EAAE,aAAa,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC7C,MAAM,CAAC,OAAO,CACZ,qFAAqF,CACtF,CAAC;gBACF,OAAO;YACT,CAAC;YACD,MAAM,aAAa,GAAG,MAAM,IAAA,6BAAgB,GAAE,CAAC;YAC/C,IAAA,gCAAyB,EAAC,aAAa,EAAE,MAAM,CAAC,CAAC;YAEjD,MAAM,gBAAgB,GAAG,MAAM,IAAA,2CAAyB,EACtD,MAAM,EACN,aAAa,CAAC,IAAI,CACnB,CAAC;YAEF,MAAM,gBAAgB,CAAC,cAAc,CACnC,gBAAgB,EAChB,CAAC,WAAW,CAAC,EACb,WAAW,CAAC,qBAAqB,EAAE,EACnC;gBACE,wFAAwF;gBACxF,aAAa,EAAE,CAAC;aACjB,CACF,CAAC;QACJ,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,gEAAgE;QAChE,MAAM,CAAC,OAAO,CACZ,wCAAwC,IAAA,sBAAe,EAAC,KAAK,CAAC,EAAE,CACjE,CAAC;IACJ,CAAC;AACH,CAAC;AAED,KAAK,UAAU,EAAE,CAAC"}
+4 -3
View File
@@ -43,8 +43,8 @@ const logging_1 = require("./logging");
const start_proxy_1 = require("./start-proxy");
const util = __importStar(require("./util"));
const UPDATEJOB_PROXY = "update-job-proxy";
const UPDATEJOB_PROXY_VERSION = "v2.0.20241023203727";
const UPDATEJOB_PROXY_URL_PREFIX = "https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.18.1/";
const UPDATEJOB_PROXY_VERSION = "v2.0.20250424171100";
const UPDATEJOB_PROXY_URL_PREFIX = "https://github.com/github/codeql-action/releases/download/codeql-bundle-v2.21.1/";
const KEY_SIZE = 2048;
const KEY_EXPIRY_YEARS = 2;
const CERT_SUBJECT = [
@@ -112,7 +112,8 @@ async function runWrapper() {
ca,
};
// Start the Proxy
const proxyBin = await getProxyBinaryPath();
const proxyBin = actionsUtil.getOptionalInput("proxy_binary") ??
(await getProxyBinaryPath());
await startProxy(proxyBin, proxyConfig, proxyLogFilePath, logger);
}
async function startProxy(binPath, config, logFilePath, logger) {
File diff suppressed because one or more lines are too long
+29 -28
View File
@@ -1,6 +1,6 @@
{
"name": "codeql",
"version": "3.28.14",
"version": "3.28.17",
"lockfileVersion": 3,
"requires": true,
"packages": {
@@ -920,9 +920,9 @@
}
},
"node_modules/@eslint/js": {
"version": "9.23.0",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.23.0.tgz",
"integrity": "sha512-35MJ8vCPU0ZMxo7zfev2pypqTwWTofFZO6m4KAtdoFhRpLJUpHTZZ+KB3C7Hb1d7bULYwO4lJXGCi5Se+8OMbw==",
"version": "9.24.0",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.24.0.tgz",
"integrity": "sha512-uIY/y3z0uvOGX8cp1C2fiC4+ZmBhp6yZWkojtHL1YEMnRt1Y63HB9TM17proGEmeG7HeUY+UP36F0aknKYTpYA==",
"dev": true,
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -1075,9 +1075,9 @@
}
},
"node_modules/@mswjs/interceptors": {
"version": "0.38.0",
"resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.38.0.tgz",
"integrity": "sha512-nPHVM+LUl4V1kXPXuTcNN5OMD//ltCQ0lccuEagvidJdpbig3hP3W6/ctWHx6mee7vZIWE0L+Mqj3vx0ASlm/w==",
"version": "0.38.1",
"resolved": "https://registry.npmjs.org/@mswjs/interceptors/-/interceptors-0.38.1.tgz",
"integrity": "sha512-JWLtvwpj2aCk2UvLlSQ12BFF/wBJJd0NhhYf7cz4k+tMhymmLn8ss3irznjWPvOsASV2raqb5EjTw+NRoeVDag==",
"dev": true,
"dependencies": {
"@open-draft/deferred-promise": "^2.2.0",
@@ -1870,14 +1870,14 @@
"node": ">=4"
}
},
"node_modules/@types/adm-zip": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/@types/adm-zip/-/adm-zip-0.5.7.tgz",
"integrity": "sha512-DNEs/QvmyRLurdQPChqq0Md4zGvPwHerAJYWk9l2jCbD1VPpnzRJorOdiq4zsw09NFbYnhfsoEhWtxIzXpn2yw==",
"node_modules/@types/archiver": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@types/archiver/-/archiver-6.0.3.tgz",
"integrity": "sha512-a6wUll6k3zX6qs5KlxIggs1P1JcYJaTCx2gnlr+f0S1yd2DoaEwoIK10HmBaLnZwWneBz+JBm0dwcZu0zECBcQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
"@types/readdir-glob": "*"
}
},
"node_modules/@types/aws-lambda": {
@@ -1936,6 +1936,16 @@
"@types/node": "*"
}
},
"node_modules/@types/readdir-glob": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@types/readdir-glob/-/readdir-glob-1.1.5.tgz",
"integrity": "sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/semver": {
"version": "7.7.0",
"resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.0.tgz",
@@ -2635,14 +2645,6 @@
"node": ">=0.4.0"
}
},
"node_modules/adm-zip": {
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz",
"integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==",
"engines": {
"node": ">=12.0"
}
},
"node_modules/agent-base": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz",
@@ -6540,12 +6542,12 @@
"license": "MIT"
},
"node_modules/nock": {
"version": "14.0.2",
"resolved": "https://registry.npmjs.org/nock/-/nock-14.0.2.tgz",
"integrity": "sha512-jDUBpCNY7KLyOF2FTiT4mLRxV2kpjo4YrcGtv3IMCIwqFKxOQFrmeXefvuEiWvS3ApPWQHAkakkkVpoOrDNCVg==",
"version": "14.0.3",
"resolved": "https://registry.npmjs.org/nock/-/nock-14.0.3.tgz",
"integrity": "sha512-sJ9RNmCuYBqXDmGZZHgZ1D1441MqFOU4T5aeLGVGEB4OWI/2LM0mZlkfBQzQKdOfJypL+2nPPBugXKjixBn4kQ==",
"dev": true,
"dependencies": {
"@mswjs/interceptors": "^0.38.0",
"@mswjs/interceptors": "^0.38.1",
"json-stringify-safe": "^5.0.1",
"propagate": "^2.0.0"
},
@@ -8334,11 +8336,10 @@
}
},
"node_modules/typescript": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz",
"integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==",
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@eslint/js",
"version": "9.23.0",
"version": "9.24.0",
"description": "ESLint JavaScript language implementation",
"main": "./src/index.js",
"types": "./types/index.d.ts",
@@ -5,8 +5,9 @@ import {
} from "./chunk-H5O73WD2.mjs";
import {
FetchResponse,
IS_PATCHED_MODULE
} from "./chunk-5UK33FSU.mjs";
IS_PATCHED_MODULE,
canParseUrl
} from "./chunk-FK37CTPH.mjs";
import {
hasConfigurableGlobal
} from "./chunk-TX5GBTFY.mjs";
@@ -19,16 +20,6 @@ import {
import { invariant } from "outvariant";
import { DeferredPromise } from "@open-draft/deferred-promise";
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/interceptors/fetch/utils/createNetworkError.ts
function createNetworkError(cause) {
return Object.assign(new TypeError("Failed to fetch"), {
@@ -293,4 +284,4 @@ FetchInterceptor.symbol = Symbol("fetch");
export {
FetchInterceptor
};
//# sourceMappingURL=chunk-PBC2PID2.mjs.map
//# sourceMappingURL=chunk-3NVFHQ5L.mjs.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@ import {
import {
FetchResponse,
IS_PATCHED_MODULE
} from "./chunk-5UK33FSU.mjs";
} from "./chunk-FK37CTPH.mjs";
import {
hasConfigurableGlobal
} from "./chunk-TX5GBTFY.mjs";
@@ -841,4 +841,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
export {
XMLHttpRequestInterceptor
};
//# sourceMappingURL=chunk-DODHRDV6.mjs.map
//# sourceMappingURL=chunk-E2WFHJX6.mjs.map
@@ -1,6 +1,28 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/glossary.ts
var IS_PATCHED_MODULE = Symbol("isPatchedModule");
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/utils/getValueBySymbol.ts
function getValueBySymbol(symbolName, source) {
const ownSymbols = Object.getOwnPropertySymbols(source);
const symbol = ownSymbols.find((symbol2) => {
return symbol2.description === symbolName;
});
if (symbol) {
return Reflect.get(source, symbol);
}
return;
}
// src/utils/fetchUtils.ts
var _FetchResponse = class extends Response {
static isConfigurableStatusCode(status) {
@@ -17,18 +39,20 @@ var _FetchResponse = class extends Response {
return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
}
static setUrl(url, response) {
if (!url) {
if (!url || url === "about:" || !canParseUrl(url)) {
return;
}
if (response.url != "") {
return;
const state = getValueBySymbol("state", response);
if (state) {
state.urlList.push(new URL(url));
} else {
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
/**
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -50,12 +74,9 @@ var _FetchResponse = class extends Response {
status: safeStatus
});
if (status !== safeStatus) {
const stateSymbol = Object.getOwnPropertySymbols(this).find(
(symbol) => symbol.description === "state"
);
if (stateSymbol) {
const state = Reflect.get(this, stateSymbol);
Reflect.set(state, "status", status);
const state = getValueBySymbol("state", this);
if (state) {
state.status = status;
} else {
Object.defineProperty(this, "status", {
value: status,
@@ -79,5 +100,6 @@ FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE; exports.FetchResponse = FetchResponse;
//# sourceMappingURL=chunk-BC2BLJQN.js.map
exports.IS_PATCHED_MODULE = IS_PATCHED_MODULE; exports.canParseUrl = canParseUrl; exports.FetchResponse = FetchResponse;
//# sourceMappingURL=chunk-F7RG3QQH.js.map
File diff suppressed because one or more lines are too long
@@ -1,6 +1,28 @@
// src/glossary.ts
var IS_PATCHED_MODULE = Symbol("isPatchedModule");
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/utils/getValueBySymbol.ts
function getValueBySymbol(symbolName, source) {
const ownSymbols = Object.getOwnPropertySymbols(source);
const symbol = ownSymbols.find((symbol2) => {
return symbol2.description === symbolName;
});
if (symbol) {
return Reflect.get(source, symbol);
}
return;
}
// src/utils/fetchUtils.ts
var _FetchResponse = class extends Response {
static isConfigurableStatusCode(status) {
@@ -17,18 +39,20 @@ var _FetchResponse = class extends Response {
return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
}
static setUrl(url, response) {
if (!url) {
if (!url || url === "about:" || !canParseUrl(url)) {
return;
}
if (response.url != "") {
return;
const state = getValueBySymbol("state", response);
if (state) {
state.urlList.push(new URL(url));
} else {
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
/**
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -50,12 +74,9 @@ var _FetchResponse = class extends Response {
status: safeStatus
});
if (status !== safeStatus) {
const stateSymbol = Object.getOwnPropertySymbols(this).find(
(symbol) => symbol.description === "state"
);
if (stateSymbol) {
const state = Reflect.get(this, stateSymbol);
Reflect.set(state, "status", status);
const state = getValueBySymbol("state", this);
if (state) {
state.status = status;
} else {
Object.defineProperty(this, "status", {
value: status,
@@ -78,6 +99,7 @@ FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
export {
IS_PATCHED_MODULE,
canParseUrl,
FetchResponse
};
//# sourceMappingURL=chunk-5UK33FSU.mjs.map
//# sourceMappingURL=chunk-FK37CTPH.mjs.map
File diff suppressed because one or more lines are too long
@@ -6,7 +6,8 @@ var _chunkFGSEOIC4js = require('./chunk-FGSEOIC4.js');
var _chunkBC2BLJQNjs = require('./chunk-BC2BLJQN.js');
var _chunkF7RG3QQHjs = require('./chunk-F7RG3QQH.js');
var _chunkPFGO5BSMjs = require('./chunk-PFGO5BSM.js');
@@ -19,16 +20,6 @@ var _chunkTIPR373Rjs = require('./chunk-TIPR373R.js');
var _outvariant = require('outvariant');
var _deferredpromise = require('@open-draft/deferred-promise');
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/interceptors/fetch/utils/createNetworkError.ts
function createNetworkError(cause) {
return Object.assign(new TypeError("Failed to fetch"), {
@@ -180,12 +171,12 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
async setup() {
const pureFetch = globalThis.fetch;
_outvariant.invariant.call(void 0,
!pureFetch[_chunkBC2BLJQNjs.IS_PATCHED_MODULE],
!pureFetch[_chunkF7RG3QQHjs.IS_PATCHED_MODULE],
'Failed to patch the "fetch" module: already patched.'
);
globalThis.fetch = async (input, init) => {
const requestId = _chunkTIPR373Rjs.createRequestId.call(void 0, );
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input;
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !_chunkF7RG3QQHjs.canParseUrl.call(void 0, input) ? new URL(input, location.origin) : input;
const request = new Request(resolvedInput, init);
const responsePromise = new (0, _deferredpromise.DeferredPromise)();
const controller = new (0, _chunkFGSEOIC4js.RequestController)(request);
@@ -205,9 +196,9 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
rawResponse
});
const decompressedStream = decompressResponse(rawResponse);
const response = decompressedStream === null ? rawResponse : new (0, _chunkBC2BLJQNjs.FetchResponse)(decompressedStream, rawResponse);
_chunkBC2BLJQNjs.FetchResponse.setUrl(request.url, response);
if (_chunkBC2BLJQNjs.FetchResponse.isRedirectResponse(response.status)) {
const response = decompressedStream === null ? rawResponse : new (0, _chunkF7RG3QQHjs.FetchResponse)(decompressedStream, rawResponse);
_chunkF7RG3QQHjs.FetchResponse.setUrl(request.url, response);
if (_chunkF7RG3QQHjs.FetchResponse.isRedirectResponse(response.status)) {
if (request.redirect === "error") {
responsePromise.reject(createNetworkError("unexpected redirect"));
return;
@@ -270,13 +261,13 @@ var _FetchInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
return response;
});
};
Object.defineProperty(globalThis.fetch, _chunkBC2BLJQNjs.IS_PATCHED_MODULE, {
Object.defineProperty(globalThis.fetch, _chunkF7RG3QQHjs.IS_PATCHED_MODULE, {
enumerable: true,
configurable: true,
value: true
});
this.subscriptions.push(() => {
Object.defineProperty(globalThis.fetch, _chunkBC2BLJQNjs.IS_PATCHED_MODULE, {
Object.defineProperty(globalThis.fetch, _chunkF7RG3QQHjs.IS_PATCHED_MODULE, {
value: void 0
});
globalThis.fetch = pureFetch;
@@ -293,4 +284,4 @@ FetchInterceptor.symbol = Symbol("fetch");
exports.FetchInterceptor = FetchInterceptor;
//# sourceMappingURL=chunk-P3AXGLYB.js.map
//# sourceMappingURL=chunk-H4LFCCBA.js.map
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@ var _chunkFGSEOIC4js = require('./chunk-FGSEOIC4.js');
var _chunkBC2BLJQNjs = require('./chunk-BC2BLJQN.js');
var _chunkF7RG3QQHjs = require('./chunk-F7RG3QQH.js');
var _chunkPFGO5BSMjs = require('./chunk-PFGO5BSM.js');
@@ -206,8 +206,8 @@ function parseJson(data) {
// src/interceptors/XMLHttpRequest/utils/createResponse.ts
function createResponse(request, body) {
const responseBodyOrNull = _chunkBC2BLJQNjs.FetchResponse.isResponseWithBody(request.status) ? body : null;
return new (0, _chunkBC2BLJQNjs.FetchResponse)(responseBodyOrNull, {
const responseBodyOrNull = _chunkF7RG3QQHjs.FetchResponse.isResponseWithBody(request.status) ? body : null;
return new (0, _chunkF7RG3QQHjs.FetchResponse)(responseBodyOrNull, {
url: request.responseURL,
status: request.status,
statusText: request.statusText,
@@ -807,7 +807,7 @@ var _XMLHttpRequestInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
logger.info('patching "XMLHttpRequest" module...');
const PureXMLHttpRequest = globalThis.XMLHttpRequest;
_outvariant.invariant.call(void 0,
!PureXMLHttpRequest[_chunkBC2BLJQNjs.IS_PATCHED_MODULE],
!PureXMLHttpRequest[_chunkF7RG3QQHjs.IS_PATCHED_MODULE],
'Failed to patch the "XMLHttpRequest" module: already patched.'
);
globalThis.XMLHttpRequest = createXMLHttpRequestProxy({
@@ -818,13 +818,13 @@ var _XMLHttpRequestInterceptor = class extends _chunkTIPR373Rjs.Interceptor {
'native "XMLHttpRequest" module patched!',
globalThis.XMLHttpRequest.name
);
Object.defineProperty(globalThis.XMLHttpRequest, _chunkBC2BLJQNjs.IS_PATCHED_MODULE, {
Object.defineProperty(globalThis.XMLHttpRequest, _chunkF7RG3QQHjs.IS_PATCHED_MODULE, {
enumerable: true,
configurable: true,
value: true
});
this.subscriptions.push(() => {
Object.defineProperty(globalThis.XMLHttpRequest, _chunkBC2BLJQNjs.IS_PATCHED_MODULE, {
Object.defineProperty(globalThis.XMLHttpRequest, _chunkF7RG3QQHjs.IS_PATCHED_MODULE, {
value: void 0
});
globalThis.XMLHttpRequest = PureXMLHttpRequest;
@@ -841,4 +841,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor;
//# sourceMappingURL=chunk-ZIT2QX7D.js.map
//# sourceMappingURL=chunk-J2HDR5D7.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -5,7 +5,7 @@ var _chunkLK6DILFKjs = require('./chunk-LK6DILFK.js');
var _chunkBC2BLJQNjs = require('./chunk-BC2BLJQN.js');
var _chunkF7RG3QQHjs = require('./chunk-F7RG3QQH.js');
@@ -75,5 +75,5 @@ function getCleanUrl(url, isAbsolute = true) {
exports.BatchInterceptor = BatchInterceptor; exports.FetchResponse = _chunkBC2BLJQNjs.FetchResponse; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkTIPR373Rjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunkBC2BLJQNjs.IS_PATCHED_MODULE; exports.Interceptor = _chunkTIPR373Rjs.Interceptor; exports.InterceptorReadyState = _chunkTIPR373Rjs.InterceptorReadyState; exports.createRequestId = _chunkTIPR373Rjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkTIPR373Rjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkTIPR373Rjs.getGlobalSymbol;
exports.BatchInterceptor = BatchInterceptor; exports.FetchResponse = _chunkF7RG3QQHjs.FetchResponse; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkTIPR373Rjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunkF7RG3QQHjs.IS_PATCHED_MODULE; exports.Interceptor = _chunkTIPR373Rjs.Interceptor; exports.InterceptorReadyState = _chunkTIPR373Rjs.InterceptorReadyState; exports.createRequestId = _chunkTIPR373Rjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkTIPR373Rjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkTIPR373Rjs.getGlobalSymbol;
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -5,7 +5,7 @@ import {
import {
FetchResponse,
IS_PATCHED_MODULE
} from "./chunk-5UK33FSU.mjs";
} from "./chunk-FK37CTPH.mjs";
import {
INTERNAL_REQUEST_ID_HEADER_NAME,
Interceptor,
@@ -1,12 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZIT2QX7Djs = require('../../chunk-ZIT2QX7D.js');
var _chunkJ2HDR5D7js = require('../../chunk-J2HDR5D7.js');
require('../../chunk-LK6DILFK.js');
require('../../chunk-FGSEOIC4.js');
require('../../chunk-BC2BLJQN.js');
require('../../chunk-F7RG3QQH.js');
require('../../chunk-PFGO5BSM.js');
require('../../chunk-TIPR373R.js');
exports.XMLHttpRequestInterceptor = _chunkZIT2QX7Djs.XMLHttpRequestInterceptor;
exports.XMLHttpRequestInterceptor = _chunkJ2HDR5D7js.XMLHttpRequestInterceptor;
//# sourceMappingURL=index.js.map
@@ -1,9 +1,9 @@
import {
XMLHttpRequestInterceptor
} from "../../chunk-DODHRDV6.mjs";
} from "../../chunk-E2WFHJX6.mjs";
import "../../chunk-6HYIRFX2.mjs";
import "../../chunk-H5O73WD2.mjs";
import "../../chunk-5UK33FSU.mjs";
import "../../chunk-FK37CTPH.mjs";
import "../../chunk-TX5GBTFY.mjs";
import "../../chunk-QED3Q6Z2.mjs";
export {
+3 -3
View File
@@ -1,11 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkP3AXGLYBjs = require('../../chunk-P3AXGLYB.js');
var _chunkH4LFCCBAjs = require('../../chunk-H4LFCCBA.js');
require('../../chunk-FGSEOIC4.js');
require('../../chunk-BC2BLJQN.js');
require('../../chunk-F7RG3QQH.js');
require('../../chunk-PFGO5BSM.js');
require('../../chunk-TIPR373R.js');
exports.FetchInterceptor = _chunkP3AXGLYBjs.FetchInterceptor;
exports.FetchInterceptor = _chunkH4LFCCBAjs.FetchInterceptor;
//# sourceMappingURL=index.js.map
+2 -2
View File
@@ -1,8 +1,8 @@
import {
FetchInterceptor
} from "../../chunk-PBC2PID2.mjs";
} from "../../chunk-3NVFHQ5L.mjs";
import "../../chunk-H5O73WD2.mjs";
import "../../chunk-5UK33FSU.mjs";
import "../../chunk-FK37CTPH.mjs";
import "../../chunk-TX5GBTFY.mjs";
import "../../chunk-QED3Q6Z2.mjs";
export {
+5 -5
View File
@@ -1,19 +1,19 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZIT2QX7Djs = require('../chunk-ZIT2QX7D.js');
var _chunkJ2HDR5D7js = require('../chunk-J2HDR5D7.js');
require('../chunk-LK6DILFK.js');
var _chunkP3AXGLYBjs = require('../chunk-P3AXGLYB.js');
var _chunkH4LFCCBAjs = require('../chunk-H4LFCCBA.js');
require('../chunk-FGSEOIC4.js');
require('../chunk-BC2BLJQN.js');
require('../chunk-F7RG3QQH.js');
require('../chunk-PFGO5BSM.js');
require('../chunk-TIPR373R.js');
// src/presets/browser.ts
var browser_default = [
new (0, _chunkP3AXGLYBjs.FetchInterceptor)(),
new (0, _chunkZIT2QX7Djs.XMLHttpRequestInterceptor)()
new (0, _chunkH4LFCCBAjs.FetchInterceptor)(),
new (0, _chunkJ2HDR5D7js.XMLHttpRequestInterceptor)()
];
+3 -3
View File
@@ -1,12 +1,12 @@
import {
XMLHttpRequestInterceptor
} from "../chunk-DODHRDV6.mjs";
} from "../chunk-E2WFHJX6.mjs";
import "../chunk-6HYIRFX2.mjs";
import {
FetchInterceptor
} from "../chunk-PBC2PID2.mjs";
} from "../chunk-3NVFHQ5L.mjs";
import "../chunk-H5O73WD2.mjs";
import "../chunk-5UK33FSU.mjs";
import "../chunk-FK37CTPH.mjs";
import "../chunk-TX5GBTFY.mjs";
import "../chunk-QED3Q6Z2.mjs";
+11 -11
View File
@@ -1,16 +1,16 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkYBN5MFAPjs = require('./chunk-YBN5MFAP.js');
var _chunkMCB574K6js = require('./chunk-MCB574K6.js');
var _chunk3HCE66HZjs = require('./chunk-3HCE66HZ.js');
var _chunkGO7ZOUKBjs = require('./chunk-GO7ZOUKB.js');
var _chunkLCA4FKWYjs = require('./chunk-LCA4FKWY.js');
var _chunk2R5JZR3Ljs = require('./chunk-2R5JZR3L.js');
require('./chunk-LK6DILFK.js');
var _chunkCF5C3K5Ujs = require('./chunk-CF5C3K5U.js');
var _chunkDPVSIR6Jjs = require('./chunk-DPVSIR6J.js');
require('./chunk-PFGO5BSM.js');
require('./chunk-73NOP3T5.js');
@@ -20,17 +20,17 @@ var _chunk6L3PFBGTjs = require('./chunk-6L3PFBGT.js');
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/RemoteHttpInterceptor.ts
var RemoteHttpInterceptor = class extends _chunkYBN5MFAPjs.BatchInterceptor {
var RemoteHttpInterceptor = class extends _chunkMCB574K6js.BatchInterceptor {
constructor() {
super({
name: "remote-interceptor",
interceptors: [
new (0, _chunk3HCE66HZjs.ClientRequestInterceptor)(),
new (0, _chunkLCA4FKWYjs.XMLHttpRequestInterceptor)(),
new (0, _chunkCF5C3K5Ujs.FetchInterceptor)()
new (0, _chunkGO7ZOUKBjs.ClientRequestInterceptor)(),
new (0, _chunk2R5JZR3Ljs.XMLHttpRequestInterceptor)(),
new (0, _chunkDPVSIR6Jjs.FetchInterceptor)()
]
});
}
@@ -65,7 +65,7 @@ var RemoteHttpInterceptor = class extends _chunkYBN5MFAPjs.BatchInterceptor {
const responseInit = JSON.parse(
serializedResponse
);
const mockedResponse = new (0, _chunkWZTE4PCOjs.FetchResponse)(responseInit.body, {
const mockedResponse = new (0, _chunkDLID3GDGjs.FetchResponse)(responseInit.body, {
url: request.url,
status: responseInit.status,
statusText: responseInit.statusText,
@@ -98,7 +98,7 @@ function requestReviver(key, value) {
return value;
}
}
var _RemoteHttpResolver = class extends _chunkWZTE4PCOjs.Interceptor {
var _RemoteHttpResolver = class extends _chunkDLID3GDGjs.Interceptor {
constructor(options) {
super(_RemoteHttpResolver.symbol);
this.process = options.process;
+5 -5
View File
@@ -1,16 +1,16 @@
import {
BatchInterceptor
} from "./chunk-PJA4E426.mjs";
} from "./chunk-TBU3WLO3.mjs";
import {
ClientRequestInterceptor
} from "./chunk-FWJSC2QD.mjs";
} from "./chunk-JDAAQ7RU.mjs";
import {
XMLHttpRequestInterceptor
} from "./chunk-OMWE7UVM.mjs";
} from "./chunk-RXMZLFWG.mjs";
import "./chunk-6HYIRFX2.mjs";
import {
FetchInterceptor
} from "./chunk-ZSYLU3GR.mjs";
} from "./chunk-NIASNH2Q.mjs";
import "./chunk-TX5GBTFY.mjs";
import "./chunk-6YM4PLBI.mjs";
import {
@@ -20,7 +20,7 @@ import {
import {
FetchResponse,
Interceptor
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/RemoteHttpInterceptor.ts
var RemoteHttpInterceptor = class extends BatchInterceptor {
@@ -18,7 +18,7 @@ var _chunk6L3PFBGTjs = require('./chunk-6L3PFBGT.js');
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/interceptors/XMLHttpRequest/index.ts
var _outvariant = require('outvariant');
@@ -206,8 +206,8 @@ function parseJson(data) {
// src/interceptors/XMLHttpRequest/utils/createResponse.ts
function createResponse(request, body) {
const responseBodyOrNull = _chunkWZTE4PCOjs.FetchResponse.isResponseWithBody(request.status) ? body : null;
return new (0, _chunkWZTE4PCOjs.FetchResponse)(responseBodyOrNull, {
const responseBodyOrNull = _chunkDLID3GDGjs.FetchResponse.isResponseWithBody(request.status) ? body : null;
return new (0, _chunkDLID3GDGjs.FetchResponse)(responseBodyOrNull, {
url: request.responseURL,
status: request.status,
statusText: request.statusText,
@@ -253,7 +253,7 @@ var XMLHttpRequestController = class {
this[kIsRequestHandled] = false;
this.events = /* @__PURE__ */ new Map();
this.uploadEvents = /* @__PURE__ */ new Map();
this.requestId = _chunkWZTE4PCOjs.createRequestId.call(void 0, );
this.requestId = _chunkDLID3GDGjs.createRequestId.call(void 0, );
this.requestHeaders = new Headers();
this.responseBuffer = new Uint8Array();
this.request = createProxy(initialRequest, {
@@ -335,7 +335,7 @@ var XMLHttpRequestController = class {
);
if (IS_NODE) {
this.request.setRequestHeader(
_chunkWZTE4PCOjs.INTERNAL_REQUEST_ID_HEADER_NAME,
_chunkDLID3GDGjs.INTERNAL_REQUEST_ID_HEADER_NAME,
this.requestId
);
}
@@ -795,7 +795,7 @@ function createXMLHttpRequestProxy({
}
// src/interceptors/XMLHttpRequest/index.ts
var _XMLHttpRequestInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
var _XMLHttpRequestInterceptor = class extends _chunkDLID3GDGjs.Interceptor {
constructor() {
super(_XMLHttpRequestInterceptor.interceptorSymbol);
}
@@ -841,4 +841,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
exports.XMLHttpRequestInterceptor = XMLHttpRequestInterceptor;
//# sourceMappingURL=chunk-LCA4FKWY.js.map
//# sourceMappingURL=chunk-2R5JZR3L.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -158,6 +158,28 @@ function createRequestId() {
return Math.random().toString(16).slice(2);
}
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/utils/getValueBySymbol.ts
function getValueBySymbol(symbolName, source) {
const ownSymbols = Object.getOwnPropertySymbols(source);
const symbol = ownSymbols.find((symbol2) => {
return symbol2.description === symbolName;
});
if (symbol) {
return Reflect.get(source, symbol);
}
return;
}
// src/utils/fetchUtils.ts
var _FetchResponse = class extends Response {
static isConfigurableStatusCode(status) {
@@ -174,18 +196,20 @@ var _FetchResponse = class extends Response {
return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
}
static setUrl(url, response) {
if (!url) {
if (!url || url === "about:" || !canParseUrl(url)) {
return;
}
if (response.url != "") {
return;
const state = getValueBySymbol("state", response);
if (state) {
state.urlList.push(new URL(url));
} else {
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
/**
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -207,12 +231,9 @@ var _FetchResponse = class extends Response {
status: safeStatus
});
if (status !== safeStatus) {
const stateSymbol = Object.getOwnPropertySymbols(this).find(
(symbol) => symbol.description === "state"
);
if (stateSymbol) {
const state = Reflect.get(this, stateSymbol);
Reflect.set(state, "status", status);
const state = getValueBySymbol("state", this);
if (state) {
state.status = status;
} else {
Object.defineProperty(this, "status", {
value: status,
@@ -241,5 +262,6 @@ FetchResponse.STATUS_CODES_WITH_REDIRECT = [301, 302, 303, 307, 308];
exports.INTERNAL_REQUEST_ID_HEADER_NAME = INTERNAL_REQUEST_ID_HEADER_NAME; exports.getGlobalSymbol = getGlobalSymbol; exports.deleteGlobalSymbol = deleteGlobalSymbol; exports.InterceptorReadyState = InterceptorReadyState; exports.Interceptor = Interceptor; exports.createRequestId = createRequestId; exports.FetchResponse = FetchResponse;
//# sourceMappingURL=chunk-WZTE4PCO.js.map
exports.INTERNAL_REQUEST_ID_HEADER_NAME = INTERNAL_REQUEST_ID_HEADER_NAME; exports.getGlobalSymbol = getGlobalSymbol; exports.deleteGlobalSymbol = deleteGlobalSymbol; exports.InterceptorReadyState = InterceptorReadyState; exports.Interceptor = Interceptor; exports.createRequestId = createRequestId; exports.canParseUrl = canParseUrl; exports.FetchResponse = FetchResponse;
//# sourceMappingURL=chunk-DLID3GDG.js.map
File diff suppressed because one or more lines are too long
@@ -13,22 +13,13 @@ var _chunk6L3PFBGTjs = require('./chunk-6L3PFBGT.js');
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/interceptors/fetch/index.ts
var _outvariant = require('outvariant');
var _deferredpromise = require('@open-draft/deferred-promise');
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/interceptors/fetch/utils/createNetworkError.ts
function createNetworkError(cause) {
return Object.assign(new TypeError("Failed to fetch"), {
@@ -185,7 +176,7 @@ function decompressResponse(response) {
}
// src/interceptors/fetch/index.ts
var _FetchInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
var _FetchInterceptor = class extends _chunkDLID3GDGjs.Interceptor {
constructor() {
super(_FetchInterceptor.symbol);
}
@@ -199,8 +190,8 @@ var _FetchInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
'Failed to patch the "fetch" module: already patched.'
);
globalThis.fetch = async (input, init) => {
const requestId = _chunkWZTE4PCOjs.createRequestId.call(void 0, );
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !canParseUrl(input) ? new URL(input, location.origin) : input;
const requestId = _chunkDLID3GDGjs.createRequestId.call(void 0, );
const resolvedInput = typeof input === "string" && typeof location !== "undefined" && !_chunkDLID3GDGjs.canParseUrl.call(void 0, input) ? new URL(input, location.origin) : input;
const request = new Request(resolvedInput, init);
const responsePromise = new (0, _deferredpromise.DeferredPromise)();
const controller = new (0, _chunk6L3PFBGTjs.RequestController)(request);
@@ -220,9 +211,9 @@ var _FetchInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
rawResponse
});
const decompressedStream = decompressResponse(rawResponse);
const response = decompressedStream === null ? rawResponse : new (0, _chunkWZTE4PCOjs.FetchResponse)(decompressedStream, rawResponse);
_chunkWZTE4PCOjs.FetchResponse.setUrl(request.url, response);
if (_chunkWZTE4PCOjs.FetchResponse.isRedirectResponse(response.status)) {
const response = decompressedStream === null ? rawResponse : new (0, _chunkDLID3GDGjs.FetchResponse)(decompressedStream, rawResponse);
_chunkDLID3GDGjs.FetchResponse.setUrl(request.url, response);
if (_chunkDLID3GDGjs.FetchResponse.isRedirectResponse(response.status)) {
if (request.redirect === "error") {
responsePromise.reject(createNetworkError("unexpected redirect"));
return;
@@ -308,4 +299,4 @@ FetchInterceptor.symbol = Symbol("fetch");
exports.FetchInterceptor = FetchInterceptor;
//# sourceMappingURL=chunk-CF5C3K5U.js.map
//# sourceMappingURL=chunk-DPVSIR6J.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@ var _chunk6L3PFBGTjs = require('./chunk-6L3PFBGT.js');
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/interceptors/ClientRequest/index.ts
var _http = require('http'); var _http2 = _interopRequireDefault(_http);
@@ -304,7 +304,7 @@ var MockHttpSocket = class extends MockSocket {
this.shouldKeepAlive = shouldKeepAlive;
const url = new URL(path, this.baseUrl);
const method = ((_a = this.connectionOptions.method) == null ? void 0 : _a.toUpperCase()) || "GET";
const headers = _chunkWZTE4PCOjs.FetchResponse.parseRawHeaders(rawHeaders);
const headers = _chunkDLID3GDGjs.FetchResponse.parseRawHeaders(rawHeaders);
const canHaveBody = method !== "GET" && method !== "HEAD";
if (url.username || url.password) {
if (!headers.has("authorization")) {
@@ -325,7 +325,7 @@ var MockHttpSocket = class extends MockSocket {
}
});
}
const requestId = _chunkWZTE4PCOjs.createRequestId.call(void 0, );
const requestId = _chunkDLID3GDGjs.createRequestId.call(void 0, );
this.request = new Request(url, {
method,
headers,
@@ -335,7 +335,7 @@ var MockHttpSocket = class extends MockSocket {
body: canHaveBody ? _stream.Readable.toWeb(this.requestStream) : null
});
Reflect.set(this.request, kRequestId, requestId);
if (this.request.headers.has(_chunkWZTE4PCOjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
if (this.request.headers.has(_chunkDLID3GDGjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
this.passthrough();
return;
}
@@ -346,8 +346,8 @@ var MockHttpSocket = class extends MockSocket {
});
};
this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => {
const headers = _chunkWZTE4PCOjs.FetchResponse.parseRawHeaders(rawHeaders);
const response = new (0, _chunkWZTE4PCOjs.FetchResponse)(
const headers = _chunkDLID3GDGjs.FetchResponse.parseRawHeaders(rawHeaders);
const response = new (0, _chunkDLID3GDGjs.FetchResponse)(
/**
* @note The Fetch API response instance exposed to the consumer
* is created over the response stream of the HTTP parser. It is NOT
@@ -355,7 +355,7 @@ var MockHttpSocket = class extends MockSocket {
* in response listener while the Socket instance delays the emission
* of "end" and other events until those response listeners are finished.
*/
_chunkWZTE4PCOjs.FetchResponse.isResponseWithBody(status) ? _stream.Readable.toWeb(
_chunkDLID3GDGjs.FetchResponse.isResponseWithBody(status) ? _stream.Readable.toWeb(
this.responseStream = new (0, _stream.Readable)({ read() {
} })
) : null,
@@ -370,7 +370,8 @@ var MockHttpSocket = class extends MockSocket {
this.request,
"Failed to handle a response: request does not exist"
);
if (this.request.headers.has(_chunkWZTE4PCOjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
_chunkDLID3GDGjs.FetchResponse.setUrl(this.request.url, response);
if (this.request.headers.has(_chunkDLID3GDGjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
return;
}
this.responseListenersPromise = this.onResponse({
@@ -451,7 +452,7 @@ var MockHttpSocket = class extends MockSocket {
);
const rawRequestHeaders = getRawFetchHeaders(this.request.headers);
const requestHeadersString = rawRequestHeaders.filter(([name]) => {
return name.toLowerCase() !== _chunkWZTE4PCOjs.INTERNAL_REQUEST_ID_HEADER_NAME;
return name.toLowerCase() !== _chunkDLID3GDGjs.INTERNAL_REQUEST_ID_HEADER_NAME;
}).map(([name, value]) => `${name}: ${value}`).join("\r\n");
const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}`;
socket.write(headersChunk, encoding, callback);
@@ -936,7 +937,7 @@ function normalizeClientRequestArgs(defaultProtocol, args) {
}
// src/interceptors/ClientRequest/index.ts
var _ClientRequestInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
var _ClientRequestInterceptor = class extends _chunkDLID3GDGjs.Interceptor {
constructor() {
super(_ClientRequestInterceptor.symbol);
this.onRequest = async ({
@@ -1061,4 +1062,4 @@ ClientRequestInterceptor.symbol = Symbol("client-request-interceptor");
exports.ClientRequestInterceptor = ClientRequestInterceptor;
//# sourceMappingURL=chunk-3HCE66HZ.js.map
//# sourceMappingURL=chunk-GO7ZOUKB.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -10,7 +10,7 @@ import {
INTERNAL_REQUEST_ID_HEADER_NAME,
Interceptor,
createRequestId
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/interceptors/ClientRequest/index.ts
import http2 from "http";
@@ -370,6 +370,7 @@ var MockHttpSocket = class extends MockSocket {
this.request,
"Failed to handle a response: request does not exist"
);
FetchResponse.setUrl(this.request.url, response);
if (this.request.headers.has(INTERNAL_REQUEST_ID_HEADER_NAME)) {
return;
}
@@ -1061,4 +1062,4 @@ ClientRequestInterceptor.symbol = Symbol("client-request-interceptor");
export {
ClientRequestInterceptor
};
//# sourceMappingURL=chunk-FWJSC2QD.mjs.map
//# sourceMappingURL=chunk-JDAAQ7RU.mjs.map
File diff suppressed because one or more lines are too long
@@ -1,9 +1,9 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/BatchInterceptor.ts
var BatchInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
var BatchInterceptor = class extends _chunkDLID3GDGjs.Interceptor {
constructor(options) {
BatchInterceptor.symbol = Symbol(options.name);
super(BatchInterceptor.symbol);
@@ -48,4 +48,4 @@ var BatchInterceptor = class extends _chunkWZTE4PCOjs.Interceptor {
exports.BatchInterceptor = BatchInterceptor;
//# sourceMappingURL=chunk-YBN5MFAP.js.map
//# sourceMappingURL=chunk-MCB574K6.js.map
@@ -12,23 +12,14 @@ import {
import {
FetchResponse,
Interceptor,
canParseUrl,
createRequestId
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/interceptors/fetch/index.ts
import { invariant } from "outvariant";
import { DeferredPromise } from "@open-draft/deferred-promise";
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/interceptors/fetch/utils/createNetworkError.ts
function createNetworkError(cause) {
return Object.assign(new TypeError("Failed to fetch"), {
@@ -308,4 +299,4 @@ FetchInterceptor.symbol = Symbol("fetch");
export {
FetchInterceptor
};
//# sourceMappingURL=chunk-ZSYLU3GR.mjs.map
//# sourceMappingURL=chunk-NIASNH2Q.mjs.map
File diff suppressed because one or more lines are too long
@@ -18,7 +18,7 @@ import {
INTERNAL_REQUEST_ID_HEADER_NAME,
Interceptor,
createRequestId
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/interceptors/XMLHttpRequest/index.ts
import { invariant as invariant2 } from "outvariant";
@@ -841,4 +841,4 @@ XMLHttpRequestInterceptor.interceptorSymbol = Symbol("xhr");
export {
XMLHttpRequestInterceptor
};
//# sourceMappingURL=chunk-OMWE7UVM.mjs.map
//# sourceMappingURL=chunk-RXMZLFWG.mjs.map
@@ -1,6 +1,6 @@
import {
Interceptor
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/BatchInterceptor.ts
var BatchInterceptor = class extends Interceptor {
@@ -48,4 +48,4 @@ var BatchInterceptor = class extends Interceptor {
export {
BatchInterceptor
};
//# sourceMappingURL=chunk-PJA4E426.mjs.map
//# sourceMappingURL=chunk-TBU3WLO3.mjs.map
File diff suppressed because one or more lines are too long
@@ -158,6 +158,28 @@ function createRequestId() {
return Math.random().toString(16).slice(2);
}
// src/utils/canParseUrl.ts
function canParseUrl(url) {
try {
new URL(url);
return true;
} catch (_error) {
return false;
}
}
// src/utils/getValueBySymbol.ts
function getValueBySymbol(symbolName, source) {
const ownSymbols = Object.getOwnPropertySymbols(source);
const symbol = ownSymbols.find((symbol2) => {
return symbol2.description === symbolName;
});
if (symbol) {
return Reflect.get(source, symbol);
}
return;
}
// src/utils/fetchUtils.ts
var _FetchResponse = class extends Response {
static isConfigurableStatusCode(status) {
@@ -174,18 +196,20 @@ var _FetchResponse = class extends Response {
return !_FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status);
}
static setUrl(url, response) {
if (!url) {
if (!url || url === "about:" || !canParseUrl(url)) {
return;
}
if (response.url != "") {
return;
const state = getValueBySymbol("state", response);
if (state) {
state.urlList.push(new URL(url));
} else {
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
Object.defineProperty(response, "url", {
value: url,
enumerable: true,
configurable: true,
writable: false
});
}
/**
* Parses the given raw HTTP headers into a Fetch API `Headers` instance.
@@ -207,12 +231,9 @@ var _FetchResponse = class extends Response {
status: safeStatus
});
if (status !== safeStatus) {
const stateSymbol = Object.getOwnPropertySymbols(this).find(
(symbol) => symbol.description === "state"
);
if (stateSymbol) {
const state = Reflect.get(this, stateSymbol);
Reflect.set(state, "status", status);
const state = getValueBySymbol("state", this);
if (state) {
state.status = status;
} else {
Object.defineProperty(this, "status", {
value: status,
@@ -240,6 +261,7 @@ export {
InterceptorReadyState,
Interceptor,
createRequestId,
canParseUrl,
FetchResponse
};
//# sourceMappingURL=chunk-I7HQIBT7.mjs.map
//# sourceMappingURL=chunk-YM42IU6M.mjs.map
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -1,6 +1,6 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkYBN5MFAPjs = require('./chunk-YBN5MFAP.js');
var _chunkMCB574K6js = require('./chunk-MCB574K6.js');
@@ -16,7 +16,7 @@ var _chunk73NOP3T5js = require('./chunk-73NOP3T5.js');
var _chunkWZTE4PCOjs = require('./chunk-WZTE4PCO.js');
var _chunkDLID3GDGjs = require('./chunk-DLID3GDG.js');
// src/utils/getCleanUrl.ts
function getCleanUrl(url, isAbsolute = true) {
@@ -35,5 +35,5 @@ function getCleanUrl(url, isAbsolute = true) {
exports.BatchInterceptor = _chunkYBN5MFAPjs.BatchInterceptor; exports.FetchResponse = _chunkWZTE4PCOjs.FetchResponse; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkWZTE4PCOjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunk73NOP3T5js.IS_PATCHED_MODULE; exports.Interceptor = _chunkWZTE4PCOjs.Interceptor; exports.InterceptorReadyState = _chunkWZTE4PCOjs.InterceptorReadyState; exports.createRequestId = _chunkWZTE4PCOjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkWZTE4PCOjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkWZTE4PCOjs.getGlobalSymbol;
exports.BatchInterceptor = _chunkMCB574K6js.BatchInterceptor; exports.FetchResponse = _chunkDLID3GDGjs.FetchResponse; exports.INTERNAL_REQUEST_ID_HEADER_NAME = _chunkDLID3GDGjs.INTERNAL_REQUEST_ID_HEADER_NAME; exports.IS_PATCHED_MODULE = _chunk73NOP3T5js.IS_PATCHED_MODULE; exports.Interceptor = _chunkDLID3GDGjs.Interceptor; exports.InterceptorReadyState = _chunkDLID3GDGjs.InterceptorReadyState; exports.createRequestId = _chunkDLID3GDGjs.createRequestId; exports.decodeBuffer = _chunkLK6DILFKjs.decodeBuffer; exports.deleteGlobalSymbol = _chunkDLID3GDGjs.deleteGlobalSymbol; exports.encodeBuffer = _chunkLK6DILFKjs.encodeBuffer; exports.getCleanUrl = getCleanUrl; exports.getGlobalSymbol = _chunkDLID3GDGjs.getGlobalSymbol;
//# sourceMappingURL=index.js.map
+2 -2
View File
@@ -1,6 +1,6 @@
import {
BatchInterceptor
} from "./chunk-PJA4E426.mjs";
} from "./chunk-TBU3WLO3.mjs";
import {
decodeBuffer,
encodeBuffer
@@ -16,7 +16,7 @@ import {
createRequestId,
deleteGlobalSymbol,
getGlobalSymbol
} from "./chunk-I7HQIBT7.mjs";
} from "./chunk-YM42IU6M.mjs";
// src/utils/getCleanUrl.ts
function getCleanUrl(url, isAbsolute = true) {
@@ -1,9 +1,9 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk3HCE66HZjs = require('../../chunk-3HCE66HZ.js');
var _chunkGO7ZOUKBjs = require('../../chunk-GO7ZOUKB.js');
require('../../chunk-6L3PFBGT.js');
require('../../chunk-WZTE4PCO.js');
require('../../chunk-DLID3GDG.js');
exports.ClientRequestInterceptor = _chunk3HCE66HZjs.ClientRequestInterceptor;
exports.ClientRequestInterceptor = _chunkGO7ZOUKBjs.ClientRequestInterceptor;
//# sourceMappingURL=index.js.map
@@ -1,8 +1,8 @@
import {
ClientRequestInterceptor
} from "../../chunk-FWJSC2QD.mjs";
} from "../../chunk-JDAAQ7RU.mjs";
import "../../chunk-5KMS5CTP.mjs";
import "../../chunk-I7HQIBT7.mjs";
import "../../chunk-YM42IU6M.mjs";
export {
ClientRequestInterceptor
};
@@ -1,12 +1,12 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkLCA4FKWYjs = require('../../chunk-LCA4FKWY.js');
var _chunk2R5JZR3Ljs = require('../../chunk-2R5JZR3L.js');
require('../../chunk-LK6DILFK.js');
require('../../chunk-PFGO5BSM.js');
require('../../chunk-73NOP3T5.js');
require('../../chunk-6L3PFBGT.js');
require('../../chunk-WZTE4PCO.js');
require('../../chunk-DLID3GDG.js');
exports.XMLHttpRequestInterceptor = _chunkLCA4FKWYjs.XMLHttpRequestInterceptor;
exports.XMLHttpRequestInterceptor = _chunk2R5JZR3Ljs.XMLHttpRequestInterceptor;
//# sourceMappingURL=index.js.map
@@ -1,11 +1,11 @@
import {
XMLHttpRequestInterceptor
} from "../../chunk-OMWE7UVM.mjs";
} from "../../chunk-RXMZLFWG.mjs";
import "../../chunk-6HYIRFX2.mjs";
import "../../chunk-TX5GBTFY.mjs";
import "../../chunk-6YM4PLBI.mjs";
import "../../chunk-5KMS5CTP.mjs";
import "../../chunk-I7HQIBT7.mjs";
import "../../chunk-YM42IU6M.mjs";
export {
XMLHttpRequestInterceptor
};
+3 -3
View File
@@ -1,11 +1,11 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCF5C3K5Ujs = require('../../chunk-CF5C3K5U.js');
var _chunkDPVSIR6Jjs = require('../../chunk-DPVSIR6J.js');
require('../../chunk-PFGO5BSM.js');
require('../../chunk-73NOP3T5.js');
require('../../chunk-6L3PFBGT.js');
require('../../chunk-WZTE4PCO.js');
require('../../chunk-DLID3GDG.js');
exports.FetchInterceptor = _chunkCF5C3K5Ujs.FetchInterceptor;
exports.FetchInterceptor = _chunkDPVSIR6Jjs.FetchInterceptor;
//# sourceMappingURL=index.js.map
+2 -2
View File
@@ -1,10 +1,10 @@
import {
FetchInterceptor
} from "../../chunk-ZSYLU3GR.mjs";
} from "../../chunk-NIASNH2Q.mjs";
import "../../chunk-TX5GBTFY.mjs";
import "../../chunk-6YM4PLBI.mjs";
import "../../chunk-5KMS5CTP.mjs";
import "../../chunk-I7HQIBT7.mjs";
import "../../chunk-YM42IU6M.mjs";
export {
FetchInterceptor
};
+7 -7
View File
@@ -1,23 +1,23 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunk3HCE66HZjs = require('../chunk-3HCE66HZ.js');
var _chunkGO7ZOUKBjs = require('../chunk-GO7ZOUKB.js');
var _chunkLCA4FKWYjs = require('../chunk-LCA4FKWY.js');
var _chunk2R5JZR3Ljs = require('../chunk-2R5JZR3L.js');
require('../chunk-LK6DILFK.js');
var _chunkCF5C3K5Ujs = require('../chunk-CF5C3K5U.js');
var _chunkDPVSIR6Jjs = require('../chunk-DPVSIR6J.js');
require('../chunk-PFGO5BSM.js');
require('../chunk-73NOP3T5.js');
require('../chunk-6L3PFBGT.js');
require('../chunk-WZTE4PCO.js');
require('../chunk-DLID3GDG.js');
// src/presets/node.ts
var node_default = [
new (0, _chunk3HCE66HZjs.ClientRequestInterceptor)(),
new (0, _chunkLCA4FKWYjs.XMLHttpRequestInterceptor)(),
new (0, _chunkCF5C3K5Ujs.FetchInterceptor)()
new (0, _chunkGO7ZOUKBjs.ClientRequestInterceptor)(),
new (0, _chunk2R5JZR3Ljs.XMLHttpRequestInterceptor)(),
new (0, _chunkDPVSIR6Jjs.FetchInterceptor)()
];
+4 -4
View File
@@ -1,17 +1,17 @@
import {
ClientRequestInterceptor
} from "../chunk-FWJSC2QD.mjs";
} from "../chunk-JDAAQ7RU.mjs";
import {
XMLHttpRequestInterceptor
} from "../chunk-OMWE7UVM.mjs";
} from "../chunk-RXMZLFWG.mjs";
import "../chunk-6HYIRFX2.mjs";
import {
FetchInterceptor
} from "../chunk-ZSYLU3GR.mjs";
} from "../chunk-NIASNH2Q.mjs";
import "../chunk-TX5GBTFY.mjs";
import "../chunk-6YM4PLBI.mjs";
import "../chunk-5KMS5CTP.mjs";
import "../chunk-I7HQIBT7.mjs";
import "../chunk-YM42IU6M.mjs";
// src/presets/node.ts
var node_default = [
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@mswjs/interceptors",
"description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.",
"version": "0.38.0",
"version": "0.38.1",
"main": "./lib/node/index.js",
"module": "./lib/node/index.mjs",
"types": "./lib/node/index.d.ts",
@@ -592,6 +592,8 @@ export class MockHttpSocket extends MockSocket {
'Failed to handle a response: request does not exist'
)
FetchResponse.setUrl(this.request.url, response)
/**
* @fixme Stop relying on the "X-Request-Id" request header
* to figure out if one interceptor has been invoked within another.
+41 -16
View File
@@ -1,7 +1,29 @@
import { canParseUrl } from './canParseUrl'
import { getValueBySymbol } from './getValueBySymbol'
export interface FetchResponseInit extends ResponseInit {
url?: string
}
interface UndiciFetchInternalState {
aborted: boolean
rangeRequested: boolean
timingAllowPassed: boolean
requestIncludesCredentials: boolean
type: ResponseType
status: number
statusText: string
timingInfo: unknown
cacheState: unknown
headersList: Record<symbol, Map<string, unknown>>
urlList: Array<URL>
body?: {
stream: ReadableStream
source: unknown
length: number
}
}
export class FetchResponse extends Response {
/**
* Response status codes for responses that cannot have body.
@@ -28,20 +50,25 @@ export class FetchResponse extends Response {
}
static setUrl(url: string | undefined, response: Response): void {
if (!url) {
if (!url || url === 'about:' || !canParseUrl(url)) {
return
}
if (response.url != '') {
return
}
const state = getValueBySymbol<UndiciFetchInternalState>('state', response)
Object.defineProperty(response, 'url', {
value: url,
enumerable: true,
configurable: true,
writable: false,
})
if (state) {
// In Undici, push the URL to the internal list of URLs.
// This will respect the `response.url` getter logic correctly.
state.urlList.push(new URL(url))
} else {
// In other libraries, redefine the `url` property directly.
Object.defineProperty(response, 'url', {
value: url,
enumerable: true,
configurable: true,
writable: false,
})
}
}
/**
@@ -72,12 +99,10 @@ export class FetchResponse extends Response {
* @note Undici keeps an internal "Symbol(state)" that holds
* the actual value of response status. Update that in Node.js.
*/
const stateSymbol = Object.getOwnPropertySymbols(this).find(
(symbol) => symbol.description === 'state'
)
if (stateSymbol) {
const state = Reflect.get(this, stateSymbol) as object
Reflect.set(state, 'status', status)
const state = getValueBySymbol<UndiciFetchInternalState>('state', this)
if (state) {
state.status = status
} else {
Object.defineProperty(this, 'status', {
value: status,
-15
View File
@@ -1,15 +0,0 @@
# Installation
> `npm install --save @types/adm-zip`
# Summary
This package contains type definitions for adm-zip (https://github.com/cthackers/adm-zip).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/adm-zip.
### Additional Details
* Last updated: Thu, 28 Nov 2024 16:02:52 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
# Credits
These definitions were written by [John Vilk](https://github.com/jvilk), [Abner Oliveira](https://github.com/abner), [BendingBender](https://github.com/BendingBender), and [Lei Nelissen](https://github.com/LeiNelissen).
-368
View File
@@ -1,368 +0,0 @@
/// <reference types="node" />
import * as FS from "fs";
import { Constants } from "./util";
declare class AdmZip {
/**
* @param fileNameOrRawData If provided, reads an existing archive. Otherwise creates a new, empty archive.
* @param options Options when initializing the ZIP file
*/
constructor(fileNameOrRawData?: string | Buffer, options?: Partial<AdmZip.InitOptions>);
/**
* Extracts the given entry from the archive and returns the content as a Buffer object
* @param entry ZipEntry object or String with the full path of the entry
* @param pass Password used for decrypting the file
* @return Buffer or Null in case of error
*/
readFile(entry: string | AdmZip.IZipEntry, pass?: string | Buffer): Buffer | null;
/**
* Asynchronous `readFile`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with a `Buffer` or `null` in case of error.
*/
readFileAsync(entry: string | AdmZip.IZipEntry, callback: (data: Buffer | null, err: string) => void): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsText(fileName: string | AdmZip.IZipEntry, encoding?: string): string;
/**
* Asynchronous `readAsText`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with the resulting string.
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsTextAsync(
fileName: string | AdmZip.IZipEntry,
callback: (data: string, err: string) => void,
encoding?: string,
): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory.
* @param entry The full path of the entry or a `IZipEntry` object.
*/
deleteFile(entry: string | AdmZip.IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified file or `IZipEntry`. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string | AdmZip.IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry The full path of the entry or a `IZipEntry` object.
* @return The comment of the specified entry.
*/
getZipEntryComment(entry: string | AdmZip.IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param content The entry's new contents.
*/
updateFile(entry: string | AdmZip.IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
* @param zipName Name for the file.
* @param comment Comment to be attached to the file
*/
addLocalFile(localPath: string, zipPath?: string, zipName?: string, comment?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Default: `""`.
* @param filter RegExp or Function if files match will be included.
*/
addLocalFolder(localPath: string, zipPath?: string, filter?: RegExp | ((filename: string) => boolean)): void;
/**
* Asynchronous addLocalFile
* @param localPath
* @param callback
* @param zipPath optional path inside zip
* @param filter optional RegExp or Function if files match will
* be included.
*/
addLocalFolderAsync(
localPath: string,
callback: (success?: boolean, err?: string) => void,
zipPath?: string,
filter?: RegExp | ((filename: string) => boolean),
): void;
/**
* @param localPath - path where files will be extracted
* @param props - optional properties
* @param props.zipPath - optional path inside zip
* @param props.filter - RegExp or Function if files match will be included.
*/
addLocalFolderPromise(
localPath: string,
props: { zipPath?: string; filter?: RegExp | ((filename: string) => boolean) },
): Promise<void>;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the `entryName` must end in `"/"` and a `null`
* buffer should be provided.
* @param entryName Entry path.
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
* @return The entry corresponding to one which was just added.
*/
addFile(entryName: string, content: Buffer, comment?: string, attr?: number): AdmZip.IZipEntry;
/**
* Returns an array of `IZipEntry` objects representing the files and folders
* inside the archive.
*/
getEntries(): AdmZip.IZipEntry[];
/**
* Returns a `IZipEntry` object representing the file or folder specified by `name`.
* @param name Name of the file or folder to retrieve.
* @return The entry corresponding to the `name`.
*/
getEntry(name: string): AdmZip.IZipEntry | null;
/**
* Returns the number of entries in the ZIP
* @return The amount of entries in the ZIP
*/
getEntryCount(): number;
/**
* Loop through each entry in the ZIP
* @param callback The callback that receives each individual entry
*/
forEach(callback: (entry: AdmZip.IZipEntry) => void): void;
/**
* Extracts the given entry to the given `targetPath`.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param targetPath Target folder where to write the file.
* @param maintainEntryPath If maintainEntryPath is `true` and the entry is
* inside a folder, the entry folder will be created in `targetPath` as
* well. Default: `true`.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
* @param keepOriginalPermission The file will be set as the permission from
* the entry if this is true. Default: `false`.
* @param outFileName String If set will override the filename of the
* extracted file (Only works if the entry is a file)
* @return Boolean
*/
extractEntryTo(
entryPath: string | AdmZip.IZipEntry,
targetPath: string,
maintainEntryPath?: boolean,
overwrite?: boolean,
keepOriginalPermission?: boolean,
outFileName?: string,
): boolean;
/**
* Test the archive
* @param password The password for the archive
*/
test(password?: string | Buffer): boolean;
/**
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
* @param keepOriginalPermission The file will be set as the permission from
* the entry if this is true. Default: `false`.
* @param password The password for the archive
*/
extractAllTo(
targetPath: string,
overwrite?: boolean,
keepOriginalPermission?: boolean,
password?: string | Buffer,
): void;
/**
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
* @param keepOriginalPermission The file will be set as the permission from
* the entry if this is true. Default: `false`.
* @param callback The callback function will be called after extraction.
*/
extractAllToAsync(
targetPath: string,
overwrite?: boolean,
keepOriginalPermission?: boolean,
callback?: (error?: Error) => void,
): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no `targetFileName` is provided, it will
* overwrite the opened zip.
*/
writeZip(targetFileName?: string, callback?: (error: Error | null) => void): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no `targetFileName` is provided, it will
* overwrite the opened zip.
*/
writeZipPromise(targetFileName?: string, props?: { overwrite?: boolean; perm?: number }): Promise<boolean>;
/**
* Returns the content of the entire zip file.
*/
toBuffer(): Buffer;
/**
* Asynchronously returns the content of the entire zip file.
* @param onSuccess called with the content of the zip file, once it has been generated.
* @param onFail unused.
* @param onItemStart called before an entry is compressed.
* @param onItemEnd called after an entry is compressed.
*/
toBuffer(
onSuccess: (buffer: Buffer) => void,
onFail?: (...args: any[]) => void,
onItemStart?: (name: string) => void,
onItemEnd?: (name: string) => void,
): void;
/**
* Asynchronously convert the promise to a Buffer
*/
toBufferPromise(): Promise<Buffer>;
}
declare namespace AdmZip {
/**
* The `IZipEntry` is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
// disable warning about the I-prefix in interface name to prevent breaking stuff for users without a major bump
// eslint-disable-next-line @typescript-eslint/naming-convention
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
readonly rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
readonly name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
readonly isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
readonly header: EntryHeader;
attr: number;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string | Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer, err: string) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
interface EntryHeader {
made: number;
version: number;
flags: number;
method: number;
time: Date;
crc: number;
compressedSize: number;
size: number;
fileNameLength: number;
extraLength: number;
commentLength: number;
diskNumStart: number;
inAttr: number;
attr: number;
offset: number;
readonly encripted: boolean;
readonly entryHeaderSize: number;
readonly realDataOffset: number;
readonly dataHeader: DataHeader;
loadDataHeaderFromBinary(data: Buffer): void;
loadFromBinary(data: Buffer): void;
dataHeaderToBinary(): Buffer;
entryHeaderToBinary(): Buffer;
toString(): string;
}
interface DataHeader {
version: number;
flags: number;
method: number;
time: number;
crc: number;
compressedSize: number;
size: number;
fnameLen: number;
extraLen: number;
}
interface InitOptions {
/* If true it disables files sorting */
noSort: boolean;
/* Read entries during load (initial loading may be slower) */
readEntries: boolean;
/* Read method */
method: (typeof Constants)[keyof typeof Constants] | number;
/* file system */
fs: null | typeof FS;
}
}
export = AdmZip;
-43
View File
@@ -1,43 +0,0 @@
{
"name": "@types/adm-zip",
"version": "0.5.7",
"description": "TypeScript definitions for adm-zip",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/adm-zip",
"license": "MIT",
"contributors": [
{
"name": "John Vilk",
"githubUsername": "jvilk",
"url": "https://github.com/jvilk"
},
{
"name": "Abner Oliveira",
"githubUsername": "abner",
"url": "https://github.com/abner"
},
{
"name": "BendingBender",
"githubUsername": "BendingBender",
"url": "https://github.com/BendingBender"
},
{
"name": "Lei Nelissen",
"githubUsername": "LeiNelissen",
"url": "https://github.com/LeiNelissen"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/adm-zip"
},
"scripts": {},
"dependencies": {
"@types/node": "*"
},
"peerDependencies": {},
"typesPublisherContentHash": "2b7ccefc1df4e05662e7d47904e27f4af394ff59c9d5f8b3ea47f579e5146bba",
"typeScriptVersion": "5.0"
}
-178
View File
@@ -1,178 +0,0 @@
export const Constants: {
/* The local file header */
LOCHDR: 30; // LOC header size
LOCSIG: 0x04034b50; // "PK\003\004"
LOCVER: 4; // version needed to extract
LOCFLG: 6; // general purpose bit flag
LOCHOW: 8; // compression method
LOCTIM: 10; // modification time (2 bytes time, 2 bytes date)
LOCCRC: 14; // uncompressed file crc-32 value
LOCSIZ: 18; // compressed size
LOCLEN: 22; // uncompressed size
LOCNAM: 26; // filename length
LOCEXT: 28; // extra field length
/* The Data descriptor */
EXTSIG: 0x08074b50; // "PK\007\008"
EXTHDR: 16; // EXT header size
EXTCRC: 4; // uncompressed file crc-32 value
EXTSIZ: 8; // compressed size
EXTLEN: 12; // uncompressed size
/* The central directory file header */
CENHDR: 46; // CEN header size
CENSIG: 0x02014b50; // "PK\001\002"
CENVEM: 4; // version made by
CENVER: 6; // version needed to extract
CENFLG: 8; // encrypt, decrypt flags
CENHOW: 10; // compression method
CENTIM: 12; // modification time (2 bytes time, 2 bytes date)
CENCRC: 16; // uncompressed file crc-32 value
CENSIZ: 20; // compressed size
CENLEN: 24; // uncompressed size
CENNAM: 28; // filename length
CENEXT: 30; // extra field length
CENCOM: 32; // file comment length
CENDSK: 34; // volume number start
CENATT: 36; // internal file attributes
CENATX: 38; // external file attributes (host system dependent)
CENOFF: 42; // LOC header offset
/* The entries in the end of central directory */
ENDHDR: 22; // END header size
ENDSIG: 0x06054b50; // "PK\005\006"
ENDSUB: 8; // number of entries on this disk
ENDTOT: 10; // total number of entries
ENDSIZ: 12; // central directory size in bytes
ENDOFF: 16; // offset of first CEN header
ENDCOM: 20; // zip file comment length
END64HDR: 20; // zip64 END header size
END64SIG: 0x07064b50; // zip64 Locator signature, "PK\006\007"
END64START: 4; // number of the disk with the start of the zip64
END64OFF: 8; // relative offset of the zip64 end of central directory
END64NUMDISKS: 16; // total number of disks
ZIP64SIG: 0x06064b50; // zip64 signature, "PK\006\006"
ZIP64HDR: 56; // zip64 record minimum size
ZIP64LEAD: 12; // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE
ZIP64SIZE: 4; // zip64 size of the central directory record
ZIP64VEM: 12; // zip64 version made by
ZIP64VER: 14; // zip64 version needed to extract
ZIP64DSK: 16; // zip64 number of this disk
ZIP64DSKDIR: 20; // number of the disk with the start of the record directory
ZIP64SUB: 24; // number of entries on this disk
ZIP64TOT: 32; // total number of entries
ZIP64SIZB: 40; // zip64 central directory size in bytes
ZIP64OFF: 48; // offset of start of central directory with respect to the starting disk number
ZIP64EXTRA: 56; // extensible data sector
/* Compression methods */
STORED: 0; // no compression
SHRUNK: 1; // shrunk
REDUCED1: 2; // reduced with compression factor 1
REDUCED2: 3; // reduced with compression factor 2
REDUCED3: 4; // reduced with compression factor 3
REDUCED4: 5; // reduced with compression factor 4
IMPLODED: 6; // imploded
// 7 reserved for Tokenizing compression algorithm
DEFLATED: 8; // deflated
ENHANCED_DEFLATED: 9; // enhanced deflated
PKWARE: 10; // PKWare DCL imploded
// 11 reserved by PKWARE
BZIP2: 12; // compressed using BZIP2
// 13 reserved by PKWARE
LZMA: 14; // LZMA
// 15-17 reserved by PKWARE
IBM_TERSE: 18; // compressed using IBM TERSE
IBM_LZ77: 19; // IBM LZ77 z
AES_ENCRYPT: 99; // WinZIP AES encryption method
/* General purpose bit flag */
// values can obtained with expression 2**bitnr
FLG_ENC: 1; // Bit 0: encrypted file
FLG_COMP1: 2; // Bit 1, compression option
FLG_COMP2: 4; // Bit 2, compression option
FLG_DESC: 8; // Bit 3, data descriptor
FLG_ENH: 16; // Bit 4, enhanced deflating
FLG_PATCH: 32; // Bit 5, indicates that the file is compressed patched data.
FLG_STR: 64; // Bit 6, strong encryption (patented)
// Bits 7-10: Currently unused.
FLG_EFS: 2048; // Bit 11: Language encoding flag (EFS)
// Bit 12: Reserved by PKWARE for enhanced compression.
// Bit 13: encrypted the Central Directory (patented).
// Bits 14-15: Reserved by PKWARE.
FLG_MSK: 4096; // mask header values
/* Load type */
FILE: 2;
BUFFER: 1;
NONE: 0;
/* 4.5 Extensible data fields */
EF_ID: 0;
EF_SIZE: 2;
/* Header IDs */
ID_ZIP64: 0x0001;
ID_AVINFO: 0x0007;
ID_PFS: 0x0008;
ID_OS2: 0x0009;
ID_NTFS: 0x000a;
ID_OPENVMS: 0x000c;
ID_UNIX: 0x000d;
ID_FORK: 0x000e;
ID_PATCH: 0x000f;
ID_X509_PKCS7: 0x0014;
ID_X509_CERTID_F: 0x0015;
ID_X509_CERTID_C: 0x0016;
ID_STRONGENC: 0x0017;
ID_RECORD_MGT: 0x0018;
ID_X509_PKCS7_RL: 0x0019;
ID_IBM1: 0x0065;
ID_IBM2: 0x0066;
ID_POSZIP: 0x4690;
EF_ZIP64_OR_32: 0xffffffff;
EF_ZIP64_OR_16: 0xffff;
EF_ZIP64_SUNCOMP: 0;
EF_ZIP64_SCOMP: 8;
EF_ZIP64_RHO: 16;
EF_ZIP64_DSN: 24;
};
export const Errors: {
/* Header error messages */
INVALID_LOC: "Invalid LOC header (bad signature)";
INVALID_CEN: "Invalid CEN header (bad signature)";
INVALID_END: "Invalid END header (bad signature)";
/* ZipEntry error messages */
NO_DATA: "Nothing to decompress";
BAD_CRC: "CRC32 checksum failed";
FILE_IN_THE_WAY: "There is a file in the way: %s";
UNKNOWN_METHOD: "Invalid/unsupported compression method";
/* Inflater error messages */
AVAIL_DATA: "inflate::Available inflate data did not terminate";
INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block";
TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes";
INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths";
INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length";
INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete";
INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths";
INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths";
INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement";
INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)";
/* ADM-ZIP error messages */
CANT_EXTRACT_FILE: "Could not extract the file";
CANT_OVERRIDE: "Target file already exists";
NO_ZIP: "No zip file was loaded";
NO_ENTRY: "Entry doesn't exist";
DIRECTORY_CONTENT_ERROR: "A directory cannot have content";
FILE_NOT_FOUND: "File not found: %s";
NOT_IMPLEMENTED: "Not implemented";
INVALID_FILENAME: "Invalid filename";
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found";
};
+16
View File
@@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/archiver`
# Summary
This package contains type definitions for archiver (https://github.com/archiverjs/node-archiver).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/archiver.
### Additional Details
* Last updated: Wed, 23 Oct 2024 03:36:41 GMT
* Dependencies: [@types/readdir-glob](https://npmjs.com/package/@types/readdir-glob)
# Credits
These definitions were written by [ Esri
// Dolan Miu](https://github.com/dolanmiu), [Crevil](https://github.com/crevil), and [Piotr Błażejewicz](https://github.com/peterblazejewicz).
+137
View File
@@ -0,0 +1,137 @@
import * as fs from "fs";
import * as ReaddirGlob from "readdir-glob";
import * as stream from "stream";
import { ZlibOptions } from "zlib";
type Partial<T> = {
[P in keyof T]?: T[P];
};
// This library adds `cwd` to the options
type GlobOptions = ReaddirGlob.Options & { cwd?: string };
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- support for ConstructorFn function and classes
type ConstructorFn<T> = Function | (new(...params: any[]) => T);
declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver;
declare namespace archiver {
type Format = "zip" | "tar";
function create(format: string, options?: ArchiverOptions): Archiver;
/** Check if the format is already registered. */
function isRegisteredFormat(format: string): boolean;
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
function registerFormat(format: string, module: Function): void;
interface EntryData {
/** Sets the entry name including internal path */
name: string;
/** Sets the entry date */
date?: Date | string | undefined;
/** Sets the entry permissions */
mode?: number | undefined;
/**
* Sets a path prefix for the entry name.
* Useful when working with methods like `directory` or `glob`
*/
prefix?: string | undefined;
/**
* Sets the fs stat data for this entry allowing
* for reduction of fs stat calls when stat data is already known
*/
stats?: fs.Stats | undefined;
}
interface ZipEntryData extends EntryData {
/** Sets the compression method to STORE */
store?: boolean | undefined;
}
type TarEntryData = EntryData;
interface ProgressData {
entries: {
total: number;
processed: number;
};
fs: {
totalBytes: number;
processedBytes: number;
};
}
/** A function that lets you either opt out of including an entry (by returning false), or modify the contents of an entry as it is added (by returning an EntryData) */
type EntryDataFunction = (entry: EntryData) => false | EntryData;
class ArchiverError extends Error {
code: string; // Since archiver format support is modular, we cannot enumerate all possible error codes, as the modules can throw arbitrary ones.
data: any;
path?: any;
constructor(code: string, data: any);
}
interface Archiver extends stream.Transform {
abort(): this;
append(source: stream.Readable | Buffer | string, data?: EntryData | ZipEntryData | TarEntryData): this;
/** if false is passed for destpath, the path of a chunk of data in the archive is set to the root */
directory(dirpath: string, destpath: false | string, data?: Partial<EntryData> | EntryDataFunction): this;
file(filename: string, data: EntryData): this;
glob(pattern: string, options?: GlobOptions, data?: Partial<EntryData>): this;
finalize(): Promise<void>;
setFormat(format: string): this;
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
setModule(module: Function): this;
pointer(): number;
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
use(plugin: Function): this;
symlink(filepath: string, target: string, mode?: number): this;
on(event: "error" | "warning", listener: (error: ArchiverError) => void): this;
on(event: "data", listener: (data: Buffer) => void): this;
on(event: "progress", listener: (progress: ProgressData) => void): this;
on(event: "close" | "drain" | "finish", listener: () => void): this;
on(event: "pipe" | "unpipe", listener: (src: stream.Readable) => void): this;
on(event: "entry", listener: (entry: EntryData) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
}
type ArchiverOptions = CoreOptions & TransformOptions & ZipOptions & TarOptions;
interface CoreOptions {
statConcurrency?: number | undefined;
}
interface TransformOptions {
allowHalfOpen?: boolean | undefined;
readableObjectMode?: boolean | undefined;
writeableObjectMode?: boolean | undefined;
decodeStrings?: boolean | undefined;
encoding?: string | undefined;
highWaterMark?: number | undefined;
objectmode?: boolean | undefined;
}
interface ZipOptions {
comment?: string | undefined;
forceLocalTime?: boolean | undefined;
forceZip64?: boolean | undefined;
/** @default false */
namePrependSlash?: boolean | undefined;
store?: boolean | undefined;
zlib?: ZlibOptions | undefined;
}
interface TarOptions {
gzip?: boolean | undefined;
gzipOptions?: ZlibOptions | undefined;
}
}
export = archiver;
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@types/archiver",
"version": "6.0.3",
"description": "TypeScript definitions for archiver",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/archiver",
"license": "MIT",
"contributors": [
{
"name": " Esri\n// Dolan Miu",
"githubUsername": "dolanmiu",
"url": "https://github.com/dolanmiu"
},
{
"name": "Crevil",
"githubUsername": "crevil",
"url": "https://github.com/crevil"
},
{
"name": "Piotr Błażejewicz",
"githubUsername": "peterblazejewicz",
"url": "https://github.com/peterblazejewicz"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/archiver"
},
"scripts": {},
"dependencies": {
"@types/readdir-glob": "*"
},
"peerDependencies": {},
"typesPublisherContentHash": "5ab2f0d52b813039b334365186e5714b86698972ff1c43ce35e5f9ed27227a14",
"typeScriptVersion": "4.8"
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
+15
View File
@@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/readdir-glob`
# Summary
This package contains type definitions for readdir-glob (https://github.com/Yqnn/node-readdir-glob).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/readdir-glob.
### Additional Details
* Last updated: Mon, 20 Nov 2023 23:36:24 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
# Credits
These definitions were written by [Dolan Miu](https://github.com/dolanmiu).
+124
View File
@@ -0,0 +1,124 @@
/// <reference types="node" />
import { EventEmitter } from "events";
import * as fs from "fs";
declare function readdirGlob(root: string, options: readdirGlob.Options): readdirGlob.ReaddirGlob;
declare namespace readdirGlob {
interface Options {
/**
* Glob pattern or Array of Glob patterns to match the found files with. A file has to match at least one of the provided patterns to be returned.
*/
pattern?: string | string[];
/**
* Allow pattern to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot.
*/
dot?: boolean;
/**
* Disable `**` matching against multiple folder names.
*/
noglobstar?: boolean;
/**
* Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**\/*.js`, matching all js files in all directories.
*/
matchBase?: boolean;
/**
* Perform a case-insensitive match. Note: on case-insensitive file systems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors.
*/
nocase?: boolean;
/**
* Glob pattern or Array of Glob patterns to exclude matches. If a file or a folder matches at least one of the provided patterns, it's not returned.
* It doesn't prevent files from folder content to be returned. Note: ignore patterns are always in dot:true mode.
*/
ignore?: string | string[];
/**
* Glob pattern or Array of Glob patterns to exclude folders.
* If a folder matches one of the provided patterns, it's not returned, and it's not explored: this prevents any of its children to be returned.
* Note: skip patterns are always in dot:true mode.
*/
skip?: string | string[];
/**
* Follow symlinked directories. Note that requires to stat _all_ results, and so reduces performance.
*/
follow?: boolean;
/**
* Set to true to stat _all_ results. This reduces performance.
*/
stat?: boolean;
/**
* Do not match directories, only files.
*/
nodir?: boolean;
/**
* Add a `/` character to directory matches.
*/
mark?: boolean;
/**
* When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings.
*/
silent?: boolean;
/**
* Absolute paths will be returned instead of relative paths.
*/
absolute?: boolean;
}
interface Match {
/**
* relative path of the matched file
*/
relative: string;
/**
* absolute path of the matched file
*/
absolute: string;
/**
* stat of the matched file (only if stat:true option is used)
*/
stat?: fs.Stats;
}
class ReaddirGlob extends EventEmitter {
constructor(cwd: string, cb: (error: Error | null, matches?: readonly Match[]) => void);
constructor(cwd: string, options: Options, cb: (error: Error | null, matches?: readonly Match[]) => void);
/**
* Every time a match is found, this is emitted with the specific thing that matched.
*/
on(event: "match", callback: (match: Match) => void): this;
/**
* When the matching is finished, this is emitted with all the matches found.
*/
on(event: "error", callback: (error: Error) => void): this;
/**
* Emitted when an unexpected error is encountered.
*/
on(event: "end", callback: (matches: readonly Match[]) => void): this;
/**
* Temporarily stop the search
*/
pause(): void;
/**
* Resume the search
*/
resume(): void;
/**
* Stop the search forever
*/
abort(): void;
/**
* The options object passed in.
*/
options: Options;
/**
* Boolean which is set to true when calling `pause()`.
*/
paused: boolean;
/**
* Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting.
*/
aborted: boolean;
}
}
export = readdirGlob;
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@types/readdir-glob",
"version": "1.1.5",
"description": "TypeScript definitions for readdir-glob",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/readdir-glob",
"license": "MIT",
"contributors": [
{
"name": "Dolan Miu",
"githubUsername": "dolanmiu",
"url": "https://github.com/dolanmiu"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/readdir-glob"
},
"scripts": {},
"dependencies": {
"@types/node": "*"
},
"typesPublisherContentHash": "7bdc6e6f815f6791c4762b917d4437d2172faa334bd34f1ce9eb5307ecc565f1",
"typeScriptVersion": "4.5"
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2012 Another-D-Mention Software and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-87
View File
@@ -1,87 +0,0 @@
# ADM-ZIP for NodeJS
ADM-ZIP is a pure JavaScript implementation for zip data compression for [NodeJS](https://nodejs.org/).
<a href="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml">
<img src="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml/badge.svg" alt="Build Status">
</a>
# Installation
With [npm](https://www.npmjs.com/) do:
$ npm install adm-zip
**Electron** file system support described below.
## What is it good for?
The library allows you to:
- decompress zip files directly to disk or in memory buffers
- compress files and store them to disk in .zip format or in compressed buffers
- update content of/add new/delete files from an existing .zip
# Dependencies
There are no other nodeJS libraries that ADM-ZIP is dependent of
# Examples
## Basic usage
```javascript
var AdmZip = require("adm-zip");
// reading archives
var zip = new AdmZip("./my_file.zip");
var password = "1234567890";
var zipEntries = zip.getEntries(); // an array of ZipEntry records - add password parameter if entries are password protected
zipEntries.forEach(function (zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString("utf8"));
}
});
// outputs the content of some_folder/my_file.txt
console.log(zip.readAsText("some_folder/my_file.txt"));
// extracts the specified file to the specified location
zip.extractEntryTo(/*entry name*/ "some_folder/my_file.txt", /*target path*/ "/home/me/tempfolder", /*maintainEntryPath*/ false, /*overwrite*/ true);
// extracts everything
zip.extractAllTo(/*target path*/ "/home/me/zipcontent/", /*overwrite*/ true);
// creating archives
var zip = new AdmZip();
// add file directly
var content = "inner content of the file";
zip.addFile("test.txt", Buffer.from(content, "utf8"), "entry comment goes here");
// add local file
zip.addLocalFile("/home/me/some_picture.png");
// get everything as a buffer
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/ "/home/me/files.zip");
// ... more examples in the wiki
```
For more detailed information please check out the [wiki](https://github.com/cthackers/adm-zip/wiki).
## Electron original-fs
ADM-ZIP has supported electron **original-fs** for years without any user interractions but it causes problem with bundlers like rollup etc. For continuing support **original-fs** or any other custom file system module. There is possible specify your module by **fs** option in ADM-ZIP constructor.
Example:
```javascript
const AdmZip = require("adm-zip");
const OriginalFs = require("original-fs");
// reading archives
const zip = new AdmZip("./my_file.zip", { fs: OriginalFs });
.
.
.
```
-949
View File
@@ -1,949 +0,0 @@
const Utils = require("./util");
const pth = require("path");
const ZipEntry = require("./zipEntry");
const ZipFile = require("./zipFile");
const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean");
const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string");
const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function");
const defaultOptions = {
// option "noSort" : if true it disables files sorting
noSort: false,
// read entries during load (initial loading may be slower)
readEntries: false,
// default method is none
method: Utils.Constants.NONE,
// file system
fs: null
};
module.exports = function (/**String*/ input, /** object */ options) {
let inBuffer = null;
// create object based default options, allowing them to be overwritten
const opts = Object.assign(Object.create(null), defaultOptions);
// test input variable
if (input && "object" === typeof input) {
// if value is not buffer we accept it to be object with options
if (!(input instanceof Uint8Array)) {
Object.assign(opts, input);
input = opts.input ? opts.input : undefined;
if (opts.input) delete opts.input;
}
// if input is buffer
if (Buffer.isBuffer(input)) {
inBuffer = input;
opts.method = Utils.Constants.BUFFER;
input = undefined;
}
}
// assign options
Object.assign(opts, options);
// instanciate utils filesystem
const filetools = new Utils(opts);
if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") {
opts.decoder = Utils.decoder;
}
// if input is file name we retrieve its content
if (input && "string" === typeof input) {
// load zip file
if (filetools.fs.existsSync(input)) {
opts.method = Utils.Constants.FILE;
opts.filename = input;
inBuffer = filetools.fs.readFileSync(input);
} else {
throw Utils.Errors.INVALID_FILENAME();
}
}
// create variable
const _zip = new ZipFile(inBuffer, opts);
const { canonical, sanitize, zipnamefix } = Utils;
function getEntry(/**Object*/ entry) {
if (entry && _zip) {
var item;
// If entry was given as a file name
if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry));
// if entry was given as a ZipEntry object
if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
if (item) {
return item;
}
}
return null;
}
function fixPath(zipPath) {
const { join, normalize, sep } = pth.posix;
// convert windows file separators and normalize
return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep));
}
function filenameFilter(filterfn) {
if (filterfn instanceof RegExp) {
// if filter is RegExp wrap it
return (function (rx) {
return function (filename) {
return rx.test(filename);
};
})(filterfn);
} else if ("function" !== typeof filterfn) {
// if filter is not function we will replace it
return () => true;
}
return filterfn;
}
// keep last character on folders
const relativePath = (local, entry) => {
let lastChar = entry.slice(-1);
lastChar = lastChar === filetools.sep ? filetools.sep : "";
return pth.relative(local, entry) + lastChar;
};
return {
/**
* Extracts the given entry from the archive and returns the content as a Buffer object
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @param {Buffer|string} [pass] - password
* @return Buffer or Null in case of error
*/
readFile: function (entry, pass) {
var item = getEntry(entry);
return (item && item.getData(pass)) || null;
},
/**
* Returns how many child elements has on entry (directories) on files it is always 0
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @returns {integer}
*/
childCount: function (entry) {
const item = getEntry(entry);
if (item) {
return _zip.getChildCount(item);
}
},
/**
* Asynchronous readFile
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @param {callback} callback
*
* @return Buffer or Null in case of error
*/
readFileAsync: function (entry, callback) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(callback);
} else {
callback(null, "getEntry failed for:" + entry);
}
},
/**
* Extracts the given entry from the archive and returns the content as plain text in the given encoding
* @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry
* @param {string} encoding - Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsText: function (entry, encoding) {
var item = getEntry(entry);
if (item) {
var data = item.getData();
if (data && data.length) {
return data.toString(encoding || "utf8");
}
}
return "";
},
/**
* Asynchronous readAsText
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @param {callback} callback
* @param {string} [encoding] - Optional. If no encoding is specified utf8 is used
*
* @return String
*/
readAsTextAsync: function (entry, callback, encoding) {
var item = getEntry(entry);
if (item) {
item.getDataAsync(function (data, err) {
if (err) {
callback(data, err);
return;
}
if (data && data.length) {
callback(data.toString(encoding || "utf8"));
} else {
callback("");
}
});
} else {
callback("");
}
},
/**
* Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
*
* @param {ZipEntry|string} entry
* @returns {void}
*/
deleteFile: function (entry, withsubfolders = true) {
// @TODO: test deleteFile
var item = getEntry(entry);
if (item) {
_zip.deleteFile(item.entryName, withsubfolders);
}
},
/**
* Remove the entry from the file or directory without affecting any nested entries
*
* @param {ZipEntry|string} entry
* @returns {void}
*/
deleteEntry: function (entry) {
// @TODO: test deleteEntry
var item = getEntry(entry);
if (item) {
_zip.deleteEntry(item.entryName);
}
},
/**
* Adds a comment to the zip. The zip must be rewritten after adding the comment.
*
* @param {string} comment
*/
addZipComment: function (comment) {
// @TODO: test addZipComment
_zip.comment = comment;
},
/**
* Returns the zip comment
*
* @return String
*/
getZipComment: function () {
return _zip.comment || "";
},
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
* The comment cannot exceed 65535 characters in length
*
* @param {ZipEntry} entry
* @param {string} comment
*/
addZipEntryComment: function (entry, comment) {
var item = getEntry(entry);
if (item) {
item.comment = comment;
}
},
/**
* Returns the comment of the specified entry
*
* @param {ZipEntry} entry
* @return String
*/
getZipEntryComment: function (entry) {
var item = getEntry(entry);
if (item) {
return item.comment || "";
}
return "";
},
/**
* Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
*
* @param {ZipEntry} entry
* @param {Buffer} content
*/
updateFile: function (entry, content) {
var item = getEntry(entry);
if (item) {
item.setData(content);
}
},
/**
* Adds a file from the disk to the archive
*
* @param {string} localPath File to add to zip
* @param {string} [zipPath] Optional path inside the zip
* @param {string} [zipName] Optional name for the file
* @param {string} [comment] Optional file comment
*/
addLocalFile: function (localPath, zipPath, zipName, comment) {
if (filetools.fs.existsSync(localPath)) {
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// p - local file name
const p = pth.win32.basename(pth.win32.normalize(localPath));
// add file name into zippath
zipPath += zipName ? zipName : p;
// read file attributes
const _attr = filetools.fs.statSync(localPath);
// get file content
const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);
// if folder
if (_attr.isDirectory()) zipPath += filetools.sep;
// add file into zip file
this.addFile(zipPath, data, comment, _attr);
} else {
throw Utils.Errors.FILE_NOT_FOUND(localPath);
}
},
/**
* Callback for showing if everything was done.
*
* @callback doneCallback
* @param {Error} err - Error object
* @param {boolean} done - was request fully completed
*/
/**
* Adds a file from the disk to the archive
*
* @param {(object|string)} options - options object, if it is string it us used as localPath.
* @param {string} options.localPath - Local path to the file.
* @param {string} [options.comment] - Optional file comment.
* @param {string} [options.zipPath] - Optional path inside the zip
* @param {string} [options.zipName] - Optional name for the file
* @param {doneCallback} callback - The callback that handles the response.
*/
addLocalFileAsync: function (options, callback) {
options = typeof options === "object" ? options : { localPath: options };
const localPath = pth.resolve(options.localPath);
const { comment } = options;
let { zipPath, zipName } = options;
const self = this;
filetools.fs.stat(localPath, function (err, stats) {
if (err) return callback(err, false);
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// p - local file name
const p = pth.win32.basename(pth.win32.normalize(localPath));
// add file name into zippath
zipPath += zipName ? zipName : p;
if (stats.isFile()) {
filetools.fs.readFile(localPath, function (err, data) {
if (err) return callback(err, false);
self.addFile(zipPath, data, comment, stats);
return setImmediate(callback, undefined, true);
});
} else if (stats.isDirectory()) {
zipPath += filetools.sep;
self.addFile(zipPath, Buffer.alloc(0), comment, stats);
return setImmediate(callback, undefined, true);
}
});
},
/**
* Adds a local directory and all its nested files and directories to the archive
*
* @param {string} localPath - local path to the folder
* @param {string} [zipPath] - optional path inside zip
* @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included.
*/
addLocalFolder: function (localPath, zipPath, filter) {
// Prepare filter
filter = filenameFilter(filter);
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// normalize the path first
localPath = pth.normalize(localPath);
if (filetools.fs.existsSync(localPath)) {
const items = filetools.findFiles(localPath);
const self = this;
if (items.length) {
for (const filepath of items) {
const p = pth.join(zipPath, relativePath(localPath, filepath));
if (filter(p)) {
self.addLocalFile(filepath, pth.dirname(p));
}
}
}
} else {
throw Utils.Errors.FILE_NOT_FOUND(localPath);
}
},
/**
* Asynchronous addLocalFolder
* @param {string} localPath
* @param {callback} callback
* @param {string} [zipPath] optional path inside zip
* @param {RegExp|function} [filter] optional RegExp or Function if files match will
* be included.
*/
addLocalFolderAsync: function (localPath, callback, zipPath, filter) {
// Prepare filter
filter = filenameFilter(filter);
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// normalize the path first
localPath = pth.normalize(localPath);
var self = this;
filetools.fs.open(localPath, "r", function (err) {
if (err && err.code === "ENOENT") {
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
} else if (err) {
callback(undefined, err);
} else {
var items = filetools.findFiles(localPath);
var i = -1;
var next = function () {
i += 1;
if (i < items.length) {
var filepath = items[i];
var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix
p = p
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\x20-\x7E]/g, ""); // accent fix
if (filter(p)) {
filetools.fs.stat(filepath, function (er0, stats) {
if (er0) callback(undefined, er0);
if (stats.isFile()) {
filetools.fs.readFile(filepath, function (er1, data) {
if (er1) {
callback(undefined, er1);
} else {
self.addFile(zipPath + p, data, "", stats);
next();
}
});
} else {
self.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats);
next();
}
});
} else {
process.nextTick(() => {
next();
});
}
} else {
callback(true, undefined);
}
};
next();
}
});
},
/**
* Adds a local directory and all its nested files and directories to the archive
*
* @param {object | string} options - options object, if it is string it us used as localPath.
* @param {string} options.localPath - Local path to the folder.
* @param {string} [options.zipPath] - optional path inside zip.
* @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included.
* @param {function|string} [options.namefix] - optional function to help fix filename
* @param {doneCallback} callback - The callback that handles the response.
*
*/
addLocalFolderAsync2: function (options, callback) {
const self = this;
options = typeof options === "object" ? options : { localPath: options };
localPath = pth.resolve(fixPath(options.localPath));
let { zipPath, filter, namefix } = options;
if (filter instanceof RegExp) {
filter = (function (rx) {
return function (filename) {
return rx.test(filename);
};
})(filter);
} else if ("function" !== typeof filter) {
filter = function () {
return true;
};
}
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// Check Namefix function
if (namefix == "latin1") {
namefix = (str) =>
str
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only)
}
if (typeof namefix !== "function") namefix = (str) => str;
// internal, create relative path + fix the name
const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));
const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));
filetools.fs.open(localPath, "r", function (err) {
if (err && err.code === "ENOENT") {
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
} else if (err) {
callback(undefined, err);
} else {
filetools.findFilesAsync(localPath, function (err, fileEntries) {
if (err) return callback(err);
fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));
if (!fileEntries.length) callback(undefined, false);
setImmediate(
fileEntries.reverse().reduce(function (next, entry) {
return function (err, done) {
if (err || done === false) return setImmediate(next, err, false);
self.addLocalFileAsync(
{
localPath: entry,
zipPath: pth.dirname(relPathFix(entry)),
zipName: fileNameFix(entry)
},
next
);
};
}, callback)
);
});
}
});
},
/**
* Adds a local directory and all its nested files and directories to the archive
*
* @param {string} localPath - path where files will be extracted
* @param {object} props - optional properties
* @param {string} [props.zipPath] - optional path inside zip
* @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included.
* @param {function|string} [props.namefix] - optional function to help fix filename
*/
addLocalFolderPromise: function (localPath, props) {
return new Promise((resolve, reject) => {
this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {
if (err) reject(err);
if (done) resolve(this);
});
});
},
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null buffer should be provided.
* Comment and attributes are optional
*
* @param {string} entryName
* @param {Buffer | string} content - file content as buffer or utf8 coded string
* @param {string} [comment] - file comment
* @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object
*/
addFile: function (entryName, content, comment, attr) {
entryName = zipnamefix(entryName);
let entry = getEntry(entryName);
const update = entry != null;
// prepare new entry
if (!update) {
entry = new ZipEntry(opts);
entry.entryName = entryName;
}
entry.comment = comment || "";
const isStat = "object" === typeof attr && attr instanceof filetools.fs.Stats;
// last modification time from file stats
if (isStat) {
entry.header.time = attr.mtime;
}
// Set file attribute
var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)
// extended attributes field for Unix
// set file type either S_IFDIR / S_IFREG
let unix = entry.isDirectory ? 0x4000 : 0x8000;
if (isStat) {
// File attributes from file stats
unix |= 0xfff & attr.mode;
} else if ("number" === typeof attr) {
// attr from given attr values
unix |= 0xfff & attr;
} else {
// Default values:
unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)
}
fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes
entry.attr = fileattr;
entry.setData(content);
if (!update) _zip.setEntry(entry);
return entry;
},
/**
* Returns an array of ZipEntry objects representing the files and folders inside the archive
*
* @param {string} [password]
* @returns Array
*/
getEntries: function (password) {
_zip.password = password;
return _zip ? _zip.entries : [];
},
/**
* Returns a ZipEntry object representing the file or folder specified by ``name``.
*
* @param {string} name
* @return ZipEntry
*/
getEntry: function (/**String*/ name) {
return getEntry(name);
},
getEntryCount: function () {
return _zip.getEntryCount();
},
forEach: function (callback) {
return _zip.forEach(callback);
},
/**
* Extracts the given entry to the given targetPath
* If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
*
* @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry
* @param {string} targetPath - Target folder where to write the file
* @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE
* @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true.
* @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true.
* @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file)
*
* @return Boolean
*/
extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {
overwrite = get_Bool(false, overwrite);
keepOriginalPermission = get_Bool(false, keepOriginalPermission);
maintainEntryPath = get_Bool(true, maintainEntryPath);
outFileName = get_Str(keepOriginalPermission, outFileName);
var item = getEntry(entry);
if (!item) {
throw Utils.Errors.NO_ENTRY();
}
var entryName = canonical(item.entryName);
var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName));
if (item.isDirectory) {
var children = _zip.getEntryChildren(item);
children.forEach(function (child) {
if (child.isDirectory) return;
var content = child.getData();
if (!content) {
throw Utils.Errors.CANT_EXTRACT_FILE();
}
var name = canonical(child.entryName);
var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));
// The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;
filetools.writeFileTo(childName, content, overwrite, fileAttr);
});
return true;
}
var content = item.getData(_zip.password);
if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();
if (filetools.fs.existsSync(target) && !overwrite) {
throw Utils.Errors.CANT_OVERRIDE();
}
// The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileTo(target, content, overwrite, fileAttr);
return true;
},
/**
* Test the archive
* @param {string} [pass]
*/
test: function (pass) {
if (!_zip) {
return false;
}
for (var entry in _zip.entries) {
try {
if (entry.isDirectory) {
continue;
}
var content = _zip.entries[entry].getData(pass);
if (!content) {
return false;
}
} catch (err) {
return false;
}
}
return true;
},
/**
* Extracts the entire archive to the given location
*
* @param {string} targetPath Target location
* @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.
* Default is FALSE
* @param {string|Buffer} [pass] password
*/
extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) {
keepOriginalPermission = get_Bool(false, keepOriginalPermission);
pass = get_Str(keepOriginalPermission, pass);
overwrite = get_Bool(false, overwrite);
if (!_zip) throw Utils.Errors.NO_ZIP();
_zip.entries.forEach(function (entry) {
var entryName = sanitize(targetPath, canonical(entry.entryName));
if (entry.isDirectory) {
filetools.makeDir(entryName);
return;
}
var content = entry.getData(pass);
if (!content) {
throw Utils.Errors.CANT_EXTRACT_FILE();
}
// The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileTo(entryName, content, overwrite, fileAttr);
try {
filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
} catch (err) {
throw Utils.Errors.CANT_EXTRACT_FILE();
}
});
},
/**
* Asynchronous extractAllTo
*
* @param {string} targetPath Target location
* @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE
* @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.
* Default is FALSE
* @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown.
*/
extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) {
callback = get_Fun(overwrite, keepOriginalPermission, callback);
keepOriginalPermission = get_Bool(false, keepOriginalPermission);
overwrite = get_Bool(false, overwrite);
if (!callback) {
return new Promise((resolve, reject) => {
this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) {
if (err) {
reject(err);
} else {
resolve(this);
}
});
});
}
if (!_zip) {
callback(Utils.Errors.NO_ZIP());
return;
}
targetPath = pth.resolve(targetPath);
// convert entryName to
const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));
const getError = (msg, file) => new Error(msg + ': "' + file + '"');
// separate directories from files
const dirEntries = [];
const fileEntries = [];
_zip.entries.forEach((e) => {
if (e.isDirectory) {
dirEntries.push(e);
} else {
fileEntries.push(e);
}
});
// Create directory entries first synchronously
// this prevents race condition and assures folders are there before writing files
for (const entry of dirEntries) {
const dirPath = getPath(entry);
// The reverse operation for attr depend on method addFile()
const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
try {
filetools.makeDir(dirPath);
if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr);
// in unix timestamp will change if files are later added to folder, but still
filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);
} catch (er) {
callback(getError("Unable to create folder", dirPath));
}
}
fileEntries.reverse().reduce(function (next, entry) {
return function (err) {
if (err) {
next(err);
} else {
const entryName = pth.normalize(canonical(entry.entryName));
const filePath = sanitize(targetPath, entryName);
entry.getDataAsync(function (content, err_1) {
if (err_1) {
next(err_1);
} else if (!content) {
next(Utils.Errors.CANT_EXTRACT_FILE());
} else {
// The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {
if (!succ) {
next(getError("Unable to write file", filePath));
}
filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) {
if (err_2) {
next(getError("Unable to set times", filePath));
} else {
next();
}
});
});
}
});
}
};
}, callback)();
},
/**
* Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
*
* @param {string} targetFileName
* @param {function} callback
*/
writeZip: function (targetFileName, callback) {
if (arguments.length === 1) {
if (typeof targetFileName === "function") {
callback = targetFileName;
targetFileName = "";
}
}
if (!targetFileName && opts.filename) {
targetFileName = opts.filename;
}
if (!targetFileName) return;
var zipData = _zip.compressToBuffer();
if (zipData) {
var ok = filetools.writeFileTo(targetFileName, zipData, true);
if (typeof callback === "function") callback(!ok ? new Error("failed") : null, "");
}
},
/**
*
* @param {string} targetFileName
* @param {object} [props]
* @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true.
* @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true.
* @returns {Promise<void>}
*/
writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {
const { overwrite, perm } = Object.assign({ overwrite: true }, props);
return new Promise((resolve, reject) => {
// find file name
if (!targetFileName && opts.filename) targetFileName = opts.filename;
if (!targetFileName) reject("ADM-ZIP: ZIP File Name Missing");
this.toBufferPromise().then((zipData) => {
const ret = (done) => (done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file"));
filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);
}, reject);
});
},
/**
* @returns {Promise<Buffer>} A promise to the Buffer.
*/
toBufferPromise: function () {
return new Promise((resolve, reject) => {
_zip.toAsyncBuffer(resolve, reject);
});
},
/**
* Returns the content of the entire zip file as a Buffer object
*
* @prop {function} [onSuccess]
* @prop {function} [onFail]
* @prop {function} [onItemStart]
* @prop {function} [onItemEnd]
* @returns {Buffer}
*/
toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) {
if (typeof onSuccess === "function") {
_zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
return null;
}
return _zip.compressToBuffer();
}
};
};
-374
View File
@@ -1,374 +0,0 @@
var Utils = require("../util"),
Constants = Utils.Constants;
/* The central directory file header */
module.exports = function () {
var _verMade = 20, // v2.0
_version = 10, // v1.0
_flags = 0,
_method = 0,
_time = 0,
_crc = 0,
_compressedSize = 0,
_size = 0,
_fnameLen = 0,
_extraLen = 0,
_comLen = 0,
_diskStart = 0,
_inattr = 0,
_attr = 0,
_offset = 0;
_verMade |= Utils.isWin ? 0x0a00 : 0x0300;
// Set EFS flag since filename and comment fields are all by default encoded using UTF-8.
// Without it file names may be corrupted for other apps when file names use unicode chars
_flags |= Constants.FLG_EFS;
const _localHeader = {
extraLen: 0
};
// casting
const uint32 = (val) => Math.max(0, val) >>> 0;
const uint16 = (val) => Math.max(0, val) & 0xffff;
const uint8 = (val) => Math.max(0, val) & 0xff;
_time = Utils.fromDate2DOS(new Date());
return {
get made() {
return _verMade;
},
set made(val) {
_verMade = val;
},
get version() {
return _version;
},
set version(val) {
_version = val;
},
get flags() {
return _flags;
},
set flags(val) {
_flags = val;
},
get flags_efs() {
return (_flags & Constants.FLG_EFS) > 0;
},
set flags_efs(val) {
if (val) {
_flags |= Constants.FLG_EFS;
} else {
_flags &= ~Constants.FLG_EFS;
}
},
get flags_desc() {
return (_flags & Constants.FLG_DESC) > 0;
},
set flags_desc(val) {
if (val) {
_flags |= Constants.FLG_DESC;
} else {
_flags &= ~Constants.FLG_DESC;
}
},
get method() {
return _method;
},
set method(val) {
switch (val) {
case Constants.STORED:
this.version = 10;
case Constants.DEFLATED:
default:
this.version = 20;
}
_method = val;
},
get time() {
return Utils.fromDOS2Date(this.timeval);
},
set time(val) {
this.timeval = Utils.fromDate2DOS(val);
},
get timeval() {
return _time;
},
set timeval(val) {
_time = uint32(val);
},
get timeHighByte() {
return uint8(_time >>> 8);
},
get crc() {
return _crc;
},
set crc(val) {
_crc = uint32(val);
},
get compressedSize() {
return _compressedSize;
},
set compressedSize(val) {
_compressedSize = uint32(val);
},
get size() {
return _size;
},
set size(val) {
_size = uint32(val);
},
get fileNameLength() {
return _fnameLen;
},
set fileNameLength(val) {
_fnameLen = val;
},
get extraLength() {
return _extraLen;
},
set extraLength(val) {
_extraLen = val;
},
get extraLocalLength() {
return _localHeader.extraLen;
},
set extraLocalLength(val) {
_localHeader.extraLen = val;
},
get commentLength() {
return _comLen;
},
set commentLength(val) {
_comLen = val;
},
get diskNumStart() {
return _diskStart;
},
set diskNumStart(val) {
_diskStart = uint32(val);
},
get inAttr() {
return _inattr;
},
set inAttr(val) {
_inattr = uint32(val);
},
get attr() {
return _attr;
},
set attr(val) {
_attr = uint32(val);
},
// get Unix file permissions
get fileAttr() {
return (_attr || 0) >> 16 & 0xfff;
},
get offset() {
return _offset;
},
set offset(val) {
_offset = uint32(val);
},
get encrypted() {
return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;
},
get centralHeaderSize() {
return Constants.CENHDR + _fnameLen + _extraLen + _comLen;
},
get realDataOffset() {
return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen;
},
get localHeader() {
return _localHeader;
},
loadLocalHeaderFromBinary: function (/*Buffer*/ input) {
var data = input.slice(_offset, _offset + Constants.LOCHDR);
// 30 bytes and should start with "PK\003\004"
if (data.readUInt32LE(0) !== Constants.LOCSIG) {
throw Utils.Errors.INVALID_LOC();
}
// version needed to extract
_localHeader.version = data.readUInt16LE(Constants.LOCVER);
// general purpose bit flag
_localHeader.flags = data.readUInt16LE(Constants.LOCFLG);
// compression method
_localHeader.method = data.readUInt16LE(Constants.LOCHOW);
// modification time (2 bytes time, 2 bytes date)
_localHeader.time = data.readUInt32LE(Constants.LOCTIM);
// uncompressed file crc-32 valu
_localHeader.crc = data.readUInt32LE(Constants.LOCCRC);
// compressed size
_localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);
// uncompressed size
_localHeader.size = data.readUInt32LE(Constants.LOCLEN);
// filename length
_localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);
// extra field length
_localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);
// read extra data
const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;
const extraEnd = extraStart + _localHeader.extraLen;
return input.slice(extraStart, extraEnd);
},
loadFromBinary: function (/*Buffer*/ data) {
// data should be 46 bytes and start with "PK 01 02"
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
throw Utils.Errors.INVALID_CEN();
}
// version made by
_verMade = data.readUInt16LE(Constants.CENVEM);
// version needed to extract
_version = data.readUInt16LE(Constants.CENVER);
// encrypt, decrypt flags
_flags = data.readUInt16LE(Constants.CENFLG);
// compression method
_method = data.readUInt16LE(Constants.CENHOW);
// modification time (2 bytes time, 2 bytes date)
_time = data.readUInt32LE(Constants.CENTIM);
// uncompressed file crc-32 value
_crc = data.readUInt32LE(Constants.CENCRC);
// compressed size
_compressedSize = data.readUInt32LE(Constants.CENSIZ);
// uncompressed size
_size = data.readUInt32LE(Constants.CENLEN);
// filename length
_fnameLen = data.readUInt16LE(Constants.CENNAM);
// extra field length
_extraLen = data.readUInt16LE(Constants.CENEXT);
// file comment length
_comLen = data.readUInt16LE(Constants.CENCOM);
// volume number start
_diskStart = data.readUInt16LE(Constants.CENDSK);
// internal file attributes
_inattr = data.readUInt16LE(Constants.CENATT);
// external file attributes
_attr = data.readUInt32LE(Constants.CENATX);
// LOC header offset
_offset = data.readUInt32LE(Constants.CENOFF);
},
localHeaderToBinary: function () {
// LOC header size (30 bytes)
var data = Buffer.alloc(Constants.LOCHDR);
// "PK\003\004"
data.writeUInt32LE(Constants.LOCSIG, 0);
// version needed to extract
data.writeUInt16LE(_version, Constants.LOCVER);
// general purpose bit flag
data.writeUInt16LE(_flags, Constants.LOCFLG);
// compression method
data.writeUInt16LE(_method, Constants.LOCHOW);
// modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.LOCTIM);
// uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.LOCCRC);
// compressed size
data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);
// uncompressed size
data.writeUInt32LE(_size, Constants.LOCLEN);
// filename length
data.writeUInt16LE(_fnameLen, Constants.LOCNAM);
// extra field length
data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);
return data;
},
centralHeaderToBinary: function () {
// CEN header size (46 bytes)
var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);
// "PK\001\002"
data.writeUInt32LE(Constants.CENSIG, 0);
// version made by
data.writeUInt16LE(_verMade, Constants.CENVEM);
// version needed to extract
data.writeUInt16LE(_version, Constants.CENVER);
// encrypt, decrypt flags
data.writeUInt16LE(_flags, Constants.CENFLG);
// compression method
data.writeUInt16LE(_method, Constants.CENHOW);
// modification time (2 bytes time, 2 bytes date)
data.writeUInt32LE(_time, Constants.CENTIM);
// uncompressed file crc-32 value
data.writeUInt32LE(_crc, Constants.CENCRC);
// compressed size
data.writeUInt32LE(_compressedSize, Constants.CENSIZ);
// uncompressed size
data.writeUInt32LE(_size, Constants.CENLEN);
// filename length
data.writeUInt16LE(_fnameLen, Constants.CENNAM);
// extra field length
data.writeUInt16LE(_extraLen, Constants.CENEXT);
// file comment length
data.writeUInt16LE(_comLen, Constants.CENCOM);
// volume number start
data.writeUInt16LE(_diskStart, Constants.CENDSK);
// internal file attributes
data.writeUInt16LE(_inattr, Constants.CENATT);
// external file attributes
data.writeUInt32LE(_attr, Constants.CENATX);
// LOC header offset
data.writeUInt32LE(_offset, Constants.CENOFF);
return data;
},
toJSON: function () {
const bytes = function (nr) {
return nr + " bytes";
};
return {
made: _verMade,
version: _version,
flags: _flags,
method: Utils.methodToString(_method),
time: this.time,
crc: "0x" + _crc.toString(16).toUpperCase(),
compressedSize: bytes(_compressedSize),
size: bytes(_size),
fileNameLength: bytes(_fnameLen),
extraLength: bytes(_extraLen),
commentLength: bytes(_comLen),
diskNumStart: _diskStart,
inAttr: _inattr,
attr: _attr,
offset: _offset,
centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)
};
},
toString: function () {
return JSON.stringify(this.toJSON(), null, "\t");
}
};
};

Some files were not shown because too many files have changed in this diff Show More