@motionskit/cli 0.1.0 → 0.2.2
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.
- package/README.md +1 -1
- package/dist/index.js +27 -9
- package/dist/main.js +266 -71
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @motionskit/cli
|
|
2
2
|
|
|
3
|
-
`motions init`, `check`, `test`, `push`, `pull` and `
|
|
3
|
+
`motions init`, `check`, `test`, `push`, `pull`, `open` and `retry`.
|
|
4
4
|
|
|
5
5
|
From a directory with `tenant.yaml`, `motions push` publishes a draft and prints a link. `motions push --live` makes it the version new batches open on. `MOTIONS_URL` defaults to `http://localhost:8787`. `MOTIONS_TOKEN` is an API key (`mot_…`) sent as `authorization: Bearer`.
|
|
6
6
|
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/compile.ts
|
|
2
2
|
import { createHash as createHash2 } from "crypto";
|
|
3
3
|
import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
4
|
-
import {
|
|
4
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
|
|
5
5
|
import { fileURLToPath } from "url";
|
|
6
6
|
import {
|
|
7
7
|
CRM_WRITES,
|
|
@@ -142,7 +142,10 @@ var RawMotion = z.strictObject({
|
|
|
142
142
|
calendar: z.record(id, calendarSpec).optional(),
|
|
143
143
|
approvers: z.array(z.string()).min(1, "a motion needs at least one approver"),
|
|
144
144
|
reasons: z.array(id).optional(),
|
|
145
|
-
input: z.strictObject({
|
|
145
|
+
input: z.strictObject({
|
|
146
|
+
list: z.string().optional(),
|
|
147
|
+
columns: z.record(id, z.strictObject({ required: z.boolean().optional(), aliases: z.array(z.string().trim().min(1)).optional() }).nullable()).optional()
|
|
148
|
+
}).optional(),
|
|
146
149
|
steps: z.array(step).min(1, "a motion needs at least one step"),
|
|
147
150
|
queues: z.record(id, queue).optional()
|
|
148
151
|
});
|
|
@@ -262,7 +265,7 @@ function ttlSeconds(ttl) {
|
|
|
262
265
|
}
|
|
263
266
|
async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
|
|
264
267
|
const tenantDir = resolve(tenantRoot);
|
|
265
|
-
const id2 = dir
|
|
268
|
+
const id2 = folderName(dir);
|
|
266
269
|
const where2 = `${tenant}/sources/${id2}`;
|
|
267
270
|
const root = resolve(dir);
|
|
268
271
|
const index = join3(root, "index.ts");
|
|
@@ -348,11 +351,15 @@ function monorepoTenants() {
|
|
|
348
351
|
if (!existsSync3(dir)) return null;
|
|
349
352
|
return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync3(join4(dir, name, "tenant.yaml"))).sort().map((name) => join4(dir, name));
|
|
350
353
|
}
|
|
354
|
+
function folderName(dir) {
|
|
355
|
+
const leaf = win32.basename(win32.normalize(dir));
|
|
356
|
+
return leaf !== "." && leaf !== ".." ? leaf : win32.basename(resolve2(dir));
|
|
357
|
+
}
|
|
351
358
|
function tenantIdentity(dir) {
|
|
352
359
|
const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
|
|
353
360
|
const motionsDir = join4(dir, "motions");
|
|
354
361
|
const motions = existsSync3(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync3(join4(motionsDir, name, "motion.yaml"))).sort() : [];
|
|
355
|
-
return { id: meta.id ??
|
|
362
|
+
return { id: meta.id ?? folderName(dir), motions };
|
|
356
363
|
}
|
|
357
364
|
var tenantsDir = () => {
|
|
358
365
|
const dir = resolve2(dirname2(fileURLToPath(import.meta.url)), "../../..", "tenants");
|
|
@@ -384,7 +391,8 @@ var MotionErrors = class extends Error {
|
|
|
384
391
|
async function compileMotion(tenant, dir) {
|
|
385
392
|
const tenantDir = findTenantDir(dir);
|
|
386
393
|
if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
|
|
387
|
-
const
|
|
394
|
+
const folder = folderName(dir);
|
|
395
|
+
const where2 = `${tenant.id}/${folder}/motion.yaml`;
|
|
388
396
|
const parsed = parseMotion(readYaml(join4(dir, "motion.yaml")));
|
|
389
397
|
if (!parsed.ok) throw new MotionErrors(where2, parsed.errors);
|
|
390
398
|
const raw = parsed.motion;
|
|
@@ -423,17 +431,18 @@ async function compileMotion(tenant, dir) {
|
|
|
423
431
|
for (const [id2, q] of Object.entries(raw.queues ?? {})) {
|
|
424
432
|
queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
|
|
425
433
|
}
|
|
434
|
+
const motion = raw.motion ?? folder;
|
|
426
435
|
const manifest = {
|
|
427
436
|
tenant: tenant.id,
|
|
428
|
-
motion
|
|
429
|
-
title: raw.title ??
|
|
437
|
+
motion,
|
|
438
|
+
title: raw.title ?? motion,
|
|
430
439
|
timezone: raw.timezone ?? tenant.timezone,
|
|
431
440
|
calendar: raw.calendar ?? {},
|
|
432
441
|
approvers,
|
|
433
442
|
reasons: raw.reasons ?? [],
|
|
434
443
|
rules,
|
|
435
444
|
rulesVersion: rulesVersion(rules),
|
|
436
|
-
input: raw.input
|
|
445
|
+
input: compileInput(raw.input),
|
|
437
446
|
steps,
|
|
438
447
|
queues
|
|
439
448
|
};
|
|
@@ -441,10 +450,19 @@ async function compileMotion(tenant, dir) {
|
|
|
441
450
|
if (errors.length) throw new MotionErrors(where2, errors);
|
|
442
451
|
return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
|
|
443
452
|
}
|
|
453
|
+
function compileInput(input) {
|
|
454
|
+
if (!input) return {};
|
|
455
|
+
const { columns, ...rest } = input;
|
|
456
|
+
if (!columns) return rest;
|
|
457
|
+
return {
|
|
458
|
+
...rest,
|
|
459
|
+
columns: Object.fromEntries(Object.entries(columns).map(([name, c]) => [name, { required: c?.required ?? false, aliases: c?.aliases ?? [] }]))
|
|
460
|
+
};
|
|
461
|
+
}
|
|
444
462
|
async function compileTenant(tenantDir) {
|
|
445
463
|
const dir = resolve2(tenantDir);
|
|
446
464
|
const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
|
|
447
|
-
const id2 = meta.id ??
|
|
465
|
+
const id2 = meta.id ?? folderName(tenantDir);
|
|
448
466
|
const timezone = meta.timezone ?? "America/Sao_Paulo";
|
|
449
467
|
const connection = readYaml(join4(dir, "crm.yaml"));
|
|
450
468
|
const seedPath = join4(dir, "crm-seed.json");
|
package/dist/main.js
CHANGED
|
@@ -1,11 +1,104 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/main.ts
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
|
|
4
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
|
|
5
|
+
import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
|
|
7
6
|
import { parseArgs } from "util";
|
|
8
7
|
|
|
8
|
+
// src/batches.ts
|
|
9
|
+
function matchMotionsList(lists, query) {
|
|
10
|
+
const byId = lists.find((l) => l.id === query);
|
|
11
|
+
if (byId) return byId;
|
|
12
|
+
const exact = lists.filter((l) => l.name === query);
|
|
13
|
+
if (exact.length === 1) return exact[0];
|
|
14
|
+
if (exact.length > 1) {
|
|
15
|
+
throw new Error(`"${query}" matches ${exact.length} Motions lists (${exact.map((l) => l.id).join(", ")}); pass the list id`);
|
|
16
|
+
}
|
|
17
|
+
const folded = query.trim().toLowerCase();
|
|
18
|
+
const byName = lists.filter((l) => l.name.trim().toLowerCase() === folded);
|
|
19
|
+
if (byName.length === 1) return byName[0];
|
|
20
|
+
if (byName.length > 1) {
|
|
21
|
+
throw new Error(`"${query}" matches ${byName.length} Motions lists (${byName.map((l) => l.id).join(", ")}); pass the list id`);
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
async function openBatch(call, input) {
|
|
26
|
+
if (input.list !== void 0 && input.companies !== void 0) {
|
|
27
|
+
throw new Error("pass --list or --companies, not both");
|
|
28
|
+
}
|
|
29
|
+
if (input.again && input.list === void 0) {
|
|
30
|
+
throw new Error("--again requires --list <id-or-name>");
|
|
31
|
+
}
|
|
32
|
+
const base = `/api/tenants/${encodeURIComponent(input.tenant)}`;
|
|
33
|
+
const body = {};
|
|
34
|
+
if (input.label !== void 0) body.label = input.label;
|
|
35
|
+
if (input.companies !== void 0) {
|
|
36
|
+
const ids = input.companies.split(",").map((s) => s.trim()).filter(Boolean);
|
|
37
|
+
if (!ids.length) throw new Error("--companies needs at least one company id");
|
|
38
|
+
body.companies = ids;
|
|
39
|
+
} else if (input.list !== void 0) {
|
|
40
|
+
const query = input.list.trim();
|
|
41
|
+
if (!query) throw new Error("--list needs a list id or name");
|
|
42
|
+
const { lists } = await call(`${base}/lists`, void 0, input.tenant);
|
|
43
|
+
const matched = matchMotionsList(lists, query);
|
|
44
|
+
if (matched) {
|
|
45
|
+
body.fromList = { id: matched.id, ...input.again ? { again: true } : {} };
|
|
46
|
+
} else {
|
|
47
|
+
if (input.again) throw new Error(`no Motions list "${query}" in ${input.tenant}; --again only applies to Motions lists`);
|
|
48
|
+
body.list = query;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return call(`${base}/motions/${encodeURIComponent(input.motion)}/batches`, body, input.tenant);
|
|
52
|
+
}
|
|
53
|
+
function isStoppedOrFailed(cell) {
|
|
54
|
+
if (!cell || cell.fenced) return false;
|
|
55
|
+
return cell.state === "failed" || cell.state === "parked" && cell.nextAt === void 0;
|
|
56
|
+
}
|
|
57
|
+
function runnableSteps(motion) {
|
|
58
|
+
return new Set(motion.steps.filter((s) => s.kind === "company" || s.kind === "batch").map((s) => s.id));
|
|
59
|
+
}
|
|
60
|
+
function findCompany(companies, query) {
|
|
61
|
+
return companies.find((c) => c.key === query) ?? companies.find((c) => c.key.endsWith(`:${query}`));
|
|
62
|
+
}
|
|
63
|
+
function selectRetries(snap, batch, options2 = {}) {
|
|
64
|
+
const runnable = runnableSteps(snap.motion);
|
|
65
|
+
const step2 = options2.step?.trim();
|
|
66
|
+
const company = options2.company?.trim();
|
|
67
|
+
if (step2 !== void 0) {
|
|
68
|
+
if (!step2) throw new Error("--step needs a step id");
|
|
69
|
+
if (!runnable.has(step2)) throw new Error(`${step2} is not a runnable step in ${snap.motion.motion}`);
|
|
70
|
+
}
|
|
71
|
+
if (company !== void 0) {
|
|
72
|
+
if (!company) throw new Error("--company needs a company id");
|
|
73
|
+
const found = findCompany(snap.status.companies, company);
|
|
74
|
+
if (!found) throw new Error(`no company ${company} in ${batch}`);
|
|
75
|
+
if (step2) {
|
|
76
|
+
if (found.cells[step2]?.fenced) throw new Error(`${found.key} is already sealed past ${step2} in ${batch}`);
|
|
77
|
+
return [{ company: found.key, step: step2 }];
|
|
78
|
+
}
|
|
79
|
+
const steps = snap.motion.steps.filter((s) => runnable.has(s.id) && isStoppedOrFailed(found.cells[s.id])).map((s) => s.id);
|
|
80
|
+
if (!steps.length) throw new Error(`${found.key} has no failed or stopped step in ${batch}; pass --step <id>`);
|
|
81
|
+
return steps.map((s) => ({ company: found.key, step: s }));
|
|
82
|
+
}
|
|
83
|
+
const ordered = step2 ? [step2] : snap.motion.steps.filter((s) => runnable.has(s.id)).map((s) => s.id);
|
|
84
|
+
const out = [];
|
|
85
|
+
for (const c of snap.status.companies) {
|
|
86
|
+
for (const s of ordered) {
|
|
87
|
+
if (isStoppedOrFailed(c.cells[s])) out.push({ company: c.key, step: s });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
async function retryBatch(call, input) {
|
|
93
|
+
const snap = await call(`/api/batches/${encodeURIComponent(input.batch)}`, void 0, input.tenant);
|
|
94
|
+
const tenant = snap.status.tenant;
|
|
95
|
+
const targets = selectRetries(snap, input.batch, { company: input.company, step: input.step });
|
|
96
|
+
for (const target of targets) {
|
|
97
|
+
await call(`/api/batches/${encodeURIComponent(input.batch)}/retry`, target, tenant);
|
|
98
|
+
}
|
|
99
|
+
return { tenant, retried: targets };
|
|
100
|
+
}
|
|
101
|
+
|
|
9
102
|
// src/client.ts
|
|
10
103
|
import { existsSync, readFileSync } from "fs";
|
|
11
104
|
import { dirname, join } from "path";
|
|
@@ -23,9 +116,9 @@ function tokenFiles() {
|
|
|
23
116
|
}
|
|
24
117
|
return files;
|
|
25
118
|
}
|
|
26
|
-
function tokenFor(tenant, url2) {
|
|
119
|
+
function tokenFor(tenant, url2, batch) {
|
|
27
120
|
if (process.env.MOTIONS_TOKEN) return process.env.MOTIONS_TOKEN;
|
|
28
|
-
if (!tenant) return void 0;
|
|
121
|
+
if (!tenant && !batch) return void 0;
|
|
29
122
|
let hostname;
|
|
30
123
|
try {
|
|
31
124
|
hostname = new URL(url2).hostname;
|
|
@@ -36,8 +129,16 @@ function tokenFor(tenant, url2) {
|
|
|
36
129
|
for (const file2 of tokenFiles()) {
|
|
37
130
|
if (!existsSync(file2)) continue;
|
|
38
131
|
try {
|
|
39
|
-
const
|
|
40
|
-
if (
|
|
132
|
+
const tenants = JSON.parse(readFileSync(file2, "utf8")).tenants;
|
|
133
|
+
if (!tenants) continue;
|
|
134
|
+
if (tenant) {
|
|
135
|
+
if (tenants[tenant]) return tenants[tenant];
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (batch) {
|
|
139
|
+
const match = Object.keys(tenants).filter((t) => batch === t || batch.startsWith(`${t}-`)).sort((a, b) => b.length - a.length)[0];
|
|
140
|
+
if (match && tenants[match]) return tenants[match];
|
|
141
|
+
}
|
|
41
142
|
} catch {
|
|
42
143
|
}
|
|
43
144
|
}
|
|
@@ -58,9 +159,10 @@ function describeFailure(path, status, text) {
|
|
|
58
159
|
if (status === 403) return code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`;
|
|
59
160
|
return `${path} \u2192 ${status}${code ? ` ${code}` : ""}: ${message}`;
|
|
60
161
|
}
|
|
61
|
-
async function api(url2, path, body) {
|
|
62
|
-
const
|
|
63
|
-
const
|
|
162
|
+
async function api(url2, path, body, tenant) {
|
|
163
|
+
const pathTenant = tenant ?? path.match(/\/api\/tenants\/([^/]+)/)?.[1];
|
|
164
|
+
const batch = pathTenant ? void 0 : path.match(/\/api\/batches\/([^/?#]+)/)?.[1];
|
|
165
|
+
const key = tokenFor(pathTenant ? decodeURIComponent(pathTenant) : void 0, url2, batch ? decodeURIComponent(batch) : void 0);
|
|
64
166
|
const headers = { accept: "application/json", ...key ? { authorization: `Bearer ${key}` } : {} };
|
|
65
167
|
if (body !== void 0) headers["content-type"] = "application/json";
|
|
66
168
|
const res = await fetch(`${url2.replace(/\/$/, "")}${path}`, {
|
|
@@ -76,7 +178,7 @@ async function api(url2, path, body) {
|
|
|
76
178
|
// src/compile.ts
|
|
77
179
|
import { createHash as createHash2 } from "crypto";
|
|
78
180
|
import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
|
|
79
|
-
import {
|
|
181
|
+
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
|
|
80
182
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
81
183
|
import {
|
|
82
184
|
CRM_WRITES,
|
|
@@ -229,7 +331,10 @@ var RawMotion = z.strictObject({
|
|
|
229
331
|
calendar: z.record(id, calendarSpec).optional(),
|
|
230
332
|
approvers: z.array(z.string()).min(1, "a motion needs at least one approver"),
|
|
231
333
|
reasons: z.array(id).optional(),
|
|
232
|
-
input: z.strictObject({
|
|
334
|
+
input: z.strictObject({
|
|
335
|
+
list: z.string().optional(),
|
|
336
|
+
columns: z.record(id, z.strictObject({ required: z.boolean().optional(), aliases: z.array(z.string().trim().min(1)).optional() }).nullable()).optional()
|
|
337
|
+
}).optional(),
|
|
233
338
|
steps: z.array(step).min(1, "a motion needs at least one step"),
|
|
234
339
|
queues: z.record(id, queue).optional()
|
|
235
340
|
});
|
|
@@ -349,7 +454,7 @@ function ttlSeconds(ttl) {
|
|
|
349
454
|
}
|
|
350
455
|
async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
|
|
351
456
|
const tenantDir = resolve(tenantRoot);
|
|
352
|
-
const id2 = dir
|
|
457
|
+
const id2 = folderName(dir);
|
|
353
458
|
const where2 = `${tenant}/sources/${id2}`;
|
|
354
459
|
const root = resolve(dir);
|
|
355
460
|
const index = join4(root, "index.ts");
|
|
@@ -476,11 +581,15 @@ function monorepoTenants() {
|
|
|
476
581
|
if (!existsSync4(dir)) return null;
|
|
477
582
|
return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync4(join5(dir, name, "tenant.yaml"))).sort().map((name) => join5(dir, name));
|
|
478
583
|
}
|
|
584
|
+
function folderName(dir) {
|
|
585
|
+
const leaf = win32.basename(win32.normalize(dir));
|
|
586
|
+
return leaf !== "." && leaf !== ".." ? leaf : win32.basename(resolve2(dir));
|
|
587
|
+
}
|
|
479
588
|
function tenantIdentity(dir) {
|
|
480
589
|
const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
|
|
481
590
|
const motionsDir = join5(dir, "motions");
|
|
482
591
|
const motions = existsSync4(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync4(join5(motionsDir, name, "motion.yaml"))).sort() : [];
|
|
483
|
-
return { id: meta.id ??
|
|
592
|
+
return { id: meta.id ?? folderName(dir), motions };
|
|
484
593
|
}
|
|
485
594
|
var readYaml = (path) => YAML2.parse(readFileSync4(path, "utf8"));
|
|
486
595
|
var grant = (g) => ({ read: g?.read ?? [], propose: g?.propose ?? [] });
|
|
@@ -507,7 +616,8 @@ var MotionErrors = class extends Error {
|
|
|
507
616
|
async function compileMotion(tenant, dir) {
|
|
508
617
|
const tenantDir = findTenantDir(dir);
|
|
509
618
|
if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
|
|
510
|
-
const
|
|
619
|
+
const folder = folderName(dir);
|
|
620
|
+
const where2 = `${tenant.id}/${folder}/motion.yaml`;
|
|
511
621
|
const parsed2 = parseMotion(readYaml(join5(dir, "motion.yaml")));
|
|
512
622
|
if (!parsed2.ok) throw new MotionErrors(where2, parsed2.errors);
|
|
513
623
|
const raw = parsed2.motion;
|
|
@@ -546,17 +656,18 @@ async function compileMotion(tenant, dir) {
|
|
|
546
656
|
for (const [id2, q] of Object.entries(raw.queues ?? {})) {
|
|
547
657
|
queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
|
|
548
658
|
}
|
|
659
|
+
const motion = raw.motion ?? folder;
|
|
549
660
|
const manifest = {
|
|
550
661
|
tenant: tenant.id,
|
|
551
|
-
motion
|
|
552
|
-
title: raw.title ??
|
|
662
|
+
motion,
|
|
663
|
+
title: raw.title ?? motion,
|
|
553
664
|
timezone: raw.timezone ?? tenant.timezone,
|
|
554
665
|
calendar: raw.calendar ?? {},
|
|
555
666
|
approvers,
|
|
556
667
|
reasons: raw.reasons ?? [],
|
|
557
668
|
rules,
|
|
558
669
|
rulesVersion: rulesVersion(rules),
|
|
559
|
-
input: raw.input
|
|
670
|
+
input: compileInput(raw.input),
|
|
560
671
|
steps,
|
|
561
672
|
queues
|
|
562
673
|
};
|
|
@@ -564,10 +675,19 @@ async function compileMotion(tenant, dir) {
|
|
|
564
675
|
if (errors.length) throw new MotionErrors(where2, errors);
|
|
565
676
|
return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
|
|
566
677
|
}
|
|
678
|
+
function compileInput(input) {
|
|
679
|
+
if (!input) return {};
|
|
680
|
+
const { columns, ...rest } = input;
|
|
681
|
+
if (!columns) return rest;
|
|
682
|
+
return {
|
|
683
|
+
...rest,
|
|
684
|
+
columns: Object.fromEntries(Object.entries(columns).map(([name, c]) => [name, { required: c?.required ?? false, aliases: c?.aliases ?? [] }]))
|
|
685
|
+
};
|
|
686
|
+
}
|
|
567
687
|
async function compileTenant(tenantDir) {
|
|
568
688
|
const dir = resolve2(tenantDir);
|
|
569
689
|
const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
|
|
570
|
-
const id2 = meta.id ??
|
|
690
|
+
const id2 = meta.id ?? folderName(tenantDir);
|
|
571
691
|
const timezone = meta.timezone ?? "America/Sao_Paulo";
|
|
572
692
|
const connection = readYaml(join5(dir, "crm.yaml"));
|
|
573
693
|
const seedPath = join5(dir, "crm-seed.json");
|
|
@@ -589,7 +709,7 @@ function tenantCrmProblems(tenant, systems = CRM_WRITES) {
|
|
|
589
709
|
|
|
590
710
|
// src/init.ts
|
|
591
711
|
import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
|
|
592
|
-
import { basename
|
|
712
|
+
import { basename, dirname as dirname4, join as join6, resolve as resolve3 } from "path";
|
|
593
713
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
594
714
|
var TENANT_ID = /^[a-z][a-z0-9_-]{0,62}$/;
|
|
595
715
|
function cliVersion() {
|
|
@@ -602,7 +722,7 @@ var file = (dir, path, contents) => {
|
|
|
602
722
|
};
|
|
603
723
|
function init(target = ".") {
|
|
604
724
|
const dir = resolve3(target);
|
|
605
|
-
const id2 =
|
|
725
|
+
const id2 = basename(dir);
|
|
606
726
|
if (!TENANT_ID.test(id2)) throw new Error(`${id2} is not a tenant id: lowercase letters, digits, - and _, starting with a letter`);
|
|
607
727
|
if (existsSync5(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
|
|
608
728
|
mkdirSync2(dir, { recursive: true });
|
|
@@ -806,13 +926,78 @@ function inside(root, rel) {
|
|
|
806
926
|
return dest;
|
|
807
927
|
}
|
|
808
928
|
|
|
929
|
+
// src/vitest.ts
|
|
930
|
+
import { spawnSync } from "child_process";
|
|
931
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
|
|
932
|
+
import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
|
|
933
|
+
function findVitestPackage(dir) {
|
|
934
|
+
for (let at = resolve5(dir); ; ) {
|
|
935
|
+
const candidate = join8(at, "node_modules", "vitest", "package.json");
|
|
936
|
+
if (existsSync7(candidate)) return candidate;
|
|
937
|
+
const parent = dirname5(at);
|
|
938
|
+
if (parent === at) return null;
|
|
939
|
+
at = parent;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
function resolveVitest(dir) {
|
|
943
|
+
const pkgPath = findVitestPackage(dir);
|
|
944
|
+
if (pkgPath) {
|
|
945
|
+
try {
|
|
946
|
+
const pkg = JSON.parse(readFileSync7(pkgPath, "utf8"));
|
|
947
|
+
const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.vitest ?? "./vitest.mjs";
|
|
948
|
+
const entry = resolve5(dirname5(pkgPath), rel);
|
|
949
|
+
if (existsSync7(entry)) return entry;
|
|
950
|
+
} catch {
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
throw new Error(`${dir} has no vitest. Add it to devDependencies and install.`);
|
|
954
|
+
}
|
|
955
|
+
function vitestConfig(dir) {
|
|
956
|
+
const root = resolve5(dir);
|
|
957
|
+
const folder = join8(root, "node_modules", ".motions");
|
|
958
|
+
mkdirSync3(folder, { recursive: true });
|
|
959
|
+
const stub = join8(folder, "workers-stub.js");
|
|
960
|
+
writeFileSync3(stub, "export class WorkerEntrypoint {}\n");
|
|
961
|
+
const config = join8(folder, "vitest.config.ts");
|
|
962
|
+
writeFileSync3(
|
|
963
|
+
config,
|
|
964
|
+
`import { defineConfig } from "vitest/config";
|
|
965
|
+
|
|
966
|
+
export default defineConfig({
|
|
967
|
+
root: ${JSON.stringify(root.split(sep4).join("/"))},
|
|
968
|
+
resolve: { alias: { "cloudflare:workers": ${JSON.stringify(stub.split(sep4).join("/"))} } },
|
|
969
|
+
test: {
|
|
970
|
+
include: ["motions/*/tests/**/*.test.ts"],
|
|
971
|
+
passWithNoTests: true,
|
|
972
|
+
server: { deps: { inline: [/@motionskit\\/sdk/, /@motionskit\\/kernel/] } },
|
|
973
|
+
},
|
|
974
|
+
});
|
|
975
|
+
`
|
|
976
|
+
);
|
|
977
|
+
return config;
|
|
978
|
+
}
|
|
979
|
+
function runVitest(dir, spawn = spawnSync) {
|
|
980
|
+
const entry = resolveVitest(dir);
|
|
981
|
+
const run2 = spawn(process.execPath, [entry, "run", "--config", vitestConfig(dir)], { cwd: dir, stdio: "inherit" });
|
|
982
|
+
if (run2.error) throw run2.error;
|
|
983
|
+
return run2.status === 0;
|
|
984
|
+
}
|
|
985
|
+
function runTenantTests(dirs, spawn = spawnSync) {
|
|
986
|
+
let failed = 0;
|
|
987
|
+
for (const dir of dirs) {
|
|
988
|
+
if (!runVitest(dir, spawn)) failed++;
|
|
989
|
+
}
|
|
990
|
+
if (failed) throw new Error(`${failed} tenant${failed > 1 ? "s" : ""} failed the tests`);
|
|
991
|
+
}
|
|
992
|
+
|
|
809
993
|
// src/main.ts
|
|
810
|
-
var USAGE = `usage: motions <check|push|pull|test|open|init|publish> \u2026
|
|
994
|
+
var USAGE = `usage: motions <check|push|pull|test|open|retry|init|publish> \u2026
|
|
811
995
|
check [tenant] compile the tenant in this directory, or every tenant in this repo
|
|
812
996
|
push [--live] [-m message] publish a draft (or go live with --live) and print a link
|
|
813
997
|
pull <version> [--motion id] [--force]
|
|
814
998
|
test run motions/*/tests with the tenant's vitest
|
|
815
|
-
open <tenant> <motion> [--list name | --companies id,id] [--label text]
|
|
999
|
+
open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]
|
|
1000
|
+
retry <batch> [--company id] [--step id]
|
|
816
1001
|
init [dir] scaffold a tenant repo
|
|
817
1002
|
publish [tenant] from this repo, push --live over tenants/*`;
|
|
818
1003
|
var parsed = (() => {
|
|
@@ -829,6 +1014,9 @@ var parsed = (() => {
|
|
|
829
1014
|
force: { type: "boolean", default: false },
|
|
830
1015
|
list: { type: "string" },
|
|
831
1016
|
companies: { type: "string" },
|
|
1017
|
+
company: { type: "string" },
|
|
1018
|
+
step: { type: "string" },
|
|
1019
|
+
again: { type: "boolean", default: false },
|
|
832
1020
|
label: { type: "string" },
|
|
833
1021
|
reseed: { type: "boolean", default: false },
|
|
834
1022
|
help: { type: "boolean", short: "h", default: false }
|
|
@@ -850,14 +1038,14 @@ var [command, ...args] = positionals;
|
|
|
850
1038
|
var url = values.url.replace(/\/$/, "");
|
|
851
1039
|
function resolveTenants(positional, fallbackAll) {
|
|
852
1040
|
if (values.tenant) {
|
|
853
|
-
const found = findTenantDir(
|
|
1041
|
+
const found = findTenantDir(resolve6(values.tenant));
|
|
854
1042
|
if (!found) throw new Error(`no tenant.yaml in ${values.tenant}`);
|
|
855
1043
|
return [found];
|
|
856
1044
|
}
|
|
857
1045
|
if (positional) {
|
|
858
|
-
const direct = findTenantDir(
|
|
859
|
-
if (
|
|
860
|
-
const match = monorepoTenants()?.find((dir) => dir
|
|
1046
|
+
const direct = findTenantDir(resolve6(positional));
|
|
1047
|
+
if (existsSync8(positional) && direct) return [direct];
|
|
1048
|
+
const match = monorepoTenants()?.find((dir) => folderName(dir) === positional);
|
|
861
1049
|
if (match) return [match];
|
|
862
1050
|
throw new Error(`no tenant ${positional}`);
|
|
863
1051
|
}
|
|
@@ -899,7 +1087,7 @@ async function check(only) {
|
|
|
899
1087
|
for (const dir of resolveTenants(only, true)) {
|
|
900
1088
|
const tenant = await compileTenant(dir).catch((e) => {
|
|
901
1089
|
failed++;
|
|
902
|
-
console.error(`${dir
|
|
1090
|
+
console.error(`${folderName(dir)}: ${e.message}`);
|
|
903
1091
|
return null;
|
|
904
1092
|
});
|
|
905
1093
|
if (!tenant) continue;
|
|
@@ -933,7 +1121,7 @@ async function push() {
|
|
|
933
1121
|
async function publish(only) {
|
|
934
1122
|
const all = monorepoTenants();
|
|
935
1123
|
if (!all) throw new Error("publish runs over this repo's tenants/*; from a tenant repo use motions push --live");
|
|
936
|
-
const dirs = only ? all.filter((dir) => dir
|
|
1124
|
+
const dirs = only ? all.filter((dir) => folderName(dir) === only) : all;
|
|
937
1125
|
if (only && !dirs.length) throw new Error(`no tenant ${only}`);
|
|
938
1126
|
await pushDirs(dirs, !values.draft);
|
|
939
1127
|
}
|
|
@@ -954,8 +1142,8 @@ async function pull(version) {
|
|
|
954
1142
|
if (!motion) throw new Error(`this tenant has ${motions.length} motions; pass --motion <id>`);
|
|
955
1143
|
const sha = await resolveSha(id2, motion, version);
|
|
956
1144
|
const { files } = await api(url, `/api/tenants/${id2}/motions/${motion}/versions/${sha}/files`);
|
|
957
|
-
const motionDir =
|
|
958
|
-
const writes = Object.entries(files).map(([path, next]) => ({ rel:
|
|
1145
|
+
const motionDir = join9(dir, "motions", motion);
|
|
1146
|
+
const writes = Object.entries(files).map(([path, next]) => ({ rel: join9("motions", motion, path), path, next }));
|
|
959
1147
|
if (!values.force) {
|
|
960
1148
|
const blocked = blockedOverwrites(dir, writes);
|
|
961
1149
|
if (blocked.length) throw new Error(`refusing to overwrite uncommitted changes (pass --force):
|
|
@@ -966,11 +1154,11 @@ async function pull(version) {
|
|
|
966
1154
|
let unchanged = 0;
|
|
967
1155
|
for (const write of writes.sort((a, b) => a.rel < b.rel ? -1 : 1)) {
|
|
968
1156
|
const dest = inside(motionDir, write.path);
|
|
969
|
-
const existed =
|
|
970
|
-
const same = existed &&
|
|
1157
|
+
const existed = existsSync8(dest);
|
|
1158
|
+
const same = existed && readFileSync8(dest, "utf8") === write.next;
|
|
971
1159
|
if (!same) {
|
|
972
|
-
|
|
973
|
-
|
|
1160
|
+
mkdirSync4(dirname6(dest), { recursive: true });
|
|
1161
|
+
writeFileSync4(dest, write.next);
|
|
974
1162
|
}
|
|
975
1163
|
if (!existed) {
|
|
976
1164
|
created++;
|
|
@@ -982,55 +1170,62 @@ async function pull(version) {
|
|
|
982
1170
|
}
|
|
983
1171
|
console.log(`pulled ${id2}/${motion} @ ${sha.slice(0, 10)} (${created} created, ${updated} updated, ${unchanged} unchanged)`);
|
|
984
1172
|
}
|
|
985
|
-
function vitestConfig(dir) {
|
|
986
|
-
const folder = join8(dir, "node_modules", ".motions");
|
|
987
|
-
mkdirSync3(folder, { recursive: true });
|
|
988
|
-
const stub = join8(folder, "workers-stub.js");
|
|
989
|
-
writeFileSync3(stub, "export class WorkerEntrypoint {}\n");
|
|
990
|
-
const config = join8(folder, "vitest.config.ts");
|
|
991
|
-
writeFileSync3(
|
|
992
|
-
config,
|
|
993
|
-
`import { defineConfig } from "vitest/config";
|
|
994
|
-
|
|
995
|
-
export default defineConfig({
|
|
996
|
-
root: ${JSON.stringify(dir)},
|
|
997
|
-
resolve: { alias: { "cloudflare:workers": ${JSON.stringify(stub)} } },
|
|
998
|
-
test: {
|
|
999
|
-
include: ["motions/*/tests/**/*.test.ts"],
|
|
1000
|
-
passWithNoTests: true,
|
|
1001
|
-
server: { deps: { inline: [/@motionskit\\/sdk/, /@motionskit\\/kernel/] } },
|
|
1002
|
-
},
|
|
1003
|
-
});
|
|
1004
|
-
`
|
|
1005
|
-
);
|
|
1006
|
-
return config;
|
|
1007
|
-
}
|
|
1008
1173
|
async function test(only) {
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
const
|
|
1014
|
-
|
|
1174
|
+
runTenantTests(resolveTenants(only, true));
|
|
1175
|
+
}
|
|
1176
|
+
function optionalTenant() {
|
|
1177
|
+
if (values.tenant) {
|
|
1178
|
+
const found = findTenantDir(resolve6(values.tenant));
|
|
1179
|
+
return found ? tenantIdentity(found).id : values.tenant;
|
|
1015
1180
|
}
|
|
1016
|
-
|
|
1181
|
+
const here = findTenantDir(process.cwd());
|
|
1182
|
+
return here ? tenantIdentity(here).id : void 0;
|
|
1017
1183
|
}
|
|
1018
|
-
async function open(tenant, motion) {
|
|
1019
|
-
if (!tenant || !motion
|
|
1020
|
-
|
|
1184
|
+
async function open(tenant, motion, extra) {
|
|
1185
|
+
if (!tenant || !motion || extra) {
|
|
1186
|
+
throw new Error("usage: motions open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]");
|
|
1187
|
+
}
|
|
1188
|
+
const out = await openBatch((path, body, t) => api(url, path, body, t), {
|
|
1189
|
+
tenant,
|
|
1190
|
+
motion,
|
|
1021
1191
|
list: values.list,
|
|
1022
|
-
companies: values.companies
|
|
1023
|
-
label: values.label
|
|
1192
|
+
companies: values.companies,
|
|
1193
|
+
label: values.label,
|
|
1194
|
+
again: values.again
|
|
1024
1195
|
});
|
|
1025
|
-
|
|
1196
|
+
const suffix = out.reused ? " (existing batch for this list and version; pass --again to open another)" : out.skipped ? ` (${out.skipped} skipped)` : out.missing?.length ? ` (${out.missing.length} not in CRM)` : "";
|
|
1197
|
+
console.log(`${out.reused ? "reused" : "opened"} batch ${out.id} with ${out.companies} companies${suffix}`);
|
|
1026
1198
|
console.log(` ${url}/t/${tenant}/batches/${out.id}`);
|
|
1027
1199
|
}
|
|
1200
|
+
async function retry(batch, extra) {
|
|
1201
|
+
if (!batch || extra || values.companies !== void 0) {
|
|
1202
|
+
throw new Error("usage: motions retry <batch> [--company id] [--step id]");
|
|
1203
|
+
}
|
|
1204
|
+
const { tenant, retried } = await retryBatch((path, body, t) => api(url, path, body, t), {
|
|
1205
|
+
batch,
|
|
1206
|
+
company: values.company,
|
|
1207
|
+
step: values.step,
|
|
1208
|
+
tenant: optionalTenant()
|
|
1209
|
+
});
|
|
1210
|
+
if (!retried.length) {
|
|
1211
|
+
console.log(values.step ? `nothing to retry at ${values.step} in ${batch}` : `nothing to retry in ${batch}`);
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
if (retried.length === 1) {
|
|
1215
|
+
console.log(`retried ${retried[0].company} at ${retried[0].step}`);
|
|
1216
|
+
} else {
|
|
1217
|
+
console.log(`retried ${retried.length} cells in ${batch}:`);
|
|
1218
|
+
for (const target of retried) console.log(` ${target.company} \xB7 ${target.step}`);
|
|
1219
|
+
}
|
|
1220
|
+
console.log(` ${url}/t/${tenant}/batches/${batch}`);
|
|
1221
|
+
}
|
|
1028
1222
|
var commands = {
|
|
1029
1223
|
check,
|
|
1030
1224
|
push,
|
|
1031
1225
|
pull,
|
|
1032
1226
|
test,
|
|
1033
1227
|
open,
|
|
1228
|
+
retry,
|
|
1034
1229
|
init: (dir) => {
|
|
1035
1230
|
const created = init(dir);
|
|
1036
1231
|
console.log(`created ${created}`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motionskit/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"esbuild": "^0.28.2",
|
|
30
30
|
"yaml": "^2.9.1",
|
|
31
31
|
"zod": "^4.6.7",
|
|
32
|
-
"@motionskit/kernel": "0.
|
|
32
|
+
"@motionskit/kernel": "0.2.2"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@types/node": "^22.19.0",
|