@cogover/sdk 0.12.2 → 0.13.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.
@@ -251,7 +251,10 @@ is not reached. When jobs are not enabled for the Workspace, the error is
251
251
  is `"system"`, and `data.object()` works only if the project's approved identity
252
252
  policy sets `allowInternalSystem: true`; otherwise its calls throw
253
253
  `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
254
- `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
254
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual. In a run
255
+ that has a user, `records.aggregate` through `data.object()` has the limits of
256
+ `data.asUser()`; use `data.asSystem()` to group (see
257
+ [Aggregates](records.md#aggregates)).
255
258
  - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
256
259
  `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
257
260
  within the runtime limits of the job lane.
@@ -12,7 +12,7 @@ The reference is split into the following pages. Each page covers one area of th
12
12
  | Page | Covers |
13
13
  |---|---|
14
14
  | [Scripts and HTTP routes](scripts-and-routes.md) | `defineScript`; HTTP routers and request context; Invocation identity and workspace; HTTP response API; Logging |
15
- | [Records and schema](records.md) | Record API; Filters and sorting; Record execution identities; Schema API; Workspace declarations |
15
+ | [Records and schema](records.md) | Record API; Choosing fields; Linked records; Aggregates; Filters and sorting; Record execution identities; Schema API; Workspace declarations |
16
16
  | [Record triggers](record-triggers.md) | Record triggers |
17
17
  | [Background jobs](background-jobs.md) | Background jobs |
18
18
  | [Outbound HTTP and secrets](fetch-and-secrets.md) | Outbound HTTP `fetch`; Secrets and credentials |
@@ -89,6 +89,12 @@ throws it to report a temporary failure, and Cogover runs the handler again late
89
89
  meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
90
90
  that throws it rejects the write like any other failure.
91
91
 
92
+ A record read (`get`, `getMany`, or `list`) without a valid `fields` option throws
93
+ `ValidationError` with the message `fields is required: pass field slugs or "*"
94
+ (@cogover/sdk 0.13.0+)`. Cogover returns the same error to a project version that was
95
+ published with an older SDK and reads without `fields` (see
96
+ [Choosing fields](records.md#choosing-fields)).
97
+
92
98
  `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
93
99
  `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
94
100
  with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
@@ -179,7 +185,8 @@ set by the platform and may differ between environments.
179
185
  262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
180
186
  or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
181
187
  is the limit. A capability result larger than 1,048,576 bytes is withheld the same
182
- way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records or fields. The
188
+ way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records, or name the
189
+ fields instead of `"*"`. The
183
190
  operation itself did run, so a write may have completed.
184
191
  - When the Workspace already has too many executions waiting, a new HTTP call is
185
192
  refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
@@ -287,6 +287,14 @@ trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
287
287
  `TriggerOldValues` make every field optional because a field that is not listed in
288
288
  `fields`, or that has no value, is `undefined`.
289
289
 
290
+ Lookup and reference values in `new` and `old` carry the linked record's `name`. This
291
+ differs from records read through `data`, whose lookup values have `name: ""` unless
292
+ the read uses `expandLookups` (see [Linked records](records.md#linked-records)). Reads
293
+ through `data` in a trigger follow the same rules as in a script, including the
294
+ required `fields`. For a change made by a user, `data.object()` reads as that user, so
295
+ its `records.aggregate` has the limits of `data.asUser()`: use `data.asSystem()` to
296
+ group (see [Aggregates](records.md#aggregates)).
297
+
290
298
  ### Validating and changing records
291
299
 
292
300
  This section applies to before-change triggers. In an after-change trigger the
@@ -387,6 +395,10 @@ a request that only validates input without saving.
387
395
  receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
388
396
  - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
389
397
  one write share a total budget of 8 seconds.
398
+ - **Reads delay the write.** The user's write waits while the handler reads. Each
399
+ expanded lookup reads another Object, and `records.aggregate`, which is allowed, is
400
+ computed from a search index that is about one second behind: it does not count the
401
+ change being made, and may miss changes saved just before it. Keep such calls few.
390
402
 
391
403
  ### After-change execution rules
392
404
 
@@ -6,9 +6,10 @@ This page is part of the [`@cogover/sdk` API reference](overview.md).
6
6
 
7
7
  ```typescript
8
8
  const orders = data.object("order");
9
- await orders.records.get(id, { fields });
10
- await orders.records.getMany(ids, { fields });
11
- await orders.records.list({ where, orderBy, fields, limit, cursor });
9
+ await orders.records.get(id, { fields, expandLookups });
10
+ await orders.records.getMany(ids, { fields, expandLookups });
11
+ await orders.records.list({ where, orderBy, fields, limit, cursor, expandLookups });
12
+ await orders.records.aggregate({ where, groupBy, metrics, limit });
12
13
  await orders.records.create(fields);
13
14
  await orders.records.update(id, fields);
14
15
  await orders.records.batchInsert(records);
@@ -17,6 +18,10 @@ await orders.records.upsertByUniqueField(matchBy, fields);
17
18
  await orders.records.deleteMany(ids);
18
19
  ```
19
20
 
21
+ Every read names the fields it returns: `fields` is required by `get`, `getMany`, and
22
+ `list` (see [Choosing fields](#choosing-fields)). Lookups are not expanded unless the
23
+ read asks for it with `expandLookups` (see [Linked records](#linked-records)).
24
+
20
25
  ### Record values and results
21
26
 
22
27
  ```typescript
@@ -26,8 +31,13 @@ type CogoverRecordId = string & {
26
31
 
27
32
  interface RecordReference<ObjectSlug extends string = string> {
28
33
  readonly id: CogoverRecordId;
34
+ // "" unless the read expanded this lookup; a `reference` field keeps its stored name.
29
35
  readonly name: string;
30
36
  readonly objectSlug?: ObjectSlug;
37
+ // Present only when the read expanded this lookup and the linked record could be read.
38
+ readonly fields?: ObjectSlug extends keyof WorkspaceObjects
39
+ ? Readonly<Partial<WorkspaceObjects[ObjectSlug]>>
40
+ : Readonly<Record<string, unknown>>;
31
41
  }
32
42
 
33
43
  interface UrlValue {
@@ -49,6 +59,7 @@ interface CogoverRecord<Fields> {
49
59
  readonly system: {
50
60
  readonly createdAt: number;
51
61
  readonly updatedAt: number;
62
+ // `name` is "" unless the read used `expandLookups`.
52
63
  readonly createdBy?: { readonly id: string; readonly name: string };
53
64
  };
54
65
  }
@@ -111,20 +122,116 @@ and non-null.
111
122
  ### Data clients and operations
112
123
 
113
124
  ```typescript
114
- interface GetRecordOptions<Fields> {
115
- readonly fields?: readonly (keyof Fields & string)[];
125
+ type FieldSelection<Fields> = "*" | readonly (keyof Fields & string)[];
126
+
127
+ type SelectedFields<Fields, Selection extends FieldSelection<Fields>> =
128
+ Selection extends "*" ? Fields
129
+ : Selection extends readonly (infer Slug)[] ? Pick<Fields, Slug & keyof Fields>
130
+ : Fields;
131
+
132
+ type ExpandLookups<Fields> =
133
+ | boolean
134
+ | {
135
+ // LookupFieldSlug: the lookup and reference fields of Fields. LinkedFieldSlug: the field
136
+ // slugs of the linked Object, or any string when that Object is not declared.
137
+ readonly [Slug in LookupFieldSlug<Fields>]?: "*" | readonly LinkedFieldSlug<Fields[Slug]>[];
138
+ };
139
+
140
+ interface GetRecordOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
141
+ readonly fields: Selection;
142
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
116
143
  }
117
144
 
118
- interface GetManyOptions<Fields> {
119
- readonly fields: readonly (keyof Fields & string)[];
145
+ interface GetManyOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
146
+ readonly fields: Selection;
147
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
120
148
  }
121
149
 
122
- interface ListOptions<Fields> {
150
+ interface ListOptions<Fields, Selection extends FieldSelection<Fields> = FieldSelection<Fields>> {
123
151
  readonly where?: FilterExpression;
124
152
  readonly orderBy?: readonly SortExpression[];
125
- readonly fields?: readonly (keyof Fields & string)[];
153
+ readonly fields: Selection;
126
154
  readonly limit?: number;
127
155
  readonly cursor?: string;
156
+ readonly expandLookups?: ExpandLookups<SelectedFields<Fields, Selection>>;
157
+ }
158
+
159
+ type AggregateMetric<Fields> =
160
+ | { readonly count: "id" | CountableFieldSlug<Fields> }
161
+ | { readonly countDistinct: CountableFieldSlug<Fields> }
162
+ | { readonly sum: NumberFieldSlug<Fields> }
163
+ | { readonly avg: NumberFieldSlug<Fields> }
164
+ | { readonly min: NumberOrTextFieldSlug<Fields> }
165
+ | { readonly max: NumberOrTextFieldSlug<Fields> };
166
+ // CountableFieldSlug: every field except file and URL fields. NumberFieldSlug: the fields
167
+ // typed `number`. NumberOrTextFieldSlug: the fields typed `number` or `string` (a `date` is
168
+ // a string). Each is any string when Fields is not declared.
169
+
170
+ type AsUserAggregateMetric<Fields> =
171
+ | { readonly count: "id" | NumberFieldSlug<Fields> }
172
+ | { readonly sum: NumberFieldSlug<Fields> }
173
+ | { readonly avg: NumberFieldSlug<Fields> }
174
+ | { readonly min: NumberFieldSlug<Fields> }
175
+ | { readonly max: NumberFieldSlug<Fields> };
176
+
177
+ type AggregateMetrics<Fields> = Readonly<Record<string, AggregateMetric<Fields>>>;
178
+ type AsUserAggregateMetrics<Fields> = Readonly<Record<string, AsUserAggregateMetric<Fields>>>;
179
+
180
+ interface AggregateOptions<
181
+ Fields,
182
+ Metrics extends AggregateMetrics<Fields> | AsUserAggregateMetrics<Fields> = AggregateMetrics<Fields>,
183
+ > {
184
+ readonly where?: FilterExpression;
185
+ readonly metrics: Metrics;
186
+ readonly groupBy?: never;
187
+ readonly limit?: never;
188
+ }
189
+
190
+ interface GroupedAggregateOptions<
191
+ Fields,
192
+ Metrics extends AggregateMetrics<Fields> = AggregateMetrics<Fields>,
193
+ GroupBy extends readonly (keyof Fields & string)[] = readonly (keyof Fields & string)[],
194
+ > {
195
+ readonly where?: FilterExpression;
196
+ readonly groupBy: GroupBy;
197
+ readonly metrics: Metrics;
198
+ readonly limit?: number;
199
+ }
200
+
201
+ type AggregateValues<Metrics> = {
202
+ readonly [Name in keyof Metrics]:
203
+ Metrics[Name] extends
204
+ | { readonly count: string }
205
+ | { readonly countDistinct: string }
206
+ | { readonly sum: string }
207
+ ? number
208
+ : number | null;
209
+ };
210
+
211
+ type AggregateGroupKey<Fields, Slug extends keyof Fields & string> = {
212
+ // CogoverRecordId for a lookup, the option slug for a choice, boolean, number, and
213
+ // epoch milliseconds (`number`) for a date: text cannot be grouped, so a `string` field is a date.
214
+ readonly [K in Slug]: GroupKeyValue<Fields[K]>;
215
+ };
216
+
217
+ interface AggregateResult<Values = Readonly<Record<string, number | null>>> {
218
+ readonly values: Values;
219
+ }
220
+
221
+ interface AggregateGroup<
222
+ Key = Readonly<Record<string, string | number | boolean>>,
223
+ Values = Readonly<Record<string, number | null>>,
224
+ > {
225
+ readonly key: Key;
226
+ readonly values: Values;
227
+ }
228
+
229
+ interface AggregateGroupResult<
230
+ Key = Readonly<Record<string, string | number | boolean>>,
231
+ Values = Readonly<Record<string, number | null>>,
232
+ > {
233
+ readonly groups: AggregateGroup<Key, Values>[];
234
+ readonly truncated: boolean;
128
235
  }
129
236
 
130
237
  interface RecordWritesApi<Fields> {
@@ -139,10 +246,33 @@ interface RecordWritesApi<Fields> {
139
246
  deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
140
247
  }
141
248
 
142
- interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
143
- get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
144
- getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
145
- list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
249
+ interface AsUserRecordsApi<Fields> extends RecordWritesApi<Fields> {
250
+ get<const Selection extends FieldSelection<Fields>>(
251
+ id: string,
252
+ options: GetRecordOptions<Fields, Selection>,
253
+ ): Promise<CogoverRecord<SelectedFields<Fields, Selection>> | null>;
254
+ getMany<const Selection extends FieldSelection<Fields>>(
255
+ ids: readonly string[],
256
+ options: GetManyOptions<Fields, Selection>,
257
+ ): Promise<GetManyResult<SelectedFields<Fields, Selection>>>;
258
+ list<const Selection extends FieldSelection<Fields>>(
259
+ options: ListOptions<Fields, Selection>,
260
+ ): Promise<RecordPage<SelectedFields<Fields, Selection>>>;
261
+ aggregate<const Metrics extends AsUserAggregateMetrics<Fields>>(
262
+ options: AggregateOptions<Fields, Metrics>,
263
+ ): Promise<AggregateResult<AggregateValues<Metrics>>>;
264
+ }
265
+
266
+ interface RecordsApi<Fields> extends AsUserRecordsApi<Fields> {
267
+ aggregate<const Metrics extends AggregateMetrics<Fields>>(
268
+ options: AggregateOptions<Fields, Metrics>,
269
+ ): Promise<AggregateResult<AggregateValues<Metrics>>>;
270
+ aggregate<
271
+ const Metrics extends AggregateMetrics<Fields>,
272
+ const GroupBy extends readonly (keyof Fields & string)[],
273
+ >(
274
+ options: GroupedAggregateOptions<Fields, Metrics, GroupBy>,
275
+ ): Promise<AggregateGroupResult<AggregateGroupKey<Fields, GroupBy[number]>, AggregateValues<Metrics>>>;
146
276
  }
147
277
 
148
278
  interface WriteObjectClient<Fields> {
@@ -155,8 +285,12 @@ interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
155
285
  readonly records: RecordsApi<Fields>;
156
286
  }
157
287
 
288
+ interface AsUserObjectClient<Fields> extends WriteObjectClient<Fields> {
289
+ readonly records: AsUserRecordsApi<Fields>;
290
+ }
291
+
158
292
  interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
159
- object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
293
+ object<Slug extends keyof Schema & string>(slug: Slug): AsUserObjectClient<Schema[Slug]>;
160
294
  }
161
295
 
162
296
  interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
@@ -171,7 +305,7 @@ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
171
305
  `system` object containing creation/update metadata.
172
306
 
173
307
  `getMany(ids, { fields })` reads up to 200 records by ID with a single capability
174
- call. `fields` is required and must be a non-empty list of field slugs. IDs are
308
+ call. `fields` is required, as for every read (see [Choosing fields](#choosing-fields)). IDs are
175
309
  trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
176
310
  ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
177
311
  An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
@@ -189,9 +323,13 @@ const accountById = new Map(records.map(record => [record.id, record]));
189
323
  Use `getMany` instead of calling `get` in a loop. Every capability call counts
190
324
  towards the project's limits, and a record trigger can receive 200 records at once.
191
325
 
192
- Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
193
- responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
194
- `RecordReference` and send only the ID to Cogover.
326
+ Service `0`/`1` booleans are normalized to JavaScript booleans. A lookup or reference
327
+ value is a `RecordReference` with `id`, `name`, and `objectSlug`. Its `name` is `""`
328
+ unless the read expanded the lookup, except in a `reference` field, which stores the
329
+ name with the record; an expanded value also has the linked record's `fields` (see
330
+ [Linked records](#linked-records)). The `new` and `old` values of a
331
+ [record trigger](record-triggers.md) always carry lookup names. Writes accept an ID or
332
+ a `RecordReference` and send only the ID to Cogover.
195
333
 
196
334
  A `file` field is read as `FileValue` objects: one `FileValue`, or `null`, for a
197
335
  single file field and an array for a multiple one. `url` is present only when Cogover
@@ -207,6 +345,203 @@ milliseconds. Writes accept the same forms and also an ISO 8601 string, which is
207
345
  field as its UTC day. Other text for these fields throws `ValidationError` with
208
346
  `details.reason` `"INVALID_FIELD_VALUE"`.
209
347
 
348
+ ### Choosing fields
349
+
350
+ `get`, `getMany`, and `list` return only the fields named in `fields`, so a read
351
+ costs no more than what the script uses. `fields` is required and is one of:
352
+
353
+ - a non-empty list of field slugs, trimmed and deduplicated in their original order;
354
+ - the string `"*"` on its own: every field that the identity in use may read and the
355
+ project's identity policy grants. When the policy grants only some fields, `"*"`
356
+ means those fields, not every field of the Object.
357
+
358
+ Leaving `fields` out, or passing `null`, an empty list, `["*"]`, or a value that is not
359
+ a field slug, throws `ValidationError` before any request is sent, with this message:
360
+
361
+ ```text
362
+ fields is required: pass field slugs or "*" (@cogover/sdk 0.13.0+)
363
+ ```
364
+
365
+ Cogover refuses such a read with the same message, so a project version published with
366
+ an older SDK that reads without `fields` fails the same way: add `fields` to its reads
367
+ and publish it again.
368
+
369
+ The system slugs `id`, `created`, `updated`, and `created_by` may be listed; their
370
+ values are always returned in `id` and `system`, not in `fields`. `where` and `orderBy`
371
+ may use fields that are not in `fields`. Every field of `fields`, `where`, and
372
+ `orderBy` must be granted by the project's identity policy, otherwise the read throws
373
+ `PermissionDeniedError`; a slug that the Object does not have throws `ValidationError`.
374
+
375
+ The result type follows `fields`. With workspace declarations, `fields: ["code",
376
+ "amount"]` returns `CogoverRecord<Pick<Fields, "code" | "amount">>`, so reading a field
377
+ that was not requested is a compile error, and `"*"` returns every declared field:
378
+
379
+ ```typescript
380
+ const order = await orders.records.get(orderId, { fields: ["code", "amount"] });
381
+ const amount = order?.fields.amount; // number | null | undefined
382
+ // order?.fields.status would not compile: `status` was not requested.
383
+ const full = await orders.records.get(orderId, { fields: "*" });
384
+ ```
385
+
386
+ A capability result is limited to 1,048,576 bytes (see
387
+ [Execution limits](overview.md#execution-limits)). `"*"` on an Object with many or long
388
+ fields can exceed it, particularly with `getMany` or a `list` page of 200 records; the
389
+ call then throws `ValidationError` with `details.limit`. Name the fields the script
390
+ needs, or read fewer records per call.
391
+
392
+ ### Linked records
393
+
394
+ A read does not look up the records that its lookup fields point to unless it asks for
395
+ them:
396
+
397
+ - a `lookup_normal` value is `{ id, name: "", objectSlug }`, or an array of them for a
398
+ multiple lookup;
399
+ - a `reference` value keeps its `name`, which the record stores;
400
+ - `system.createdBy` is `{ id, name: "" }`.
401
+
402
+ Set `expandLookups` when the script needs the names or fields of the linked records:
403
+
404
+ ```typescript
405
+ const page = await orders.records.list({
406
+ fields: ["code", "customer", "owner"],
407
+ expandLookups: { customer: ["credit_limit", "tier"], owner: "*" },
408
+ limit: 50,
409
+ });
410
+ const customer = page.items[0]?.fields.customer;
411
+ // { id: "...", name: "ABC Company", objectSlug: "account",
412
+ // fields: { credit_limit: 5000000, tier: "gold" } }
413
+ ```
414
+
415
+ - `true` expands every lookup and reference field among the returned fields, each with
416
+ `"*"` of the linked Object.
417
+ - An object expands only the fields it names. Each key must be a lookup or reference
418
+ field that is also in `fields`; its value is `"*"` or a non-empty list of field slugs
419
+ of the linked Object.
420
+ - `false`, or leaving it out, expands nothing.
421
+
422
+ An expanded value is `{ id, name, objectSlug, fields }`, where `fields` holds the
423
+ selected fields of the linked record. With workspace declarations, the `fields` of a
424
+ `RecordReference<"account">` are typed as a partial of the `account` fields. When
425
+ `expandLookups` is present, `system.createdBy.name` is also filled in with the `name`
426
+ field of the creator's personnel record, which can be a generated code rather than the
427
+ person's full name; for display names, use
428
+ [`org.personnel.get`](organization-structure.md#orgpersonnelgetid-options-and-orgpersonnelgetmanyids-options)
429
+ with `withDisplay: true`.
430
+
431
+ Linked records are read with the same identity as the read itself: the caller,
432
+ `data.asUser()`, or `data.asSystem()`. The project's identity policy must grant reading
433
+ the linked Object:
434
+
435
+ - With `true` or `"*"`, only the linked fields that the policy grants are returned.
436
+ When the policy does not grant reading the linked Object, its values stay
437
+ unexpanded.
438
+ - With a list of fields, every listed field must be granted, otherwise the read throws
439
+ `PermissionDeniedError` whose `details.objectSlug` is the linked Object and, for a field
440
+ that is not granted, `details.fieldSlug` is that field; a slug that the linked Object
441
+ does not have throws `ValidationError`.
442
+ - A linked record that cannot be read, because the identity may not see it or it was
443
+ deleted, stays unexpanded, without `fields`.
444
+
445
+ An unexpanded value is `{ id, name: "", objectSlug }` in a lookup field; in a
446
+ `reference` field it keeps the name that the record stores.
447
+
448
+ Only one level is expanded: lookups inside a linked record's `fields` are
449
+ `{ id, name: "", objectSlug }`. One call expands at most 1,000 distinct linked records;
450
+ more throws `ValidationError` (`expandLookups can resolve at most 1000 linked records per
451
+ call`) and nothing is read. The read is still one capability call, but Cogover reads
452
+ every linked Object as well, which takes time: expand only the lookups whose names or
453
+ fields the script uses. The result, linked records included, must fit in the
454
+ 1,048,576-byte limit.
455
+
456
+ An `expandLookups` value of the wrong shape throws `ValidationError` before any request
457
+ is sent: an empty object, a key that is not a field slug or is not in `fields`, or a
458
+ value that is neither `"*"` nor a non-empty list of field slugs.
459
+
460
+ ### Aggregates
461
+
462
+ `records.aggregate(options)` counts, sums, averages, and finds the smallest and largest
463
+ values of the records that match `where`, in one capability call and without reading
464
+ the records:
465
+
466
+ ```typescript
467
+ const totals = await orders.records.aggregate({
468
+ where: orders.fields.status.eq("paid"),
469
+ metrics: { orders: { count: "id" }, revenue: { sum: "amount" } },
470
+ });
471
+ // { values: { orders: 120, revenue: 530000000 } }
472
+
473
+ const byStatus = await orders.records.aggregate({
474
+ groupBy: ["status"],
475
+ metrics: { orders: { count: "id" }, revenue: { sum: "amount" } },
476
+ limit: 100,
477
+ });
478
+ // { groups: [{ key: { status: "paid" }, values: { orders: 120, revenue: 530000000 } }],
479
+ // truncated: false }
480
+ ```
481
+
482
+ `metrics` names 1 to 20 metrics. A metric name is a letter followed by up to 63
483
+ letters, digits, or underscores, and each metric is exactly one of:
484
+
485
+ | Metric | Field | Value |
486
+ |---|---|---|
487
+ | `{ count: "id" }` | | number of matching records |
488
+ | `{ count: field }` | any field except `reference`, `file`, and `url` | number of matching records with a value in the field |
489
+ | `{ countDistinct: field }` | the fields that `count` accepts | number of distinct values, approximate on large sets |
490
+ | `{ sum: field }` | `numeric`, `decimal`, `currency`, `percent` | sum |
491
+ | `{ avg: field }` | the number types above | average; `null` when no matching record has a value |
492
+ | `{ min: field }`, `{ max: field }` | the number types above, `date`, `date_time` | smallest or largest value; `null` when no matching record has a value; epoch milliseconds for a date |
493
+
494
+ Counts and sums are `0` when no record matches.
495
+
496
+ `where` works as in `list`. Without `groupBy`, the result is `{ values }` with one value
497
+ per metric name. With `groupBy`, a list of 1 to 3 field slugs, the result is
498
+ `{ groups, truncated }`: one `{ key, values }` entry for each combination of values,
499
+ the groups with the most records first. `groupBy` accepts fields of type
500
+ `single_choice`, `multi_choices`, `radio_button`, `checkbox`, `boolean`,
501
+ `lookup_normal`, `date`, `date_time`, `numeric`, `decimal`, `currency`, and `percent`;
502
+ another field, such as a text or `reference` field, throws `ValidationError`. `key` maps
503
+ each `groupBy` field to its value: the record ID for a lookup, the option slug for a
504
+ choice, `true` or `false`, a number, or epoch milliseconds for a `date` or `date_time`.
505
+ A key value is never `null`: a record without a value in a `groupBy` field is in no
506
+ group.
507
+
508
+ `limit`, accepted only with `groupBy`, is the most groups to return: 1 to 5,000, and
509
+ 1,000 when it is left out. `truncated` is `true` when there were more groups and only
510
+ the first `limit` are returned.
511
+
512
+ Every field of `where`, `groupBy`, and `metrics`, except `"id"`, must be granted by the
513
+ project's identity policy, otherwise the call throws `PermissionDeniedError`. Only the
514
+ records that the identity in use can see are counted.
515
+
516
+ A client from `data.asUser()` has narrower limits:
517
+
518
+ - It cannot group. Its type does not accept `groupBy`, and passing it anyway throws
519
+ `ValidationError` (`aggregate with groupBy is not supported for asUser(); use the
520
+ caller or asSystem()`).
521
+ - Its metrics are `count` on `"id"`, and `count`, `sum`, `avg`, `min`, and `max` on
522
+ number fields (`AsUserAggregateMetric`). Another metric throws `ValidationError`
523
+ (`metrics.<name>: asUser() without groupBy supports only count on id and count, sum,
524
+ avg, min and max on number fields; use the caller or asSystem()`).
525
+
526
+ The same limits apply to `data.object()` when the execution reads as a user who is not
527
+ an HTTP caller: in a record trigger for a change made by a user, or in a job run that
528
+ has a user. Grouping
529
+ there throws `ValidationError` (`aggregate with groupBy is not supported for the default
530
+ identity of this invocation, which reads as a delegated user; use asSystem()`). Use
531
+ `data.asSystem()` there, or the caller in an HTTP route, for groups and the other
532
+ metrics.
533
+
534
+ Invalid options throw `ValidationError` before any request is sent: no metric or more
535
+ than 20, an invalid metric name, a metric that is not exactly one of the forms above,
536
+ an empty `groupBy` or one with more than 3 fields, `limit` without `groupBy`, or a
537
+ `limit` outside 1 to 5,000.
538
+
539
+ Aggregates are computed from a search index that follows record writes after a short
540
+ delay, usually about one second, so a record written just before may not be counted
541
+ yet. `aggregate` is allowed in a before-change record trigger, but the user's write
542
+ waits while it runs: keep such calls few, and do not rely on them to see the records
543
+ being written.
544
+
210
545
  ## Filters and sorting
211
546
 
212
547
  ```typescript
@@ -295,9 +630,9 @@ maps each field slug (`$record` for the whole record) to the trigger's error cod
295
630
  the others are still deleted, the rejected IDs are in `notDeleted`, and
296
631
  `recordErrors` maps each rejected ID to `{ reason: "TRIGGER_REJECTED", fieldErrors?,
297
632
  messages? }`. When the trigger rejects every record, nothing is deleted and the call
298
- throws `ValidationError` with `details.reason` `"TRIGGER_REJECTED"`. Record IDs, object slugs, the field slugs of `getMany`, and the
299
- `matchBy` of `upsertByUniqueField` are validated before a request is sent; Cogover
300
- checks the other field slugs.
633
+ throws `ValidationError` with `details.reason` `"TRIGGER_REJECTED"`. Record IDs, object slugs, the options of `get`,
634
+ `getMany`, `list`, and `aggregate`, and the `matchBy` of `upsertByUniqueField` are
635
+ validated before a request is sent; Cogover checks that the field slugs exist.
301
636
 
302
637
  A field value that Cogover refuses throws `ValidationError` whose `details` name the
303
638
  field in `fieldSlug`: `details.reason` is `"REQUIRED_FIELD_MISSING"` for a required
@@ -326,15 +661,16 @@ invocation this is the caller; a system invocation keeps system access.
326
661
 
327
662
  Returns a new immutable client for reads and writes as the specified personnel ID (not an
328
663
  account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
329
- value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
330
- whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
331
- `deleteMany` as well as batch insert, batch update, and business upsert, with the
332
- same argument and return types as the default record API.
333
-
334
- `get(id, options?)` returns `CogoverRecord<TFields> | null`; `list(options?)` returns
335
- `RecordPage<TFields>`. Field selection, filters, sorting and cursors work as on the
336
- default client. Reads apply the selected user's permissions and approved project
337
- field restrictions. An empty successful lookup returns `null`; server failures
664
+ value throws `ValidationError`. Its `object(slug)` returns `AsUserObjectClient<TFields>`,
665
+ whose `records: AsUserRecordsApi<TFields>` exposes `get`, `getMany`, `list`, `aggregate`,
666
+ `create`, `update`, and `deleteMany` as well as batch insert, batch update, and business
667
+ upsert, with the same argument and return types as the default record API, except that
668
+ its `aggregate` cannot group.
669
+
670
+ `get(id, options)` returns the record or `null`, and `list(options)` returns a
671
+ `RecordPage`, both narrowed to `fields`. Field selection, `expandLookups`, filters,
672
+ sorting and cursors work as on the default client. Reads, linked records included,
673
+ apply the selected user's permissions and approved project field restrictions. An empty successful lookup returns `null`; server failures
338
674
  throw errors instead of being treated as missing records or an empty page.
339
675
 
340
676
  ```typescript
@@ -350,8 +686,8 @@ const page = await delegatedOrders.records.list({
350
686
  ### `data.asSystem(): DataApi<TSchema>`
351
687
 
352
688
  Returns a new immutable client for system record access, including during an
353
- authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
354
- `deleteMany`, including batch writes and business upsert. System access does not
689
+ authenticated public invocation. It supports `get`, `getMany`, `list`, `aggregate` (with
690
+ groups), `create`, `update`, and `deleteMany`, including batch writes and business upsert. System access does not
355
691
  apply the caller's record permissions; approved project restrictions, field
356
692
  validation, workspace boundaries, and runtime limits still apply. It neither
357
693
  changes the invocation's caller nor modifies existing clients.
@@ -443,5 +779,14 @@ types as follows:
443
779
  | unknown field type | `unknown` |
444
780
 
445
781
  Fields that are not required include `null`; metadata marked `multiple` becomes a
446
- readonly array unless its base type is already an array. Add the generated file to
782
+ readonly array unless its base type is already an array. When a lookup's target Object
783
+ is declared too, the `fields` of its `RecordReference` are typed from that Object, and
784
+ `expandLookups` accepts only that Object's field slugs. Add the generated file to
447
785
  the project's TypeScript compilation and do not edit it manually.
786
+
787
+ The generated file imports the SDK types that its fields use (`RecordReference`,
788
+ `FileValue`, `UrlValue`) with `import type`. A file generated by `@cogover/sdk` before
789
+ 0.13.0 did not import them: with `skipLibCheck: false` it fails with `Cannot find name
790
+ 'RecordReference'`, and with `skipLibCheck: true` its lookup, file, and URL fields are
791
+ silently typed `any`, which also disables the checks on `fields`, `expandLookups`, and
792
+ `aggregate` for them. Generate such a file again.
@@ -71,6 +71,9 @@ expiry. Both option values must be safe integers. `expectedVersion` enables
71
71
  compare-and-set: `0` means create only, a positive value must match the current
72
72
  version, and omission is an unconditional upsert.
73
73
  Conflicts throw `StateConflictError`; the returned entry has the new version.
74
+ A project keeps at most 100,000 unexpired entries: a `set` that would create another
75
+ throws `RateLimitError` and writes nothing, while updates of existing keys still work.
76
+ Expired entries are removed automatically and do not count.
74
77
 
75
78
  A version counts the writes since the entry was created. After `delete` or expiry, the
76
79
  next `set` creates a new entry whose version starts again at 1, so a version seen