CodeSampleX

Пример

@rollup/plugin-commonjs 28.0.9: demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs

Проверенный пример — npm @rollup/plugin-commonjs 28.0.9: demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs. Контракт выполнен на node 22 · linux…

sha256:dcb0198dd0c255dda02dde4e2d0b3288ce4b86030d5718036e6f602304423dae

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-03

Кейс

HOW
Цель
demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs
Пакеты
Символы
  • ignoreGlobal
Окружение
node 22.23.2
Создан
2026-09-03T13:43:15Z

Контракт

  1. External references to global in CommonJS modules are rewritten into a cross-environment commonjsGlobal preamble helper by default (ignoreGlobal: false).
  2. The default commonjsGlobal preamble safely resolves to globalThis or fallback object, allowing property assignments in isolated contexts without a native global identifier.
  3. Setting ignoreGlobal: true disables global rewriting, preserving literal global references in the bundle and omitting the commonjsGlobal preamble helper.
  4. Evaluating bundle output with ignoreGlobal: true throws ReferenceError when executed in an isolated runtime context lacking a global identifier, whereas default ignoreGlobal: false succeeds.

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Notes: @rollup/plugin-commonjs ignoreGlobal Behavior

## Search Result
`search_known_solution` returned `NO_SAFE_MATCH` for `ignoreGlobal` under `pkg:npm/%40rollup/plugin-commonjs@28.0.9`. Existing samples covered `strictRequires`, `esmExternals`, `defaultIsModuleExports`, `ignoreTryCatch`, `ignoreDynamicRequires`, and `transformMixedEsModules`, but none covered the `ignoreGlobal` option.

## Naive Model Assumption
Developers and LLM code generators often assume that `@rollup/plugin-commonjs` leaves global variable references like Node's `global` untouched during CommonJS transformation, or conversely assume that `global` will always be provided at runtime by the environment.

