@cogover/sdk 0.10.0 → 0.12.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.
@@ -0,0 +1,92 @@
1
+ import { CogoverApiError, ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { optionalBoolean, optionalChoice, optionalIdempotencyKey, optionalText, personnelIds, requireKnownKeys, requiredText, } from "./internal/messaging.js";
4
+ import { isRecord } from "./internal/values.js";
5
+ const MAX_RECIPIENTS = 200;
6
+ const MAX_TITLE_CHARS = 200;
7
+ const MAX_SUBTITLE_CHARS = 200;
8
+ const MAX_CONTENT_CHARS = 16_384;
9
+ const MAX_LINK_CHARS = 2_048;
10
+ const CHANNEL_ID = /^[A-Za-z0-9_-]{1,64}$/u;
11
+ // The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
12
+ const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
13
+ const APP_PATH = /^\/(?!\/)[^\s\\]*$/u;
14
+ const MESSAGE_KEYS = new Set([
15
+ "to", "exclude", "title", "content", "contentType", "subtitle", "display", "link", "sender", "channel",
16
+ "email", "idempotencyKey",
17
+ ]);
18
+ const LINK_KEYS = new Set(["url", "openIn"]);
19
+ const CONTENT_TYPES = new Set(["text", "html"]);
20
+ const DISPLAYS = new Set(["SIMPLE", "FULL"]);
21
+ const SENDERS = new Set(["workspace", "actor"]);
22
+ const LINK_TARGETS = new Set(["SAME_TAB", "NEW_TAB"]);
23
+ /** @internal */
24
+ export function createNotificationsApi() {
25
+ return Object.freeze({
26
+ async send(message) {
27
+ const result = await callBridge("notifications.send", notificationPayload(message));
28
+ if (!isRecord(result) || typeof result.requestId !== "string" || typeof result.notified !== "number"
29
+ || !Array.isArray(result.skippedPersonnelIds) || typeof result.duplicate !== "boolean") {
30
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Notification result is invalid");
31
+ }
32
+ return Object.freeze({
33
+ requestId: result.requestId,
34
+ notified: result.notified,
35
+ skippedPersonnelIds: Object.freeze(result.skippedPersonnelIds.filter((id) => typeof id === "string")),
36
+ duplicate: result.duplicate,
37
+ });
38
+ },
39
+ });
40
+ }
41
+ function notificationPayload(message) {
42
+ const input = requireKnownKeys(message, MESSAGE_KEYS, "notifications.send() message");
43
+ const to = personnelIds(input.to, "to", MAX_RECIPIENTS, false);
44
+ if (to.length === 0)
45
+ throw new ValidationError("to must name at least one personnel ID");
46
+ const payload = {
47
+ to,
48
+ title: requiredText(input.title, "title", MAX_TITLE_CHARS),
49
+ content: requiredText(input.content, "content", MAX_CONTENT_CHARS),
50
+ };
51
+ if (input.exclude !== undefined)
52
+ payload.exclude = personnelIds(input.exclude, "exclude", MAX_RECIPIENTS, true);
53
+ const contentType = optionalChoice(input.contentType, "contentType", CONTENT_TYPES);
54
+ if (contentType !== undefined)
55
+ payload.contentType = contentType;
56
+ const subtitle = optionalText(input.subtitle, "subtitle", MAX_SUBTITLE_CHARS);
57
+ const display = optionalChoice(input.display, "display", DISPLAYS);
58
+ if (subtitle !== undefined) {
59
+ if (display === "SIMPLE")
60
+ throw new ValidationError("subtitle requires display \"FULL\"");
61
+ payload.subtitle = subtitle;
62
+ }
63
+ if (display !== undefined)
64
+ payload.display = display;
65
+ if (input.link !== undefined)
66
+ payload.link = notificationLink(input.link);
67
+ const sender = optionalChoice(input.sender, "sender", SENDERS);
68
+ if (sender !== undefined)
69
+ payload.sender = sender;
70
+ if (input.channel !== undefined) {
71
+ if (typeof input.channel !== "string" || !CHANNEL_ID.test(input.channel)) {
72
+ throw new ValidationError("channel must be a notification channel record ID");
73
+ }
74
+ payload.channel = input.channel;
75
+ }
76
+ const email = optionalBoolean(input.email, "email");
77
+ if (email !== undefined)
78
+ payload.email = email;
79
+ const idempotencyKey = optionalIdempotencyKey(input.idempotencyKey, "notifications.send()");
80
+ if (idempotencyKey !== undefined)
81
+ payload.idempotencyKey = idempotencyKey;
82
+ return payload;
83
+ }
84
+ function notificationLink(value) {
85
+ const link = requireKnownKeys(value, LINK_KEYS, "link");
86
+ const url = requiredText(link.url, "link.url", MAX_LINK_CHARS);
87
+ if (!APP_PATH.test(url) && !HTTP_URL.test(url)) {
88
+ throw new ValidationError("link.url must be a path starting with / or an absolute http or https URL");
89
+ }
90
+ const openIn = optionalChoice(link.openIn, "link.openIn", LINK_TARGETS);
91
+ return openIn === undefined ? { url } : { url, openIn };
92
+ }
package/dist/org.d.ts ADDED
@@ -0,0 +1,227 @@
1
+ /** Options of a read that can also return display data. */
2
+ export interface OrgReadOptions {
3
+ /**
4
+ * Adds names in `language`, and for personnel their email, avatar and code. Costs at most one extra read
5
+ * per kind of data; without it the answer comes from memory.
6
+ */
7
+ readonly withDisplay?: boolean;
8
+ /** Language of department and position names, such as `"vi-VN"`; defaults to the invocation language. */
9
+ readonly language?: string;
10
+ }
11
+ type WithDisplay = {
12
+ readonly withDisplay: true;
13
+ };
14
+ type Displayed<D extends boolean, T> = D extends true ? T : {};
15
+ /** Display data of a personnel. */
16
+ export interface OrgPersonnelDisplay {
17
+ /** Full name as the workspace shows it. */
18
+ readonly name: string;
19
+ readonly email: string | null;
20
+ /** Public URL of the avatar, or `null`. */
21
+ readonly avatar: string | null;
22
+ /** Personnel code, or `null`. */
23
+ readonly code: string | null;
24
+ }
25
+ /** Display data of a department or position. */
26
+ export interface OrgNameDisplay {
27
+ /** Name in the requested language, or the stored default name. */
28
+ readonly name: string;
29
+ }
30
+ /** The place of a personnel in one department. A personnel has at most one membership per department. */
31
+ export type OrgMembership<D extends boolean = false> = {
32
+ readonly personnelId: string;
33
+ readonly departmentId: string;
34
+ readonly positionId: string | null;
35
+ /** `0` for staff; `1` for the highest manager level of the department, `2` for the next one, and so on. */
36
+ readonly level: number;
37
+ /** Whether this is the personnel's primary department. */
38
+ readonly primary: boolean;
39
+ } & Displayed<D, {
40
+ readonly departmentName: string | null;
41
+ readonly positionName: string | null;
42
+ }>;
43
+ /** An active personnel of the workspace. */
44
+ export type OrgPersonnel<D extends boolean = false> = {
45
+ readonly id: string;
46
+ /** `null` for a personnel without a workspace account. */
47
+ readonly accountId: string | null;
48
+ /** Primary department first, then in tree order. */
49
+ readonly memberships: readonly OrgMembership<D>[];
50
+ } & Displayed<D, {
51
+ readonly display: OrgPersonnelDisplay | null;
52
+ }>;
53
+ /** One membership row returned by a member listing, with the personnel's account. */
54
+ export type OrgMember<D extends boolean = false> = OrgMembership<D> & {
55
+ readonly accountId: string | null;
56
+ } & Displayed<D, {
57
+ readonly display: OrgPersonnelDisplay | null;
58
+ }>;
59
+ /** An active department. */
60
+ export type OrgDepartment<D extends boolean = false> = {
61
+ readonly id: string;
62
+ /** `null` for a root department. */
63
+ readonly parentId: string | null;
64
+ /** `1` for a root department, `2` for its children, and so on. */
65
+ readonly level: number;
66
+ /** Child departments in display order. */
67
+ readonly childIds: readonly string[];
68
+ /** Positions that apply to the department. */
69
+ readonly positionIds: readonly string[];
70
+ } & Displayed<D, {
71
+ readonly display: OrgNameDisplay | null;
72
+ }>;
73
+ /** A department with its child departments, as returned by `departments.tree()`. */
74
+ export type OrgDepartmentNode<D extends boolean = false> = OrgDepartment<D> & {
75
+ /** Empty below the requested depth even when `childIds` is not. */
76
+ readonly children: readonly OrgDepartmentNode<D>[];
77
+ };
78
+ /** An active position. */
79
+ export type OrgPosition<D extends boolean = false> = {
80
+ readonly id: string;
81
+ /** `true`: applies only to `departmentIds`; `false`: applies to every department except `excludedDepartmentIds`. */
82
+ readonly departmentOnly: boolean;
83
+ readonly departmentIds: readonly string[];
84
+ readonly excludedDepartmentIds: readonly string[];
85
+ } & Displayed<D, {
86
+ readonly display: OrgNameDisplay | null;
87
+ }>;
88
+ /** The managers of one level of one department. */
89
+ export type OrgManagerTier<D extends boolean = false> = {
90
+ readonly departmentId: string;
91
+ readonly level: number;
92
+ /** `0` for the starting department, `1` for its parent, and so on. */
93
+ readonly distance: number;
94
+ /** Several personnel may share a level. */
95
+ readonly personnelIds: readonly string[];
96
+ } & Displayed<D, {
97
+ readonly departmentName: string | null;
98
+ readonly personnel: readonly {
99
+ readonly id: string;
100
+ readonly display: OrgPersonnelDisplay | null;
101
+ }[];
102
+ }>;
103
+ /** Managers above a personnel or a department, nearest first, up to the root department. */
104
+ export interface OrgManagerChain<D extends boolean = false> {
105
+ readonly fromDepartmentId: string;
106
+ /** Level of the personnel in `fromDepartmentId`; `0` for a department chain. */
107
+ readonly personnelLevel: number;
108
+ readonly tiers: readonly OrgManagerTier<D>[];
109
+ /** Departments passed without any eligible manager. */
110
+ readonly vacantDepartmentIds: readonly string[];
111
+ /** `true` when a parent department is inactive, so the chain stops before the real root. */
112
+ readonly truncated: boolean;
113
+ }
114
+ /** One page of a listing. */
115
+ export interface OrgPage<T> {
116
+ readonly items: readonly T[];
117
+ /** Number of items in all pages. */
118
+ readonly total: number;
119
+ /** Pass as `cursor` to read the next page; absent on the last page. */
120
+ readonly nextCursor?: string;
121
+ }
122
+ /** Result of `personnel.getMany()`. */
123
+ export interface OrgGetManyResult<T> {
124
+ /** Found personnel, in request order. */
125
+ readonly items: readonly T[];
126
+ /** Requested IDs that are not active personnel, in request order. */
127
+ readonly missingIds: readonly string[];
128
+ }
129
+ /** Options of a member listing. */
130
+ export interface OrgPageOptions extends OrgReadOptions {
131
+ /** Also list the members of every sub-department. */
132
+ readonly includeSubDepartments?: boolean;
133
+ /** Only personnel with a workspace account. */
134
+ readonly accountOnly?: boolean;
135
+ /** Page size: default 500 and at most 2000; default and at most 200 with `withDisplay`. */
136
+ readonly limit?: number;
137
+ readonly cursor?: string;
138
+ }
139
+ export interface OrgDepartmentMembersOptions extends OrgPageOptions {
140
+ /** Only members holding this position. */
141
+ readonly positionId?: string;
142
+ }
143
+ export interface OrgPositionMembersOptions extends OrgPageOptions {
144
+ /** Only holders in this department (and its sub-departments with `includeSubDepartments`). */
145
+ readonly departmentId?: string;
146
+ }
147
+ export interface OrgManagerOptions extends OrgReadOptions {
148
+ /** Only managers with a workspace account, for example approvers. */
149
+ readonly accountOnly?: boolean;
150
+ }
151
+ export interface OrgPersonnelChainOptions extends OrgManagerOptions {
152
+ /** Only the chain that starts in this department. */
153
+ readonly departmentId?: string;
154
+ }
155
+ export interface OrgTreeOptions extends OrgReadOptions {
156
+ /** Start below this department instead of at every root. */
157
+ readonly rootId?: string;
158
+ /** Number of levels to return, 1 to 100; defaults to all. */
159
+ readonly depth?: number;
160
+ }
161
+ export interface OrgIsInDepartmentOptions {
162
+ /** Also count membership of a sub-department. */
163
+ readonly includeSubDepartments?: boolean;
164
+ }
165
+ export interface OrgIsManagerOfOptions {
166
+ /** Only consider the chain that starts in this department of the personnel. */
167
+ readonly departmentId?: string;
168
+ /** Only the nearest manager level counts. */
169
+ readonly directOnly?: boolean;
170
+ }
171
+ /** Personnel of the workspace. */
172
+ export interface OrgPersonnelApi {
173
+ get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgPersonnel<true> | null>;
174
+ get(id: string, options?: OrgReadOptions): Promise<OrgPersonnel | null>;
175
+ /** Reads up to 200 personnel in one call; unknown IDs are reported in `missingIds`. */
176
+ getMany(ids: readonly string[], options: OrgReadOptions & WithDisplay): Promise<OrgGetManyResult<OrgPersonnel<true>>>;
177
+ getMany(ids: readonly string[], options?: OrgReadOptions): Promise<OrgGetManyResult<OrgPersonnel>>;
178
+ /** One chain per department of the personnel, primary department first; empty for an unknown personnel. */
179
+ managerChain(id: string, options: OrgPersonnelChainOptions & WithDisplay): Promise<readonly OrgManagerChain<true>[]>;
180
+ managerChain(id: string, options?: OrgPersonnelChainOptions): Promise<readonly OrgManagerChain[]>;
181
+ }
182
+ /** Departments of the workspace. */
183
+ export interface OrgDepartmentsApi {
184
+ get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgDepartment<true> | null>;
185
+ get(id: string, options?: OrgReadOptions): Promise<OrgDepartment | null>;
186
+ /** Root departments (or `rootId`) with their sub-departments; at most 5000 departments. */
187
+ tree(options: OrgTreeOptions & WithDisplay): Promise<readonly OrgDepartmentNode<true>[]>;
188
+ tree(options?: OrgTreeOptions): Promise<readonly OrgDepartmentNode[]>;
189
+ /** Parent first, root last. */
190
+ ancestors(id: string, options: OrgReadOptions & WithDisplay): Promise<readonly OrgDepartment<true>[]>;
191
+ ancestors(id: string, options?: OrgReadOptions): Promise<readonly OrgDepartment[]>;
192
+ /** Memberships of the department, managers first by level, then staff. */
193
+ members(id: string, options: OrgDepartmentMembersOptions & WithDisplay): Promise<OrgPage<OrgMember<true>>>;
194
+ members(id: string, options?: OrgDepartmentMembersOptions): Promise<OrgPage<OrgMember>>;
195
+ /** Managers of this department only, level 1 first. */
196
+ managers(id: string, options: OrgManagerOptions & WithDisplay): Promise<readonly OrgManagerTier<true>[]>;
197
+ managers(id: string, options?: OrgManagerOptions): Promise<readonly OrgManagerTier[]>;
198
+ /** Managers above a staff member of the department, nearest first. */
199
+ managerChain(id: string, options: OrgManagerOptions & WithDisplay): Promise<OrgManagerChain<true>>;
200
+ managerChain(id: string, options?: OrgManagerOptions): Promise<OrgManagerChain>;
201
+ }
202
+ /** Positions of the workspace. */
203
+ export interface OrgPositionsApi {
204
+ list(options: OrgReadOptions & WithDisplay): Promise<readonly OrgPosition<true>[]>;
205
+ list(options?: OrgReadOptions): Promise<readonly OrgPosition[]>;
206
+ get(id: string, options: OrgReadOptions & WithDisplay): Promise<OrgPosition<true> | null>;
207
+ get(id: string, options?: OrgReadOptions): Promise<OrgPosition | null>;
208
+ /** Holders of the position, in tree order of their departments. */
209
+ members(id: string, options: OrgPositionMembersOptions & WithDisplay): Promise<OrgPage<OrgMember<true>>>;
210
+ members(id: string, options?: OrgPositionMembersOptions): Promise<OrgPage<OrgMember>>;
211
+ }
212
+ /**
213
+ * Read-only access to the departments, positions and personnel of the workspace. Structure answers come from
214
+ * memory; `withDisplay` adds names and avatars. Other personnel fields are read with `data.object("personnel")`.
215
+ */
216
+ export interface OrgApi {
217
+ readonly personnel: OrgPersonnelApi;
218
+ readonly departments: OrgDepartmentsApi;
219
+ readonly positions: OrgPositionsApi;
220
+ /** The personnel of the invocation's user; `null` without a user. */
221
+ me(options: OrgReadOptions & WithDisplay): Promise<OrgPersonnel<true> | null>;
222
+ me(options?: OrgReadOptions): Promise<OrgPersonnel | null>;
223
+ isInDepartment(personnelId: string, departmentId: string, options?: OrgIsInDepartmentOptions): Promise<boolean>;
224
+ /** Whether `managerId` appears in a manager chain of `personnelId`. */
225
+ isManagerOf(managerId: string, personnelId: string, options?: OrgIsManagerOfOptions): Promise<boolean>;
226
+ }
227
+ export {};
package/dist/org.js ADDED
@@ -0,0 +1,227 @@
1
+ import { CogoverApiError, ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { isRecord } from "./internal/values.js";
4
+ const MAX_IDS = 200;
5
+ const MAX_PAGE_SIZE = 2000;
6
+ const MAX_TREE_DEPTH = 100;
7
+ const ID = /^[A-Za-z0-9_-]{1,64}$/u;
8
+ const LANGUAGE = /^[A-Za-z]{2,8}(?:[-_][A-Za-z0-9]{1,8}){0,3}$/u;
9
+ const DISPLAY_OPTIONS = ["withDisplay", "language"];
10
+ /** @internal */
11
+ export function createOrgApi(invocation) {
12
+ function payloadFor(method, options, allowed, display) {
13
+ if (options === undefined || options === null)
14
+ return {};
15
+ if (!isRecord(options))
16
+ throw new ValidationError(`${method} options must be an object`);
17
+ const payload = {};
18
+ for (const [name, value] of Object.entries(options)) {
19
+ if (value === undefined)
20
+ continue;
21
+ if (display && name === "withDisplay") {
22
+ payload.withDisplay = requireBoolean(value, `${method} withDisplay`);
23
+ }
24
+ else if (display && name === "language") {
25
+ payload.language = requireLanguage(value, `${method} language`);
26
+ }
27
+ else if (Object.prototype.hasOwnProperty.call(allowed, name)) {
28
+ payload[name] = option(allowed[name], value, `${method} ${name}`);
29
+ }
30
+ else {
31
+ throw new ValidationError(`${method} does not support option '${name}'`);
32
+ }
33
+ }
34
+ if (display && payload.withDisplay === true && payload.language === undefined) {
35
+ const language = defaultLanguage();
36
+ if (language !== undefined)
37
+ payload.language = language;
38
+ }
39
+ return payload;
40
+ }
41
+ function defaultLanguage() {
42
+ let context;
43
+ try {
44
+ context = invocation();
45
+ }
46
+ catch {
47
+ // Without invocation metadata the stored default names are returned.
48
+ return undefined;
49
+ }
50
+ const language = context.user?.membership.language ?? context.user?.language ?? context.workspace.language;
51
+ return typeof language === "string" && LANGUAGE.test(language) ? language : undefined;
52
+ }
53
+ async function read(operation, payload) {
54
+ return callBridge(operation, payload);
55
+ }
56
+ async function object(operation, payload) {
57
+ const result = await read(operation, payload);
58
+ if (!isRecord(result))
59
+ throw invalidResponse(operation);
60
+ return result;
61
+ }
62
+ async function nullableObject(operation, payload) {
63
+ const result = await read(operation, payload);
64
+ if (result !== null && !isRecord(result))
65
+ throw invalidResponse(operation);
66
+ return result;
67
+ }
68
+ async function list(operation, payload) {
69
+ const result = await read(operation, payload);
70
+ if (!Array.isArray(result))
71
+ throw invalidResponse(operation);
72
+ return Object.freeze(result);
73
+ }
74
+ async function flag(operation, payload) {
75
+ const result = await read(operation, payload);
76
+ if (typeof result !== "boolean")
77
+ throw invalidResponse(operation);
78
+ return result;
79
+ }
80
+ const pageOptions = {
81
+ includeSubDepartments: "boolean", accountOnly: "boolean", limit: "limit", cursor: "cursor",
82
+ };
83
+ const personnel = {
84
+ get(id, options) {
85
+ return nullableObject("org.personnel.get", {
86
+ ...payloadFor("personnel.get()", options, {}, true), id: requireId(id, "personnel id"),
87
+ });
88
+ },
89
+ getMany(ids, options) {
90
+ if (!Array.isArray(ids))
91
+ throw new ValidationError("personnel.getMany() requires an array of ids");
92
+ const unique = [...new Set(ids.map(id => requireId(id, "personnel id")))];
93
+ if (unique.length > MAX_IDS) {
94
+ throw new ValidationError(`personnel.getMany() supports at most ${MAX_IDS} unique ids`);
95
+ }
96
+ return object("org.personnel.getMany", {
97
+ ...payloadFor("personnel.getMany()", options, {}, true), ids: unique,
98
+ });
99
+ },
100
+ managerChain(id, options) {
101
+ return list("org.personnel.managerChain", {
102
+ ...payloadFor("personnel.managerChain()", options, { departmentId: "id", accountOnly: "boolean" }, true),
103
+ id: requireId(id, "personnel id"),
104
+ });
105
+ },
106
+ };
107
+ const departments = {
108
+ get(id, options) {
109
+ return nullableObject("org.departments.get", {
110
+ ...payloadFor("departments.get()", options, {}, true), id: requireId(id, "department id"),
111
+ });
112
+ },
113
+ tree(options) {
114
+ return list("org.departments.tree", payloadFor("departments.tree()", options, { rootId: "id", depth: "depth" }, true));
115
+ },
116
+ ancestors(id, options) {
117
+ return list("org.departments.ancestors", {
118
+ ...payloadFor("departments.ancestors()", options, {}, true), id: requireId(id, "department id"),
119
+ });
120
+ },
121
+ members(id, options) {
122
+ return object("org.departments.members", {
123
+ ...payloadFor("departments.members()", options, { ...pageOptions, positionId: "id" }, true),
124
+ id: requireId(id, "department id"),
125
+ });
126
+ },
127
+ managers(id, options) {
128
+ return list("org.departments.managers", {
129
+ ...payloadFor("departments.managers()", options, { accountOnly: "boolean" }, true),
130
+ id: requireId(id, "department id"),
131
+ });
132
+ },
133
+ managerChain(id, options) {
134
+ return object("org.departments.managerChain", {
135
+ ...payloadFor("departments.managerChain()", options, { accountOnly: "boolean" }, true),
136
+ id: requireId(id, "department id"),
137
+ });
138
+ },
139
+ };
140
+ const positions = {
141
+ list(options) {
142
+ return list("org.positions.list", payloadFor("positions.list()", options, {}, true));
143
+ },
144
+ get(id, options) {
145
+ return nullableObject("org.positions.get", {
146
+ ...payloadFor("positions.get()", options, {}, true), id: requireId(id, "position id"),
147
+ });
148
+ },
149
+ members(id, options) {
150
+ return object("org.positions.members", {
151
+ ...payloadFor("positions.members()", options, { ...pageOptions, departmentId: "id" }, true),
152
+ id: requireId(id, "position id"),
153
+ });
154
+ },
155
+ };
156
+ return Object.freeze({
157
+ personnel: Object.freeze(personnel),
158
+ departments: Object.freeze(departments),
159
+ positions: Object.freeze(positions),
160
+ async me(options) {
161
+ // Validate before deciding, so a wrong option fails the same way with and without a user.
162
+ payloadFor("me()", options, {}, true);
163
+ const context = invocation();
164
+ const personnelId = context.identity === "user" ? context.user.membership.personnelId : undefined;
165
+ if (personnelId === undefined)
166
+ return null;
167
+ return personnel.get(personnelId, options);
168
+ },
169
+ isInDepartment(personnelId, departmentId, options) {
170
+ return flag("org.isInDepartment", {
171
+ ...payloadFor("isInDepartment()", options, { includeSubDepartments: "boolean" }, false),
172
+ personnelId: requireId(personnelId, "personnel id"),
173
+ departmentId: requireId(departmentId, "department id"),
174
+ });
175
+ },
176
+ isManagerOf(managerId, personnelId, options) {
177
+ return flag("org.isManagerOf", {
178
+ ...payloadFor("isManagerOf()", options, { departmentId: "id", directOnly: "boolean" }, false),
179
+ managerId: requireId(managerId, "manager id"),
180
+ personnelId: requireId(personnelId, "personnel id"),
181
+ });
182
+ },
183
+ });
184
+ }
185
+ function option(kind, value, label) {
186
+ switch (kind) {
187
+ case "boolean":
188
+ return requireBoolean(value, label);
189
+ case "id":
190
+ return requireId(value, label);
191
+ case "limit":
192
+ return requireInteger(value, label, 1, MAX_PAGE_SIZE);
193
+ case "depth":
194
+ return requireInteger(value, label, 1, MAX_TREE_DEPTH);
195
+ case "cursor":
196
+ if (typeof value !== "string" || value === "")
197
+ throw new ValidationError(`${label} must be a cursor`);
198
+ return value;
199
+ default:
200
+ throw new ValidationError(`${label} is not supported`);
201
+ }
202
+ }
203
+ function requireId(value, label) {
204
+ if (typeof value !== "string" || !ID.test(value))
205
+ throw new ValidationError(`${label} must be a valid id`);
206
+ return value;
207
+ }
208
+ function requireBoolean(value, label) {
209
+ if (typeof value !== "boolean")
210
+ throw new ValidationError(`${label} must be a boolean`);
211
+ return value;
212
+ }
213
+ function requireInteger(value, label, min, max) {
214
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
215
+ throw new ValidationError(`${label} must be an integer between ${min} and ${max}`);
216
+ }
217
+ return value;
218
+ }
219
+ function requireLanguage(value, label) {
220
+ if (typeof value !== "string" || !LANGUAGE.test(value)) {
221
+ throw new ValidationError(`${label} must be a language tag such as "vi-VN"`);
222
+ }
223
+ return value;
224
+ }
225
+ function invalidResponse(operation) {
226
+ return new CogoverApiError("INVALID_BRIDGE_RESPONSE", `${operation} returned an unexpected response`);
227
+ }
package/dist/router.js CHANGED
@@ -60,9 +60,12 @@ export function createRouter() {
60
60
  state: context.state,
61
61
  locks: context.locks,
62
62
  push: context.push,
63
+ notifications: context.notifications,
64
+ email: context.email,
63
65
  jobs: context.jobs,
64
66
  secrets: context.secrets,
65
67
  crypto: context.crypto,
68
+ org: context.org,
66
69
  });
