@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.
- package/README.md +61 -12
- package/dist/data.d.ts +160 -13
- package/dist/data.js +30 -14
- package/dist/index.d.ts +1 -1
- package/dist/internal/record-reads.js +183 -0
- package/dist/records.d.ts +18 -0
- package/docs/en/api-reference/background-jobs.md +4 -1
- package/docs/en/api-reference/overview.md +9 -2
- package/docs/en/api-reference/record-triggers.md +12 -0
- package/docs/en/api-reference/records.md +378 -33
- package/docs/en/api-reference/state-and-locks.md +3 -0
- package/docs/en/usage-guide.md +66 -1
- package/package.json +1 -1
- package/scripts/generate-workspace-types.mjs +19 -7
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
|
|
|
@@ -149,7 +150,8 @@ export const triggers = [
|
|
|
149
150
|
];
|
|
150
151
|
```
|
|
151
152
|
|
|
152
|
-
`record.new` and `record.old` contain only the listed `fields
|
|
153
|
+
`record.new` and `record.old` contain only the listed `fields`, and their lookup
|
|
154
|
+
values carry the linked record's name. Assign fields of
|
|
153
155
|
`record.new` to change what is saved: only `writableFields` may change, and values
|
|
154
156
|
use the same format as `records.update` input. `record.addError(field, code,
|
|
155
157
|
message?)` rejects a record; the optional English message is shown to the end user
|
|
@@ -348,16 +350,37 @@ const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_public_key"
|
|
|
348
350
|
## Record API
|
|
349
351
|
|
|
350
352
|
An Object client exposes `records.get`, `records.getMany`, `records.list`,
|
|
351
|
-
`records.
|
|
352
|
-
`records.upsertByUniqueField`, and `records.deleteMany`. List
|
|
353
|
-
field references, so scripts do not provide
|
|
354
|
-
response envelopes.
|
|
353
|
+
`records.aggregate`, `records.create`, `records.update`, `records.batchInsert`,
|
|
354
|
+
`records.batchUpdate`, `records.upsertByUniqueField`, and `records.deleteMany`. List
|
|
355
|
+
filters are built from typed field references, so scripts do not provide
|
|
356
|
+
transport-specific field metadata or response envelopes.
|
|
357
|
+
|
|
358
|
+
Every read names the fields it needs: `fields` is required by `get`, `getMany`, and
|
|
359
|
+
`list`, either as a list of field slugs or as `"*"` for every field that the identity
|
|
360
|
+
in use and the project's identity policy may read. A read without `fields` throws
|
|
361
|
+
`ValidationError` (`fields is required: pass field slugs or "*" (@cogover/sdk
|
|
362
|
+
0.13.0+)`). With workspace types, the result is narrowed to the requested fields, so
|
|
363
|
+
reading a field that was not requested is a compile error. A single result is limited
|
|
364
|
+
to 1 MiB; prefer a list of fields to `"*"` for `getMany` and large pages.
|
|
355
365
|
|
|
356
366
|
Cogover normalizes service values to the declared SDK types: booleans become
|
|
357
|
-
`true`/`false`, and lookup/reference values are
|
|
358
|
-
`{ id, name, objectSlug }
|
|
359
|
-
|
|
360
|
-
|
|
367
|
+
`true`/`false`, and lookup/reference values are `RecordReference` objects
|
|
368
|
+
`{ id, name, objectSlug }`. A lookup's `name` is `""`, and so is
|
|
369
|
+
`system.createdBy.name`, unless the read sets `expandLookups`; a `reference` field
|
|
370
|
+
keeps the name it stores. `expandLookups: true`, or an object such as
|
|
371
|
+
`{ customer: ["credit_limit", "tier"], owner: "*" }`, adds the linked records' names
|
|
372
|
+
and selected `fields`, read one level deep with the same identity and permissions
|
|
373
|
+
as the read itself. Expand only the lookups the script uses, since each one reads
|
|
374
|
+
more data. For writes, reference fields accept either a record ID or a
|
|
375
|
+
`RecordReference`; only the ID is sent to the Record API.
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
const order = await orders.records.get(orderId, {
|
|
379
|
+
fields: ["code", "amount", "customer"],
|
|
380
|
+
expandLookups: { customer: ["credit_limit"] },
|
|
381
|
+
});
|
|
382
|
+
const creditLimit = order?.fields.customer?.fields?.credit_limit;
|
|
383
|
+
```
|
|
361
384
|
|
|
362
385
|
```typescript
|
|
363
386
|
import { and, defineScript } from "@cogover/sdk";
|
|
@@ -365,6 +388,7 @@ import { and, defineScript } from "@cogover/sdk";
|
|
|
365
388
|
export default defineScript(async ({ data }) => {
|
|
366
389
|
const orders = data.object("order");
|
|
367
390
|
return orders.records.list({
|
|
391
|
+
fields: ["code", "status", "total"],
|
|
368
392
|
where: and(
|
|
369
393
|
orders.fields.status.in(["new", "nurturing"]),
|
|
370
394
|
orders.fields.is_active.eq(true),
|
|
@@ -381,6 +405,28 @@ call. `fields` is required. The result is `{ records, missingIds }`: IDs that do
|
|
|
381
405
|
exist or are not visible to the identity in use are reported in `missingIds` instead
|
|
382
406
|
of being dropped. Prefer it to calling `records.get` in a loop.
|
|
383
407
|
|
|
408
|
+
`records.aggregate` counts, sums, averages, and finds the smallest and largest values
|
|
409
|
+
of the matching records in one call, without reading them. `groupBy` groups by up to
|
|
410
|
+
three fields and `limit` (1 to 5,000, default 1,000) caps the groups; `truncated`
|
|
411
|
+
reports that more groups exist. Aggregates follow record writes after about one
|
|
412
|
+
second. A client from `data.asUser()`, like `data.object()` in a trigger or job that runs
|
|
413
|
+
as a user, cannot group and supports only counts and number metrics; use
|
|
414
|
+
`data.asSystem()` there.
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
const totals = await orders.records.aggregate({
|
|
418
|
+
where: orders.fields.status.eq("paid"),
|
|
419
|
+
metrics: { orders: { count: "id" }, revenue: { sum: "total" } },
|
|
420
|
+
});
|
|
421
|
+
// totals.values: { orders: 120, revenue: 530000000 }
|
|
422
|
+
|
|
423
|
+
const byStatus = await orders.records.aggregate({
|
|
424
|
+
groupBy: ["status"],
|
|
425
|
+
metrics: { orders: { count: "id" }, average: { avg: "total" } },
|
|
426
|
+
});
|
|
427
|
+
// byStatus.groups: [{ key: { status: "paid" }, values: { orders: 120, average: 4416666 } }]
|
|
428
|
+
```
|
|
429
|
+
|
|
384
430
|
Batch writes are best-effort per row. Check `result.success` or every entry in
|
|
385
431
|
`result.results`; a successful request envelope does not mean every row succeeded.
|
|
386
432
|
Business upsert accepts one `matchBy` field that must be configured as a single-field
|
|
@@ -438,7 +484,7 @@ await data.asSystem().object("order").records.update(order.id, changes);
|
|
|
438
484
|
|
|
439
485
|
Both methods return new immutable clients and preserve workspace typing. `asUser`
|
|
440
486
|
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;
|
|
487
|
+
batch writes and business upsert, except grouping in `records.aggregate`. Reads apply that user's permissions and approved field restrictions;
|
|
442
488
|
read access must be approved separately from writes. `asSystem` supports the
|
|
443
489
|
full record API, including in authenticated public scripts, without changing the
|
|
444
490
|
original caller or existing clients. `asSystem` may also write fields whose manual
|
|
@@ -590,7 +636,10 @@ npx cogover-generate-workspace-types objects.json workspace.d.ts
|
|
|
590
636
|
```
|
|
591
637
|
|
|
592
638
|
The declaration makes object slugs, field slugs, value types, and choice option
|
|
593
|
-
slugs available to TypeScript
|
|
639
|
+
slugs available to TypeScript, and types the `fields` of an expanded lookup from
|
|
640
|
+
its target Object. It imports the SDK types it uses (`RecordReference`, `FileValue`,
|
|
641
|
+
`UrlValue`); regenerate a declaration made by a version before 0.13.0, which left
|
|
642
|
+
them unresolved and typed those fields as `any` under `skipLibCheck`. `schema.object(slug)` is read-only; Object and
|
|
594
643
|
field mutation are intentionally not part of this SDK.
|
|
595
644
|
|
|
596
645
|
## 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
|
-
|
|
5
|
-
|
|
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
|
-
|
|
8
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
26
|
-
|
|
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
|
-
|
|
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):
|
|
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:
|
|
34
|
-
|
|
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
|
-
|
|
46
|
-
|
|
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
|
-
|
|
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
|
|
69
|
-
orderBy: options
|
|
70
|
-
fields:
|
|
71
|
-
limit: options
|
|
72
|
-
cursor: options
|
|
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";
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { CogoverApiError, ValidationError } from "../errors.js";
|
|
2
|
+
import { isRecord } from "./values.js";
|
|
3
|
+
/** Refusal of a read without a valid `fields` option; Cogover refuses such a read with the same message. */
|
|
4
|
+
export const FIELDS_REQUIRED = 'fields is required: pass field slugs or "*" (@cogover/sdk 0.13.0+)';
|
|
5
|
+
/** Refusal of a grouped aggregate on a client from `asUser()`; Cogover refuses it with the same message. */
|
|
6
|
+
export const AS_USER_GROUP_BY = "aggregate with groupBy is not supported for asUser(); use the caller or asSystem()";
|
|
7
|
+
/** Refusal of a metric that a client from `asUser()` cannot compute; Cogover refuses it with the same message. */
|
|
8
|
+
const AS_USER_METRICS = "asUser() without groupBy supports only count on id and count, sum, avg, min and max on "
|
|
9
|
+
+ "number fields; use the caller or asSystem()";
|
|
10
|
+
export const MAX_METRICS = 20;
|
|
11
|
+
export const MAX_GROUP_BY_FIELDS = 3;
|
|
12
|
+
export const MAX_GROUPS = 5000;
|
|
13
|
+
const FIELD_SLUG = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
14
|
+
const METRIC_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
|
|
15
|
+
const METRIC_OPERATIONS = new Set(["count", "sum", "avg", "min", "max", "countDistinct"]);
|
|
16
|
+
/** Validates the `fields` option of `get`, `getMany` and `list`. */
|
|
17
|
+
export function normalizeFieldSelection(value) {
|
|
18
|
+
if (value === "*") {
|
|
19
|
+
return "*";
|
|
20
|
+
}
|
|
21
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
22
|
+
throw new ValidationError(FIELDS_REQUIRED);
|
|
23
|
+
}
|
|
24
|
+
const slugs = new Set();
|
|
25
|
+
for (const item of value) {
|
|
26
|
+
const slug = typeof item === "string" ? item.trim() : "";
|
|
27
|
+
// `["*"]` lands here too: "*" is only accepted on its own, not inside the list.
|
|
28
|
+
if (!FIELD_SLUG.test(slug)) {
|
|
29
|
+
throw new ValidationError(FIELDS_REQUIRED);
|
|
30
|
+
}
|
|
31
|
+
slugs.add(slug);
|
|
32
|
+
}
|
|
33
|
+
return [...slugs];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Validates the `expandLookups` option against the requested fields. `undefined` means that no lookup is expanded;
|
|
37
|
+
* Cogover checks that each named field is a lookup and that the linked fields exist.
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeExpandLookups(value, fields) {
|
|
40
|
+
if (value === undefined || value === false) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
if (value === true) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
if (!isRecord(value)) {
|
|
47
|
+
throw new ValidationError('expandLookups must be true or an object that maps lookup field slugs to field slugs or "*"');
|
|
48
|
+
}
|
|
49
|
+
const lookupFields = Object.keys(value);
|
|
50
|
+
if (lookupFields.length === 0) {
|
|
51
|
+
throw new ValidationError("expandLookups must name at least one lookup field");
|
|
52
|
+
}
|
|
53
|
+
// No prototype, so that a field slug such as `__proto__` stays an ordinary key.
|
|
54
|
+
const normalized = Object.create(null);
|
|
55
|
+
for (const lookupField of lookupFields) {
|
|
56
|
+
if (!FIELD_SLUG.test(lookupField)) {
|
|
57
|
+
throw new ValidationError(`Invalid expandLookups field slug '${lookupField}'`);
|
|
58
|
+
}
|
|
59
|
+
if (fields !== "*" && !fields.includes(lookupField)) {
|
|
60
|
+
throw new ValidationError(`expandLookups field '${lookupField}' must also be listed in fields`);
|
|
61
|
+
}
|
|
62
|
+
const linkedFields = value[lookupField];
|
|
63
|
+
if (linkedFields === "*") {
|
|
64
|
+
normalized[lookupField] = "*";
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const invalid = () => new ValidationError(`expandLookups.${lookupField} must be "*" or a non-empty array of field slugs`);
|
|
68
|
+
if (!Array.isArray(linkedFields) || linkedFields.length === 0) {
|
|
69
|
+
throw invalid();
|
|
70
|
+
}
|
|
71
|
+
const slugs = new Set();
|
|
72
|
+
for (const item of linkedFields) {
|
|
73
|
+
const slug = typeof item === "string" ? item.trim() : "";
|
|
74
|
+
if (!FIELD_SLUG.test(slug)) {
|
|
75
|
+
throw invalid();
|
|
76
|
+
}
|
|
77
|
+
slugs.add(slug);
|
|
78
|
+
}
|
|
79
|
+
normalized[lookupField] = [...slugs];
|
|
80
|
+
}
|
|
81
|
+
return normalized;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Validates the options of `records.aggregate` and converts each metric to `{ op, field }`. `delegated` is true for
|
|
85
|
+
* a client from `asUser()`, which cannot group.
|
|
86
|
+
*/
|
|
87
|
+
export function normalizeAggregateOptions(options, delegated) {
|
|
88
|
+
if (!isRecord(options)) {
|
|
89
|
+
throw new ValidationError("aggregate() requires an options object with metrics");
|
|
90
|
+
}
|
|
91
|
+
const { where, groupBy, metrics, limit } = options;
|
|
92
|
+
if (groupBy !== undefined && delegated) {
|
|
93
|
+
throw new ValidationError(AS_USER_GROUP_BY);
|
|
94
|
+
}
|
|
95
|
+
const normalizedMetrics = normalizeMetrics(metrics);
|
|
96
|
+
if (delegated) {
|
|
97
|
+
// The other limits of asUser() depend on the field types, which Cogover checks.
|
|
98
|
+
const distinct = Object.keys(normalizedMetrics).find(name => normalizedMetrics[name].op === "countDistinct");
|
|
99
|
+
if (distinct !== undefined) {
|
|
100
|
+
throw new ValidationError(`metrics.${distinct}: ${AS_USER_METRICS}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (groupBy === undefined) {
|
|
104
|
+
if (limit !== undefined) {
|
|
105
|
+
throw new ValidationError("aggregate() accepts limit only together with groupBy");
|
|
106
|
+
}
|
|
107
|
+
return where === undefined ? { metrics: normalizedMetrics } : { where, metrics: normalizedMetrics };
|
|
108
|
+
}
|
|
109
|
+
const normalizedGroupBy = normalizeGroupBy(groupBy);
|
|
110
|
+
if (limit !== undefined
|
|
111
|
+
&& (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > MAX_GROUPS)) {
|
|
112
|
+
throw new ValidationError(`aggregate() limit must be an integer from 1 to ${MAX_GROUPS}`);
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
...(where === undefined ? {} : { where }),
|
|
116
|
+
groupBy: normalizedGroupBy,
|
|
117
|
+
metrics: normalizedMetrics,
|
|
118
|
+
...(limit === undefined ? {} : { limit }),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function normalizeMetrics(value) {
|
|
122
|
+
const names = isRecord(value) ? Object.keys(value) : [];
|
|
123
|
+
if (!isRecord(value) || names.length === 0 || names.length > MAX_METRICS) {
|
|
124
|
+
throw new ValidationError(`aggregate() requires metrics: an object with 1 to ${MAX_METRICS} named metrics`);
|
|
125
|
+
}
|
|
126
|
+
const normalized = Object.create(null);
|
|
127
|
+
for (const name of names) {
|
|
128
|
+
if (!METRIC_NAME.test(name)) {
|
|
129
|
+
throw new ValidationError(`Invalid metric name '${name}': use a letter followed by up to 63 letters, digits or underscores`);
|
|
130
|
+
}
|
|
131
|
+
const metric = value[name];
|
|
132
|
+
const operations = isRecord(metric) ? Object.keys(metric) : [];
|
|
133
|
+
const op = operations[0];
|
|
134
|
+
const field = isRecord(metric) && op !== undefined && typeof metric[op] === "string"
|
|
135
|
+
? metric[op].trim()
|
|
136
|
+
: "";
|
|
137
|
+
if (operations.length !== 1 || op === undefined || !METRIC_OPERATIONS.has(op) || !FIELD_SLUG.test(field)) {
|
|
138
|
+
throw new ValidationError(`Metric '${name}' must be exactly one of { count }, { sum }, { avg }, { min }, `
|
|
139
|
+
+ "{ max } or { countDistinct } with a field slug");
|
|
140
|
+
}
|
|
141
|
+
normalized[name] = { op, field };
|
|
142
|
+
}
|
|
143
|
+
return normalized;
|
|
144
|
+
}
|
|
145
|
+
function normalizeGroupBy(value) {
|
|
146
|
+
const message = `aggregate() groupBy must list 1 to ${MAX_GROUP_BY_FIELDS} field slugs`;
|
|
147
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
148
|
+
throw new ValidationError(message);
|
|
149
|
+
}
|
|
150
|
+
const slugs = new Set();
|
|
151
|
+
for (const item of value) {
|
|
152
|
+
const slug = typeof item === "string" ? item.trim() : "";
|
|
153
|
+
if (!FIELD_SLUG.test(slug)) {
|
|
154
|
+
throw new ValidationError(`Invalid groupBy field slug '${String(item)}'`);
|
|
155
|
+
}
|
|
156
|
+
slugs.add(slug);
|
|
157
|
+
}
|
|
158
|
+
if (slugs.size > MAX_GROUP_BY_FIELDS) {
|
|
159
|
+
throw new ValidationError(message);
|
|
160
|
+
}
|
|
161
|
+
return [...slugs];
|
|
162
|
+
}
|
|
163
|
+
/** Checks the shape of a `records.aggregate` result before the script sees it. */
|
|
164
|
+
export function requireAggregateResult(result, request) {
|
|
165
|
+
const metricNames = Object.keys(request.metrics);
|
|
166
|
+
const validValues = (values) => isRecord(values) && metricNames.every(name => {
|
|
167
|
+
const value = values[name];
|
|
168
|
+
return value === null || (typeof value === "number" && Number.isFinite(value));
|
|
169
|
+
});
|
|
170
|
+
const valid = isRecord(result) && (request.groupBy === undefined
|
|
171
|
+
? validValues(result.values)
|
|
172
|
+
: Array.isArray(result.groups) && typeof result.truncated === "boolean"
|
|
173
|
+
&& result.groups.every(group => isRecord(group) && validValues(group.values) && isRecord(group.key)
|
|
174
|
+
&& request.groupBy.every(slug => isGroupKeyValue(group.key[slug]))));
|
|
175
|
+
if (!valid) {
|
|
176
|
+
throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.aggregate returned an invalid result");
|
|
177
|
+
}
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
function isGroupKeyValue(value) {
|
|
181
|
+
return typeof value === "string" || typeof value === "boolean"
|
|
182
|
+
|| (typeof value === "number" && Number.isFinite(value));
|
|
183
|
+
}
|
package/dist/records.d.ts
CHANGED
|
@@ -1,10 +1,24 @@
|
|
|
1
|
+
import type { WorkspaceObjects } from "./workspace.js";
|
|
1
2
|
export type CogoverRecordId = string & {
|
|
2
3
|
readonly __cogoverRecordIdBrand: unique symbol;
|
|
3
4
|
};
|
|
5
|
+
/** Fields of a linked record: the target Object's fields when it is declared in `WorkspaceObjects`. */
|
|
6
|
+
type LinkedRecordFields<TObjectSlug extends string> = TObjectSlug extends keyof WorkspaceObjects ? Readonly<Partial<WorkspaceObjects[TObjectSlug]>> : Readonly<Record<string, unknown>>;
|
|
7
|
+
/** Value of a lookup or reference field: the linked record. */
|
|
4
8
|
export interface RecordReference<TObjectSlug extends string = string> {
|
|
5
9
|
readonly id: CogoverRecordId;
|
|
10
|
+
/**
|
|
11
|
+
* Name of the linked record. A record read through `data` without `expandLookups` has `""` here, except in a
|
|
12
|
+
* `reference` field, which stores the name with the record; so does a linked record that could not be read.
|
|
13
|
+
* The `new` and `old` values of a record trigger always carry the name.
|
|
14
|
+
*/
|
|
6
15
|
readonly name: string;
|
|
7
16
|
readonly objectSlug?: TObjectSlug;
|
|
17
|
+
/**
|
|
18
|
+
* Fields of the linked record, present only when the read expanded this lookup with `expandLookups` and the
|
|
19
|
+
* linked record could be read. Lookups inside these fields are not expanded.
|
|
20
|
+
*/
|
|
21
|
+
readonly fields?: LinkedRecordFields<TObjectSlug>;
|
|
8
22
|
}
|
|
9
23
|
export interface UrlValue {
|
|
10
24
|
readonly url: string;
|
|
@@ -25,6 +39,10 @@ export interface CogoverRecord<TFields> {
|
|
|
25
39
|
readonly updatedAt: number;
|
|
26
40
|
readonly createdBy?: {
|
|
27
41
|
readonly id: string;
|
|
42
|
+
/**
|
|
43
|
+
* `""` unless the read used `expandLookups`; then the `name` field of the creator's personnel record,
|
|
44
|
+
* which can be a generated code rather than the person's full name.
|
|
45
|
+
*/
|
|
28
46
|
readonly name: string;
|
|
29
47
|
};
|
|
30
48
|
};
|