CodeSampleX

Пример

core-js 3.42.0: Demonstrate that core-js/configurator overrides polyfill aggressiveness via usePolyfill, useNative, and useFeatureDetection, and that useNative still installs polyfills for undefined features.

Проверенный пример — npm core-js 3.42.0: Demonstrate that core-js/configurator overrides polyfill aggressiveness via usePolyfill, useNative, and…

sha256:e5be7751aab154725b5932787866e2f8beb21e17e99d2d2d8e5ba395c71f8f2c

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
3
Ключи подписи, собравшие его
3
Заявленная среда node linux x64 node node npm

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-08

Кейс

HOW
Цель
Demonstrate that core-js/configurator overrides polyfill aggressiveness via usePolyfill, useNative, and useFeatureDetection, and that useNative still installs polyfills for undefined features.
Пакеты
Символы
  • core-js/configurator
Окружение
node
Создан
2026-08-18T00:52:08Z

Контракт

  1. Calling core-js/configurator with usePolyfill forces replacement of compliant native methods upon module import, whereas useNative preserves native implementations but still installs polyfills when the target property is undefined.
  2. usePolyfill with Array.prototype.toReversed replaces the native implementation.
  3. Normalization accepts Array#findLast and array.findlastindex interchangeably.
  4. useNative with structuredClone preserves the native structuredClone implementation.
  5. useFeatureDetection resets earlier forced aggressiveness overrides back to feature detection.
  6. useNative with Iterator.range installs the polyfill when the native property is absent.
  7. Calling configurator after a module has already been imported does not retroactively replace already-evaluated methods.

Файлы

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

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

Исходный код

NOTES.md
# core-js configurator runtime behavior

## Search Results
Prior queries for `core-js` returned three existing samples:
- `sha256:4e81896c990fad1d791ae670b07599a0959713e40553090289cca7fb0943fe99`: Rejection of invalid `Iterator.range` arguments (`NaN`) with `RangeError`.
- `sha256:771727fb4ca310f83f1ec90c4a2f32315fedc9adae20af901d39e2e339f493f2`: Capturing built-in `URL.prototype.toString` during `URL.prototype.toJSON` installation.
- `sha256:94ecf6a51292da84f82ff7f1f2b8cb3ab6b763507c9dd919398f8a0f581b31dd`: Polyfilled `Object.groupBy` returning null-prototype objects.

None of those existing samples cover `core-js/configurator` or programmatic polyfill aggressiveness control.

## Pinned Release
- `core-js`: `3.42.0`
- Runtime: Node.js (ESM test runner importing CommonJS modules via `node:module.createRequire`)

## Observed Behavior
`core-js/configurator` allows configuring feature detection aggressiveness before polyfill modules are evaluated:

1. **`usePolyfill`**: Forces `core-js` to replace native implementations with polyfill implementations even when the host runtime environment provides a standard-compliant method (e.g. replacing `Array.prototype.toReversed`).
2. **Identifier Normalization**: Feature names are normalized by converting `#` and `.prototype.` into `.` and lowercasing. `Array.prototype.findLast`, `Array#findLast`, and `array.findlast` are all normalized to `array.findlast`.
3. **`useNative`**: Preserves existing native implementations when present, preventing `core-js` from forcing an overwrite (e.g. preserving Node's native `structuredClone`).
4. **`useNative` with Missing Features**: If the native target property is `undefined` in the host environment (e.g. `Iterator.range`), `useNative` does not prevent polyfill installation; `core-js` still installs the polyfill because no native implementation exists.
5. **`useFeatureDetection`**: Resets previously configured forced overrides back to default feature-detection logic.
6. **Execution Timing**: Polyfills are applied synchronously when each polyfill module is imported/required. Calling `configurator` after a module has already been imported produces no retroactive effect on already-evaluated prototypes.

## Traps and Failure Modes
- **Belief that `useNative` suppresses polyfills completely**: A developer expecting `useNative: ['Iterator.range']` to block `core-js` from polyfilling missing APIs will find that missing (`undefined`) methods are still polyfilled. Polyfills under `useNative` are skipped only when a native property is already present on the target object.
- **Silent failure from post-import configuration**: Calling `configurator` after importing polyfill bundles fails silently without throwing an error, but leaves the native methods untouched because polyfill installation occurs during initial module load.
csx.json
{"case":{"believed":"Configuring core-js with useNative prevents polyfills from being installed even when the target feature is completely missing from the environment.","caseId":"case:sha256:ec6ba31712ecd1a813f24f6b29d9759b85850ff6b093f51d2b4ef23434e4b4a6","contract":["Calling core-js/configurator with usePolyfill forces replacement of compliant native methods upon module import, whereas useNative preserves native implementations but still installs polyfills when the target property is undefined.","usePolyfill with Array.prototype.toReversed replaces the native implementation.","Normalization accepts Array#findLast and array.findlastindex interchangeably.","useNative with structuredClone preserves the native structuredClone implementation.","useFeatureDetection resets earlier forced aggressiveness overrides back to feature detection.","useNative with Iterator.range installs the polyfill when the native property is absent.","Calling configurator after a module has already been imported does not retroactively replace already-evaluated methods."],"goal":"Demonstrate that core-js/configurator overrides polyfill aggressiveness via usePolyfill, useNative, and useFeatureDetection, and that useNative still installs polyfills for undefined features.","kind":"HOW","packages":["pkg:npm/core-js@3.42.0"],"schemaVersion":1,"symbols":["core-js/configurator"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/core-js@3.42.0"],"schemaVersion":1,"symbols":["core-js/configurator"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-core-js-config",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-core-js-config",
      "version": "1.0.0",
      "dependencies": {
        "core-js": "3.42.0"
      }
    },
    "node_modules/core-js": {
      "version": "3.42.0",
      "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.42.0.tgz",
      "integrity": "sha512-Sz4PP4ZA+Rq4II21qkNqOEDTDrCvcANId3xpIgB34NDkWc3UduWj2dqEtN9yZIq8Dk3HyPI33x9sqqU5C8sr0g==",
      "hasInstallScript": true,
      "license": "MIT",
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/core-js"
      }
    }
  }
}
package.json
{
  "name": "npm-core-js-config",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "core-js": "3.42.0"
  }
}
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const configurator = require('core-js/configurator');

