CodeSampleX

Ejemplo

typescript 7.0.2: Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration

Muestra verificada para npm typescript 7.0.2: Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration.…

sha256:b720861e7dc24b617b90ce608b733690aeeb81f19596487a0bd133175acf95c7

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Caso

HOW
Objetivo
Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration
Paquetes
Símbolos
  • createClassDeclaration
  • createMethodDeclaration
Creado
2026-08-20T06:05:56Z

Contrato

  1. buildClassDeclaration constructs a class declaration AST node with properties and methods and validates it with isClassDeclaration
  2. buildMethodDeclaration constructs method declarations with access modifiers, async keyword, and parameters using createMethodDeclaration
  3. buildClassDeclaration constructs class declarations with generic type parameters and heritage clauses (extends and implements)
  4. inspectClassDeclaration extracts class metadata including name, modifiers, heritage clauses, properties, and methods using type guards

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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: Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@7.0.2
Demonstrate these symbols/APIs:
  - createClassDeclaration
  - createMethodDeclaration

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:b0693cde29696f48574e6cebaed6a7d7f666de5229f40b2685c5442dcd494f1a","contract":["buildClassDeclaration constructs a class declaration AST node with properties and methods and validates it with isClassDeclaration","buildMethodDeclaration constructs method declarations with access modifiers, async keyword, and parameters using createMethodDeclaration","buildClassDeclaration constructs class declarations with generic type parameters and heritage clauses (extends and implements)","inspectClassDeclaration extracts class metadata including name, modifiers, heritage clauses, properties, and methods using type guards"],"goal":"Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration","kind":"HOW","packages":["pkg:npm/typescript@7.0.2"],"schemaVersion":1,"symbols":["createClassDeclaration","createMethodDeclaration"]},"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/typescript@7.0.2"],"schemaVersion":1,"symbols":["createClassDeclaration","createMethodDeclaration"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "typescript-class-declaration-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "typescript-class-declaration-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "typescript": "7.0.2"
      }
    },
    "node_modules/@typescript/typescript-aix-ppc64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
      "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
      "cpu": [
        "ppc64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "aix"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-darwin-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
      "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-darwin-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
      "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-freebsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
      "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-freebsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
      "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-arm": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
      "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
      "cpu": [
        "arm"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
      "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-loong64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
      "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
      "cpu": [
        "loong64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-mips64el": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
      "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
      "cpu": [
        "mips64el"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-ppc64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
      "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
      "cpu": [
        "ppc64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-riscv64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
      "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
      "cpu": [
        "riscv64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-s390x": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
      "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
      "cpu": [
        "s390x"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
      "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-netbsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
      "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-netbsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
      "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-openbsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
      "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-openbsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
      "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-sunos-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
      "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "sunos"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-win32-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
      "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-win32-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
      "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/typescript": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
      "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc"
      },
      "engines": {
        "node": ">=16.20.0"
      },
      "optionalDependencies": {
        "@typescript/typescript-aix-ppc64": "7.0.2",
        "@typescript/typescript-darwin-arm64": "7.0.2",
        "@typescript/typescript-darwin-x64": "7.0.2",
        "@typescript/typescript-freebsd-arm64": "7.0.2",
        "@typescript/typescript-freebsd-x64": "7.0.2",
        "@typescript/typescript-linux-arm": "7.0.2",
        "@typescript/typescript-linux-arm64": "7.0.2",
        "@typescript/typescript-linux-loong64": "7.0.2",
        "@typescript/typescript-linux-mips64el": "7.0.2",
        "@typescript/typescript-linux-ppc64": "7.0.2",
        "@typescript/typescript-linux-riscv64": "7.0.2",
        "@typescript/typescript-linux-s390x": "7.0.2",
        "@typescript/typescript-linux-x64": "7.0.2",
        "@typescript/typescript-netbsd-arm64": "7.0.2",
        "@typescript/typescript-netbsd-x64": "7.0.2",
        "@typescript/typescript-openbsd-arm64": "7.0.2",
        "@typescript/typescript-openbsd-x64": "7.0.2",
        "@typescript/typescript-sunos-x64": "7.0.2",
        "@typescript/typescript-win32-arm64": "7.0.2",
        "@typescript/typescript-win32-x64": "7.0.2"
      }
    }
  }
}
package.json
{
  "name": "typescript-class-declaration-sample",
  "version": "1.0.0",
  "description": "Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "typescript": "7.0.2"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Construct and validate TypeScript class declarations using createClassDeclaration and createMethodDeclaration",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@7.0.2"
  ],
  "symbols": [
    "createClassDeclaration",
    "createMethodDeclaration"
  ]
}
src/index.mjs
import {
  createClassDeclaration,
  createMethodDeclaration,
  createConstructorDeclaration,
  createPropertyDeclaration,
  createHeritageClause,
  createExpressionWithTypeArguments,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createTypeParameterDeclaration,
  createParameterDeclaration,
  createBlock,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
} from 'typescript/unstable/ast/factory';

import {
  SyntaxKind,
  formatSyntaxKind,
  isClassDeclaration,
  isMethodDeclaration,
  isPropertyDeclaration,
  isConstructorDeclaration,
  isHeritageClause,
  isIdentifier,
  isToken,
  isBlock,
  isKeywordTypeNode,
  isTypeReferenceNode,
} from 'typescript/unstable/ast';

/**
 * Converts a string type name or TypeNode into a valid TypeNode.
 *
 * @param {string | object} [type] - Type name or AST TypeNode.
 * @returns {object | undefined} AST TypeNode.
 */
function toTypeNode(type) {
  if (!type) return undefined;
  if (typeof type === 'object') return type;
  switch (type) {
    case 'string':
      return createKeywordTypeNode(SyntaxKind.StringKeyword);
    case 'number':
      return createKeywordTypeNode(SyntaxKind.NumberKeyword);
    case 'boolean':
      return createKeywordTypeNode(SyntaxKind.BooleanKeyword);
    case 'void':
      return createKeywordTypeNode(SyntaxKind.VoidKeyword);
    case 'any':
      return createKeywordTypeNode(SyntaxKind.AnyKeyword);
    default:
      return createTypeReferenceNode(createIdentifier(type), undefined);
  }
}

/**
 * Builds a Parameter AST node from parameter descriptor.
 *
 * @param {string | object} param - Parameter name or descriptor.
 * @returns {object} Parameter AST node.
 */
function buildParameter(param) {
  if (typeof param === 'string') {
    return createParameterDeclaration(
      undefined,
      undefined,
      createIdentifier(param),
      undefined,
      undefined,
      undefined
    );
  }
  const nameNode = typeof param.name === 'string' ? createIdentifier(param.name) : param.name;
  const typeNode = toTypeNode(param.type);
  const questionToken = param.isOptional ? createToken(SyntaxKind.QuestionToken) : undefined;
  return createParameterDeclaration(
    undefined,
    undefined,
    nameNode,
    questionToken,
    typeNode,
    param.initializer
  );
}

/**
 * Builds a MethodDeclaration AST node using createMethodDeclaration.
 *
 * @param {string | object} name - Method name or identifier.
 * @param {Array<string | object>} [parameters=[]] - Method parameters.
 * @param {string | object} [returnType] - Method return type.
 * @param {Array<object>} [bodyStatements=[]] - Statements for the method body.
 * @param {object} [options={}] - Method modifiers and options.
 * @param {'public' | 'private' | 'protected'} [options.access] - Access modifier.
 * @param {boolean} [options.isStatic=false] - Whether method is static.
 * @param {boolean} [options.isAsync=false] - Whether method is async.
 * @returns {object} MethodDeclaration AST node.
 */
export function buildMethodDeclaration(name, parameters = [], returnType = undefined, bodyStatements = [], options = {}) {
  const nameNode = typeof name === 'string' ? createIdentifier(name) : name;
  const paramNodes = parameters.map((p) => buildParameter(p));
  const retTypeNode = toTypeNode(returnType);
  const bodyBlock = createBlock(bodyStatements, true);

  const modifiers = [];
  if (options.access === 'public') {
    modifiers.push(createToken(SyntaxKind.PublicKeyword));
  } else if (options.access === 'private') {
    modifiers.push(createToken(SyntaxKind.PrivateKeyword));
  } else if (options.access === 'protected') {
    modifiers.push(createToken(SyntaxKind.ProtectedKeyword));
  }
  if (options.isStatic) {
    modifiers.push(createToken(SyntaxKind.StaticKeyword));
  }
  if (options.isAsync) {
    modifiers.push(createToken(SyntaxKind.AsyncKeyword));
  }

  return createMethodDeclaration(
    modifiers.length > 0 ? modifiers : undefined,
    undefined,
    nameNode,
    undefined,
    undefined,
    paramNodes,
    retTypeNode,
    bodyBlock
  );
}

/**
 * Builds a PropertyDeclaration AST node using createPropertyDeclaration.
 *
 * @param {string | object} name - Property name or identifier.
 * @param {string | object} [type='string'] - Property type.
 * @param {object} [options={}] - Property options.
 * @param {'public' | 'private' | 'protected'} [options.access] - Access modifier.
 * @param {boolean} [options.isStatic=false] - Whether property is static.
 * @param {boolean} [options.isReadonly=false] - Whether property is readonly.
 * @param {boolean} [options.isOptional=false] - Whether property is optional.
 * @param {object} [options.initializer] - Property initializer expression AST.
 * @returns {object} PropertyDeclaration AST node.
 */
export function buildPropertyDeclaration(name, type = 'string', options = {}) {
  const nameNode = typeof name === 'string' ? createIdentifier(name) : name;
  const typeNode = toTypeNode(type);
  const postfixToken = options.isOptional ? createToken(SyntaxKind.QuestionToken) : undefined;

  const modifiers = [];
  if (options.access === 'public') {
    modifiers.push(createToken(SyntaxKind.PublicKeyword));
  } else if (options.access === 'private') {
    modifiers.push(createToken(SyntaxKind.PrivateKeyword));
  } else if (options.access === 'protected') {
    modifiers.push(createToken(SyntaxKind.ProtectedKeyword));
  }
  if (options.isStatic) {
    modifiers.push(createToken(SyntaxKind.StaticKeyword));
  }
  if (options.isReadonly) {
    modifiers.push(createToken(SyntaxKind.ReadonlyKeyword));
  }

  return createPropertyDeclaration(
    modifiers.length > 0 ? modifiers : undefined,
    nameNode,
    postfixToken,
    typeNode,
    options.initializer
  );
}

/**
 * Builds a ConstructorDeclaration AST node using createConstructorDeclaration.
 *
 * @param {Array<string | object>} [parameters=[]] - Constructor parameters.
 * @param {Array<object>} [bodyStatements=[]] - Constructor body statements.
 * @param {object} [options={}] - Constructor options.
 * @param {'public' | 'private' | 'protected'} [options.access] - Access modifier.
 * @returns {object} ConstructorDeclaration AST node.
 */
export function buildConstructorDeclaration(parameters = [], bodyStatements = [], options = {}) {
  const paramNodes = parameters.map((p) => buildParameter(p));
  const bodyBlock = createBlock(bodyStatements, true);

  const modifiers = [];
  if (options.access === 'public') {
    modifiers.push(createToken(SyntaxKind.PublicKeyword));
  } else if (options.access === 'private') {
    modifiers.push(createToken(SyntaxKind.PrivateKeyword));
  } else if (options.access === 'protected') {
    modifiers.push(createToken(SyntaxKind.ProtectedKeyword));
  }

  return createConstructorDeclaration(
    modifiers.length > 0 ? modifiers : undefined,
    undefined,
    paramNodes,
    undefined,
    bodyBlock
  );
}

/**
 * Builds a ClassDeclaration AST node using createClassDeclaration.
 *
 * @param {string | object} name - Class name or identifier.
 * @param {Array<object>} [members=[]] - Class members (properties, methods, constructor).
 * @param {object} [options={}] - Class options.
 * @param {boolean} [options.isExported=false] - Whether class is exported.
 * @param {boolean} [options.isAbstract=false] - Whether class is abstract.
 * @param {Array<string | object>} [options.typeParameters] - Generic type parameters.
 * @param {string | object} [options.extends] - Base class name to extend.
 * @param {Array<string | object>} [options.implements] - Interface names to implement.
 * @returns {object} ClassDeclaration AST node.
 */
export function buildClassDeclaration(name, members = [], options = {}) {
  const nameNode = typeof name === 'string' ? createIdentifier(name) : name;

  const modifiers = [];
  if (options.isExported) {
    modifiers.push(createToken(SyntaxKind.ExportKeyword));
  }
  if (options.isAbstract) {
    modifiers.push(createToken(SyntaxKind.AbstractKeyword));
  }

  let typeParams = undefined;
  if (Array.isArray(options.typeParameters) && options.typeParameters.length > 0) {
    typeParams = options.typeParameters.map((tp) => {
      const tpName = typeof tp === 'string' ? tp : tp.name;
      return createTypeParameterDeclaration(undefined, createIdentifier(tpName), undefined, undefined, undefined);
    });
  }

  const heritageClauses = [];
  if (options.extends) {
    const extName = typeof options.extends === 'string' ? options.extends : options.extends.name;
    heritageClauses.push(
      createHeritageClause(createToken(SyntaxKind.ExtendsKeyword), [
        createExpressionWithTypeArguments(createIdentifier(extName), undefined),
      ])
    );
  }
  if (Array.isArray(options.implements) && options.implements.length > 0) {
    const implTypes = options.implements.map((impl) => {
      const implName = typeof impl === 'string' ? impl : impl.name;
      return createExpressionWithTypeArguments(createIdentifier(implName), undefined);
    });
    heritageClauses.push(createHeritageClause(createToken(SyntaxKind.ImplementsKeyword), implTypes));
  }

  return createClassDeclaration(
    modifiers.length > 0 ? modifiers : undefined,
    nameNode,
    typeParams,
    heritageClauses.length > 0 ? heritageClauses : undefined,
    members
  );
}

/**
 * Inspects a ClassDeclaration AST node and extracts its metadata using AST type guards.
 *
 * @param {object} node - ClassDeclaration AST node.
 * @returns {object} Inspected class metadata.
 */
export function inspectClassDeclaration(node) {
  if (!node || typeof node !== 'object' || !isClassDeclaration(node)) {
    throw new TypeError('Expected a ClassDeclaration AST node');
  }

  const rawName = node.name && isIdentifier(node.name) ? node.name.text : undefined;
  const modifiers = Array.isArray(node.modifiers) ? node.modifiers : [];
  const isExported = modifiers.some((m) => m.kind === SyntaxKind.ExportKeyword);
  const isAbstract = modifiers.some((m) => m.kind === SyntaxKind.AbstractKeyword);

  const typeParameters = [];
  if (Array.isArray(node.typeParameters)) {
    for (const tp of node.typeParameters) {
      if (tp && tp.name && isIdentifier(tp.name)) {
        typeParameters.push(tp.name.text);
      }
    }
  }

  let extendsName = undefined;
  const implementsNames = [];
  const heritageClauses = Array.isArray(node.heritageClauses) ? node.heritageClauses : [];
  for (const hc of heritageClauses) {
    if (hc.token && hc.token.kind === SyntaxKind.ExtendsKeyword) {
      if (Array.isArray(hc.types) && hc.types.length > 0) {
        const expr = hc.types[0].expression;
        if (expr && isIdentifier(expr)) {
          extendsName = expr.text;
        }
      }
    } else if (hc.token && hc.token.kind === SyntaxKind.ImplementsKeyword) {
      if (Array.isArray(hc.types)) {
        for (const t of hc.types) {
          if (t.expression && isIdentifier(t.expression)) {
            implementsNames.push(t.expression.text);
          }
        }
      }
    }
  }

  const rawMembers = Array.isArray(node.members) ? node.members : [];
  const properties = [];
  const methods = [];
  let hasConstructor = false;

  for (const m of rawMembers) {
    if (isConstructorDeclaration(m)) {
      hasConstructor = true;
    } else if (isPropertyDeclaration(m)) {
      const mName = m.name && isIdentifier(m.name) ? m.name.text : undefined;
      const mModifiers = Array.isArray(m.modifiers) ? m.modifiers : [];
      const isStatic = mModifiers.some((mod) => mod.kind === SyntaxKind.StaticKeyword);
      const isReadonly = mModifiers.some((mod) => mod.kind === SyntaxKind.ReadonlyKeyword);
      const isOptional = m.postfixToken !== undefined && m.postfixToken.kind === SyntaxKind.QuestionToken;
      properties.push({
        name: mName,
        isStatic,
        isReadonly,
        isOptional,
      });
    } else if (isMethodDeclaration(m)) {
      const mName = m.name && isIdentifier(m.name) ? m.name.text : undefined;
      const mModifiers = Array.isArray(m.modifiers) ? m.modifiers : [];
      const isStatic = mModifiers.some((mod) => mod.kind === SyntaxKind.StaticKeyword);
      const isAsync = mModifiers.some((mod) => mod.kind === SyntaxKind.AsyncKeyword);
      const parameterCount = Array.isArray(m.parameters) ? m.parameters.length : 0;
      methods.push({
        name: mName,
        isStatic,
        isAsync,
        parameterCount,
      });
    }
  }

  return {
    kind: node.kind,
    kindName: formatSyntaxKind(node.kind),
    isClassDeclaration: true,
    name: rawName,
    isExported,
    isAbstract,
    typeParameterCount: typeParameters.length,
    typeParameters,
    heritageClauseCount: heritageClauses.length,
    extends: extendsName,
    implements: implementsNames,
    memberCount: rawMembers.length,
    properties,
    methods,
    hasConstructor,
  };
}

export {
  createClassDeclaration,
  createMethodDeclaration,
  createConstructorDeclaration,
  createPropertyDeclaration,
  createHeritageClause,
  createExpressionWithTypeArguments,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createTypeParameterDeclaration,
  createParameterDeclaration,
  createBlock,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
  isClassDeclaration,
  isMethodDeclaration,
  isPropertyDeclaration,
  isConstructorDeclaration,
  isHeritageClause,
  isIdentifier,
  isToken,
  isBlock,
  isKeywordTypeNode,
  isTypeReferenceNode,
  SyntaxKind,
  formatSyntaxKind,
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  buildClassDeclaration,
  buildMethodDeclaration,
  buildPropertyDeclaration,
  buildConstructorDeclaration,
  inspectClassDeclaration,
  createClassDeclaration,
  createMethodDeclaration,
  createConstructorDeclaration,
  createPropertyDeclaration,
  createHeritageClause,
  createExpressionWithTypeArguments,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createTypeParameterDeclaration,
  createParameterDeclaration,
  createBlock,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
  isClassDeclaration,
  isMethodDeclaration,
  isPropertyDeclaration,
  isConstructorDeclaration,
  isHeritageClause,
  isIdentifier,
  isToken,
  isBlock,
  isKeywordTypeNode,
  isTypeReferenceNode,
  SyntaxKind,
  formatSyntaxKind,
} from '../src/index.mjs';

// Contract 1: buildClassDeclaration constructs a class declaration AST node with properties and methods and validates it with isClassDeclaration
{
  const idProp = buildPropertyDeclaration('id', 'string', { isReadonly: true });
  const getNameMethod = buildMethodDeclaration('getName', [], 'string', [createReturnStatement(createStringLiteral('"Alice"'))]);

  const clsNode = buildClassDeclaration('User', [idProp, getNameMethod], { isExported: true });

  assert.ok(clsNode, 'Class node should be defined');
  assert.strictEqual(isClassDeclaration(clsNode), true, 'Node should satisfy isClassDeclaration');
  assert.strictEqual(formatSyntaxKind(clsNode.kind), 'ClassDeclaration', 'Kind name should be ClassDeclaration');
  assert.strictEqual(clsNode.members.length, 2, 'Class should contain 2 members');
  assert.strictEqual(isPropertyDeclaration(clsNode.members[0]), true, 'First member should be PropertyDeclaration');
  assert.strictEqual(isMethodDeclaration(clsNode.members[1]), true, 'Second member should be MethodDeclaration');
}

// Contract 2: buildMethodDeclaration constructs method declarations with access modifiers, async keyword, and parameters using createMethodDeclaration
{
  const fetchMethod = buildMethodDeclaration(
    'fetchData',
    [{ name: 'url', type: 'string' }, { name: 'timeout', type: 'number', isOptional: true }],
    'Promise',
    [createReturnStatement(createIdentifier('url'))],
    { access: 'public', isAsync: true }
  );

  assert.ok(fetchMethod, 'Method node should be defined');
  assert.strictEqual(isMethodDeclaration(fetchMethod), true, 'Should satisfy isMethodDeclaration');
  assert.strictEqual(fetchMethod.name.text, 'fetchData', 'Method name should match');
  assert.strictEqual(fetchMethod.parameters.length, 2, 'Should have 2 parameters');
  assert.strictEqual(fetchMethod.parameters[0].name.text, 'url', 'First param name should be url');
  assert.strictEqual(fetchMethod.parameters[1].questionToken.kind, SyntaxKind.QuestionToken, 'Second param should be optional');
  assert.ok(fetchMethod.modifiers.some((m) => m.kind === SyntaxKind.AsyncKeyword), 'Should have AsyncKeyword');
  assert.ok(fetchMethod.modifiers.some((m) => m.kind === SyntaxKind.PublicKeyword), 'Should have PublicKeyword');
}

// Contract 3: buildClassDeclaration constructs class declarations with generic type parameters and heritage clauses (extends and implements)
{
  const processMethod = buildMethodDeclaration('process', [{ name: 'item', type: 'T' }], 'void', []);
  const genericCls = buildClassDeclaration(
    'DataHandler',
    [processMethod],
    {
      isExported: true,
      typeParameters: ['T', 'TResult'],
      extends: 'BaseHandler',
      implements: ['IHandler', 'IDisposable'],
    }
  );

  assert.ok(genericCls, 'Generic class should be defined');
  assert.strictEqual(isClassDeclaration(genericCls), true, 'Should satisfy isClassDeclaration');
  assert.strictEqual(genericCls.typeParameters.length, 2, 'Should have 2 type parameters');
  assert.strictEqual(genericCls.heritageClauses.length, 2, 'Should have 2 heritage clauses');
  assert.strictEqual(isHeritageClause(genericCls.heritageClauses[0]), true, 'First clause is HeritageClause');
  assert.strictEqual(genericCls.heritageClauses[0].token.kind, SyntaxKind.ExtendsKeyword, 'First clause should be ExtendsKeyword');
  assert.strictEqual(genericCls.heritageClauses[1].token.kind, SyntaxKind.ImplementsKeyword, 'Second clause should be ImplementsKeyword');
  assert.strictEqual(genericCls.heritageClauses[1].types.length, 2, 'Implements clause should have 2 types');
}

// Contract 4: inspectClassDeclaration extracts class metadata including name, modifiers, heritage clauses, properties, and methods using type guards
{
  const countProp = buildPropertyDeclaration('instanceCount', 'number', { isStatic: true });
  const nameProp = buildPropertyDeclaration('name', 'string', { isReadonly: true });
  const ctor = buildConstructorDeclaration([{ name: 'name', type: 'string' }], []);
  const saveMethod = buildMethodDeclaration('save', [], 'boolean', [createReturnStatement(createIdentifier('true'))], { access: 'public' });

  const cls = buildClassDeclaration(
    'Repository',
    [countProp, nameProp, ctor, saveMethod],
    {
      isExported: true,
      isAbstract: true,
      typeParameters: ['TEntity'],
      extends: 'BaseRepository',
      implements: ['IRepository'],
    }
  );

  const info = inspectClassDeclaration(cls);
  assert.strictEqual(info.isClassDeclaration, true, 'isClassDeclaration should be true');
  assert.strictEqual(info.kindName, 'ClassDeclaration', 'kindName should be ClassDeclaration');
  assert.strictEqual(info.name, 'Repository', 'name should match Repository');
  assert.strictEqual(info.isExported, true, 'isExported should be true');
  assert.strictEqual(info.isAbstract, true, 'isAbstract should be true');
  assert.strictEqual(info.typeParameterCount, 1, 'typeParameterCount should be 1');
  assert.deepStrictEqual(info.typeParameters, ['TEntity'], 'typeParameters should match [TEntity]');
  assert.strictEqual(info.heritageClauseCount, 2, 'heritageClauseCount should be 2');
  assert.strictEqual(info.extends, 'BaseRepository', 'extends should match BaseRepository');
  assert.deepStrictEqual(info.implements, ['IRepository'], 'implements should match [IRepository]');
  assert.strictEqual(info.memberCount, 4, 'memberCount should be 4');
  assert.strictEqual(info.hasConstructor, true, 'hasConstructor should be true');
  assert.strictEqual(info.properties.length, 2, 'properties count should be 2');
  assert.strictEqual(info.properties[0].name, 'instanceCount', 'First property name should be instanceCount');
  assert.strictEqual(info.properties[0].isStatic, true, 'First property should be static');
  assert.strictEqual(info.properties[1].name, 'name', 'Second property name should be name');
  assert.strictEqual(info.properties[1].isReadonly, true, 'Second property should be readonly');
  assert.strictEqual(info.methods.length, 1, 'methods count should be 1');
  assert.strictEqual(info.methods[0].name, 'save', 'Method name should be save');

  assert.throws(
    () => inspectClassDeclaration(null),
    { name: 'TypeError' },
    'inspectClassDeclaration should throw TypeError on null input'
  );
  assert.throws(
    () => inspectClassDeclaration({ kind: 999 }),
    { name: 'TypeError' },
    'inspectClassDeclaration should throw TypeError on non-ClassDeclaration node'
  );
}

console.log('All pkg:npm/typescript@7.0.2 contracts passed successfully.');

Seeder de origen

anónimo