@colixsystems/actions-client 0.4.0 → 0.4.1

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
@@ -10,6 +10,8 @@ An Action is a server-side script the workspace owns. The app may run one only w
10
10
 
11
11
  ## Status
12
12
 
13
+ `v0.4.1` — the factory option checks, URL joining and request headers now come from the transport the clients share. Two small changes: a `getRequestHeaders` value of `null` or `undefined` is no longer sent as the text "null", and a `multipartFetchImpl` option that is not a function is now refused with a `TypeError`, as in the other clients. No export or request shape changed.
14
+
13
15
  `v0.4.0` — adds `enqueue`, which queues an Action run instead of waiting for it. `v0.3.0` added `createConnectorsClient`, which calls a workspace's REST connectors through the operations it listed for apps.
14
16
 
15
17
  ## Public API
package/dist/client.js CHANGED
@@ -9,15 +9,10 @@
9
9
  // opt-in of the Action for apps. This client only carries the id and input.
10
10
 
11
11
  import { ActionError, errorFromResponse } from "./errors.js";
12
+ import { buildHeaders, joinUrl, readClientOptions } from "./transport.js";
12
13
 
13
14
  const NAMESPACE = "actions";
14
15
 
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
16
  /**
22
17
  * @param {object} opts
23
18
  * @param {string} opts.baseUrl
@@ -32,43 +27,16 @@ function joinUrl(base, path) {
32
27
  * @returns the `send(method, path, body, operation)` both clients use.
33
28
  */
34
29
  export function createSender(opts, factory, namespace, toError) {
35
- if (!opts || typeof opts !== "object") {
36
- throw new TypeError(`${factory}: opts is required`);
37
- }
38
- const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
39
- if (typeof baseUrl !== "string" || baseUrl.length === 0) {
40
- throw new TypeError(`${factory}: baseUrl is required`);
41
- }
42
- if (typeof getToken !== "function") {
43
- throw new TypeError(`${factory}: getToken must be a function`);
44
- }
45
- if (typeof getTenantId !== "function") {
46
- throw new TypeError(`${factory}: getTenantId must be a function`);
47
- }
48
- if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
49
- throw new TypeError(
50
- `${factory}: getRequestHeaders must be a function when provided`,
51
- );
52
- }
53
- const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
54
- if (typeof fetchImpl !== "function") {
55
- throw new TypeError(
56
- `${factory}: no fetch available. Pass fetchImpl or run in an environment with global fetch.`,
57
- );
58
- }
30
+ const { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl } = readClientOptions(
31
+ factory,
32
+ opts,
33
+ );
59
34
 