67
70
  });
68
71
  },
package/dist/script.d.ts CHANGED
@@ -7,10 +7,13 @@ import type { EffectiveWorkspaceObjects } from "./workspace.js";
7
7
  import type { ProjectState } from "./state.js";
8
8
  import type { DistributedLocks } from "./locks.js";
9
9
  import type { PushApi } from "./push.js";
10
+ import type { NotificationsApi } from "./notifications.js";
11
+ import type { EmailApi } from "./email.js";
10
12
  import type { InvocationContext } from "./invocation.js";
11
13
  import type { JobsApi } from "./jobs.js";
12
14
  import type { SecretsApi } from "./secrets.js";
13
15
  import type { CryptoApi } from "./crypto.js";
16
+ import type { OrgApi } from "./org.js";
14
17
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
15
18
  readonly input: TInput;
16
19
  readonly request: ScriptRequest<TInput>;
@@ -22,9 +25,12 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
22
25
  readonly state: ProjectState;
23
26
  readonly locks: DistributedLocks;
24
27
  readonly push: PushApi<TSchema>;
28
+ readonly notifications: NotificationsApi;
29
+ readonly email: EmailApi<TSchema>;
25
30
  readonly jobs: JobsApi;
26
31
  readonly secrets: SecretsApi;
27
32
  readonly crypto: CryptoApi;
