@cogover/sdk 0.11.0 → 0.12.1

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 (41) hide show
  1. package/README.md +65 -21
  2. package/dist/crypto.js +89 -46
  3. package/dist/data.js +4 -1
  4. package/dist/email.d.ts +77 -0
  5. package/dist/email.js +192 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/internal/base64.js +76 -27
  8. package/dist/internal/bridge.js +41 -3
  9. package/dist/internal/job-config.js +7 -1
  10. package/dist/internal/job-runtime.js +4 -0
  11. package/dist/internal/messaging.js +75 -0
  12. package/dist/internal/trigger-runtime.js +5 -0
  13. package/dist/internal/utf8.js +18 -17
  14. package/dist/jobs.d.ts +4 -0
  15. package/dist/locks.js +13 -3
  16. package/dist/logger.js +47 -1
  17. package/dist/notifications.d.ts +56 -0
  18. package/dist/notifications.js +92 -0
  19. package/dist/org.js +14 -14
  20. package/dist/records.d.ts +13 -0
  21. package/dist/response.js +21 -1
  22. package/dist/router.js +2 -0
  23. package/dist/schema.d.ts +1 -0
  24. package/dist/script.d.ts +4 -0
  25. package/dist/script.js +11 -3
  26. package/dist/trigger.d.ts +6 -0
  27. package/docs/en/api-reference/background-jobs.md +288 -0
  28. package/docs/en/api-reference/cryptography.md +317 -0
  29. package/docs/en/api-reference/fetch-and-secrets.md +184 -0
  30. package/docs/en/api-reference/inbound-webhooks.md +65 -0
  31. package/docs/en/api-reference/notifications-and-email.md +317 -0
  32. package/docs/en/api-reference/organization-structure.md +304 -0
  33. package/docs/en/api-reference/overview.md +198 -0
  34. package/docs/en/api-reference/push-messages.md +115 -0
  35. package/docs/en/api-reference/record-triggers.md +469 -0
  36. package/docs/en/api-reference/records.md +447 -0
  37. package/docs/en/api-reference/scripts-and-routes.md +354 -0
  38. package/docs/en/api-reference/state-and-locks.md +162 -0
  39. package/docs/en/usage-guide.md +218 -19
  40. package/package.json +1 -1
  41. package/docs/en/api-reference.md +0 -2619
