@trops/dash-check 0.0.0-stage → 0.1.0

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +309 -2
  3. package/cli/bin.js +12 -0
  4. package/cli/index.d.ts +7 -0
  5. package/cli/index.js +566 -0
  6. package/examples/changes-match-plan.bad.json +4 -0
  7. package/examples/changes-match-plan.check.js +10 -0
  8. package/examples/changes-match-plan.sample.json +4 -0
  9. package/examples/every-acceptance-has-a-test.bad.json +3 -0
  10. package/examples/every-acceptance-has-a-test.check.js +19 -0
  11. package/examples/every-acceptance-has-a-test.sample.json +3 -0
  12. package/examples/helpers/changelog.js +23 -0
  13. package/examples/jira-comment-from-job.bad.json +5 -0
  14. package/examples/jira-comment-from-job.check.js +10 -0
  15. package/examples/jira-comment-from-job.sample.json +5 -0
  16. package/examples/merge-outcome.bad.json +4 -0
  17. package/examples/merge-outcome.check.js +9 -0
  18. package/examples/merge-outcome.sample.json +4 -0
  19. package/examples/on-branch.bad.json +6 -0
  20. package/examples/on-branch.check.js +12 -0
  21. package/examples/on-branch.sample.json +6 -0
  22. package/examples/plan-complete.bad.json +5 -0
  23. package/examples/plan-complete.check.js +14 -0
  24. package/examples/plan-complete.sample.json +5 -0
  25. package/examples/pr-ci.bad.json +4 -0
  26. package/examples/pr-ci.check.js +12 -0
  27. package/examples/pr-ci.sample.json +4 -0
  28. package/examples/ready-for-review.bad.json +6 -0
  29. package/examples/ready-for-review.check.json +12 -0
  30. package/examples/ready-for-review.sample.json +6 -0
  31. package/examples/setup.bad.json +6 -0
  32. package/examples/setup.check.js +8 -0
  33. package/examples/setup.sample.json +6 -0
  34. package/examples/ticket-has-acceptance.bad.json +4 -0
  35. package/examples/ticket-has-acceptance.check.js +10 -0
  36. package/examples/ticket-has-acceptance.sample.json +4 -0
  37. package/examples/validate.bad.json +6 -0
  38. package/examples/validate.check.js +14 -0
  39. package/examples/validate.sample.json +6 -0
  40. package/examples/work-committed.bad.json +13 -0
  41. package/examples/work-committed.check.js +13 -0
  42. package/examples/work-committed.sample.json +5 -0
  43. package/examples/workspace-cleaned.bad.json +4 -0
  44. package/examples/workspace-cleaned.check.js +7 -0
  45. package/examples/workspace-cleaned.sample.json +4 -0
  46. package/helpers/commands.js +62 -0
  47. package/helpers/files.js +74 -0
  48. package/helpers/git.js +116 -0
  49. package/helpers/github.js +77 -0
  50. package/helpers/handoff.js +80 -0
  51. package/helpers/index.d.ts +15 -0
  52. package/helpers/index.js +36 -0
  53. package/helpers/node.js +106 -0
  54. package/helpers/plan.js +55 -0
  55. package/helpers/tracker.js +60 -0
  56. package/index.d.ts +325 -0
  57. package/index.js +86 -0
  58. package/lib/adapters/fs.js +85 -0
  59. package/lib/adapters/git.js +87 -0
  60. package/lib/adapters/github.js +151 -0
  61. package/lib/adapters/run.js +76 -0
  62. package/lib/adapters/tool.js +64 -0
  63. package/lib/context.js +102 -0
  64. package/lib/discover.js +102 -0
  65. package/lib/expect.js +238 -0
  66. package/lib/glob.js +89 -0
  67. package/lib/handoff.js +68 -0
  68. package/lib/helper.js +219 -0
  69. package/lib/register.js +35 -0
  70. package/lib/runner.js +214 -0
  71. package/lib/scope.js +107 -0
  72. package/lib/util.js +122 -0
  73. package/lib/values.js +138 -0
  74. package/package.json +59 -4
  75. package/recipe/index.d.ts +70 -0
  76. package/recipe/index.js +381 -0
  77. package/recipe/schema.json +55 -0
