@cogover/sdk 0.12.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,8 @@ documentation, and type checking.
11
11
  ## Requirements
12
12
 
13
13
  - Node.js 18 or later.
14
- - A TypeScript project using ECMAScript Modules (ESM).
14
+ - A TypeScript project using ECMAScript Modules (ESM), type checked with TypeScript 5.0
15
+ or later.
15
16
 
16
17
  ## Installation
17
18
 
@@ -48,7 +49,9 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
48
49
  data, schema, logging, state, lock, push, notification, email, job, secret, and
49
50
  crypto APIs, waits for the async handler, and serializes its result. Cogover
50
51
  authentication credentials are not exposed to project code, and Cogover enforces
51
- the configured permissions and limits on capability calls.
52
+ the configured permissions and the per-execution limits on capability calls and
53
+ records. `limits.usage()` (also `context.limits`) reports how much of each budget
54
+ the execution has used, without a capability call.
52
55
 
53
56
  ## Current identity and workspace
54
57
 
@@ -149,7 +152,8 @@ export const triggers = [
149
152
  ];
150
153
  ```
151
154
 
152
- `record.new` and `record.old` contain only the listed `fields`. Assign fields of
155
+ `record.new` and `record.old` contain only the listed `fields`, and their lookup
156
+ values carry the linked record's name. Assign fields of
153
157
  `record.new` to change what is saved: only `writableFields` may change, and values
154
158
  use the same format as `records.update` input. `record.addError(field, code,
155
159
  message?)` rejects a record; the optional English message is shown to the end user
@@ -348,16 +352,38 @@ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key"
348
352
  ## Record API
349
353
 
350
354
  An Object client exposes `records.get`, `records.getMany`, `records.list`,
351
- `records.create`, `records.update`, `records.batchInsert`, `records.batchUpdate`,
352
- `records.upsertByUniqueField`, and `records.deleteMany`. List filters are built from typed
353
- field references, so scripts do not provide transport-specific field metadata or
354
- response envelopes.
355
+ `records.aggregate`, `records.create`, `records.update`, `records.batchInsert`,
356
+ `records.batchUpdate`, `records.upsertByUniqueField`, and `records.deleteMany`. List
357
+ filters are built from typed field references, so scripts do not provide
358
+ transport-specific field metadata or response envelopes.
359
+
360
+ Every read names the fields it needs: `fields` is required by `get`, `getMany`, and
361
+ `list`, either as a list of field slugs or as `"*"` for every field that the identity
362
+ in use may read (with `data.asUser()` or `data.asSystem()`, only the fields that the
363
+ project's identity policy grants). A read without `fields` throws
364
+ `ValidationError` (`fields is required: pass field slugs or "*" (@cogover/sdk
365
+ 0.13.0+)`). With workspace types, the result is narrowed to the requested fields, so
366
+ reading a field that was not requested is a compile error. A single result is limited
367
+ to 1 MiB; prefer a list of fields to `"*"` for `getMany` and large pages.
355
368
 
356
369
  Cogover normalizes service values to the declared SDK types: booleans become
357
- `true`/`false`, and lookup/reference values are reduced to
358
- `{ id, name, objectSlug }` so nested record fields are not exposed. For writes,
359
- reference fields accept either a record ID or a `RecordReference`; only the ID is
360
- sent to the Record API.
370
+ `true`/`false`, and lookup/reference values are `RecordReference` objects
371
+ `{ id, name, objectSlug }`. A lookup's `name` is `""`, and so is
372
+ `system.createdBy.name`, unless the read sets `expandLookups`; a `reference` field
373
+ keeps the name it stores. `expandLookups: true`, or an object such as
374
+ `{ customer: ["credit_limit", "tier"], owner: "*" }`, adds the linked records' names
375
+ and selected `fields`, read one level deep with the same identity and permissions
376
+ as the read itself. Expand only the lookups the script uses, since each one reads
377
+ more data. For writes, reference fields accept either a record ID or a
378
+ `RecordReference`; only the ID is sent to the Record API.
379
+
380
+ ```typescript
381
+ const order = await orders.records.get(orderId, {
382
+ fields: ["code", "amount", "customer"],
383
+ expandLookups: { customer: ["credit_limit"] },
384
+ });
385
+ const creditLimit = order?.fields.customer?.fields?.credit_limit;
386
+ ```
361
387
 
362
388
  ```typescript
