@theholocron/cli 5.0.0-alpha.252 → 5.0.0-alpha.253

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.mjs +349 -131
  2. package/dist/cli.mjs.map +1 -1
  3. package/package.json +16 -16
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
4
4
  import { LOG_LEVELS, NoopAnalyticsSink, NoopErrorSink, redactObject } from "@theholocron/observability/core";
5
5
  import yargs from "yargs";
6
6
  import { hideBin } from "yargs/helpers";
@@ -5983,7 +5983,7 @@ function deriveDefaults(input) {
5983
5983
  };
5984
5984
  }
5985
5985
  // src/commands/plugin-create/templates/auth.ts
5986
- function render$17(inputs) {
5986
+ function render$16(inputs) {
5987
5987
  return `import { AuthError, createResolveToken, type ResolveTokenInput } from "@theholocron/cli";
5988
5988
 
5989
5989
  export { AuthError };
@@ -6000,10 +6000,10 @@ export const resolveToken = createResolveToken({
6000
6000
  `;
6001
6001
  }
6002
6002
  // src/commands/plugin-create/templates/auth-test.ts
6003
- function render$16(inputs) {
6003
+ function render$15(inputs) {
6004
6004
  return `import { describe, expect, it } from "vitest";
6005
6005
 
6006
- import { AuthError, resolveToken } from "../auth.js";
6006
+ import { AuthError, resolveToken } from "./auth.js";
6007
6007
 
6008
6008
  const noKeyring = () => null;
6009
6009
 
@@ -6051,7 +6051,7 @@ describe("resolveToken", () => {
6051
6051
  `;
6052
6052
  }
6053
6053
  // src/commands/plugin-create/templates/capability.ts
6054
- function render$15(inputs) {
6054
+ function render$14(inputs) {
6055
6055
  const clientClass = `${inputs.vendorName}RestClient`;
6056
6056
  const capabilityInterface = inputs.capability.charAt(0).toUpperCase() + inputs.capability.slice(1);
6057
6057
  return `/**
@@ -6086,13 +6086,13 @@ export class ${inputs.capabilityClass} {
6086
6086
  `;
6087
6087
  }
6088
6088
  // src/commands/plugin-create/templates/capability-test.ts
6089
- function render$14(inputs) {
6089
+ function render$13(inputs) {
6090
6090
  const factoryName = `create${inputs.vendorName}RestClient`;
6091
- return `import { describe, expect, it } from "vitest";
6091
+ return `import { stubFetch } from "@theholocron/http-client/testing";
6092
+ import { describe, expect, it } from "vitest";
6092
6093
 
6093
- import { ${inputs.capabilityClass} } from "../capabilities/${inputs.capability}.js";
6094
6094
  import { ${factoryName} } from "../rest.js";
6095
- import { stubFetch } from "./helpers.js";
6095
+ import { ${inputs.capabilityClass} } from "./${inputs.capability}.js";
6096
6096
 
6097
6097
  // Stub client used by the constructor smoke test. Real capability
6098
6098
  // tests replace this with per-method stubs once implementations land.
@@ -6118,7 +6118,7 @@ describe("${inputs.capabilityClass}", () => {
6118
6118
  `;
6119
6119
  }
6120
6120
  // src/commands/plugin-create/templates/eslint-config.ts
6121
- function render$13(_inputs) {
6121
+ function render$12(_inputs) {
6122
6122
  return `import type { Linter } from "eslint";
6123
6123
 
6124
6124
  import root from "../../eslint.config.js";
@@ -6126,61 +6126,12 @@ import root from "../../eslint.config.js";
6126
6126
  export default [...root, { ignores: ["dist/**", "coverage/**"] }] satisfies Linter.Config[];
6127
6127
  `;
6128
6128
  }
6129
- // src/commands/plugin-create/templates/helpers.ts
6130
- function render$12(_inputs) {
6131
- return `import { vi, type Mock } from "vitest";
6132
-
6133
- export interface FetchCall {
6134
- url: string;
6135
- method: string;
6136
- headers: Record<string, string>;
6137
- body: unknown;
6138
- }
6139
-
6140
- export interface FetchStub {
6141
- fetch: typeof fetch;
6142
- calls: FetchCall[];
6143
- mock: Mock;
6144
- }
6145
-
6146
- export function stubFetch(responses: Array<{ status?: number; body?: unknown; text?: string }>): FetchStub {
6147
- const calls: FetchCall[] = [];
6148
- let i = 0;
6149
- const mock = vi.fn(async (input: string | URL, init?: RequestInit) => {
6150
- const url = typeof input === "string" ? input : input.toString();
6151
- const body = typeof init?.body === "string" ? safeJsonParse(init.body) : (init?.body ?? null);
6152
- calls.push({
6153
- url,
6154
- method: (init?.method ?? "GET").toUpperCase(),
6155
- headers: (init?.headers as Record<string, string>) ?? {},
6156
- body,
6157
- });
6158
- const next = responses[i++] ?? { status: 200, body: {} };
6159
- const status = next.status ?? 200;
6160
- if (status === 204 || status === 205 || status === 304) {
6161
- return new Response(null, { status });
6162
- }
6163
- const text = next.text ?? (typeof next.body === "string" ? next.body : JSON.stringify(next.body ?? {}));
6164
- return new Response(text, { status });
6165
- });
6166
- return { fetch: mock as unknown as typeof fetch, calls, mock };
6167
- }
6168
-
6169
- function safeJsonParse(s: string): unknown {
6170
- try {
6171
- return JSON.parse(s);
6172
- } catch {
6173
- return s;
6174
- }
6175
- }
6176
- `;
6177
- }
6178
6129
  // src/commands/plugin-create/templates/index-test.ts
6179
6130
  function render$11(inputs) {
6180
- return `import { describe, expect, it } from "vitest";
6131
+ return `import { stubFetch } from "@theholocron/http-client/testing";
6132
+ import { describe, expect, it } from "vitest";
6181
6133
 
6182
- import { AUTH_HINT, createPlugin } from "../index.js";
6183
- import { stubFetch } from "./helpers.js";
6134
+ import { AUTH_HINT, createPlugin } from "./index.js";
6184
6135
 
6185
6136
  describe("createPlugin", () => {
6186
6137
  it("wires the ${inputs.capability} capability against the given fetch + token", () => {
@@ -6230,40 +6181,47 @@ function render$10(inputs) {
6230
6181
  import: "./dist/index.mjs",
6231
6182
  default: "./dist/index.mjs"
6232
6183
  } },
6184
+ files: ["dist"],
6233
6185
  scripts: {
6234
6186
  "delivery.build": "tsdown",
6235
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
6236
- "verification.typeSafety": "holocron run verification.typeSafety --",
6237
- "verification.unitTests": "holocron run verification.unitTests --",
6187
+ "sourceQuality.staticAnalysis": "eslint .",
6238
6188
  "test:watch": "vitest",
6239
- validate: "tsx scripts/validate.mjs"
6240
- },
6241
- peerDependencies: {
6242
- "@theholocron/cli": "workspace:*",
6243
- "@theholocron/misc-utils": "catalog:utils"
6189
+ validate: "tsx scripts/validate.mjs",
6190
+ "verification.typeSafety": "tsc --noEmit",
6191
+ "verification.unitTests": "vitest run"
6244
6192
  },
6245
6193
  devDependencies: {
6246
6194
  "@theholocron/cli": "workspace:*",
6247
- "@theholocron/misc-utils": "catalog:utils",
6248
- "@theholocron/tsconfig": "catalog:configs",
6195
+ "@theholocron/eslint-config": "catalog:configs",
6196
+ "@theholocron/http-client": "workspace:^",
6197
+ "@theholocron/misc-utils": "workspace:^",
6198
+ "@theholocron/tsconfig": "workspace:^",
6199
+ "@theholocron/tsdown-config": "workspace:^",
6200
+ "@theholocron/vitest-config": "workspace:^",
6249
6201
  "@types/node": "catalog:",
6250
6202
  "@vitest/coverage-v8": "catalog:",
6203
+ "@vitest/eslint-plugin": "catalog:",
6251
6204
  eslint: "catalog:",
6205
+ "eslint-plugin-n": "catalog:",
6252
6206
  globals: "catalog:",
6253
6207
  tsdown: "catalog:",
6254
6208
  tsx: "catalog:",
6255
6209
  typescript: "catalog:",
6256
6210
  vitest: "catalog:"
6257
6211
  },
6212
+ peerDependencies: {
6213
+ "@theholocron/cli": "workspace:*",
6214
+ "@theholocron/misc-utils": "catalog:utils"
6215
+ },
6258
6216
  engines: { node: ">=22" },
6259
- publishConfig: { access: "public" },
6260
- files: ["dist"]
6217
+ publishConfig: { access: "public" }
6261
6218
  }, null, 2) + "\n";
6262
6219
  }
6263
6220
  // src/commands/plugin-create/templates/plugin-index.ts
6264
6221
  function render$9(inputs) {
6265
6222
  const clientClass = `${inputs.vendorName}RestClient`;
6266
6223
  const factoryName = `create${inputs.vendorName}RestClient`;
6224
+ const restSpecifiers = [`type ${clientClass}`, factoryName].sort((a, b) => a.replace(/^type /, "").localeCompare(b.replace(/^type /, ""), "en")).join(", ");
6267
6225
  const capabilityInterface = inputs.capability.charAt(0).toUpperCase() + inputs.capability.slice(1);
6268
6226
  return `/**
6269
6227
  * \`@theholocron/holocron-plugin-${inputs.slug}\` — entrypoint.
@@ -6280,7 +6238,7 @@ function render$9(inputs) {
6280
6238
 
6281
6239
  import { resolveToken, type ResolveTokenInput } from "./auth.js";
6282
6240
  import { ${inputs.capabilityClass} } from "./capabilities/${inputs.capability}.js";
6283
- import { ${factoryName}, type ${clientClass} } from "./rest.js";
6241
+ import { ${restSpecifiers} } from "./rest.js";
6284
6242
 
6285
6243
  export interface ${inputs.vendorName}PluginOptions extends ResolveTokenInput {
6286
6244
  /** Override base URL for tests. */
@@ -6340,8 +6298,8 @@ export const AUTH_HINT =
6340
6298
  // ── Public re-exports ────────────────────────────────────────────────
6341
6299
 
6342
6300
  export * from "./auth.js";
6343
- export { type ${clientClass}, ${factoryName} } from "./rest.js";
6344
6301
  export { ${inputs.capabilityClass} } from "./capabilities/${inputs.capability}.js";
6302
+ export { ${restSpecifiers} } from "./rest.js";
6345
6303
  export { verifyToken } from "./verify-token.js";
6346
6304
  export type { VerifyTokenFailure, VerifyTokenResult, VerifyTokenSuccess } from "@theholocron/cli";
6347
6305
  `;
@@ -6448,10 +6406,10 @@ export function ${factoryName}(opts: {
6448
6406
  function render$6(inputs) {
6449
6407
  const factoryName = `create${inputs.vendorName}RestClient`;
6450
6408
  return `import { ProviderApiError } from "@theholocron/cli";
6409
+ import { stubFetch } from "@theholocron/http-client/testing";
6451
6410
  import { describe, expect, it } from "vitest";
6452
6411
 
6453
- import { ${factoryName} } from "../rest.js";
6454
- import { stubFetch } from "./helpers.js";
6412
+ import { ${factoryName} } from "./rest.js";
6455
6413
 
6456
6414
  describe("${factoryName}", () => {
6457
6415
  \tit("sends bearer + accept headers and returns the parsed body", async () => {
@@ -6516,16 +6474,13 @@ function render$5(inputs) {
6516
6474
  }, null, 2) + "\n";
6517
6475
  }
6518
6476
  // src/commands/plugin-create/templates/tsdown-config.ts
6477
+ /**
6478
+ * Per-package tsdown config. Only written when the target workspace has no
6479
+ * repo-root `tsdown.config.ts` (tsdown finds that one by walking up from the
6480
+ * package directory); see `plugin-create/index.ts`.
6481
+ */
6519
6482
  function render$4(_inputs) {
6520
- return `import { defineConfig } from "tsdown";
6521
-
6522
- export default defineConfig({
6523
- entry: ["src/index.ts"],
6524
- format: "esm",
6525
- dts: true,
6526
- clean: true,
6527
- deps: { neverBundle: [/^@theholocron\\//] },
6528
- });
6483
+ return `export { default } from "@theholocron/tsdown-config/presets/library";
6529
6484
  `;
6530
6485
  }
6531
6486
  // src/commands/plugin-create/templates/validate-script.ts
@@ -6570,9 +6525,10 @@ function render$3(inputs) {
6570
6525
  * surface. Model on \`plugins/holocron-plugin-infisical/scripts/validate.mjs\`.
6571
6526
  */
6572
6527
 
6528
+ import { errorMessage } from "@theholocron/misc-utils";
6529
+
6573
6530
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- filled in by operator
6574
6531
  import { AuthError, createPlugin, resolveToken, verifyToken } from "../src/index.ts";
6575
- import { errorMessage } from "@theholocron/misc-utils";
6576
6532
 
6577
6533
  const args = process.argv.slice(2);
6578
6534
 
@@ -6719,10 +6675,10 @@ export async function verifyToken(token: string, opts: VerifyTokenOptions = {}):
6719
6675
  }
6720
6676
  // src/commands/plugin-create/templates/verify-token-test.ts
6721
6677
  function render$1(_inputs) {
6722
- return `import { describe, expect, it } from "vitest";
6678
+ return `import { stubFetch } from "@theholocron/http-client/testing";
6679
+ import { describe, expect, it } from "vitest";
6723
6680
 
6724
- import { verifyToken } from "../verify-token.js";
6725
- import { stubFetch } from "./helpers.js";
6681
+ import { verifyToken } from "./verify-token.js";
6726
6682
 
6727
6683
  describe("verifyToken", () => {
6728
6684
  it("returns ok with a subject when /me returns 200", async () => {
@@ -6732,6 +6688,21 @@ describe("verifyToken", () => {
6732
6688
  expect((result as { ok: boolean; subject?: string }).subject).toMatch(/user@example.com/);
6733
6689
  });
6734
6690
 
6691
+ it("falls back to name, then id, then a placeholder for the subject", async () => {
6692
+ const named = stubFetch([{ status: 200, body: { name: "Ada" } }]);
6693
+ expect(await verifyToken("t", { fetch: named.fetch })).toEqual({ ok: true, subject: "user @ Ada" });
6694
+ const ided = stubFetch([{ status: 200, body: { id: "u_1" } }]);
6695
+ expect(await verifyToken("t", { fetch: ided.fetch })).toEqual({ ok: true, subject: "user @ u_1" });
6696
+ const empty = stubFetch([{ status: 200, body: {} }]);
6697
+ expect(await verifyToken("t", { fetch: empty.fetch })).toEqual({ ok: true, subject: "user @ unknown" });
6698
+ });
6699
+
6700
+ it("sends the request to the base URL override", async () => {
6701
+ const stub = stubFetch([{ status: 200, body: { email: "user@example.com" } }]);
6702
+ await verifyToken("token", { baseUrl: "https://override.example", fetch: stub.fetch });
6703
+ expect(stub.calls[0]?.url).toBe("https://override.example/me");
6704
+ });
6705
+
6735
6706
  it("returns ok:false with the error message on 401", async () => {
6736
6707
  const stub = stubFetch([{ status: 401, body: { messages: ["Invalid token"] } }]);
6737
6708
  const result = await verifyToken("bad", { fetch: stub.fetch });
@@ -6752,21 +6723,7 @@ describe("verifyToken", () => {
6752
6723
  }
6753
6724
  // src/commands/plugin-create/templates/vitest-config.ts
6754
6725
  function render(_inputs) {
6755
- return `import { defineConfig } from "vitest/config";
6756
-
6757
- export default defineConfig({
6758
- test: {
6759
- environment: "node",
6760
- globals: false,
6761
- coverage: {
6762
- provider: "v8",
6763
- reporter: ["text", "html", "json-summary"],
6764
- include: ["src/**/*.ts"],
6765
- exclude: ["src/**/__tests__/**", "src/**/*.test.ts", "src/index.ts"],
6766
- thresholds: { lines: 0, functions: 0, branches: 0, statements: 0 },
6767
- },
6768
- },
6769
- });
6726
+ return `export { default } from "@theholocron/vitest-config/bundles/library";
6770
6727
  `;
6771
6728
  }
6772
6729
  // src/commands/plugin-create/index.ts
@@ -6783,9 +6740,11 @@ export default defineConfig({
6783
6740
  * 3. Capability sanity — must be one of the 14 known keys; warn for
6784
6741
  * many-cardinality caps.
6785
6742
  * 4. Generate — for each template, write to
6786
- * plugins/holocron-plugin-<slug>/<path>.
6743
+ * plugins/holocron-plugin-<slug>/<path>. Tests sit beside their source;
6744
+ * tsdown.config.ts is written only when the workspace has no root one.
6787
6745
  * 5. Verify (unless --no-verify) — runs pnpm install +
6788
- * pnpm --filter <pkg> typecheck lint test.
6746
+ * pnpm --filter <pkg> verification.typeSafety, sourceQuality.staticAnalysis,
6747
+ * verification.unitTests.
6789
6748
  * 6. Print next steps.
6790
6749
  */
6791
6750
  /**
@@ -6818,11 +6777,12 @@ const TEMPLATES = [
6818
6777
  },
6819
6778
  {
6820
6779
  path: "eslint.config.ts",
6821
- render: render$13
6780
+ render: render$12
6822
6781
  },
6823
6782
  {
6824
6783
  path: "tsdown.config.ts",
6825
- render: render$4
6784
+ render: render$4,
6785
+ when: (cwd) => !hasRootTsdownConfig(cwd)
6826
6786
  },
6827
6787
  {
6828
6788
  path: "README.md",
@@ -6830,7 +6790,7 @@ const TEMPLATES = [
6830
6790
  },
6831
6791
  {
6832
6792
  path: "src/auth.ts",
6833
- render: render$17
6793
+ render: render$16
6834
6794
  },
6835
6795
  {
6836
6796
  path: "src/rest.ts",
@@ -6846,30 +6806,26 @@ const TEMPLATES = [
6846
6806
  },
6847
6807
  {
6848
6808
  path: "src/capabilities/{{capability}}.ts",
6849
- render: render$15
6850
- },
6851
- {
6852
- path: "src/__tests__/helpers.ts",
6853
- render: render$12
6809
+ render: render$14
6854
6810
  },
6855
6811
  {
6856
- path: "src/__tests__/auth.test.ts",
6857
- render: render$16
6812
+ path: "src/auth.test.ts",
6813
+ render: render$15
6858
6814
  },
6859
6815
  {
6860
- path: "src/__tests__/rest.test.ts",
6816
+ path: "src/rest.test.ts",
6861
6817
  render: render$6
6862
6818
  },
6863
6819
  {
6864
- path: "src/__tests__/verify-token.test.ts",
6820
+ path: "src/verify-token.test.ts",
6865
6821
  render: render$1
6866
6822
  },
6867
6823
  {
6868
- path: "src/__tests__/{{capability}}.test.ts",
6869
- render: render$14
6824
+ path: "src/capabilities/{{capability}}.test.ts",
6825
+ render: render$13
6870
6826
  },
6871
6827
  {
6872
- path: "src/__tests__/index.test.ts",
6828
+ path: "src/index.test.ts",
6873
6829
  render: render$11
6874
6830
  },
6875
6831
  {
@@ -6877,6 +6833,10 @@ const TEMPLATES = [
6877
6833
  render: render$3
6878
6834
  }
6879
6835
  ];
6836
+ /** Whether the workspace root carries the shared `tsdown.config.ts`. */
6837
+ function hasRootTsdownConfig(cwd) {
6838
+ return existsSync(path.join(cwd, "tsdown.config.ts"));
6839
+ }
6880
6840
  /** Replace `{{capability}}` in a template path with the actual capability key. */
6881
6841
  function resolvePath(template, inputs) {
6882
6842
  return template.replace(/\{\{capability\}\}/g, inputs.capability);
@@ -6908,6 +6868,7 @@ function runPluginCreate(input) {
6908
6868
  baseUrl: trimTrailingSlashes(input.baseUrl),
6909
6869
  transport: derived.transport
6910
6870
  };
6871
+ const templates = TEMPLATES.filter((template) => template.when?.(cwd) ?? true);
6911
6872
  const filesWritten = [];
6912
6873
  print(`Scaffolding @theholocron/holocron-plugin-${inputs.slug}${input.dryRun ? " (dry-run)" : ""}`);
6913
6874
  print(` → ${packageDir}`);
@@ -6916,7 +6877,7 @@ function runPluginCreate(input) {
6916
6877
  capability: inputs.capability,
6917
6878
  dryRun: input.dryRun || void 0
6918
6879
  }, "plugin create: start");
6919
- for (const template of TEMPLATES) {
6880
+ for (const template of templates) {
6920
6881
  const resolvedPath = resolvePath(template.path, inputs);
6921
6882
  const filepath = path.join(packageDir, resolvedPath);
6922
6883
  const content = template.render(inputs);
@@ -6979,7 +6940,7 @@ function runPluginCreate(input) {
6979
6940
  };
6980
6941
  }
6981
6942
  }
6982
- if (!input.dryRun) printNextSteps$1(print, inputs);
6943
+ if (!input.dryRun) printNextSteps$1(print, inputs, filesWritten.length);
6983
6944
  logger.info({
6984
6945
  slug: inputs.slug,
6985
6946
  capability: inputs.capability,
@@ -7035,17 +6996,17 @@ function defaultExec$3(cmd, args, opts) {
7035
6996
  stdio: opts.stdio
7036
6997
  });
7037
6998
  }
7038
- function printNextSteps$1(print, inputs) {
6999
+ function printNextSteps$1(print, inputs, filesCount) {
7039
7000
  print("");
7040
- print(` Scaffolded @theholocron/holocron-plugin-${inputs.slug} (18 files).`);
7001
+ print(` Scaffolded @theholocron/holocron-plugin-${inputs.slug} (${filesCount} files).`);
7041
7002
  print("");
7042
7003
  print(" Next:");
7043
7004
  print(` 1. pnpm install # picks up the workspace package`);
7044
- print(` 2. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} typecheck # green`);
7045
- print(` 3. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} lint # green`);
7046
- print(` 4. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} test # green (stubs pass, real tests are it.todo)`);
7005
+ print(` 2. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} verification.typeSafety # green`);
7006
+ print(` 3. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} sourceQuality.staticAnalysis # green`);
7007
+ print(` 4. pnpm --filter @theholocron/holocron-plugin-${inputs.slug} verification.unitTests # green (stubs pass, real tests are it.todo)`);
7047
7008
  print(` 5. Implement ${inputs.capabilityClass} methods in src/capabilities/${inputs.capability}.ts`);
7048
- print(` 6. Replace it.todo(...) with real tests in src/__tests__/${inputs.capability}.test.ts`);
7009
+ print(` 6. Replace it.todo(...) with real tests in src/capabilities/${inputs.capability}.test.ts`);
7049
7010
  print(" 7. Commit + push when capability is functionally complete.");
7050
7011
  }
7051
7012
  // src/commands/plugin-create/plugin-create.args.ts
@@ -10180,6 +10141,262 @@ function coreProbes(loader, builtIn = /* @__PURE__ */ new Map()) {
10180
10141
  }
10181
10142
  } };
10182
10143
  }
10144
+ // src/commands/probe/docs-coverage/count-symbols.ts
10145
+ /** TypeDoc's `ReflectionKind` numbers for the kinds that should be documented, by name. */
10146
+ const KINDS = {
10147
+ 8: "Enum",
10148
+ 32: "Variable",
10149
+ 64: "Function",
10150
+ 128: "Class",
10151
+ 256: "Interface",
10152
+ 1024: "Property",
10153
+ 2048: "Method",
10154
+ 262144: "Accessor",
10155
+ 2097152: "TypeAlias"
10156
+ };
10157
+ function hasComment(comment) {
10158
+ return Boolean(comment?.summary?.length || comment?.blockTags?.length);
10159
+ }
10160
+ function isDocumented(r) {
10161
+ return hasComment(r.comment) || (r.signatures ?? []).some((s) => hasComment(s.comment)) || hasComment(r.getSignature?.comment) || hasComment(r.setSignature?.comment);
10162
+ }
10163
+ /**
10164
+ * The symbols a package exports that should carry a doc comment, from TypeDoc's JSON model: functions, classes,
10165
+ * interfaces, type aliases, variables, enums, and the public members of those. Private, inherited and external
10166
+ * members are not counted. `fallbackFile` stands in for a symbol TypeDoc gives no source for.
10167
+ */
10168
+ function countSymbols(children, fallbackFile) {
10169
+ const out = [];
10170
+ const walk = (r) => {
10171
+ const kind = KINDS[r.kind];
10172
+ if (kind && !r.flags?.isPrivate && !r.flags?.isExternal && !r.inheritedFrom) {
10173
+ const source = r.sources?.[0] ?? r.signatures?.[0]?.sources?.[0];
10174
+ out.push({
10175
+ kind,
10176
+ name: r.name,
10177
+ file: source?.fileName ?? fallbackFile,
10178
+ line: source?.line ?? 1,
10179
+ documented: isDocumented(r)
10180
+ });
10181
+ }
10182
+ for (const child of r.children ?? []) walk(child);
10183
+ for (const child of r.type?.declaration?.children ?? []) walk(child);
10184
+ };
10185
+ for (const child of children ?? []) walk(child);
10186
+ return out;
10187
+ }
10188
+ // src/commands/probe/docs-coverage/added-lines.ts
10189
+ /**
10190
+ * The lines a unified diff (`git diff -U0`) adds or changes, by file: from each hunk header
10191
+ * `@@ -a,b +c,d @@`, the new-file lines `c` … `c + d - 1` (a missing `d` is one line, `0` is a pure deletion).
10192
+ */
10193
+ function addedLines(diff) {
10194
+ const out = /* @__PURE__ */ new Map();
10195
+ let file;
10196
+ for (const line of diff.split("\n")) {
10197
+ if (line.startsWith("+++ ")) {
10198
+ file = line === "+++ /dev/null" ? void 0 : line.replace(/^\+\+\+ b\//, "");
10199
+ continue;
10200
+ }
10201
+ const hunk = /^@@ -\S+ \+(\d+)(?:,(\d+))? @@/.exec(line);
10202
+ if (!hunk || !file) continue;
10203
+ const start = Number(hunk[1]);
10204
+ const count = hunk[2] === void 0 ? 1 : Number(hunk[2]);
10205
+ const lines = out.get(file) ?? /* @__PURE__ */ new Set();
10206
+ for (let i = 0; i < count; i++) lines.add(start + i);
10207
+ out.set(file, lines);
10208
+ }
10209
+ return out;
10210
+ }
10211
+ // src/commands/probe/docs-coverage/measure-docs-coverage.ts
10212
+ /** Where a package's public API starts: `src/index.ts`, or `index.ts` for a flat layout. */
10213
+ const ENTRIES = ["src/index.ts", "index.ts"];
10214
+ function workspaceEntries(repoRoot) {
10215
+ return discoverWorkspacePackages(repoRoot).flatMap(({ name, dir, relativeDir, manifest }) => {
10216
+ const entry = ENTRIES.find((e) => existsSync(join(dir, e)));
10217
+ if (!name || manifest.private || !entry) return [];
10218
+ const tsconfig = join(dir, "tsconfig.json");
10219
+ return [{
10220
+ name,
10221
+ dir: relativeDir,
10222
+ entry: join(dir, entry),
10223
+ ...existsSync(tsconfig) ? { tsconfig } : {}
10224
+ }];
10225
+ });
10226
+ }
10227
+ /** The doc-comment coverage of every public package: one TypeDoc pass per entry point, sorted by directory. */
10228
+ function measureDocsCoverage(input) {
10229
+ return (input.packages ?? workspaceEntries(input.repoRoot)).filter(({ dir }) => input.only?.(dir) ?? true).map(({ name, dir, entry, tsconfig }) => ({
10230
+ name,
10231
+ dir,
10232
+ symbols: countSymbols(input.typedoc(entry, tsconfig).children, `${dir}/src/index.ts`)
10233
+ })).sort((a, b) => a.dir.localeCompare(b.dir));
10234
+ }
10235
+ // src/commands/probe/docs-coverage/to-lcov.ts
10236
+ /**
10237
+ * The documented/undocumented symbols as an lcov report, one `DA` line per symbol (hit when it has a doc
10238
+ * comment), so a coverage service reads doc coverage like line coverage and can show it for the lines a PR changes.
10239
+ */
10240
+ function toLcov(packages) {
10241
+ const byFile = /* @__PURE__ */ new Map();
10242
+ for (const { symbols } of packages) for (const { file, line, documented } of symbols) {
10243
+ const lines = byFile.get(file) ?? /* @__PURE__ */ new Map();
10244
+ lines.set(line, (lines.get(line) ?? true) && documented);
10245
+ byFile.set(file, lines);
10246
+ }
10247
+ const out = ["TN:"];
10248
+ for (const [file, lines] of [...byFile].sort(([a], [b]) => a.localeCompare(b))) {
10249
+ const sorted = [...lines].sort(([a], [b]) => a - b);
10250
+ out.push(`SF:${file}`);
10251
+ for (const [line, documented] of sorted) out.push(`DA:${line},${documented ? 1 : 0}`);
10252
+ out.push(`LF:${sorted.length}`, `LH:${sorted.filter(([, d]) => d).length}`, "end_of_record");
10253
+ }
10254
+ return `${out.join("\n")}\n`;
10255
+ }
10256
+ // src/commands/probe/docs-coverage/docs-coverage-probes.ts
10257
+ /** The group of probes that report how much of the public API carries doc comments. */
10258
+ const DOCS_PROVIDER = "docs";
10259
+ /** Runs the repo's own TypeDoc on one entry point and reads its JSON model. */
10260
+ function runTypedoc(repoRoot) {
10261
+ /* v8 ignore start -- spawns the real TypeDoc; the probes are tested with an injected one */
10262
+ return (entry, tsconfig) => {
10263
+ const bin = join(dirname(createRequire(join(repoRoot, "package.json")).resolve("typedoc/package.json")), "bin/typedoc");
10264
+ const out = join(mkdtempSync(join(tmpdir(), "docs-coverage-")), "model.json");
10265
+ execFileSync(process.execPath, [
10266
+ bin,
10267
+ ...[
10268
+ "--entryPoints",
10269
+ entry,
10270
+ "--json",
10271
+ out,
10272
+ "--basePath",
10273
+ repoRoot,
10274
+ "--skipErrorChecking"
10275
+ ],
10276
+ ...[
10277
+ "--logLevel",
10278
+ "None",
10279
+ "--excludeExternals",
10280
+ "--exclude",
10281
+ "**/*.test.ts"
10282
+ ],
10283
+ ...tsconfig ? ["--tsconfig", tsconfig] : []
10284
+ ], {
10285
+ cwd: repoRoot,
10286
+ stdio: "pipe"
10287
+ });
10288
+ return JSON.parse(readFileSync(out, "utf8"));
10289
+ };
10290
+ /* v8 ignore stop */
10291
+ }
10292
+ /** The diff of the PR's `.ts` files against the base (`BASE_SHA`, or the merge base with `origin/alpha`). */
10293
+ function realDiff(repoRoot) {
10294
+ /* v8 ignore start -- runs the real git; the probe is tested with an injected diff */
10295
+ return () => {
10296
+ const base = process.env["BASE_SHA"] || "origin/alpha";
10297
+ return execFileSync("git", [
10298
+ "diff",
10299
+ "-U0",
10300
+ "--no-color",
10301
+ `${base}...HEAD`,
10302
+ "--",
10303
+ "*.ts"
10304
+ ], {
10305
+ cwd: repoRoot,
10306
+ encoding: "utf8",
10307
+ maxBuffer: 67108864
10308
+ });
10309
+ };
10310
+ /* v8 ignore stop */
10311
+ }
10312
+ function percent(documented, total) {
10313
+ return `${total === 0 ? 100 : Math.round(100 * documented / total)}%`;
10314
+ }
10315
+ function summarise$1(ctx, packages) {
10316
+ let total = 0;
10317
+ let documented = 0;
10318
+ ctx.say({
10319
+ status: "heading",
10320
+ label: "Documented exports"
10321
+ });
10322
+ for (const { dir, symbols } of packages) {
10323
+ const done = symbols.filter((s) => s.documented).length;
10324
+ total += symbols.length;
10325
+ documented += done;
10326
+ ctx.say({
10327
+ status: "info",
10328
+ label: dir,
10329
+ detail: `${done}/${symbols.length} (${percent(done, symbols.length)})`
10330
+ });
10331
+ }
10332
+ ctx.say({
10333
+ status: documented === total ? "ok" : "info",
10334
+ label: "total",
10335
+ detail: `${documented}/${total} (${percent(documented, total)})`
10336
+ });
10337
+ }
10338
+ /**
10339
+ * `docs coverage`: how much of each public package's exported API has a doc comment (functions, classes, interfaces,
10340
+ * types, constants and their public members), measured with the repo's TypeDoc. `docs lcov` writes the same
10341
+ * numbers as `coverage/docs.lcov`, for a coverage service to read. `docs patch` fails for each export a PR adds or
10342
+ * changes without a doc comment, which is the check CI runs.
10343
+ */
10344
+ function docsCoverageProbes(repoRoot, typedoc = runTypedoc(repoRoot), diff = realDiff(repoRoot)) {
10345
+ const measure = () => measureDocsCoverage({
10346
+ repoRoot,
10347
+ typedoc
10348
+ });
10349
+ return {
10350
+ coverage: {
10351
+ summary: "Show how much of each package's exported API has a doc comment.",
10352
+ writes: false,
10353
+ async run(ctx) {
10354
+ summarise$1(ctx, measure());
10355
+ }
10356
+ },
10357
+ patch: {
10358
+ summary: "Fail for each export a PR adds or changes that has no doc comment (against BASE_SHA).",
10359
+ writes: false,
10360
+ async run(ctx) {
10361
+ const added = addedLines(diff());
10362
+ const touched = (dir) => [...added.keys()].some((file) => file.startsWith(`${dir}/`));
10363
+ const missing = measureDocsCoverage({
10364
+ repoRoot,
10365
+ typedoc,
10366
+ only: touched
10367
+ }).flatMap(({ symbols }) => symbols).filter((s) => added.get(s.file)?.has(s.line));
10368
+ const undocumented = missing.filter((s) => !s.documented);
10369
+ ctx.say({
10370
+ status: "heading",
10371
+ label: "Exports this PR adds or changes"
10372
+ });
10373
+ for (const { file, line, kind, name } of undocumented) ctx.say({
10374
+ status: "fail",
10375
+ label: `${file}:${line}`,
10376
+ detail: `${kind} ${name} has no doc comment`
10377
+ });
10378
+ if (undocumented.length === 0) ctx.say({
10379
+ status: "ok",
10380
+ label: `${missing.length} checked`,
10381
+ detail: "every one has a doc comment"
10382
+ });
10383
+ }
10384
+ },
10385
+ lcov: {
10386
+ summary: "Write coverage/docs.lcov: the doc-comment coverage as an lcov report.",
10387
+ writes: true,
10388
+ async run(ctx) {
10389
+ const packages = measure();
10390
+ const file = join(repoRoot, "coverage", "docs.lcov");
10391
+ await ctx.write(`write ${file}`, async () => {
10392
+ mkdirSync(dirname(file), { recursive: true });
10393
+ writeFileSync(file, toLcov(packages));
10394
+ });
10395
+ summarise$1(ctx, packages);
10396
+ }
10397
+ }
10398
+ };
10399
+ }
10183
10400
  // src/commands/probe/list-probes.ts
10184
10401
  /** The listing `holocron probe` prints: each provider, and under it each probe with its summary; writers are marked. */
10185
10402
  function listProbes(groups) {
@@ -10363,6 +10580,7 @@ async function runProbeCommand(input) {
10363
10580
  });
10364
10581
  groups.set(CORE_PROVIDER, coreProbes(loader, /* @__PURE__ */ new Map([[COMLINK_PROVIDER, comlink]])));
10365
10582
  groups.set(COMLINK_PROVIDER, comlink);
10583
+ groups.set(DOCS_PROVIDER, docsCoverageProbes(input.context.repoRoot, input.typedoc));
10366
10584
  if (!input.provider) {
10367
10585
  if (input.pick) await input.pick(groups);
10368
10586
  else for (const line of listProbes(groups)) print(line);