CodeSampleX

示例

browserslist 4.28.8: Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with browserslist

已验证示例 — npm browserslist 4.28.8: Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with…

sha256:e798bc73a962540ec9f157a362f2aeef2714978ef9348da3dfef0b2a078ce2c6

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
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-08-24

案例

HOW
目标
Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with browserslist
包
符号
  • browserslist.findConfig
  • browserslist.loadConfig
  • browserslist.nodeVersions
  • browserslist.parseConfig
环境
node 22.23.2
创建时间
2026-08-24T20:19:22Z

契约

  1. browserslist.parseConfig(configString) parses multi-environment config text into section maps, stripping comments and empty lines
  2. browserslist.parseConfig('') on empty or comment-only string returns an object with an empty defaults array
  3. browserslist.findConfig(dir) discovers .browserslistrc files and returns structured section mappings
  4. browserslist.findConfig(dir) discovers package.json browserslist array configurations and wraps them under defaults
  5. browserslist.findConfig(dir) returns undefined when no configuration file exists in the directory tree
  6. browserslist.loadConfig({ path, env }) selects queries for the specified environment, defaulting to production
  7. browserslist.loadConfig({ path, env }) falls back to the defaults section when an unknown environment is requested
  8. browserslist(null, { path, env }) resolves target browsers directly from discovered configuration files
  9. browserslist.nodeVersions exposes an array of all known Node.js release versions used for node query resolution

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# browserslist Public API Behavior

## Prior Findings
A network search found samples focusing on custom stats queries (`opts.stats` with `in my stats`) and Babel cache retention (`browserslist.clearCaches`). This project investigates multi-environment configuration parsing (`browserslist.parseConfig`), configuration file discovery (`browserslist.findConfig`), environment loading (`browserslist.loadConfig`), and Node.js version matrix queries (`browserslist.nodeVersions`).

## Pinned Release
- `browserslist`: `4.28.8` (resolved via `npm`)
- Runtime: Node.js (tested on Node 22 ESM)

## Observed Behavior & Traps

### 1. Section-based Configuration Parsing (`parseConfig`)
- `browserslist.parseConfig(text)` parses multi-environment configuration strings into an object mapping environment names (`defaults`, `production`, `development`, etc.) to arrays of query strings.
- Leading queries before any `[section]` header are automatically placed under the `defaults` key.
- Comments (`# ...`) and empty lines are stripped.
- Parsing an empty string or comments-only string returns `{ defaults: [] }`.

### 2. Configuration Discovery (`findConfig`)
- `browserslist.findConfig(path)` searches upward for `.browserslistrc` or `package.json` with a `browserslist` property.
- When given `.browserslistrc`, it returns structured section mappings (`{ defaults: [...], ...sections }`).
- When given `package.json` with an array `browserslist`, it wraps queries under `{ defaults: [...] }`.
- When given `package.json` with an object `browserslist`, it returns section mappings directly.
- When no configuration file exists in the directory hierarchy, it returns `undefined`.

### 3. Environment Selection and Fallback (`loadConfig`)
- `browserslist.loadConfig({ path, env })` extracts the query array for the target environment.
- If `env` is omitted, it defaults to `production` (or `process.env.BROWSERSLIST_ENV` / `process.env.NODE_ENV`).
- If the requested `env` is not present in the configuration, it gracefully falls back to the `defaults` section.
- If no configuration file is found, it returns `undefined`.

### 4. Query Execution with Discovered Configuration
- Calling `browserslist(null, { path, env })` evaluates the queries discovered via config resolution against the Can I Use database.