// 1. usePolyfill forces replacement of compliant native methods
const nativeToReversed = Array.prototype.toReversed;
configurator({ usePolyfill: ['Array.prototype.toReversed'] });
require('core-js/actual/array/to-reversed');
assert.notStrictEqual(
  Array.prototype.toReversed,
  nativeToReversed,
  'usePolyfill must force replacement of native Array.prototype.toReversed'
);

// 2. Normalization accepts prototype, hash, and lowercase specifiers interchangeably
const nativeFindLast = Array.prototype.findLast;
const nativeFindLastIndex = Array.prototype.findLastIndex;
configurator({
  usePolyfill: [
    'Array#findLast',
    'array.findlastindex',
  ],
});
require('core-js/actual/array/find-last');
require('core-js/actual/array/find-last-index');
assert.notStrictEqual(
  Array.prototype.findLast,
  nativeFindLast,
  'usePolyfill with hash notation must force replacement of Array.prototype.findLast'
);
assert.notStrictEqual(
  Array.prototype.findLastIndex,
  nativeFindLastIndex,
  'usePolyfill with normalized lowercase notation must force replacement of Array.prototype.findLastIndex'
);

// 3. useNative preserves native implementation when present (structuredClone is replaced by default in Node)
const nativeStructuredClone = globalThis.structuredClone;
configurator({ useNative: ['structuredClone'] });
require('core-js/actual/structured-clone');
assert.strictEqual(
  globalThis.structuredClone,
  nativeStructuredClone,
  'useNative must prevent core-js from replacing compliant native structuredClone'
);

// 4. useFeatureDetection resets previously configured overrides back to detection
const nativeIncludes = Array.prototype.includes;
configurator({ usePolyfill: ['Array.prototype.includes'] });
configurator({ useFeatureDetection: ['Array.prototype.includes'] });
require('core-js/actual/array/includes');
assert.strictEqual(
  Array.prototype.includes,
  nativeIncludes,
  'useFeatureDetection must reset forced override and preserve compliant native includes'
);

// 5. useNative still installs polyfill when native property is undefined
assert.strictEqual(
  typeof (globalThis.Iterator && globalThis.Iterator.range),
  'undefined',
  'Iterator.range must initially be undefined in this environment'
);
configurator({ useNative: ['Iterator.range'] });
require('core-js/modules/esnext.iterator.range');
assert.strictEqual(
  typeof Iterator.range,
  'function',
  'useNative must still install polyfill when native property is completely absent'
);

// 6. Configurator calls after module evaluation have no retroactive effect
const nativeFilter = Array.prototype.filter;
require('core-js/actual/array/filter');
assert.strictEqual(Array.prototype.filter, nativeFilter);
configurator({ usePolyfill: ['Array.prototype.filter'] });
assert.strictEqual(
  Array.prototype.filter,
  nativeFilter,
  'Calling configurator after module import must not retroactively replace already-evaluated methods'
);

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

csx-seed