33
+ readonly org: OrgApi;
28
34
  }
29
35
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
30
36
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -8,11 +8,14 @@ import { createSchemaApi } from "./schema.js";
8
8
  import { createStateApi } from "./state.js";
9
9
  import { createLocksApi } from "./locks.js";
10
10
  import { createPushApi } from "./push.js";
11
+ import { createNotificationsApi } from "./notifications.js";
12
+ import { createEmailApi } from "./email.js";
11
13
  import { installCogoverFetch } from "./fetch.js";
12
14
  import { invocationContext } from "./internal/invocation.js";
13
15
  import { createJobsApi } from "./internal/jobs-api.js";
14
16
  import { createSecretsApi } from "./secrets.js";
15
17
  import { crypto } from "./crypto.js";
18
+ import { createOrgApi } from "./org.js";
16
19
  export function defineScript(handler) {
17
20
  if (typeof handler !== "function") {
18
21
  throw new ValidationError("defineScript() requires a handler function");
@@ -48,9 +51,12 @@ export function createSandboxHandler(handler) {
48
51
  state: createStateApi(),
49
52
  locks: createLocksApi(),
50
53
  push: createPushApi(),
54
+ notifications: createNotificationsApi(),
55
+ email: createEmailApi(),
51
56
  jobs: createJobsApi(),
52
57
  secrets: createSecretsApi(),
53
58
  crypto,
59
+ org: createOrgApi(() => invocation ??= invocationContext(input)),
54
60
  });
55
61
  if (output === null) {
56
62
  return null;
package/dist/trigger.d.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { CryptoApi } from "./crypto.js";
2
2
  import type { DataApi } from "./data.js";
3
3
  import type { JobsApi } from "./jobs.js";
4
+ import type { OrgApi } from "./org.js";
4
5
  import type { SecretsApi } from "./secrets.js";
5
6
  import type { InvocationContext } from "./invocation.js";
6
7
  import type { ScriptLogger } from "./logger.js";
7
8
  import type { PushApi } from "./push.js";
9
+ import type { NotificationsApi } from "./notifications.js";
10
+ import type { EmailApi } from "./email.js";
8
11
  import type { FilterOperator } from "./query.js";
9
12
  import type { CogoverRecordId, UpdateFields } from "./records.js";
10
13
  import type { SchemaApi } from "./schema.js";
@@ -120,11 +123,16 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
120
123
  readonly log: ScriptLogger;
121
124
  /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
122
125
  readonly push: PushApi<TSchema>;
126
+ /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
127
+ readonly notifications: NotificationsApi;
128
+ /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
129
+ readonly email: EmailApi<TSchema>;
123
130
  /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
124
131
  readonly jobs: JobsApi;
125
132
  /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
126
133
  readonly secrets: SecretsApi;
127
134
  readonly crypto: CryptoApi;
135
+ readonly org: OrgApi;
128
136
  }
129
137
  export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
130
138
  /** Declares a record trigger. Add the result to the project's `triggers` export. */