@colixsystems/actions-client 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AppStudio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @colixsystems/actions-client
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
+ Scoped client for running a workspace's **Actions** from an AppStudio app. It is a sibling of [`@colixsystems/agents-client`](../agents-client), [`@colixsystems/link-preview-client`](../link-preview-client) and the other domain clients: a standalone `fetch`-based client you instantiate with `createActionsClient({ baseUrl, getToken, getTenantId })`.
4
+
5
+ > **Why this is a package and not host code.** The web Player and the exported Expo app instantiate the *same* package. It backs `WidgetContext.actions`, and the hosts' no-code "Run action" event uses it too, so a widget run and a Button run send the identical request on both hosts. Widgets never import this package — they read `ctx.actions` through `@colixsystems/widget-sdk`.
6
+
7
+ ## What it does
8
+
9
+ An Action is a server-side script the workspace owns. The app may run one only when the workspace has allowed apps to run it. The script runs on the server, as the workspace's bound integration identity; the app sends an id and an optional input and gets back the value the script passed to `respond()`.
10
+
11
+ ## Status
12
+
13
+ `v0.1.0` — pre-publish. Not yet published to npm.
14
+
15
+ ## Public API
16
+
17
+ ```js
18
+ import {
19
+ createActionsClient,
20
+ ActionError,
21
+ ValidationError,
22
+ ForbiddenError,
23
+ NotFoundError,
24
+ RateLimitedError,
25
+ ServerError,
26
+ } from "@colixsystems/actions-client";
27
+
28
+ const actions = createActionsClient({
29
+ baseUrl: "https://api.appstudio.io/api/v1",
30
+ getToken: () => "Bearer ...",
31
+ getTenantId: () => "tenant_abc",
32
+ // Optional: per-request extra headers. Called with
33
+ // { namespace: "actions", operation: "run" } and merged in.
34
+ getRequestHeaders: ({ namespace, operation }) => ({}),
35
+ // fetchImpl defaults to globalThis.fetch.
36
+ });
37
+
38
+ const { ok, result } = await actions.run(actionId, { client_id: "c-123" });
39
+ ```
40
+
41
+ The request is `POST {baseUrl}/app-actions/:actionId/run` with `Authorization: Bearer <token>` and `x-tenant-id`. The body is `{ input }`; when `input` is omitted or `null` no body is sent. It answers `{ ok, result }`, where `result` is the value the script passed to `respond()`, or `null`.
42
+
43
+ An empty, `.` or `..` `actionId` rejects with a `TypeError` before any request. A run is **never retried**: an Action can have side effects.
44
+
45
+ ## Errors
46
+
47
+ Every failed run rejects with an `ActionError` (or a subclass) carrying `code`, `status` (0 when no HTTP answer arrived) and the error body as `details`. `code` is always a stable code: the server's `code` when it is CODE-shaped (`TOKEN_EXPIRED`), else the code for the status below, else `ACTION_FAILED`. A bare message such as `Unauthorized` never becomes the code.
48
+
49
+ | Class | Status | `code` when the server sends none |
50
+ | ----- | ------ | --------------------------------- |
51
+ | `ValidationError` | 400 | `INVALID_ACTION_INPUT` |
52
+ | `ActionError` | 401 | `AUTH_REQUIRED` — no signed-in app user (`TOKEN_EXPIRED` / `TOKEN_INVALID` when the session is dead) |
53
+ | `ForbiddenError` | 403 | `ACTION_NOT_APP_INVOKABLE` — the workspace has not allowed apps to run it |
54
+ | `NotFoundError` | 404 | `ACTION_NOT_FOUND` |
55
+ | `RateLimitedError` | 429 | `RATE_LIMITED` |
56
+ | `ServerError` | 5xx | `ACTION_FAILED` — the script failed or the server is unavailable |
57
+ | `ActionError` | 0 | `ACTION_FAILED` — offline, or no session to send; the original error is `cause` |
58
+
59
+ ## License
60
+
61
+ MIT
package/dist/client.js ADDED
@@ -0,0 +1,123 @@
1
+ // Actions client factory.
2
+ // The host injects baseUrl, a token provider, a tenant-id provider, an optional
3
+ // per-request header provider, and an optional fetch implementation. Widgets
4
+ // never touch this directly — they receive a built client through
5
+ // WidgetContext.actions. The hosts' Button "Run action" dispatch uses it too,
6
+ // so a no-code run and a widget run send the identical request.
7
+ //
8
+ // The server decides what may run: the app-user JWT plus the workspace's
9
+ // opt-in of the Action for apps. This client only carries the id and input.
10
+
11
+ import { ActionError, errorFromResponse } from "./errors.js";
12
+
13
+ const NAMESPACE = "actions";
14
+
15
+ function joinUrl(base, path) {
16
+ const b = base.endsWith("/") ? base.slice(0, -1) : base;
17
+ const p = path.startsWith("/") ? path : `/${path}`;
18
+ return `${b}${p}`;
19
+ }
20
+
21
+ /**
22
+ * @param {object} opts
23
+ * @param {string} opts.baseUrl
24
+ * @param {() => string | Promise<string>} opts.getToken Bearer token (with or without the "Bearer " prefix).
25
+ * @param {() => string | Promise<string>} opts.getTenantId Returns the x-tenant-id header value.
26
+ * @param {(ctx: { namespace: string, operation: string }) => object | Promise<object>} [opts.getRequestHeaders]
27
+ * Optional extra headers merged per request.
28
+ * @param {typeof fetch} [opts.fetchImpl] Defaults to globalThis.fetch.
29
+ */
30
+ export function createActionsClient(opts) {
31
+ if (!opts || typeof opts !== "object") {
32
+ throw new TypeError("createActionsClient: opts is required");
33
+ }
34
+ const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
35
+ if (typeof baseUrl !== "string" || baseUrl.length === 0) {
36
+ throw new TypeError("createActionsClient: baseUrl is required");
37
+ }
38
+ if (typeof getToken !== "function") {
39
+ throw new TypeError("createActionsClient: getToken must be a function");
40
+ }
41
+ if (typeof getTenantId !== "function") {
42
+ throw new TypeError("createActionsClient: getTenantId must be a function");
43
+ }
44
+ if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
45
+ throw new TypeError(
46
+ "createActionsClient: getRequestHeaders must be a function when provided",
47
+ );
48
+ }
49
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
50
+ if (typeof fetchImpl !== "function") {
51
+ throw new TypeError(
52
+ "createActionsClient: no fetch available. Pass fetchImpl or run in an environment with global fetch.",
53
+ );
54
+ }
55
+
56
+ async function post(path, body, operation) {
57
+ const token = await getToken();
58
+ const tenantId = await getTenantId();
59
+ const headers = { accept: "application/json" };
60
+ if (token)
61
+ headers.authorization = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
62
+ if (tenantId) headers["x-tenant-id"] = tenantId;
63
+ if (body !== undefined) headers["content-type"] = "application/json";
64
+ if (getRequestHeaders) {
65
+ const extra = await getRequestHeaders({ namespace: NAMESPACE, operation });
66
+ if (extra && typeof extra === "object") Object.assign(headers, extra);
67
+ }
68
+
69
+ const res = await fetchImpl(joinUrl(baseUrl, path), {
70
+ method: "POST",
71
+ headers,
72
+ body: body !== undefined ? JSON.stringify(body) : undefined,
73
+ });
74
+ const text = await res.text();
75
+ let parsed = null;
76
+ if (text.length > 0) {
77
+ try {
78
+ parsed = JSON.parse(text);
79
+ } catch {
80
+ parsed = { raw: text };
81
+ }
82
+ }
83
+ if (!res.ok) throw errorFromResponse(res.status, parsed);
84
+ return parsed;
85
+ }
86
+
87
+ return {
88
+ /**
89
+ * Run one Action and resolve to `{ ok, result }`. `result` is the value
90
+ * the script passed to `respond()` (any JSON), or null. Omit `input` (or
91
+ * pass null) to send no body. Never retried: a run can have side effects.
92
+ */
93
+ async run(actionId, input) {
94
+ // "." and ".." survive encodeURIComponent and fetch would resolve them.
95
+ if (
96
+ typeof actionId !== "string" ||
97
+ actionId.trim().length === 0 ||
98
+ actionId === "." ||
99
+ actionId === ".."
100
+ ) {
101
+ throw new TypeError("run(actionId): actionId must be a non-empty string");
102
+ }
103
+ let body;
104
+ try {
105
+ body = await post(
106
+ `/app-actions/${encodeURIComponent(actionId)}/run`,
107
+ input == null ? undefined : { input },
108
+ "run",
109
+ );
110
+ } catch (err) {
111
+ if (err instanceof ActionError) throw err;
112
+ // No HTTP answer (offline, or no session to send) keeps the generic code.
113
+ throw new ActionError(`Action request failed: ${err?.message || err}`, {
114
+ code: "ACTION_FAILED",
115
+ status: 0,
116
+ cause: err,
117
+ });
118
+ }
119
+ const src = body && typeof body === "object" ? body : {};
120
+ return { ok: src.ok === true, result: src.result === undefined ? null : src.result };
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,204 @@
1
+ // sc-13843 — @colixsystems/actions-client contract tests: the request shape,
2
+ // the auth/tenant headers, the `{ ok, result }` answer and the error codes the
3
+ // hosts forward on `appstudio:action-error`.
4
+
5
+ import assert from "node:assert/strict";
6
+ import { test } from "node:test";
7
+ import {
8
+ createActionsClient,
9
+ ActionError,
10
+ ValidationError,
11
+ ForbiddenError,
12
+ NotFoundError,
13
+ RateLimitedError,
14
+ ServerError,
15
+ errorFromResponse,
16
+ } from "./index.js";
17
+
18
+ function makeFetch(next) {
19
+ const calls = [];
20
+ const fetchImpl = async (url, init) => {
21
+ calls.push({ url, init });
22
+ if (next.throws) throw next.throws;
23
+ return {
24
+ ok: next.status >= 200 && next.status < 300,
25
+ status: next.status,
26
+ text: async () =>
27
+ next.text !== undefined
28
+ ? next.text
29
+ : next.body === undefined
30
+ ? ""
31
+ : JSON.stringify(next.body),
32
+ };
33
+ };
34
+ return { fetchImpl, calls };
35
+ }
36
+
37
+ function makeClient(fetchImpl, extra = {}) {
38
+ return createActionsClient({
39
+ baseUrl: "https://api.example.test/api/v1/",
40
+ getToken: () => "jwt-token",
41
+ getTenantId: () => "tenant-abc",
42
+ fetchImpl,
43
+ ...extra,
44
+ });
45
+ }
46
+
47
+ test("run posts { input } to the encoded app-action path with auth headers", async () => {
48
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true, result: { n: 1 } } });
49
+ const out = await makeClient(fetchImpl).run("act/1 ä", { slot: 3 });
50
+
51
+ assert.equal(calls.length, 1);
52
+ assert.equal(
53
+ calls[0].url,
54
+ `https://api.example.test/api/v1/app-actions/${encodeURIComponent("act/1 ä")}/run`,
55
+ );
56
+ assert.equal(calls[0].init.method, "POST");
57
+ assert.deepEqual(JSON.parse(calls[0].init.body), { input: { slot: 3 } });
58
+ assert.equal(calls[0].init.headers.authorization, "Bearer jwt-token");
59
+ assert.equal(calls[0].init.headers["x-tenant-id"], "tenant-abc");
60
+ assert.equal(calls[0].init.headers["content-type"], "application/json");
61
+ assert.deepEqual(out, { ok: true, result: { n: 1 } });
62
+ });
63
+
64
+ test("run with no input (or null) sends no body", async () => {
65
+ for (const input of [undefined, null]) {
66
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true, result: null } });
67
+ await makeClient(fetchImpl).run("act-1", input);
68
+ assert.equal(calls[0].init.body, undefined);
69
+ assert.equal(calls[0].init.headers["content-type"], undefined);
70
+ }
71
+ });
72
+
73
+ test("a token that already carries Bearer is not doubled", async () => {
74
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true, result: 1 } });
75
+ await makeClient(fetchImpl, { getToken: () => "Bearer abc" }).run("act-1");
76
+ assert.equal(calls[0].init.headers.authorization, "Bearer abc");
77
+ });
78
+
79
+ test("getRequestHeaders is asked with the actions namespace and merged", async () => {
80
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true, result: 1 } });
81
+ const seen = [];
82
+ await makeClient(fetchImpl, {
83
+ getRequestHeaders: (ctx) => {
84
+ seen.push(ctx);
85
+ return { "x-extra": "1" };
86
+ },
87
+ }).run("act-1");
88
+ assert.deepEqual(seen, [{ namespace: "actions", operation: "run" }]);
89
+ assert.equal(calls[0].init.headers["x-extra"], "1");
90
+ });
91
+
92
+ test("the answer is normalised to { ok, result } with a null result by default", async () => {
93
+ const { fetchImpl } = makeFetch({ status: 200, body: { ok: false } });
94
+ assert.deepEqual(await makeClient(fetchImpl).run("act-1"), { ok: false, result: null });
95
+ const empty = makeFetch({ status: 200 });
96
+ assert.deepEqual(await makeClient(empty.fetchImpl).run("act-1"), { ok: false, result: null });
97
+ });
98
+
99
+ test("an empty or blank id rejects without a request", async () => {
100
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true } });
101
+ const client = makeClient(fetchImpl);
102
+ for (const id of ["", " ", ".", "..", undefined, 42]) {
103
+ await assert.rejects(() => client.run(id), TypeError);
104
+ }
105
+ assert.equal(calls.length, 0);
106
+ });
107
+
108
+ test("each status maps to its typed error with the envelope's code", async () => {
109
+ const cases = [
110
+ [400, "INVALID_ACTION_INPUT", ValidationError],
111
+ [401, "TOKEN_EXPIRED", ActionError],
112
+ [403, "ACTION_NOT_APP_INVOKABLE", ForbiddenError],
113
+ [404, "ACTION_NOT_FOUND", NotFoundError],
114
+ [429, "RATE_LIMITED", RateLimitedError],
115
+ [500, "ACTION_SCRIPT_FAILED", ServerError],
116
+ ];
117
+ for (const [status, code, Klass] of cases) {
118
+ const { fetchImpl } = makeFetch({
119
+ status,
120
+ body: { statusCode: status, message: "Nope", code },
121
+ });
122
+ const err = await makeClient(fetchImpl).run("act-1").catch((e) => e);
123
+ assert.ok(err instanceof Klass, `${status} → ${Klass.name}`);
124
+ assert.ok(err instanceof ActionError);
125
+ assert.equal(err.code, code);
126
+ assert.equal(err.status, status);
127
+ assert.equal(err.message, "Nope");
128
+ }
129
+ });
130
+
131
+ test("a missing or message-shaped code becomes the status's stable code", () => {
132
+ const cases = [
133
+ [400, { message: "Tenant ID required" }, "INVALID_ACTION_INPUT"],
134
+ [401, { message: "Unauthorized" }, "AUTH_REQUIRED"],
135
+ [401, null, "AUTH_REQUIRED"],
136
+ [403, { message: "Not allowed", code: "Not allowed" }, "ACTION_NOT_APP_INVOKABLE"],
137
+ [404, { message: "ACTION_NOT_FOUND" }, "ACTION_NOT_FOUND"],
138
+ [429, { message: "Too many requests" }, "RATE_LIMITED"],
139
+ [500, { message: "Internal Server Error" }, "ACTION_FAILED"],
140
+ [502, { raw: "<html>" }, "ACTION_FAILED"],
141
+ [500, null, "ACTION_FAILED"],
142
+ [418, { code: "teapot" }, "ACTION_FAILED"],
143
+ ];
144
+ for (const [status, body, code] of cases) {
145
+ assert.equal(errorFromResponse(status, body).code, code, `${status} ${JSON.stringify(body)}`);
146
+ }
147
+ assert.equal(errorFromResponse(401, { message: "Unauthorized" }).message, "Unauthorized");
148
+ assert.equal(errorFromResponse(500, null).message, "ACTION_FAILED");
149
+ });
150
+
151
+ test("a bodyless 401 rejects AUTH_REQUIRED", async () => {
152
+ const { fetchImpl } = makeFetch({ status: 401 });
153
+ const err = await makeClient(fetchImpl).run("act-1").catch((e) => e);
154
+ assert.ok(err instanceof ActionError);
155
+ assert.equal(err.code, "AUTH_REQUIRED");
156
+ assert.equal(err.status, 401);
157
+ });
158
+
159
+ test("a non-JSON error body still rejects with ACTION_FAILED", async () => {
160
+ const { fetchImpl } = makeFetch({ status: 502, text: "Bad gateway" });
161
+ const err = await makeClient(fetchImpl).run("act-1").catch((e) => e);
162
+ assert.ok(err instanceof ServerError);
163
+ assert.equal(err.code, "ACTION_FAILED");
164
+ assert.equal(err.status, 502);
165
+ });
166
+
167
+ test("a network failure or a token provider failure rejects as ACTION_FAILED", async () => {
168
+ const offline = makeFetch({ throws: new TypeError("Failed to fetch") });
169
+ const err = await makeClient(offline.fetchImpl).run("act-1").catch((e) => e);
170
+ assert.ok(err instanceof ActionError);
171
+ assert.equal(err.code, "ACTION_FAILED");
172
+ assert.equal(err.status, 0);
173
+
174
+ const sessionErr = Object.assign(new Error("Sign in again"), { code: "SESSION_UNAVAILABLE" });
175
+ const { fetchImpl, calls } = makeFetch({ status: 200, body: { ok: true } });
176
+ const err2 = await makeClient(fetchImpl, {
177
+ getToken: () => {
178
+ throw sessionErr;
179
+ },
180
+ })
181
+ .run("act-1")
182
+ .catch((e) => e);
183
+ assert.equal(err2.code, "ACTION_FAILED");
184
+ assert.equal(err2.cause, sessionErr);
185
+ assert.equal(calls.length, 0);
186
+ });
187
+
188
+ test("a failed run is never retried", async () => {
189
+ const { fetchImpl, calls } = makeFetch({ status: 503, body: { code: "BUSY" } });
190
+ await assert.rejects(() => makeClient(fetchImpl).run("act-1"));
191
+ assert.equal(calls.length, 1);
192
+ });
193
+
194
+ test("the factory validates its providers", () => {
195
+ assert.throws(() => createActionsClient(), TypeError);
196
+ assert.throws(
197
+ () => createActionsClient({ baseUrl: "", getToken: () => "", getTenantId: () => "" }),
198
+ TypeError,
199
+ );
200
+ assert.throws(
201
+ () => createActionsClient({ baseUrl: "/api", getToken: "x", getTenantId: () => "" }),
202
+ TypeError,
203
+ );
204
+ });
package/dist/errors.js ADDED
@@ -0,0 +1,95 @@
1
+ // Typed error hierarchy for the actions client.
2
+ // Each subclass carries .code, .status and .details. This module is the one
3
+ // owner of the stable `code`: the server envelope's `code` when it is
4
+ // CODE-shaped, else the code for the HTTP status, else "ACTION_FAILED". The
5
+ // hosts put it on `appstudio:action-error` and useAction surfaces it as is.
6
+
7
+ export class ActionError extends Error {
8
+ constructor(
9
+ message,
10
+ { code = "ACTION_FAILED", status = 0, details = null, cause = undefined } = {},
11
+ ) {
12
+ super(message);
13
+ this.name = "ActionError";
14
+ this.code = code;
15
+ this.status = status;
16
+ this.details = details;
17
+ if (cause !== undefined) this.cause = cause;
18
+ }
19
+ }
20
+
21
+ // 400 — INVALID_ACTION_INPUT: the input is not plain JSON within the limits,
22
+ // or the Action's own input check refused it.
23
+ export class ValidationError extends ActionError {
24
+ constructor(message = "Invalid action input", code = "INVALID_ACTION_INPUT", details = null) {
25
+ super(message, { code, status: 400, details });
26
+ this.name = "ValidationError";
27
+ }
28
+ }
29
+
30
+ // 403 — ACTION_NOT_APP_INVOKABLE: the workspace has not let the app run it.
31
+ export class ForbiddenError extends ActionError {
32
+ constructor(message = "Forbidden", code = "ACTION_NOT_APP_INVOKABLE", details = null) {
33
+ super(message, { code, status: 403, details });
34
+ this.name = "ForbiddenError";
35
+ }
36
+ }
37
+
38
+ // 404 — ACTION_NOT_FOUND: no such Action in this workspace.
39
+ export class NotFoundError extends ActionError {
40
+ constructor(message = "Not found", code = "ACTION_NOT_FOUND", details = null) {
41
+ super(message, { code, status: 404, details });
42
+ this.name = "NotFoundError";
43
+ }
44
+ }
45
+
46
+ export class RateLimitedError extends ActionError {
47
+ constructor(message = "Rate limited", code = "RATE_LIMITED", details = null) {
48
+ super(message, { code, status: 429, details });
49
+ this.name = "RateLimitedError";
50
+ }
51
+ }
52
+
53
+ export class ServerError extends ActionError {
54
+ constructor(message = "Server error", code = "ACTION_FAILED", status = 500, details = null) {
55
+ super(message, { code, status, details });
56
+ this.name = "ServerError";
57
+ }
58
+ }
59
+
60
+ const CODE_SHAPED = /^[A-Z][A-Z0-9_]+$/;
61
+
62
+ const CODE_BY_STATUS = {
63
+ 400: "INVALID_ACTION_INPUT",
64
+ 401: "AUTH_REQUIRED",
65
+ 403: "ACTION_NOT_APP_INVOKABLE",
66
+ 404: "ACTION_NOT_FOUND",
67
+ 429: "RATE_LIMITED",
68
+ };
69
+
70
+ /**
71
+ * Map an HTTP status + the house error envelope `{ statusCode, message, code }`
72
+ * to the matching ActionError subclass.
73
+ */
74
+ export function errorFromResponse(status, body) {
75
+ const details = body && typeof body === "object" ? body : null;
76
+ const envelopeCode = details && typeof details.code === "string" ? details.code : "";
77
+ // A bare `{ message: "Unauthorized" }` must not become a widget's code.
78
+ const code = CODE_SHAPED.test(envelopeCode)
79
+ ? envelopeCode
80
+ : CODE_BY_STATUS[status] || "ACTION_FAILED";
81
+ const message = (details && typeof details.message === "string" && details.message) || code;
82
+ switch (status) {
83
+ case 400:
84
+ return new ValidationError(message, code, details);
85
+ case 403:
86
+ return new ForbiddenError(message, code, details);
87
+ case 404:
88
+ return new NotFoundError(message, code, details);
89
+ case 429:
90
+ return new RateLimitedError(message, code, details);
91
+ default:
92
+ if (status >= 500) return new ServerError(message, code, status, details);
93
+ return new ActionError(message, { code, status, details });
94
+ }
95
+ }
@@ -0,0 +1,57 @@
1
+ // Hand-written ambient types for @colixsystems/actions-client.
2
+ // The package is plain ESM JavaScript; this file is shipped for IDE
3
+ // IntelliSense. Keep in sync with src/index.js when adding exports.
4
+
5
+ /** What one run answers. `result` is the value the script passed to `respond()`, or null. */
6
+ export interface ActionRunResult {
7
+ ok: boolean;
8
+ result: unknown;
9
+ }
10
+
11
+ export interface ActionsClient {
12
+ /**
13
+ * POST /app-actions/:actionId/run. Omit `input` (or pass null) to send no body.
14
+ * An empty, ".", or ".." id rejects with a TypeError before any request.
15
+ */
16
+ run(actionId: string, input?: Record<string, unknown> | null): Promise<ActionRunResult>;
17
+ }
18
+
19
+ export interface RequestHeaderContext {
20
+ namespace: string;
21
+ operation: string;
22
+ }
23
+
24
+ export interface CreateActionsClientOptions {
25
+ baseUrl: string;
26
+ getToken: () => string | Promise<string>;
27
+ getTenantId: () => string | Promise<string>;
28
+ getRequestHeaders?: (
29
+ ctx: RequestHeaderContext,
30
+ ) => Record<string, string> | Promise<Record<string, string>>;
31
+ fetchImpl?: typeof fetch;
32
+ }
33
+
34
+ export function createActionsClient(opts: CreateActionsClientOptions): ActionsClient;
35
+
36
+ export class ActionError extends Error {
37
+ /**
38
+ * The server's `code` when CODE-shaped, else the status's code
39
+ * (400 INVALID_ACTION_INPUT, 401 AUTH_REQUIRED, 403 ACTION_NOT_APP_INVOKABLE,
40
+ * 404 ACTION_NOT_FOUND, 429 RATE_LIMITED), else "ACTION_FAILED".
41
+ */
42
+ code: string;
43
+ /** The HTTP status; 0 when no HTTP answer arrived. */
44
+ status: number;
45
+ details: unknown;
46
+ constructor(
47
+ message: string,
48
+ init?: { code?: string; status?: number; details?: unknown; cause?: unknown },
49
+ );
50
+ }
51
+ export class ValidationError extends ActionError {}
52
+ export class ForbiddenError extends ActionError {}
53
+ export class NotFoundError extends ActionError {}
54
+ export class RateLimitedError extends ActionError {}
55
+ export class ServerError extends ActionError {}
56
+
57
+ export function errorFromResponse(status: number, body: unknown): ActionError;
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ // Public entry for @colixsystems/actions-client.
2
+
3
+ export { createActionsClient } from "./client.js";
4
+ export {
5
+ ActionError,
6
+ ValidationError,
7
+ ForbiddenError,
8
+ NotFoundError,
9
+ RateLimitedError,
10
+ ServerError,
11
+ errorFromResponse,
12
+ } from "./errors.js";
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@colixsystems/actions-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Scoped client for running a workspace's Actions from an AppStudio app. Used by widgets through the injected WidgetContext.actions.",
5
+ "homepage": "https://github.com/Colix-AB/AppStudio",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "scripts": {
23
+ "build": "node scripts/build.js",
24
+ "test": "node --test src/*.test.js"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "keywords": [
34
+ "appstudio",
35
+ "actions",
36
+ "client"
37
+ ],
38
+ "license": "MIT"
39
+ }