Exemple
@eslint/core 0.17.0: implement TextSourceCode for custom AST traversal with getLoc and getRange
Échantillon vérifié pour npm @eslint/core 0.17.0: implement TextSourceCode for custom AST traversal with getLoc and getRange. Le contrat s'est exécuté sur…
sha256:1e63bf81376698031072152eed04a0c53c8dbc064b14c0123ca8e1c475cb5670
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 1
- Clés de signature qui l’ont compilé
- 1
Environnement déclaré
linux 24 · ubuntu · glibc 2.39 x64 npm
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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-28 |
Cas
HOW- Objectif
- implement TextSourceCode for custom AST traversal with getLoc and getRange
- Paquets
- Symboles
-
- @eslint/core.SourceCodeBase
- @eslint/core.TextSourceCode
- Créé
- 2026-08-28T05:46:50Z
Contrat
- exports ESM and CJS type declarations for TextSourceCode and SourceCodeBase interfaces
- implements TextSourceCode and SourceCodeBase interface properties: text, ast, visitorKeys, getLoc, getRange, and traverse
- computes source location with 1-indexed line and 0-indexed column from character offsets via getLoc
- derives start and end character offset tuples via getRange from node locations
- traverse generator yields VisitTraversalStep items with enter (phase 1) and exit (phase 2) order
- supports language options lifecycle, disable directives, and finalization on TextSourceCode instance
Fichiers
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/source-code.mjs
- test/contract.mjs
Code source
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: implement TextSourceCode for custom AST traversal with getLoc and getRange
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/%40eslint/core@0.17.0
Demonstrate these symbols/APIs:
- @eslint/core.SourceCodeBase
- @eslint/core.TextSourceCode
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.
{"case":{"caseId":"case:sha256:48e2c922a9520c1392c7bcfc2a08e1660cbd5cfd7458256d6a495f27abf037e7","contract":["exports ESM and CJS type declarations for TextSourceCode and SourceCodeBase interfaces","implements TextSourceCode and SourceCodeBase interface properties: text, ast, visitorKeys, getLoc, getRange, and traverse","computes source location with 1-indexed line and 0-indexed column from character offsets via getLoc","derives start and end character offset tuples via getRange from node locations","traverse generator yields VisitTraversalStep items with enter (phase 1) and exit (phase 2) order","supports language options lifecycle, disable directives, and finalization on TextSourceCode instance"],"goal":"implement TextSourceCode for custom AST traversal with getLoc and getRange","kind":"HOW","packages":["pkg:npm/%40eslint/core@0.17.0"],"schemaVersion":1,"symbols":["@eslint/core.SourceCodeBase","@eslint/core.TextSourceCode"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40eslint/core@0.17.0"],"schemaVersion":1,"subject":"pkg:npm/%40eslint/core@0.17.0","symbols":["@eslint/core.SourceCodeBase","@eslint/core.TextSourceCode"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-eslint-core-text-source-code",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-eslint-core-text-source-code",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"@eslint/core": "0.17.0"
}
},
"node_modules/@eslint/core": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz",
"integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==",
"license": "Apache-2.0",
"dependencies": {
"@types/json-schema": "^7.0.15"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
"license": "MIT"
}
}
}
{
"name": "sample-eslint-core-text-source-code",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"@eslint/core": "0.17.0"
}
}
{
"schemaVersion": 1,
"goal": "implement TextSourceCode for custom AST traversal with getLoc and getRange",
"kind": "HOW",
"packages": [
"pkg:npm/%40eslint/core@0.17.0"
],
"symbols": [
"@eslint/core.SourceCodeBase",
"@eslint/core.TextSourceCode"
]
}
/**
* Custom implementation of @eslint/core TextSourceCode.
*
* Implements SourceCodeBase and TextSourceCode contract for ESLint languages.
*/
/**
* Compute line start offsets in text for fast line/col computation.
* @param {string} text
* @returns {number[]}
*/
function computeLineStarts(text) {
const starts = [0];
for (let i = 0; i < text.length; i++) {
if (text[i] === '\n') {
starts.push(i + 1);
}
}
return starts;
}
/**
* TextSourceCode implementation compliant with @eslint/core.
*/
export class CustomTextSourceCode {
/**
* @param {object} options
* @param {string} options.text
* @param {object} options.ast
* @param {Record<string, string[]>} [options.visitorKeys]
*/
constructor({ text, ast, visitorKeys }) {
this.text = text;
this.ast = ast;
this.visitorKeys = visitorKeys || {
Program: ['body'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
Identifier: [],
Literal: []
};
this.lineStarts = computeLineStarts(text);
this.languageOptions = {};
}
/**
* Return start and end Position {line, column} for a syntax element.
* @param {{ loc?: { start: { line: number, column: number }, end: { line: number, column: number } }, range?: [number, number] }} syntaxElement
* @returns {{ start: { line: number, column: number }, end: { line: number, column: number } }}
*/
getLoc(syntaxElement) {
if (syntaxElement.loc) {
return syntaxElement.loc;
}
if (syntaxElement.range) {
const [startOffset, endOffset] = syntaxElement.range;
return {
start: this._offsetToPosition(startOffset),
end: this._offsetToPosition(endOffset)
};
}
throw new Error('Syntax element missing loc or range');
}
/**
* Return [startOffset, endOffset] for a syntax element.
* @param {{ range?: [number, number], loc?: { start: { line: number, column: number }, end: { line: number, column: number } } }} syntaxElement
* @returns {[number, number]}
*/
getRange(syntaxElement) {
if (syntaxElement.range) {
return syntaxElement.range;
}
if (syntaxElement.loc) {
const startOffset = this._positionToOffset(syntaxElement.loc.start);
const endOffset = this._positionToOffset(syntaxElement.loc.end);
return [startOffset, endOffset];
}
throw new Error('Syntax element missing range or loc');
}
/**
* Generator yielding TraversalStep objects:
* kind: 1 (VisitTraversalStep), phase: 1 (enter) | 2 (exit).
* @returns {Iterable<{ kind: 1, target: object, phase: 1 | 2, args: unknown[] }>}
*/
*traverse() {
const visited = new Set();
const visitorKeys = this.visitorKeys;
function* walk(node) {
if (!node || typeof node !== 'object') {
return;
}
if (visited.has(node)) {
return;
}
visited.add(node);
// Phase 1: enter node
yield {
kind: 1,
target: node,
phase: 1,
args: []
};
const keys = (node.type && visitorKeys[node.type]) || Object.keys(node);
for (const key of keys) {
const child = node[key];
if (Array.isArray(child)) {
for (const item of child) {
if (item && typeof item === 'object' && item.type) {
yield* walk(item);
}
}
} else if (child && typeof child === 'object' && child.type) {
yield* walk(child);
}
}
// Phase 2: exit node
yield {
kind: 1,
target: node,
phase: 2,
args: []
};
}
yield* walk(this.ast);
}
/**
* Apply language options passed from ESLint.
* @param {Record<string, unknown>} options
*/
applyLanguageOptions(options) {
this.languageOptions = { ...this.languageOptions, ...options };
}
/**
* Return disable directives.
*/
getDisableDirectives() {
return {
directives: [],
problems: []
};
}
/**
* Return inline config nodes.
*/
getInlineConfigNodes() {
return [];
}
/**
* Finalize source code object.
*/
finalize() {
Object.freeze(this);
}
/**
* @private
*/
_offsetToPosition(offset) {
let line = 1;
for (let i = 1; i < this.lineStarts.length; i++) {
if (this.lineStarts[i] > offset) {
break;
}
line = i + 1;
}
const lineStart = this.lineStarts[line - 1];
const column = offset - lineStart;
return { line, column };
}
/**
* @private
*/
_positionToOffset(pos) {
const lineIdx = pos.line - 1;
if (lineIdx < 0 || lineIdx >= this.lineStarts.length) {
return 0;
}
return this.lineStarts[lineIdx] + pos.column;
}
}
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { CustomTextSourceCode } from '../src/source-code.mjs';
// Locate package directory from node_modules relative to process.cwd() or import.meta.url
const cwdPkgDir = path.resolve(process.cwd(), 'node_modules/@eslint/core');
const scriptRelativePkgDir = path.resolve(path.dirname(new URL(import.meta.url).pathname), '../node_modules/@eslint/core');
const pkgDir = fs.existsSync(cwdPkgDir) ? cwdPkgDir : scriptRelativePkgDir;
const pkgPath = path.join(pkgDir, 'package.json');
assert.ok(fs.existsSync(pkgPath), 'package.json must exist in node_modules/@eslint/core');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
// 1. exports ESM and CJS type declarations for TextSourceCode and SourceCodeBase interfaces
assert.equal(pkg.name, '@eslint/core', 'Package name must be @eslint/core');
assert.equal(pkg.version, '0.17.0', 'Package version must be 0.17.0');
const esmDtsContent = fs.readFileSync(path.join(pkgDir, 'dist/esm/types.d.ts'), 'utf8');
const cjsDtsContent = fs.readFileSync(path.join(pkgDir, 'dist/cjs/types.d.cts'), 'utf8');
assert.ok(esmDtsContent.includes('export interface TextSourceCode<'), 'TextSourceCode interface exported in ESM');
assert.ok(esmDtsContent.includes('interface SourceCodeBase<'), 'SourceCodeBase interface defined in ESM');
assert.ok(cjsDtsContent.includes('export interface TextSourceCode<'), 'TextSourceCode interface exported in CJS');
// Sample code and AST fixture
const sampleText = 'const x = 42;\nconst y = "hello";\n';
const sampleAst = {
type: 'Program',
range: [0, 33],
body: [
{
type: 'VariableDeclaration',
kind: 'const',
range: [0, 13],
declarations: [
{
type: 'VariableDeclarator',
range: [6, 12],
id: { type: 'Identifier', name: 'x', range: [6, 7] },
init: { type: 'Literal', value: 42, range: [10, 12] }
}
]
},
{
type: 'VariableDeclaration',
kind: 'const',
range: [14, 32],
declarations: [
{
type: 'VariableDeclarator',
range: [20, 31],
id: { type: 'Identifier', name: 'y', range: [20, 21] },
init: { type: 'Literal', value: 'hello', range: [24, 31] }
}
]
}
]
};
const sourceCode = new CustomTextSourceCode({
text: sampleText,
ast: sampleAst
});
// 2. implements TextSourceCode and SourceCodeBase interface properties: text, ast, visitorKeys, getLoc, getRange, and traverse
assert.equal(sourceCode.text, sampleText, 'TextSourceCode.text must contain the source text');
assert.equal(sourceCode.ast, sampleAst, 'TextSourceCode.ast must match the provided AST');
assert.ok(typeof sourceCode.visitorKeys === 'object', 'TextSourceCode must provide visitorKeys');
assert.equal(typeof sourceCode.getLoc, 'function', 'TextSourceCode must implement getLoc');
assert.equal(typeof sourceCode.getRange, 'function', 'TextSourceCode must implement getRange');
assert.equal(typeof sourceCode.traverse, 'function', 'TextSourceCode must implement traverse');
// 3. computes source location with 1-indexed line and 0-indexed column from character offsets via getLoc
const var1 = sampleAst.body[0];
const loc1 = sourceCode.getLoc(var1);
assert.deepEqual(loc1, {
start: { line: 1, column: 0 },
end: { line: 1, column: 13 }
}, 'getLoc for line 1 node must calculate 1-indexed line 1 and column 0..13');
const var2 = sampleAst.body[1];
const loc2 = sourceCode.getLoc(var2);
assert.deepEqual(loc2, {
start: { line: 2, column: 0 },
end: { line: 2, column: 18 }
}, 'getLoc for line 2 node must calculate 1-indexed line 2 and column 0..18');
const id2 = var2.declarations[0].id;
const locId2 = sourceCode.getLoc(id2);
assert.deepEqual(locId2, {
start: { line: 2, column: 6 },
end: { line: 2, column: 7 }
}, 'getLoc for inline identifier on line 2 must compute correct offset');
// 4. derives start and end character offset tuples via getRange from node locations
const range1 = sourceCode.getRange(var1);
assert.deepEqual(range1, [0, 13], 'getRange must return [0, 13]');
const range2 = sourceCode.getRange(var2);
assert.deepEqual(range2, [14, 32], 'getRange must return [14, 32]');
// Round-trip test from loc to range
const synthesizedNodeWithLoc = { loc: locId2 };
assert.deepEqual(sourceCode.getRange(synthesizedNodeWithLoc), [20, 21], 'getRange derived from loc coordinates');
// 5. traverse generator yields VisitTraversalStep items with enter (phase 1) and exit (phase 2) order
const steps = Array.from(sourceCode.traverse());
assert.ok(steps.length > 0, 'traverse must yield steps');
for (const step of steps) {
assert.equal(step.kind, 1, 'Every step in AST visit must have kind: 1 (VisitTraversalStep)');
assert.ok(step.phase === 1 || step.phase === 2, 'Step phase must be 1 (enter) or 2 (exit)');
assert.ok(typeof step.target === 'object' && step.target !== null, 'Target must be an AST node');
assert.ok(Array.isArray(step.args), 'Step args must be an array');
}
// First step enters Program, last step exits Program
assert.equal(steps[0].target.type, 'Program');
assert.equal(steps[0].phase, 1, 'First step is enter Program');
assert.equal(steps[steps.length - 1].target.type, 'Program');
assert.equal(steps[steps.length - 1].phase, 2, 'Last step is exit Program');
// Verify paired enter and exit for each node
const entered = [];
const exited = [];
for (const step of steps) {
if (step.phase === 1) entered.push(step.target.type);
if (step.phase === 2) exited.push(step.target.type);
}
assert.equal(entered.length, exited.length, 'Enter and exit counts must match');
assert.deepEqual(entered, ['Program', 'VariableDeclaration', 'VariableDeclarator', 'Identifier', 'Literal', 'VariableDeclaration', 'VariableDeclarator', 'Identifier', 'Literal']);
// 6. supports language options lifecycle, disable directives, and finalization on TextSourceCode instance
sourceCode.applyLanguageOptions({ ecmaVersion: 2024, sourceType: 'module' });
assert.deepEqual(sourceCode.languageOptions, { ecmaVersion: 2024, sourceType: 'module' });
assert.deepEqual(sourceCode.getDisableDirectives(), { directives: [], problems: [] });
assert.deepEqual(sourceCode.getInlineConfigNodes(), []);
sourceCode.finalize();
assert.ok(Object.isFrozen(sourceCode), 'finalize freezes sourceCode instance');
console.log('Contract tests passed successfully.');
Seeder d'origine
anonyme