@@ -235,7 +235,9 @@ export default defineScript<Input>(async ({ input }) => {
235
235
  ```
236
236
 
237
237
  This Fetch-compatible API uses Cogover's managed network layer; it does not provide
238
- unrestricted Node.js network access. Only public HTTPS URLs on port 443 are supported.
238
+ unrestricted Node.js network access. Only public HTTPS URLs are supported, on port 443
239
+ or on another port whose exact origin a Workspace administrator approved for the
240
+ project.
239
241
  V1 does not follow redirects, maintain a cookie jar, stream, support WebSocket,
240
242
  accept IP-literal/userinfo URLs, or expose proxy, dispatcher, agent, DNS, or TLS
241
243
  configuration. Requests and responses are bounded. For remote mutations, use the
@@ -381,8 +383,8 @@ export default defineScript(async ({ locks }) =>
381
383
  }));
382
384
  ```
383
385
 
384
- `withLock` attempts release in `finally`; acquisition failure throws
385
- `LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
386
+ `withLock` releases the lease after the callback; when both fail, the callback's own
387
+ error is thrown. Acquisition failure throws `LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
386
388
  longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
387
389
  token in downstream systems where possible to reject stale writers. Locks do not
388
390
  replace idempotency or provide exactly-once execution.
@@ -480,7 +482,8 @@ router.post("/recalculate", async ({ jobs, response }) => {
480
482
 
481
483
  - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
482
484
  to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
483
- `jobs`, `secrets`, `crypto`, and `org` APIs as a script. Its return value is ignored.
485
+ `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
486
+ Its return value is ignored.
484
487
  - A run enqueued from a route or trigger acts as the user of that call. A scheduled
485
488
  run has no user: `data.object()` works only when the identity policy allows the
486
489
  system identity, so approve `allowInternalSystem` for projects with schedules.
@@ -498,9 +501,203 @@ router.post("/recalculate", async ({ jobs, response }) => {
498
501
  `duplicate: true`; `delayMs` or `runAt` postpones a run by up to 30 days. A
499
502
  payload is JSON of at most 64 KiB.
500
503
 
501
- See the [background job reference](api-reference.md#background-jobs) for every
504
+ See the [background job reference](api-reference/background-jobs.md#background-jobs) for every
502
505
  option and rule.
503
506
 
507
+ ## Send notifications and email
508
+
509
+ `notifications.send` puts a notification in people's notification list (the bell)
510
+ and, as the workspace's notification channel decides, also delivers it by web and
511
+ mobile push and as an email copy. `email.send` sends a real email from a shared
512
+ workspace mailbox or from the personal mailbox of the user who started the
513
+ execution, and can log it on a record's timeline. Both work in scripts, routes,
514
+ after-change triggers, and jobs; before-change triggers cannot use them.
515
+
516
+ ### Ask for an approval
517
+
518
+ ```typescript
519
+ import { defineTrigger } from "@cogover/sdk";
520
+
521
+ // Record ID of the workspace's "Approvals" notification channel.
522
+ const APPROVAL_CHANNEL = "NCHXXXXXXXXXXXX";
523
+
524
+ export const triggers = [
525
+ defineTrigger({
526
+ key: "leave_request_submitted",
527
+ object: "leave_request",
528
+ timing: "afterChange",
529
+ operations: ["create", "update"],
530
+ fields: ["status", "days"],
531
+ changedFields: ["status"],
532
+ when: { op: "=", field: "status", params: "submitted" },
533
+ runWhen: "onEnter",
534
+ }, async ({ records, trigger, invocation, org, notifications }) => {
535
+ const requesterId = invocation.user?.membership.personnelId;
536
+ if (requesterId === undefined) return;
537
+ // The nearest managers of the requester approve.
538
+ const [chain] = await org.personnel.managerChain(requesterId, { accountOnly: true });
539
+ const approverIds = chain?.tiers[0]?.personnelIds ?? [];
540
+ if (approverIds.length === 0) return;
541
+
542
+ for (const record of records) {
543
+ await notifications.send({
544
+ to: approverIds,
545
+ exclude: ["actor"],
546
+ sender: "actor",
547
+ title: "Leave request waiting for your approval",
548
+ subtitle: `${record.new.days} day(s)`,
549
+ content: "A leave request was submitted and needs your decision.",
550
+ link: { url: `/app/leave_request/${record.id}` },
551
+ channel: APPROVAL_CHANNEL,
552
+ // The same change of the same record always produces the same key.
553
+ idempotencyKey: `leave-approval:${trigger.changeId}:${record.id}`,
554
+ });
555
+ }
556
+ }),
557
+ ];
558
+ ```
559
+
560
+ - `to` takes 1 to 200 personnel IDs. Personnel without a user account are skipped
561
+ and returned in `skippedPersonnelIds`; `exclude: ["actor"]` skips the user who
562
+ caused the execution, and `sender: "actor"` shows that user as the sender.
563
+ - `channel` is the record ID of a notification channel of the workspace. It decides
564
+ which deliveries (in the web app, web push, mobile push, email) are enabled, and
565
+ each user may override it; without a channel, every delivery is enabled. Pass
566
+ `email: false` to never send the email copy. The copy comes from a Cogover
567
+ notification address and counts against the workspace plan's daily
568
+ notification-email limit.
569
+ - `link.url` is a path of the web app starting with `/` or an absolute `http(s)`
570
+ URL. `contentType: "html"` keeps only basic formatting such as paragraphs, lists,
571
+ tables, and links.
572
+ - Notifications need no approval in the identity policy.
573
+
574
+ ### Send a quote from a shared mailbox
575
+
576
+ ```typescript
577
+ import { createRouter, NotFoundError } from "@cogover/sdk";
578
+
579
+ const router = createRouter();
580
+
581
+ router.post("/quotes/:id/send", async ({ request, data, email, response }) => {
582
+ const quotes = data.object("quote");
583
+ const quote = await quotes.records.get(request.params.id, { fields: ["code"] });
584
+ if (!quote) throw new NotFoundError("quote", request.params.id);
585
+
586
+ // Pick the mailbox by address instead of hard-coding its ID.
587
+ const sales = (await email.senders()).find(sender => sender.email === "sales@example.com");
588
+ if (!sales) {
589
+ return response.json({ msg: "The sales mailbox is not available to this module." }, { status: 409 });
590
+ }
591
+
592
+ const result = await email.send({
593
+ from: { mailbox: sales.id },
594
+ subject: `Quote ${quote.fields.code}`,
595
+ html: "<p>Dear customer,</p><p>Please find our quote attached.</p>",
596
+ // Logs the email on the quote's timeline, with open and click tracking.
597
+ record: { object: "quote", recordId: quote.id },
598
+ // The customer's address comes from the quote's email field.
599
+ recordEmailFields: ["contact_email"],
600
+ attachments: [{ object: "quote", recordId: quote.id, field: "quote_pdf" }],
601
+ // A double click or a retried request does not send the quote twice.
602
+ idempotencyKey: `quote-email:${quote.id}`,
603
+ });
604
+ return response.json({ requestId: result.requestId, duplicate: result.duplicate }, { status: 202 });
605
+ });
606
+
607
+ export default router.toHandler();
608
+ ```
609
+
610
+ - `from` is `{ mailbox: id }` for a shared workspace mailbox or `"actor"` for the
611
+ default personal mailbox of the user who started the execution. Recipients are
612
+ addresses, `{ email, name }`, or `{ personnelId }`, at most 50 in `to`, `cc`, and
613
+ `bcc` together. Give exactly one of `html` and `text`.
614
+ - `recordEmailFields`, `attachments` (at most 10 files and 20 MB in total), and
615
+ `appendSignature` require `record`; `appendSignature` also requires
616
+ `from: "actor"`. The records must be readable by the execution's default identity.
617
+ - Without `record`, the email is only sent from the mailbox (`delivery: "direct"`).
618
+
619
+ ### Allow the module to send email
620
+
621
+ A module can send email only from the mailboxes an administrator allowed. The
622
+ administrator adds an `email` section to the Project's identity policy and approves
623
+ the policy for the version you publish:
624
+
625
+ ```json
626
+ {
627
+ "email": {
628
+ "workspaceMailboxIds": ["EMWXXXXXXXXXXXX"],
629
+ "allowActorMailbox": false
630
+ }
631
+ }
632
+ ```
633
+
634
+ `workspaceMailboxIds` lists the shared mailboxes the module may send from, and
635
+ `allowActorMailbox: true` allows `from: "actor"`. The section follows the rest of
636
+ the policy: it applies to the callers selected by `callerPersonnelIds`, and to
637
+ executions without a user (scheduled jobs, inbound webhooks) only when the policy
638
+ sets `allowInternalSystem: true`. A policy may contain only an `email` section. Any
639
+ other sender is refused with `PermissionDeniedError` and
640
+ `details.reason === "EMAIL_SENDER_NOT_GRANTED"`; `email.senders()` shows the
641
+ mailboxes the current execution may use.
642
+
643
+ ### Best-effort delivery
644
+
645
+ - A successful call means Cogover accepted the notification or email. Delivery
646
+ happens afterwards, and a later failure, such as a rejected address, is not
647
+ reported to the script. Record "sent" in your data as "accepted for sending", not
648
+ as proof of delivery.
649
+ - A sent notification or email cannot be recalled.
650
+ - By default a project may address 5,000 notification recipients and send 500
651
+ emails per hour; beyond that the call throws `RateLimitError` and sends nothing.
652
+ Spread large mailings over several job runs.
653
+
654
+ ### Use `idempotencyKey` in jobs and triggers
655
+
656
+ Jobs are delivered at least once and after-change triggers may run more than once,
657
+ so a retried run would notify or email again. Give each message an
658
+ `idempotencyKey` that stays the same across retries: a second call with the same
659
+ key within 7 days returns the first result with `duplicate: true` and sends
660
+ nothing.
661
+
662
+ ```typescript
663
+ import { defineJob } from "@cogover/sdk";
664
+
665
+ const BILLING_MAILBOX = "EMWXXXXXXXXXXXX";
666
+
667
+ export const overdueReminders = defineJob({
668
+ key: "overdue_invoice_reminders",
669
+ schedule: { cron: "0 8 * * *", timezone: "Asia/Ho_Chi_Minh" },
670
+ }, async ({ job, data, email }) => {
671
+ const invoices = data.object("invoice");
672
+ const overdue = await invoices.records.list({
673
+ where: invoices.fields.status.eq("overdue"),
674
+ fields: ["code"],
675
+ limit: 200,
676
+ });
677
+ for (const invoice of overdue.items) {
678
+ await email.send({
679
+ from: { mailbox: BILLING_MAILBOX },
680
+ subject: `Invoice ${invoice.fields.code} is overdue`,
681
+ text: "Our records show that this invoice is overdue. Please arrange payment.",
682
+ record: { object: "invoice", recordId: invoice.id },
683
+ recordEmailFields: ["billing_email"],
684
+ // job.id stays the same across attempts, so a retried run skips the emails it already sent.
685
+ idempotencyKey: `${job.id}:${invoice.id}`,
686
+ });
687
+ }
688
+ });
689
+
690
+ export const jobs = [overdueReminders];
691
+ ```
692
+
693
+ A scheduled run has no user, so this job needs `allowInternalSystem: true` in the
694
+ identity policy for both `data.object()` and the mailbox grant, and it cannot use
695
+ `from: "actor"`. A call made while an earlier call with the same key is still
696
+ sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`; let the run
697
+ fail with `RetryableError` or try again later. See
698
+ [Notifications](api-reference/notifications-and-email.md#notifications) and
699
+ [Email](api-reference/notifications-and-email.md#email) in the API reference for every option and error.
700
+
504
701
  ## Choose the identity for record operations
505
702
 
506
703
  Keep using `data.object("order")` to inherit the caller's identity. When an
@@ -538,7 +735,7 @@ reads apply the selected user's permissions; failures never retry as system.
538
735
  An uncaught permission error returns HTTP 403 with `code: "PERMISSION_DENIED"`.
539
736
  `reason: "IDENTITY_NOT_GRANTED"` means the project lacks approval to select that
540
737
  identity. Check `writesMayHaveCompleted` before considering a retry: earlier writes
541
- are not rolled back. See the [error response reference](api-reference.md#errors).
738
+ are not rolled back. See the [error response reference](api-reference/overview.md#errors).
542
739
 
543
740
  Unapproved selections fail; there is no automatic fallback. A project with
544
741
  privileged access must validate which records a caller may request it to process;
@@ -546,7 +743,7 @@ being able to see a record is not sufficient business authorization. Never let
546
743
  request input grant system privileges. Never place a Cogover API key or
547
744
  authentication object in module code, and never log or return credentials for an
548
745
  external service. See
549
- [API reference](api-reference.md#record-execution-identities).
746
+ [API reference](api-reference/records.md#record-execution-identities).
550
747
 
551
748
  ## Record triggers
552
749
 
@@ -651,10 +848,11 @@ inside the loop. Collect the IDs, call `records.getMany` once, and look the resu
651
848
  up from a `Map`, as in the example above.
652
849
 
653
850
  **Read-only.** A before-change trigger may read records and schema. Record writes,
654
- `fetch`, locks, state writes, and push messages are refused with `PermissionDeniedError`
655
- (`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
656
- has `records`, `trigger`, `invocation`, `data`, `schema`, `log`, and `push`; it has
657
- no `request`, `response`, `state`, or `locks`.
851
+ `fetch`, locks, state writes, push messages, notifications, and email are refused with
852
+ `PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`), for every identity.
853
+ The trigger context has `records`, `trigger`, `invocation`, `data`, `schema`, `log`,
854
+ `push`, `notifications`, and `email`; it has no `request`, `response`, `state`, or
855
+ `locks`.
658
856
 
659
857
  **Identity.** `data.object()` acts as the user who made the change, with that user's
660
858
  permissions, so a read can legitimately return nothing for a record the user cannot
@@ -665,15 +863,15 @@ in scripts.
665
863
  before-change triggers of one write share 8 seconds. Before-change triggers fail
666
864
  closed: when a handler throws, runs out of time, or cannot be run, the write is
667
865
  rejected and nothing is saved. Keep handlers short and deterministic. See the
668
- [record trigger reference](api-reference.md#record-triggers).
866
+ [record trigger reference](api-reference/record-triggers.md#record-triggers).
669
867
 
670
868
  ### After-change triggers
671
869
 
672
870
  Set `timing: "afterChange"` to run code after a change has been saved. The handler
673
871
  runs asynchronously, shortly after the write: the writer does not wait for it, and
674
872
  the handler can neither reject nor modify the saved change. Unlike a before-change
675
- trigger it may write records, call `fetch`, read secrets, and enqueue background
676
- jobs, like a script.
873
+ trigger it may write records, call `fetch`, read secrets, send notifications and
874
+ email, and enqueue background jobs, like a script.
677
875
 
678
876
  ```typescript
679
877
  import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
@@ -739,7 +937,7 @@ export const triggers = [
739
937
  - **Order.** After-change triggers of one change run independently; do not rely on
740
938
  their relative order, and read the current record when the latest values matter.
741
939
 
742
- See [After-change execution rules](api-reference.md#after-change-execution-rules).
940
+ See [After-change execution rules](api-reference/record-triggers.md#after-change-execution-rules).
743
941
 
744
942
  ## Recommended TypeScript configuration
745
943
 
@@ -783,9 +981,10 @@ Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `p
783
981
  decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
784
982
  `body`. Authentication headers are never exposed. Plain return values are JSON with
785
983
  HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
786
- status, safe response headers, and text/binary bodies. Missing routes return 404;
787
- unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
788
- Validate all business input. See the [router API reference](api-reference.md#http-routers-and-request-context).
984
+ status, safe response headers, and text/binary bodies. Missing routes, including a
985
+ path registered only for other methods, return 404; methods other than these five
986
+ return 405. Existing `defineScript()` projects continue at `/`.
987
+ Validate all business input. See the [router API reference](api-reference/scripts-and-routes.md#http-routers-and-request-context).
789
988
 
790
989
  ## Receive webhooks
791
990
 
@@ -848,4 +1047,4 @@ export const jobs = [
848
1047
  - Providers retry webhooks that did not get a 2xx answer, so use the event's own
849
1048
  ID as the job's `idempotencyKey`.
850
1049
 
851
- See [Inbound webhooks](api-reference.md#inbound-webhooks) for the complete rules.
1050
+ See [Inbound webhooks](api-reference/inbound-webhooks.md#inbound-webhooks) for the complete rules.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,