### 5. Node.js Version Matrix (`nodeVersions`)
- `browserslist.nodeVersions` exposes an array of all known Node.js release version strings used for evaluating node queries (e.g. `node 18.0.0`).
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: Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with browserslist
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/browserslist@4.28.8
Demonstrate these symbols/APIs:
  - browserslist.findConfig
  - browserslist.loadConfig
  - browserslist.nodeVersions
  - browserslist.parseConfig
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:09e42fddd2cfe13065c052fe4fc483495ade2524fa8d0479ce2a9592b2de7259","constraints":{"executionContext":"node"},"contract":["browserslist.parseConfig(configString) parses multi-environment config text into section maps, stripping comments and empty lines","browserslist.parseConfig('') on empty or comment-only string returns an object with an empty defaults array","browserslist.findConfig(dir) discovers .browserslistrc files and returns structured section mappings","browserslist.findConfig(dir) discovers package.json browserslist array configurations and wraps them under defaults","browserslist.findConfig(dir) returns undefined when no configuration file exists in the directory tree","browserslist.loadConfig({ path, env }) selects queries for the specified environment, defaulting to production","browserslist.loadConfig({ path, env }) falls back to the defaults section when an unknown environment is requested","browserslist(null, { path, env }) resolves target browsers directly from discovered configuration files","browserslist.nodeVersions exposes an array of all known Node.js release versions used for node query resolution"],"goal":"Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with browserslist","kind":"HOW","packages":["pkg:npm/browserslist@4.28.8"],"schemaVersion":1,"symbols":["browserslist.findConfig","browserslist.loadConfig","browserslist.nodeVersions","browserslist.parseConfig"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/browserslist@4.28.8"],"schemaVersion":1,"subject":"pkg:npm/browserslist@4.28.8","symbols":["browserslist.findConfig","browserslist.loadConfig","browserslist.nodeVersions","browserslist.parseConfig"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "browserslist-config-and-node-versions",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "browserslist-config-and-node-versions",
      "version": "1.0.0",
      "dependencies": {
        "browserslist": "4.28.8"
      }
    },
    "node_modules/baseline-browser-mapping": {
      "version": "2.11.19",
      "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.19.tgz",
      "integrity": "sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw==",
      "license": "Apache-2.0",
      "bin": {
        "baseline-browser-mapping": "dist/cli.cjs"
      },
      "engines": {
        "node": ">=6.0.0"
      }
    },
    "node_modules/browserslist": {
      "version": "4.28.8",
      "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz",
      "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==",
      "funding": [
        {
          "type": "opencollective",
          "url": "https://opencollective.com/browserslist"
        },
        {
          "type": "tidelift",
          "url": "https://tidelift.com/funding/github/npm/browserslist"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "baseline-browser-mapping": "^2.11.12",
        "caniuse-lite": "^1.0.30001809",
        "electron-to-chromium": "^1.5.402",
        "node-releases": "^2.0.53",
        "update-browserslist-db": "^1.3.0"
      },
      "bin": {
        "browserslist": "cli.js"
      },
      "engines": {
        "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
      }
    },
    "node_modules/caniuse-lite": {
      "version": "1.0.30001810",
      "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz",
      "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==",
      "funding": [
        {
          "type": "opencollective",
          "url": "https://opencollective.com/browserslist"
        },
        {
          "type": "tidelift",
          "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "CC-BY-4.0"
    },
    "node_modules/electron-to-chromium": {
      "version": "1.5.413",
      "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.413.tgz",
      "integrity": "sha512-F1XPKvt7HVfly5WND90ec16nFsdr4g5x/cVUP3EqjeyXynupabGDqpMa84wwvuYGDnldXLBz6DLXyZXWO9TPvw==",
      "license": "ISC"
    },
    "node_modules/escalade": {
      "version": "3.2.0",
      "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
      "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/node-releases": {
      "version": "2.0.53",
      "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.53.tgz",
      "integrity": "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==",
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    },
    "node_modules/update-browserslist-db": {
      "version": "1.3.1",
      "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.1.tgz",
      "integrity": "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==",
      "funding": [
        {
          "type": "opencollective",
          "url": "https://opencollective.com/browserslist"
        },
        {
          "type": "tidelift",
          "url": "https://tidelift.com/funding/github/npm/browserslist"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "escalade": "^3.2.0",
        "picocolors": "^1.1.1"
      },
      "bin": {
        "update-browserslist-db": "cli.js"
      },
      "peerDependencies": {
        "browserslist": ">= 4.21.0"
      }
    }
  }
}
package.json
{
  "name": "browserslist-config-and-node-versions",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "browserslist": "4.28.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse multi-environment configuration sections, load environment configurations, and query Node.js versions with browserslist",
  "kind": "HOW",
  "packages": [
    "pkg:npm/browserslist@4.28.8"
  ],
  "symbols": [
    "browserslist.findConfig",
    "browserslist.loadConfig",
    "browserslist.nodeVersions",
    "browserslist.parseConfig"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import browserslist from 'browserslist';

// 1. browserslist.parseConfig(configString) parses multi-environment config text into section maps, stripping comments and empty lines
const multiEnvConfig = `
# Default query section
> 1%
last 2 versions

[production]
> 0.2%
not dead

[development]
last 1 chrome version
`;
const parsed = browserslist.parseConfig(multiEnvConfig);
assert.deepStrictEqual(parsed, {
  defaults: ['> 1%', 'last 2 versions'],
  production: ['> 0.2%', 'not dead'],
  development: ['last 1 chrome version']
});

// 2. browserslist.parseConfig('') on empty or comment-only string returns an object with an empty defaults array
assert.deepStrictEqual(browserslist.parseConfig(''), { defaults: [] });
assert.deepStrictEqual(browserslist.parseConfig('# Just a comment line\n\n'), { defaults: [] });

// Create isolated temporary directories for configuration discovery tests
const tempBase = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-browserslist-test-'));
try {
  const rcDir = path.join(tempBase, 'rc-project');
  fs.mkdirSync(rcDir, { recursive: true });
  fs.writeFileSync(
    path.join(rcDir, '.browserslistrc'),
    '[production]\nchrome >= 100\n\n[development]\nlast 1 chrome version\n'
  );

  const pkgArrayDir = path.join(tempBase, 'pkg-array-project');
  fs.mkdirSync(pkgArrayDir, { recursive: true });
  fs.writeFileSync(
    path.join(pkgArrayDir, 'package.json'),
    JSON.stringify({ browserslist: ['> 1%', 'not dead'] })
  );

  const pkgObjDir = path.join(tempBase, 'pkg-obj-project');
  fs.mkdirSync(pkgObjDir, { recursive: true });
  fs.writeFileSync(
    path.join(pkgObjDir, 'package.json'),
    JSON.stringify({
      browserslist: {
        production: ['> 0.5%'],
        development: ['last 1 chrome version']
      }
    })
  );

  const emptyDir = path.join(tempBase, 'empty-project');
  fs.mkdirSync(emptyDir, { recursive: true });

  // 3. browserslist.findConfig(dir) discovers .browserslistrc files and returns structured section mappings
  const foundRc = browserslist.findConfig(rcDir);
  assert.deepStrictEqual(foundRc, {
    defaults: [],
    production: ['chrome >= 100'],
    development: ['last 1 chrome version']
  });

  // 4. browserslist.findConfig(dir) discovers package.json browserslist array configurations and wraps them under defaults
  const foundPkgArray = browserslist.findConfig(pkgArrayDir);
  assert.deepStrictEqual(foundPkgArray, {
    defaults: ['> 1%', 'not dead']
  });

  // 5. browserslist.findConfig(dir) returns undefined when no configuration file exists in the directory tree
  const foundNone = browserslist.findConfig(emptyDir);
  assert.strictEqual(foundNone, undefined);

  // 6. browserslist.loadConfig({ path, env }) selects queries for the specified environment, defaulting to production
  const loadedDefault = browserslist.loadConfig({ path: rcDir });
  assert.deepStrictEqual(loadedDefault, ['chrome >= 100']);

  const loadedDev = browserslist.loadConfig({ path: rcDir, env: 'development' });
  assert.deepStrictEqual(loadedDev, ['last 1 chrome version']);

  // 7. browserslist.loadConfig({ path, env }) falls back to the defaults section when an unknown environment is requested
  const fallbackRcDir = path.join(tempBase, 'fallback-rc-project');
  fs.mkdirSync(fallbackRcDir, { recursive: true });
  fs.writeFileSync(
    path.join(fallbackRcDir, '.browserslistrc'),
    'last 2 versions\n\n[modern]\nchrome >= 110\n'
  );
  const loadedUnknown = browserslist.loadConfig({ path: fallbackRcDir, env: 'staging' });
  assert.deepStrictEqual(loadedUnknown, ['last 2 versions']);

  // 8. browserslist(null, { path, env }) resolves target browsers directly from discovered configuration files
  const targets = browserslist(null, { path: pkgObjDir, env: 'development' });
  assert.ok(Array.isArray(targets) && targets.length > 0);
  assert.ok(targets.some(t => t.startsWith('chrome ')));

  // 9. browserslist.nodeVersions exposes an array of all known Node.js release versions used for node query resolution
  assert.ok(Array.isArray(browserslist.nodeVersions));
  assert.ok(browserslist.nodeVersions.includes('18.0.0'));
  assert.ok(browserslist.nodeVersions.includes('20.0.0'));
  const nodeTargets = browserslist('node 18.0.0');
  assert.deepStrictEqual(nodeTargets, ['node 18.0.0']);

  console.log('Contract passed successfully.');
} finally {
  fs.rmSync(tempBase, { recursive: true, force: true });
}

原始种子者

匿名