CodeSampleX

サンプル

typescript 7.0.2: createMethodDeclaration

検証済みサンプル — npm typescript 7.0.2: createMethodDeclaration. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: buildMethodDeclaration constructs a…

sha256:918f66ce59eeb495c3b132e47b33d43105a72a730c971b74d00e5900234b7058

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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

ケース

HOW
ゴール
verify typescript.createMethodDeclaration in pkg:npm/typescript@7.0.2
パッケージ
シンボル
  • typescript.createMethodDeclaration
作成日
2026-08-28T07:25:01Z

コントラクト

  1. buildMethodDeclaration constructs a method declaration AST node with parameters, return type, and body block, and validates it with isMethodDeclaration
  2. buildMethodDeclaration supports access modifiers (public, private, protected), static, async, and abstract modifiers
  3. buildMethodDeclaration supports generator methods with asterisk tokens and generic type parameters
  4. inspectMethodDeclaration extracts method metadata including name, modifiers, type parameters, parameters, and whether it has a body, throwing TypeError on invalid nodes

ファイル

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

ソースアーティファクトをダウンロード (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.createMethodDeclaration in pkg:npm/typescript@7.0.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@7.0.2
Demonstrate these symbols/APIs:
  - typescript.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:82ec7785f52ecade55a9dc76ffdeef86c0398e9aca9e86eee13f1956a68da2f1","contract":["buildMethodDeclaration constructs a method declaration AST node with parameters, return type, and body block, and validates it with isMethodDeclaration","buildMethodDeclaration supports access modifiers (public, private, protected), static, async, and abstract modifiers","buildMethodDeclaration supports generator methods with asterisk tokens and generic type parameters","inspectMethodDeclaration extracts method metadata including name, modifiers, type parameters, parameters, and whether it has a body, throwing TypeError on invalid nodes"],"goal":"verify typescript.createMethodDeclaration in pkg:npm/typescript@7.0.2","kind":"HOW","packages":["pkg:npm/typescript@7.0.2"],"schemaVersion":1,"symbols":["typescript.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,"subject":"pkg:npm/typescript@7.0.2","symbols":["typescript.createMethodDeclaration"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "typescript-create-method-declaration-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "typescript-create-method-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-create-method-declaration-sample",
  "version": "1.0.0",
  "description": "Construct and validate TypeScript method declarations using 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": "verify typescript.createMethodDeclaration in pkg:npm/typescript@7.0.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@7.0.2"
  ],
  "symbols": [
    "typescript.createMethodDeclaration"
  ]
}
src/index.mjs
import {
  createMethodDeclaration,
  createParameterDeclaration,
  createTypeParameterDeclaration,
  createBlock,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
} from 'typescript/unstable/ast/factory';

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

