@cogover/sdk 0.5.0 → 0.6.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.
@@ -0,0 +1,211 @@
1
+ import { createDataApi } from "../data.js";
2
+ import { ValidationError } from "../errors.js";
3
+ import { installCogoverFetch } from "../fetch.js";
4
+ import { SCRIPT_LOGGER } from "../logger.js";
5
+ import { createSchemaApi } from "../schema.js";
6
+ import { invocationContext } from "./invocation.js";
7
+ import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
8
+ import { TRIGGER_SLUG } from "./trigger-config.js";
9
+ import { errorMessage, isRecord } from "./values.js";
10
+ const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
11
+ const MAX_ERROR_MESSAGE_LENGTH = 500;
12
+ // Both spellings of a timing and an operation are accepted; project code only ever sees the SDK literals.
13
+ const TIMINGS = new Map([
14
+ ["beforeChange", "beforeChange"],
15
+ ["BEFORE_CHANGE", "beforeChange"],
16
+ ["afterChange", "afterChange"],
17
+ ["AFTER_CHANGE", "afterChange"],
18
+ ]);
19
+ const OPERATIONS = new Map([
20
+ ["create", "create"],
21
+ ["CREATE", "create"],
22
+ ["update", "update"],
23
+ ["UPDATE", "update"],
24
+ ["delete", "delete"],
25
+ ["DELETE", "delete"],
26
+ ]);
27
+ export function createTriggerSandboxHandler(manifest, handler) {
28
+ const writableFields = new Set(manifest.writableFields);
29
+ return async (inputJson) => {
30
+ installCogoverFetch();
31
+ let input;
32
+ try {
33
+ input = JSON.parse(inputJson);
34
+ }
35
+ catch (error) {
36
+ throw new ValidationError("Trigger input must be valid JSON", errorMessage(error));
37
+ }
38
+ if (!isRecord(input))
39
+ throw new ValidationError("Trigger input must be a JSON object");
40
+ const trigger = triggerInfo(input, manifest);
41
+ const entries = recordEntries(input.records, trigger.operation);
42
+ let invocation;
43
+ await handler(Object.freeze({
44
+ records: Object.freeze(entries.map(entry => entry.record)),
45
+ trigger,
46
+ get invocation() {
47
+ return invocation ??= invocationContext(input);
48
+ },
49
+ data: createDataApi(),
50
+ schema: createSchemaApi(),
51
+ log: SCRIPT_LOGGER,
52
+ }));
53
+ const results = [];
54
+ for (const entry of entries) {
55
+ // Always diff: changing a field outside writableFields is a bug even on a rejected record.
56
+ const changes = recordChanges(entry, manifest.key, writableFields);
57
+ if (entry.errors.length > 0) {
58
+ results.push({ key: entry.key, errors: entry.errors });
59
+ }
60
+ else if (changes !== null) {
61
+ results.push({ key: entry.key, changes });
62
+ }
63
+ }
64
+ return JSON.stringify({ results });
65
+ };
66
+ }
67
+ function triggerInfo(input, manifest) {
68
+ const context = isRecord(input.__context) ? input.__context : undefined;
69
+ const raw = context !== undefined && isRecord(context.trigger) ? context.trigger : undefined;
70
+ if (raw === undefined) {
71
+ throw new ValidationError("Trigger metadata is unavailable outside Cogover Runtime");
72
+ }
73
+ const timing = TIMINGS.get(raw.timing);
74
+ const operation = OPERATIONS.get(raw.operation);
75
+ if (timing === undefined)
76
+ throw new ValidationError("Invalid trigger timing metadata");
77
+ if (operation === undefined)
78
+ throw new ValidationError("Invalid trigger operation metadata");
79
+ const info = Object.freeze({
80
+ id: requiredString(raw.id, "id"),
81
+ key: requiredString(raw.key, "key"),
82
+ timing,
83
+ operation,
84
+ objectSlug: requiredString(raw.objectSlug, "objectSlug"),
85
+ changeId: requiredString(raw.changeId, "changeId"),
86
+ });
87
+ // A mismatch means the call was routed to a definition it was not registered for.
88
+ if (info.key !== manifest.key || info.timing !== manifest.timing
89
+ || info.objectSlug !== manifest.object || !manifest.operations.includes(info.operation)) {
90
+ throw new ValidationError(`Trigger input for '${info.key}' (${info.timing} ${info.operation} on '${info.objectSlug}') `
91
+ + `does not match the definition of '${manifest.key}' `
92
+ + `(${manifest.timing} ${manifest.operations.join("/")} on '${manifest.object}')`);
93
+ }
94
+ return info;
95
+ }
96
+ function requiredString(value, name) {
97
+ if (typeof value !== "string" || value === "") {
98
+ throw new ValidationError(`Invalid trigger ${name} metadata`);
99
+ }
100
+ return value;
101
+ }
102
+ function recordEntries(records, operation) {
103
+ if (!Array.isArray(records))
104
+ throw new ValidationError("Trigger input records must be an array");
105
+ const keys = new Set();
106
+ return records.map((raw, index) => {
107
+ const invalid = (reason) => new ValidationError(`Trigger input record at index ${index} is invalid: ${reason}`);
108
+ if (!isRecord(raw))
109
+ throw invalid("it must be an object");
110
+ const key = raw.key;
111
+ if (typeof key !== "string" || key === "")
112
+ throw invalid("key must be a non-empty string");
113
+ if (keys.has(key))
114
+ throw invalid(`duplicate key '${key}'`);
115
+ keys.add(key);
116
+ if (raw.id !== undefined && raw.id !== null && typeof raw.id !== "string") {
117
+ throw invalid("id must be a string or null");
118
+ }
119
+ // An omitted value means null: JSON writers commonly drop null properties.
120
+ const current = fieldValues(raw.new, "new", invalid);
121
+ const old = fieldValues(raw.old, "old", invalid);
122
+ if ((operation === "delete") !== (current === null)) {
123
+ throw invalid(operation === "delete"
124
+ ? "new must be null when the operation is delete"
125
+ : `new is required when the operation is ${operation}`);
126
+ }
127
+ if ((operation === "create") !== (old === null)) {
128
+ throw invalid(operation === "create"
129
+ ? "old must be null when the operation is create"
130
+ : `old is required when the operation is ${operation}`);
131
+ }
132
+ const changedFields = raw.changedFields ?? [];
133
+ if (!Array.isArray(changedFields) || changedFields.some(field => typeof field !== "string")) {
134
+ throw invalid("changedFields must be an array of field slugs");
135
+ }
136
+ const errors = [];
137
+ const record = {
138
+ key,
139
+ id: typeof raw.id === "string" ? raw.id : null,
140
+ get new() {
141
+ return current;
142
+ },
143
+ set new(_value) {
144
+ throw new ValidationError(current === null
145
+ ? "A record that is being deleted has no new values and cannot be modified"
146
+ : "record.new cannot be replaced; assign its fields instead, for example record.new.status = \"approved\"");
147
+ },
148
+ old: deepFreeze(old),
149
+ changedFields: deepFreeze([...changedFields]),
150
+ addError(field, code, message) {
151
+ errors.push(recordError(field, code, message));
152
+ },
153
+ };
154
+ return {
155
+ key,
156
+ record: Object.freeze(record),
157
+ current,
158
+ snapshot: current === null ? null : cloneJson(current),
159
+ errors,
160
+ };
161
+ });
162
+ }
163
+ function fieldValues(value, name, invalid) {
164
+ if (value === undefined || value === null)
165
+ return null;
166
+ if (!isRecord(value))
167
+ throw invalid(`${name} must be an object or null`);
168
+ return value;
169
+ }
170
+ function recordError(field, code, message) {
171
+ if (field !== null && (typeof field !== "string" || !TRIGGER_SLUG.test(field))) {
172
+ throw new ValidationError("addError() field must be a valid field slug, or null for a record-level error");
173
+ }
174
+ if (typeof code !== "string" || !ERROR_CODE.test(code)) {
175
+ throw new ValidationError("addError() code must start with an upper-case letter and contain "
176
+ + "at most 64 upper-case letters, digits or underscores, for example AMOUNT_TOO_LARGE");
177
+ }
178
+ if (message === undefined || message === null || message === "")
179
+ return { field, code };
180
+ if (typeof message !== "string" || message.length > MAX_ERROR_MESSAGE_LENGTH) {
181
+ throw new ValidationError(`addError() message must be a string of at most ${MAX_ERROR_MESSAGE_LENGTH} characters`);
182
+ }
183
+ return { field, code, message };
184
+ }
185
+ /** Top-level diff of record.new against its snapshot, or null when the handler changed nothing. */
186
+ function recordChanges(entry, triggerKey, writableFields) {
187
+ const { current, snapshot } = entry;
188
+ if (current === null || snapshot === null)
189
+ return null;
190
+ // A null prototype keeps every field slug, including "__proto__", an ordinary own property.
191
+ const changes = Object.create(null);
192
+ let changed = false;
193
+ for (const field of new Set([...Object.keys(snapshot), ...Object.keys(current)])) {
194
+ const existed = Object.prototype.hasOwnProperty.call(snapshot, field);
195
+ const assigned = Object.prototype.hasOwnProperty.call(current, field) ? current[field] : undefined;
196
+ if (assigned === undefined && !existed)
197
+ continue;
198
+ // Deleting a field or assigning undefined clears it.
199
+ const after = assigned === undefined
200
+ ? null
201
+ : toJsonValue(assigned, `Trigger '${triggerKey}': the value assigned to field '${field}'`);
202
+ if (existed && jsonEquals(snapshot[field], after))
203
+ continue;
204
+ if (!writableFields.has(field)) {
205
+ throw new ValidationError(`Trigger '${triggerKey}' changed field '${field}', which is not listed in writableFields`, { triggerKey, field, recordKey: entry.key });
206
+ }
207
+ changes[field] = after;
208
+ changed = true;
209
+ }
210
+ return changed ? changes : null;
211
+ }
package/dist/records.d.ts CHANGED
@@ -34,6 +34,11 @@ export interface RecordPage<TFields> {
34
34
  readonly total: number;
35
35
  readonly nextCursor?: string;
36
36
  }