363
389
  import { and, defineScript } from "@cogover/sdk";
@@ -365,6 +391,7 @@ import { and, defineScript } from "@cogover/sdk";
365
391
  export default defineScript(async ({ data }) => {
366
392
  const orders = data.object("order");
367
393
  return orders.records.list({
394
+ fields: ["code", "status", "total"],
368
395
  where: and(
369
396
  orders.fields.status.in(["new", "nurturing"]),
370
397
  orders.fields.is_active.eq(true),
@@ -381,6 +408,28 @@ call. `fields` is required. The result is `{ records, missingIds }`: IDs that do
381
408
  exist or are not visible to the identity in use are reported in `missingIds` instead
382
409
  of being dropped. Prefer it to calling `records.get` in a loop.
383
410
 
411
+ `records.aggregate` counts, sums, averages, and finds the smallest and largest values
412
+ of the matching records in one call, without reading them. `groupBy` groups by up to
413
+ three fields and `limit` (1 to 5,000, default 1,000) caps the groups; `truncated`
414
+ reports that more groups exist. Aggregates follow record writes after about one
415
+ second. A client from `data.asUser()`, like `data.object()` in a trigger or job that runs
416
+ as a user, cannot group and supports only counts and number metrics; use
417
+ `data.asSystem()` there.
418
+
419
+ ```typescript
420
+ const totals = await orders.records.aggregate({
421
+ where: orders.fields.status.eq("paid"),
422
+ metrics: { orders: { count: "id" }, revenue: { sum: "total" } },
423
+ });
424
+ // totals.values: { orders: 120, revenue: 530000000 }
425
+
426
+ const byStatus = await orders.records.aggregate({
427
+ groupBy: ["status"],
428
+ metrics: { orders: { count: "id" }, average: { avg: "total" } },
429
+ });
430
+ // byStatus.groups: [{ key: { status: "paid" }, values: { orders: 120, average: 4416666 } }]
431
+ ```
432
+
384
433
  Batch writes are best-effort per row. Check `result.success` or every entry in
385
434
  `result.results`; a successful request envelope does not mean every row succeeded.
386
435
  Business upsert accepts one `matchBy` field that must be configured as a single-field
@@ -438,7 +487,7 @@ await data.asSystem().object("order").records.update(order.id, changes);
438
487
 
439
488
  Both methods return new immutable clients and preserve workspace typing. `asUser`
440
489
  accepts a personnel ID (not an account ID) and supports the full record API, including
441
- batch writes and business upsert. Reads apply that user's permissions and approved field restrictions;
490
+ batch writes and business upsert, except grouping in `records.aggregate`. Reads apply that user's permissions and approved field restrictions;
442
491
  read access must be approved separately from writes. `asSystem` supports the
443
492
  full record API, including in authenticated public scripts, without changing the
444
493
  original caller or existing clients. `asSystem` may also write fields whose manual
@@ -590,7 +639,10 @@ npx cogover-generate-workspace-types objects.json workspace.d.ts
590
639
  ```
591
640
 
592
641
  The declaration makes object slugs, field slugs, value types, and choice option
593
- slugs available to TypeScript. `schema.object(slug)` is read-only; Object and
642
+ slugs available to TypeScript, and types the `fields` of an expanded lookup from
643
+ its target Object. It imports the SDK types it uses (`RecordReference`, `FileValue`,
644
+ `UrlValue`); regenerate a declaration made by a version before 0.13.0, which left
645
+ them unresolved and typed those fields as `any` under `skipLibCheck`. `schema.object(slug)` is read-only; Object and
594
646
  field mutation are intentionally not part of this SDK.
595
647
 
596
648
  ## TypeScript
package/dist/data.d.ts CHANGED
@@ -1,18 +1,146 @@
1
1
  import type { FieldReferences, FilterExpression, SortExpression } from "./query.js";
2
- import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, GetManyResult, RecordPage, UpdateFields, UpsertFields, UpsertResult } from "./records.js";
3
- import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
4
- export interface GetRecordOptions<TFields> {
5
- readonly fields?: readonly StringKeyOf<TFields>[];
2
+ import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, FileValue, GetManyResult, RecordPage, UpdateFields, UpsertFields, UpsertResult, UrlValue } from "./records.js";
3
+ import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf, WorkspaceObjects } from "./workspace.js";
4
+ /**
5
+ * Fields a read returns: a non-empty list of field slugs, or `"*"` for every field that the identity in use and the
6
+ * project's identity policy may read.
7
+ */
8
+ export type FieldSelection<TFields> = "*" | readonly StringKeyOf<TFields>[];
9
+ /** Fields of the records that a read returns for `fields`: only the listed fields, or every field for `"*"`. */
10
+ export type SelectedFields<TFields, TSelection extends FieldSelection<TFields>> = TSelection extends "*" ? TFields : TSelection extends readonly (infer TSlug)[] ? StringKeyOf<TFields> extends TSlug ? TFields : Pick<TFields, Extract<TSlug, keyof TFields>> : TFields;
11
+ /** A lookup or reference value, told apart from a file value by its branded ID. */
12
+ interface LinkedRecordValue {
13
+ readonly id: CogoverRecordId;
14
+ readonly name: string;
6
15
  }
7
- export interface GetManyOptions<TFields> {
8
- readonly fields: readonly StringKeyOf<TFields>[];
16
+ /** Slugs of the lookup and reference fields; a field of unknown type may be one. */
17
+ type LookupFieldSlug<TFields> = string extends keyof TFields ? string : {
18
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends LinkedRecordValue | readonly LinkedRecordValue[] ? K : never;
19
+ }[StringKeyOf<TFields>];
20
+ type LinkedObjectSlug<TValue> = NonNullable<TValue> extends readonly (infer TItem)[] ? LinkedObjectSlug<TItem> : NonNullable<TValue> extends {
21
+ readonly objectSlug?: infer TSlug;
22
+ } ? Exclude<TSlug, undefined> : string;
23
+ type LinkedFieldSlug<TValue> = LinkedObjectSlug<TValue> extends infer TSlug ? TSlug extends keyof WorkspaceObjects ? StringKeyOf<WorkspaceObjects[TSlug]> : string : string;
24
+ /**
25
+ * Lookups to expand in a read: `true` expands every lookup and reference field in `fields`; an object expands only
26
+ * the named ones, each with the linked record's field slugs or `"*"`. `false` expands nothing, like leaving it out.
27
+ */
28
+ export type ExpandLookups<TFields> = boolean | ([LookupFieldSlug<TFields>] extends [never] ? never : {
29
+ readonly [K in LookupFieldSlug<TFields>]?: "*" | readonly LinkedFieldSlug<TFields[K]>[];
30
+ });
31
+ export interface GetRecordOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
32
+ readonly fields: TSelection;
33
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
9
34
  }
10
- export interface ListOptions<TFields> {
35
+ export interface GetManyOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
36
+ readonly fields: TSelection;
37
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
38
+ }
39
+ export interface ListOptions<TFields, TSelection extends FieldSelection<TFields> = FieldSelection<TFields>> {
11
40
  readonly where?: FilterExpression;
12
41
  readonly orderBy?: readonly SortExpression[];
13
- readonly fields?: readonly StringKeyOf<TFields>[];
42
+ readonly fields: TSelection;
14
43
  readonly limit?: number;
15
44
  readonly cursor?: string;
45
+ readonly expandLookups?: ExpandLookups<SelectedFields<TFields, TSelection>>;
46
+ }
47
+ /** Slugs of the fields whose values are `TValue`; a field of unknown type may be one. */
48
+ type FieldSlugOfType<TFields, TValue> = string extends keyof TFields ? string : {
49
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends TValue ? K : never;
50
+ }[StringKeyOf<TFields>];
51
+ /** Slugs of the fields that can be counted: every field except file and URL fields (and reference fields). */
52
+ type CountableFieldSlug<TFields> = string extends keyof TFields ? string : {
53
+ [K in StringKeyOf<TFields>]-?: unknown extends TFields[K] ? K : NonNullable<TFields[K]> extends LinkedRecordValue | readonly LinkedRecordValue[] ? K : NonNullable<TFields[K]> extends UrlValue | FileValue | readonly (UrlValue | FileValue)[] ? never : K;
54
+ }[StringKeyOf<TFields>];
55
+ /**
56
+ * One metric of `records.aggregate`. `count` counts the matching records for `"id"` and the records with a value
57
+ * otherwise; `countDistinct` counts distinct values approximately on large sets; neither takes a reference, file or
58
+ * URL field. `sum` and `avg` take a number field; `min` and `max` take a number or date field.
59
+ */
60
+ export type AggregateMetric<TFields> = {
61
+ readonly count: "id" | CountableFieldSlug<TFields>;
62
+ } | {
63
+ readonly countDistinct: CountableFieldSlug<TFields>;
64
+ } | {
65
+ readonly sum: FieldSlugOfType<TFields, number>;
66
+ } | {
67
+ readonly avg: FieldSlugOfType<TFields, number>;
68
+ } | {
69
+ readonly min: FieldSlugOfType<TFields, number | string>;
70
+ } | {
71
+ readonly max: FieldSlugOfType<TFields, number | string>;
72
+ };
73
+ /**
74
+ * One metric of `records.aggregate` on a client from `asUser()`: `count` on `"id"` or a number field, or `sum`,
75
+ * `avg`, `min` or `max` on a number field.
76
+ */
77
+ export type AsUserAggregateMetric<TFields> = {
78
+ readonly count: "id" | FieldSlugOfType<TFields, number>;
79
+ } | {
80
+ readonly sum: FieldSlugOfType<TFields, number>;
81
+ } | {
82
+ readonly avg: FieldSlugOfType<TFields, number>;
83
+ } | {
84
+ readonly min: FieldSlugOfType<TFields, number>;
85
+ } | {
86
+ readonly max: FieldSlugOfType<TFields, number>;
87
+ };
88
+ type AggregateMetrics<TFields> = Readonly<Record<string, AggregateMetric<TFields>>>;
89
+ type AsUserAggregateMetrics<TFields> = Readonly<Record<string, AsUserAggregateMetric<TFields>>>;
90
+ /** Options of `records.aggregate` without groups: one set of metric values over every matching record. */
91
+ export interface AggregateOptions<TFields, TMetrics extends AggregateMetrics<TFields> | AsUserAggregateMetrics<TFields> = AggregateMetrics<TFields>> {
92
+ readonly where?: FilterExpression;
93
+ /** 1 to 20 metrics by name: a letter followed by up to 63 letters, digits or underscores. */
94
+ readonly metrics: TMetrics;
95
+ /** Grouping uses `GroupedAggregateOptions`; a client from `asUser()` cannot group. */
96
+ readonly groupBy?: never;
97
+ /** Only a grouped aggregate takes `limit`. */
98
+ readonly limit?: never;
99
+ }
100
+ /** Options of `records.aggregate` with groups: metric values for each combination of the `groupBy` values. */
101
+ export interface GroupedAggregateOptions<TFields, TMetrics extends AggregateMetrics<TFields> = AggregateMetrics<TFields>, TGroupBy extends readonly StringKeyOf<TFields>[] = readonly StringKeyOf<TFields>[]> {
102
+ readonly where?: FilterExpression;
103
+ /** 1 to 3 field slugs. */
104
+ readonly groupBy: TGroupBy;
105
+ /** 1 to 20 metrics by name: a letter followed by up to 63 letters, digits or underscores. */
106
+ readonly metrics: TMetrics;
107
+ /** Most groups to return, from 1 to 5000; Cogover returns up to 1000 when it is left out. */
108
+ readonly limit?: number;
109
+ }
110
+ /**
111
+ * Metric values by metric name. Counts and sums are numbers, `0` when no record matches; `avg`, `min` and `max` are
112
+ * `null` when no matching record has a value.
113
+ */
114
+ export type AggregateValues<TMetrics> = {
115
+ readonly [K in keyof TMetrics]: TMetrics[K] extends {
116
+ readonly count: string;
117
+ } | {
118
+ readonly countDistinct: string;
119
+ } | {
120
+ readonly sum: string;
121
+ } ? number : number | null;
122
+ };
123
+ type AggregateKeyValue<TValue> = TValue extends LinkedRecordValue ? CogoverRecordId : TValue extends readonly (infer TItem)[] ? AggregateKeyValue<NonNullable<TItem>> : TValue extends boolean ? boolean : TValue extends number ? number : TValue extends string ? string extends TValue ? number : TValue : string | number | boolean;
124
+ /**
125
+ * Values of one group by field slug: a record ID for a lookup, an option slug for a choice, `true`/`false`, a
126
+ * number, or epoch milliseconds for a date or date-time field. Text fields cannot be grouped, so a field typed
127
+ * `string` is a date here.
128
+ */
129
+ export type AggregateGroupKey<TFields, TSlug extends StringKeyOf<TFields>> = {
130
+ readonly [K in TSlug]: AggregateKeyValue<NonNullable<TFields[K]>>;
131
+ };
132
+ export interface AggregateResult<TValues = Readonly<Record<string, number | null>>> {
133
+ readonly values: TValues;
134
+ }
135
+ export interface AggregateGroup<TKey = Readonly<Record<string, string | number | boolean>>, TValues = Readonly<Record<string, number | null>>> {
136
+ readonly key: TKey;
137
+ readonly values: TValues;
138
+ }
139
+ export interface AggregateGroupResult<TKey = Readonly<Record<string, string | number | boolean>>, TValues = Readonly<Record<string, number | null>>> {
140
+ /** Groups with the most records first. A record without a value in a `groupBy` field is in no group. */
141
+ readonly groups: AggregateGroup<TKey, TValues>[];
142
+ /** `true` when there were more groups than `limit` and only the first `limit` are returned. */
143
+ readonly truncated: boolean;
16
144
  }
17
145
  export interface RecordWritesApi<TFields> {
18
146
  create(fields: CreateFields<TFields>): Promise<CogoverRecordId>;
@@ -22,11 +150,25 @@ export interface RecordWritesApi<TFields> {
22
150
  upsertByUniqueField<TMatchBy extends StringKeyOf<TFields>>(matchBy: TMatchBy, fields: UpsertFields<TFields, TMatchBy>): Promise<UpsertResult>;
23
151
  deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
24
152
  }
25
- export interface RecordsApi<TFields> extends RecordWritesApi<TFields> {
26
- get(id: string, options?: GetRecordOptions<TFields>): Promise<CogoverRecord<TFields> | null>;
153
+ /** Record API of a client from `asUser()`: the same as `RecordsApi` except that `aggregate` cannot group. */
154
+ export interface AsUserRecordsApi<TFields> extends RecordWritesApi<TFields> {
155
+ /** Reads one record; `null` when it does not exist or the identity in use cannot read it. */
156
+ get<const TSelection extends FieldSelection<TFields>>(id: string, options: GetRecordOptions<TFields, TSelection>): Promise<CogoverRecord<SelectedFields<TFields, TSelection>> | null>;
27
157
  /** Reads up to 200 records by ID in one call; unreadable IDs are reported in `missingIds`. */
28
- getMany(ids: readonly string[], options: GetManyOptions<TFields>): Promise<GetManyResult<TFields>>;
29
- list(options?: ListOptions<TFields>): Promise<RecordPage<TFields>>;
158
+ getMany<const TSelection extends FieldSelection<TFields>>(ids: readonly string[], options: GetManyOptions<TFields, TSelection>): Promise<GetManyResult<SelectedFields<TFields, TSelection>>>;
159
+ /** Reads one page of up to 200 matching records. */
160
+ list<const TSelection extends FieldSelection<TFields>>(options: ListOptions<TFields, TSelection>): Promise<RecordPage<SelectedFields<TFields, TSelection>>>;
161
+ /**
162
+ * Computes metrics over every matching record in one call; only the metrics of `AsUserAggregateMetric`. The
163
+ * same limits apply to `data.object()` where the execution reads as a user who is not the HTTP caller.
164
+ */
165
+ aggregate<const TMetrics extends AsUserAggregateMetrics<TFields>>(options: AggregateOptions<TFields, TMetrics>): Promise<AggregateResult<AggregateValues<TMetrics>>>;
166
+ }
167
+ export interface RecordsApi<TFields> extends AsUserRecordsApi<TFields> {
168
+ /** Computes metrics over every matching record in one call. */
169
+ aggregate<const TMetrics extends AggregateMetrics<TFields>>(options: AggregateOptions<TFields, TMetrics>): Promise<AggregateResult<AggregateValues<TMetrics>>>;
170
+ /** Computes metrics for each group of matching records in one call. */
171
+ aggregate<const TMetrics extends AggregateMetrics<TFields>, const TGroupBy extends readonly StringKeyOf<TFields>[]>(options: GroupedAggregateOptions<TFields, TMetrics, TGroupBy>): Promise<AggregateGroupResult<AggregateGroupKey<TFields, TGroupBy[number]>, AggregateValues<TMetrics>>>;
30
172
  }
31
173
  export interface WriteObjectClient<TFields> {
32
174
  readonly slug: string;
@@ -36,9 +178,13 @@ export interface WriteObjectClient<TFields> {
36
178
  export interface ObjectClient<TFields> extends WriteObjectClient<TFields> {
37
179
  readonly records: RecordsApi<TFields>;
38
180
  }
181
+ /** Object client of `asUser()`: its `records.aggregate` cannot group. */
182
+ export interface AsUserObjectClient<TFields> extends WriteObjectClient<TFields> {
183
+ readonly records: AsUserRecordsApi<TFields>;
184
+ }
39
185
  /** Reads and writes as an approved personnel ID. Authorization is enforced by Cogover. */
40
186
  export interface AsUserDataApi<TSchema extends object = EffectiveWorkspaceObjects> {
41
- object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
187
+ object<K extends StringKeyOf<TSchema>>(slug: K): AsUserObjectClient<FieldsFor<TSchema, K>>;
42
188
  }
43
189
  export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
44
190
  object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
@@ -47,3 +193,4 @@ export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
47
193
  /** New system client, including in public invocations. Requires approval; does not change this client. */
48
194
  asSystem(): DataApi<TSchema>;
49
195
  }
196
+ export {};
package/dist/data.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CogoverApiError, ValidationError } from "./errors.js";
2
2
  import { callBridge } from "./internal/bridge.js";
3
+ import { normalizeAggregateOptions, normalizeExpandLookups, normalizeFieldSelection, requireAggregateResult, } from "./internal/record-reads.js";
3
4
  import { requireFieldSlug, requireFields, requireSlug, requireText } from "./internal/validation.js";
4
5
  import { isRecord } from "./internal/values.js";
5
6
  import { createFieldReferences } from "./query.js";
@@ -27,11 +28,12 @@ function createObjectClient(slug, identity) {
27
28
  const fields = createFieldReferences();
28
29
  const records = Object.freeze({
29
30
  async get(id, options) {
31
+ const recordId = requireText(id, "record id");
30
32
  return callBridge("records.get", {
31
33
  identity,
32
34
  objectSlug: slug,
33
- id: requireText(id, "record id"),
34
- fields: options?.fields,
35
+ id: recordId,
36
+ ...readSelection(options),
35
37
  });
36
38
  },
37
39
  async getMany(ids, options) {
@@ -42,11 +44,8 @@ function createObjectClient(slug, identity) {
42
44
  if (uniqueIds.length > MAX_BATCH_RECORDS) {
43
45
  throw new ValidationError(`getMany() supports at most ${MAX_BATCH_RECORDS} unique record ids`);
44
46
  }
45
- const requestedFields = options?.fields;
46
- if (!Array.isArray(requestedFields) || requestedFields.length === 0) {
47
- throw new ValidationError("getMany() requires a non-empty fields array");
48
- }
49
- const fieldSlugs = [...new Set(requestedFields.map((field) => requireFieldSlug(field)))];
47
+ // `fields` is checked even when there is nothing to read, so the mistake is never hidden.
48
+ const selection = readSelection(options);
50
49
  if (uniqueIds.length === 0) {
51
50
  return { records: [], missingIds: [] };
52
51
  }
@@ -54,7 +53,7 @@ function createObjectClient(slug, identity) {
54
53
  identity,
55
54
  objectSlug: slug,
56
55
  ids: uniqueIds,
57
- fields: fieldSlugs,
56
+ ...selection,
58
57
  });
59
58
  if (!isRecord(result) || !Array.isArray(result.records) || !Array.isArray(result.missingIds)) {
60
59
  throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.getMany returned an invalid result");
@@ -62,16 +61,27 @@ function createObjectClient(slug, identity) {
62
61
  return result;
63
62
  },
64
63
  async list(options) {
64
+ const selection = readSelection(options);
65
65
  return callBridge("records.list", {
66
66
  identity,
67
67
  objectSlug: slug,
68
- where: options?.where,
69
- orderBy: options?.orderBy,
70
- fields: options?.fields,
71
- limit: options?.limit,
72
- cursor: options?.cursor,
68
+ where: options.where,
69
+ orderBy: options.orderBy,
70
+ fields: selection.fields,
71
+ limit: options.limit,
72
+ cursor: options.cursor,
73
+ expandLookups: selection.expandLookups,
73
74
  });
74
75
  },
76
+ async aggregate(options) {
77
+ const request = normalizeAggregateOptions(options, identity?.kind === "user");
78
+ const result = await callBridge("records.aggregate", {
79
+ identity,
80
+ objectSlug: slug,
81
+ ...request,
82
+ });
83
+ return requireAggregateResult(result, request);
84
+ },
75
85
  async create(fieldsToCreate) {
76
86
  return callBridge("records.create", {
77
87
  identity,
@@ -154,7 +164,13 @@ function createObjectClient(slug, identity) {
154
164
  });
155
165
  },
156
166
  });
157
- return Object.freeze({ slug, fields, records });
167
+ return Object.freeze({ slug, fields, records: records });
168
+ }
169
+ /** The validated `fields` and `expandLookups` of a read; `expandLookups` is left out when nothing is expanded. */
170
+ function readSelection(options) {
171
+ const fields = normalizeFieldSelection(isRecord(options) ? options.fields : undefined);
172
+ const expandLookups = normalizeExpandLookups(isRecord(options) ? options.expandLookups : undefined, fields);
173
+ return expandLookups === undefined ? { fields } : { fields, expandLookups };
158
174
  }
159
175
  function requireBatch(records, operation) {
160
176
  if (!Array.isArray(records) || records.length === 0) {
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { WorkspaceObjects } from "./workspace.js";
3
3
  export type { CogoverRecordId, RecordReference, UrlValue, FileValue, CogoverRecord, RecordPage, GetManyResult, DeleteResult, BatchWriteRowResult, BatchWriteResponse, BatchUpdateItem, UpsertFields, UpsertResult, CreateFields, UpdateFields, } from "./records.js";
4
4
  export { and, or } from "./query.js";
5
5
  export type { FilterOperator, FilterCondition, FilterGroup, FilterExpression, SortExpression, FieldReference, FieldReferences, } from "./query.js";
6
- export type { GetRecordOptions, GetManyOptions, ListOptions, RecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, DataApi, } from "./data.js";
6
+ export type { FieldSelection, SelectedFields, ExpandLookups, GetRecordOptions, GetManyOptions, ListOptions, AggregateMetric, AsUserAggregateMetric, AggregateOptions, GroupedAggregateOptions, AggregateValues, AggregateGroupKey, AggregateResult, AggregateGroup, AggregateGroupResult, RecordsApi, AsUserRecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, AsUserObjectClient, DataApi, } from "./data.js";
7
7
  export type { ObjectMetadata, SchemaApi } from "./schema.js";
8
8
  export type { ScriptLogger } from "./logger.js";
9
9
  export { defineScript } from "./script.js";
@@ -14,6 +14,8 @@ export { defineJob } from "./jobs.js";
14
14
  export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
15
15
  export type { SecretsApi } from "./secrets.js";
16
16
  export type { OrgApi, OrgPersonnelApi, OrgDepartmentsApi, OrgPositionsApi, OrgReadOptions, OrgPageOptions, OrgDepartmentMembersOptions, OrgPositionMembersOptions, OrgManagerOptions, OrgPersonnelChainOptions, OrgTreeOptions, OrgIsInDepartmentOptions, OrgIsManagerOfOptions, OrgPersonnelDisplay, OrgNameDisplay, OrgMembership, OrgMember, OrgPersonnel, OrgDepartment, OrgDepartmentNode, OrgPosition, OrgManagerTier, OrgManagerChain, OrgPage, OrgGetManyResult, } from "./org.js";
17
+ export { limits } from "./limits.js";
18
+ export type { LimitsApi, LimitUsage, LimitCounter } from "./limits.js";
17
19
  export { crypto } from "./crypto.js";
18
20
  export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
19
21
  export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ export { and, or } from "./query.js";
3
3
  export { defineScript } from "./script.js";
4
4
  export { defineTrigger } from "./trigger.js";
5
5
  export { defineJob } from "./jobs.js";
6
+ export { limits } from "./limits.js";
6
7
  export { crypto } from "./crypto.js";
7
8
  export { createRouter } from "./router.js";
8
9
  export { fetch } from "./fetch.js";
@@ -1,4 +1,6 @@
1
1
  import { crypto } from "../crypto.js";
2
+ import { limits } from "../limits.js";
3
+ import { runInvocation } from "./local-invocation.js";
2
4
  import { createDataApi } from "../data.js";
3
5
  import { ValidationError } from "../errors.js";
4
6
  import { installCogoverFetch } from "../fetch.js";
@@ -34,7 +36,7 @@ export function createJobSandboxHandler(manifest, handler) {
34
36
  throw new ValidationError("Job input must be a JSON object");
35
37
  const job = jobInfo(input, manifest);
36
38
  let invocation;
37
- await handler(Object.freeze({
39
+ await runInvocation("job", async () => handler(Object.freeze({
38
40
  job,
39
41
  payload: input.payload ?? null,
40
42
  get invocation() {
@@ -51,7 +53,8 @@ export function createJobSandboxHandler(manifest, handler) {
51
53
  secrets: createSecretsApi(),
52
54
  crypto,
53
55
  org: createOrgApi(() => invocation ??= invocationContext(input)),
54
- }));
56
+ limits,
57
+ })));
55
58
  // The result of a job is not delivered anywhere, so nothing is serialized.
56
59
  return null;
57
60
  };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Runs one handler invocation. When the handler runs locally under Cogover Dev CLI, the CLI provides a hook that
3
+ * counts the invocation's calls against the budgets of its lane; Cogover Runtime counts them on the host instead.
4
+ */
5
+ export function runInvocation(lane, run) {
6
+ const hook = globalThis.__cogoverLocalInvocation;
7
+ return typeof hook === "function" ? hook(lane, run) : run();
8
+ }