@cogover/sdk 0.1.2 → 0.6.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 (51) hide show
  1. package/README.md +347 -24
  2. package/dist/data.d.ts +49 -0
  3. package/dist/data.js +170 -0
  4. package/dist/errors.d.ts +37 -0
  5. package/dist/errors.js +72 -0
  6. package/dist/fetch.d.ts +28 -0
  7. package/dist/fetch.js +96 -0
  8. package/dist/index.d.ts +23 -3
  9. package/dist/index.js +8 -5
  10. package/dist/internal/bridge.js +48 -0
  11. package/dist/internal/invocation.js +57 -0
  12. package/dist/internal/json.js +81 -0
  13. package/dist/internal/request.js +87 -0
  14. package/dist/internal/trigger-config.js +212 -0
  15. package/dist/internal/trigger-runtime.js +211 -0
  16. package/dist/internal/validation.js +28 -0
  17. package/dist/internal/values.js +6 -0
  18. package/dist/invocation.d.ts +40 -0
  19. package/dist/invocation.js +1 -0
  20. package/dist/legacy.d.ts +2 -0
  21. package/dist/legacy.js +4 -0
  22. package/dist/locks.d.ts +19 -0
  23. package/dist/locks.js +68 -0
  24. package/dist/logger.d.ts +6 -0
  25. package/dist/logger.js +14 -0
  26. package/dist/query.d.ts +52 -0
  27. package/dist/query.js +59 -0
  28. package/dist/records.d.ts +79 -0
  29. package/dist/records.js +1 -0
  30. package/dist/request.d.ts +18 -0
  31. package/dist/request.js +1 -0
  32. package/dist/response.d.ts +21 -0
  33. package/dist/response.js +108 -0
  34. package/dist/router.d.ts +13 -0
  35. package/dist/router.js +104 -0
  36. package/dist/schema.d.ts +26 -0
  37. package/dist/schema.js +11 -0
  38. package/dist/script.d.ts +23 -0
  39. package/dist/script.js +56 -0
  40. package/dist/state.d.ts +24 -0
  41. package/dist/state.js +91 -0
  42. package/dist/trigger.d.ts +121 -0
  43. package/dist/trigger.js +15 -0
  44. package/dist/workspace.d.ts +8 -0
  45. package/dist/workspace.js +1 -0
  46. package/docs/en/api-reference.md +1415 -0
  47. package/docs/en/usage-guide.md +495 -0
  48. package/package.json +17 -5
  49. package/scripts/generate-workspace-types.mjs +135 -0
  50. package/dist/index.d.ts.map +0 -1
  51. package/dist/index.js.map +0 -1
