@motionskit/cli 0.0.0-stage → 0.2.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.
- package/README.md +6 -2
- package/dist/index.d.ts +53 -0
- package/dist/index.js +481 -0
- package/dist/main.js +1060 -0
- package/package.json +44 -3
package/dist/main.js
ADDED
|
@@ -0,0 +1,1060 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/main.ts
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
|
|
6
|
+
import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
|
|
7
|
+
import { parseArgs } from "util";
|
|
8
|
+
|
|
9
|
+
// src/client.ts
|
|
10
|
+
import { existsSync, readFileSync } from "fs";
|
|
11
|
+
import { dirname, join } from "path";
|
|
12
|
+
import { fileURLToPath } from "url";
|
|
13
|
+
var LOCAL = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
14
|
+
function tokenFiles() {
|
|
15
|
+
if (process.env.MOTIONS_DEV_DIR) return [join(process.env.MOTIONS_DEV_DIR, "tokens.json")];
|
|
16
|
+
const files = [fileURLToPath(new URL("../../../.motions-dev/tokens.json", import.meta.url))];
|
|
17
|
+
let dir = process.cwd();
|
|
18
|
+
for (; ; ) {
|
|
19
|
+
files.push(join(dir, ".motions-dev", "tokens.json"));
|
|
20
|
+
const parent = dirname(dir);
|
|
21
|
+
if (parent === dir) break;
|
|
22
|
+
dir = parent;
|
|
23
|
+
}
|
|
24
|
+
return files;
|
|
25
|
+
}
|
|
26
|
+
function tokenFor(tenant, url2) {
|
|
27
|
+
if (process.env.MOTIONS_TOKEN) return process.env.MOTIONS_TOKEN;
|
|
28
|
+
if (!tenant) return void 0;
|
|
29
|
+
let hostname;
|
|
30
|
+
try {
|
|
31
|
+
hostname = new URL(url2).hostname;
|
|
32
|
+
} catch {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
if (!LOCAL.has(hostname)) return void 0;
|
|
36
|
+
for (const file2 of tokenFiles()) {
|
|
37
|
+
if (!existsSync(file2)) continue;
|
|
38
|
+
try {
|
|
39
|
+
const key = JSON.parse(readFileSync(file2, "utf8")).tenants?.[tenant];
|
|
40
|
+
if (key) return key;
|
|
41
|
+
} catch {
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
46
|
+
function describeFailure(path, status, text) {
|
|
47
|
+
let code;
|
|
48
|
+
let message = text.trim();
|
|
49
|
+
try {
|
|
50
|
+
const body = JSON.parse(text);
|
|
51
|
+
if (typeof body.error?.message === "string") {
|
|
52
|
+
code = body.error.code;
|
|
53
|
+
message = body.error.message;
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
if (status === 401) return code ? `unauthorized (${code}): ${message}` : `unauthorized: ${message}`;
|
|
58
|
+
if (status === 403) return code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`;
|
|
59
|
+
return `${path} \u2192 ${status}${code ? ` ${code}` : ""}: ${message}`;
|
|
60
|
+
}
|
|
61
|
+
async function api(url2, path, body) {
|
|
62
|
+
const tenant = path.match(/\/api\/tenants\/([^/]+)/)?.[1];
|
|
63
|
+
const key = tokenFor(tenant, url2);
|
|
64
|
+
const headers = { accept: "application/json", ...key ? { authorization: `Bearer ${key}` } : {} };
|
|
65
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
66
|
+
const res = await fetch(`${url2.replace(/\/$/, "")}${path}`, {
|
|
67
|
+
method: body === void 0 ? "GET" : "POST",
|
|
68
|
+
headers,
|
|
69
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
70
|
+
});
|
|
71
|
+
const text = await res.text();
|
|
72
|
+
if (!res.ok) throw new Error(describeFailure(path, res.status, text));
|
|
73
|
+
return text ? JSON.parse(text) : {};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/compile.ts
|
|
77
|
+
import { createHash as createHash2 } from "crypto";
|
|
78
|
+
import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
|
|
79
|
+
import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve2, sep as sep2 } from "path";
|
|
80
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
81
|
+
import {
|
|
82
|
+
CRM_WRITES,
|
|
83
|
+
crmProblems,
|
|
84
|
+
rulesVersion,
|
|
85
|
+
STEP_BUILD,
|
|
86
|
+
STEP_ENTRY_FILE,
|
|
87
|
+
stepEntry,
|
|
88
|
+
unknownCrmSystem,
|
|
89
|
+
validateManifest,
|
|
90
|
+
versionId as versionId2
|
|
91
|
+
} from "@motionskit/kernel";
|
|
92
|
+
import { build as build2 } from "esbuild";
|
|
93
|
+
import YAML2 from "yaml";
|
|
94
|
+
|
|
95
|
+
// src/bundle.ts
|
|
96
|
+
import { builtinModules, createRequire } from "module";
|
|
97
|
+
import { join as join2 } from "path";
|
|
98
|
+
function resolveFrom(tenantDir, spec) {
|
|
99
|
+
try {
|
|
100
|
+
return createRequire(join2(tenantDir, "package.json")).resolve(spec);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
const detail = e instanceof Error ? e.message : String(e);
|
|
103
|
+
throw new Error(`can't resolve ${spec} from ${tenantDir} (${detail})`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function tenantSdk(tenantDir) {
|
|
107
|
+
return {
|
|
108
|
+
name: "tenant-sdk",
|
|
109
|
+
setup(b) {
|
|
110
|
+
b.onResolve({ filter: /^@motionskit\/sdk(\/|$)/ }, (args2) => ({ path: resolveFrom(tenantDir, args2.path) }));
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
var NODE_BUILTINS = new Set(builtinModules);
|
|
115
|
+
function nodeBuiltins() {
|
|
116
|
+
return {
|
|
117
|
+
name: "node-builtins",
|
|
118
|
+
setup(b) {
|
|
119
|
+
b.onResolve({ filter: /.*/ }, (args2) => {
|
|
120
|
+
const name = args2.path.startsWith("node:") ? args2.path.slice(5) : args2.path;
|
|
121
|
+
if (!NODE_BUILTINS.has(name) && !NODE_BUILTINS.has(`node:${name}`)) return;
|
|
122
|
+
return { path: `node:${name}`, external: true };
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/fixtures.ts
|
|
129
|
+
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "fs";
|
|
130
|
+
import { join as join3 } from "path";
|
|
131
|
+
import { readFixtureFiles } from "@motionskit/kernel";
|
|
132
|
+
var FIXTURES_DIR = join3("fixtures", "sources");
|
|
133
|
+
function readTenantFixtures(dir, sources) {
|
|
134
|
+
const problems = [];
|
|
135
|
+
let enabled = false;
|
|
136
|
+
if (sources !== void 0 && sources !== null) {
|
|
137
|
+
if (typeof sources !== "object" || Array.isArray(sources)) problems.push("tenant.yaml: sources must be a map such as { fixtures: true }");
|
|
138
|
+
else {
|
|
139
|
+
const { fixtures } = sources;
|
|
140
|
+
if (fixtures !== void 0 && typeof fixtures !== "boolean") problems.push("tenant.yaml: sources.fixtures must be true or false");
|
|
141
|
+
else enabled = fixtures === true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const folder = join3(dir, FIXTURES_DIR);
|
|
145
|
+
const files = existsSync2(folder) ? readdirSync(folder).filter((name) => name.endsWith(".json")) : [];
|
|
146
|
+
const read = readFixtureFiles(files.map((name) => [`fixtures/sources/${name}`, readFileSync2(join3(folder, name), "utf8")]));
|
|
147
|
+
problems.push(...read.errors);
|
|
148
|
+
if (problems.length) throw new Error(`fixtures:
|
|
149
|
+
${problems.join("\n ")}`);
|
|
150
|
+
return { enabled, files: files.sort(), entries: read.entries };
|
|
151
|
+
}
|
|
152
|
+
function fixturesLine(f) {
|
|
153
|
+
if (!f.enabled && !f.files.length) return null;
|
|
154
|
+
const count = `${f.entries.length} ${f.entries.length === 1 ? "entry" : "entries"} in ${f.files.length} file${f.files.length === 1 ? "" : "s"}`;
|
|
155
|
+
return f.enabled ? ` fixtures on: built-in sources answer from ${count}` : ` fixtures off (${count}; set sources.fixtures in tenant.yaml to use them)`;
|
|
156
|
+
}
|
|
157
|
+
function upsertBody(tenant, reseed) {
|
|
158
|
+
const body = { title: tenant.title, timezone: tenant.timezone, connection: tenant.connection, reseed };
|
|
159
|
+
if (tenant.seed) body.seed = tenant.seed;
|
|
160
|
+
body.sources = { fixtures: tenant.fixtures.enabled };
|
|
161
|
+
if (tenant.fixtures.enabled) body.fixtures = tenant.fixtures.entries;
|
|
162
|
+
return body;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/manifest.ts
|
|
166
|
+
import { parseDuration } from "@motionskit/kernel";
|
|
167
|
+
import { z } from "zod";
|
|
168
|
+
var ID = /^[a-z][a-z0-9_]*$/;
|
|
169
|
+
var id = z.string().regex(ID, "ids are lowercase snake_case");
|
|
170
|
+
var json = z.lazy(() => z.union([z.null(), z.boolean(), z.number(), z.string(), z.array(json), z.record(z.string(), json)]));
|
|
171
|
+
var CRM_OBJECTS = ["companies", "contacts", "deals", "owners", "notes"];
|
|
172
|
+
var CRM_ACTIONS = [
|
|
173
|
+
"companies.update",
|
|
174
|
+
"contacts.create",
|
|
175
|
+
"contacts.update",
|
|
176
|
+
"associate",
|
|
177
|
+
"notes.create",
|
|
178
|
+
"notes.pin"
|
|
179
|
+
];
|
|
180
|
+
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
181
|
+
var calendarSpec = z.strictObject({ in: z.string().optional(), at: z.string().optional(), weekday: z.enum(WEEKDAYS).optional() }).superRefine((spec, ctx) => {
|
|
182
|
+
const issue = (message) => ctx.addIssue({ code: "custom", message });
|
|
183
|
+
if (spec.in !== void 0) {
|
|
184
|
+
if (spec.at !== void 0 || spec.weekday !== void 0) issue(`use either "in" or "at" (with an optional "weekday"), not both`);
|
|
185
|
+
else if (parseDuration(spec.in) === null) issue(`"in" must be a duration such as "4h" or "2d", got "${spec.in}"`);
|
|
186
|
+
} else if (spec.at === void 0) issue(`needs "in" (a duration), "at" (an instant), or "weekday" and "at"`);
|
|
187
|
+
else if (spec.weekday !== void 0) {
|
|
188
|
+
if (!/^([01]?\d|2[0-3]):[0-5]\d$/.test(spec.at)) issue(`"at" must be a time such as "18:00" when a weekday is given, got "${spec.at}"`);
|
|
189
|
+
} else if (Number.isNaN(Date.parse(spec.at))) issue(`"at" must be an ISO instant, or a time with a "weekday", got "${spec.at}"`);
|
|
190
|
+
}).transform((spec) => spec);
|
|
191
|
+
var crm = z.strictObject({ read: z.array(z.enum(CRM_OBJECTS)).optional(), propose: z.array(z.enum(CRM_ACTIONS)).optional() });
|
|
192
|
+
var cap = z.strictObject({ per_company_usd: z.number().positive().optional(), per_batch_usd: z.number().positive().optional() });
|
|
193
|
+
var RUNNABLE = ["run", "sources", "crm", "cap", "retries"];
|
|
194
|
+
var ONLY = { when: ["company"], until: ["checkpoint"], approval: ["changeset"] };
|
|
195
|
+
var step = z.strictObject({
|
|
196
|
+
id,
|
|
197
|
+
kind: z.enum(["company", "batch", "checkpoint", "changeset"]).optional(),
|
|
198
|
+
title: z.string().optional(),
|
|
199
|
+
after: z.array(z.string()).optional(),
|
|
200
|
+
run: z.string().optional(),
|
|
201
|
+
sources: z.array(z.string()).optional(),
|
|
202
|
+
crm: crm.optional(),
|
|
203
|
+
cap: cap.optional(),
|
|
204
|
+
retries: z.number().int().min(0).max(10).optional(),
|
|
205
|
+
when: z.strictObject({ fact: z.string(), in: z.array(json).min(1) }).optional(),
|
|
206
|
+
until: z.strictObject({ at: z.string().optional(), event: z.string().optional(), manual: z.boolean().optional() }).optional(),
|
|
207
|
+
approval: z.enum(["required", "auto"]).optional()
|
|
208
|
+
}).superRefine((s, ctx) => {
|
|
209
|
+
const kind = s.kind ?? "company";
|
|
210
|
+
const runnable = kind === "company" || kind === "batch";
|
|
211
|
+
if (runnable && !s.run) ctx.addIssue({ code: "custom", path: ["run"], message: `is required for ${kind} steps` });
|
|
212
|
+
for (const key of RUNNABLE)
|
|
213
|
+
if (!runnable && s[key] !== void 0) ctx.addIssue({ code: "custom", path: [key], message: `is not allowed on ${kind} steps` });
|
|
214
|
+
for (const [key, kinds] of Object.entries(ONLY)) {
|
|
215
|
+
if (s[key] !== void 0 && !kinds.includes(kind))
|
|
216
|
+
ctx.addIssue({ code: "custom", path: [key], message: `is only allowed on ${kinds.join(", ")} steps` });
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
var queue = z.strictObject({
|
|
220
|
+
title: z.string().optional(),
|
|
221
|
+
owner: z.string().optional(),
|
|
222
|
+
deadline: z.string().optional(),
|
|
223
|
+
default: z.enum(["hold", "drop", "continue", "recommended"]).optional()
|
|
224
|
+
});
|
|
225
|
+
var RawMotion = z.strictObject({
|
|
226
|
+
motion: id.optional(),
|
|
227
|
+
title: z.string().optional(),
|
|
228
|
+
timezone: z.string().optional(),
|
|
229
|
+
calendar: z.record(id, calendarSpec).optional(),
|
|
230
|
+
approvers: z.array(z.string()).min(1, "a motion needs at least one approver"),
|
|
231
|
+
reasons: z.array(id).optional(),
|
|
232
|
+
input: z.strictObject({
|
|
233
|
+
list: z.string().optional(),
|
|
234
|
+
columns: z.record(id, z.strictObject({ required: z.boolean().optional(), aliases: z.array(z.string().trim().min(1)).optional() }).nullable()).optional()
|
|
235
|
+
}).optional(),
|
|
236
|
+
steps: z.array(step).min(1, "a motion needs at least one step"),
|
|
237
|
+
queues: z.record(id, queue).optional()
|
|
238
|
+
});
|
|
239
|
+
function where(raw, path) {
|
|
240
|
+
let out = "";
|
|
241
|
+
let node = raw;
|
|
242
|
+
for (const key of path) {
|
|
243
|
+
node = node?.[key];
|
|
244
|
+
if (typeof key === "number") {
|
|
245
|
+
const label = node && typeof node.id === "string" ? ` (${node.id})` : "";
|
|
246
|
+
out += `[${key}]${label}`;
|
|
247
|
+
} else out += out ? `.${String(key)}` : String(key);
|
|
248
|
+
}
|
|
249
|
+
return out || "motion";
|
|
250
|
+
}
|
|
251
|
+
function references(raw) {
|
|
252
|
+
const out = [];
|
|
253
|
+
const issue = (path, message) => out.push({ path, message });
|
|
254
|
+
const calendar = raw.calendar && typeof raw.calendar === "object" ? raw.calendar : {};
|
|
255
|
+
const keys = Object.keys(calendar);
|
|
256
|
+
const ref = (path, value) => {
|
|
257
|
+
if (typeof value !== "string" || value in calendar || parseDuration(value) !== null) return;
|
|
258
|
+
issue(
|
|
259
|
+
path,
|
|
260
|
+
`"${value}" is neither a calendar key nor a duration${keys.length ? `; calendar keys are ${keys.join(", ")}` : "; the motion has no calendar"}`
|
|
261
|
+
);
|
|
262
|
+
};
|
|
263
|
+
if (typeof raw.timezone === "string") {
|
|
264
|
+
try {
|
|
265
|
+
new Intl.DateTimeFormat("en-US", { timeZone: raw.timezone });
|
|
266
|
+
} catch {
|
|
267
|
+
issue(["timezone"], `"${raw.timezone}" is not an IANA time zone`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const steps = Array.isArray(raw.steps) ? raw.steps : [];
|
|
271
|
+
const ids = steps.map((s) => typeof s?.id === "string" ? s.id : "");
|
|
272
|
+
const upstream = /* @__PURE__ */ new Map();
|
|
273
|
+
steps.forEach((s, i) => {
|
|
274
|
+
if (!s || typeof s !== "object") return;
|
|
275
|
+
const id2 = ids[i];
|
|
276
|
+
const after = Array.isArray(s.after) ? s.after : i > 0 ? [ids[i - 1]] : [];
|
|
277
|
+
const ups = /* @__PURE__ */ new Set();
|
|
278
|
+
if (id2 && upstream.has(id2)) issue(["steps", i, "id"], `duplicate step id "${id2}"`);
|
|
279
|
+
after.forEach((dep, j) => {
|
|
280
|
+
const known = typeof dep === "string" ? upstream.get(dep) : void 0;
|
|
281
|
+
if (!known) issue(["steps", i, "after", j], ids.includes(String(dep)) ? `"${dep}" must be an earlier step` : `no step "${dep}"`);
|
|
282
|
+
else for (const d of [dep, ...known]) ups.add(d);
|
|
283
|
+
});
|
|
284
|
+
if (id2) upstream.set(id2, ups);
|
|
285
|
+
ref(["steps", i, "until", "at"], s.until?.at);
|
|
286
|
+
const fact = s.when?.fact;
|
|
287
|
+
const head = typeof fact === "string" ? fact.split(".")[0] : void 0;
|
|
288
|
+
if (head && head !== "core" && head !== "fields" && !ups.has(head))
|
|
289
|
+
issue(["steps", i, "when", "fact"], `"${fact}" must start with core, fields, or an upstream step id`);
|
|
290
|
+
});
|
|
291
|
+
const queues = raw.queues && typeof raw.queues === "object" ? raw.queues : {};
|
|
292
|
+
for (const [qid, q] of Object.entries(queues)) ref(["queues", qid, "deadline"], q?.deadline);
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
function parseMotion(raw) {
|
|
296
|
+
const doc = raw ?? {};
|
|
297
|
+
const result = RawMotion.safeParse(doc);
|
|
298
|
+
const issues = [...result.success ? [] : result.error.issues, ...doc && typeof doc === "object" ? references(doc) : []];
|
|
299
|
+
if (result.success && !issues.length) return { ok: true, motion: result.data };
|
|
300
|
+
return { ok: false, errors: issues.map((i) => `${where(raw, i.path)}: ${i.message}`) };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// src/sources.ts
|
|
304
|
+
import { createHash } from "crypto";
|
|
305
|
+
import { existsSync as existsSync3, mkdirSync, readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
|
|
306
|
+
import { dirname as dirname2, isAbsolute, join as join4, relative, resolve, sep } from "path";
|
|
307
|
+
import { parseDuration as parseDuration2, validateSourceManifest, versionId } from "@motionskit/kernel";
|
|
308
|
+
import { build } from "esbuild";
|
|
309
|
+
import YAML from "yaml";
|
|
310
|
+
import { z as z2 } from "zod";
|
|
311
|
+
var sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
312
|
+
var SourceErrors = class extends Error {
|
|
313
|
+
constructor(where2, errors) {
|
|
314
|
+
super(`${where2}:
|
|
315
|
+
${errors.join("\n ")}`);
|
|
316
|
+
this.where = where2;
|
|
317
|
+
this.errors = errors;
|
|
318
|
+
}
|
|
319
|
+
where;
|
|
320
|
+
errors;
|
|
321
|
+
};
|
|
322
|
+
var SourceYaml = z2.strictObject({ title: z2.string().optional() }).nullable();
|
|
323
|
+
var options = (entry, resolveDir, platform, tenantDir) => ({
|
|
324
|
+
absWorkingDir: tenantDir,
|
|
325
|
+
metafile: true,
|
|
326
|
+
stdin: { contents: entry, resolveDir, sourcefile: "entry.ts", loader: "ts" },
|
|
327
|
+
bundle: true,
|
|
328
|
+
write: false,
|
|
329
|
+
format: "esm",
|
|
330
|
+
platform,
|
|
331
|
+
target: "es2022",
|
|
332
|
+
mainFields: ["module", "main"],
|
|
333
|
+
conditions: ["workerd", "worker", "import", "default"],
|
|
334
|
+
external: ["cloudflare:workers"],
|
|
335
|
+
plugins: [tenantSdk(tenantDir), nodeBuiltins()],
|
|
336
|
+
nodePaths: [join4(tenantDir, "node_modules")],
|
|
337
|
+
legalComments: "none",
|
|
338
|
+
logLevel: "silent"
|
|
339
|
+
});
|
|
340
|
+
async function definition(index, tenantDir) {
|
|
341
|
+
const out = await build(options(`export { default } from ${JSON.stringify(index)};
|
|
342
|
+
`, dirname2(index), "node", tenantDir));
|
|
343
|
+
const code = out.outputFiles[0].text;
|
|
344
|
+
const mod = await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
|
|
345
|
+
return mod.default;
|
|
346
|
+
}
|
|
347
|
+
function ttlSeconds(ttl) {
|
|
348
|
+
if (ttl === void 0) return 0;
|
|
349
|
+
if (typeof ttl === "number") return Number.isInteger(ttl) && ttl >= 0 ? ttl : `ttl must be a whole number of seconds, got ${ttl}`;
|
|
350
|
+
const ms = typeof ttl === "string" ? parseDuration2(ttl) : null;
|
|
351
|
+
return ms === null ? `ttl must be a duration such as "7d" or "12h", or seconds, got ${JSON.stringify(ttl)}` : Math.round(ms / 1e3);
|
|
352
|
+
}
|
|
353
|
+
async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
|
|
354
|
+
const tenantDir = resolve(tenantRoot);
|
|
355
|
+
const id2 = dir.split(sep).at(-1);
|
|
356
|
+
const where2 = `${tenant}/sources/${id2}`;
|
|
357
|
+
const root = resolve(dir);
|
|
358
|
+
const index = join4(root, "index.ts");
|
|
359
|
+
if (!existsSync3(index)) throw new SourceErrors(where2, ["index.ts does not exist"]);
|
|
360
|
+
const yamlPath = join4(root, "source.yaml");
|
|
361
|
+
const yaml = SourceYaml.safeParse(existsSync3(yamlPath) ? YAML.parse(readFileSync3(yamlPath, "utf8")) : null);
|
|
362
|
+
if (!yaml.success)
|
|
363
|
+
throw new SourceErrors(
|
|
364
|
+
`${where2}/source.yaml`,
|
|
365
|
+
yaml.error.issues.map(
|
|
366
|
+
(i) => i.code === "unrecognized_keys" ? `only takes a title; ${i.keys.join(", ")} belong${i.keys.length > 1 ? "" : "s"} in defineSource in index.ts` : `${i.path.join(".") || "source.yaml"}: ${i.message}`
|
|
367
|
+
)
|
|
368
|
+
);
|
|
369
|
+
const def = await definition(index, tenantDir).catch((e) => {
|
|
370
|
+
const first = e.errors?.[0]?.text ?? e.message.split("\n")[0];
|
|
371
|
+
throw new SourceErrors(where2, [`index.ts could not be loaded: ${first}`]);
|
|
372
|
+
});
|
|
373
|
+
if (def?.kind !== "source") throw new SourceErrors(where2, ["index.ts must `export default defineSource({ \u2026 })`"]);
|
|
374
|
+
const errors = [];
|
|
375
|
+
if (def.id !== id2) errors.push(`the source's id "${def.id}" must match its folder, sources/${id2}`);
|
|
376
|
+
const ops = {};
|
|
377
|
+
for (const [name, op] of Object.entries(def.ops ?? {})) {
|
|
378
|
+
if (!op?.input || typeof op.input !== "object" || !("~standard" in op.input))
|
|
379
|
+
errors.push(`op ${name}: input must be a Standard Schema (zod 4, valibot, arktype\u2026)`);
|
|
380
|
+
if (typeof op?.call !== "function") errors.push(`op ${name}: call must be a function`);
|
|
381
|
+
const ttl = ttlSeconds(op?.ttl);
|
|
382
|
+
if (typeof ttl === "string") errors.push(`op ${name}: ${ttl}`);
|
|
383
|
+
ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0 };
|
|
384
|
+
}
|
|
385
|
+
const out = await build(
|
|
386
|
+
options(
|
|
387
|
+
`import def from ${JSON.stringify(index)};
|
|
388
|
+
import { serveSource } from "@motionskit/sdk/harness";
|
|
389
|
+
export default serveSource(def);
|
|
390
|
+
`,
|
|
391
|
+
root,
|
|
392
|
+
"neutral",
|
|
393
|
+
tenantDir
|
|
394
|
+
)
|
|
395
|
+
);
|
|
396
|
+
const bundle2 = out.outputFiles[0].text;
|
|
397
|
+
const manifest = {
|
|
398
|
+
tenant,
|
|
399
|
+
source: id2,
|
|
400
|
+
title: yaml.data?.title ?? def.title ?? id2,
|
|
401
|
+
hosts: [...def.hosts ?? []],
|
|
402
|
+
secrets: [...def.secrets ?? []],
|
|
403
|
+
ops,
|
|
404
|
+
bundle: sha256(bundle2)
|
|
405
|
+
};
|
|
406
|
+
errors.push(...validateSourceManifest(manifest));
|
|
407
|
+
if (errors.length) throw new SourceErrors(where2, errors);
|
|
408
|
+
const files = {};
|
|
409
|
+
for (const input of Object.keys(out.metafile.inputs).map((p) => resolve(tenantDir, p))) {
|
|
410
|
+
const path = relative(root, input);
|
|
411
|
+
if (existsSync3(input) && !path.startsWith("..") && !isAbsolute(path) && !path.split(sep).includes("node_modules"))
|
|
412
|
+
files[path.split(sep).join("/")] = readFileSync3(input, "utf8");
|
|
413
|
+
}
|
|
414
|
+
if (existsSync3(yamlPath)) files["source.yaml"] = readFileSync3(yamlPath, "utf8");
|
|
415
|
+
return { dir: root, manifest: { ...manifest, sha: versionId(manifest, files) }, bundle: bundle2, files };
|
|
416
|
+
}
|
|
417
|
+
async function compileSources(tenantDir, tenant) {
|
|
418
|
+
const dir = join4(tenantDir, "sources");
|
|
419
|
+
if (!existsSync3(dir)) return [];
|
|
420
|
+
const out = [];
|
|
421
|
+
for (const name of readdirSync2(dir).sort()) if (existsSync3(join4(dir, name, "index.ts"))) out.push(await compileSource(tenant, join4(dir, name), tenantDir));
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
function sourceTypes(sources) {
|
|
425
|
+
const lines = sources.map((s) => ` ${s.manifest.source}: SourceClient<typeof import("../sources/${s.manifest.source}/index.ts").default>;`);
|
|
426
|
+
return `// Generated by \`motions check\` from sources/*/index.ts; do not edit.
|
|
427
|
+
import type { SourceClient } from "@motionskit/sdk";
|
|
428
|
+
|
|
429
|
+
declare module "@motionskit/sdk" {
|
|
430
|
+
interface SourcesCatalog {
|
|
431
|
+
${lines.join("\n")}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
`;
|
|
435
|
+
}
|
|
436
|
+
function writeSourceTypes(tenantDir, sources) {
|
|
437
|
+
const path = join4(tenantDir, ".motions", "sources.d.ts");
|
|
438
|
+
mkdirSync(dirname2(path), { recursive: true });
|
|
439
|
+
writeFileSync(path, sources.length ? sourceTypes(sources) : "export {};\n");
|
|
440
|
+
return path;
|
|
441
|
+
}
|
|
442
|
+
function reportSources(sources) {
|
|
443
|
+
for (const { manifest: m, bundle: bundle2 } of sources) {
|
|
444
|
+
console.log(
|
|
445
|
+
` source ${m.source} @ ${m.sha.slice(0, 10)} ${(bundle2.length / 1024).toFixed(0)} KB, hosts=[${m.hosts.join(", ")}] secrets=[${m.secrets.join(", ")}]`
|
|
446
|
+
);
|
|
447
|
+
for (const [op, { ttlSeconds: ttlSeconds2 }] of Object.entries(m.ops)) console.log(` op ${m.source}.${op}${ttlSeconds2 ? ` ttl=${ttlSeconds2}s` : ""}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async function publishSources(post, tenant, sources, opts) {
|
|
451
|
+
for (const { dir, manifest, bundle: bundle2, files } of sources) {
|
|
452
|
+
const out = await post(`/api/tenants/${tenant}/sources/${manifest.source}/versions`, {
|
|
453
|
+
manifest,
|
|
454
|
+
bundle: bundle2,
|
|
455
|
+
files,
|
|
456
|
+
origin: opts.origin(dir),
|
|
457
|
+
live: opts.live,
|
|
458
|
+
...opts.message ? { message: opts.message } : {}
|
|
459
|
+
});
|
|
460
|
+
console.log(
|
|
461
|
+
`published source ${tenant}/${manifest.source} @ ${manifest.sha.slice(0, 10)} (${out.created ? "new" : "unchanged"}${out.live ? ", live" : ", draft"})`
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/compile.ts
|
|
467
|
+
var sha2562 = (text) => createHash2("sha256").update(text).digest("hex");
|
|
468
|
+
function findTenantDir(start) {
|
|
469
|
+
let dir = resolve2(start);
|
|
470
|
+
for (; ; ) {
|
|
471
|
+
if (existsSync4(join5(dir, "tenant.yaml"))) return dir;
|
|
472
|
+
const parent = dirname3(dir);
|
|
473
|
+
if (parent === dir) return null;
|
|
474
|
+
dir = parent;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
function monorepoTenants() {
|
|
478
|
+
const dir = resolve2(dirname3(fileURLToPath2(import.meta.url)), "../../..", "tenants");
|
|
479
|
+
if (!existsSync4(dir)) return null;
|
|
480
|
+
return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync4(join5(dir, name, "tenant.yaml"))).sort().map((name) => join5(dir, name));
|
|
481
|
+
}
|
|
482
|
+
function tenantIdentity(dir) {
|
|
483
|
+
const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
|
|
484
|
+
const motionsDir = join5(dir, "motions");
|
|
485
|
+
const motions = existsSync4(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync4(join5(motionsDir, name, "motion.yaml"))).sort() : [];
|
|
486
|
+
return { id: meta.id ?? basename(dir), motions };
|
|
487
|
+
}
|
|
488
|
+
var readYaml = (path) => YAML2.parse(readFileSync4(path, "utf8"));
|
|
489
|
+
var grant = (g) => ({ read: g?.read ?? [], propose: g?.propose ?? [] });
|
|
490
|
+
async function bundle(stepFile, tenantDir) {
|
|
491
|
+
const result = await build2({
|
|
492
|
+
...STEP_BUILD,
|
|
493
|
+
absWorkingDir: tenantDir,
|
|
494
|
+
stdin: { contents: stepEntry(stepFile), resolveDir: dirname3(stepFile), sourcefile: STEP_ENTRY_FILE, loader: "ts" },
|
|
495
|
+
plugins: [tenantSdk(tenantDir), nodeBuiltins()]
|
|
496
|
+
});
|
|
497
|
+
const inputs = Object.keys(result.metafile.inputs).map((p) => resolve2(tenantDir, p));
|
|
498
|
+
return { code: result.outputFiles[0].text, inputs: inputs.filter((p) => p !== join5(dirname3(stepFile), STEP_ENTRY_FILE) && existsSync4(p)) };
|
|
499
|
+
}
|
|
500
|
+
var MotionErrors = class extends Error {
|
|
501
|
+
constructor(where2, errors) {
|
|
502
|
+
super(`${where2}:
|
|
503
|
+
${errors.join("\n ")}`);
|
|
504
|
+
this.where = where2;
|
|
505
|
+
this.errors = errors;
|
|
506
|
+
}
|
|
507
|
+
where;
|
|
508
|
+
errors;
|
|
509
|
+
};
|
|
510
|
+
async function compileMotion(tenant, dir) {
|
|
511
|
+
const tenantDir = findTenantDir(dir);
|
|
512
|
+
if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
|
|
513
|
+
const where2 = `${tenant.id}/${dir.split("/").at(-1)}/motion.yaml`;
|
|
514
|
+
const parsed2 = parseMotion(readYaml(join5(dir, "motion.yaml")));
|
|
515
|
+
if (!parsed2.ok) throw new MotionErrors(where2, parsed2.errors);
|
|
516
|
+
const raw = parsed2.motion;
|
|
517
|
+
const rulesPath = join5(dir, "rules.yaml");
|
|
518
|
+
const rules = existsSync4(rulesPath) ? readYaml(rulesPath) ?? {} : {};
|
|
519
|
+
const bundles = {};
|
|
520
|
+
const files = { "motion.yaml": readFileSync4(join5(dir, "motion.yaml"), "utf8") };
|
|
521
|
+
if (existsSync4(rulesPath)) files["rules.yaml"] = readFileSync4(rulesPath, "utf8");
|
|
522
|
+
const root = resolve2(dir);
|
|
523
|
+
const compileRun = async (run2) => {
|
|
524
|
+
const file2 = resolve2(dir, run2);
|
|
525
|
+
if (!existsSync4(file2)) throw new MotionErrors(where2, [`${run2} does not exist`]);
|
|
526
|
+
const { code, inputs } = await bundle(file2, tenantDir);
|
|
527
|
+
for (const input of inputs) {
|
|
528
|
+
const path = relative2(root, input);
|
|
529
|
+
if (!path.startsWith("..") && !isAbsolute2(path) && !path.split(sep2).includes("node_modules"))
|
|
530
|
+
files[path.split(sep2).join("/")] = readFileSync4(input, "utf8");
|
|
531
|
+
}
|
|
532
|
+
const sha = sha2562(code);
|
|
533
|
+
bundles[sha] = code;
|
|
534
|
+
return sha;
|
|
535
|
+
};
|
|
536
|
+
const steps = [];
|
|
537
|
+
for (const [i, s] of raw.steps.entries()) {
|
|
538
|
+
const kind = s.kind ?? "company";
|
|
539
|
+
const after = s.after ?? (i > 0 ? [raw.steps[i - 1].id] : []);
|
|
540
|
+
const base = { id: s.id, title: s.title, after };
|
|
541
|
+
if (kind === "company" || kind === "batch") {
|
|
542
|
+
const runnable = { bundle: await compileRun(s.run), sources: s.sources ?? [], crm: grant(s.crm), cap: s.cap, retries: s.retries ?? 2 };
|
|
543
|
+
steps.push(kind === "company" ? { ...base, kind, ...runnable, when: s.when } : { ...base, kind, ...runnable });
|
|
544
|
+
} else if (kind === "checkpoint") steps.push({ ...base, kind, until: s.until });
|
|
545
|
+
else steps.push({ ...base, kind, approval: s.approval ?? "required" });
|
|
546
|
+
}
|
|
547
|
+
const queues = {};
|
|
548
|
+
const approvers = raw.approvers;
|
|
549
|
+
for (const [id2, q] of Object.entries(raw.queues ?? {})) {
|
|
550
|
+
queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
|
|
551
|
+
}
|
|
552
|
+
const manifest = {
|
|
553
|
+
tenant: tenant.id,
|
|
554
|
+
motion: raw.motion ?? dir.split("/").at(-1),
|
|
555
|
+
title: raw.title ?? raw.motion ?? dir,
|
|
556
|
+
timezone: raw.timezone ?? tenant.timezone,
|
|
557
|
+
calendar: raw.calendar ?? {},
|
|
558
|
+
approvers,
|
|
559
|
+
reasons: raw.reasons ?? [],
|
|
560
|
+
rules,
|
|
561
|
+
rulesVersion: rulesVersion(rules),
|
|
562
|
+
input: compileInput(raw.input),
|
|
563
|
+
steps,
|
|
564
|
+
queues
|
|
565
|
+
};
|
|
566
|
+
const errors = validateManifest(manifest);
|
|
567
|
+
if (errors.length) throw new MotionErrors(where2, errors);
|
|
568
|
+
return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
|
|
569
|
+
}
|
|
570
|
+
function compileInput(input) {
|
|
571
|
+
if (!input) return {};
|
|
572
|
+
const { columns, ...rest } = input;
|
|
573
|
+
if (!columns) return rest;
|
|
574
|
+
return {
|
|
575
|
+
...rest,
|
|
576
|
+
columns: Object.fromEntries(Object.entries(columns).map(([name, c]) => [name, { required: c?.required ?? false, aliases: c?.aliases ?? [] }]))
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
async function compileTenant(tenantDir) {
|
|
580
|
+
const dir = resolve2(tenantDir);
|
|
581
|
+
const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
|
|
582
|
+
const id2 = meta.id ?? dir.split("/").filter(Boolean).at(-1);
|
|
583
|
+
const timezone = meta.timezone ?? "America/Sao_Paulo";
|
|
584
|
+
const connection = readYaml(join5(dir, "crm.yaml"));
|
|
585
|
+
const seedPath = join5(dir, "crm-seed.json");
|
|
586
|
+
const seed = existsSync4(seedPath) ? JSON.parse(readFileSync4(seedPath, "utf8")) : null;
|
|
587
|
+
const fixtures = readTenantFixtures(dir, meta.sources);
|
|
588
|
+
const motionsDir = join5(dir, "motions");
|
|
589
|
+
const motions = [];
|
|
590
|
+
for (const name of readdirSync3(motionsDir).sort()) {
|
|
591
|
+
if (existsSync4(join5(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join5(motionsDir, name)));
|
|
592
|
+
}
|
|
593
|
+
return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources: await compileSources(dir, id2), fixtures, motions };
|
|
594
|
+
}
|
|
595
|
+
function tenantCrmProblems(tenant, systems = CRM_WRITES) {
|
|
596
|
+
const system = tenant.connection?.system;
|
|
597
|
+
const unknown = unknownCrmSystem(system, systems);
|
|
598
|
+
if (unknown) return [`crm.yaml: ${unknown}`];
|
|
599
|
+
return tenant.motions.flatMap(({ manifest }) => crmProblems(system, manifest.steps, systems).map((p) => `${manifest.motion}: ${p}`));
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// src/init.ts
|
|
603
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
|
|
604
|
+
import { basename as basename2, dirname as dirname4, join as join6, resolve as resolve3 } from "path";
|
|
605
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
606
|
+
var TENANT_ID = /^[a-z][a-z0-9_-]{0,62}$/;
|
|
607
|
+
function cliVersion() {
|
|
608
|
+
return JSON.parse(readFileSync5(fileURLToPath3(new URL("../package.json", import.meta.url)), "utf8")).version;
|
|
609
|
+
}
|
|
610
|
+
var file = (dir, path, contents) => {
|
|
611
|
+
const dest = join6(dir, path);
|
|
612
|
+
mkdirSync2(dirname4(dest), { recursive: true });
|
|
613
|
+
writeFileSync2(dest, contents);
|
|
614
|
+
};
|
|
615
|
+
function init(target = ".") {
|
|
616
|
+
const dir = resolve3(target);
|
|
617
|
+
const id2 = basename2(dir);
|
|
618
|
+
if (!TENANT_ID.test(id2)) throw new Error(`${id2} is not a tenant id: lowercase letters, digits, - and _, starting with a letter`);
|
|
619
|
+
if (existsSync5(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
|
|
620
|
+
mkdirSync2(dir, { recursive: true });
|
|
621
|
+
const version = cliVersion();
|
|
622
|
+
file(dir, "tenant.yaml", `id: ${id2}
|
|
623
|
+
title: ${id2}
|
|
624
|
+
timezone: America/Sao_Paulo
|
|
625
|
+
`);
|
|
626
|
+
file(dir, "crm.yaml", "system: memory\nmode: read_write\ncompanies:\n core: { name: name, domain: domain }\n");
|
|
627
|
+
file(
|
|
628
|
+
dir,
|
|
629
|
+
"motions/example/motion.yaml",
|
|
630
|
+
"title: Example\napprovers: [owner]\nreasons: [no_domain]\n\nsteps:\n - id: greet\n title: Record the domain\n run: steps/greet.ts\n"
|
|
631
|
+
);
|
|
632
|
+
file(
|
|
633
|
+
dir,
|
|
634
|
+
"motions/example/steps/greet.ts",
|
|
635
|
+
`import { defineStep, drop } from "@motionskit/sdk";
|
|
636
|
+
|
|
637
|
+
export default defineStep({
|
|
638
|
+
async run(company) {
|
|
639
|
+
if (!company.core.domain) return drop("no_domain");
|
|
640
|
+
return { facts: { domain: company.core.domain } };
|
|
641
|
+
},
|
|
642
|
+
});
|
|
643
|
+
`
|
|
644
|
+
);
|
|
645
|
+
file(
|
|
646
|
+
dir,
|
|
647
|
+
"motions/example/tests/greet.test.ts",
|
|
648
|
+
`import { serve } from "@motionskit/sdk/harness";
|
|
649
|
+
import { expect, test } from "vitest";
|
|
650
|
+
import greet from "../steps/greet.ts";
|
|
651
|
+
|
|
652
|
+
const input = (domain: string | null) => ({
|
|
653
|
+
kind: "company" as const,
|
|
654
|
+
batch: { id: "b", tenant: ${JSON.stringify(id2)}, motion: "example", version: "v", label: "t", openedAt: 0 },
|
|
655
|
+
step: "greet",
|
|
656
|
+
rules: {},
|
|
657
|
+
clock: Date.parse("2026-11-02T12:00:00Z"),
|
|
658
|
+
calendar: {},
|
|
659
|
+
companies: [{ record: { key: "co", core: { name: "Acme", domain, country: null, tax_id: null, crm: { system: "memory", object: "company" as const, id: "1", owner_id: null } }, fields: {} }, facts: {}, answers: {}, attempt: "a" }],
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
const caps = { sources: { call: async () => ({ ok: true as const, data: null }) }, crm: { read: async () => ({ ok: true as const, data: null }), prepare: async () => ({ ok: true as const, data: { before: null } }) } };
|
|
663
|
+
|
|
664
|
+
test("drops a company that has no domain", async () => {
|
|
665
|
+
const out = await new (serve(greet))().run(input(null), caps);
|
|
666
|
+
expect(out.co).toMatchObject({ status: "ok", outcome: { lane: "drop", reason: "no_domain" } });
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
test("records the domain", async () => {
|
|
670
|
+
const out = await new (serve(greet))().run(input("acme.com"), caps);
|
|
671
|
+
expect(out.co).toMatchObject({ status: "ok", facts: { domain: "acme.com" } });
|
|
672
|
+
});
|
|
673
|
+
`
|
|
674
|
+
);
|
|
675
|
+
file(
|
|
676
|
+
dir,
|
|
677
|
+
"package.json",
|
|
678
|
+
`${JSON.stringify(
|
|
679
|
+
{
|
|
680
|
+
name: id2,
|
|
681
|
+
private: true,
|
|
682
|
+
type: "module",
|
|
683
|
+
scripts: { check: "motions check", test: "motions test", typecheck: "tsc -p .", push: "motions push" },
|
|
684
|
+
devDependencies: { "@motionskit/cli": version, "@motionskit/sdk": version, typescript: "^5.9.3", vitest: "^5.1.0" }
|
|
685
|
+
},
|
|
686
|
+
null,
|
|
687
|
+
2
|
|
688
|
+
)}
|
|
689
|
+
`
|
|
690
|
+
);
|
|
691
|
+
file(
|
|
692
|
+
dir,
|
|
693
|
+
"tsconfig.json",
|
|
694
|
+
`${JSON.stringify(
|
|
695
|
+
{
|
|
696
|
+
compilerOptions: {
|
|
697
|
+
target: "ES2022",
|
|
698
|
+
module: "ESNext",
|
|
699
|
+
moduleResolution: "Bundler",
|
|
700
|
+
allowImportingTsExtensions: true,
|
|
701
|
+
strict: true,
|
|
702
|
+
noEmit: true,
|
|
703
|
+
skipLibCheck: true
|
|
704
|
+
},
|
|
705
|
+
include: ["motions", "sources", ".motions/*.d.ts"]
|
|
706
|
+
},
|
|
707
|
+
null,
|
|
708
|
+
2
|
|
709
|
+
)}
|
|
710
|
+
`
|
|
711
|
+
);
|
|
712
|
+
file(dir, ".gitignore", "node_modules\ndist\n");
|
|
713
|
+
file(
|
|
714
|
+
dir,
|
|
715
|
+
"README.md",
|
|
716
|
+
`# ${id2}
|
|
717
|
+
|
|
718
|
+
A Motions tenant. Install, then check and test:
|
|
719
|
+
|
|
720
|
+
\`\`\`
|
|
721
|
+
npm install
|
|
722
|
+
npx motions check
|
|
723
|
+
npm run typecheck
|
|
724
|
+
npx motions test
|
|
725
|
+
\`\`\`
|
|
726
|
+
|
|
727
|
+
\`motions push\` publishes a draft and prints a link. \`motions push --live\` makes it the version new batches open on. Set \`MOTIONS_URL\` (default \`http://localhost:8787\`) and \`MOTIONS_TOKEN\` (an API key, \`mot_\u2026\`).
|
|
728
|
+
|
|
729
|
+
GitHub: pull requests run \`check\`, \`typecheck\` and \`test\`. Pushes to \`main\` run the Motions action, which publishes live. Add the \`MOTIONS_TOKEN\` secret and the \`MOTIONS_URL\` variable to the repo.
|
|
730
|
+
`
|
|
731
|
+
);
|
|
732
|
+
file(
|
|
733
|
+
dir,
|
|
734
|
+
".github/workflows/motions.yml",
|
|
735
|
+
`name: Motions
|
|
736
|
+
|
|
737
|
+
on:
|
|
738
|
+
pull_request:
|
|
739
|
+
push:
|
|
740
|
+
branches: [main]
|
|
741
|
+
|
|
742
|
+
jobs:
|
|
743
|
+
check:
|
|
744
|
+
if: github.event_name == 'pull_request'
|
|
745
|
+
runs-on: ubuntu-latest
|
|
746
|
+
steps:
|
|
747
|
+
- uses: actions/checkout@v4
|
|
748
|
+
- uses: actions/setup-node@v4
|
|
749
|
+
with:
|
|
750
|
+
node-version: 22
|
|
751
|
+
- run: npm install
|
|
752
|
+
- run: npx motions check
|
|
753
|
+
- run: npm run typecheck
|
|
754
|
+
- run: npx motions test
|
|
755
|
+
|
|
756
|
+
push:
|
|
757
|
+
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
|
758
|
+
runs-on: ubuntu-latest
|
|
759
|
+
steps:
|
|
760
|
+
- uses: actions/checkout@v4
|
|
761
|
+
- uses: fernandoabolafio/motions/actions/push@main
|
|
762
|
+
with:
|
|
763
|
+
url: \${{ vars.MOTIONS_URL }}
|
|
764
|
+
token: \${{ secrets.MOTIONS_TOKEN }}
|
|
765
|
+
`
|
|
766
|
+
);
|
|
767
|
+
return dir;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// src/origin.ts
|
|
771
|
+
import { execFileSync } from "child_process";
|
|
772
|
+
function git(dir, ...args2) {
|
|
773
|
+
try {
|
|
774
|
+
return execFileSync("git", ["-C", dir, ...args2], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trimEnd();
|
|
775
|
+
} catch {
|
|
776
|
+
return void 0;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
function origin(dir, env = process.env) {
|
|
780
|
+
if (env.GITHUB_ACTIONS === "true") {
|
|
781
|
+
const repo2 = env.GITHUB_REPOSITORY;
|
|
782
|
+
const commit2 = env.GITHUB_SHA;
|
|
783
|
+
if (!repo2 || !commit2) throw new Error("GITHUB_ACTIONS is set but GITHUB_REPOSITORY or GITHUB_SHA is missing");
|
|
784
|
+
return { kind: "github", repo: repo2, commit: commit2 };
|
|
785
|
+
}
|
|
786
|
+
const commit = git(dir, "rev-parse", "HEAD");
|
|
787
|
+
if (!commit) return { kind: "cli" };
|
|
788
|
+
const repo = git(dir, "remote", "get-url", "origin")?.replace(/^([a-z+]+:\/\/)[^@/]*@/i, "$1");
|
|
789
|
+
return { kind: "cli", ...repo ? { repo } : {}, commit, dirty: !!git(dir, "status", "--porcelain", "--", ".") };
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// src/tree.ts
|
|
793
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
794
|
+
import { join as join7, relative as relative3, resolve as resolve4, sep as sep3 } from "path";
|
|
795
|
+
function fromRoot(root, repoPath) {
|
|
796
|
+
const top = git(root, "rev-parse", "--show-toplevel");
|
|
797
|
+
if (!top) return repoPath;
|
|
798
|
+
const prefix = relative3(resolve4(top), resolve4(root)).split(sep3).join("/");
|
|
799
|
+
if (!prefix || prefix.startsWith("..")) return repoPath;
|
|
800
|
+
return repoPath.startsWith(`${prefix}/`) ? repoPath.slice(prefix.length + 1) : repoPath;
|
|
801
|
+
}
|
|
802
|
+
function blockedOverwrites(root, writes) {
|
|
803
|
+
const changed = writes.filter((w) => {
|
|
804
|
+
const dest = join7(root, w.rel);
|
|
805
|
+
return existsSync6(dest) && readFileSync6(dest, "utf8") !== w.next;
|
|
806
|
+
});
|
|
807
|
+
if (!changed.length) return [];
|
|
808
|
+
const status = git(root, "status", "--porcelain", "--untracked-files=all", "--", ...changed.map((w) => w.rel));
|
|
809
|
+
if (status === void 0) return changed.map((w) => w.rel);
|
|
810
|
+
if (!status) return [];
|
|
811
|
+
const dirty = status.split("\n").filter(Boolean).map((line) => fromRoot(root, line.slice(3).replace(/^.* -> /, "")));
|
|
812
|
+
return changed.map((w) => w.rel).filter((rel) => dirty.some((d) => d === rel));
|
|
813
|
+
}
|
|
814
|
+
function inside(root, rel) {
|
|
815
|
+
const dest = resolve4(root, rel);
|
|
816
|
+
const base = resolve4(root);
|
|
817
|
+
if (dest !== base && !dest.startsWith(base + sep3)) throw new Error(`refusing to write ${rel}`);
|
|
818
|
+
return dest;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// src/main.ts
|
|
822
|
+
var USAGE = `usage: motions <check|push|pull|test|open|init|publish> \u2026
|
|
823
|
+
check [tenant] compile the tenant in this directory, or every tenant in this repo
|
|
824
|
+
push [--live] [-m message] publish a draft (or go live with --live) and print a link
|
|
825
|
+
pull <version> [--motion id] [--force]
|
|
826
|
+
test run motions/*/tests with the tenant's vitest
|
|
827
|
+
open <tenant> <motion> [--list name | --companies id,id] [--label text]
|
|
828
|
+
init [dir] scaffold a tenant repo
|
|
829
|
+
publish [tenant] from this repo, push --live over tenants/*`;
|
|
830
|
+
var parsed = (() => {
|
|
831
|
+
try {
|
|
832
|
+
return parseArgs({
|
|
833
|
+
allowPositionals: true,
|
|
834
|
+
options: {
|
|
835
|
+
url: { type: "string", default: process.env.MOTIONS_URL ?? "http://localhost:8787" },
|
|
836
|
+
tenant: { type: "string" },
|
|
837
|
+
live: { type: "boolean", default: false },
|
|
838
|
+
draft: { type: "boolean", default: false },
|
|
839
|
+
message: { type: "string", short: "m" },
|
|
840
|
+
motion: { type: "string" },
|
|
841
|
+
force: { type: "boolean", default: false },
|
|
842
|
+
list: { type: "string" },
|
|
843
|
+
companies: { type: "string" },
|
|
844
|
+
label: { type: "string" },
|
|
845
|
+
reseed: { type: "boolean", default: false },
|
|
846
|
+
help: { type: "boolean", short: "h", default: false }
|
|
847
|
+
}
|
|
848
|
+
});
|
|
849
|
+
} catch (e) {
|
|
850
|
+
console.error(`${e.message.split(". ")[0]}
|
|
851
|
+
|
|
852
|
+
${USAGE}`);
|
|
853
|
+
process.exit(1);
|
|
854
|
+
}
|
|
855
|
+
})();
|
|
856
|
+
var { positionals, values } = parsed;
|
|
857
|
+
if (values.help) {
|
|
858
|
+
console.log(USAGE);
|
|
859
|
+
process.exit(0);
|
|
860
|
+
}
|
|
861
|
+
var [command, ...args] = positionals;
|
|
862
|
+
var url = values.url.replace(/\/$/, "");
|
|
863
|
+
function resolveTenants(positional, fallbackAll) {
|
|
864
|
+
if (values.tenant) {
|
|
865
|
+
const found = findTenantDir(resolve5(values.tenant));
|
|
866
|
+
if (!found) throw new Error(`no tenant.yaml in ${values.tenant}`);
|
|
867
|
+
return [found];
|
|
868
|
+
}
|
|
869
|
+
if (positional) {
|
|
870
|
+
const direct = findTenantDir(resolve5(positional));
|
|
871
|
+
if (existsSync7(positional) && direct) return [direct];
|
|
872
|
+
const match = monorepoTenants()?.find((dir) => dir.split(sep4).at(-1) === positional);
|
|
873
|
+
if (match) return [match];
|
|
874
|
+
throw new Error(`no tenant ${positional}`);
|
|
875
|
+
}
|
|
876
|
+
const here = findTenantDir(process.cwd());
|
|
877
|
+
if (here) return [here];
|
|
878
|
+
if (fallbackAll) {
|
|
879
|
+
const all = monorepoTenants();
|
|
880
|
+
if (all?.length) return all;
|
|
881
|
+
}
|
|
882
|
+
throw new Error("no tenant.yaml found from the current directory; pass --tenant <dir>");
|
|
883
|
+
}
|
|
884
|
+
function versionLink(tenant, motion, sha) {
|
|
885
|
+
return `${url}/t/${tenant}/motions/${motion}/versions/${sha}`;
|
|
886
|
+
}
|
|
887
|
+
async function pushDirs(dirs, live) {
|
|
888
|
+
for (const dir of dirs) {
|
|
889
|
+
const tenant = await compileTenant(dir);
|
|
890
|
+
const upserted = await api(url, `/api/tenants/${tenant.id}`, upsertBody(tenant, values.reseed));
|
|
891
|
+
if (upserted.seeded) console.log(`seeded ${tenant.id}'s CRM with ${upserted.seeded} records`);
|
|
892
|
+
if (upserted.fixtures !== void 0) console.log(`${tenant.id} is in fixture mode: built-in sources answer from ${upserted.fixtures} fixtures`);
|
|
893
|
+
await publishSources((path, body) => api(url, path, body), tenant.id, tenant.sources, { live, message: values.message, origin });
|
|
894
|
+
for (const { dir: motionDir, manifest, bundles, files } of tenant.motions) {
|
|
895
|
+
const out = await api(url, `/api/tenants/${tenant.id}/motions/${manifest.motion}/versions`, {
|
|
896
|
+
manifest,
|
|
897
|
+
bundles,
|
|
898
|
+
files,
|
|
899
|
+
origin: origin(motionDir),
|
|
900
|
+
live,
|
|
901
|
+
...values.message ? { message: values.message } : {}
|
|
902
|
+
});
|
|
903
|
+
console.log(`${tenant.id}/${manifest.motion} @ ${manifest.sha.slice(0, 10)} (${out.created ? "new" : "unchanged"}, ${out.live ? "live" : "draft"})`);
|
|
904
|
+
console.log(` ${versionLink(tenant.id, manifest.motion, manifest.sha)}`);
|
|
905
|
+
if (out.warning) console.log(`warning: ${out.warning}`);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
async function check(only) {
|
|
910
|
+
let failed = 0;
|
|
911
|
+
for (const dir of resolveTenants(only, true)) {
|
|
912
|
+
const tenant = await compileTenant(dir).catch((e) => {
|
|
913
|
+
failed++;
|
|
914
|
+
console.error(`${dir.split(sep4).at(-1)}: ${e.message}`);
|
|
915
|
+
return null;
|
|
916
|
+
});
|
|
917
|
+
if (!tenant) continue;
|
|
918
|
+
console.log(`${tenant.id} (${tenant.timezone})`);
|
|
919
|
+
for (const { manifest, bundles } of tenant.motions) {
|
|
920
|
+
const kb = Object.values(bundles).reduce((n, code) => n + code.length, 0) / 1024;
|
|
921
|
+
console.log(
|
|
922
|
+
` ${manifest.motion} @ ${manifest.sha.slice(0, 10)} ${manifest.steps.length} steps, ${Object.keys(bundles).length} bundles (${kb.toFixed(0)} KB), ${manifest.rulesVersion}`
|
|
923
|
+
);
|
|
924
|
+
for (const s of manifest.steps) {
|
|
925
|
+
const detail = "bundle" in s ? ` ${s.bundle.slice(0, 8)} sources=[${s.sources.join(", ")}]` : "";
|
|
926
|
+
console.log(` ${s.kind.padEnd(10)} ${s.id}${detail}`);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
const fixtures = fixturesLine(tenant.fixtures);
|
|
930
|
+
if (fixtures) console.log(fixtures);
|
|
931
|
+
reportSources(tenant.sources);
|
|
932
|
+
writeSourceTypes(dir, tenant.sources);
|
|
933
|
+
const refused = tenantCrmProblems(tenant);
|
|
934
|
+
if (refused.length) {
|
|
935
|
+
failed++;
|
|
936
|
+
console.error(`${tenant.id}:
|
|
937
|
+
${refused.join("\n ")}`);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (failed) throw new Error(`${failed} tenant${failed > 1 ? "s" : ""} failed the check`);
|
|
941
|
+
}
|
|
942
|
+
async function push() {
|
|
943
|
+
await pushDirs(resolveTenants(void 0, false), values.live && !values.draft);
|
|
944
|
+
}
|
|
945
|
+
async function publish(only) {
|
|
946
|
+
const all = monorepoTenants();
|
|
947
|
+
if (!all) throw new Error("publish runs over this repo's tenants/*; from a tenant repo use motions push --live");
|
|
948
|
+
const dirs = only ? all.filter((dir) => dir.split(sep4).at(-1) === only) : all;
|
|
949
|
+
if (only && !dirs.length) throw new Error(`no tenant ${only}`);
|
|
950
|
+
await pushDirs(dirs, !values.draft);
|
|
951
|
+
}
|
|
952
|
+
async function resolveSha(tenant, motion, version) {
|
|
953
|
+
if (/^[0-9a-f]{64}$/.test(version)) return version;
|
|
954
|
+
const listed = await api(url, `/api/tenants/${tenant}/motions/${motion}/versions`);
|
|
955
|
+
const matches = listed.versions.filter((v) => v.sha.startsWith(version));
|
|
956
|
+
if (matches.length === 1) return matches[0].sha;
|
|
957
|
+
if (!matches.length) throw new Error(`no version ${version} of ${tenant}/${motion}`);
|
|
958
|
+
throw new Error(`${version} matches ${matches.length} versions of ${tenant}/${motion}; pass a longer prefix`);
|
|
959
|
+
}
|
|
960
|
+
async function pull(version) {
|
|
961
|
+
if (!version) throw new Error("usage: motions pull <version> [--motion <id>] [--force]");
|
|
962
|
+
const dir = resolveTenants(void 0, false)[0];
|
|
963
|
+
if (!dir) throw new Error("no tenant.yaml found from the current directory; pass --tenant <dir>");
|
|
964
|
+
const { id: id2, motions } = tenantIdentity(dir);
|
|
965
|
+
const motion = values.motion ?? (motions.length === 1 ? motions[0] : void 0);
|
|
966
|
+
if (!motion) throw new Error(`this tenant has ${motions.length} motions; pass --motion <id>`);
|
|
967
|
+
const sha = await resolveSha(id2, motion, version);
|
|
968
|
+
const { files } = await api(url, `/api/tenants/${id2}/motions/${motion}/versions/${sha}/files`);
|
|
969
|
+
const motionDir = join8(dir, "motions", motion);
|
|
970
|
+
const writes = Object.entries(files).map(([path, next]) => ({ rel: join8("motions", motion, path), path, next }));
|
|
971
|
+
if (!values.force) {
|
|
972
|
+
const blocked = blockedOverwrites(dir, writes);
|
|
973
|
+
if (blocked.length) throw new Error(`refusing to overwrite uncommitted changes (pass --force):
|
|
974
|
+
${blocked.join("\n ")}`);
|
|
975
|
+
}
|
|
976
|
+
let created = 0;
|
|
977
|
+
let updated = 0;
|
|
978
|
+
let unchanged = 0;
|
|
979
|
+
for (const write of writes.sort((a, b) => a.rel < b.rel ? -1 : 1)) {
|
|
980
|
+
const dest = inside(motionDir, write.path);
|
|
981
|
+
const existed = existsSync7(dest);
|
|
982
|
+
const same = existed && readFileSync7(dest, "utf8") === write.next;
|
|
983
|
+
if (!same) {
|
|
984
|
+
mkdirSync3(dirname5(dest), { recursive: true });
|
|
985
|
+
writeFileSync3(dest, write.next);
|
|
986
|
+
}
|
|
987
|
+
if (!existed) {
|
|
988
|
+
created++;
|
|
989
|
+
console.log(`created ${write.rel}`);
|
|
990
|
+
} else if (!same) {
|
|
991
|
+
updated++;
|
|
992
|
+
console.log(`updated ${write.rel}`);
|
|
993
|
+
} else unchanged++;
|
|
994
|
+
}
|
|
995
|
+
console.log(`pulled ${id2}/${motion} @ ${sha.slice(0, 10)} (${created} created, ${updated} updated, ${unchanged} unchanged)`);
|
|
996
|
+
}
|
|
997
|
+
function vitestConfig(dir) {
|
|
998
|
+
const folder = join8(dir, "node_modules", ".motions");
|
|
999
|
+
mkdirSync3(folder, { recursive: true });
|
|
1000
|
+
const stub = join8(folder, "workers-stub.js");
|
|
1001
|
+
writeFileSync3(stub, "export class WorkerEntrypoint {}\n");
|
|
1002
|
+
const config = join8(folder, "vitest.config.ts");
|
|
1003
|
+
writeFileSync3(
|
|
1004
|
+
config,
|
|
1005
|
+
`import { defineConfig } from "vitest/config";
|
|
1006
|
+
|
|
1007
|
+
export default defineConfig({
|
|
1008
|
+
root: ${JSON.stringify(dir)},
|
|
1009
|
+
resolve: { alias: { "cloudflare:workers": ${JSON.stringify(stub)} } },
|
|
1010
|
+
test: {
|
|
1011
|
+
include: ["motions/*/tests/**/*.test.ts"],
|
|
1012
|
+
passWithNoTests: true,
|
|
1013
|
+
server: { deps: { inline: [/@motionskit\\/sdk/, /@motionskit\\/kernel/] } },
|
|
1014
|
+
},
|
|
1015
|
+
});
|
|
1016
|
+
`
|
|
1017
|
+
);
|
|
1018
|
+
return config;
|
|
1019
|
+
}
|
|
1020
|
+
async function test(only) {
|
|
1021
|
+
let failed = 0;
|
|
1022
|
+
for (const dir of resolveTenants(only, true)) {
|
|
1023
|
+
const bin = join8(dir, "node_modules", ".bin", "vitest");
|
|
1024
|
+
if (!existsSync7(bin)) throw new Error(`${dir} has no vitest. Add it to devDependencies and install.`);
|
|
1025
|
+
const run2 = spawnSync(bin, ["run", "--config", vitestConfig(dir)], { cwd: dir, stdio: "inherit" });
|
|
1026
|
+
if (run2.status !== 0) failed++;
|
|
1027
|
+
}
|
|
1028
|
+
if (failed) throw new Error(`${failed} tenant${failed > 1 ? "s" : ""} failed the tests`);
|
|
1029
|
+
}
|
|
1030
|
+
async function open(tenant, motion) {
|
|
1031
|
+
if (!tenant || !motion) throw new Error("usage: motions open <tenant> <motion> [--list name | --companies id,id] [--label text]");
|
|
1032
|
+
const out = await api(url, `/api/tenants/${tenant}/motions/${motion}/batches`, {
|
|
1033
|
+
list: values.list,
|
|
1034
|
+
companies: values.companies?.split(",").map((s) => s.trim()),
|
|
1035
|
+
label: values.label
|
|
1036
|
+
});
|
|
1037
|
+
console.log(`opened batch ${out.id} with ${out.companies} companies`);
|
|
1038
|
+
console.log(` ${url}/t/${tenant}/batches/${out.id}`);
|
|
1039
|
+
}
|
|
1040
|
+
var commands = {
|
|
1041
|
+
check,
|
|
1042
|
+
push,
|
|
1043
|
+
pull,
|
|
1044
|
+
test,
|
|
1045
|
+
open,
|
|
1046
|
+
init: (dir) => {
|
|
1047
|
+
const created = init(dir);
|
|
1048
|
+
console.log(`created ${created}`);
|
|
1049
|
+
},
|
|
1050
|
+
publish
|
|
1051
|
+
};
|
|
1052
|
+
var run = command ? commands[command] : void 0;
|
|
1053
|
+
if (!run) {
|
|
1054
|
+
console.log(USAGE);
|
|
1055
|
+
process.exit(1);
|
|
1056
|
+
}
|
|
1057
|
+
Promise.resolve(run(...args)).catch((e) => {
|
|
1058
|
+
console.error(e.message);
|
|
1059
|
+
process.exit(1);
|
|
1060
|
+
});
|