package/lib/values.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * values.js: reading a value by path, and filling "{placeholders}".
3
+ *
4
+ * A path starts at one of the context's data roots:
5
+ * input, answer, handoff, item, workspace, picks, row, settings, step, job, env
6
+ * Any other first word is looked up in the picked table rows, then in the
7
+ * team settings, so "{repo.baseBranch}" is row.repo.baseBranch and
8
+ * "{workRoot}" is settings.workRoot.
9
+ */
10
+ "use strict";
11
+
12
+ const { getPath, splitPath, isObj, isEmpty, DashCheckError } = require("./util");
13
+
14
+ const ROOTS = ["input", "answer", "handoff", "item", "workspace", "picks", "row", "settings", "step", "job", "env"];
15
+ const TOKEN = /\{\{|\}\}|\{([A-Za-z_$][\w$-]*(?:\.[\w$-]+)*)\}/g;
16
+
17
+ /** { found, value } for a path in a context. */
18
+ function lookup(ctx, p) {
19
+ const parts = splitPath(p);
20
+ if (!parts.length) return { found: false };
21
+ const [first, ...rest] = parts;
22
+ if (ROOTS.includes(first)) {
23
+ const v = getPath(ctx[first], rest);
24
+ return { found: v !== undefined, value: v };
25
+ }
26
+ for (const root of ["row", "settings"]) {
27
+ const base = ctx[root];
28
+ if (isObj(base) && base[first] !== undefined) {
29
+ const v = getPath(base, parts);
30
+ return { found: v !== undefined, value: v };
31
+ }
32
+ }
33
+ return { found: false };
34
+ }
35
+
36
+ /** The value at a path ("handoff.files", "repo.baseBranch"), or undefined. */
37
+ function get(ctx, p) {
38
+ return lookup(ctx, p).value;
39
+ }
40
+
41
+ /** Is there a placeholder in this text? */
42
+ const hasPlaceholder = (s) => typeof s === "string" && /\{[A-Za-z_$][\w$-]*(?:\.[\w$-]+)*\}/.test(s);
43
+
44
+ /**
45
+ * Fill "{placeholders}" in a string (deep in arrays and objects).
46
+ * A string that is only one placeholder keeps the value's type.
47
+ * "{{" and "}}" are literal braces.
48
+ * @param {object} ctx
49
+ * @param {any} value
50
+ * @param {{ missing?: "throw" | "empty" | "keep" }} [opts]
51
+ */
52
+ function fill(ctx, value, opts = {}) {
53
+ const missing = opts.missing || "throw";
54
+ if (Array.isArray(value)) return value.map((v) => fill(ctx, v, opts));
55
+ if (isObj(value)) {
56
+ const out = {};
57
+ for (const [k, v] of Object.entries(value)) out[k] = fill(ctx, v, opts);
58
+ return out;
59
+ }
60
+ if (typeof value !== "string") return value;
61
+ const whole = value.match(/^\{([A-Za-z_$][\w$-]*(?:\.[\w$-]+)*)\}$/);
62
+ if (whole) {
63
+ const r = lookup(ctx, whole[1]);
64
+ if (r.found) return r.value;
65
+ return onMissing(whole[1], value, missing);
66
+ }
67
+ return value.replace(TOKEN, (m, p) => {
68
+ if (m === "{{") return "{";
69
+ if (m === "}}") return "}";
70
+ const r = lookup(ctx, p);
71
+ if (r.found) return typeof r.value === "object" ? JSON.stringify(r.value) : String(r.value);
72
+ const out = onMissing(p, m, missing);
73
+ return out === undefined ? "" : out;
74
+ });
75
+ }
76
+
77
+ function onMissing(p, raw, missing) {
78
+ if (missing === "keep") return raw;
79
+ if (missing === "empty") return undefined;
80
+ const first = splitPath(p)[0];
81
+ const where = ROOTS.includes(first)
82
+ ? `the job has no ${p}`
83
+ : `there's no table row or team setting named "${first}"${p.includes(".") ? ` with ${p.slice(first.length + 1)}` : ""}`;
84
+ throw new DashCheckError(`{${p}} has no value here (${where})`, {
85
+ fix: "pick the row or set the setting on the team, or give the value directly",
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Is a `when` true? A path ("handoff.prUrl") or a placeholder
91
+ * ("{mergeWhenGreen}"); "!" in front turns it around. Empty, false,
92
+ * "false", "no", "off" and "0" are false.
93
+ */
94
+ function when(ctx, expr) {
95
+ if (typeof expr === "boolean") return expr;
96
+ if (expr === undefined || expr === null) return true;
97
+ let s = String(expr).trim();
98
+ let not = false;
99
+ while (s.startsWith("!")) {
100
+ not = !not;
101
+ s = s.slice(1).trim();
102
+ }
103
+ const v = hasPlaceholder(s) ? fill(ctx, s, { missing: "empty" }) : get(ctx, s);
104
+ return not ? !truthy(v) : truthy(v);
105
+ }
106
+
107
+ function truthy(v) {
108
+ if (typeof v === "string") return !["", "false", "no", "off", "0"].includes(v.trim().toLowerCase());
109
+ if (typeof v === "number") return v !== 0 && !Number.isNaN(v);
110
+ if (typeof v === "boolean") return v;
111
+ return !isEmpty(v);
112
+ }
113
+
114
+ /**
115
+ * Every value path in a sample input's context, for a value picker:
116
+ * [{ path, type, sample }].
117
+ */
118
+ function valuePaths(ctx, { maxDepth = 4, max = 300 } = {}) {
119
+ const out = [];
120
+ const walk = (v, p, d) => {
121
+ if (out.length >= max) return;
122
+ const type = Array.isArray(v) ? "list" : v === null ? "null" : typeof v;
123
+ if (p) out.push({ path: p, type, ...(type === "object" || type === "list" ? {} : { sample: v }) });
124
+ if (d >= maxDepth) return;
125
+ if (isObj(v)) for (const k of Object.keys(v)) walk(v[k], p ? `${p}.${k}` : k, d + 1);
126
+ };
127
+ for (const root of ["handoff", "item", "workspace", "picks", "row", "settings", "step", "job"]) {
128
+ const v = ctx[root];
129
+ if (isObj(v)) {
130
+ const plain = {};
131
+ for (const [k, x] of Object.entries(v)) if (typeof x !== "function") plain[k] = x;
132
+ walk(plain, root, 0);
133
+ }
134
+ }
135
+ return out;
136
+ }
137
+
138
+ module.exports = { ROOTS, lookup, get, fill, when, truthy, hasPlaceholder, valuePaths };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@trops/dash-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Compose deterministic checks from small, described building blocks: Jest-style files, JSON recipes and helpers. Runs in Dash, in CI and on a laptop.",
5
+ "license": "MIT",
6
+ "author": "trops",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/trops/dash-check.git"
10
+ },
11
+ "homepage": "https://github.com/trops/dash-check#readme",
12
+ "bugs": "https://github.com/trops/dash-check/issues",
13
+ "keywords": ["dash", "checks", "ci", "testing", "bots", "deterministic"],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "type": "commonjs",
18
+ "main": "./index.js",
19
+ "types": "./index.d.ts",
20
+ "bin": {
21
+ "dash-check": "cli/bin.js"
22
+ },
23
+ "exports": {
24
+ ".": {
25
+ "types": "./index.d.ts",
26
+ "default": "./index.js"
27
+ },
28
+ "./helpers": {
29
+ "types": "./helpers/index.d.ts",
30
+ "default": "./helpers/index.js"
31
+ },
32
+ "./recipe": {
33
+ "types": "./recipe/index.d.ts",
34
+ "default": "./recipe/index.js"
35
+ },
36
+ "./recipe/schema.json": "./recipe/schema.json",
37
+ "./cli": {
38
+ "types": "./cli/index.d.ts",
39
+ "default": "./cli/index.js"
40
+ },
41
+ "./lib/register.js": "./lib/register.js",
42
+ "./package.json": "./package.json"
43
+ },
44
+ "files": [
45
+ "index.js",
46
+ "index.d.ts",
47
+ "lib/",
48
+ "helpers/",
49
+ "recipe/",
50
+ "cli/",
51
+ "examples/",
52
+ "README.md",
53
+ "LICENSE"
54
+ ],
55
+ "scripts": {
56
+ "test": "node --test test/*.test.js"
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }
@@ -0,0 +1,70 @@
1
+ // Types for @trops/dash-check/recipe: checks as data.
2
+ import type { Context, ContextOptions, Failure, RunResult, Helper } from "..";
3
+
4
+ export interface UseStep {
5
+ use: string;
6
+ with?: Record<string, unknown>;
7
+ when?: string | boolean;
8
+ message?: string;
9
+ label?: string;
10
+ }
11
+
12
+ export interface ExpectStep {
13
+ expect: string;
14
+ matcher: string;
15
+ args?: unknown[];
16
+ not?: boolean;
17
+ when?: string | boolean;
18
+ message?: string;
19
+ label?: string;
20
+ }
21
+
22
+ export type Step = UseStep | ExpectStep;
23
+
24
+ export interface Recipe {
25
+ $schema?: string;
26
+ name: string;
27
+ description?: string;
28
+ version?: 1;
29
+ steps: Step[];
30
+ }
31
+
32
+ export interface StepResult {
33
+ index: number;
34
+ label: string;
35
+ sentence: string;
36
+ pass: boolean;
37
+ skipped?: boolean;
38
+ reason: string;
39
+ failures: Failure[];
40
+ ms?: number;
41
+ }
42
+
43
+ export interface RecipeResult extends RunResult {
44
+ steps: StepResult[];
45
+ errors?: Array<{ path: string; message: string }>;
46
+ }
47
+
48
+ export interface RecipeOptions extends ContextOptions {
49
+ getHelper?: (id: string) => Helper | null;
50
+ /** Run only these steps (by index). */
51
+ only?: number[];
52
+ ctx?: Context;
53
+ }
54
+
55
+ export const schema: Record<string, any>;
56
+ export function validateRecipe(recipe: unknown, opts?: { getHelper?: (id: string) => Helper | null }): { valid: boolean; errors: Array<{ path: string; message: string }> };
57
+ export function compileRecipe(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null }): {
58
+ name: string;
59
+ steps: Array<{ index: number; label: string; when?: string | boolean; run(ctx: Context): Promise<unknown>; step: Step }>;
60
+ check(ctx: Context): Promise<void>;
61
+ };
62
+ export function runRecipe(recipe: Recipe, input?: Record<string, any>, opts?: RecipeOptions): Promise<RecipeResult>;
63
+ /** The recipe as a .check.js file that gives the same result. */
64
+ export function recipeToCode(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null; file?: string }): string;
65
+ export const toCode: typeof recipeToCode;
66
+ /** One sentence per step. */
67
+ export function explain(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null }): string[];
68
+ export function valuePaths(ctx: Context): Array<{ path: string; type: string; sample?: unknown }>;
69
+ export function slug(name: string): string;
70
+ export function pathCode(path: string): string;
@@ -0,0 +1,381 @@
1
+ /**
2
+ * @trops/dash-check/recipe: checks as data.
3
+ *
4
+ * { "name": "the work is ready for review",
5
+ * "steps": [
6
+ * { "use": "git.committedSince", "with": { "base": "{repo.baseBranch}" } },
7
+ * { "expect": "handoff.files", "matcher": "toHaveLengthAtLeast", "args": [1],
8
+ * "message": "The handoff lists no changed files" } ] }
9
+ *
10
+ * validateRecipe, compileRecipe, runRecipe (a result per step),
11
+ * recipeToCode (the same check as a .check.js file) and explain (sentences).
12
+ * A recipe makes the same calls a file makes: helpers and expect.
13
+ */
14
+ "use strict";
15
+
16
+ const core = require("..");
17
+ require("../helpers");
18
+ const schema = require("./schema.json");
19
+
20
+ const { expect, getHelper, sentenceOf, createContext, collect, fill, when, get, valuePaths } = core;
21
+ const { summarize } = require("../lib/runner");
22
+ const { coerce } = require("../lib/helper");
23
+ const { display } = require("../lib/scope");
24
+ const { isObj, fmt } = require("../lib/util");
25
+ const { hasPlaceholder } = require("../lib/values");
26
+
27
+ const PATH_RE = /^[A-Za-z_$][\w$-]*(\.[\w$-]+)*$/;
28
+ const HELPER_ID_RE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
29
+ const USE_KEYS = ["use", "with", "when", "message", "label"];
30
+ const EXPECT_KEYS = ["expect", "matcher", "args", "not", "when", "message", "label"];
31
+ const TOP_KEYS = ["$schema", "name", "description", "version", "steps"];
32
+
33
+ /**
34
+ * What's wrong with a recipe.
35
+ * @param {object} recipe
36
+ * @param {{ getHelper?: (id: string) => any }} [opts] where helpers are found
37
+ * @returns {{ valid: boolean, errors: Array<{ path: string, message: string }> }}
38
+ */
39
+ function validateRecipe(recipe, opts = {}) {
40
+ const find = opts.getHelper || getHelper;
41
+ const errors = [];
42
+ const err = (path, message) => errors.push({ path, message });
43
+ if (!isObj(recipe)) {
44
+ err("", "A recipe is a JSON object: { \"name\": …, \"steps\": [ … ] }");
45
+ return { valid: false, errors };
46
+ }
47
+ for (const k of Object.keys(recipe)) if (!TOP_KEYS.includes(k)) err(k, `"${k}" isn't part of a recipe (use ${TOP_KEYS.slice(1).join(", ")})`);
48
+ if (typeof recipe.name !== "string" || !recipe.name.trim()) err("name", "Give the recipe a name: what it proves");
49
+ if (recipe.description !== undefined && typeof recipe.description !== "string") err("description", "description must be text");
50
+ if (recipe.version !== undefined && recipe.version !== 1) err("version", "This dash-check reads recipe version 1");
51
+ if (!Array.isArray(recipe.steps) || !recipe.steps.length) {
52
+ err("steps", "Add at least one step: { \"use\": \"helper.id\" } or { \"expect\": \"handoff.key\", \"matcher\": \"toBeDefined\" }");
53
+ return { valid: false, errors };
54
+ }
55
+ recipe.steps.forEach((s, i) => {
56
+ const at = `steps[${i}]`;
57
+ if (!isObj(s)) return err(at, "A step is an object");
58
+ const isUse = s.use !== undefined;
59
+ const isExpect = s.expect !== undefined;
60
+ if (isUse === isExpect) return err(at, 'A step has either "use" (a helper) or "expect" (a value), not both or neither');
61
+ const keys = isUse ? USE_KEYS : EXPECT_KEYS;
62
+ for (const k of Object.keys(s)) if (!keys.includes(k)) err(`${at}.${k}`, `"${k}" isn't part of a${isUse ? " use" : "n expect"} step`);
63
+ if (s.message !== undefined && typeof s.message !== "string") err(`${at}.message`, "message must be text");
64
+ if (s.label !== undefined && typeof s.label !== "string") err(`${at}.label`, "label must be text");
65
+ if (s.when !== undefined && typeof s.when !== "string" && typeof s.when !== "boolean") err(`${at}.when`, "when is a value path or a {placeholder}");
66
+ if (isUse) {
67
+ if (typeof s.use !== "string" || !HELPER_ID_RE.test(s.use)) return err(`${at}.use`, `"${s.use}" isn't a helper id (e.g. git.committedSince)`);
68
+ const h = find(s.use);
69
+ if (!h) return err(`${at}.use`, `There's no helper ${s.use}`);
70
+ if (s.with !== undefined && !isObj(s.with)) return err(`${at}.with`, "with is an object of the helper's params");
71
+ const given = s.with || {};
72
+ const params = h.meta.params;
73
+ for (const k of Object.keys(given)) {
74
+ if (k === "message") err(`${at}.with.message`, 'Put message on the step, next to "use"');
75
+ else if (!params[k]) err(`${at}.with.${k}`, `${s.use} has no param "${k}" (it has ${Object.keys(params).join(", ") || "none"})`);
76
+ }
77
+ for (const [k, p] of Object.entries(params)) {
78
+ const v = given[k];
79
+ if (v === undefined) {
80
+ if (p.required && p.default === undefined) err(`${at}.with.${k}`, `${s.use} needs ${p.label} (${k})`);
81
+ continue;
82
+ }
83
+ if (typeof v === "string" && hasPlaceholder(v)) continue;
84
+ if (p.type === "list" && Array.isArray(v) && v.some((x) => typeof x === "string" && hasPlaceholder(x))) continue;
85
+ try {
86
+ coerce(s.use, k, p, v);
87
+ } catch (e) {
88
+ err(`${at}.with.${k}`, e.message);
89
+ }
90
+ }
91
+ } else {
92
+ if (typeof s.expect !== "string" || !PATH_RE.test(s.expect)) err(`${at}.expect`, `"${s.expect}" isn't a value path (e.g. handoff.files)`);
93
+ const m = typeof s.matcher === "string" ? expect.meta(s.matcher) : null;
94
+ if (!m) {
95
+ err(`${at}.matcher`, `There's no matcher ${fmt(s.matcher)} (use one of ${expect.matchers().map((x) => x.id).join(", ")})`);
96
+ return;
97
+ }
98
+ if (s.args !== undefined && !Array.isArray(s.args)) return err(`${at}.args`, "args is a list of the matcher's params");
99
+ const n = (s.args || []).length;
100
+ if (n !== m.params.length) {
101
+ err(`${at}.args`, `${s.matcher} takes ${m.params.length} arg${m.params.length === 1 ? "" : "s"}${m.params.length ? ` (${m.params.map((p) => p.name).join(", ")})` : ""}, not ${n}`);
102
+ }
103
+ (s.args || []).forEach((a, j) => {
104
+ const p = m.params[j];
105
+ if (!p) return;
106
+ if (p.type === "number" && typeof a !== "number" && !(typeof a === "string" && hasPlaceholder(a))) err(`${at}.args[${j}]`, `${p.label} must be a number`);
107
+ if (p.type === "list" && !Array.isArray(a) && !(typeof a === "string" && hasPlaceholder(a))) err(`${at}.args[${j}]`, `${p.label} must be a list`);
108
+ if (p.type === "regex" && typeof a === "string" && !hasPlaceholder(a)) {
109
+ try {
110
+ new RegExp(a);
111
+ } catch (e) {
112
+ err(`${at}.args[${j}]`, `${p.label} isn't a valid pattern (${e.message})`);
113
+ }
114
+ }
115
+ });
116
+ if (s.not !== undefined && typeof s.not !== "boolean") err(`${at}.not`, "not is true or false");
117
+ }
118
+ });
119
+ return { valid: errors.length === 0, errors };
120
+ }
121
+
122
+ /** A step's row label ("Work is committed", "Expect handoff.files"). */
123
+ function stepLabel(step, find = getHelper) {
124
+ if (step.label) return step.label;
125
+ if (step.use) {
126
+ const h = find(step.use);
127
+ return h ? h.meta.label : step.use;
128
+ }
129
+ return `Expect ${step.expect}`;
130
+ }
131
+
132
+ function matcherArgs(ctx, step) {
133
+ const args = (step.args || []).map((a) => fill(ctx, a));
134
+ const meta = expect.meta(step.matcher);
135
+ return args.map((a, i) => (meta.params[i] && meta.params[i].type === "regex" && typeof a === "string" ? new RegExp(a) : a));
136
+ }
137
+
138
+ /**
139
+ * A recipe as functions: { name, steps: [{ index, label, when, run(ctx) }], check(ctx) }.
140
+ * `check(ctx)` runs every step the way a .check.js file would.
141
+ * Throws when the recipe isn't valid, listing every problem.
142
+ */
143
+ function compileRecipe(recipe, opts = {}) {
144
+ const v = validateRecipe(recipe, opts);
145
+ if (!v.valid) {
146
+ const e = new Error(`The recipe isn't valid: ${v.errors.map((x) => `${x.path ? `${x.path}: ` : ""}${x.message}`).join("; ")}`);
147
+ e.errors = v.errors;
148
+ throw e;
149
+ }
150
+ const find = opts.getHelper || getHelper;
151
+ const steps = recipe.steps.map((step, index) => {
152
+ let run;
153
+ if (step.use) {
154
+ const h = find(step.use);
155
+ run = (ctx) => h(ctx, { ...(step.with || {}), ...(step.message ? { message: step.message } : {}) });
156
+ } else {
157
+ run = (ctx) => {
158
+ const args = matcherArgs(ctx, step);
159
+ const e = expect(get(ctx, step.expect), step.expect);
160
+ const m = step.not ? e.not : e;
161
+ return m[step.matcher](...args, ...(step.message ? [fill(ctx, step.message, { missing: "keep" })] : []));
162
+ };
163
+ }
164
+ return { index, label: stepLabel(step, find), when: step.when, run, step };
165
+ });
166
+ async function check(ctx) {
167
+ for (const s of steps) {
168
+ if (s.when !== undefined && !when(ctx, s.when)) continue;
169
+ await s.run(ctx);
170
+ }
171
+ }
172
+ return { name: recipe.name.trim(), steps, check };
173
+ }
174
+
175
+ /**
176
+ * Run a recipe: a result per step, and the check's result.
177
+ * @param {object} recipe
178
+ * @param {object} [input] the check input (a sample, or Dash's)
179
+ * @param {{ only?: number[], ctx?: object, getHelper?: Function } & object} [opts]
180
+ * only: run just these steps (by index); others createContext options
181
+ * @returns {Promise<{ pass, reason, checks, steps: Array<{ index, label, sentence, pass, skipped?, reason, failures, ms }> }>}
182
+ */
183
+ async function runRecipe(recipe, input, opts = {}) {
184
+ let compiled;
185
+ try {
186
+ compiled = compileRecipe(recipe, opts);
187
+ } catch (e) {
188
+ const name = (isObj(recipe) && typeof recipe.name === "string" && recipe.name) || "recipe";
189
+ return {
190
+ pass: false,
191
+ reason: e.message,
192
+ errors: e.errors || [],
193
+ checks: [{ name, pass: false, reason: e.message, failures: [{ message: e.message }] }],
194
+ steps: [],
195
+ };
196
+ }
197
+ const ctx = opts.ctx || createContext(input || {}, opts);
198
+ const only = Array.isArray(opts.only) ? opts.only : null;
199
+ const lines = explain(recipe, opts);
200
+ const steps = [];
201
+ const failures = [];
202
+ const notes = [];
203
+ let broken = null;
204
+ const t0 = Date.now();
205
+ for (const s of compiled.steps) {
206
+ const base = { index: s.index, label: s.label, sentence: lines[s.index] };
207
+ if (only && !only.includes(s.index)) {
208
+ steps.push({ ...base, pass: true, skipped: true, reason: "Not run (only other steps were asked for)", failures: [] });
209
+ continue;
210
+ }
211
+ if (broken !== null) {
212
+ steps.push({ ...base, pass: false, skipped: true, reason: `Not run: step ${broken + 1} broke`, failures: [] });
213
+ continue;
214
+ }
215
+ if (s.when !== undefined && !when(ctx, s.when)) {
216
+ steps.push({ ...base, pass: true, skipped: true, reason: `Skipped: ${s.when} is false`, failures: [] });
217
+ continue;
218
+ }
219
+ const t = Date.now();
220
+ const r = await collect(() => s.run(ctx));
221
+ if (r.failures.some((f) => f.error) && !s.step.use) broken = s.index;
222
+ const pass = r.failures.length === 0;
223
+ failures.push(...r.failures);
224
+ notes.push(...r.notes);
225
+ steps.push({
226
+ ...base,
227
+ pass,
228
+ reason: pass ? r.notes.join("; ") || "Passed" : r.failures.map(display).join("; "),
229
+ failures: r.failures,
230
+ ms: Date.now() - t,
231
+ });
232
+ }
233
+ const pass = failures.length === 0;
234
+ const checkRec = {
235
+ name: compiled.name,
236
+ pass,
237
+ reason: pass ? notes.join("; ") || "Passed" : failures.map(display).join("; "),
238
+ failures,
239
+ ms: Date.now() - t0,
240
+ };
241
+ return { ...summarize([checkRec]), steps };
242
+ }
243
+
244
+ // ---- recipe → code ------------------------------------------------------
245
+
246
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
247
+
248
+ function jsValue(v, indent) {
249
+ if (Array.isArray(v)) {
250
+ const inner = v.map((x) => jsValue(x, indent));
251
+ const one = `[${inner.join(", ")}]`;
252
+ return one.length <= 70 ? one : `[\n${inner.map((x) => `${indent} ${x}`).join(",\n")},\n${indent}]`;
253
+ }
254
+ if (isObj(v)) return jsObject(v, indent);
255
+ return JSON.stringify(v);
256
+ }
257
+
258
+ function jsObject(o, indent) {
259
+ const entries = Object.entries(o).map(([k, v]) => `${IDENT.test(k) ? k : JSON.stringify(k)}: ${jsValue(v, `${indent} `)}`);
260
+ if (!entries.length) return "{}";
261
+ const one = `{ ${entries.join(", ")} }`;
262
+ if (one.length <= 72 && !one.includes("\n")) return one;
263
+ return `{\n${entries.map((e) => `${indent} ${e}`).join(",\n")},\n${indent}}`;
264
+ }
265
+
266
+ /** A value path as JS on ctx: handoff.plan.cause → ctx.handoff.plan?.cause. */
267
+ function pathCode(p) {
268
+ const parts = p.split(".");
269
+ const { ROOTS } = require("../lib/values");
270
+ if (!ROOTS.includes(parts[0]) || parts.length === 1 || !parts.every((x) => IDENT.test(x) || /^\d+$/.test(x))) {
271
+ return `ctx.get(${JSON.stringify(p)})`;
272
+ }
273
+ let out = `ctx.${parts[0]}`;
274
+ parts.slice(1).forEach((k, i) => {
275
+ const acc = /^\d+$/.test(k) ? `[${k}]` : `.${k}`;
276
+ out += i === 0 ? acc : `?.${acc.replace(/^\./, "")}`;
277
+ });
278
+ return out;
279
+ }
280
+
281
+ function argCode(a, type) {
282
+ if (typeof a === "string" && hasPlaceholder(a)) return `ctx.fill(${JSON.stringify(a)})`;
283
+ if (type === "regex" && typeof a === "string") {
284
+ try {
285
+ return String(new RegExp(a));
286
+ } catch (_e) {
287
+ return JSON.stringify(a);
288
+ }
289
+ }
290
+ return jsValue(a, " ");
291
+ }
292
+
293
+ /**
294
+ * The recipe as a .check.js file that gives the same result.
295
+ * @param {object} recipe
296
+ * @param {{ getHelper?: Function, file?: string }} [opts]
297
+ */
298
+ function recipeToCode(recipe, opts = {}) {
299
+ const compiled = compileRecipe(recipe, opts);
300
+ const find = opts.getHelper || getHelper;
301
+ const groups = new Set();
302
+ let usesHelperById = false;
303
+ let usesExpect = false;
304
+ const body = [];
305
+ for (const s of compiled.steps) {
306
+ const step = s.step;
307
+ const pad = step.when !== undefined ? " " : " ";
308
+ const lines = [];
309
+ if (step.use) {
310
+ const h = find(step.use);
311
+ const builtin = require("../helpers").all.includes(h);
312
+ const params = { ...(step.with || {}), ...(step.message ? { message: step.message } : {}) };
313
+ const arg = Object.keys(params).length ? `, ${jsObject(params, pad)}` : "";
314
+ if (builtin) {
315
+ const [g, ...rest] = step.use.split(".");
316
+ groups.add(g);
317
+ lines.push(`${pad}await ${g}.${rest.join(".")}(ctx${arg});`);
318
+ } else {
319
+ usesHelperById = true;
320
+ lines.push(`${pad}await helper(${JSON.stringify(step.use)})(ctx${arg});`);
321
+ }
322
+ } else {
323
+ usesExpect = true;
324
+ const meta = expect.meta(step.matcher);
325
+ const args = (step.args || []).map((a, i) => argCode(a, meta.params[i] && meta.params[i].type));
326
+ if (step.message) args.push(hasPlaceholder(step.message) ? `ctx.fill(${JSON.stringify(step.message)}, { missing: "keep" })` : JSON.stringify(step.message));
327
+ const head = `${pad}expect(${pathCode(step.expect)}, ${JSON.stringify(step.expect)})`;
328
+ const call = `${step.not ? ".not" : ""}.${step.matcher}(${args.join(", ")});`;
329
+ if (head.length + call.length <= 90) lines.push(head + call);
330
+ else lines.push(head, `${pad} ${call}`);
331
+ }
332
+ if (step.when !== undefined) {
333
+ body.push(` if (ctx.when(${JSON.stringify(step.when)})) {`, ...lines, " }");
334
+ } else body.push(...lines);
335
+ }
336
+ const coreNames = ["check", ...(usesExpect ? ["expect"] : []), ...(usesHelperById ? ["helper"] : [])];
337
+ const file = opts.file || `.dash/checks/${slug(recipe.name)}.check.js`;
338
+ const head = [
339
+ `// ${file} (generated by recipeToCode)`,
340
+ `const { ${coreNames.join(", ")} } = require("@trops/dash-check");`,
341
+ ];
342
+ if (groups.size) head.push(`const { ${[...groups].join(", ")} } = require("@trops/dash-check/helpers");`);
343
+ return `${head.join("\n")}\n\ncheck(${JSON.stringify(compiled.name)}, async (ctx) => {\n${body.join("\n")}\n});\n`;
344
+ }
345
+
346
+ /** A name as a file name: "The work is ready" → "the-work-is-ready". */
347
+ function slug(name) {
348
+ return String(name || "check").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "check";
349
+ }
350
+
351
+ // ---- explain --------------------------------------------------------------
352
+
353
+ /**
354
+ * The recipe as sentences, one per step:
355
+ * "Work is committed: at least 1 commit(s) past {repo.baseBranch}, and nothing uncommitted"
356
+ * @returns {string[]}
357
+ */
358
+ function explain(recipe, opts = {}) {
359
+ const find = opts.getHelper || getHelper;
360
+ if (!isObj(recipe) || !Array.isArray(recipe.steps)) return [];
361
+ return recipe.steps.map((s) => {
362
+ if (!isObj(s)) return "(not a step)";
363
+ let text;
364
+ if (s.use) {
365
+ const h = find(s.use);
366
+ if (!h) text = `${s.use} (no such helper)`;
367
+ else {
368
+ const said = sentenceOf(h.meta, s.with || {});
369
+ text = `${s.label || h.meta.label}${said ? `: ${said}` : ""}`;
370
+ }
371
+ } else {
372
+ const said = expect.has(s.matcher) ? expect.sentence(s.matcher, s.expect, s.args || [], !!s.not) : `${s.expect} ${s.matcher}`;
373
+ text = `${s.label ? `${s.label}: ` : ""}Expect ${said}`;
374
+ }
375
+ if (s.when !== undefined) text = `Only when ${s.when}: ${text}`;
376
+ if (s.message) text += `. If it fails, say: "${s.message}"`;
377
+ return text;
378
+ });
379
+ }
380
+
381
+ module.exports = { schema, validateRecipe, compileRecipe, runRecipe, recipeToCode, toCode: recipeToCode, explain, valuePaths, slug, pathCode };