@cogover/sdk 0.12.0 → 0.12.2

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.
@@ -1,41 +1,105 @@
1
- const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1
+ const A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2
2
  const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
3
- // Sandboxed code has neither Buffer nor atob/btoa, so binary data crosses the bridge through these helpers.
3
+ let digits;
4
+ /** 6-bit value of each base64 character code; "=" reads as 0 once the text has been validated. */
5
+ function digitTable() {
6
+ if (digits === undefined) {
7
+ const table = new Int32Array(128);
8
+ for (let index = 0; index < A.length; index++)
9
+ table[A.charCodeAt(index)] = index;
10
+ digits = table;
11
+ }
12
+ return digits;
13
+ }
4
14
  /** Standard base64 with padding (RFC 4648 section 4). */
5
15
  export function encodeBase64(bytes) {
6
- let result = "";
7
- for (let index = 0; index < bytes.length; index += 3) {
8
- const first = bytes[index] ?? 0;
9
- const second = bytes[index + 1] ?? 0;
10
- const third = bytes[index + 2] ?? 0;
11
- const value = (first << 16) | (second << 8) | third;
12
- result += ALPHABET.charAt((value >>> 18) & 63)
13
- + ALPHABET.charAt((value >>> 12) & 63)
14
- + (index + 1 < bytes.length ? ALPHABET.charAt((value >>> 6) & 63) : "=")
15
- + (index + 2 < bytes.length ? ALPHABET.charAt(value & 63) : "=");
16
+ const toBase64 = Uint8Array.prototype.toBase64;
17
+ return typeof toBase64 === "function" ? toBase64.call(bytes) : encodeBase64InGuest(bytes);
18
+ }
19
+ /** Lowercase hexadecimal, two digits per byte. */
20
+ export function encodeHex(bytes) {
21
+ const toHex = Uint8Array.prototype.toHex;
22
+ if (typeof toHex === "function")
23
+ return toHex.call(bytes);
24
+ let hex = "";
25
+ for (const byte of bytes)
26
+ hex += (byte < 16 ? "0" : "") + byte.toString(16);
27
+ return hex;
28
+ }
29
+ function encodeBase64InGuest(bytes) {
30
+ const length = bytes.length;
31
+ const whole = length - (length % 3);
32
+ const parts = [];
33
+ let index = 0;
34
+ for (; index + 24 <= whole; index += 24) {
35
+ parts[parts.length] = A.charAt(bytes[index] >>> 2) + A.charAt(((bytes[index] & 3) << 4) | (bytes[index + 1] >>> 4))
36
+ + A.charAt(((bytes[index + 1] & 15) << 2) | (bytes[index + 2] >>> 6)) + A.charAt(bytes[index + 2] & 63)
37
+ + A.charAt(bytes[index + 3] >>> 2) + A.charAt(((bytes[index + 3] & 3) << 4) | (bytes[index + 4] >>> 4))
38
+ + A.charAt(((bytes[index + 4] & 15) << 2) | (bytes[index + 5] >>> 6)) + A.charAt(bytes[index + 5] & 63)
39
+ + A.charAt(bytes[index + 6] >>> 2) + A.charAt(((bytes[index + 6] & 3) << 4) | (bytes[index + 7] >>> 4))
40
+ + A.charAt(((bytes[index + 7] & 15) << 2) | (bytes[index + 8] >>> 6)) + A.charAt(bytes[index + 8] & 63)
41
+ + A.charAt(bytes[index + 9] >>> 2) + A.charAt(((bytes[index + 9] & 3) << 4) | (bytes[index + 10] >>> 4))
42
+ + A.charAt(((bytes[index + 10] & 15) << 2) | (bytes[index + 11] >>> 6)) + A.charAt(bytes[index + 11] & 63)
43
+ + A.charAt(bytes[index + 12] >>> 2) + A.charAt(((bytes[index + 12] & 3) << 4) | (bytes[index + 13] >>> 4))
44
+ + A.charAt(((bytes[index + 13] & 15) << 2) | (bytes[index + 14] >>> 6)) + A.charAt(bytes[index + 14] & 63)
45
+ + A.charAt(bytes[index + 15] >>> 2) + A.charAt(((bytes[index + 15] & 3) << 4) | (bytes[index + 16] >>> 4))
46
+ + A.charAt(((bytes[index + 16] & 15) << 2) | (bytes[index + 17] >>> 6)) + A.charAt(bytes[index + 17] & 63)
47
+ + A.charAt(bytes[index + 18] >>> 2) + A.charAt(((bytes[index + 18] & 3) << 4) | (bytes[index + 19] >>> 4))
48
+ + A.charAt(((bytes[index + 19] & 15) << 2) | (bytes[index + 20] >>> 6)) + A.charAt(bytes[index + 20] & 63)
49
+ + A.charAt(bytes[index + 21] >>> 2) + A.charAt(((bytes[index + 21] & 3) << 4) | (bytes[index + 22] >>> 4))
50
+ + A.charAt(((bytes[index + 22] & 15) << 2) | (bytes[index + 23] >>> 6)) + A.charAt(bytes[index + 23] & 63);
51
+ }
52
+ for (; index < whole; index += 3) {
53
+ parts[parts.length] = A.charAt(bytes[index] >>> 2) + A.charAt(((bytes[index] & 3) << 4) | (bytes[index + 1] >>> 4))
54
+ + A.charAt(((bytes[index + 1] & 15) << 2) | (bytes[index + 2] >>> 6)) + A.charAt(bytes[index + 2] & 63);
16
55
  }
17
- return result;
56
+ if (length - whole === 1) {
57
+ parts[parts.length] = `${A.charAt(bytes[whole] >>> 2)}${A.charAt((bytes[whole] & 3) << 4)}==`;
58
+ }
59
+ else if (length - whole === 2) {
60
+ parts[parts.length] = `${A.charAt(bytes[whole] >>> 2)}${A.charAt(((bytes[whole] & 3) << 4) | (bytes[whole + 1] >>> 4))}`
61
+ + `${A.charAt((bytes[whole + 1] & 15) << 2)}=`;
62
+ }
63
+ return parts.join("");
18
64
  }
19
65
  /** Decodes padded standard base64; returns null for text that is not canonical base64. */
20
66
  export function decodeBase64(text) {
67
+ // The built-in also accepts whitespace and missing padding, so the text is validated first either way.
21
68
  if (typeof text !== "string" || !BASE64.test(text))
22
69
  return null;
70
+ const fromBase64 = Uint8Array.fromBase64;
71
+ return typeof fromBase64 === "function" ? fromBase64.call(Uint8Array, text) : decodeBase64InGuest(text);
72
+ }
73
+ function decodeBase64InGuest(text) {
74
+ const table = digitTable();
23
75
  const padding = text.endsWith("==") ? 2 : text.endsWith("=") ? 1 : 0;
24
- const bytes = new Uint8Array((text.length / 4) * 3 - padding);
76
+ const groups = text.length / 4;
77
+ // One spare byte: each group is written as a 32-bit word whose last byte the next group overwrites.
78
+ const buffer = new Uint8Array(groups * 3 + 1);
79
+ const view = new DataView(buffer.buffer);
80
+ let index = 0;
25
81
  let position = 0;
26
- for (let index = 0; index < text.length; index += 4) {
27
- const value = (digit(text, index) << 18) | (digit(text, index + 1) << 12)
28
- | (digit(text, index + 2) << 6) | digit(text, index + 3);
29
- if (position < bytes.length)
30
- bytes[position++] = (value >>> 16) & 255;
31
- if (position < bytes.length)
32
- bytes[position++] = (value >>> 8) & 255;
33
- if (position < bytes.length)
34
- bytes[position++] = value & 255;
82
+ for (; index + 32 <= text.length; index += 32, position += 24) {
83
+ view.setUint32(position, (table[text.charCodeAt(index)] << 26) | (table[text.charCodeAt(index + 1)] << 20)
84
+ | (table[text.charCodeAt(index + 2)] << 14) | (table[text.charCodeAt(index + 3)] << 8)),
85
+ view.setUint32(position + 3, (table[text.charCodeAt(index + 4)] << 26) | (table[text.charCodeAt(index + 5)] << 20)
86
+ | (table[text.charCodeAt(index + 6)] << 14) | (table[text.charCodeAt(index + 7)] << 8)),
87
+ view.setUint32(position + 6, (table[text.charCodeAt(index + 8)] << 26) | (table[text.charCodeAt(index + 9)] << 20)
88
+ | (table[text.charCodeAt(index + 10)] << 14) | (table[text.charCodeAt(index + 11)] << 8)),
89
+ view.setUint32(position + 9, (table[text.charCodeAt(index + 12)] << 26) | (table[text.charCodeAt(index + 13)] << 20)
90
+ | (table[text.charCodeAt(index + 14)] << 14) | (table[text.charCodeAt(index + 15)] << 8)),
91
+ view.setUint32(position + 12, (table[text.charCodeAt(index + 16)] << 26) | (table[text.charCodeAt(index + 17)] << 20)
92
+ | (table[text.charCodeAt(index + 18)] << 14) | (table[text.charCodeAt(index + 19)] << 8)),
93
+ view.setUint32(position + 15, (table[text.charCodeAt(index + 20)] << 26) | (table[text.charCodeAt(index + 21)] << 20)
94
+ | (table[text.charCodeAt(index + 22)] << 14) | (table[text.charCodeAt(index + 23)] << 8)),
95
+ view.setUint32(position + 18, (table[text.charCodeAt(index + 24)] << 26) | (table[text.charCodeAt(index + 25)] << 20)
96
+ | (table[text.charCodeAt(index + 26)] << 14) | (table[text.charCodeAt(index + 27)] << 8)),
97
+ view.setUint32(position + 21, (table[text.charCodeAt(index + 28)] << 26) | (table[text.charCodeAt(index + 29)] << 20)
98
+ | (table[text.charCodeAt(index + 30)] << 14) | (table[text.charCodeAt(index + 31)] << 8));
35
99
  }
36
- return bytes;
37
- }
38
- function digit(text, index) {
39
- const character = text.charAt(index);
40
- return character === "=" ? 0 : ALPHABET.indexOf(character);
100
+ for (; index < text.length; index += 4, position += 3) {
101
+ view.setUint32(position, (table[text.charCodeAt(index)] << 26) | (table[text.charCodeAt(index + 1)] << 20)
102
+ | (table[text.charCodeAt(index + 2)] << 14) | (table[text.charCodeAt(index + 3)] << 8));
103
+ }
104
+ return buffer.slice(0, groups * 3 - padding);
41
105
  }
@@ -1,13 +1,40 @@
1
- import { CogoverApiError, NotFoundError, PermissionDeniedError, RateLimitError, StateConflictError, LockLostError, ValidationError, } from "../errors.js";
1
+ import { CogoverApiError, NotFoundError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockLostError, ValidationError, } from "../errors.js";
2
+ import { utf8ByteLength } from "./utf8.js";
2
3
  import { errorMessage, isRecord } from "./values.js";
3
- export async function callBridge(operation, payload) {
4
+ /**
5
+ * Largest capability request, envelope included, that Cogover accepts. A larger one would end the whole execution
6
+ * with a platform failure that a script cannot catch, so it is refused here as a ValidationError instead.
7
+ */
8
+ export const MAX_BRIDGE_REQUEST_BYTES = 256 * 1024;
9
+ /** Bytes of the request envelope around an empty operation name and an empty payload. */
10
+ const ENVELOPE_BYTES = JSON.stringify({ version: 1, operation: "", payload: {} }).length;
11
+ /**
12
+ * Sends one capability request. `minimumPayloadBytes`, when given, must not exceed the UTF-8 size of the
13
+ * JSON-encoded payload: a request that cannot fit is then refused before it is serialized, so values that encode
14
+ * themselves while serializing (large bytes as base64) cost no CPU time or statements from the invocation's limits.
15
+ */
16
+ export async function callBridge(operation, payload, minimumPayloadBytes = 0) {
4
17
  const bridge = globalThis.__cogoverBridgeCall;
5
18
  if (typeof bridge !== "function") {
6
19
  throw new CogoverApiError("CAPABILITY_UNAVAILABLE", "Cogover data capabilities are only available inside the Cogover runtime");
7
20
  }
21
+ if (ENVELOPE_BYTES + operation.length + minimumPayloadBytes > MAX_BRIDGE_REQUEST_BYTES) {
22
+ throw requestTooLarge(operation);
23
+ }
24
+ let requestJson;
25
+ try {
26
+ requestJson = JSON.stringify({ version: 1, operation, payload });
27
+ }
28
+ catch (error) {
29
+ throw new CogoverApiError("BRIDGE_ERROR", errorMessage(error));
30
+ }
31
+ // A UTF-16 code unit never takes more than three UTF-8 bytes, so a short request needs no count.
32
+ if (requestJson.length * 3 > MAX_BRIDGE_REQUEST_BYTES && utf8ByteLength(requestJson) > MAX_BRIDGE_REQUEST_BYTES) {
33
+ throw requestTooLarge(operation);
34
+ }
8
35
  let responseJson;
9
36
  try {
10
- responseJson = await bridge(JSON.stringify({ version: 1, operation, payload }));
37
+ responseJson = await bridge(requestJson);
11
38
  }
12
39
  catch (error) {
13
40
  throw new CogoverApiError("BRIDGE_ERROR", errorMessage(error));
@@ -24,6 +51,15 @@ export async function callBridge(operation, payload) {
24
51
  }
25
52
  throw publicError(response.error);
26
53
  }
54
+ /** The same error Cogover reports for a request it refuses before dispatch. */
55
+ function requestTooLarge(operation) {
56
+ return publicError({
57
+ code: operation === "http.fetch" ? "FETCH_REQUEST_TOO_LARGE" : "VALIDATION_ERROR",
58
+ message: `The ${operation} request must not exceed ${MAX_BRIDGE_REQUEST_BYTES} bytes once JSON-encoded; `
59
+ + "send less data in one call",
60
+ details: { limit: MAX_BRIDGE_REQUEST_BYTES },
61
+ });
62
+ }
27
63
  function publicError(error) {
28
64
  switch (error.code) {
29
65
  case "NOT_FOUND": {
@@ -38,6 +74,8 @@ function publicError(error) {
38
74
  return new PermissionDeniedError(error.message, error.details);
39
75
  case "RATE_LIMITED":
40
76
  return new RateLimitError(error.message, error.details);
77
+ case "RETRYABLE":
78
+ return new RetryableError(error.message, error.details);
41
79
  case "STATE_CONFLICT":
42
80
  return new StateConflictError(error.message, error.details);
43
81
  case "LOCK_LOST":
@@ -12,6 +12,8 @@ const MIN_ATTEMPTS = 1;
12
12
  const MAX_ATTEMPTS = 10;
13
13
  const DEFAULT_ATTEMPTS = 5;
14
14
  const MAX_TIMEZONE_LENGTH = 64;
15
+ // Cogover refuses a longer expression when the version is published.
16
+ const MAX_CRON_LENGTH = 128;
15
17
  const DEFAULT_TIMEZONE = "UTC";
16
18
  // The shape of an IANA zone ID; Cogover checks that the zone exists when the version is published.
17
19
  const TIMEZONE = /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)*$/;
@@ -93,8 +95,12 @@ function normalizeCron(expression, fail) {
93
95
  if (fields.length !== 5) {
94
96
  throw fail("schedule", `schedule.cron must contain exactly five fields, found ${fields.length}`);
95
97
  }
98
+ const normalized = fields.join(" ");
99
+ if (normalized.length > MAX_CRON_LENGTH) {
100
+ throw fail("schedule", `schedule.cron must be a non-empty string of at most ${MAX_CRON_LENGTH} characters`);
101
+ }
96
102
  fields.forEach((field, index) => validateCronField(field, CRON_FIELDS[index], fail));
97
- return fields.join(" ");
103
+ return normalized;
98
104
  }
99
105
  function validateCronField(field, spec, fail) {
100
106
  const unsupported = (item) => fail("schedule", `schedule.cron ${spec.name} field contains the unsupported value '${item}'; `
@@ -1,55 +1,20 @@
1
- /** Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. */
1
+ const NON_ASCII = /[^\u0000-\u007f]/;
2
+ const TWO_BYTE_UNITS = /[\u0080-\u07ff]/g;
3
+ const THREE_BYTE_UNITS = /[\u0800-\ud7ff\ue000-\uffff]/g;
4
+ const SURROGATE_UNITS = /[\ud800-\udfff]/g;
5
+ const SURROGATE_PAIRS = /[\ud800-\udbff][\udc00-\udfff]/g;
6
+ /**
7
+ * Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. Native regular
8
+ * expressions count the code units, so the cost in the sandbox statement budget does not grow with the length.
9
+ */
2
10
  export function utf8ByteLength(value) {
3
- let bytes = 0;
4
- for (let index = 0; index < value.length; index++) {
5
- const code = value.charCodeAt(index);
6
- if (code < 0x80)
7
- bytes++;
8
- else if (code < 0x800)
9
- bytes += 2;
10
- else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length
11
- && value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) {
12
- bytes += 4;
13
- index++;
14
- }
15
- else
16
- bytes += 3;
17
- }
18
- return bytes;
19
- }
20
- /** UTF-8 encoding without TextEncoder, which the sandbox does not provide; a lone surrogate becomes U+FFFD. */
21
- export function encodeUtf8(value) {
22
- const bytes = new Uint8Array(utf8ByteLength(value));
23
- let position = 0;
24
- for (let index = 0; index < value.length; index++) {
25
- let code = value.charCodeAt(index);
26
- if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
27
- const low = value.charCodeAt(index + 1);
28
- if (low >= 0xdc00 && low <= 0xdfff) {
29
- code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00);
30
- index++;
31
- }
32
- }
33
- if (code >= 0xd800 && code <= 0xdfff)
34
- code = 0xfffd;
35
- if (code < 0x80) {
36
- bytes[position++] = code;
37
- }
38
- else if (code < 0x800) {
39
- bytes[position++] = 0xc0 | (code >> 6);
40
- bytes[position++] = 0x80 | (code & 63);
41
- }
42
- else if (code < 0x10000) {
43
- bytes[position++] = 0xe0 | (code >> 12);
44
- bytes[position++] = 0x80 | ((code >> 6) & 63);
45
- bytes[position++] = 0x80 | (code & 63);
46
- }
47
- else {
48
- bytes[position++] = 0xf0 | (code >> 18);
49
- bytes[position++] = 0x80 | ((code >> 12) & 63);
50
- bytes[position++] = 0x80 | ((code >> 6) & 63);
51
- bytes[position++] = 0x80 | (code & 63);
52
- }
53
- }
54
- return bytes;
11
+ if (!NON_ASCII.test(value))
12
+ return value.length;
13
+ const matchedUnits = (pattern) => value.length - value.replace(pattern, "").length;
14
+ const surrogateUnits = matchedUnits(SURROGATE_UNITS);
15
+ const pairedUnits = surrogateUnits === 0 ? 0 : matchedUnits(SURROGATE_PAIRS);
16
+ // Every unit counts one byte, plus one for U+0080-U+07FF, two for the rest of the BMP, one for each unit of
17
+ // a surrogate pair (four bytes a pair) and two for a lone surrogate (encoded as U+FFFD).
18
+ return value.length + matchedUnits(TWO_BYTE_UNITS) + 2 * matchedUnits(THREE_BYTE_UNITS)
19
+ + pairedUnits + 2 * (surrogateUnits - pairedUnits);
55
20
  }
package/dist/locks.js CHANGED
@@ -30,12 +30,22 @@ export function createLocksApi() {
30
30
  const acquired = await api.acquire(key, options);
31
31
  if (acquired === null)
32
32
  throw new LockUnavailableError(key);
33
+ let result;
33
34
  try {
34
- return await callback(acquired);
35
+ result = await callback(acquired);
35
36
  }
36
- finally {
37
- await acquired.release();
37
+ catch (error) {
38
+ try {
39
+ await acquired.release();
40
+ }
41
+ catch {
42
+ // The callback's error is the one the caller must see; an unreleased lease expires on its own.
43
+ }
44
+ throw error;
38
45
  }
46
+ // After a successful callback a failed release (for example LockLostError) is reported.
47
+ await acquired.release();
48
+ return result;
39
49
  },
40
50
  };
41
51
  return Object.freeze(api);
package/dist/logger.js CHANGED
@@ -1,9 +1,55 @@
1
+ // Longest details text written for one log line; the rest is cut and marked.
2
+ const MAX_DETAILS_CHARS = 8192;
1
3
  function writeLog(level, message, details) {
2
4
  if (details === undefined) {
3
5
  console.log(`[${level}] ${message}`);
4
6
  return;
5
7
  }
6
- console.log(`[${level}] ${message}`, details);
8
+ // One preformatted string: the sandbox console does not format a second argument ("[object Object]").
9
+ console.log(`[${level}] ${message} ${formatDetails(details)}`);
10
+ }
11
+ /** JSON text of a details value that never throws, whatever the value contains. */
12
+ function formatDetails(details) {
13
+ let text;
14
+ try {
15
+ text = JSON.stringify(details, safeReplacer());
16
+ }
17
+ catch {
18
+ // A hostile toJSON() or getter must not turn a log call into a failure.
19
+ text = undefined;
20
+ }
21
+ if (text === undefined)
22
+ text = "[unserializable]";
23
+ return text.length > MAX_DETAILS_CHARS ? `${text.slice(0, MAX_DETAILS_CHARS)}…[truncated]` : text;
24
+ }
25
+ /** Replaces cycles, BigInt, errors, maps and sets, which JSON.stringify would reject or print as {}. */
26
+ function safeReplacer() {
27
+ // Objects on the path from the root to the value being written; a value found on it is a cycle.
28
+ const ancestors = [];
29
+ return function replacer(_key, value) {
30
+ if (ancestors.length > 0) {
31
+ const holder = ancestors.indexOf(this);
32
+ if (holder >= 0)
33
+ ancestors.length = holder + 1;
34
+ else
35
+ ancestors.push(this);
36
+ }
37
+ if (typeof value === "bigint")
38
+ return value.toString();
39
+ if (typeof value !== "object" || value === null)
40
+ return value;
41
+ if (ancestors.includes(value))
42
+ return "[Circular]";
43
+ if (ancestors.length === 0)
44
+ ancestors.push(value);
45
+ if (value instanceof Error)
46
+ return { name: value.name, message: value.message };
47
+ if (value instanceof Map)
48
+ return Object.fromEntries(value);
49
+ if (value instanceof Set)
50
+ return [...value];
51
+ return value;
52
+ };
7
53
  }
8
54
  /** @internal */
9
55
  export const SCRIPT_LOGGER = Object.freeze({
package/dist/org.js CHANGED
@@ -81,12 +81,12 @@ export function createOrgApi(invocation) {
81
81
  includeSubDepartments: "boolean", accountOnly: "boolean", limit: "limit", cursor: "cursor",
82
82
  };
83
83
  const personnel = {
84
- get(id, options) {
84
+ async get(id, options) {
85
85
  return nullableObject("org.personnel.get", {
86
86
  ...payloadFor("personnel.get()", options, {}, true), id: requireId(id, "personnel id"),
87
87
  });
88
88
  },
89
- getMany(ids, options) {
89
+ async getMany(ids, options) {
90
90
  if (!Array.isArray(ids))
91
91
  throw new ValidationError("personnel.getMany() requires an array of ids");
92
92
  const unique = [...new Set(ids.map(id => requireId(id, "personnel id")))];
@@ -97,7 +97,7 @@ export function createOrgApi(invocation) {
97
97
  ...payloadFor("personnel.getMany()", options, {}, true), ids: unique,
98
98
  });
99
99
  },
100
- managerChain(id, options) {
100
+ async managerChain(id, options) {
101
101
  return list("org.personnel.managerChain", {
102
102
  ...payloadFor("personnel.managerChain()", options, { departmentId: "id", accountOnly: "boolean" }, true),
103
103
  id: requireId(id, "personnel id"),
@@ -105,32 +105,32 @@ export function createOrgApi(invocation) {
105
105
  },
106
106
  };
107
107
  const departments = {
108
- get(id, options) {
108
+ async get(id, options) {
109
109
  return nullableObject("org.departments.get", {
110
110
  ...payloadFor("departments.get()", options, {}, true), id: requireId(id, "department id"),
111
111
  });
112
112
  },
113
- tree(options) {
113
+ async tree(options) {
114
114
  return list("org.departments.tree", payloadFor("departments.tree()", options, { rootId: "id", depth: "depth" }, true));
115
115
  },
116
- ancestors(id, options) {
116
+ async ancestors(id, options) {
117
117
  return list("org.departments.ancestors", {
118
118
  ...payloadFor("departments.ancestors()", options, {}, true), id: requireId(id, "department id"),
119
119
  });
120
120
  },
121
- members(id, options) {
121
+ async members(id, options) {
122
122
  return object("org.departments.members", {
123
123
  ...payloadFor("departments.members()", options, { ...pageOptions, positionId: "id" }, true),
124
124
  id: requireId(id, "department id"),
125
125
  });
126
126
  },
127
- managers(id, options) {
127
+ async managers(id, options) {
128
128
  return list("org.departments.managers", {
129
129
  ...payloadFor("departments.managers()", options, { accountOnly: "boolean" }, true),
130
130
  id: requireId(id, "department id"),
131
131
  });
132
132
  },
133
- managerChain(id, options) {
133
+ async managerChain(id, options) {
134
134
  return object("org.departments.managerChain", {
135
135
  ...payloadFor("departments.managerChain()", options, { accountOnly: "boolean" }, true),
136
136
  id: requireId(id, "department id"),
@@ -138,15 +138,15 @@ export function createOrgApi(invocation) {
138
138
  },
139
139
  };
140
140
  const positions = {
141
- list(options) {
141
+ async list(options) {
142
142
  return list("org.positions.list", payloadFor("positions.list()", options, {}, true));
143
143
  },
144
- get(id, options) {
144
+ async get(id, options) {
145
145
  return nullableObject("org.positions.get", {
146
146
  ...payloadFor("positions.get()", options, {}, true), id: requireId(id, "position id"),
147
147
  });
148
148
  },
149
- members(id, options) {
149
+ async members(id, options) {
150
150
  return object("org.positions.members", {
151
151
  ...payloadFor("positions.members()", options, { ...pageOptions, departmentId: "id" }, true),
152
152
  id: requireId(id, "position id"),
@@ -166,14 +166,14 @@ export function createOrgApi(invocation) {
166
166
  return null;
167
167
  return personnel.get(personnelId, options);
168
168
  },
169
- isInDepartment(personnelId, departmentId, options) {
169
+ async isInDepartment(personnelId, departmentId, options) {
170
170
  return flag("org.isInDepartment", {
171
171
  ...payloadFor("isInDepartment()", options, { includeSubDepartments: "boolean" }, false),
172
172
  personnelId: requireId(personnelId, "personnel id"),
173
173
  departmentId: requireId(departmentId, "department id"),
174
174
  });
175
175
  },
176
- isManagerOf(managerId, personnelId, options) {
176
+ async isManagerOf(managerId, personnelId, options) {
177
177
  return flag("org.isManagerOf", {
178
178
  ...payloadFor("isManagerOf()", options, { departmentId: "id", directOnly: "boolean" }, false),
179
179
  managerId: requireId(managerId, "manager id"),
package/dist/records.d.ts CHANGED
@@ -42,6 +42,15 @@ export interface GetManyResult<TFields> {
42
42
  export interface DeleteResult {
43
43
  readonly deleted: CogoverRecordId[];
44
44
  readonly notDeleted: CogoverRecordId[];
45
+ /**
46
+ * Present only when a before-change record trigger kept some of the records from being deleted: record ID to
47
+ * the trigger's error codes by field slug (`$record` for the whole record) and its texts.
48
+ */
49
+ readonly recordErrors?: Readonly<Record<CogoverRecordId, {
50
+ readonly reason: "TRIGGER_REJECTED";
51
+ readonly fieldErrors?: Readonly<Record<string, string>>;
52
+ readonly messages?: readonly string[];
53
+ }>>;
45
54
  }
46
55
  export interface BatchWriteRowResult {
47
56
  readonly referenceId: string;
@@ -49,6 +58,10 @@ export interface BatchWriteRowResult {
49
58
  readonly r: number;
50
59
  readonly msg?: string;
51
60
  readonly success: boolean;
61
+ /** Row a before-change record trigger rejected (`r` 70): error code by field slug, `$record` for the whole record. */
62
+ readonly fieldErrors?: Readonly<Record<string, string>>;
63
+ /** Row a before-change record trigger rejected (`r` 70): the texts the trigger attached to its error codes. */
64
+ readonly messages?: readonly string[];
52
65
  }
53
66
  /** Batch writes are best-effort per row; inspect `success` or every row result. */
54
67
  export interface BatchWriteResponse {
package/dist/response.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import { ValidationError } from "./errors.js";
2
2
  import { encodeBase64 } from "./internal/base64.js";
3
3
  const RESPONSE_KEY = "__cogoverHttpResponse";
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4
5
  const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
5
6
  const DENIED_HEADERS = new Set([
6
7
  "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "trailer",
7
8
  "set-cookie", "server", "date", "proxy-authenticate",
8
9
  ]);
10
+ // Only objects made by these helpers are responses. A returned value that merely has the same JSON shape is data.
11
+ const envelopes = new WeakMap();
9
12
  /** @internal */
10
13
  export function createResponseApi() {
11
14
  return Object.freeze({
@@ -40,6 +43,9 @@ export function createResponseApi() {
40
43
  || /[\r\n]/.test(location)) {
41
44
  throw new ValidationError("response.redirect() location is invalid");
42
45
  }
46
+ if (!REDIRECT_STATUSES.has(status)) {
47
+ throw new ValidationError("response.redirect() status must be 301, 302, 303, 307 or 308");
48
+ }
43
49
  return response("empty", null, { status, headers: { location } });
44
50
  },
45
51
  });
@@ -54,9 +60,23 @@ function response(bodyType, body, init, defaultContentType) {
54
60
  bodyType,
55
61
  body,
56
62
  });
57
- return Object.freeze({
63
+ const scriptResponse = Object.freeze({
58
64
  toJSON: () => Object.freeze({ [RESPONSE_KEY]: envelope }),
59
65
  });
66
+ envelopes.set(scriptResponse, envelope);
67
+ return scriptResponse;
68
+ }
69
+ /**
70
+ * @internal JSON text of a handler result. Cogover passes each invocation a token that only a response made by
71
+ * these helpers carries, so a returned value can never choose the status, headers or body type by imitating the
72
+ * envelope. Without a token (outside Cogover) a response serializes to the bare envelope.
73
+ */
74
+ export function serializeHandlerOutput(output, responseToken) {
75
+ const envelope = typeof output === "object" && output !== null ? envelopes.get(output) : undefined;
76
+ if (envelope !== undefined && typeof responseToken === "string" && responseToken.length > 0) {
77
+ return JSON.stringify({ [RESPONSE_KEY]: { ...envelope, token: responseToken } });
78
+ }
79
+ return JSON.stringify(output);
60
80
  }
61
81
  function validateStatus(status) {
62
82
  if (!Number.isInteger(status) || status < 200 || status > 599) {
package/dist/schema.d.ts CHANGED
@@ -12,6 +12,7 @@ export interface ObjectMetadata {
12
12
  readonly multiple: boolean;
13
13
  readonly readOnly: boolean;
14
14
  readonly manualModifyAllow?: boolean;
15
+ readonly creatable?: boolean;
15
16
  readonly metaData?: Readonly<Record<string, unknown>>;
16
17
  readonly options?: readonly {
17
18
  readonly id: string;
package/dist/script.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createDataApi } from "./data.js";
2
2
  import { NotFoundError, ValidationError } from "./errors.js";
3
3
  import { scriptRequest } from "./internal/request.js";
4
- import { createResponseApi } from "./response.js";
4
+ import { createResponseApi, serializeHandlerOutput } from "./response.js";
5
5
  import { errorMessage } from "./internal/values.js";
6
6
  import { SCRIPT_LOGGER } from "./logger.js";
7
7
  import { createSchemaApi } from "./schema.js";
@@ -16,6 +16,7 @@ import { createJobsApi } from "./internal/jobs-api.js";
16
16
  import { createSecretsApi } from "./secrets.js";
17
17
  import { crypto } from "./crypto.js";
18
18
  import { createOrgApi } from "./org.js";
19
+ const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
19
20
  export function defineScript(handler) {
20
21
  if (typeof handler !== "function") {
21
22
  throw new ValidationError("defineScript() requires a handler function");
@@ -28,7 +29,7 @@ export function defineScript(handler) {
28
29
  }
29
30
  /** @internal */
30
31
  export function createSandboxHandler(handler) {
31
- return async (inputJson) => {
32
+ const sandboxHandler = async (inputJson, responseToken) => {
32
33
  installCogoverFetch();
33
34
  let input;
34
35
  try {
@@ -61,10 +62,13 @@ export function createSandboxHandler(handler) {
61
62
  if (output === null) {
62
63
  return null;
63
64
  }
64
- const outputJson = JSON.stringify(output);
65
+ const outputJson = serializeHandlerOutput(output, responseToken);
65
66
  if (outputJson === undefined) {
66
67
  throw new ValidationError("Script output must be JSON serializable");
67
68
  }
68
69
  return outputJson;
69
70
  };
71
+ // Tells Cogover that this handler accepts a per-invocation response token as its second argument.
72
+ Object.defineProperty(sandboxHandler, RESPONSE_TOKEN_VERSION_MEMBER, { value: 1 });
73
+ return sandboxHandler;
70
74
  }