pax_global_header00006660000000000000000000000064143441741360014521gustar00rootroot0000000000000052 comment=772c49b6639629ab786b68d1530457971f7f34fb cacache-17.0.3/000077500000000000000000000000001434417413600131605ustar00rootroot00000000000000cacache-17.0.3/.commitlintrc.js000066400000000000000000000005531434417413600163030ustar00rootroot00000000000000/* This file is automatically added by @npmcli/template-oss. Do not edit. */ module.exports = { extends: ['@commitlint/config-conventional'], rules: { 'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'deps', 'chore']], 'header-max-length': [2, 'always', 80], 'subject-case': [0, 'always', ['lower-case', 'sentence-case', 'start-case']], }, } cacache-17.0.3/.eslintrc.js000066400000000000000000000005451434417413600154230ustar00rootroot00000000000000/* This file is automatically added by @npmcli/template-oss. Do not edit. */ 'use strict' const { readdirSync: readdir } = require('fs') const localConfigs = readdir(__dirname) .filter((file) => file.startsWith('.eslintrc.local.')) .map((file) => `./${file}`) module.exports = { root: true, extends: [ '@npmcli', ...localConfigs, ], } cacache-17.0.3/.eslintrc.local.js000066400000000000000000000001631434417413600165100ustar00rootroot00000000000000'use strict' module.exports = { rules: { strict: 'error', 'no-shadow': 0, // XXX: fix this later }, } cacache-17.0.3/.github/000077500000000000000000000000001434417413600145205ustar00rootroot00000000000000cacache-17.0.3/.github/CODEOWNERS000066400000000000000000000001321434417413600161070ustar00rootroot00000000000000# This file is automatically added by @npmcli/template-oss. Do not edit. * @npm/cli-team cacache-17.0.3/.github/ISSUE_TEMPLATE/000077500000000000000000000000001434417413600167035ustar00rootroot00000000000000cacache-17.0.3/.github/ISSUE_TEMPLATE/bug.yml000066400000000000000000000026551434417413600202130ustar00rootroot00000000000000# This file is automatically added by @npmcli/template-oss. Do not edit. name: Bug description: File a bug/issue title: "[BUG] " labels: [ Bug, Needs Triage ] body: - type: checkboxes attributes: label: Is there an existing issue for this? description: Please [search here](./issues) to see if an issue already exists for your problem. options: - label: I have searched the existing issues required: true - type: textarea attributes: label: Current Behavior description: A clear & concise description of what you're experiencing. validations: required: false - type: textarea attributes: label: Expected Behavior description: A clear & concise description of what you expected to happen. validations: required: false - type: textarea attributes: label: Steps To Reproduce description: Steps to reproduce the behavior. value: | 1. In this environment... 2. With this config... 3. Run '...' 4. See error... validations: required: false - type: textarea attributes: label: Environment description: | examples: - **npm**: 7.6.3 - **Node**: 13.14.0 - **OS**: Ubuntu 20.04 - **platform**: Macbook Pro value: | - npm: - Node: - OS: - platform: validations: required: false �����������������������������������������������������������������������������������cacache-17.0.3/.github/ISSUE_TEMPLATE/config.yml����������������������������������������������������0000664�0000000�0000000�00000000145�14344174136�0020673�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. blank_issues_enabled: true ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/dependabot.yml���������������������������������������������������������������0000664�0000000�0000000�00000000563�14344174136�0017354�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. version: 2 updates: - package-ecosystem: npm directory: / schedule: interval: daily allow: - dependency-type: direct versioning-strategy: increase-if-necessary commit-message: prefix: deps prefix-development: chore labels: - "Dependencies" ���������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/matchers/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0016326�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/matchers/tap.json������������������������������������������������������������0000664�0000000�0000000�00000001204�14344174136�0020002�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "//@npmcli/template-oss": "This file is automatically added by @npmcli/template-oss. Do not edit.", "problemMatcher": [ { "owner": "tap", "pattern": [ { "regexp": "^\\s*not ok \\d+ - (.*)", "message": 1 }, { "regexp": "^\\s*---" }, { "regexp": "^\\s*at:" }, { "regexp": "^\\s*line:\\s*(\\d+)", "line": 1 }, { "regexp": "^\\s*column:\\s*(\\d+)", "column": 1 }, { "regexp": "^\\s*file:\\s*(.*)", "file": 1 } ] } ] } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/settings.yml�����������������������������������������������������������������0000664�0000000�0000000�00000000055�14344174136�0017103�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������--- _extends: '.github:npm-cli/settings.yml' �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/�������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0016555�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/audit.yml����������������������������������������������������������0000664�0000000�0000000�00000002132�14344174136�0020404�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: Audit on: workflow_dispatch: schedule: # "At 08:00 UTC (01:00 PT) on Monday" https://crontab.guru/#0_8_*_*_1 - cron: "0 8 * * 1" jobs: audit: name: Audit Dependencies if: github.repository_owner == 'npm' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund --package-lock - name: Run Production Audit run: npm audit --omit=dev - name: Run Full Audit run: npm audit --audit-level=none ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/ci-release.yml�����������������������������������������������������0000664�0000000�0000000�00000015376�14344174136�0021325�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: CI - Release on: workflow_dispatch: inputs: ref: required: true type: string default: main workflow_call: inputs: ref: required: true type: string check-sha: required: true type: string jobs: lint-all: name: Lint All if: github.repository_owner == 'npm' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Get Workflow Job uses: actions/github-script@v6 if: inputs.check-sha id: check-output env: JOB_NAME: "Lint All" MATRIX_NAME: "" with: script: | const { owner, repo } = context.repo const { data } = await github.rest.actions.listJobsForWorkflowRun({ owner, repo, run_id: context.runId, per_page: 100 }) const jobName = process.env.JOB_NAME + process.env.MATRIX_NAME const job = data.jobs.find(j => j.name.endsWith(jobName)) const jobUrl = job?.html_url const shaUrl = `${context.serverUrl}/${owner}/${repo}/commit/${{ inputs.check-sha }}` let summary = `This check is assosciated with ${shaUrl}\n\n` if (jobUrl) { summary += `For run logs, click here: ${jobUrl}` } else { summary += `Run logs could not be found for a job with name: "${jobName}"` } return { summary } - name: Create Check uses: LouisBrunner/checks-action@v1.3.1 id: check if: inputs.check-sha with: token: ${{ secrets.GITHUB_TOKEN }} status: in_progress name: Lint All sha: ${{ inputs.check-sha }} output: ${{ steps.check-output.outputs.result }} - name: Checkout uses: actions/checkout@v3 with: ref: ${{ inputs.ref }} - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Lint run: npm run lint --ignore-scripts - name: Post Lint run: npm run postlint --ignore-scripts - name: Conclude Check uses: LouisBrunner/checks-action@v1.3.1 if: steps.check.outputs.check_id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ job.status }} check_id: ${{ steps.check.outputs.check_id }} test-all: name: Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }} if: github.repository_owner == 'npm' strategy: fail-fast: false matrix: platform: - name: Linux os: ubuntu-latest shell: bash - name: macOS os: macos-latest shell: bash node-version: - 14.17.0 - 14.x - 16.13.0 - 16.x - 18.0.0 - 18.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Get Workflow Job uses: actions/github-script@v6 if: inputs.check-sha id: check-output env: JOB_NAME: "Test All" MATRIX_NAME: " - ${{ matrix.platform.name }} - ${{ matrix.node-version }}" with: script: | const { owner, repo } = context.repo const { data } = await github.rest.actions.listJobsForWorkflowRun({ owner, repo, run_id: context.runId, per_page: 100 }) const jobName = process.env.JOB_NAME + process.env.MATRIX_NAME const job = data.jobs.find(j => j.name.endsWith(jobName)) const jobUrl = job?.html_url const shaUrl = `${context.serverUrl}/${owner}/${repo}/commit/${{ inputs.check-sha }}` let summary = `This check is assosciated with ${shaUrl}\n\n` if (jobUrl) { summary += `For run logs, click here: ${jobUrl}` } else { summary += `Run logs could not be found for a job with name: "${jobName}"` } return { summary } - name: Create Check uses: LouisBrunner/checks-action@v1.3.1 id: check if: inputs.check-sha with: token: ${{ secrets.GITHUB_TOKEN }} status: in_progress name: Test All - ${{ matrix.platform.name }} - ${{ matrix.node-version }} sha: ${{ inputs.check-sha }} output: ${{ steps.check-output.outputs.result }} - name: Checkout uses: actions/checkout@v3 with: ref: ${{ inputs.ref }} - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Update Windows npm # node 12 and 14 ship with npm@6, which is known to fail when updating itself in windows if: matrix.platform.os == 'windows-latest' && (startsWith(matrix.node-version, '12.') || startsWith(matrix.node-version, '14.')) run: | curl -sO https://registry.npmjs.org/npm/-/npm-7.5.4.tgz tar xf npm-7.5.4.tgz cd package node lib/npm.js install --no-fund --no-audit -g ..\npm-7.5.4.tgz cd .. rmdir /s /q package - name: Install npm@7 if: startsWith(matrix.node-version, '10.') run: npm i --prefer-online --no-fund --no-audit -g npm@7 - name: Install npm@latest if: ${{ !startsWith(matrix.node-version, '10.') }} run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test run: npm test --ignore-scripts - name: Conclude Check uses: LouisBrunner/checks-action@v1.3.1 if: steps.check.outputs.check_id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ job.status }} check_id: ${{ steps.check.outputs.check_id }} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/ci.yml�������������������������������������������������������������0000664�0000000�0000000�00000006206�14344174136�0017677�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: CI on: workflow_dispatch: pull_request: push: branches: - main - latest schedule: # "At 09:00 UTC (02:00 PT) on Monday" https://crontab.guru/#0_9_*_*_1 - cron: "0 9 * * 1" jobs: lint: name: Lint if: github.repository_owner == 'npm' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Lint run: npm run lint --ignore-scripts - name: Post Lint run: npm run postlint --ignore-scripts test: name: Test - ${{ matrix.platform.name }} - ${{ matrix.node-version }} if: github.repository_owner == 'npm' strategy: fail-fast: false matrix: platform: - name: Linux os: ubuntu-latest shell: bash - name: macOS os: macos-latest shell: bash node-version: - 14.17.0 - 14.x - 16.13.0 - 16.x - 18.0.0 - 18.x runs-on: ${{ matrix.platform.os }} defaults: run: shell: ${{ matrix.platform.shell }} steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Update Windows npm # node 12 and 14 ship with npm@6, which is known to fail when updating itself in windows if: matrix.platform.os == 'windows-latest' && (startsWith(matrix.node-version, '12.') || startsWith(matrix.node-version, '14.')) run: | curl -sO https://registry.npmjs.org/npm/-/npm-7.5.4.tgz tar xf npm-7.5.4.tgz cd package node lib/npm.js install --no-fund --no-audit -g ..\npm-7.5.4.tgz cd .. rmdir /s /q package - name: Install npm@7 if: startsWith(matrix.node-version, '10.') run: npm i --prefer-online --no-fund --no-audit -g npm@7 - name: Install npm@latest if: ${{ !startsWith(matrix.node-version, '10.') }} run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Add Problem Matcher run: echo "::add-matcher::.github/matchers/tap.json" - name: Test run: npm test --ignore-scripts ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/codeql-analysis.yml������������������������������������������������0000664�0000000�0000000�00000001605�14344174136�0022372�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: CodeQL on: push: branches: - main - latest pull_request: branches: - main - latest schedule: # "At 10:00 UTC (03:00 PT) on Monday" https://crontab.guru/#0_10_*_*_1 - cron: "0 10 * * 1" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: javascript - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 ���������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/post-dependabot.yml������������������������������������������������0000664�0000000�0000000�00000011633�14344174136�0022374�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: Post Dependabot on: pull_request permissions: contents: write jobs: template-oss: name: template-oss if: github.repository_owner == 'npm' && github.actor == 'dependabot[bot]' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 with: ref: ${{ github.event.pull_request.head.ref }} - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Fetch Dependabot Metadata id: metadata uses: dependabot/fetch-metadata@v1 with: github-token: ${{ secrets.GITHUB_TOKEN }} # Dependabot can update multiple directories so we output which directory # it is acting on so we can run the command for the correct root or workspace - name: Get Dependabot Directory if: contains(steps.metadata.outputs.dependency-names, '@npmcli/template-oss') id: flags run: | dependabot_dir="${{ steps.metadata.outputs.directory }}" if [[ "$dependabot_dir" == "/" ]]; then echo "::set-output name=workspace::-iwr" else # strip leading slash from directory so it works as a # a path to the workspace flag echo "::set-output name=workspace::-w ${dependabot_dir#/}" fi - name: Apply Changes if: steps.flags.outputs.workspace id: apply run: | npm run template-oss-apply ${{ steps.flags.outputs.workspace }} if [[ `git status --porcelain` ]]; then echo "::set-output name=changes::true" fi # This only sets the conventional commit prefix. This workflow can't reliably determine # what the breaking change is though. If a BREAKING CHANGE message is required then # this PR check will fail and the commit will be amended with stafftools if [[ "${{ steps.metadata.outputs.update-type }}" == "version-update:semver-major" ]]; then prefix='feat!' else prefix='chore' fi echo "::set-output name=message::$prefix: postinstall for dependabot template-oss PR" # This step will fail if template-oss has made any workflow updates. It is impossible # for a workflow to update other workflows. In the case it does fail, we continue # and then try to apply only a portion of the changes in the next step - name: Push All Changes if: steps.apply.outputs.changes id: push continue-on-error: true env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | git commit -am "${{ steps.apply.outputs.message }}" git push # If the previous step failed, then reset the commit and remove any workflow changes # and attempt to commit and push again. This is helpful because we will have a commit # with the correct prefix that we can then --amend with @npmcli/stafftools later. - name: Push All Changes Except Workflows if: steps.apply.outputs.changes && steps.push.outcome == 'failure' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | git reset HEAD~ git checkout HEAD -- .github/workflows/ git clean -fd .github/workflows/ git commit -am "${{ steps.apply.outputs.message }}" git push # Check if all the necessary template-oss changes were applied. Since we continued # on errors in one of the previous steps, this check will fail if our follow up # only applied a portion of the changes and we need to followup manually. # # Note that this used to run `lint` and `postlint` but that will fail this action # if we've also shipped any linting changes separate from template-oss. We do # linting in another action, so we want to fail this one only if there are # template-oss changes that could not be applied. - name: Check Changes if: steps.apply.outputs.changes run: | npm exec --offline ${{ steps.flags.outputs.workspace }} -- template-oss-check - name: Fail on Breaking Change if: steps.apply.outputs.changes && startsWith(steps.apply.outputs.message, 'feat!') run: | echo "This PR has a breaking change. Run 'npx -p @npmcli/stafftools gh template-oss-fix'" echo "for more information on how to fix this with a BREAKING CHANGE footer." exit 1 �����������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/pull-request.yml���������������������������������������������������0000664�0000000�0000000�00000002545�14344174136�0021750�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: Pull Request on: pull_request: types: - opened - reopened - edited - synchronize jobs: commitlint: name: Lint Commits if: github.repository_owner == 'npm' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Run Commitlint on Commits id: commit continue-on-error: true run: | npx --offline commitlint -V --from origin/${{ github.base_ref }} --to ${{ github.event.pull_request.head.sha }} - name: Run Commitlint on PR Title if: steps.commit.outcome == 'failure' run: | echo ${{ github.event.pull_request.title }} | npx --offline commitlint -V �����������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.github/workflows/release.yml��������������������������������������������������������0000664�0000000�0000000�00000024113�14344174136�0020721�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. name: Release on: workflow_dispatch: push: branches: - main - latest - release/v* permissions: contents: write pull-requests: write checks: write jobs: release: outputs: pr: ${{ steps.release.outputs.pr }} releases: ${{ steps.release.outputs.releases }} release-flags: ${{ steps.release.outputs.release-flags }} branch: ${{ steps.release.outputs.pr-branch }} pr-number: ${{ steps.release.outputs.pr-number }} comment-id: ${{ steps.pr-comment.outputs.result }} check-id: ${{ steps.check.outputs.check_id }} name: Release if: github.repository_owner == 'npm' runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Release Please id: release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | npx --offline template-oss-release-please ${{ github.ref_name }} ${{ github.event_name }} - name: Post Pull Request Comment if: steps.release.outputs.pr-number uses: actions/github-script@v6 id: pr-comment env: PR_NUMBER: ${{ steps.release.outputs.pr-number }} REF_NAME: ${{ github.ref_name }} with: script: | const { REF_NAME, PR_NUMBER } = process.env const repo = { owner: context.repo.owner, repo: context.repo.repo } const issue = { ...repo, issue_number: PR_NUMBER } const { data: workflow } = await github.rest.actions.getWorkflowRun({ ...repo, run_id: context.runId }) let body = '## Release Manager\n\n' const comments = await github.paginate(github.rest.issues.listComments, issue) let commentId = comments?.find(c => c.user.login === 'github-actions[bot]' && c.body.startsWith(body))?.id body += `Release workflow run: ${workflow.html_url}\n\n#### Force CI to Update This Release\n\n` body += `This PR will be updated and CI will run for every non-\`chore:\` commit that is pushed to \`main\`. ` body += `To force CI to update this PR, run this command:\n\n` body += `\`\`\`\ngh workflow run release.yml -r ${REF_NAME}\n\`\`\`` if (commentId) { await github.rest.issues.updateComment({ ...repo, comment_id: commentId, body }) } else { const { data: comment } = await github.rest.issues.createComment({ ...issue, body }) commentId = comment?.id } return commentId - name: Get Workflow Job uses: actions/github-script@v6 if: steps.release.outputs.pr-sha id: check-output env: JOB_NAME: "Release" MATRIX_NAME: "" with: script: | const { owner, repo } = context.repo const { data } = await github.rest.actions.listJobsForWorkflowRun({ owner, repo, run_id: context.runId, per_page: 100 }) const jobName = process.env.JOB_NAME + process.env.MATRIX_NAME const job = data.jobs.find(j => j.name.endsWith(jobName)) const jobUrl = job?.html_url const shaUrl = `${context.serverUrl}/${owner}/${repo}/commit/${{ steps.release.outputs.pr-sha }}` let summary = `This check is assosciated with ${shaUrl}\n\n` if (jobUrl) { summary += `For run logs, click here: ${jobUrl}` } else { summary += `Run logs could not be found for a job with name: "${jobName}"` } return { summary } - name: Create Check uses: LouisBrunner/checks-action@v1.3.1 id: check if: steps.release.outputs.pr-sha with: token: ${{ secrets.GITHUB_TOKEN }} status: in_progress name: Release sha: ${{ steps.release.outputs.pr-sha }} output: ${{ steps.check-output.outputs.result }} update: needs: release outputs: sha: ${{ steps.commit.outputs.sha }} check-id: ${{ steps.check.outputs.check_id }} name: Update - Release if: github.repository_owner == 'npm' && needs.release.outputs.pr runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 ref: ${{ needs.release.outputs.branch }} - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Run Post Pull Request Actions env: RELEASE_PR_NUMBER: ${{ needs.release.outputs.pr-number }} RELEASE_COMMENT_ID: ${{ needs.release.outputs.comment-id }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | npm exec --offline -- template-oss-release-manager --lockfile=false npm run rp-pull-request --ignore-scripts --if-present - name: Commit id: commit env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | git commit --all --amend --no-edit || true git push --force-with-lease echo "::set-output name=sha::$(git rev-parse HEAD)" - name: Get Workflow Job uses: actions/github-script@v6 if: steps.commit.outputs.sha id: check-output env: JOB_NAME: "Update - Release" MATRIX_NAME: "" with: script: | const { owner, repo } = context.repo const { data } = await github.rest.actions.listJobsForWorkflowRun({ owner, repo, run_id: context.runId, per_page: 100 }) const jobName = process.env.JOB_NAME + process.env.MATRIX_NAME const job = data.jobs.find(j => j.name.endsWith(jobName)) const jobUrl = job?.html_url const shaUrl = `${context.serverUrl}/${owner}/${repo}/commit/${{ steps.commit.outputs.sha }}` let summary = `This check is assosciated with ${shaUrl}\n\n` if (jobUrl) { summary += `For run logs, click here: ${jobUrl}` } else { summary += `Run logs could not be found for a job with name: "${jobName}"` } return { summary } - name: Create Check uses: LouisBrunner/checks-action@v1.3.1 id: check if: steps.commit.outputs.sha with: token: ${{ secrets.GITHUB_TOKEN }} status: in_progress name: Release sha: ${{ steps.commit.outputs.sha }} output: ${{ steps.check-output.outputs.result }} - name: Conclude Check uses: LouisBrunner/checks-action@v1.3.1 if: needs.release.outputs.check-id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ job.status }} check_id: ${{ needs.release.outputs.check-id }} ci: name: CI - Release needs: [ release, update ] if: needs.release.outputs.pr uses: ./.github/workflows/ci-release.yml with: ref: ${{ needs.release.outputs.branch }} check-sha: ${{ needs.update.outputs.sha }} post-ci: needs: [ release, update, ci ] name: Post CI - Release if: github.repository_owner == 'npm' && needs.release.outputs.pr && always() runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Get Needs Result id: needs-result run: | result="" if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]]; then result="failure" elif [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then result="cancelled" else result="success" fi echo "::set-output name=result::$result" - name: Conclude Check uses: LouisBrunner/checks-action@v1.3.1 if: needs.update.outputs.check-id && always() with: token: ${{ secrets.GITHUB_TOKEN }} conclusion: ${{ steps.needs-result.outputs.result }} check_id: ${{ needs.update.outputs.check-id }} post-release: needs: release name: Post Release - Release if: github.repository_owner == 'npm' && needs.release.outputs.releases runs-on: ubuntu-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 - name: Setup Git User run: | git config --global user.email "npm-cli+bot@github.com" git config --global user.name "npm CLI robot" - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18.x - name: Install npm@latest run: npm i --prefer-online --no-fund --no-audit -g npm@latest - name: npm Version run: npm -v - name: Install Dependencies run: npm i --ignore-scripts --no-audit --no-fund - name: Run Post Release Actions env: RELEASES: ${{ needs.release.outputs.releases }} run: | npm run rp-release --ignore-scripts --if-present ${{ join(fromJSON(needs.release.outputs.release-flags), ' ') }} �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.gitignore���������������������������������������������������������������������������0000664�0000000�0000000�00000000665�14344174136�0015157�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# This file is automatically added by @npmcli/template-oss. Do not edit. # ignore everything in the root /* # keep these !**/.gitignore !/.commitlintrc.js !/.eslintrc.js !/.eslintrc.local.* !/.github/ !/.gitignore !/.npmrc !/.release-please-manifest.json !/bin/ !/CHANGELOG* !/CODE_OF_CONDUCT.md !/docs/ !/lib/ !/LICENSE* !/map.js !/package.json !/README* !/release-please-config.json !/scripts/ !/SECURITY.md !/tap-snapshots/ !/test/ ���������������������������������������������������������������������������cacache-17.0.3/.npmrc�������������������������������������������������������������������������������0000664�0000000�0000000�00000000135�14344174136�0014277�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������; This file is automatically added by @npmcli/template-oss. Do not edit. package-lock=false �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/.release-please-manifest.json��������������������������������������������������������0000664�0000000�0000000�00000000024�14344174136�0020620�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ ".": "17.0.3" } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/CHANGELOG.md�������������������������������������������������������������������������0000664�0000000�0000000�00000111431�14344174136�0014772�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# Changelog ## [17.0.3](https://github.com/npm/cacache/compare/v17.0.2...v17.0.3) (2022-12-07) ### Dependencies * [`0dc98f7`](https://github.com/npm/cacache/commit/0dc98f7ca0940ea010ef3ba5257887e36083b3a2) [#156](https://github.com/npm/cacache/pull/156) bump minipass from 3.3.6 to 4.0.0 ## [17.0.2](https://github.com/npm/cacache/compare/v17.0.1...v17.0.2) (2022-11-04) ### Bug Fixes * [`4a7382f`](https://github.com/npm/cacache/commit/4a7382f5e6c72c59587d45167346c1b6e81a3cde) [#152](https://github.com/npm/cacache/pull/152) replace @npmcli/move-file with @npmcli/fs (@lukekarrys) ## [17.0.1](https://github.com/npm/cacache/compare/v17.0.0...v17.0.1) (2022-10-17) ### Dependencies * [`d3515de`](https://github.com/npm/cacache/commit/d3515dec8ee6305d564389f5e52363637666f718) [#146](https://github.com/npm/cacache/pull/146) bump unique-filename from 2.0.1 to 3.0.0 * [`e57ebd9`](https://github.com/npm/cacache/commit/e57ebd9edcd4ac93df7ccbe1eee66a7a2c41c0a7) [#143](https://github.com/npm/cacache/pull/143) bump ssri from 9.0.1 to 10.0.0 * [`9dd537a`](https://github.com/npm/cacache/commit/9dd537a5ab53f5f84e16ff9e69ebd9f28e3f8c54) [#144](https://github.com/npm/cacache/pull/144) bump @npmcli/move-file from 2.0.1 to 3.0.0 ## [17.0.0](https://github.com/npm/cacache/compare/v16.1.3...v17.0.0) (2022-10-13) ### ⚠️ BREAKING CHANGES * this module no longer attempts to change file ownership automatically * this package is now async only, all synchronous methods have been removed * `cacache` is now compatible with the following semver range for node: `^14.17.0 || ^16.13.0 || >=18.0.0` ### Features * [`479b135`](https://github.com/npm/cacache/commit/479b1352a72ea3a6bc403545e269d3add985c6ee) [#141](https://github.com/npm/cacache/pull/141) do not alter file ownership (#141) (@nlf) * [`f57bb4d`](https://github.com/npm/cacache/commit/f57bb4d3ec6147843fac673c6578c3d231f336df) [#140](https://github.com/npm/cacache/pull/140) remove sync methods (#140) (@nlf) * [`cfebcde`](https://github.com/npm/cacache/commit/cfebcdea59e3fc1ff33fbe4b3fa6f05aa765326f) [#133](https://github.com/npm/cacache/pull/133) postinstall for dependabot template-oss PR (@lukekarrys) ## [16.1.3](https://github.com/npm/cacache/compare/v16.1.2...v16.1.3) (2022-08-23) ### Dependencies * bump unique-filename from 1.1.1 to 2.0.0 ([#123](https://github.com/npm/cacache/issues/123)) ([6235554](https://github.com/npm/cacache/commit/6235554e46d19a9d9af25f87aa797fb85efc9519)) ## [16.1.2](https://github.com/npm/cacache/compare/v16.1.1...v16.1.2) (2022-08-15) ### Bug Fixes * linting ([#121](https://github.com/npm/cacache/issues/121)) ([a683cff](https://github.com/npm/cacache/commit/a683cffdfd956e1a4ac0e5ccbfa30615192e1ea0)) ## [16.1.1](https://github.com/npm/cacache/compare/v16.1.0...v16.1.1) (2022-06-02) ### Bug Fixes * **read:** change lstat to stat to correctly evaluate file size ([#114](https://github.com/npm/cacache/issues/114)) ([e3a2928](https://github.com/npm/cacache/commit/e3a2928e053e19fb6e8e73946ffe3d212e402ba7)) ## [16.1.0](https://github.com/npm/cacache/compare/v16.0.7...v16.1.0) (2022-05-17) ### Features * allow external integrity/size source ([#110](https://github.com/npm/cacache/issues/110)) ([61785e1](https://github.com/npm/cacache/commit/61785e106765f4b44041de318f6e387d93759e60)) ### Bug Fixes * move to async functions where possible ([#106](https://github.com/npm/cacache/issues/106)) ([71d4389](https://github.com/npm/cacache/commit/71d4389ff8a35330c3fedce97761094e243d4faf)) ### [16.0.7](https://github.com/npm/cacache/compare/v16.0.6...v16.0.7) (2022-04-27) ### Bug Fixes * **put:** don't flush if an error happened ([e870016](https://github.com/npm/cacache/commit/e8700167e036f392e5554af2d582caa17e4e7237)) * remove disposer ([76ab648](https://github.com/npm/cacache/commit/76ab64857b6874bc54d542ddd483c526434c0b9b)) * remove fs.copyFile checks ([90776fd](https://github.com/npm/cacache/commit/90776fd4a6c5362ea56a979b9611bdf4391e1fd8)) ### [16.0.6](https://github.com/npm/cacache/compare/v16.0.5...v16.0.6) (2022-04-21) ### Bug Fixes * normalize win32 paths before globbing ([4bdd5d5](https://github.com/npm/cacache/commit/4bdd5d5ce21147d67a46b6d2e1ec65007b31705c)) ### [16.0.5](https://github.com/npm/cacache/compare/v16.0.4...v16.0.5) (2022-04-20) ### Dependencies * bump glob from 7.2.0 to 8.0.1 ([#98](https://github.com/npm/cacache/issues/98)) ([74a11f9](https://github.com/npm/cacache/commit/74a11f9f5a1543d593217078a5357707680e2bb1)) ### [16.0.4](https://github.com/npm/cacache/compare/v16.0.3...v16.0.4) (2022-04-05) ### Dependencies * bump @npmcli/move-file from 1.1.2 to 2.0.0 ([#94](https://github.com/npm/cacache/issues/94)) ([f3d64f6](https://github.com/npm/cacache/commit/f3d64f6c238f99433df260fe52081177bdedee86)) * bump ssri from 8.0.1 to 9.0.0 ([#95](https://github.com/npm/cacache/issues/95)) ([fb44f5f](https://github.com/npm/cacache/commit/fb44f5f6bf85f9ee45ba52eb63088b108eca076d)) ### [16.0.3](https://github.com/npm/cacache/compare/v16.0.2...v16.0.3) (2022-03-22) ### Dependencies * bump @npmcli/fs from 1.1.1 to 2.1.0 ([#88](https://github.com/npm/cacache/issues/88)) ([9c9c91c](https://github.com/npm/cacache/commit/9c9c91ce13b941a12c73b95940c5d0b4f4dbf3d0)) * update lru-cache requirement from ^7.5.1 to ^7.7.1 ([#87](https://github.com/npm/cacache/issues/87)) ([800079f](https://github.com/npm/cacache/commit/800079fc5fd18e624bcc53dae3b5f432033e1096)) ### [16.0.2](https://www.github.com/npm/cacache/compare/v16.0.1...v16.0.2) (2022-03-16) ### Bug Fixes * use lru-cache.clear ([#80](https://www.github.com/npm/cacache/issues/80)) ([a48e020](https://www.github.com/npm/cacache/commit/a48e020ca86d28a569578617cc4c7efb76aa8194)) ### [16.0.1](https://www.github.com/npm/cacache/compare/v16.0.0...v16.0.1) (2022-03-15) ### Dependencies * bump lru-cache from 6.0.0 to 7.5.1 ([#77](https://www.github.com/npm/cacache/issues/77)) ([6a3a886](https://www.github.com/npm/cacache/commit/6a3a8863f079aaccb623c4f8d933c485b82e0671)) * update glob requirement from ^7.1.4 to ^7.2.0 ([#74](https://www.github.com/npm/cacache/issues/74)) ([27f1a63](https://www.github.com/npm/cacache/commit/27f1a63cc14de34585330c7ad50f5ae00b3b5b54)) * update minipass requirement from ^3.1.1 to ^3.1.6 ([#76](https://www.github.com/npm/cacache/issues/76)) ([954a430](https://www.github.com/npm/cacache/commit/954a43056fd01ca3a359581dfe32cdfd0ada5f8d)) ## [16.0.0](https://www.github.com/npm/cacache/compare/v15.3.0...v16.0.0) (2022-03-14) ### ⚠ BREAKING CHANGES * this drops support for node10 and non-LTS versions of node12 and node14. ### Bug Fixes * move files to lib ([cfa4a79](https://www.github.com/npm/cacache/commit/cfa4a7974e1a2b4c4d00613afe20b1925fbe639a)) ### Dependencies * @npmcli/template-oss@2.9.2 ([6e051a7](https://www.github.com/npm/cacache/commit/6e051a782e18288c51914562ae93b4ce52a81ad1)) * update @npmcli/move-file requirement from ^1.0.1 to ^1.1.2 ([#70](https://www.github.com/npm/cacache/issues/70)) ([ddf797a](https://www.github.com/npm/cacache/commit/ddf797a1906e2b285165e544d5ae29a4bb1514ef)) * update fs-minipass requirement from ^2.0.0 to ^2.1.0 ([#72](https://www.github.com/npm/cacache/issues/72)) ([07a5aa1](https://www.github.com/npm/cacache/commit/07a5aa17a8d2245d69f613f9351d4cf84865ade8)) * update minipass-pipeline requirement from ^1.2.2 to ^1.2.4 ([#69](https://www.github.com/npm/cacache/issues/69)) ([372d1a1](https://www.github.com/npm/cacache/commit/372d1a1533aaa8ea37c4cb98f99f40461c9bddac)) * update mkdirp requirement from ^1.0.3 to ^1.0.4 ([#73](https://www.github.com/npm/cacache/issues/73)) ([5fbd50f](https://www.github.com/npm/cacache/commit/5fbd50f1000e8065d754a7c8c89c1c9747532618)) * update tar requirement from ^6.0.2 to ^6.1.11 ([#71](https://www.github.com/npm/cacache/issues/71)) ([4d35625](https://www.github.com/npm/cacache/commit/4d3562565dc52fe51cc5de2fbffceddb63f65118)) ## [15.2.0](https://github.com/npm/cacache/releases/v15.2.0) (2021-05-25) * [8892a92](https://github.com/npm/cacache/commit/8892a92) add a validateEntry option to compact * [460b951](https://github.com/npm/cacache/commit/460b951) allow fully deleting indexes ## [15.1.0](https://github.com/npm/cacache/compare/v15.0.6...v15.1.0) (2021-05-19) ### Features * allow formatEntry to keep entries with no integrity value ([930f531](https://github.com/npm/cacache/commit/930f5313825a84277c531defe53696b8c9f4ef70)), closes [#53](https://github.com/npm/cacache/issues/53) * expose index.insert, implement and expose index.compact ([c4efb74](https://github.com/npm/cacache/commit/c4efb7427cd40694933a46ef3eb59d32ce4d0eed)) ### [15.0.6](https://github.com/npm/cacache/compare/v15.0.5...v15.0.6) (2021-03-22) ### [15.0.5](https://github.com/npm/cacache/compare/v15.0.4...v15.0.5) (2020-07-11) ### [15.0.4](https://github.com/npm/cacache/compare/v15.0.3...v15.0.4) (2020-06-03) ### Bug Fixes * replace move-file dep with @npmcli/move-file ([bf88af0](https://github.com/npm/cacache/commit/bf88af04e50cca9b54041151139ffc1fd415e2dc)), closes [#37](https://github.com/npm/cacache/issues/37) ### [15.0.3](https://github.com/npm/cacache/compare/v15.0.2...v15.0.3) (2020-04-28) ### Bug Fixes * actually remove move-concurrently dep ([29e6eec](https://github.com/npm/cacache/commit/29e6eec9fee73444ee09daf1c1be06ddd5fe57f6)) ### [15.0.2](https://github.com/npm/cacache/compare/v15.0.1...v15.0.2) (2020-04-28) ### Bug Fixes * tacks should be a dev dependency ([93ec158](https://github.com/npm/cacache/commit/93ec15852f0fdf1753ea7f75b4b8926daf8a7565)) ## [15.0.1](https://github.com/npm/cacache/compare/v15.0.0...v15.0.1) (2020-04-27) * **deps:** Use move-file instead of move-file-concurrently. ([92b125](https://github.com/npm/cacache/commit/92b1251a11b9848878b6c0d101b18bd8845acaa6)) ## [15.0.0](https://github.com/npm/cacache/compare/v14.0.0...v15.0.0) (2020-02-18) ### ⚠ BREAKING CHANGES * drop figgy-pudding and use canonical option names. ### Features * remove figgy-pudding ([57d11bc](https://github.com/npm/cacache/commit/57d11bce34f979247d1057d258acc204c4944491)) ## [14.0.0](https://github.com/npm/cacache/compare/v13.0.1...v14.0.0) (2020-01-28) ### ⚠ BREAKING CHANGES * **deps:** bumps engines to >= 10 * **deps:** tar v6 and mkdirp v1 ([5a66e7a](https://github.com/npm/cacache/commit/5a66e7a)) ### [13.0.1](https://github.com/npm/cacache/compare/v13.0.0...v13.0.1) (2019-09-30) ### Bug Fixes * **fix-owner:** chownr.sync quits on non-root uid ([08801be](https://github.com/npm/cacache/commit/08801be)) ## [13.0.0](https://github.com/npm/cacache/compare/v12.0.3...v13.0.0) (2019-09-25) ### ⚠ BREAKING CHANGES * This subtly changes the streaming interface of everything in cacache that streams, which is, well, everything in cacache. Most users will probably not notice, but any code that depended on stream behavior always being deferred until next tick will need to adjust. The mississippi methods 'to', 'from', 'through', and so on, have been replaced with their Minipass counterparts, and streaming interaction with the file system is done via fs-minipass. The following modules are of interest here: - [minipass](http://npm.im/minipass) The core stream library. - [fs-minipass](http://npm.im/fs-minipass) Note that the 'WriteStream' class from fs-minipass is _not_ a Minipass stream, but rather a plain old EventEmitter that duck types as a Writable. - [minipass-collect](http://npm.im/minipass-collect) Gather up all the data from a stream. Cacache only uses Collect.PassThrough, which is a basic Minipass passthrough stream which emits a 'collect' event with the completed data just before the 'end' event. - [minipass-pipeline](http://npm.im/minipass-pipeline) Connect one or more streams into a pipe chain. Errors anywhere in the pipeline are proxied down the chain and then up to the Pipeline object itself. Writes go into the head, reads go to the tail. Used in place of pump() and pumpify(). - [minipass-flush](http://npm.im/minipass-flush) A Minipass passthrough stream that defers its 'end' event until after a flush() method has completed (either calling the supplied callback, or returning a promise.) Use in place of flush-write-stream (aka mississippi.to). Streams from through2, concat-stream, and the behavior provided by end-of-stream are all implemented in Minipass itself. Features of interest to cacache, which make Minipass a particularly good fit: - All of the 'endish' events are normalized, so we can just listen on 'end' and know that finish, prefinish, and close will be handled as well. - Minipass doesn't waste time [containing zalgo](https://blog.izs.me/2013/08/designing-apis-for-asynchrony). - Minipass has built-in support for promises that indicate the end or error: stream.promise(), stream.collect(), and stream.concat(). - With reliable and consistent timing guarantees, much less error-checking logic is required. We can be more confident that an error is being thrown or emitted in the correct place, rather than in a callback which is deferred, resulting in a hung promise or uncaughtException. The biggest downside of Minipass is that it lacks some of the internal characteristics of node-core streams, which many community modules use to identify streams. They have no _writableState or _readableState objects, or _read or _write methods. As a result, the is-stream module (at least, at the time of this commit) doesn't recognize Minipass streams as readable or writable streams. All in all, the changes required of downstream users should be minimal, but are unlikely to be zero. Hence the semver major change. ### Features * replace all streams with Minipass streams ([f4c0962](https://github.com/npm/cacache/commit/f4c0962)) * **deps:** Add minipass and minipass-pipeline ([a6545a9](https://github.com/npm/cacache/commit/a6545a9)) * **promise:** converted .resolve to native promise, converted .map and .reduce to native ([220c56d](https://github.com/npm/cacache/commit/220c56d)) * **promise:** individually promisifing functions as needed ([74b939e](https://github.com/npm/cacache/commit/74b939e)) * **promise:** moved .reject from bluebird to native promise ([1d56da1](https://github.com/npm/cacache/commit/1d56da1)) * **promise:** removed .fromNode, removed .join ([9c457a0](https://github.com/npm/cacache/commit/9c457a0)) * **promise:** removed .map, replaced with p-map. removed .try ([cc3ee05](https://github.com/npm/cacache/commit/cc3ee05)) * **promise:** removed .tap ([0260f12](https://github.com/npm/cacache/commit/0260f12)) * **promise:** removed .using/.disposer ([5d832f3](https://github.com/npm/cacache/commit/5d832f3)) * **promise:** removed bluebird ([c21298c](https://github.com/npm/cacache/commit/c21298c)) * **promise:** removed bluebird specific .catch calls ([28aeeac](https://github.com/npm/cacache/commit/28aeeac)) * **promise:** replaced .reduce and .mapSeries ([478f5cb](https://github.com/npm/cacache/commit/478f5cb)) ### [12.0.3](https://github.com/npm/cacache/compare/v12.0.2...v12.0.3) (2019-08-19) ### Bug Fixes * do not chown if not running as root ([2d80af9](https://github.com/npm/cacache/commit/2d80af9)) ### [12.0.2](https://github.com/npm/cacache/compare/v12.0.1...v12.0.2) (2019-07-19) ### [12.0.1](https://github.com/npm/cacache/compare/v12.0.0...v12.0.1) (2019-07-19) * **deps** Abstracted out `lib/util/infer-owner.js` to [@npmcli/infer-owner](https://www.npmjs.com/package/@npmcli/infer-owner) so that it could be more easily used in other parts of the npm CLI. ## [12.0.0](https://github.com/npm/cacache/compare/v11.3.3...v12.0.0) (2019-07-15) ### Features * infer uid/gid instead of accepting as options ([ac84d14](https://github.com/npm/cacache/commit/ac84d14)) * **i18n:** add another error message ([676cb32](https://github.com/npm/cacache/commit/676cb32)) ### BREAKING CHANGES * the uid gid options are no longer respected or necessary. As of this change, cacache will always match the cache contents to the ownership of the cache directory (or its parent directory), regardless of what the caller passes in. Reasoning: The number one reason to use a uid or gid option was to keep root-owned files from causing problems in the cache. In npm's case, this meant that CLI's ./lib/command.js had to work out the appropriate uid and gid, then pass it to the libnpmcommand module, which had to in turn pass the uid and gid to npm-registry-fetch, which then passed it to make-fetch-happen, which passed it to cacache. (For package fetching, pacote would be in that mix as well.) Added to that, `cacache.rm()` will actually _write_ a file into the cache index, but has no way to accept an option so that its call to entry-index.js will write the index with the appropriate uid/gid. Little ownership bugs were all over the place, and tricky to trace through. (Why should make-fetch-happen even care about accepting or passing uids and gids? It's an http library.) This change allows us to keep the cache from having mixed ownership in any situation. Of course, this _does_ mean that if you have a root-owned but user-writable folder (for example, `/tmp`), then the cache will try to chown everything to root. The solution is for the user to create a folder, make it user-owned, and use that, rather than relying on cacache to create the root cache folder. If we decide to restore the uid/gid opts, and use ownership inference only when uid/gid are unset, then take care to also make rm take an option object, and pass it through to entry-index.js. ### [11.3.3](https://github.com/npm/cacache/compare/v11.3.2...v11.3.3) (2019-06-17) ### Bug Fixes * **audit:** npm audit fix ([200a6d5](https://github.com/npm/cacache/commit/200a6d5)) * **config:** Add ssri config 'error' option ([#146](https://github.com/npm/cacache/issues/146)) ([47de8f5](https://github.com/npm/cacache/commit/47de8f5)) * **deps:** npm audit fix ([481a7dc](https://github.com/npm/cacache/commit/481a7dc)) * **standard:** standard --fix ([7799149](https://github.com/npm/cacache/commit/7799149)) * **write:** avoid another cb never called situation ([5156561](https://github.com/npm/cacache/commit/5156561)) <a name="11.3.2"></a> ## [11.3.2](https://github.com/npm/cacache/compare/v11.3.1...v11.3.2) (2018-12-21) ### Bug Fixes * **get:** make sure to handle errors in the .then ([b10bcd0](https://github.com/npm/cacache/commit/b10bcd0)) <a name="11.3.1"></a> ## [11.3.1](https://github.com/npm/cacache/compare/v11.3.0...v11.3.1) (2018-11-05) ### Bug Fixes * **get:** export hasContent.sync properly ([d76c920](https://github.com/npm/cacache/commit/d76c920)) <a name="11.3.0"></a> # [11.3.0](https://github.com/npm/cacache/compare/v11.2.0...v11.3.0) (2018-11-05) ### Features * **get:** add sync API for reading ([db1e094](https://github.com/npm/cacache/commit/db1e094)) <a name="11.2.0"></a> # [11.2.0](https://github.com/npm/cacache/compare/v11.1.0...v11.2.0) (2018-08-08) ### Features * **read:** add sync support to other internal read.js fns ([fe638b6](https://github.com/npm/cacache/commit/fe638b6)) <a name="11.1.0"></a> # [11.1.0](https://github.com/npm/cacache/compare/v11.0.3...v11.1.0) (2018-08-01) ### Features * **read:** add sync support for low-level content read ([b43af83](https://github.com/npm/cacache/commit/b43af83)) <a name="11.0.3"></a> ## [11.0.3](https://github.com/npm/cacache/compare/v11.0.2...v11.0.3) (2018-08-01) ### Bug Fixes * **config:** add ssri config options ([#136](https://github.com/npm/cacache/issues/136)) ([10d5d9a](https://github.com/npm/cacache/commit/10d5d9a)) * **perf:** refactor content.read to avoid lstats ([c5ac10e](https://github.com/npm/cacache/commit/c5ac10e)) * **test:** oops when removing safe-buffer ([1950490](https://github.com/npm/cacache/commit/1950490)) <a name="11.0.2"></a> ## [11.0.2](https://github.com/npm/cacache/compare/v11.0.1...v11.0.2) (2018-05-07) ### Bug Fixes * **verify:** size param no longer lost in a verify ([#131](https://github.com/npm/cacache/issues/131)) ([c614a19](https://github.com/npm/cacache/commit/c614a19)), closes [#130](https://github.com/npm/cacache/issues/130) <a name="11.0.1"></a> ## [11.0.1](https://github.com/npm/cacache/compare/v11.0.0...v11.0.1) (2018-04-10) <a name="11.0.0"></a> # [11.0.0](https://github.com/npm/cacache/compare/v10.0.4...v11.0.0) (2018-04-09) ### Features * **opts:** use figgy-pudding for opts ([#128](https://github.com/npm/cacache/issues/128)) ([33d4eed](https://github.com/npm/cacache/commit/33d4eed)) ### meta * drop support for node@4 ([529f347](https://github.com/npm/cacache/commit/529f347)) ### BREAKING CHANGES * node@4 is no longer supported <a name="10.0.4"></a> ## [10.0.4](https://github.com/npm/cacache/compare/v10.0.3...v10.0.4) (2018-02-16) <a name="10.0.3"></a> ## [10.0.3](https://github.com/npm/cacache/compare/v10.0.2...v10.0.3) (2018-02-16) ### Bug Fixes * **content:** rethrow aggregate errors as ENOENT ([fa918f5](https://github.com/npm/cacache/commit/fa918f5)) <a name="10.0.2"></a> ## [10.0.2](https://github.com/npm/cacache/compare/v10.0.1...v10.0.2) (2018-01-07) ### Bug Fixes * **ls:** deleted entries could cause a premature stream EOF ([347dc36](https://github.com/npm/cacache/commit/347dc36)) <a name="10.0.1"></a> ## [10.0.1](https://github.com/npm/cacache/compare/v10.0.0...v10.0.1) (2017-11-15) ### Bug Fixes * **move-file:** actually use the fallback to `move-concurrently` (#110) ([073fbe1](https://github.com/npm/cacache/commit/073fbe1)) <a name="10.0.0"></a> # [10.0.0](https://github.com/npm/cacache/compare/v9.3.0...v10.0.0) (2017-10-23) ### Features * **license:** relicense to ISC (#111) ([fdbb4e5](https://github.com/npm/cacache/commit/fdbb4e5)) ### Performance Improvements * more copyFile benchmarks ([63787bb](https://github.com/npm/cacache/commit/63787bb)) ### BREAKING CHANGES * **license:** the license has been changed from CC0-1.0 to ISC. <a name="9.3.0"></a> # [9.3.0](https://github.com/npm/cacache/compare/v9.2.9...v9.3.0) (2017-10-07) ### Features * **copy:** added cacache.get.copy api for fast copies (#107) ([067b5f6](https://github.com/npm/cacache/commit/067b5f6)) <a name="9.2.9"></a> ## [9.2.9](https://github.com/npm/cacache/compare/v9.2.8...v9.2.9) (2017-06-17) <a name="9.2.8"></a> ## [9.2.8](https://github.com/npm/cacache/compare/v9.2.7...v9.2.8) (2017-06-05) ### Bug Fixes * **ssri:** bump ssri for bugfix ([c3232ea](https://github.com/npm/cacache/commit/c3232ea)) <a name="9.2.7"></a> ## [9.2.7](https://github.com/npm/cacache/compare/v9.2.6...v9.2.7) (2017-06-05) ### Bug Fixes * **content:** make verified content completely read-only (#96) ([4131196](https://github.com/npm/cacache/commit/4131196)) <a name="9.2.6"></a> ## [9.2.6](https://github.com/npm/cacache/compare/v9.2.5...v9.2.6) (2017-05-31) ### Bug Fixes * **node:** update ssri to prevent old node 4 crash ([5209ffe](https://github.com/npm/cacache/commit/5209ffe)) <a name="9.2.5"></a> ## [9.2.5](https://github.com/npm/cacache/compare/v9.2.4...v9.2.5) (2017-05-25) ### Bug Fixes * **deps:** fix lockfile issues and bump ssri ([84e1d7e](https://github.com/npm/cacache/commit/84e1d7e)) <a name="9.2.4"></a> ## [9.2.4](https://github.com/npm/cacache/compare/v9.2.3...v9.2.4) (2017-05-24) ### Bug Fixes * **deps:** bumping deps ([bbccb12](https://github.com/npm/cacache/commit/bbccb12)) <a name="9.2.3"></a> ## [9.2.3](https://github.com/npm/cacache/compare/v9.2.2...v9.2.3) (2017-05-24) ### Bug Fixes * **rm:** stop crashing if content is missing on rm ([ac90bc0](https://github.com/npm/cacache/commit/ac90bc0)) <a name="9.2.2"></a> ## [9.2.2](https://github.com/npm/cacache/compare/v9.2.1...v9.2.2) (2017-05-14) ### Bug Fixes * **i18n:** lets pretend this didn't happen ([519b4ee](https://github.com/npm/cacache/commit/519b4ee)) <a name="9.2.1"></a> ## [9.2.1](https://github.com/npm/cacache/compare/v9.2.0...v9.2.1) (2017-05-14) ### Bug Fixes * **docs:** fixing translation messup ([bb9e4f9](https://github.com/npm/cacache/commit/bb9e4f9)) <a name="9.2.0"></a> # [9.2.0](https://github.com/npm/cacache/compare/v9.1.0...v9.2.0) (2017-05-14) ### Features * **i18n:** add Spanish translation for API ([531f9a4](https://github.com/npm/cacache/commit/531f9a4)) <a name="9.1.0"></a> # [9.1.0](https://github.com/npm/cacache/compare/v9.0.0...v9.1.0) (2017-05-14) ### Features * **i18n:** Add Spanish translation and i18n setup (#91) ([323b90c](https://github.com/npm/cacache/commit/323b90c)) <a name="9.0.0"></a> # [9.0.0](https://github.com/npm/cacache/compare/v8.0.0...v9.0.0) (2017-04-28) ### Bug Fixes * **memoization:** actually use the LRU ([0e55dc9](https://github.com/npm/cacache/commit/0e55dc9)) ### Features * **memoization:** memoizers can be injected through opts.memoize (#90) ([e5614c7](https://github.com/npm/cacache/commit/e5614c7)) ### BREAKING CHANGES * **memoization:** If you were passing an object to opts.memoize, it will now be used as an injected memoization object. If you were only passing booleans and other non-objects through that option, no changes are needed. <a name="8.0.0"></a> # [8.0.0](https://github.com/npm/cacache/compare/v7.1.0...v8.0.0) (2017-04-22) ### Features * **read:** change hasContent to return {sri, size} (#88) ([bad6c49](https://github.com/npm/cacache/commit/bad6c49)), closes [#87](https://github.com/npm/cacache/issues/87) ### BREAKING CHANGES * **read:** hasContent now returns an object with `{sri, size}` instead of `sri`. Use `result.sri` anywhere that needed the old return value. <a name="7.1.0"></a> # [7.1.0](https://github.com/npm/cacache/compare/v7.0.5...v7.1.0) (2017-04-20) ### Features * **size:** handle content size info (#49) ([91230af](https://github.com/npm/cacache/commit/91230af)) <a name="7.0.5"></a> ## [7.0.5](https://github.com/npm/cacache/compare/v7.0.4...v7.0.5) (2017-04-18) ### Bug Fixes * **integrity:** new ssri with fixed integrity stream ([6d13e8e](https://github.com/npm/cacache/commit/6d13e8e)) * **write:** wrap stuff in promises to improve errors ([3624fc5](https://github.com/npm/cacache/commit/3624fc5)) <a name="7.0.4"></a> ## [7.0.4](https://github.com/npm/cacache/compare/v7.0.3...v7.0.4) (2017-04-15) ### Bug Fixes * **fix-owner:** throw away ENOENTs on chownr ([d49bbcd](https://github.com/npm/cacache/commit/d49bbcd)) <a name="7.0.3"></a> ## [7.0.3](https://github.com/npm/cacache/compare/v7.0.2...v7.0.3) (2017-04-05) ### Bug Fixes * **read:** fixing error message for integrity verification failures ([9d4f0a5](https://github.com/npm/cacache/commit/9d4f0a5)) <a name="7.0.2"></a> ## [7.0.2](https://github.com/npm/cacache/compare/v7.0.1...v7.0.2) (2017-04-03) ### Bug Fixes * **integrity:** use EINTEGRITY error code and update ssri ([8dc2e62](https://github.com/npm/cacache/commit/8dc2e62)) <a name="7.0.1"></a> ## [7.0.1](https://github.com/npm/cacache/compare/v7.0.0...v7.0.1) (2017-04-03) ### Bug Fixes * **docs:** fix header name conflict in readme ([afcd456](https://github.com/npm/cacache/commit/afcd456)) <a name="7.0.0"></a> # [7.0.0](https://github.com/npm/cacache/compare/v6.3.0...v7.0.0) (2017-04-03) ### Bug Fixes * **test:** fix content.write tests when running in docker ([d2e9b6a](https://github.com/npm/cacache/commit/d2e9b6a)) ### Features * **integrity:** subresource integrity support (#78) ([b1e731f](https://github.com/npm/cacache/commit/b1e731f)) ### BREAKING CHANGES * **integrity:** The entire API has been overhauled to use SRI hashes instead of digest/hashAlgorithm pairs. SRI hashes follow the Subresource Integrity standard and support strings and objects compatible with [`ssri`](https://npm.im/ssri). * This change bumps the index version, which will invalidate all previous index entries. Content entries will remain intact, and existing caches will automatically reuse any content from before this breaking change. * `cacache.get.info()`, `cacache.ls()`, and `cacache.ls.stream()` will now return objects that looks like this: ``` { key: String, integrity: '<algorithm>-<base64hash>', path: ContentPath, time: Date<ms>, metadata: Any } ``` * `opts.digest` and `opts.hashAlgorithm` are obsolete for any API calls that used them. * Anywhere `opts.digest` was accepted, `opts.integrity` is now an option. Any valid SRI hash is accepted here -- multiple hash entries will be resolved according to the standard: first, the "strongest" hash algorithm will be picked, and then each of the entries for that algorithm will be matched against the content. Content will be validated if *any* of the entries match (so, a single integrity string can be used for multiple "versions" of the same document/data). * `put.byDigest()`, `put.stream.byDigest`, `get.byDigest()` and `get.stream.byDigest()` now expect an SRI instead of a `digest` + `opts.hashAlgorithm` pairing. * `get.hasContent()` now expects an integrity hash instead of a digest. If content exists, it will return the specific single integrity hash that was found in the cache. * `verify()` has learned to handle integrity-based caches, and forgotten how to handle old-style cache indices due to the format change. * `cacache.rm.content()` now expects an integrity hash instead of a hex digest. <a name="6.3.0"></a> # [6.3.0](https://github.com/npm/cacache/compare/v6.2.0...v6.3.0) (2017-04-01) ### Bug Fixes * **fixOwner:** ignore EEXIST race condition from mkdirp ([4670e9b](https://github.com/npm/cacache/commit/4670e9b)) * **index:** ignore index removal races when inserting ([b9d2fa2](https://github.com/npm/cacache/commit/b9d2fa2)) * **memo:** use lru-cache for better mem management (#75) ([d8ac5aa](https://github.com/npm/cacache/commit/d8ac5aa)) ### Features * **dependencies:** Switch to move-concurrently (#77) ([dc6482d](https://github.com/npm/cacache/commit/dc6482d)) <a name="6.2.0"></a> # [6.2.0](https://github.com/npm/cacache/compare/v6.1.2...v6.2.0) (2017-03-15) ### Bug Fixes * **index:** additional bucket entry verification with checksum (#72) ([f8e0f25](https://github.com/npm/cacache/commit/f8e0f25)) * **verify:** return fixOwner.chownr promise ([6818521](https://github.com/npm/cacache/commit/6818521)) ### Features * **tmp:** safe tmp dir creation/management util (#73) ([c42da71](https://github.com/npm/cacache/commit/c42da71)) <a name="6.1.2"></a> ## [6.1.2](https://github.com/npm/cacache/compare/v6.1.1...v6.1.2) (2017-03-13) ### Bug Fixes * **index:** set default hashAlgorithm ([d6eb2f0](https://github.com/npm/cacache/commit/d6eb2f0)) <a name="6.1.1"></a> ## [6.1.1](https://github.com/npm/cacache/compare/v6.1.0...v6.1.1) (2017-03-13) ### Bug Fixes * **coverage:** bumping coverage for verify (#71) ([0b7faf6](https://github.com/npm/cacache/commit/0b7faf6)) * **deps:** glob should have been a regular dep :< ([0640bc4](https://github.com/npm/cacache/commit/0640bc4)) <a name="6.1.0"></a> # [6.1.0](https://github.com/npm/cacache/compare/v6.0.2...v6.1.0) (2017-03-12) ### Bug Fixes * **coverage:** more coverage for content reads (#70) ([ef4f70a](https://github.com/npm/cacache/commit/ef4f70a)) * **tests:** use safe-buffer because omfg (#69) ([6ab8132](https://github.com/npm/cacache/commit/6ab8132)) ### Features * **rm:** limited rm.all and fixed bugs (#66) ([d5d25ba](https://github.com/npm/cacache/commit/d5d25ba)), closes [#66](https://github.com/npm/cacache/issues/66) * **verify:** tested, working cache verifier/gc (#68) ([45ad77a](https://github.com/npm/cacache/commit/45ad77a)) <a name="6.0.2"></a> ## [6.0.2](https://github.com/npm/cacache/compare/v6.0.1...v6.0.2) (2017-03-11) ### Bug Fixes * **index:** segment cache items with another subbucket (#64) ([c3644e5](https://github.com/npm/cacache/commit/c3644e5)) <a name="6.0.1"></a> ## [6.0.1](https://github.com/npm/cacache/compare/v6.0.0...v6.0.1) (2017-03-05) ### Bug Fixes * **docs:** Missed spots in README ([8ffb7fa](https://github.com/npm/cacache/commit/8ffb7fa)) <a name="6.0.0"></a> # [6.0.0](https://github.com/npm/cacache/compare/v5.0.3...v6.0.0) (2017-03-05) ### Bug Fixes * **api:** keep memo cache mostly-internal ([2f72d0a](https://github.com/npm/cacache/commit/2f72d0a)) * **content:** use the rest of the string, not the whole string ([fa8f3c3](https://github.com/npm/cacache/commit/fa8f3c3)) * **deps:** removed `format-number@2.0.2` ([1187791](https://github.com/npm/cacache/commit/1187791)) * **deps:** removed inflight@1.0.6 ([0d1819c](https://github.com/npm/cacache/commit/0d1819c)) * **deps:** rimraf@2.6.1 ([9efab6b](https://github.com/npm/cacache/commit/9efab6b)) * **deps:** standard@9.0.0 ([4202cba](https://github.com/npm/cacache/commit/4202cba)) * **deps:** tap@10.3.0 ([aa03088](https://github.com/npm/cacache/commit/aa03088)) * **deps:** weallcontribute@1.0.8 ([ad4f4dc](https://github.com/npm/cacache/commit/ad4f4dc)) * **docs:** add security note to hashKey ([03f81ba](https://github.com/npm/cacache/commit/03f81ba)) * **hashes:** change default hashAlgorithm to sha512 ([ea00ba6](https://github.com/npm/cacache/commit/ea00ba6)) * **hashes:** missed a spot for hashAlgorithm defaults ([45997d8](https://github.com/npm/cacache/commit/45997d8)) * **index:** add length header before JSON for verification ([fb8cb4d](https://github.com/npm/cacache/commit/fb8cb4d)) * **index:** change index filenames to sha1s of keys ([bbc5fca](https://github.com/npm/cacache/commit/bbc5fca)) * **index:** who cares about race conditions anyway ([b1d3888](https://github.com/npm/cacache/commit/b1d3888)) * **perf:** bulk-read get+read for massive speed ([d26cdf9](https://github.com/npm/cacache/commit/d26cdf9)) * **perf:** use bulk file reads for index reads ([79a8891](https://github.com/npm/cacache/commit/79a8891)) * **put-stream:** remove tmp file on stream insert error ([65f6632](https://github.com/npm/cacache/commit/65f6632)) * **put-stream:** robustified and predictibilized ([daf9e08](https://github.com/npm/cacache/commit/daf9e08)) * **put-stream:** use new promise API for moves ([1d36013](https://github.com/npm/cacache/commit/1d36013)) * **readme:** updated to reflect new default hashAlgo ([c60a2fa](https://github.com/npm/cacache/commit/c60a2fa)) * **verify:** tiny typo fix ([db22d05](https://github.com/npm/cacache/commit/db22d05)) ### Features * **api:** converted external api ([7bf032f](https://github.com/npm/cacache/commit/7bf032f)) * **cacache:** exported clearMemoized() utility ([8d2c5b6](https://github.com/npm/cacache/commit/8d2c5b6)) * **cache:** add versioning to content and index ([31bc549](https://github.com/npm/cacache/commit/31bc549)) * **content:** collate content files into subdirs ([c094d9f](https://github.com/npm/cacache/commit/c094d9f)) * **deps:** `@npmcorp/move@1.0.0` ([bdd00bf](https://github.com/npm/cacache/commit/bdd00bf)) * **deps:** `bluebird@3.4.7` ([3a17aff](https://github.com/npm/cacache/commit/3a17aff)) * **deps:** `promise-inflight@1.0.1` ([a004fe6](https://github.com/npm/cacache/commit/a004fe6)) * **get:** added memoization support for get ([c77d794](https://github.com/npm/cacache/commit/c77d794)) * **get:** export hasContent ([2956ec3](https://github.com/npm/cacache/commit/2956ec3)) * **index:** add hashAlgorithm and format insert ret val ([b639746](https://github.com/npm/cacache/commit/b639746)) * **index:** collate index files into subdirs ([e8402a5](https://github.com/npm/cacache/commit/e8402a5)) * **index:** promisify entry index ([cda3335](https://github.com/npm/cacache/commit/cda3335)) * **memo:** added memoization lib ([da07b92](https://github.com/npm/cacache/commit/da07b92)) * **memo:** export memoization api ([954b1b3](https://github.com/npm/cacache/commit/954b1b3)) * **move-file:** add move fallback for weird errors ([5cf4616](https://github.com/npm/cacache/commit/5cf4616)) * **perf:** bulk content write api ([51b536e](https://github.com/npm/cacache/commit/51b536e)) * **put:** added memoization support to put ([b613a70](https://github.com/npm/cacache/commit/b613a70)) * **read:** switched to promises ([a869362](https://github.com/npm/cacache/commit/a869362)) * **rm:** added memoization support to rm ([4205cf0](https://github.com/npm/cacache/commit/4205cf0)) * **rm:** switched to promises ([a000d24](https://github.com/npm/cacache/commit/a000d24)) * **util:** promise-inflight ownership fix requests ([9517cd7](https://github.com/npm/cacache/commit/9517cd7)) * **util:** use promises for api ([ae204bb](https://github.com/npm/cacache/commit/ae204bb)) * **verify:** converted to Promises ([f0b3974](https://github.com/npm/cacache/commit/f0b3974)) ### BREAKING CHANGES * cache: index/content directories are now versioned. Previous caches are no longer compatible and cannot be migrated. * util: fix-owner now uses Promises instead of callbacks * index: Previously-generated index entries are no longer compatible and the index must be regenerated. * index: The index format has changed and previous caches are no longer compatible. Existing caches will need to be regenerated. * hashes: Default hashAlgorithm changed from sha1 to sha512. If you rely on the prior setting, pass `opts.hashAlgorithm` in explicitly. * content: Previously-generated content directories are no longer compatible and must be regenerated. * verify: API is now promise-based * read: Switches to a Promise-based API and removes callback stuff * rm: Switches to a Promise-based API and removes callback stuff * index: this changes the API to work off promises instead of callbacks * api: this means we are going all in on promises now ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/CODE_OF_CONDUCT.md�������������������������������������������������������������������0000664�0000000�0000000�00000000507�14344174136�0015761�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- This file is automatically added by @npmcli/template-oss. Do not edit. --> All interactions in this repo are covered by the [npm Code of Conduct](https://docs.npmjs.com/policies/conduct) The npm cli team may, at its own discretion, moderate, remove, or edit any interactions such as pull requests, issues, and comments. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/LICENSE.md���������������������������������������������������������������������������0000664�0000000�0000000�00000001363�14344174136�0014567�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/README.md����������������������������������������������������������������������������0000664�0000000�0000000�00000054562�14344174136�0014453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������# cacache [![npm version](https://img.shields.io/npm/v/cacache.svg)](https://npm.im/cacache) [![license](https://img.shields.io/npm/l/cacache.svg)](https://npm.im/cacache) [![Travis](https://img.shields.io/travis/npm/cacache.svg)](https://travis-ci.org/npm/cacache) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/npm/cacache?svg=true)](https://ci.appveyor.com/project/npm/cacache) [![Coverage Status](https://coveralls.io/repos/github/npm/cacache/badge.svg?branch=latest)](https://coveralls.io/github/npm/cacache?branch=latest) [`cacache`](https://github.com/npm/cacache) is a Node.js library for managing local key and content address caches. It's really fast, really good at concurrency, and it will never give you corrupted data, even if cache files get corrupted or manipulated. On systems that support user and group settings on files, cacache will match the `uid` and `gid` values to the folder where the cache lives, even when running as `root`. It was written to be used as [npm](https://npm.im)'s local cache, but can just as easily be used on its own. ## Install `$ npm install --save cacache` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * [Using localized APIs](#localized-api) * Reading * [`ls`](#ls) * [`ls.stream`](#ls-stream) * [`get`](#get-data) * [`get.stream`](#get-stream) * [`get.info`](#get-info) * [`get.hasContent`](#get-hasContent) * Writing * [`put`](#put-data) * [`put.stream`](#put-stream) * [`rm.all`](#rm-all) * [`rm.entry`](#rm-entry) * [`rm.content`](#rm-content) * [`index.compact`](#index-compact) * [`index.insert`](#index-insert) * Utilities * [`clearMemoized`](#clear-memoized) * [`tmp.mkdir`](#tmp-mkdir) * [`tmp.withTmp`](#with-tmp) * Integrity * [Subresource Integrity](#integrity) * [`verify`](#verify) * [`verify.lastRun`](#verify-last-run) ### Example ```javascript const cacache = require('cacache') const fs = require('fs') const tarball = '/path/to/mytar.tgz' const cachePath = '/tmp/my-toy-cache' const key = 'my-unique-key-1234' // Cache it! Use `cachePath` as the root of the content cache cacache.put(cachePath, key, '10293801983029384').then(integrity => { console.log(`Saved content to ${cachePath}.`) }) const destination = '/tmp/mytar.tgz' // Copy the contents out of the cache and into their destination! // But this time, use stream instead! cacache.get.stream( cachePath, key ).pipe( fs.createWriteStream(destination) ).on('finish', () => { console.log('done extracting!') }) // The same thing, but skip the key index. cacache.get.byDigest(cachePath, integrityHash).then(data => { fs.writeFile(destination, data, err => { console.log('tarball data fetched based on its sha512sum and written out!') }) }) ``` ### Features * Extraction by key or by content address (shasum, etc) * [Subresource Integrity](#integrity) web standard support * Multi-hash support - safely host sha1, sha512, etc, in a single cache * Automatic content deduplication * Fault tolerance (immune to corruption, partial writes, process races, etc) * Consistency guarantees on read and write (full data verification) * Lockless, high-concurrency cache access * Streaming support * Promise support * Fast -- sub-millisecond reads and writes including verification * Arbitrary metadata storage * Garbage collection and additional offline verification * Thorough test coverage * There's probably a bloom filter in there somewhere. Those are cool, right? 🤔 ### Contributing The cacache team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### <a name="ls"></a> `> cacache.ls(cache) -> Promise<Object>` Lists info for all entries currently in the cache as a single large object. Each entry in the object will be keyed by the unique index key, with corresponding [`get.info`](#get-info) objects as the values. ##### Example ```javascript cacache.ls(cachePath).then(console.log) // Output { 'my-thing': { key: 'my-thing', integrity: 'sha512-BaSe64/EnCoDED+HAsh==' path: '.testcache/content/deadbeef', // joined with `cachePath` time: 12345698490, size: 4023948, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } }, 'other-thing': { key: 'other-thing', integrity: 'sha1-ANothER+hasH=', path: '.testcache/content/bada55', time: 11992309289, size: 111112 } } ``` #### <a name="ls-stream"></a> `> cacache.ls.stream(cache) -> Readable` Lists info for all entries currently in the cache as a single large object. This works just like [`ls`](#ls), except [`get.info`](#get-info) entries are returned as `'data'` events on the returned stream. ##### Example ```javascript cacache.ls.stream(cachePath).on('data', console.log) // Output { key: 'my-thing', integrity: 'sha512-BaSe64HaSh', path: '.testcache/content/deadbeef', // joined with `cachePath` time: 12345698490, size: 13423, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } } { key: 'other-thing', integrity: 'whirlpool-WoWSoMuchSupport', path: '.testcache/content/bada55', time: 11992309289, size: 498023984029 } { ... } ``` #### <a name="get-data"></a> `> cacache.get(cache, key, [opts]) -> Promise({data, metadata, integrity})` Returns an object with the cached data, digest, and metadata identified by `key`. The `data` property of this object will be a `Buffer` instance that presumably holds some data that means something to you. I'm sure you know what to do with it! cacache just won't care. `integrity` is a [Subresource Integrity](#integrity) string. That is, a string that can be used to verify `data`, which looks like `<hash-algorithm>-<base64-integrity-hash>`. If there is no content identified by `key`, or if the locally-stored data does not pass the validity checksum, the promise will be rejected. A sub-function, `get.byDigest` may be used for identical behavior, except lookup will happen by integrity hash, bypassing the index entirely. This version of the function *only* returns `data` itself, without any wrapper. See: [options](#get-options) ##### Note This function loads the entire cache entry into memory before returning it. If you're dealing with Very Large data, consider using [`get.stream`](#get-stream) instead. ##### Example ```javascript // Look up by key cache.get(cachePath, 'my-thing').then(console.log) // Output: { metadata: { thingName: 'my' }, integrity: 'sha512-BaSe64HaSh', data: Buffer#<deadbeef>, size: 9320 } // Look up by digest cache.get.byDigest(cachePath, 'sha512-BaSe64HaSh').then(console.log) // Output: Buffer#<deadbeef> ``` #### <a name="get-stream"></a> `> cacache.get.stream(cache, key, [opts]) -> Readable` Returns a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the cached data identified by `key`. If there is no content identified by `key`, or if the locally-stored data does not pass the validity checksum, an error will be emitted. `metadata` and `integrity` events will be emitted before the stream closes, if you need to collect that extra data about the cached entry. A sub-function, `get.stream.byDigest` may be used for identical behavior, except lookup will happen by integrity hash, bypassing the index entirely. This version does not emit the `metadata` and `integrity` events at all. See: [options](#get-options) ##### Example ```javascript // Look up by key cache.get.stream( cachePath, 'my-thing' ).on('metadata', metadata => { console.log('metadata:', metadata) }).on('integrity', integrity => { console.log('integrity:', integrity) }).pipe( fs.createWriteStream('./x.tgz') ) // Outputs: metadata: { ... } integrity: 'sha512-SoMeDIGest+64==' // Look up by digest cache.get.stream.byDigest( cachePath, 'sha512-SoMeDIGest+64==' ).pipe( fs.createWriteStream('./x.tgz') ) ``` #### <a name="get-info"></a> `> cacache.get.info(cache, key) -> Promise` Looks up `key` in the cache index, returning information about the entry if one exists. ##### Fields * `key` - Key the entry was looked up under. Matches the `key` argument. * `integrity` - [Subresource Integrity hash](#integrity) for the content this entry refers to. * `path` - Filesystem path where content is stored, joined with `cache` argument. * `time` - Timestamp the entry was first added on. * `metadata` - User-assigned metadata associated with the entry/content. ##### Example ```javascript cacache.get.info(cachePath, 'my-thing').then(console.log) // Output { key: 'my-thing', integrity: 'sha256-MUSTVERIFY+ALL/THINGS==' path: '.testcache/content/deadbeef', time: 12345698490, size: 849234, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } } ``` #### <a name="get-hasContent"></a> `> cacache.get.hasContent(cache, integrity) -> Promise` Looks up a [Subresource Integrity hash](#integrity) in the cache. If content exists for this `integrity`, it will return an object, with the specific single integrity hash that was found in `sri` key, and the size of the found content as `size`. If no content exists for this integrity, it will return `false`. ##### Example ```javascript cacache.get.hasContent(cachePath, 'sha256-MUSTVERIFY+ALL/THINGS==').then(console.log) // Output { sri: { source: 'sha256-MUSTVERIFY+ALL/THINGS==', algorithm: 'sha256', digest: 'MUSTVERIFY+ALL/THINGS==', options: [] }, size: 9001 } cacache.get.hasContent(cachePath, 'sha521-NOT+IN/CACHE==').then(console.log) // Output false ``` ##### <a name="get-options"></a> Options ##### `opts.integrity` If present, the pre-calculated digest for the inserted content. If this option is provided and does not match the post-insertion digest, insertion will fail with an `EINTEGRITY` error. ##### `opts.memoize` Default: null If explicitly truthy, cacache will read from memory and memoize data on bulk read. If `false`, cacache will read from disk data. Reader functions by default read from in-memory cache. ##### `opts.size` If provided, the data stream will be verified to check that enough data was passed through. If there's more or less data than expected, insertion will fail with an `EBADSIZE` error. #### <a name="put-data"></a> `> cacache.put(cache, key, data, [opts]) -> Promise` Inserts data passed to it into the cache. The returned Promise resolves with a digest (generated according to [`opts.algorithms`](#optsalgorithms)) after the cache entry has been successfully written. See: [options](#put-options) ##### Example ```javascript fetch( 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz' ).then(data => { return cacache.put(cachePath, 'registry.npmjs.org|cacache@1.0.0', data) }).then(integrity => { console.log('integrity hash is', integrity) }) ``` #### <a name="put-stream"></a> `> cacache.put.stream(cache, key, [opts]) -> Writable` Returns a [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams) that inserts data written to it into the cache. Emits an `integrity` event with the digest of written contents when it succeeds. See: [options](#put-options) ##### Example ```javascript request.get( 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz' ).pipe( cacache.put.stream( cachePath, 'registry.npmjs.org|cacache@1.0.0' ).on('integrity', d => console.log(`integrity digest is ${d}`)) ) ``` ##### <a name="put-options"></a> Options ##### `opts.metadata` Arbitrary metadata to be attached to the inserted key. ##### `opts.size` If provided, the data stream will be verified to check that enough data was passed through. If there's more or less data than expected, insertion will fail with an `EBADSIZE` error. ##### `opts.integrity` If present, the pre-calculated digest for the inserted content. If this option is provided and does not match the post-insertion digest, insertion will fail with an `EINTEGRITY` error. `algorithms` has no effect if this option is present. ##### `opts.integrityEmitter` *Streaming only* If present, uses the provided event emitter as a source of truth for both integrity and size. This allows use cases where integrity is already being calculated outside of cacache to reuse that data instead of calculating it a second time. The emitter must emit both the `'integrity'` and `'size'` events. NOTE: If this option is provided, you must verify that you receive the correct integrity value yourself and emit an `'error'` event if there is a mismatch. [ssri Integrity Streams](https://github.com/npm/ssri#integrity-stream) do this for you when given an expected integrity. ##### `opts.algorithms` Default: ['sha512'] Hashing algorithms to use when calculating the [subresource integrity digest](#integrity) for inserted data. Can use any algorithm listed in `crypto.getHashes()` or `'omakase'`/`'お任せします'` to pick a random hash algorithm on each insertion. You may also use any anagram of `'modnar'` to use this feature. Currently only supports one algorithm at a time (i.e., an array length of exactly `1`). Has no effect if `opts.integrity` is present. ##### `opts.memoize` Default: null If provided, cacache will memoize the given cache insertion in memory, bypassing any filesystem checks for that key or digest in future cache fetches. Nothing will be written to the in-memory cache unless this option is explicitly truthy. If `opts.memoize` is an object or a `Map`-like (that is, an object with `get` and `set` methods), it will be written to instead of the global memoization cache. Reading from disk data can be forced by explicitly passing `memoize: false` to the reader functions, but their default will be to read from memory. ##### `opts.tmpPrefix` Default: null Prefix to append on the temporary directory name inside the cache's tmp dir. #### <a name="rm-all"></a> `> cacache.rm.all(cache) -> Promise` Clears the entire cache. Mainly by blowing away the cache directory itself. ##### Example ```javascript cacache.rm.all(cachePath).then(() => { console.log('THE APOCALYPSE IS UPON US 😱') }) ``` #### <a name="rm-entry"></a> `> cacache.rm.entry(cache, key, [opts]) -> Promise` Alias: `cacache.rm` Removes the index entry for `key`. Content will still be accessible if requested directly by content address ([`get.stream.byDigest`](#get-stream)). By default, this appends a new entry to the index with an integrity of `null`. If `opts.removeFully` is set to `true` then the index file itself will be physically deleted rather than appending a `null`. To remove the content itself (which might still be used by other entries), use [`rm.content`](#rm-content). Or, to safely vacuum any unused content, use [`verify`](#verify). ##### Example ```javascript cacache.rm.entry(cachePath, 'my-thing').then(() => { console.log('I did not like it anyway') }) ``` #### <a name="rm-content"></a> `> cacache.rm.content(cache, integrity) -> Promise` Removes the content identified by `integrity`. Any index entries referring to it will not be usable again until the content is re-added to the cache with an identical digest. ##### Example ```javascript cacache.rm.content(cachePath, 'sha512-SoMeDIGest/IN+BaSE64==').then(() => { console.log('data for my-thing is gone!') }) ``` #### <a name="index-compact"></a> `> cacache.index.compact(cache, key, matchFn, [opts]) -> Promise` Uses `matchFn`, which must be a synchronous function that accepts two entries and returns a boolean indicating whether or not the two entries match, to deduplicate all entries in the cache for the given `key`. If `opts.validateEntry` is provided, it will be called as a function with the only parameter being a single index entry. The function must return a Boolean, if it returns `true` the entry is considered valid and will be kept in the index, if it returns `false` the entry will be removed from the index. If `opts.validateEntry` is not provided, however, every entry in the index will be deduplicated and kept until the first `null` integrity is reached, removing all entries that were written before the `null`. The deduplicated list of entries is both written to the index, replacing the existing content, and returned in the Promise. #### <a name="index-insert"></a> `> cacache.index.insert(cache, key, integrity, opts) -> Promise` Writes an index entry to the cache for the given `key` without writing content. It is assumed if you are using this method, you have already stored the content some other way and you only wish to add a new index to that content. The `metadata` and `size` properties are read from `opts` and used as part of the index entry. Returns a Promise resolving to the newly added entry. #### <a name="clear-memoized"></a> `> cacache.clearMemoized()` Completely resets the in-memory entry cache. #### <a name="tmp-mkdir"></a> `> tmp.mkdir(cache, opts) -> Promise<Path>` Returns a unique temporary directory inside the cache's `tmp` dir. This directory will use the same safe user assignment that all the other stuff use. Once the directory is made, it's the user's responsibility that all files within are given the appropriate `gid`/`uid` ownership settings to match the rest of the cache. If not, you can ask cacache to do it for you by calling [`tmp.fix()`](#tmp-fix), which will fix all tmp directory permissions. If you want automatic cleanup of this directory, use [`tmp.withTmp()`](#with-tpm) See: [options](#tmp-options) ##### Example ```javascript cacache.tmp.mkdir(cache).then(dir => { fs.writeFile(path.join(dir, 'blablabla'), Buffer#<1234>, ...) }) ``` #### <a name="tmp-fix"></a> `> tmp.fix(cache) -> Promise` Sets the `uid` and `gid` properties on all files and folders within the tmp folder to match the rest of the cache. Use this after manually writing files into [`tmp.mkdir`](#tmp-mkdir) or [`tmp.withTmp`](#with-tmp). ##### Example ```javascript cacache.tmp.mkdir(cache).then(dir => { writeFile(path.join(dir, 'file'), someData).then(() => { // make sure we didn't just put a root-owned file in the cache cacache.tmp.fix().then(() => { // all uids and gids match now }) }) }) ``` #### <a name="with-tmp"></a> `> tmp.withTmp(cache, opts, cb) -> Promise` Creates a temporary directory with [`tmp.mkdir()`](#tmp-mkdir) and calls `cb` with it. The created temporary directory will be removed when the return value of `cb()` resolves, the tmp directory will be automatically deleted once that promise completes. The same caveats apply when it comes to managing permissions for the tmp dir's contents. See: [options](#tmp-options) ##### Example ```javascript cacache.tmp.withTmp(cache, dir => { return fs.writeFile(path.join(dir, 'blablabla'), 'blabla contents', { encoding: 'utf8' }) }).then(() => { // `dir` no longer exists }) ``` ##### <a name="tmp-options"></a> Options ##### `opts.tmpPrefix` Default: null Prefix to append on the temporary directory name inside the cache's tmp dir. #### <a name="integrity"></a> Subresource Integrity Digests For content verification and addressing, cacache uses strings following the [Subresource Integrity spec](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). That is, any time cacache expects an `integrity` argument or option, it should be in the format `<hashAlgorithm>-<base64-hash>`. One deviation from the current spec is that cacache will support any hash algorithms supported by the underlying Node.js process. You can use `crypto.getHashes()` to see which ones you can use. ##### Generating Digests Yourself If you have an existing content shasum, they are generally formatted as a hexadecimal string (that is, a sha1 would look like: `5f5513f8822fdbe5145af33b64d8d970dcf95c6e`). In order to be compatible with cacache, you'll need to convert this to an equivalent subresource integrity string. For this example, the corresponding hash would be: `sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4=`. If you want to generate an integrity string yourself for existing data, you can use something like this: ```javascript const crypto = require('crypto') const hashAlgorithm = 'sha512' const data = 'foobarbaz' const integrity = ( hashAlgorithm + '-' + crypto.createHash(hashAlgorithm).update(data).digest('base64') ) ``` You can also use [`ssri`](https://npm.im/ssri) to have a richer set of functionality around SRI strings, including generation, parsing, and translating from existing hex-formatted strings. #### <a name="verify"></a> `> cacache.verify(cache, opts) -> Promise` Checks out and fixes up your cache: * Cleans up corrupted or invalid index entries. * Custom entry filtering options. * Garbage collects any content entries not referenced by the index. * Checks integrity for all content entries and removes invalid content. * Fixes cache ownership. * Removes the `tmp` directory in the cache and all its contents. When it's done, it'll return an object with various stats about the verification process, including amount of storage reclaimed, number of valid entries, number of entries removed, etc. ##### <a name="verify-options"></a> Options ##### `opts.concurrency` Default: 20 Number of concurrently read files in the filesystem while doing clean up. ##### `opts.filter` Receives a formatted entry. Return false to remove it. Note: might be called more than once on the same entry. ##### `opts.log` Custom logger function: ``` log: { silly () {} } log.silly('verify', 'verifying cache at', cache) ``` ##### Example ```sh echo somegarbage >> $CACHEPATH/content/deadbeef ``` ```javascript cacache.verify(cachePath).then(stats => { // deadbeef collected, because of invalid checksum. console.log('cache is much nicer now! stats:', stats) }) ``` #### <a name="verify-last-run"></a> `> cacache.verify.lastRun(cache) -> Promise` Returns a `Date` representing the last time `cacache.verify` was run on `cache`. ##### Example ```javascript cacache.verify(cachePath).then(() => { cacache.verify.lastRun(cachePath).then(lastTime => { console.log('cacache.verify was last called on' + lastTime) }) }) ``` ����������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/SECURITY.md��������������������������������������������������������������������������0000664�0000000�0000000�00000002467�14344174136�0014762�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!-- This file is automatically added by @npmcli/template-oss. Do not edit. --> GitHub takes the security of our software products and services seriously, including the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub). If you believe you have found a security vulnerability in this GitHub-owned open source repository, you can report it to us in one of two ways. If the vulnerability you have found is *not* [in scope for the GitHub Bug Bounty Program](https://bounty.github.com/#scope) or if you do not wish to be considered for a bounty reward, please report the issue to us directly using [private vulnerability reporting](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability). If the vulnerability you have found is [in scope for the GitHub Bug Bounty Program](https://bounty.github.com/#scope) and you would like for your finding to be considered for a bounty reward, please submit the vulnerability to us through [HackerOne](https://hackerone.com/github) in order to be eligible to receive a bounty award. **Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** Thanks for helping make GitHub safe for everyone. ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/���������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0013726�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/content/�������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0015400�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/content/path.js������������������������������������������������������������������0000664�0000000�0000000�00000001341�14344174136�0016671�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const contentVer = require('../../package.json')['cache-version'].content const hashToSegments = require('../util/hash-to-segments') const path = require('path') const ssri = require('ssri') // Current format of content file path: // // sha512-BaSE64Hex= -> // ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee // module.exports = contentPath function contentPath (cache, integrity) { const sri = ssri.parse(integrity, { single: true }) // contentPath is the *strongest* algo given return path.join( contentDir(cache), sri.algorithm, ...hashToSegments(sri.hexDigest()) ) } module.exports.contentDir = contentDir function contentDir (cache) { return path.join(cache, `content-v${contentVer}`) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/content/read.js������������������������������������������������������������������0000664�0000000�0000000�00000010471�14344174136�0016654�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const fsm = require('fs-minipass') const ssri = require('ssri') const contentPath = require('./path') const Pipeline = require('minipass-pipeline') module.exports = read const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 async function read (cache, integrity, opts = {}) { const { size } = opts const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // get size const stat = await fs.stat(cpath) return { stat, cpath, sri } }) if (typeof size === 'number' && stat.size !== size) { throw sizeError(size, stat.size) } if (stat.size > MAX_SINGLE_READ_SIZE) { return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() } const data = await fs.readFile(cpath, { encoding: null }) if (!ssri.checkData(data, sri)) { throw integrityError(sri, cpath) } return data } const readPipeline = (cpath, size, sri, stream) => { stream.push( new fsm.ReadStream(cpath, { size, readSize: MAX_SINGLE_READ_SIZE, }), ssri.integrityStream({ integrity: sri, size, }) ) return stream } module.exports.stream = readStream module.exports.readStream = readStream function readStream (cache, integrity, opts = {}) { const { size } = opts const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { // just stat to ensure it exists const stat = await fs.stat(cpath) return { stat, cpath, sri } }) if (typeof size === 'number' && size !== stat.size) { return stream.emit('error', sizeError(size, stat.size)) } return readPipeline(cpath, stat.size, sri, stream) }).catch(err => stream.emit('error', err)) return stream } module.exports.copy = copy function copy (cache, integrity, dest) { return withContentSri(cache, integrity, (cpath, sri) => { return fs.copyFile(cpath, dest) }) } module.exports.hasContent = hasContent async function hasContent (cache, integrity) { if (!integrity) { return false } try { return await withContentSri(cache, integrity, async (cpath, sri) => { const stat = await fs.stat(cpath) return { size: stat.size, sri, stat } }) } catch (err) { if (err.code === 'ENOENT') { return false } if (err.code === 'EPERM') { /* istanbul ignore else */ if (process.platform !== 'win32') { throw err } else { return false } } } } async function withContentSri (cache, integrity, fn) { const sri = ssri.parse(integrity) // If `integrity` has multiple entries, pick the first digest // with available local data. const algo = sri.pickAlgorithm() const digests = sri[algo] if (digests.length <= 1) { const cpath = contentPath(cache, digests[0]) return fn(cpath, digests[0]) } else { // Can't use race here because a generic error can happen before // a ENOENT error, and can happen before a valid result const results = await Promise.all(digests.map(async (meta) => { try { return await withContentSri(cache, meta, fn) } catch (err) { if (err.code === 'ENOENT') { return Object.assign( new Error('No matching content found for ' + sri.toString()), { code: 'ENOENT' } ) } return err } })) // Return the first non error if it is found const result = results.find((r) => !(r instanceof Error)) if (result) { return result } // Throw the No matching content found error const enoentError = results.find((r) => r.code === 'ENOENT') if (enoentError) { throw enoentError } // Throw generic error throw results.find((r) => r instanceof Error) } } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function integrityError (sri, path) { const err = new Error(`Integrity verification failed for ${sri} (${path})`) err.code = 'EINTEGRITY' err.sri = sri err.path = path return err } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/content/rm.js��������������������������������������������������������������������0000664�0000000�0000000�00000000741�14344174136�0016356�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const contentPath = require('./path') const { hasContent } = require('./read') module.exports = rm async function rm (cache, integrity) { const content = await hasContent(cache, integrity) // ~pretty~ sure we can't end up with a content lacking sri, but be safe if (content && content.sri) { await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) return true } else { return false } } �������������������������������cacache-17.0.3/lib/content/write.js�����������������������������������������������������������������0000664�0000000�0000000�00000012021�14344174136�0017064�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const events = require('events') const contentPath = require('./path') const fs = require('fs/promises') const moveFile = require('../util/move-file') const Minipass = require('minipass') const Pipeline = require('minipass-pipeline') const Flush = require('minipass-flush') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const fsm = require('fs-minipass') module.exports = write async function write (cache, data, opts = {}) { const { algorithms, size, integrity } = opts if (algorithms && algorithms.length > 1) { throw new Error('opts.algorithms only supports a single algorithm for now') } if (typeof size === 'number' && data.length !== size) { throw sizeError(size, data.length) } const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) if (integrity && !ssri.checkData(data, integrity, opts)) { throw checksumError(integrity, sri) } const tmp = await makeTmp(cache, opts) try { await fs.writeFile(tmp.target, data, { flag: 'wx' }) await moveToDestination(tmp, cache, sri, opts) return { integrity: sri, size: data.length } } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } module.exports.stream = writeStream // writes proxied to the 'inputStream' that is passed to the Promise // 'end' is deferred until content is handled. class CacacheWriteStream extends Flush { constructor (cache, opts) { super() this.opts = opts this.cache = cache this.inputStream = new Minipass() this.inputStream.on('error', er => this.emit('error', er)) this.inputStream.on('drain', () => this.emit('drain')) this.handleContentP = null } write (chunk, encoding, cb) { if (!this.handleContentP) { this.handleContentP = handleContent( this.inputStream, this.cache, this.opts ) } return this.inputStream.write(chunk, encoding, cb) } flush (cb) { this.inputStream.end(() => { if (!this.handleContentP) { const e = new Error('Cache input stream was empty') e.code = 'ENODATA' // empty streams are probably emitting end right away. // defer this one tick by rejecting a promise on it. return Promise.reject(e).catch(cb) } // eslint-disable-next-line promise/catch-or-return this.handleContentP.then( (res) => { res.integrity && this.emit('integrity', res.integrity) // eslint-disable-next-line promise/always-return res.size !== null && this.emit('size', res.size) cb() }, (er) => cb(er) ) }) } } function writeStream (cache, opts = {}) { return new CacacheWriteStream(cache, opts) } async function handleContent (inputStream, cache, opts) { const tmp = await makeTmp(cache, opts) try { const res = await pipeToTmp(inputStream, cache, tmp.target, opts) await moveToDestination( tmp, cache, res.integrity, opts ) return res } finally { if (!tmp.moved) { await fs.rm(tmp.target, { recursive: true, force: true }) } } } async function pipeToTmp (inputStream, cache, tmpTarget, opts) { const outStream = new fsm.WriteStream(tmpTarget, { flags: 'wx', }) if (opts.integrityEmitter) { // we need to create these all simultaneously since they can fire in any order const [integrity, size] = await Promise.all([ events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), events.once(opts.integrityEmitter, 'size').then(res => res[0]), new Pipeline(inputStream, outStream).promise(), ]) return { integrity, size } } let integrity let size const hashStream = ssri.integrityStream({ integrity: opts.integrity, algorithms: opts.algorithms, size: opts.size, }) hashStream.on('integrity', i => { integrity = i }) hashStream.on('size', s => { size = s }) const pipeline = new Pipeline(inputStream, hashStream, outStream) await pipeline.promise() return { integrity, size } } async function makeTmp (cache, opts) { const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) return { target: tmpTarget, moved: false, } } async function moveToDestination (tmp, cache, sri, opts) { const destination = contentPath(cache, sri) const destDir = path.dirname(destination) await fs.mkdir(destDir, { recursive: true }) await moveFile(tmp.target, destination) tmp.moved = true } function sizeError (expected, found) { /* eslint-disable-next-line max-len */ const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) err.expected = expected err.found = found err.code = 'EBADSIZE' return err } function checksumError (expected, found) { const err = new Error(`Integrity check failed: Wanted: ${expected} Found: ${found}`) err.code = 'EINTEGRITY' err.expected = expected err.found = found return err } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/entry-index.js�������������������������������������������������������������������0000664�0000000�0000000�00000021624�14344174136�0016537�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const crypto = require('crypto') const { appendFile, mkdir, readFile, readdir, rm, writeFile, } = require('fs/promises') const Minipass = require('minipass') const path = require('path') const ssri = require('ssri') const uniqueFilename = require('unique-filename') const contentPath = require('./content/path') const hashToSegments = require('./util/hash-to-segments') const indexV = require('../package.json')['cache-version'].index const { moveFile } = require('@npmcli/fs') module.exports.NotFoundError = class NotFoundError extends Error { constructor (cache, key) { super(`No cache entry for ${key} found in ${cache}`) this.code = 'ENOENT' this.cache = cache this.key = key } } module.exports.compact = compact async function compact (cache, key, matchFn, opts = {}) { const bucket = bucketPath(cache, key) const entries = await bucketEntries(bucket) const newEntries = [] // we loop backwards because the bottom-most result is the newest // since we add new entries with appendFile for (let i = entries.length - 1; i >= 0; --i) { const entry = entries[i] // a null integrity could mean either a delete was appended // or the user has simply stored an index that does not map // to any content. we determine if the user wants to keep the // null integrity based on the validateEntry function passed in options. // if the integrity is null and no validateEntry is provided, we break // as we consider the null integrity to be a deletion of everything // that came before it. if (entry.integrity === null && !opts.validateEntry) { break } // if this entry is valid, and it is either the first entry or // the newEntries array doesn't already include an entry that // matches this one based on the provided matchFn, then we add // it to the beginning of our list if ((!opts.validateEntry || opts.validateEntry(entry) === true) && (newEntries.length === 0 || !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { newEntries.unshift(entry) } } const newIndex = '\n' + newEntries.map((entry) => { const stringified = JSON.stringify(entry) const hash = hashEntry(stringified) return `${hash}\t${stringified}` }).join('\n') const setup = async () => { const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) await mkdir(path.dirname(target), { recursive: true }) return { target, moved: false, } } const teardown = async (tmp) => { if (!tmp.moved) { return rm(tmp.target, { recursive: true, force: true }) } } const write = async (tmp) => { await writeFile(tmp.target, newIndex, { flag: 'wx' }) await mkdir(path.dirname(bucket), { recursive: true }) // we use @npmcli/move-file directly here because we // want to overwrite the existing file await moveFile(tmp.target, bucket) tmp.moved = true } // write the file atomically const tmp = await setup() try { await write(tmp) } finally { await teardown(tmp) } // we reverse the list we generated such that the newest // entries come first in order to make looping through them easier // the true passed to formatEntry tells it to keep null // integrity values, if they made it this far it's because // validateEntry returned true, and as such we should return it return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) } module.exports.insert = insert async function insert (cache, key, integrity, opts = {}) { const { metadata, size } = opts const bucket = bucketPath(cache, key) const entry = { key, integrity: integrity && ssri.stringify(integrity), time: Date.now(), size, metadata, } try { await mkdir(path.dirname(bucket), { recursive: true }) const stringified = JSON.stringify(entry) // NOTE - Cleverness ahoy! // // This works because it's tremendously unlikely for an entry to corrupt // another while still preserving the string length of the JSON in // question. So, we just slap the length in there and verify it on read. // // Thanks to @isaacs for the whiteboarding session that ended up with // this. await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } return formatEntry(cache, entry) } module.exports.find = find async function find (cache, key) { const bucket = bucketPath(cache, key) try { const entries = await bucketEntries(bucket) return entries.reduce((latest, next) => { if (next && next.key === key) { return formatEntry(cache, next) } else { return latest } }, null) } catch (err) { if (err.code === 'ENOENT') { return null } else { throw err } } } module.exports.delete = del function del (cache, key, opts = {}) { if (!opts.removeFully) { return insert(cache, key, null, opts) } const bucket = bucketPath(cache, key) return rm(bucket, { recursive: true, force: true }) } module.exports.lsStream = lsStream function lsStream (cache) { const indexDir = bucketDir(cache) const stream = new Minipass({ objectMode: true }) // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const buckets = await readdirOrEmpty(indexDir) await Promise.all(buckets.map(async (bucket) => { const bucketPath = path.join(indexDir, bucket) const subbuckets = await readdirOrEmpty(bucketPath) await Promise.all(subbuckets.map(async (subbucket) => { const subbucketPath = path.join(bucketPath, subbucket) // "/cachename/<bucket 0xFF>/<bucket 0xFF>./*" const subbucketEntries = await readdirOrEmpty(subbucketPath) await Promise.all(subbucketEntries.map(async (entry) => { const entryPath = path.join(subbucketPath, entry) try { const entries = await bucketEntries(entryPath) // using a Map here prevents duplicate keys from showing up // twice, I guess? const reduced = entries.reduce((acc, entry) => { acc.set(entry.key, entry) return acc }, new Map()) // reduced is a map of key => entry for (const entry of reduced.values()) { const formatted = formatEntry(cache, entry) if (formatted) { stream.write(formatted) } } } catch (err) { if (err.code === 'ENOENT') { return undefined } throw err } })) })) })) stream.end() return stream }).catch(err => stream.emit('error', err)) return stream } module.exports.ls = ls async function ls (cache) { const entries = await lsStream(cache).collect() return entries.reduce((acc, xs) => { acc[xs.key] = xs return acc }, {}) } module.exports.bucketEntries = bucketEntries async function bucketEntries (bucket, filter) { const data = await readFile(bucket, 'utf8') return _bucketEntries(data, filter) } function _bucketEntries (data, filter) { const entries = [] data.split('\n').forEach((entry) => { if (!entry) { return } const pieces = entry.split('\t') if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { // Hash is no good! Corruption or malice? Doesn't matter! // EJECT EJECT return } let obj try { obj = JSON.parse(pieces[1]) } catch (_) { // eslint-ignore-next-line no-empty-block } // coverage disabled here, no need to test with an entry that parses to something falsey // istanbul ignore else if (obj) { entries.push(obj) } }) return entries } module.exports.bucketDir = bucketDir function bucketDir (cache) { return path.join(cache, `index-v${indexV}`) } module.exports.bucketPath = bucketPath function bucketPath (cache, key) { const hashed = hashKey(key) return path.join.apply( path, [bucketDir(cache)].concat(hashToSegments(hashed)) ) } module.exports.hashKey = hashKey function hashKey (key) { return hash(key, 'sha256') } module.exports.hashEntry = hashEntry function hashEntry (str) { return hash(str, 'sha1') } function hash (str, digest) { return crypto .createHash(digest) .update(str) .digest('hex') } function formatEntry (cache, entry, keepAll) { // Treat null digests as deletions. They'll shadow any previous entries. if (!entry.integrity && !keepAll) { return null } return { key: entry.key, integrity: entry.integrity, path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, size: entry.size, time: entry.time, metadata: entry.metadata, } } function readdirOrEmpty (dir) { return readdir(dir).catch((err) => { if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { return [] } throw err }) } ������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/get.js���������������������������������������������������������������������������0000664�0000000�0000000�00000010552�14344174136�0015046�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const Collect = require('minipass-collect') const Minipass = require('minipass') const Pipeline = require('minipass-pipeline') const index = require('./entry-index') const memo = require('./memoization') const read = require('./content/read') async function getData (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return { metadata: memoized.entry.metadata, data: memoized.data, integrity: memoized.entry.integrity, size: memoized.entry.size, } } const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } const data = await read(cache, entry.integrity, { integrity, size }) if (memoize) { memo.put(cache, entry, data, opts) } return { data, metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports = getData async function getDataByDigest (cache, key, opts = {}) { const { integrity, memoize, size } = opts const memoized = memo.get.byDigest(cache, key, opts) if (memoized && memoize !== false) { return memoized } const res = await read(cache, key, { integrity, size }) if (memoize) { memo.put.byDigest(cache, key, res, opts) } return res } module.exports.byDigest = getDataByDigest const getMemoizedStream = (memoized) => { const stream = new Minipass() stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(memoized.entry.metadata) ev === 'integrity' && cb(memoized.entry.integrity) ev === 'size' && cb(memoized.entry.size) }) stream.end(memoized.data) return stream } function getStream (cache, key, opts = {}) { const { memoize, size } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return getMemoizedStream(memoized) } const stream = new Pipeline() // Set all this up to run on the stream and then just return the stream Promise.resolve().then(async () => { const entry = await index.find(cache, key) if (!entry) { throw new index.NotFoundError(cache, key) } stream.emit('metadata', entry.metadata) stream.emit('integrity', entry.integrity) stream.emit('size', entry.size) stream.on('newListener', function (ev, cb) { ev === 'metadata' && cb(entry.metadata) ev === 'integrity' && cb(entry.integrity) ev === 'size' && cb(entry.size) }) const src = read.readStream( cache, entry.integrity, { ...opts, size: typeof size !== 'number' ? entry.size : size } ) if (memoize) { const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put(cache, entry, data, opts)) stream.unshift(memoStream) } stream.unshift(src) return stream }).catch((err) => stream.emit('error', err)) return stream } module.exports.stream = getStream function getStreamDigest (cache, integrity, opts = {}) { const { memoize } = opts const memoized = memo.get.byDigest(cache, integrity, opts) if (memoized && memoize !== false) { const stream = new Minipass() stream.end(memoized) return stream } else { const stream = read.readStream(cache, integrity, opts) if (!memoize) { return stream } const memoStream = new Collect.PassThrough() memoStream.on('collect', data => memo.put.byDigest( cache, integrity, data, opts )) return new Pipeline(stream, memoStream) } } module.exports.stream.byDigest = getStreamDigest function info (cache, key, opts = {}) { const { memoize } = opts const memoized = memo.get(cache, key, opts) if (memoized && memoize !== false) { return Promise.resolve(memoized.entry) } else { return index.find(cache, key) } } module.exports.info = info async function copy (cache, key, dest, opts = {}) { const entry = await index.find(cache, key, opts) if (!entry) { throw new index.NotFoundError(cache, key) } await read.copy(cache, entry.integrity, dest, opts) return { metadata: entry.metadata, size: entry.size, integrity: entry.integrity, } } module.exports.copy = copy async function copyByDigest (cache, key, dest, opts = {}) { await read.copy(cache, key, dest, opts) return key } module.exports.copy.byDigest = copyByDigest module.exports.hasContent = read.hasContent ������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/index.js�������������������������������������������������������������������������0000664�0000000�0000000�00000002326�14344174136�0015376�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const get = require('./get.js') const put = require('./put.js') const rm = require('./rm.js') const verify = require('./verify.js') const { clearMemoized } = require('./memoization.js') const tmp = require('./util/tmp.js') const index = require('./entry-index.js') module.exports.index = {} module.exports.index.compact = index.compact module.exports.index.insert = index.insert module.exports.ls = index.ls module.exports.ls.stream = index.lsStream module.exports.get = get module.exports.get.byDigest = get.byDigest module.exports.get.stream = get.stream module.exports.get.stream.byDigest = get.stream.byDigest module.exports.get.copy = get.copy module.exports.get.copy.byDigest = get.copy.byDigest module.exports.get.info = get.info module.exports.get.hasContent = get.hasContent module.exports.put = put module.exports.put.stream = put.stream module.exports.rm = rm.entry module.exports.rm.all = rm.all module.exports.rm.entry = module.exports.rm module.exports.rm.content = rm.content module.exports.clearMemoized = clearMemoized module.exports.tmp = {} module.exports.tmp.mkdir = tmp.mkdir module.exports.tmp.withTmp = tmp.withTmp module.exports.verify = verify module.exports.verify.lastRun = verify.lastRun ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/memoization.js�������������������������������������������������������������������0000664�0000000�0000000�00000002677�14344174136�0016633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const LRU = require('lru-cache') const MEMOIZED = new LRU({ max: 500, maxSize: 50 * 1024 * 1024, // 50MB ttl: 3 * 60 * 1000, // 3 minutes sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, }) module.exports.clearMemoized = clearMemoized function clearMemoized () { const old = {} MEMOIZED.forEach((v, k) => { old[k] = v }) MEMOIZED.clear() return old } module.exports.put = put function put (cache, entry, data, opts) { pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) putDigest(cache, entry.integrity, data, opts) } module.exports.put.byDigest = putDigest function putDigest (cache, integrity, data, opts) { pickMem(opts).set(`digest:${cache}:${integrity}`, data) } module.exports.get = get function get (cache, key, opts) { return pickMem(opts).get(`key:${cache}:${key}`) } module.exports.get.byDigest = getDigest function getDigest (cache, integrity, opts) { return pickMem(opts).get(`digest:${cache}:${integrity}`) } class ObjProxy { constructor (obj) { this.obj = obj } get (key) { return this.obj[key] } set (key, val) { this.obj[key] = val } } function pickMem (opts) { if (!opts || !opts.memoize) { return MEMOIZED } else if (opts.memoize.get && opts.memoize.set) { return opts.memoize } else if (typeof opts.memoize === 'object') { return new ObjProxy(opts.memoize) } else { return MEMOIZED } } �����������������������������������������������������������������cacache-17.0.3/lib/put.js���������������������������������������������������������������������������0000664�0000000�0000000�00000003667�14344174136�0015110�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const index = require('./entry-index') const memo = require('./memoization') const write = require('./content/write') const Flush = require('minipass-flush') const { PassThrough } = require('minipass-collect') const Pipeline = require('minipass-pipeline') const putOpts = (opts) => ({ algorithms: ['sha512'], ...opts, }) module.exports = putData async function putData (cache, key, data, opts = {}) { const { memoize } = opts opts = putOpts(opts) const res = await write(cache, data, opts) const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) if (memoize) { memo.put(cache, entry, data, opts) } return res.integrity } module.exports.stream = putStream function putStream (cache, key, opts = {}) { const { memoize } = opts opts = putOpts(opts) let integrity let size let error let memoData const pipeline = new Pipeline() // first item in the pipeline is the memoizer, because we need // that to end first and get the collected data. if (memoize) { const memoizer = new PassThrough().on('collect', data => { memoData = data }) pipeline.push(memoizer) } // contentStream is a write-only, not a passthrough // no data comes out of it. const contentStream = write.stream(cache, opts) .on('integrity', (int) => { integrity = int }) .on('size', (s) => { size = s }) .on('error', (err) => { error = err }) pipeline.push(contentStream) // last but not least, we write the index and emit hash and size, // and memoize if we're doing that pipeline.push(new Flush({ async flush () { if (!error) { const entry = await index.insert(cache, key, integrity, { ...opts, size }) if (memoize && memoData) { memo.put(cache, entry, memoData, opts) } pipeline.emit('integrity', integrity) pipeline.emit('size', size) } }, })) return pipeline } �������������������������������������������������������������������������cacache-17.0.3/lib/rm.js����������������������������������������������������������������������������0000664�0000000�0000000�00000001427�14344174136�0014706�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { rm } = require('fs/promises') const glob = require('./util/glob.js') const index = require('./entry-index') const memo = require('./memoization') const path = require('path') const rmContent = require('./content/rm') module.exports = entry module.exports.entry = entry function entry (cache, key, opts) { memo.clearMemoized() return index.delete(cache, key, opts) } module.exports.content = content function content (cache, integrity) { memo.clearMemoized() return rmContent(cache, integrity) } module.exports.all = all async function all (cache) { memo.clearMemoized() const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/util/����������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0014703�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/util/glob.js���������������������������������������������������������������������0000664�0000000�0000000�00000000331�14344174136�0016161�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { promisify } = require('util') const glob = promisify(require('glob')) const globify = (pattern) => pattern.split('//').join('/') module.exports = (path, options) => glob(globify(path), options) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/util/hash-to-segments.js���������������������������������������������������������0000664�0000000�0000000�00000000217�14344174136�0020427�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' module.exports = hashToSegments function hashToSegments (hash) { return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/util/move-file.js����������������������������������������������������������������0000664�0000000�0000000�00000003564�14344174136�0017134�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const { moveFile: move } = require('@npmcli/fs') const pinflight = require('promise-inflight') module.exports = moveFile async function moveFile (src, dest) { const isWindows = process.platform === 'win32' // This isn't quite an fs.rename -- the assumption is that // if `dest` already exists, and we get certain errors while // trying to move it, we should just not bother. // // In the case of cache corruption, users will receive an // EINTEGRITY error elsewhere, and can remove the offending // content their own way. // // Note that, as the name suggests, this strictly only supports file moves. try { await fs.link(src, dest) } catch (err) { if (isWindows && err.code === 'EPERM') { // XXX This is a really weird way to handle this situation, as it // results in the src file being deleted even though the dest // might not exist. Since we pretty much always write files to // deterministic locations based on content hash, this is likely // ok (or at worst, just ends in a future cache miss). But it would // be worth investigating at some time in the future if this is // really what we want to do here. } else if (err.code === 'EEXIST' || err.code === 'EBUSY') { // file already exists, so whatever } else { throw err } } try { await Promise.all([ fs.unlink(src), !isWindows && fs.chmod(dest, '0444'), ]) } catch (e) { return pinflight('cacache-move-file:' + dest, async () => { await fs.stat(dest).catch((err) => { if (err.code !== 'ENOENT') { // Something else is wrong here. Bail bail bail throw err } }) // file doesn't already exist! let's try a rename -> copy fallback // only delete if it successfully copies return move(src, dest) }) } } ��������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/util/tmp.js����������������������������������������������������������������������0000664�0000000�0000000�00000001270�14344174136�0016041�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { withTempDir } = require('@npmcli/fs') const fs = require('fs/promises') const path = require('path') module.exports.mkdir = mktmpdir async function mktmpdir (cache, opts = {}) { const { tmpPrefix } = opts const tmpDir = path.join(cache, 'tmp') await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) // do not use path.join(), it drops the trailing / if tmpPrefix is unset const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` return fs.mkdtemp(target, { owner: 'inherit' }) } module.exports.withTmp = withTmp function withTmp (cache, opts, cb) { if (!cb) { cb = opts opts = {} } return withTempDir(path.join(cache, 'tmp'), cb, opts) } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/lib/verify.js������������������������������������������������������������������������0000664�0000000�0000000�00000014571�14344174136�0015600�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { mkdir, readFile, rm, stat, truncate, writeFile, } = require('fs/promises') const pMap = require('p-map') const contentPath = require('./content/path') const fsm = require('fs-minipass') const glob = require('./util/glob.js') const index = require('./entry-index') const path = require('path') const ssri = require('ssri') const hasOwnProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key) const verifyOpts = (opts) => ({ concurrency: 20, log: { silly () {} }, ...opts, }) module.exports = verify async function verify (cache, opts) { opts = verifyOpts(opts) opts.log.silly('verify', 'verifying cache at', cache) const steps = [ markStartTime, fixPerms, garbageCollect, rebuildIndex, cleanTmp, writeVerifile, markEndTime, ] const stats = {} for (const step of steps) { const label = step.name const start = new Date() const s = await step(cache, opts) if (s) { Object.keys(s).forEach((k) => { stats[k] = s[k] }) } const end = new Date() if (!stats.runTime) { stats.runTime = {} } stats.runTime[label] = end - start } stats.runTime.total = stats.endTime - stats.startTime opts.log.silly( 'verify', 'verification finished for', cache, 'in', `${stats.runTime.total}ms` ) return stats } async function markStartTime (cache, opts) { return { startTime: new Date() } } async function markEndTime (cache, opts) { return { endTime: new Date() } } async function fixPerms (cache, opts) { opts.log.silly('verify', 'fixing cache permissions') await mkdir(cache, { recursive: true }) return null } // Implements a naive mark-and-sweep tracing garbage collector. // // The algorithm is basically as follows: // 1. Read (and filter) all index entries ("pointers") // 2. Mark each integrity value as "live" // 3. Read entire filesystem tree in `content-vX/` dir // 4. If content is live, verify its checksum and delete it if it fails // 5. If content is not marked as live, rm it. // async function garbageCollect (cache, opts) { opts.log.silly('verify', 'garbage collecting content') const indexStream = index.lsStream(cache) const liveContent = new Set() indexStream.on('data', (entry) => { if (opts.filter && !opts.filter(entry)) { return } liveContent.add(entry.integrity.toString()) }) await new Promise((resolve, reject) => { indexStream.on('end', resolve).on('error', reject) }) const contentDir = contentPath.contentDir(cache) const files = await glob(path.join(contentDir, '**'), { follow: false, nodir: true, nosort: true, }) const stats = { verifiedContent: 0, reclaimedCount: 0, reclaimedSize: 0, badContentCount: 0, keptSize: 0, } await pMap( files, async (f) => { const split = f.split(/[/\\]/) const digest = split.slice(split.length - 3).join('') const algo = split[split.length - 4] const integrity = ssri.fromHex(digest, algo) if (liveContent.has(integrity.toString())) { const info = await verifyContent(f, integrity) if (!info.valid) { stats.reclaimedCount++ stats.badContentCount++ stats.reclaimedSize += info.size } else { stats.verifiedContent++ stats.keptSize += info.size } } else { // No entries refer to this content. We can delete. stats.reclaimedCount++ const s = await stat(f) await rm(f, { recursive: true, force: true }) stats.reclaimedSize += s.size } return stats }, { concurrency: opts.concurrency } ) return stats } async function verifyContent (filepath, sri) { const contentInfo = {} try { const { size } = await stat(filepath) contentInfo.size = size contentInfo.valid = true await ssri.checkStream(new fsm.ReadStream(filepath), sri) } catch (err) { if (err.code === 'ENOENT') { return { size: 0, valid: false } } if (err.code !== 'EINTEGRITY') { throw err } await rm(filepath, { recursive: true, force: true }) contentInfo.valid = false } return contentInfo } async function rebuildIndex (cache, opts) { opts.log.silly('verify', 'rebuilding index') const entries = await index.ls(cache) const stats = { missingContent: 0, rejectedEntries: 0, totalEntries: 0, } const buckets = {} for (const k in entries) { /* istanbul ignore else */ if (hasOwnProperty(entries, k)) { const hashed = index.hashKey(k) const entry = entries[k] const excluded = opts.filter && !opts.filter(entry) excluded && stats.rejectedEntries++ if (buckets[hashed] && !excluded) { buckets[hashed].push(entry) } else if (buckets[hashed] && excluded) { // skip } else if (excluded) { buckets[hashed] = [] buckets[hashed]._path = index.bucketPath(cache, k) } else { buckets[hashed] = [entry] buckets[hashed]._path = index.bucketPath(cache, k) } } } await pMap( Object.keys(buckets), (key) => { return rebuildBucket(cache, buckets[key], stats, opts) }, { concurrency: opts.concurrency } ) return stats } async function rebuildBucket (cache, bucket, stats, opts) { await truncate(bucket._path) // This needs to be serialized because cacache explicitly // lets very racy bucket conflicts clobber each other. for (const entry of bucket) { const content = contentPath(cache, entry.integrity) try { await stat(content) await index.insert(cache, entry.key, entry.integrity, { metadata: entry.metadata, size: entry.size, }) stats.totalEntries++ } catch (err) { if (err.code === 'ENOENT') { stats.rejectedEntries++ stats.missingContent++ } else { throw err } } } } function cleanTmp (cache, opts) { opts.log.silly('verify', 'cleaning tmp directory') return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) } async function writeVerifile (cache, opts) { const verifile = path.join(cache, '_lastverified') opts.log.silly('verify', 'writing verifile to ' + verifile) return writeFile(verifile, `${Date.now()}`) } module.exports.lastRun = lastRun async function lastRun (cache) { const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) return new Date(+data) } ���������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/package.json�������������������������������������������������������������������������0000664�0000000�0000000�00000003676�14344174136�0015462�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "name": "cacache", "version": "17.0.3", "cache-version": { "content": "2", "index": "5" }, "description": "Fast, fault-tolerant, cross-platform, disk-based, data-agnostic, content-addressable cache.", "main": "lib/index.js", "files": [ "bin/", "lib/" ], "scripts": { "test": "tap", "snap": "tap", "coverage": "tap", "test-docker": "docker run -it --rm --name pacotest -v \"$PWD\":/tmp -w /tmp node:latest npm test", "lint": "eslint \"**/*.js\"", "npmclilint": "npmcli-lint", "lintfix": "npm run lint -- --fix", "postsnap": "npm run lintfix --", "postlint": "template-oss-check", "posttest": "npm run lint", "template-oss-apply": "template-oss-apply --force" }, "repository": { "type": "git", "url": "https://github.com/npm/cacache.git" }, "keywords": [ "cache", "caching", "content-addressable", "sri", "sri hash", "subresource integrity", "cache", "storage", "store", "file store", "filesystem", "disk cache", "disk storage" ], "license": "ISC", "dependencies": { "@npmcli/fs": "^3.1.0", "fs-minipass": "^2.1.0", "glob": "^8.0.1", "lru-cache": "^7.7.1", "minipass": "^4.0.0", "minipass-collect": "^1.0.2", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^4.0.0", "promise-inflight": "^1.0.1", "ssri": "^10.0.0", "tar": "^6.1.11", "unique-filename": "^3.0.0" }, "devDependencies": { "@npmcli/eslint-config": "^4.0.0", "@npmcli/template-oss": "4.10.0", "tap": "^16.0.0" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", "windowsCI": false, "version": "4.10.0" }, "author": "GitHub Inc.", "tap": { "nyc-arg": [ "--exclude", "tap-snapshots/**" ] } } ������������������������������������������������������������������cacache-17.0.3/release-please-config.json�����������������������������������������������������������0000664�0000000�0000000�00000001254�14344174136�0020207�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{ "exclude-packages-from-root": true, "group-pull-request-title-pattern": "chore: release ${version}", "pull-request-title-pattern": "chore: release${component} ${version}", "changelog-sections": [ { "type": "feat", "section": "Features", "hidden": false }, { "type": "fix", "section": "Bug Fixes", "hidden": false }, { "type": "docs", "section": "Documentation", "hidden": false }, { "type": "deps", "section": "Dependencies", "hidden": false }, { "type": "chore", "hidden": true } ], "packages": { ".": { "package-name": "" } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/��������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0014137�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/content/������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0015611�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/content/read.js�����������������������������������������������������������������0000664�0000000�0000000�00000017741�14344174136�0017074�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs') const path = require('path') const ssri = require('ssri') const t = require('tap') const CacheContent = require('../fixtures/cache-content') const read = require('../../lib/content/read') // defines reusable errors const genericError = new Error('ERR') genericError.code = 'ERR' const permissionError = new Error('EPERM') permissionError.code = 'EPERM' // helpers const getRead = (t, opts) => t.mock('../../lib/content/read', opts) const getReadStatFailure = (t, err) => getRead(t, { fs: { ...fs, statSync: () => { throw err }, }, 'fs/promises': { ...fs.promises, stat: async (path) => { throw err }, }, }) t.test('read: returns a Promise with cache content data', async t => { const CONTENT = Buffer.from('foobarbaz') const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const data = await read(CACHE, INTEGRITY) t.same(data, CONTENT, 'cache contents read correctly') }) t.test('read.stream: returns a stream with cache content data', async t => { const CONTENT = Buffer.from('foobarbaz') const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const stream = read.stream(CACHE, INTEGRITY) const [fromStream, fromBulk] = await Promise.all([ stream.concat(), read(CACHE, INTEGRITY, { size: CONTENT.length }), ]) t.same(fromStream, CONTENT, 'stream data checks out') t.same(fromBulk, CONTENT, 'promise data checks out') }) t.test('read: allows hashAlgorithm configuration', async t => { const CONTENT = Buffer.from('foobarbaz') const HASH = 'sha384' const INTEGRITY = ssri.fromData(CONTENT, { algorithms: [HASH] }) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const stream = read.stream(CACHE, INTEGRITY) const [fromStream, fromBulk] = await Promise.all([ stream.concat(), read(CACHE, INTEGRITY), ]) t.same(fromStream, CONTENT, 'stream used algorithm') t.same(fromBulk, CONTENT, 'promise used algorithm') }) t.test('read: errors if content missing', async t => { const CACHE = t.testdir({}) const stream = read.stream(CACHE, 'sha512-whatnot') stream.on('data', function (data) { throw new Error('unexpected data: ' + JSON.stringify(data)) }) stream.on('end', function () { throw new Error('end was emitted even though stream errored') }) await t.rejects( stream.promise(), { code: 'ENOENT' }, 'stream got the right error' ) await t.rejects( read(CACHE, 'sha512-whatnot'), { code: 'ENOENT' }, 'bulk got the right error' ) }) t.test('read: errors if content fails checksum', async t => { const CONTENT = Buffer.from('foobarbaz') const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT.slice(3), // invalid contents! }) ) const stream = read.readStream(CACHE, INTEGRITY) stream.on('end', function () { throw new Error('end was emitted even though stream errored') }) await t.rejects( stream.promise(), { code: 'EINTEGRITY' }, 'stream got the right error' ) await t.rejects( read(CACHE, INTEGRITY), { code: 'EINTEGRITY' }, 'bulk got the right error' ) }) t.test('read: errors if content size does not match size option', async t => { const CONTENT = Buffer.from('foobarbaz') const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT.slice(3), // invalid contents! }) ) const stream = read.readStream(CACHE, INTEGRITY, { size: CONTENT.length }) stream.on('end', function () { throw new Error('end was called even though stream errored') }) await t.rejects( stream.promise(), { code: 'EBADSIZE' }, 'stream got the right error' ) await t.rejects( read(CACHE, INTEGRITY, { size: CONTENT.length }), { code: 'EBADSIZE' }, 'bulk got the right error' ) }) t.test('read: error while parsing provided integrity data', function (t) { const CACHE = t.testdir() const INTEGRITY = 'sha1-deadbeef' const mockedRead = getRead(t, { ssri: { parse (sri) { throw genericError }, }, }) t.plan(1) return t.rejects( mockedRead(CACHE, INTEGRITY), genericError, 'should reject promise upon catching internal errors' ) }) t.test('read: unknown error parsing nested integrity data', function (t) { const CACHE = t.testdir() const INTEGRITY = 'sha1-deadbeef sha1-13371337' // patches method in order to force a last error scenario const mockedRead = getRead(t, { ssri: { parse (sri) { if (sri !== INTEGRITY) { throw genericError } return ssri.parse(sri) }, }, }) t.plan(1) return t.rejects( mockedRead(CACHE, INTEGRITY), genericError, 'should throw unknown errors' ) }) t.test('read: returns only first result if other hashes fails', function (t) { // sets up a cache that has multiple entries under the // same algorithm but then only one has real contents in the fs const CONTENT = { foo: Buffer.from('foo'), bar: Buffer.from('bar'), } const INTEGRITY = ssri.fromData(CONTENT.foo).concat( ssri.fromData(CONTENT.bar) ) const CACHE = t.testdir( CacheContent({ [INTEGRITY.sha512[1]]: CONTENT.bar, }) ) t.plan(1) return t.resolveMatch( read(CACHE, INTEGRITY), CONTENT.bar, 'should return only the first valid result' ) }) t.test('read: opening large files', function (t) { const CACHE = t.testdir() const mockedRead = getRead(t, { 'fs/promises': { ...fs.promises, stat: async (path) => { return { size: Number.MAX_SAFE_INTEGER } }, }, 'fs-minipass': { ReadStream: class { constructor (path, opts) { t.match( opts, { readSize: 64 * 1024 * 1024, size: Number.MAX_SAFE_INTEGER, }, 'should use fs-minipass interface' ) } }, }, 'minipass-pipeline': Array, }) t.plan(1) mockedRead(CACHE, 'sha1-deadbeef') }) t.test('hasContent: tests content existence', async t => { const CACHE = t.testdir( CacheContent({ 'sha1-deadbeef': '', }) ) const content = await read.hasContent(CACHE, 'sha1-deadbeef') t.ok(content.sri, 'returned sri for this content') t.equal(content.size, 0, 'returned the right size for this content') t.ok(content.stat.isFile(), 'returned actual stat object') await t.resolveMatch( read.hasContent(CACHE, 'sha1-not-there'), false, 'returned false for missing content' ) await t.resolveMatch( read.hasContent(CACHE, 'sha1-not-here sha1-also-not-here'), false, 'multi-content hash failures work ok' ) }) t.test('hasContent: permission error', (t) => { const CACHE = t.testdir() // setup a syntetic permission error const mockedRead = getReadStatFailure(t, permissionError) t.plan(1) t.rejects( mockedRead.hasContent(CACHE, 'sha1-deadbeef sha1-13371337'), permissionError, 'should reject on permission errors' ) }) t.test('hasContent: generic error', (t) => { const CACHE = t.testdir() const mockedRead = getReadStatFailure(t, genericError) t.plan(1) t.resolves( mockedRead.hasContent(CACHE, 'sha1-deadbeef sha1-13371337'), 'should not reject on generic errors' ) }) t.test('hasContent: no integrity provided', (t) => { const CACHE = t.testdir() t.resolveMatch( read.hasContent(CACHE, ''), false, 'should resolve with a value of false' ) t.end() }) t.test('copy: copies content to a destination path', async t => { const CONTENT = Buffer.from('foobarbaz') const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const DEST = path.join(CACHE, 'foobar-file') await read.copy(CACHE, INTEGRITY, DEST) const data = await fs.promises.readFile(DEST) t.same(data, CONTENT, 'file successfully copied') }) �������������������������������cacache-17.0.3/test/content/rm.js�������������������������������������������������������������������0000664�0000000�0000000�00000002077�14344174136�0016573�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const contentPath = require('../../lib/content/path') const fs = require('fs/promises') const t = require('tap') const CacheContent = require('../fixtures/cache-content') const rm = require('../../lib/content/rm') t.test('removes a content entry', function (t) { const CACHE = t.testdir( CacheContent({ 'sha1-deadbeef': '', }) ) return rm(CACHE, 'sha1-deadbeef') .then(() => fs.stat(contentPath(CACHE, 'sha1-deadbeef'))) .then(() => { throw new Error('expected an error') }) .catch((err) => { t.ok(err, 'fs.stat failed on rmed content') t.equal('ENOENT', err.code, 'file does not exist anymore') }) }) t.test('works fine if entry missing', function (t) { const CACHE = t.testdir(CacheContent({})) return rm(CACHE, 'sha1-deadbeef') .then(() => fs.stat(contentPath(CACHE, 'sha1-deadbeef'))) .then(() => { throw new Error('expected an error') }) .catch((err) => { t.ok(err, 'fs.stat failed on rmed content') t.equal('ENOENT', err.code, 'file does not exist anymore') }) }) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/content/write.js����������������������������������������������������������������0000664�0000000�0000000�00000024245�14344174136�0017310�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const events = require('events') const fs = require('fs') const Minipass = require('minipass') const path = require('path') const ssri = require('ssri') const t = require('tap') const CacheContent = require('../fixtures/cache-content') const contentPath = require('../../lib/content/path') const write = require('../../lib/content/write') t.test('basic put', async t => { const CACHE = t.testdir() const CONTENT = 'foobarbaz' // Default is sha512 const INTEGRITY = ssri.fromData(CONTENT) let integrity await write.stream(CACHE).on('integrity', (i) => { integrity = i }).end(CONTENT).promise() const cpath = contentPath(CACHE, integrity) t.same(integrity, INTEGRITY, 'calculated integrity value matches') t.ok(fs.lstatSync(cpath).isFile(), 'content inserted as a single file') t.equal(fs.readFileSync(cpath, 'utf8'), CONTENT, 'contents are identical to inserted content') }) t.test('basic put, providing external integrity emitter', async (t) => { const CACHE = t.testdir() const CONTENT = 'foobarbaz' const INTEGRITY = ssri.fromData(CONTENT) const write = t.mock('../../lib/content/write.js', { ssri: { ...ssri, integrityStream: () => { throw new Error('Should not be called') }, }, }) const source = new Minipass().end(CONTENT) const tee = new Minipass() const integrityStream = ssri.integrityStream() // since the integrityStream is not going anywhere, we need to manually resume it // otherwise it'll get stuck in paused mode and will never process any data events integrityStream.resume() const integrityStreamP = Promise.all([ events.once(integrityStream, 'integrity').then((res) => res[0]), events.once(integrityStream, 'size').then((res) => res[0]), ]) const contentStream = write.stream(CACHE, { integrityEmitter: integrityStream }) const contentStreamP = Promise.all([ events.once(contentStream, 'integrity').then((res) => res[0]), events.once(contentStream, 'size').then((res) => res[0]), contentStream.promise(), ]) tee.pipe(integrityStream) tee.pipe(contentStream) source.pipe(tee) const [ [ssriIntegrity, ssriSize], [contentIntegrity, contentSize], ] = await Promise.all([ integrityStreamP, contentStreamP, ]) t.equal(ssriSize, CONTENT.length, 'ssri got the right size') t.equal(contentSize, CONTENT.length, 'content got the right size') t.same(ssriIntegrity, INTEGRITY, 'ssri got the right integrity') t.same(contentIntegrity, INTEGRITY, 'content got the right integrity') const cpath = contentPath(CACHE, ssriIntegrity) t.ok(fs.lstatSync(cpath).isFile(), 'content inserted as a single file') t.equal(fs.readFileSync(cpath, 'utf8'), CONTENT, 'contents are identical to inserted content') }) t.test("checks input digest doesn't match data", async t => { const CONTENT = 'foobarbaz' const integrity = ssri.fromData(CONTENT) let int1 = null let int2 = null const CACHE = t.testdir() await t.rejects( write.stream(CACHE, { integrity }).on('integrity', (int) => { int1 = int }) .end('bazbarfoo').promise(), { code: 'EINTEGRITY' }, 'returns integrity error' ) t.equal(int1, null, 'no digest emitted') await write.stream(CACHE, { integrity }).on('integrity', int => { int2 = int }) .end(CONTENT).promise() t.same(int2, integrity, 'returns a matching digest') }) t.test('errors if stream ends with no data', async t => { const CACHE = t.testdir() let integrity = null await t.rejects( write.stream(CACHE).end('').on('integrity', int => { integrity = int }).promise(), { code: 'ENODATA' }, 'get an error with a useful code' ) t.equal(integrity, null, 'no digest returned') }) t.test('errors if input size does not match expected', async t => { let int1 = null let int2 = null const CACHE = t.testdir() await t.rejects( write.stream(CACHE, { size: 5 }).on('integrity', int => { int1 = int }).end('abc').promise(), { code: 'EBADSIZE', expected: 5, found: 3 }, 'get an error when data smaller than expected' ) t.equal(int1, null, 'no digest returned') await t.rejects( write.stream(CACHE, { size: 5 }).on('integrity', int => { int2 = int }).end('abcdefghi').promise(), { code: 'EBADSIZE', expected: 5, found: 9 }, 'get an error when data bigger than expected' ) t.equal(int2, null, 'no digest returned') }) t.test('does not overwrite content if already on disk', async t => { const CONTENT = 'foobarbaz' const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: 'nope', }) ) let int1 let int2 // With a digest -- early short-circuiting await write.stream(CACHE, { integrity: INTEGRITY }).on('integrity', int => { int1 = int }) .end(CONTENT).promise() t.same(int1, INTEGRITY, 'short-circuit returns a matching digest') const d1 = fs.readFileSync(contentPath(CACHE, INTEGRITY), 'utf8') t.equal(d1, 'nope', 'process short-circuited. Data not written.') await write.stream(CACHE).on('integrity', int => { int2 = int }) .end(CONTENT).promise() t.same(int2, INTEGRITY, 'full write returns a matching digest') const d2 = fs.readFileSync(contentPath(CACHE, INTEGRITY), 'utf8') t.equal(d2, 'nope', 'previously-written data intact - no dupe write') }) t.test('errors if input stream errors', async t => { let integrity = null const CACHE = t.testdir() const putter = write.stream(CACHE) .on('integrity', (int) => { integrity = int }) setTimeout(() => putter.inputStream.emit('error', new Error('bleh'))) await t.rejects(putter.promise(), { message: 'bleh' }) t.equal(integrity, null, 'no digest returned') t.throws(() => { fs.statSync(contentPath(CACHE, ssri.fromData('foobarbaz'))) }, { code: 'ENOENT', }, 'target file missing. No files created') }) t.test('exits normally if file already open', (t) => { const CONTENT = 'foobarbaz' const INTEGRITY = ssri.fromData(CONTENT) const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) let integrity // This case would only fail on Windows, when an entry is being read. // Generally, you'd get an EBUSY back. fs.open(contentPath(CACHE, INTEGRITY), 'r+', async function (err, fd) { if (err) { throw err } await write.stream(CACHE).on('integrity', int => { integrity = int }) .end(CONTENT) .promise() t.same(integrity, INTEGRITY, 'returns a matching digest') fs.closeSync(fd) fs.rmSync(contentPath(CACHE, INTEGRITY), { recursive: true, force: true }) t.end() }) }) t.test('cleans up tmp on successful completion', async t => { const CONTENT = 'foobarbaz' const CACHE = t.testdir() await write.stream(CACHE).end(CONTENT).promise() await new Promise((resolve, reject) => { const tmp = path.join(CACHE, 'tmp') fs.readdir(tmp, function (err, files) { if (!err || (err && err.code === 'ENOENT')) { files = files || [] t.same(files, [], 'nothing in the tmp dir!') resolve() } else { reject(err) } }) }) }) t.test('cleans up tmp on streaming error', (t) => { const CONTENT = 'foobarbaz' const CACHE = t.testdir() return t.rejects( write.stream(CACHE, { size: 1 }) .end(CONTENT) .promise(), { code: 'EBADSIZE' }, 'got expected code' ) .then(() => new Promise((resolve, reject) => { const tmp = path.join(CACHE, 'tmp') fs.readdir(tmp, function (err, files) { if (!err || (err && err.code === 'ENOENT')) { files = files || [] t.same(files, [], 'nothing in the tmp dir!') resolve() } else { reject(err) } }) })) }) t.test('cleans up tmp on non streaming error', (t) => { // mock writefile and make it reject const CONTENT = 'foobarbaz' const CACHE = t.testdir({ 'content-v2': 'oh no a file' }) return t.rejects(write(CACHE, CONTENT)) .then(() => new Promise((resolve, reject) => { const tmp = path.join(CACHE, 'tmp') fs.readdir(tmp, function (err, files) { if (!err || (err && err.code === 'ENOENT')) { files = files || [] t.same(files, [], 'nothing in the tmp dir!') resolve() } else { reject(err) } }) })) }) t.test('checks the size of stream data if opts.size provided', (t) => { const CONTENT = 'foobarbaz' let int1 = null const int2 = null let int3 = null const CACHE = t.testdir() t.test('chair too small', t => { const w = write.stream(CACHE, { size: CONTENT.length }) w.write(CONTENT.slice(3)) w.on('integrity', int => { int1 = int }) setTimeout(() => w.end()) return t.rejects(w.promise(), { code: 'EBADSIZE' }, 'bad size error code') .then(() => t.equal(int1, null, 'no digest returned by first stream')) }) t.test('chair is too big', t => { const w = write.stream(CACHE, { size: CONTENT.length }) w.write(CONTENT) setTimeout(() => w.end('quux')) return t.rejects(w.promise(), { code: 'EBADSIZE' }, 'bad size error code') .then(() => t.equal(int2, null, 'no digest returned by second stream')) }) return t.test('chair is juuuuust right', t => { const w = write.stream(CACHE, { size: CONTENT.length }) w.write(CONTENT) w.on('integrity', int => { int3 = int }) setTimeout(() => w.end()) return w.promise().then(() => t.ok(int3, 'got a digest')) }) }) t.test('only one algorithm for now', async t => { const CACHE = t.testdir() await t.rejects(() => write(CACHE, 'foo', { algorithms: [1, 2] }), { message: 'opts.algorithms only supports a single algorithm for now', }) }) t.test('writes to cache with default options', t => { const CACHE = t.testdir() return t.resolveMatch(write(CACHE, 'foo'), { size: 3, integrity: { sha512: [ { /* eslint-disable-next-line max-len */ source: 'sha512-9/u6bgY2+JDlb7vzKD5STG+jIErimDgtYkdB0NxmODJuKCxBvl5CVNiCB3LFUYosWowMf37aGVlKfrU5RT4e1w==', /* eslint-disable-next-line max-len */ digest: '9/u6bgY2+JDlb7vzKD5STG+jIErimDgtYkdB0NxmODJuKCxBvl5CVNiCB3LFUYosWowMf37aGVlKfrU5RT4e1w==', algorithm: 'sha512', options: [], }, ], }, }) }) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/entry-index.find.js�������������������������������������������������������������0000664�0000000�0000000�00000012031�14344174136�0017657�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const CacheIndex = require('./fixtures/cache-index') const path = require('path') const t = require('tap') const SIZE = 999 const contentPath = require('../lib/content/path') const index = require('../lib/entry-index') t.test('index.find cache hit', async t => { const entry = { key: 'whatever', integrity: 'whatnot-deadbeef', time: 12345, metadata: 'omgsometa', size: 5, } const CACHE = t.testdir( CacheIndex({ whatever: entry, }) ) const info = await index.find(CACHE, entry.key) t.ok(info, 'cache hit') t.equal( info.path, contentPath(CACHE, entry.integrity), 'path added to info' ) delete info.path t.same(info, entry, 'rest of info matches entry on disk') }) t.test('index.find cache miss', async t => { const CACHE = t.testdir( CacheIndex({ foo: { key: 'foo' }, 'w/e': { key: 'w/e' }, }) ) await t.resolveMatch( index.find(CACHE, 'whatever'), null, 'cache miss when specific key not present' ) }) t.test('index.find no cache', async t => { await t.resolveMatch( index.find(path.resolve('adirectorythatdoesnotexit'), 'whatever'), null, 'if there is no cache dir, behaves like a cache miss' ) }) t.test('index.find key case-sensitivity', async t => { const CACHE = t.testdir( CacheIndex({ jsonstream: { key: 'jsonstream', integrity: 'sha1-lowercase', time: 54321, size: SIZE, }, JSONStream: { key: 'JSONStream', integrity: 'sha1-capitalised', time: 12345, size: SIZE, }, }) ) await t.resolveMatch( index.find(CACHE, 'JSONStream'), { key: 'JSONStream' }, 'fetched the correct entry' ) await t.resolveMatch( index.find(CACHE, 'jsonstream'), { key: 'jsonstream' }, 'fetched the correct entry' ) await t.resolveMatch( index.find(CACHE, 'jsonStream'), null, 'no entry for jsonStream' ) }) t.test('index.find path-breaking characters', async t => { const entry = { key: ';;!registry\nhttps://registry.npmjs.org/back \\ slash@Cool™?', integrity: 'sha1-deadbeef', time: 12345, metadata: 'omgsometa', size: 9, } const CACHE = t.testdir( CacheIndex({ [entry.key]: entry, }) ) const info = await index.find(CACHE, entry.key) t.ok(info, 'cache hit') delete info.path t.same( info, entry, 'info remains intact even with fs-unfriendly chars' ) }) t.test('index.find extremely long keys', async t => { let key = '' for (let i = 0; i < 10000; i++) { key += i } const entry = { key: key, integrity: 'sha1-deadbeef', time: 12345, metadata: 'woo', size: 10, } const CACHE = t.testdir( CacheIndex({ [entry.key]: entry, }) ) const info = await index.find(CACHE, entry.key) t.ok(info, 'cache hit') delete info.path t.same(info, entry, 'info remains intact even with absurdly long key') }) t.test('index.find multiple index entries for key', async t => { const key = 'whatever' const CACHE = t.testdir( CacheIndex({ whatever: [ { key: key, integrity: 'sha1-deadbeef', time: 54321 }, { key: key, integrity: 'sha1-bada55', time: 12345 }, ], }) ) const info = await index.find(CACHE, key) t.ok(info, 'cache hit') t.equal(info.integrity, 'sha1-bada55', 'most recent entry wins') }) t.test('index.find garbled data in index file', async t => { // Even though `index.insert()` is safe from direct // race conditions, it's still possible for individual // entries to become corrupted, or to be partially written, // since `index.find` does not acquire a write-preventing lock. // // Because entries are newline-prepended and only one // can be written at a time, the main possible corruption // source is if an append fails mid-write (for example, due // to the process crashing). In this case, the corrupt entry // will simply be skipped. const key = 'whatever' const stringified = JSON.stringify({ key: key, integrity: 'sha1-deadbeef', time: 54321, }) const CACHE = t.testdir( CacheIndex({ whatever: '\n' + `${index.hashEntry(stringified)}\t${stringified}` + '\n{"key": "' + key + '"\noway', }) ) const info = await index.find(CACHE, key) t.ok(info, 'cache hit in spite of crash-induced fail') t.equal(info.integrity, 'sha1-deadbeef', ' recent entry wins') }) t.test('index.find hash conflict in same bucket', async t => { // This... is very unlikely to happen. But hey. const entry = { key: 'whatever', integrity: 'sha1-deadbeef', time: 12345, metadata: 'yay', size: 8, } const CACHE = t.testdir( CacheIndex({ whatever: [ { key: 'ohnoes', integrity: 'sha1-welp!' }, entry, { key: 'nope', integrity: 'sha1-bada55' }, ], }) ) const info = await index.find(CACHE, entry.key) t.ok(info, 'cache hit') delete info.path t.same( info, entry, 'got the right one even though different keys exist in index' ) }) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/entry-index.insert.js�����������������������������������������������������������0000664�0000000�0000000�00000013363�14344174136�0020254�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const CacheIndex = require('./fixtures/cache-index') const contentPath = require('../lib/content/path') const fs = require('fs/promises') const t = require('tap') const index = require('../lib/entry-index') const key = 'foo' const integrity = 'sha512-deadbeef' const size = 999 t.test('basic insertion', async t => { const cache = t.testdir({}) const bucket = index.bucketPath(cache, key) const insertEntry = await index.insert(cache, key, integrity, { size, metadata: 'foo' }) t.same( insertEntry, { key, integrity, path: contentPath(cache, integrity), time: insertEntry.time, metadata: 'foo', size, }, 'formatted entry returned' ) const data = await fs.readFile(bucket, 'utf8') t.equal(data[0], '\n', 'first entry starts with a \\n') const split = data.split('\t') t.equal( split[0].slice(1), index.hashEntry(split[1]), 'consistency header correct' ) const entry = JSON.parse(split[1]) t.ok(entry.time, 'entry has a timestamp') t.same( entry, { key, integrity, time: entry.time, metadata: 'foo', size, }, 'entry matches what was inserted' ) }) t.test('inserts additional entries into existing key', async t => { const cache = t.testdir({}) const bucket = index.bucketPath(cache, key) await index.insert(cache, key, integrity, { size, metadata: 1 }) await index.insert(cache, key, integrity, { size, metadata: 2 }) const data = await fs.readFile(bucket, 'utf8') const entries = data .split('\n') .slice(1) .map((line) => { return JSON.parse(line.split('\t')[1]) }) entries.forEach(function (e) { delete e.time }) t.same( entries, [ { key, integrity, metadata: 1, size, }, { key, integrity, metadata: 2, size, }, ], 'all entries present' ) }) t.test('separates entries even if one is corrupted', async t => { // TODO - check that middle-of-string corrupted writes won't hurt. const cache = t.testdir( CacheIndex({ foo: '\n' + JSON.stringify({ key, integrity: 'meh', time: 54321, size, }) + '\n{"key": "' + key + '"\noway', }) ) const bucket = index.bucketPath(cache, key) await index.insert(cache, key, integrity, { size }) const data = await fs.readFile(bucket, 'utf8') const entry = JSON.parse(data.split('\n')[4].split('\t')[1]) delete entry.time t.same( entry, { key, integrity, size, }, 'new entry unaffected by corruption' ) }) t.test('optional arbitrary metadata', async t => { const cache = t.testdir({}) const bucket = index.bucketPath(cache, key) const metadata = { foo: 'bar' } await index.insert(cache, key, integrity, { size, metadata: metadata }) const data = await fs.readFile(bucket, 'utf8') const entry = JSON.parse(data.split('\t')[1]) delete entry.time t.same( entry, { key, integrity, metadata: metadata, size, }, 'entry includes inserted metadata' ) }) t.test('key case-sensitivity', async t => { const cache = t.testdir({}) await Promise.all([ index.insert(cache, key, integrity, { size }), index.insert(cache, key.toUpperCase(), `${integrity}upper`, { size }), ]) const [entry, upperEntry] = await Promise.all([ index.find(cache, key), index.find(cache, key.toUpperCase()), ]) delete entry.time delete upperEntry.time t.same( { key: entry.key, integrity: entry.integrity, size, }, { key, integrity, size, }, 'regular entry exists' ) t.same( { key: upperEntry.key, integrity: upperEntry.integrity, size, }, { key: key.toUpperCase(), integrity: `${integrity}upper`, size, }, 'case-variant entry intact' ) }) t.test('path-breaking characters', async t => { const cache = t.testdir({}) const newKey = ';;!registry\nhttps://registry.npmjs.org/back \\ slash@Cool™?' await index.insert(cache, newKey, integrity, { size }) const bucket = index.bucketPath(cache, newKey) const data = await fs.readFile(bucket, 'utf8') const entry = JSON.parse(data.split('\t')[1]) delete entry.time t.same( entry, { key: newKey, integrity, size, }, 'entry exists and matches original key with invalid chars' ) }) t.test('extremely long keys', async t => { const cache = t.testdir({}) let newKey = '' for (let i = 0; i < 10000; i++) { newKey += i } await index.insert(cache, newKey, integrity, { size }) const bucket = index.bucketPath(cache, newKey) const data = await fs.readFile(bucket, 'utf8') const entry = JSON.parse(data.split('\t')[1]) delete entry.time t.same( entry, { key: newKey, integrity, size, }, 'entry exists in spite of INCREDIBLY LONG key' ) }) t.test('ENOENT from appendFile is ignored', async (t) => { const cache = t.testdir() const indexMocked = t.mock('../lib/entry-index.js', { 'fs/promises': { ...fs, appendFile: async () => { throw Object.assign(new Error('fake enoent'), { code: 'ENOENT' }) }, }, }) await t.resolves(() => indexMocked.insert(cache, key, integrity, { size })) }) t.test('generic error from appendFile rejects', async (t) => { const cache = t.testdir() const indexMocked = t.mock('../lib/entry-index.js', { 'fs/promises': { ...fs, appendFile: async () => { throw Object.assign(new Error('fake eperm'), { code: 'EPERM' }) }, }, }) await t.rejects(() => indexMocked.insert(cache, key, integrity, { size }), { code: 'EPERM' }) }) t.test('concurrent writes') �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/entry-index.js������������������������������������������������������������������0000664�0000000�0000000�00000020372�14344174136�0016747�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs') const path = require('path') const ssri = require('ssri') const t = require('tap') const index = require('../lib/entry-index') const CacheContent = require('./fixtures/cache-content') // defines reusable errors const genericError = new Error('ERR') genericError.code = 'ERR' const missingFileError = new Error('ENOENT') missingFileError.code = 'ENOENT' const getEntryIndex = (t, opts) => t.mock('../lib/entry-index', opts) const getEntryIndexReadFileFailure = (t, err) => getEntryIndex(t, { 'fs/promises': { ...fs.promises, readFile: async (path, encode) => { throw err }, }, fs: { ...fs, readFileSync: () => { throw genericError }, }, }) // helpers const CONTENT = Buffer.from('foobarbaz', 'utf8') const INTEGRITY = ssri.fromData(CONTENT).toString() const KEY = 'my-test-key' const cacheContent = CacheContent({ [INTEGRITY]: CONTENT, }) t.test('compact', async (t) => { const cache = t.testdir(cacheContent) await Promise.all([ index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), ]) const bucket = index.bucketPath(cache, KEY) const entries = await index.bucketEntries(bucket) t.equal(entries.length, 4, 'started with 4 entries') const filter = (entryA, entryB) => entryA.metadata.rev === entryB.metadata.rev const compacted = await index.compact(cache, KEY, filter) t.equal(compacted.length, 2, 'should return only two entries') const newEntries = await index.bucketEntries(bucket) t.equal(newEntries.length, 2, 'bucket was deduplicated') }) t.test('compact: treats null integrity without validateEntry as a delete', async (t) => { const cache = t.testdir(cacheContent) // this one does not use Promise.all because we want to be certain // things are written in the right order await index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }) await index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }) // this is a delete, revs 1, 2 and 3 will be omitted await index.insert(cache, KEY, null, { metadata: { rev: 3 } }) await index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 4 } }) const bucket = index.bucketPath(cache, KEY) const entries = await index.bucketEntries(bucket) t.equal(entries.length, 4, 'started with 4 entries') const filter = (entryA, entryB) => entryA.metadata.rev === entryB.metadata.rev const compacted = await index.compact(cache, KEY, filter) t.equal(compacted.length, 1, 'should return only one entry') t.equal(compacted[0].metadata.rev, 4, 'kept rev 4') const newEntries = await index.bucketEntries(bucket) t.equal(newEntries.length, 1, 'bucket was deduplicated') }) t.test('compact: leverages validateEntry to skip invalid entries', async (t) => { const cache = t.testdir(cacheContent) await Promise.all([ index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), ]) const bucket = index.bucketPath(cache, KEY) const entries = await index.bucketEntries(bucket) t.equal(entries.length, 4, 'started with 4 entries') const matchFn = (entryA, entryB) => entryA.metadata.rev === entryB.metadata.rev const validateEntry = (entry) => entry.metadata.rev > 1 const compacted = await index.compact(cache, KEY, matchFn, { validateEntry }) t.equal(compacted.length, 1, 'should return only one entries') t.equal(compacted[0].metadata.rev, 2, 'kept the rev 2 entry') const newEntries = await index.bucketEntries(bucket) t.equal(newEntries.length, 1, 'bucket was deduplicated') }) t.test('compact: validateEntry allows for keeping null integrity', async (t) => { const cache = t.testdir(cacheContent) await Promise.all([ index.insert(cache, KEY, null, { metadata: { rev: 1 } }), index.insert(cache, KEY, null, { metadata: { rev: 2 } }), index.insert(cache, KEY, null, { metadata: { rev: 2 } }), index.insert(cache, KEY, null, { metadata: { rev: 1 } }), ]) const bucket = index.bucketPath(cache, KEY) const entries = await index.bucketEntries(bucket) t.equal(entries.length, 4, 'started with 4 entries') const matchFn = (entryA, entryB) => entryA.metadata.rev === entryB.metadata.rev const validateEntry = (entry) => entry.metadata.rev > 1 const compacted = await index.compact(cache, KEY, matchFn, { validateEntry }) t.equal(compacted.length, 1, 'should return only one entry') t.equal(compacted[0].metadata.rev, 2, 'kept the rev 2 entry') const newEntries = await index.bucketEntries(bucket) t.equal(newEntries.length, 1, 'bucket was deduplicated') }) t.test('compact: error in moveFile removes temp', async (t) => { const cache = t.testdir(cacheContent) await Promise.all([ index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 2 } }), index.insert(cache, KEY, INTEGRITY, { metadata: { rev: 1 } }), ]) const { compact } = getEntryIndex(t, { '@npmcli/fs': { moveFile: () => Promise.reject(new Error('foo')) }, }) const filter = (entryA, entryB) => entryA.metadata.rev === entryB.metadata.rev await t.rejects(compact(cache, KEY, filter), { message: 'foo' }, 'promise rejected') const tmpFiles = fs.readdirSync(path.join(cache, 'tmp')) t.equal(tmpFiles.length, 0, 'temp file is gone') }) t.test('delete: removeFully deletes the index entirely', async (t) => { const cache = t.testdir(cacheContent) const bucket = index.bucketPath(cache, KEY) await index.insert(cache, KEY, INTEGRITY) const entries = await index.bucketEntries(bucket) t.equal(entries.length, 1, 'has an entry') // do a normal delete first, this appends a null integrity await index.delete(cache, KEY) const delEntries = await index.bucketEntries(bucket) t.equal(delEntries.length, 2, 'should now have 2 entries') t.equal(delEntries[1].integrity, null, 'has a null integrity last') // then a full delete await index.delete(cache, KEY, { removeFully: true }) await t.rejects( index.bucketEntries(bucket), { code: 'ENOENT' }, 'rejects with ENOENT because file is gone' ) }) t.test('find: error on parsing json data', (t) => { const cache = t.testdir(cacheContent) // mocks readFile in order to return a borked json payload const { find } = getEntryIndex(t, { '@npmcli/fs': Object.assign({}, require('@npmcli/fs'), { readFile: async (path, encode) => { return '\ncec8d2e4685534ed189b563c8ee1cb1cb7c72874\t{"""// foo' }, }), }) t.plan(1) t.resolveMatch( find(cache, KEY), null, 'should resolve with null' ) }) t.test('find: unknown error on finding entries', (t) => { const cache = t.testdir(cacheContent) const { find } = getEntryIndexReadFileFailure(t, genericError) t.plan(1) t.rejects( find(cache, KEY), genericError, 'should reject with the unknown error thrown' ) }) t.test('lsStream: unknown error reading files', async (t) => { const cache = t.testdir(cacheContent) await index.insert(cache, KEY, INTEGRITY) const { lsStream } = getEntryIndexReadFileFailure(t, genericError) return new Promise((resolve) => { lsStream(cache) .on('error', err => { t.equal(err, genericError, 'should emit an error') resolve() }) }) }) t.test('lsStream: missing files error', async (t) => { const cache = t.testdir(cacheContent) await index.insert(cache, KEY, INTEGRITY) const { lsStream } = getEntryIndexReadFileFailure(t, missingFileError) return new Promise((resolve, reject) => { lsStream(cache) .on('error', reject) .on('end', resolve) }) }) t.test('lsStream: unknown error reading dirs', (t) => { const cache = t.testdir(cacheContent) const { lsStream } = getEntryIndex(t, { 'fs/promises': { ...fs.promises, readdir: async (path) => { throw genericError }, }, }) lsStream(cache) .on('error', err => { t.equal(err, genericError, 'should emit an error') t.end() }) }) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/fixtures/�����������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0016010�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/fixtures/cache-content.js�������������������������������������������������������0000664�0000000�0000000�00000001162�14344174136�0021061�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const contentPath = require('../../lib/content/path') const path = require('path') module.exports = CacheContent function CacheContent (entries) { const tree = {} Object.keys(entries).forEach(function (k) { const cpath = contentPath('', k) const content = entries[k] const parts = cpath.split(path.sep) insertContent(tree, parts, content) }) return tree } function insertContent (tree, pathTo, content) { const key = pathTo[0] if (pathTo.length <= 1) { tree[key] = content } else { tree[key] = tree[key] || {} insertContent(tree[key], pathTo.slice(1), content) } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/fixtures/cache-index.js���������������������������������������������������������0000664�0000000�0000000�00000002521�14344174136�0020516�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const index = require('../../lib/entry-index') const path = require('path') const bucketPath = index.bucketPath const hashEntry = index.hashEntry // Creates a simulated index using the chained lookup structure, from // an unhashed version of the index (basically `cacache.ls`). // // The returned object is for use with Tacks module.exports = CacheIndex function CacheIndex (entries) { const tree = {} Object.keys(entries).forEach(function (k) { const bpath = bucketPath('', k) const parts = bpath.split(path.sep) let lines = entries[k] let serialised if (typeof lines === 'string') { serialised = lines } else { if (typeof lines.length !== 'number') { lines = [lines] } serialised = '\n' + lines .map((line) => { const stringified = JSON.stringify(line) return `${hashEntry(stringified)}\t${stringified}` }) .join('\n') } insertContent(tree, parts, serialised) }) return tree } function insertContent (tree, pathTo, content) { const key = pathTo[0] if (pathTo.length <= 1) { if (tree[key]) { tree[key] = [tree[key], content].join('\n') } else { tree[key] = content } } else { tree[key] = tree[key] || {} insertContent(tree[key], pathTo.slice(1), content) } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/get.js��������������������������������������������������������������������������0000664�0000000�0000000�00000031027�14344174136�0015257�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const index = require('../lib/entry-index') const memo = require('../lib/memoization') const path = require('path') const t = require('tap') const ssri = require('ssri') const CacheContent = require('./fixtures/cache-content') const CONTENT = Buffer.from('foobarbaz', 'utf8') const SIZE = CONTENT.length const KEY = 'my-test-key' const INTEGRITY = ssri.fromData(CONTENT).toString() const METADATA = { foo: 'bar' } const { get } = require('..') function opts (extra) { return Object.assign( { size: SIZE, metadata: METADATA, }, extra ) } // Simple wrapper util cause this gets WORDY function streamGet (byDigest) { const args = [].slice.call(arguments, 1) let integrity let metadata let size const stream = (byDigest ? get.stream.byDigest : get.stream).apply(null, args) return stream .on('integrity', (int) => { integrity = ssri.stringify(int) }) .on('metadata', (m) => { metadata = m }) .on('size', (s) => { size = s }) .concat() .then((data) => ({ data, integrity, metadata, size, })) } t.test('get.info index entry lookup', async t => { const CACHE = t.testdir() const indexInsert = await index.insert(CACHE, KEY, INTEGRITY, opts()) const entry = await get.info(CACHE, KEY) t.same(entry, indexInsert, 'get.info() returned the right entry') }) t.test('get will throw ENOENT if not found', (t) => { const CACHE = t.testdir() return get(CACHE, KEY) .then(() => { throw new Error('lookup should fail') }) .catch((err) => { t.ok(err, 'got an error') t.equal(err.code, 'ENOENT', 'error code is ENOENT') return get.info(CACHE, KEY) }) .catch((err) => { t.ok(err, 'got an error') t.equal(err.code, 'ENOENT', 'error code is ENOENT') }) }) t.test('basic bulk get', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) await t.resolveMatch( get(CACHE, KEY), { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'bulk key get returned proper data' ) await t.resolveMatch( get.byDigest(CACHE, INTEGRITY), CONTENT, 'byDigest returned proper data' ) }) t.test('get.byDigest without memoization', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) const res = await get(CACHE, KEY) t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'bulk key get returned proper data') memo.clearMemoized() t.same(memo.get.byDigest(CACHE, INTEGRITY), undefined) const resByDig = await get.byDigest(CACHE, INTEGRITY) t.same(resByDig, CONTENT, 'byDigest returned proper data') t.same(memo.get.byDigest(CACHE, INTEGRITY), undefined) const resByDigMemo = await get.byDigest(CACHE, INTEGRITY) t.same(resByDigMemo, CONTENT, 'byDigest returned proper data') }) t.test('get.byDigest with memoization', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) const res = await get(CACHE, KEY) t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'bulk key get returned proper data') memo.clearMemoized() t.same(memo.get.byDigest(CACHE, INTEGRITY), undefined) const resByDig = await get.byDigest(CACHE, INTEGRITY, { memoize: true }) t.same(resByDig, CONTENT, 'byDigest returned proper data') t.notSame(memo.get.byDigest(CACHE, INTEGRITY), undefined) const resByDigMemo = await get.byDigest(CACHE, INTEGRITY, { memoize: true }) t.same(resByDigMemo, CONTENT, 'byDigest returned proper data') }) t.test('get without memoization', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) const res = await get(CACHE, KEY) t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'bulk key get returned proper data') memo.clearMemoized() t.same(memo.get(CACHE, KEY), undefined) const resByDig = await get(CACHE, KEY) t.same(resByDig, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'get returned proper data') t.same(memo.get(CACHE, KEY), undefined) const resByDigMemo = await get(CACHE, KEY) t.same(resByDigMemo, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'get returned proper data') }) t.test('get with memoization', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) const res = await get(CACHE, KEY) t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'bulk key get returned proper data') memo.clearMemoized() t.same(memo.get(CACHE, KEY), undefined) const resByDig = await get(CACHE, KEY, { memoize: true }) t.same(resByDig, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'get returned proper data') t.notSame(memo.get(CACHE, KEY), undefined) const resByDigMemo = await get(CACHE, KEY, { memoize: true }) t.same(resByDigMemo, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'get returned proper data') }) t.test('basic stream get', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) await index.insert(CACHE, KEY, INTEGRITY, opts()) const [byKey, byDigest] = await Promise.all([ streamGet(false, CACHE, KEY), streamGet(true, CACHE, INTEGRITY), ]) t.same( byKey, { data: CONTENT, integrity: INTEGRITY, metadata: METADATA, size: SIZE, }, 'got all expected data and fields from key fetch' ) t.same(byDigest.data, CONTENT, 'got correct data from digest fetch') }) t.test('get.stream add new listeners post stream creation', async (t) => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) return index.insert(CACHE, KEY, INTEGRITY, opts()).then(() => { const OPTS = { memoize: false, size: CONTENT.length } const stream = get.stream(CACHE, KEY, OPTS) return Promise.all([ new Promise((resolve) => stream.on('integrity', resolve)), new Promise((resolve) => stream.on('metadata', resolve)), new Promise((resolve) => stream.on('size', resolve)), ]).then(() => { [ 'integrity', 'metadata', 'size', ].forEach(ev => { stream.on(ev, () => { t.ok(`${ev} listener added`) }) }) return stream.concat() }) }) }) t.test('get.copy will throw ENOENT if not found', (t) => { const CACHE = t.testdir() const DEST = path.join(CACHE, 'not-found') return get.copy(CACHE, 'NOT-FOUND', DEST) .then(() => { throw new Error('lookup should fail') }) .catch((err) => { t.ok(err, 'got an error') t.equal(err.code, 'ENOENT', 'error code is ENOENT') }) }) t.test('get.copy with fs.copyfile', (t) => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const DEST = path.join(CACHE, 'copymehere') return index .insert(CACHE, KEY, INTEGRITY, opts()) .then(() => get.copy(CACHE, KEY, DEST)) .then((res) => { t.same( res, { metadata: METADATA, integrity: INTEGRITY, size: SIZE, }, 'copy operation returns basic metadata' ) return fs.readFile(DEST) }) .then((data) => { t.same(data, CONTENT, 'data copied by key matches') return fs.rm(DEST, { recursive: true, force: true }) }) .then(() => get.copy.byDigest(CACHE, INTEGRITY, DEST)) .then(() => fs.readFile(DEST)) .then((data) => { t.same(data, CONTENT, 'data copied by digest matches') return fs.rm(DEST, { recursive: true, force: true }) }) }) t.test('memoizes data on bulk read', (t) => { memo.clearMemoized() const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) return index.insert(CACHE, KEY, INTEGRITY, opts()).then((ENTRY) => { return get(CACHE, KEY) .then(() => { t.same(memo.get(CACHE, KEY), null, 'no memoization!') return get(CACHE, KEY, { memoize: true }) }) .then((res) => { t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'usual data returned' ) t.same( memo.get(CACHE, KEY), { entry: ENTRY, data: CONTENT, }, 'data inserted into memoization cache' ) return fs.rm(CACHE, { recursive: true, force: true }) }) .then(() => { return get(CACHE, KEY) }) .then((res) => { t.same( res, { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'memoized data fetched by default' ) return get(CACHE, KEY, { memoize: false }) .then(() => { throw new Error('expected get to fail') }) .catch((err) => { t.ok(err, 'got an error from unmemoized get') t.equal(err.code, 'ENOENT', 'cached content not found') t.same( memo.get(CACHE, KEY), { entry: ENTRY, data: CONTENT, }, 'data still in memoization cache' ) }) }) }) }) t.test('memoizes data on stream read', async t => { memo.clearMemoized() const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const ENTRY = await index.insert(CACHE, KEY, INTEGRITY, opts()) await Promise.all([ streamGet(false, CACHE, KEY), streamGet(true, CACHE, INTEGRITY), ]) t.same(memo.get(CACHE, KEY), null, 'no memoization by key!') t.same( memo.get.byDigest(CACHE, INTEGRITY), null, 'no memoization by digest!' ) memo.clearMemoized() const byDigest = await streamGet(true, CACHE, INTEGRITY, { memoize: true, }) t.same(byDigest.data, CONTENT, 'usual data returned from stream') t.same(memo.get(CACHE, KEY), null, 'digest fetch = no key entry') t.same( memo.get.byDigest(CACHE, INTEGRITY), CONTENT, 'content memoized' ) t.same( memo.get.byDigest('whatev', INTEGRITY), null, 'content memoization filtered by cache' ) memo.clearMemoized() await t.resolveMatch( streamGet(false, CACHE, KEY, { memoize: true }), { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'usual data returned from key fetch' ) t.same( memo.get(CACHE, KEY), { entry: ENTRY, data: CONTENT, }, 'data inserted into memoization cache' ) t.same( memo.get.byDigest(CACHE, INTEGRITY), CONTENT, 'content memoized by digest, too' ) t.same( memo.get('whatev', KEY), null, 'entry memoization filtered by cache' ) await fs.rm(CACHE, { recursive: true, force: true }) await t.resolveMatch( streamGet(false, CACHE, KEY), { metadata: METADATA, data: CONTENT, integrity: INTEGRITY, size: SIZE, }, 'key fetch fulfilled by memoization cache' ) await t.resolveMatch( streamGet(true, CACHE, INTEGRITY), { data: CONTENT }, 'digest fetch fulfilled by memoization cache' ) await t.rejects( streamGet(false, CACHE, KEY, { memoize: false }), { code: 'ENOENT' }, 'key get memoization bypassed' ) await t.rejects( streamGet(true, CACHE, INTEGRITY, { memoize: false }), { code: 'ENOENT' }, 'digest get memoization bypassed' ) }) t.test('get.info uses memoized data', async t => { memo.clearMemoized() const CACHE = t.testdir() const ENTRY = { key: KEY, integrity: INTEGRITY, time: +new Date(), size: SIZE, metadata: null, } memo.put(CACHE, ENTRY, CONTENT) const info = await get.info(CACHE, KEY) t.same(info, ENTRY, 'got the entry from memoization cache') }) t.test('identical hashes with different algorithms do not conflict') t.test('throw error if something is really wrong with bucket') ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/ls.js���������������������������������������������������������������������������0000664�0000000�0000000�00000007551�14344174136�0015123�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const CacheIndex = require('./fixtures/cache-index') const contentPath = require('../lib/content/path') const index = require('../lib/entry-index.js') const t = require('tap') const { ls } = require('..') t.test('basic listing', async t => { const contents = { whatever: { key: 'whatever', integrity: 'sha512-deadbeef', time: 12345, metadata: 'omgsometa', size: 234234, }, whatnot: { key: 'whatnot', integrity: 'sha512-bada55', time: 54321, metadata: null, size: 425345345, }, } const CACHE = t.testdir(CacheIndex(contents)) contents.whatever.path = contentPath(CACHE, contents.whatever.integrity) contents.whatnot.path = contentPath(CACHE, contents.whatnot.integrity) const listing = await ls(CACHE) t.same(listing, contents, 'index contents correct') const newListing = {} const stream = ls.stream(CACHE) stream.on('data', (entry) => { newListing[entry.key] = entry }) await stream.promise() t.same(newListing, contents, 'ls is streamable') }) t.test('separate keys in conflicting buckets', async t => { const contents = { whatever: { key: 'whatever', integrity: 'sha512-deadbeef', time: 12345, metadata: 'omgsometa', size: 5, }, whatev: { key: 'whatev', integrity: 'sha512-bada55', time: 54321, metadata: null, size: 99234234, }, } const CACHE = t.testdir( CacheIndex({ // put both in the same bucket whatever: [contents.whatever, contents.whatev], }) ) contents.whatever.path = contentPath(CACHE, contents.whatever.integrity) contents.whatev.path = contentPath(CACHE, contents.whatev.integrity) const listing = await ls(CACHE) t.same(listing, contents, 'index contents correct') }) t.test('works fine on an empty/missing cache', async t => { const CACHE = t.testdir() const listing = await ls(CACHE) t.same(listing, {}, 'returned an empty listing') }) t.test('ignores non-dir files', async t => { const index = CacheIndex({ whatever: { key: 'whatever', integrity: 'sha512-deadbeef', time: 12345, metadata: 'omgsometa', size: 234234, }, }) index.garbage = 'hello world' const CACHE = t.testdir(index) const listing = await ls(CACHE) t.equal(Object.keys(listing).length, 1, 'only 1 item in listing') t.equal(listing.whatever.key, 'whatever', 'only the correct entry listed') }) t.test('correctly ignores deleted entries', (t) => { const contents = { whatever: { key: 'whatever', integrity: 'sha512-deadbeef', time: 12345, metadata: 'omgsometa', size: 234234, }, whatnot: { key: 'whatnot', integrity: 'sha512-bada55', time: 54321, metadata: null, size: 425345345, }, whatwhere: { key: 'whatwhere', integrity: 'sha512-bada55e5', time: 54321, metadata: null, size: 425345345, }, } const CACHE = t.testdir(CacheIndex(contents)) contents.whatever.path = contentPath(CACHE, contents.whatever.integrity) contents.whatnot.path = contentPath(CACHE, contents.whatnot.integrity) contents.whatwhere.path = contentPath(CACHE, contents.whatwhere.integrity) return index .delete(CACHE, 'whatnot') .then(() => ls(CACHE)) .then((listing) => t.same( listing, { whatever: contents.whatever, whatwhere: contents.whatwhere, }, 'index contents correct' ) ) .then(() => { const listing = {} const stream = ls.stream(CACHE) stream.on('data', (entry) => { listing[entry.key] = entry }) return stream.promise().then(() => t.same( listing, { whatever: contents.whatever, whatwhere: contents.whatwhere, }, 'ls is streamable' ) ) }) }) �������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/memoization.js������������������������������������������������������������������0000664�0000000�0000000�00000010004�14344174136�0017023�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { test } = require('tap') const memo = require('../lib/memoization') const CACHE = 'mycache' const ENTRY = { key: 'foo', integrity: 'sha512-deadbeef', time: new Date(), metadata: null, } const DATA = 'foobarbaz' test('memoizes entry and data by key', (t) => { memo.put(CACHE, ENTRY, DATA) t.same( memo.clearMemoized(), { [`key:${CACHE}:${ENTRY.key}`]: { entry: ENTRY, data: DATA, }, [`digest:${CACHE}:${ENTRY.integrity}`]: DATA, }, 'cache has both key and digest entries' ) t.end() }) test('can fetch data by key', (t) => { memo.put(CACHE, ENTRY, DATA) t.same( memo.get(CACHE, ENTRY.key), { entry: ENTRY, data: DATA, }, 'fetched data correctly' ) t.same( memo.get(CACHE + 'meh', ENTRY.key), null, 'different caches store different keyspaces' ) memo.clearMemoized() t.end() }) test('can fetch data by digest', (t) => { memo.put(CACHE, ENTRY, DATA) t.same( memo.get.byDigest(CACHE, ENTRY.integrity), DATA, 'got raw data by digest, without an entry' ) memo.clearMemoized() t.end() }) test('can clear out the memoization cache', (t) => { memo.put(CACHE, ENTRY, DATA) memo.clearMemoized() t.same(memo.get(CACHE, ENTRY.key), null, 'entry not there anymore') t.same( memo.get.byDigest(ENTRY.integrity), null, 'digest-based data not there anymore' ) t.end() }) test('accepts optional injected cache', (t) => { memo.clearMemoized() const MEMO = new Map() memo.put(CACHE, ENTRY, DATA, { memoize: MEMO }) t.same( memo.get(CACHE, ENTRY.key), null, 'entry not in global memo cache' ) t.same( memo.get(CACHE, ENTRY.key, { memoize: MEMO }), { entry: ENTRY, data: DATA }, 'entry fetched from injected memoizer' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: MEMO }), DATA, 'content entry fetched from injected memoizer' ) t.same( MEMO.get(`key:${CACHE}:${ENTRY.key}`), { entry: ENTRY, data: DATA }, 'entry is in the injected memoizer' ) t.same( MEMO.get(`digest:${CACHE}:${ENTRY.integrity}`), DATA, 'content entry is in the injected memoizer' ) MEMO.clear() t.same( memo.get(CACHE, ENTRY.key, { memoize: MEMO }), null, 'tried to read from cleared memoizer' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: MEMO }), null, 'tried to read by digest from cleared memoizer' ) memo.put.byDigest(CACHE, ENTRY.integrity, DATA, { memoize: MEMO }) t.same( MEMO.get(`digest:${CACHE}:${ENTRY.integrity}`), DATA, 'content entry is in the injected memoizer' ) const obj = {} memo.put(CACHE, ENTRY, DATA, { memoize: obj }) t.same( memo.get(CACHE, ENTRY.key, { memoize: obj }), { entry: ENTRY, data: DATA }, 'entry fetched from injected object memoizer' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: MEMO }), DATA, 'content entry fetched from injected object memoizer' ) memo.clearMemoized() memo.put(CACHE, ENTRY, DATA, { memoize: 'foo' }) t.same( memo.get(CACHE, ENTRY.key, { memoize: 'foo' }), { entry: ENTRY, data: DATA }, 'entry fetched from global memoization obj on non-obj option' ) t.same( memo.get(CACHE, ENTRY.key, { memoize: 'foo' }), { entry: ENTRY, data: DATA }, 'entry fetched from global memoization obj on non-obj option' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: 'foo' }), DATA, 'content entry fetched global memoizer obj on non-obj option' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: 'foo' }), DATA, 'content entry fetched global memoizer obj on non-obj option' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: false }), DATA, 'content entry fetched global memoizer obj on non-obj option' ) t.same( memo.get.byDigest(CACHE, ENTRY.integrity, { memoize: false }), DATA, 'content entry fetched global memoizer obj on non-obj option' ) t.end() }) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/put.js��������������������������������������������������������������������������0000664�0000000�0000000�00000007541�14344174136�0015314�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const index = require('../lib/entry-index') const memo = require('../lib/memoization') const t = require('tap') const ssri = require('ssri') const CONTENT = Buffer.from('foobarbaz', 'utf8') const KEY = 'my-test-key' const INTEGRITY = ssri.fromData(CONTENT).toString() const METADATA = { foo: 'bar' } const contentPath = require('../lib/content/path') const put = require('..').put t.test('basic bulk insertion', async t => { const CACHE = t.testdir() const integrity = await put(CACHE, KEY, CONTENT) t.equal(integrity.toString(), INTEGRITY, 'returned content integrity') const dataPath = contentPath(CACHE, integrity) const data = await fs.readFile(dataPath) t.same(data, CONTENT, 'content was correctly inserted') }) t.test('basic stream insertion', async t => { const CACHE = t.testdir() let int const stream = put.stream(CACHE, KEY).on('integrity', (i) => { int = i }) await stream.end(CONTENT).promise() t.equal(int.toString(), INTEGRITY, 'returned integrity matches expected') const data = await fs.readFile(contentPath(CACHE, int)) t.same(data, CONTENT, 'contents are identical to inserted content') }) t.test('adds correct entry to index before finishing', async t => { const CACHE = t.testdir() await put(CACHE, KEY, CONTENT, { metadata: METADATA }) const entry = await index.find(CACHE, KEY) t.ok(entry, 'got an entry') t.equal(entry.key, KEY, 'entry has the right key') t.equal(entry.integrity, INTEGRITY, 'entry has the right key') t.same(entry.metadata, METADATA, 'metadata also inserted') }) t.test('optionally memoizes data on bulk insertion', async t => { const CACHE = t.testdir() const integrity = await put(CACHE, KEY, CONTENT, { metadata: METADATA, memoize: true, }) t.equal(integrity.toString(), INTEGRITY, 'integrity returned as usual') const entry = await index.find(CACHE, KEY) // index.find is not memoized t.same( memo.get(CACHE, KEY), { data: CONTENT, entry: entry, }, 'content inserted into memoization cache by key' ) t.same( memo.get.byDigest(CACHE, INTEGRITY), CONTENT, 'content inserted into memoization cache by integrity' ) }) t.test('optionally memoizes data on stream insertion', async t => { const CACHE = t.testdir() let int const stream = put .stream(CACHE, KEY, { metadata: METADATA, memoize: true, }) .on('integrity', (i) => { int = i }) await stream.end(CONTENT).promise() t.equal(int.toString(), INTEGRITY, 'integrity emitted as usual') const data = await fs.readFile(contentPath(CACHE, int)) t.same(data, CONTENT, 'contents are identical to inserted content') const entry = await index.find(CACHE, KEY) // index.find is not memoized t.same( memo.get(CACHE, KEY), { data: CONTENT, entry: entry, }, 'content inserted into memoization cache by key' ) t.same( memo.get.byDigest(CACHE, INTEGRITY), CONTENT, 'content inserted into memoization cache by integrity' ) }) t.test('errors if integrity errors', async t => { const CACHE = t.testdir() await t.rejects( put(CACHE, KEY, CONTENT, { integrity: 'sha1-BaDDigEST' }), { code: 'EINTEGRITY' }, 'got error from bad integrity' ) }) t.test('signals error if error writing to cache', async t => { const CACHE = t.testdir() const [bulkErr, streamErr] = await Promise.all([ put(CACHE, KEY, CONTENT, { size: 2, }) .then(() => { throw new Error('expected to get a bad size error') }) .catch((err) => err), put.stream(CACHE, KEY, { size: 2 }).end(CONTENT).promise() .then(() => { throw new Error('expected to get a bad size error') }) .catch((err) => err), ]) t.equal(bulkErr.code, 'EBADSIZE', 'got error from bulk write') t.equal(streamErr.code, 'EBADSIZE', 'got error from stream write') }) ���������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/rm.js���������������������������������������������������������������������������0000664�0000000�0000000�00000004542�14344174136�0015120�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const index = require('../lib/entry-index') const path = require('path') const t = require('tap') const ssri = require('ssri') const CacheContent = require('./fixtures/cache-content') const CONTENT = Buffer.from('foobarbaz') const KEY = 'my-test-key' const INTEGRITY = ssri.fromData(CONTENT) const METADATA = { foo: 'bar' } const contentPath = require('../lib/content/path') const get = require('..').get const rm = require('..').rm const cacheContent = CacheContent({ [INTEGRITY]: CONTENT, }) t.test('rm.entry removes entries, not content', async t => { const cache = t.testdir(cacheContent) await index.insert(cache, KEY, INTEGRITY, { metadata: METADATA }) t.equal(rm, rm.entry, 'rm is an alias for rm.entry') await rm.entry(cache, KEY) await t.rejects( get(cache, KEY), { code: 'ENOENT', message: new RegExp(KEY), }, 'entry no longer accessible' ) const data = await fs.readFile(contentPath(cache, INTEGRITY)) t.same(data, CONTENT, 'content remains in cache') }) t.test('rm.content removes content, not entries', (t) => { const cache = t.testdir(cacheContent) return index .insert(cache, KEY, INTEGRITY, { metadata: METADATA, }) .then(() => { return rm.content(cache, INTEGRITY) }) .then(() => { return get(cache, KEY) }) .then((res) => { throw new Error('unexpected success') }) .catch((err) => { if (err.code === 'ENOENT') { t.match(err.message, /no such file/, 'entry no longer accessible') return } throw err }) .then(() => { return fs.readFile(contentPath(cache, INTEGRITY)) }) .then(() => { throw new Error('unexpected success') }) .catch((err) => { if (err.code === 'ENOENT') { t.match(err.message, /no such file/, 'content gone') return } throw err }) }) t.test('rm.all deletes content and index dirs', async t => { const cache = t.testdir(cacheContent) await index.insert(cache, KEY, INTEGRITY, { metadata: METADATA }) await fs.mkdir(path.join(cache, 'tmp')) await fs.writeFile(path.join(cache, 'other.js'), 'hi') await rm.all(cache) const files = await fs.readdir(cache) t.same( files.sort(), ['other.js', 'tmp'], 'removes content and index directories without touching other stuff' ) }) ��������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/util/���������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14344174136�0015114�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/util/move-file.js���������������������������������������������������������������0000664�0000000�0000000�00000011717�14344174136�0017344�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const { chmod, open, readFile, readdir, stat, } = require('fs/promises') const fs = require('fs') const path = require('path') const t = require('tap') const moveFile = require('../../lib/util/move-file') t.test('move a file', function (t) { const testDir = t.testdir({ src: 'foo', }) return moveFile(testDir + '/src', testDir + '/dest') .then(() => { return readFile(testDir + '/dest', 'utf8') }) .then((data) => { t.equal(data, 'foo', 'file data correct') return stat(testDir + '/src').catch((err) => { t.ok(err, 'src read error') t.equal(err.code, 'ENOENT', 'src does not exist') }) }) }) t.test('does not clobber existing files', function (t) { const testDir = t.testdir({ src: 'foo', dest: 'bar', }) return moveFile(testDir + '/src', testDir + '/dest') .then(() => { return readFile(testDir + '/dest', 'utf8') }) .then((data) => { t.equal(data, 'bar', 'conflicting file left intact') return stat(testDir + '/src').catch((err) => { t.ok(err, 'src read error') t.equal(err.code, 'ENOENT', 'src file still deleted') }) }) }) t.test('does not move a file into an existing directory', async t => { const testDir = t.testdir({ src: 'foo', dest: {}, }) await moveFile(testDir + '/src', testDir + '/dest') const files = await readdir(testDir + '/dest') t.equal(files.length, 0, 'directory remains empty') }) t.test('does not error if destination file is open', function (t) { const testDir = t.testdir({ src: 'foo', dest: 'bar', }) return open(testDir + '/dest', 'r+').then((fh) => { return moveFile(testDir + '/src', testDir + '/dest') .then(() => { return fh.close() }) .then(() => { return readFile(testDir + '/dest', 'utf8') }) .then((data) => { t.equal(data, 'bar', 'destination left intact') return stat(testDir + '/src').catch((err) => { t.ok(err, 'src read error') t.equal(err.code, 'ENOENT', 'src does not exist') }) }) }) }) t.test('fallback to renaming on missing files post-move', async t => { const testDir = t.testdir({ src: 'foo', }) const missingFileError = new Error('ENOENT') missingFileError.code = 'ENOENT' const mockFS = { ...fs.promises, async unlink (path) { throw missingFileError }, async stat (path) { throw missingFileError }, } const mockedMoveFile = t.mock('../../lib/util/move-file', { 'fs/promises': mockFS, }) await mockedMoveFile(testDir + '/src', testDir + '/dest') const data = await readFile(testDir + '/dest', 'utf8') t.equal(data, 'foo', 'file data correct') await t.rejects( stat(testDir + '/src'), { code: 'ENOENT' }, './src does not exist' ) }) t.test('non ENOENT error on move fallback', async function (t) { const testDir = t.testdir({ src: 'foo', }) const missingFileError = new Error('ENOENT') missingFileError.code = 'ENOENT' const otherError = new Error('UNKNOWN') otherError.code = 'OTHER' const mockFS = { ...fs.promises, async unlink (path) { throw missingFileError }, async stat (path) { throw otherError }, } const mockedMoveFile = t.mock('../../lib/util/move-file', { 'fs/promises': mockFS, }) await t.rejects( mockedMoveFile(testDir + '/src', testDir + '/dest'), { code: 'OTHER' }, 'throws other error' ) }) t.test('verify weird EPERM on Windows behavior', t => { const processPlatform = process.platform Object.defineProperty(process, 'platform', { value: 'win32' }) t.teardown(() => { Object.defineProperty(process, 'platform', { value: processPlatform }) }) let calledMonkeyPatch = false const mockFS = { ...fs.promises, link: async (src, dest) => { calledMonkeyPatch = true throw Object.assign(new Error('yolo'), { code: 'EPERM' }) }, } const mockedMoveFile = t.mock('../../lib/util/move-file.js', { 'fs/promises': mockFS, }) const testDir = t.testdir({ eperm: { src: 'epermmy', }, }) return mockedMoveFile(testDir + '/eperm/src', testDir + '/eperm/dest') .then(() => t.ok(calledMonkeyPatch, 'called the patched fs.link fn')) .then(() => t.rejects(readFile('eperm/dest'), { code: 'ENOENT', }, 'destination file did not get written')) .then(() => t.rejects(readFile('eperm/src'), { code: 'ENOENT', }, 'src file did get deleted')) }) t.test( 'errors if dest is not writable', { skip: process.platform === 'win32', }, async t => { const testDir = t.testdir({ src: 'foo', dest: {}, }) await chmod(testDir + '/dest', parseInt('400', 8)) await t.rejects( moveFile(testDir + '/src', path.join(testDir + '/dest', 'file')), { code: 'EACCES' }, 'error is about permissions' ) const data = await readFile(testDir + '/src', 'utf8') t.equal(data, 'foo', 'src contents left intact') } ) �������������������������������������������������cacache-17.0.3/test/util/tmp.js���������������������������������������������������������������������0000664�0000000�0000000�00000002435�14344174136�0016256�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const fs = require('fs/promises') const path = require('path') const t = require('tap') const CACHE = t.testdir() const tmp = require('../../lib/util/tmp.js') t.test('creates a unique tmpdir inside the cache', async t => { const dir = await tmp.mkdir(CACHE) t.match( path.relative(CACHE, dir), /^tmp[\\/].*/, 'returns a path inside tmp' ) const s = await fs.stat(dir) t.ok(s.isDirectory(), 'path points to an existing directory') }) t.test('provides a utility that does resource disposal on tmp', async t => { const dir = await tmp.withTmp(CACHE, async (dir) => { const s = await fs.stat(dir) t.ok(s.isDirectory(), 'path points to an existing directory') return dir }) const [nope, yes] = await Promise.all([ fs.stat(dir) .then(() => { throw new Error('expected fail') }) .catch((err) => { if (err.code === 'ENOENT') { return undefined } throw err }), fs.stat(path.join(CACHE, 'tmp')), ]) t.notOk(nope, 'tmp subdir removed') t.ok(yes.isDirectory(), 'tmp parent dir left intact') }) t.test('withTmp should accept both opts and cb params', async t => { await tmp.withTmp(CACHE, { tmpPrefix: 'foo' }, dir => { t.ok(dir, 'dir should contain a valid response') }) }) �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������cacache-17.0.3/test/verify.js�����������������������������������������������������������������������0000664�0000000�0000000�00000023161�14344174136�0016004�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'use strict' const contentPath = require('../lib/content/path') const index = require('../lib/entry-index') const fs = require('fs/promises') const path = require('path') const t = require('tap') const ssri = require('ssri') const CacheContent = require('./fixtures/cache-content') const CONTENT = Buffer.from('foobarbaz', 'utf8') const KEY = 'my-test-key' const INTEGRITY = ssri.fromData(CONTENT) const METADATA = { foo: 'bar' } const verify = require('..').verify // defines reusable errors const genericError = new Error('ERR') genericError.code = 'ERR' // helpers const getVerify = (t, opts) => t.mock('../lib/verify', opts) async function mockCache (t) { const cacheContent = CacheContent({ [INTEGRITY]: CONTENT, }) cacheContent.tmp = {} const CACHE = t.testdir(cacheContent) await index.insert(CACHE, KEY, INTEGRITY, { metadata: METADATA, }) return CACHE } t.test('removes corrupted index entries from buckets', async t => { const CACHE = await mockCache(t) const BUCKET = index.bucketPath(CACHE, KEY) const BUCKETDATA = await fs.readFile(BUCKET, 'utf8') // traaaaash await fs.appendFile(BUCKET, '\n234uhhh') const stats = await verify(CACHE) t.equal( stats.missingContent, 0, 'content valid because of good entry' ) t.equal(stats.totalEntries, 1, 'only one entry counted') const bucketData = await fs.readFile(BUCKET, 'utf8') const bucketEntry = JSON.parse(bucketData.split('\t')[1]) const targetEntry = JSON.parse(BUCKETDATA.split('\t')[1]) targetEntry.time = bucketEntry.time // different timestamps t.same( bucketEntry, targetEntry, 'bucket only contains good entry' ) }) t.test('removes shadowed index entries from buckets', async t => { const CACHE = await mockCache(t) const BUCKET = index.bucketPath(CACHE, KEY) const newEntry = await index.insert(CACHE, KEY, INTEGRITY, { metadata: 'meh' }) const stats = await verify(CACHE) t.equal( stats.missingContent, 0, 'content valid because of good entry' ) t.equal(stats.totalEntries, 1, 'only one entry counted') const bucketData = await fs.readFile(BUCKET, 'utf8') const stringified = JSON.stringify({ key: newEntry.key, integrity: newEntry.integrity.toString(), time: +bucketData.match(/"time":([0-9]+)/)[1], metadata: newEntry.metadata, }) t.equal( bucketData, `\n${index.hashEntry(stringified)}\t${stringified}`, 'only the most recent entry is still in the bucket' ) }) t.test('accepts function for custom user filtering of index entries', async t => { const KEY2 = KEY + 'aaa' const KEY3 = KEY + 'bbb' const CACHE = await mockCache(t) const [entryA, entryB] = await Promise.all([ index.insert(CACHE, KEY2, INTEGRITY, { metadata: 'haayyyy', }), index.insert(CACHE, KEY3, INTEGRITY, { metadata: 'haayyyy again', }), ]) const newEntries = { [entryA.key]: entryA, [entryB.key]: entryB, } const stats = await verify(CACHE, { filter (entry) { return entry.key.length === KEY2.length }, }) t.same( { verifiedContent: stats.verifiedContent, rejectedEntries: stats.rejectedEntries, totalEntries: stats.totalEntries, }, { verifiedContent: 1, rejectedEntries: 1, totalEntries: 2, }, 'reported relevant changes' ) const entries = await index.ls(CACHE) entries[KEY2].time = newEntries[KEY2].time entries[KEY3].time = newEntries[KEY3].time t.same(entries, newEntries, 'original entry not included') }) t.test('removes corrupted content', async t => { const CACHE = await mockCache(t) const cpath = contentPath(CACHE, INTEGRITY) await fs.truncate(cpath, CONTENT.length - 1) const stats = await verify(CACHE) delete stats.startTime delete stats.runTime delete stats.endTime t.same( stats, { verifiedContent: 0, reclaimedCount: 1, reclaimedSize: CONTENT.length - 1, badContentCount: 1, keptSize: 0, missingContent: 1, rejectedEntries: 1, totalEntries: 0, }, 'reported correct collection counts' ) await t.rejects( fs.stat(cpath), /no such file/, 'content no longer in cache' ) }) t.test('removes content not referenced by any entries', async t => { const CACHE = t.testdir( CacheContent({ [INTEGRITY]: CONTENT, }) ) const stats = await verify(CACHE) delete stats.startTime delete stats.runTime delete stats.endTime t.same( stats, { verifiedContent: 0, reclaimedCount: 1, reclaimedSize: CONTENT.length, badContentCount: 0, keptSize: 0, missingContent: 0, rejectedEntries: 0, totalEntries: 0, }, 'reported correct collection counts' ) }) t.test('cleans up contents of tmp dir', async t => { const CACHE = await mockCache(t) const tmpFile = path.join(CACHE, 'tmp', 'x') const misc = path.join(CACHE, 'y') await Promise.all([fs.writeFile(tmpFile, ''), fs.writeFile(misc, '')]) await verify(CACHE) const [err, stat] = await Promise.all([ fs.stat(tmpFile).catch((err) => { if (err.code === 'ENOENT') { return err } throw err }), fs.stat(misc), ]) t.equal(err.code, 'ENOENT', 'tmp file was blown away') t.ok(stat, 'misc file was not touched') }) t.test('writes a file with last verification time', async t => { const CACHE = t.testdir() await verify(CACHE) const [fromLastRun, fromFile] = await Promise.all([ verify.lastRun(CACHE), fs.readFile(path.join(CACHE, '_lastverified'), 'utf8').then((data) => { return new Date(parseInt(data)) }), ]) t.equal(+fromLastRun, +fromFile, 'last verified was writen') }) t.test('missing file error when validating cache content', async t => { const missingFileError = new Error('ENOENT') missingFileError.code = 'ENOENT' const mockVerify = getVerify(t, { 'fs/promises': Object.assign({}, fs, { stat: async (path) => { throw missingFileError }, }), }) t.plan(1) const CACHE = await mockCache(t) await t.resolveMatch( mockVerify(CACHE), { verifiedContent: 0, rejectedEntries: 1, totalEntries: 0, }, 'should reject entry' ) }) t.test('unknown error when validating content', async t => { const mockVerify = getVerify(t, { 'fs/promises': Object.assign({}, fs, { stat: async (path) => { throw genericError }, }), }) t.plan(1) const CACHE = await mockCache(t) await t.rejects( mockVerify(CACHE), genericError, 'should throw any unknown errors' ) }) t.test('unknown error when checking sri stream', async t => { const mockVerify = getVerify(t, { ssri: Object.assign({}, ssri, { checkStream: () => Promise.reject(genericError), }), }) const CACHE = await mockCache(t) await t.rejects( mockVerify(CACHE), genericError, 'should throw any unknown errors' ) }) t.test('unknown error when rebuilding bucket', async t => { // rebuild bucket uses stat after content-validation // shouldFail controls the right time to mock the error let shouldFail = false const mockVerify = getVerify(t, { 'fs/promises': Object.assign({}, fs, { stat: async (path) => { if (shouldFail) { throw genericError } shouldFail = true return fs.stat(path) }, }), }) const CACHE = await mockCache(t) await t.rejects( mockVerify(CACHE), genericError, 'should throw any unknown errors' ) }) t.test('re-builds the index with the size parameter', async t => { const KEY2 = KEY + 'aaa' const KEY3 = KEY + 'bbb' const CACHE = await mockCache(t) await Promise.all([ index.insert(CACHE, KEY2, INTEGRITY, { metadata: 'haayyyy', size: 20, }), index.insert(CACHE, KEY3, INTEGRITY, { metadata: 'haayyyy again', size: 30, }), ]) const newEntries = await index.ls(CACHE) const stats = await verify(CACHE) t.same( { verifiedContent: stats.verifiedContent, rejectedEntries: stats.rejectedEntries, totalEntries: stats.totalEntries, }, { verifiedContent: 1, rejectedEntries: 0, totalEntries: 3, }, 'reported relevant changes' ) const entries = await index.ls(CACHE) entries[KEY].time = newEntries[KEY].time entries[KEY2].time = newEntries[KEY2].time entries[KEY3].time = newEntries[KEY3].time t.same( entries, newEntries, 'original index entries not preserved' ) }) t.test('hash collisions', async t => { const mockVerify = getVerify(t, { '../lib/entry-index': Object.assign({}, index, { hashKey: () => 'aaa', }), }) t.plan(1) const CACHE = await mockCache(t) await index.insert(CACHE, 'foo', INTEGRITY, { metadata: 'foo', }) const stats = await mockVerify(CACHE) t.same( { verifiedContent: stats.verifiedContent, rejectedEntries: stats.rejectedEntries, totalEntries: stats.totalEntries, }, { verifiedContent: 1, rejectedEntries: 0, totalEntries: 2, }, 'should resolve with no errors' ) }) t.test('hash collisions excluded', async t => { const mockVerify = getVerify(t, { '../lib/entry-index': Object.assign({}, index, { hashKey: () => 'aaa', }), }) t.plan(1) const CACHE = await mockCache(t) await index.insert(CACHE, 'foo', INTEGRITY, { metadata: 'foo' }) const stats = await mockVerify(CACHE, { filter: () => null }) t.same( { verifiedContent: stats.verifiedContent, rejectedEntries: stats.rejectedEntries, totalEntries: stats.totalEntries, }, { verifiedContent: 0, rejectedEntries: 2, totalEntries: 0, }, 'should resolve while also excluding filtered out entries' ) }) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������