## Failure Mode
By default (`ignoreGlobal: false`), `@rollup/plugin-commonjs` scans CommonJS modules for free `global` identifiers and rewrites them to a cross-environment `commonjsGlobal` helper that safely falls back across `globalThis`, `window`, `global`, `self`, or `{}`.
When `ignoreGlobal: true` is configured, this rewriting is completely skipped, preserving the literal identifier `global`. When the resulting bundle executes in strict environments or isolated sandboxes without a global identifier named `global`, code accessing `global` immediately throws `ReferenceError: global is not defined`.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40rollup/plugin-commonjs@28.0.9
Demonstrate these symbols/APIs:
  - ignoreGlobal

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:46d3d024d325aaa7cdaaa8929548eb630790dde96d481685c837e2e7ff9d1321","contract":["External references to global in CommonJS modules are rewritten into a cross-environment commonjsGlobal preamble helper by default (ignoreGlobal: false).","The default commonjsGlobal preamble safely resolves to globalThis or fallback object, allowing property assignments in isolated contexts without a native global identifier.","Setting ignoreGlobal: true disables global rewriting, preserving literal global references in the bundle and omitting the commonjsGlobal preamble helper.","Evaluating bundle output with ignoreGlobal: true throws ReferenceError when executed in an isolated runtime context lacking a global identifier, whereas default ignoreGlobal: false succeeds."],"goal":"demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs","kind":"HOW","packages":["pkg:npm/%40rollup/plugin-commonjs@28.0.9"],"schemaVersion":1,"symbols":["ignoreGlobal"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40rollup/plugin-commonjs@28.0.9"],"schemaVersion":1,"subject":"pkg:npm/%40rollup/plugin-commonjs@28.0.9","symbols":["ignoreGlobal"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-rollup-plugin-commonjs-ignore-global",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-rollup-plugin-commonjs-ignore-global",
      "version": "1.0.0",
      "dependencies": {
        "@rollup/plugin-commonjs": "28.0.9",
        "rollup": "4.34.8"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.6.0",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
      "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
      "license": "MIT"
    },
    "node_modules/@rollup/plugin-commonjs": {
      "version": "28.0.9",
      "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-28.0.9.tgz",
      "integrity": "sha512-PIR4/OHZ79romx0BVVll/PkwWpJ7e5lsqFa3gFfcrFPWwLXLV39JVUzQV9RKjWerE7B845Hqjj9VYlQeieZ2dA==",
      "license": "MIT",
      "dependencies": {
        "@rollup/pluginutils": "^5.0.1",
        "commondir": "^1.0.1",
        "estree-walker": "^2.0.2",
        "fdir": "^6.2.0",
        "is-reference": "1.2.1",
        "magic-string": "^0.30.3",
        "picomatch": "^4.0.2"
      },
      "engines": {
        "node": ">=16.0.0 || 14 >= 14.17"
      },
      "peerDependencies": {
        "rollup": "^2.68.0||^3.0.0||^4.0.0"
      },
      "peerDependenciesMeta": {
        "rollup": {
          "optional": true
        }
      }
    },
    "node_modules/@rollup/pluginutils": {
      "version": "5.4.0",
      "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz",
      "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "^1.0.0",
        "estree-walker": "^2.0.2",
        "picomatch": "^4.0.2"
      },
      "engines": {
        "node": ">=14.0.0"
      },
      "peerDependencies": {
        "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
      },
      "peerDependenciesMeta": {
        "rollup": {
          "optional": true
        }
      }
    },
    "node_modules/@rollup/rollup-android-arm-eabi": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.34.8.tgz",
      "integrity": "sha512-q217OSE8DTp8AFHuNHXo0Y86e1wtlfVrXiAlwkIvGRQv9zbc6mE3sjIVfwI8sYUyNxwOg0j/Vm1RKM04JcWLJw==",
      "cpu": [
        "arm"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "android"
      ]
    },
    "node_modules/@rollup/rollup-android-arm64": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.34.8.tgz",
      "integrity": "sha512-Gigjz7mNWaOL9wCggvoK3jEIUUbGul656opstjaUSGC3eT0BM7PofdAJaBfPFWWkXNVAXbaQtC99OCg4sJv70Q==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "android"
      ]
    },
    "node_modules/@rollup/rollup-darwin-arm64": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.34.8.tgz",
      "integrity": "sha512-02rVdZ5tgdUNRxIUrFdcMBZQoaPMrxtwSb+/hOfBdqkatYHR3lZ2A2EGyHq2sGOd0Owk80oV3snlDASC24He3Q==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ]
    },
    "node_modules/@rollup/rollup-darwin-x64": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.34.8.tgz",
      "integrity": "sha512-qIP/elwR/tq/dYRx3lgwK31jkZvMiD6qUtOycLhTzCvrjbZ3LjQnEM9rNhSGpbLXVJYQ3rq39A6Re0h9tU2ynw==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ]
    },
    "node_modules/@rollup/rollup-freebsd-arm64": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.34.8.tgz",
      "integrity": "sha512-IQNVXL9iY6NniYbTaOKdrlVP3XIqazBgJOVkddzJlqnCpRi/yAeSOa8PLcECFSQochzqApIOE1GHNu3pCz+BDA==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "freebsd"
      ]
    },
    "node_modules/@rollup/rollup-freebsd-x64": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.34.8.tgz",
      "integrity": "sha512-TYXcHghgnCqYFiE3FT5QwXtOZqDj5GmaFNTNt3jNC+vh22dc/ukG2cG+pi75QO4kACohZzidsq7yKTKwq/Jq7Q==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "freebsd"
      ]
    },
    "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.34.8.tgz",
      "integrity": "sha512-A4iphFGNkWRd+5m3VIGuqHnG3MVnqKe7Al57u9mwgbyZ2/xF9Jio72MaY7xxh+Y87VAHmGQr73qoKL9HPbXj1g==",
      "cpu": [
        "arm"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-arm-musleabihf": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.34.8.tgz",
      "integrity": "sha512-S0lqKLfTm5u+QTxlFiAnb2J/2dgQqRy/XvziPtDd1rKZFXHTyYLoVL58M/XFwDI01AQCDIevGLbQrMAtdyanpA==",
      "cpu": [
        "arm"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-arm64-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.34.8.tgz",
      "integrity": "sha512-jpz9YOuPiSkL4G4pqKrus0pn9aYwpImGkosRKwNi+sJSkz+WU3anZe6hi73StLOQdfXYXC7hUfsQlTnjMd3s1A==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-arm64-musl": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.34.8.tgz",
      "integrity": "sha512-KdSfaROOUJXgTVxJNAZ3KwkRc5nggDk+06P6lgi1HLv1hskgvxHUKZ4xtwHkVYJ1Rep4GNo+uEfycCRRxht7+Q==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-loongarch64-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.34.8.tgz",
      "integrity": "sha512-NyF4gcxwkMFRjgXBM6g2lkT58OWztZvw5KkV2K0qqSnUEqCVcqdh2jN4gQrTn/YUpAcNKyFHfoOZEer9nwo6uQ==",
      "cpu": [
        "loong64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-powerpc64le-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.34.8.tgz",
      "integrity": "sha512-LMJc999GkhGvktHU85zNTDImZVUCJ1z/MbAJTnviiWmmjyckP5aQsHtcujMjpNdMZPT2rQEDBlJfubhs3jsMfw==",
      "cpu": [
        "ppc64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-riscv64-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.34.8.tgz",
      "integrity": "sha512-xAQCAHPj8nJq1PI3z8CIZzXuXCstquz7cIOL73HHdXiRcKk8Ywwqtx2wrIy23EcTn4aZ2fLJNBB8d0tQENPCmw==",
      "cpu": [
        "riscv64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-s390x-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.34.8.tgz",
      "integrity": "sha512-DdePVk1NDEuc3fOe3dPPTb+rjMtuFw89gw6gVWxQFAuEqqSdDKnrwzZHrUYdac7A7dXl9Q2Vflxpme15gUWQFA==",
      "cpu": [
        "s390x"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-x64-gnu": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.34.8.tgz",
      "integrity": "sha512-8y7ED8gjxITUltTUEJLQdgpbPh1sUQ0kMTmufRF/Ns5tI9TNMNlhWtmPKKHCU0SilX+3MJkZ0zERYYGIVBYHIA==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-linux-x64-musl": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.34.8.tgz",
      "integrity": "sha512-SCXcP0ZpGFIe7Ge+McxY5zKxiEI5ra+GT3QRxL0pMMtxPfpyLAKleZODi1zdRHkz5/BhueUrYtYVgubqe9JBNQ==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ]
    },
    "node_modules/@rollup/rollup-win32-arm64-msvc": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.34.8.tgz",
      "integrity": "sha512-YHYsgzZgFJzTRbth4h7Or0m5O74Yda+hLin0irAIobkLQFRQd1qWmnoVfwmKm9TXIZVAD0nZ+GEb2ICicLyCnQ==",
      "cpu": [
        "arm64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ]
    },
    "node_modules/@rollup/rollup-win32-ia32-msvc": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.34.8.tgz",
      "integrity": "sha512-r3NRQrXkHr4uWy5TOjTpTYojR9XmF0j/RYgKCef+Ag46FWUTltm5ziticv8LdNsDMehjJ543x/+TJAek/xBA2w==",
      "cpu": [
        "ia32"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ]
    },
    "node_modules/@rollup/rollup-win32-x64-msvc": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.34.8.tgz",
      "integrity": "sha512-U0FaE5O1BCpZSeE6gBl3c5ObhePQSfk9vDRToMmTkbhCOgW4jqvtS5LGyQ76L1fH8sM0keRp4uDTsbjiUyjk0g==",
      "cpu": [
        "x64"
      ],
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ]
    },
    "node_modules/@types/estree": {
      "version": "1.0.9",
      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
      "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
      "license": "MIT"
    },
    "node_modules/commondir": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
      "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==",
      "license": "MIT"
    },
    "node_modules/estree-walker": {
      "version": "2.0.2",
      "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
      "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
      "license": "MIT"
    },
    "node_modules/fdir": {
      "version": "6.5.0",
      "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
      "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
      "license": "MIT",
      "engines": {
        "node": ">=12.0.0"
      },
      "peerDependencies": {
        "picomatch": "^3 || ^4"
      },
      "peerDependenciesMeta": {
        "picomatch": {
          "optional": true
        }
      }
    },
    "node_modules/fsevents": {
      "version": "2.3.3",
      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
      "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
      "hasInstallScript": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
      }
    },
    "node_modules/is-reference": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz",
      "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "*"
      }
    },
    "node_modules/magic-string": {
      "version": "0.30.21",
      "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
      "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
      "license": "MIT",
      "dependencies": {
        "@jridgewell/sourcemap-codec": "^1.5.5"
      }
    },
    "node_modules/picomatch": {
      "version": "4.0.7",
      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
      "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://github.com/sponsors/jonschlinkert"
      }
    },
    "node_modules/rollup": {
      "version": "4.34.8",
      "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.34.8.tgz",
      "integrity": "sha512-489gTVMzAYdiZHFVA/ig/iYFllCcWFHMvUHI1rpFmkoUtRlQxqh6/yiNqnYibjMZ2b/+FUQwldG+aLsEt6bglQ==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "1.0.6"
      },
      "bin": {
        "rollup": "dist/bin/rollup"
      },
      "engines": {
        "node": ">=18.0.0",
        "npm": ">=8.0.0"
      },
      "optionalDependencies": {
        "@rollup/rollup-android-arm-eabi": "4.34.8",
        "@rollup/rollup-android-arm64": "4.34.8",
        "@rollup/rollup-darwin-arm64": "4.34.8",
        "@rollup/rollup-darwin-x64": "4.34.8",
        "@rollup/rollup-freebsd-arm64": "4.34.8",
        "@rollup/rollup-freebsd-x64": "4.34.8",
        "@rollup/rollup-linux-arm-gnueabihf": "4.34.8",
        "@rollup/rollup-linux-arm-musleabihf": "4.34.8",
        "@rollup/rollup-linux-arm64-gnu": "4.34.8",
        "@rollup/rollup-linux-arm64-musl": "4.34.8",
        "@rollup/rollup-linux-loongarch64-gnu": "4.34.8",
        "@rollup/rollup-linux-powerpc64le-gnu": "4.34.8",
        "@rollup/rollup-linux-riscv64-gnu": "4.34.8",
        "@rollup/rollup-linux-s390x-gnu": "4.34.8",
        "@rollup/rollup-linux-x64-gnu": "4.34.8",
        "@rollup/rollup-linux-x64-musl": "4.34.8",
        "@rollup/rollup-win32-arm64-msvc": "4.34.8",
        "@rollup/rollup-win32-ia32-msvc": "4.34.8",
        "@rollup/rollup-win32-x64-msvc": "4.34.8",
        "fsevents": "~2.3.2"
      }
    },
    "node_modules/rollup/node_modules/@types/estree": {
      "version": "1.0.6",
      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz",
      "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-rollup-plugin-commonjs-ignore-global",
  "version": "1.0.0",
  "type": "module",
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@rollup/plugin-commonjs": "28.0.9",
    "rollup": "4.34.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "demonstrate ignoreGlobal behavior in @rollup/plugin-commonjs",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40rollup/plugin-commonjs@28.0.9"
  ],
  "symbols": [
    "ignoreGlobal"
  ]
}
src/index.js
import * as rollup from 'rollup';
import commonjs from '@rollup/plugin-commonjs';

