@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/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @motionskit/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`motions init`, `check`, `test`, `push`, `pull` and `open`.
|
|
4
|
+
|
|
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
|
+
|
|
7
|
+
Inside the motions repo, `motions publish [tenant]` is `push --live` over `tenants/*`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { FixtureEntry, SourceVersion, MotionVersion, Json } from '@motionskit/kernel';
|
|
2
|
+
|
|
3
|
+
/** `tenant.yaml`'s `sources.fixtures` switch and every entry of `fixtures/sources/*.json`, in the order the gateway matches them. */
|
|
4
|
+
type TenantFixtures = {
|
|
5
|
+
enabled: boolean;
|
|
6
|
+
files: string[];
|
|
7
|
+
entries: FixtureEntry[];
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/** `files` holds the source's own files by path relative to its folder: source.yaml, index.ts and whatever index.ts imports from there. */
|
|
11
|
+
type CompiledSource = {
|
|
12
|
+
dir: string;
|
|
13
|
+
manifest: SourceVersion;
|
|
14
|
+
bundle: string;
|
|
15
|
+
files: Record<string, string>;
|
|
16
|
+
};
|
|
17
|
+
declare function compileSource(tenant: string, dir: string, tenantRoot?: string): Promise<CompiledSource>;
|
|
18
|
+
declare function compileSources(tenantDir: string, tenant: string): Promise<CompiledSource[]>;
|
|
19
|
+
|
|
20
|
+
/** The directory that contains `tenant.yaml`, walking up from `start`, or null. */
|
|
21
|
+
declare function findTenantDir(start: string): string | null;
|
|
22
|
+
/** This repo's `tenants/*`, when the CLI is running from the monorepo. Null for a published install. `src/` and `dist/` are both three levels below the repo, so the same relative path works from source and from the bundle. */
|
|
23
|
+
declare function monorepoTenants(): string[] | null;
|
|
24
|
+
declare function tenantIdentity(dir: string): {
|
|
25
|
+
id: string;
|
|
26
|
+
motions: string[];
|
|
27
|
+
};
|
|
28
|
+
declare const tenantsDir: () => string;
|
|
29
|
+
type Tenant = {
|
|
30
|
+
id: string;
|
|
31
|
+
title: string;
|
|
32
|
+
timezone: string;
|
|
33
|
+
connection: Json;
|
|
34
|
+
seed: Json | null;
|
|
35
|
+
/** Custom sources. The push publishes these before motions. */
|
|
36
|
+
sources: CompiledSource[];
|
|
37
|
+
fixtures: TenantFixtures;
|
|
38
|
+
motions: Compiled[];
|
|
39
|
+
};
|
|
40
|
+
/** `files` holds the motion's sources by path relative to its folder: motion.yaml, rules.yaml and every file a step bundles from there. */
|
|
41
|
+
type Compiled = {
|
|
42
|
+
dir: string;
|
|
43
|
+
manifest: MotionVersion;
|
|
44
|
+
bundles: Record<string, string>;
|
|
45
|
+
files: Record<string, string>;
|
|
46
|
+
};
|
|
47
|
+
declare function compileMotion(tenant: {
|
|
48
|
+
id: string;
|
|
49
|
+
timezone: string;
|
|
50
|
+
}, dir: string): Promise<Compiled>;
|
|
51
|
+
declare function compileTenant(tenantDir: string): Promise<Tenant>;
|
|
52
|
+
|
|
53
|
+
export { type Compiled, type CompiledSource, type Tenant, compileMotion, compileSource, compileSources, compileTenant, findTenantDir, monorepoTenants, tenantIdentity, tenantsDir };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
// src/compile.ts
|
|
2
|
+
import { createHash as createHash2 } from "crypto";
|
|
3
|
+
import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
4
|
+
import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve2, sep as sep2 } from "path";
|
|
5
|
+
import { fileURLToPath } from "url";
|
|
6
|
+
import {
|
|
7
|
+
CRM_WRITES,
|
|
8
|
+
crmProblems,
|
|
9
|
+
rulesVersion,
|
|
10
|
+
STEP_BUILD,
|
|
11
|
+
STEP_ENTRY_FILE,
|
|
12
|
+
stepEntry,
|
|
13
|
+
unknownCrmSystem,
|
|
14
|
+
validateManifest,
|
|
15
|
+
versionId as versionId2
|
|
16
|
+
} from "@motionskit/kernel";
|
|
17
|
+
import { build as build2 } from "esbuild";
|
|
18
|
+
import YAML2 from "yaml";
|
|
19
|
+
|
|
20
|
+
// src/bundle.ts
|
|
21
|
+
import { builtinModules, createRequire } from "module";
|
|
22
|
+
import { join } from "path";
|
|
23
|
+
function resolveFrom(tenantDir, spec) {
|
|
24
|
+
try {
|
|
25
|
+
return createRequire(join(tenantDir, "package.json")).resolve(spec);
|
|
26
|
+
} catch (e) {
|
|
27
|
+
const detail = e instanceof Error ? e.message : String(e);
|
|
28
|
+
throw new Error(`can't resolve ${spec} from ${tenantDir} (${detail})`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function tenantSdk(tenantDir) {
|
|
32
|
+
return {
|
|
33
|
+
name: "tenant-sdk",
|
|
34
|
+
setup(b) {
|
|
35
|
+
b.onResolve({ filter: /^@motionskit\/sdk(\/|$)/ }, (args) => ({ path: resolveFrom(tenantDir, args.path) }));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
var NODE_BUILTINS = new Set(builtinModules);
|
|
40
|
+
function nodeBuiltins() {
|
|
41
|
+
return {
|
|
42
|
+
name: "node-builtins",
|
|
43
|
+
setup(b) {
|
|
44
|
+
b.onResolve({ filter: /.*/ }, (args) => {
|
|
45
|
+
const name = args.path.startsWith("node:") ? args.path.slice(5) : args.path;
|
|
46
|
+
if (!NODE_BUILTINS.has(name) && !NODE_BUILTINS.has(`node:${name}`)) return;
|
|
47
|
+
return { path: `node:${name}`, external: true };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/fixtures.ts
|
|
54
|
+
import { existsSync, readdirSync, readFileSync } from "fs";
|
|
55
|
+
import { join as join2 } from "path";
|
|
56
|
+
import { readFixtureFiles } from "@motionskit/kernel";
|
|
57
|
+
var FIXTURES_DIR = join2("fixtures", "sources");
|
|
58
|
+
function readTenantFixtures(dir, sources) {
|
|
59
|
+
const problems = [];
|
|
60
|
+
let enabled = false;
|
|
61
|
+
if (sources !== void 0 && sources !== null) {
|
|
62
|
+
if (typeof sources !== "object" || Array.isArray(sources)) problems.push("tenant.yaml: sources must be a map such as { fixtures: true }");
|
|
63
|
+
else {
|
|
64
|
+
const { fixtures } = sources;
|
|
65
|
+
if (fixtures !== void 0 && typeof fixtures !== "boolean") problems.push("tenant.yaml: sources.fixtures must be true or false");
|
|
66
|
+
else enabled = fixtures === true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const folder = join2(dir, FIXTURES_DIR);
|
|
70
|
+
const files = existsSync(folder) ? readdirSync(folder).filter((name) => name.endsWith(".json")) : [];
|
|
71
|
+
const read = readFixtureFiles(files.map((name) => [`fixtures/sources/${name}`, readFileSync(join2(folder, name), "utf8")]));
|
|
72
|
+
problems.push(...read.errors);
|
|
73
|
+
if (problems.length) throw new Error(`fixtures:
|
|
74
|
+
${problems.join("\n ")}`);
|
|
75
|
+
return { enabled, files: files.sort(), entries: read.entries };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/manifest.ts
|
|
79
|
+
import { parseDuration } from "@motionskit/kernel";
|
|
80
|
+
import { z } from "zod";
|
|
81
|
+
var ID = /^[a-z][a-z0-9_]*$/;
|
|
82
|
+
var id = z.string().regex(ID, "ids are lowercase snake_case");
|
|
83
|
+
var json = z.lazy(() => z.union([z.null(), z.boolean(), z.number(), z.string(), z.array(json), z.record(z.string(), json)]));
|
|
84
|
+
var CRM_OBJECTS = ["companies", "contacts", "deals", "owners", "notes"];
|
|
85
|
+
var CRM_ACTIONS = [
|
|
86
|
+
"companies.update",
|
|
87
|
+
"contacts.create",
|
|
88
|
+
"contacts.update",
|
|
89
|
+
"associate",
|
|
90
|
+
"notes.create",
|
|
91
|
+
"notes.pin"
|
|
92
|
+
];
|
|
93
|
+
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
94
|
+
var calendarSpec = z.strictObject({ in: z.string().optional(), at: z.string().optional(), weekday: z.enum(WEEKDAYS).optional() }).superRefine((spec, ctx) => {
|
|
95
|
+
const issue = (message) => ctx.addIssue({ code: "custom", message });
|
|
96
|
+
if (spec.in !== void 0) {
|
|
97
|
+
if (spec.at !== void 0 || spec.weekday !== void 0) issue(`use either "in" or "at" (with an optional "weekday"), not both`);
|
|
98
|
+
else if (parseDuration(spec.in) === null) issue(`"in" must be a duration such as "4h" or "2d", got "${spec.in}"`);
|
|
99
|
+
} else if (spec.at === void 0) issue(`needs "in" (a duration), "at" (an instant), or "weekday" and "at"`);
|
|
100
|
+
else if (spec.weekday !== void 0) {
|
|
101
|
+
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}"`);
|
|
102
|
+
} else if (Number.isNaN(Date.parse(spec.at))) issue(`"at" must be an ISO instant, or a time with a "weekday", got "${spec.at}"`);
|
|
103
|
+
}).transform((spec) => spec);
|
|
104
|
+
var crm = z.strictObject({ read: z.array(z.enum(CRM_OBJECTS)).optional(), propose: z.array(z.enum(CRM_ACTIONS)).optional() });
|
|
105
|
+
var cap = z.strictObject({ per_company_usd: z.number().positive().optional(), per_batch_usd: z.number().positive().optional() });
|
|
106
|
+
var RUNNABLE = ["run", "sources", "crm", "cap", "retries"];
|
|
107
|
+
var ONLY = { when: ["company"], until: ["checkpoint"], approval: ["changeset"] };
|
|
108
|
+
var step = z.strictObject({
|
|
109
|
+
id,
|
|
110
|
+
kind: z.enum(["company", "batch", "checkpoint", "changeset"]).optional(),
|
|
111
|
+
title: z.string().optional(),
|
|
112
|
+
after: z.array(z.string()).optional(),
|
|
113
|
+
run: z.string().optional(),
|
|
114
|
+
sources: z.array(z.string()).optional(),
|
|
115
|
+
crm: crm.optional(),
|
|
116
|
+
cap: cap.optional(),
|
|
117
|
+
retries: z.number().int().min(0).max(10).optional(),
|
|
118
|
+
when: z.strictObject({ fact: z.string(), in: z.array(json).min(1) }).optional(),
|
|
119
|
+
until: z.strictObject({ at: z.string().optional(), event: z.string().optional(), manual: z.boolean().optional() }).optional(),
|
|
120
|
+
approval: z.enum(["required", "auto"]).optional()
|
|
121
|
+
}).superRefine((s, ctx) => {
|
|
122
|
+
const kind = s.kind ?? "company";
|
|
123
|
+
const runnable = kind === "company" || kind === "batch";
|
|
124
|
+
if (runnable && !s.run) ctx.addIssue({ code: "custom", path: ["run"], message: `is required for ${kind} steps` });
|
|
125
|
+
for (const key of RUNNABLE)
|
|
126
|
+
if (!runnable && s[key] !== void 0) ctx.addIssue({ code: "custom", path: [key], message: `is not allowed on ${kind} steps` });
|
|
127
|
+
for (const [key, kinds] of Object.entries(ONLY)) {
|
|
128
|
+
if (s[key] !== void 0 && !kinds.includes(kind))
|
|
129
|
+
ctx.addIssue({ code: "custom", path: [key], message: `is only allowed on ${kinds.join(", ")} steps` });
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
var queue = z.strictObject({
|
|
133
|
+
title: z.string().optional(),
|
|
134
|
+
owner: z.string().optional(),
|
|
135
|
+
deadline: z.string().optional(),
|
|
136
|
+
default: z.enum(["hold", "drop", "continue", "recommended"]).optional()
|
|
137
|
+
});
|
|
138
|
+
var RawMotion = z.strictObject({
|
|
139
|
+
motion: id.optional(),
|
|
140
|
+
title: z.string().optional(),
|
|
141
|
+
timezone: z.string().optional(),
|
|
142
|
+
calendar: z.record(id, calendarSpec).optional(),
|
|
143
|
+
approvers: z.array(z.string()).min(1, "a motion needs at least one approver"),
|
|
144
|
+
reasons: z.array(id).optional(),
|
|
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(),
|
|
149
|
+
steps: z.array(step).min(1, "a motion needs at least one step"),
|
|
150
|
+
queues: z.record(id, queue).optional()
|
|
151
|
+
});
|
|
152
|
+
function where(raw, path) {
|
|
153
|
+
let out = "";
|
|
154
|
+
let node = raw;
|
|
155
|
+
for (const key of path) {
|
|
156
|
+
node = node?.[key];
|
|
157
|
+
if (typeof key === "number") {
|
|
158
|
+
const label = node && typeof node.id === "string" ? ` (${node.id})` : "";
|
|
159
|
+
out += `[${key}]${label}`;
|
|
160
|
+
} else out += out ? `.${String(key)}` : String(key);
|
|
161
|
+
}
|
|
162
|
+
return out || "motion";
|
|
163
|
+
}
|
|
164
|
+
function references(raw) {
|
|
165
|
+
const out = [];
|
|
166
|
+
const issue = (path, message) => out.push({ path, message });
|
|
167
|
+
const calendar = raw.calendar && typeof raw.calendar === "object" ? raw.calendar : {};
|
|
168
|
+
const keys = Object.keys(calendar);
|
|
169
|
+
const ref = (path, value) => {
|
|
170
|
+
if (typeof value !== "string" || value in calendar || parseDuration(value) !== null) return;
|
|
171
|
+
issue(
|
|
172
|
+
path,
|
|
173
|
+
`"${value}" is neither a calendar key nor a duration${keys.length ? `; calendar keys are ${keys.join(", ")}` : "; the motion has no calendar"}`
|
|
174
|
+
);
|
|
175
|
+
};
|
|
176
|
+
if (typeof raw.timezone === "string") {
|
|
177
|
+
try {
|
|
178
|
+
new Intl.DateTimeFormat("en-US", { timeZone: raw.timezone });
|
|
179
|
+
} catch {
|
|
180
|
+
issue(["timezone"], `"${raw.timezone}" is not an IANA time zone`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const steps = Array.isArray(raw.steps) ? raw.steps : [];
|
|
184
|
+
const ids = steps.map((s) => typeof s?.id === "string" ? s.id : "");
|
|
185
|
+
const upstream = /* @__PURE__ */ new Map();
|
|
186
|
+
steps.forEach((s, i) => {
|
|
187
|
+
if (!s || typeof s !== "object") return;
|
|
188
|
+
const id2 = ids[i];
|
|
189
|
+
const after = Array.isArray(s.after) ? s.after : i > 0 ? [ids[i - 1]] : [];
|
|
190
|
+
const ups = /* @__PURE__ */ new Set();
|
|
191
|
+
if (id2 && upstream.has(id2)) issue(["steps", i, "id"], `duplicate step id "${id2}"`);
|
|
192
|
+
after.forEach((dep, j) => {
|
|
193
|
+
const known = typeof dep === "string" ? upstream.get(dep) : void 0;
|
|
194
|
+
if (!known) issue(["steps", i, "after", j], ids.includes(String(dep)) ? `"${dep}" must be an earlier step` : `no step "${dep}"`);
|
|
195
|
+
else for (const d of [dep, ...known]) ups.add(d);
|
|
196
|
+
});
|
|
197
|
+
if (id2) upstream.set(id2, ups);
|
|
198
|
+
ref(["steps", i, "until", "at"], s.until?.at);
|
|
199
|
+
const fact = s.when?.fact;
|
|
200
|
+
const head = typeof fact === "string" ? fact.split(".")[0] : void 0;
|
|
201
|
+
if (head && head !== "core" && head !== "fields" && !ups.has(head))
|
|
202
|
+
issue(["steps", i, "when", "fact"], `"${fact}" must start with core, fields, or an upstream step id`);
|
|
203
|
+
});
|
|
204
|
+
const queues = raw.queues && typeof raw.queues === "object" ? raw.queues : {};
|
|
205
|
+
for (const [qid, q] of Object.entries(queues)) ref(["queues", qid, "deadline"], q?.deadline);
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
function parseMotion(raw) {
|
|
209
|
+
const doc = raw ?? {};
|
|
210
|
+
const result = RawMotion.safeParse(doc);
|
|
211
|
+
const issues = [...result.success ? [] : result.error.issues, ...doc && typeof doc === "object" ? references(doc) : []];
|
|
212
|
+
if (result.success && !issues.length) return { ok: true, motion: result.data };
|
|
213
|
+
return { ok: false, errors: issues.map((i) => `${where(raw, i.path)}: ${i.message}`) };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/sources.ts
|
|
217
|
+
import { createHash } from "crypto";
|
|
218
|
+
import { existsSync as existsSync2, mkdirSync, readdirSync as readdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
219
|
+
import { dirname, isAbsolute, join as join3, relative, resolve, sep } from "path";
|
|
220
|
+
import { parseDuration as parseDuration2, validateSourceManifest, versionId } from "@motionskit/kernel";
|
|
221
|
+
import { build } from "esbuild";
|
|
222
|
+
import YAML from "yaml";
|
|
223
|
+
import { z as z2 } from "zod";
|
|
224
|
+
var sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
225
|
+
var SourceErrors = class extends Error {
|
|
226
|
+
constructor(where2, errors) {
|
|
227
|
+
super(`${where2}:
|
|
228
|
+
${errors.join("\n ")}`);
|
|
229
|
+
this.where = where2;
|
|
230
|
+
this.errors = errors;
|
|
231
|
+
}
|
|
232
|
+
where;
|
|
233
|
+
errors;
|
|
234
|
+
};
|
|
235
|
+
var SourceYaml = z2.strictObject({ title: z2.string().optional() }).nullable();
|
|
236
|
+
var options = (entry, resolveDir, platform, tenantDir) => ({
|
|
237
|
+
absWorkingDir: tenantDir,
|
|
238
|
+
metafile: true,
|
|
239
|
+
stdin: { contents: entry, resolveDir, sourcefile: "entry.ts", loader: "ts" },
|
|
240
|
+
bundle: true,
|
|
241
|
+
write: false,
|
|
242
|
+
format: "esm",
|
|
243
|
+
platform,
|
|
244
|
+
target: "es2022",
|
|
245
|
+
mainFields: ["module", "main"],
|
|
246
|
+
conditions: ["workerd", "worker", "import", "default"],
|
|
247
|
+
external: ["cloudflare:workers"],
|
|
248
|
+
plugins: [tenantSdk(tenantDir), nodeBuiltins()],
|
|
249
|
+
nodePaths: [join3(tenantDir, "node_modules")],
|
|
250
|
+
legalComments: "none",
|
|
251
|
+
logLevel: "silent"
|
|
252
|
+
});
|
|
253
|
+
async function definition(index, tenantDir) {
|
|
254
|
+
const out = await build(options(`export { default } from ${JSON.stringify(index)};
|
|
255
|
+
`, dirname(index), "node", tenantDir));
|
|
256
|
+
const code = out.outputFiles[0].text;
|
|
257
|
+
const mod = await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
|
|
258
|
+
return mod.default;
|
|
259
|
+
}
|
|
260
|
+
function ttlSeconds(ttl) {
|
|
261
|
+
if (ttl === void 0) return 0;
|
|
262
|
+
if (typeof ttl === "number") return Number.isInteger(ttl) && ttl >= 0 ? ttl : `ttl must be a whole number of seconds, got ${ttl}`;
|
|
263
|
+
const ms = typeof ttl === "string" ? parseDuration2(ttl) : null;
|
|
264
|
+
return ms === null ? `ttl must be a duration such as "7d" or "12h", or seconds, got ${JSON.stringify(ttl)}` : Math.round(ms / 1e3);
|
|
265
|
+
}
|
|
266
|
+
async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
|
|
267
|
+
const tenantDir = resolve(tenantRoot);
|
|
268
|
+
const id2 = dir.split(sep).at(-1);
|
|
269
|
+
const where2 = `${tenant}/sources/${id2}`;
|
|
270
|
+
const root = resolve(dir);
|
|
271
|
+
const index = join3(root, "index.ts");
|
|
272
|
+
if (!existsSync2(index)) throw new SourceErrors(where2, ["index.ts does not exist"]);
|
|
273
|
+
const yamlPath = join3(root, "source.yaml");
|
|
274
|
+
const yaml = SourceYaml.safeParse(existsSync2(yamlPath) ? YAML.parse(readFileSync2(yamlPath, "utf8")) : null);
|
|
275
|
+
if (!yaml.success)
|
|
276
|
+
throw new SourceErrors(
|
|
277
|
+
`${where2}/source.yaml`,
|
|
278
|
+
yaml.error.issues.map(
|
|
279
|
+
(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}`
|
|
280
|
+
)
|
|
281
|
+
);
|
|
282
|
+
const def = await definition(index, tenantDir).catch((e) => {
|
|
283
|
+
const first = e.errors?.[0]?.text ?? e.message.split("\n")[0];
|
|
284
|
+
throw new SourceErrors(where2, [`index.ts could not be loaded: ${first}`]);
|
|
285
|
+
});
|
|
286
|
+
if (def?.kind !== "source") throw new SourceErrors(where2, ["index.ts must `export default defineSource({ \u2026 })`"]);
|
|
287
|
+
const errors = [];
|
|
288
|
+
if (def.id !== id2) errors.push(`the source's id "${def.id}" must match its folder, sources/${id2}`);
|
|
289
|
+
const ops = {};
|
|
290
|
+
for (const [name, op] of Object.entries(def.ops ?? {})) {
|
|
291
|
+
if (!op?.input || typeof op.input !== "object" || !("~standard" in op.input))
|
|
292
|
+
errors.push(`op ${name}: input must be a Standard Schema (zod 4, valibot, arktype\u2026)`);
|
|
293
|
+
if (typeof op?.call !== "function") errors.push(`op ${name}: call must be a function`);
|
|
294
|
+
const ttl = ttlSeconds(op?.ttl);
|
|
295
|
+
if (typeof ttl === "string") errors.push(`op ${name}: ${ttl}`);
|
|
296
|
+
ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0 };
|
|
297
|
+
}
|
|
298
|
+
const out = await build(
|
|
299
|
+
options(
|
|
300
|
+
`import def from ${JSON.stringify(index)};
|
|
301
|
+
import { serveSource } from "@motionskit/sdk/harness";
|
|
302
|
+
export default serveSource(def);
|
|
303
|
+
`,
|
|
304
|
+
root,
|
|
305
|
+
"neutral",
|
|
306
|
+
tenantDir
|
|
307
|
+
)
|
|
308
|
+
);
|
|
309
|
+
const bundle2 = out.outputFiles[0].text;
|
|
310
|
+
const manifest = {
|
|
311
|
+
tenant,
|
|
312
|
+
source: id2,
|
|
313
|
+
title: yaml.data?.title ?? def.title ?? id2,
|
|
314
|
+
hosts: [...def.hosts ?? []],
|
|
315
|
+
secrets: [...def.secrets ?? []],
|
|
316
|
+
ops,
|
|
317
|
+
bundle: sha256(bundle2)
|
|
318
|
+
};
|
|
319
|
+
errors.push(...validateSourceManifest(manifest));
|
|
320
|
+
if (errors.length) throw new SourceErrors(where2, errors);
|
|
321
|
+
const files = {};
|
|
322
|
+
for (const input of Object.keys(out.metafile.inputs).map((p) => resolve(tenantDir, p))) {
|
|
323
|
+
const path = relative(root, input);
|
|
324
|
+
if (existsSync2(input) && !path.startsWith("..") && !isAbsolute(path) && !path.split(sep).includes("node_modules"))
|
|
325
|
+
files[path.split(sep).join("/")] = readFileSync2(input, "utf8");
|
|
326
|
+
}
|
|
327
|
+
if (existsSync2(yamlPath)) files["source.yaml"] = readFileSync2(yamlPath, "utf8");
|
|
328
|
+
return { dir: root, manifest: { ...manifest, sha: versionId(manifest, files) }, bundle: bundle2, files };
|
|
329
|
+
}
|
|
330
|
+
async function compileSources(tenantDir, tenant) {
|
|
331
|
+
const dir = join3(tenantDir, "sources");
|
|
332
|
+
if (!existsSync2(dir)) return [];
|
|
333
|
+
const out = [];
|
|
334
|
+
for (const name of readdirSync2(dir).sort()) if (existsSync2(join3(dir, name, "index.ts"))) out.push(await compileSource(tenant, join3(dir, name), tenantDir));
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// src/compile.ts
|
|
339
|
+
var sha2562 = (text) => createHash2("sha256").update(text).digest("hex");
|
|
340
|
+
function findTenantDir(start) {
|
|
341
|
+
let dir = resolve2(start);
|
|
342
|
+
for (; ; ) {
|
|
343
|
+
if (existsSync3(join4(dir, "tenant.yaml"))) return dir;
|
|
344
|
+
const parent = dirname2(dir);
|
|
345
|
+
if (parent === dir) return null;
|
|
346
|
+
dir = parent;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function monorepoTenants() {
|
|
350
|
+
const dir = resolve2(dirname2(fileURLToPath(import.meta.url)), "../../..", "tenants");
|
|
351
|
+
if (!existsSync3(dir)) return null;
|
|
352
|
+
return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync3(join4(dir, name, "tenant.yaml"))).sort().map((name) => join4(dir, name));
|
|
353
|
+
}
|
|
354
|
+
function tenantIdentity(dir) {
|
|
355
|
+
const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
|
|
356
|
+
const motionsDir = join4(dir, "motions");
|
|
357
|
+
const motions = existsSync3(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync3(join4(motionsDir, name, "motion.yaml"))).sort() : [];
|
|
358
|
+
return { id: meta.id ?? basename(dir), motions };
|
|
359
|
+
}
|
|
360
|
+
var tenantsDir = () => {
|
|
361
|
+
const dir = resolve2(dirname2(fileURLToPath(import.meta.url)), "../../..", "tenants");
|
|
362
|
+
if (!existsSync3(dir)) throw new Error("no tenants directory; run this from a tenant, or from the motions repo");
|
|
363
|
+
return dir;
|
|
364
|
+
};
|
|
365
|
+
var readYaml = (path) => YAML2.parse(readFileSync3(path, "utf8"));
|
|
366
|
+
var grant = (g) => ({ read: g?.read ?? [], propose: g?.propose ?? [] });
|
|
367
|
+
async function bundle(stepFile, tenantDir) {
|
|
368
|
+
const result = await build2({
|
|
369
|
+
...STEP_BUILD,
|
|
370
|
+
absWorkingDir: tenantDir,
|
|
371
|
+
stdin: { contents: stepEntry(stepFile), resolveDir: dirname2(stepFile), sourcefile: STEP_ENTRY_FILE, loader: "ts" },
|
|
372
|
+
plugins: [tenantSdk(tenantDir), nodeBuiltins()]
|
|
373
|
+
});
|
|
374
|
+
const inputs = Object.keys(result.metafile.inputs).map((p) => resolve2(tenantDir, p));
|
|
375
|
+
return { code: result.outputFiles[0].text, inputs: inputs.filter((p) => p !== join4(dirname2(stepFile), STEP_ENTRY_FILE) && existsSync3(p)) };
|
|
376
|
+
}
|
|
377
|
+
var MotionErrors = class extends Error {
|
|
378
|
+
constructor(where2, errors) {
|
|
379
|
+
super(`${where2}:
|
|
380
|
+
${errors.join("\n ")}`);
|
|
381
|
+
this.where = where2;
|
|
382
|
+
this.errors = errors;
|
|
383
|
+
}
|
|
384
|
+
where;
|
|
385
|
+
errors;
|
|
386
|
+
};
|
|
387
|
+
async function compileMotion(tenant, dir) {
|
|
388
|
+
const tenantDir = findTenantDir(dir);
|
|
389
|
+
if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
|
|
390
|
+
const where2 = `${tenant.id}/${dir.split("/").at(-1)}/motion.yaml`;
|
|
391
|
+
const parsed = parseMotion(readYaml(join4(dir, "motion.yaml")));
|
|
392
|
+
if (!parsed.ok) throw new MotionErrors(where2, parsed.errors);
|
|
393
|
+
const raw = parsed.motion;
|
|
394
|
+
const rulesPath = join4(dir, "rules.yaml");
|
|
395
|
+
const rules = existsSync3(rulesPath) ? readYaml(rulesPath) ?? {} : {};
|
|
396
|
+
const bundles = {};
|
|
397
|
+
const files = { "motion.yaml": readFileSync3(join4(dir, "motion.yaml"), "utf8") };
|
|
398
|
+
if (existsSync3(rulesPath)) files["rules.yaml"] = readFileSync3(rulesPath, "utf8");
|
|
399
|
+
const root = resolve2(dir);
|
|
400
|
+
const compileRun = async (run) => {
|
|
401
|
+
const file = resolve2(dir, run);
|
|
402
|
+
if (!existsSync3(file)) throw new MotionErrors(where2, [`${run} does not exist`]);
|
|
403
|
+
const { code, inputs } = await bundle(file, tenantDir);
|
|
404
|
+
for (const input of inputs) {
|
|
405
|
+
const path = relative2(root, input);
|
|
406
|
+
if (!path.startsWith("..") && !isAbsolute2(path) && !path.split(sep2).includes("node_modules"))
|
|
407
|
+
files[path.split(sep2).join("/")] = readFileSync3(input, "utf8");
|
|
408
|
+
}
|
|
409
|
+
const sha = sha2562(code);
|
|
410
|
+
bundles[sha] = code;
|
|
411
|
+
return sha;
|
|
412
|
+
};
|
|
413
|
+
const steps = [];
|
|
414
|
+
for (const [i, s] of raw.steps.entries()) {
|
|
415
|
+
const kind = s.kind ?? "company";
|
|
416
|
+
const after = s.after ?? (i > 0 ? [raw.steps[i - 1].id] : []);
|
|
417
|
+
const base = { id: s.id, title: s.title, after };
|
|
418
|
+
if (kind === "company" || kind === "batch") {
|
|
419
|
+
const runnable = { bundle: await compileRun(s.run), sources: s.sources ?? [], crm: grant(s.crm), cap: s.cap, retries: s.retries ?? 2 };
|
|
420
|
+
steps.push(kind === "company" ? { ...base, kind, ...runnable, when: s.when } : { ...base, kind, ...runnable });
|
|
421
|
+
} else if (kind === "checkpoint") steps.push({ ...base, kind, until: s.until });
|
|
422
|
+
else steps.push({ ...base, kind, approval: s.approval ?? "required" });
|
|
423
|
+
}
|
|
424
|
+
const queues = {};
|
|
425
|
+
const approvers = raw.approvers;
|
|
426
|
+
for (const [id2, q] of Object.entries(raw.queues ?? {})) {
|
|
427
|
+
queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
|
|
428
|
+
}
|
|
429
|
+
const manifest = {
|
|
430
|
+
tenant: tenant.id,
|
|
431
|
+
motion: raw.motion ?? dir.split("/").at(-1),
|
|
432
|
+
title: raw.title ?? raw.motion ?? dir,
|
|
433
|
+
timezone: raw.timezone ?? tenant.timezone,
|
|
434
|
+
calendar: raw.calendar ?? {},
|
|
435
|
+
approvers,
|
|
436
|
+
reasons: raw.reasons ?? [],
|
|
437
|
+
rules,
|
|
438
|
+
rulesVersion: rulesVersion(rules),
|
|
439
|
+
input: compileInput(raw.input),
|
|
440
|
+
steps,
|
|
441
|
+
queues
|
|
442
|
+
};
|
|
443
|
+
const errors = validateManifest(manifest);
|
|
444
|
+
if (errors.length) throw new MotionErrors(where2, errors);
|
|
445
|
+
return { dir: root, manifest: { ...manifest, sha: versionId2(manifest, files) }, bundles, files };
|
|
446
|
+
}
|
|
447
|
+
function compileInput(input) {
|
|
448
|
+
if (!input) return {};
|
|
449
|
+
const { columns, ...rest } = input;
|
|
450
|
+
if (!columns) return rest;
|
|
451
|
+
return {
|
|
452
|
+
...rest,
|
|
453
|
+
columns: Object.fromEntries(Object.entries(columns).map(([name, c]) => [name, { required: c?.required ?? false, aliases: c?.aliases ?? [] }]))
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
async function compileTenant(tenantDir) {
|
|
457
|
+
const dir = resolve2(tenantDir);
|
|
458
|
+
const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
|
|
459
|
+
const id2 = meta.id ?? dir.split("/").filter(Boolean).at(-1);
|
|
460
|
+
const timezone = meta.timezone ?? "America/Sao_Paulo";
|
|
461
|
+
const connection = readYaml(join4(dir, "crm.yaml"));
|
|
462
|
+
const seedPath = join4(dir, "crm-seed.json");
|
|
463
|
+
const seed = existsSync3(seedPath) ? JSON.parse(readFileSync3(seedPath, "utf8")) : null;
|
|
464
|
+
const fixtures = readTenantFixtures(dir, meta.sources);
|
|
465
|
+
const motionsDir = join4(dir, "motions");
|
|
466
|
+
const motions = [];
|
|
467
|
+
for (const name of readdirSync3(motionsDir).sort()) {
|
|
468
|
+
if (existsSync3(join4(motionsDir, name, "motion.yaml"))) motions.push(await compileMotion({ id: id2, timezone }, join4(motionsDir, name)));
|
|
469
|
+
}
|
|
470
|
+
return { id: id2, title: meta.title ?? id2, timezone, connection, seed, sources: await compileSources(dir, id2), fixtures, motions };
|
|
471
|
+
}
|
|
472
|
+
export {
|
|
473
|
+
compileMotion,
|
|
474
|
+
compileSource,
|
|
475
|
+
compileSources,
|
|
476
|
+
compileTenant,
|
|
477
|
+
findTenantDir,
|
|
478
|
+
monorepoTenants,
|
|
479
|
+
tenantIdentity,
|
|
480
|
+
tenantsDir
|
|
481
|
+
};
|