@cogover/sdk 0.1.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +347 -24
  2. package/dist/data.d.ts +49 -0
  3. package/dist/data.js +170 -0
  4. package/dist/errors.d.ts +37 -0
  5. package/dist/errors.js +72 -0
  6. package/dist/fetch.d.ts +28 -0
  7. package/dist/fetch.js +96 -0
  8. package/dist/index.d.ts +23 -3
  9. package/dist/index.js +8 -5
  10. package/dist/internal/bridge.js +48 -0
  11. package/dist/internal/invocation.js +57 -0
  12. package/dist/internal/json.js +81 -0
  13. package/dist/internal/request.js +87 -0
  14. package/dist/internal/trigger-config.js +212 -0
  15. package/dist/internal/trigger-runtime.js +211 -0
  16. package/dist/internal/validation.js +28 -0
  17. package/dist/internal/values.js +6 -0
  18. package/dist/invocation.d.ts +40 -0
  19. package/dist/invocation.js +1 -0
  20. package/dist/legacy.d.ts +2 -0
  21. package/dist/legacy.js +4 -0
  22. package/dist/locks.d.ts +19 -0
  23. package/dist/locks.js +68 -0
  24. package/dist/logger.d.ts +6 -0
  25. package/dist/logger.js +14 -0
  26. package/dist/query.d.ts +52 -0
  27. package/dist/query.js +59 -0
  28. package/dist/records.d.ts +79 -0
  29. package/dist/records.js +1 -0
  30. package/dist/request.d.ts +18 -0
  31. package/dist/request.js +1 -0
  32. package/dist/response.d.ts +21 -0
  33. package/dist/response.js +108 -0
  34. package/dist/router.d.ts +13 -0
  35. package/dist/router.js +104 -0
  36. package/dist/schema.d.ts +26 -0
  37. package/dist/schema.js +11 -0
  38. package/dist/script.d.ts +23 -0
  39. package/dist/script.js +56 -0
  40. package/dist/state.d.ts +24 -0
  41. package/dist/state.js +91 -0
  42. package/dist/trigger.d.ts +121 -0
  43. package/dist/trigger.js +15 -0
  44. package/dist/workspace.d.ts +8 -0
  45. package/dist/workspace.js +1 -0
  46. package/docs/en/api-reference.md +1415 -0
  47. package/docs/en/usage-guide.md +495 -0
  48. package/package.json +17 -5
  49. package/scripts/generate-workspace-types.mjs +135 -0
  50. package/dist/index.d.ts.map +0 -1
  51. package/dist/index.js.map +0 -1
