From 14ab66c9204f751f12e42b76802ef87b6a1e4a09 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 16:22:58 +0000 Subject: [PATCH 1/3] Scaffold the Pegma workspace and land cache-core Phase 1. Add the org-standard pnpm monorepo (health/scheduler layout), Phase 1 packages @pegma/cache-core and @pegma/cache-conformance, and prove the in-memory store against the conformance suite. Adapter packages are named in the plan only. Co-authored-by: Fly Over Coder --- .editorconfig | 12 + .gitattributes | 7 + .github/workflows/ci.yml | 50 + .github/workflows/codeql.yml | 46 + .github/workflows/publish.yml | 126 +++ .gitignore | 14 + .nvmrc | 1 + .prettierignore | 1 + AGENTS.md | 89 ++ CONTRIBUTING.md | 42 + LICENSE | 2 +- README.md | 75 +- SECURITY.md | 20 + docs/PROJECT_PLAN.md | 182 ++++ docs/RELEASING.md | 69 ++ package.json | 29 + packages/cache-conformance/LICENSE | 21 + packages/cache-conformance/README.md | 34 + packages/cache-conformance/package.json | 40 + packages/cache-conformance/src/index.test.ts | 28 + packages/cache-conformance/src/index.ts | 298 ++++++ packages/cache-conformance/tsconfig.json | 12 + packages/cache-core/LICENSE | 21 + packages/cache-core/README.md | 34 + packages/cache-core/package.json | 39 + packages/cache-core/src/index.test.ts | 160 +++ packages/cache-core/src/index.ts | 590 +++++++++++ packages/cache-core/tsconfig.json | 11 + pnpm-lock.yaml | 949 +++++++++++++++++ pnpm-workspace.yaml | 5 + scripts/release-packages.d.mts | 86 ++ scripts/release-packages.mjs | 1002 ++++++++++++++++++ tests/release-packages.test.ts | 267 +++++ tsconfig.base.json | 18 + tsconfig.json | 7 + tsconfig.test.json | 16 + vitest.config.ts | 8 + 37 files changed, 4408 insertions(+), 3 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/codeql.yml create mode 100644 .github/workflows/publish.yml create mode 100644 .gitignore create mode 100644 .nvmrc create mode 100644 .prettierignore create mode 100644 AGENTS.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 docs/PROJECT_PLAN.md create mode 100644 docs/RELEASING.md create mode 100644 package.json create mode 100644 packages/cache-conformance/LICENSE create mode 100644 packages/cache-conformance/README.md create mode 100644 packages/cache-conformance/package.json create mode 100644 packages/cache-conformance/src/index.test.ts create mode 100644 packages/cache-conformance/src/index.ts create mode 100644 packages/cache-conformance/tsconfig.json create mode 100644 packages/cache-core/LICENSE create mode 100644 packages/cache-core/README.md create mode 100644 packages/cache-core/package.json create mode 100644 packages/cache-core/src/index.test.ts create mode 100644 packages/cache-core/src/index.ts create mode 100644 packages/cache-core/tsconfig.json create mode 100644 pnpm-lock.yaml create mode 100644 pnpm-workspace.yaml create mode 100644 scripts/release-packages.d.mts create mode 100644 scripts/release-packages.mjs create mode 100644 tests/release-packages.test.ts create mode 100644 tsconfig.base.json create mode 100644 tsconfig.json create mode 100644 tsconfig.test.json create mode 100644 vitest.config.ts diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..1014ba7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dcb9ec8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +* text=auto eol=lf + +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.webp binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..888dd75 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,50 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + name: Node.js ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: + - 22 + - 24 + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Set up pnpm + uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda # v4.1.0 + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: ${{ matrix.node-version }} + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Check formatting + run: pnpm run format:check + + - name: Check types + run: pnpm run check + + - name: Run tests + run: pnpm test diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..08c614b --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,46 @@ +name: CodeQL + +on: + push: + branches: + - main + pull_request: + branches: + - main + schedule: + - cron: "31 7 * * 1" + +permissions: + contents: read + security-events: write + +concurrency: + group: codeql-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + analyze: + name: Analyze JavaScript and TypeScript + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 + with: + languages: javascript-typescript + + - name: Build + uses: github/codeql-action/autobuild@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 + + - name: Analyze + uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..e6d0b62 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,126 @@ +# Publishes exact tarballs prepared from a signed stable release tag. +# Authentication is npm trusted-publisher OIDC only; no token fallback exists. + +name: Publish + +on: + release: + types: [published] + +permissions: + contents: read + +concurrency: + group: npm-publish + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-latest + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} + + steps: + - name: Check out the release tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: refs/tags/${{ github.event.release.tag_name }} + fetch-depth: 0 + + - name: Fetch the protected release branch + run: git fetch --no-tags origin main:refs/remotes/origin/main + + - name: Configure approved release signers + shell: bash + run: | + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + exit 1 + fi + allowed_signers="${RUNNER_TEMP}/release-allowed-signers" + umask 077 + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + git config --local gpg.format ssh + git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + registry-url: https://registry.npmjs.org + package-manager-cache: false + + - name: Enable Corepack + run: corepack enable + + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Check formatting + run: pnpm run format:check + + - name: Check types + run: pnpm run check + + - name: Run tests + run: pnpm test + + - name: Prepare and verify release tarballs + run: pnpm run release:pack -- --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + + - name: Upload the prepared release + id: upload + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0 + with: + name: cache-core-release-${{ github.run_id }} + path: .release/ + if-no-files-found: error + include-hidden-files: true + overwrite: true + retention-days: 30 + + - name: Record the prepared artifact digest + run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + + publish: + needs: prepare + runs-on: ubuntu-latest + environment: npm-publish + permissions: + contents: read + id-token: write + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_COMMIT: ${{ github.sha }} + + steps: + - name: Check out the exact release tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: refs/tags/${{ github.event.release.tag_name }} + fetch-depth: 1 + + - name: Set up Node.js and the npm registry + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24.18.0 + registry-url: https://registry.npmjs.org + package-manager-cache: false + + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 + + - name: Download the prepared release + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: cache-core-release-${{ github.run_id }} + path: .release + + - name: Publish verified prepared tarballs + run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b1d9e5c --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +node_modules/ +dist/ +coverage/ +*.tsbuildinfo +.release/ + +.env +.env.* +!.env.example + +.DS_Store +Thumbs.db +.idea/ +.vscode/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..bd5535a --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +pnpm-lock.yaml diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ee69bba --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,89 @@ +# Working in this repository + +Read this before changing anything. It is short on purpose. + +## What this is part of + +Cache Core is the ephemeral-caching component of **Pegma**, a family of +MIT-licensed packages a host application composes. Shared time and logging +contracts live in `@pegma/spine`. Durable state belongs in +`@pegma/storage-core` — this repository refuses that job. One repository per +component, publishing under the `@pegma` scope. + +The governing principle, which every rule below follows from: + +> **Optimize for a fresh agent context window.** How much must be read to make +> a correct change, and how does the change prove itself correct? Minimize the +> first, mechanize the second. + +A cache that lies about freshness, stamps over a neighbor's namespace, or +falls back to unbounded local memory when Redis is down is worse than no +cache. Weigh changes accordingly. + +## Hard rules + +**The conformance suite is the specification.** A behaviour that is not +asserted in `@pegma/cache-conformance` is not something a host or adapter may +rely on. Add cases with the behaviour, never after. + +**Injected Clock and Logger only.** TTL, sliding expiry, and XFetch read +`clock.now()`. Never call `Date.now()` on a production path. Log outcomes +coarsely (namespace, status) — never keys, values, or customer content. + +**Namespaces are strict.** `formatCacheKey` is the only legal wire form. +Redis Cluster hash tags are in the contract (`hashTag` becomes `{tag}` in +the formatted key). Do not invent implicit cross-partition multi-key ops. + +**Single-flight is process-local honesty.** N parallel misses for one key +must run `compute` exactly once in that process. Do not pretend this is a +distributed lock. + +**Fail-open computes; fail-closed refuses.** When the backend errors, a +`fail-open` `getOrCompute` still runs `compute` and returns the value. A +`fail-closed` call returns `error` and does not compute. Never install an +unbounded in-process map as a fallback when the remote cache is down. + +**No vendor clients in application code.** Adapters wrap Redis, Azure Cache, +ElastiCache, or Upstash. Hosts depend on `CacheStore`. Do not create an +adapter package until implementation begins and a named consumer exists. + +**This is not durable state.** Persistence, optimistic concurrency, and +transactions belong in `@pegma/storage-core`. A cache miss is not data loss. + +**Pin `@pegma/*` deps exactly.** A caret would let CI resolve a version +nobody tested against. + +**Never write literal control characters into source.** Write them as escape +sequences such as backslash-u-0000 through backslash-u-001F, and verify the +bytes after any tool-assisted edit. + +## Packaging traps already paid for + +Each published package needs its **own** README and LICENSE inside the package +directory; npm ignores files at the repository root. Each needs `prepack` +running the build. Each package `tsconfig.json` must exclude +`src/**/*.test.ts`, or compiled tests ship to consumers. + +`runNpm` / release scripts must invoke a real npm CLI. Ignore `npm_execpath` +when pnpm set it, or pack/publish silently go through pnpm. + +## Workflow + +Work on a `claude/*` branch and open a pull request. The gate is +`pnpm run format:check`, `pnpm run check`, `pnpm test` — all three, on Node 22 +and 24. + +Publishing is trusted-publisher only; no tokens exist. A release starts from a +protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by +`gh release create vX.Y.Z --verify-tag`. See `docs/RELEASING.md`. + +## Where things stand + +Phase 1: `@pegma/cache-core` (ports, codecs, `formatCacheKey`, single-flight +helper, in-memory store) and `@pegma/cache-conformance` (executable suite). +Redis / Azure Redis / ElastiCache / Upstash adapters are later phases — do +not create those packages here yet. + +Siblings: [spine](https://github.com/pegma-dev/spine), +[storage-core](https://github.com/pegma-dev/storage-core), +[health](https://github.com/pegma-dev/health). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..423a380 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing to Cache Core + +Thank you for helping improve Cache Core. + +## Before opening an issue + +- Search existing issues for related work. +- Use GitHub's private vulnerability reporting flow for security concerns. +- Describe the cache behaviour you need and which refusal it must not + violate (durability, cross-partition multi-key ops, unbounded memory + fallback, vendor clients in application code). +- If a proposal needs this package to own durable state or to create an + adapter before a consumer exists, say so explicitly — those are the + changes the design cannot absorb. + +## Local development + +Cache Core requires Node.js 22 or 24. + +```sh +corepack enable +pnpm install --frozen-lockfile +pnpm run check +pnpm test +pnpm run format:check +``` + +## Pull requests + +Keep pull requests focused. Include: + +- the problem being solved; +- the intended component behavior; +- conformance cases for any behaviour a host or adapter may rely on; +- documentation for public API changes. + +A behaviour that is not in the conformance suite is not part of the contract. + +## License + +By contributing, you agree that your contributions will be licensed under the +MIT License. diff --git a/LICENSE b/LICENSE index 833a7d0..897032a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Pegma +Copyright (c) 2026 RetireGolden, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 58c9975..47835f4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,73 @@ -# cache-core -Provider-neutral ephemeral caching for Pegma hosts: typed key namespaces, stampede protection, and a conformance suite. +# Cache Core + +[![CI](https://github.com/pegma-dev/cache-core/actions/workflows/ci.yml/badge.svg)](https://github.com/pegma-dev/cache-core/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) + +Provider-neutral ephemeral caching for [Pegma](https://pegma.dev) hosts: +typed key namespaces, cache-aside `getOrCompute` with stampede protection, +and a conformance suite every adapter must pass. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. Packages are not published yet. No +> public API is stable. + +## Owns + +- Strict key namespacing with schema-aware codecs (JSON and binary) +- Cache-aside `getOrCompute` with single-flight coalescing and optional + probabilistic early expiration (XFetch) +- Sliding and absolute TTL via an injected Spine `Clock` +- Fail-open / fail-closed fallback policies +- A conformance suite every adapter must pass + +## Refuses + +- Durability guarantees — durable state belongs in + [`@pegma/storage-core`](https://github.com/pegma-dev/storage-core) +- Implicit cross-partition multi-key ops; Redis Cluster hash tags are in + the contract +- Unbounded local memory fallbacks when a remote cache is down +- Vendor clients leaking into application code + +## Packages + +| Package | Role | Phase | +| ---------------------------- | ----------------------------------------- | ----- | +| `@pegma/cache-core` | Port, codecs, single-flight, memory store | 1 | +| `@pegma/cache-conformance` | Executable suite every adapter must pass | 1 | +| `@pegma/cache-redis` | Generic Redis adapter | later | +| `@pegma/cache-azure-redis` | Azure Cache for Redis adapter | later | +| `@pegma/cache-elasticache` | Amazon ElastiCache adapter | later | +| `@pegma/cache-upstash-redis` | Upstash Redis adapter | later | + +Adapter packages are not created until implementation begins and a named +consumer exists. + +## Constraint that shapes everything + +**The conformance suite is the specification.** A behaviour not asserted +there is not something a host may rely on. An adapter is finished when it +passes the suite. + +## Documentation + +- [Project plan](docs/PROJECT_PLAN.md) — phases, scope, and decisions +- [Releasing](docs/RELEASING.md) — trusted-publisher release runbook + +## Development + +Requires Node.js 22 or 24. Corepack is bundled through Node 24; on Node 25 +or newer, install it first. + +```sh +npm install -g corepack +corepack enable +pnpm install --frozen-lockfile +pnpm run format:check +pnpm run check +pnpm test +``` + +## License + +[MIT](LICENSE) © 2026 RetireGolden, LLC diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..26dd9cf --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,20 @@ +# Security Policy + +## Supported versions + +This project is in early `0.x` development and is not published yet. +Security fixes apply to the latest reviewed source until the first +advertised release of `@pegma/cache-core`. + +## Reporting a vulnerability + +Please use GitHub's private vulnerability reporting for this repository. +Do not open a public issue for suspected vulnerabilities. + +When reporting, include: + +- the package and version; +- a clear description of the issue; +- steps to reproduce; and +- the impact if a cache key, value, or log line could expose secrets, + customer identifiers, or weaken an isolation boundary between namespaces. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md new file mode 100644 index 0000000..a394e41 --- /dev/null +++ b/docs/PROJECT_PLAN.md @@ -0,0 +1,182 @@ +# Cache Core Project Plan + +## Status + +**Stage:** Phase 1 — ports, in-memory store, and the conformance suite. +Nothing is published. (`0.1.0`, unpublished.) + +**License:** MIT + +**Time and logging:** injected `@pegma/spine` `Clock` and `Logger`, pinned +exactly. This component never creates a clock and never calls `Date.now()` +on a production path. + +## Vision + +Every host eventually caches something, and nearly all of them get the same +quiet parts wrong: keys that collide across tenants, a stampede when a hot +entry expires, a TTL that follows wall clocks the test suite cannot pin, and +a "temporary" in-process map that becomes the production fallback when Redis +is down. The failure is silent — stale reads, thundering herds, or an +unbounded memory leak — and it surfaces as a latency cliff or a support +ticket, never as a typed error. + +One ephemeral-cache port, provider-agnostic, whose namespacing, single-flight +coalescing, clock-driven TTL, and fallback policy are the component — so a +host wires an adapter and gets the part everyone gets wrong, already right. + +## Where it sits in the stack + +Beside two components that deliberately refuse this job: +[`@pegma/storage-core`](https://github.com/pegma-dev/storage-core) persists +records and explicitly is not a cache; Spine supplies time and logging and +explicitly is not a store. The ephemeral read-through layer in the middle is +owned by nobody — this component is that middle. A typical host path: +request → **cache-core `getOrCompute`** → origin (storage, HTTP, or compute) +→ adapter (Redis or memory). Durable writes still go through storage-core. + +## Fundamental model + +**Cache key** — `{ namespace, key, hashTag? }`. `formatCacheKey` is the only +legal wire form. Namespaces do not share entries. A Redis Cluster hash tag, +when present, is embedded as `{tag}` so multi-key ops that a later adapter +opts into can colocate — they are never implied by the port. + +**Cache result** — `hit | miss | error`. Expected absence is `miss`. +Infrastructure failure is `error`. A successful `getOrCompute` that had to +run `compute` still returns `hit` with the computed value: the caller asked +for a value, and received one. + +**Codec** — schema-aware `encode` / `decode` over `Uint8Array`. JSON and +raw bytes ship as helpers; a host may supply its own. The store persists +bytes, not objects. + +**TTL** — absolute, sliding, or both, measured against the injected Clock. +Sliding refresh cannot extend past an absolute deadline. Expiry is a cache +concern, not a durability concern. + +**Single-flight** — process-local coalescing so N parallel misses for one +formatted key run `compute` exactly once. This is not a distributed lock +and must not be documented as one. + +**XFetch** — optional probabilistic early expiration so a hot key can +recompute before the deadline and dodge a stampede. Beta is a caller +choice; the clock is still the injected one. + +**Fallback policy** — `fail-open` computes when the backend errors; +`fail-closed` returns `error` and does not compute. Neither policy +installs an in-process map as a substitute store. + +## Design decisions + +### Ephemeral is the product + +A cache miss is not data loss. Anything that must survive a process restart +or a flushed Redis belongs in storage-core. Refusing durability is what +keeps this port honest and implementable on every adapter. + +### The suite is the specification + +Siblings export conformance as a subpath of the core package +(`@pegma/storage-core/conformance`). This repository publishes +`@pegma/cache-conformance` as its own package because Nathan's spec named +it that way and later adapters will depend on the suite without pulling +the memory store into their production graph. The _shape_ matches the +siblings: framework-free `conformanceCases`, one empty backend per case. + +### Hash tags are in the contract; multi-key ops are not + +Redis Cluster requires a hash tag for any atomic multi-key command. The +key type carries `hashTag` so an adapter can format `{tag}namespace:key`. +The port still refuses implicit cross-partition multi-key operations — +those land with a later adapter, named, tested, and never smuggled into +`get` / `set`. + +### No adapter package without a consumer + +The Pegma rule: do not create `cache-redis`, `cache-azure-redis`, +`cache-elasticache`, or `cache-upstash-redis` until implementation begins +and a named consumer exists. Phase 1 ships the port, the memory store, and +the suite those adapters will have to pass. + +### Vendor clients stay behind the port + +Application code depends on `CacheStore`. An adapter may import `ioredis` +or the Azure SDK; a host must not. The memory store exists so tests and +local composition never take a network client. + +## Scope + +### In scope + +- Ports (`CacheResult`, `CacheCodec`, `CacheKey`, `CacheStore`). +- `formatCacheKey`, JSON/bytes codecs, single-flight helper. +- In-memory store for tests and local hosts. +- Conformance: namespace isolation, TTL vs injected Clock, single-flight, + tag invalidation, fail-open compute on backend error. +- Optional XFetch on `getOrCompute`. + +### Non-goals + +- **Durability, transactions, or optimistic concurrency.** + `@pegma/storage-core`. +- **Implicit cross-partition multi-key operations.** Hash tags are + formatting, not a multi-key API. +- **Unbounded local memory fallbacks when a remote cache is down.** + Fail-open computes; it does not accumulate. +- **Vendor clients in application code.** +- **Redis / Azure Redis / ElastiCache / Upstash packages in Phase 1.** + +## Package architecture + +| Package | Responsibility | Phase | +| ---------------------------- | ---------------------------------- | ----- | +| `@pegma/cache-core` | Port, codecs, helper, memory store | 1 | +| `@pegma/cache-conformance` | Executable suite | 1 | +| `@pegma/cache-redis` | Generic Redis adapter | 2 | +| `@pegma/cache-azure-redis` | Azure Cache for Redis adapter | 3 | +| `@pegma/cache-elasticache` | Amazon ElastiCache adapter | 4 | +| `@pegma/cache-upstash-redis` | Upstash Redis adapter | 5 | + +Dependencies: `@pegma/spine` pinned exactly. Conformance pins +`@pegma/cache-core` to the workspace version. + +## Delivery phases + +### Phase 1 — port, memory store, conformance (this PR) + +`CacheStore`, codecs, `formatCacheKey`, single-flight `getOrCompute` +helper, in-memory store, and the suite cases listed above. The in-memory +store is the first adapter and must pass. + +### Phase 2 — generic Redis adapter + +`@pegma/cache-redis` against a real empty Redis (or a faithful local +server). Created only when implementation begins and a consumer exists. +Must pass `@pegma/cache-conformance`. + +### Phase 3 — Azure Cache for Redis + +Thin adapter over the same port. Real backend, same suite. + +### Phase 4 — Amazon ElastiCache + +Thin adapter. Cluster hash-tag behaviour is proven here, not implied. + +### Phase 5 — Upstash Redis + +Thin adapter for the serverless Redis client. Same suite. + +## Open questions + +**Distributed single-flight.** Process-local coalescing is Phase 1. +A Redis-backed lock or Redlock-shaped helper is a later adapter concern +and must not leak into the port as a durability claim. + +**Tag invalidation on cluster.** Memory can scan. Cluster adapters may +need a sidecar index or hash-tagged tag keys. The suite asserts the +observable (tagged entries disappear); it does not prescribe the index. + +**XFetch beta defaults.** Phase 1 leaves beta optional and off unless +requested. A default will be chosen when a second consumer shares a +preference — not before. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..f54c756 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,69 @@ +# Release operations + +`@pegma/cache-core` and `@pegma/cache-conformance` publish only from a +stable GitHub release. Merging a pull request never publishes, and the +workflow has no manual-dispatch or npm-token fallback. + +## Required external configuration + +Before the first release through this workflow: + +- configure `@pegma/cache-core` and `@pegma/cache-conformance` on npm with + the GitHub Actions trusted publisher `pegma-dev/cache-core`, workflow + `publish.yml`, environment `npm-publish`, and allowed action + `npm publish`; +- create the GitHub `npm-publish` environment. A second reviewer is not + required under Pegma's single-maintainer policy; +- create the repository Actions variable `RELEASE_ALLOWED_SIGNERS` containing + the reviewed Git SSH allowed-signers entry for the maintainer's release key; + this is public-key material, not a secret; and +- create an active tag ruleset targeting `v*` that prevents tag updates and + deletions and limits tag creation to the release maintainer. + +Do not add `NODE_AUTH_TOKEN`, an npm automation token, or another credential +fallback. After one trusted-publisher release is verified, disable any +remaining traditional npm publish tokens. + +## Release procedure + +The version in `packages/cache-core/package.json` and +`packages/cache-conformance/package.json` is the release version. Both +public packages publish at the same version. Change it through an ordinary +reviewed pull request and run the complete gate on Node 22 and 24. + +After that pull request is merged, create a signed annotated tag at the exact +`origin/main` commit, push the tag, verify the fetched tag, and only then +create the GitHub release with `--verify-tag`. Do not let GitHub create the tag +and never move or recreate a release tag. + +The release workflow verifies that the tag: + +- is a stable annotated `vX.Y.Z` tag signed by an allowed signer; +- matches the package version; +- points to the checkout and the GitHub release-event commit; and +- is contained in `origin/main`. + +Its preparation job has no OIDC permission. It installs the reviewed npm +`11.18.0` release and the pinned pnpm without dependency caching, runs the +full gate, builds and packs once with that npm CLI, smoke-tests the tarball +from a clean consumer, records its SHA-1 and SHA-512 integrity, and uploads +the exact prepared artifacts. The lockfile source of truth is `pnpm-lock.yaml`. + +Only the `npm-publish` job receives `id-token: write`. It installs no +dependencies and does not download pnpm. It runs +`node scripts/release-packages.mjs publish`, verifies the prepared manifest +and tarball hashes against the release commit, and publishes those tarballs +with npm provenance. + +## Safe retry + +The workflow is globally serialized. Re-run the failed release jobs against +the unchanged tag: + +- an absent version is published; +- an existing version with identical `dist.integrity` is verified and skipped; +- a different integrity, or any registry error other than `E404`, stops the + release. + +Never unpublish and reuse a version. If any released byte must change, prepare +a new version and a new signed tag. diff --git a/package.json b/package.json new file mode 100644 index 0000000..2de6033 --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "cache-core", + "version": "0.0.0", + "private": true, + "description": "Provider-neutral ephemeral caching for Pegma hosts.", + "license": "MIT", + "type": "module", + "packageManager": "pnpm@10.34.5", + "engines": { + "node": ">=22" + }, + "scripts": { + "build": "tsc -b", + "check": "tsc -b --pretty false && tsc -p tsconfig.test.json --pretty false", + "clean": "tsc -b --clean", + "format": "prettier --write .", + "format:check": "prettier --check .", + "release:check": "node scripts/release-packages.mjs check", + "release:pack": "node scripts/release-packages.mjs pack", + "release:publish": "node scripts/release-packages.mjs publish", + "test": "pnpm run build && vitest run" + }, + "devDependencies": { + "@types/node": "^26.1.1", + "prettier": "^3.9.6", + "typescript": "^7.0.2", + "vitest": "^4.1.10" + } +} diff --git a/packages/cache-conformance/LICENSE b/packages/cache-conformance/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/cache-conformance/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cache-conformance/README.md b/packages/cache-conformance/README.md new file mode 100644 index 0000000..28d789b --- /dev/null +++ b/packages/cache-conformance/README.md @@ -0,0 +1,34 @@ +# `@pegma/cache-conformance` + +Executable conformance suite every `@pegma/cache-core` adapter must pass. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +```ts +import { + createControllableClock, + createMemoryCacheStore, + createUnavailableCacheStore, +} from "@pegma/cache-core"; +import { conformanceCases } from "@pegma/cache-conformance"; +import { noopLogger } from "@pegma/spine"; + +const clock = createControllableClock("2026-08-15T16:00:00.000Z"); +const logger = noopLogger; + +for (const testCase of conformanceCases) { + it(testCase.name, () => + testCase.run({ + clock, + logger, + createStore: () => createMemoryCacheStore({ clock, logger }), + createUnavailableStore: () => + createUnavailableCacheStore({ clock, logger }), + }), + ); +} +``` + +The suite is the specification. A behaviour that is not asserted here is +not something a host may rely on. diff --git a/packages/cache-conformance/package.json b/packages/cache-conformance/package.json new file mode 100644 index 0000000..b2f9d48 --- /dev/null +++ b/packages/cache-conformance/package.json @@ -0,0 +1,40 @@ +{ + "name": "@pegma/cache-conformance", + "version": "0.1.0", + "description": "Executable conformance suite every @pegma/cache-core adapter must pass.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/cache-core.git", + "directory": "packages/cache-conformance" + }, + "dependencies": { + "@pegma/cache-core": "0.1.0", + "@pegma/spine": "0.1.2" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/cache-conformance/src/index.test.ts b/packages/cache-conformance/src/index.test.ts new file mode 100644 index 0000000..f44445d --- /dev/null +++ b/packages/cache-conformance/src/index.test.ts @@ -0,0 +1,28 @@ +import { describe, it } from "vitest"; + +import { + createControllableClock, + createMemoryCacheStore, + createUnavailableCacheStore, +} from "@pegma/cache-core"; +import { noopLogger } from "@pegma/spine"; + +import { conformanceCases } from "./index.js"; + +const START = "2026-08-15T16:00:00.000Z"; + +describe("createMemoryCacheStore", () => { + for (const testCase of conformanceCases) { + it(testCase.name, async () => { + const clock = createControllableClock(START); + const logger = noopLogger; + await testCase.run({ + clock, + logger, + createStore: () => createMemoryCacheStore({ clock, logger }), + createUnavailableStore: () => + createUnavailableCacheStore({ clock, logger }), + }); + }); + } +}); diff --git a/packages/cache-conformance/src/index.ts b/packages/cache-conformance/src/index.ts new file mode 100644 index 0000000..ffcd0be --- /dev/null +++ b/packages/cache-conformance/src/index.ts @@ -0,0 +1,298 @@ +import assert from "node:assert/strict"; + +import { + createUnavailableCacheStore, + formatCacheKey, + jsonCodec, + type CacheKey, + type CacheStore, + type ControllableClock, +} from "@pegma/cache-core"; +import { noopLogger, type Logger } from "@pegma/spine"; + +/** + * The behaviour every {@link CacheStore} implementation must exhibit. + * + * These cases are the specification. An adapter is finished when it passes + * them, and a behaviour that is not asserted here is not something a + * host may rely on. + * + * The suite has no test-framework dependency so that it can run under + * whatever runner an adapter already uses: + * + * ```ts + * for (const testCase of conformanceCases) { + * it(testCase.name, () => testCase.run(context)); + * } + * ``` + */ +export interface ConformanceContext { + readonly clock: ControllableClock; + readonly logger: Logger; + /** + * Stores returned during one case must share one initially empty physical + * backend. Adapters should return a fresh handle per call so cases prove + * that guarantees do not depend on process-local state, unless the factory + * intentionally reuses one backend for multi-instance checks. + */ + createStore(): CacheStore; + /** + * A store whose get/set/delete/ping fail. Memory uses + * {@link createUnavailableCacheStore}; adapters should point at a downed + * backend. Used only by fail-open / fail-closed cases. + */ + createUnavailableStore(): CacheStore; +} + +export interface ConformanceCase { + readonly name: string; + run(context: ConformanceContext): Promise; +} + +const codec = jsonCodec(); + +function key(namespace: string, id: string, hashTag?: string): CacheKey { + return hashTag === undefined + ? { namespace, key: id } + : { namespace, key: id, hashTag }; +} + +function testCase( + name: string, + run: (store: CacheStore, context: ConformanceContext) => Promise, +): ConformanceCase { + return { name, run: (context) => run(context.createStore(), context) }; +} + +export const conformanceCases: readonly ConformanceCase[] = [ + testCase( + "get returns miss for a key that was never written", + async (store) => { + assert.deepEqual(await store.get(key("ns", "absent"), codec), { + status: "miss", + }); + }, + ), + + testCase("set then get round-trips through the codec", async (store) => { + const address = key("widgets", "hammer"); + const written = await store.set(address, "claw", codec); + assert.equal(written.status, "hit"); + const got = await store.get(address, codec); + assert.equal(got.status, "hit"); + if (got.status === "hit") { + assert.equal(got.value, "claw"); + } + }), + + testCase("namespaces do not share records", async (store) => { + await store.set(key("alpha", "shared"), "in-alpha", codec); + assert.deepEqual(await store.get(key("beta", "shared"), codec), { + status: "miss", + }); + const got = await store.get(key("alpha", "shared"), codec); + assert.equal(got.status, "hit"); + if (got.status === "hit") { + assert.equal(got.value, "in-alpha"); + } + }), + + testCase( + "keys that share a separator character stay distinct", + async (store) => { + await store.set(key("a", "b:c"), "first", codec); + await store.set(key("ab", "c"), "second", codec); + const first = await store.get(key("a", "b:c"), codec); + const second = await store.get(key("ab", "c"), codec); + assert.equal(first.status, "hit"); + assert.equal(second.status, "hit"); + if (first.status === "hit" && second.status === "hit") { + assert.equal(first.value, "first"); + assert.equal(second.value, "second"); + } + }, + ), + + testCase( + "hash tags change the formatted key without leaking", + async (store) => { + const tagged = key("sessions", "one", "user-1"); + const plain = key("sessions", "one"); + assert.equal(formatCacheKey(tagged), "{user-1}sessions:one"); + assert.equal(formatCacheKey(plain), "sessions:one"); + await store.set(tagged, "tagged", codec); + assert.deepEqual(await store.get(plain, codec), { status: "miss" }); + const got = await store.get(tagged, codec); + assert.equal(got.status, "hit"); + if (got.status === "hit") { + assert.equal(got.value, "tagged"); + } + }, + ), + + testCase( + "absolute TTL expires against the injected Clock", + async (store, context) => { + const address = key("ttl", "absolute"); + await store.set(address, "fresh", codec, { ttl: { absoluteMs: 1_000 } }); + const before = await store.get(address, codec); + assert.equal(before.status, "hit"); + context.clock.advance(1_001); + assert.deepEqual(await store.get(address, codec), { status: "miss" }); + }, + ), + + testCase( + "sliding TTL refreshes on get and still expires", + async (store, context) => { + const address = key("ttl", "sliding"); + await store.set(address, "fresh", codec, { ttl: { slidingMs: 1_000 } }); + context.clock.advance(600); + const mid = await store.get(address, codec); + assert.equal(mid.status, "hit"); + context.clock.advance(600); + const still = await store.get(address, codec); + assert.equal(still.status, "hit"); + context.clock.advance(1_001); + assert.deepEqual(await store.get(address, codec), { status: "miss" }); + }, + ), + + testCase( + "sliding TTL cannot extend past an absolute deadline", + async (store, context) => { + const address = key("ttl", "both"); + await store.set(address, "fresh", codec, { + ttl: { absoluteMs: 1_000, slidingMs: 5_000 }, + }); + context.clock.advance(400); + const mid = await store.get(address, codec); + assert.equal(mid.status, "hit"); + context.clock.advance(700); + assert.deepEqual(await store.get(address, codec), { status: "miss" }); + }, + ), + + { + name: "N parallel misses run compute exactly once", + async run(context) { + const store = context.createStore(); + const address = key("flight", "hot"); + let computes = 0; + let entered = (): void => {}; + const started = new Promise((resolve) => { + entered = resolve; + }); + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const pending = Array.from({ length: 8 }, () => + store.getOrCompute(address, { + codec, + compute: async () => { + computes += 1; + entered(); + await gate; + return "computed"; + }, + }), + ); + await started; + await Promise.resolve(); + release(); + const results = await Promise.all(pending); + assert.equal(computes, 1); + for (const result of results) { + assert.equal(result.status, "hit"); + if (result.status === "hit") { + assert.equal(result.value, "computed"); + } + } + }, + }, + + testCase("tag invalidation removes every tagged entry", async (store) => { + await store.set(key("tags", "a"), "A", codec, { tags: ["group"] }); + await store.set(key("tags", "b"), "B", codec, { tags: ["group"] }); + await store.set(key("tags", "c"), "C", codec, { tags: ["other"] }); + const invalidated = await store.invalidateTags(["group"]); + assert.equal(invalidated.status, "hit"); + if (invalidated.status === "hit") { + assert.equal(invalidated.value, 2); + } + assert.deepEqual(await store.get(key("tags", "a"), codec), { + status: "miss", + }); + assert.deepEqual(await store.get(key("tags", "b"), codec), { + status: "miss", + }); + const kept = await store.get(key("tags", "c"), codec); + assert.equal(kept.status, "hit"); + if (kept.status === "hit") { + assert.equal(kept.value, "C"); + } + }), + + { + name: "fail-open computes when the backend errors", + async run(context) { + const store = context.createUnavailableStore(); + let computes = 0; + const result = await store.getOrCompute(key("down", "item"), { + codec, + fallback: "fail-open", + compute: () => { + computes += 1; + return "from-origin"; + }, + }); + assert.equal(computes, 1); + assert.equal(result.status, "hit"); + if (result.status === "hit") { + assert.equal(result.value, "from-origin"); + } + }, + }, + + { + name: "fail-closed returns error and does not compute", + async run(context) { + const store = context.createUnavailableStore(); + let computes = 0; + const result = await store.getOrCompute(key("down", "item"), { + codec, + fallback: "fail-closed", + compute: () => { + computes += 1; + return "should-not-run"; + }, + }); + assert.equal(computes, 0); + assert.equal(result.status, "error"); + }, + }, + + testCase("delete reports whether a live entry was removed", async (store) => { + const address = key("del", "one"); + await store.set(address, "x", codec); + const first = await store.delete(address); + assert.deepEqual(first, { status: "hit", value: true }); + assert.deepEqual(await store.get(address, codec), { status: "miss" }); + const second = await store.delete(address); + assert.deepEqual(second, { status: "hit", value: false }); + }), + + testCase("ping succeeds on a live store", async (store) => { + assert.deepEqual(await store.ping(), { status: "hit", value: true }); + }), +]; + +export function defaultUnavailableStore( + context: Pick, +): CacheStore { + return createUnavailableCacheStore({ + clock: context.clock, + logger: context.logger ?? noopLogger, + }); +} diff --git a/packages/cache-conformance/tsconfig.json b/packages/cache-conformance/tsconfig.json new file mode 100644 index 0000000..337ee68 --- /dev/null +++ b/packages/cache-conformance/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../cache-core" }] +} diff --git a/packages/cache-core/LICENSE b/packages/cache-core/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/cache-core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/cache-core/README.md b/packages/cache-core/README.md new file mode 100644 index 0000000..4067b24 --- /dev/null +++ b/packages/cache-core/README.md @@ -0,0 +1,34 @@ +# `@pegma/cache-core` + +Provider-neutral ephemeral caching for Pegma hosts: namespaced keys, +schema-aware codecs, cache-aside `getOrCompute`, and an in-memory store. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +```ts +import { + createControllableClock, + createMemoryCacheStore, + jsonCodec, +} from "@pegma/cache-core"; + +const clock = createControllableClock("2026-08-15T16:00:00.000Z"); +const cache = createMemoryCacheStore({ clock }); +const codec = jsonCodec(); + +const result = await cache.getOrCompute( + { namespace: "sessions", key: "abc", hashTag: "user-1" }, + { + codec, + ttl: { absoluteMs: 60_000 }, + fallback: "fail-open", + compute: () => loadSession(), + }, +); +``` + +Hosts inject a Spine `Clock` and `Logger`. This package never creates a +network client. Durable state belongs in `@pegma/storage-core`. + +Every adapter must pass `@pegma/cache-conformance`. diff --git a/packages/cache-core/package.json b/packages/cache-core/package.json new file mode 100644 index 0000000..265c05c --- /dev/null +++ b/packages/cache-core/package.json @@ -0,0 +1,39 @@ +{ + "name": "@pegma/cache-core", + "version": "0.1.0", + "description": "Provider-neutral ephemeral caching: namespaced keys, cache-aside getOrCompute, and an in-memory store.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/cache-core.git", + "directory": "packages/cache-core" + }, + "dependencies": { + "@pegma/spine": "0.1.2" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/cache-core/src/index.test.ts b/packages/cache-core/src/index.test.ts new file mode 100644 index 0000000..a521362 --- /dev/null +++ b/packages/cache-core/src/index.test.ts @@ -0,0 +1,160 @@ +import { describe, expect, it } from "vitest"; + +import { + CacheKeyValidationError, + bytesCodec, + createControllableClock, + createMemoryCacheStore, + createSingleFlight, + formatCacheKey, + jsonCodec, + shouldExpireEarly, +} from "./index.js"; + +const START = "2026-08-15T16:00:00.000Z"; + +describe("formatCacheKey", () => { + it("joins namespace and key", () => { + expect(formatCacheKey({ namespace: "sessions", key: "abc" })).toBe( + "sessions:abc", + ); + }); + + it("embeds a Redis Cluster hash tag", () => { + expect( + formatCacheKey({ + namespace: "sessions", + key: "abc", + hashTag: "user-1", + }), + ).toBe("{user-1}sessions:abc"); + }); + + it("rejects an empty namespace", () => { + expect(() => formatCacheKey({ namespace: "", key: "a" })).toThrow( + CacheKeyValidationError, + ); + }); + + it("rejects a colon in the namespace", () => { + expect(() => formatCacheKey({ namespace: "a:b", key: "c" })).toThrow( + CacheKeyValidationError, + ); + }); + + it("rejects a control character in the key", () => { + expect(() => + formatCacheKey({ namespace: "ns", key: `bad\u0000key` }), + ).toThrow(CacheKeyValidationError); + }); +}); + +describe("codecs", () => { + it("round-trips JSON", () => { + const codec = jsonCodec<{ readonly n: number }>(); + expect(codec.decode(codec.encode({ n: 3 }))).toEqual({ n: 3 }); + }); + + it("copies bytes so later mutation is invisible", () => { + const input = new Uint8Array([1, 2, 3]); + const stored = bytesCodec.encode(input); + input[0] = 9; + expect([...bytesCodec.decode(stored)]).toEqual([1, 2, 3]); + }); +}); + +describe("createSingleFlight", () => { + it("coalesces concurrent work for one key", async () => { + const flight = createSingleFlight(); + let runs = 0; + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const pending = [ + flight.do("k", async () => { + runs += 1; + await gate; + return "one"; + }), + flight.do("k", async () => { + runs += 1; + return "two"; + }), + ]; + release(); + expect(await Promise.all(pending)).toEqual(["one", "one"]); + expect(runs).toBe(1); + }); +}); + +describe("shouldExpireEarly", () => { + it("is more likely near expiry", () => { + expect( + shouldExpireEarly({ + nowMs: 999, + expiresAtMs: 1_000, + lastComputeMs: 50, + beta: 1, + random: () => 0.5, + }), + ).toBe(true); + expect( + shouldExpireEarly({ + nowMs: 0, + expiresAtMs: 1_000_000, + lastComputeMs: 1, + beta: 1, + random: () => 0.5, + }), + ).toBe(false); + }); +}); + +describe("createMemoryCacheStore", () => { + it("gives each store its own records", async () => { + const clock = createControllableClock(START); + const first = createMemoryCacheStore({ clock }); + const second = createMemoryCacheStore({ clock }); + const codec = jsonCodec(); + await first.set({ namespace: "ns", key: "only" }, "secret", codec); + expect(await second.get({ namespace: "ns", key: "only" }, codec)).toEqual({ + status: "miss", + }); + }); + + it("recomputes under XFetch when the random draw says so", async () => { + const clock = createControllableClock(START); + const store = createMemoryCacheStore({ + clock, + random: () => 0.5, + }); + const codec = jsonCodec(); + const address = { namespace: "xfetch", key: "hot" }; + let computes = 0; + const first = await store.getOrCompute(address, { + codec, + ttl: { absoluteMs: 60_000 }, + earlyExpiration: { beta: 1 }, + compute: () => { + computes += 1; + clock.advance(50); + return `v${computes}`; + }, + }); + expect(first).toMatchObject({ status: "hit", value: "v1" }); + // Remaining TTL is ~20ms; with beta=1, delta=50, random=0.5, XFetch fires. + clock.advance(59_980); + const second = await store.getOrCompute(address, { + codec, + ttl: { absoluteMs: 60_000 }, + earlyExpiration: { beta: 1 }, + compute: () => { + computes += 1; + return `v${computes}`; + }, + }); + expect(computes).toBe(2); + expect(second).toMatchObject({ status: "hit", value: "v2" }); + }); +}); diff --git a/packages/cache-core/src/index.ts b/packages/cache-core/src/index.ts new file mode 100644 index 0000000..e44b55a --- /dev/null +++ b/packages/cache-core/src/index.ts @@ -0,0 +1,590 @@ +import { + noopLogger, + type Clock, + type IsoTimestamp, + type Logger, +} from "@pegma/spine"; + +/** Outcome of a cache operation. */ +export type CacheResult = + | { + readonly status: "hit"; + readonly value: T; + readonly expiresAt?: IsoTimestamp; + readonly lastComputeMs?: number; + } + | { readonly status: "miss" } + | { readonly status: "error"; readonly error: unknown }; + +/** Schema-aware encode/decode over opaque bytes. */ +export interface CacheCodec { + readonly encode: (value: T) => Uint8Array; + readonly decode: (bytes: Uint8Array) => T; +} + +/** + * Logical cache address. {@link formatCacheKey} is the only legal wire form. + * `hashTag`, when present, becomes `{tag}` so a Redis Cluster adapter can + * colocate keys; the port never implies a multi-key operation. + */ +export interface CacheKey { + readonly namespace: string; + readonly key: string; + readonly hashTag?: string; +} + +export type CacheFallbackPolicy = "fail-open" | "fail-closed"; + +export interface CacheTtl { + readonly absoluteMs?: number; + readonly slidingMs?: number; +} + +export interface CacheSetOptions { + readonly ttl?: CacheTtl; + readonly tags?: readonly string[]; + readonly lastComputeMs?: number; +} + +export interface CacheEarlyExpiration { + readonly beta?: number; +} + +export interface CacheGetOrComputeOptions { + readonly compute: () => Promise | T; + readonly codec: CacheCodec; + readonly ttl?: CacheTtl; + readonly tags?: readonly string[]; + readonly fallback?: CacheFallbackPolicy; + readonly earlyExpiration?: CacheEarlyExpiration; +} + +export interface CacheStore { + get(key: CacheKey, codec: CacheCodec): Promise>; + set( + key: CacheKey, + value: T, + codec: CacheCodec, + options?: CacheSetOptions, + ): Promise>; + delete(key: CacheKey): Promise>; + getOrCompute( + key: CacheKey, + options: CacheGetOrComputeOptions, + ): Promise>; + invalidateTags(tags: readonly string[]): Promise>; + ping(): Promise>; +} + +export interface CacheDependencies { + readonly clock: Clock; + readonly logger?: Logger; + readonly random?: () => number; +} + +/** Rejects a {@link CacheKey} that cannot be formatted safely. */ +export class CacheKeyValidationError extends Error { + constructor(message: string) { + super(message); + this.name = "CacheKeyValidationError"; + } +} + +const CONTROL = /[\u0000-\u001F\u007F]/u; + +function requireToken(value: string, label: string): string { + if (value.length === 0) { + throw new CacheKeyValidationError(`${label} must not be empty`); + } + if (CONTROL.test(value)) { + throw new CacheKeyValidationError(`${label} must not contain controls`); + } + if (value.includes("{") || value.includes("}")) { + throw new CacheKeyValidationError(`${label} must not contain braces`); + } + return value; +} + +/** + * Formats a {@link CacheKey} for the wire. Namespaces cannot contain `:`, so + * `namespace:key` cannot collide across a `:` inside the key. + */ +export function formatCacheKey(key: CacheKey): string { + const namespace = requireToken(key.namespace, "namespace"); + if (namespace.includes(":")) { + throw new CacheKeyValidationError("namespace must not contain ':'"); + } + const id = requireToken(key.key, "key"); + if (key.hashTag === undefined) { + return `${namespace}:${id}`; + } + const hashTag = requireToken(key.hashTag, "hashTag"); + return `{${hashTag}}${namespace}:${id}`; +} + +export function jsonCodec(): CacheCodec { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + return { + encode(value) { + return encoder.encode(JSON.stringify(value)); + }, + decode(bytes) { + return JSON.parse(decoder.decode(bytes)) as T; + }, + }; +} + +export const bytesCodec: CacheCodec = { + encode(value) { + return value.slice(); + }, + decode(bytes) { + return bytes.slice(); + }, +}; + +export interface SingleFlight { + do(key: string, work: () => Promise): Promise; +} + +/** Process-local coalescing. Not a distributed lock. */ +export function createSingleFlight(): SingleFlight { + const inflight = new Map>(); + return { + do(key: string, work: () => Promise): Promise { + const existing = inflight.get(key); + if (existing !== undefined) { + return existing as Promise; + } + const pending = Promise.resolve() + .then(work) + .finally(() => { + inflight.delete(key); + }); + inflight.set(key, pending); + return pending; + }, + }; +} + +export interface ControllableClock extends Clock { + set(at: IsoTimestamp): void; + advance(ms: number): void; +} + +export function createControllableClock( + start: IsoTimestamp, +): ControllableClock { + let current = start; + return { + now: () => current, + set(at) { + current = at; + }, + advance(ms) { + current = new Date( + Date.parse(current) + ms, + ).toISOString() as IsoTimestamp; + }, + }; +} + +function clockMs(clock: Clock): number { + return Date.parse(clock.now()); +} + +function toIso(ms: number): IsoTimestamp { + return new Date(ms).toISOString() as IsoTimestamp; +} + +function logOutcome( + logger: Logger, + status: "hit" | "miss" | "error" | "compute", + namespace: string, +): void { + logger.log("info", `cache.${status}`, { namespace, status }); +} + +/** + * Classic XFetch: recompute when + * `now - expiry >= beta * lastComputeMs * log(random())`. + */ +export function shouldExpireEarly(options: { + readonly nowMs: number; + readonly expiresAtMs: number; + readonly lastComputeMs: number; + readonly beta: number; + readonly random: () => number; +}): boolean { + if (options.lastComputeMs <= 0 || options.beta <= 0) { + return false; + } + const unit = options.random(); + const sample = unit > 0 && unit < 1 ? unit : Number.EPSILON; + return ( + options.nowMs - options.expiresAtMs >= + options.beta * options.lastComputeMs * Math.log(sample) + ); +} + +export interface GetOrComputeBackend { + get(key: CacheKey, codec: CacheCodec): Promise>; + set( + key: CacheKey, + value: T, + codec: CacheCodec, + options?: CacheSetOptions, + ): Promise>; +} + +export interface RunGetOrComputeOptions extends CacheGetOrComputeOptions { + readonly key: CacheKey; + readonly backend: GetOrComputeBackend; + readonly clock: Clock; + readonly logger: Logger; + readonly singleFlight: SingleFlight; + readonly random?: () => number; +} + +/** + * Cache-aside helper adapters should call. Single-flight is process-local. + * Fail-open computes when `get` errors; fail-closed returns that error. + */ +export async function runGetOrCompute( + options: RunGetOrComputeOptions, +): Promise> { + const formatted = formatCacheKey(options.key); + const fallback = options.fallback ?? "fail-closed"; + const random = options.random ?? Math.random; + return options.singleFlight.do(formatted, async () => { + let read: CacheResult; + try { + read = await options.backend.get(options.key, options.codec); + } catch (error) { + read = { status: "error", error }; + } + + if (read.status === "hit") { + const expiresAt = read.expiresAt; + const lastComputeMs = read.lastComputeMs; + if ( + options.earlyExpiration !== undefined && + expiresAt !== undefined && + lastComputeMs !== undefined + ) { + const beta = options.earlyExpiration.beta ?? 1; + if ( + shouldExpireEarly({ + nowMs: clockMs(options.clock), + expiresAtMs: Date.parse(expiresAt), + lastComputeMs, + beta, + random, + }) + ) { + const recomputed = await computeAndStore( + options, + clockMs(options.clock), + ); + if (recomputed.status === "hit") { + return recomputed; + } + return read; + } + } + logOutcome(options.logger, "hit", options.key.namespace); + return read; + } + + if (read.status === "error") { + logOutcome(options.logger, "error", options.key.namespace); + if (fallback === "fail-closed") { + return read; + } + } else { + logOutcome(options.logger, "miss", options.key.namespace); + } + + return computeAndStore(options, clockMs(options.clock)); + }); +} + +async function computeAndStore( + options: RunGetOrComputeOptions, + startedMs: number, +): Promise> { + logOutcome(options.logger, "compute", options.key.namespace); + try { + const value = await options.compute(); + const lastComputeMs = Math.max(0, clockMs(options.clock) - startedMs); + const setOptions: CacheSetOptions = { + ...(options.ttl === undefined ? {} : { ttl: options.ttl }), + ...(options.tags === undefined ? {} : { tags: options.tags }), + lastComputeMs, + }; + try { + await options.backend.set(options.key, value, options.codec, setOptions); + } catch { + // A failed write must not hide a successful compute. + } + return { status: "hit", value }; + } catch (error) { + return { status: "error", error }; + } +} + +interface MemoryEntry { + bytes: Uint8Array; + tags: readonly string[]; + absoluteDeadlineMs: number | null; + slidingMs: number | null; + expiresAtMs: number | null; + lastComputeMs: number; +} + +function ttlDeadlines( + nowMs: number, + ttl: CacheTtl | undefined, +): Pick { + const absoluteMs = ttl?.absoluteMs; + const slidingMs = ttl?.slidingMs; + const absoluteDeadlineMs = + absoluteMs === undefined ? null : nowMs + absoluteMs; + const sliding = slidingMs === undefined ? null : slidingMs; + let expiresAtMs: number | null = null; + if (absoluteDeadlineMs !== null && sliding !== null) { + expiresAtMs = Math.min(absoluteDeadlineMs, nowMs + sliding); + } else if (absoluteDeadlineMs !== null) { + expiresAtMs = absoluteDeadlineMs; + } else if (sliding !== null) { + expiresAtMs = nowMs + sliding; + } + return { absoluteDeadlineMs, slidingMs: sliding, expiresAtMs }; +} + +function refreshSliding(entry: MemoryEntry, nowMs: number): void { + if (entry.slidingMs === null) { + return; + } + let next = nowMs + entry.slidingMs; + if (entry.absoluteDeadlineMs !== null) { + next = Math.min(next, entry.absoluteDeadlineMs); + } + entry.expiresAtMs = next; +} + +export function createMemoryCacheStore(options: CacheDependencies): CacheStore { + const clock = options.clock; + const logger = options.logger ?? noopLogger; + const random = options.random ?? Math.random; + const entries = new Map(); + const tagged = new Map>(); + const singleFlight = createSingleFlight(); + + function forgetTags(formatted: string, tags: readonly string[]): void { + for (const tag of tags) { + const keys = tagged.get(tag); + if (keys === undefined) { + continue; + } + keys.delete(formatted); + if (keys.size === 0) { + tagged.delete(tag); + } + } + } + + function rememberTags(formatted: string, tags: readonly string[]): void { + for (const tag of tags) { + const keys = tagged.get(tag) ?? new Set(); + keys.add(formatted); + tagged.set(tag, keys); + } + } + + const store: CacheStore = { + async get(key, codec) { + const formatted = formatCacheKey(key); + const entry = entries.get(formatted); + const nowMs = clockMs(clock); + if ( + entry === undefined || + (entry.expiresAtMs !== null && nowMs >= entry.expiresAtMs) + ) { + if (entry !== undefined) { + forgetTags(formatted, entry.tags); + entries.delete(formatted); + } + logOutcome(logger, "miss", key.namespace); + return { status: "miss" }; + } + refreshSliding(entry, nowMs); + try { + const value = codec.decode(entry.bytes); + const hit: CacheResult = { + status: "hit", + value, + ...(entry.expiresAtMs === null + ? {} + : { expiresAt: toIso(entry.expiresAtMs) }), + ...(entry.lastComputeMs > 0 + ? { lastComputeMs: entry.lastComputeMs } + : {}), + }; + logOutcome(logger, "hit", key.namespace); + return hit; + } catch (error) { + forgetTags(formatted, entry.tags); + entries.delete(formatted); + logOutcome(logger, "error", key.namespace); + return { status: "error", error }; + } + }, + + async set(key, value, codec, setOptions) { + const formatted = formatCacheKey(key); + const nowMs = clockMs(clock); + const previous = entries.get(formatted); + if (previous !== undefined) { + forgetTags(formatted, previous.tags); + } + const tags = setOptions?.tags ?? []; + const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); + entries.set(formatted, { + bytes: codec.encode(value).slice(), + tags, + lastComputeMs: setOptions?.lastComputeMs ?? 0, + ...deadlines, + }); + rememberTags(formatted, tags); + return { status: "hit", value: true }; + }, + + async delete(key) { + const formatted = formatCacheKey(key); + const entry = entries.get(formatted); + if (entry === undefined) { + return { status: "hit", value: false }; + } + forgetTags(formatted, entry.tags); + entries.delete(formatted); + return { status: "hit", value: true }; + }, + + async getOrCompute( + key: CacheKey, + computeOptions: CacheGetOrComputeOptions, + ): Promise> { + return runGetOrCompute({ + key, + backend: store, + clock, + logger, + singleFlight, + random, + compute: computeOptions.compute, + codec: computeOptions.codec, + ...(computeOptions.ttl === undefined + ? {} + : { ttl: computeOptions.ttl }), + ...(computeOptions.tags === undefined + ? {} + : { tags: computeOptions.tags }), + ...(computeOptions.fallback === undefined + ? {} + : { fallback: computeOptions.fallback }), + ...(computeOptions.earlyExpiration === undefined + ? {} + : { earlyExpiration: computeOptions.earlyExpiration }), + }); + }, + + async invalidateTags(tags) { + let removed = 0; + for (const tag of tags) { + const keys = tagged.get(tag); + if (keys === undefined) { + continue; + } + for (const formatted of [...keys]) { + const entry = entries.get(formatted); + if (entry === undefined) { + continue; + } + forgetTags(formatted, entry.tags); + entries.delete(formatted); + removed += 1; + } + } + return { status: "hit", value: removed }; + }, + + async ping() { + return { status: "hit", value: true }; + }, + }; + + return store; +} + +/** + * Backend that always errors on storage ops. `getOrCompute` still computes + * under fail-open. This is a test double, not a local-memory fallback. + */ +export function createUnavailableCacheStore( + options: CacheDependencies, +): CacheStore { + const clock = options.clock; + const logger = options.logger ?? noopLogger; + const random = options.random ?? Math.random; + const singleFlight = createSingleFlight(); + const down = new Error("cache backend unavailable"); + + const store: CacheStore = { + async get() { + return { status: "error", error: down }; + }, + async set() { + return { status: "error", error: down }; + }, + async delete() { + return { status: "error", error: down }; + }, + async getOrCompute( + key: CacheKey, + computeOptions: CacheGetOrComputeOptions, + ): Promise> { + return runGetOrCompute({ + key, + backend: store, + clock, + logger, + singleFlight, + random, + compute: computeOptions.compute, + codec: computeOptions.codec, + ...(computeOptions.ttl === undefined + ? {} + : { ttl: computeOptions.ttl }), + ...(computeOptions.tags === undefined + ? {} + : { tags: computeOptions.tags }), + ...(computeOptions.fallback === undefined + ? {} + : { fallback: computeOptions.fallback }), + ...(computeOptions.earlyExpiration === undefined + ? {} + : { earlyExpiration: computeOptions.earlyExpiration }), + }); + }, + async invalidateTags() { + return { status: "error", error: down }; + }, + async ping() { + return { status: "error", error: down }; + }, + }; + + return store; +} diff --git a/packages/cache-core/tsconfig.json b/packages/cache-core/tsconfig.json new file mode 100644 index 0000000..0e6e4b0 --- /dev/null +++ b/packages/cache-core/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": [] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..dd5b46d --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,949 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@types/node': + specifier: ^26.1.1 + version: 26.2.0 + prettier: + specifier: ^3.9.6 + version: 3.9.6 + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^4.1.10 + version: 4.1.10(@types/node@26.2.0)(vite@8.2.1(@types/node@26.2.0)) + + packages/cache-conformance: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + + packages/cache-core: + dependencies: + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + +packages: + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@oxc-project/types@0.144.0': + resolution: {integrity: sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg==} + + '@pegma/spine@0.1.2': + resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==} + engines: {node: '>=22'} + + '@rolldown/binding-android-arm64@1.2.4': + resolution: {integrity: sha512-jHC2cnyKz5xU2fhECtFl8OZ83cYNt13GZQD+0uMJ/X3o+ijmd56okHhTUwxVSHPx1IRVIJEZ1/1pPzeLCU6XKA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.4': + resolution: {integrity: sha512-Dc5mPD8F5F/FS8i01syd7FTF6yB2fVthH/TRkjwJkzUK6EpoxHtqvZQP5Zwq80/5z19TWYHIg1KOHboCgVx/aQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.4': + resolution: {integrity: sha512-fpDm4oBo6SqLvWUYCmFhdde3U9KH2fRNNMeAnAPAIwxRL345xutL0EtEUcuoxsoazdJGv/MuDBQHlCDrtbvqOg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.4': + resolution: {integrity: sha512-rSJoreDE/HoIzoaib6MTp5jQtCTdMHKIvItAKT/ImS6Y6Ww76oUaeMyp4Vc/fAgd/ehji068IxetHXAnqUwN9A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.4': + resolution: {integrity: sha512-/jm8OGHgn7oGaJu3i/qZI9spUGcJ+y/lk43ttQ/iO1tOd9NissG6o97bighBCiL+BKRngmcDuR6ikfwYdJmVuQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.4': + resolution: {integrity: sha512-tIP06BeD9EqvECBrPZ+sqdPlYrT+aYaAiu1wYziVx5elRK/ftm33JxVDy2bXGbr6J0CrtirCkR87/X5a2euEng==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.4': + resolution: {integrity: sha512-Ql1Q0EQqVThvn9VAVlwNzsUvbSFtCMGjLpRRi4pk5i7NZZ4n5ISiLMjHYtus4VQ2PvkSw24zyaCVsiS+sXPj1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.4': + resolution: {integrity: sha512-GjbjXD4XXfN19D0LZNbmiCBUoDiRACsYHr0yaIbbn8aFsXjHZifcYqu/W5Er5X2X990WjHXFrxarn5chzItorQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.4': + resolution: {integrity: sha512-p5WR0NOwaRmJ/B1b6IjEFLLivwEsf3PrdBIhRbhTCQisbo2SvHHpG4ELB/+FgQNnB88LTOF86upmJmbvZdQ2lw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.4': + resolution: {integrity: sha512-4/GyVjmhR+Tc6HLJvwc1sOhPqAZtySiSMesOZyX6JQ5XBxoTDEMKQzvo07NIK6nTon/SivlZqvhzvuVBNQhObQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.4': + resolution: {integrity: sha512-l9eeLsCNvPpmSXUej0etw/J1eqV0Jj1D5G/xG6YTijmE6dkv6E2QezgWbTfQk63v952DPqrjOCoiqxq7Bw0YUQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.4': + resolution: {integrity: sha512-e0F355MSTMm3+UOqtV3L24gFUp2N5m1f8L/7d56deik6va+AXdrt9F8LbzGpeWGWRbZEDq4m8NVnJDeBtf9DZg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.4': + resolution: {integrity: sha512-AWLi0uBRYh6QlE7OKhiz+phZC0qwtij2QZmhmOdsLdFn64m7oMpooE9ICE3lhm9xMb4SpDo2WbHcxX1iFLFtqw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.4': + resolution: {integrity: sha512-UwSDJOg3dqCAejWdxclJjCsh3Qq4vLYMDxmyHqo1btz3stK2VqgwNd3mm5tuIwzSlGIQ/1H9Hr+Zn09mrezNqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@26.2.0': + resolution: {integrity: sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/expect@4.1.10': + resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} + + '@vitest/mocker@4.1.10': + resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.10': + resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==} + + '@vitest/runner@4.1.10': + resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==} + + '@vitest/snapshot@4.1.10': + resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==} + + '@vitest/spy@4.1.10': + resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==} + + '@vitest/utils@4.1.10': + resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + es-module-lexer@2.3.1: + resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + nanoid@3.3.18: + resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@2.1.4: + resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==} + engines: {node: '>=12.20.0'} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.5: + resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} + engines: {node: '>=12'} + + postcss@8.5.26: + resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==} + engines: {node: ^10 || ^12 || >=14} + + prettier@3.9.6: + resolution: {integrity: sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==} + engines: {node: '>=14'} + hasBin: true + + rolldown@1.2.4: + resolution: {integrity: sha512-rSr7irW0K7QRWzjdJXqZowkcRdDtjRduh43rBltnVKd0VFq839l1lJoDvGJb6gl7+4rTTCrPWu+YfujUL8Ug7w==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.2.0: + resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.3.0: + resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} + engines: {node: '>=14.0.0'} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@8.3.0: + resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} + + vite@8.2.1: + resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.4.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.10: + resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.10 + '@vitest/browser-preview': 4.1.10 + '@vitest/browser-webdriverio': 4.1.10 + '@vitest/coverage-istanbul': 4.1.10 + '@vitest/coverage-v8': 4.1.10 + '@vitest/ui': 4.1.10 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + +snapshots: + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@oxc-project/types@0.144.0': {} + + '@pegma/spine@0.1.2': {} + + '@rolldown/binding-android-arm64@1.2.4': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.4': + optional: true + + '@rolldown/binding-darwin-x64@1.2.4': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.4': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.4': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.4': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.4': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.4': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.4': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.4': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.4': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.4': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.4': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.4': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/node@26.2.0': + dependencies: + undici-types: 8.3.0 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/expect@4.1.10': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + chai: 6.2.2 + tinyrainbow: 3.1.1 + + '@vitest/mocker@4.1.10(vite@8.2.1(@types/node@26.2.0))': + dependencies: + '@vitest/spy': 4.1.10 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.2.1(@types/node@26.2.0) + + '@vitest/pretty-format@4.1.10': + dependencies: + tinyrainbow: 3.1.1 + + '@vitest/runner@4.1.10': + dependencies: + '@vitest/utils': 4.1.10 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + '@vitest/utils': 4.1.10 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.10': {} + + '@vitest/utils@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.1 + + assertion-error@2.0.1: {} + + chai@6.2.2: {} + + convert-source-map@2.0.0: {} + + detect-libc@2.1.2: {} + + es-module-lexer@2.3.1: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.5): + optionalDependencies: + picomatch: 4.0.5 + + fsevents@2.3.3: + optional: true + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + nanoid@3.3.18: {} + + obug@2.1.4: {} + + pathe@2.0.3: {} + + picocolors@1.1.1: {} + + picomatch@4.0.5: {} + + postcss@8.5.26: + dependencies: + nanoid: 3.3.18 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prettier@3.9.6: {} + + rolldown@1.2.4: + dependencies: + '@oxc-project/types': 0.144.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm64': 1.2.4 + '@rolldown/binding-darwin-arm64': 1.2.4 + '@rolldown/binding-darwin-x64': 1.2.4 + '@rolldown/binding-freebsd-x64': 1.2.4 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.4 + '@rolldown/binding-linux-arm64-gnu': 1.2.4 + '@rolldown/binding-linux-arm64-musl': 1.2.4 + '@rolldown/binding-linux-ppc64-gnu': 1.2.4 + '@rolldown/binding-linux-s390x-gnu': 1.2.4 + '@rolldown/binding-linux-x64-gnu': 1.2.4 + '@rolldown/binding-linux-x64-musl': 1.2.4 + '@rolldown/binding-openharmony-arm64': 1.2.4 + '@rolldown/binding-win32-arm64-msvc': 1.2.4 + '@rolldown/binding-win32-x64-msvc': 1.2.4 + + siginfo@2.0.0: {} + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@4.2.0: {} + + tinybench@2.9.0: {} + + tinyexec@1.3.0: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.5) + picomatch: 4.0.5 + + tinyrainbow@3.1.1: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@8.3.0: {} + + vite@8.2.1(@types/node@26.2.0): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.5 + postcss: 8.5.26 + rolldown: 1.2.4 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.2.0 + fsevents: 2.3.3 + + vitest@4.1.10(@types/node@26.2.0)(vite@8.2.1(@types/node@26.2.0)): + dependencies: + '@vitest/expect': 4.1.10 + '@vitest/mocker': 4.1.10(vite@8.2.1(@types/node@26.2.0)) + '@vitest/pretty-format': 4.1.10 + '@vitest/runner': 4.1.10 + '@vitest/snapshot': 4.1.10 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + es-module-lexer: 2.3.1 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.4 + pathe: 2.0.3 + picomatch: 4.0.5 + std-env: 4.2.0 + tinybench: 2.9.0 + tinyexec: 1.3.0 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.1 + vite: 8.2.1(@types/node@26.2.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.2.0 + transitivePeerDependencies: + - msw + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..df27858 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,5 @@ +packages: + - "packages/*" + +linkWorkspacePackages: true +preferWorkspacePackages: true diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts new file mode 100644 index 0000000..bc2e344 --- /dev/null +++ b/scripts/release-packages.d.mts @@ -0,0 +1,86 @@ +export interface ReleasePackageDefinition { + readonly directory: string; + readonly name: string; +} + +export interface ValidationOptions { + readonly root?: string; + readonly releaseTag?: string; + readonly releasePrerelease?: boolean | string; + readonly expectedReleaseCommit?: string; + readonly requireClean?: boolean; + readonly requireMainAncestor?: boolean; + readonly requireReleaseTag?: boolean; +} + +export interface ReleaseCommandOptions extends ValidationOptions { + readonly manifest?: string; + readonly output?: string; +} + +export interface PublicPackageManifest { + readonly name: string; + readonly version: string; + readonly [key: string]: unknown; +} + +export interface ValidatedPackage { + readonly definition: ReleasePackageDefinition; + readonly manifest: PublicPackageManifest; + readonly packageDirectory: string; +} + +export interface ValidationResult { + readonly root: string; + readonly packages: readonly ValidatedPackage[]; + readonly releaseTag: string | undefined; +} + +export const RELEASE_PACKAGES: readonly ReleasePackageDefinition[]; + +export function parsePnpmLockfileImporters( + text: string, +): Record< + string, + Record> +>; + +export function resolvedVersionSatisfies( + version: string, + specifier: string, +): boolean; + +export function lockDependencyMatches( + lockDependency: { specifier?: string; version?: string } | undefined, + specifier: string, + options?: { workspace?: boolean }, +): boolean; + +export function isNormalReleaseVersion(version: string): boolean; + +export function parseArguments( + arguments_: readonly string[], +): ReleaseCommandOptions; + +export function validateRepository( + options?: ValidationOptions, +): Promise; + +export function validateReleaseTag(options?: { + readonly root?: string; + readonly releaseTag?: string; + readonly expectedReleaseCommit?: string; +}): { headCommit: string; releaseTag: string }; + +export function decidePublication( + localIntegrity: string, + registryIntegrity: string | null, +): "publish" | "skip"; + +export function prepareRelease( + options?: ReleaseCommandOptions, +): Promise<{ manifestPath: string; manifest: unknown }>; + +export function publishPreparedRelease( + options?: ReleaseCommandOptions, +): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs new file mode 100644 index 0000000..5d45f41 --- /dev/null +++ b/scripts/release-packages.mjs @@ -0,0 +1,1002 @@ +import { spawnSync } from "node:child_process"; +import { createHash, timingSafeEqual } from "node:crypto"; +import { + mkdtemp, + mkdir, + readFile, + readdir, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const REPOSITORY_URL = "git+https://github.com/pegma-dev/cache-core.git"; +const NODE_RANGE = ">=22"; +const REVIEWED_PNPM_VERSION = "10.34.5"; +const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u; +const DEPENDENCY_SECTIONS = [ + "dependencies", + "devDependencies", + "optionalDependencies", +]; + +/** Public packages in dependency order (core before the conformance suite). */ +export const RELEASE_PACKAGES = [ + { + directory: "cache-core", + name: "@pegma/cache-core", + }, + { + directory: "cache-conformance", + name: "@pegma/cache-conformance", + }, +]; + +const RELEASE_NAMES = new Set(RELEASE_PACKAGES.map(({ name }) => name)); +const FIRST_RELEASE_VERSION = "0.1.0"; + +export function isNormalReleaseVersion(version) { + const match = + typeof version === "string" ? STABLE_SEMVER.exec(version) : null; + // Reject the entire 0.0.x bootstrap range from the normal release lane. + return match !== null && (match[1] !== "0" || match[2] !== "0"); +} + +function fail(message) { + throw new Error(message); +} + +async function readJson(path) { + return JSON.parse(await readFile(path, "utf8")); +} + +function sameJson(left, right) { + return JSON.stringify(left) === JSON.stringify(right); +} + +function safeEqual(left, right) { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return ( + leftBytes.length === rightBytes.length && + timingSafeEqual(leftBytes, rightBytes) + ); +} + +function run(command, arguments_, options = {}) { + const result = spawnSync(command, arguments_, { + cwd: options.cwd, + encoding: "utf8", + env: options.env ?? process.env, + shell: options.shell ?? false, + stdio: options.capture ? "pipe" : "inherit", + }); + if (result.error) { + throw result.error; + } + if (result.status !== 0 && !options.allowFailure) { + const detail = [result.stdout, result.stderr].filter(Boolean).join("\n"); + fail( + `${command} ${arguments_.join(" ")} failed with exit code ${String(result.status)}${detail ? `:\n${detail}` : ""}`, + ); + } + return result; +} + +/** `pnpm run` sets npm_execpath to pnpm; pack/view/publish must still be npm. */ +function npmEnvironment(env = process.env) { + const isolated = { ...env }; + delete isolated.npm_execpath; + return isolated; +} + +function runNpm(arguments_, options = {}) { + return run(process.platform === "win32" ? "npm.cmd" : "npm", arguments_, { + ...options, + env: npmEnvironment(options.env ?? process.env), + shell: process.platform === "win32", + }); +} + +function runPnpm(arguments_, options = {}) { + return run(process.platform === "win32" ? "pnpm.cmd" : "pnpm", arguments_, { + ...options, + shell: process.platform === "win32", + }); +} + +function unquoteYamlScalar(value) { + if ( + (value.startsWith("'") && value.endsWith("'")) || + (value.startsWith('"') && value.endsWith('"')) + ) { + return value.slice(1, -1); + } + return value; +} + +/** Reads pnpm-lock.yaml importers without a YAML dependency. */ +export function parsePnpmLockfileImporters(text) { + const importers = {}; + let inImporters = false; + let currentPath = null; + let currentSection = null; + let currentDep = null; + + for (const line of text.split(/\r?\n/u)) { + if (!inImporters) { + if (line === "importers:") { + inImporters = true; + } + continue; + } + if (line.length > 0 && !line.startsWith(" ") && line.endsWith(":")) { + break; + } + if (line.trim() === "") { + continue; + } + + const importerMatch = /^ {2}(\S[^:]*):$/u.exec(line); + if (importerMatch !== null) { + currentPath = unquoteYamlScalar(importerMatch[1]); + importers[currentPath] = {}; + currentSection = null; + currentDep = null; + continue; + } + + const sectionMatch = + /^ {4}(dependencies|devDependencies|optionalDependencies|peerDependencies):$/u.exec( + line, + ); + if (sectionMatch !== null && currentPath !== null) { + currentSection = sectionMatch[1]; + importers[currentPath][currentSection] = {}; + currentDep = null; + continue; + } + + const depMatch = /^ {6}([^:]+):$/u.exec(line); + if (depMatch !== null && currentPath !== null && currentSection !== null) { + currentDep = unquoteYamlScalar(depMatch[1]); + importers[currentPath][currentSection][currentDep] = {}; + continue; + } + + const fieldMatch = /^ {8}(specifier|version): (.+)$/u.exec(line); + if ( + fieldMatch !== null && + currentPath !== null && + currentSection !== null && + currentDep !== null + ) { + importers[currentPath][currentSection][currentDep][fieldMatch[1]] = + unquoteYamlScalar(fieldMatch[2]); + } + } + return importers; +} + +function parseSemverTriple(version) { + const match = STABLE_SEMVER.exec(version); + if (match === null) { + return null; + } + return [Number(match[1]), Number(match[2]), Number(match[3])]; +} + +function leadingResolvedSemver(version) { + const full = /^(\d+)\.(\d+)\.(\d+)/u.exec(version); + if (full !== null) { + return [Number(full[1]), Number(full[2]), Number(full[3])]; + } + const majorMinor = /^(\d+)\.(\d+)(?![.\d])/u.exec(version); + if (majorMinor !== null) { + return [Number(majorMinor[1]), Number(majorMinor[2]), 0]; + } + const major = /^(\d+)(?![.\d])/u.exec(version); + if (major !== null) { + return [Number(major[1]), 0, 0]; + } + return null; +} + +function compareSemver(left, right) { + for (let index = 0; index < 3; index += 1) { + if (left[index] !== right[index]) { + return left[index] < right[index] ? -1 : 1; + } + } + return 0; +} + +function caretUpperBound([major, minor, patch]) { + if (major > 0) { + return [major + 1, 0, 0]; + } + if (minor > 0) { + return [0, minor + 1, 0]; + } + return [0, 0, patch + 1]; +} + +function tildeUpperBound([major, minor]) { + return [major, minor + 1, 0]; +} + +function inHalfOpenRange(resolved, lower, upper) { + return ( + compareSemver(resolved, lower) >= 0 && compareSemver(resolved, upper) < 0 + ); +} + +function lockfileResolvedIdentity(resolved) { + const suffix = resolved.indexOf("("); + return suffix === -1 ? resolved : resolved.slice(0, suffix); +} + +function parseCaretFloor(version) { + const triple = parseSemverTriple(version); + if (triple !== null) { + return { lower: triple, upper: caretUpperBound(triple) }; + } + const majorMinor = /^(\d+)\.(\d+)$/u.exec(version); + if (majorMinor !== null) { + const major = Number(majorMinor[1]); + const minor = Number(majorMinor[2]); + const lower = [major, minor, 0]; + // npm: ^0.0 → <0.1.0; ^1.2 → <2.0.0 + const upper = major > 0 ? [major + 1, 0, 0] : [0, minor + 1, 0]; + return { lower, upper }; + } + const major = /^(\d+)$/u.exec(version); + if (major !== null) { + const value = Number(major[1]); + // npm: ^0 → <1.0.0; ^1 → <2.0.0 + return { lower: [value, 0, 0], upper: [value + 1, 0, 0] }; + } + return null; +} + +/** Exact pins must match; ranges accept a resolved version in the specifier. */ +export function resolvedVersionSatisfies(version, specifier) { + const resolvedId = lockfileResolvedIdentity(version); + // Exact pins, including prereleases, match by identity after stripping + // pnpm peer suffixes at the first "(". + if (resolvedId === specifier) { + return true; + } + if (STABLE_SEMVER.test(specifier)) { + return false; + } + if (specifier === "*" || specifier === "x" || specifier === "X") { + return leadingResolvedSemver(version) !== null; + } + const resolved = leadingResolvedSemver(version); + if (resolved === null) { + return false; + } + if (specifier.startsWith("^")) { + const range = parseCaretFloor(specifier.slice(1)); + return ( + range !== null && inHalfOpenRange(resolved, range.lower, range.upper) + ); + } + if (specifier.startsWith("~")) { + const lower = parseSemverTriple(specifier.slice(1)); + return ( + lower !== null && inHalfOpenRange(resolved, lower, tildeUpperBound(lower)) + ); + } + const majorOnly = /^(\d+)$/u.exec(specifier); + if (majorOnly !== null) { + const lower = [Number(majorOnly[1]), 0, 0]; + return inHalfOpenRange(resolved, lower, [lower[0] + 1, 0, 0]); + } + const majorMinor = /^(\d+)\.(\d+)$/u.exec(specifier); + if (majorMinor !== null) { + const lower = [Number(majorMinor[1]), Number(majorMinor[2]), 0]; + return inHalfOpenRange(resolved, lower, tildeUpperBound(lower)); + } + return false; +} + +/** + * Each lockfile importer entry must carry that dependency's own specifier and + * a resolved version that satisfies it. Independent substring matches can + * accept a swapped pin; exact-equality on ranges rejects a valid lockfile. + */ +export function lockDependencyMatches(lockDependency, specifier, options = {}) { + if ( + lockDependency === undefined || + unquoteYamlScalar(lockDependency.specifier ?? "") !== specifier || + typeof lockDependency.version !== "string" + ) { + return false; + } + const version = unquoteYamlScalar(lockDependency.version); + if (options.workspace === true) { + return version.startsWith("link:"); + } + return resolvedVersionSatisfies(version, specifier); +} + +function gitCommand() { + return process.platform === "win32" ? "git.exe" : "git"; +} + +function hashTarball(bytes) { + return { + shasum: createHash("sha1").update(bytes).digest("hex"), + integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + }; +} + +function exportSpecifiers(manifest) { + if ( + manifest.exports === null || + typeof manifest.exports !== "object" || + Array.isArray(manifest.exports) + ) { + fail(`${manifest.name} must declare object-form exports`); + } + return Object.keys(manifest.exports).map((key) => + key === "." ? manifest.name : `${manifest.name}${key.slice(1)}`, + ); +} + +function exportTargets(value) { + if (typeof value === "string") { + return [value]; + } + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + return Object.values(value).flatMap(exportTargets); + } + return []; +} + +async function validatePackage(root, definition, lockfile) { + const packageDirectory = join(root, "packages", definition.directory); + const manifest = await readJson(join(packageDirectory, "package.json")); + if (manifest.name !== definition.name) { + fail(`expected ${definition.name} in packages/${definition.directory}`); + } + if (!STABLE_SEMVER.test(manifest.version)) { + fail(`${definition.name} must use a stable semantic version`); + } + if ( + manifest.private === true || + manifest.license !== "MIT" || + manifest.type !== "module" || + manifest.publishConfig?.access !== "public" || + manifest.engines?.node !== NODE_RANGE || + manifest.repository?.type !== "git" || + manifest.repository?.url !== REPOSITORY_URL || + manifest.repository?.directory !== `packages/${definition.directory}` + ) { + fail(`${definition.name} has invalid public package metadata`); + } + if ( + !Array.isArray(manifest.files) || + manifest.files.length === 0 || + manifest.files.some((entry) => !entry.startsWith("dist/")) + ) { + fail(`${definition.name} must publish only its dist allowlist`); + } + if ( + typeof manifest.scripts?.prepack !== "string" || + !manifest.scripts.prepack.includes("build") + ) { + fail(`${definition.name} must build during prepack`); + } + const targets = exportTargets(manifest.exports); + if ( + targets.length === 0 || + targets.some( + (target) => + typeof target !== "string" || + !target.startsWith("./dist/") || + target.includes(".."), + ) + ) { + fail(`${definition.name} exports must point into dist`); + } + await stat(join(packageDirectory, "README.md")); + await stat(join(packageDirectory, "LICENSE")); + + const lockEntry = lockfile[`packages/${definition.directory}`]; + if (lockEntry === undefined || typeof lockEntry !== "object") { + fail( + `${definition.name} is missing from pnpm-lock.yaml workspace inventory`, + ); + } + for (const section of DEPENDENCY_SECTIONS) { + for (const [name, version] of Object.entries(manifest[section] ?? {})) { + const workspace = RELEASE_NAMES.has(name); + if (workspace) { + const dependency = RELEASE_PACKAGES.find( + (entry) => entry.name === name, + ); + const dependencyManifest = await readJson( + join(root, "packages", dependency.directory, "package.json"), + ); + if (version !== dependencyManifest.version) { + fail( + `${definition.name} must pin ${name} to its exact workspace version`, + ); + } + } + if ( + !lockDependencyMatches(lockEntry[section]?.[name], version, { + workspace, + }) + ) { + fail( + workspace + ? `${definition.name} must pin ${name} to its exact workspace version` + : `${definition.name} ${name}@${version} is not synchronized with pnpm-lock.yaml`, + ); + } + } + } + return { definition, manifest, packageDirectory }; +} + +async function publicWorkspaceInventory(root) { + const directories = await readdir(join(root, "packages"), { + withFileTypes: true, + }); + const names = []; + for (const directory of directories) { + if (!directory.isDirectory()) { + continue; + } + const manifestPath = join(root, "packages", directory.name, "package.json"); + try { + const manifest = await readJson(manifestPath); + if (manifest.private !== true) { + names.push(manifest.name); + } + } catch (error) { + if (error?.code !== "ENOENT") { + throw error; + } + } + } + return names.sort(); +} + +export function validateReleaseTag(options = {}) { + const root = resolve(options.root ?? defaultRoot()); + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + const expectedReleaseCommit = + options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; + if (releaseTag === undefined || !/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { + fail("a stable release tag is required"); + } + if ( + expectedReleaseCommit === undefined || + !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) + ) { + fail("an exact release event commit is required"); + } + + const tagRef = `refs/tags/${releaseTag}`; + const objectType = run(gitCommand(), ["cat-file", "-t", tagRef], { + cwd: root, + capture: true, + allowFailure: true, + }); + if (objectType.status !== 0 || objectType.stdout.trim() !== "tag") { + fail("the release ref must be an annotated tag object"); + } + const headCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + const tagCommit = run(gitCommand(), ["rev-parse", `${tagRef}^{commit}`], { + cwd: root, + capture: true, + }).stdout.trim(); + if ( + !safeEqual(headCommit, tagCommit) || + !safeEqual(headCommit, expectedReleaseCommit) + ) { + fail( + "the release checkout, signed tag target, and release event commit must match", + ); + } + const signature = run(gitCommand(), ["verify-tag", "--raw", tagRef], { + cwd: root, + capture: true, + allowFailure: true, + }); + if (signature.status !== 0) { + fail("the release tag signature is not valid for an approved signer"); + } + const onMain = run( + gitCommand(), + ["merge-base", "--is-ancestor", tagCommit, "refs/remotes/origin/main"], + { cwd: root, capture: true, allowFailure: true }, + ); + if (onMain.status !== 0) { + fail("the release tag commit must be contained in origin/main"); + } + return { headCommit, releaseTag }; +} + +export async function validateRepository(options = {}) { + const root = resolve(options.root ?? defaultRoot()); + const rootManifest = await readJson(join(root, "package.json")); + if ( + rootManifest.private !== true || + rootManifest.packageManager !== `pnpm@${REVIEWED_PNPM_VERSION}` + ) { + fail(`the private root must pin pnpm@${REVIEWED_PNPM_VERSION}`); + } + const expectedInventory = RELEASE_PACKAGES.map(({ name }) => name).sort(); + const actualInventory = await publicWorkspaceInventory(root); + if (!sameJson(actualInventory, expectedInventory)) { + fail("public workspace inventory does not match the reviewed release list"); + } + const lockfile = parsePnpmLockfileImporters( + await readFile(join(root, "pnpm-lock.yaml"), "utf8"), + ); + const packages = []; + for (const definition of RELEASE_PACKAGES) { + packages.push(await validatePackage(root, definition, lockfile)); + } + + if (options.requireClean) { + const status = run(gitCommand(), ["status", "--porcelain"], { + cwd: root, + capture: true, + }).stdout; + if (status.trim() !== "") { + fail("release preparation requires a clean checkout"); + } + } + if (options.requireMainAncestor) { + const head = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + const onMain = run( + gitCommand(), + ["merge-base", "--is-ancestor", head, "refs/remotes/origin/main"], + { cwd: root, capture: true, allowFailure: true }, + ); + if (onMain.status !== 0) { + fail("release commit must be contained in origin/main"); + } + } + + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + if (releaseTag !== undefined) { + if (!/^v\d+\.\d+\.\d+$/u.test(releaseTag)) { + fail("release tag must be a stable vX.Y.Z tag"); + } + const version = releaseTag.slice(1); + if (!packages.some(({ manifest }) => manifest.version === version)) { + fail( + `release tag ${releaseTag} does not match any public package version`, + ); + } + const prerelease = + options.releasePrerelease ?? process.env.RELEASE_PRERELEASE ?? false; + if (prerelease === true || prerelease === "true") { + fail("prereleases cannot publish packages"); + } + } + if (options.requireReleaseTag) { + validateReleaseTag({ + root, + releaseTag, + expectedReleaseCommit: options.expectedReleaseCommit, + }); + } + return { root, packages, releaseTag }; +} + +function verifyPackedFiles(manifest, files) { + const paths = files.map(({ path }) => path); + for (const required of ["package.json", "README.md", "LICENSE"]) { + if (!paths.includes(required)) { + fail(`${manifest.name} tarball is missing ${required}`); + } + } + if ( + paths.some( + (path) => + !["package.json", "README.md", "LICENSE"].includes(path) && + !path.startsWith("dist/"), + ) + ) { + fail( + `${manifest.name} tarball contains a file outside the reviewed allowlist`, + ); + } + for (const target of exportTargets(manifest.exports)) { + const path = target.replace(/^\.\//u, ""); + if (!paths.includes(path)) { + fail(`${manifest.name} tarball is missing exported file ${path}`); + } + } +} + +async function smokeTestTarballs(root, packageRecords) { + const directory = await mkdtemp(join(tmpdir(), "pegma-release-smoke-")); + try { + await writeFile( + join(directory, "package.json"), + '{"name":"pegma-release-smoke","private":true,"type":"module"}\n', + ); + runNpm( + [ + "install", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "--package-lock=false", + ...packageRecords.map(({ tarballPath }) => tarballPath), + ], + { cwd: directory, capture: true }, + ); + for (const { manifest } of packageRecords) { + for (const specifier of exportSpecifiers(manifest)) { + run( + process.execPath, + [ + "--input-type=module", + "--eval", + `await import(${JSON.stringify(specifier)})`, + ], + { cwd: directory, capture: true }, + ); + } + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +function queryRegistryIntegrity(name, version) { + const spec = `${name}@${version}`; + const result = runNpm(["view", spec, "dist.integrity", "--json"], { + capture: true, + allowFailure: true, + }); + if (result.status === 0) { + const integrity = JSON.parse(result.stdout); + if (typeof integrity !== "string" || integrity.length === 0) { + fail(`${spec} exists without dist.integrity`); + } + return integrity; + } + const output = `${result.stdout}\n${result.stderr}`; + if (/\bE404\b/u.test(output)) { + return null; + } + fail(`npm registry lookup failed for ${spec}:\n${output.trim()}`); +} + +export function decidePublication(localIntegrity, registryIntegrity) { + if (registryIntegrity === null) { + return "publish"; + } + if (safeEqual(localIntegrity, registryIntegrity)) { + return "skip"; + } + fail("the registry version exists with different tarball integrity"); +} + +export async function prepareRelease(options = {}) { + const { root, packages, releaseTag } = await validateRepository(options); + for (const { manifest } of packages) { + if (!isNormalReleaseVersion(manifest.version)) { + fail( + `normal releases require version ${FIRST_RELEASE_VERSION} or later (got ${manifest.name}@${manifest.version})`, + ); + } + } + const gitCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: root, + capture: true, + }).stdout.trim(); + if (!/^[0-9a-f]{40,64}$/u.test(gitCommit)) { + fail(`git returned an invalid commit SHA: ${gitCommit}`); + } + const output = resolve(root, options.output ?? ".release"); + await mkdir(output, { recursive: true }); + if ((await readdir(output)).length !== 0) { + fail(`release output directory must be empty: ${output}`); + } + + runPnpm(["run", "build"], { cwd: root }); + const records = []; + const tagVersion = releaseTag?.slice(1); + for (const { definition, manifest } of packages) { + const result = runNpm( + [ + "pack", + join(root, "packages", definition.directory), + "--json", + "--pack-destination", + output, + ], + { cwd: root, capture: true }, + ); + const [packed] = JSON.parse(result.stdout); + if ( + packed?.name !== definition.name || + packed?.version !== manifest.version || + typeof packed.filename !== "string" || + !Array.isArray(packed.files) + ) { + fail(`npm pack returned invalid metadata for ${definition.name}`); + } + verifyPackedFiles(manifest, packed.files); + const tarballPath = join(output, basename(packed.filename)); + const hashes = hashTarball(await readFile(tarballPath)); + if ( + !safeEqual(hashes.integrity, packed.integrity) || + !safeEqual(hashes.shasum, packed.shasum) + ) { + fail(`${definition.name} tarball hashes do not match npm pack metadata`); + } + records.push({ + name: definition.name, + version: manifest.version, + directory: definition.directory, + tarball: basename(tarballPath), + tarballPath, + integrity: hashes.integrity, + shasum: hashes.shasum, + publish: tagVersion === undefined || manifest.version === tagVersion, + files: packed.files + .map(({ path, size }) => ({ path, size })) + .sort((left, right) => left.path.localeCompare(right.path)), + manifest, + }); + } + await smokeTestTarballs(root, records); + + if (releaseTag !== undefined) { + for (const record of records.filter(({ publish }) => !publish)) { + const registryIntegrity = queryRegistryIntegrity( + record.name, + record.version, + ); + if ( + registryIntegrity === null || + !safeEqual(record.integrity, registryIntegrity) + ) { + fail( + `${record.name}@${record.version} is not selected by ${releaseTag} and must exactly match npm`, + ); + } + } + } + + const manifest = { + schemaVersion: 1, + gitCommit, + releaseTag: releaseTag ?? null, + packages: records.map( + ({ tarballPath, manifest: _manifest, ...record }) => record, + ), + }; + const manifestPath = join(output, "package-manifest.json"); + await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + return { manifestPath, manifest }; +} + +async function verifyPreparedManifest(manifestPath) { + const manifest = await readJson(manifestPath); + if ( + manifest.schemaVersion !== 1 || + !/^[0-9a-f]{40,64}$/u.test(manifest.gitCommit) || + !/^v\d+\.\d+\.\d+$/u.test(manifest.releaseTag) || + !Array.isArray(manifest.packages) || + !sameJson( + manifest.packages.map(({ name }) => name), + RELEASE_PACKAGES.map(({ name }) => name), + ) + ) { + fail("prepared package manifest has an invalid package inventory"); + } + const currentCommit = run(gitCommand(), ["rev-parse", "HEAD"], { + cwd: defaultRoot(), + capture: true, + }).stdout.trim(); + if (!safeEqual(currentCommit, manifest.gitCommit)) { + fail("prepared package manifest commit does not match the checkout"); + } + const tagVersion = manifest.releaseTag.slice(1); + if (!manifest.packages.some(({ publish }) => publish)) { + fail("prepared package manifest has no release candidates"); + } + for (const [index, record] of manifest.packages.entries()) { + const definition = RELEASE_PACKAGES[index]; + const expectedTarball = `${definition.name + .slice(1) + .replace("/", "-")}-${record.version}.tgz`; + if ( + record.directory !== definition.directory || + record.tarball !== expectedTarball || + !STABLE_SEMVER.test(record.version) || + record.publish !== (record.version === tagVersion) || + typeof record.integrity !== "string" || + typeof record.shasum !== "string" || + !Array.isArray(record.files) + ) { + fail(`${record.name} has invalid prepared metadata`); + } + const tarball = resolve(dirname(manifestPath), record.tarball); + if (dirname(tarball) !== resolve(dirname(manifestPath))) { + fail(`${record.name} tarball must be beside the package manifest`); + } + const hashes = hashTarball(await readFile(tarball)); + if ( + !safeEqual(hashes.integrity, record.integrity) || + !safeEqual(hashes.shasum, record.shasum) + ) { + fail(`${record.name} prepared tarball has changed`); + } + } + return manifest; +} + +function requireTrustedPublishingNpm() { + const version = runNpm(["--version"], { capture: true }).stdout.trim(); + const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); + if (match === null) { + fail(`could not parse npm version ${version}`); + } + const [, majorText, minorText, patchText] = match; + const [major, minor, patch] = [majorText, minorText, patchText].map(Number); + if ( + major < 11 || + (major === 11 && minor < 5) || + (major === 11 && minor === 5 && patch < 1) + ) { + fail("trusted publishing requires npm 11.5.1 or newer"); + } +} + +function wait(milliseconds) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); +} + +function confirmRegistryIntegrity(record) { + for (let attempt = 0; attempt < 6; attempt += 1) { + const integrity = queryRegistryIntegrity(record.name, record.version); + if (integrity !== null && safeEqual(record.integrity, integrity)) { + return; + } + if (attempt < 5) { + wait(2 ** attempt * 1000); + } + } + fail( + `${record.name}@${record.version} did not become visible with the prepared integrity`, + ); +} + +export async function publishPreparedRelease(options = {}) { + if ( + process.env.GITHUB_ACTIONS !== "true" || + process.env.GITHUB_EVENT_NAME !== "release" + ) { + fail("release:publish is restricted to a GitHub release workflow"); + } + requireTrustedPublishingNpm(); + const manifestPath = resolve( + options.manifest ?? ".release/package-manifest.json", + ); + const manifest = await verifyPreparedManifest(manifestPath); + const releaseTag = options.releaseTag ?? process.env.RELEASE_TAG; + const expectedReleaseCommit = + options.expectedReleaseCommit ?? process.env.RELEASE_COMMIT; + if (releaseTag !== manifest.releaseTag) { + fail("prepared manifest must match the release tag"); + } + if ( + expectedReleaseCommit === undefined || + !/^[0-9a-f]{40,64}$/u.test(expectedReleaseCommit) || + !safeEqual(manifest.gitCommit, expectedReleaseCommit) + ) { + fail("prepared package manifest must match the release event commit"); + } + for (const record of manifest.packages.filter(({ publish }) => publish)) { + const registryIntegrity = queryRegistryIntegrity( + record.name, + record.version, + ); + const decision = decidePublication(record.integrity, registryIntegrity); + if (decision === "skip") { + process.stdout.write( + `Verified existing ${record.name}@${record.version}; skipping.\n`, + ); + continue; + } + const tarball = resolve(dirname(manifestPath), record.tarball); + runNpm(["publish", tarball, "--access", "public", "--provenance"], { + cwd: dirname(manifestPath), + }); + confirmRegistryIntegrity(record); + } +} + +export function parseArguments(arguments_) { + const options = {}; + for (let index = 0; index < arguments_.length; index += 1) { + const argument = arguments_[index]; + if (argument === "--") { + continue; + } + if (argument === "--require-main-ancestor") { + options.requireMainAncestor = true; + continue; + } + if (argument === "--require-clean") { + options.requireClean = true; + continue; + } + if (argument === "--require-release-tag") { + options.requireReleaseTag = true; + continue; + } + const key = + argument === "--root" + ? "root" + : argument === "--output" + ? "output" + : argument === "--manifest" + ? "manifest" + : argument === "--expected-release-commit" + ? "expectedReleaseCommit" + : null; + if (key === null || arguments_[index + 1] === undefined) { + fail(`unknown or incomplete argument: ${argument}`); + } + options[key] = arguments_[index + 1]; + index += 1; + } + return options; +} + +function defaultRoot() { + return resolve(dirname(fileURLToPath(import.meta.url)), ".."); +} + +async function main() { + const [command, ...arguments_] = process.argv.slice(2); + const options = parseArguments(arguments_); + if (command === "check") { + await validateRepository(options); + process.stdout.write("Release metadata is valid.\n"); + return; + } + if (command === "pack") { + const { manifestPath } = await prepareRelease(options); + process.stdout.write(`Prepared release packages at ${manifestPath}.\n`); + return; + } + if (command === "publish") { + await publishPreparedRelease(options); + return; + } + fail("usage: release-packages.mjs [options]"); +} + +const isMain = + process.argv[1] !== undefined && + resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isMain) { + await main(); +} diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts new file mode 100644 index 0000000..73e2713 --- /dev/null +++ b/tests/release-packages.test.ts @@ -0,0 +1,267 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + RELEASE_PACKAGES, + decidePublication, + isNormalReleaseVersion, + lockDependencyMatches, + parseArguments, + parsePnpmLockfileImporters, + resolvedVersionSatisfies, + validateRepository, +} from "../scripts/release-packages.mjs"; + +const packageVersion = ( + JSON.parse( + readFileSync( + join(process.cwd(), "packages", "cache-core", "package.json"), + "utf8", + ), + ) as { version: string } +).version; + +describe("release package metadata", () => { + it("accepts npm's cross-platform argument separator", () => { + expect(parseArguments(["--", "--output", ".release"])).toEqual({ + output: ".release", + }); + }); + + it("validates package manifests and the lockfile together", async () => { + await expect(validateRepository()).resolves.toBeDefined(); + }); + + it("keeps the exact public package inventory in dependency order", () => { + expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual([ + "@pegma/cache-core", + "@pegma/cache-conformance", + ]); + }); + + it("ships the synchronized 0.1.0 package set with exact internal pins", () => { + const manifests = RELEASE_PACKAGES.map(({ directory }) => + JSON.parse( + readFileSync( + join(process.cwd(), "packages", directory, "package.json"), + "utf8", + ), + ), + ) as Array<{ + name: string; + version: string; + dependencies?: Record; + }>; + + expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ + { name: "@pegma/cache-core", version: "0.1.0" }, + { name: "@pegma/cache-conformance", version: "0.1.0" }, + ]); + expect(manifests[1]?.dependencies?.["@pegma/cache-core"]).toBe("0.1.0"); + expect(manifests[0]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); + expect(packageVersion).toBe("0.1.0"); + }); + + it("rejects the bootstrap range from the normal release lane", () => { + expect(isNormalReleaseVersion("0.0.0")).toBe(false); + expect(isNormalReleaseVersion("0.0.1")).toBe(false); + expect(isNormalReleaseVersion("0.1.0")).toBe(true); + expect(isNormalReleaseVersion("1.0.0")).toBe(true); + }); + + it("pins pnpm as the workspace package manager", () => { + const manifest = JSON.parse( + readFileSync(join(process.cwd(), "package.json"), "utf8"), + ) as { packageManager?: string }; + expect(manifest.packageManager).toBe("pnpm@10.34.5"); + expect(existsSync(join(process.cwd(), "pnpm-lock.yaml"))).toBe(true); + expect(existsSync(join(process.cwd(), "pnpm-workspace.yaml"))).toBe(true); + expect(existsSync(join(process.cwd(), "package-lock.json"))).toBe(false); + expect(existsSync(join(process.cwd(), "yarn.lock"))).toBe(false); + }); + + it("reads workspace inventory and link pins from pnpm-lock.yaml", () => { + const importers = parsePnpmLockfileImporters(`importers: + + .: + devDependencies: + prettier: + specifier: ^3.9.6 + version: 3.9.6 + + packages/cache-core: + dependencies: + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + + packages/cache-conformance: + dependencies: + '@pegma/cache-core': + specifier: 0.1.0 + version: link:../cache-core + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + +packages: + prettier@3.9.6: + resolution: {integrity: sha512-example} +`); + expect(Object.keys(importers)).toEqual([ + ".", + "packages/cache-core", + "packages/cache-conformance", + ]); + expect(importers["packages/cache-core"]).toEqual({ + dependencies: { + "@pegma/spine": { specifier: "0.1.2", version: "0.1.2" }, + }, + }); + expect( + importers["packages/cache-conformance"]?.dependencies?.[ + "@pegma/cache-core" + ], + ).toEqual({ + specifier: "0.1.0", + version: "link:../cache-core", + }); + expect(importers["packages/cache-conformance"]?.peerDependencies).toBe( + undefined, + ); + + const live = parsePnpmLockfileImporters( + readFileSync(join(process.cwd(), "pnpm-lock.yaml"), "utf8"), + ); + expect( + live["packages/cache-conformance"]?.dependencies?.["@pegma/cache-core"], + ).toEqual({ + specifier: "0.1.0", + version: "link:../cache-core", + }); + expect( + lockDependencyMatches( + live["packages/cache-core"]?.dependencies?.["@pegma/spine"], + "0.1.2", + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/cache-conformance"]?.dependencies?.["@pegma/cache-core"], + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + }); + + it("matches each lockfile dependency to its own specifier and resolved version", () => { + expect( + lockDependencyMatches({ specifier: "0.1.2", version: "0.1.2" }, "0.1.2"), + ).toBe(true); + expect( + lockDependencyMatches({ specifier: "0.1.2", version: "0.4.0" }, "0.1.2"), + ).toBe(false); + expect( + lockDependencyMatches( + { specifier: "0.1.0", version: "link:../cache-core" }, + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + expect( + lockDependencyMatches({ specifier: "0.1.0", version: "0.1.0" }, "0.1.0", { + workspace: true, + }), + ).toBe(false); + expect(resolvedVersionSatisfies("1.2.3", "^1.2.0")).toBe(true); + expect( + resolvedVersionSatisfies("1.2.3(@types/node@26.1.2)", "^1.2.0"), + ).toBe(true); + expect(resolvedVersionSatisfies("2.0.0", "^1.2.0")).toBe(false); + expect(resolvedVersionSatisfies("0.2.9", "^0.2.3")).toBe(true); + expect(resolvedVersionSatisfies("0.3.0", "^0.2.3")).toBe(false); + expect(resolvedVersionSatisfies("0.0.3", "^0.0.3")).toBe(true); + expect(resolvedVersionSatisfies("0.0.4", "^0.0.3")).toBe(false); + expect(resolvedVersionSatisfies("0.1.1", "0.1.1")).toBe(true); + expect(resolvedVersionSatisfies("0.1.1(@pegma/spine@0.1.1)", "0.1.1")).toBe( + true, + ); + expect(resolvedVersionSatisfies("0.1.2", "0.1.1")).toBe(false); + expect(resolvedVersionSatisfies("1.2.3-rc.1", "1.2.3")).toBe(false); + expect(resolvedVersionSatisfies("1.2.3-rc.1", "1.2.3-rc.1")).toBe(true); + expect( + resolvedVersionSatisfies("1.2.3-rc.1(@foo@1.0.0)", "1.2.3-rc.1"), + ).toBe(true); + expect(resolvedVersionSatisfies("1.2.3", "1.2.3-rc.1")).toBe(false); + expect(resolvedVersionSatisfies("0.9.0", "^0")).toBe(true); + expect(resolvedVersionSatisfies("1.0.0", "^0")).toBe(false); + expect(resolvedVersionSatisfies("0.0.9", "^0.0")).toBe(true); + expect(resolvedVersionSatisfies("0.1.0", "^0.0")).toBe(false); + }); + + it("keeps pack, registry view, and publish on the npm CLI", () => { + const source = readFileSync( + join(process.cwd(), "scripts/release-packages.mjs"), + "utf8", + ); + expect(source).not.toMatch( + /(?:npmExecPath|npm_execpath)\s*(?:\?\?|===|!==)/u, + ); + expect(source).toMatch( + /function runNpm\([\s\S]*?process\.platform === "win32" \? "npm\.cmd" : "npm"/u, + ); + }); +}); + +describe("release source authentication", () => { + it("keeps preparation outside the OIDC-enabled publisher job", () => { + const workflow = readFileSync( + join(process.cwd(), ".github", "workflows", "publish.yml"), + "utf8", + ); + const jobsMarker = "\njobs:\n"; + const jobsIndex = workflow.indexOf(jobsMarker); + expect(jobsIndex).toBeGreaterThanOrEqual(0); + const header = workflow.slice(0, jobsIndex); + const jobs = workflow.slice(jobsIndex + jobsMarker.length); + const prepareStart = jobs.indexOf(" prepare:"); + const publishStart = jobs.indexOf("\n publish:"); + expect(header).not.toContain("id-token: write"); + expect(prepareStart).toBeGreaterThanOrEqual(0); + expect(publishStart).toBeGreaterThan(prepareStart); + const prepare = jobs.slice(prepareStart, publishStart); + const publish = jobs.slice(publishStart); + expect(prepare).not.toContain("id-token: write"); + expect(prepare).toContain("npm install --global npm@11.18.0"); + expect(prepare).toContain("pnpm run release:pack"); + expect(publish).toContain("id-token: write"); + expect(publish).not.toContain("npm ci"); + expect(publish).toContain("npm install --global npm@11.18.0"); + expect(publish).not.toContain("pnpm install"); + expect(publish).not.toContain("corepack"); + expect(publish).not.toContain("pnpm run"); + expect(publish).not.toContain("pnpm/action-setup"); + expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(workflow).not.toContain("workflow_dispatch"); + expect(workflow).toContain("retention-days: 30"); + }); +}); + +describe("retry-safe publication", () => { + const integrity = "sha512-cHJlcGFyZWQtdGFyYmFsbA=="; + + it("publishes an absent version", () => { + expect(decidePublication(integrity, null)).toBe("publish"); + }); + + it("skips a byte-identical existing version", () => { + expect(decidePublication(integrity, integrity)).toBe("skip"); + }); + + it("rejects an existing version with different bytes", () => { + expect(() => decidePublication(integrity, "sha512-ZGlmZmVyZW50")).toThrow( + "different tarball integrity", + ); + }); +}); diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..012a496 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "composite": true, + "declaration": true, + "declarationMap": true, + "exactOptionalPropertyTypes": true, + "forceConsistentCasingInFileNames": true, + "module": "NodeNext", + "moduleResolution": "NodeNext", + "noEmitOnError": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "target": "ES2022", + "verbatimModuleSyntax": true + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..ea19186 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./packages/cache-core" }, + { "path": "./packages/cache-conformance" } + ] +} diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 0000000..6f0b9d8 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,16 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "composite": false, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + "noEmit": true, + "types": ["node"] + }, + "include": [ + "packages/*/src/**/*.test.ts", + "tests/**/*.test.ts", + "vitest.config.ts" + ] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..a191fca --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["packages/**/*.test.ts", "tests/**/*.test.ts"], + exclude: ["**/dist/**", "**/node_modules/**"], + }, +}); From c0180416aee4e7c367d58fae889f1ecfa6fe1dda Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 16:29:15 +0000 Subject: [PATCH 2/3] Isolate fallback outcomes and snapshot tag arrays. Single-flight now coalesces get and compute separately so mixed fail-open/fail-closed callers keep their own policy. Memory-store set copies tags before indexing so later array mutation cannot desync invalidateTags. Co-authored-by: Fly Over Coder --- packages/cache-core/src/index.test.ts | 99 +++++++++++++++++++++++++++ packages/cache-core/src/index.ts | 96 ++++++++++++++------------ 2 files changed, 152 insertions(+), 43 deletions(-) diff --git a/packages/cache-core/src/index.test.ts b/packages/cache-core/src/index.test.ts index a521362..ce01b2b 100644 --- a/packages/cache-core/src/index.test.ts +++ b/packages/cache-core/src/index.test.ts @@ -6,6 +6,7 @@ import { createControllableClock, createMemoryCacheStore, createSingleFlight, + createUnavailableCacheStore, formatCacheKey, jsonCodec, shouldExpireEarly, @@ -157,4 +158,102 @@ describe("createMemoryCacheStore", () => { expect(computes).toBe(2); expect(second).toMatchObject({ status: "hit", value: "v2" }); }); + + it("does not let a later tag-array mutation poison the index", async () => { + const clock = createControllableClock(START); + const store = createMemoryCacheStore({ clock }); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "row" }; + const tags = ["group"]; + await store.set(address, "v1", codec, { tags }); + tags[0] = "mutated"; + await store.delete(address); + await store.set(address, "v2", codec); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + expect(await store.get(address, codec)).toMatchObject({ + status: "hit", + value: "v2", + }); + }); +}); + +describe("runGetOrCompute fallback isolation", () => { + it("does not give a fail-closed caller a fail-open compute", async () => { + const clock = createControllableClock(START); + const store = createUnavailableCacheStore({ clock }); + const codec = jsonCodec(); + const address = { namespace: "down", key: "shared" }; + let computes = 0; + let entered = (): void => {}; + const started = new Promise((resolve) => { + entered = resolve; + }); + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + + const open = store.getOrCompute(address, { + codec, + fallback: "fail-open", + compute: async () => { + computes += 1; + entered(); + await gate; + return "from-origin"; + }, + }); + await started; + const closed = store.getOrCompute(address, { + codec, + fallback: "fail-closed", + compute: () => { + computes += 1; + return "should-not-run"; + }, + }); + const closedResult = await closed; + expect(closedResult.status).toBe("error"); + expect(computes).toBe(1); + release(); + await expect(open).resolves.toMatchObject({ + status: "hit", + value: "from-origin", + }); + expect(computes).toBe(1); + }); + + it("does not let a fail-closed flight block fail-open compute", async () => { + const clock = createControllableClock(START); + const store = createUnavailableCacheStore({ clock }); + const codec = jsonCodec(); + const address = { namespace: "down", key: "shared" }; + let computes = 0; + + const [closed, open] = await Promise.all([ + store.getOrCompute(address, { + codec, + fallback: "fail-closed", + compute: () => { + computes += 1; + return "should-not-run"; + }, + }), + store.getOrCompute(address, { + codec, + fallback: "fail-open", + compute: () => { + computes += 1; + return "from-origin"; + }, + }), + ]); + + expect(closed.status).toBe("error"); + expect(open).toMatchObject({ status: "hit", value: "from-origin" }); + expect(computes).toBe(1); + }); }); diff --git a/packages/cache-core/src/index.ts b/packages/cache-core/src/index.ts index e44b55a..66f63c6 100644 --- a/packages/cache-core/src/index.ts +++ b/packages/cache-core/src/index.ts @@ -250,6 +250,8 @@ export interface RunGetOrComputeOptions extends CacheGetOrComputeOptions { /** * Cache-aside helper adapters should call. Single-flight is process-local. * Fail-open computes when `get` errors; fail-closed returns that error. + * Get and compute are coalesced separately so mixed fallbacks keep their + * own outcomes while still sharing backend and origin work. */ export async function runGetOrCompute( options: RunGetOrComputeOptions, @@ -257,57 +259,65 @@ export async function runGetOrCompute( const formatted = formatCacheKey(options.key); const fallback = options.fallback ?? "fail-closed"; const random = options.random ?? Math.random; - return options.singleFlight.do(formatted, async () => { - let read: CacheResult; - try { - read = await options.backend.get(options.key, options.codec); - } catch (error) { - read = { status: "error", error }; - } + const getFlight = `${formatted}#get`; + const computeFlight = `${formatted}#compute`; + + let read: CacheResult; + try { + read = await options.singleFlight.do(getFlight, async () => { + try { + return await options.backend.get(options.key, options.codec); + } catch (error) { + return { status: "error", error }; + } + }); + } catch (error) { + read = { status: "error", error }; + } - if (read.status === "hit") { - const expiresAt = read.expiresAt; - const lastComputeMs = read.lastComputeMs; + if (read.status === "hit") { + const expiresAt = read.expiresAt; + const lastComputeMs = read.lastComputeMs; + if ( + options.earlyExpiration !== undefined && + expiresAt !== undefined && + lastComputeMs !== undefined + ) { + const beta = options.earlyExpiration.beta ?? 1; if ( - options.earlyExpiration !== undefined && - expiresAt !== undefined && - lastComputeMs !== undefined + shouldExpireEarly({ + nowMs: clockMs(options.clock), + expiresAtMs: Date.parse(expiresAt), + lastComputeMs, + beta, + random, + }) ) { - const beta = options.earlyExpiration.beta ?? 1; - if ( - shouldExpireEarly({ - nowMs: clockMs(options.clock), - expiresAtMs: Date.parse(expiresAt), - lastComputeMs, - beta, - random, - }) - ) { - const recomputed = await computeAndStore( - options, - clockMs(options.clock), - ); - if (recomputed.status === "hit") { - return recomputed; - } - return read; + const recomputed = await options.singleFlight.do(computeFlight, () => + computeAndStore(options, clockMs(options.clock)), + ); + if (recomputed.status === "hit") { + return recomputed; } + return read; } - logOutcome(options.logger, "hit", options.key.namespace); - return read; } + logOutcome(options.logger, "hit", options.key.namespace); + return read; + } - if (read.status === "error") { - logOutcome(options.logger, "error", options.key.namespace); - if (fallback === "fail-closed") { - return read; - } - } else { - logOutcome(options.logger, "miss", options.key.namespace); + if (read.status === "error") { + logOutcome(options.logger, "error", options.key.namespace); + if (fallback === "fail-closed") { + return read; } + } else { + logOutcome(options.logger, "miss", options.key.namespace); + } - return computeAndStore(options, clockMs(options.clock)); - }); + return options.singleFlight.do(computeFlight, () => + computeAndStore(options, clockMs(options.clock)), + ); } async function computeAndStore( @@ -449,7 +459,7 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { if (previous !== undefined) { forgetTags(formatted, previous.tags); } - const tags = setOptions?.tags ?? []; + const tags = [...(setOptions?.tags ?? [])]; const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); entries.set(formatted, { bytes: codec.encode(value).slice(), From 2a58d85071e88388cc13591d7fd52b52062895b8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 16:32:34 +0000 Subject: [PATCH 3/3] Encode before reindexing and treat expired delete as a miss. Memory-store set now encodes first so a thrown codec leaves the previous entry and tag index intact. Delete purges expired rows and reports them as not live, matching get. Co-authored-by: Fly Over Coder --- packages/cache-core/src/index.test.ts | 49 +++++++++++++++++++++++++++ packages/cache-core/src/index.ts | 29 +++++++++------- 2 files changed, 66 insertions(+), 12 deletions(-) diff --git a/packages/cache-core/src/index.test.ts b/packages/cache-core/src/index.test.ts index ce01b2b..8b03b81 100644 --- a/packages/cache-core/src/index.test.ts +++ b/packages/cache-core/src/index.test.ts @@ -178,6 +178,55 @@ describe("createMemoryCacheStore", () => { value: "v2", }); }); + + it("keeps the previous entry indexed when encode throws", async () => { + const clock = createControllableClock(START); + const store = createMemoryCacheStore({ clock }); + const codec = jsonCodec(); + const address = { namespace: "tags", key: "row" }; + await store.set(address, "v1", codec, { tags: ["group"] }); + const exploding: typeof codec = { + encode() { + throw new Error("cannot encode"); + }, + decode() { + throw new Error("unused"); + }, + }; + await expect( + store.set(address, "v2", exploding, { tags: ["other"] }), + ).rejects.toThrow("cannot encode"); + expect(await store.get(address, codec)).toMatchObject({ + status: "hit", + value: "v1", + }); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 1, + }); + expect(await store.get(address, codec)).toEqual({ status: "miss" }); + }); + + it("treats delete of an expired entry as a miss and purges it", async () => { + const clock = createControllableClock(START); + const store = createMemoryCacheStore({ clock }); + const codec = jsonCodec(); + const address = { namespace: "ttl", key: "stale" }; + await store.set(address, "old", codec, { + ttl: { absoluteMs: 1_000 }, + tags: ["group"], + }); + clock.advance(1_000); + expect(await store.delete(address)).toEqual({ + status: "hit", + value: false, + }); + expect(await store.get(address, codec)).toEqual({ status: "miss" }); + expect(await store.invalidateTags(["group"])).toEqual({ + status: "hit", + value: 0, + }); + }); }); describe("runGetOrCompute fallback isolation", () => { diff --git a/packages/cache-core/src/index.ts b/packages/cache-core/src/index.ts index 66f63c6..feabeb7 100644 --- a/packages/cache-core/src/index.ts +++ b/packages/cache-core/src/index.ts @@ -413,18 +413,23 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { } } + function isExpired(entry: MemoryEntry, nowMs: number): boolean { + return entry.expiresAtMs !== null && nowMs >= entry.expiresAtMs; + } + + function purge(formatted: string, entry: MemoryEntry): void { + forgetTags(formatted, entry.tags); + entries.delete(formatted); + } + const store: CacheStore = { async get(key, codec) { const formatted = formatCacheKey(key); const entry = entries.get(formatted); const nowMs = clockMs(clock); - if ( - entry === undefined || - (entry.expiresAtMs !== null && nowMs >= entry.expiresAtMs) - ) { + if (entry === undefined || isExpired(entry, nowMs)) { if (entry !== undefined) { - forgetTags(formatted, entry.tags); - entries.delete(formatted); + purge(formatted, entry); } logOutcome(logger, "miss", key.namespace); return { status: "miss" }; @@ -445,8 +450,7 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { logOutcome(logger, "hit", key.namespace); return hit; } catch (error) { - forgetTags(formatted, entry.tags); - entries.delete(formatted); + purge(formatted, entry); logOutcome(logger, "error", key.namespace); return { status: "error", error }; } @@ -455,6 +459,7 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { async set(key, value, codec, setOptions) { const formatted = formatCacheKey(key); const nowMs = clockMs(clock); + const bytes = codec.encode(value).slice(); const previous = entries.get(formatted); if (previous !== undefined) { forgetTags(formatted, previous.tags); @@ -462,7 +467,7 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { const tags = [...(setOptions?.tags ?? [])]; const deadlines = ttlDeadlines(nowMs, setOptions?.ttl); entries.set(formatted, { - bytes: codec.encode(value).slice(), + bytes, tags, lastComputeMs: setOptions?.lastComputeMs ?? 0, ...deadlines, @@ -477,9 +482,9 @@ export function createMemoryCacheStore(options: CacheDependencies): CacheStore { if (entry === undefined) { return { status: "hit", value: false }; } - forgetTags(formatted, entry.tags); - entries.delete(formatted); - return { status: "hit", value: true }; + const expired = isExpired(entry, clockMs(clock)); + purge(formatted, entry); + return { status: "hit", value: !expired }; }, async getOrCompute(