/**
 * Bundles a CommonJS entry module using Rollup and @rollup/plugin-commonjs.
 *
 * @param {string} entryCode - The CommonJS entry source code.
 * @param {object} [pluginOptions] - Options passed to @rollup/plugin-commonjs.
 * @param {object} [outputOptions] - Rollup output options (defaults to format: 'cjs').
 * @returns {Promise<{ code: string }>} Generated bundle output code.
 */
export async function bundleCommonJs(entryCode, pluginOptions = {}, outputOptions = {}) {
  const bundle = await rollup.rollup({
    input: 'entry.cjs',
    plugins: [
      {
        name: 'virtual-fixtures',
        resolveId(id) {
          if (id === 'entry.cjs') {
            return id;
          }
          return null;
        },
        load(id) {
          if (id === 'entry.cjs') {
            return entryCode;
          }
          return null;
        }
      },
      commonjs(pluginOptions)
    ]
  });

  const { output } = await bundle.generate({
    format: 'cjs',
    ...outputOptions
  });

  return { code: output[0].code };
}
test/contract.mjs
import assert from 'node:assert/strict';
import vm from 'node:vm';
import { bundleCommonJs } from '../src/index.js';

async function runContract() {
  const globalSetterFixture = `
module.exports = {
  setAndGet(key, value) {
    global[key] = value;
    return global[key];
  }
};
`;

  // ---------------------------------------------------------------------------
  // Contract Assertion 1:
  // External references to global in CommonJS modules are rewritten into a
  // cross-environment commonjsGlobal preamble helper by default (ignoreGlobal: false).
  // ---------------------------------------------------------------------------
  {
    const defaultResult = await bundleCommonJs(globalSetterFixture);
    assert.match(
      defaultResult.code,
      /var\s+commonjsGlobal\s*=\s*typeof\s+globalThis/,
      'assert @rollup/plugin-commonjs by default rewrites free references to global to commonjsGlobal helper'
    );
    assert.match(
      defaultResult.code,
      /commonjsGlobal\[key\]\s*=\s*value/,
      'assert member access on global is rewritten to commonjsGlobal[key]'
    );

    // Explicit ignoreGlobal: false behaves identically to default
    const explicitFalseResult = await bundleCommonJs(globalSetterFixture, { ignoreGlobal: false });
    assert.match(
      explicitFalseResult.code,
      /var\s+commonjsGlobal\s*=\s*typeof\s+globalThis/,
      'assert explicit ignoreGlobal: false includes commonjsGlobal preamble'
    );
  }

  // ---------------------------------------------------------------------------
  // Contract Assertion 2:
  // The default commonjsGlobal preamble safely resolves to globalThis or fallback
  // object, allowing property assignments in isolated contexts without a native global identifier.
  // ---------------------------------------------------------------------------
  {
    const defaultResult = await bundleCommonJs(globalSetterFixture);
    const sandbox = { globalThis: {}, module: {}, exports: {} };
    const context = vm.createContext(sandbox);
    vm.runInContext(defaultResult.code, context);

    const mod = sandbox.module.exports;
    const value = mod.setAndGet('sampleKey', 'sampleVal');
    assert.equal(
      value,
      'sampleVal',
      'assert commonjsGlobal resolves and executes safely in isolated context without global'
    );
    assert.equal(
      sandbox.globalThis.sampleKey,
      'sampleVal',
      'assert property assigned through commonjsGlobal is stored on globalThis'
    );
  }

  // ---------------------------------------------------------------------------
  // Contract Assertion 3:
  // Setting ignoreGlobal: true disables global rewriting, preserving literal
  // global references in the bundle and omitting the commonjsGlobal preamble helper.
  // ---------------------------------------------------------------------------
  {
    const ignoreResult = await bundleCommonJs(globalSetterFixture, { ignoreGlobal: true });
    assert.doesNotMatch(
      ignoreResult.code,
      /commonjsGlobal/,
      'assert setting ignoreGlobal: true omits commonjsGlobal preamble helper'
    );
    assert.match(
      ignoreResult.code,
      /global\[key\]\s*=\s*value/,
      'assert setting ignoreGlobal: true preserves literal global references in bundle output'
    );
  }

  // ---------------------------------------------------------------------------
  // Contract Assertion 4:
  // Evaluating bundle output with ignoreGlobal: true throws ReferenceError when
  // executed in an isolated runtime context lacking a global identifier, whereas
  // default ignoreGlobal: false succeeds.
  // ---------------------------------------------------------------------------
  {
    const ignoreResult = await bundleCommonJs(globalSetterFixture, { ignoreGlobal: true });
    const sandbox = { globalThis: {}, module: {}, exports: {} };
    const context = vm.createContext(sandbox);
    vm.runInContext(ignoreResult.code, context);

    const mod = sandbox.module.exports;
    assert.throws(
      () => {
        mod.setAndGet('sampleKey', 'sampleVal');
      },
      {
        name: 'ReferenceError',
        message: /global is not defined/
      },
      'assert execution with ignoreGlobal: true throws ReferenceError in context without global'
    );
  }

  console.log('All contract assertions passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract failed:', err);
  process.exit(1);
});

Исходный сидер

аноним