@cogover/sdk 0.1.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +250 -24
  2. package/dist/data.d.ts +44 -0
  3. package/dist/data.js +143 -0
  4. package/dist/errors.d.ts +30 -0
  5. package/dist/errors.js +62 -0
  6. package/dist/fetch.d.ts +28 -0
  7. package/dist/fetch.js +96 -0
  8. package/dist/index.d.ts +21 -3
  9. package/dist/index.js +7 -5
  10. package/dist/internal/bridge.js +48 -0
  11. package/dist/internal/invocation.js +57 -0
  12. package/dist/internal/request.js +87 -0
  13. package/dist/internal/validation.js +28 -0
  14. package/dist/internal/values.js +6 -0
  15. package/dist/invocation.d.ts +40 -0
  16. package/dist/invocation.js +1 -0
  17. package/dist/legacy.d.ts +2 -0
  18. package/dist/legacy.js +4 -0
  19. package/dist/locks.d.ts +19 -0
  20. package/dist/locks.js +68 -0
  21. package/dist/logger.d.ts +6 -0
  22. package/dist/logger.js +14 -0
  23. package/dist/query.d.ts +52 -0
  24. package/dist/query.js +59 -0
  25. package/dist/records.d.ts +74 -0
  26. package/dist/records.js +1 -0
  27. package/dist/request.d.ts +18 -0
  28. package/dist/request.js +1 -0
  29. package/dist/response.d.ts +21 -0
  30. package/dist/response.js +108 -0
  31. package/dist/router.d.ts +13 -0
  32. package/dist/router.js +104 -0
  33. package/dist/schema.d.ts +26 -0
  34. package/dist/schema.js +11 -0
  35. package/dist/script.d.ts +23 -0
  36. package/dist/script.js +56 -0
  37. package/dist/state.d.ts +24 -0
  38. package/dist/state.js +91 -0
  39. package/dist/workspace.d.ts +8 -0
  40. package/dist/workspace.js +1 -0
  41. package/docs/en/api-reference.md +948 -0
  42. package/docs/en/usage-guide.md +284 -0
  43. package/package.json +17 -5
  44. package/scripts/generate-workspace-types.mjs +135 -0
  45. package/dist/index.d.ts.map +0 -1
  46. package/dist/index.js.map +0 -1