@@ -0,0 +1,495 @@
1
+ # Using `@cogover/sdk`
2
+
3
+ ## What is a Custom Backend Module?
4
+
5
+ A **Custom Backend Module** adds server-side business logic to a Cogover
6
+ workspace. Use one to process requests, validate or transform data, automate
7
+ record operations, check or adjust records before they are saved, expose HTTP
8
+ routes, or integrate Cogover with an external service. It is different from a Custom Frontend Module, which implements a user
9
+ interface.
10
+
11
+ Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
12
+ types and APIs for the current invocation, workspace data, schema metadata,
13
+ logging, outbound HTTPS requests, state, and distributed locks. Cogover executes
14
+ the module with the permissions and resource limits configured for the project.
15
+
16
+ A typical development flow is:
17
+
18
+ 1. Create a TypeScript project and install `@cogover/sdk`.
19
+ 2. Generate `workspace.d.ts` so workspace Objects and fields are type-safe.
20
+ 3. Implement and locally type-check the module's default handler and its record
21
+ triggers.
22
+ 4. Publish the module to Cogover, configure its permissions, and invoke it
23
+ through the intended trigger or HTTP route.
24
+
25
+ ## Installation and type checking
26
+
27
+ ```bash
28
+ npm install @cogover/sdk
29
+ npx tsc --noEmit
30
+ ```
31
+
32
+ Place the generated `workspace.d.ts` declaration alongside the module's source
33
+ and include it in the TypeScript project.
34
+
35
+ ## Quick start
36
+
37
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
38
+ fields used below.
39
+
40
+ ```typescript
41
+ import { defineScript, NotFoundError } from "@cogover/sdk";
42
+
43
+ interface Input { recordId: string }
44
+ interface Output { recordId: string; total: number }
45
+
46
+ export default defineScript<Input, Output>(async ({ input, data, log }) => {
47
+ const orders = data.object("order");
48
+ const order = await orders.records.get(input.recordId, {
49
+ fields: ["subtotal", "tax", "status"],
50
+ });
51
+ if (!order) throw new NotFoundError("order", input.recordId);
52
+
53
+ const total = (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0);
54
+ await orders.records.update(order.id, { status: "processed", total });
55
+ log.info("Order processed", { recordId: order.id, total });
56
+ return { recordId: order.id, total };
57
+ });
58
+ ```
59
+
60
+ Generate `workspace.d.ts` from Object Info metadata and include it in the script's
61
+ TypeScript project. Cogover authentication credentials are not exposed to project
62
+ code. Access to data and external services is governed by the project's configured
63
+ permissions and limits.
64
+
65
+ The runtime applies object/operation/field permissions, capability call and byte
66
+ budgets, and a wall-clock deadline to the complete async handler lifecycle.
67
+
68
+ ## Read the current identity and workspace
69
+
70
+ Use the immutable `invocation` snapshot when business logic needs the user or
71
+ system identity and workspace that Cogover already resolved. This is an in-memory
72
+ read and does not make a data API request:
73
+
74
+ ```typescript
75
+ export default defineScript(({ invocation }) => {
76
+ const {workspace} = invocation;
77
+ if (invocation.identity === "system") {
78
+ return {workspaceId: workspace.id, user: null};
79
+ }
80
+ return {
81
+ workspaceId: workspace.id,
82
+ workspaceName: workspace.name,
83
+ accountId: invocation.user.accountId,
84
+ personnelId: invocation.user.membership.personnelId,
85
+ };
86
+ });
87
+ ```
88
+
89
+ Use the Record API only when you need richer, current Personnel business fields
90
+ such as department, position, manager, or custom fields. The snapshot intentionally
91
+ contains only documented fields and omits credentials and raw authentication data.
92
+
93
+ ## Filter and sort records
94
+
95
+ ```typescript
96
+ import { and, defineScript } from "@cogover/sdk";
97
+
98
+ export default defineScript(async ({ data }) => {
99
+ const orders = data.object("order");
100
+ return orders.records.list({
101
+ where: and(
102
+ orders.fields.status.in(["new", "nurturing"]),
103
+ orders.fields.is_active.eq(true),
104
+ orders.fields.total.gte(1_000_000),
105
+ ),
106
+ orderBy: [orders.fields.updated.desc()],
107
+ limit: 50,
108
+ });
109
+ });
110
+ ```
111
+
112
+ ## Read many records by ID
113
+
114
+ `records.getMany` reads up to 200 records with one capability call. `fields` is
115
+ required, and IDs that cannot be read are reported instead of being dropped:
116
+
117
+ ```typescript
118
+ const accounts = data.object("account");
119
+ const { records, missingIds } = await accounts.records.getMany(accountIds, {
120
+ fields: ["name", "credit_limit"],
121
+ });
122
+ const accountById = new Map(records.map(record => [String(record.id), record]));
123
+ if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds });
124
+ ```
125
+
126
+ Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
127
+ `ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
128
+ every capability call counts towards the project's limits.
129
+
130
+ ## Call an external API with `fetch`
131
+
132
+ ```typescript
133
+ import { defineScript, fetch } from "@cogover/sdk";
134
+
135
+ interface Input {
136
+ externalToken: string;
137
+ orderId: string;
138
+ }
139
+
140
+ export default defineScript<Input>(async ({ input }) => {
141
+ const response = await fetch("https://api.example.com/v1/orders", {
142
+ method: "POST",
143
+ headers: {
144
+ authorization: `Bearer ${input.externalToken}`,
145
+ "content-type": "application/json",
146
+ },
147
+ body: JSON.stringify({ id: input.orderId }),
148
+ timeoutMs: 5_000,
149
+ });
150
+ if (!response.ok) return { status: response.status };
151
+ return response.json();
152
+ });
153
+ ```
154
+
155
+ This Fetch-compatible API uses Cogover's managed network layer; it does not provide
156
+ unrestricted Node.js network access. Only public HTTPS URLs on port 443 are supported.
157
+ V1 does not follow redirects, maintain a cookie jar, stream, support WebSocket,
158
+ accept IP-literal/userinfo URLs, or expose proxy, dispatcher, agent, DNS, or TLS
159
+ configuration. Requests and responses are bounded. For remote mutations, use the
160
+ destination API's idempotency mechanism: a timeout or missing response does not
161
+ prove that the remote request was not applied.
162
+
163
+ ## Permissions and limits
164
+
165
+ - Cogover authentication credentials are never exposed to module code. Access is
166
+ limited to the configured Objects, operations, and fields.
167
+ - TypeScript types do not replace runtime validation of business input.
168
+ - Cogover limits capability calls, request and response sizes, and execution time.
169
+ - Do not automatically retry writes after a timeout because the commit outcome may
170
+ be unknown.
171
+
172
+ ## Store small progress with state
173
+
174
+ Use state for synchronization cursors, checkpoints, or small coordination flags
175
+ that must survive multiple executions and deployed project versions. Each value is
176
+ JSON of at most 32 KiB:
177
+
178
+ ```typescript
179
+ export default defineScript(async ({ state }) => {
180
+ const sync = state.namespace("inventory-sync");
181
+ const current = await sync.get<{ cursor: string }>("cursor");
182
+ const nextCursor = await fetchNextPage(current?.value.cursor);
183
+
184
+ const saved = await sync.set("cursor", { cursor: nextCursor }, {
185
+ expectedVersion: current?.version ?? 0,
186
+ ttlSeconds: 86_400,
187
+ });
188
+ return { version: saved.version };
189
+ });
190
+ ```
191
+
192
+ `expectedVersion` prevents overwriting a concurrent change. On
193
+ `StateConflictError`, read again and make a business-level merge/retry decision.
194
+ State is not for secrets or large data and is not transactional with record calls.
195
+
196
+ ## Prevent concurrent work with distributed locks
197
+
198
+ ```typescript
199
+ export default defineScript(async ({ locks }) =>
200
+ locks.withLock("daily-import", { namespace: "inventory", waitMs: 500 }, async lease => {
201
+ await runImport({ fencingToken: lease.fencingToken });
202
+ return { completed: true };
203
+ }));
204
+ ```
205
+
206
+ `withLock` attempts release in `finally`; acquisition failure throws
207
+ `LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
208
+ longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
209
+ token in downstream systems where possible to reject stale writers. Locks do not
210
+ replace idempotency or provide exactly-once execution.
211
+
212
+ ## Choose the identity for record operations
213
+
214
+ Keep using `data.object("order")` to inherit the caller's identity. When an
215
+ administrator has approved the project and caller for identity selection, use:
216
+
217
+ ```typescript
218
+ const orders = data.object("order");
219
+ const order = await orders.records.get(input.recordId, { fields: ["description"] });
220
+ if (!order) throw new NotFoundError("order", input.recordId);
221
+
222
+ // Choose one operation as required by the business workflow:
223
+ await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
224
+ // Or: await data.asSystem().object("order").records.update(order.id, { description: "System update" });
225
+ ```
226
+
227
+ `asUser` uses a personnel ID and supports both reads and writes. `asSystem` also supports reads and
228
+ can be used in public scripts without changing their authenticated caller. Both
229
+ return new clients, preserve workspace typing, and leave existing clients intact.
230
+
231
+ To read under a selected user, use the same scoped client for `get` and `list`:
232
+
233
+ ```typescript
234
+ const delegatedOrders = data.asUser(personnelId).object("order");
235
+ const record = await delegatedOrders.records.get(input.recordId, { fields: ["description"] });
236
+ const page = await delegatedOrders.records.list({ fields: ["description"], limit: 20 });
237
+ // Fetch another page with the same identity:
238
+ if (page.nextCursor) {
239
+ await delegatedOrders.records.list({ fields: ["description"], limit: 20, cursor: page.nextCursor });
240
+ }
241
+ ```
242
+
243
+ The administrator must approve read access separately from write access. These
244
+ reads apply the selected user's permissions; failures never retry as system.
245
+
246
+ An uncaught permission error returns HTTP 403 with `code: "PERMISSION_DENIED"`.
247
+ `reason: "IDENTITY_NOT_GRANTED"` means the project lacks approval to select that
248
+ identity. Check `writesMayHaveCompleted` before considering a retry: earlier writes
249
+ are not rolled back. See the [error response reference](api-reference.md#errors).
250
+
251
+ Unapproved selections fail; there is no automatic fallback. A project with
252
+ privileged access must validate which records a caller may request it to process;
253
+ being able to see a record is not sufficient business authorization. Never let
254
+ request input grant system privileges. Never place a Cogover API key or
255
+ authentication object in module code, and never log or return credentials for an
256
+ external service. See
257
+ [API reference](api-reference.md#record-execution-identities).
258
+
259
+ ## Record triggers
260
+
261
+ A record trigger runs your code when records of one Object are created, updated, or
262
+ deleted. A **before-change** trigger runs before the change is saved: it can reject
263
+ the change with validation errors and it can adjust the values that will be saved.
264
+ An **after-change** trigger runs after the change has been saved, for follow-up work
265
+ such as updating related records or notifying another system; see
266
+ [After-change triggers](#after-change-triggers). A trigger runs for every source of a write — the Cogover web application, API keys,
267
+ imports, automation processes, and other Custom Backend Modules — so a rule placed
268
+ in a trigger cannot be bypassed by choosing a different way to write the record.
269
+ Maintenance writes made by Cogover itself, such as recalculating formula and rollup
270
+ fields, background record merges, and cascading deletes, do not run triggers.
271
+
272
+ Declare triggers with `defineTrigger` and list them in the named `triggers` export.
273
+ The default export remains the HTTP handler and is optional in a project that only
274
+ has triggers. This example assumes that `workspace.d.ts` declares the Objects and
275
+ fields it uses.
276
+
277
+ ```typescript
278
+ import { defineTrigger, type RecordReference } from "@cogover/sdk";
279
+
280
+ const referenceId = (value: string | RecordReference | null | undefined): string | undefined =>
281
+ typeof value === "string" ? value : value?.id;
282
+
283
+ export const triggers = [
284
+ defineTrigger({
285
+ key: "order_credit_check",
286
+ name: "Order credit check",
287
+ object: "order",
288
+ timing: "beforeChange",
289
+ operations: ["create", "update"],
290
+ fields: ["status", "amount", "customer"],
291
+ changedFields: ["status", "amount", "customer"],
292
+ when: { op: "=", field: "status", params: "confirmed" },
293
+ writableFields: ["approval_level"],
294
+ }, async ({ records, data }) => {
295
+ // One read for the whole list, never one read per record.
296
+ const customerIds = records.flatMap(record => referenceId(record.new.customer) ?? []);
297
+ const customers = await data.object("account").records.getMany(customerIds, {
298
+ fields: ["credit_limit"],
299
+ });
300
+ const limitById = new Map<string, number>(
301
+ customers.records.map(customer => [customer.id, customer.fields.credit_limit ?? 0]),
302
+ );
303
+
304
+ for (const record of records) {
305
+ const amount = record.new.amount ?? 0;
306
+ const limit = limitById.get(referenceId(record.new.customer) ?? "");
307
+ if (limit === undefined) {
308
+ record.addError("customer", "CUSTOMER_NOT_AVAILABLE", "Select a customer that you can access.");
309
+ continue;
310
+ }
311
+ if (amount > limit) {
312
+ record.addError("amount", "CREDIT_LIMIT_EXCEEDED", "Amount exceeds the customer's credit limit.");
313
+ continue;
314
+ }
315
+ record.new.approval_level = amount > 100_000_000 ? "high" : "standard";
316
+ }
317
+ }),
318
+ ];
319
+ ```
320
+
321
+ Cogover applies the triggers of the active project version. What each setting does:
322
+
323
+ - `fields` selects the values delivered in `record.new` and `record.old`. Only
324
+ these fields and `id` are present, so a field that is not listed is `undefined`.
325
+ List only what the handler reads: one call is limited to 200 KiB.
326
+ - `operations` chooses `"create"`, `"update"`, and `"delete"`. `record.old` is
327
+ `null` for a created record and `record.new` is `null` for a deleted one; the
328
+ TypeScript types follow the operations you declare.
329
+ - `changedFields` makes an update run the trigger only when at least one listed
330
+ field changed. `record.changedFields` tells the handler which fields changed.
331
+ - `when` only runs the trigger for matching records. It is a plain object such as
332
+ `{ op: "=", field: "status", params: "confirmed" }`, combined with
333
+ `{ op: "and", conditions: [...] }` or `{ op: "or", conditions: [...] }`.
334
+ `runWhen: "onEnter"` runs the trigger only when a record starts matching `when`,
335
+ instead of on every matching write.
336
+ - `writableFields` lists the fields the handler may change (before-change only).
337
+ - `order` (1000–8999, default 5000) positions the trigger among the triggers of the
338
+ same Object. Later triggers see the values changed by earlier ones.
339
+ - `timeoutMs` (100–3000, default 2000) is the time budget of one call.
340
+
341
+ **Validate.** Call `record.addError(field, code, message?)` to reject a record; pass
342
+ `null` as the field for an error about the whole record. The code is an upper-case
343
+ identifier such as `CREDIT_LIMIT_EXCEEDED`. The optional message is an English text
344
+ of at most 500 characters that Cogover shows to the end user when it has no
345
+ translation for the code. A rejected record is not saved. In a batch write the other
346
+ rows continue.
347
+
348
+ **Modify.** Assign fields of `record.new`, for example
349
+ `record.new.approval_level = "high"`. Only `writableFields` may change; changing any
350
+ other field makes the write fail with a `ValidationError` naming the field. Assigned
351
+ values use the same format as `records.update` input, so a reference field accepts a
352
+ record ID and a date field accepts `"yyyy-MM-dd"`. Assigning `null` clears a field. Cogover validates the final values again before saving. A trigger
353
+ may fill a field whose manual entry is disabled, but never a read-only field such as
354
+ a formula, auto number, or rollup.
355
+
356
+ **Process the whole list.** A handler receives up to 200 records in one call: a
357
+ batch write or an import calls it once per chunk, not once per record. Never read
358
+ inside the loop. Collect the IDs, call `records.getMany` once, and look the results
359
+ up from a `Map`, as in the example above.
360
+
361
+ **Read-only.** A before-change trigger may read records and schema. Record writes,
362
+ `fetch`, locks, and state writes are refused with `PermissionDeniedError`
363
+ (`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
364
+ has `records`, `trigger`, `invocation`, `data`, `schema`, and `log`; it has no
365
+ `request`, `response`, `state`, or `locks`.
366
+
367
+ **Identity.** `data.object()` acts as the user who made the change, with that user's
368
+ permissions, so a read can legitimately return nothing for a record the user cannot
369
+ see. `data.asUser()` and `data.asSystem()` need the same administrator approval as
370
+ in scripts.
371
+
372
+ **Time budget and failures.** A call must finish within `timeoutMs`, and all
373
+ before-change triggers of one write share 8 seconds. Before-change triggers fail
374
+ closed: when a handler throws, runs out of time, or cannot be run, the write is
375
+ rejected and nothing is saved. Keep handlers short and deterministic. See the
376
+ [record trigger reference](api-reference.md#record-triggers).
377
+
378
+ ### After-change triggers
379
+
380
+ Set `timing: "afterChange"` to run code after a change has been saved. The handler
381
+ runs asynchronously, shortly after the write: the writer does not wait for it, and
382
+ the handler can neither reject nor modify the saved change. Unlike a before-change
383
+ trigger it may write records and call `fetch`, like a script.
384
+
385
+ ```typescript
386
+ import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
387
+
388
+ export const triggers = [
389
+ defineTrigger({
390
+ key: "order_confirmed_followup",
391
+ object: "order",
392
+ timing: "afterChange",
393
+ operations: ["create", "update"],
394
+ fields: ["status", "amount", "customer"],
395
+ changedFields: ["status"],
396
+ when: { op: "=", field: "status", params: "confirmed" },
397
+ runWhen: "onEnter",
398
+ }, async ({ records, trigger, data }) => {
399
+ for (const record of records) {
400
+ // record.new holds the saved values; record.id is always set after the save.
401
+ const response = await fetch("https://erp.example.com/orders", {
402
+ method: "POST",
403
+ headers: {
404
+ "content-type": "application/json",
405
+ "idempotency-key": `${trigger.changeId}:${record.id}`,
406
+ },
407
+ body: JSON.stringify({ id: record.id, amount: record.new.amount }),
408
+ });
409
+ if (response.status >= 500) {
410
+ // Temporary problem: ask Cogover to run this handler again later.
411
+ throw new RetryableError("The ERP is temporarily unavailable");
412
+ }
413
+ if (!response.ok) continue; // Permanent problem: retrying would not help.
414
+
415
+ await data.object("order_activity").records.create({
416
+ order: record.id,
417
+ activity: "Sent to ERP",
418
+ });
419
+ }
420
+ }),
421
+ ];
422
+ ```
423
+
424
+ - **Saved values.** `record.new` contains the values as saved, including the record
425
+ ID and values assigned while saving, such as an auto number. `record.old` contains
426
+ the values before the change. A deleted record has `record.new === null`.
427
+ - **No blocking, no changes.** `writableFields` is not allowed and `record.new` must
428
+ not be changed. `record.addError()` rejects nothing here; the errors are only
429
+ written to the project log. To change the record, call `records.update`.
430
+ - **Best-effort delivery.** Cogover does not guarantee that the handler runs exactly
431
+ once: it may occasionally run more than once for the same change, or not at all.
432
+ Make handlers idempotent — `trigger.changeId` together with `record.id` identifies
433
+ one change of one record — and never rely on an after-change trigger as the only
434
+ guarantee of a critical rule. Put such rules in a before-change trigger.
435
+ - **Retries.** Throw `RetryableError` for a temporary failure. Cogover runs the
436
+ handler again later, by default up to 5 more times with growing delays from about
437
+ one second to about ten minutes. A call that runs out of time is retried the same
438
+ way. Any other error is logged and not retried, so catch the errors you can handle
439
+ and decide which of them deserve a retry.
440
+ - **Loops end.** A write made by the handler runs triggers again, possibly including
441
+ the same one. Cogover limits such chains: every automated write uses one step of a
442
+ fixed budget (10 steps for a change made directly by a user or an API client), and
443
+ after-change triggers stop running once it is used up. Narrow the trigger with
444
+ `changedFields`, `when`, and `runWhen: "onEnter"` so its own writes do not start
445
+ it again.
446
+ - **Order.** After-change triggers of one change run independently; do not rely on
447
+ their relative order, and read the current record when the latest values matter.
448
+
449
+ See [After-change execution rules](api-reference.md#after-change-execution-rules).
450
+
451
+ ## Recommended TypeScript configuration
452
+
453
+ ```json
454
+ {
455
+ "compilerOptions": {
456
+ "target": "ES2022",
457
+ "module": "ESNext",
458
+ "moduleResolution": "Bundler",
459
+ "strict": true,
460
+ "noEmit": true,
461
+ "skipLibCheck": true
462
+ },
463
+ "include": ["src/**/*.ts", "workspace.d.ts"]
464
+ }
465
+ ```
466
+
467
+ Import from `@cogover/sdk` and project-local source only. Custom Backend Modules
468
+ do not support Node.js built-ins, unapproved packages, URL imports, `require()`, or
469
+ dynamic `import()`.
470
+
471
+ ## Full HTTP routes and responses
472
+
473
+ ```typescript
474
+ import { createRouter } from "@cogover/sdk";
475
+
476
+ const router = createRouter();
477
+ router.get("/orders/:orderId", ({ request, response }) => response.json({
478
+ orderId: request.params.orderId,
479
+ expand: request.query.expand,
480
+ }));
481
+ router.post<{ description: string }, object>("/orders", ({ request, response }) =>
482
+ response.json({ description: request.body.description }, { status: 201 }));
483
+ router.put("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
484
+ router.patch("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
485
+ router.delete("/orders/:orderId", ({ response }) => response.empty());
486
+ export default router.toHandler();
487
+ ```
488
+
489
+ Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `path`,
490
+ decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
491
+ `body`. Authentication headers are never exposed. Plain return values are JSON with
492
+ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
493
+ status, safe response headers, and text/binary bodies. Missing routes return 404;
494
+ unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
495
+ Validate all business input. See the [router API reference](api-reference.md#http-routers-and-request-context).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.1.2",
4
- "description": "TypeScript SDK for customer code running on Cogover",
3
+ "version": "0.6.0",
4
+ "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "./dist/index.js",
@@ -14,16 +14,24 @@
14
14
  "default": "./dist/index.js"
15
15
  }
16
16
  },
17
+ "bin": {
18
+ "cogover-generate-workspace-types": "scripts/generate-workspace-types.mjs"
19
+ },
17
20
  "files": [
18
21
  "dist",
22
+ "!dist/internal/**/*.d.ts",
23
+ "docs/en",
24
+ "scripts/generate-workspace-types.mjs",
19
25
  "README.md"
20
26
  ],
21
27
  "scripts": {
22
28
  "clean": "node ./scripts/clean.mjs",
23
29
  "build": "npm run clean && tsc -p tsconfig.json && npm run build:runtime",
24
30
  "build:runtime": "node ./scripts/build-runtime-module.mjs",
25
- "typecheck": "tsc -p tsconfig.json --noEmit",
26
- "test": "npm run build && node --test",
31
+ "generate:workspace-types": "node ./scripts/generate-workspace-types.mjs",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
33
+ "typecheck:dist": "tsc -p tsconfig.dist-test.json --noEmit",
34
+ "test": "npm run build && npm run typecheck:dist && node --test",
27
35
  "check": "npm run typecheck && npm test",
28
36
  "pack:dry-run": "npm pack --dry-run --ignore-scripts",
29
37
  "prepack": "npm run check"
@@ -37,7 +45,11 @@
37
45
  "typescript"
38
46
  ],
39
47
  "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
40
51
  "devDependencies": {
41
- "typescript": "5.9.3"
52
+ "esbuild": "0.28.2",
53
+ "typescript": "7.0.2"
42
54
  }
43
55
  }
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+
5
+ const [inputPath, outputPath] = process.argv.slice(2);
6
+ if (!inputPath || !outputPath) {
7
+ throw new Error("Usage: node generate-workspace-types.mjs <objects.json> <workspace.d.ts>");
8
+ }
9
+
10
+ const document = JSON.parse(await readFile(inputPath, "utf8"));
11
+ const objects = extractObjects(document);
12
+ const declaration = renderDeclaration(objects);
13
+ await writeFile(outputPath, declaration, "utf8");
14
+
15
+ function extractObjects(documentValue) {
16
+ const candidates = [
17
+ documentValue,
18
+ documentValue?.items,
19
+ documentValue?.data?.items,
20
+ documentValue?.data?.rows,
21
+ ];
22
+ const objectsValue = candidates.find(Array.isArray);
23
+ if (!objectsValue) {
24
+ throw new Error("Object metadata must contain an items array");
25
+ }
26
+ return objectsValue;
27
+ }
28
+
29
+ function renderDeclaration(objectsValue) {
30
+ const objectLines = objectsValue
31
+ .filter((object) => typeof object?.slug === "string" && object.slug.length > 0)
32
+ .sort((left, right) => left.slug.localeCompare(right.slug))
33
+ .map(renderObject)
34
+ .join("\n");
35
+
36
+ return `// Generated by @cogover/sdk. Do not edit manually.\n`
37
+ + `import "@cogover/sdk";\n\n`
38
+ + `declare module "@cogover/sdk" {\n`
39
+ + ` interface WorkspaceObjects {\n`
40
+ + objectLines
41
+ + ` }\n`
42
+ + `}\n`;
43
+ }
44
+
45
+ function renderObject(object) {
46
+ const fields = Array.isArray(object.fields) ? object.fields : [];
47
+ const fieldLines = fields
48
+ .filter((field) => typeof field?.slug === "string" && field.slug.length > 0)
49
+ .sort((left, right) => left.slug.localeCompare(right.slug))
50
+ .map((field) => ` ${property(field.slug)}: ${fieldType(field)};\n`)
51
+ .join("");
52
+ return ` ${property(object.slug)}: {\n${fieldLines} };\n`;
53
+ }
54
+
55
+ function fieldType(field) {
56
+ const baseType = baseFieldType(field);
57
+ const nullableType = field.required === true ? baseType : `${baseType} | null`;
58
+ return field.multiple === true && !baseType.endsWith("[]")
59
+ ? `readonly ${parenthesize(baseType)}[]${field.required === true ? "" : " | null"}`
60
+ : nullableType;
61
+ }
62
+
63
+ function baseFieldType(field) {
64
+ switch (field.fieldType) {
65
+ case "short_text":
66
+ case "long_text":
67
+ case "phone":
68
+ case "email":
69
+ case "regex":
70
+ case "auto_number":
71
+ case "date":
72
+ return "string";
73
+ case "boolean":
74
+ return "boolean";
75
+ case "numeric":
76
+ case "decimal":
77
+ case "currency":
78
+ case "percent":
79
+ case "rating":
80
+ case "time":
81
+ case "date_time":
82
+ case "time_duration":
83
+ return "number";
84
+ case "single_choice":
85
+ return optionUnion(field.options);
86
+ case "multi_choices":
87
+ case "label":
88
+ case "cascading":
89
+ return `readonly ${parenthesize(optionUnion(field.options))}[]`;
90
+ case "url":
91
+ return "UrlValue";
92
+ case "file":
93
+ return "FileValue";
94
+ case "lookup_normal":
95
+ case "reference": {
96
+ const objectSlug = referenceObjectSlug(field);
97
+ return objectSlug === null
98
+ ? "RecordReference"
99
+ : `RecordReference<${JSON.stringify(objectSlug)}>`;
100
+ }
101
+ case "date_range":
102
+ return "readonly [string, string]";
103
+ case "date_time_range":
104
+ case "time_range":
105
+ return "readonly [number, number]";
106
+ default:
107
+ return "unknown";
108
+ }
109
+ }
110
+
111
+ function optionUnion(options) {
112
+ const slugs = Array.isArray(options)
113
+ ? options
114
+ .map((option) => option?.slug)
115
+ .filter((slug) => typeof slug === "string" && slug.length > 0)
116
+ : [];
117
+ return slugs.length === 0 ? "string" : slugs.map(JSON.stringify).join(" | ");
118
+ }
119
+
120
+ function referenceObjectSlug(field) {
121
+ const metadata = field.metaData ?? field.meta_data ?? {};
122
+ return metadata.objectSlug
123
+ ?? metadata.object_slug
124
+ ?? metadata.lookupObjectSlug
125
+ ?? metadata.lookup_object_slug
126
+ ?? null;
127
+ }
128
+
129
+ function property(value) {
130
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(value) ? value : JSON.stringify(value);
131
+ }
132
+
133
+ function parenthesize(value) {
134
+ return value.includes(" | ") ? `(${value})` : value;
135
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,UAAU,cAAc,CAAC,IAAY;IACvC,OAAO,SAAS,IAAI,EAAE,CAAC;AAC3B,CAAC"}