@mark1russell7/conventions 0.36.2 → 0.37.1

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawnSync } from "node:child_process";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
4
  import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
5
5
  import { createHash } from "node:crypto";
6
6
  import { parseAllDocuments } from "yaml";
@@ -12,7 +12,7 @@ const RULE_FIELDS = [
12
12
  "generated",
13
13
  "reason"
14
14
  ];
15
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
16
  const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
17
17
  /** This function gives the options of a rule with their defaults. */
18
18
  function defaultOptions(rule) {
@@ -32,18 +32,18 @@ function parseConfig(value, rules) {
32
32
  options: defaultOptions(rule)
33
33
  };
34
34
  if (value === void 0) return { rules: result };
35
- if (!isObject(value)) throw new Error("The field conventions of package.json must be an object.");
35
+ if (!isObject$1(value)) throw new Error("The field conventions of package.json must be an object.");
36
36
  const unknown = Object.keys(value).filter((key) => key !== "packages" && key !== "rules" && key !== "$comment");
37
37
  if (unknown.length > 0) throw new Error(`conventions has unknown fields: ${unknown.join(", ")}.`);
38
38
  const packages = value["packages"];
39
39
  if (packages !== void 0 && !isStrings(packages)) throw new Error("conventions.packages must be an array of globs.");
40
40
  const rulesValue = value["rules"] ?? {};
41
- if (!isObject(rulesValue)) throw new Error("conventions.rules must be an object, with a rule id for each key.");
41
+ if (!isObject$1(rulesValue)) throw new Error("conventions.rules must be an object, with a rule id for each key.");
42
42
  for (const [id, entry] of Object.entries(rulesValue)) {
43
43
  const rule = byId.get(id);
44
44
  if (rule === void 0) throw new Error(`conventions.rules has an unknown rule: ${id}. The rules are: ${[...byId.keys()].join(", ")}.`);
45
45
  const where = `conventions.rules["${id}"]`;
46
- if (!isObject(entry)) throw new Error(`${where} must be an object, for example { "off": "<reason>" }.`);
46
+ if (!isObject$1(entry)) throw new Error(`${where} must be an object, for example { "off": "<reason>" }.`);
47
47
  const off = entry["off"];
48
48
  if (off !== void 0 && (typeof off !== "string" || off.trim() === "")) throw new Error(`${where}.off must be the reason why the rule is off, as text.`);
49
49
  const ignore = entry["ignore"] ?? [];
@@ -2211,6 +2211,325 @@ const securityOneJob = {
2211
2211
  return breaks;
2212
2212
  }
2213
2213
  };
2214
+ // src/rules/shared-ci.ts
2215
+ /**
2216
+ * The rule `shared-ci`: a repository uses the shared workflows and actions of the template, and keeps no copy of them.
2217
+ * Its `ci.yml` uses the shared workflow `reusable-ci.yml` of the template. No workflow file and no action of the
2218
+ * repository has the name of a shared workflow or a shared action. The template itself is the home, so the rule does
2219
+ * not examine it.
2220
+ */
2221
+ /** The shared workflows of the template, by file name. */
2222
+ const SHARED_WORKFLOWS = [
2223
+ "reusable-ai-review.yml",
2224
+ "reusable-ci.yml",
2225
+ "reusable-codex-review.yml",
2226
+ "reusable-mutation.yml",
2227
+ "reusable-pages.yml",
2228
+ "reusable-release-build.yml",
2229
+ "reusable-release-tag.yml",
2230
+ "reusable-security.yml"
2231
+ ];
2232
+ /** The shared actions of the template, by folder name under `.github/actions`. */
2233
+ const SHARED_ACTIONS = [
2234
+ "changes",
2235
+ "changeset-check",
2236
+ "coverage",
2237
+ "data-stamps",
2238
+ "gate-summary",
2239
+ "green-main",
2240
+ "npm-publish",
2241
+ "security-scan",
2242
+ "setup-playwright",
2243
+ "site-check",
2244
+ "site-pages"
2245
+ ];
2246
+ /** The `uses` value of a job that calls the shared CI, with no pin. */
2247
+ const SHARED_CI = "mark1russell7/template/.github/workflows/reusable-ci.yml";
2248
+ /** The action folder of a path: `.github/actions/<name>/action.yml` gives `<name>`. */
2249
+ const ACTION = /^\.github\/actions\/([^/]+)\//;
2250
+ /** The file name of a path. */
2251
+ const baseName = (path) => path.slice(path.lastIndexOf("/") + 1);
2252
+ /** This function tells if a job of a workflow text uses the shared CI of the template. */
2253
+ function callsSharedCi(file, text) {
2254
+ return readWorkflow(file, text).jobs.some((job) => job.steps.some((step) => step.uses === SHARED_CI));
2255
+ }
2256
+ const sharedCi = {
2257
+ id: "shared-ci",
2258
+ title: "`ci.yml` calls the shared workflow `reusable-ci.yml` of the template, and no workflow or action copies a shared one.",
2259
+ reason: "The shared CI is the one place where each check of a repository is set: the typecheck, the tests, the conventions, the API report and the summary check CI OK that the ruleset needs. A ci.yml with its own steps, or a copy of a shared workflow or action, does not get the fixes and the new checks of the template, and it drifts with no sign. On 2026-11-07, 3 of 19 repositories of the account ran CI steps of their own, and the rule was only text in each CLAUDE.md.",
2260
+ fix: "Make ci.yml call mark1russell7/template/.github/workflows/reusable-ci.yml at a pinned commit, and give the differences as its inputs (CI.md). Remove the local copy of a shared workflow or action, and call the one of the template. A repository that cannot call the shared CI turns the rule off with its reason.",
2261
+ sources: [
2262
+ {
2263
+ repo: "template",
2264
+ rule: "shared-workflows",
2265
+ doc: "CLAUDE.md: the workflows use the shared workflows and actions of the template; a repository changes only the inputs of its callers"
2266
+ },
2267
+ {
2268
+ repo: "template",
2269
+ rule: "ci",
2270
+ doc: "CI.md, CI: a caller of reusable-ci.yml needs no inputs, and gives each difference as an input"
2271
+ },
2272
+ {
2273
+ repo: "highways",
2274
+ rule: "ci",
2275
+ doc: ".github/workflows/ci.yml:1: the job ci is the shared CI (reusable-ci.yml, CI.md)"
2276
+ },
2277
+ {
2278
+ repo: "packing",
2279
+ rule: "ci",
2280
+ doc: ".github/workflows/ci.yml:1: the job ci is the shared CI (reusable-ci.yml, CI.md)"
2281
+ },
2282
+ {
2283
+ repo: "ste-lint",
2284
+ rule: "ci",
2285
+ doc: ".github/workflows/ci.yml (2026-11-07): its own steps, no call of reusable-ci.yml; the same in optional and lag"
2286
+ }
2287
+ ],
2288
+ options: {
2289
+ home: {
2290
+ type: "strings",
2291
+ default: ["template-monorepo"],
2292
+ description: "The names of the root packages that own the shared workflows. The rule does not examine them."
2293
+ },
2294
+ ciFile: {
2295
+ type: "string",
2296
+ default: ".github/workflows/ci.yml",
2297
+ description: "The workflow file that must call the shared CI."
2298
+ }
2299
+ },
2300
+ check(context, options) {
2301
+ const home = options["home"];
2302
+ const name = context.rootPackage.manifest["name"];
2303
+ if (typeof name === "string" && home.includes(name)) return { skipped: `the repository is the home of the shared workflows (${name})` };
2304
+ const files = context.gitFiles();
2305
+ if (files === void 0) return { skipped: "the root is not in a git repository" };
2306
+ const breaks = [];
2307
+ for (const file of files.filter((path) => WORKFLOW$1.test(path)).sort(byCode)) if (SHARED_WORKFLOWS.includes(baseName(file))) breaks.push({
2308
+ file,
2309
+ message: `${file} has the name of a shared workflow of the template: it is a local copy, which does not get the fixes of the template.`
2310
+ });
2311
+ const actions = /* @__PURE__ */ new Set();
2312
+ for (const file of files) {
2313
+ const folder = ACTION.exec(file)?.[1];
2314
+ if (folder !== void 0 && SHARED_ACTIONS.includes(folder) && !actions.has(folder)) {
2315
+ actions.add(folder);
2316
+ breaks.push({
2317
+ file: `.github/actions/${folder}`,
2318
+ message: `.github/actions/${folder} has the name of a shared action of the template: it is a local copy, which does not get the fixes of the template.`
2319
+ });
2320
+ }
2321
+ }
2322
+ const ciFile = options["ciFile"];
2323
+ const path = join(context.root, ciFile);
2324
+ if (!existsSync(path)) breaks.push({
2325
+ file: ciFile,
2326
+ message: `${ciFile} is missing, so no job calls the shared CI of the template.`
2327
+ });
2328
+ else if (!callsSharedCi(ciFile, readFileSync(path, "utf8"))) breaks.push({
2329
+ file: ciFile,
2330
+ message: `No job of ${ciFile} calls ${SHARED_CI}: the CI runs its own steps, and does not get the checks of the template.`
2331
+ });
2332
+ return breaks;
2333
+ }
2334
+ };
2335
+ // src/rules/tsconfig-test.ts
2336
+ /**
2337
+ * The rule `tsconfig-test`: each TypeScript package has a `tsconfig.test.json`, and its typecheck
2338
+ * examines it.
2339
+ */
2340
+ /** The ends of the name of a test file: `.test.` or `.spec.`, then an extension of JavaScript or TypeScript. */
2341
+ const TEST_ENDS = ["test", "spec"].flatMap((kind) => [
2342
+ "",
2343
+ "c",
2344
+ "m"
2345
+ ].flatMap((module) => ["j", "t"].flatMap((lang) => ["", "x"].map((jsx) => `.${kind}.${module}${lang}s${jsx}`))));
2346
+ /**
2347
+ * This function tells if a path is a test file: `*.test.*` or `*.spec.*` of JavaScript or TypeScript, or a file in a
2348
+ * folder `__tests__`. It uses string operations, with no regular expression, so a long path takes linear time.
2349
+ */
2350
+ function isTestFile(path) {
2351
+ const segments = path.split("/");
2352
+ const name = segments[segments.length - 1] ?? "";
2353
+ if (name !== "" && segments.slice(0, -1).includes("__tests__")) return true;
2354
+ return TEST_ENDS.some((end) => name.length > end.length && name.endsWith(end));
2355
+ }
2356
+ /** This function tells if git tracks a test file in the package folder `folder` (`""` is the root). */
2357
+ function hasTests(files, folder) {
2358
+ const prefix = folder === "" ? "" : `${folder}/`;
2359
+ return files.some((path) => path.startsWith(prefix) && isTestFile(path.slice(prefix.length)));
2360
+ }
2361
+ const tsconfigTest = {
2362
+ id: "tsconfig-test",
2363
+ title: "Each package with a `tsconfig.json` and test files has a `tsconfig.test.json`, and its `typecheck` script examines it.",
2364
+ reason: "The build config leaves out the tests. Without a second config, `pnpm typecheck` does not examine the tests, and a type error in a test hides until the test runs.",
2365
+ fix: "Add `tsconfig.test.json` (extends `./tsconfig.json`, includes the tests, `noEmit`), and set the script `typecheck` to `tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json`. Keep `--noEmit` on the first call when the build config emits, so that a typecheck writes no build output.",
2366
+ sources: [
2367
+ {
2368
+ repo: "coeval",
2369
+ rule: "package-tsconfig-test",
2370
+ doc: "CLAUDE.md:18"
2371
+ },
2372
+ {
2373
+ repo: "coeval",
2374
+ rule: "tsconfig-test",
2375
+ doc: "CLAUDE.md:18"
2376
+ },
2377
+ {
2378
+ repo: "crawler",
2379
+ rule: "pkg-tsconfig-test",
2380
+ doc: "CLAUDE.md:18"
2381
+ },
2382
+ {
2383
+ repo: "crawler",
2384
+ rule: "tsconfig-test",
2385
+ doc: "CLAUDE.md:18"
2386
+ },
2387
+ {
2388
+ repo: "headroom",
2389
+ rule: "tsconfig-test",
2390
+ doc: "CLAUDE.md:32"
2391
+ },
2392
+ {
2393
+ repo: "headroom",
2394
+ rule: "tsconfig-test-per-package",
2395
+ doc: "CLAUDE.md:32"
2396
+ },
2397
+ {
2398
+ repo: "Vex",
2399
+ rule: "package-tsconfig-test",
2400
+ doc: "CLAUDE.md:23"
2401
+ },
2402
+ {
2403
+ repo: "Vex",
2404
+ rule: "tsconfig-test",
2405
+ doc: "CLAUDE.md:23"
2406
+ }
2407
+ ],
2408
+ options: { file: {
2409
+ type: "string",
2410
+ default: "tsconfig.test.json",
2411
+ description: "The name of the config of the tests."
2412
+ } },
2413
+ check(context, options) {
2414
+ const file = typeof options["file"] === "string" ? options["file"] : "tsconfig.test.json";
2415
+ const tracked = context.gitFiles();
2416
+ const breaks = [];
2417
+ for (const info of codePackages(context)) {
2418
+ if (!hasFile(info.dir, "tsconfig.json")) continue;
2419
+ if (tracked !== void 0 && !hasTests(tracked, info.folder)) continue;
2420
+ if (!hasFile(info.dir, file)) {
2421
+ breaks.push({
2422
+ file: inFolder(info.folder, file),
2423
+ message: `The package has a tsconfig.json and no ${file}.`
2424
+ });
2425
+ continue;
2426
+ }
2427
+ const scripts = info.manifest["scripts"];
2428
+ const typecheck = typeof scripts === "object" && scripts !== null ? scripts["typecheck"] : void 0;
2429
+ if (typeof typecheck === "string" && !typecheck.includes(file)) {
2430
+ const line = lineOf(info.text, "\"typecheck\"");
2431
+ breaks.push({
2432
+ file: info.file,
2433
+ ...line === void 0 ? {} : { line },
2434
+ message: `The script typecheck ("${typecheck}") does not examine ${file}.`,
2435
+ fix: `Add \`tsc -p ${file}\` to the script typecheck.`
2436
+ });
2437
+ }
2438
+ }
2439
+ return breaks;
2440
+ }
2441
+ };
2442
+ // src/rules/service-run-main.ts
2443
+ /**
2444
+ * The rule `service-run-main`: in a server package, only the entry `src/main.ts` starts the service with `run()`. A
2445
+ * server package is a package with a dependency on `@mark1russell7/service` and a file `src/main.ts`, as the preset
2446
+ * `service` of `pnpm package add` writes it. The other source files declare the service and give it to the entry.
2447
+ */
2448
+ /** The package of the service. */
2449
+ const SERVICE_PACKAGE = "@mark1russell7/service";
2450
+ /** An import of the service package or of one of its entries. */
2451
+ const SERVICE_IMPORT = /\bfrom\s+["']@mark1russell7\/service(\/[^"']*)?["']|\bimport\s*\(\s*["']@mark1russell7\/service(\/[^"']*)?["']\s*\)/;
2452
+ /** A call of `run(` on a value, but not on `this`. */
2453
+ const RUN_CALL = /(?<!\bthis)\.run\s*\(/;
2454
+ /** The source files that the rule reads. */
2455
+ const SOURCE = /\.(c|m)?tsx?$/;
2456
+ /** This function gives the lines (from 1) of the calls of `run(` in a source text that imports the service package. */
2457
+ function runCalls(text) {
2458
+ if (!SERVICE_IMPORT.test(text)) return [];
2459
+ const found = [];
2460
+ text.split(/\r?\n/).forEach((line, index) => {
2461
+ const comment = line.indexOf("//");
2462
+ const code = comment < 0 ? line : line.slice(0, comment);
2463
+ const trimmed = code.trimStart();
2464
+ if (trimmed.startsWith("*") || trimmed.startsWith("/*")) return;
2465
+ if (RUN_CALL.test(code)) found.push(index + 1);
2466
+ });
2467
+ return found;
2468
+ }
2469
+ /** This function tells if a manifest has a dependency on the service package. */
2470
+ const dependsOnService = (manifest) => {
2471
+ const dependencies = manifest["dependencies"];
2472
+ return typeof dependencies === "object" && dependencies !== null && "@mark1russell7/service" in dependencies;
2473
+ };
2474
+ const serviceRunMain = {
2475
+ id: "service-run-main",
2476
+ title: "In a server package, only the entry `src/main.ts` starts the service with `run()`.",
2477
+ reason: "run() of @mark1russell7/service owns the process: it starts the listeners, it reads the signals, and it ends the process. A module that starts it cannot be imported by a test or by a second entry without a second server. When only the entry starts it, each other module gives a service that a test can start, check and stop.",
2478
+ fix: "Move the call of run() to src/main.ts. Export the service (or a function that makes it) from the module, and start it in the entry.",
2479
+ sources: [
2480
+ {
2481
+ repo: "template",
2482
+ rule: "service-preset",
2483
+ doc: "CLAUDE.md: make a server package with --preset=service; only its entry src/main.ts uses run() of @mark1russell7/service"
2484
+ },
2485
+ {
2486
+ repo: "template",
2487
+ rule: "service-preset",
2488
+ doc: "packages/cli/src/commands/package/add.ts: the preset service writes src/main.ts and the script start"
2489
+ },
2490
+ {
2491
+ repo: "systems",
2492
+ rule: "service-run-main",
2493
+ doc: "packages/reference/src/main.ts:3: only this file starts run()"
2494
+ },
2495
+ {
2496
+ repo: "vex",
2497
+ rule: "service-run-main",
2498
+ doc: "packages/mcp/src/main.ts: the one call of run() of the package"
2499
+ }
2500
+ ],
2501
+ options: { main: {
2502
+ type: "string",
2503
+ default: "src/main.ts",
2504
+ description: "The entry of a server package, the one file that starts the service."
2505
+ } },
2506
+ check(context, options) {
2507
+ const main = typeof options["main"] === "string" ? options["main"] : "src/main.ts";
2508
+ const tracked = context.gitFiles();
2509
+ if (tracked === void 0) return { skipped: "the root is not in a git repository" };
2510
+ const breaks = [];
2511
+ for (const info of codePackages(context)) {
2512
+ if (!dependsOnService(info.manifest) || !hasFile(info.dir, main)) continue;
2513
+ const prefix = info.folder === "" ? "" : `${info.folder}/`;
2514
+ const entry = inFolder(info.folder, main);
2515
+ const own = tracked.filter((path) => path.startsWith(`${prefix}src/`) && SOURCE.test(path) && !/\.d\.(c|m)?ts$/.test(path) && path !== entry && !isTestFile(path.slice(prefix.length)));
2516
+ for (const file of own.sort(byCode)) {
2517
+ let text;
2518
+ try {
2519
+ text = readFileSync(join(context.root, file), "utf8");
2520
+ } catch {
2521
+ continue;
2522
+ }
2523
+ for (const line of runCalls(text)) breaks.push({
2524
+ file,
2525
+ line,
2526
+ message: `${file} starts the service with run(). In a server package only ${entry} does.`
2527
+ });
2528
+ }
2529
+ }
2530
+ return breaks;
2531
+ }
2532
+ };
2214
2533
  // src/change.ts
2215
2534
  /**
2216
2535
  * The change that a check examines: the option `--base`, the merge commit of a pull request, or a push to the default
@@ -9113,9 +9432,280 @@ const noBuildOutput = {
9113
9432
  }));
9114
9433
  }
9115
9434
  };
9435
+ // src/private-names.ts
9436
+ /**
9437
+ * The private name list: a JSON file outside of the public repositories, with the names of private projects. The file
9438
+ * `schema/private-names.schema.json` tells its form. This module parses the list and finds its names in a line or in a
9439
+ * path. It has no input or output.
9440
+ *
9441
+ * A result tells the place of a name by its index in the list, for example `name 3 of the private name list`. A result
9442
+ * does not show the text, the id, the project or a pattern, because the id of a name is the private name.
9443
+ */
9444
+ /** The name of the private name list in a break and in an error. A break does not show the path of the file. */
9445
+ const PRIVATE_NAME_LIST = "the private name list";
9446
+ /**
9447
+ * This error tells that a private name list is not valid. Its reason names a field by the index of its entry, and
9448
+ * does not show a value of the list.
9449
+ */
9450
+ var PrivateNameListError = class extends Error {
9451
+ /** The reason, for example `name 3 of the private name list: the field seeds has no text`. */
9452
+ reason;
9453
+ constructor(reason) {
9454
+ super(`The private name list is not valid: ${reason}.`);
9455
+ this.name = "PrivateNameListError";
9456
+ this.reason = reason;
9457
+ }
9458
+ };
9459
+ /** The compiled names, by entry. The parse fills it, and a list of another source gets its entries on the first use. */
9460
+ const compiled = /* @__PURE__ */ new WeakMap();
9461
+ /** The form of a word: letters, digits, `_` and `-`. So the word is a literal in a regular expression. */
9462
+ const WORD = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
9463
+ /** The form of a word of `commonAfter`: lower-case letters. The check compares it with the next word in lower case. */
9464
+ const AFTER = /^[a-z]+$/;
9465
+ /** This function gives the compiled regular expressions of a name. */
9466
+ function compiledOf(rule) {
9467
+ const known = compiled.get(rule);
9468
+ if (known !== void 0) return known;
9469
+ const made = {
9470
+ patterns: rule.patterns.map((source) => new RegExp(source)),
9471
+ ...rule.word === void 0 || rule.word === "" ? {} : { word: new RegExp(`\\b${rule.word}\\b`, "g") }
9472
+ };
9473
+ compiled.set(rule, made);
9474
+ return made;
9475
+ }
9476
+ /** This function tells if a value is a list of texts that are not empty. */
9477
+ const isTexts = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item !== "");
9478
+ /** This function tells if a value is an object that is not a list. */
9479
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9480
+ /** This function gives the first field of `entry` that `known` does not have, or undefined. */
9481
+ const unknownField = (entry, known) => Object.keys(entry).find((key) => !known.includes(key));
9482
+ /** This function gives a name of the list after a check of its fields. The error names the entry by its index. */
9483
+ function nameOf(entry, at) {
9484
+ const fail = (reason) => {
9485
+ throw new PrivateNameListError(`${at}: ${reason}`);
9486
+ };
9487
+ if (!isObject(entry)) return fail("the entry is not an object");
9488
+ if (unknownField(entry, [
9489
+ "id",
9490
+ "project",
9491
+ "seeds",
9492
+ "patterns",
9493
+ "word",
9494
+ "commonAfter"
9495
+ ]) !== void 0) fail("the entry has a field that the schema does not have");
9496
+ const { id, project, seeds, patterns, word, commonAfter } = entry;
9497
+ if (typeof id !== "string" || id === "") fail("the field id is not a text");
9498
+ if (typeof project !== "string" || project === "") fail("the field project is not a text");
9499
+ if (!isTexts(seeds) || seeds.length === 0) fail("the field seeds is not a list of one or more texts");
9500
+ if (!isTexts(patterns)) fail("the field patterns is not a list of texts");
9501
+ if (word !== void 0 && (typeof word !== "string" || !WORD.test(word))) fail("the field word is not one word of letters, digits, _ and -");
9502
+ if (commonAfter !== void 0 && (!Array.isArray(commonAfter) || !commonAfter.every((item) => typeof item === "string" && AFTER.test(item)))) fail("the field commonAfter is not a list of lower-case words");
9503
+ if (commonAfter !== void 0 && word === void 0) fail("the field commonAfter has no field word");
9504
+ const rule = {
9505
+ id,
9506
+ project,
9507
+ seeds,
9508
+ patterns,
9509
+ ...word === void 0 ? {} : { word },
9510
+ ...commonAfter === void 0 ? {} : { commonAfter }
9511
+ };
9512
+ rule.patterns.forEach((source, index) => {
9513
+ try {
9514
+ new RegExp(source);
9515
+ } catch {
9516
+ fail(`pattern ${String(index + 1)} is not a valid regular expression`);
9517
+ }
9518
+ });
9519
+ compiledOf(rule);
9520
+ return rule;
9521
+ }
9522
+ /** This function gives an entry of the list `allow` after a check of its fields. */
9523
+ function allowedOf(entry, at, ids) {
9524
+ const fail = (reason) => {
9525
+ throw new PrivateNameListError(`${at}: ${reason}`);
9526
+ };
9527
+ if (!isObject(entry)) return fail("the entry is not an object");
9528
+ if (unknownField(entry, [
9529
+ "repo",
9530
+ "path",
9531
+ "name",
9532
+ "why"
9533
+ ]) !== void 0) fail("the entry has a field that the schema does not have");
9534
+ const { repo, path, name, why } = entry;
9535
+ if (typeof repo !== "string" || repo === "") fail("the field repo is not a text");
9536
+ if (typeof path !== "string" || path === "") fail("the field path is not a text");
9537
+ if (typeof why !== "string" || why === "") fail("the field why is not a text");
9538
+ if (name !== void 0 && (typeof name !== "string" || !ids.has(name))) fail("the field name is not the id of a name of the list");
9539
+ return {
9540
+ repo,
9541
+ path,
9542
+ why,
9543
+ ...name === void 0 ? {} : { name }
9544
+ };
9545
+ }
9546
+ /**
9547
+ * This function parses the text of a private name list, and checks it against the schema. It also checks each regular
9548
+ * expression and the ids. It throws a `PrivateNameListError` when the text is not valid. The error shows no value of the text.
9549
+ */
9550
+ function parsePrivateNames(text) {
9551
+ let data;
9552
+ try {
9553
+ data = JSON.parse(text);
9554
+ } catch {
9555
+ throw new PrivateNameListError("the text is not valid JSON");
9556
+ }
9557
+ if (!isObject(data)) throw new PrivateNameListError("the text is not a JSON object");
9558
+ if (unknownField(data, [
9559
+ "$schema",
9560
+ "$comment",
9561
+ "names",
9562
+ "allow"
9563
+ ]) !== void 0) throw new PrivateNameListError("the object has a field that the schema does not have");
9564
+ if (data["$comment"] !== void 0 && typeof data["$comment"] !== "string") throw new PrivateNameListError("the field $comment is not a text");
9565
+ const names = data["names"];
9566
+ const allow = data["allow"] ?? [];
9567
+ if (!Array.isArray(names)) throw new PrivateNameListError("the field names is not a list");
9568
+ if (!Array.isArray(allow)) throw new PrivateNameListError("the field allow is not a list");
9569
+ const rules = names.map((entry, index) => nameOf(entry, `name ${String(index + 1)} of ${PRIVATE_NAME_LIST}`));
9570
+ const ids = /* @__PURE__ */ new Set();
9571
+ rules.forEach((rule, index) => {
9572
+ if (ids.has(rule.id)) throw new PrivateNameListError(`name ${String(index + 1)} of ${PRIVATE_NAME_LIST}: the id is also the id of an earlier name`);
9573
+ ids.add(rule.id);
9574
+ });
9575
+ return {
9576
+ names: rules,
9577
+ allow: allow.map((entry, index) => allowedOf(entry, `allow entry ${String(index + 1)} of ${PRIVATE_NAME_LIST}`, ids))
9578
+ };
9579
+ }
9580
+ /** The words before a name in code: a declaration, a type or an operator. */
9581
+ const CODE_BEFORE = /\b(class|interface|type|new|extends|implements|const|let|enum|struct|typeof|instanceof|as)\s+$/;
9582
+ /** A line of code that imports or exports names. */
9583
+ const CODE_LINE = /^\s*(import|export)\b/;
9584
+ /** The words before a common noun: an article or a count. */
9585
+ const COUNT_BEFORE = /\b(a|an|any|each|every|one|our|this|your)\s+$/i;
9586
+ /** A word with a capital letter before the word: a title, or a name of more words. */
9587
+ const TITLE_BEFORE = /[A-Z][\w-]*\s+$/;
9588
+ /** The words with a capital letter that start a sentence part, not a title. */
9589
+ const WORD_BEFORE = /\b(And|By|For|From|In|Of|See|To|With)\s+$/;
9590
+ /**
9591
+ * This function tells if the word of `rule` at `index` of `line` is a common word or code, and not the name of the
9592
+ * project. Code is a type, a key or a part of a path. A common word comes after an article, in a title or before a noun.
9593
+ */
9594
+ function isCommonUse(line, index, rule) {
9595
+ const word = rule.word ?? "";
9596
+ const before = line.slice(0, index);
9597
+ const after = line.slice(index + word.length);
9598
+ if (/^\s*[\]>{};]/.test(after) || /["[]$/.test(before) || /=>\s*$/.test(before)) return true;
9599
+ if (/^[<([{]/.test(after) || /^\.\w/.test(after) || after.startsWith("::") || /^:\s*[{[(]/.test(after)) return true;
9600
+ if (/^[-/]/.test(after) || /[-/]$/.test(before)) return true;
9601
+ if (/[<.]$/.test(before)) return true;
9602
+ if (CODE_BEFORE.test(before) || CODE_LINE.test(line)) return true;
9603
+ if (/[`'"]$/.test(before) && /^[`'"]/.test(after)) return true;
9604
+ if (/[\w)\]?]:\s*$/.test(before) && /^\s*([,;)=|&>]|$)/.test(after)) return true;
9605
+ if (COUNT_BEFORE.test(before)) return true;
9606
+ if (TITLE_BEFORE.test(before) && !WORD_BEFORE.test(before)) return true;
9607
+ const next = /^\s+([A-Za-z]+)/.exec(after)?.[1];
9608
+ if (next === void 0) return false;
9609
+ return /^[A-Z][a-z]/.test(next) || (rule.commonAfter ?? []).includes(next.toLowerCase());
9610
+ }
9611
+ /**
9612
+ * This function gives the first name of `names` in `line`, or undefined. For each name in sequence, a pattern match is
9613
+ * a hit. A match of the word is a hit when `isCommonUse` is false. It does not use the seeds or the list `allow`.
9614
+ */
9615
+ function firstNameMatch(line, names) {
9616
+ for (let at = 0; at < names.length; at++) {
9617
+ const hit = nameMatch(line, names, at);
9618
+ if (hit !== void 0) return hit;
9619
+ }
9620
+ }
9621
+ /**
9622
+ * This function gives each name of `names` in `line`, in the sequence of the list. Each name gives one hit at most: its
9623
+ * first pattern match, or else its first word match that is not a common use.
9624
+ */
9625
+ function nameMatches(line, names) {
9626
+ const hits = [];
9627
+ for (let at = 0; at < names.length; at++) {
9628
+ const hit = nameMatch(line, names, at);
9629
+ if (hit !== void 0) hits.push(hit);
9630
+ }
9631
+ return hits;
9632
+ }
9633
+ /** This function gives the hit of the name at position `at` of `names` in `line`, or undefined. */
9634
+ function nameMatch(line, names, at) {
9635
+ const rule = names[at];
9636
+ if (rule === void 0) return void 0;
9637
+ const { patterns, word } = compiledOf(rule);
9638
+ for (const pattern of patterns) {
9639
+ const found = pattern.exec(line);
9640
+ if (found !== null) return {
9641
+ name: at + 1,
9642
+ rule,
9643
+ index: found.index
9644
+ };
9645
+ }
9646
+ if (word === void 0) return void 0;
9647
+ for (const found of line.matchAll(word)) if (!isCommonUse(line, found.index, rule)) return {
9648
+ name: at + 1,
9649
+ rule,
9650
+ index: found.index
9651
+ };
9652
+ }
9653
+ /** This function gives the name part of a repository: `name` for `owner/name`, in lower case. */
9654
+ const repoName = (repo) => (repo.split("/").at(-1) ?? repo).toLowerCase();
9655
+ /**
9656
+ * This function tells if the list `allow` permits the name `id` in the file `path` of the repository `repo`. An entry
9657
+ * with the repository `name` or `owner/name` matches the repository `owner/name`. Case of a repository is not significant.
9658
+ */
9659
+ function isAllowedHit(allow, repo, path, id) {
9660
+ const full = repo.toLowerCase();
9661
+ return allow.some((entry) => {
9662
+ const named = entry.repo.toLowerCase();
9663
+ return (named.includes("/") ? named === full : named === repoName(repo)) && entry.path === path && (entry.name === void 0 || entry.name === id);
9664
+ });
9665
+ }
9666
+ /**
9667
+ * This function gives each name of the list in one line of a file or of a message, in the sequence of the list. The line
9668
+ * must have a seed of the list. Each name gives one hit at most. A permitted hit at the place does not count.
9669
+ */
9670
+ function lineNameHits(list, line, place = {}) {
9671
+ if (!list.names.some((rule) => rule.seeds.some((seed) => line.includes(seed)))) return [];
9672
+ const { repo, path } = place;
9673
+ const hits = nameMatches(line, list.names);
9674
+ if (repo === void 0 || path === void 0) return hits;
9675
+ return hits.filter((hit) => !isAllowedHit(list.allow, repo, path, hit.rule.id));
9676
+ }
9677
+ /**
9678
+ * This function gives the first name of the list in one line of a file or of a message, or undefined. It is the first
9679
+ * hit of `lineNameHits`, so a permitted hit does not hide a hit of another name.
9680
+ */
9681
+ function lineNameHit(list, line, place = {}) {
9682
+ return lineNameHits(list, line, place)[0];
9683
+ }
9684
+ /**
9685
+ * This function gives the first name of the list whose pattern matches a path of a file, or undefined. Only the patterns
9686
+ * apply, because a path has no sentence. The seeds and the list `allow` do not apply.
9687
+ */
9688
+ function pathNameHit(list, path) {
9689
+ for (let at = 0; at < list.names.length; at++) {
9690
+ const rule = list.names[at];
9691
+ if (rule === void 0) continue;
9692
+ const found = compiledOf(rule).patterns.map((pattern) => pattern.exec(path)).find((match) => match !== null);
9693
+ if (found !== void 0 && found !== null) return {
9694
+ name: at + 1,
9695
+ rule,
9696
+ index: found.index
9697
+ };
9698
+ }
9699
+ }
9116
9700
  // src/rules/no-local-paths.ts
9117
9701
  /**
9118
- * The rule `no-local-paths`: no tracked file names the home folder of a user of a computer.
9702
+ * The rule `no-local-paths`: no tracked file names the home folder of a user of a computer. The commit messages of a
9703
+ * change and the title and the body of its pull request do not name one either. The same is true for each private
9704
+ * pattern of the environment variable `CONVENTIONS_PRIVATE_PATTERNS`. A break of a private pattern does not show the
9705
+ * text or the pattern, because a public log must not name them.
9706
+ *
9707
+ * The module also has the core of the command `conventions pre-push`. The core has the setting of the private name list,
9708
+ * the private patterns and the breaks of one text.
9119
9709
  */
9120
9710
  /** The extensions of files that are not text. The rule does not read them. */
9121
9711
  const BINARY = new Set(".png .jpg .jpeg .gif .webp .avif .ico .bmp .tiff .pdf .zip .gz .tgz .bz2 .xz .7z .tar .woff .woff2 .ttf .otf .eot .mp3 .mp4 .webm .mov .wav .ogg .wasm .node .exe .dll .so .dylib .bin .db .sqlite .duckdb".split(" "));
@@ -9148,12 +9738,174 @@ const HOME_PATTERNS = [
9148
9738
  /(?<![\w.~-])\/Users\/(?<user>[^/\s"'`<>|:*?%$(){}[\],;]+)/g,
9149
9739
  /(?<![\w.~-])\/home\/(?<user>[^/\s"'`<>|:*?%$(){}[\],;]+)/g
9150
9740
  ];
9151
- const noLocalPaths = {
9152
- id: "no-local-paths",
9153
- title: "No tracked file has the home folder of a user (`C:\\Users\\<name>`, `/Users/<name>`, `/home/<name>`).",
9154
- reason: "A public file must not name a computer, a user or a path of a computer. A local path also works only on one computer.",
9155
- fix: "Use a path relative to the repository, `~`, an environment variable, or a placeholder such as `<you>`.",
9156
- sources: [
9741
+ /** The name of the environment variable of the private patterns. */
9742
+ const PRIVATE_PATTERNS_VARIABLE = "CONVENTIONS_PRIVATE_PATTERNS";
9743
+ /** The name of the environment variable of the path of the private name list. */
9744
+ const PRIVATE_NAMES_FILE_VARIABLE = "CONVENTIONS_PRIVATE_NAMES_FILE";
9745
+ /** The key of the git configuration of the path of the private name list. */
9746
+ const PRIVATE_NAMES_FILE_CONFIG = "conventions.privateNamesFile";
9747
+ /** This function gives the regular expression of a pattern, or undefined when the pattern is not valid. */
9748
+ function compilePattern(source) {
9749
+ try {
9750
+ return new RegExp(source, "g");
9751
+ } catch {
9752
+ return;
9753
+ }
9754
+ }
9755
+ /** This function compiles the patterns of a check. A private pattern that is not valid has no matcher. */
9756
+ function compile(privates, options) {
9757
+ const extra = (options.patterns ?? []).map((source) => ({ regex: new RegExp(source, "g") }));
9758
+ for (const pattern of privates.patterns ?? []) {
9759
+ const regex = compilePattern(pattern.source);
9760
+ if (regex !== void 0) extra.push({
9761
+ regex,
9762
+ secret: pattern
9763
+ });
9764
+ }
9765
+ return {
9766
+ ...privates.names === void 0 ? {} : { names: privates.names },
9767
+ extra,
9768
+ allowed: new Set([...DEFAULT_ALLOWED, ...options.allow ?? []].map((name) => name.toLowerCase())),
9769
+ homes: options.homes !== false
9770
+ };
9771
+ }
9772
+ /** This function gives the breaks of one text with compiled patterns. */
9773
+ function textBreaks(name, text, matchers, options) {
9774
+ const breaks = [];
9775
+ const first = options.firstLine ?? 1;
9776
+ const lines = text.split(/\r?\n/);
9777
+ for (let index = 0; index < lines.length; index++) {
9778
+ const line = lines[index] ?? "";
9779
+ const at = first + index;
9780
+ const isReason = options.rootPackage === true && /^\s*"(?:reason|off)"\s*:/.test(line);
9781
+ if (matchers.homes && !isReason) for (const pattern of HOME_PATTERNS) for (const match of line.matchAll(pattern)) {
9782
+ const user = match.groups?.["user"] ?? "";
9783
+ if (user.length < 2 || matchers.allowed.has(user.toLowerCase())) continue;
9784
+ breaks.push({
9785
+ file: name,
9786
+ line: at,
9787
+ message: `The text "${match[0]}" is the home folder of a user.`
9788
+ });
9789
+ }
9790
+ if (matchers.names !== void 0) {
9791
+ const place = {
9792
+ ...options.repo === void 0 ? {} : { repo: options.repo },
9793
+ ...options.path === void 0 ? {} : { path: options.path }
9794
+ };
9795
+ const hit = options.isPath === true ? pathNameHit(matchers.names, line) : lineNameHit(matchers.names, line, place);
9796
+ if (hit !== void 0) breaks.push({
9797
+ file: name,
9798
+ line: at,
9799
+ message: `A text names name ${String(hit.name)} of ${PRIVATE_NAME_LIST}.`,
9800
+ fix: "Remove the text. The check does not show the text, because the name is private."
9801
+ });
9802
+ }
9803
+ for (const matcher of matchers.extra) {
9804
+ if (options.rootPackage === true && matcher.secret === void 0 && line.trim().replace(/,$/, "") === JSON.stringify(matcher.regex.source)) continue;
9805
+ for (const match of line.matchAll(matcher.regex)) breaks.push(matcher.secret === void 0 ? {
9806
+ file: name,
9807
+ line: at,
9808
+ message: `The text "${match[0]}" matches the pattern ${matcher.regex.source}.`,
9809
+ fix: "Remove the text."
9810
+ } : {
9811
+ file: name,
9812
+ line: at,
9813
+ message: `A text matches the private pattern on line ${String(matcher.secret.line)} of ${matcher.secret.label}.`,
9814
+ fix: "Remove the text. The check does not show the text, because the pattern is private."
9815
+ });
9816
+ }
9817
+ }
9818
+ return breaks;
9819
+ }
9820
+ /** This function gives the patterns of the lines of `text`, with the line of each (from 1). It skips empty lines. */
9821
+ function patternLines(text, label) {
9822
+ return text.split("\n").map((source, index) => ({
9823
+ source: source.trim(),
9824
+ line: index + 1,
9825
+ label
9826
+ })).filter((pattern) => pattern.source !== "");
9827
+ }
9828
+ /** This function gives the private patterns of the environment variable, with the line of each (from 1). */
9829
+ function privatePatterns(env) {
9830
+ return patternLines(env["CONVENTIONS_PRIVATE_PATTERNS"] ?? "", PRIVATE_PATTERNS_VARIABLE);
9831
+ }
9832
+ /**
9833
+ * This function gives the path of the private name list: the environment variable `CONVENTIONS_PRIVATE_NAMES_FILE`,
9834
+ * else the git configuration `conventions.privateNamesFile`. It gives undefined when neither has a value.
9835
+ */
9836
+ function privateNamesFile(env, git) {
9837
+ const fromEnv = env["CONVENTIONS_PRIVATE_NAMES_FILE"]?.trim() ?? "";
9838
+ if (fromEnv !== "") return fromEnv;
9839
+ const fromGit = git([
9840
+ "config",
9841
+ "--type=path",
9842
+ "--get",
9843
+ "conventions.privateNamesFile"
9844
+ ])?.trim() ?? "";
9845
+ return fromGit === "" ? void 0 : fromGit;
9846
+ }
9847
+ /** This function gives a break for each private pattern that is not a valid regular expression. A break does not show the pattern. */
9848
+ function invalidPatternBreaks(patterns) {
9849
+ return patterns.filter((pattern) => compilePattern(pattern.source) === void 0).map((pattern) => ({
9850
+ file: pattern.label,
9851
+ line: pattern.line,
9852
+ message: `Line ${String(pattern.line)} of ${pattern.label} is not a valid regular expression.`,
9853
+ fix: "Correct the regular expression. The check does not show the pattern, because it is private."
9854
+ }));
9855
+ }
9856
+ /**
9857
+ * This function gives the breaks of one text: a file, a commit message or the body of a pull request. Each break has the
9858
+ * file `name`. A break of a private source does not show the text, the name or the pattern. A line has one break or no
9859
+ * break of the private name list. The breaks of home folders use `HOME_PATTERNS` and the permitted names. A private pattern
9860
+ * that is not valid gives no break here: refer to `invalidPatternBreaks`.
9861
+ */
9862
+ function privateTextBreaks(name, text, privates, options = {}) {
9863
+ return textBreaks(name, text, compile(privates, options), options);
9864
+ }
9865
+ /**
9866
+ * This function gives the texts of the change that are not files. They are each commit message of a pull request (or of the
9867
+ * range of `--base`). They are also the title and the body of the pull request, from the event file of GitHub Actions.
9868
+ */
9869
+ function changeTexts(context) {
9870
+ const texts = [];
9871
+ const range = rangeOf(context);
9872
+ if (!("skipped" in range)) {
9873
+ const log = context.git([
9874
+ "log",
9875
+ "--no-merges",
9876
+ "--format=%H%x00%B%x1e",
9877
+ ...range.log
9878
+ ]) ?? "";
9879
+ for (const entry of log.split("")) {
9880
+ const [sha, message] = entry.replace(/^\s+/, "").split("\0");
9881
+ if (sha !== void 0 && sha !== "" && message !== void 0) texts.push({
9882
+ name: `commit ${sha.slice(0, 12)}`,
9883
+ text: message
9884
+ });
9885
+ }
9886
+ }
9887
+ const file = context.env["GITHUB_EVENT_PATH"];
9888
+ if (file !== void 0 && file !== "" && existsSync(file)) try {
9889
+ const event = JSON.parse(readFileSync(file, "utf8"));
9890
+ const title = event.pull_request?.title;
9891
+ const body = event.pull_request?.body;
9892
+ if (typeof title === "string") texts.push({
9893
+ name: "pull request title",
9894
+ text: title
9895
+ });
9896
+ if (typeof body === "string") texts.push({
9897
+ name: "pull request body",
9898
+ text: body
9899
+ });
9900
+ } catch {}
9901
+ return texts;
9902
+ }
9903
+ const noLocalPaths = {
9904
+ id: "no-local-paths",
9905
+ title: "No tracked file, commit message of the change or text of its pull request has a private pattern or the home folder of a user (`C:\\Users\\<name>`, `/Users/<name>`, `/home/<name>`).",
9906
+ reason: "A public file must not name a computer, a user or a path of a computer. A local path also works only on one computer.",
9907
+ fix: "Use a path relative to the repository, `~`, an environment variable, or a placeholder such as `<you>`.",
9908
+ sources: [
9157
9909
  {
9158
9910
  repo: "client",
9159
9911
  rule: "I12",
@@ -9195,11 +9947,17 @@ const noLocalPaths = {
9195
9947
  check(context, options) {
9196
9948
  const files = context.gitFiles();
9197
9949
  if (files === void 0) return { skipped: "the root is not in a git repository" };
9198
- const allowed = new Set([...DEFAULT_ALLOWED, ...Array.isArray(options["allow"]) ? options["allow"] : []].map((name) => name.toLowerCase()));
9199
- const fromEnv = (context.env["CONVENTIONS_PRIVATE_PATTERNS"] ?? "").split("\n").map((line) => line.trim()).filter((line) => line !== "");
9200
- const extra = [...Array.isArray(options["patterns"]) ? options["patterns"] : [], ...fromEnv].map((source) => new RegExp(source, "g"));
9950
+ const settings = {
9951
+ allow: Array.isArray(options["allow"]) ? [...options["allow"]] : [],
9952
+ patterns: Array.isArray(options["patterns"]) ? [...options["patterns"]] : []
9953
+ };
9954
+ const privates = privatePatterns(context.env);
9955
+ const matchers = compile({ patterns: privates }, settings);
9201
9956
  const rootFile = context.rootPackage.file;
9202
- const breaks = [];
9957
+ const breaks = invalidPatternBreaks(privates);
9958
+ const add = (items) => {
9959
+ for (const item of items) breaks.push(item);
9960
+ };
9203
9961
  for (const file of files) {
9204
9962
  if (BINARY.has(extname(file).toLowerCase())) continue;
9205
9963
  const path = join(context.root, file);
@@ -9211,30 +9969,9 @@ const noLocalPaths = {
9211
9969
  continue;
9212
9970
  }
9213
9971
  if (text.includes("\0")) continue;
9214
- const lines = text.split(/\r?\n/);
9215
- for (let index = 0; index < lines.length; index++) {
9216
- const line = lines[index] ?? "";
9217
- const isReason = file === rootFile && /^\s*"(?:reason|off)"\s*:/.test(line);
9218
- for (const pattern of isReason ? [] : HOME_PATTERNS) for (const match of line.matchAll(pattern)) {
9219
- const user = match.groups?.["user"] ?? "";
9220
- if (user.length < 2 || allowed.has(user.toLowerCase())) continue;
9221
- breaks.push({
9222
- file,
9223
- line: index + 1,
9224
- message: `The text "${match[0]}" is the home folder of a user.`
9225
- });
9226
- }
9227
- for (const pattern of extra) {
9228
- if (file === rootFile && line.trim().replace(/,$/, "") === JSON.stringify(pattern.source)) continue;
9229
- for (const match of line.matchAll(pattern)) breaks.push({
9230
- file,
9231
- line: index + 1,
9232
- message: `The text "${match[0]}" matches the pattern ${pattern.source}.`,
9233
- fix: "Remove the text."
9234
- });
9235
- }
9236
- }
9972
+ add(textBreaks(file, text, matchers, { rootPackage: file === rootFile }));
9237
9973
  }
9974
+ for (const change of changeTexts(context)) add(textBreaks(change.name, change.text, matchers, {}));
9238
9975
  return breaks;
9239
9976
  }
9240
9977
  };
@@ -11792,113 +12529,6 @@ const sourceMain = {
11792
12529
  return breaks;
11793
12530
  }
11794
12531
  };
11795
- // src/rules/tsconfig-test.ts
11796
- /**
11797
- * The rule `tsconfig-test`: each TypeScript package has a `tsconfig.test.json`, and its typecheck
11798
- * examines it.
11799
- */
11800
- /** The ends of the name of a test file: `.test.` or `.spec.`, then an extension of JavaScript or TypeScript. */
11801
- const TEST_ENDS = ["test", "spec"].flatMap((kind) => [
11802
- "",
11803
- "c",
11804
- "m"
11805
- ].flatMap((module) => ["j", "t"].flatMap((lang) => ["", "x"].map((jsx) => `.${kind}.${module}${lang}s${jsx}`))));
11806
- /**
11807
- * This function tells if a path is a test file: `*.test.*` or `*.spec.*` of JavaScript or TypeScript, or a file in a
11808
- * folder `__tests__`. It uses string operations, with no regular expression, so a long path takes linear time.
11809
- */
11810
- function isTestFile(path) {
11811
- const segments = path.split("/");
11812
- const name = segments[segments.length - 1] ?? "";
11813
- if (name !== "" && segments.slice(0, -1).includes("__tests__")) return true;
11814
- return TEST_ENDS.some((end) => name.length > end.length && name.endsWith(end));
11815
- }
11816
- /** This function tells if git tracks a test file in the package folder `folder` (`""` is the root). */
11817
- function hasTests(files, folder) {
11818
- const prefix = folder === "" ? "" : `${folder}/`;
11819
- return files.some((path) => path.startsWith(prefix) && isTestFile(path.slice(prefix.length)));
11820
- }
11821
- const tsconfigTest = {
11822
- id: "tsconfig-test",
11823
- title: "Each package with a `tsconfig.json` and test files has a `tsconfig.test.json`, and its `typecheck` script examines it.",
11824
- reason: "The build config leaves out the tests. Without a second config, `pnpm typecheck` does not examine the tests, and a type error in a test hides until the test runs.",
11825
- fix: "Add `tsconfig.test.json` (extends `./tsconfig.json`, includes the tests, `noEmit`), and set the script `typecheck` to `tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json`. Keep `--noEmit` on the first call when the build config emits, so that a typecheck writes no build output.",
11826
- sources: [
11827
- {
11828
- repo: "coeval",
11829
- rule: "package-tsconfig-test",
11830
- doc: "CLAUDE.md:18"
11831
- },
11832
- {
11833
- repo: "coeval",
11834
- rule: "tsconfig-test",
11835
- doc: "CLAUDE.md:18"
11836
- },
11837
- {
11838
- repo: "crawler",
11839
- rule: "pkg-tsconfig-test",
11840
- doc: "CLAUDE.md:18"
11841
- },
11842
- {
11843
- repo: "crawler",
11844
- rule: "tsconfig-test",
11845
- doc: "CLAUDE.md:18"
11846
- },
11847
- {
11848
- repo: "headroom",
11849
- rule: "tsconfig-test",
11850
- doc: "CLAUDE.md:32"
11851
- },
11852
- {
11853
- repo: "headroom",
11854
- rule: "tsconfig-test-per-package",
11855
- doc: "CLAUDE.md:32"
11856
- },
11857
- {
11858
- repo: "Vex",
11859
- rule: "package-tsconfig-test",
11860
- doc: "CLAUDE.md:23"
11861
- },
11862
- {
11863
- repo: "Vex",
11864
- rule: "tsconfig-test",
11865
- doc: "CLAUDE.md:23"
11866
- }
11867
- ],
11868
- options: { file: {
11869
- type: "string",
11870
- default: "tsconfig.test.json",
11871
- description: "The name of the config of the tests."
11872
- } },
11873
- check(context, options) {
11874
- const file = typeof options["file"] === "string" ? options["file"] : "tsconfig.test.json";
11875
- const tracked = context.gitFiles();
11876
- const breaks = [];
11877
- for (const info of codePackages(context)) {
11878
- if (!hasFile(info.dir, "tsconfig.json")) continue;
11879
- if (tracked !== void 0 && !hasTests(tracked, info.folder)) continue;
11880
- if (!hasFile(info.dir, file)) {
11881
- breaks.push({
11882
- file: inFolder(info.folder, file),
11883
- message: `The package has a tsconfig.json and no ${file}.`
11884
- });
11885
- continue;
11886
- }
11887
- const scripts = info.manifest["scripts"];
11888
- const typecheck = typeof scripts === "object" && scripts !== null ? scripts["typecheck"] : void 0;
11889
- if (typeof typecheck === "string" && !typecheck.includes(file)) {
11890
- const line = lineOf(info.text, "\"typecheck\"");
11891
- breaks.push({
11892
- file: info.file,
11893
- ...line === void 0 ? {} : { line },
11894
- message: `The script typecheck ("${typecheck}") does not examine ${file}.`,
11895
- fix: `Add \`tsc -p ${file}\` to the script typecheck.`
11896
- });
11897
- }
11898
- }
11899
- return breaks;
11900
- }
11901
- };
11902
12532
  // src/rules/tests-required.ts
11903
12533
  /**
11904
12534
  * The rule `tests-required`: no test runner passes when it finds no test (`passWithNoTests`).
@@ -12851,6 +13481,7 @@ const RULES = [
12851
13481
  workspaceProtocol,
12852
13482
  trustPolicy,
12853
13483
  sourceMain,
13484
+ serviceRunMain,
12854
13485
  tsconfigTest,
12855
13486
  cuePreset,
12856
13487
  requiredScripts,
@@ -12875,16 +13506,396 @@ const RULES = [
12875
13506
  gateAfterCancel,
12876
13507
  gateTrigger,
12877
13508
  securityOneJob,
13509
+ sharedCi,
12878
13510
  homePackage,
12879
13511
  licenseFile,
12880
13512
  pagesSite,
12881
13513
  pagesAfterRelease,
12882
13514
  sharedDocs
12883
13515
  ];
13516
+ // src/pre-push.ts
13517
+ /**
13518
+ * The commands `conventions pre-push` and `conventions hook install`. The hook `pre-push` of git starts the first
13519
+ * command before each push. It examines the new commits of the push with the private name list, which is outside
13520
+ * of the public repositories. The second command writes that hook.
13521
+ */
13522
+ /** The line of `conventions pre-push` when no setting names a private name list and no environment variable has a pattern. */
13523
+ const NO_READ_LINE = `conventions pre-push: No read: no private name list. Set ${PRIVATE_NAMES_FILE_VARIABLE} or the git config ${PRIVATE_NAMES_FILE_CONFIG}.`;
13524
+ /** A sha of no commit: git gives it for a ref that the push deletes, or for a ref that the remote does not have. */
13525
+ const ZERO = /^0+$/;
13526
+ /** The form of a sha of a commit. */
13527
+ const SHA = /^[0-9a-f]{40,64}$/;
13528
+ /**
13529
+ * This function reads the settings of the rule `no-local-paths` in the root `package.json`: the state, the permitted names
13530
+ * and the globs of `ignore` and `generated`. They apply only to the home folders. A private pattern always counts.
13531
+ */
13532
+ function homeSettings(root, readFile) {
13533
+ try {
13534
+ const config = parseConfig(JSON.parse(readFile(join(root, "package.json")))["conventions"], RULES).rules["no-local-paths"];
13535
+ if (config === void 0) return {
13536
+ on: true,
13537
+ allow: [],
13538
+ ignore: []
13539
+ };
13540
+ const allow = config.options["allow"];
13541
+ return {
13542
+ on: config.off === void 0,
13543
+ allow: Array.isArray(allow) ? [...allow] : [],
13544
+ ignore: [...config.ignore, ...config.generated ?? []]
13545
+ };
13546
+ } catch {
13547
+ return {
13548
+ on: true,
13549
+ allow: [],
13550
+ ignore: []
13551
+ };
13552
+ }
13553
+ }
13554
+ /** This function gives the text of a path in a header of a patch, without the quotes of git. */
13555
+ function unquote(path) {
13556
+ if (!path.startsWith("\"") || !path.endsWith("\"")) return path;
13557
+ const bytes = [];
13558
+ const body = path.slice(1, -1);
13559
+ const escapes = {
13560
+ a: 7,
13561
+ b: 8,
13562
+ t: 9,
13563
+ n: 10,
13564
+ v: 11,
13565
+ f: 12,
13566
+ r: 13,
13567
+ "\"": 34,
13568
+ "\\": 92
13569
+ };
13570
+ for (let index = 0; index < body.length; index++) {
13571
+ if (body.charAt(index) !== "\\") {
13572
+ const char = String.fromCodePoint(body.codePointAt(index) ?? 0);
13573
+ bytes.push(...Buffer.from(char, "utf8"));
13574
+ index += char.length - 1;
13575
+ continue;
13576
+ }
13577
+ const octal = /^[0-7]{3}/.exec(body.slice(index + 1));
13578
+ if (octal !== null) {
13579
+ bytes.push(parseInt(octal[0], 8));
13580
+ index += 3;
13581
+ continue;
13582
+ }
13583
+ const next = body.charAt(index + 1);
13584
+ bytes.push(escapes[next] ?? next.charCodeAt(0));
13585
+ index += 1;
13586
+ }
13587
+ return Buffer.from(bytes).toString("utf8");
13588
+ }
13589
+ /**
13590
+ * This function gives the added lines of a patch of `git show --unified=0`, in runs of lines that follow each other.
13591
+ * It reads the counts of each hunk, so an added line that starts with `+++` is a line, not a header. It also reads the
13592
+ * combined patch of a merge commit, with one column of marks for each parent.
13593
+ */
13594
+ function addedRuns(patch) {
13595
+ const runs = [];
13596
+ let file;
13597
+ let columns = 1;
13598
+ let parentLeft = [];
13599
+ let resultLeft = 0;
13600
+ let next = 0;
13601
+ for (const raw of patch.split("\n")) {
13602
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
13603
+ if (line.startsWith("\\")) continue;
13604
+ if (resultLeft > 0 || parentLeft.some((count) => count > 0)) {
13605
+ const marks = line.slice(0, columns);
13606
+ const removed = marks.includes("-");
13607
+ for (let column = 0; column < columns; column++) {
13608
+ const mark = marks.charAt(column);
13609
+ if (mark === "-" || !removed && mark === " ") parentLeft[column] = (parentLeft[column] ?? 0) - 1;
13610
+ }
13611
+ if (removed) continue;
13612
+ resultLeft -= 1;
13613
+ if (marks.includes("+") && file !== void 0) {
13614
+ const text = line.slice(columns);
13615
+ const last = runs.at(-1);
13616
+ if (last !== void 0 && last.file === file && last.first + last.lines.length === next) last.lines.push(text);
13617
+ else runs.push({
13618
+ file,
13619
+ first: next,
13620
+ lines: [text]
13621
+ });
13622
+ }
13623
+ next += 1;
13624
+ continue;
13625
+ }
13626
+ if (line.startsWith("diff ")) {
13627
+ file = void 0;
13628
+ continue;
13629
+ }
13630
+ if (line.startsWith("+++ ")) {
13631
+ const path = unquote(line.slice(4));
13632
+ file = path === "/dev/null" ? void 0 : path.replace(/^b\//, "");
13633
+ continue;
13634
+ }
13635
+ const hunk = /^(@{2,}) ((?:-\d+(?:,\d+)? )+)\+(\d+)(?:,(\d+))? \1/.exec(line);
13636
+ if (hunk === null) continue;
13637
+ columns = (hunk[1] ?? "@@").length - 1;
13638
+ parentLeft = (hunk[2] ?? "").trim().split(" ").map((range) => {
13639
+ const count = /^-\d+(?:,(\d+))?$/.exec(range)?.[1];
13640
+ return count === void 0 ? 1 : Number(count);
13641
+ });
13642
+ next = Number(hunk[3]);
13643
+ resultLeft = hunk[4] === void 0 ? 1 : Number(hunk[4]);
13644
+ }
13645
+ return runs;
13646
+ }
13647
+ /** This function gives the place of a break as `file:line`. */
13648
+ const placeOf$1 = (item) => item.line === void 0 ? item.file : `${item.file}:${String(item.line)}`;
13649
+ /** This function examines one commit: its message, the paths that it adds or changes, and each line that it adds. */
13650
+ function readCommit(sha, privates, home, repo, git) {
13651
+ const short = sha.slice(0, 12);
13652
+ const message = git([
13653
+ "show",
13654
+ "-s",
13655
+ "--format=%B",
13656
+ sha
13657
+ ]);
13658
+ const names = git([
13659
+ "show",
13660
+ "--format=",
13661
+ "--name-only",
13662
+ "--diff-filter=AMRC",
13663
+ "-z",
13664
+ "--no-ext-diff",
13665
+ sha
13666
+ ]);
13667
+ const patch = git([
13668
+ "-c",
13669
+ "core.quotePath=false",
13670
+ "show",
13671
+ "--format=",
13672
+ "--no-color",
13673
+ "--unified=0",
13674
+ "--no-ext-diff",
13675
+ "--no-textconv",
13676
+ "--src-prefix=a/",
13677
+ "--dst-prefix=b/",
13678
+ sha
13679
+ ]);
13680
+ if (message === void 0 || names === void 0 || patch === void 0) return void 0;
13681
+ const breaks = [];
13682
+ const add = (items) => {
13683
+ for (const item of items) breaks.push(item);
13684
+ };
13685
+ const text = message.replace(/\s+$/, "");
13686
+ add(privateTextBreaks(`commit ${short} message`, text, privates, {
13687
+ allow: home.allow,
13688
+ homes: home.on
13689
+ }));
13690
+ let lines = text === "" ? 0 : text.split(/\r?\n/).length;
13691
+ const runs = addedRuns(patch);
13692
+ const paths = names.replace(/^\n+/, "").split("\0").filter((path) => path !== "");
13693
+ for (const run of runs) if (!paths.includes(run.file)) paths.push(run.file);
13694
+ const shown = /* @__PURE__ */ new Map();
13695
+ paths.forEach((path, index) => {
13696
+ const homes = home.on && !matchesAny(path, home.ignore);
13697
+ const found = privateTextBreaks(`commit ${short} path ${String(index + 1)}`, path, privates, {
13698
+ allow: home.allow,
13699
+ homes,
13700
+ isPath: true
13701
+ });
13702
+ lines += 1;
13703
+ shown.set(path, found.length > 0 ? `commit ${short} path ${String(index + 1)}` : `commit ${short} ${path}`);
13704
+ for (const item of found) breaks.push({
13705
+ file: item.file,
13706
+ message: item.message.replace(/^A text /, "The path "),
13707
+ ...item.fix === void 0 ? {} : { fix: item.fix }
13708
+ });
13709
+ });
13710
+ for (const run of runs) {
13711
+ const homes = home.on && !matchesAny(run.file, home.ignore);
13712
+ const place = {
13713
+ ...repo === void 0 ? {} : { repo },
13714
+ path: run.file
13715
+ };
13716
+ add(privateTextBreaks(shown.get(run.file) ?? `commit ${short} ${run.file}`, run.lines.join("\n"), privates, {
13717
+ allow: home.allow,
13718
+ homes,
13719
+ firstLine: run.first,
13720
+ rootPackage: run.file === "package.json",
13721
+ ...place
13722
+ }));
13723
+ lines += run.lines.length;
13724
+ }
13725
+ return {
13726
+ breaks,
13727
+ lines
13728
+ };
13729
+ }
13730
+ /** This function gives the reason of a read that failed, in words. */
13731
+ function readReason(error) {
13732
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
13733
+ if (code === "ENOENT") return "the file does not exist";
13734
+ if (code === "EISDIR") return "the path is a folder";
13735
+ if (code === "EACCES" || code === "EPERM") return "the file has no read permission";
13736
+ return error instanceof Error ? error.message : String(error);
13737
+ }
13738
+ /**
13739
+ * This function gives the repository `owner/name` of the push: from the URL of the hook, else from `git remote get-url`.
13740
+ * It gives undefined when neither URL is a URL of a GitHub repository.
13741
+ */
13742
+ function repoOfPush(options) {
13743
+ return (options.url === void 0 ? void 0 : repositoryOfRemote(options.url)) ?? repositoryOfRemote(options.git([
13744
+ "remote",
13745
+ "get-url",
13746
+ options.remote
13747
+ ]) ?? "");
13748
+ }
13749
+ /**
13750
+ * This function is the command `conventions pre-push`. It examines each new commit of the push: its message, the paths
13751
+ * that it adds or changes, and each line that it adds. It writes the breaks to `stderr`, and gives the exit code: 1 on a
13752
+ * break, 0 on a pass. With no private name list and no private pattern, it writes the line `NO_READ_LINE` and gives 0.
13753
+ */
13754
+ function prePush(options, io) {
13755
+ const readFile = options.readFile ?? ((path) => readFileSync(path, "utf8"));
13756
+ const file = privateNamesFile(options.env, options.git);
13757
+ const patterns = privatePatterns(options.env);
13758
+ if (file === void 0 && patterns.length === 0) {
13759
+ io.stderr(`${NO_READ_LINE}\n`);
13760
+ return 0;
13761
+ }
13762
+ let names;
13763
+ if (file !== void 0) {
13764
+ const source = (options.env["CONVENTIONS_PRIVATE_NAMES_FILE"]?.trim() ?? "") !== "" ? PRIVATE_NAMES_FILE_VARIABLE : `the git config ${PRIVATE_NAMES_FILE_CONFIG}`;
13765
+ let text;
13766
+ try {
13767
+ text = readFile(resolve(options.root, file));
13768
+ } catch (error) {
13769
+ io.stderr(`conventions pre-push: Cannot read the private name list that ${source} names: ${readReason(error)}. Correct the setting or the file. The push stops.\n`);
13770
+ return 1;
13771
+ }
13772
+ try {
13773
+ names = parsePrivateNames(text);
13774
+ } catch (error) {
13775
+ const reason = error instanceof PrivateNameListError ? error.reason : "the parse failed";
13776
+ io.stderr(`conventions pre-push: The private name list that ${source} names is not valid: ${reason}. Correct the file. The push stops.\n`);
13777
+ return 1;
13778
+ }
13779
+ }
13780
+ const privates = {
13781
+ ...names === void 0 ? {} : { names },
13782
+ patterns
13783
+ };
13784
+ const repo = names === void 0 || names.allow.length === 0 ? void 0 : repoOfPush(options);
13785
+ const home = homeSettings(options.root, readFile);
13786
+ const breaks = invalidPatternBreaks(patterns);
13787
+ const commits = /* @__PURE__ */ new Set();
13788
+ for (const line of options.input.split(/\r?\n/)) {
13789
+ if (line.trim() === "") continue;
13790
+ const [localRef, localSha, , remoteSha] = line.trim().split(/\s+/);
13791
+ if (localSha === void 0 || remoteSha === void 0 || !SHA.test(localSha) || !SHA.test(remoteSha)) {
13792
+ io.stderr(`conventions pre-push: The input line "${line.trim()}" does not have the form <local ref> <local sha> <remote ref> <remote sha>. The push stops.\n`);
13793
+ return 1;
13794
+ }
13795
+ if (ZERO.test(localSha)) continue;
13796
+ const others = [
13797
+ "rev-list",
13798
+ localSha,
13799
+ "--not",
13800
+ `--remotes=${options.remote}`
13801
+ ];
13802
+ const listed = ZERO.test(remoteSha) ? options.git(others) : options.git([
13803
+ "rev-list",
13804
+ localSha,
13805
+ `^${remoteSha}`
13806
+ ]) ?? options.git(others);
13807
+ if (listed === void 0) {
13808
+ io.stderr(`conventions pre-push: git cannot list the new commits of ${localRef ?? localSha}. The push stops.\n`);
13809
+ return 1;
13810
+ }
13811
+ for (const sha of listed.split(/\r?\n/)) if (SHA.test(sha.trim())) commits.add(sha.trim());
13812
+ }
13813
+ let lines = 0;
13814
+ for (const sha of commits) {
13815
+ const read = readCommit(sha, privates, home, repo, options.git);
13816
+ if (read === void 0) {
13817
+ io.stderr(`conventions pre-push: git cannot show the commit ${sha.slice(0, 12)}. The push stops.\n`);
13818
+ return 1;
13819
+ }
13820
+ for (const item of read.breaks) breaks.push(item);
13821
+ lines += read.lines;
13822
+ }
13823
+ if (breaks.length === 0) {
13824
+ io.stderr(`conventions pre-push: ${String(commits.size)} commits, ${String(lines)} lines read, 0 breaks.\n`);
13825
+ return 0;
13826
+ }
13827
+ const out = [`conventions pre-push: ${String(commits.size)} commits, ${String(lines)} lines read, ${String(breaks.length)} breaks. The push stops.`];
13828
+ for (const item of breaks) {
13829
+ out.push(` ${placeOf$1(item)} ${item.message}`);
13830
+ if (item.fix !== void 0) out.push(` fix: ${item.fix}`);
13831
+ }
13832
+ out.push("Change the commits (git commit --amend, or git rebase), and push again.");
13833
+ io.stderr(`${out.join("\n")}\n`);
13834
+ return 1;
13835
+ }
13836
+ /** The marker line of the hook that `conventions hook install` writes. The command rewrites only a hook with this line. */
13837
+ const HOOK_MARKER = "# conventions hook: pre-push";
13838
+ /** The text of the hook `pre-push` that `conventions hook install` writes: a POSIX shell script. */
13839
+ const PRE_PUSH_HOOK = `#!/bin/sh
13840
+ ${HOOK_MARKER}
13841
+ # The command "conventions hook install" wrote this file, and each install writes it again.
13842
+ # The hook examines the new commits of each push with the private name list.
13843
+ root="$(git rev-parse --show-toplevel)" || exit 1
13844
+ bin="$root/node_modules/.bin/conventions"
13845
+ if [ -x "$bin" ]; then
13846
+ exec "$bin" pre-push "$@"
13847
+ fi
13848
+ exec pnpm exec conventions pre-push "$@"
13849
+ `;
13850
+ /** This function tells if the environment is a CI run. */
13851
+ const isCi = (env) => ["true", "1"].includes((env["CI"] ?? "").toLowerCase()) || env["GITHUB_ACTIONS"] === "true";
13852
+ /**
13853
+ * This function is the command `conventions hook install`. It writes the hook `pre-push` into the hooks folder of git,
13854
+ * so it uses the folder of `core.hooksPath` and works in a worktree. It keeps a hook that does not have `HOOK_MARKER`, and writes a warning.
13855
+ * In CI or outside a git repository, it writes one line and does nothing.
13856
+ */
13857
+ function installHook(options, io) {
13858
+ if (isCi(options.env)) {
13859
+ io.stdout("conventions hook install: CI has no push hook, so the command does nothing.\n");
13860
+ return 0;
13861
+ }
13862
+ const hooks = options.git([
13863
+ "rev-parse",
13864
+ "--git-path",
13865
+ "hooks"
13866
+ ])?.trim() ?? "";
13867
+ if (hooks === "") {
13868
+ io.stdout("conventions hook install: The folder is not in a git repository, so the command does nothing.\n");
13869
+ return 0;
13870
+ }
13871
+ const dir = resolve(options.cwd, hooks);
13872
+ const file = join(dir, "pre-push");
13873
+ const shown = `${hooks.replace(/[\\/]+$/, "")}/pre-push`;
13874
+ const before = existsSync(file) ? readFileSync(file, "utf8") : void 0;
13875
+ if (before !== void 0 && !before.includes("# conventions hook: pre-push")) {
13876
+ io.stderr(`conventions hook install: warning: ${shown} exists and conventions did not write it. The command keeps it. Add the line 'conventions pre-push "$@"' to it, or remove it and install again.\n`);
13877
+ return 0;
13878
+ }
13879
+ if (before === "#!/bin/sh\n# conventions hook: pre-push\n# The command \"conventions hook install\" wrote this file, and each install writes it again.\n# The hook examines the new commits of each push with the private name list.\nroot=\"$(git rev-parse --show-toplevel)\" || exit 1\nbin=\"$root/node_modules/.bin/conventions\"\nif [ -x \"$bin\" ]; then\n exec \"$bin\" pre-push \"$@\"\nfi\nexec pnpm exec conventions pre-push \"$@\"\n") {
13880
+ io.stdout(`conventions hook install: ${shown} is current.\n`);
13881
+ return 0;
13882
+ }
13883
+ try {
13884
+ mkdirSync(dir, { recursive: true });
13885
+ writeFileSync(file, PRE_PUSH_HOOK, { mode: 493 });
13886
+ chmodSync(file, 493);
13887
+ } catch (error) {
13888
+ io.stderr(`conventions hook install: Cannot write ${shown}: ${error instanceof Error ? error.message : String(error)}\n`);
13889
+ return 1;
13890
+ }
13891
+ io.stdout(`conventions hook install: ${before === void 0 ? "wrote" : "updated"} ${shown}.\n`);
13892
+ return 0;
13893
+ }
12884
13894
  // src/run.ts
12885
13895
  /**
12886
13896
  * The commands `check`, `fix` and `--list` of the bin `conventions`, as functions. `runChecks` starts the
12887
13897
  * rules, `runFix` writes the edits of the breaks, and `runCli` reads the arguments and writes the result.
13898
+ * The commands `pre-push` and `hook install` are in `pre-push.ts`.
12888
13899
  */
12889
13900
  /** This function reads a `package.json` file. */
12890
13901
  function readPackage(root, dir) {
@@ -13150,12 +14161,21 @@ const USAGE = `Usage: conventions check [options]
13150
14161
  conventions fix [options]
13151
14162
  conventions --list
13152
14163
  conventions map [words] [--markdown | --json] [--overlay <file>]
14164
+ conventions pre-push <remote> [<url>]
14165
+ conventions hook install
13153
14166
 
13154
14167
  check Start each rule. Exit code 1 when a rule has a break.
13155
14168
  fix Write the fixes of the breaks that have one, and check again. Exit code 1 when a break stays.
13156
14169
  --list Show each rule: why, fix, options, state and the audit rows that it comes from.
13157
14170
  map Show the home package of each area of code, or of the areas that match the words.
13158
14171
  --markdown writes the table with the rule, and --overlay adds the homes of a JSON file.
14172
+ pre-push The git hook pre-push starts it. It reads the refs of the push on the standard input, and
14173
+ examines each new commit with the private name list: the message, the paths and the added
14174
+ lines. Exit code 1 on a break. The list is the JSON file of CONVENTIONS_PRIVATE_NAMES_FILE, else
14175
+ of the git config conventions.privateNamesFile. CONVENTIONS_PRIVATE_PATTERNS adds one regular
14176
+ expression on each line. With neither, it writes a "No read" line and gives 0.
14177
+ hook install Write the hook pre-push into the hooks folder of git. It keeps a hook that it did not write.
14178
+ In CI, or outside a git repository, it does nothing.
13159
14179
 
13160
14180
  --root <folder> The root of the repository. The default is the current folder.
13161
14181
  --rule <id> Only this rule. Use it again for more rules.
@@ -13201,6 +14221,8 @@ var UsageError = class extends Error {};
13201
14221
  /** This function starts the bin with the arguments `args`, and gives its exit code. */
13202
14222
  function runCli(args, io) {
13203
14223
  if (args[0] === "map") return runMap(args.slice(1), io);
14224
+ if (args[0] === "pre-push") return runPrePush(args.slice(1), io);
14225
+ if (args[0] === "hook") return runHook(args.slice(1), io);
13204
14226
  let check = false;
13205
14227
  let fix = false;
13206
14228
  let list = false;
@@ -13315,6 +14337,37 @@ function runMap(args, io) {
13315
14337
  else io.stdout(mapText(found));
13316
14338
  return 0;
13317
14339
  }
13318
- export { isPinned as $, codePackages as $t, pathsOf as A, findHomes as At, lockedVersions as B, securityOneJob as Bt, configsOfScript as C, declaredName as Ct, hasTests as D, signaturesOf as Dt, testsRequired as E, repoOf as Et, sharedDocsRule as F, HOME_EXPORTS as Ft, NPM_REGISTRY as G, prPathFilters as Gt, publishedMinor as H, ACTIONS_COMMIT as Ht, roadmapOfLine as I, SECURITY_SCAN_COMMIT as It, npmLookup as J, readWorkflow as Jt, SHIPPED_FIELDS as K, summaryName as Kt, roadmapParses as L, SECURITY_SCAN_INPUTS as Lt, HOME_TIMEOUT_MS as M, mapText as Mt, blockHash as N, mergeHomes as Nt, tsconfigTest as O, HOMES as Ot, githubFetch as P, readOverlay as Pt, isGitSpecifier as Q, cleanPath as Qt, requiredScripts as R, SECURITY_TIMEOUT_MINUTES as Rt, typedScripts as S, repositoryIsPublic as St, typedFiles as T, messageOf as Tt, publishedMinorRule as U, convertGate as Ut, minorOf as V, withOneJob as Vt, reachOf as W, gateTrigger as Wt, unreleasedChangeRule as X, cuePreset as Xt, unreleasedChange as Y, STRICT_OPTIONS as Yt, pipeFails as Z, DEPENDENCY_FIELDS as Zt, setVersions as _, LICENSE_TEXTS as _t, listRules as a, parseJsonc as an, pushMainOnly as at, TRAIN_SCOPES as b, licenseFileOf as bt, runCli as c, runGit as cn, pagesSite as ct, RULES as d, globToRegExp as dn, HOME_PATTERNS as dt, hasFile as en, pinnedGitDeps as et, workspaceProtocol as f, packageFolders as fn, noLocalPaths as ft, namedVersions as g, mainCheck as gt, yamlFaults as h, parseConfig as hn, hasImportMetaMain as ht, formatResult as i, matchesAny as in, scheduleMinute as it, sourceMain as j, mapMarkdown as jt, isSourcePath as k, MAP_RULE as kt, runFix as l, specifiersOf as ln, apiReportScript as lt, workflowParses as m, defaultOptions as mn, REAL_COMPARE as mt, annotations as n, keyLine as nn, repositoryOfRemote as nt, readConfig as o, readJsonc as on, PAGES_WORKFLOWS as ot, GITHUB_YAML as p, workspaceGlobs as pn, noBuildOutput as pt, UNSHIPPED_FILES as q, gateAfterCancel as qt, createContext as r, lineOf as rn, runnerBudget as rt, runChecks as s, replaceLine as sn, pagesCalls as st, USAGE as t, inFolder as tn, pagesAfterRelease as tt, summaryMarkdown as u, globFolders as un, DEFAULT_ALLOWED as ut, versionTitle as v, authorOf as vt, scriptsOf as w, homePackage as wt, trustPolicy as x, mitText as xt, IGNORE_AFTER as y, licenseFile as yt, releaseFiles as z, securityCallers as zt };
14340
+ /** The command `pre-push`: the arguments of the git hook, the remote and its URL. */
14341
+ function runPrePush(args, io) {
14342
+ const remote = args[0];
14343
+ if (remote === void 0 || remote.startsWith("-") || args.length > 2) {
14344
+ io.stderr(`conventions: The command pre-push takes the name of the remote and, after it, its URL.\n\n${USAGE}`);
14345
+ return 2;
14346
+ }
14347
+ const top = runGit(io.cwd, ["rev-parse", "--show-toplevel"])?.trim() ?? "";
14348
+ const root = top === "" ? io.cwd : top;
14349
+ const url = args[1];
14350
+ return prePush({
14351
+ remote,
14352
+ ...url === void 0 ? {} : { url },
14353
+ input: io.stdin ?? "",
14354
+ env: io.env,
14355
+ root,
14356
+ git: (gitArgs) => runGit(root, gitArgs)
14357
+ }, io);
14358
+ }
14359
+ /** The command `hook install`: it writes the git hook pre-push. */
14360
+ function runHook(args, io) {
14361
+ if (args.length !== 1 || args[0] !== "install") {
14362
+ io.stderr(`conventions: The command hook takes one argument: install.\n\n${USAGE}`);
14363
+ return 2;
14364
+ }
14365
+ return installHook({
14366
+ cwd: io.cwd,
14367
+ env: io.env,
14368
+ git: (gitArgs) => runGit(io.cwd, gitArgs)
14369
+ }, io);
14370
+ }
14371
+ export { unreleasedChangeRule as $, mergeHomes as $t, typedFiles as A, hasFile as An, nameMatches as At, roadmapParses as B, globFolders as Bn, licenseFileOf as Bt, versionTitle as C, gateAfterCancel as Cn, PRIVATE_NAME_LIST as Ct, typedScripts as D, DEPENDENCY_FIELDS as Dn, isCommonUse as Dt, trustPolicy as E, cuePreset as En, isAllowedHit as Et, HOME_TIMEOUT_MS as F, parseJsonc as Fn, hasImportMetaMain as Ft, publishedMinor as G, parseConfig as Gn, messageOf as Gt, releaseFiles as H, packageFolders as Hn, repositoryIsPublic as Ht, blockHash as I, readJsonc as In, mainCheck as It, NPM_REGISTRY as J, HOMES as Jt, publishedMinorRule as K, repoOf as Kt, githubFetch as L, replaceLine as Ln, LICENSE_TEXTS as Lt, isSourcePath as M, keyLine as Mn, pathNameHit as Mt, pathsOf as N, lineOf as Nn, noBuildOutput as Nt, configsOfScript as O, cleanPath as On, lineNameHit as Ot, sourceMain as P, matchesAny as Pn, REAL_COMPARE as Pt, unreleasedChange as Q, mapText as Qt, sharedDocsRule as R, runGit as Rn, authorOf as Rt, setVersions as S, summaryName as Sn, privateTextBreaks as St, TRAIN_SCOPES as T, STRICT_OPTIONS as Tn, firstNameMatch as Tt, lockedVersions as U, workspaceGlobs as Un, declaredName as Ut, requiredScripts as V, globToRegExp as Vn, mitText as Vt, minorOf as W, defaultOptions as Wn, homePackage as Wt, UNSHIPPED_FILES as X, findHomes as Xt, SHIPPED_FIELDS as Y, MAP_RULE as Yt, npmLookup as Z, mapMarkdown as Zt, workspaceProtocol as _, withOneJob as _n, PRIVATE_PATTERNS_VARIABLE as _t, listRules as a, hasTests as an, repositoryOfRemote as at, yamlFaults as b, gateTrigger as bn, privateNamesFile as bt, runCli as c, SHARED_CI as cn, pushMainOnly as ct, HOOK_MARKER as d, sharedCi as dn, pagesSite as dt, readOverlay as en, pipeFails as et, NO_READ_LINE as f, SECURITY_SCAN_COMMIT as fn, apiReportScript as ft, RULES as g, securityOneJob as gn, PRIVATE_NAMES_FILE_VARIABLE as gt, prePush as h, securityCallers as hn, PRIVATE_NAMES_FILE_CONFIG as ht, formatResult as i, serviceRunMain as in, pagesAfterRelease as it, testsRequired as j, inFolder as jn, parsePrivateNames as jt, scriptsOf as k, codePackages as kn, lineNameHits as kt, runFix as l, SHARED_WORKFLOWS as ln, PAGES_WORKFLOWS as lt, installHook as m, SECURITY_TIMEOUT_MINUTES as mn, HOME_PATTERNS as mt, annotations as n, SERVICE_PACKAGE as nn, isPinned as nt, readConfig as o, tsconfigTest as on, runnerBudget as ot, PRE_PUSH_HOOK as p, SECURITY_SCAN_INPUTS as pn, DEFAULT_ALLOWED as pt, reachOf as q, signaturesOf as qt, createContext as r, runCalls as rn, pinnedGitDeps as rt, runChecks as s, SHARED_ACTIONS as sn, scheduleMinute as st, USAGE as t, HOME_EXPORTS as tn, isGitSpecifier as tt, summaryMarkdown as u, callsSharedCi as un, pagesCalls as ut, GITHUB_YAML as v, ACTIONS_COMMIT as vn, invalidPatternBreaks as vt, IGNORE_AFTER as w, readWorkflow as wn, PrivateNameListError as wt, namedVersions as x, prPathFilters as xn, privatePatterns as xt, workflowParses as y, convertGate as yn, noLocalPaths as yt, roadmapOfLine as z, specifiersOf as zn, licenseFile as zt };
13319
14372
 
13320
- //# sourceMappingURL=run-CDGXnpQk.js.map
14373
+ //# sourceMappingURL=run-DjrYJDna.js.map