@crasi/bisque-spec 0.0.0-stage → 0.3.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/dist/index.js ADDED
@@ -0,0 +1,1404 @@
1
+ // src/schema.ts
2
+ import { z } from "zod";
3
+ import { IRSchema, Literal } from "@crasi/bisque-ir";
4
+ var Title = z.record(z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/), z.string().min(1).max(80));
5
+ var Label = z.record(z.string().regex(/^[a-z]{2}(-[A-Z]{2})?$/), z.string().min(1).max(40));
6
+ var FORMATS = ["number", "money", "percent", "date", "month", "text"];
7
+ var Format = z.enum(FORMATS);
8
+ var ArgExprSchema = z.lazy(
9
+ () => z.union([
10
+ z.object({ field: z.string() }).strict(),
11
+ z.object({ input: z.string() }).strict(),
12
+ z.object({ param: z.string() }).strict(),
13
+ z.object({ literal: z.union([Literal, z.array(Literal).max(50)]) }).strict(),
14
+ z.object({ today: z.number().int().min(-3660).max(3660) }).strict(),
15
+ /** `"Clearance {products.name}"`: row columns interpolated as text. */
16
+ z.object({ template: z.string().max(120) }).strict(),
17
+ z.object({ list: z.array(ArgExprSchema).max(50) }).strict()
18
+ ])
19
+ );
20
+ var Args = z.record(z.string(), ArgExprSchema);
21
+ var ParamSchema = z.union([
22
+ /** Follow the page: `host.context.month`. */
23
+ z.object({ bind: z.string().regex(/^host\.context\.[A-Za-z_]\w*$/) }).strict(),
24
+ z.object({ control: z.literal("slider"), label: Label, min: z.number(), max: z.number(), step: z.number().positive().optional(), default: z.number() }).strict(),
25
+ z.object({
26
+ control: z.literal("select"),
27
+ label: Label,
28
+ options: z.array(z.object({ value: Literal, label: Label }).strict()).min(1).max(30),
29
+ default: Literal
30
+ }).strict(),
31
+ z.object({ control: z.literal("toggle"), label: Label, default: z.boolean() }).strict()
32
+ ]);
33
+ var Column = z.object({ field: z.string(), label: Label.optional(), format: Format.optional() }).strict();
34
+ var OnClick = z.object({ navigate: z.string(), args: Args }).strict();
35
+ var common = {
36
+ title: Title,
37
+ data: IRSchema,
38
+ params: z.record(z.string().regex(/^[A-Za-z_]\w*$/), ParamSchema).optional(),
39
+ onClick: OnClick.optional()
40
+ };
41
+ var SankeySpec = z.object({
42
+ component: z.literal("sankey"),
43
+ ...common,
44
+ encode: z.object({ source: z.string(), target: z.string(), value: z.string(), label: z.enum(["value", "share-of-source", "share-of-total"]).optional() }).strict(),
45
+ otherBucket: z.object({ maxTargets: z.number().int().min(2).max(50) }).strict().optional()
46
+ }).strict();
47
+ var XY = z.object({
48
+ x: z.string(),
49
+ y: z.union([z.string(), z.array(z.string()).min(1).max(4)]),
50
+ series: z.string().optional(),
51
+ stacked: z.boolean().optional(),
52
+ horizontal: z.boolean().optional(),
53
+ format: Format.optional()
54
+ }).strict();
55
+ var BarSpec = z.object({
56
+ component: z.literal("bar"),
57
+ ...common,
58
+ encode: XY,
59
+ otherBucket: z.object({ maxCategories: z.number().int().min(2).max(50) }).strict().optional()
60
+ }).strict();
61
+ var LineSpec = z.object({ component: z.literal("line"), ...common, encode: XY }).strict();
62
+ var AreaSpec = z.object({ component: z.literal("area"), ...common, encode: XY }).strict();
63
+ var TableSpec = z.object({ component: z.literal("table"), ...common, encode: z.object({ columns: z.array(Column).min(1).max(12) }).strict() }).strict();
64
+ var KpiSpec = z.object({
65
+ component: z.literal("kpi"),
66
+ ...common,
67
+ encode: z.object({ value: z.string(), format: Format.optional(), label: Label.optional() }).strict()
68
+ }).strict();
69
+ var EditableColumn = Column.extend({
70
+ /** Editing this cell invokes the intent; `value` names the arg that receives the new value. */
71
+ edit: z.object({ intent: z.string(), value: z.string(), args: Args }).strict().optional()
72
+ }).strict();
73
+ var GridSpec = z.object({
74
+ component: z.literal("grid"),
75
+ ...common,
76
+ encode: z.object({ rowKey: z.string(), columns: z.array(EditableColumn).min(1).max(12) }).strict()
77
+ }).strict();
78
+ var RowInput = z.object({
79
+ name: z.string().regex(/^[A-Za-z_]\w*$/),
80
+ label: Label,
81
+ type: z.enum(["number", "text"]),
82
+ default: z.union([z.number(), z.string()]).optional(),
83
+ min: z.number().optional(),
84
+ max: z.number().optional()
85
+ }).strict();
86
+ var ActionTableSpec = z.object({
87
+ component: z.literal("actionTable"),
88
+ ...common,
89
+ encode: z.object({
90
+ rowKey: z.string(),
91
+ columns: z.array(Column).min(1).max(10),
92
+ inputs: z.array(RowInput).max(4).optional(),
93
+ /** One intent call per selected row; one host confirm covers the batch (I12). */
94
+ action: z.object({ intent: z.string(), label: Label, args: Args }).strict()
95
+ }).strict()
96
+ }).strict();
97
+ var SpecBody = z.discriminatedUnion("component", [SankeySpec, BarSpec, LineSpec, AreaSpec, TableSpec, KpiSpec, GridSpec, ActionTableSpec]);
98
+ var Placement = z.object({
99
+ slot: z.string(),
100
+ /** Required when the slot holds pages (a nav entry): the entry's label. */
101
+ label: Label.optional()
102
+ }).strict();
103
+ var ArtifactManifestSchema = z.object({
104
+ reads: z.array(z.string()).max(12),
105
+ acts: z.array(z.string()).max(12),
106
+ /** Contribution points are an L3 feature (after v1); specs contribute nothing beyond their placement. */
107
+ contributes: z.object({}).strict().optional()
108
+ }).strict();
109
+ var DraftSchema = z.object({
110
+ kind: z.literal("spec"),
111
+ body: SpecBody,
112
+ manifest: ArtifactManifestSchema,
113
+ placement: Placement
114
+ }).strict();
115
+
116
+ // src/validate.ts
117
+ import { nest, problem } from "@crasi/bisque-core";
118
+ import { canAct } from "@crasi/bisque-contract";
119
+ import { validateIR, zodProblems } from "@crasi/bisque-ir";
120
+ var DEFERRED_KEYS = ["schedule", "channel", "cron", "notify"];
121
+ var UNSAFE = [/<\s*\/?\s*[a-z!]/i, /[a-z][a-z0-9+.-]*:\/\//i, /javascript:/i, /data:[a-z]+\//i, /url\s*\(/i, /expression\s*\(/i, /@import/i, /\bstyle\s*=/i, /\bon[a-z]+\s*=/i];
122
+ var at = (path, k) => path ? `${path}.${k}` : String(k);
123
+ function scanStrings(v, path, out, deferred = true) {
124
+ if (typeof v === "string") {
125
+ if (UNSAFE.some((re) => re.test(v))) out.push(problem(path, "unsafe_text", "text may not contain HTML, CSS or URLs"));
126
+ return;
127
+ }
128
+ if (Array.isArray(v)) return v.forEach((x, i) => scanStrings(x, at(path, i), out, deferred));
129
+ if (v && typeof v === "object")
130
+ for (const [k, x] of Object.entries(v)) {
131
+ if (deferred && DEFERRED_KEYS.includes(k))
132
+ out.push(problem(at(path, k), "deferred", "a view runs only while it is open; schedules and delivery are automations (propose_automation), not part of a view"));
133
+ scanStrings(x, at(path, k), out, deferred);
134
+ }
135
+ }
136
+ function unsafeTextProblems(input) {
137
+ const out = [];
138
+ scanStrings(input, "", out, false);
139
+ return out;
140
+ }
141
+ function paramTypes(spec, m) {
142
+ const out = {};
143
+ for (const [name, p] of Object.entries(spec.params ?? {})) {
144
+ if ("bind" in p) out[name] = m.context[p.bind.slice("host.context.".length)]?.type.type ?? "any";
145
+ else out[name] = p.control === "slider" ? "number" : p.control === "toggle" ? "boolean" : "any";
146
+ }
147
+ return out;
148
+ }
149
+ function encodeColumns(spec) {
150
+ const e = spec.encode;
151
+ switch (spec.component) {
152
+ case "sankey":
153
+ return [
154
+ { path: "encode.source", col: spec.encode.source },
155
+ { path: "encode.target", col: spec.encode.target },
156
+ { path: "encode.value", col: spec.encode.value, numeric: true }
157
+ ];
158
+ case "bar":
159
+ case "line":
160
+ case "area": {
161
+ const ys = Array.isArray(spec.encode.y) ? spec.encode.y : [spec.encode.y];
162
+ return [
163
+ { path: "encode.x", col: spec.encode.x },
164
+ ...ys.map((y, i) => ({ path: Array.isArray(spec.encode.y) ? `encode.y.${i}` : "encode.y", col: y, numeric: true })),
165
+ ...spec.encode.series ? [{ path: "encode.series", col: spec.encode.series }] : []
166
+ ];
167
+ }
168
+ case "kpi":
169
+ return [{ path: "encode.value", col: spec.encode.value, numeric: true }];
170
+ case "table":
171
+ return spec.encode.columns.map((c, i) => ({ path: `encode.columns.${i}.field`, col: c.field }));
172
+ case "grid":
173
+ case "actionTable":
174
+ return [{ path: "encode.rowKey", col: e.rowKey }, ...e.columns.map((c, i) => ({ path: `encode.columns.${i}.field`, col: c.field }))];
175
+ }
176
+ }
177
+ function argRefs(expr, path, out) {
178
+ if ("field" in expr) out.push({ path, kind: "field", name: expr.field });
179
+ else if ("input" in expr) out.push({ path, kind: "input", name: expr.input });
180
+ else if ("param" in expr) out.push({ path, kind: "param", name: expr.param });
181
+ else if ("template" in expr) for (const m of expr.template.matchAll(/\{([^}]+)\}/g)) out.push({ path, kind: "field", name: m[1] });
182
+ else if ("list" in expr) expr.list.forEach((x, i) => argRefs(x, `${path}.list.${i}`, out));
183
+ }
184
+ function invoked(spec) {
185
+ const intents = /* @__PURE__ */ new Set();
186
+ if (spec.component === "actionTable") intents.add(spec.encode.action.intent);
187
+ if (spec.component === "grid") {
188
+ for (const c of spec.encode.columns) if (c.edit) intents.add(c.edit.intent);
189
+ }
190
+ return { intents: [...intents], navigations: spec.onClick ? [spec.onClick.navigate] : [] };
191
+ }
192
+ function validateDraft(input, m, opts) {
193
+ const out = { ok: false, problems: [], warnings: [], columns: {}, touched: [] };
194
+ const P = out.problems;
195
+ scanStrings(input, "", P);
196
+ const parsed = DraftSchema.safeParse(input);
197
+ if (!parsed.success) {
198
+ P.push(...zodProblems(parsed.error));
199
+ return dedupe(out);
200
+ }
201
+ const draft = parsed.data;
202
+ out.draft = draft;
203
+ const spec = draft.body;
204
+ const slot = m.slots[draft.placement.slot];
205
+ if (!slot) P.push(problem("placement.slot", "unknown_slot", `unknown slot "${draft.placement.slot}" (slots: ${Object.keys(m.slots).join(", ")})`));
206
+ else {
207
+ const asPage = slot.accepts.includes("page") && !slot.accepts.includes("spec");
208
+ if (!asPage && !slot.accepts.includes("spec")) P.push(problem("placement.slot", "slot_kind", `slot ${draft.placement.slot} does not accept specs`));
209
+ if (asPage && !draft.placement.label?.[m.defaultLocale]) P.push(problem("placement.label", "schema", `a page in ${draft.placement.slot} needs a label in ${m.defaultLocale}`));
210
+ }
211
+ for (const [name, p] of Object.entries(spec.params ?? {})) {
212
+ if ("bind" in p) {
213
+ const key = p.bind.slice("host.context.".length);
214
+ if (!m.context[key]) P.push(problem(`body.params.${name}.bind`, "context", `the host declares no context "${key}"`));
215
+ else if (slot && !slot.context.includes(key))
216
+ P.push(
217
+ problem(`body.params.${name}.bind`, "context", `slot ${draft.placement.slot} does not provide context "${key}" (it provides: ${slot.context.join(", ") || "nothing"})`)
218
+ );
219
+ } else if (p.control === "slider" && (p.min >= p.max || p.default < p.min || p.default > p.max)) {
220
+ P.push(problem(`body.params.${name}`, "schema", "slider needs min < max and a default between them"));
221
+ }
222
+ }
223
+ const v = validateIR(spec.data, m, { reads: draft.manifest.reads, role: opts.role, params: paramTypes(spec, m) });
224
+ P.push(...nest("body.data", v.problems));
225
+ out.columns = v.columns;
226
+ out.touched = v.touched;
227
+ for (const r of draft.manifest.reads)
228
+ if (!v.touched.includes(r)) P.push(problem("manifest.reads", "unused_read", `declares ${r} but never reads it; list exactly what the query touches`));
229
+ if (v.ir) {
230
+ for (const { path, col, numeric: numeric2 } of encodeColumns(spec)) {
231
+ const c = v.columns[col];
232
+ if (!c) P.push(problem(`body.${path}`, "encode", `"${col}" is not a column of the query (columns: ${Object.keys(v.columns).join(", ")})`));
233
+ else if (numeric2 && c.type !== "number") P.push(problem(`body.${path}`, "encode", `"${col}" must be a number column`));
234
+ }
235
+ if (spec.component === "kpi" && v.ir.groupBy?.length) P.push(problem("body.data.groupBy", "encode", "a KPI shows one number; remove groupBy"));
236
+ if (spec.component === "sankey" && spec.encode.source === spec.encode.target) P.push(problem("body.encode.target", "encode", "source and target must differ"));
237
+ }
238
+ const { intents, navigations } = invoked(spec);
239
+ for (const i of intents) {
240
+ if (!m.intents[i]) P.push(problem("body", "unknown_intent", `unknown intent "${i}" (intents: ${Object.keys(m.intents).join(", ") || "none"})`));
241
+ else if (!draft.manifest.acts.includes(i)) P.push(problem("manifest.acts", "undeclared_act", `invokes ${i}, which the manifest does not declare`));
242
+ else if (!canAct(m, opts.role, i)) P.push(problem("manifest.acts", "role_denied", `role ${opts.role} cannot use ${i}`));
243
+ }
244
+ for (const a of draft.manifest.acts) if (!intents.includes(a)) P.push(problem("manifest.acts", "unused_read", `declares ${a} but never invokes it`));
245
+ for (const n of navigations)
246
+ if (!m.navigation[n]) P.push(problem("body.onClick.navigate", "unknown_intent", `unknown navigation "${n}" (navigations: ${Object.keys(m.navigation).join(", ") || "none"})`));
247
+ const inputs = new Set(spec.component === "actionTable" ? (spec.encode.inputs ?? []).map((x) => x.name) : []);
248
+ const checkArgs = (args, schema, path, extra = []) => {
249
+ const props = Object.keys(schema?.properties ?? {});
250
+ const required = (schema?.required ?? []).filter((r) => !extra.includes(r));
251
+ for (const k of Object.keys(args)) if (!props.includes(k)) P.push(problem(`${path}.${k}`, "schema", `unknown argument "${k}" (arguments: ${props.join(", ")})`));
252
+ for (const r of required) if (!(r in args)) P.push(problem(path, "schema", `missing argument "${r}"`));
253
+ const refs = [];
254
+ for (const [k, e] of Object.entries(args)) argRefs(e, `${path}.${k}`, refs);
255
+ for (const r of refs) {
256
+ if (r.kind === "field" && !v.columns[r.name]) P.push(problem(r.path, "encode", `"${r.name}" is not a column of the query`));
257
+ if (r.kind === "input" && !inputs.has(r.name)) P.push(problem(r.path, "encode", `"${r.name}" is not a declared row input`));
258
+ if (r.kind === "param" && !spec.params?.[r.name]) P.push(problem(r.path, "unknown_param", `param "${r.name}" is not declared`));
259
+ }
260
+ };
261
+ if (spec.component === "actionTable") checkArgs(spec.encode.action.args, m.intents[spec.encode.action.intent]?.args, "body.encode.action.args");
262
+ if (spec.component === "grid")
263
+ spec.encode.columns.forEach((c, i) => c.edit && checkArgs(c.edit.args, m.intents[c.edit.intent]?.args, `body.encode.columns.${i}.edit.args`, [c.edit.value]));
264
+ if (spec.onClick) checkArgs(spec.onClick.args, m.navigation[spec.onClick.navigate]?.args, "body.onClick.args");
265
+ if (!spec.title[m.defaultLocale]) P.push(problem("body.title", "locale", `title needs a ${m.defaultLocale} entry`));
266
+ for (const l of m.locales) if (!spec.title[l]) out.warnings.push(problem("body.title", "locale", `no ${l} title; ${m.defaultLocale} is shown instead`));
267
+ return dedupe(out, true);
268
+ }
269
+ function dedupe(out, done = false) {
270
+ const seen = /* @__PURE__ */ new Set();
271
+ out.problems = out.problems.filter((p) => {
272
+ const k = `${p.path}|${p.message}`;
273
+ if (seen.has(k)) return false;
274
+ seen.add(k);
275
+ return true;
276
+ });
277
+ out.ok = done && out.problems.length === 0;
278
+ return out;
279
+ }
280
+
281
+ // src/describe.ts
282
+ import { fieldLabel, resourceLabel } from "@crasi/bisque-contract";
283
+ import { measureOf } from "@crasi/bisque-ir";
284
+ function localize(text, locale, fallback) {
285
+ if (!text) return "";
286
+ return text[locale] ?? text[fallback] ?? Object.values(text)[0] ?? "";
287
+ }
288
+ function columnLabel(c, col) {
289
+ const ir = c.spec.data;
290
+ for (const raw of ir.measures ?? []) {
291
+ const { agg, field, as } = measureOf(raw);
292
+ if (as === col) return measurePhrase(c, agg, field, true);
293
+ }
294
+ const [res, f] = col.includes(".") ? [col.slice(0, col.indexOf(".")), col.slice(col.indexOf(".") + 1)] : [ir.scan, col];
295
+ return fieldLabel(c.m, res, f);
296
+ }
297
+ function fieldOf(c, name) {
298
+ return name.includes(".") ? { res: name.slice(0, name.indexOf(".")), f: name.slice(name.indexOf(".") + 1) } : { res: c.spec.data.scan, f: name };
299
+ }
300
+ function measurePhrase(c, agg, field, short = false) {
301
+ if (agg === "count" && field === "*") return short ? `number of ${resourceLabel(c.m, c.spec.data.scan)}` : `Number of ${resourceLabel(c.m, c.spec.data.scan)}`;
302
+ const { res, f } = fieldOf(c, field);
303
+ const label = fieldLabel(c.m, res, f);
304
+ const isDate = ["date", "datetime"].includes(c.m.resources[res]?.fields[f]?.type ?? "");
305
+ const words = {
306
+ sum: short ? label : `Sum of ${label}`,
307
+ avg: `${short ? "average" : "Average"} ${label}`,
308
+ count: `${short ? "number" : "Number"} of ${label}`,
309
+ countDistinct: `${short ? "number" : "Number"} of distinct ${label}`,
310
+ min: `${short ? isDate ? "earliest" : "lowest" : isDate ? "Earliest" : "Lowest"} ${label}`,
311
+ max: `${short ? isDate ? "latest" : "highest" : isDate ? "Latest" : "Highest"} ${label}`
312
+ };
313
+ return words[agg];
314
+ }
315
+ var MONTH = /^\d{4}-\d{2}(-01)?$/;
316
+ var DATE = /^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/;
317
+ function formatValue(v, locale) {
318
+ if (typeof v === "string" && MONTH.test(v)) return (/* @__PURE__ */ new Date(`${v.slice(0, 7)}-01T00:00:00Z`)).toLocaleDateString(locale, { month: "long", year: "numeric", timeZone: "UTC" });
319
+ if (typeof v === "string" && DATE.test(v))
320
+ return (/* @__PURE__ */ new Date(`${v.slice(0, 10)}T00:00:00Z`)).toLocaleDateString(locale, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
321
+ if (Array.isArray(v)) return v.map((x) => formatValue(x, locale)).join(", ");
322
+ return String(v);
323
+ }
324
+ function scalarText(c, v) {
325
+ if (v && typeof v === "object" && "param" in v) {
326
+ const p = c.spec.params?.[v.param];
327
+ if (p && "bind" in p) {
328
+ const key = p.bind.slice("host.context.".length);
329
+ const cur2 = c.opts.context?.[key];
330
+ const follows = c.m.context[key]?.label ?? `the ${key} you are viewing`;
331
+ return { text: cur2 !== void 0 ? formatValue(cur2, c.locale) : `the ${key} being viewed`, follows };
332
+ }
333
+ const cur = c.opts.params?.[v.param] ?? (p && "default" in p ? p.default : void 0);
334
+ return { text: cur !== void 0 ? `${formatValue(cur, c.locale)} (adjustable)` : `the chosen ${v.param}` };
335
+ }
336
+ if (v && typeof v === "object" && "today" in v) {
337
+ return { text: v.today === 0 ? "today" : v.today > 0 ? `${v.today} days from today` : `${-v.today} days ago` };
338
+ }
339
+ return { text: formatValue(v, c.locale) };
340
+ }
341
+ function filterPhrase(c, cond, follows) {
342
+ const [field, op] = cond;
343
+ const { res, f } = fieldOf(c, field);
344
+ const label = fieldLabel(c.m, res, f);
345
+ if (op === "isNull") return `where ${label} is empty`;
346
+ if (op === "notNull") return `where ${label} is set`;
347
+ const raw = cond[2];
348
+ const vals = (Array.isArray(raw) ? raw : [raw]).map((x) => {
349
+ const t = scalarText(c, x);
350
+ if (t.follows) follows.add(t.follows);
351
+ return t.text;
352
+ });
353
+ const isMonth = f === "month";
354
+ switch (op) {
355
+ case "=":
356
+ return isMonth ? `in ${vals[0]}` : `where ${label} is ${vals[0]}`;
357
+ case "!=":
358
+ return `where ${label} is not ${vals[0]}`;
359
+ case "in":
360
+ return `where ${label} is ${vals.join(", ")}`;
361
+ case "notIn":
362
+ return `excluding ${label} ${vals.join(", ")}`;
363
+ case "match":
364
+ return `for ${vals.join(", ")}`;
365
+ case "<": {
366
+ const today = Array.isArray(raw) ? void 0 : raw;
367
+ if (today && typeof today === "object" && "today" in today && today.today < 0) return `where ${label} is more than ${-today.today} days ago`;
368
+ return `where ${label} is before ${vals[0]}`.replace(/before (\d+(\.\d+)?)$/, "below $1");
369
+ }
370
+ case "<=": {
371
+ const today = Array.isArray(raw) ? void 0 : raw;
372
+ if (today && typeof today === "object" && "today" in today && today.today >= 0) return `with ${label} within the next ${today.today} days`;
373
+ return `where ${label} is at most ${vals[0]}`;
374
+ }
375
+ case ">":
376
+ return `where ${label} is above ${vals[0]}`;
377
+ case ">=": {
378
+ const today = Array.isArray(raw) ? void 0 : raw;
379
+ if (today && typeof today === "object" && "today" in today && today.today <= 0) return `in the last ${-today.today} days`;
380
+ return `where ${label} is at least ${vals[0]}`;
381
+ }
382
+ }
383
+ return "";
384
+ }
385
+ function groupingPhrase(c) {
386
+ const s = c.spec;
387
+ const L = (col) => columnLabel(c, col);
388
+ switch (s.component) {
389
+ case "sankey":
390
+ return `from each ${L(s.encode.source)} to each ${L(s.encode.target)}`;
391
+ case "bar":
392
+ return `by ${L(s.encode.x)}${s.encode.series ? `, split by ${L(s.encode.series)}` : ""}`;
393
+ case "line":
394
+ case "area":
395
+ return `over ${L(s.encode.x)}${s.encode.series ? `, one line per ${L(s.encode.series)}` : ""}`;
396
+ case "kpi":
397
+ return "";
398
+ default: {
399
+ const g = withoutKeys(c, s.data.groupBy ?? []);
400
+ return g.length ? `one row per ${g.map(L).join(" and ")}` : `listing ${withoutKeys(c, s.data.select ?? []).map(L).join(", ")}`;
401
+ }
402
+ }
403
+ }
404
+ function withoutKeys(c, cols) {
405
+ const resOf = (col) => fieldOf(c, col).res;
406
+ const isKey = (col) => {
407
+ const { res, f } = fieldOf(c, col);
408
+ return f === (c.m.resources[res]?.key ?? "id");
409
+ };
410
+ return cols.filter((col) => !isKey(col) || !cols.some((o) => o !== col && resOf(o) === resOf(col) && !isKey(o)));
411
+ }
412
+ function headline(c, follows) {
413
+ const ir = c.spec.data;
414
+ const measures = (ir.measures ?? []).map((raw) => {
415
+ const { agg, field } = measureOf(raw);
416
+ return measurePhrase(c, agg, field);
417
+ });
418
+ const lead = measures.length ? [measures[0], ...measures.slice(1).map((x) => x.charAt(0).toLowerCase() + x.slice(1))].join(" and ") : `${resourceLabel(c.m, ir.scan).replace(/^./, (x) => x.toUpperCase())}`;
419
+ const filters = (ir.where ?? []).map((w) => filterPhrase(c, w, follows)).filter(Boolean);
420
+ if (measures.length && filters.length && /^(with|where) /.test(filters[0])) filters[0] = `of ${resourceLabel(c.m, ir.scan)} ${filters[0]}`;
421
+ const grouping = groupingPhrase(c);
422
+ return `${[lead, ...filters].join(" ")}${grouping ? `, ${grouping}` : ""}.`;
423
+ }
424
+ function placedText(m, d, locale) {
425
+ const slot = m.slots[d.placement.slot];
426
+ const where = slot?.label ?? d.placement.slot;
427
+ return d.placement.label ? `${where} as \u201C${localize(d.placement.label, locale, m.defaultLocale)}\u201D` : where;
428
+ }
429
+ function intentLabel(m, name, locale) {
430
+ const l = m.intents[name]?.label;
431
+ if (!l) return name;
432
+ return typeof l === "string" ? l : localize(l, locale, m.defaultLocale);
433
+ }
434
+ function describeDraft(d, m, opts = {}) {
435
+ const locale = opts.locale ?? m.defaultLocale;
436
+ const spec = d.body;
437
+ const c = { m, spec, opts, locale };
438
+ const follows = /* @__PURE__ */ new Set();
439
+ const lines = [headline(c, follows)];
440
+ const ir = spec.data;
441
+ if (spec.component === "sankey" && spec.encode.label === "share-of-source")
442
+ lines.push(`Each flow is labelled with its share of the ${columnLabel(c, spec.encode.source)}'s total.`);
443
+ if (spec.component === "sankey" && spec.otherBucket)
444
+ lines.push(`${capitalize(plural(columnLabel(c, spec.encode.target)))} after the top ${spec.otherBucket.maxTargets} are grouped as Other.`);
445
+ if (spec.component === "bar" && spec.otherBucket)
446
+ lines.push(`${capitalize(plural(columnLabel(c, spec.encode.x)))} after the top ${spec.otherBucket.maxCategories} are grouped as Other.`);
447
+ const order = ir.orderBy?.[0];
448
+ if (order && ir.limit <= 50 && spec.component !== "sankey") lines.push(`Top ${ir.limit} by ${columnLabel(c, order[0])}${order[1] === "asc" ? ", lowest first" : ""}.`);
449
+ for (const [, p] of Object.entries(spec.params ?? {})) if (!("bind" in p)) lines.push(`Adjustable: ${localize(p.label, locale, m.defaultLocale)}.`);
450
+ for (const f of follows) lines.push(`Follows ${f}.`);
451
+ if (spec.onClick) {
452
+ const n = m.navigation[spec.onClick.navigate];
453
+ lines.push(`Click an item to ${n?.describe ? n.describe.charAt(0).toLowerCase() + n.describe.slice(1) : `open ${spec.onClick.navigate}`}.`);
454
+ }
455
+ const changes = [];
456
+ if (spec.component === "actionTable") {
457
+ const i = m.intents[spec.encode.action.intent];
458
+ changes.push(`${intentLabel(m, spec.encode.action.intent, locale)} for each selected row${i?.policy === "confirm" ? " (asks you first)" : ""}`);
459
+ }
460
+ if (spec.component === "grid") {
461
+ for (const col of spec.encode.columns)
462
+ if (col.edit) {
463
+ const i = m.intents[col.edit.intent];
464
+ changes.push(`Editing ${columnLabel(c, col.field)} calls ${intentLabel(m, col.edit.intent, locale)}${i?.policy === "confirm" ? " (asks you first)" : ""}`);
465
+ }
466
+ }
467
+ return {
468
+ title: localize(spec.title, locale, m.defaultLocale),
469
+ lines,
470
+ reads: d.manifest.reads.map((r) => resourceLabel(m, r)),
471
+ changes: changes.length ? changes : invoked(spec).intents.length ? invoked(spec).intents.map((i) => intentLabel(m, i, locale)) : [],
472
+ placed: placedText(m, d, locale)
473
+ };
474
+ }
475
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
476
+ var plural = (s) => s.endsWith("s") ? s : s.endsWith("y") ? `${s.slice(0, -1)}ies` : `${s}s`;
477
+ function diffDrafts(a, b, m, opts = {}) {
478
+ const locale = opts.locale ?? m.defaultLocale;
479
+ const ca = { m, spec: a.body, opts, locale };
480
+ const cb = { m, spec: b.body, opts, locale };
481
+ const out = [];
482
+ if (a.body.component !== b.body.component) out.push(`Chart: ${a.body.component} \u2192 ${b.body.component}`);
483
+ const ms = (c) => (c.spec.data.measures ?? []).map((raw) => {
484
+ const x = measureOf(raw);
485
+ return measurePhrase(c, x.agg, x.field, true);
486
+ });
487
+ const [ma, mb] = [ms(ca), ms(cb)];
488
+ if (ma.join("|") !== mb.join("|")) out.push(`Measure: ${ma.join(", ") || "none"} \u2192 ${mb.join(", ") || "none"}`);
489
+ const fs = (c) => (c.spec.data.where ?? []).map((w) => ({ key: JSON.stringify(w), text: filterPhrase(c, w, /* @__PURE__ */ new Set()) }));
490
+ const [fa, fb] = [fs(ca), fs(cb)];
491
+ const fbKeys = new Set(fb.map((x) => x.key)), faKeys = new Set(fa.map((x) => x.key));
492
+ for (const x of fb) if (!faKeys.has(x.key)) out.push(`Filter: + ${x.text.replace(/^(for|where|in) /, "")}`);
493
+ for (const x of fa) if (!fbKeys.has(x.key)) out.push(`Filter: \u2212 ${x.text.replace(/^(for|where|in) /, "")}`);
494
+ const ga = groupingPhrase(ca), gb = groupingPhrase(cb);
495
+ if (ga !== gb && a.body.component === b.body.component) out.push(`Grouping: ${ga || "none"} \u2192 ${gb || "none"}`);
496
+ const ta = localize(a.body.title, locale, m.defaultLocale), tb = localize(b.body.title, locale, m.defaultLocale);
497
+ if (ta !== tb) out.push(`Title: ${ta} \u2192 ${tb}`);
498
+ const ob = (s) => s.component === "sankey" ? s.otherBucket?.maxTargets : s.component === "bar" ? s.otherBucket?.maxCategories : void 0;
499
+ if (ob(a.body) !== ob(b.body)) out.push(`Top: ${ob(a.body) ?? "all"} \u2192 ${ob(b.body) ?? "all"}`);
500
+ if (a.body.data.limit !== b.body.data.limit) out.push(`Rows: at most ${a.body.data.limit} \u2192 ${b.body.data.limit}`);
501
+ if (a.placement.slot !== b.placement.slot) out.push(`Placed: ${placedText(m, a, locale)} \u2192 ${placedText(m, b, locale)}`);
502
+ const ia = invoked(a.body).intents.join(", "), ib = invoked(b.body).intents.join(", ");
503
+ if (ia !== ib) out.push(`Changes: ${ia || "nothing"} \u2192 ${ib || "nothing"}`);
504
+ return out;
505
+ }
506
+
507
+ // src/adjust.ts
508
+ import { MAX_ROWS } from "@crasi/bisque-core";
509
+ import { measureOf as measureOf2 } from "@crasi/bisque-ir";
510
+ var COMPONENT_LABEL = {
511
+ sankey: "Sankey",
512
+ bar: "Bar chart",
513
+ line: "Line chart",
514
+ area: "Area chart",
515
+ table: "Table",
516
+ kpi: "Number",
517
+ grid: "Editable grid",
518
+ actionTable: "Action table"
519
+ };
520
+ function compatibleComponents(spec) {
521
+ if (spec.component === "grid" || spec.component === "actionTable") return [spec.component];
522
+ const groups = spec.data.groupBy?.length ?? 0;
523
+ const measures = spec.data.measures?.length ?? 0;
524
+ if (!measures) return ["table"];
525
+ if (groups === 0) return ["kpi", "table"];
526
+ if (groups === 1) return ["bar", "line", "area", "table"];
527
+ return ["sankey", "bar", "table"];
528
+ }
529
+ function adjustables(d, m) {
530
+ const s = d.body;
531
+ const out = [];
532
+ const comps = compatibleComponents(s);
533
+ if (comps.length > 1) out.push({ id: "component", label: "Show as", type: "select", value: s.component, options: comps.map((c) => ({ value: c, label: COMPONENT_LABEL[c] })) });
534
+ if (s.component === "sankey") {
535
+ out.push({ id: "otherBucket", label: "Top targets", type: "number", value: s.otherBucket?.maxTargets ?? 12, min: 2, max: 50 });
536
+ out.push({
537
+ id: "sankeyLabel",
538
+ label: "Labels",
539
+ type: "select",
540
+ value: s.encode.label ?? "value",
541
+ options: [
542
+ { value: "value", label: "Values" },
543
+ { value: "share-of-source", label: "Share of source" },
544
+ { value: "share-of-total", label: "Share of total" }
545
+ ]
546
+ });
547
+ }
548
+ if (s.component === "bar") {
549
+ out.push({ id: "otherBucket", label: "Top categories", type: "number", value: s.otherBucket?.maxCategories ?? 12, min: 2, max: 50 });
550
+ if (s.encode.series)
551
+ out.push({
552
+ id: "stacked",
553
+ label: "Bars",
554
+ type: "select",
555
+ value: s.encode.stacked ? "stacked" : "grouped",
556
+ options: [
557
+ { value: "stacked", label: "Stacked" },
558
+ { value: "grouped", label: "Side by side" }
559
+ ]
560
+ });
561
+ }
562
+ const cap = Math.min(m.resources[s.data.scan]?.cap ?? MAX_ROWS, MAX_ROWS);
563
+ out.push({ id: "limit", label: "Rows at most", type: "number", value: s.data.limit, min: 1, max: cap });
564
+ if (s.data.orderBy?.length)
565
+ out.push({
566
+ id: "order",
567
+ label: "Order",
568
+ type: "select",
569
+ value: s.data.orderBy[0][1],
570
+ options: [
571
+ { value: "desc", label: "Highest first" },
572
+ { value: "asc", label: "Lowest first" }
573
+ ]
574
+ });
575
+ return out;
576
+ }
577
+ function applyAdjustment(d, id, value) {
578
+ const s = structuredClone(d.body);
579
+ switch (id) {
580
+ case "component":
581
+ return { ...d, body: switchComponent(s, value) };
582
+ case "otherBucket":
583
+ if (s.component === "sankey") s.otherBucket = { maxTargets: Number(value) };
584
+ if (s.component === "bar") s.otherBucket = { maxCategories: Number(value) };
585
+ break;
586
+ case "sankeyLabel":
587
+ if (s.component === "sankey") s.encode.label = value;
588
+ break;
589
+ case "stacked":
590
+ if (s.component === "bar") s.encode.stacked = value === "stacked";
591
+ break;
592
+ case "limit":
593
+ s.data.limit = Math.max(1, Math.floor(Number(value)));
594
+ break;
595
+ case "order":
596
+ if (s.data.orderBy?.length) s.data.orderBy[0] = [s.data.orderBy[0][0], value];
597
+ break;
598
+ }
599
+ return { ...d, body: s };
600
+ }
601
+ function switchComponent(s, to) {
602
+ if (s.component === to) return s;
603
+ const groups = s.data.groupBy ?? [];
604
+ const measures = (s.data.measures ?? []).map((x) => measureOf2(x).as);
605
+ const base = { title: s.title, data: s.data, params: s.params, onClick: s.onClick };
606
+ const value = measures[0];
607
+ switch (to) {
608
+ case "sankey":
609
+ return { component: "sankey", ...base, encode: { source: groups[0], target: groups[1], value }, otherBucket: { maxTargets: 12 } };
610
+ case "bar":
611
+ return { component: "bar", ...base, encode: { x: groups[0], y: value, ...groups[1] ? { series: groups[1], stacked: true } : {} } };
612
+ case "line":
613
+ case "area":
614
+ return { component: to, ...base, encode: { x: groups[0], y: measures.length > 1 ? measures : value, ...groups[1] ? { series: groups[1] } : {} } };
615
+ case "kpi":
616
+ return { component: "kpi", ...base, encode: { value } };
617
+ case "table":
618
+ return { component: "table", ...base, encode: { columns: [...groups, ...measures, ...s.data.select ?? []].map((field) => ({ field })) } };
619
+ default:
620
+ return s;
621
+ }
622
+ }
623
+
624
+ // src/diagnostics.ts
625
+ import { z as z2 } from "zod";
626
+ import { bucketCount, bucketShare, COUNT_BUCKETS } from "@crasi/bisque-core";
627
+ var RENDER_ERRORS = ["empty", "too_many_categories", "all_null", "unresolved_names", "ambiguous_names", "component_error"];
628
+ var Bucket = z2.enum(COUNT_BUCKETS);
629
+ var ColumnName = z2.string().regex(/^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/i).max(80);
630
+ var DiagnosticsSchema = z2.object({
631
+ proposal: z2.string().max(64),
632
+ valid: z2.boolean(),
633
+ rows: Bucket,
634
+ distinct: z2.record(ColumnName, Bucket),
635
+ nullShare: z2.record(ColumnName, z2.number().min(0).max(1).multipleOf(0.1)),
636
+ otherBucket: z2.enum(["applied", "not needed", "not set"]),
637
+ truncated: z2.boolean(),
638
+ renderErrors: z2.array(z2.enum(RENDER_ERRORS)).max(RENDER_ERRORS.length)
639
+ }).strict();
640
+ function categorical(spec) {
641
+ switch (spec.component) {
642
+ case "sankey":
643
+ return [spec.encode.source, spec.encode.target];
644
+ case "bar":
645
+ case "line":
646
+ case "area":
647
+ return [spec.encode.x, ...spec.encode.series ? [spec.encode.series] : []];
648
+ default:
649
+ return spec.data.groupBy ?? [];
650
+ }
651
+ }
652
+ function numeric(spec) {
653
+ switch (spec.component) {
654
+ case "sankey":
655
+ return [spec.encode.value];
656
+ case "bar":
657
+ case "line":
658
+ case "area":
659
+ return Array.isArray(spec.encode.y) ? spec.encode.y : [spec.encode.y];
660
+ case "kpi":
661
+ return [spec.encode.value];
662
+ default:
663
+ return (spec.data.measures ?? []).map((m) => m.as);
664
+ }
665
+ }
666
+ function renderDiagnostics(proposal, spec, res, opts) {
667
+ const distinct = {};
668
+ const counts = {};
669
+ for (const col of categorical(spec)) {
670
+ counts[col] = new Set(res.rows.map((r) => String(r[col]))).size;
671
+ distinct[col] = bucketCount(counts[col]);
672
+ }
673
+ const nullShare = {};
674
+ for (const col of numeric(spec)) nullShare[col] = res.rows.length ? bucketShare(res.rows.filter((r) => r[col] == null).length / res.rows.length) : 0;
675
+ const errors = /* @__PURE__ */ new Set();
676
+ if (res.total === 0) errors.add("empty");
677
+ if (Object.values(nullShare).some((s) => s === 1) && res.rows.length) errors.add("all_null");
678
+ if (res.resolution.some((r) => r.status === "unmatched")) errors.add("unresolved_names");
679
+ if (res.resolution.some((r) => r.status === "ambiguous")) errors.add("ambiguous_names");
680
+ if (opts.renderError) errors.add("component_error");
681
+ let otherBucket = "not set";
682
+ const cap = spec.component === "sankey" ? spec.otherBucket?.maxTargets : spec.component === "bar" ? spec.otherBucket?.maxCategories : void 0;
683
+ const bucketCol = spec.component === "sankey" ? spec.encode.target : spec.component === "bar" ? spec.encode.x : void 0;
684
+ if (cap && bucketCol) otherBucket = counts[bucketCol] > cap ? "applied" : "not needed";
685
+ else if (bucketCol && counts[bucketCol] > 50) errors.add("too_many_categories");
686
+ return {
687
+ proposal,
688
+ valid: opts.valid,
689
+ rows: bucketCount(res.total),
690
+ distinct,
691
+ nullShare,
692
+ otherBucket,
693
+ truncated: res.truncated,
694
+ renderErrors: [...errors]
695
+ };
696
+ }
697
+ function repairReason(d) {
698
+ const reasons = [];
699
+ if (d.renderErrors.includes("empty")) reasons.push("the query returned no rows on the user's data; check filters and that the month or names exist");
700
+ if (d.renderErrors.includes("all_null")) reasons.push("the measure is empty for every row; it may be the wrong field");
701
+ if (d.renderErrors.includes("too_many_categories")) reasons.push("there are more than 50 categories; add otherBucket or a tighter filter");
702
+ if (d.renderErrors.includes("component_error")) reasons.push("the component failed to render this data shape");
703
+ return reasons.length ? reasons.join("; ") : null;
704
+ }
705
+
706
+ // src/args.ts
707
+ import { addDaysIso } from "@crasi/bisque-ir";
708
+ function evalArg(e, s) {
709
+ if ("field" in e) return s.row?.[e.field] ?? null;
710
+ if ("input" in e) return s.inputs?.[e.input] ?? null;
711
+ if ("param" in e) return s.params?.[e.param] ?? null;
712
+ if ("literal" in e) return e.literal;
713
+ if ("today" in e) return addDaysIso(s.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), e.today);
714
+ if ("template" in e) return e.template.replace(/\{([^}]+)\}/g, (_, k) => String(s.row?.[k] ?? "")).slice(0, 200);
715
+ return e.list.map((x) => evalArg(x, s));
716
+ }
717
+ function evalArgs(args, s) {
718
+ return Object.fromEntries(Object.entries(args).map(([k, e]) => [k, evalArg(e, s)]));
719
+ }
720
+
721
+ // src/migrate.ts
722
+ function migrateDraft(d, renames) {
723
+ if (!Object.keys(renames).length) return null;
724
+ const scan = d.body.data.scan;
725
+ const rename = (name) => {
726
+ const [res, f] = name.includes(".") ? [name.slice(0, name.indexOf(".")), name.slice(name.indexOf(".") + 1)] : [scan, name];
727
+ const to = renames[res]?.[f];
728
+ if (!to) return name;
729
+ return name.includes(".") ? `${res}.${to}` : to;
730
+ };
731
+ let changed = false;
732
+ const walk = (v, key) => {
733
+ if (typeof v === "string" && key && FIELD_KEYS.has(key)) {
734
+ const r = rename(v);
735
+ if (r !== v) changed = true;
736
+ return r;
737
+ }
738
+ if (Array.isArray(v)) {
739
+ if ((key === "cond" || key === "order") && typeof v[0] === "string") {
740
+ const r = rename(v[0]);
741
+ if (r !== v[0]) changed = true;
742
+ return [r, ...v.slice(1).map((x) => walk(x))];
743
+ }
744
+ const childKey = key === "where" ? "cond" : key === "orderBy" ? "order" : key === "groupBy" || key === "select" || key === "y" ? "field" : void 0;
745
+ return v.map((x) => walk(x, childKey));
746
+ }
747
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k)]));
748
+ return v;
749
+ };
750
+ const body = walk(d.body);
751
+ return changed ? { ...d, body } : null;
752
+ }
753
+ var FIELD_KEYS = /* @__PURE__ */ new Set(["field", "on", "sum", "avg", "min", "max", "count", "countDistinct", "source", "target", "value", "x", "y", "series", "rowKey"]);
754
+
755
+ // src/catalog.ts
756
+ var CATALOG_LINE = "catalog: sankey(source,target,value,otherBucket) bar(x,y,series,stacked) line(x,y,series) area(x,y,series) table(columns) kpi(value) grid(rowKey,columns[edit\u2192intent]) actionTable(rowKey,columns,inputs,action\u2192intent) params(bind host.context.*|slider|select|toggle)";
757
+ var SPEC_GUIDE = `## Spec format (propose_spec.draft)
758
+
759
+ {
760
+ "kind": "spec",
761
+ "body": {
762
+ "component": "sankey" | "bar" | "line" | "area" | "table" | "kpi" | "grid" | "actionTable",
763
+ "title": { "<locale>": "\u226480 chars", ... one entry per host locale },
764
+ "data": <query>,
765
+ "encode": <per component, below>,
766
+ "params": { "<name>": { "bind": "host.context.<key>" } | { "control": "slider", "label": {..}, "min": n, "max": n, "step": n, "default": n } | { "control": "select", "label": {..}, "options": [{ "value": v, "label": {..} }], "default": v } | { "control": "toggle", "label": {..}, "default": bool } },
767
+ "onClick": { "navigate": "<navigation name>", "args": { "<arg>": <argExpr> } },
768
+ "otherBucket": { "maxTargets": n } // sankey only; bar uses { "maxCategories": n }
769
+ },
770
+ "manifest": { "reads": [exactly the resources the query touches], "acts": [exactly the intents the spec invokes] },
771
+ "placement": { "slot": "<slot id>", "label": { "<locale>": "\u226440 chars" } } // label only for page slots such as nav.primary
772
+ }
773
+
774
+ <query>:
775
+ {
776
+ "scan": "<resource>",
777
+ "join": [{ "on": "<field of scan, or resource.field of an already joined resource>", "to": "<the resource that field references>" }],
778
+ "where": [["<field>", "=" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "notIn", <value>], ["<field>", "match", ["Name", ...]], ["<field>", "isNull" | "notNull"]],
779
+ "groupBy": ["<field>", ...],
780
+ "measures": [{ "sum" | "avg" | "min" | "max" | "count" | "countDistinct": "<field>" | "*" (count only), "as": "<name>" }],
781
+ "select": ["<field>", ...], // instead of groupBy/measures, for plain row lists
782
+ "orderBy": [["<output column>", "asc" | "desc"]],
783
+ "limit": <integer, required, \u2264 the resource's row cap>
784
+ }
785
+ Field names: unqualified = field of scan; fields of joined resources are qualified ("products.name").
786
+ Joins may only follow declared references (fields shown as "-> resource"). Each resource joins once.
787
+ <value>: a literal, a list of literals, { "param": "<name>" } (declared in params), or { "today": <days offset> } for dates.
788
+ "match" filters take the user's own words for names (e.g. ["Metro", "TABAC"]); the host resolves them to its real values and asks the user if a name is ambiguous. Use match for any name the user mentions; never guess ids.
789
+ Output columns are named exactly as written in groupBy/select, plus each measure's "as".
790
+
791
+ encode by component (every referenced name must be an output column):
792
+ - sankey: { "source": col, "target": col, "value": number col, "label": "value" | "share-of-source" | "share-of-total" }
793
+ - bar: { "x": col, "y": number col | [number cols], "series": col?, "stacked": bool?, "horizontal": bool? }
794
+ - line, area: { "x": col, "y": number col | [number cols], "series": col? }
795
+ - table: { "columns": [{ "field": col, "label": {..}?, "format": "number"|"money"|"percent"|"date"|"month"|"text"? }] }
796
+ - kpi: { "value": number col } \u2014 query has measures and no groupBy
797
+ - grid: { "rowKey": col, "columns": [{ "field": col, "label"?, "format"?, "edit": { "intent": "<intent>", "value": "<arg that receives the edited value>", "args": { "<arg>": <argExpr> } }? }] }
798
+ - actionTable: { "rowKey": col, "columns": [...], "inputs": [{ "name": id, "label": {..}, "type": "number"|"text", "default"?, "min"?, "max"? }], "action": { "intent": "<intent>", "label": {..}, "args": { "<arg>": <argExpr> } } }
799
+ One intent call per selected row; the host shows one confirmation for the whole batch.
800
+
801
+ <argExpr>: { "field": col } | { "input": "<row input name>" } | { "param": "<name>" } | { "literal": v | [v] } | { "today": days } | { "template": "text with {col} placeholders" } | { "list": [<argExpr>, ...] }
802
+
803
+ Never put HTML, CSS, URLs or scripts in any string. Do not write descriptions: the host generates the card text from the spec.`;
804
+
805
+ // src/protocol.ts
806
+ import { z as z4 } from "zod";
807
+
808
+ // src/automation.ts
809
+ import { z as z3 } from "zod";
810
+ import { BisqueError, canonicalJson, nest as nest2, problem as problem2 } from "@crasi/bisque-core";
811
+ import { canAutomate, canAutomateIntent, channelLabel } from "@crasi/bisque-contract";
812
+ import { IRSchema as IRSchema2, runIR, validateIR as validateIR2, zodProblems as zodProblems2 } from "@crasi/bisque-ir";
813
+ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
814
+ var ScheduleSchema = z3.discriminatedUnion("every", [
815
+ z3.object({ every: z3.literal("hour") }).strict(),
816
+ z3.object({ every: z3.literal("day"), at: z3.number().int().min(0).max(23).optional() }).strict(),
817
+ z3.object({ every: z3.literal("weekday"), at: z3.number().int().min(0).max(23).optional() }).strict(),
818
+ z3.object({ every: z3.literal("week"), on: z3.enum(WEEKDAYS), at: z3.number().int().min(0).max(23).optional() }).strict(),
819
+ z3.object({ every: z3.literal("month"), day: z3.number().int().min(1).max(28), at: z3.number().int().min(0).max(23).optional() }).strict()
820
+ ]);
821
+ var AutoColumn = z3.object({ field: z3.string(), label: Label.optional(), format: Format.optional() }).strict();
822
+ var AutomationActionSchema = z3.union([
823
+ /** Tell the owner, on a channel the host declares (`email`). */
824
+ z3.object({ notify: z3.string().max(40) }).strict(),
825
+ /** Call an intent the host marked `automate`, once per reported row. */
826
+ z3.object({ intent: z3.string().max(80), args: Args }).strict()
827
+ ]);
828
+ var MAX_STEPS = 4;
829
+ var AutomationThenSchema = z3.union([AutomationActionSchema, z3.array(AutomationActionSchema).min(1).max(MAX_STEPS)]);
830
+ function automationSteps(a) {
831
+ return Array.isArray(a.then) ? a.then : [a.then];
832
+ }
833
+ var isNotify = (s) => "notify" in s;
834
+ var AutomationSchema = z3.object({
835
+ kind: z3.literal("automation"),
836
+ title: Title,
837
+ /** When to look. */
838
+ schedule: ScheduleSchema,
839
+ /** What to look for: the rows this query returns are the rows the automation reports. */
840
+ data: IRSchema2,
841
+ /**
842
+ * `rows`: act only when the query returns rows to report.
843
+ * `always`: deliver every time, even "nothing today" (a digest). Notify only.
844
+ */
845
+ when: z3.enum(["rows", "always"]),
846
+ /**
847
+ * `new`: report a row once, the first time it matches (needs `key`).
848
+ * `all`: report every matching row every time.
849
+ */
850
+ repeat: z3.enum(["new", "all"]),
851
+ /** Output column that identifies a row, for `repeat: "new"`. */
852
+ key: z3.string().optional(),
853
+ /** What a notification shows, in order. */
854
+ columns: z3.array(AutoColumn).min(1).max(8),
855
+ then: AutomationThenSchema,
856
+ manifest: z3.object({
857
+ reads: z3.array(z3.string()).max(12),
858
+ acts: z3.array(z3.string()).max(MAX_STEPS),
859
+ channels: z3.array(z3.string()).max(1)
860
+ }).strict()
861
+ }).strict();
862
+ var MAX_REPORTED_ROWS = 50;
863
+ function validateAutomation(input, m, opts) {
864
+ const out = { ok: false, problems: [], columns: {} };
865
+ const P = out.problems;
866
+ if (!m.automations) {
867
+ P.push(problem2("", "deferred", "this app does not run automations: it declares no automations block"));
868
+ return out;
869
+ }
870
+ P.push(...unsafeTextProblems(input));
871
+ const parsed = AutomationSchema.safeParse(input);
872
+ if (!parsed.success) {
873
+ P.push(...zodProblems2(parsed.error));
874
+ return out;
875
+ }
876
+ const a = parsed.data;
877
+ out.automation = a;
878
+ if (!canAutomate(m, opts.role)) P.push(problem2("", "role_denied", `role ${opts.role} cannot create automations`));
879
+ if (m.automations.cadence === "day") {
880
+ if (a.schedule.every === "hour") P.push(problem2("schedule.every", "schema", "this app checks automations once a day; use day, weekday, week or month"));
881
+ if ("at" in a.schedule && a.schedule.at !== void 0) P.push(problem2("schedule.at", "schema", "this app checks automations once a day, in the morning; leave out at"));
882
+ }
883
+ const v = validateIR2(a.data, m, { reads: a.manifest.reads, role: opts.role });
884
+ P.push(...nest2("data", v.problems));
885
+ out.columns = v.columns;
886
+ for (const r of a.manifest.reads)
887
+ if (!v.touched.includes(r)) P.push(problem2("manifest.reads", "unused_read", `declares ${r} but never reads it; list exactly what the query touches`));
888
+ if (v.params.length) P.push(problem2("data", "unknown_param", "an automation runs on its own, with no page to follow: use fixed values or {today: n}, not params"));
889
+ if (v.ir) {
890
+ a.columns.forEach((c, i) => {
891
+ if (!v.columns[c.field]) P.push(problem2(`columns.${i}.field`, "encode", `"${c.field}" is not a column of the query (columns: ${Object.keys(v.columns).join(", ")})`));
892
+ });
893
+ if (a.key && !v.columns[a.key]) P.push(problem2("key", "encode", `"${a.key}" is not a column of the query`));
894
+ }
895
+ if (a.repeat === "new" && !a.key) P.push(problem2("key", "schema", 'repeat "new" needs key: the column that identifies a row, such as id'));
896
+ const steps = automationSteps(a);
897
+ const at2 = (i) => Array.isArray(a.then) ? `then.${i}` : "then";
898
+ const intents = steps.filter((x) => !isNotify(x));
899
+ const notifies = steps.filter(isNotify);
900
+ if (notifies.length > 1) P.push(problem2("then", "schema", "a workflow sends at most one message: keep one notify step"));
901
+ if (notifies.length && !isNotify(steps[steps.length - 1]))
902
+ P.push(problem2("then", "schema", "notify must be the last step: it reports the rows that went through the steps before it"));
903
+ if (a.when === "always" && !notifies.length) P.push(problem2("when", "schema", 'when "always" is for notifications; an intent runs only for rows'));
904
+ steps.forEach((step, i) => {
905
+ if (isNotify(step)) {
906
+ if (!m.automations?.channels[step.notify])
907
+ P.push(problem2(`${at2(i)}.notify`, "unknown_field", `unknown channel "${step.notify}" (channels: ${Object.keys(m.automations?.channels ?? {}).join(", ") || "none"})`));
908
+ return;
909
+ }
910
+ const name = step.intent;
911
+ const intent = m.intents[name];
912
+ if (!intent) P.push(problem2(`${at2(i)}.intent`, "unknown_intent", `unknown intent "${name}"`));
913
+ else if (!intent.automate) P.push(problem2(`${at2(i)}.intent`, "role_denied", `${name} is not marked automate in the contract, so it only runs when a person clicks`));
914
+ else if (!canAutomateIntent(m, opts.role, name)) P.push(problem2(`${at2(i)}.intent`, "role_denied", `role ${opts.role} cannot use ${name} in an automation`));
915
+ if (intent) {
916
+ const props = Object.keys(intent.args.properties ?? {});
917
+ const required = intent.args.required ?? [];
918
+ for (const k of Object.keys(step.args)) if (!props.includes(k)) P.push(problem2(`${at2(i)}.args.${k}`, "schema", `unknown argument "${k}" (arguments: ${props.join(", ")})`));
919
+ for (const r of required) if (!(r in step.args)) P.push(problem2(`${at2(i)}.args`, "schema", `missing argument "${r}"`));
920
+ for (const [k, e] of Object.entries(step.args)) argProblems(e, `${at2(i)}.args.${k}`, v.columns, P);
921
+ }
922
+ });
923
+ const acts = [...new Set(intents.map((x) => x.intent))];
924
+ const channels = notifies.map((x) => x.notify);
925
+ if (a.manifest.acts.join() !== acts.join())
926
+ P.push(problem2("manifest.acts", "undeclared_act", `manifest.acts must be ${JSON.stringify(acts)}: the intents the steps call, in order`));
927
+ if (a.manifest.channels.join() !== channels.join()) P.push(problem2("manifest.channels", "undeclared_act", `manifest.channels must be ${JSON.stringify(channels)}`));
928
+ if (!a.title[m.defaultLocale]) P.push(problem2("title", "locale", `title needs a ${m.defaultLocale} entry`));
929
+ out.ok = P.length === 0;
930
+ return out;
931
+ }
932
+ function argProblems(e, path, columns, P) {
933
+ if ("field" in e && !columns[e.field]) P.push(problem2(path, "encode", `"${e.field}" is not a column of the query`));
934
+ if ("input" in e || "param" in e) P.push(problem2(path, "schema", "an automation has no inputs or params; use field, literal, today or template"));
935
+ if ("template" in e) {
936
+ for (const m of e.template.matchAll(/\{([^}]+)\}/g)) if (!columns[m[1]]) P.push(problem2(path, "encode", `"${m[1]}" is not a column of the query`));
937
+ }
938
+ if ("list" in e) e.list.forEach((x, i) => argProblems(x, `${path}.list.${i}`, columns, P));
939
+ }
940
+ var DAY_NAMES = { mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday", sun: "Sunday" };
941
+ var ordinal = (n) => `${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"}`;
942
+ function describeSchedule(s, m) {
943
+ if (s.every === "hour") return "Every hour";
944
+ const hour = "at" in s ? s.at : void 0;
945
+ const daily = m.automations?.cadence !== "hour";
946
+ const when = hour === void 0 && daily ? " morning" : ` at ${String(hour ?? 0).padStart(2, "0")}:00 (${m.automations?.timeZone ?? "UTC"})`;
947
+ switch (s.every) {
948
+ case "day":
949
+ return when === " morning" ? "Every morning" : `Every day${when}`;
950
+ case "weekday":
951
+ return `Every weekday${when}`;
952
+ case "week":
953
+ return `Every ${DAY_NAMES[s.on]}${when}`;
954
+ case "month":
955
+ return `On the ${ordinal(s.day)} of every month${when === " morning" ? ", in the morning" : when}`;
956
+ }
957
+ }
958
+ function automationAsDraft(a) {
959
+ return {
960
+ kind: "spec",
961
+ body: { component: "table", title: a.title, data: a.data, encode: { columns: a.columns } },
962
+ manifest: { reads: a.manifest.reads, acts: [] },
963
+ placement: { slot: "automation" }
964
+ };
965
+ }
966
+ function describeAutomation(a, m, opts = {}) {
967
+ const locale = opts.locale ?? m.defaultLocale;
968
+ const d = describeDraft(automationAsDraft(a), m, { locale });
969
+ const looks = d.lines[0].replace(/\.$/, "");
970
+ const lines = [`${describeSchedule(a.schedule, m)}, checks: ${looks.charAt(0).toLowerCase()}${looks.slice(1)}.`];
971
+ const changes = [];
972
+ const steps = automationSteps(a);
973
+ const notify = steps.find(isNotify);
974
+ const intents = steps.filter((x) => !isNotify(x));
975
+ const each = a.repeat === "new" ? "new " : "";
976
+ const labelOf = (name) => {
977
+ const i = m.intents[name];
978
+ return typeof i?.label === "string" ? i.label : i?.label ? localize(i.label, locale, m.defaultLocale) : name;
979
+ };
980
+ if (intents.length) {
981
+ const labels = intents.map((x) => labelOf(x.intent));
982
+ lines.push(`For each ${each}matching row, runs ${labels.join(", then ")} without asking.`);
983
+ if (intents.length > 1) lines.push("A row goes to the next step only when the one before it succeeded; one that fails resumes there on the next run.");
984
+ for (const l of labels) changes.push(`${l} for each ${each}row, unattended`);
985
+ }
986
+ if (notify) {
987
+ const ch = channelLabel(m, notify.notify);
988
+ if (intents.length) lines.push(`${a.when === "always" ? "Every time, even when there were none, sends" : "Then sends"} you the rows it handled by ${ch}.`);
989
+ else if (a.when === "always")
990
+ lines.push(`Sends you ${a.repeat === "new" ? "the rows that are new since last time" : "the matching rows"} by ${ch} every time, even when there are none.`);
991
+ else lines.push(`If ${a.repeat === "new" ? "any row is new since last time" : "any rows match"}, sends ${a.repeat === "new" ? "them" : "them all"} to you by ${ch}.`);
992
+ changes.push(`Sends ${ch} to you only`);
993
+ }
994
+ if (a.repeat === "new") lines.push("A row is reported once, the first time it matches.");
995
+ const cap = Math.min(MAX_REPORTED_ROWS, ...intents.map((x) => m.intents[x.intent]?.batch ?? 1));
996
+ lines.push(`At most ${cap} ${cap === 1 ? "row" : "rows"} per run.`);
997
+ return { title: localize(a.title, locale, m.defaultLocale), lines, reads: d.reads, changes };
998
+ }
999
+ function localParts(at2, timeZone) {
1000
+ const f = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23", weekday: "short" });
1001
+ const parts = Object.fromEntries(f.formatToParts(at2).map((p) => [p.type, p.value]));
1002
+ return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour) % 24, weekday: parts.weekday.toLowerCase().slice(0, 3) };
1003
+ }
1004
+ function shiftDate(date, days) {
1005
+ const d = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
1006
+ d.setUTCDate(d.getUTCDate() + days);
1007
+ return { date: d.toISOString().slice(0, 10), weekday: WEEKDAYS[(d.getUTCDay() + 6) % 7] };
1008
+ }
1009
+ function lastSlot(s, now, timeZone = "UTC") {
1010
+ const here = localParts(now, timeZone);
1011
+ const key = (date, hour) => `${date}T${String(hour).padStart(2, "0")}`;
1012
+ if (s.every === "hour") return key(here.date, here.hour);
1013
+ const at2 = s.at ?? 0;
1014
+ for (let back = 0; back < 40; back++) {
1015
+ const { date, weekday } = shiftDate(here.date, -back);
1016
+ if (back === 0 && here.hour < at2) continue;
1017
+ const ok = s.every === "day" || s.every === "weekday" && !["sat", "sun"].includes(weekday) || s.every === "week" && weekday === s.on || s.every === "month" && Number(date.slice(8, 10)) === s.day;
1018
+ if (ok) return key(date, at2);
1019
+ }
1020
+ return key(here.date, at2);
1021
+ }
1022
+ function isDue(s, opts) {
1023
+ const tz = opts.timeZone ?? "UTC";
1024
+ const slot = lastSlot(s, opts.now, tz);
1025
+ const since = localParts(new Date(opts.lastRunAt ?? opts.createdAt), tz);
1026
+ return `${since.date}T${String(since.hour).padStart(2, "0")}` < slot;
1027
+ }
1028
+ var ALERT_AFTER_FAILURES = 3;
1029
+ var MAX_SEEN = 2e3;
1030
+ async function runAutomation(r, opts) {
1031
+ const out = await runOnce(r, opts);
1032
+ const before = r.state ?? {};
1033
+ const s = out.state;
1034
+ if (s.lastStatus === "broken") {
1035
+ if (before.lastStatus !== "broken") out.alert = { kind: "broken", automationId: r.id, title: titleOf(r.automation, opts), message: s.lastMessage ?? "" };
1036
+ return out;
1037
+ }
1038
+ if (!out.ran) return out;
1039
+ s.failures = s.lastStatus === "error" ? (before.failures ?? 0) + 1 : void 0;
1040
+ if (s.failures === ALERT_AFTER_FAILURES) out.alert = { kind: "failing", automationId: r.id, title: titleOf(r.automation, opts), message: s.lastMessage ?? "" };
1041
+ return out;
1042
+ }
1043
+ function titleOf(a, opts) {
1044
+ const m = opts.manifest;
1045
+ const t = a?.title;
1046
+ if (t && typeof t === "object") return localize(t, opts.locale ?? m.defaultLocale, m.defaultLocale) || "Automation";
1047
+ return "Automation";
1048
+ }
1049
+ async function queryRows(ir, today, opts) {
1050
+ if (opts.query) return opts.query(ir, { today });
1051
+ const load = opts.load;
1052
+ if (!load) throw new BisqueError("runAutomation needs load or query");
1053
+ const touched = [ir.scan, ...(ir.join ?? []).map((j) => j.to)];
1054
+ const loaded = /* @__PURE__ */ new Map();
1055
+ await Promise.all(touched.map(async (res) => loaded.set(res, await load(res))));
1056
+ return runIR(
1057
+ ir,
1058
+ (res) => {
1059
+ const rows = loaded.get(res);
1060
+ if (!rows) throw new BisqueError(`resource ${res} was not loaded`);
1061
+ return rows;
1062
+ },
1063
+ { manifest: opts.manifest, today }
1064
+ );
1065
+ }
1066
+ async function runOnce(r, opts) {
1067
+ const m = opts.manifest;
1068
+ const now = opts.now ?? /* @__PURE__ */ new Date();
1069
+ const state = { ...r.state };
1070
+ const v = validateAutomation(r.automation, m, { role: r.role });
1071
+ if (!v.ok || !v.automation) {
1072
+ return {
1073
+ ran: false,
1074
+ state: {
1075
+ ...state,
1076
+ lastStatus: "broken",
1077
+ lastMessage: v.problems.map((p) => p.message).join("; ").slice(0, 500)
1078
+ },
1079
+ problems: v.problems
1080
+ };
1081
+ }
1082
+ const a = v.automation;
1083
+ const tz = m.automations?.timeZone ?? "UTC";
1084
+ if (!opts.force && !isDue(a.schedule, { now, lastRunAt: state.lastRunAt, createdAt: r.createdAt, timeZone: tz })) return { ran: false, state };
1085
+ const done = (s) => ({ ran: true, state: { ...state, ...s, lastRunAt: now.toISOString() } });
1086
+ try {
1087
+ const today = localParts(now, tz).date;
1088
+ const result = await queryRows(a.data, today, opts);
1089
+ const keyOf = (row) => a.key ? String(row[a.key] ?? "") : canonicalJson(row);
1090
+ const seen = new Set(state.seen ?? []);
1091
+ const fresh = a.repeat === "new" ? result.rows.filter((row) => !seen.has(keyOf(row))) : result.rows;
1092
+ const report = fresh.slice(0, MAX_REPORTED_ROWS);
1093
+ const nextSeen = a.repeat === "new" ? [...state.seen ?? [], ...report.map(keyOf)].slice(-MAX_SEEN) : state.seen;
1094
+ if (!report.length && a.when === "rows") return done({ lastStatus: "quiet", lastCount: 0, lastMessage: void 0, seen: nextSeen });
1095
+ const steps = automationSteps(a);
1096
+ const notify = steps.find(isNotify);
1097
+ const intents = steps.filter((x) => !isNotify(x));
1098
+ const sendTo = async (rows) => {
1099
+ if (!notify) return;
1100
+ if (!opts.notify) throw new BisqueError("this host has no channel sender");
1101
+ const d = describeAutomation(a, m, { locale: opts.locale });
1102
+ const columns = a.columns.map((c) => ({
1103
+ field: c.field,
1104
+ label: c.label ? localize(c.label, opts.locale ?? m.defaultLocale, m.defaultLocale) : columnLabel2(v.columns[c.field], c.field),
1105
+ format: c.format
1106
+ }));
1107
+ await opts.notify({ channel: notify.notify, automationId: r.id, title: d.title, lines: d.lines, columns, rows, matched: result.total, more: fresh.length - rows.length });
1108
+ };
1109
+ if (!intents.length) {
1110
+ await sendTo(report);
1111
+ return done({ lastStatus: "sent", lastCount: report.length, lastMessage: void 0, seen: nextSeen, progress: void 0 });
1112
+ }
1113
+ if (!opts.act) throw new BisqueError("this host cannot run intents from automations");
1114
+ const cap = Math.min(...intents.map((x) => m.intents[x.intent]?.batch ?? 1), MAX_REPORTED_ROWS);
1115
+ const batch = report.slice(0, cap);
1116
+ const progress = { ...state.progress };
1117
+ const failed = [];
1118
+ const finished = [];
1119
+ for (const row of batch) {
1120
+ const k = keyOf(row);
1121
+ let step = progress[k] ?? 0;
1122
+ for (; step < intents.length; step++) {
1123
+ const res = await opts.act(intents[step].intent, evalArgs(intents[step].args, { row, today }));
1124
+ if (!res.ok) {
1125
+ failed.push(res.message ?? "failed");
1126
+ break;
1127
+ }
1128
+ }
1129
+ if (step < intents.length) progress[k] = step;
1130
+ else {
1131
+ delete progress[k];
1132
+ finished.push(row);
1133
+ }
1134
+ }
1135
+ const finishedKeys = finished.map(keyOf);
1136
+ const seenAfter = a.repeat === "new" ? [...state.seen ?? [], ...finishedKeys].slice(-MAX_SEEN) : state.seen;
1137
+ const live = new Set(result.rows.map(keyOf));
1138
+ for (const k of Object.keys(progress)) if (!live.has(k)) delete progress[k];
1139
+ if (notify && (finished.length || a.when === "always")) await sendTo(finished);
1140
+ return done({
1141
+ lastStatus: failed.length ? "error" : notify && (finished.length || a.when === "always") ? "sent" : "acted",
1142
+ lastCount: finished.length,
1143
+ lastMessage: failed.length ? `${failed.length} of ${batch.length} failed: ${failed[0]}`.slice(0, 500) : void 0,
1144
+ seen: seenAfter,
1145
+ progress: Object.keys(progress).length ? progress : void 0
1146
+ });
1147
+ } catch (e) {
1148
+ const problems = e instanceof BisqueError ? e.problems : [];
1149
+ return { ran: true, state: { ...state, lastRunAt: now.toISOString(), lastStatus: "error", lastMessage: (e instanceof Error ? e.message : String(e)).slice(0, 500) }, problems };
1150
+ }
1151
+ }
1152
+ function columnLabel2(c, field) {
1153
+ if (c?.label) return c.label;
1154
+ const base = field.includes(".") ? field.slice(field.indexOf(".") + 1) : field;
1155
+ return base.replace(/_/g, " ");
1156
+ }
1157
+ var AUTOMATION_GUIDE = `## Automation format (propose_automation.automation)
1158
+
1159
+ {
1160
+ "kind": "automation",
1161
+ "title": { "<locale>": "\u226480 chars", ... },
1162
+ "schedule": { "every": "day" } | { "every": "weekday" } | { "every": "week", "on": "mon"|"tue"|"wed"|"thu"|"fri"|"sat"|"sun" } | { "every": "month", "day": 1-28 } | { "every": "hour" },
1163
+ // add "at": 0-23 (hour) only when the reference says automations are checked every hour
1164
+ "data": <query>, // same query format as a spec; no params: use { "today": n } for relative dates
1165
+ "when": "rows" | "always", // rows: only when there is something to report; always: a digest every time (notify only)
1166
+ "repeat": "new" | "all", // new: report each row once, the first time it matches; all: every matching row every time
1167
+ "key": "<output column that identifies a row, e.g. id>", // required for repeat "new"
1168
+ "columns": [{ "field": col, "label"?: {..}, "format"?: "number"|"money"|"percent"|"date"|"month"|"text" }], // what the message shows, 1-8
1169
+ "then": <step> | [<step>, ...], // one step, or a workflow of up to 4: intents run in order per row, then at most one notify, last
1170
+ // <step>: { "notify": "<channel>" } | { "intent": "<automatable intent>", "args": { "<arg>": <argExpr without input/param> } }
1171
+ "manifest": { "reads": [resources the query touches], "acts": [the intents the steps call, in order, no repeats], "channels": [the notify step's channel, if any] }
1172
+ }
1173
+ Notifications always go to the user who owns the automation; never ask for or write an address.
1174
+ "for more than N days" on a date field is ["<field>", "<", { "today": -N }]. Prefer repeat "new" with key "id" for alerts, so the user is told once per row.
1175
+ "Do X, then email me" is a workflow: [{ "intent": "x", ... }, { "notify": "email" }]; the message lists the rows every intent step succeeded for.`;
1176
+ function sameAutomation(a, b) {
1177
+ return canonicalJson(a) === canonicalJson(b);
1178
+ }
1179
+
1180
+ // src/protocol.ts
1181
+ var ContextValue = z4.union([z4.string().max(64), z4.number(), z4.boolean(), z4.null()]);
1182
+ var ProposeRequestSchema = z4.object({
1183
+ /** What the user typed: their own disclosure (§3.4). */
1184
+ prompt: z4.string().min(1).max(4e3),
1185
+ context: z4.object({
1186
+ page: z4.string().max(200).optional(),
1187
+ slot: z4.string().max(80).optional(),
1188
+ locale: z4.string().max(10),
1189
+ /** Only keys the contract declares in `context`; the conductor rejects others. */
1190
+ values: z4.record(z4.string().max(40), ContextValue).default({})
1191
+ }).strict(),
1192
+ contract: z4.object({ app: z4.string().max(80), version: z4.string().max(40), hash: z4.string().regex(/^[0-9a-f]{64}$/) }).strict(),
1193
+ /** Prior turns as text the user typed and short assistant replies; no data. */
1194
+ history: z4.array(z4.object({ role: z4.enum(["user", "assistant"]), text: z4.string().max(4e3) }).strict()).max(20).default([]),
1195
+ /** The draft being refined, when the user is revising a proposal or a saved artifact. */
1196
+ current: DraftSchema.optional(),
1197
+ /** Values of fields the host marks `values: "share"` (P1 exception a), keyed `resource.field`. */
1198
+ sharedValues: z4.record(z4.string().max(80), z4.array(z4.string().max(120)).max(500)).optional(),
1199
+ /**
1200
+ * Current values of the contract's theme tokens, sent only when the host
1201
+ * lets users change the theme by asking. Host settings, not records:
1202
+ * typed colours, lengths and options.
1203
+ */
1204
+ theme: z4.record(z4.string().max(40), z4.string().max(64)).optional(),
1205
+ /**
1206
+ * True when the host takes automation proposals here and this user may
1207
+ * make them. Absent or false: the conductor answers schedule and
1208
+ * delivery requests with explain_limit.
1209
+ */
1210
+ automations: z4.boolean().optional(),
1211
+ /** The automation being refined, when the user is revising one. */
1212
+ currentAutomation: AutomationSchema.optional()
1213
+ }).strict();
1214
+ var PushRequestSchema = z4.object({
1215
+ manifest: z4.record(z4.string(), z4.unknown()),
1216
+ review: z4.object({ contractHash: z4.string().regex(/^[0-9a-f]{64}$/), signer: z4.string().min(1).max(200), signedAt: z4.string() }).passthrough()
1217
+ }).strict();
1218
+
1219
+ // src/theme.ts
1220
+ import { problem as problem3 } from "@crasi/bisque-core";
1221
+ import { canWorkspace, themeLabel } from "@crasi/bisque-contract";
1222
+ var THEME_COLOR = /^(#[0-9a-f]{3,4}|#[0-9a-f]{6}|#[0-9a-f]{8}|(rgb|hsl)a?\(\s*[\d.]+%?\s*,?\s*[\d.]+%?\s*,?\s*[\d.]+%?\s*([,/]\s*[\d.]+%?\s*)?\))$/i;
1223
+ var THEME_LENGTH = /^\d{1,3}(\.\d{1,2})?(px|rem|em)$/;
1224
+ var MAX_TOKENS = 32;
1225
+ function themeValueOk(m, token, value) {
1226
+ const t = m.theme?.[token];
1227
+ if (!t || typeof value !== "string" || value.length > 64) return false;
1228
+ if (t === "color") return THEME_COLOR.test(value);
1229
+ if (t === "length") return THEME_LENGTH.test(value);
1230
+ return Array.isArray(t) && t.includes(value);
1231
+ }
1232
+ function validateThemeTokens(input, m, opts) {
1233
+ const P = [];
1234
+ const tokens = {};
1235
+ const declared = Object.keys(m.theme ?? {});
1236
+ if (!declared.length) return { ok: false, problems: [problem3("", "deferred", "this app declares no theme tokens, so its look cannot be changed by asking")], tokens };
1237
+ if (!input || typeof input !== "object" || Array.isArray(input))
1238
+ return { ok: false, problems: [problem3("tokens", "schema", "tokens must be an object of token name to value")], tokens };
1239
+ const entries = Object.entries(input);
1240
+ if (!entries.length) P.push(problem3("tokens", "schema", "propose at least one token"));
1241
+ if (entries.length > MAX_TOKENS) P.push(problem3("tokens", "limit", `at most ${MAX_TOKENS} tokens`));
1242
+ for (const [k, v] of entries) {
1243
+ const path = `tokens.${k}`;
1244
+ const t = m.theme[k];
1245
+ if (!t) {
1246
+ P.push(problem3(path, "unknown_field", `"${k}" is not a theme token (tokens: ${declared.join(", ")})`));
1247
+ continue;
1248
+ }
1249
+ if (!themeValueOk(m, k, v)) {
1250
+ const want = Array.isArray(t) ? `one of ${t.join(", ")}` : t === "color" ? "a hex colour like #0f5c8a" : "a length like 8px";
1251
+ P.push(problem3(path, "type", `${k} must be ${want}`));
1252
+ continue;
1253
+ }
1254
+ tokens[k] = v;
1255
+ }
1256
+ if (!canWorkspace(m, opts.role)) P.push(problem3("", "role_denied", `role ${opts.role} cannot change the workspace theme; only workspace admins can`));
1257
+ return { ok: P.length === 0, problems: P, tokens };
1258
+ }
1259
+ function describeTheme(before, after, m) {
1260
+ const lines = [];
1261
+ for (const k of Object.keys(m.theme ?? {})) {
1262
+ if (!(k in after) || after[k] === before[k]) continue;
1263
+ const label = themeLabel(m, k);
1264
+ lines.push(`${label.charAt(0).toUpperCase()}${label.slice(1)}: ${before[k] ?? "default"} \u2192 ${after[k]}`);
1265
+ }
1266
+ return lines.length ? lines : ["No change."];
1267
+ }
1268
+ function mergeTheme(current, proposed, m) {
1269
+ const out = {};
1270
+ for (const [k, v] of Object.entries({ ...current, ...proposed })) if (themeValueOk(m, k, v)) out[k] = v;
1271
+ return out;
1272
+ }
1273
+
1274
+ // src/template.ts
1275
+ import { z as z5 } from "zod";
1276
+ import { problem as problem4 } from "@crasi/bisque-core";
1277
+ var TemplateSchema = z5.object({
1278
+ format: z5.literal(1),
1279
+ kind: z5.literal("template"),
1280
+ app: z5.string().min(1).max(80),
1281
+ /** The contract version the template was made against. */
1282
+ contractVersion: z5.string().max(40),
1283
+ draft: DraftSchema
1284
+ }).strict();
1285
+ function toTemplate(draft, m) {
1286
+ return { format: 1, kind: "template", app: m.app, contractVersion: m.version, draft: structuredClone(draft) };
1287
+ }
1288
+ var DISPLAY_KEYS = /* @__PURE__ */ new Set(["title", "label"]);
1289
+ function templateDisclosure(draft) {
1290
+ const text = /* @__PURE__ */ new Set();
1291
+ const values = /* @__PURE__ */ new Set();
1292
+ const walkDisplay = (v, display) => {
1293
+ if (typeof v === "string") {
1294
+ if (display) text.add(v);
1295
+ return;
1296
+ }
1297
+ if (Array.isArray(v)) return v.forEach((x) => walkDisplay(x, display));
1298
+ if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) walkDisplay(x, display || DISPLAY_KEYS.has(k));
1299
+ };
1300
+ walkDisplay(draft.body, false);
1301
+ walkDisplay(draft.placement, false);
1302
+ for (const c of draft.body.data.where ?? []) {
1303
+ if (c.length < 3) continue;
1304
+ const raw = c[2];
1305
+ for (const x of Array.isArray(raw) ? raw : [raw]) if (typeof x === "string") values.add(x);
1306
+ }
1307
+ const walkArgs = (e) => {
1308
+ if ("literal" in e)
1309
+ for (const x of Array.isArray(e.literal) ? e.literal : [e.literal]) {
1310
+ if (typeof x === "string") values.add(x);
1311
+ }
1312
+ else if ("template" in e) text.add(e.template);
1313
+ else if ("list" in e) e.list.forEach(walkArgs);
1314
+ };
1315
+ const b = draft.body;
1316
+ if (b.onClick) Object.values(b.onClick.args).forEach(walkArgs);
1317
+ if (b.component === "actionTable") Object.values(b.encode.action.args).forEach(walkArgs);
1318
+ if (b.component === "grid") {
1319
+ for (const col of b.encode.columns) if (col.edit) Object.values(col.edit.args).forEach(walkArgs);
1320
+ }
1321
+ return { text: [...text], values: [...values] };
1322
+ }
1323
+ function fromTemplate(input, m, opts) {
1324
+ const parsed = TemplateSchema.safeParse(input);
1325
+ if (!parsed.success) return { ok: false, migrated: false, problems: parsed.error.issues.map((i) => problem4(i.path.join("."), "schema", i.message)) };
1326
+ const t = parsed.data;
1327
+ if (t.app !== m.app) return { ok: false, migrated: false, problems: [problem4("app", "schema", `this template is for ${t.app}, not ${m.app}`)] };
1328
+ const migrated = opts.renames ? migrateDraft(t.draft, opts.renames) : null;
1329
+ const v = validateDraft(migrated ?? t.draft, m, { role: opts.role });
1330
+ return { ok: v.ok, problems: v.problems, draft: v.draft, migrated: !!migrated };
1331
+ }
1332
+ export {
1333
+ ALERT_AFTER_FAILURES,
1334
+ AUTOMATION_GUIDE,
1335
+ ActionTableSpec,
1336
+ AreaSpec,
1337
+ ArgExprSchema,
1338
+ Args,
1339
+ ArtifactManifestSchema,
1340
+ AutomationActionSchema,
1341
+ AutomationSchema,
1342
+ AutomationThenSchema,
1343
+ BarSpec,
1344
+ CATALOG_LINE,
1345
+ DiagnosticsSchema,
1346
+ DraftSchema,
1347
+ FORMATS,
1348
+ Format,
1349
+ GridSpec,
1350
+ KpiSpec,
1351
+ Label,
1352
+ LineSpec,
1353
+ MAX_REPORTED_ROWS,
1354
+ MAX_STEPS,
1355
+ ParamSchema,
1356
+ Placement,
1357
+ ProposeRequestSchema,
1358
+ PushRequestSchema,
1359
+ RENDER_ERRORS,
1360
+ RowInput,
1361
+ SPEC_GUIDE,
1362
+ SankeySpec,
1363
+ ScheduleSchema,
1364
+ SpecBody,
1365
+ THEME_COLOR,
1366
+ THEME_LENGTH,
1367
+ TableSpec,
1368
+ TemplateSchema,
1369
+ Title,
1370
+ WEEKDAYS,
1371
+ adjustables,
1372
+ applyAdjustment,
1373
+ automationAsDraft,
1374
+ automationSteps,
1375
+ compatibleComponents,
1376
+ describeAutomation,
1377
+ describeDraft,
1378
+ describeSchedule,
1379
+ describeTheme,
1380
+ diffDrafts,
1381
+ encodeColumns,
1382
+ evalArg,
1383
+ evalArgs,
1384
+ fromTemplate,
1385
+ invoked,
1386
+ isDue,
1387
+ lastSlot,
1388
+ localize,
1389
+ mergeTheme,
1390
+ migrateDraft,
1391
+ renderDiagnostics,
1392
+ repairReason,
1393
+ runAutomation,
1394
+ sameAutomation,
1395
+ switchComponent,
1396
+ templateDisclosure,
1397
+ themeValueOk,
1398
+ toTemplate,
1399
+ unsafeTextProblems,
1400
+ validateAutomation,
1401
+ validateDraft,
1402
+ validateThemeTokens
1403
+ };
1404
+ //# sourceMappingURL=index.js.map