@composable-os/sdk 0.0.0-stage → 0.1.0-beta.8
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/LICENSE +109 -0
- package/dist/automation-check.d.ts +38 -0
- package/dist/automation-check.js +454 -0
- package/dist/automation.d.ts +767 -0
- package/dist/automation.js +303 -0
- package/dist/behaviour.d.ts +3 -0
- package/dist/behaviour.js +153 -0
- package/dist/capacity.d.ts +51 -0
- package/dist/capacity.js +68 -0
- package/dist/contract.d.ts +706 -0
- package/dist/contract.js +42 -0
- package/dist/document.d.ts +165 -0
- package/dist/document.js +636 -0
- package/dist/field-types.d.ts +11 -0
- package/dist/field-types.js +93 -0
- package/dist/formula/ast.d.ts +67 -0
- package/dist/formula/ast.js +22 -0
- package/dist/formula/compile.d.ts +37 -0
- package/dist/formula/compile.js +379 -0
- package/dist/formula/index.d.ts +3 -0
- package/dist/formula/index.js +4 -0
- package/dist/formula/parser.d.ts +13 -0
- package/dist/formula/parser.js +365 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +21 -0
- package/dist/manifest.d.ts +1131 -0
- package/dist/manifest.js +1229 -0
- package/dist/media.d.ts +9 -0
- package/dist/media.js +43 -0
- package/dist/permissions.d.ts +17 -0
- package/dist/permissions.js +44 -0
- package/dist/renamed.d.ts +16 -0
- package/dist/renamed.js +59 -0
- package/dist/rich-text-fixture.d.ts +121 -0
- package/dist/rich-text-fixture.js +67 -0
- package/dist/rich-text.d.ts +34 -0
- package/dist/rich-text.js +138 -0
- package/dist/runtime.d.ts +95 -0
- package/dist/runtime.js +312 -0
- package/dist/sellable.d.ts +103 -0
- package/dist/sellable.js +258 -0
- package/dist/slug.d.ts +11 -0
- package/dist/slug.js +23 -0
- package/dist/states.d.ts +64 -0
- package/dist/states.js +101 -0
- package/dist/testing.d.ts +151 -0
- package/dist/testing.js +670 -0
- package/package.json +34 -4
- package/src/automation-check.ts +534 -0
- package/src/automation.ts +743 -0
- package/src/behaviour.ts +215 -0
- package/src/capacity.ts +112 -0
- package/src/contract.ts +766 -0
- package/src/document.ts +788 -0
- package/src/field-types.ts +106 -0
- package/src/formula/ast.ts +72 -0
- package/src/formula/compile.ts +454 -0
- package/src/formula/index.ts +4 -0
- package/src/formula/parser.ts +417 -0
- package/src/index.ts +33 -0
- package/src/manifest.ts +1484 -0
- package/src/media.ts +46 -0
- package/src/permissions.ts +60 -0
- package/src/renamed.ts +63 -0
- package/src/rich-text-fixture.ts +68 -0
- package/src/rich-text.ts +173 -0
- package/src/runtime.ts +410 -0
- package/src/sellable.ts +396 -0
- package/src/slug.ts +25 -0
- package/src/states.ts +162 -0
- package/src/testing.ts +836 -0
- package/README.md +0 -3
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// Automations (ADR 0028, ADR 0130, ADR 0131): `defineAutomation` declares a trigger, optional
|
|
2
|
+
// declarative conditions, the steps it takes (with their intents: what they read, write, notify
|
|
3
|
+
// and wait for) and a `run` handler shaped like a Cloudflare Workflow. The host renders the
|
|
4
|
+
// plain-English summary and step diagram from the declarations alone (no AI), evaluates the
|
|
5
|
+
// conditions before it starts a run, and runs `run` durably on Cloudflare Workflows: every
|
|
6
|
+
// `step.do` executes in a Dynamic Worker as actor `automation` under the extension principal.
|
|
7
|
+
//
|
|
8
|
+
// The declarations are the contract the diagram, the summary and the approval screen show, so the
|
|
9
|
+
// runtime holds `run` to them: every `step.do` / `step.sleep` / `step.waitForEvent` name must be a
|
|
10
|
+
// declared step of the matching kind. Effects a step did not declare are still gated at run time
|
|
11
|
+
// (and flagged in the run history), never silently allowed.
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { GATEKEEPER_MODULES, } from "./contract.js";
|
|
14
|
+
const UNIT_MS = {
|
|
15
|
+
second: 1_000,
|
|
16
|
+
minute: 60_000,
|
|
17
|
+
hour: 3_600_000,
|
|
18
|
+
day: 86_400_000,
|
|
19
|
+
week: 604_800_000,
|
|
20
|
+
};
|
|
21
|
+
/** Milliseconds in a duration. Throws on a malformed one. */
|
|
22
|
+
export function durationMs(duration) {
|
|
23
|
+
if (typeof duration === "number") {
|
|
24
|
+
if (!Number.isFinite(duration) || duration < 0)
|
|
25
|
+
throw new Error("Durations are >= 0 ms");
|
|
26
|
+
return duration;
|
|
27
|
+
}
|
|
28
|
+
const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/.exec(duration);
|
|
29
|
+
if (!match)
|
|
30
|
+
throw new Error(`"${duration}" is not a duration like "3 days" or "90 minutes"`);
|
|
31
|
+
return Math.round(Number(match[1]) * UNIT_MS[match[2]]);
|
|
32
|
+
}
|
|
33
|
+
// ---------------------------------------------------------------------------------------------
|
|
34
|
+
// Triggers
|
|
35
|
+
/** Record lifecycle events every core and extension object emits after commit. */
|
|
36
|
+
export const RECORD_EVENTS = ["created", "updated", "deleted", "restored"];
|
|
37
|
+
/**
|
|
38
|
+
* Sync events (stage 6, ADR 0112): what the built-in email and calendar sync records when it
|
|
39
|
+
* writes, updates or removes an activity. `meeting.scheduled` is a new meeting (the sync service
|
|
40
|
+
* records it as `meeting.created`; both names match it).
|
|
41
|
+
*/
|
|
42
|
+
export const SYNC_EVENT_TYPES = [
|
|
43
|
+
"email.received",
|
|
44
|
+
"email.sent",
|
|
45
|
+
"email.deleted",
|
|
46
|
+
"meeting.scheduled",
|
|
47
|
+
"meeting.created",
|
|
48
|
+
"meeting.updated",
|
|
49
|
+
"meeting.cancelled",
|
|
50
|
+
];
|
|
51
|
+
export const AUTOMATION_TRIGGER_TYPES = [
|
|
52
|
+
"record",
|
|
53
|
+
"fieldChanged",
|
|
54
|
+
"schedule",
|
|
55
|
+
"dateRelative",
|
|
56
|
+
"manual",
|
|
57
|
+
"approvalDecided",
|
|
58
|
+
"webhook",
|
|
59
|
+
"syncEvent",
|
|
60
|
+
];
|
|
61
|
+
export function defineAutomation(automation) {
|
|
62
|
+
return automation;
|
|
63
|
+
}
|
|
64
|
+
// ---------------------------------------------------------------------------------------------
|
|
65
|
+
// Manifest form (JSON: no handler). Stored in core_automations.spec.
|
|
66
|
+
const scalar = z.union([z.string().max(500), z.number(), z.boolean(), z.null()]);
|
|
67
|
+
export const valueMatchSchema = z.union([
|
|
68
|
+
scalar,
|
|
69
|
+
z.object({ in: z.array(scalar).min(1).max(50) }).strict(),
|
|
70
|
+
z.object({ stageType: z.enum(["open", "won", "lost"]) }).strict(),
|
|
71
|
+
]);
|
|
72
|
+
const objectName = z.string().min(1).max(80);
|
|
73
|
+
const fieldName = z.string().min(1).max(80);
|
|
74
|
+
export const automationTriggerSchema = z.discriminatedUnion("type", [
|
|
75
|
+
z
|
|
76
|
+
.object({
|
|
77
|
+
type: z.literal("record"),
|
|
78
|
+
object: objectName,
|
|
79
|
+
on: z.array(z.enum(RECORD_EVENTS)).min(1).max(4),
|
|
80
|
+
includeBulk: z.boolean().optional(),
|
|
81
|
+
})
|
|
82
|
+
.strict(),
|
|
83
|
+
z
|
|
84
|
+
.object({
|
|
85
|
+
type: z.literal("fieldChanged"),
|
|
86
|
+
object: objectName,
|
|
87
|
+
field: fieldName,
|
|
88
|
+
from: valueMatchSchema.optional(),
|
|
89
|
+
to: valueMatchSchema.optional(),
|
|
90
|
+
includeBulk: z.boolean().optional(),
|
|
91
|
+
})
|
|
92
|
+
.strict(),
|
|
93
|
+
z.object({ type: z.literal("schedule"), cron: z.string().min(9).max(100) }).strict(),
|
|
94
|
+
z
|
|
95
|
+
.object({
|
|
96
|
+
type: z.literal("dateRelative"),
|
|
97
|
+
object: objectName,
|
|
98
|
+
field: fieldName,
|
|
99
|
+
offsetDays: z.number().int().min(-365).max(365),
|
|
100
|
+
zoneField: fieldName.optional(),
|
|
101
|
+
})
|
|
102
|
+
.strict(),
|
|
103
|
+
z
|
|
104
|
+
.object({
|
|
105
|
+
type: z.literal("manual"),
|
|
106
|
+
object: objectName,
|
|
107
|
+
label: z.string().min(1).max(60),
|
|
108
|
+
bulk: z.boolean().optional(),
|
|
109
|
+
})
|
|
110
|
+
.strict(),
|
|
111
|
+
z
|
|
112
|
+
.object({
|
|
113
|
+
type: z.literal("approvalDecided"),
|
|
114
|
+
decision: z.enum(["approved", "rejected", "any"]).optional(),
|
|
115
|
+
operation: z.string().max(100).optional(),
|
|
116
|
+
object: objectName.optional(),
|
|
117
|
+
})
|
|
118
|
+
.strict(),
|
|
119
|
+
z
|
|
120
|
+
.object({
|
|
121
|
+
type: z.literal("webhook"),
|
|
122
|
+
endpoint: z
|
|
123
|
+
.string()
|
|
124
|
+
.min(1)
|
|
125
|
+
.max(64)
|
|
126
|
+
.regex(/^[a-z0-9][a-z0-9_-]*$/, "Endpoint ids are lowercase letters, digits, - and _"),
|
|
127
|
+
events: z.array(z.string().min(1).max(200)).min(1).max(50).optional(),
|
|
128
|
+
})
|
|
129
|
+
.strict(),
|
|
130
|
+
z
|
|
131
|
+
.object({
|
|
132
|
+
type: z.literal("syncEvent"),
|
|
133
|
+
event: z.enum(SYNC_EVENT_TYPES),
|
|
134
|
+
from: z.enum(["person", "organisation", "either"]).optional(),
|
|
135
|
+
})
|
|
136
|
+
.strict(),
|
|
137
|
+
]);
|
|
138
|
+
export const automationConnectionSchema = z
|
|
139
|
+
.object({
|
|
140
|
+
id: z.string().min(1).max(40),
|
|
141
|
+
gatekeeper: z.enum(GATEKEEPER_MODULES),
|
|
142
|
+
purpose: z.string().min(1).max(200),
|
|
143
|
+
})
|
|
144
|
+
.strict();
|
|
145
|
+
export const durationSchema = z.union([
|
|
146
|
+
z.number().int().min(0),
|
|
147
|
+
z.string().regex(/^\s*\d+(?:\.\d+)?\s+(second|minute|hour|day|week)s?\s*$/),
|
|
148
|
+
]);
|
|
149
|
+
export const recipientSchema = z.union([
|
|
150
|
+
z.literal("admins"),
|
|
151
|
+
z.literal("actor"),
|
|
152
|
+
z.object({ field: fieldName }).strict(),
|
|
153
|
+
z.object({ managerOf: fieldName }).strict(),
|
|
154
|
+
z.object({ userId: z.string().min(1).max(64) }).strict(),
|
|
155
|
+
]);
|
|
156
|
+
const writeIntentSchema = z
|
|
157
|
+
.object({
|
|
158
|
+
object: objectName,
|
|
159
|
+
action: z.enum(["create", "update", "delete"]).optional(),
|
|
160
|
+
count: z.number().int().min(1).max(10_000).optional(),
|
|
161
|
+
titles: z.array(z.string().max(200)).max(50).optional(),
|
|
162
|
+
assignTo: recipientSchema.optional(),
|
|
163
|
+
linkedToTrigger: z.boolean().optional(),
|
|
164
|
+
})
|
|
165
|
+
.strict();
|
|
166
|
+
const notifyIntentSchema = z
|
|
167
|
+
.object({
|
|
168
|
+
to: recipientSchema,
|
|
169
|
+
message: z.string().min(1).max(500),
|
|
170
|
+
body: z.string().min(1).max(2000).optional(),
|
|
171
|
+
})
|
|
172
|
+
.strict();
|
|
173
|
+
const stepName = z.string().min(1).max(60);
|
|
174
|
+
const stepLabel = z.string().min(1).max(120).optional();
|
|
175
|
+
export const automationStepSchema = z.union([
|
|
176
|
+
z
|
|
177
|
+
.object({
|
|
178
|
+
name: stepName,
|
|
179
|
+
label: stepLabel,
|
|
180
|
+
kind: z.literal("do").optional(),
|
|
181
|
+
reads: z.array(objectName).max(50).optional(),
|
|
182
|
+
writes: z.array(writeIntentSchema).max(20).optional(),
|
|
183
|
+
notifies: z.array(notifyIntentSchema).max(20).optional(),
|
|
184
|
+
calls: z.array(z.string().max(100)).max(50).optional(),
|
|
185
|
+
})
|
|
186
|
+
.strict(),
|
|
187
|
+
z
|
|
188
|
+
.object({
|
|
189
|
+
name: stepName,
|
|
190
|
+
label: stepLabel,
|
|
191
|
+
kind: z.literal("sleep"),
|
|
192
|
+
duration: durationSchema,
|
|
193
|
+
})
|
|
194
|
+
.strict(),
|
|
195
|
+
z
|
|
196
|
+
.object({
|
|
197
|
+
name: stepName,
|
|
198
|
+
label: stepLabel,
|
|
199
|
+
kind: z.literal("waitForEvent"),
|
|
200
|
+
event: z.string().min(1).max(100),
|
|
201
|
+
timeout: durationSchema.optional(),
|
|
202
|
+
})
|
|
203
|
+
.strict(),
|
|
204
|
+
z
|
|
205
|
+
.object({
|
|
206
|
+
name: stepName,
|
|
207
|
+
label: z.string().min(1).max(120),
|
|
208
|
+
kind: z.literal("condition"),
|
|
209
|
+
clause: z.string().min(1).max(200).optional(),
|
|
210
|
+
})
|
|
211
|
+
.strict(),
|
|
212
|
+
]);
|
|
213
|
+
const filterOpSchema = z.enum([
|
|
214
|
+
"eq",
|
|
215
|
+
"neq",
|
|
216
|
+
"lt",
|
|
217
|
+
"lte",
|
|
218
|
+
"gt",
|
|
219
|
+
"gte",
|
|
220
|
+
"between",
|
|
221
|
+
"in",
|
|
222
|
+
"not_in",
|
|
223
|
+
"contains",
|
|
224
|
+
"not_contains",
|
|
225
|
+
"starts_with",
|
|
226
|
+
"ends_with",
|
|
227
|
+
"is_null",
|
|
228
|
+
"is_not_null",
|
|
229
|
+
]);
|
|
230
|
+
export const automationConditionSchema = z.lazy(() => z.union([
|
|
231
|
+
z.object({ field: fieldName, op: filterOpSchema, value: z.unknown().optional() }).strict(),
|
|
232
|
+
z.object({ and: z.array(automationConditionSchema).min(1).max(20) }).strict(),
|
|
233
|
+
z.object({ or: z.array(automationConditionSchema).min(1).max(20) }).strict(),
|
|
234
|
+
]));
|
|
235
|
+
export const onRejectedSchema = z.union([
|
|
236
|
+
z.literal("stop"),
|
|
237
|
+
z.literal("continue"),
|
|
238
|
+
z.object({ notify: recipientSchema, message: z.string().max(500).optional() }).strict(),
|
|
239
|
+
]);
|
|
240
|
+
export const automationRailsSchema = z
|
|
241
|
+
.object({
|
|
242
|
+
maxRunsPerMinute: z.number().int().min(1).max(600).optional(),
|
|
243
|
+
maxWritesPerHour: z.number().int().min(1).max(100_000).optional(),
|
|
244
|
+
debounceSeconds: z.number().int().min(0).max(3600).optional(),
|
|
245
|
+
})
|
|
246
|
+
.strict();
|
|
247
|
+
export const automationManifestSchema = z.object({
|
|
248
|
+
label: z.string().min(1).max(100),
|
|
249
|
+
description: z.string().min(1).max(2000),
|
|
250
|
+
trigger: automationTriggerSchema,
|
|
251
|
+
conditions: automationConditionSchema.optional(),
|
|
252
|
+
steps: z.array(automationStepSchema).min(1).max(50),
|
|
253
|
+
onRejected: onRejectedSchema.optional(),
|
|
254
|
+
rails: automationRailsSchema.optional(),
|
|
255
|
+
connections: z.array(automationConnectionSchema).max(10).optional(),
|
|
256
|
+
enabled: z.boolean().optional(),
|
|
257
|
+
});
|
|
258
|
+
/**
|
|
259
|
+
* Turns `ctx.notify(to, message)` into a `notification.send` input for `event`'s run: field and
|
|
260
|
+
* manager recipients point at the trigger record, `"actor"` is whoever started a manual run,
|
|
261
|
+
* `{record}` in the title and body becomes the trigger record's title, and the dedupe key
|
|
262
|
+
* (`<runId>:<key>`, key = `<step name>:<n>` with n counting notify calls within that step, so it is the same on every replay) makes a retried or replayed step send each
|
|
263
|
+
* notification once. Shared by the runtime and the testing harness.
|
|
264
|
+
*/
|
|
265
|
+
export function notificationInput(event, to, message, key) {
|
|
266
|
+
const record = event.record;
|
|
267
|
+
const recipients = Array.isArray(to) ? to : [to];
|
|
268
|
+
const resolved = recipients.map((recipient) => {
|
|
269
|
+
if (recipient === "admins")
|
|
270
|
+
return { role: "admin" };
|
|
271
|
+
if (recipient === "actor") {
|
|
272
|
+
const userId = event.manual?.userId;
|
|
273
|
+
if (!userId)
|
|
274
|
+
throw new Error('"actor" recipients need a manual trigger (a person started it)');
|
|
275
|
+
return { userId };
|
|
276
|
+
}
|
|
277
|
+
if ("userId" in recipient)
|
|
278
|
+
return { userId: recipient.userId };
|
|
279
|
+
if (!record) {
|
|
280
|
+
throw new Error(`A ${event.trigger} run has no trigger record, so ${JSON.stringify(recipient)} cannot be resolved`);
|
|
281
|
+
}
|
|
282
|
+
const ref = { object: record.object, id: record.id };
|
|
283
|
+
return "field" in recipient
|
|
284
|
+
? { field: recipient.field, record: ref }
|
|
285
|
+
: { managerOf: recipient.managerOf, record: ref };
|
|
286
|
+
});
|
|
287
|
+
const title = record?.title ?? "the record";
|
|
288
|
+
const fill = (text) => text.replaceAll("{record}", title);
|
|
289
|
+
const wanted = message.link ?? (record ? "record" : undefined);
|
|
290
|
+
const link = wanted === "run"
|
|
291
|
+
? { kind: "automationRun", automationId: event.automation, runId: event.runId }
|
|
292
|
+
: wanted === "record" && record
|
|
293
|
+
? { kind: "record", object: record.object, id: record.id }
|
|
294
|
+
: undefined;
|
|
295
|
+
return {
|
|
296
|
+
to: resolved,
|
|
297
|
+
type: "automation.message",
|
|
298
|
+
title: fill(message.title).slice(0, 200),
|
|
299
|
+
...(message.body === undefined ? {} : { body: fill(message.body) }),
|
|
300
|
+
...(link ? { link } : {}),
|
|
301
|
+
dedupeKey: `${event.runId}:${key}`.slice(0, 200),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
|
|
2
|
+
/** Reports problems with `objects.<name>`'s behaviour keys through `contract`. */
|
|
3
|
+
export declare function checkObjectBehaviour(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Contract checks for an object's behaviour keys (ADR 0100): indexes, timeline links, the stage
|
|
2
|
+
// behaviour and seed records. Called by validateManifest for every declared object.
|
|
3
|
+
import { STAGE_TYPES } from "./contract.js";
|
|
4
|
+
const NUMERIC = ["number", "percent", "currency"];
|
|
5
|
+
const SEED_KEY_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
|
|
6
|
+
/** Reports problems with `objects.<name>`'s behaviour keys through `contract`. */
|
|
7
|
+
export function checkObjectBehaviour(m, name, object, contract) {
|
|
8
|
+
const path = `objects.${name}`;
|
|
9
|
+
const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
|
|
10
|
+
const isSingle = (field) => field !== undefined && field.type !== "formula" && field.type !== "multiSelect" && !field.many;
|
|
11
|
+
const relationTo = (field) => field?.type === "relation" && !field.many ? field.to : undefined;
|
|
12
|
+
const ownObject = (target) => target?.startsWith(`${m.id}.`) ? m.objects[target.slice(m.id.length + 1)] : undefined;
|
|
13
|
+
(object.indexes ?? []).forEach((columns, i) => {
|
|
14
|
+
if (new Set(columns).size !== columns.length) {
|
|
15
|
+
contract(`${path}.indexes.${i}`, "An index lists each field once");
|
|
16
|
+
}
|
|
17
|
+
for (const column of columns) {
|
|
18
|
+
if (column === "createdAt" || column === "updatedAt")
|
|
19
|
+
continue;
|
|
20
|
+
if (!isSingle(fieldOf(column))) {
|
|
21
|
+
contract(`${path}.indexes.${i}`, `Index field "${column}" must be a single-valued, non-formula field of ${name}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
(object.timelineLinks ?? []).forEach((local, i) => {
|
|
26
|
+
if (!relationTo(fieldOf(local))) {
|
|
27
|
+
contract(`${path}.timelineLinks.${i}`, `"${local}" must be a relation field (one record)`);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
const stages = object.stages;
|
|
31
|
+
if (stages) {
|
|
32
|
+
const sp = `${path}.stages`;
|
|
33
|
+
const stageTarget = relationTo(fieldOf(stages.field));
|
|
34
|
+
const stageObject = ownObject(stageTarget);
|
|
35
|
+
if (!stageObject) {
|
|
36
|
+
contract(`${sp}.field`, `"${stages.field}" must be a relation field (one record) to another of this extension's objects`);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
if (fieldOf(stages.field)?.readOnly) {
|
|
40
|
+
contract(`${sp}.field`, "The stage field cannot be read-only");
|
|
41
|
+
}
|
|
42
|
+
const sf = (local) => Object.hasOwn(stageObject.fields, local) ? stageObject.fields[local] : undefined;
|
|
43
|
+
const type = sf(stages.stage.type);
|
|
44
|
+
const values = type?.options?.map((o) => o.value) ?? [];
|
|
45
|
+
if (type?.type !== "select" || !STAGE_TYPES.every((t) => values.includes(t))) {
|
|
46
|
+
contract(`${sp}.stage.type`, `"${stages.stage.type}" must be a select field of ${stageTarget} with options open, won and lost`);
|
|
47
|
+
}
|
|
48
|
+
const order = sf(stages.stage.order);
|
|
49
|
+
if (!order || !NUMERIC.includes(order.type)) {
|
|
50
|
+
contract(`${sp}.stage.order`, `"${stages.stage.order}" must be a number field of ${stageTarget}`);
|
|
51
|
+
}
|
|
52
|
+
if (stages.stage.requiredFields !== undefined) {
|
|
53
|
+
const required = sf(stages.stage.requiredFields);
|
|
54
|
+
if (required?.type !== "multiSelect") {
|
|
55
|
+
contract(`${sp}.stage.requiredFields`, `"${stages.stage.requiredFields}" must be a multiSelect field of ${stageTarget}`);
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
for (const option of required.options ?? []) {
|
|
59
|
+
const target = fieldOf(option.value);
|
|
60
|
+
if (!target || target.type === "formula" || target.readOnly) {
|
|
61
|
+
contract(`${sp}.stage.requiredFields`, `Option "${option.value}" must name a writable field of ${name}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (stages.stage.probability !== undefined) {
|
|
67
|
+
const probability = sf(stages.stage.probability);
|
|
68
|
+
if (!probability || !NUMERIC.includes(probability.type)) {
|
|
69
|
+
contract(`${sp}.stage.probability`, `"${stages.stage.probability}" must be a number or percent field of ${stageTarget}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const stageGroup = stages.stage.group ? relationTo(sf(stages.stage.group)) : undefined;
|
|
73
|
+
if (stages.stage.group !== undefined && !stageGroup) {
|
|
74
|
+
contract(`${sp}.stage.group`, `"${stages.stage.group}" must be a relation field (one record) of ${stageTarget}`);
|
|
75
|
+
}
|
|
76
|
+
if ((stages.group === undefined) !== (stages.stage.group === undefined)) {
|
|
77
|
+
contract(`${sp}.group`, "Declare both group and stage.group, or neither");
|
|
78
|
+
}
|
|
79
|
+
else if (stages.group !== undefined && relationTo(fieldOf(stages.group)) !== stageGroup) {
|
|
80
|
+
contract(`${sp}.group`, `"${stages.group}" must be a relation field to the same object as ${stageTarget}.${stages.stage.group}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (stages.probability) {
|
|
84
|
+
const field = fieldOf(stages.probability.field);
|
|
85
|
+
if (!field || !NUMERIC.includes(field.type) || field.readOnly) {
|
|
86
|
+
contract(`${sp}.probability.field`, `"${stages.probability.field}" must be a writable number or percent field`);
|
|
87
|
+
}
|
|
88
|
+
const flag = fieldOf(stages.probability.overridden);
|
|
89
|
+
if (flag?.type !== "boolean" || flag.readOnly) {
|
|
90
|
+
contract(`${sp}.probability.overridden`, `"${stages.probability.overridden}" must be a writable boolean field`);
|
|
91
|
+
}
|
|
92
|
+
if (!stages.stage.probability) {
|
|
93
|
+
contract(`${sp}.stage.probability`, "probability needs the stage's default probability");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (stages.closedDate !== undefined) {
|
|
97
|
+
const field = fieldOf(stages.closedDate);
|
|
98
|
+
if ((field?.type !== "date" && field?.type !== "datetime") || !field.readOnly) {
|
|
99
|
+
contract(`${sp}.closedDate`, `"${stages.closedDate}" must be a read-only date or datetime field`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (stages.status !== undefined) {
|
|
103
|
+
const field = fieldOf(stages.status);
|
|
104
|
+
const values = field?.options?.map((o) => o.value) ?? [];
|
|
105
|
+
if (field?.type !== "select" ||
|
|
106
|
+
!field.readOnly ||
|
|
107
|
+
!STAGE_TYPES.every((t) => values.includes(t))) {
|
|
108
|
+
contract(`${sp}.status`, `"${stages.status}" must be a read-only select field with options open, won and lost`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (stages.defaultGroupSetting !== undefined) {
|
|
112
|
+
const setting = m.settings?.[stages.defaultGroupSetting];
|
|
113
|
+
if (!stages.group) {
|
|
114
|
+
contract(`${sp}.defaultGroupSetting`, "defaultGroupSetting needs a group");
|
|
115
|
+
}
|
|
116
|
+
else if (setting?.type !== "text" && setting?.type !== "select") {
|
|
117
|
+
contract(`${sp}.defaultGroupSetting`, `"${stages.defaultGroupSetting}" must be a text or select setting of this extension`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const [type, list] of Object.entries(stages.requiredByType ?? {})) {
|
|
121
|
+
for (const local of list ?? []) {
|
|
122
|
+
const field = fieldOf(local);
|
|
123
|
+
if (!field || field.type === "formula" || field.readOnly) {
|
|
124
|
+
contract(`${sp}.requiredByType.${type}`, `"${local}" must be a writable field of ${name}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const [key, values] of Object.entries(object.seed ?? {})) {
|
|
130
|
+
const kp = `${path}.seed.${key}`;
|
|
131
|
+
if (!SEED_KEY_RE.test(key))
|
|
132
|
+
contract(kp, "Seed keys must be camelCase");
|
|
133
|
+
for (const [local, value] of Object.entries(values)) {
|
|
134
|
+
const field = fieldOf(local);
|
|
135
|
+
if (!field || field.type === "formula" || field.readOnly) {
|
|
136
|
+
contract(`${kp}.${local}`, `"${local}" is not a writable field of ${name}`);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
140
|
+
const ref = value.seed;
|
|
141
|
+
const target = ownObject(field.type === "relation" ? field.to : undefined);
|
|
142
|
+
if (typeof ref !== "string" || !target?.seed || !Object.hasOwn(target.seed, ref)) {
|
|
143
|
+
contract(`${kp}.${local}`, "A seed reference ({ seed: key }) must name a seed record of the relation's target");
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
for (const [local, field] of Object.entries(object.fields)) {
|
|
148
|
+
if (field.required && !(local in values)) {
|
|
149
|
+
contract(kp, `Seed record "${key}" needs required field "${local}"`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { ExtensionManifest, ObjectManifest } from "./manifest.ts";
|
|
3
|
+
/**
|
|
4
|
+
* What customers and the public are told about a record's places (staff always see the real
|
|
5
|
+
* numbers): `exact`, the number left; `low`, available, "only N left" at or below `lowAt`, or sold
|
|
6
|
+
* out; `availability`, available or sold out.
|
|
7
|
+
*/
|
|
8
|
+
export declare const CAPACITY_SHOW: readonly ["exact", "low", "availability"];
|
|
9
|
+
export type CapacityShow = (typeof CAPACITY_SHOW)[number];
|
|
10
|
+
/**
|
|
11
|
+
* The read-only values the host adds to every record of an object with a capacity: places held
|
|
12
|
+
* while someone pays, places taken, and places left (the record's and its pool's, whichever is
|
|
13
|
+
* fewer; null when unlimited). An object with a capacity cannot have fields of these names.
|
|
14
|
+
*/
|
|
15
|
+
export declare const CAPACITY_VALUES: readonly ["held", "taken", "available"];
|
|
16
|
+
/**
|
|
17
|
+
* A limited number of places (ADR 0430). The host keeps a counter per record and refuses, in the
|
|
18
|
+
* database, any claim past the places: a hold while an order is unpaid, confirmed when it is paid.
|
|
19
|
+
* A hold has no clock of its own: it lasts as long as what it was taken for.
|
|
20
|
+
*
|
|
21
|
+
* - `places` is this object's number field holding how many places there are. Empty means
|
|
22
|
+
* unlimited. Staff edit it; lowering it below what is held and taken is refused with the
|
|
23
|
+
* numbers, for every actor, and nothing ever sells beyond it.
|
|
24
|
+
* - `pool` is a relation field (one record) to another of this extension's objects that itself
|
|
25
|
+
* declares a capacity, and no pool: a claim on this record also claims on that record, in the
|
|
26
|
+
* same batch (a ticket type's places within its event's). One level only.
|
|
27
|
+
* - `show` is what customers and the public are told (default `availability`); `lowAt` is the
|
|
28
|
+
* threshold for `low`.
|
|
29
|
+
* - `releaseOnRefund` (default true): a refunded order's places go back on sale.
|
|
30
|
+
*/
|
|
31
|
+
export interface CapacitySpec {
|
|
32
|
+
places: string;
|
|
33
|
+
pool?: string;
|
|
34
|
+
show?: CapacityShow;
|
|
35
|
+
lowAt?: number;
|
|
36
|
+
releaseOnRefund?: boolean;
|
|
37
|
+
}
|
|
38
|
+
export declare const capacityManifestSchema: z.ZodObject<{
|
|
39
|
+
places: z.ZodString;
|
|
40
|
+
pool: z.ZodOptional<z.ZodString>;
|
|
41
|
+
show: z.ZodOptional<z.ZodEnum<{
|
|
42
|
+
exact: "exact";
|
|
43
|
+
low: "low";
|
|
44
|
+
availability: "availability";
|
|
45
|
+
}>>;
|
|
46
|
+
lowAt: z.ZodOptional<z.ZodNumber>;
|
|
47
|
+
releaseOnRefund: z.ZodOptional<z.ZodBoolean>;
|
|
48
|
+
}, z.core.$strict>;
|
|
49
|
+
export type CapacityManifest = z.infer<typeof capacityManifestSchema>;
|
|
50
|
+
/** Reports problems with `objects.<name>.capacity` through `contract`. */
|
|
51
|
+
export declare function checkObjectCapacity(m: ExtensionManifest, name: string, object: ObjectManifest, contract: (path: string, message: string) => void): void;
|
package/dist/capacity.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// The `capacity` behaviour (stage 26, ADR 0430, ADR 0431): an object declares that its records
|
|
2
|
+
// have a limited number of places, and the host never gives out more than there are, for every
|
|
3
|
+
// actor. Its declaration, its manifest schema and its contract checks live here; the host's side
|
|
4
|
+
// is packages/core/src/capacity/.
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
/**
|
|
7
|
+
* What customers and the public are told about a record's places (staff always see the real
|
|
8
|
+
* numbers): `exact`, the number left; `low`, available, "only N left" at or below `lowAt`, or sold
|
|
9
|
+
* out; `availability`, available or sold out.
|
|
10
|
+
*/
|
|
11
|
+
export const CAPACITY_SHOW = ["exact", "low", "availability"];
|
|
12
|
+
/**
|
|
13
|
+
* The read-only values the host adds to every record of an object with a capacity: places held
|
|
14
|
+
* while someone pays, places taken, and places left (the record's and its pool's, whichever is
|
|
15
|
+
* fewer; null when unlimited). An object with a capacity cannot have fields of these names.
|
|
16
|
+
*/
|
|
17
|
+
export const CAPACITY_VALUES = ["held", "taken", "available"];
|
|
18
|
+
const fieldName = z.string().max(40);
|
|
19
|
+
export const capacityManifestSchema = z
|
|
20
|
+
.object({
|
|
21
|
+
places: fieldName,
|
|
22
|
+
pool: fieldName.optional(),
|
|
23
|
+
show: z.enum(CAPACITY_SHOW).optional(),
|
|
24
|
+
lowAt: z.number().int().min(1).max(1_000_000).optional(),
|
|
25
|
+
releaseOnRefund: z.boolean().optional(),
|
|
26
|
+
})
|
|
27
|
+
.strict();
|
|
28
|
+
/** Reports problems with `objects.<name>.capacity` through `contract`. */
|
|
29
|
+
export function checkObjectCapacity(m, name, object, contract) {
|
|
30
|
+
const capacity = object.capacity;
|
|
31
|
+
if (!capacity)
|
|
32
|
+
return;
|
|
33
|
+
const path = `objects.${name}.capacity`;
|
|
34
|
+
const fieldOf = (local) => Object.hasOwn(object.fields, local) ? object.fields[local] : undefined;
|
|
35
|
+
const places = fieldOf(capacity.places);
|
|
36
|
+
if (places?.type !== "number" || places.many) {
|
|
37
|
+
contract(`${path}.places`, `"${capacity.places}" must be a number field of ${name}`);
|
|
38
|
+
}
|
|
39
|
+
for (const reserved of CAPACITY_VALUES) {
|
|
40
|
+
if (Object.hasOwn(object.fields, reserved)) {
|
|
41
|
+
contract(`objects.${name}.fields.${reserved}`, `"${reserved}" is a value the host adds to an object with a capacity; rename the field`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (capacity.pool !== undefined) {
|
|
45
|
+
const pool = fieldOf(capacity.pool);
|
|
46
|
+
const target = pool?.type === "relation" && !pool.many ? pool.to : undefined;
|
|
47
|
+
const local = target?.startsWith(`${m.id}.`) ? target.slice(m.id.length + 1) : undefined;
|
|
48
|
+
const targetObject = local !== undefined && Object.hasOwn(m.objects, local) ? m.objects[local] : undefined;
|
|
49
|
+
if (!targetObject) {
|
|
50
|
+
contract(`${path}.pool`, `"${capacity.pool}" must be a relation field (one record) to another of this extension's objects`);
|
|
51
|
+
}
|
|
52
|
+
else if (local === name) {
|
|
53
|
+
contract(`${path}.pool`, "An object cannot be its own pool");
|
|
54
|
+
}
|
|
55
|
+
else if (!targetObject.capacity) {
|
|
56
|
+
contract(`${path}.pool`, `The pool's object ${target} must declare a capacity`);
|
|
57
|
+
}
|
|
58
|
+
else if (targetObject.capacity.pool !== undefined) {
|
|
59
|
+
contract(`${path}.pool`, `The pool's object ${target} has a pool of its own; capacity has one level of pool`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (capacity.lowAt !== undefined && capacity.show !== "low") {
|
|
63
|
+
contract(`${path}.lowAt`, 'lowAt is the threshold of show: "low"');
|
|
64
|
+
}
|
|
65
|
+
if (capacity.show === "low" && capacity.lowAt === undefined) {
|
|
66
|
+
contract(`${path}.lowAt`, 'show: "low" needs lowAt, the number at or below which it says so');
|
|
67
|
+
}
|
|
68
|
+
}
|