package/dist/errors.js ADDED
@@ -0,0 +1,72 @@
1
+ import { isRecord } from "./internal/values.js";
2
+ export class CogoverApiError extends Error {
3
+ code;
4
+ /** Original server result code; undefined for errors without a server response. */
5
+ r;
6
+ details;
7
+ constructor(code, message, details) {
8
+ super(message);
9
+ this.name = "CogoverApiError";
10
+ this.code = code;
11
+ this.r = isRecord(details) && typeof details.r === "number" && Number.isSafeInteger(details.r)
12
+ ? details.r
13
+ : undefined;
14
+ this.details = details;
15
+ }
16
+ }
17
+ export class NotFoundError extends CogoverApiError {
18
+ resource;
19
+ resourceId;
20
+ constructor(resource, resourceId, message, details) {
21
+ super("NOT_FOUND", message ?? `${resource} '${resourceId}' was not found`, { ...(isRecord(details) ? details : {}), resource, resourceId });
22
+ this.name = "NotFoundError";
23
+ this.resource = resource;
24
+ this.resourceId = resourceId;
25
+ }
26
+ }
27
+ export class ValidationError extends CogoverApiError {
28
+ constructor(message, details) {
29
+ super("VALIDATION_ERROR", message, details);
30
+ this.name = "ValidationError";
31
+ }
32
+ }
33
+ export class PermissionDeniedError extends CogoverApiError {
34
+ constructor(message, details) {
35
+ super("PERMISSION_DENIED", message, details);
36
+ this.name = "PermissionDeniedError";
37
+ }
38
+ }
39
+ export class RateLimitError extends CogoverApiError {
40
+ constructor(message, details) {
41
+ super("RATE_LIMITED", message, details);
42
+ this.name = "RateLimitError";
43
+ }
44
+ }
45
+ /**
46
+ * Thrown by an after-change trigger handler to report a temporary failure. Cogover runs the handler again
47
+ * later. Anywhere else it is an ordinary failure.
48
+ */
49
+ export class RetryableError extends CogoverApiError {
50
+ constructor(message, details) {
51
+ super("RETRYABLE", message, details);
52
+ this.name = "RetryableError";
53
+ }
54
+ }
55
+ export class StateConflictError extends CogoverApiError {
56
+ constructor(message, details) {
57
+ super("STATE_CONFLICT", message, details);
58
+ this.name = "StateConflictError";
59
+ }
60
+ }
61
+ export class LockUnavailableError extends CogoverApiError {
62
+ constructor(key, message, details) {
63
+ super("LOCK_NOT_ACQUIRED", message ?? `Lock '${key}' could not be acquired`, details);
64
+ this.name = "LockUnavailableError";
65
+ }
66
+ }
67
+ export class LockLostError extends CogoverApiError {
68
+ constructor(message, details) {
69
+ super("LOCK_LOST", message, details);
70
+ this.name = "LockLostError";
71
+ }
72
+ }
@@ -0,0 +1,28 @@
1
+ export interface CogoverFetchInit {
2
+ readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ readonly headers?: Readonly<Record<string, string>>;
4
+ readonly body?: string;
5
+ readonly timeoutMs?: number;
6
+ }
7
+ export interface CogoverFetchHeaders {
8
+ get(name: string): string | null;
9
+ has(name: string): boolean;
10
+ entries(): IterableIterator<[string, string]>;
11
+ [Symbol.iterator](): IterableIterator<[string, string]>;
12
+ }
13
+ export interface CogoverFetchResponse {
14
+ readonly ok: boolean;
15
+ readonly status: number;
16
+ readonly statusText: string;
17
+ readonly url: string;
18
+ readonly redirected: false;
19
+ readonly headers: CogoverFetchHeaders;
20
+ readonly bodyUsed: boolean;
21
+ text(): Promise<string>;
22
+ json<T = unknown>(): Promise<T>;
23
+ }
24
+ /** Fetch-compatible API using Cogover's managed network layer. */
25
+ export declare function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
26
+ declare global {
27
+ function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
28
+ }
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,23 @@
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, GetManyResult, 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, GetManyOptions, 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 { defineTrigger } from "./trigger.js";
12
+ export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCondition, TriggerFilterGroup, TriggerFilter, TriggerConfig, TriggerManifest, TriggerSandboxHandler, TriggerDefinition, TriggerInfo, TriggerNewValues, TriggerOldValues, TriggerRecord, TriggerContext, TriggerHandler, } from "./trigger.js";
13
+ export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentUser, UserInvocationContext, SystemInvocationContext, InvocationContext, } from "./invocation.js";
14
+ export { createRouter } from "./router.js";
15
+ export type { ScriptRouter } from "./router.js";
16
+ export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPathParams, } from "./request.js";
17
+ export type { ResponseApi, ResponseInit, BinaryResponseInit, ResponseHeaderValue, ScriptResponse, } from "./response.js";
18
+ export type { ProjectState, StateNamespace, StateEntry, StateWriteOptions, StateDeleteOptions, } from "./state.js";
19
+ export type { DistributedLocks, LockLease, LockOptions, } from "./locks.js";
20
+ export { fetch } from "./fetch.js";
21
+ export type { CogoverFetchInit, CogoverFetchHeaders, CogoverFetchResponse, } from "./fetch.js";
22
+ export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
23
+ export { createGreeting } from "./legacy.js";
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
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 { defineTrigger } from "./trigger.js";
5
+ export { createRouter } from "./router.js";
6
+ export { fetch } from "./fetch.js";
7
+ export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
8
+ 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,81 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { errorMessage } from "./values.js";
3
+ /**
4
+ * Converts a value to plain JSON data using JSON.stringify semantics, but rejects every value that
5
+ * JSON.stringify would silently change or drop (NaN, functions, Map/Set, undefined array items...).
6
+ * Silent coercion would turn a calculation bug into a cleared field.
7
+ */
8
+ export function toJsonValue(value, label) {
9
+ let serialized;
10
+ try {
11
+ serialized = JSON.stringify(value, strictReplacer);
12
+ }
13
+ catch (error) {
14
+ throw new ValidationError(`${label} must be JSON serializable: ${errorMessage(error)}`);
15
+ }
16
+ if (serialized === undefined) {
17
+ throw new ValidationError(`${label} must be JSON serializable`);
18
+ }
19
+ return JSON.parse(serialized);
20
+ }
21
+ /** Deep copy of data that is already plain JSON. */
22
+ export function cloneJson(value) {
23
+ return JSON.parse(JSON.stringify(value));
24
+ }
25
+ /** Structural equality of two plain JSON values; object key order is irrelevant. */
26
+ export function jsonEquals(left, right) {
27
+ if (left === right)
28
+ return true;
29
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null) {
30
+ return false;
31
+ }
32
+ if (Array.isArray(left) || Array.isArray(right)) {
33
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
34
+ return false;
35
+ return left.every((item, index) => jsonEquals(item, right[index]));
36
+ }
37
+ const leftObject = left;
38
+ const rightObject = right;
39
+ const leftKeys = Object.keys(leftObject);
40
+ if (leftKeys.length !== Object.keys(rightObject).length)
41
+ return false;
42
+ return leftKeys.every(key => Object.prototype.hasOwnProperty.call(rightObject, key)
43
+ && jsonEquals(leftObject[key], rightObject[key]));
44
+ }
45
+ export function deepFreeze(value) {
46
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
47
+ Object.freeze(value);
48
+ for (const item of Object.values(value))
49
+ deepFreeze(item);
50
+ }
51
+ return value;
52
+ }
53
+ // JSON.stringify invokes the replacer after toJSON(), so a Date arrives here as its ISO string.
54
+ function strictReplacer(_key, value) {
55
+ if (value === undefined) {
56
+ if (Array.isArray(this))
57
+ throw new TypeError("undefined is not allowed inside an array");
58
+ return value; // An undefined object property is omitted, exactly like JSON.stringify.
59
+ }
60
+ switch (typeof value) {
61
+ case "number":
62
+ if (!Number.isFinite(value))
63
+ throw new TypeError("numbers must be finite");
64
+ return value;
65
+ case "bigint":
66
+ case "function":
67
+ case "symbol":
68
+ throw new TypeError(`${typeof value} values are not supported`);
69
+ case "object": {
70
+ if (value === null || Array.isArray(value))
71
+ return value;
72
+ const prototype = Object.getPrototypeOf(value);
73
+ if (prototype !== Object.prototype && prototype !== null) {
74
+ throw new TypeError("only plain objects and arrays are supported");
75
+ }
76
+ return value;
77
+ }
78
+ default:
79
+ return value;
80
+ }
81
+ }
@@ -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
+ }