37
+ /** Result of `records.getMany`: the readable records plus every requested ID that could not be read. */
38
+ export interface GetManyResult<TFields> {
39
+ readonly records: CogoverRecord<TFields>[];
40
+ readonly missingIds: CogoverRecordId[];
41
+ }
37
42
  export interface DeleteResult {
38
43
  readonly deleted: CogoverRecordId[];
39
44
  readonly notDeleted: CogoverRecordId[];
@@ -0,0 +1,121 @@
1
+ import type { DataApi } from "./data.js";
2
+ import type { InvocationContext } from "./invocation.js";
3
+ import type { ScriptLogger } from "./logger.js";
4
+ import type { FilterOperator } from "./query.js";
5
+ import type { CogoverRecordId, UpdateFields } from "./records.js";
6
+ import type { SchemaApi } from "./schema.js";
7
+ import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
8
+ /** When a record trigger runs relative to the record change. */
9
+ export type TriggerTiming = "beforeChange" | "afterChange";
10
+ /** Record operations a trigger can subscribe to. */
11
+ export type TriggerOperation = "create" | "update" | "delete";
12
+ /** `"onEnter"` runs only when a record starts matching `when`; `"always"` runs whenever it matches. */
13
+ export type TriggerRunWhen = "always" | "onEnter";
14
+ /** One field comparison of a trigger `when` filter. */
15
+ export interface TriggerFilterCondition {
16
+ readonly op: FilterOperator;
17
+ readonly field: string;
18
+ /** Comparison value; omitted for `"is null"` and `"not null"`. */
19
+ readonly params?: unknown;
20
+ }
21
+ /** Combines trigger `when` filters with `and` or `or`. */
22
+ export interface TriggerFilterGroup {
23
+ readonly op: "and" | "or";
24
+ readonly conditions: readonly TriggerFilter[];
25
+ }
26
+ export type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
27
+ type TriggerObjectFields<TObject extends string, TSchema extends object> = TObject extends keyof TSchema ? FieldsFor<TSchema, TObject> : Record<string, unknown>;
28
+ type TriggerFieldSlug<TObject extends string, TSchema extends object> = StringKeyOf<TriggerObjectFields<TObject, TSchema>>;
29
+ /** Options accepted by `defineTrigger`. */
30
+ export interface TriggerConfig<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> {
31
+ /** Stable identifier of the trigger inside the project. */
32
+ readonly key: string;
33
+ /** Display name; defaults to `key`. */
34
+ readonly name?: string;
35
+ /** Slug of the Object whose records run this trigger. */
36
+ readonly object: TObject;
37
+ readonly timing: TriggerTiming;
38
+ readonly operations: readonly TOperation[];
39
+ /** Fields delivered in `record.new` and `record.old`. */
40
+ readonly fields: readonly TriggerFieldSlug<TObject, TSchema>[];
41
+ /** Updates run the trigger only when at least one of these fields changed. */
42
+ readonly changedFields?: readonly TriggerFieldSlug<TObject, TSchema>[];
43
+ /** Only records matching this filter run the trigger. */
44
+ readonly when?: TriggerFilter;
45
+ readonly runWhen?: TriggerRunWhen;
46
+ /** Fields the handler may change through `record.new`. */
47
+ readonly writableFields?: readonly TriggerFieldSlug<TObject, TSchema>[];
48
+ /** Position among the triggers of the same Object; lower values run first. */
49
+ readonly order?: number;
50
+ /** Time budget of one handler call, in milliseconds. */
51
+ readonly timeoutMs?: number;
52
+ }
53
+ /** Normalized, immutable trigger configuration with every default applied. */
54
+ export interface TriggerManifest {
55
+ readonly key: string;
56
+ readonly name?: string;
57
+ readonly object: string;
58
+ readonly timing: TriggerTiming;
59
+ readonly operations: readonly TriggerOperation[];
60
+ readonly fields: readonly string[];
61
+ readonly changedFields?: readonly string[];
62
+ readonly when?: TriggerFilter;
63
+ readonly runWhen: TriggerRunWhen;
64
+ readonly writableFields: readonly string[];
65
+ readonly order: number;
66
+ readonly timeoutMs: number;
67
+ }
68
+ /** Entry point reserved for Cogover; project code does not call it. */
69
+ export type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
70
+ /** Result of `defineTrigger`; list it in the project's `triggers` export. */
71
+ export interface TriggerDefinition {
72
+ readonly key: string;
73
+ readonly config: TriggerManifest;
74
+ /** Reserved for Cogover; project code does not call it. */
75
+ readonly __cogoverTriggerHandler: TriggerSandboxHandler;
76
+ }
77
+ /** Identifies the trigger and the record change of the current call. */
78
+ export interface TriggerInfo<TOperation extends TriggerOperation = TriggerOperation> {
79
+ readonly id: string;
80
+ readonly key: string;
81
+ readonly timing: TriggerTiming;
82
+ readonly operation: TOperation;
83
+ readonly objectSlug: string;
84
+ /** Identifies the record change that caused this call. */
85
+ readonly changeId: string;
86
+ }
87
+ /** Mutable field values after the change. Assigned values use the `records.update` input format. */
88
+ export type TriggerNewValues<TFields> = {
89
+ -readonly [K in keyof TFields]?: TFields[K] | Exclude<UpdateFields<TFields>[K], undefined>;
90
+ };
91
+ /** Immutable field values before the change. */
92
+ export type TriggerOldValues<TFields> = {
93
+ readonly [K in keyof TFields]?: TFields[K];
94
+ };
95
+ type TriggerValuesFor<TAbsentFor extends TriggerOperation, TOperation extends TriggerOperation, TValues> = [TOperation] extends [TAbsentFor] ? null : TAbsentFor extends TOperation ? TValues | null : TValues;
96
+ /** One record of the change being processed. */
97
+ export interface TriggerRecord<TFields = Record<string, unknown>, TOperation extends TriggerOperation = TriggerOperation> {
98
+ /** Correlates this record with its result; not a record ID. */
99
+ readonly key: string;
100
+ /** `null` while a record that is being created has no ID yet. */
101
+ readonly id: CogoverRecordId | null;
102
+ /** `null` when the record is being deleted. */
103
+ readonly new: TriggerValuesFor<"delete", TOperation, TriggerNewValues<TFields>>;
104
+ /** `null` when the record is being created. */
105
+ readonly old: TriggerValuesFor<"create", TOperation, TriggerOldValues<TFields>>;
106
+ readonly changedFields: readonly StringKeyOf<TFields>[];
107
+ /** Rejects this record. Pass `null` as the field for an error about the whole record. */
108
+ addError(field: StringKeyOf<TFields> | null, code: string, message?: string): void;
109
+ }
110
+ export interface TriggerContext<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> {
111
+ readonly records: readonly TriggerRecord<TriggerObjectFields<TObject, TSchema>, TOperation>[];
112
+ readonly trigger: TriggerInfo<TOperation>;
113
+ readonly invocation: InvocationContext;
114
+ readonly data: DataApi<TSchema>;
115
+ readonly schema: SchemaApi<TSchema>;
116
+ readonly log: ScriptLogger;
117
+ }
118
+ export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
119
+ /** Declares a record trigger. Add the result to the project's `triggers` export. */
120
+ export declare function defineTrigger<TObject extends StringKeyOf<TSchema>, TOperation extends TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects>(config: TriggerConfig<TObject, TOperation, TSchema>, handler: TriggerHandler<TObject, TOperation, TSchema>): TriggerDefinition;
121
+ export {};
@@ -0,0 +1,15 @@
1
+ import { ValidationError } from "./errors.js";
2
+ import { normalizeTriggerConfig } from "./internal/trigger-config.js";
3
+ import { createTriggerSandboxHandler } from "./internal/trigger-runtime.js";
4
+ /** Declares a record trigger. Add the result to the project's `triggers` export. */
5
+ export function defineTrigger(config, handler) {
6
+ const manifest = normalizeTriggerConfig(config);
7
+ if (typeof handler !== "function") {
8
+ throw new ValidationError(`Trigger '${manifest.key}' requires a handler function`);
9
+ }
10
+ return Object.freeze({
11
+ key: manifest.key,
12
+ config: manifest,
13
+ __cogoverTriggerHandler: createTriggerSandboxHandler(manifest, handler),
14
+ });
15
+ }