@colixsystems/actions-client 0.4.0 → 0.4.2

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,10 @@ 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.2` — internal: carries the newer transport the clients share, which gained options other clients use. This client's requests, retries and errors are unchanged.
14
+
15
+ `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.
16
+
13
17
  `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
18
 
15
19
  ## 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,265 @@
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 = ["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, neverRetryCodes) {
86
+ if (!err || neverRetryCodes.includes(err.code)) 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, retryAfterHeader: string | null) => Error,
147
+ * retryVerbs?: string[] | "all",
148
+ * neverRetryCodes?: string[] }} policy
149
+ * `retryVerbs` defaults to GET and HEAD. An error whose `code` is in
150
+ * `neverRetryCodes` is final.
151
+ * @returns {{ BaseError, fromResponse, withRetry }} `withRetry` is the client's public export.
152
+ */
153
+ export function defineTransportPolicy({
154
+ BaseError,
155
+ fromResponse,
156
+ retryVerbs = RETRY_VERBS,
157
+ neverRetryCodes = [],
158
+ }) {
159
+ /**
160
+ * Run `attempt` with retries: a retried verb up to `retries` (default 3)
161
+ * more times on a network failure, a 429 or a 5xx; other verbs once. Each
162
+ * attempt gets its own AbortSignal, aborted after `timeoutMs` (default
163
+ * 10 s); an attempt that timed out is not resent.
164
+ *
165
+ * @param {{ method?: string, timeoutMs?: number, retries?: number }} opts
166
+ * @param {(signal: AbortSignal) => Promise<any>} attempt
167
+ */
168
+ async function withRetry(opts, attempt) {
169
+ const method = (opts?.method || "GET").toUpperCase();
170
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
171
+ const retries = Number.isInteger(opts?.retries) ? Math.max(0, opts.retries) : BACKOFF_MS.length;
172
+ const retried = retryVerbs === "all" || retryVerbs.includes(method);
173
+ const maxAttempts = retried ? retries + 1 : 1;
174
+ for (let i = 0; ; i++) {
175
+ const outcome = await timedAttempt(attempt, timeoutMs);
176
+ if (outcome.ok) return outcome.value;
177
+ const { error } = outcome;
178
+ const hintMs = retryAfterMsByError.get(error) ?? 0;
179
+ // The server may still be working on a request we timed out.
180
+ const final = i === maxAttempts - 1 || outcome.timedOut || hintMs > MAX_RETRY_AFTER_MS;
181
+ if (final || !isRetryable(error, neverRetryCodes)) throw error;
182
+ await sleep(Math.max(BACKOFF_MS[Math.min(i, BACKOFF_MS.length - 1)], hintMs));
183
+ }
184
+ }
185
+ return { BaseError, fromResponse, withRetry };
186
+ }
187
+
188
+ /**
189
+ * Validate a client factory's options and build the request its methods call.
190
+ *
191
+ * @param {string} factory The factory name, prefixed to every option error.
192
+ * @param {object} opts The factory's options.
193
+ * @param {ReturnType<typeof defineTransportPolicy>} policy
194
+ * @param {{ namespace?: string }} [defaults] The namespace a call without one reports.
195
+ */
196
+ export function createRequester(factory, opts, policy, { namespace: defaultNamespace } = {}) {
197
+ const options = readClientOptions(factory, opts);
198
+ const { baseUrl, fetchImpl, multipartFetchImpl } = options;
199
+ const { BaseError, fromResponse, withRetry } = policy;
200
+
201
+ /**
202
+ * `body` is sent as JSON; `formData` verbatim over `multipartFetchImpl`, with
203
+ * no content-type so the runtime sets the multipart boundary.
204
+ * `responseType: "arrayBuffer"` resolves a successful response to its bytes.
205
+ * `accept` replaces the accept header after the host's headers.
206
+ */
207
+ async function request(
208
+ method,
209
+ path,
210
+ {
211
+ body,
212
+ formData,
213
+ headers: callHeaders,
214
+ namespace = defaultNamespace,
215
+ operation,
216
+ timeoutMs,
217
+ responseType = "json",
218
+ accept,
219
+ onResponse,
220
+ } = {},
221
+ ) {
222
+ const url = joinUrl(baseUrl, path);
223
+ const headers = await buildHeaders(options, {
224
+ json: body !== undefined,
225
+ headers: callHeaders,
226
+ namespace,
227
+ operation,
228
+ });
229
+ // The format this call parses outranks a host's accept header.
230
+ if (accept) headers.accept = accept;
231
+
232
+ const isMultipart = formData !== undefined;
233
+ const send = isMultipart ? multipartFetchImpl : fetchImpl;
234
+ const payload = isMultipart ? formData : body === undefined ? undefined : JSON.stringify(body);
235
+ const deadline = timeoutMs ?? (isMultipart ? MULTIPART_TIMEOUT_MS : undefined);
236
+
237
+ return withRetry({ method, timeoutMs: deadline }, async (signal) => {
238
+ let res;
239
+ let content;
240
+ // The body read can fail like the fetch, so both are classified here.
241
+ try {
242
+ res = await send(url, { method, headers, body: payload, signal });
243
+ // An error still comes back as the JSON envelope.
244
+ content =
245
+ res.ok && responseType === "arrayBuffer"
246
+ ? await res.arrayBuffer()
247
+ : parseBody(await res.text());
248
+ } catch (err) {
249
+ const reason = signal.aborted ? "request timed out" : err?.message;
250
+ throw new BaseError(`Network failure: ${reason}`, { code: "NETWORK", status: 0 });
251
+ }
252
+ if (!res.ok) {
253
+ const retryAfterHeader = res.headers?.get?.("retry-after") ?? null;
254
+ const err = fromResponse(res.status, content, retryAfterHeader);
255
+ const hintMs = res.status === 429 ? retryAfterMs(content, retryAfterHeader) : null;
256
+ if (hintMs != null) retryAfterMsByError.set(err, hintMs);
257
+ throw err;
258
+ }
259
+ onResponse?.(res);
260
+ return content;
261
+ });
262
+ }
263
+
264
+ return { request, ...options };
265
+ }
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.2",
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",