CodeSampleX

Пример

@typescript-eslint/scope-manager 8.69.0: ClassStaticBlockScope

Проверенный пример — npm @typescript-eslint/scope-manager 8.69.0: ClassStaticBlockScope. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:cf2dee710e8fb92dfdb1c5dde4576b12b9bdb15dbecd776ef691776ae343f346

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-10-11

Кейс

HOW
Цель
verify @typescript-eslint/scope-manager.ClassStaticBlockScope in pkg:npm/%40typescript-eslint/scope-manager@8.69.0
Пакеты
Символы
  • @typescript-eslint/scope-manager.ClassStaticBlockScope
Окружение
node 22.23.2
Создан
2026-10-11T16:27:05Z

Контракт

  1. ClassStaticBlockScope instance can be directly instantiated with ScopeManager, upper scope, and StaticBlock AST node
  2. analyze creates a ClassStaticBlockScope for a StaticBlock inside a ClassDeclaration
  3. variables declared inside a StaticBlock are scoped to the ClassStaticBlockScope and do not leak to ClassScope or outer scope
  4. ClassStaticBlockScope manages child scopes such as nested function declarations or block statements
  5. ClassStaticBlockScope enforces strict mode when nested within a class scope

Файлы

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

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

Исходный код

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: verify @typescript-eslint/scope-manager.ClassStaticBlockScope in pkg:npm/%40typescript-eslint/scope-manager@8.69.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40typescript-eslint/scope-manager@8.69.0
Demonstrate these symbols/APIs:
  - @typescript-eslint/scope-manager.ClassStaticBlockScope

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:3b75ef8daa896c330f96392776e65a3ec71cb14bec02e25d0b485759ae5fbe34","contract":["ClassStaticBlockScope instance can be directly instantiated with ScopeManager, upper scope, and StaticBlock AST node","analyze creates a ClassStaticBlockScope for a StaticBlock inside a ClassDeclaration","variables declared inside a StaticBlock are scoped to the ClassStaticBlockScope and do not leak to ClassScope or outer scope","ClassStaticBlockScope manages child scopes such as nested function declarations or block statements","ClassStaticBlockScope enforces strict mode when nested within a class scope"],"goal":"verify @typescript-eslint/scope-manager.ClassStaticBlockScope in pkg:npm/%40typescript-eslint/scope-manager@8.69.0","kind":"HOW","packages":["pkg:npm/%40typescript-eslint/scope-manager@8.69.0"],"schemaVersion":1,"symbols":["@typescript-eslint/scope-manager.ClassStaticBlockScope"]},"contractCommand":["node","test/contract.cjs"],"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/%40typescript-eslint/scope-manager@8.69.0"],"schemaVersion":1,"subject":"pkg:npm/%40typescript-eslint/scope-manager@8.69.0","symbols":["@typescript-eslint/scope-manager.ClassStaticBlockScope"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-typescript-eslint-scope-manager-class-static-block-scope",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-typescript-eslint-scope-manager-class-static-block-scope",
      "version": "1.0.0",
      "dependencies": {
        "@typescript-eslint/scope-manager": "8.69.0"
      }
    },
    "node_modules/@typescript-eslint/scope-manager": {
      "version": "8.69.0",
      "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.69.0.tgz",
      "integrity": "sha512-ewfspqWvSxKSOaplqAUNbaSFO0eB6w1EtQ+esfYFRm3614Ty4uNtExkcbgd6nWsXphbqKyf9ZYdbZdv2xEoWEQ==",
      "license": "MIT",
      "dependencies": {
        "@typescript-eslint/types": "8.69.0",
        "@typescript-eslint/visitor-keys": "8.69.0"
      },
      "engines": {
        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/typescript-eslint"
      }
    },
    "node_modules/@typescript-eslint/types": {
      "version": "8.69.0",
      "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.69.0.tgz",
      "integrity": "sha512-K3VrubUPhlo9VDBS6QdI8YB5j7ClpqLRdefcz6PFrhnwicehBweqQ9Evhl4l+FYz0HdDmMqIiSX0aldGRYtDCA==",
      "license": "MIT",
      "engines": {
        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/typescript-eslint"
      }
    },
    "node_modules/@typescript-eslint/visitor-keys": {
      "version": "8.69.0",
      "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.69.0.tgz",
      "integrity": "sha512-+rmdgPA+EXkNgKYvHvFfhrs35utXbwaC5PGpDquSXcoXQDKUA5UjV0LmTucG/4JXkM31BTu4TilHtrN8IVBe8w==",
      "license": "MIT",
      "dependencies": {
        "@typescript-eslint/types": "8.69.0",
        "eslint-visitor-keys": "^5.0.0"
      },
      "engines": {
        "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/typescript-eslint"
      }
    },
    "node_modules/eslint-visitor-keys": {
      "version": "5.0.1",
      "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz",
      "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==",
      "license": "Apache-2.0",
      "engines": {
        "node": "^20.19.0 || ^22.13.0 || >=24"
      },
      "funding": {
        "url": "https://opencollective.com/eslint"
      }
    }
  }
}
package.json
{
  "name": "verify-typescript-eslint-scope-manager-class-static-block-scope",
  "version": "1.0.0",
  "private": true,
  "description": "verify @typescript-eslint/scope-manager.ClassStaticBlockScope in pkg:npm/@typescript-eslint/scope-manager@8.69.0",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "@typescript-eslint/scope-manager": "8.69.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @typescript-eslint/scope-manager.ClassStaticBlockScope in pkg:npm/%40typescript-eslint/scope-manager@8.69.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40typescript-eslint/scope-manager@8.69.0"
  ],
  "symbols": [
    "@typescript-eslint/scope-manager.ClassStaticBlockScope"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const {
  analyze,
  ClassStaticBlockScope,
  ScopeManager,
  ScopeType,
} = require('@typescript-eslint/scope-manager');

/**
 * Creates a ClassStaticBlockScope directly with a given scope manager, upper scope, and StaticBlock AST node.
 *
 * @param {ScopeManager} scopeManager - The scope manager instance
 * @param {import('@typescript-eslint/scope-manager').Scope} upperScope - The enclosing parent scope (typically ClassScope)
 * @param {object} blockNode - AST node representing the StaticBlock
 * @returns {ClassStaticBlockScope}
 */
function createDirectClassStaticBlockScope(scopeManager, upperScope, blockNode) {
  return new ClassStaticBlockScope(scopeManager, upperScope, blockNode);
}

/**
 * Analyzes an ESTree AST and extracts all ClassStaticBlockScope instances.
 *
 * @param {object} ast - ESTree Program AST node
 * @param {object} [options] - Optional analysis configuration
 * @returns {{ scopeManager: ScopeManager, staticBlockScopes: ClassStaticBlockScope[] }}
 */
function analyzeAndFindClassStaticBlockScopes(ast, options) {
  const scopeManager = analyze(ast, options);
  const staticBlockScopes = scopeManager.scopes.filter(
    (scope) => scope instanceof ClassStaticBlockScope
  );
  return { scopeManager, staticBlockScopes };
}

/**
 * Extracts metadata from a ClassStaticBlockScope instance.
 *
 * @param {ClassStaticBlockScope} staticBlockScope - The ClassStaticBlockScope to inspect
 * @returns {{
 *   type: string,
 *   isStrict: boolean,
 *   blockType: string | null,
 *   boundVariables: string[],
 *   childScopeTypes: string[],
 *   upperType: string | null
 * }}
 */
function getClassStaticBlockScopeMetadata(staticBlockScope) {
  if (!staticBlockScope || !(staticBlockScope instanceof ClassStaticBlockScope)) {
    throw new TypeError('Expected an instance of ClassStaticBlockScope');
  }
  return {
    type: staticBlockScope.type,
    isStrict: staticBlockScope.isStrict,
    blockType: staticBlockScope.block ? staticBlockScope.block.type : null,
    boundVariables: Array.from(staticBlockScope.set.keys()),
    childScopeTypes: staticBlockScope.childScopes.map((child) => child.type),
    upperType: staticBlockScope.upper ? staticBlockScope.upper.type : null,
  };
}

module.exports = {
  createDirectClassStaticBlockScope,
  analyzeAndFindClassStaticBlockScopes,
  getClassStaticBlockScopeMetadata,
};
test/contract.cjs
const assert = require('node:assert/strict');
const {
  analyze,
  ClassScope,
  ClassStaticBlockScope,
  ScopeManager,
  GlobalScope,
  ScopeType,
  DefinitionType,
} = require('@typescript-eslint/scope-manager');
const {
  createDirectClassStaticBlockScope,
  analyzeAndFindClassStaticBlockScopes,
  getClassStaticBlockScopeMetadata,
} = require('../src/index.js');

// 1. ClassStaticBlockScope instance can be directly instantiated with ScopeManager, upper scope, and StaticBlock AST node
const manager = new ScopeManager({});
const programNode = { type: 'Program', sourceType: 'module', body: [] };
const globalScope = new GlobalScope(manager, programNode);
const classNode = {
  type: 'ClassDeclaration',
  id: { type: 'Identifier', name: 'DatabaseService', decorators: [] },
  superClass: null,
  decorators: [],
  implements: [],
  body: { type: 'ClassBody', body: [] },
};
const classScope = new ClassScope(manager, globalScope, classNode);
const staticBlockNode = {
  type: 'StaticBlock',
  body: [],
};

const directScope = createDirectClassStaticBlockScope(manager, classScope, staticBlockNode);

assert.ok(directScope instanceof ClassStaticBlockScope, 'Instance should be ClassStaticBlockScope');
assert.strictEqual(directScope.type, ScopeType.classStaticBlock, 'Scope type should match ScopeType.classStaticBlock');
assert.strictEqual(directScope.type, 'class-static-block', 'Scope type should be "class-static-block"');
assert.strictEqual(directScope.upper, classScope, 'Upper scope should match parent ClassScope');
assert.strictEqual(directScope.block, staticBlockNode, 'Block should reference the StaticBlock AST node');
assert.strictEqual(directScope.isStrict, true, 'ClassStaticBlockScope should inherit strict mode from class scope');

const directMeta = getClassStaticBlockScopeMetadata(directScope);
assert.strictEqual(directMeta.type, 'class-static-block');
assert.strictEqual(directMeta.isStrict, true);
assert.strictEqual(directMeta.blockType, 'StaticBlock');
assert.strictEqual(directMeta.upperType, 'class');

// 2. analyze creates a ClassStaticBlockScope for a StaticBlock inside a ClassDeclaration
const classAst = {
  type: 'Program',
  sourceType: 'module',
  body: [
    {
      type: 'ClassDeclaration',
      id: { type: 'Identifier', name: 'AppConfig', decorators: [] },
      superClass: null,
      decorators: [],
      implements: [],
      body: {
        type: 'ClassBody',
        body: [
          {
            type: 'StaticBlock',
            body: [
              {
                type: 'ExpressionStatement',
                expression: {
                  type: 'CallExpression',
                  callee: {
                    type: 'MemberExpression',
                    object: { type: 'Identifier', name: 'AppConfig', decorators: [] },
                    property: { type: 'Identifier', name: 'init', decorators: [] },
                    computed: false,
                  },
                  arguments: [],
                },
              },
            ],
          },
        ],
      },
    },
  ],
  range: [0, 80],
  loc: { start: { line: 1, column: 0 }, end: { line: 5, column: 1 } },
};

const { scopeManager: analyzedManager, staticBlockScopes: analyzedScopes } =
  analyzeAndFindClassStaticBlockScopes(classAst, { sourceType: 'module' });

assert.strictEqual(analyzedScopes.length, 1, 'Should find exactly one ClassStaticBlockScope');
const analyzedScope = analyzedScopes[0];

assert.ok(analyzedScope instanceof ClassStaticBlockScope, 'Must be an instance of ClassStaticBlockScope');
assert.strictEqual(analyzedScope.type, ScopeType.classStaticBlock, 'Type should be classStaticBlock');
assert.strictEqual(analyzedScope.block, classAst.body[0].body.body[0], 'Block should match StaticBlock AST node');
assert.ok(analyzedScope.upper instanceof ClassScope, 'Upper scope must be ClassScope');
assert.strictEqual(analyzedScope.upper.block, classAst.body[0], 'Upper scope block must be ClassDeclaration');

// 3. variables declared inside a StaticBlock are scoped to the ClassStaticBlockScope and do not leak to ClassScope or outer scope
const scopedVarsAst = {
  type: 'Program',
  sourceType: 'module',
  body: [
    {
      type: 'ClassDeclaration',
      id: { type: 'Identifier', name: 'Registry', decorators: [] },
      superClass: null,
      decorators: [],
      implements: [],
      body: {
        type: 'ClassBody',
        body: [
          {
            type: 'StaticBlock',
            body: [
              {
                type: 'VariableDeclaration',
                kind: 'const',
                declarations: [
                  {
                    type: 'VariableDeclarator',
                    id: { type: 'Identifier', name: 'cacheLimit', decorators: [] },
                    init: { type: 'Literal', value: 100 },
                  },
                ],
                decorators: [],
              },
              {
                type: 'VariableDeclaration',
                kind: 'var',
                declarations: [
                  {
                    type: 'VariableDeclarator',
                    id: { type: 'Identifier', name: 'activeConnection', decorators: [] },
                    init: { type: 'Literal', value: null },
                  },
                ],
                decorators: [],
              },
            ],
          },
        ],
      },
    },
  ],
  range: [0, 100],
  loc: { start: { line: 1, column: 0 }, end: { line: 8, column: 1 } },
};

const { scopeManager: scopedManager, staticBlockScopes: registryScopes } =
  analyzeAndFindClassStaticBlockScopes(scopedVarsAst, { sourceType: 'module' });

assert.strictEqual(registryScopes.length, 1, 'Should find one StaticBlock scope');
const registryStaticScope = registryScopes[0];
const registryClassScope = registryStaticScope.upper;
const moduleScope = registryClassScope.upper;

assert.ok(registryStaticScope.set.has('cacheLimit'), 'cacheLimit must be bound in ClassStaticBlockScope');
assert.ok(registryStaticScope.set.has('activeConnection'), 'activeConnection must be bound in ClassStaticBlockScope');

const cacheLimitVar = registryStaticScope.set.get('cacheLimit');
assert.strictEqual(cacheLimitVar.name, 'cacheLimit');
assert.strictEqual(cacheLimitVar.defs[0].type, DefinitionType.Variable);

const connVar = registryStaticScope.set.get('activeConnection');
assert.strictEqual(connVar.name, 'activeConnection');
assert.strictEqual(connVar.defs[0].type, DefinitionType.Variable);

// Verify variables do NOT leak to ClassScope or outer module scope
assert.strictEqual(registryClassScope.set.has('cacheLimit'), false, 'cacheLimit must not leak to ClassScope');
assert.strictEqual(registryClassScope.set.has('activeConnection'), false, 'activeConnection must not leak to ClassScope');
assert.strictEqual(moduleScope.set.has('cacheLimit'), false, 'cacheLimit must not leak to module scope');
assert.strictEqual(moduleScope.set.has('activeConnection'), false, 'activeConnection must not leak to module scope');

// 4. ClassStaticBlockScope manages child scopes such as nested function declarations or block statements
const childScopeAst = {
  type: 'Program',
  sourceType: 'module',
  body: [
    {
      type: 'ClassDeclaration',
      id: { type: 'Identifier', name: 'Initializer', decorators: [] },
      superClass: null,
      decorators: [],
      implements: [],
      body: {
        type: 'ClassBody',
        body: [
          {
            type: 'StaticBlock',
            body: [
              {
                type: 'FunctionDeclaration',
                id: { type: 'Identifier', name: 'bootstrap', decorators: [] },
                generator: false,
                async: false,
                params: [],
                body: { type: 'BlockStatement', body: [] },
                decorators: [],
              },
            ],
          },
        ],
      },
    },
  ],
  range: [0, 80],
  loc: { start: { line: 1, column: 0 }, end: { line: 6, column: 1 } },
};

const { staticBlockScopes: initScopes } =
  analyzeAndFindClassStaticBlockScopes(childScopeAst, { sourceType: 'module' });

assert.strictEqual(initScopes.length, 1);
const initStaticScope = initScopes[0];
assert.strictEqual(initStaticScope.childScopes.length, 1, 'StaticBlock should have one child function scope');
const childFnScope = initStaticScope.childScopes[0];
assert.strictEqual(childFnScope.type, ScopeType.function, 'Child scope should be function scope');
assert.strictEqual(childFnScope.upper, initStaticScope, 'Child function scope upper reference must point to ClassStaticBlockScope');

const initMeta = getClassStaticBlockScopeMetadata(initStaticScope);
assert.deepStrictEqual(initMeta.childScopeTypes, ['function']);
assert.ok(initMeta.boundVariables.includes('bootstrap'));

// 5. ClassStaticBlockScope enforces strict mode when nested within a class scope
assert.strictEqual(directScope.isStrict, true, 'Direct instance inside ClassScope must be strict');
assert.strictEqual(analyzedScope.isStrict, true, 'Analyzed static block scope must be strict');
assert.strictEqual(registryStaticScope.isStrict, true, 'Analyzed registry static block scope must be strict');

// Error handling validation
assert.throws(
  () => getClassStaticBlockScopeMetadata(null),
  /Expected an instance of ClassStaticBlockScope/,
  'getClassStaticBlockScopeMetadata should throw TypeError for invalid input'
);
assert.throws(
  () => getClassStaticBlockScopeMetadata({}),
  /Expected an instance of ClassStaticBlockScope/,
  'getClassStaticBlockScopeMetadata should throw TypeError for non-ClassStaticBlockScope instance'
);

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

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

аноним