@cogover/sdk 0.1.1 → 0.5.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 +256 -30
- package/dist/data.d.ts +44 -0
- package/dist/data.js +143 -0
- package/dist/errors.d.ts +30 -0
- package/dist/errors.js +62 -0
- package/dist/fetch.d.ts +28 -0
- package/dist/fetch.js +96 -0
- package/dist/index.d.ts +21 -3
- package/dist/index.js +7 -5
- package/dist/internal/bridge.js +48 -0
- package/dist/internal/invocation.js +57 -0
- package/dist/internal/request.js +87 -0
- package/dist/internal/validation.js +28 -0
- package/dist/internal/values.js +6 -0
- package/dist/invocation.d.ts +40 -0
- package/dist/invocation.js +1 -0
- package/dist/legacy.d.ts +2 -0
- package/dist/legacy.js +4 -0
- package/dist/locks.d.ts +19 -0
- package/dist/locks.js +68 -0
- package/dist/logger.d.ts +6 -0
- package/dist/logger.js +14 -0
- package/dist/query.d.ts +52 -0
- package/dist/query.js +59 -0
- package/dist/records.d.ts +74 -0
- package/dist/records.js +1 -0
- package/dist/request.d.ts +18 -0
- package/dist/request.js +1 -0
- package/dist/response.d.ts +21 -0
- package/dist/response.js +108 -0
- package/dist/router.d.ts +13 -0
- package/dist/router.js +104 -0
- package/dist/schema.d.ts +26 -0
- package/dist/schema.js +11 -0
- package/dist/script.d.ts +23 -0
- package/dist/script.js +56 -0
- package/dist/state.d.ts +24 -0
- package/dist/state.js +91 -0
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.js +1 -0
- package/docs/en/api-reference.md +948 -0
- package/docs/en/usage-guide.md +284 -0
- package/package.json +17 -5
- package/scripts/generate-workspace-types.mjs +135 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
# API reference: `@cogover/sdk`
|
|
2
|
+
|
|
3
|
+
`@cogover/sdk` is the public TypeScript contract for developing Custom Backend
|
|
4
|
+
Modules on Cogover. Cogover authentication credentials are never exposed to
|
|
5
|
+
module code; capability calls are restricted by the permissions and limits
|
|
6
|
+
configured for the project.
|
|
7
|
+
|
|
8
|
+
## `defineScript`
|
|
9
|
+
|
|
10
|
+
`defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
|
|
11
|
+
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, and `locks`, awaits the handler,
|
|
12
|
+
and serializes its result.
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
function defineScript<
|
|
16
|
+
Input = unknown,
|
|
17
|
+
Output = unknown,
|
|
18
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
19
|
+
>(handler: ScriptHandler<Input, Output, Schema>): SandboxHandler;
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The related public types are:
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
type SandboxHandler = (inputJson: string) => Promise<string | null>;
|
|
26
|
+
|
|
27
|
+
type ScriptHandler<Input, Output, Schema extends object = EffectiveWorkspaceObjects> =
|
|
28
|
+
(context: ScriptContext<Input, Schema>) =>
|
|
29
|
+
Output | ScriptResponse<unknown> | null |
|
|
30
|
+
Promise<Output | ScriptResponse<unknown> | null>;
|
|
31
|
+
|
|
32
|
+
interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects> {
|
|
33
|
+
readonly input: Input;
|
|
34
|
+
readonly request: ScriptRequest<Input>;
|
|
35
|
+
readonly invocation: InvocationContext;
|
|
36
|
+
readonly data: DataApi<Schema>;
|
|
37
|
+
readonly schema: SchemaApi<Schema>;
|
|
38
|
+
readonly log: ScriptLogger;
|
|
39
|
+
readonly response: ResponseApi;
|
|
40
|
+
readonly state: ProjectState;
|
|
41
|
+
readonly locks: DistributedLocks;
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`defineScript` rejects a non-function handler with `ValidationError`. The returned
|
|
46
|
+
handler rejects invalid input JSON and values that cannot be serialized to JSON.
|
|
47
|
+
Returning `null` produces a null handler result; returning `undefined` is invalid.
|
|
48
|
+
|
|
49
|
+
## HTTP routers and request context
|
|
50
|
+
|
|
51
|
+
`ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
|
|
52
|
+
`log`, `state`, and `locks` to both script and route handlers. `input` preserves the invocation
|
|
53
|
+
input. Prefer `request.body` for business data: it excludes invocation metadata and
|
|
54
|
+
transport/authentication fields removed by Cogover.
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
58
|
+
type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
|
|
59
|
+
type ScriptHeaders = Readonly<Record<string, string>>;
|
|
60
|
+
type ScriptPathParams = Readonly<Record<string, string>>;
|
|
61
|
+
|
|
62
|
+
interface ScriptRequest<TBody = unknown> {
|
|
63
|
+
readonly method: RequestMethod;
|
|
64
|
+
readonly path: string; // Relative to /api/v1/ts-projects/{projectSlug}
|
|
65
|
+
readonly params: ScriptPathParams;
|
|
66
|
+
readonly query: ScriptQuery;
|
|
67
|
+
readonly headers: ScriptHeaders;
|
|
68
|
+
readonly body: TBody;
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The descriptor and metadata maps are frozen; its body is not deeply frozen. Method,
|
|
73
|
+
path, query, and allowlisted headers come from Cogover, not from business fields.
|
|
74
|
+
Repeated query names become readonly arrays. Header names are lower-case and
|
|
75
|
+
credentials such as `authorization` and `cookie` are never exposed. Dynamic path
|
|
76
|
+
parameters are percent-decoded after safe route matching. TypeScript types do not
|
|
77
|
+
validate runtime business input.
|
|
78
|
+
|
|
79
|
+
## Invocation identity and workspace
|
|
80
|
+
|
|
81
|
+
`context.invocation` is a synchronous, immutable snapshot built from metadata that
|
|
82
|
+
Cogover already authenticated and loaded for the current execution. Reading it
|
|
83
|
+
does not make a data API request.
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
type InvocationContext = UserInvocationContext | SystemInvocationContext;
|
|
87
|
+
|
|
88
|
+
interface CurrentWorkspace {
|
|
89
|
+
readonly id: string;
|
|
90
|
+
readonly name?: string;
|
|
91
|
+
readonly domain?: string;
|
|
92
|
+
readonly language?: string;
|
|
93
|
+
readonly timezone?: string;
|
|
94
|
+
readonly dateFormat?: string;
|
|
95
|
+
readonly timeFormat?: string;
|
|
96
|
+
readonly numberFormat?: string;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
interface CurrentWorkspaceMembership {
|
|
100
|
+
readonly personnelId?: string;
|
|
101
|
+
readonly language?: string;
|
|
102
|
+
readonly timezone?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface CurrentUser {
|
|
106
|
+
readonly accountId: string;
|
|
107
|
+
readonly email?: string;
|
|
108
|
+
readonly firstName?: string;
|
|
109
|
+
readonly lastName?: string;
|
|
110
|
+
readonly avatar?: string;
|
|
111
|
+
readonly language?: string;
|
|
112
|
+
readonly timezone?: string;
|
|
113
|
+
readonly membership: CurrentWorkspaceMembership;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface UserInvocationContext {
|
|
117
|
+
readonly identity: "user";
|
|
118
|
+
readonly workspace: CurrentWorkspace;
|
|
119
|
+
readonly user: CurrentUser;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface SystemInvocationContext {
|
|
123
|
+
readonly identity: "system";
|
|
124
|
+
readonly workspace: CurrentWorkspace;
|
|
125
|
+
readonly user: null;
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
All fields are readonly. Optional profile and workspace fields may be absent, so
|
|
130
|
+
scripts must not assume that they contain a value.
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
export default defineScript(({ invocation }) => {
|
|
134
|
+
if (invocation.identity === "system") {
|
|
135
|
+
return {workspaceId: invocation.workspace.id, user: null};
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
workspaceId: invocation.workspace.id,
|
|
139
|
+
accountId: invocation.user.accountId,
|
|
140
|
+
personnelId: invocation.user.membership.personnelId,
|
|
141
|
+
};
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Cogover ignores caller-supplied invocation metadata and creates this snapshot from
|
|
146
|
+
the authenticated request context. Raw authentication data, tokens, and credentials
|
|
147
|
+
are not included. A handler called outside Cogover has no authenticated invocation
|
|
148
|
+
snapshot.
|
|
149
|
+
|
|
150
|
+
### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
|
|
151
|
+
|
|
152
|
+
Creates an independent router. `TSchema extends object` defaults to the effective
|
|
153
|
+
workspace schema, preserving `WorkspaceObjects` augmentation for data and schema
|
|
154
|
+
APIs. Routes match a method and case-sensitive static or dynamic path; static routes
|
|
155
|
+
take precedence over dynamic routes. `/` addresses
|
|
156
|
+
the canonical project URL without a route suffix.
|
|
157
|
+
`/index` is a separate route, registered explicitly. `defineScript()` remains valid
|
|
158
|
+
for `/`; requesting a child path on it throws `NotFoundError` before its handler runs.
|
|
159
|
+
|
|
160
|
+
### `router.addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>`
|
|
161
|
+
|
|
162
|
+
Registers a handler and returns the same router for chaining. Supported methods are
|
|
163
|
+
`GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. A path is `/` or static/dynamic
|
|
164
|
+
components such as `/orders/:orderId`. Static components start with an ASCII letter
|
|
165
|
+
or digit, may contain letters, digits, `_`, or `-`, and are at most 100 characters.
|
|
166
|
+
Parameter names start with an ASCII letter, may contain letters, digits, or `_`, are
|
|
167
|
+
at most 64 characters, and must be unique in a route. The complete path is at most
|
|
168
|
+
1,024 characters.
|
|
169
|
+
Child trailing slashes, empty segments, `.`, `..`, percent escapes in the template,
|
|
170
|
+
`?`, `#`, and wildcards are rejected. Duplicate or structurally ambiguous routes for
|
|
171
|
+
one method, invalid handlers, or more than 256 routes throw `ValidationError`.
|
|
172
|
+
|
|
173
|
+
Handlers are ordinary `ScriptHandler` functions, not functions already wrapped in
|
|
174
|
+
`defineScript()`. They receive the same data/schema/log APIs, input and request context.
|
|
175
|
+
The same handler may be registered at more than one path.
|
|
176
|
+
|
|
177
|
+
### `router.get/post/put/patch/delete(path, handler): ScriptRouter<TSchema>`
|
|
178
|
+
|
|
179
|
+
Method-specific shorthand for `addRoute()`, with identical validation, return value,
|
|
180
|
+
and errors.
|
|
181
|
+
|
|
182
|
+
### `router.toHandler(): SandboxHandler`
|
|
183
|
+
|
|
184
|
+
Returns a default-exportable handler that captures a snapshot of the current routes.
|
|
185
|
+
Later registrations do not affect an existing handler. It parses input, dispatches
|
|
186
|
+
exactly one route, awaits it, and serializes the result just like `defineScript()`.
|
|
187
|
+
`null` remains null; an undefined result throws `ValidationError`. Missing routes
|
|
188
|
+
throw `NotFoundError` (HTTP 404). Unsupported invocation methods use
|
|
189
|
+
`CogoverApiError` with `code: "METHOD_NOT_ALLOWED"` (HTTP 405). Invalid invocation
|
|
190
|
+
metadata throws `ValidationError`.
|
|
191
|
+
When invoked directly without Cogover request metadata, handlers default to POST `/`.
|
|
192
|
+
|
|
193
|
+
Routes inherit project authentication, permissions and runtime limits. Registering a
|
|
194
|
+
route grants no additional permission or separate security boundary. Idempotency
|
|
195
|
+
replay is scoped to method/path as well as project version and caller; use a new key
|
|
196
|
+
for each distinct business operation.
|
|
197
|
+
|
|
198
|
+
## HTTP response API
|
|
199
|
+
|
|
200
|
+
Returning a plain JSON-serializable value keeps the compatible `200
|
|
201
|
+
application/json` behavior. Use the context's `response` helpers to control status,
|
|
202
|
+
headers, content type, or body representation:
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
router.post("/orders", ({ response }) => response.json({ id: "ORD-1" }, {
|
|
206
|
+
status: 201,
|
|
207
|
+
headers: { location: "/orders/ORD-1", "x-request-state": "created" },
|
|
208
|
+
}));
|
|
209
|
+
|
|
210
|
+
router.get("/files/:fileId", ({ response }) =>
|
|
211
|
+
response.bytes(new Uint8Array([0, 1, 255]), { contentType: "application/octet-stream" }));
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
type ResponseHeaderValue = string | readonly string[];
|
|
216
|
+
|
|
217
|
+
interface ResponseInit {
|
|
218
|
+
readonly status?: number;
|
|
219
|
+
readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
interface BinaryResponseInit extends ResponseInit {
|
|
223
|
+
readonly contentType?: string;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
interface ResponseApi {
|
|
227
|
+
json<T>(body: T, init?: ResponseInit): ScriptResponse<T>;
|
|
228
|
+
text(body: string, init?: ResponseInit): ScriptResponse<string>;
|
|
229
|
+
bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
|
|
230
|
+
empty(init?: ResponseInit): ScriptResponse<null>;
|
|
231
|
+
redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
response.json(body, init?)
|
|
235
|
+
response.text(body, init?)
|
|
236
|
+
response.bytes(body: Uint8Array, { status?, headers?, contentType? }?)
|
|
237
|
+
response.empty(init?) // status defaults to 204
|
|
238
|
+
response.redirect(location, status?) // status defaults to 302
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Status must be an integer from 200 through 599. Header values may be one string or
|
|
242
|
+
a readonly string array. Hop-by-hop, credential-setting, and reserved Cogover headers
|
|
243
|
+
are rejected. Header names and values cannot contain newlines;
|
|
244
|
+
at most 50 headers are accepted. A header name is at most 128 characters and each
|
|
245
|
+
value at most 8,192 characters. Default content types are
|
|
246
|
+
`application/json; charset=utf-8`, `text/plain; charset=utf-8`, and
|
|
247
|
+
`application/octet-stream`. Redirect status is restricted to 301, 302, 303, 307, or
|
|
248
|
+
308. Helpers return an opaque `ScriptResponse`; application code must not construct
|
|
249
|
+
the transport envelope directly. A redirect location must be non-empty, at most
|
|
250
|
+
4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
|
|
251
|
+
`response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
|
|
252
|
+
|
|
253
|
+
## Outbound HTTP `fetch`
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
|
|
257
|
+
|
|
258
|
+
interface CogoverFetchInit {
|
|
259
|
+
readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
260
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
261
|
+
readonly body?: string;
|
|
262
|
+
readonly timeoutMs?: number;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
interface CogoverFetchHeaders {
|
|
266
|
+
get(name: string): string | null;
|
|
267
|
+
has(name: string): boolean;
|
|
268
|
+
entries(): IterableIterator<[string, string]>;
|
|
269
|
+
[Symbol.iterator](): IterableIterator<[string, string]>;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interface CogoverFetchResponse {
|
|
273
|
+
readonly ok: boolean;
|
|
274
|
+
readonly status: number;
|
|
275
|
+
readonly statusText: string;
|
|
276
|
+
readonly url: string;
|
|
277
|
+
readonly redirected: false;
|
|
278
|
+
readonly headers: CogoverFetchHeaders;
|
|
279
|
+
readonly bodyUsed: boolean;
|
|
280
|
+
text(): Promise<string>;
|
|
281
|
+
json<T = unknown>(): Promise<T>;
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Cogover installs the global `fetch()` function in the hosted runtime. Import
|
|
286
|
+
`{ fetch }` from `@cogover/sdk` when the dependency should be explicit; this also
|
|
287
|
+
prevents local Node.js from silently using its native, unrestricted `fetch` during
|
|
288
|
+
tests. The SDK function requires the Cogover runtime and always uses Cogover's
|
|
289
|
+
managed network layer. `input` must be an absolute public HTTPS URL on port 443
|
|
290
|
+
without userinfo, a fragment, or an IP-literal host. `body` accepts only a string;
|
|
291
|
+
use `JSON.stringify()` for JSON. `timeoutMs` must be a positive integer and is
|
|
292
|
+
always clamped by the platform limit.
|
|
293
|
+
|
|
294
|
+
```typescript
|
|
295
|
+
import { fetch } from "@cogover/sdk";
|
|
296
|
+
|
|
297
|
+
const response = await fetch("https://api.example.com/v1/orders", {
|
|
298
|
+
method: "POST",
|
|
299
|
+
headers: { "content-type": "application/json" },
|
|
300
|
+
body: JSON.stringify({ id: "ORD-1" }),
|
|
301
|
+
timeoutMs: 5_000,
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
`CogoverFetchResponse` exposes `ok`, `status`, `statusText`, `url`, `redirected`
|
|
306
|
+
(always `false`), `headers`, `bodyUsed`, `text()`, and `json<T>()`. The bounded,
|
|
307
|
+
buffered body can be consumed once. Header `get(name)`, `has(name)`, `entries()`,
|
|
308
|
+
and iteration are case-insensitive.
|
|
309
|
+
|
|
310
|
+
V1 does not follow redirects, persist or send cookies, stream requests/responses,
|
|
311
|
+
or support WebSocket. It does not accept `signal`, `credentials`, `redirect`, proxy,
|
|
312
|
+
dispatcher, agent, DNS resolver, or TLS configuration. HTTP URLs, ports other than
|
|
313
|
+
443, userinfo, and IP-literal hosts are unsupported. Framing, hop-by-hop, proxy,
|
|
314
|
+
forwarding, and reserved Cogover request headers are rejected. Request/response sizes,
|
|
315
|
+
headers, time, calls, destinations, and concurrency are bounded by platform quotas.
|
|
316
|
+
|
|
317
|
+
Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
|
|
318
|
+
`FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
|
|
319
|
+
`FETCH_FAILED`; quota failures use `RateLimitError`. When POST, PUT, PATCH, or DELETE
|
|
320
|
+
times out or loses its response, the remote server may already have applied the
|
|
321
|
+
request. Use the remote API's idempotency mechanism and never retry blindly.
|
|
322
|
+
|
|
323
|
+
## Record API
|
|
324
|
+
|
|
325
|
+
```typescript
|
|
326
|
+
const orders = data.object("order");
|
|
327
|
+
await orders.records.get(id, { fields });
|
|
328
|
+
await orders.records.list({ where, orderBy, fields, limit, cursor });
|
|
329
|
+
await orders.records.create(fields);
|
|
330
|
+
await orders.records.update(id, fields);
|
|
331
|
+
await orders.records.batchInsert(records);
|
|
332
|
+
await orders.records.batchUpdate(records);
|
|
333
|
+
await orders.records.upsertByUniqueField(matchBy, fields);
|
|
334
|
+
await orders.records.deleteMany(ids);
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
### Record values and results
|
|
338
|
+
|
|
339
|
+
```typescript
|
|
340
|
+
type CogoverRecordId = string & {
|
|
341
|
+
readonly __cogoverRecordIdBrand: unique symbol;
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
interface RecordReference<ObjectSlug extends string = string> {
|
|
345
|
+
readonly id: CogoverRecordId;
|
|
346
|
+
readonly name: string;
|
|
347
|
+
readonly objectSlug?: ObjectSlug;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
interface UrlValue {
|
|
351
|
+
readonly url: string;
|
|
352
|
+
readonly alias?: string;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
interface FileValue {
|
|
356
|
+
readonly id: string;
|
|
357
|
+
readonly name: string;
|
|
358
|
+
readonly size?: number;
|
|
359
|
+
readonly contentType?: string;
|
|
360
|
+
readonly url?: string;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
interface CogoverRecord<Fields> {
|
|
364
|
+
readonly id: CogoverRecordId;
|
|
365
|
+
readonly fields: Readonly<Fields>;
|
|
366
|
+
readonly system: {
|
|
367
|
+
readonly createdAt: number;
|
|
368
|
+
readonly updatedAt: number;
|
|
369
|
+
readonly createdBy?: { readonly id: string; readonly name: string };
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
interface RecordPage<Fields> {
|
|
374
|
+
readonly items: CogoverRecord<Fields>[];
|
|
375
|
+
readonly total: number;
|
|
376
|
+
readonly nextCursor?: string;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
interface DeleteResult {
|
|
380
|
+
readonly deleted: CogoverRecordId[];
|
|
381
|
+
readonly notDeleted: CogoverRecordId[];
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
interface BatchWriteRowResult {
|
|
385
|
+
readonly referenceId: string;
|
|
386
|
+
readonly id?: CogoverRecordId;
|
|
387
|
+
readonly r: number;
|
|
388
|
+
readonly msg?: string;
|
|
389
|
+
readonly success: boolean;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
interface BatchWriteResponse {
|
|
393
|
+
readonly r: number;
|
|
394
|
+
readonly msg?: string;
|
|
395
|
+
readonly results: readonly BatchWriteRowResult[];
|
|
396
|
+
readonly success: boolean;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
interface BatchUpdateItem<Fields> {
|
|
400
|
+
readonly id: CogoverRecordId;
|
|
401
|
+
readonly fields: UpdateFields<Fields>;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
interface UpsertResult {
|
|
405
|
+
readonly id: CogoverRecordId;
|
|
406
|
+
readonly created: boolean;
|
|
407
|
+
}
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
`CreateFields<Fields>` and `UpdateFields<Fields>` are partial mapped types over the
|
|
411
|
+
workspace fields. Reference values accept a string, `CogoverRecordId`, or matching
|
|
412
|
+
`RecordReference`; array fields accept readonly arrays. `UpsertFields<Fields,
|
|
413
|
+
MatchBy>` is a create-field map that requires the selected match field to be present
|
|
414
|
+
and non-null.
|
|
415
|
+
|
|
416
|
+
### Data clients and operations
|
|
417
|
+
|
|
418
|
+
```typescript
|
|
419
|
+
interface GetRecordOptions<Fields> {
|
|
420
|
+
readonly fields?: readonly (keyof Fields & string)[];
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
interface ListOptions<Fields> {
|
|
424
|
+
readonly where?: FilterExpression;
|
|
425
|
+
readonly orderBy?: readonly SortExpression[];
|
|
426
|
+
readonly fields?: readonly (keyof Fields & string)[];
|
|
427
|
+
readonly limit?: number;
|
|
428
|
+
readonly cursor?: string;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
interface RecordWritesApi<Fields> {
|
|
432
|
+
create(fields: CreateFields<Fields>): Promise<CogoverRecordId>;
|
|
433
|
+
update(id: CogoverRecordId, fields: UpdateFields<Fields>): Promise<void>;
|
|
434
|
+
batchInsert(records: readonly CreateFields<Fields>[]): Promise<BatchWriteResponse>;
|
|
435
|
+
batchUpdate(records: readonly BatchUpdateItem<Fields>[]): Promise<BatchWriteResponse>;
|
|
436
|
+
upsertByUniqueField<MatchBy extends keyof Fields & string>(
|
|
437
|
+
matchBy: MatchBy,
|
|
438
|
+
fields: UpsertFields<Fields, MatchBy>,
|
|
439
|
+
): Promise<UpsertResult>;
|
|
440
|
+
deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
|
|
444
|
+
get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
|
|
445
|
+
list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
interface WriteObjectClient<Fields> {
|
|
449
|
+
readonly slug: string;
|
|
450
|
+
readonly fields: FieldReferences<Fields>;
|
|
451
|
+
readonly records: RecordWritesApi<Fields>;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
|
|
455
|
+
readonly records: RecordsApi<Fields>;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
459
|
+
object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
463
|
+
object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
|
|
464
|
+
asUser(personnelId: string): AsUserDataApi<Schema>;
|
|
465
|
+
asSystem(): DataApi<Schema>;
|
|
466
|
+
}
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
`list` returns `RecordPage<T>` with `items`, `total`, and an optional opaque
|
|
470
|
+
`nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
|
|
471
|
+
`system` object containing creation/update metadata.
|
|
472
|
+
|
|
473
|
+
Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
|
|
474
|
+
responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
|
|
475
|
+
`RecordReference` and send only the ID to Cogover.
|
|
476
|
+
|
|
477
|
+
## Filters and sorting
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
type FilterOperator =
|
|
481
|
+
| "=" | "!=" | ">" | ">=" | "<" | "<="
|
|
482
|
+
| "like" | "not like" | "startsWith" | "endsWith"
|
|
483
|
+
| "in" | "not in" | "is null" | "not null" | "between";
|
|
484
|
+
|
|
485
|
+
interface FilterCondition {
|
|
486
|
+
readonly kind: "condition";
|
|
487
|
+
readonly field: string;
|
|
488
|
+
readonly operator: FilterOperator;
|
|
489
|
+
readonly value?: unknown;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
interface FilterGroup {
|
|
493
|
+
readonly kind: "group";
|
|
494
|
+
readonly operator: "and" | "or";
|
|
495
|
+
readonly expressions: readonly FilterExpression[];
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
type FilterExpression = FilterCondition | FilterGroup;
|
|
499
|
+
|
|
500
|
+
interface SortExpression {
|
|
501
|
+
readonly field: string;
|
|
502
|
+
readonly direction: "asc" | "desc";
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
interface FieldReference<Value> {
|
|
506
|
+
readonly slug: string;
|
|
507
|
+
eq(value: NonNullable<Value>): FilterCondition;
|
|
508
|
+
neq(value: NonNullable<Value>): FilterCondition;
|
|
509
|
+
gt(value: NonNullable<Value>): FilterCondition;
|
|
510
|
+
gte(value: NonNullable<Value>): FilterCondition;
|
|
511
|
+
lt(value: NonNullable<Value>): FilterCondition;
|
|
512
|
+
lte(value: NonNullable<Value>): FilterCondition;
|
|
513
|
+
like(value: string): FilterCondition;
|
|
514
|
+
notLike(value: string): FilterCondition;
|
|
515
|
+
startsWith(value: string): FilterCondition;
|
|
516
|
+
endsWith(value: string): FilterCondition;
|
|
517
|
+
in(values: readonly (
|
|
518
|
+
NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
|
|
519
|
+
)[]): FilterCondition;
|
|
520
|
+
notIn(values: readonly (
|
|
521
|
+
NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
|
|
522
|
+
)[]): FilterCondition;
|
|
523
|
+
isNull(): FilterCondition;
|
|
524
|
+
notNull(): FilterCondition;
|
|
525
|
+
between(from: NonNullable<Value>, to: NonNullable<Value>): FilterCondition;
|
|
526
|
+
asc(): SortExpression;
|
|
527
|
+
desc(): SortExpression;
|
|
528
|
+
}
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
Each `FieldReference<Value>` exposes `slug`, `eq`, `neq`, `gt`, `gte`, `lt`,
|
|
532
|
+
`lte`, `like`, `notLike`, `startsWith`, `endsWith`, `in`, `notIn`, `isNull`,
|
|
533
|
+
`notNull`, `between`, `asc`, and `desc`. `FieldReferences<Fields>` provides these
|
|
534
|
+
references for workspace fields and the system fields `id`, `created`, `updated`,
|
|
535
|
+
and `created_by`. `and(...expressions)` and `or(...expressions)` return a
|
|
536
|
+
`FilterGroup` and require at least one expression.
|
|
537
|
+
For array-valued fields, `in` and `notIn` accept the array's element type.
|
|
538
|
+
|
|
539
|
+
Transport-specific field metadata and response envelopes are handled by Cogover.
|
|
540
|
+
|
|
541
|
+
`create` and `update` require a non-empty field object. `batchInsert` accepts 1–200
|
|
542
|
+
field objects; `batchUpdate` accepts 1–200 `{ id, fields }` items. Both are
|
|
543
|
+
best-effort operations: their `BatchWriteResponse`
|
|
544
|
+
contains one result per input row, and callers must inspect the top-level `success`
|
|
545
|
+
flag or each row's `success`, `r`, and `msg`. A successful request is not an
|
|
546
|
+
all-or-none transaction and does not guarantee that every row was written.
|
|
547
|
+
`referenceId` identifies the zero-based input index as a string.
|
|
548
|
+
|
|
549
|
+
`deleteMany` requires at least one non-blank record ID and returns separate
|
|
550
|
+
`deleted` and `notDeleted` arrays. Record IDs, object slugs, and field slugs are
|
|
551
|
+
validated before a request is sent.
|
|
552
|
+
|
|
553
|
+
`upsertByUniqueField(matchBy, fields)` updates the record whose configured unique
|
|
554
|
+
field equals `fields[matchBy]`, or creates it when no record matches. The match field
|
|
555
|
+
must be a single, non-multiple field with uniqueness enabled, and the business key
|
|
556
|
+
must be non-null and non-blank. The result is `{ id, created }`. Because the server
|
|
557
|
+
chooses the create/update branch, the operation requires both record-create and
|
|
558
|
+
record-update permission.
|
|
559
|
+
|
|
560
|
+
A unique-key conflict is exposed as `ValidationError` with
|
|
561
|
+
`details.reason === "UNIQUE_KEY_VIOLATION"`, `objectSlug`, and `fieldSlug`. The
|
|
562
|
+
public error does not echo the rejected business-key value.
|
|
563
|
+
|
|
564
|
+
## Record execution identities
|
|
565
|
+
|
|
566
|
+
`data.object(slug)` inherits the invocation identity. For an authenticated public
|
|
567
|
+
invocation this is the caller; a system invocation keeps system access.
|
|
568
|
+
|
|
569
|
+
### `data.asUser(personnelId: string): AsUserDataApi<TSchema>`
|
|
570
|
+
|
|
571
|
+
Returns a new immutable client for reads and writes as the specified personnel ID (not an
|
|
572
|
+
account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
|
|
573
|
+
value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
|
|
574
|
+
whose `records: RecordsApi<TFields>` exposes `get`, `list`, `create`, `update`, and
|
|
575
|
+
`deleteMany` as well as batch insert, batch update, and business upsert, with the
|
|
576
|
+
same argument and return types as the default record API.
|
|
577
|
+
|
|
578
|
+
`get(id, options?)` returns `CogoverRecord<TFields> | null`; `list(options?)` returns
|
|
579
|
+
`RecordPage<TFields>`. Field selection, filters, sorting and cursors work as on the
|
|
580
|
+
default client. Reads apply the selected user's permissions and approved project
|
|
581
|
+
field restrictions. An empty successful lookup returns `null`; server failures
|
|
582
|
+
throw errors instead of being treated as missing records or an empty page.
|
|
583
|
+
|
|
584
|
+
```typescript
|
|
585
|
+
const delegatedOrders = data.asUser(personnelId).object("order");
|
|
586
|
+
const order = await delegatedOrders.records.get(recordId, { fields: ["description"] });
|
|
587
|
+
const page = await delegatedOrders.records.list({
|
|
588
|
+
fields: ["description"],
|
|
589
|
+
where: delegatedOrders.fields.description.eq("Pending review"),
|
|
590
|
+
limit: 20,
|
|
591
|
+
});
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
### `data.asSystem(): DataApi<TSchema>`
|
|
595
|
+
|
|
596
|
+
Returns a new immutable client for system record access, including during an
|
|
597
|
+
authenticated public invocation. It supports `get`, `list`, `create`, `update`, and
|
|
598
|
+
`deleteMany`, including batch writes and business upsert. System access does not
|
|
599
|
+
apply the caller's record permissions; approved project restrictions, field
|
|
600
|
+
validation, workspace boundaries, and runtime limits still apply. It neither
|
|
601
|
+
changes the invocation's caller nor modifies existing clients.
|
|
602
|
+
|
|
603
|
+
```typescript
|
|
604
|
+
const orders = data.object("order");
|
|
605
|
+
await orders.records.update(order.id, { description: "Caller update" });
|
|
606
|
+
await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
|
|
607
|
+
await data.asSystem().object("order").records.update(order.id, { description: "System update" });
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
Identity selection needs administrator approval for the project version, permitted
|
|
611
|
+
callers, target personnel, objects, operations, and fields. Selection alone grants
|
|
612
|
+
no permission. Unauthorized operations throw `PermissionDeniedError`; invalid or
|
|
613
|
+
unresolvable identities never fall back to system or caller access. Server failures
|
|
614
|
+
retain their original `CogoverApiError.r`. No credentials or workspace override are
|
|
615
|
+
accepted by these methods. Schema access is unchanged. Each write is independent;
|
|
616
|
+
the three example calls above are not a transaction.
|
|
617
|
+
|
|
618
|
+
## Project state
|
|
619
|
+
|
|
620
|
+
State is durable JSON scoped by workspace, project, namespace, and key. It is not
|
|
621
|
+
version-scoped, so it remains available after a new project version is published.
|
|
622
|
+
|
|
623
|
+
```typescript
|
|
624
|
+
interface StateEntry<T> {
|
|
625
|
+
readonly value: T;
|
|
626
|
+
readonly version: number;
|
|
627
|
+
readonly expiresAt?: number;
|
|
628
|
+
readonly createdAt: number;
|
|
629
|
+
readonly updatedAt: number;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
interface StateWriteOptions {
|
|
633
|
+
readonly expectedVersion?: number;
|
|
634
|
+
readonly ttlSeconds?: number;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
interface StateDeleteOptions {
|
|
638
|
+
readonly expectedVersion?: number;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
interface StateNamespace {
|
|
642
|
+
readonly name: string;
|
|
643
|
+
get<T>(key: string): Promise<StateEntry<T> | null>;
|
|
644
|
+
set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
|
|
645
|
+
delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
interface ProjectState {
|
|
649
|
+
namespace(name: string): StateNamespace;
|
|
650
|
+
}
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
```typescript
|
|
654
|
+
const progress = state.namespace("inventory-sync");
|
|
655
|
+
const current = await progress.get<{ cursor: string }>("cursor");
|
|
656
|
+
|
|
657
|
+
const saved = await progress.set("cursor", { cursor: "next-page" }, {
|
|
658
|
+
expectedVersion: current?.version ?? 0,
|
|
659
|
+
ttlSeconds: 3600,
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
await progress.delete("cursor", { expectedVersion: saved.version });
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
### `state.namespace(name): StateNamespace`
|
|
666
|
+
|
|
667
|
+
Creates an immutable namespace client. Namespaces are at most 128 characters and
|
|
668
|
+
keys at most 255. Both start with an ASCII letter or digit and may contain letters,
|
|
669
|
+
digits, `.`, `_`, `:`, `/`, and `-`.
|
|
670
|
+
|
|
671
|
+
### `namespace.get<T>(key): Promise<StateEntry<T> | null>`
|
|
672
|
+
|
|
673
|
+
Returns `null` when the entry is missing or expired. An entry contains `value`,
|
|
674
|
+
`version`, `createdAt`, `updatedAt`, and optional `expiresAt`; timestamps are Unix
|
|
675
|
+
milliseconds.
|
|
676
|
+
|
|
677
|
+
### `namespace.set<T>(key, value, options?): Promise<StateEntry<T>>`
|
|
678
|
+
|
|
679
|
+
Stores a JSON value of at most 32 KiB (32,768 UTF-8 bytes after serialization).
|
|
680
|
+
`ttlSeconds` ranges from one second through 365 days; omit it for no automatic
|
|
681
|
+
expiry. Both option values must be safe integers. `expectedVersion` enables
|
|
682
|
+
compare-and-set: `0` means create only, a positive value must match the current
|
|
683
|
+
version, and omission is an unconditional upsert.
|
|
684
|
+
Conflicts throw `StateConflictError`; the returned entry has the new version.
|
|
685
|
+
|
|
686
|
+
### `namespace.delete(key, options?): Promise<boolean>`
|
|
687
|
+
|
|
688
|
+
Deletes an entry and returns whether it existed. `expectedVersion` has the same CAS
|
|
689
|
+
meaning as on `set`. Expired entries are treated as absent. State operations do not
|
|
690
|
+
form a transaction with Record API calls. Do not use state for secrets, files, or
|
|
691
|
+
large data.
|
|
692
|
+
|
|
693
|
+
## Distributed locks
|
|
694
|
+
|
|
695
|
+
Locks are distributed leases scoped by workspace, project, namespace, and key. They
|
|
696
|
+
prevent concurrent executions from entering the same protected section. Prefer
|
|
697
|
+
`withLock` for automatic release:
|
|
698
|
+
|
|
699
|
+
```typescript
|
|
700
|
+
interface LockOptions {
|
|
701
|
+
readonly namespace?: string;
|
|
702
|
+
readonly waitMs?: number;
|
|
703
|
+
readonly leaseMs?: number;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
interface LockLease {
|
|
707
|
+
readonly id: string;
|
|
708
|
+
readonly key: string;
|
|
709
|
+
readonly namespace: string;
|
|
710
|
+
readonly fencingToken: number;
|
|
711
|
+
readonly expiresAt: number;
|
|
712
|
+
renew(leaseMs?: number): Promise<void>;
|
|
713
|
+
release(): Promise<void>;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
interface DistributedLocks {
|
|
717
|
+
acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
|
|
718
|
+
withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
719
|
+
withLock<T>(key: string, options: LockOptions,
|
|
720
|
+
callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
721
|
+
}
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
```typescript
|
|
725
|
+
await locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
|
|
726
|
+
await processInvoice("INV-1", lease.fencingToken);
|
|
727
|
+
// Renew only if work can approach expiresAt.
|
|
728
|
+
// await lease.renew(30_000);
|
|
729
|
+
});
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
### `locks.acquire(key, options?): Promise<LockLease | null>`
|
|
733
|
+
|
|
734
|
+
Returns a lease, or `null` when it cannot acquire one within `waitMs`. The namespace
|
|
735
|
+
defaults to `default`; `waitMs` ranges from 0 through 10,000 ms; `leaseMs` ranges
|
|
736
|
+
from 5,000 through 60,000 ms and defaults to 30,000 ms. One invocation may hold at
|
|
737
|
+
most 16 locks. Keys are at most 255 characters and namespaces at most 128; both use
|
|
738
|
+
the same character rules as state names. Numeric options must be safe integers.
|
|
739
|
+
|
|
740
|
+
A lease exposes `id`, `key`, `namespace`, `fencingToken`, `expiresAt`,
|
|
741
|
+
`renew(leaseMs?)`, and `release()`. Renew and release verify ownership with a
|
|
742
|
+
token managed by Cogover; that token is never exposed to scripts. A lost or expired
|
|
743
|
+
lease throws `LockLostError`. Repeated `release()` on the same successfully released
|
|
744
|
+
lease object is a no-op.
|
|
745
|
+
|
|
746
|
+
### `locks.withLock(key, callback)` / `locks.withLock(key, options, callback)`
|
|
747
|
+
|
|
748
|
+
Acquires the lock, runs the callback, and releases in `finally`. Failure to acquire
|
|
749
|
+
throws `LockUnavailableError`. It does not auto-renew; long callbacks must call
|
|
750
|
+
`lease.renew()` before `expiresAt`.
|
|
751
|
+
|
|
752
|
+
A lock only guarantees one valid lease at a time. Timeouts, pauses, or network
|
|
753
|
+
failures may let old work continue after its lease expires. When the downstream
|
|
754
|
+
system supports it, store/check `fencingToken` and reject stale tokens. Locks do not
|
|
755
|
+
replace idempotency, provide exactly-once execution, or combine Record API and state
|
|
756
|
+
operations into a transaction.
|
|
757
|
+
|
|
758
|
+
## Schema API
|
|
759
|
+
|
|
760
|
+
`SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
|
|
761
|
+
|
|
762
|
+
```typescript
|
|
763
|
+
interface ObjectMetadata {
|
|
764
|
+
readonly id: string;
|
|
765
|
+
readonly name: string;
|
|
766
|
+
readonly slug: string;
|
|
767
|
+
readonly fields: readonly {
|
|
768
|
+
readonly id: string;
|
|
769
|
+
readonly name: string;
|
|
770
|
+
readonly slug: string;
|
|
771
|
+
readonly fieldType: string;
|
|
772
|
+
readonly required: boolean;
|
|
773
|
+
readonly multiple: boolean;
|
|
774
|
+
readonly readOnly: boolean;
|
|
775
|
+
readonly manualModifyAllow?: boolean;
|
|
776
|
+
readonly metaData?: Readonly<Record<string, unknown>>;
|
|
777
|
+
readonly options?: readonly {
|
|
778
|
+
readonly id: string;
|
|
779
|
+
readonly slug: string;
|
|
780
|
+
readonly value: string;
|
|
781
|
+
readonly isDefault?: boolean;
|
|
782
|
+
}[];
|
|
783
|
+
}[];
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
interface SchemaApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
787
|
+
object<Slug extends keyof Schema & string>(slug: Slug): Promise<ObjectMetadata>;
|
|
788
|
+
}
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
Object and field mutation are not part of this SDK. An invalid object slug throws
|
|
792
|
+
`ValidationError`; service failures use the error types described below.
|
|
793
|
+
|
|
794
|
+
## Logging
|
|
795
|
+
|
|
796
|
+
`context.log` implements `ScriptLogger`:
|
|
797
|
+
|
|
798
|
+
```typescript
|
|
799
|
+
interface ScriptLogger {
|
|
800
|
+
debug(message: string, details?: unknown): void;
|
|
801
|
+
info(message: string, details?: unknown): void;
|
|
802
|
+
warn(message: string, details?: unknown): void;
|
|
803
|
+
error(message: string, details?: unknown): void;
|
|
804
|
+
}
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
The optional `details` value is logged separately from the message. Do not include
|
|
808
|
+
credentials, tokens, personal data, or other secrets in either argument.
|
|
809
|
+
|
|
810
|
+
## Errors
|
|
811
|
+
|
|
812
|
+
API failures become `NotFoundError`, `ValidationError`,
|
|
813
|
+
`PermissionDeniedError`, `RateLimitError`, `StateConflictError`,
|
|
814
|
+
`LockUnavailableError`, `LockLostError`, or `CogoverApiError`.
|
|
815
|
+
|
|
816
|
+
```typescript
|
|
817
|
+
class CogoverApiError extends Error {
|
|
818
|
+
readonly code: string;
|
|
819
|
+
readonly r: number | undefined;
|
|
820
|
+
readonly details?: unknown;
|
|
821
|
+
constructor(code: string, message: string, details?: unknown);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
class NotFoundError extends CogoverApiError {
|
|
825
|
+
readonly resource: string;
|
|
826
|
+
readonly resourceId: string;
|
|
827
|
+
constructor(resource: string, resourceId: string, message?: string, details?: unknown);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
class ValidationError extends CogoverApiError {
|
|
831
|
+
constructor(message: string, details?: unknown);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
class PermissionDeniedError extends CogoverApiError {
|
|
835
|
+
constructor(message: string, details?: unknown);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
class RateLimitError extends CogoverApiError {
|
|
839
|
+
constructor(message: string, details?: unknown);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
class StateConflictError extends CogoverApiError {
|
|
843
|
+
constructor(message: string, details?: unknown);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
class LockUnavailableError extends CogoverApiError {
|
|
847
|
+
constructor(key: string, message?: string, details?: unknown);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
class LockLostError extends CogoverApiError {
|
|
851
|
+
constructor(message: string, details?: unknown);
|
|
852
|
+
}
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
Errors expose the SDK category in `error.code` and the original numeric server
|
|
856
|
+
result in `error.r` (also retained in `error.details.r`). `r` is `undefined` when
|
|
857
|
+
there was no server response, such as local SDK validation. The original message
|
|
858
|
+
remains in `error.message`.
|
|
859
|
+
|
|
860
|
+
Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
|
|
861
|
+
error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
|
|
862
|
+
the original code or message. A script's returned JSON remains its own response
|
|
863
|
+
with HTTP 200. All client-facing text in `msg`, `message`, and equivalent response
|
|
864
|
+
fields must be written in English, including responses created by customer scripts.
|
|
865
|
+
|
|
866
|
+
```typescript
|
|
867
|
+
try {
|
|
868
|
+
await orders.records.update(id, fields);
|
|
869
|
+
} catch (error) {
|
|
870
|
+
if (error instanceof CogoverApiError && error.r === 37) {
|
|
871
|
+
return { r: 1001, msg: "You do not have permission to update this order." };
|
|
872
|
+
}
|
|
873
|
+
throw error;
|
|
874
|
+
}
|
|
875
|
+
```
|
|
876
|
+
|
|
877
|
+
Import `CogoverApiError` from `@cogover/sdk`.
|
|
878
|
+
|
|
879
|
+
For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
|
|
880
|
+
`r` equal to the HTTP status, `code`, and a safe `msg`:
|
|
881
|
+
|
|
882
|
+
| SDK code | HTTP / `r` |
|
|
883
|
+
|---|---|
|
|
884
|
+
| `PERMISSION_DENIED` | 403 |
|
|
885
|
+
| `NOT_FOUND` | 404 |
|
|
886
|
+
| `METHOD_NOT_ALLOWED` | 405 |
|
|
887
|
+
| `VALIDATION_ERROR` | 400 |
|
|
888
|
+
| `RATE_LIMITED` | 429 |
|
|
889
|
+
| `STATE_CONFLICT` | 409 |
|
|
890
|
+
| `LOCK_NOT_ACQUIRED` | 409 |
|
|
891
|
+
| `LOCK_LOST` | 409 |
|
|
892
|
+
| `STATE_SERVICE_UNAVAILABLE` | 503 |
|
|
893
|
+
| `LOCK_SERVICE_UNAVAILABLE` | 503 |
|
|
894
|
+
| `FETCH_DISABLED` | 503 |
|
|
895
|
+
| `FETCH_BLOCKED` | 400 |
|
|
896
|
+
| `FETCH_REQUEST_TOO_LARGE` | 413 |
|
|
897
|
+
| `FETCH_RESPONSE_TOO_LARGE` | 502 |
|
|
898
|
+
| `FETCH_TIMEOUT` | 504 |
|
|
899
|
+
| `FETCH_FAILED` | 502 |
|
|
900
|
+
| `COGOVER_API_ERROR` | 422 |
|
|
901
|
+
|
|
902
|
+
Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
|
|
903
|
+
it does not mean the selected user was denied access to a particular record.
|
|
904
|
+
Raw error messages, stack traces and arbitrary details are not returned.
|
|
905
|
+
`writesMayHaveCompleted` is true if any record write was dispatched, even if a later
|
|
906
|
+
operation failed. It is a conservative warning, not confirmation of a successful write.
|
|
907
|
+
Unknown errors and resource-limit failures retain the generic HTTP 422 response.
|
|
908
|
+
These responses do not roll back earlier writes; do not retry writes automatically.
|
|
909
|
+
|
|
910
|
+
## Workspace declarations
|
|
911
|
+
|
|
912
|
+
`WorkspaceObjects` is an open interface. Without augmentation, object and field
|
|
913
|
+
slugs are strings with unknown field values. Generate and include a declaration to
|
|
914
|
+
make them workspace-specific:
|
|
915
|
+
|
|
916
|
+
```bash
|
|
917
|
+
npx cogover-generate-workspace-types objects.json workspace.d.ts
|
|
918
|
+
```
|
|
919
|
+
|
|
920
|
+
The generator reads Object metadata, sorts object and field slugs, and maps field
|
|
921
|
+
types as follows:
|
|
922
|
+
|
|
923
|
+
| Object field type | Generated TypeScript type |
|
|
924
|
+
|---|---|
|
|
925
|
+
| `short_text`, `long_text`, `phone`, `email`, `regex`, `auto_number`, `date` | `string` |
|
|
926
|
+
| `boolean` | `boolean` |
|
|
927
|
+
| `numeric`, `decimal`, `currency`, `percent`, `rating`, `time`, `date_time`, `time_duration` | `number` |
|
|
928
|
+
| `single_choice` | union of option slugs, or `string` |
|
|
929
|
+
| `multi_choices`, `label`, `cascading` | readonly array of option slugs, or strings |
|
|
930
|
+
| `url` | `UrlValue` |
|
|
931
|
+
| `file` | `FileValue` |
|
|
932
|
+
| `lookup_normal`, `reference` | `RecordReference<ObjectSlug>` when the target is known |
|
|
933
|
+
| `date_range` | `readonly [string, string]` |
|
|
934
|
+
| `date_time_range`, `time_range` | `readonly [number, number]` |
|
|
935
|
+
| unknown field type | `unknown` |
|
|
936
|
+
|
|
937
|
+
Fields that are not required include `null`; metadata marked `multiple` becomes a
|
|
938
|
+
readonly array unless its base type is already an array. Add the generated file to
|
|
939
|
+
the project's TypeScript compilation and do not edit it manually.
|
|
940
|
+
|
|
941
|
+
## Compatibility helper
|
|
942
|
+
|
|
943
|
+
```typescript
|
|
944
|
+
function createGreeting(name: string): string;
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
`createGreeting("Cogover")` returns `"Hello Cogover"`. It remains available for
|
|
948
|
+
SDK 0.1.x compatibility and is not part of the data APIs.
|