60
35
  async function send(method, path, body, operation) {
61
- const token = await getToken();
62
- const tenantId = await getTenantId();
63
- const headers = { accept: "application/json" };
64
- if (token)
65
- headers.authorization = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
66
- if (tenantId) headers["x-tenant-id"] = tenantId;
67
- if (body !== undefined) headers["content-type"] = "application/json";
68
- if (getRequestHeaders) {
69
- const extra = await getRequestHeaders({ namespace, operation });
70
- if (extra && typeof extra === "object") Object.assign(headers, extra);
71
- }
36
+ const headers = await buildHeaders(
37
+ { getToken, getTenantId, getRequestHeaders },
38
+ { json: body !== undefined, namespace, operation },
39
+ );
72
40
 
73
41
  const res = await fetchImpl(joinUrl(baseUrl, path), {
74
42
  method,
@@ -0,0 +1,245 @@
1
+ // The one HTTP transport of the @colixsystems/*-client packages.
2
+ //
3
+ // Each client imports it through a one-line shim, `src/transport.js`, and
4
+ // its build copies this file over `dist/transport.js`. A published client
5
+ // therefore still ships with zero runtime dependencies, and the transport it
6
+ // carries is the one it was tested with. This file must import nothing; the
7
+ // build asserts that.
8
+ //
9
+ // Error classes stay in each client (`errors.js`): they are its published
10
+ // contract. A client declares its policy once, in its `retry.js`.
11
+
12
+ const DEFAULT_TIMEOUT_MS = 10_000;
13
+ // An upload lasts as long as the file takes to cross a mobile link.
14
+ const MULTIPART_TIMEOUT_MS = 5 * 60_000;
15
+ const BACKOFF_MS = [200, 400, 800];
16
+ const RETRY_VERBS = new Set(["GET", "HEAD"]);
17
+ // A longer server hint surfaces the 429 at once instead of hanging a widget.
18
+ const MAX_RETRY_AFTER_MS = DEFAULT_TIMEOUT_MS;
19
+
20
+ // Kept off the error object, so no client's errors gain a public field.
21
+ const retryAfterMsByError = new WeakMap();
22
+
23
+ export function joinUrl(base, path) {
24
+ const b = base.endsWith("/") ? base.slice(0, -1) : base;
25
+ const p = path.startsWith("/") ? path : `/${path}`;
26
+ return `${b}${p}`;
27
+ }
28
+
29
+ /**
30
+ * Today's `createXClient` option checks, each message prefixed `${factory}: `.
31
+ * `multipartFetchImpl` defaults to `fetchImpl` and is checked only when given.
32
+ */
33
+ export function readClientOptions(factory, opts) {
34
+ if (!opts || typeof opts !== "object") {
35
+ throw new TypeError(`${factory}: opts is required`);
36
+ }
37
+ const { baseUrl, getToken, getTenantId, getRequestHeaders } = opts;
38
+ if (typeof baseUrl !== "string" || baseUrl.length === 0) {
39
+ throw new TypeError(`${factory}: baseUrl is required`);
40
+ }
41
+ if (typeof getToken !== "function") {
42
+ throw new TypeError(`${factory}: getToken must be a function`);
43
+ }
44
+ if (typeof getTenantId !== "function") {
45
+ throw new TypeError(`${factory}: getTenantId must be a function`);
46
+ }
47
+ if (getRequestHeaders !== undefined && typeof getRequestHeaders !== "function") {
48
+ throw new TypeError(`${factory}: getRequestHeaders must be a function when provided`);
49
+ }
50
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
51
+ if (typeof fetchImpl !== "function") {
52
+ throw new TypeError(
53
+ `${factory}: no fetch available. Pass fetchImpl or run in an environment with global fetch.`,
54
+ );
55
+ }
56
+ const multipartFetchImpl = opts.multipartFetchImpl ?? fetchImpl;
57
+ if (typeof multipartFetchImpl !== "function") {
58
+ throw new TypeError(`${factory}: multipartFetchImpl must be a function when provided`);
59
+ }
60
+ return { baseUrl, getToken, getTenantId, getRequestHeaders, fetchImpl, multipartFetchImpl };
61
+ }
62
+
63
+ function sleep(ms) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+
67
+ function secondsToMs(value) {
68
+ const seconds = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
69
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0
70
+ ? seconds * 1000
71
+ : null;
72
+ }
73
+
74
+ // Body first: a cross-origin web Player cannot read the header, native can.
75
+ function retryAfterMs(body, header) {
76
+ const fromBody = secondsToMs(body?.retry_after);
77
+ if (fromBody != null) return fromBody;
78
+ if (typeof header !== "string" || header.trim() === "") return null;
79
+ const fromSeconds = secondsToMs(header);
80
+ if (fromSeconds != null) return fromSeconds;
81
+ const at = Date.parse(header);
82
+ return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
83
+ }
84
+
85
+ function isRetryable(err) {
86
+ if (!err) return false;
87
+ if (err.code === "NETWORK" || err.status === 429 || err.status >= 500) return true;
88
+ // A caller's own `withRetry` attempt may reject with fetch's raw TypeError.
89
+ // A raw AbortError is a caller's cancel, which must stay final.
90
+ return err.name === "TypeError";
91
+ }
92
+
93
+ /**
94
+ * The headers a client request carries, in order: accept, the Bearer token and
95
+ * the tenant when there are any, JSON content-type, the call's own headers,
96
+ * then the host's `getRequestHeaders` result without null or undefined values.
97
+ */
98
+ export async function buildHeaders(
99
+ { getToken, getTenantId, getRequestHeaders },
100
+ { json = false, headers: callHeaders, namespace, operation } = {},
101
+ ) {
102
+ const token = await getToken();
103
+ const tenantId = await getTenantId();
104
+ const headers = { accept: "application/json" };
105
+ if (token) headers.authorization = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
106
+ if (tenantId) headers["x-tenant-id"] = tenantId;
107
+ if (json) headers["content-type"] = "application/json";
108
+ Object.assign(headers, callHeaders);
109
+ // The host's headers win: they carry the widget's capability token.
110
+ const extra = getRequestHeaders ? await getRequestHeaders({ namespace, operation }) : null;
111
+ if (extra && typeof extra === "object") {
112
+ for (const [key, value] of Object.entries(extra)) {
113
+ if (value != null) headers[key] = value;
114
+ }
115
+ }
116
+ return headers;
117
+ }
118
+
119
+ // One attempt under its own timer. `timedOut` says the timer, not the
120
+ // attempt, ended it.
121
+ async function timedAttempt(attempt, timeoutMs) {
122
+ const controller = new AbortController();
123
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
124
+ try {
125
+ return { ok: true, value: await attempt(controller.signal) };
126
+ } catch (error) {
127
+ return { ok: false, error, timedOut: controller.signal.aborted };
128
+ } finally {
129
+ clearTimeout(timer);
130
+ }
131
+ }
132
+
133
+ function parseBody(text) {
134
+ if (text.length === 0) return null;
135
+ try {
136
+ return JSON.parse(text);
137
+ } catch {
138
+ return { raw: text };
139
+ }
140
+ }
141
+
142
+ /**
143
+ * One client's retry contract.
144
+ *
145
+ * @param {{ BaseError: new (message: string, init: { code: string, status: number }) => Error,
146
+ * fromResponse: (status: number, body: unknown) => Error }} policy
147
+ * @returns {{ BaseError, fromResponse, withRetry }} `withRetry` is the client's public export.
148
+ */
149
+ export function defineTransportPolicy({ BaseError, fromResponse }) {
150
+ /**
151
+ * Run `attempt` with retries: GET and HEAD up to 3 more times on a network
152
+ * failure, a 429 or a 5xx; other verbs once. Each attempt gets its own
153
+ * AbortSignal, aborted after `timeoutMs` (default 10 s); an attempt that
154
+ * timed out is not resent.
155
+ *
156
+ * @param {{ method?: string, timeoutMs?: number }} opts
157
+ * @param {(signal: AbortSignal) => Promise<any>} attempt
158
+ */
159
+ async function withRetry(opts, attempt) {
160
+ const method = (opts?.method || "GET").toUpperCase();
161
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
162
+ const maxAttempts = RETRY_VERBS.has(method) ? BACKOFF_MS.length + 1 : 1;
163
+ for (let i = 0; ; i++) {
164
+ const outcome = await timedAttempt(attempt, timeoutMs);
165
+ if (outcome.ok) return outcome.value;
166
+ const { error } = outcome;
167
+ const hintMs = retryAfterMsByError.get(error) ?? 0;
168
+ // The server may still be working on a request we timed out.
169
+ const final = i === maxAttempts - 1 || outcome.timedOut || hintMs > MAX_RETRY_AFTER_MS;
170
+ if (final || !isRetryable(error)) throw error;
171
+ await sleep(Math.max(BACKOFF_MS[i], hintMs));
172
+ }
173
+ }
174
+ return { BaseError, fromResponse, withRetry };
175
+ }
176
+
177
+ /**
178
+ * Validate a client factory's options and build the request its methods call.
179
+ *
180
+ * @param {string} factory The factory name, prefixed to every option error.
181
+ * @param {object} opts The factory's options.
182
+ * @param {ReturnType<typeof defineTransportPolicy>} policy
183
+ * @param {{ namespace?: string }} [defaults] The namespace a call without one reports.
184
+ */
185
+ export function createRequester(factory, opts, policy, { namespace: defaultNamespace } = {}) {
186
+ const options = readClientOptions(factory, opts);
187
+ const { baseUrl, fetchImpl, multipartFetchImpl } = options;
188
+ const { BaseError, fromResponse, withRetry } = policy;
189
+
190
+ /**
191
+ * `body` is sent as JSON; `formData` verbatim over `multipartFetchImpl`, with
192
+ * no content-type so the runtime sets the multipart boundary.
193
+ */
194
+ async function request(
195
+ method,
196
+ path,
197
+ {
198
+ body,
199
+ formData,
200
+ headers: callHeaders,
201
+ namespace = defaultNamespace,
202
+ operation,
203
+ timeoutMs,
204
+ onResponse,
205
+ } = {},
206
+ ) {
207
+ const url = joinUrl(baseUrl, path);
208
+ const headers = await buildHeaders(options, {
209
+ json: body !== undefined,
210
+ headers: callHeaders,
211
+ namespace,
212
+ operation,
213
+ });
214
+
215
+ const isMultipart = formData !== undefined;
216
+ const send = isMultipart ? multipartFetchImpl : fetchImpl;
217
+ const payload = isMultipart ? formData : body === undefined ? undefined : JSON.stringify(body);
218
+ const deadline = timeoutMs ?? (isMultipart ? MULTIPART_TIMEOUT_MS : undefined);
219
+
220
+ return withRetry({ method, timeoutMs: deadline }, async (signal) => {
221
+ let res;
222
+ let text;
223
+ // The body read can fail like the fetch, so both are classified here.
224
+ try {
225
+ res = await send(url, { method, headers, body: payload, signal });
226
+ text = await res.text();
227
+ } catch (err) {
228
+ const reason = signal.aborted ? "request timed out" : err?.message;
229
+ throw new BaseError(`Network failure: ${reason}`, { code: "NETWORK", status: 0 });
230
+ }
231
+ const parsed = parseBody(text);
232
+ if (!res.ok) {
233
+ const err = fromResponse(res.status, parsed);
234
+ const hintMs =
235
+ res.status === 429 ? retryAfterMs(parsed, res.headers?.get?.("retry-after")) : null;
236
+ if (hintMs != null) retryAfterMsByError.set(err, hintMs);
237
+ throw err;
238
+ }
239
+ onResponse?.(res);
240
+ return parsed;
241
+ });
242
+ }
243
+
244
+ return { request, ...options };
245
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/actions-client",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Scoped clients for running a workspace's Actions and calling its REST connectors from an AppStudio app. Used by widgets through the injected WidgetContext.actions and WidgetContext.connectors.",
5
5
  "homepage": "https://github.com/Colix-AB/AppStudio",
6
6
  "type": "module",