package/dist/fetch.js ADDED
@@ -0,0 +1,96 @@
1
+ import { ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
4
+ const OPTION_KEYS = new Set(["method", "headers", "body", "timeoutMs"]);
5
+ /** Fetch-compatible API using Cogover's managed network layer. */
6
+ export async function fetch(input, init) {
7
+ if (typeof input !== "string" || input.length === 0) {
8
+ throw new ValidationError("fetch() URL must be a non-empty string");
9
+ }
10
+ if (init !== undefined && (init === null || typeof init !== "object" || Array.isArray(init))) {
11
+ throw new ValidationError("fetch() options must be an object");
12
+ }
13
+ if (init !== undefined && Object.keys(init).some(key => !OPTION_KEYS.has(key))) {
14
+ throw new ValidationError("Unsupported fetch() option");
15
+ }
16
+ if (init?.method !== undefined && typeof init.method !== "string") {
17
+ throw new ValidationError("fetch() method must be a string");
18
+ }
19
+ const method = (init?.method ?? "GET").toUpperCase();
20
+ if (!METHODS.has(method))
21
+ throw new ValidationError(`Unsupported fetch method: ${method}`);
22
+ if (init?.body !== undefined && typeof init.body !== "string") {
23
+ throw new ValidationError("fetch() body must be a string");
24
+ }
25
+ if (init?.timeoutMs !== undefined
26
+ && (!Number.isInteger(init.timeoutMs) || init.timeoutMs <= 0)) {
27
+ throw new ValidationError("fetch() timeoutMs must be a positive integer");
28
+ }
29
+ if (init?.headers !== undefined
30
+ && (init.headers === null || typeof init.headers !== "object" || Array.isArray(init.headers))) {
31
+ throw new ValidationError("fetch() headers must be an object");
32
+ }
33
+ const payload = { url: input, method };
34
+ if (init?.headers !== undefined)
35
+ payload.headers = init.headers;
36
+ if (init?.body !== undefined)
37
+ payload.body = init.body;
38
+ if (init?.timeoutMs !== undefined)
39
+ payload.timeoutMs = init.timeoutMs;
40
+ const response = await callBridge("http.fetch", payload);
41
+ return createFetchResponse(response);
42
+ }
43
+ /** @internal */
44
+ export function installCogoverFetch() {
45
+ const globals = globalThis;
46
+ if (typeof globals.fetch !== "function") {
47
+ Object.defineProperty(globals, "fetch", {
48
+ value: fetch,
49
+ writable: false,
50
+ configurable: false,
51
+ enumerable: false,
52
+ });
53
+ }
54
+ }
55
+ function createFetchResponse(source) {
56
+ let used = false;
57
+ const consume = () => {
58
+ if (used)
59
+ throw new TypeError("Response body has already been consumed");
60
+ used = true;
61
+ return source.body;
62
+ };
63
+ const headers = createHeaders(source.headers);
64
+ const response = {
65
+ ok: source.status >= 200 && source.status <= 299,
66
+ status: source.status,
67
+ statusText: source.statusText,
68
+ url: source.url,
69
+ redirected: false,
70
+ headers,
71
+ get bodyUsed() { return used; },
72
+ async text() { return consume(); },
73
+ async json() { return JSON.parse(consume()); },
74
+ };
75
+ return Object.freeze(response);
76
+ }
77
+ function createHeaders(source) {
78
+ const values = new Map();
79
+ for (const [name, entries] of Object.entries(source)) {
80
+ values.set(name.toLowerCase(), entries.join(", "));
81
+ }
82
+ return Object.freeze({
83
+ get(name) {
84
+ return values.get(name.toLowerCase()) ?? null;
85
+ },
86
+ has(name) {
87
+ return values.has(name.toLowerCase());
88
+ },
89
+ entries() {
90
+ return values.entries();
91
+ },
92
+ [Symbol.iterator]() {
93
+ return values.entries();
94
+ },
95
+ });
96
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,21 @@
1
- /** Creates the standard greeting used by the SDK examples. */
2
- export declare function createGreeting(name: string): string;
3
- //# sourceMappingURL=index.d.ts.map
1
+ /** Public TypeScript API for Cogover projects. */
2
+ export type { WorkspaceObjects } from "./workspace.js";
3
+ export type { CogoverRecordId, RecordReference, UrlValue, FileValue, CogoverRecord, RecordPage, DeleteResult, BatchWriteRowResult, BatchWriteResponse, BatchUpdateItem, UpsertFields, UpsertResult, CreateFields, UpdateFields, } from "./records.js";
4
+ export { and, or } from "./query.js";
5
+ export type { FilterOperator, FilterCondition, FilterGroup, FilterExpression, SortExpression, FieldReference, FieldReferences, } from "./query.js";
6
+ export type { GetRecordOptions, ListOptions, RecordsApi, RecordWritesApi, WriteObjectClient, AsUserDataApi, ObjectClient, DataApi, } from "./data.js";
7
+ export type { ObjectMetadata, SchemaApi } from "./schema.js";
8
+ export type { ScriptLogger } from "./logger.js";
9
+ export { defineScript } from "./script.js";
10
+ export type { ScriptContext, ScriptHandler, SandboxHandler } from "./script.js";
11
+ export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InvocationContext, } from "./invocation.js";
12
+ export { createRouter } from "./router.js";
13
+ export type { ScriptRouter } from "./router.js";
14
+ export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
15
+ export type { ResponseApi, ResponseInit, BinaryResponseInit, ResponseHeaderValue, ScriptResponse, } from "./response.js";
16
+ export type { ProjectState, StateNamespace, StateEntry, StateWriteOptions, StateDeleteOptions, } from "./state.js";
17
+ export type { DistributedLocks, LockLease, LockOptions, } from "./locks.js";
18
+ export { fetch } from "./fetch.js";
19
+ export type { CogoverFetchInit, CogoverFetchHeaders, CogoverFetchResponse, } from "./fetch.js";
20
+ export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
21
+ export { createGreeting } from "./legacy.js";
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- /** Creates the standard greeting used by the SDK examples. */
2
- export function createGreeting(name) {
3
- return `Hello ${name}`;
4
- }
5
- //# sourceMappingURL=index.js.map
1
+ /** Public TypeScript API for Cogover projects. */
2
+ export { and, or } from "./query.js";
3
+ export { defineScript } from "./script.js";
4
+ export { createRouter } from "./router.js";
5
+ export { fetch } from "./fetch.js";
6
+ export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
7
+ export { createGreeting } from "./legacy.js";
@@ -0,0 +1,48 @@
1
+ import { CogoverApiError, NotFoundError, PermissionDeniedError, RateLimitError, StateConflictError, LockLostError, ValidationError, } from "../errors.js";
2
+ import { errorMessage, isRecord } from "./values.js";
3
+ export async function callBridge(operation, payload) {
4
+ const bridge = globalThis.__cogoverBridgeCall;
5
+ if (typeof bridge !== "function") {
6
+ throw new CogoverApiError("CAPABILITY_UNAVAILABLE", "Cogover data capabilities are only available inside the Cogover runtime");
7
+ }
8
+ let responseJson;
9
+ try {
10
+ responseJson = await bridge(JSON.stringify({ version: 1, operation, payload }));
11
+ }
12
+ catch (error) {
13
+ throw new CogoverApiError("BRIDGE_ERROR", errorMessage(error));
14
+ }
15
+ let response;
16
+ try {
17
+ response = JSON.parse(responseJson);
18
+ }
19
+ catch (error) {
20
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", errorMessage(error));
21
+ }
22
+ if (response.ok) {
23
+ return response.data;
24
+ }
25
+ throw publicError(response.error);
26
+ }
27
+ function publicError(error) {
28
+ switch (error.code) {
29
+ case "NOT_FOUND": {
30
+ const details = isRecord(error.details) ? error.details : {};
31
+ const resource = typeof details.resource === "string" ? details.resource : "record";
32
+ const resourceId = typeof details.resourceId === "string" ? details.resourceId : "unknown";
33
+ return new NotFoundError(resource, resourceId, error.message, error.details);
34
+ }
35
+ case "VALIDATION_ERROR":
36
+ return new ValidationError(error.message, error.details);
37
+ case "PERMISSION_DENIED":
38
+ return new PermissionDeniedError(error.message, error.details);
39
+ case "RATE_LIMITED":
40
+ return new RateLimitError(error.message, error.details);
41
+ case "STATE_CONFLICT":
42
+ return new StateConflictError(error.message, error.details);
43
+ case "LOCK_LOST":
44
+ return new LockLostError(error.message, error.details);
45
+ default:
46
+ return new CogoverApiError(error.code, error.message, error.details);
47
+ }
48
+ }
@@ -0,0 +1,57 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { isRecord } from "./values.js";
3
+ export function invocationContext(input) {
4
+ const context = isRecord(input) && isRecord(input.__context) ? input.__context : undefined;
5
+ if (!context)
6
+ throw new ValidationError("Invocation metadata is unavailable outside Cogover Runtime");
7
+ const workspace = workspaceSnapshot(context);
8
+ if (context.executionIdentity === "system") {
9
+ return Object.freeze({ identity: "system", workspace, user: null });
10
+ }
11
+ if (context.executionIdentity !== "user" || !isRecord(context.user)) {
12
+ throw new ValidationError("Invalid invocation identity metadata");
13
+ }
14
+ return Object.freeze({ identity: "user", workspace, user: userSnapshot(context.user) });
15
+ }
16
+ function workspaceSnapshot(context) {
17
+ const raw = isRecord(context.workspace) ? context.workspace : {};
18
+ const id = requiredString(raw.id ?? context.workspaceId, "workspace id");
19
+ return Object.freeze({
20
+ id,
21
+ ...optionalStringFields(raw, [
22
+ "name", "domain", "language", "timezone", "dateFormat", "timeFormat", "numberFormat",
23
+ ]),
24
+ });
25
+ }
26
+ function userSnapshot(raw) {
27
+ const membershipRaw = isRecord(raw.membership) ? raw.membership : {};
28
+ const membership = Object.freeze({
29
+ ...optionalStringFields(membershipRaw, ["personnelId", "language", "timezone"]),
30
+ ...(membershipRaw.personnelId === undefined && typeof raw.personnelId === "string" && raw.personnelId !== ""
31
+ ? { personnelId: raw.personnelId } : {}),
32
+ });
33
+ return Object.freeze({
34
+ accountId: requiredString(raw.accountId, "account id"),
35
+ ...optionalStringFields(raw, ["email", "firstName", "lastName", "avatar", "language", "timezone"]),
36
+ membership,
37
+ });
38
+ }
39
+ function requiredString(value, label) {
40
+ if (typeof value !== "string" || value === "") {
41
+ throw new ValidationError(`Invalid invocation ${label}`);
42
+ }
43
+ return value;
44
+ }
45
+ function optionalStringFields(source, names) {
46
+ const result = {};
47
+ for (const name of names) {
48
+ const value = source[name];
49
+ if (value === undefined)
50
+ continue;
51
+ if (typeof value !== "string")
52
+ throw new ValidationError(`Invalid invocation ${name}`);
53
+ if (value !== "")
54
+ result[name] = value;
55
+ }
56
+ return result;
57
+ }
@@ -0,0 +1,87 @@
1
+ import { CogoverApiError, ValidationError } from "../errors.js";
2
+ import { isRecord } from "./values.js";
3
+ export function validateRoutePath(path) {
4
+ if (typeof path !== "string" || path.length > 1024
5
+ || /^(?:\/|(?:\/(?:[A-Za-z0-9][A-Za-z0-9_-]{0,99}|:[A-Za-z][A-Za-z0-9_]{0,63}))+)$/.exec(path)?.[0] !== path) {
6
+ throw new ValidationError("Route must be '/' or contain static and ':parameter' segments");
7
+ }
8
+ const parameters = path.split("/").filter(segment => segment.startsWith(":"));
9
+ if (new Set(parameters).size !== parameters.length) {
10
+ throw new ValidationError("Route parameter names must be unique");
11
+ }
12
+ }
13
+ export function validateInvocationPath(path) {
14
+ if (typeof path !== "string" || path.length > 4096 || !path.startsWith("/")
15
+ || (path.length > 1 && path.endsWith("/")) || path.includes("?") || path.includes("#")
16
+ || path.includes("\\") || /[\u0000-\u001f\u007f]/.test(path)) {
17
+ throw new ValidationError("Invalid invocation route path");
18
+ }
19
+ if (path === "/")
20
+ return;
21
+ for (const segment of path.split("/").slice(1)) {
22
+ if (segment.length === 0 || segment.length > 1024 || segment === "." || segment === "..") {
23
+ throw new ValidationError("Invalid invocation route path");
24
+ }
25
+ }
26
+ }
27
+ export function scriptRequest(input) {
28
+ const context = isRecord(input) && isRecord(input.__context) ? input.__context : undefined;
29
+ const metadata = context?.request;
30
+ if (metadata !== undefined && (!isRecord(metadata)
31
+ || typeof metadata.method !== "string" || typeof metadata.path !== "string"
32
+ || (metadata.query !== undefined && !isRecord(metadata.query))
33
+ || (metadata.headers !== undefined && !isRecord(metadata.headers)))) {
34
+ throw new ValidationError("Invalid invocation request metadata");
35
+ }
36
+ // Direct SDK invocations without host metadata retain the original POST/root behavior.
37
+ const method = isRecord(metadata) ? metadata.method : "POST";
38
+ const path = isRecord(metadata) ? metadata.path : "/";
39
+ if (!isRequestMethod(method)) {
40
+ throw new CogoverApiError("METHOD_NOT_ALLOWED", `Unsupported HTTP method: ${method}`);
41
+ }
42
+ validateInvocationPath(path);
43
+ const query = freezeQuery(isRecord(metadata) ? metadata.query : undefined);
44
+ const headers = freezeHeaders(isRecord(metadata) ? metadata.headers : undefined);
45
+ let body = input;
46
+ if (isRecord(input)) {
47
+ const { __context: _context, ...businessBody } = input;
48
+ body = businessBody;
49
+ }
50
+ return Object.freeze({ method, path, params: Object.freeze({}), query, headers, body });
51
+ }
52
+ export function withRouteParams(request, params) {
53
+ return Object.freeze({ ...request, params: Object.freeze({ ...params }) });
54
+ }
55
+ function isRequestMethod(value) {
56
+ return value === "GET" || value === "POST" || value === "PUT" || value === "PATCH" || value === "DELETE";
57
+ }
58
+ function freezeQuery(value) {
59
+ if (value === undefined)
60
+ return Object.freeze({});
61
+ if (!isRecord(value))
62
+ throw new ValidationError("Invalid invocation query metadata");
63
+ const result = {};
64
+ for (const [key, raw] of Object.entries(value)) {
65
+ if (typeof raw === "string")
66
+ result[key] = raw;
67
+ else if (Array.isArray(raw) && raw.length > 0 && raw.every(item => typeof item === "string")) {
68
+ result[key] = Object.freeze([...raw]);
69
+ }
70
+ else
71
+ throw new ValidationError("Invalid invocation query metadata");
72
+ }
73
+ return Object.freeze(result);
74
+ }
75
+ function freezeHeaders(value) {
76
+ if (value === undefined)
77
+ return Object.freeze({});
78
+ if (!isRecord(value))
79
+ throw new ValidationError("Invalid invocation header metadata");
80
+ const result = {};
81
+ for (const [key, raw] of Object.entries(value)) {
82
+ if (typeof raw !== "string")
83
+ throw new ValidationError("Invalid invocation header metadata");
84
+ result[key.toLowerCase()] = raw;
85
+ }
86
+ return Object.freeze(result);
87
+ }
@@ -0,0 +1,28 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { isRecord } from "./values.js";
3
+ export function requireSlug(value) {
4
+ const slug = requireText(value, "object slug");
5
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(slug)) {
6
+ throw new ValidationError(`Invalid object slug '${slug}'`);
7
+ }
8
+ return slug;
9
+ }
10
+ export function requireFieldSlug(value, name = "field slug") {
11
+ const slug = requireText(value, name);
12
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(slug)) {
13
+ throw new ValidationError(`Invalid ${name} '${slug}'`);
14
+ }
15
+ return slug;
16
+ }
17
+ export function requireText(value, name) {
18
+ if (typeof value !== "string" || value.trim().length === 0) {
19
+ throw new ValidationError(`${name} must be a non-empty string`);
20
+ }
21
+ return value.trim();
22
+ }
23
+ export function requireFields(fields) {
24
+ if (!isRecord(fields) || Object.keys(fields).length === 0) {
25
+ throw new ValidationError("Record fields must be a non-empty object");
26
+ }
27
+ return fields;
28
+ }
@@ -0,0 +1,6 @@
1
+ export function isRecord(value) {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }
4
+ export function errorMessage(error) {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
@@ -0,0 +1,40 @@
1
+ /** Public workspace metadata provided for the current invocation. */
2
+ export interface CurrentWorkspace {
3
+ readonly id: string;
4
+ readonly name?: string;
5
+ readonly domain?: string;
6
+ readonly language?: string;
7
+ readonly timezone?: string;
8
+ readonly dateFormat?: string;
9
+ readonly timeFormat?: string;
10
+ readonly numberFormat?: string;
11
+ }
12
+ /** Public membership metadata for the current user in the current workspace. */
13
+ export interface CurrentWorkspaceMembership {
14
+ readonly personnelId?: string;
15
+ readonly language?: string;
16
+ readonly timezone?: string;
17
+ }
18
+ /** Public account metadata for the authenticated user who initiated the invocation. */
19
+ export interface CurrentUser {
20
+ readonly accountId: string;
21
+ readonly email?: string;
22
+ readonly firstName?: string;
23
+ readonly lastName?: string;
24
+ readonly avatar?: string;
25
+ readonly language?: string;
26
+ readonly timezone?: string;
27
+ readonly membership: CurrentWorkspaceMembership;
28
+ }
29
+ export interface UserInvocationContext {
30
+ readonly identity: "user";
31
+ readonly workspace: CurrentWorkspace;
32
+ readonly user: CurrentUser;
33
+ }
34
+ export interface SystemInvocationContext {
35
+ readonly identity: "system";
36
+ readonly workspace: CurrentWorkspace;
37
+ readonly user: null;
38
+ }
39
+ /** Immutable authenticated identity and workspace snapshot for one execution. */
40
+ export type InvocationContext = UserInvocationContext | SystemInvocationContext;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ /** Retained for backwards compatibility with the first SDK release. */
2
+ export declare function createGreeting(name: string): string;
package/dist/legacy.js ADDED
@@ -0,0 +1,4 @@
1
+ /** Retained for backwards compatibility with the first SDK release. */
2
+ export function createGreeting(name) {
3
+ return `Hello ${name}`;
4
+ }
@@ -0,0 +1,19 @@
1
+ export interface LockOptions {
2
+ readonly namespace?: string;
3
+ readonly waitMs?: number;
4
+ readonly leaseMs?: number;
5
+ }
6
+ export interface LockLease {
7
+ readonly id: string;
8
+ readonly key: string;
9
+ readonly namespace: string;
10
+ readonly fencingToken: number;
11
+ readonly expiresAt: number;
12
+ renew(leaseMs?: number): Promise<void>;
13
+ release(): Promise<void>;
14
+ }
15
+ export interface DistributedLocks {
16
+ acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
17
+ withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
18
+ withLock<T>(key: string, options: LockOptions, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
19
+ }
package/dist/locks.js ADDED
@@ -0,0 +1,68 @@
1
+ import { LockUnavailableError, ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { optionalInteger, validateName } from "./state.js";
4
+ const DEFAULT_NAMESPACE = "default";
5
+ const DEFAULT_LEASE_MILLIS = 30_000;
6
+ const MIN_LEASE_MILLIS = 5_000;
7
+ const MAX_LEASE_MILLIS = 60_000;
8
+ const MAX_WAIT_MILLIS = 10_000;
9
+ /** @internal */
10
+ export function createLocksApi() {
11
+ const api = {
12
+ async acquire(key, options) {
13
+ const lockKey = validateName(key, "lock key", 255);
14
+ const namespace = options?.namespace === undefined
15
+ ? DEFAULT_NAMESPACE
16
+ : validateName(options.namespace, "lock namespace", 128);
17
+ const waitMs = optionalInteger(options?.waitMs, "waitMs", 0, MAX_WAIT_MILLIS) ?? 0;
18
+ const leaseMs = optionalInteger(options?.leaseMs, "leaseMs", MIN_LEASE_MILLIS, MAX_LEASE_MILLIS) ?? DEFAULT_LEASE_MILLIS;
19
+ const payload = await callBridge("locks.acquire", {
20
+ namespace, key: lockKey, waitMs, leaseMs,
21
+ });
22
+ return payload === null ? null : lease(payload, lockKey, namespace);
23
+ },
24
+ async withLock(key, optionsOrCallback, maybeCallback) {
25
+ const options = typeof optionsOrCallback === "function" ? undefined : optionsOrCallback;
26
+ const callback = typeof optionsOrCallback === "function" ? optionsOrCallback : maybeCallback;
27
+ if (typeof callback !== "function") {
28
+ throw new ValidationError("locks.withLock() requires a callback function");
29
+ }
30
+ const acquired = await api.acquire(key, options);
31
+ if (acquired === null)
32
+ throw new LockUnavailableError(key);
33
+ try {
34
+ return await callback(acquired);
35
+ }
36
+ finally {
37
+ await acquired.release();
38
+ }
39
+ },
40
+ };
41
+ return Object.freeze(api);
42
+ }
43
+ function lease(initial, key, namespace) {
44
+ let current = initial;
45
+ let released = false;
46
+ return Object.freeze({
47
+ get id() { return current.id; },
48
+ key,
49
+ namespace,
50
+ get fencingToken() { return current.fencingToken; },
51
+ get expiresAt() { return current.expiresAt; },
52
+ async renew(leaseMs) {
53
+ if (released)
54
+ throw new ValidationError("Cannot renew a released lock lease");
55
+ const duration = optionalInteger(leaseMs, "leaseMs", MIN_LEASE_MILLIS, MAX_LEASE_MILLIS) ?? DEFAULT_LEASE_MILLIS;
56
+ current = await callBridge("locks.renew", {
57
+ leaseId: current.id,
58
+ leaseMs: duration,
59
+ });
60
+ },
61
+ async release() {
62
+ if (released)
63
+ return;
64
+ await callBridge("locks.release", { leaseId: current.id });
65
+ released = true;
66
+ },
67
+ });
68
+ }
@@ -0,0 +1,6 @@
1
+ export interface ScriptLogger {
2
+ debug(message: string, details?: unknown): void;
3
+ info(message: string, details?: unknown): void;
4
+ warn(message: string, details?: unknown): void;
5
+ error(message: string, details?: unknown): void;
6
+ }
package/dist/logger.js ADDED
@@ -0,0 +1,14 @@
1
+ function writeLog(level, message, details) {
2
+ if (details === undefined) {
3
+ console.log(`[${level}] ${message}`);
4
+ return;
5
+ }
6
+ console.log(`[${level}] ${message}`, details);
7
+ }
8
+ /** @internal */
9
+ export const SCRIPT_LOGGER = Object.freeze({
10
+ debug: (message, details) => writeLog("DEBUG", message, details),
11
+ info: (message, details) => writeLog("INFO", message, details),
12
+ warn: (message, details) => writeLog("WARN", message, details),
13
+ error: (message, details) => writeLog("ERROR", message, details),
14
+ });
@@ -0,0 +1,52 @@
1
+ import type { RecordReference } from "./records.js";
2
+ import type { StringKeyOf } from "./workspace.js";
3
+ type FilterValue<T> = NonNullable<T> extends readonly (infer TItem)[] ? NonNullable<TItem> : NonNullable<T>;
4
+ interface SystemQueryFields {
5
+ readonly id: string;
6
+ readonly created: number;
7
+ readonly updated: number;
8
+ readonly created_by: RecordReference;
9
+ }
10
+ export type FilterOperator = "=" | "!=" | ">" | ">=" | "<" | "<=" | "like" | "not like" | "startsWith" | "endsWith" | "in" | "not in" | "is null" | "not null" | "between";
11
+ export interface FilterCondition {
12
+ readonly kind: "condition";
13
+ readonly field: string;
14
+ readonly operator: FilterOperator;
15
+ readonly value?: unknown;
16
+ }
17
+ export interface FilterGroup {
18
+ readonly kind: "group";
19
+ readonly operator: "and" | "or";
20
+ readonly expressions: readonly FilterExpression[];
21
+ }
22
+ export type FilterExpression = FilterCondition | FilterGroup;
23
+ export interface SortExpression {
24
+ readonly field: string;
25
+ readonly direction: "asc" | "desc";
26
+ }
27
+ export interface FieldReference<TValue> {
28
+ readonly slug: string;
29
+ eq(value: NonNullable<TValue>): FilterCondition;
30
+ neq(value: NonNullable<TValue>): FilterCondition;
31
+ gt(value: NonNullable<TValue>): FilterCondition;
32
+ gte(value: NonNullable<TValue>): FilterCondition;
33
+ lt(value: NonNullable<TValue>): FilterCondition;
34
+ lte(value: NonNullable<TValue>): FilterCondition;
35
+ like(value: string): FilterCondition;
36
+ notLike(value: string): FilterCondition;
37
+ startsWith(value: string): FilterCondition;
38
+ endsWith(value: string): FilterCondition;
39
+ in(values: readonly FilterValue<TValue>[]): FilterCondition;
40
+ notIn(values: readonly FilterValue<TValue>[]): FilterCondition;
41
+ isNull(): FilterCondition;
42
+ notNull(): FilterCondition;
43
+ between(from: NonNullable<TValue>, to: NonNullable<TValue>): FilterCondition;
44
+ asc(): SortExpression;
45
+ desc(): SortExpression;
46
+ }
47
+ export type FieldReferences<TFields> = {
48
+ readonly [K in StringKeyOf<TFields & SystemQueryFields>]: FieldReference<(TFields & SystemQueryFields)[K]>;
49
+ };
50
+ export declare function and(...expressions: readonly FilterExpression[]): FilterGroup;
51
+ export declare function or(...expressions: readonly FilterExpression[]): FilterGroup;
52
+ export {};
package/dist/query.js ADDED
@@ -0,0 +1,59 @@
1
+ import { ValidationError } from "./errors.js";
2
+ export function and(...expressions) {
3
+ return group("and", expressions);
4
+ }
5
+ export function or(...expressions) {
6
+ return group("or", expressions);
7
+ }
8
+ /** @internal */
9
+ export function createFieldReferences() {
10
+ return new Proxy(Object.create(null), {
11
+ get(_target, property) {
12
+ if (typeof property !== "string" || property === "then" || property === "toJSON") {
13
+ return undefined;
14
+ }
15
+ return createFieldReference(property);
16
+ },
17
+ set() {
18
+ return false;
19
+ },
20
+ });
21
+ }
22
+ function createFieldReference(slug) {
23
+ const condition = (operator, value) => {
24
+ const expression = value === undefined
25
+ ? { kind: "condition", field: slug, operator }
26
+ : { kind: "condition", field: slug, operator, value };
27
+ return Object.freeze(expression);
28
+ };
29
+ return Object.freeze({
30
+ slug,
31
+ eq: (value) => condition("=", value),
32
+ neq: (value) => condition("!=", value),
33
+ gt: (value) => condition(">", value),
34
+ gte: (value) => condition(">=", value),
35
+ lt: (value) => condition("<", value),
36
+ lte: (value) => condition("<=", value),
37
+ like: (value) => condition("like", value),
38
+ notLike: (value) => condition("not like", value),
39
+ startsWith: (value) => condition("startsWith", value),
40
+ endsWith: (value) => condition("endsWith", value),
41
+ in: (values) => condition("in", values),
42
+ notIn: (values) => condition("not in", values),
43
+ isNull: () => condition("is null"),
44
+ notNull: () => condition("not null"),
45
+ between: (from, to) => condition("between", [from, to]),
46
+ asc: () => Object.freeze({ field: slug, direction: "asc" }),
47
+ desc: () => Object.freeze({ field: slug, direction: "desc" }),
48
+ });
49
+ }
50
+ function group(operator, expressions) {
51
+ if (expressions.length === 0) {
52
+ throw new ValidationError(`${operator}() requires at least one expression`);
53
+ }
54
+ return Object.freeze({
55
+ kind: "group",
56
+ operator,
57
+ expressions: Object.freeze([...expressions]),
58
+ });
59
+ }