@orbit-app/functions 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @orbit-app/functions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Write Orbit Functions: TypeScript that runs in Orbit's sandbox for one app, as the store's org. An app calls an action function. A provider event, such as a Slack reaction, runs a webhook function. A service outside Orbit runs a delegate function through a signed link, which an action or webhook function makes with `orbit.defineDelegates().sign()`.
4
+
5
+ ```bash
6
+ npm install --save-dev @orbit-app/functions esbuild
7
+ ```
8
+
9
+ ```ts
10
+ import { defineFunction, OrbitFunctionError } from "@orbit-app/functions";
11
+
12
+ export default defineFunction({
13
+ trigger: { type: "action" },
14
+ async run(input: { note: string }, orbit, ctx) {
15
+ if (!input.note) throw new OrbitFunctionError("no_note", "Write a note.");
16
+ return orbit.objects.create({
17
+ type: "kudos",
18
+ fields: [{ key: "from", value: ctx.caller.id }, { key: "note", value: input.note }],
19
+ sharing: { type: "organization", access: "read" },
20
+ });
21
+ },
22
+ });
23
+ ```
24
+
25
+ Declare each function under `functions` in `orbit.json`. `orbit publish` and `orbit pack` bundle each entry with esbuild and `serve()`, the wrapper of this package. Do not call `serve()` yourself.
26
+
27
+ The full guide (triggers, limits, org connections, the run log) is `functions.md` of the Orbit MCP server's docs. In this repository it is `api/docs/functions.md`.
28
+
29
+ ## Develop this package
30
+
31
+ - Run `pnpm install && pnpm build` in `../web` first. This package takes the types of `@orbit-app/web` from `web/dist`.
32
+ - `pnpm install`, then `pnpm test`. It runs `tsc`, then the tests of `serve()` and `defineDelegates`. `tsc` also compiles `test/research`, the spec's delegate example, against the `OrbitDelegates` that `orbit types --ts` wrote. Its `@ts-expect-error` lines must fail to compile. A CLI test writes `test/research/orbit-types.ts` again and compares it.
33
+ - `pnpm build` writes `dist/`. Build it before a local project links it.
34
+ - Publish `@orbit-app/web` first, because this package needs a registry range of it. The root README, "Release the npm packages", gives the steps.
35
+
36
+ `platform/` is not part of the package. It holds Orbit's own Cloudflare workers: `dispatch.js`, which checks the API's signature and runs a user script of the dispatch namespace, and `outbound.js`, which lets a user script reach only the Orbit API. Terraform deploys both (`.infrastructure/modules/functions`).
@@ -0,0 +1,155 @@
1
+ import { type ObjectsApi, type ObjectsClient } from "@orbit-app/web";
2
+ export { OrbitObjectError, type ObjectsApi, type ObjectsClient } from "@orbit-app/web";
3
+ export type ActionTrigger = {
4
+ type: "action";
5
+ };
6
+ export type WebhookTrigger = {
7
+ type: "connection_webhook";
8
+ provider: string;
9
+ events: readonly string[];
10
+ };
11
+ export type Caller = {
12
+ id: string;
13
+ role: string | null;
14
+ };
15
+ export type ActionContext = {
16
+ runId: string;
17
+ env: string;
18
+ caller: Caller;
19
+ };
20
+ export type WebhookContext = {
21
+ runId: string;
22
+ env: string;
23
+ attempt: number;
24
+ };
25
+ export type WebhookEvent<Payload = any> = {
26
+ provider: string;
27
+ event: string;
28
+ eventId: string;
29
+ handle: string;
30
+ receivedAt: string;
31
+ payload: Payload;
32
+ };
33
+ export type DelegateTrigger = {
34
+ type: "delegate";
35
+ };
36
+ export type DelegateTypes = {
37
+ context: Record<string, unknown>;
38
+ body: unknown;
39
+ };
40
+ export type DelegateContext<Context = Record<string, unknown>> = {
41
+ runId: string;
42
+ env: string;
43
+ delegate: {
44
+ id: string;
45
+ context: Context;
46
+ usesLeft: number;
47
+ expiresAt: string;
48
+ callId: string;
49
+ handle: string;
50
+ };
51
+ };
52
+ export type Delegate = {
53
+ id: string;
54
+ url: string;
55
+ secret: string;
56
+ expiresAt: string;
57
+ uses: number;
58
+ };
59
+ export type SignOptions<Context> = {
60
+ ttlMilliseconds: number;
61
+ uses?: number;
62
+ allowFrom?: string[];
63
+ context: Context;
64
+ };
65
+ export type Delegates<M extends Record<string, DelegateTypes>> = {
66
+ sign<N extends keyof M & string>(name: N, opts: SignOptions<M[N]["context"]>): Promise<Delegate>;
67
+ revoke(id: string): Promise<void>;
68
+ };
69
+ export type OrbitDelegateErrorCode = "invalid" | "invalid_allow_from" | "limit_reached" | "not_declared" | "not_found" | "forbidden" | "rate_limited" | "unavailable";
70
+ export declare class OrbitDelegateError extends Error {
71
+ readonly code: OrbitDelegateErrorCode;
72
+ readonly fields?: Record<string, string>;
73
+ readonly retryAfter?: number;
74
+ constructor(code: OrbitDelegateErrorCode, message: string, extra?: {
75
+ fields?: Record<string, string>;
76
+ retryAfter?: number;
77
+ });
78
+ }
79
+ export type OrbitOrg = {
80
+ id: string;
81
+ name: string;
82
+ slug: string;
83
+ };
84
+ export type OrgConnection = {
85
+ provider: string;
86
+ scopes: readonly string[];
87
+ missingScopes: readonly string[];
88
+ fetch(path: string, init?: {
89
+ method?: string;
90
+ headers?: Record<string, string>;
91
+ body?: string | Uint8Array | null;
92
+ }): Promise<Response>;
93
+ };
94
+ export type FunctionOrbit = {
95
+ objects: ObjectsApi;
96
+ defineObjects<Types extends Record<string, Record<string, unknown>>, Required extends {
97
+ [K in keyof Types]?: keyof Types[K];
98
+ } = {}>(): ObjectsClient<Types, Required>;
99
+ connections: {
100
+ get(provider: string): Promise<OrgConnection | null>;
101
+ };
102
+ defineDelegates<M extends Record<string, DelegateTypes> = Record<string, DelegateTypes>>(): Delegates<M>;
103
+ org(): OrbitOrg;
104
+ };
105
+ export type ActionFunction<Input = unknown, Output = unknown> = {
106
+ trigger: ActionTrigger;
107
+ run(input: Input, orbit: FunctionOrbit, ctx: ActionContext): Output | Promise<Output>;
108
+ };
109
+ export type WebhookFunction<Payload = any> = {
110
+ trigger: WebhookTrigger;
111
+ run(event: WebhookEvent<Payload>, orbit: FunctionOrbit, ctx: WebhookContext): void | Promise<void>;
112
+ };
113
+ export type DelegateFunction<D extends DelegateTypes = DelegateTypes, Output = unknown> = {
114
+ trigger: DelegateTrigger;
115
+ run(body: D["body"], orbit: FunctionOrbit, ctx: DelegateContext<D["context"]>): Output | Promise<Output>;
116
+ };
117
+ export declare function defineFunction<Input = unknown, Output = unknown>(def: ActionFunction<Input, Output>): ActionFunction<Input, Output>;
118
+ export declare function defineFunction<Payload = any>(def: WebhookFunction<Payload>): WebhookFunction<Payload>;
119
+ export declare function defineFunction<D extends DelegateTypes, Output = unknown>(def: DelegateFunction<D, Output>): DelegateFunction<D, Output>;
120
+ export declare class OrbitFunctionError extends Error {
121
+ readonly code: string;
122
+ constructor(code: string, message: string);
123
+ }
124
+ export type DispatchRequest = {
125
+ v: 1;
126
+ fn: string;
127
+ kind: "action" | "connection_webhook" | "delegate";
128
+ token: string;
129
+ apiBase: string;
130
+ input: unknown;
131
+ ctx: {
132
+ runId: string;
133
+ env: string;
134
+ appId: string;
135
+ caller: Caller | null;
136
+ attempt?: number;
137
+ delegate?: DelegateContext["delegate"];
138
+ org: OrbitOrg;
139
+ };
140
+ };
141
+ export type DispatchReply = {
142
+ ok: true;
143
+ value: unknown;
144
+ } | {
145
+ ok: false;
146
+ kind: "orbit" | "crash";
147
+ error: {
148
+ code: string;
149
+ message: string;
150
+ };
151
+ log?: string;
152
+ };
153
+ export declare function serve(def: ActionFunction<any, any> | WebhookFunction | DelegateFunction<any, any>, name: string): {
154
+ invoke(req: DispatchRequest): Promise<DispatchReply>;
155
+ };
package/dist/index.js ADDED
@@ -0,0 +1,229 @@
1
+ // Orbit Functions: publisher code that runs in Orbit's sandbox, never on a member's Mac. A function
2
+ // acts as the store's org. It reaches only the Orbit API, with the token of its run.
3
+ import { OrbitObjectError, typedObjects, } from "@orbit-app/web";
4
+ export { OrbitObjectError } from "@orbit-app/web";
5
+ const DELEGATE_CODES = [
6
+ "invalid",
7
+ "invalid_allow_from",
8
+ "limit_reached",
9
+ "not_declared",
10
+ "not_found",
11
+ "forbidden",
12
+ "rate_limited",
13
+ "unavailable",
14
+ ];
15
+ // The error of sign and revoke.
16
+ export class OrbitDelegateError extends Error {
17
+ code;
18
+ // One message per bad key of the context or the options, for invalid.
19
+ fields;
20
+ retryAfter;
21
+ constructor(code, message, extra = {}) {
22
+ super(message);
23
+ this.name = "OrbitDelegateError";
24
+ this.code = code;
25
+ if (extra.fields)
26
+ this.fields = extra.fields;
27
+ if (extra.retryAfter !== undefined)
28
+ this.retryAfter = extra.retryAfter;
29
+ }
30
+ }
31
+ export function defineFunction(def) {
32
+ return def;
33
+ }
34
+ const ERROR_CODE = /^[a-z0-9_]{1,64}$/;
35
+ // Throw this to give the caller a 400 with your own code. Any other throw gives function_failed,
36
+ // and the caller never sees its message or stack. The publisher reads those in the run log.
37
+ export class OrbitFunctionError extends Error {
38
+ code;
39
+ constructor(code, message) {
40
+ if (!ERROR_CODE.test(code))
41
+ throw new Error(`the error code ${code} must be 1 to 64 characters of a-z 0-9 _`);
42
+ super(message);
43
+ this.name = "OrbitFunctionError";
44
+ this.code = code;
45
+ }
46
+ }
47
+ // Turns the dispatch request into (input, orbit, ctx) and the result into JSON. It checks nothing:
48
+ // the API checks the token on each call back, and checks the reply.
49
+ export function serve(def, name) {
50
+ return {
51
+ async invoke(req) {
52
+ const crash = (message, log) => ({
53
+ ok: false,
54
+ kind: "crash",
55
+ error: { code: "function_failed", message },
56
+ ...(log !== undefined && { log }),
57
+ });
58
+ if (req?.v !== 1 || req.fn !== name)
59
+ return crash(`this bundle holds ${name}, not ${req?.fn}`);
60
+ if (def?.trigger?.type !== req.kind) {
61
+ return crash(`${name} has the trigger ${def?.trigger?.type}, but orbit.json gives ${req.kind}`);
62
+ }
63
+ // The API matched the event against orbit.json. The code must ask for the same events.
64
+ if (def.trigger.type === "connection_webhook") {
65
+ const e = req.input;
66
+ if (def.trigger.provider !== e?.provider || !def.trigger.events?.includes(e?.event)) {
67
+ return crash(`${name} does not take ${e?.provider} ${e?.event}. Its trigger in the code must match orbit.json.`);
68
+ }
69
+ }
70
+ try {
71
+ let value;
72
+ if (def.trigger.type === "action") {
73
+ const caller = req.ctx.caller;
74
+ if (!caller)
75
+ return crash("an action call has no caller");
76
+ value = await def.run(req.input, createOrbit(req), {
77
+ runId: req.ctx.runId,
78
+ env: req.ctx.env,
79
+ caller: { id: caller.id, role: caller.role },
80
+ });
81
+ }
82
+ else if (def.trigger.type === "delegate") {
83
+ const delegate = req.ctx.delegate;
84
+ if (!delegate)
85
+ return crash("a delegate call has no delegate");
86
+ value = await def.run(req.input, createOrbit(req), {
87
+ runId: req.ctx.runId,
88
+ env: req.ctx.env,
89
+ delegate: { ...delegate },
90
+ });
91
+ }
92
+ else if (def.trigger.type === "connection_webhook") {
93
+ await def.run(req.input, createOrbit(req), {
94
+ runId: req.ctx.runId,
95
+ env: req.ctx.env,
96
+ attempt: req.ctx.attempt ?? 1,
97
+ });
98
+ }
99
+ else {
100
+ // A trigger that this SDK does not know never runs as another kind.
101
+ return crash(`${name} has the unknown trigger ${String(def.trigger.type)}`);
102
+ }
103
+ // Only JSON goes back. undefined becomes null.
104
+ return { ok: true, value: value === undefined ? null : JSON.parse(JSON.stringify(value)) };
105
+ }
106
+ catch (e) {
107
+ const err = e;
108
+ // Each bundle has its own copy of this file, so check the shape, not the class.
109
+ if (err?.name === "OrbitFunctionError" && typeof err.code === "string" && ERROR_CODE.test(err.code)) {
110
+ return { ok: false, kind: "orbit", error: { code: err.code, message: String(err.message ?? "") } };
111
+ }
112
+ return crash(String(err?.message ?? e), typeof err?.stack === "string" ? err.stack : String(e));
113
+ }
114
+ },
115
+ };
116
+ }
117
+ // MARK: The client. It calls the API with the run's function token.
118
+ const OBJECT_CODES = ["not_found", "forbidden", "invalid", "conflict", "limit", "rate_limited", "unavailable"];
119
+ function createOrbit(req) {
120
+ const base = req.apiBase.replace(/\/+$/, "");
121
+ const objectError = (code, message, extra) => new OrbitObjectError(OBJECT_CODES.includes(code) ? code : "unavailable", message, extra);
122
+ const delegateError = (code, message, extra) => new OrbitDelegateError(DELEGATE_CODES.includes(code) ? code : "unavailable", message, extra);
123
+ async function call(method, path, body, fail = objectError) {
124
+ let res;
125
+ try {
126
+ res = await fetch(`${base}${path}`, {
127
+ method,
128
+ headers: {
129
+ authorization: `Bearer ${req.token}`,
130
+ ...(body !== undefined && { "content-type": "application/json" }),
131
+ },
132
+ body: body === undefined ? undefined : JSON.stringify(body),
133
+ redirect: "manual",
134
+ });
135
+ }
136
+ catch (e) {
137
+ throw fail("unavailable", `Orbit did not answer: ${String(e)}`, {});
138
+ }
139
+ if (res.status === 204)
140
+ return null;
141
+ const json = (await res.json().catch(() => null));
142
+ if (res.ok && json !== null)
143
+ return json;
144
+ throw fail(String(json?.code), typeof json?.message === "string" ? json.message : `Orbit answered ${res.status}`, {
145
+ fields: typeof json?.fields === "object" && json.fields !== null ? json.fields : undefined,
146
+ retryAfter: typeof json?.retryAfter === "number" ? json.retryAfter : undefined,
147
+ });
148
+ }
149
+ const enc = encodeURIComponent;
150
+ const objects = {
151
+ create: (input) => call("POST", "/v1/objects", input),
152
+ get: (id) => call("GET", `/v1/objects/${enc(id)}`),
153
+ getByHandle: (type, handle) => call("GET", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`),
154
+ list: (input) => call("POST", "/v1/objects/query", input),
155
+ update: (id, input) => call("PATCH", `/v1/objects/${enc(id)}`, input),
156
+ upsert: (type, handle, input = {}) => call("PUT", `/v1/objects/by-handle/${enc(type)}/${enc(handle)}`, input),
157
+ delete: async (id) => {
158
+ await call("DELETE", `/v1/objects/${enc(id)}`);
159
+ },
160
+ };
161
+ function connection(c) {
162
+ return Object.freeze({
163
+ provider: c.provider,
164
+ scopes: Object.freeze([...c.scopes]),
165
+ missingScopes: Object.freeze([...c.missingScopes]),
166
+ async fetch(rawPath, init = {}) {
167
+ const { path, query } = splitPath(rawPath);
168
+ const method = (init.method ?? "GET").toUpperCase();
169
+ const body = init.body === undefined || init.body === null
170
+ ? null
171
+ : typeof init.body === "string"
172
+ ? init.body
173
+ : { base64: toBase64(init.body) };
174
+ const reply = (await call("POST", `/v1/connections/${enc(c.provider)}/proxy`, {
175
+ method,
176
+ path,
177
+ ...(query && { query }),
178
+ headers: init.headers ?? {},
179
+ body,
180
+ owner: "org",
181
+ }));
182
+ const bytes = typeof reply.body === "string" ? reply.body : fromBase64(reply.body.base64);
183
+ const empty = [204, 205, 304].includes(reply.status) || method === "HEAD";
184
+ return new Response(empty ? null : bytes, { status: reply.status, headers: reply.headers });
185
+ },
186
+ });
187
+ }
188
+ return {
189
+ objects,
190
+ defineObjects: () => typedObjects(objects),
191
+ connections: {
192
+ async get(provider) {
193
+ const list = (await call("GET", "/v1/connections?owner=org"));
194
+ const c = list.connections.find((x) => x.provider === provider && x.status === "active");
195
+ return c ? connection(c) : null;
196
+ },
197
+ },
198
+ defineDelegates: () => ({
199
+ sign: (name, opts) => call("POST", "/v1/delegates", { name, ...opts }, delegateError),
200
+ revoke: async (id) => {
201
+ await call("DELETE", `/v1/delegates/${enc(id)}`, undefined, delegateError);
202
+ },
203
+ }),
204
+ org: () => ({ ...req.ctx.org }),
205
+ };
206
+ }
207
+ // "/users.info?user=U1" → the path and a query map, as the proxy takes them.
208
+ function splitPath(raw) {
209
+ const q = raw.indexOf("?");
210
+ if (q < 0)
211
+ return { path: raw };
212
+ const query = {};
213
+ for (const [k, v] of new URLSearchParams(raw.slice(q + 1)))
214
+ query[k] = v;
215
+ return { path: raw.slice(0, q), query };
216
+ }
217
+ function toBase64(bytes) {
218
+ let s = "";
219
+ for (const b of bytes)
220
+ s += String.fromCharCode(b);
221
+ return btoa(s);
222
+ }
223
+ function fromBase64(b64) {
224
+ const s = atob(b64);
225
+ const out = new Uint8Array(s.length);
226
+ for (let i = 0; i < s.length; i++)
227
+ out[i] = s.charCodeAt(i);
228
+ return out;
229
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@orbit-app/functions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Write Orbit Functions: publisher code that runs in Orbit's sandbox as the store's org.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "default": "./dist/index.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.build.json",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "tsc --noEmit && vitest run",
19
+ "prepack": "pnpm build"
20
+ },
21
+ "dependencies": {
22
+ "@orbit-app/web": "^0.1.0"
23
+ },
24
+ "devDependencies": {
25
+ "typescript": "^7.0.2",
26
+ "vitest": "^5.0.5"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ }
31
+ }