@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
@@ -0,0 +1,74 @@
1
+ export type CogoverRecordId = string & {
2
+ readonly __cogoverRecordIdBrand: unique symbol;
3
+ };
4
+ export interface RecordReference<TObjectSlug extends string = string> {
5
+ readonly id: CogoverRecordId;
6
+ readonly name: string;
7
+ readonly objectSlug?: TObjectSlug;
8
+ }
9
+ export interface UrlValue {
10
+ readonly url: string;
11
+ readonly alias?: string;
12
+ }
13
+ export interface FileValue {
14
+ readonly id: string;
15
+ readonly name: string;
16
+ readonly size?: number;
17
+ readonly contentType?: string;
18
+ readonly url?: string;
19
+ }
20
+ export interface CogoverRecord<TFields> {
21
+ readonly id: CogoverRecordId;
22
+ readonly fields: Readonly<TFields>;
23
+ readonly system: {
24
+ readonly createdAt: number;
25
+ readonly updatedAt: number;
26
+ readonly createdBy?: {
27
+ readonly id: string;
28
+ readonly name: string;
29
+ };
30
+ };
31
+ }
32
+ export interface RecordPage<TFields> {
33
+ readonly items: CogoverRecord<TFields>[];
34
+ readonly total: number;
35
+ readonly nextCursor?: string;
36
+ }
37
+ export interface DeleteResult {
38
+ readonly deleted: CogoverRecordId[];
39
+ readonly notDeleted: CogoverRecordId[];
40
+ }
41
+ export interface BatchWriteRowResult {
42
+ readonly referenceId: string;
43
+ readonly id?: CogoverRecordId;
44
+ readonly r: number;
45
+ readonly msg?: string;
46
+ readonly success: boolean;
47
+ }
48
+ /** Batch writes are best-effort per row; inspect `success` or every row result. */
49
+ export interface BatchWriteResponse {
50
+ readonly r: number;
51
+ readonly msg?: string;
52
+ readonly results: readonly BatchWriteRowResult[];
53
+ readonly success: boolean;
54
+ }
55
+ export interface UpsertResult {
56
+ readonly id: CogoverRecordId;
57
+ readonly created: boolean;
58
+ }
59
+ type WriteNonNullValue<TValue> = TValue extends RecordReference<infer TObjectSlug> ? string | CogoverRecordId | RecordReference<TObjectSlug> : TValue extends readonly (infer TItem)[] ? readonly WriteNonNullValue<TItem>[] : TValue;
60
+ type WriteValue<TValue> = null extends TValue ? WriteNonNullValue<NonNullable<TValue>> | null : WriteNonNullValue<TValue>;
61
+ export type CreateFields<TFields> = {
62
+ [K in keyof TFields]?: WriteValue<TFields[K]>;
63
+ };
64
+ export type UpdateFields<TFields> = {
65
+ [K in keyof TFields]?: WriteValue<TFields[K]>;
66
+ };
67
+ export interface BatchUpdateItem<TFields> {
68
+ readonly id: CogoverRecordId;
69
+ readonly fields: UpdateFields<TFields>;
70
+ }
71
+ export type UpsertFields<TFields, TMatchBy extends keyof TFields> = CreateFields<TFields> & {
72
+ readonly [K in TMatchBy]-?: Exclude<CreateFields<TFields>[K], null | undefined>;
73
+ };
74
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ /** HTTP methods supported by project routes. */
2
+ export type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ export type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
4
+ export type ScriptHeaders = Readonly<Record<string, string>>;
5
+ export type ScriptPathParams = Readonly<Record<string, string>>;
6
+ export interface ScriptRequest<TBody = unknown> {
7
+ readonly method: RequestMethod;
8
+ /** Static path relative to the project URL; the original project URL uses '/'. */
9
+ readonly path: string;
10
+ /** Decoded dynamic route parameters. Empty outside a matched router route. */
11
+ readonly params: ScriptPathParams;
12
+ /** Query parameters. Repeated names are represented as readonly arrays. */
13
+ readonly query: ScriptQuery;
14
+ /** Lower-case request headers documented by Cogover. Authentication headers are never exposed. */
15
+ readonly headers: ScriptHeaders;
16
+ /** Business input only, without invocation metadata. */
17
+ readonly body: TBody;
18
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ export type ResponseHeaderValue = string | readonly string[];
2
+ export interface ResponseInit {
3
+ readonly status?: number;
4
+ readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
5
+ }
6
+ export interface BinaryResponseInit extends ResponseInit {
7
+ readonly contentType?: string;
8
+ }
9
+ declare const scriptResponseBrand: unique symbol;
10
+ /** Opaque HTTP response returned by a project route. */
11
+ export interface ScriptResponse<TBody = unknown> {
12
+ readonly [scriptResponseBrand]: TBody;
13
+ }
14
+ export interface ResponseApi {
15
+ json<TBody>(body: TBody, init?: ResponseInit): ScriptResponse<TBody>;
16
+ text(body: string, init?: ResponseInit): ScriptResponse<string>;
17
+ bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
18
+ empty(init?: ResponseInit): ScriptResponse<null>;
19
+ redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
20
+ }
21
+ export {};
@@ -0,0 +1,108 @@
1
+ import { ValidationError } from "./errors.js";
2
+ const RESPONSE_KEY = "__cogoverHttpResponse";
3
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
4
+ const DENIED_HEADERS = new Set([
5
+ "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "trailer",
6
+ "set-cookie", "server", "date", "proxy-authenticate",
7
+ ]);
8
+ /** @internal */
9
+ export function createResponseApi() {
10
+ return Object.freeze({
11
+ json(body, init) {
12
+ if (body === undefined)
13
+ throw new ValidationError("response.json() body must be JSON serializable");
14
+ return response("json", body, init, "application/json; charset=utf-8");
15
+ },
16
+ text(body, init) {
17
+ if (typeof body !== "string")
18
+ throw new ValidationError("response.text() body must be a string");
19
+ return response("text", body, init, "text/plain; charset=utf-8");
20
+ },
21
+ bytes(body, init) {
22
+ if (!(body instanceof Uint8Array)) {
23
+ throw new ValidationError("response.bytes() body must be a Uint8Array");
24
+ }
25
+ const contentType = init?.contentType ?? "application/octet-stream";
26
+ if (typeof contentType !== "string" || contentType.length === 0 || /[\r\n]/.test(contentType)) {
27
+ throw new ValidationError("response contentType is invalid");
28
+ }
29
+ return response("bytes", encodeBase64(body), init, contentType);
30
+ },
31
+ empty(init) {
32
+ const emptyInit = init?.headers === undefined
33
+ ? { status: init?.status ?? 204 }
34
+ : { status: init?.status ?? 204, headers: init.headers };
35
+ return response("empty", null, emptyInit);
36
+ },
37
+ redirect(location, status = 302) {
38
+ if (typeof location !== "string" || location.length === 0 || location.length > 4096
39
+ || /[\r\n]/.test(location)) {
40
+ throw new ValidationError("response.redirect() location is invalid");
41
+ }
42
+ return response("empty", null, { status, headers: { location } });
43
+ },
44
+ });
45
+ }
46
+ function response(bodyType, body, init, defaultContentType) {
47
+ const status = validateStatus(init?.status ?? 200);
48
+ const headers = normalizeHeaders(init?.headers, defaultContentType);
49
+ const envelope = Object.freeze({
50
+ version: 1,
51
+ status,
52
+ headers,
53
+ bodyType,
54
+ body,
55
+ });
56
+ return Object.freeze({
57
+ toJSON: () => Object.freeze({ [RESPONSE_KEY]: envelope }),
58
+ });
59
+ }
60
+ function validateStatus(status) {
61
+ if (!Number.isInteger(status) || status < 200 || status > 599) {
62
+ throw new ValidationError("HTTP response status must be an integer between 200 and 599");
63
+ }
64
+ return status;
65
+ }
66
+ function normalizeHeaders(source, defaultContentType) {
67
+ const normalized = Object.create(null);
68
+ if (source !== undefined && (source === null || typeof source !== "object" || Array.isArray(source))) {
69
+ throw new ValidationError("HTTP response headers must be an object");
70
+ }
71
+ if (Object.keys(source ?? {}).length > 50) {
72
+ throw new ValidationError("An HTTP response supports at most 50 headers");
73
+ }
74
+ for (const [name, raw] of Object.entries(source ?? {})) {
75
+ const key = name.toLowerCase();
76
+ if (!HEADER_NAME.test(name) || DENIED_HEADERS.has(key)
77
+ || key.startsWith("x-req-") || key.startsWith("x-stringee-")) {
78
+ throw new ValidationError(`HTTP response header is not allowed: ${name}`);
79
+ }
80
+ if (normalized[key] !== undefined) {
81
+ throw new ValidationError(`Duplicate HTTP response header: ${name}`);
82
+ }
83
+ const values = typeof raw === "string" ? [raw] : Array.isArray(raw) ? [...raw] : null;
84
+ if (values === null || values.length === 0 || values.some(value => typeof value !== "string" || value.length > 8192 || /[\r\n]/.test(value))) {
85
+ throw new ValidationError(`Invalid HTTP response header value: ${name}`);
86
+ }
87
+ normalized[key] = Object.freeze(values);
88
+ }
89
+ if (defaultContentType !== undefined && normalized["content-type"] === undefined) {
90
+ normalized["content-type"] = Object.freeze([defaultContentType]);
91
+ }
92
+ return Object.freeze(normalized);
93
+ }
94
+ function encodeBase64(bytes) {
95
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
96
+ let result = "";
97
+ for (let index = 0; index < bytes.length; index += 3) {
98
+ const first = bytes[index] ?? 0;
99
+ const second = bytes[index + 1] ?? 0;
100
+ const third = bytes[index + 2] ?? 0;
101
+ const value = (first << 16) | (second << 8) | third;
102
+ result += alphabet.charAt((value >>> 18) & 63)
103
+ + alphabet.charAt((value >>> 12) & 63)
104
+ + (index + 1 < bytes.length ? alphabet.charAt((value >>> 6) & 63) : "=")
105
+ + (index + 2 < bytes.length ? alphabet.charAt(value & 63) : "=");
106
+ }
107
+ return result;
108
+ }
@@ -0,0 +1,13 @@
1
+ import type { RequestMethod } from "./request.js";
2
+ import type { SandboxHandler, ScriptHandler } from "./script.js";
3
+ import type { EffectiveWorkspaceObjects } from "./workspace.js";
4
+ export interface ScriptRouter<TSchema extends object = EffectiveWorkspaceObjects> {
5
+ addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
6
+ post<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
7
+ get<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
8
+ put<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
9
+ patch<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
10
+ delete<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
11
+ toHandler(): SandboxHandler;
12
+ }
13
+ export declare function createRouter<TSchema extends object = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>;
package/dist/router.js ADDED
@@ -0,0 +1,104 @@
1
+ import { NotFoundError, ValidationError } from "./errors.js";
2
+ import { validateRoutePath, withRouteParams } from "./internal/request.js";
3
+ import { createSandboxHandler } from "./script.js";
4
+ export function createRouter() {
5
+ const routes = [];
6
+ const router = {
7
+ addRoute(method, path, handler) {
8
+ if (!isRequestMethod(method))
9
+ throw new ValidationError(`Unsupported route method: ${String(method)}`);
10
+ validateRoutePath(path);
11
+ if (typeof handler !== "function")
12
+ throw new ValidationError("Route handler must be a function");
13
+ const signature = routeSignature(path);
14
+ if (routes.some(route => route.method === method && route.signature === signature)) {
15
+ throw new ValidationError(`Duplicate or ambiguous route: ${method} ${path}`);
16
+ }
17
+ if (routes.length >= 256)
18
+ throw new ValidationError("A router supports at most 256 routes");
19
+ routes.push(Object.freeze({ method, path, signature,
20
+ handler: handler }));
21
+ return router;
22
+ },
23
+ post(path, handler) {
24
+ return router.addRoute("POST", path, handler);
25
+ },
26
+ get(path, handler) {
27
+ return router.addRoute("GET", path, handler);
28
+ },
29
+ put(path, handler) {
30
+ return router.addRoute("PUT", path, handler);
31
+ },
32
+ patch(path, handler) {
33
+ return router.addRoute("PATCH", path, handler);
34
+ },
35
+ delete(path, handler) {
36
+ return router.addRoute("DELETE", path, handler);
37
+ },
38
+ toHandler() {
39
+ // Each exported handler gets a stable route table, never a global registry.
40
+ const registered = Object.freeze([...routes]);
41
+ return createSandboxHandler(context => {
42
+ const candidates = registered.filter(route => route.method === context.request.method);
43
+ const exact = candidates.find(route => !route.path.includes(":") && route.path === context.request.path);
44
+ const matched = exact === undefined
45
+ ? candidates.map(route => ({ route, params: matchRoute(route.path, context.request.path) }))
46
+ .find(match => match.params !== null)
47
+ : { route: exact, params: {} };
48
+ if (!matched || matched.params === null)
49
+ throw new NotFoundError("route", context.request.path);
50
+ return matched.route.handler({
51
+ input: context.input,
52
+ request: withRouteParams(context.request, matched.params),
53
+ get invocation() {
54
+ return context.invocation;
55
+ },
56
+ data: context.data,
57
+ schema: context.schema,
58
+ log: context.log,
59
+ response: context.response,
60
+ state: context.state,
61
+ locks: context.locks,
62
+ });
63
+ });
64
+ },
65
+ };
66
+ return Object.freeze(router);
67
+ }
68
+ function isRequestMethod(method) {
69
+ return method === "GET" || method === "POST" || method === "PUT"
70
+ || method === "PATCH" || method === "DELETE";
71
+ }
72
+ function routeSignature(path) {
73
+ return path.split("/").map(segment => segment.startsWith(":") ? ":" : segment).join("/");
74
+ }
75
+ function matchRoute(template, actual) {
76
+ const expected = template.split("/");
77
+ const received = actual.split("/");
78
+ if (expected.length !== received.length)
79
+ return null;
80
+ const params = Object.create(null);
81
+ for (let index = 1; index < expected.length; index++) {
82
+ const segment = expected[index];
83
+ const value = received[index];
84
+ if (segment === undefined || value === undefined)
85
+ return null;
86
+ if (!segment.startsWith(":")) {
87
+ if (segment !== value)
88
+ return null;
89
+ continue;
90
+ }
91
+ try {
92
+ const decoded = decodeURIComponent(value);
93
+ if (decoded.length === 0 || decoded === "." || decoded === ".."
94
+ || decoded.includes("/") || decoded.includes("\\") || /[\u0000-\u001f\u007f]/.test(decoded)) {
95
+ return null;
96
+ }
97
+ params[segment.slice(1)] = decoded;
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
103
+ return params;
104
+ }
@@ -0,0 +1,26 @@
1
+ import type { EffectiveWorkspaceObjects, StringKeyOf } from "./workspace.js";
2
+ export interface ObjectMetadata {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ readonly slug: string;
6
+ readonly fields: readonly {
7
+ readonly id: string;
8
+ readonly name: string;
9
+ readonly slug: string;
10
+ readonly fieldType: string;
11
+ readonly required: boolean;
12
+ readonly multiple: boolean;
13
+ readonly readOnly: boolean;
14
+ readonly manualModifyAllow?: boolean;
15
+ readonly metaData?: Readonly<Record<string, unknown>>;
16
+ readonly options?: readonly {
17
+ readonly id: string;
18
+ readonly slug: string;
19
+ readonly value: string;
20
+ readonly isDefault?: boolean;
21
+ }[];
22
+ }[];
23
+ }
24
+ export interface SchemaApi<TSchema extends object = EffectiveWorkspaceObjects> {
25
+ object<K extends StringKeyOf<TSchema>>(slug: K): Promise<ObjectMetadata>;
26
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,11 @@
1
+ import { callBridge } from "./internal/bridge.js";
2
+ import { requireSlug } from "./internal/validation.js";
3
+ /** @internal */
4
+ export function createSchemaApi() {
5
+ return Object.freeze({
6
+ async object(slug) {
7
+ const objectSlug = requireSlug(String(slug));
8
+ return callBridge("schema.object", { objectSlug });
9
+ },
10
+ });
11
+ }
@@ -0,0 +1,23 @@
1
+ import type { DataApi } from "./data.js";
2
+ import type { ScriptRequest } from "./request.js";
3
+ import type { ResponseApi, ScriptResponse } from "./response.js";
4
+ import type { ScriptLogger } from "./logger.js";
5
+ import type { SchemaApi } from "./schema.js";
6
+ import type { EffectiveWorkspaceObjects } from "./workspace.js";
7
+ import type { ProjectState } from "./state.js";
8
+ import type { DistributedLocks } from "./locks.js";
9
+ import type { InvocationContext } from "./invocation.js";
10
+ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
11
+ readonly input: TInput;
12
+ readonly request: ScriptRequest<TInput>;
13
+ readonly invocation: InvocationContext;
14
+ readonly data: DataApi<TSchema>;
15
+ readonly schema: SchemaApi<TSchema>;
16
+ readonly log: ScriptLogger;
17
+ readonly response: ResponseApi;
18
+ readonly state: ProjectState;
19
+ readonly locks: DistributedLocks;
20
+ }
21
+ export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
22
+ export type SandboxHandler = (inputJson: string) => Promise<string | null>;
23
+ export declare function defineScript<TInput = unknown, TOutput = unknown, TSchema extends object = EffectiveWorkspaceObjects>(handler: ScriptHandler<TInput, TOutput, TSchema>): SandboxHandler;
package/dist/script.js ADDED
@@ -0,0 +1,56 @@
1
+ import { createDataApi } from "./data.js";
2
+ import { NotFoundError, ValidationError } from "./errors.js";
3
+ import { scriptRequest } from "./internal/request.js";
4
+ import { createResponseApi } from "./response.js";
5
+ import { errorMessage } from "./internal/values.js";
6
+ import { SCRIPT_LOGGER } from "./logger.js";
7
+ import { createSchemaApi } from "./schema.js";
8
+ import { createStateApi } from "./state.js";
9
+ import { createLocksApi } from "./locks.js";
10
+ import { installCogoverFetch } from "./fetch.js";
11
+ import { invocationContext } from "./internal/invocation.js";
12
+ export function defineScript(handler) {
13
+ if (typeof handler !== "function") {
14
+ throw new ValidationError("defineScript() requires a handler function");
15
+ }
16
+ return createSandboxHandler(context => {
17
+ if (context.request.path !== "/")
18
+ throw new NotFoundError("route", context.request.path);
19
+ return handler(context);
20
+ });
21
+ }
22
+ /** @internal */
23
+ export function createSandboxHandler(handler) {
24
+ return async (inputJson) => {
25
+ installCogoverFetch();
26
+ let input;
27
+ try {
28
+ input = JSON.parse(inputJson);
29
+ }
30
+ catch (error) {
31
+ throw new ValidationError("Script input must be valid JSON", errorMessage(error));
32
+ }
33
+ let invocation;
34
+ const output = await handler({
35
+ input,
36
+ request: scriptRequest(input),
37
+ get invocation() {
38
+ return invocation ??= invocationContext(input);
39
+ },
40
+ data: createDataApi(),
41
+ schema: createSchemaApi(),
42
+ log: SCRIPT_LOGGER,
43
+ response: createResponseApi(),
44
+ state: createStateApi(),
45
+ locks: createLocksApi(),
46
+ });
47
+ if (output === null) {
48
+ return null;
49
+ }
50
+ const outputJson = JSON.stringify(output);
51
+ if (outputJson === undefined) {
52
+ throw new ValidationError("Script output must be JSON serializable");
53
+ }
54
+ return outputJson;
55
+ };
56
+ }
@@ -0,0 +1,24 @@
1
+ export interface StateEntry<T> {
2
+ readonly value: T;
3
+ readonly version: number;
4
+ readonly expiresAt?: number;
5
+ readonly createdAt: number;
6
+ readonly updatedAt: number;
7
+ }
8
+ export interface StateWriteOptions {
9
+ /** 0 creates only when absent; a positive value performs compare-and-set. */
10
+ readonly expectedVersion?: number;
11
+ readonly ttlSeconds?: number;
12
+ }
13
+ export interface StateDeleteOptions {
14
+ readonly expectedVersion?: number;
15
+ }
16
+ export interface StateNamespace {
17
+ readonly name: string;
18
+ get<T>(key: string): Promise<StateEntry<T> | null>;
19
+ set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
20
+ delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
21
+ }
22
+ export interface ProjectState {
23
+ namespace(name: string): StateNamespace;
24
+ }
package/dist/state.js ADDED
@@ -0,0 +1,91 @@
1
+ import { callBridge } from "./internal/bridge.js";
2
+ import { ValidationError } from "./errors.js";
3
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
4
+ const MAX_NAMESPACE_LENGTH = 128;
5
+ const MAX_KEY_LENGTH = 255;
6
+ const MAX_VALUE_BYTES = 32 * 1024;
7
+ const MAX_TTL_SECONDS = 365 * 24 * 60 * 60;
8
+ /** @internal */
9
+ export function createStateApi() {
10
+ return Object.freeze({
11
+ namespace(name) {
12
+ const namespace = validateName(name, "state namespace", MAX_NAMESPACE_LENGTH);
13
+ return Object.freeze({
14
+ name: namespace,
15
+ async get(key) {
16
+ return callBridge("state.get", {
17
+ namespace,
18
+ key: validateName(key, "state key", MAX_KEY_LENGTH),
19
+ });
20
+ },
21
+ async set(key, value, options) {
22
+ validateValue(value);
23
+ return callBridge("state.set", {
24
+ namespace,
25
+ key: validateName(key, "state key", MAX_KEY_LENGTH),
26
+ value,
27
+ expectedVersion: optionalInteger(options?.expectedVersion, "expectedVersion", 0, Number.MAX_SAFE_INTEGER),
28
+ ttlSeconds: optionalInteger(options?.ttlSeconds, "ttlSeconds", 1, MAX_TTL_SECONDS),
29
+ });
30
+ },
31
+ async delete(key, options) {
32
+ return callBridge("state.delete", {
33
+ namespace,
34
+ key: validateName(key, "state key", MAX_KEY_LENGTH),
35
+ expectedVersion: optionalInteger(options?.expectedVersion, "expectedVersion", 0, Number.MAX_SAFE_INTEGER),
36
+ });
37
+ },
38
+ });
39
+ },
40
+ });
41
+ }
42
+ function validateValue(value) {
43
+ if (value === undefined)
44
+ throw new ValidationError("state value must be JSON serializable");
45
+ let serialized;
46
+ try {
47
+ serialized = JSON.stringify(value);
48
+ }
49
+ catch {
50
+ throw new ValidationError("state value must be JSON serializable");
51
+ }
52
+ if (serialized === undefined)
53
+ throw new ValidationError("state value must be JSON serializable");
54
+ if (utf8Bytes(serialized) > MAX_VALUE_BYTES) {
55
+ throw new ValidationError(`state value must not exceed ${MAX_VALUE_BYTES} UTF-8 bytes`);
56
+ }
57
+ }
58
+ /** @internal */
59
+ export function validateName(value, label, maximumLength) {
60
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || !NAME.test(value)) {
61
+ throw new ValidationError(`${label} is invalid`);
62
+ }
63
+ return value;
64
+ }
65
+ /** @internal */
66
+ export function optionalInteger(value, label, minimum, maximum) {
67
+ if (value === undefined)
68
+ return undefined;
69
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
70
+ throw new ValidationError(`${label} must be an integer between ${minimum} and ${maximum}`);
71
+ }
72
+ return value;
73
+ }
74
+ function utf8Bytes(value) {
75
+ let bytes = 0;
76
+ for (let index = 0; index < value.length; index++) {
77
+ const code = value.charCodeAt(index);
78
+ if (code < 0x80)
79
+ bytes++;
80
+ else if (code < 0x800)
81
+ bytes += 2;
82
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length
83
+ && value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) {
84
+ bytes += 4;
85
+ index++;
86
+ }
87
+ else
88
+ bytes += 3;
89
+ }
90
+ return bytes;
91
+ }
@@ -0,0 +1,8 @@
1
+ /** Extended by customer declarations through the @cogover/sdk entry point. */
2
+ export interface WorkspaceObjects {
3
+ }
4
+ type UnknownFields = Record<string, unknown>;
5
+ export type EffectiveWorkspaceObjects = keyof WorkspaceObjects extends never ? Record<string, UnknownFields> : WorkspaceObjects;
6
+ export type StringKeyOf<T> = Extract<keyof T, string>;
7
+ export type FieldsFor<TSchema, K extends keyof TSchema> = TSchema[K] extends object ? TSchema[K] : UnknownFields;
8
+ export {};
@@ -0,0 +1 @@
1
+ export {};