/**
 * Converts a type name string or AST TypeNode into a TypeNode.
 *
 * @param {string | object} [type] - Type descriptor 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 a parameter descriptor or string.
 *
 * @param {string | object} param - Parameter name or descriptor.
 * @returns {object} ParameterDeclaration 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> | null} [bodyStatements=[]] - Statements for the method body, or null/undefined for abstract/signature methods.
 * @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.
 * @param {boolean} [options.isAbstract=false] - Whether method is abstract.
 * @param {boolean} [options.isGenerator=false] - Whether method is a generator method (*).
 * @param {boolean} [options.isOptional=false] - Whether method is optional (?).
 * @param {Array<string | object>} [options.typeParameters] - Generic type parameters.
 * @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);

  let bodyBlock = undefined;
  if (Array.isArray(bodyStatements)) {
    bodyBlock = createBlock(bodyStatements, true);
  } else if (bodyStatements && typeof bodyStatements === 'object' && isBlock(bodyStatements)) {
    bodyBlock = bodyStatements;
  }

  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));
  }
  if (options.isAbstract) {
    modifiers.push(createToken(SyntaxKind.AbstractKeyword));
  }

  const asteriskToken = options.isGenerator ? createToken(SyntaxKind.AsteriskToken) : undefined;
  const questionToken = options.isOptional ? createToken(SyntaxKind.QuestionToken) : undefined;

  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);
    });
  }

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

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

  const rawName = node.name && isIdentifier(node.name) ? node.name.text : undefined;
  const modifiers = Array.isArray(node.modifiers) ? node.modifiers : [];
  const isPublic = modifiers.some((m) => m.kind === SyntaxKind.PublicKeyword);
  const isPrivate = modifiers.some((m) => m.kind === SyntaxKind.PrivateKeyword);
  const isProtected = modifiers.some((m) => m.kind === SyntaxKind.ProtectedKeyword);
  const isStatic = modifiers.some((m) => m.kind === SyntaxKind.StaticKeyword);
  const isAsync = modifiers.some((m) => m.kind === SyntaxKind.AsyncKeyword);
  const isAbstract = modifiers.some((m) => m.kind === SyntaxKind.AbstractKeyword);

  const isGenerator = node.asteriskToken !== undefined && node.asteriskToken.kind === SyntaxKind.AsteriskToken;
  const isOptional =
    (node.postfixToken !== undefined && node.postfixToken.kind === SyntaxKind.QuestionToken) ||
    (node.questionToken !== undefined && node.questionToken.kind === SyntaxKind.QuestionToken);

  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);
      }
    }
  }

  const rawParameters = Array.isArray(node.parameters) ? node.parameters : [];
  const parameters = rawParameters.map((p) => {
    const pName = p.name && isIdentifier(p.name) ? p.name.text : undefined;
    const pOptional =
      (p.postfixToken !== undefined && p.postfixToken.kind === SyntaxKind.QuestionToken) ||
      (p.questionToken !== undefined && p.questionToken.kind === SyntaxKind.QuestionToken);
    return {
      name: pName,
      isOptional: pOptional,
    };
  });

  return {
    kind: node.kind,
    kindName: formatSyntaxKind(node.kind),
    isMethodDeclaration: true,
    name: rawName,
    isPublic,
    isPrivate,
    isProtected,
    isStatic,
    isAsync,
    isAbstract,
    isGenerator,
    isOptional,
    typeParameterCount: typeParameters.length,
    typeParameters,
    parameterCount: parameters.length,
    parameters,
    hasBody: node.body !== undefined && isBlock(node.body),
  };
}

export {
  createMethodDeclaration,
  createParameterDeclaration,
  createTypeParameterDeclaration,
  createBlock,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
  SyntaxKind,
  formatSyntaxKind,
  isMethodDeclaration,
  isIdentifier,
  isToken,
  isBlock,
  isKeywordTypeNode,
  isTypeReferenceNode,
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  buildMethodDeclaration,
  inspectMethodDeclaration,
  createMethodDeclaration,
  createParameterDeclaration,
  createTypeParameterDeclaration,
  createBlock,
  createIdentifier,
  createToken,
  createKeywordTypeNode,
  createTypeReferenceNode,
  createReturnStatement,
  createStringLiteral,
  createNumericLiteral,
  SyntaxKind,
  formatSyntaxKind,
  isMethodDeclaration,
  isIdentifier,
  isToken,
  isBlock,
  isKeywordTypeNode,
  isTypeReferenceNode,
} from '../src/index.mjs';

// Contract 1: buildMethodDeclaration constructs a method declaration AST node with parameters, return type, and body block, and validates it with isMethodDeclaration
{
  const returnStmt = createReturnStatement(createStringLiteral('hello'));
  const methodNode = buildMethodDeclaration(
    'greet',
    [{ name: 'user', type: 'string' }],
    'string',
    [returnStmt]
  );

  assert.ok(methodNode, 'Method node should be defined');
  assert.strictEqual(isMethodDeclaration(methodNode), true, 'Node should satisfy isMethodDeclaration');
  assert.strictEqual(formatSyntaxKind(methodNode.kind), 'MethodDeclaration', 'Kind name should be MethodDeclaration');
  assert.strictEqual(methodNode.name.text, 'greet', 'Method name should be greet');
  assert.strictEqual(methodNode.parameters.length, 1, 'Method should have 1 parameter');
  assert.strictEqual(methodNode.parameters[0].name.text, 'user', 'Parameter name should be user');
  assert.ok(methodNode.body, 'Method should have body');
  assert.strictEqual(isBlock(methodNode.body), true, 'Body should be a Block node');
  assert.strictEqual(methodNode.body.statements.length, 1, 'Body should contain 1 statement');
}

// Contract 2: buildMethodDeclaration supports access modifiers (public, private, protected), static, async, and abstract modifiers
{
  const asyncMethod = buildMethodDeclaration(
    'fetchData',
    [{ name: 'url', type: 'string' }, { name: 'retries', type: 'number', isOptional: true }],
    'Promise',
    [createReturnStatement(createIdentifier('url'))],
    { access: 'public', isStatic: true, isAsync: true }
  );

  assert.ok(asyncMethod, 'Async static method node should be defined');
  assert.strictEqual(isMethodDeclaration(asyncMethod), true, 'Should satisfy isMethodDeclaration');
  assert.strictEqual(asyncMethod.modifiers.length, 3, 'Should have 3 modifiers');
  assert.ok(asyncMethod.modifiers.some((m) => m.kind === SyntaxKind.PublicKeyword), 'Should have PublicKeyword');
  assert.ok(asyncMethod.modifiers.some((m) => m.kind === SyntaxKind.StaticKeyword), 'Should have StaticKeyword');
  assert.ok(asyncMethod.modifiers.some((m) => m.kind === SyntaxKind.AsyncKeyword), 'Should have AsyncKeyword');

  const abstractMethod = buildMethodDeclaration(
    'processInput',
    [{ name: 'input', type: 'any' }],
    'boolean',
    null,
    { access: 'protected', isAbstract: true }
  );

  assert.ok(abstractMethod, 'Abstract method node should be defined');
  assert.strictEqual(isMethodDeclaration(abstractMethod), true, 'Should satisfy isMethodDeclaration');
  assert.strictEqual(abstractMethod.body, undefined, 'Abstract method should have no body');
  assert.ok(abstractMethod.modifiers.some((m) => m.kind === SyntaxKind.ProtectedKeyword), 'Should have ProtectedKeyword');
  assert.ok(abstractMethod.modifiers.some((m) => m.kind === SyntaxKind.AbstractKeyword), 'Should have AbstractKeyword');
}

// Contract 3: buildMethodDeclaration supports generator methods with asterisk tokens and generic type parameters
{
  const genMethod = buildMethodDeclaration(
    'generateEntries',
    [{ name: 'limit', type: 'number' }],
    'Generator',
    [],
    { isGenerator: true, typeParameters: ['TItem', 'TContext'] }
  );

  assert.ok(genMethod, 'Generator method should be defined');
  assert.strictEqual(isMethodDeclaration(genMethod), true, 'Should satisfy isMethodDeclaration');
  assert.ok(genMethod.asteriskToken, 'Asterisk token should be present');
  assert.strictEqual(genMethod.asteriskToken.kind, SyntaxKind.AsteriskToken, 'Asterisk token kind should match');
  assert.strictEqual(genMethod.typeParameters.length, 2, 'Should have 2 type parameters');
  assert.strictEqual(genMethod.typeParameters[0].name.text, 'TItem', 'First type param is TItem');
  assert.strictEqual(genMethod.typeParameters[1].name.text, 'TContext', 'Second type param is TContext');
}

// Contract 4: inspectMethodDeclaration extracts method metadata including name, modifiers, type parameters, parameters, and whether it has a body, throwing TypeError on invalid nodes
{
  const testMethod = buildMethodDeclaration(
    'executeTask',
    [{ name: 'taskId', type: 'string' }, { name: 'options', isOptional: true }],
    'void',
    [createReturnStatement(undefined)],
    { access: 'private', isAsync: true, isOptional: true, typeParameters: ['TResult'] }
  );

  const info = inspectMethodDeclaration(testMethod);
  assert.strictEqual(info.isMethodDeclaration, true, 'isMethodDeclaration should be true');
  assert.strictEqual(info.kindName, 'MethodDeclaration', 'kindName should be MethodDeclaration');
  assert.strictEqual(info.name, 'executeTask', 'name should match executeTask');
  assert.strictEqual(info.isPrivate, true, 'isPrivate should be true');
  assert.strictEqual(info.isPublic, false, 'isPublic should be false');
  assert.strictEqual(info.isAsync, true, 'isAsync should be true');
  assert.strictEqual(info.isOptional, true, 'isOptional should be true');
  assert.strictEqual(info.isGenerator, false, 'isGenerator should be false');
  assert.strictEqual(info.typeParameterCount, 1, 'typeParameterCount should be 1');
  assert.deepStrictEqual(info.typeParameters, ['TResult'], 'typeParameters should match [TResult]');
  assert.strictEqual(info.parameterCount, 2, 'parameterCount should be 2');
  assert.strictEqual(info.parameters[0].name, 'taskId', 'First parameter name is taskId');
  assert.strictEqual(info.parameters[0].isOptional, false, 'First parameter is not optional');
  assert.strictEqual(info.parameters[1].name, 'options', 'Second parameter name is options');
  assert.strictEqual(info.parameters[1].isOptional, true, 'Second parameter is optional');
  assert.strictEqual(info.hasBody, true, 'hasBody should be true');

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

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

オリジンシーダー

匿名