@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/helper.js ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * helper.js: defineHelper, a building block made only from Layer 0 and
3
+ * described well enough for a UI to list it, render its form and read it
4
+ * back as a sentence.
5
+ *
6
+ * defineHelper({ id, group, label, description, sentence, params, reads, run })
7
+ *
8
+ * The result is a function, `await helper(ctx, params)`, with its metadata
9
+ * on `.meta`. Calling it:
10
+ * - fills each param's default, then "{placeholders}" from the context
11
+ * (a default whose placeholder has no value counts as empty);
12
+ * - checks and converts each param to its type;
13
+ * - runs it; anything it throws becomes a failure, so the check goes on;
14
+ * - with `message`, its failures say that instead (where they were stays).
15
+ */
16
+ "use strict";
17
+
18
+ const { isObj, fmt, DashCheckError } = require("./util");
19
+ const { collect, record, CheckFailure, current, note } = require("./scope");
20
+ const values = require("./values");
21
+
22
+ const TYPES = ["text", "number", "boolean", "select", "path", "glob", "regex", "list"];
23
+ const ID_RE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
24
+ const REGISTRY = new Map();
25
+
26
+ function normParams(id, params) {
27
+ if (params === undefined) return {};
28
+ if (!isObj(params)) throw new TypeError(`${id}: params must be an object of { name: { type, label, default } }`);
29
+ const out = {};
30
+ for (const [name, p] of Object.entries(params)) {
31
+ if (name === "message") throw new TypeError(`${id}: "message" is every helper's own param; don't declare it`);
32
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) throw new TypeError(`${id}: "${name}" can't be a param's name`);
33
+ const def = isObj(p) ? p : { type: p };
34
+ const type = def.type || "text";
35
+ if (!TYPES.includes(type)) throw new TypeError(`${id}: param ${name} has type "${type}"; use one of ${TYPES.join(", ")}`);
36
+ if (type === "select" && (!Array.isArray(def.options) || !def.options.length)) {
37
+ throw new TypeError(`${id}: select param ${name} needs options`);
38
+ }
39
+ out[name] = {
40
+ type,
41
+ label: def.label || name,
42
+ ...(def.description ? { description: def.description } : {}),
43
+ ...(def.default !== undefined ? { default: def.default } : {}),
44
+ ...(def.required ? { required: true } : {}),
45
+ ...(def.options ? { options: def.options.slice() } : {}),
46
+ ...(def.placeholder ? { placeholder: def.placeholder } : {}),
47
+ };
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /** A param's value, converted to its type, or throws saying what's wrong. */
53
+ function coerce(id, name, p, v) {
54
+ const bad = (what) => new DashCheckError(`${id}: ${p.label} (${name}) ${what}`, { fix: `got ${fmt(v)}` });
55
+ if (v === undefined || v === null || (typeof v === "string" && v.trim() === "")) {
56
+ if (p.required) throw new DashCheckError(`${id}: set ${p.label} (${name})`, { fix: "it has no value" });
57
+ return p.type === "list" ? [] : undefined;
58
+ }
59
+ switch (p.type) {
60
+ case "number": {
61
+ const n = typeof v === "number" ? v : Number(String(v).trim());
62
+ if (!Number.isFinite(n)) throw bad("must be a number");
63
+ return n;
64
+ }
65
+ case "boolean":
66
+ if (typeof v === "boolean") return v;
67
+ if (["true", "yes", "on", "1"].includes(String(v).toLowerCase())) return true;
68
+ if (["false", "no", "off", "0"].includes(String(v).toLowerCase())) return false;
69
+ throw bad("must be true or false");
70
+ case "select":
71
+ if (!p.options.map(String).includes(String(v))) throw bad(`must be one of ${p.options.join(", ")}`);
72
+ return p.options.find((o) => String(o) === String(v));
73
+ case "list": {
74
+ const list = Array.isArray(v) ? v : String(v).split(",");
75
+ return list.map((x) => (typeof x === "string" ? x.trim() : x)).filter((x) => x !== "" && x !== undefined && x !== null);
76
+ }
77
+ case "regex":
78
+ if (v instanceof RegExp) return v;
79
+ try {
80
+ return new RegExp(String(v));
81
+ } catch (e) {
82
+ throw bad(`isn't a valid pattern (${e.message})`);
83
+ }
84
+ default:
85
+ if (typeof v === "object") throw bad("must be text");
86
+ return String(v);
87
+ }
88
+ }
89
+
90
+ /** Fill and convert a call's params (exported for recipes and tests). */
91
+ function resolveParams(meta, ctx, given = {}) {
92
+ const out = {};
93
+ const g = isObj(given) ? given : {};
94
+ for (const k of Object.keys(g)) {
95
+ if (k !== "message" && !meta.params[k]) {
96
+ throw new DashCheckError(`${meta.id} has no param "${k}"`, { fix: `use ${Object.keys(meta.params).join(", ") || "no params"}` });
97
+ }
98
+ }
99
+ for (const [name, p] of Object.entries(meta.params)) {
100
+ let v;
101
+ if (g[name] !== undefined) v = ctx ? values.fill(ctx, g[name]) : g[name];
102
+ else if (p.default !== undefined) v = ctx ? values.fill(ctx, p.default, { missing: "empty" }) : p.default;
103
+ out[name] = coerce(meta.id, name, p, v);
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * Define a helper.
110
+ * @param {{ id: string, group?: string, label: string, description?: string,
111
+ * sentence?: string, params?: object, reads?: string[],
112
+ * run: (ctx: object, params: object) => any }} def
113
+ */
114
+ function defineHelper(def) {
115
+ if (!def || typeof def !== "object") throw new TypeError("defineHelper({ id, label, run }) needs a definition");
116
+ if (typeof def.id !== "string" || !ID_RE.test(def.id)) {
117
+ throw new TypeError(`A helper's id is "group.name" in camelCase, e.g. "team.changelogUpdated" (got ${fmt(def.id)})`);
118
+ }
119
+ if (typeof def.run !== "function") throw new TypeError(`${def.id}: give it run(ctx, params)`);
120
+ if (typeof def.label !== "string" || !def.label.trim()) throw new TypeError(`${def.id}: give it a label, e.g. "Changelog updated"`);
121
+ const meta = Object.freeze({
122
+ id: def.id,
123
+ group: def.group || def.id.split(".")[0],
124
+ label: def.label,
125
+ description: def.description || "",
126
+ sentence: def.sentence || "",
127
+ params: normParams(def.id, def.params),
128
+ reads: Array.isArray(def.reads) ? def.reads.slice() : [],
129
+ });
130
+ const runIt = def.run;
131
+
132
+ async function helper(ctx, given = {}) {
133
+ if (!ctx || typeof ctx !== "object" || !ctx.input) {
134
+ throw new TypeError(`${meta.id}(ctx, params): pass the check's ctx first`);
135
+ }
136
+ const s = await collect(async () => {
137
+ const params = resolveParams(meta, ctx, given);
138
+ await runIt(ctx, params);
139
+ });
140
+ const message = isObj(given) && typeof given.message === "string" && given.message.trim()
141
+ ? values.fill(ctx, given.message, { missing: "keep" })
142
+ : null;
143
+ const failures = s.failures.map((f) => (message ? { ...f, message, original: f.message } : f));
144
+ if (!current()) {
145
+ if (failures.length) throw new CheckFailure(failures);
146
+ return true;
147
+ }
148
+ failures.forEach(record);
149
+ s.notes.forEach(note);
150
+ return failures.length === 0;
151
+ }
152
+ Object.defineProperty(helper, "name", { value: meta.id });
153
+ helper.meta = meta;
154
+ helper.isDashCheckHelper = true;
155
+ return helper;
156
+ }
157
+
158
+ /** Fill a helper's sentence with values: "at least 1 commit(s) past main". */
159
+ function sentenceOf(meta, given = {}) {
160
+ return String(meta.sentence || "").replace(/\{(\w+)\}/g, (m, k) => {
161
+ const p = meta.params[k];
162
+ if (!p) return m;
163
+ const v = isObj(given) && given[k] !== undefined ? given[k] : p.default;
164
+ if (v === undefined || v === "") return `(${p.label})`;
165
+ if (Array.isArray(v)) return v.join(", ");
166
+ if (v instanceof RegExp) return v.source;
167
+ return String(v);
168
+ });
169
+ }
170
+
171
+ /** Add helpers to the registry (built-ins and discovered ones). */
172
+ function register(helpers, { source, replace = false } = {}) {
173
+ const added = [];
174
+ for (const h of [].concat(helpers)) {
175
+ if (!h || !h.isDashCheckHelper) throw new TypeError("register() takes helpers made with defineHelper");
176
+ const had = REGISTRY.get(h.meta.id);
177
+ if (had && had.helper !== h && !replace) {
178
+ throw new Error(`Another helper already has the id ${h.meta.id}${had.source ? ` (${had.source})` : ""}: give this one a different id`);
179
+ }
180
+ REGISTRY.set(h.meta.id, { helper: h, source: source || (had && had.source) || null });
181
+ added.push(h);
182
+ }
183
+ return added;
184
+ }
185
+
186
+ /** A registered helper by id, or null. */
187
+ function getHelper(id) {
188
+ require("../helpers");
189
+ const r = REGISTRY.get(id);
190
+ return r ? r.helper : null;
191
+ }
192
+
193
+ /** Every registered helper's metadata, with where it came from. */
194
+ function listHelpers() {
195
+ require("../helpers");
196
+ return [...REGISTRY.values()].map(({ helper, source }) => ({ ...helper.meta, params: { ...helper.meta.params }, ...(source ? { source } : {}) }));
197
+ }
198
+
199
+ function unregister(id) {
200
+ return REGISTRY.delete(id);
201
+ }
202
+
203
+ /**
204
+ * helper(id) → the helper, to call from code: await helper("team.changelog")(ctx, {…}).
205
+ * Built-ins are always there; a repo's own are found from ctx.cwd on first use.
206
+ */
207
+ function helper(id) {
208
+ return async (ctx, given) => {
209
+ let h = getHelper(id);
210
+ if (!h && ctx && ctx.cwd) {
211
+ require("./discover").loadHelpers({ cwd: ctx.cwd });
212
+ h = getHelper(id);
213
+ }
214
+ if (!h) throw new DashCheckError(`There's no helper ${id}`, { fix: "check its id, or add it to .dash/checks/helpers/" });
215
+ return h(ctx, given);
216
+ };
217
+ }
218
+
219
+ module.exports = { defineHelper, resolveParams, coerce, sentenceOf, register, getHelper, listHelpers, unregister, helper, TYPES };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * register.js: make `require("@trops/dash-check")` (and its subpaths) give
3
+ * this copy, so a check or helper file run by this CLI works even where the
4
+ * package isn't installed (npx), and shares one registry and one runner.
5
+ *
6
+ * node -r @trops/dash-check/lib/register.js my.check.js
7
+ */
8
+ "use strict";
9
+
10
+ const Module = require("module");
11
+ const path = require("path");
12
+
13
+ const ROOT = path.resolve(__dirname, "..");
14
+ const NAME = "@trops/dash-check";
15
+ const MAP = {
16
+ "": "index.js",
17
+ "/helpers": "helpers/index.js",
18
+ "/recipe": "recipe/index.js",
19
+ "/cli": "cli/index.js",
20
+ "/package.json": "package.json",
21
+ };
22
+
23
+ if (!Module.__dashCheckRegistered) {
24
+ Module.__dashCheckRegistered = true;
25
+ const orig = Module._resolveFilename;
26
+ Module._resolveFilename = function resolve(request, ...rest) {
27
+ if (typeof request === "string" && (request === NAME || request.startsWith(`${NAME}/`))) {
28
+ const sub = request.slice(NAME.length);
29
+ if (MAP[sub] !== undefined) return path.join(ROOT, MAP[sub]);
30
+ }
31
+ return orig.call(this, request, ...rest);
32
+ };
33
+ }
34
+
35
+ module.exports = { ROOT };
package/lib/runner.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * runner.js: check(), describe() and running them.
3
+ *
4
+ * A run gives
5
+ * { pass, reason, checks: [{ name, pass, skipped?, reason, failures: [{ message, at?, expected, received }], ms }] }
6
+ * and, run as a file, prints a report and then one last line,
7
+ * {"reason", "details"}: Dash's check contract, so Dash needs no new parsing.
8
+ *
9
+ * A `.check.js` file runs itself when node runs it directly
10
+ * (`node validate.check.js`), the way Dash runs a repo check today.
11
+ */
12
+ "use strict";
13
+
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+ const { collect, display } = require("./scope");
17
+ const { createContext } = require("./context");
18
+
19
+ const PKG_ROOT = path.resolve(__dirname, "..");
20
+
21
+ let suite = [];
22
+ let prefix = [];
23
+ let collecting = 0;
24
+ let autorunScheduled = false;
25
+ let ranByHand = false;
26
+
27
+ function add(name, fn, mode) {
28
+ if (typeof name !== "string" || !name.trim()) throw new TypeError("check(name, fn): give the check a name");
29
+ if (typeof fn !== "function" && mode !== "skip") throw new TypeError(`check("${name}"): give it a function, (ctx) => { … }`);
30
+ suite.push({ name: [...prefix, name.trim()].join(" › "), fn, mode });
31
+ maybeAutorun();
32
+ }
33
+
34
+ /**
35
+ * Define a check. `fn` gets the context and may be async.
36
+ * @param {string} name what it proves, said so a failure reads well
37
+ * @param {(ctx: object) => any} fn
38
+ */
39
+ function check(name, fn) {
40
+ add(name, fn, null);
41
+ }
42
+ check.skip = (name, fn) => add(name, fn, "skip");
43
+ check.only = (name, fn) => add(name, fn, "only");
44
+
45
+ /** Group checks; their names are prefixed with the group's ("group › check"). */
46
+ function describe(name, fn) {
47
+ prefix.push(String(name));
48
+ try {
49
+ const r = fn();
50
+ if (r && typeof r.then === "function") throw new TypeError(`describe("${name}") can't be async: put the awaits inside check()`);
51
+ } finally {
52
+ prefix.pop();
53
+ }
54
+ }
55
+
56
+ /** The checks defined so far (and forget them). */
57
+ function takeChecks() {
58
+ const out = suite;
59
+ suite = [];
60
+ prefix = [];
61
+ return out;
62
+ }
63
+
64
+ const cut = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
65
+
66
+ /**
67
+ * Run a list of checks against a context.
68
+ * @param {Array<{ name, fn, mode }>} checks
69
+ * @param {object} ctx from createContext
70
+ * @param {{ filter?: (name: string) => boolean }} [opts]
71
+ */
72
+ async function runChecks(checks, ctx, opts = {}) {
73
+ const hasOnly = checks.some((c) => c.mode === "only");
74
+ const results = [];
75
+ for (const c of checks) {
76
+ const skip = c.mode === "skip" || (hasOnly && c.mode !== "only") || (opts.filter && !opts.filter(c.name));
77
+ if (skip) {
78
+ results.push({ name: c.name, pass: true, skipped: true, reason: "Skipped", failures: [], ms: 0 });
79
+ continue;
80
+ }
81
+ const t0 = Date.now();
82
+ const s = await collect(() => c.fn(ctx));
83
+ const pass = s.failures.length === 0;
84
+ results.push({
85
+ name: c.name,
86
+ pass,
87
+ reason: pass ? s.notes.join("; ") || "Passed" : cut(s.failures.map(display).join("; "), 2000),
88
+ failures: s.failures,
89
+ ms: Date.now() - t0,
90
+ });
91
+ }
92
+ return summarize(results);
93
+ }
94
+
95
+ /** The run's pass and reason, from its checks. */
96
+ function summarize(checks) {
97
+ const ran = checks.filter((c) => !c.skipped);
98
+ if (!checks.length) {
99
+ return { pass: false, reason: "There are no checks here: add one with check(name, fn)", checks };
100
+ }
101
+ const failed = ran.filter((c) => !c.pass);
102
+ if (!failed.length) {
103
+ if (!ran.length) return { pass: true, reason: `Skipped all ${checks.length}`, checks };
104
+ if (ran.length === 1) {
105
+ const c = ran[0];
106
+ return { pass: true, reason: c.reason && c.reason !== "Passed" ? `${c.name}: ${c.reason}` : `Passed: ${c.name}`, checks };
107
+ }
108
+ return { pass: true, reason: cut(`${ran.length} checks passed: ${ran.map((c) => c.name).join("; ")}`, 500), checks };
109
+ }
110
+ const all = failed.flatMap((c) => c.failures.map(display));
111
+ const shown = all.slice(0, 3).join("; ");
112
+ const more = all.length > 3 ? ` (and ${all.length - 3} more)` : "";
113
+ return { pass: false, reason: cut(`${shown}${more}`, 1500), checks };
114
+ }
115
+
116
+ /** A result's last line: {"reason", "details"} (Dash's contract). */
117
+ function lastLine(result) {
118
+ const details = {
119
+ checks: (result.checks || []).map((c) => ({
120
+ name: c.name,
121
+ pass: c.pass,
122
+ ...(c.skipped ? { skipped: true } : {}),
123
+ reason: c.reason,
124
+ ...(c.failures && c.failures.length
125
+ ? { failures: c.failures.slice(0, 10).map((f) => ({ message: f.message, ...(f.at ? { at: f.at } : {}), ...("expected" in f ? { expected: f.expected } : {}), ...("received" in f ? { received: f.received } : {}) })) }
126
+ : {}),
127
+ })),
128
+ ...(result.steps ? { steps: result.steps.map((s) => ({ index: s.index, label: s.label, pass: s.pass, ...(s.skipped ? { skipped: true } : {}), reason: s.reason })) } : {}),
129
+ };
130
+ let line = JSON.stringify({ reason: result.reason, details });
131
+ if (line.length > 60000) line = JSON.stringify({ reason: result.reason, details: { cut: true } });
132
+ return line;
133
+ }
134
+
135
+ /** A Jest-like report of a result. */
136
+ function report(result, { title, color = false } = {}) {
137
+ const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
138
+ const lines = [];
139
+ if (title) lines.push(`${result.pass ? c("42;30", " PASS ") : c("41;37", " FAIL ")} ${title}`);
140
+ const items = result.steps || result.checks || [];
141
+ for (const it of items) {
142
+ const name = it.label || it.name;
143
+ if (it.skipped) lines.push(` ${c(33, "○")} ${name} ${c(2, "(skipped)")}`);
144
+ else if (it.pass) lines.push(` ${c(32, "✓")} ${name}${it.reason && it.reason !== "Passed" ? c(2, ` (${it.reason})`) : ""}${it.ms ? c(2, ` ${it.ms} ms`) : ""}`);
145
+ else {
146
+ lines.push(` ${c(31, "✗")} ${name}`);
147
+ for (const f of it.failures || []) lines.push(` ${c(31, "●")} ${display(f)}`);
148
+ }
149
+ }
150
+ return lines.join("\n");
151
+ }
152
+
153
+ /** Read a check input file (Dash's $DASH_INPUT). `{}` when there's none. */
154
+ function readInput(file) {
155
+ if (!file) return {};
156
+ try {
157
+ return JSON.parse(fs.readFileSync(file, "utf8"));
158
+ } catch (_e) {
159
+ return {};
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Run the checks defined so far (in this file).
165
+ * @param {object} [input] the check input; default: $DASH_INPUT
166
+ * @param {object} [opts] createContext options, plus { ctx } to give your own
167
+ */
168
+ async function run(input, opts = {}) {
169
+ ranByHand = true;
170
+ const ctx = opts.ctx || createContext(input === undefined ? readInput(process.env.DASH_INPUT) : input, opts);
171
+ return runChecks(takeChecks(), ctx, opts);
172
+ }
173
+
174
+ /** Load a .check.js file's checks without running them. */
175
+ function loadChecks(file) {
176
+ const full = path.resolve(file);
177
+ const before = takeChecks();
178
+ collecting++;
179
+ try {
180
+ delete require.cache[full];
181
+ require(full);
182
+ return takeChecks();
183
+ } finally {
184
+ collecting--;
185
+ suite = before;
186
+ }
187
+ }
188
+
189
+ function isInside(file, dir) {
190
+ const rel = path.relative(dir, file);
191
+ return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
192
+ }
193
+
194
+ function shouldAutorun() {
195
+ if (collecting || autorunScheduled || process.env.DASH_CHECK_NO_AUTORUN) return false;
196
+ const main = require.main && require.main.filename;
197
+ if (!main) return false;
198
+ return /\.check\.c?js$/.test(main) || !isInside(main, PKG_ROOT);
199
+ }
200
+
201
+ function maybeAutorun() {
202
+ if (!shouldAutorun()) return;
203
+ autorunScheduled = true;
204
+ setImmediate(async () => {
205
+ if (ranByHand) return;
206
+ const result = await runChecks(takeChecks(), createContext(readInput(process.env.DASH_INPUT)));
207
+ const text = process.env.DASH_CHECK_QUIET ? "" : report(result);
208
+ if (text) process.stdout.write(`${text}\n`);
209
+ process.stdout.write(`${lastLine(result)}\n`);
210
+ process.exitCode = result.pass ? 0 : 1;
211
+ });
212
+ }
213
+
214
+ module.exports = { check, describe, run, runChecks, summarize, takeChecks, loadChecks, lastLine, report, readInput };
package/lib/scope.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * scope.js: where a failing `expect` goes.
3
+ *
4
+ * Inside a running check, failures are collected (like a Jest report, every
5
+ * one is listed) and the check goes on. Outside one, a failure throws a
6
+ * CheckFailure straight away.
7
+ */
8
+ "use strict";
9
+
10
+ const { AsyncLocalStorage } = require("async_hooks");
11
+ const { safe } = require("./util");
12
+
13
+ const store = new AsyncLocalStorage();
14
+
15
+ /** Thrown by `expect` outside a running check, and by `collect` on failure. */
16
+ class CheckFailure extends Error {
17
+ constructor(failures) {
18
+ const list = Array.isArray(failures) ? failures : [failures];
19
+ super(list.map(display).join("; ") || "Failed");
20
+ this.name = "CheckFailure";
21
+ this.failures = list;
22
+ }
23
+ }
24
+
25
+ /** How a failure reads: its message, and where when it says. */
26
+ function display(f) {
27
+ if (!f) return "";
28
+ return f.at ? `${f.message}: ${f.at}` : f.message;
29
+ }
30
+
31
+ function makeFailure(message, extra = {}) {
32
+ const f = { message: String(message || "Failed") };
33
+ if (f.message.length > 2000) f.message = `${f.message.slice(0, 1999)}…`;
34
+ if (extra.at) f.at = String(extra.at).slice(0, 1000);
35
+ if ("expected" in extra && extra.expected !== undefined) f.expected = safe(extra.expected);
36
+ if ("received" in extra) f.received = safe(extra.received);
37
+ if (extra.matcher) f.matcher = extra.matcher;
38
+ if (extra.label) f.label = extra.label;
39
+ if (extra.error) f.error = true;
40
+ return f;
41
+ }
42
+
43
+ /** Record a failure in the running check, or throw one outside a check. */
44
+ function record(failure) {
45
+ const s = store.getStore();
46
+ if (!s) throw new CheckFailure([failure]);
47
+ s.failures.push(failure);
48
+ return failure;
49
+ }
50
+
51
+ /**
52
+ * Fail the running check with a message (the fix), going on with the rest.
53
+ * @param {string} message what to fix
54
+ * @param {{ at?: string, expected?: any, received?: any }} [extra]
55
+ */
56
+ function fail(message, extra) {
57
+ record(makeFailure(message, extra));
58
+ return false;
59
+ }
60
+
61
+ /** Say how the running check passed (its reason, when nothing failed). */
62
+ function note(text) {
63
+ const s = store.getStore();
64
+ if (s && text) s.notes.push(String(text));
65
+ }
66
+
67
+ /**
68
+ * Run `fn` with its own failure list. Resolves with { failures, notes,
69
+ * error }; never throws.
70
+ */
71
+ async function collect(fn) {
72
+ const s = { failures: [], notes: [] };
73
+ await store.run(s, async () => {
74
+ try {
75
+ await fn();
76
+ } catch (e) {
77
+ addError(s, e);
78
+ }
79
+ });
80
+ return s;
81
+ }
82
+
83
+ /** An error thrown inside a check, as a failure. */
84
+ function addError(s, e) {
85
+ if (e instanceof CheckFailure) {
86
+ s.failures.push(...e.failures);
87
+ return;
88
+ }
89
+ const msg = e && e.message ? e.message : String(e);
90
+ const named = e && e.name && e.name !== "Error" && e.name !== "DashCheckError" ? `${e.name}: ` : "";
91
+ s.failures.push(makeFailure(`${named}${msg}`, { error: true }));
92
+ }
93
+
94
+ const current = () => store.getStore() || null;
95
+
96
+ module.exports = {
97
+ store,
98
+ CheckFailure,
99
+ makeFailure,
100
+ record,
101
+ fail,
102
+ note,
103
+ collect,
104
+ addError,
105
+ current,
106
+ display,
107
+ };
package/lib/util.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * util.js: small pure helpers shared by the core (no I/O).
3
+ */
4
+ "use strict";
5
+
6
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
7
+
8
+ /** An error a check's author can act on. `fix` says what to do about it. */
9
+ class DashCheckError extends Error {
10
+ constructor(message, { fix, code } = {}) {
11
+ super(fix ? `${message}: ${fix}` : message);
12
+ this.name = "DashCheckError";
13
+ if (fix) this.fix = fix;
14
+ if (code !== undefined) this.code = code;
15
+ }
16
+ }
17
+
18
+ /** Empty: undefined, null, "", " ", [], {}. */
19
+ function isEmpty(v) {
20
+ if (v === undefined || v === null) return true;
21
+ if (typeof v === "string") return !v.trim();
22
+ if (Array.isArray(v)) return v.length === 0;
23
+ if (v instanceof Map || v instanceof Set) return v.size === 0;
24
+ if (isObj(v)) return Object.keys(v).length === 0;
25
+ return false;
26
+ }
27
+
28
+ function deepEqual(a, b) {
29
+ if (Object.is(a, b)) return true;
30
+ if (typeof a !== typeof b || a === null || b === null) return false;
31
+ if (typeof a !== "object") return false;
32
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
33
+ if (a instanceof RegExp || b instanceof RegExp) return String(a) === String(b);
34
+ if (a instanceof Date || b instanceof Date) {
35
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
36
+ }
37
+ const ka = Object.keys(a).filter((k) => a[k] !== undefined);
38
+ const kb = Object.keys(b).filter((k) => b[k] !== undefined);
39
+ if (ka.length !== kb.length) return false;
40
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
41
+ }
42
+
43
+ /** A value as short text for a failure message. */
44
+ function fmt(v, max = 200) {
45
+ let s;
46
+ if (v === undefined) return "missing";
47
+ if (typeof v === "string") s = JSON.stringify(v);
48
+ else if (v instanceof RegExp) s = String(v);
49
+ else if (typeof v === "function") s = `[function ${v.name || "anonymous"}]`;
50
+ else if (v instanceof Error) s = `${v.name}: ${v.message}`;
51
+ else {
52
+ try {
53
+ s = JSON.stringify(v);
54
+ } catch (_e) {
55
+ s = String(v);
56
+ }
57
+ if (s === undefined) s = String(v);
58
+ }
59
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
60
+ }
61
+
62
+ /** A JSON-safe, size-capped copy of a value (for a result's failures). */
63
+ function safe(v, depth = 0) {
64
+ if (v === undefined) return undefined;
65
+ if (v === null || typeof v === "number" || typeof v === "boolean") return v;
66
+ if (typeof v === "string") return v.length > 500 ? `${v.slice(0, 499)}…` : v;
67
+ if (typeof v === "bigint") return String(v);
68
+ if (v instanceof RegExp) return String(v);
69
+ if (v instanceof Error) return `${v.name}: ${v.message}`;
70
+ if (typeof v === "function") return `[function ${v.name || "anonymous"}]`;
71
+ if (depth >= 4) return Array.isArray(v) ? `[${v.length} items]` : "{…}";
72
+ if (Array.isArray(v)) {
73
+ const out = v.slice(0, 20).map((x) => safe(x, depth + 1));
74
+ if (v.length > 20) out.push(`… and ${v.length - 20} more`);
75
+ return out;
76
+ }
77
+ if (typeof v === "object") {
78
+ const out = {};
79
+ const keys = Object.keys(v);
80
+ for (const k of keys.slice(0, 30)) out[k] = safe(v[k], depth + 1);
81
+ if (keys.length > 30) out["…"] = `${keys.length - 30} more keys`;
82
+ return out;
83
+ }
84
+ return String(v);
85
+ }
86
+
87
+ /** Split "a.b.0.c" into ["a", "b", "0", "c"]. */
88
+ const splitPath = (p) => String(p).split(".").filter((s) => s !== "");
89
+
90
+ /** The value at a dotted path, or undefined. */
91
+ function getPath(obj, p) {
92
+ let cur = obj;
93
+ for (const k of Array.isArray(p) ? p : splitPath(p)) {
94
+ if (cur === null || cur === undefined) return undefined;
95
+ cur = cur[k];
96
+ }
97
+ return cur;
98
+ }
99
+
100
+ const plural = (n, word, many = `${word}s`) => `${n} ${n === 1 ? word : many}`;
101
+
102
+ /** The last `n` characters of some output, on a line boundary when it can. */
103
+ function tail(text, n = 1500) {
104
+ const s = String(text || "").trimEnd();
105
+ if (s.length <= n) return s;
106
+ const cut = s.slice(-n);
107
+ const nl = cut.indexOf("\n");
108
+ return `…${nl >= 0 && nl < 200 ? cut.slice(nl) : cut}`;
109
+ }
110
+
111
+ module.exports = {
112
+ isObj,
113
+ isEmpty,
114
+ deepEqual,
115
+ fmt,
116
+ safe,
117
+ splitPath,
118
+ getPath,
119
+ plural,
120
+ tail,
121
+ DashCheckError,
122
+ };