zitejs 0.10.0-start.24 → 0.10.0-start.26

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 (36) hide show
  1. package/dist/cjs/dev/signin.d.ts +2 -2
  2. package/dist/cjs/dev/signin.js +5 -5
  3. package/dist/cjs/start/provider.d.ts +8 -6
  4. package/dist/cjs/start/provider.js +98 -37
  5. package/dist/cjs/start/types.d.ts +54 -10
  6. package/dist/esm/dev/signin.d.ts +2 -2
  7. package/dist/esm/dev/signin.js +6 -6
  8. package/dist/esm/signin/conformance.js +1 -1
  9. package/dist/esm/signin/keys.d.ts +3 -7
  10. package/dist/esm/signin/keys.js +4 -10
  11. package/dist/esm/start/direct.d.ts +3 -3
  12. package/dist/esm/start/direct.js +14 -16
  13. package/dist/esm/start/index.d.ts +1 -1
  14. package/dist/esm/start/pageHead.d.ts +3 -3
  15. package/dist/esm/start/pageHead.js +3 -8
  16. package/dist/esm/start/provider.d.ts +8 -6
  17. package/dist/esm/start/provider.js +96 -35
  18. package/dist/esm/start/sdk/axios.d.ts +76 -0
  19. package/dist/esm/start/sdk/axios.js +210 -0
  20. package/dist/esm/start/sdk/nodeFetch.d.ts +41 -0
  21. package/dist/esm/start/sdk/nodeFetch.js +33 -0
  22. package/dist/esm/start/sdk/undici.d.ts +34 -0
  23. package/dist/esm/start/sdk/undici.js +18 -0
  24. package/dist/esm/start/sdkPatches.d.ts +22 -0
  25. package/dist/esm/start/sdkPatches.js +359 -0
  26. package/dist/esm/start/server.d.ts +3 -3
  27. package/dist/esm/start/server.js +17 -18
  28. package/dist/esm/start/types.d.ts +54 -10
  29. package/dist/esm/start/version.d.ts +1 -1
  30. package/dist/esm/start/version.js +1 -1
  31. package/dist/esm/start/vite.js +2 -0
  32. package/package.json +2 -1
  33. package/dist/cjs/internal/appToken.d.ts +0 -17
  34. package/dist/cjs/internal/appToken.js +0 -26
  35. package/dist/esm/internal/appToken.d.ts +0 -17
  36. package/dist/esm/internal/appToken.js +0 -22
@@ -1,15 +1,11 @@
1
- // The platform's part of every page's head: its runtime, the badge and analytics config, an installable app's manifest,
2
- // the metadata the app's settings set, and what the app's own head() leaves out. Isomorphic: head() runs on the server and again in the browser.
3
- import { appTokenClaims } from "../internal/appToken.js";
4
1
  /** Where the runtime posts a page's analytics: its `endpointUrl` and then its own path. */
5
2
  export const ANALYTICS_PATH = "/__zite/public/zite/analytics";
6
3
  const ANALYTICS_ENDPOINT = "/__zite";
7
4
  /** Served by the platform when the app is installable. */
8
5
  const MANIFEST_PATH = "/manifest.webmanifest";
9
- /** For one request: the plan its host sent, the badge its token carries, and analytics on a live page. */
6
+ /** For one request: the plan its host sent, the badge its org's plan shows, and analytics on a live page. */
10
7
  export const platformHeadOf = (page, request) => {
11
8
  const { plan } = page;
12
- const claims = request.token ? appTokenClaims(request.token) : undefined;
13
9
  const image = plan.seoImage ?? plan.image;
14
10
  return {
15
11
  title: plan.seoTitle ?? plan.fallbackTitle,
@@ -26,10 +22,9 @@ export const platformHeadOf = (page, request) => {
26
22
  ...(plan.manifest && { manifest: { themeColor: plan.manifest.theme_color, shortName: plan.manifest.short_name } }),
27
23
  ...(page.runtimeUrl && { runtimeUrl: page.runtimeUrl }),
28
24
  ...(page.demo && { demo: { listingSlug: page.demo.listingSlug, listingUrl: page.demo.listingUrl } }),
29
- // As the host decided before it read the org's plan, when there's no token to say.
30
- branding: claims?.branding ?? true,
25
+ branding: request.context.showZiteBadge,
31
26
  analytics: {
32
- appId: claims?.app ?? "",
27
+ appId: request.context.appId,
33
28
  // Previews are the builder's own visits; demos aren't the app's.
34
29
  enabled: request.mode === "live",
35
30
  endpointUrl: `${new URL(request.url).origin}${ANALYTICS_ENDPOINT}`,
@@ -1,5 +1,4 @@
1
- import { type AppTokenClaims } from "../internal/appToken.js";
2
- import type { HostMode, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
1
+ import type { AppContext, ExpiringToken, HostProps, PlatformProvider, PlatformUrls } from "./types.js";
3
2
  export declare const ziteProvider: (props: HostProps) => PlatformProvider;
4
3
  /** What `local` reads, documented in `zitejs`'s help. */
5
4
  export declare const LOCAL_ENV: {
@@ -11,11 +10,14 @@ export declare const LOCAL_ENV: {
11
10
  type Env = Record<string, string | undefined>;
12
11
  /** `ZITE_URLS`, or a throw saying what it must name. */
13
12
  export declare const localUrls: (raw: string | undefined) => PlatformUrls;
14
- /** The mode a dev token names; preview for one it doesn't. */
15
- export declare const localModeOf: (claims: AppTokenClaims | undefined) => HostMode;
16
- /** For tests: forget the minted dev token. */
13
+ /** For tests: forget the minted dev token and what the backend said of it. */
17
14
  export declare const resetDevToken: () => void;
18
- export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<string>;
15
+ export declare const mintDevToken: (backend: string, appId: string, apiKey: string) => Promise<ExpiringToken>;
16
+ /**
17
+ * What the backend says of a dev token, from the claims it verified, as OAuth's token introspection answers: asked
18
+ * once per token, whose claims never change. Throws, saying why, when it won't say.
19
+ */
20
+ export declare const describeDevToken: (backend: string, token: string) => Promise<AppContext>;
19
21
  /**
20
22
  * `local` when the developer set a dev token, or a key to mint them with, else undefined. Throws on env it can't read,
21
23
  * so a typo fails loudly rather than signing nobody in.
@@ -1,43 +1,57 @@
1
- // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, the
2
- // platform's URLs and who is calling, in props. `local`: a developer's machine, with a dev token the backend minted.
3
- import { appTokenClaims } from "../internal/appToken.js";
1
+ // The one place zitejs knows where the platform is. `zite`: Zite's dispatcher hands each request its app token, what
2
+ // the platform says of the app, the platform's URLs and who is calling, in props. `local`: a developer's machine, with
3
+ // a dev token the backend minted, which the backend also describes. The token is opaque here: zitejs only sends it.
4
4
  import { platformFetch } from "../internal/platformFetch.js";
5
5
  import { devAppId } from "./devApp.js";
6
6
  // A streamed answer can outlive the request's deadline, which the token's expiry follows.
7
7
  const RENEW_WITHIN_MS = 30_000;
8
- const expiresWithin = (token, ms) => {
9
- const claims = appTokenClaims(token);
10
- return claims !== undefined && claims.exp * 1000 - Date.now() < ms;
8
+ const expiresWithin = (expiresAt, ms) => expiresAt !== undefined && expiresAt - Date.now() < ms;
9
+ const isExpiringToken = (value) => {
10
+ const given = value;
11
+ return typeof given?.token === "string" && given.token !== "" && typeof given.expiresAt === "number" && Number.isFinite(given.expiresAt);
11
12
  };
13
+ const contextOf = ({ appId, buildId, baseId, mode, orgSettingsVersion, showZiteBadge, appUrl }) => ({
14
+ appId,
15
+ buildId,
16
+ baseId,
17
+ mode,
18
+ orgSettingsVersion,
19
+ showZiteBadge,
20
+ appUrl,
21
+ });
12
22
  const URL_NAMES = ["baseRunner", "backend", "gateway", "runs", "email", "pdf", "uploads", "steps"];
13
23
  // `local` may leave out the gateway (a call on Zite's AI key is then refused), `runs` (a preview sends no analytics,
14
24
  // and `local` keeps no run detail) and each service's own URL (the backend then answers it).
15
25
  const OPTIONAL_URLS = new Set(["gateway", "runs", "email", "pdf", "uploads", "steps"]);
16
26
  const trimmed = (urls) => Object.fromEntries(URL_NAMES.flatMap((name) => (urls[name] ? [[name, urls[name].replace(/\/+$/, "")]] : [])));
17
27
  export const ziteProvider = (props) => {
18
- let current = props.appToken;
28
+ let current = props.appToken
29
+ ? { token: props.appToken, expiresAt: props.appTokenExpiresAt }
30
+ : undefined;
19
31
  let renewing;
32
+ // Kept before `renewing` clears, so a caller that comes between them doesn't renew again.
20
33
  const renew = async () => {
21
34
  try {
22
35
  const fresh = await props.platform.appToken();
23
- return typeof fresh === "string" && fresh ? fresh : undefined;
36
+ if (isExpiringToken(fresh))
37
+ current = fresh;
24
38
  }
25
39
  catch (error) {
26
40
  // The token held still serves until it expires.
27
41
  console.error("[zite] couldn't renew the app token", error);
28
- return undefined;
29
42
  }
30
43
  };
44
+ const context = contextOf(props);
31
45
  return {
32
46
  kind: "zite",
33
47
  urls: props.urls && trimmed(props.urls),
34
48
  user: () => props.user,
49
+ context: async () => context,
35
50
  token: async () => {
36
- if (!current || !expiresWithin(current, RENEW_WITHIN_MS))
37
- return current;
38
- renewing ??= renew().finally(() => (renewing = undefined));
39
- current = (await renewing) ?? current;
40
- return current;
51
+ if (!current || !expiresWithin(current.expiresAt, RENEW_WITHIN_MS))
52
+ return current?.token;
53
+ await (renewing ??= renew().finally(() => (renewing = undefined)));
54
+ return current.token;
41
55
  },
42
56
  };
43
57
  };
@@ -82,49 +96,89 @@ const localUser = (raw) => {
82
96
  isInternal: given.isInternal === true,
83
97
  };
84
98
  };
85
- const MODES = new Set(["live", "preview", "demo"]);
86
- /** The mode a dev token names; preview for one it doesn't. */
87
- export const localModeOf = (claims) => MODES.has(claims?.mode) ? claims?.mode : "preview";
88
99
  // The backend mints them for 15 minutes.
89
100
  const RENEW_DEV_TOKEN_WITHIN_MS = 60_000;
90
- const MINT_TIMEOUT_MS = 10_000;
91
- // Per isolate, only a minted token, never a pending mint: Workers ties a request's I/O to that request.
101
+ const BACKEND_TIMEOUT_MS = 10_000;
102
+ // Per isolate, only answers, never a pending call: Workers ties a request's I/O to that request.
92
103
  let held;
93
- /** For tests: forget the minted dev token. */
104
+ let described;
105
+ /** For tests: forget the minted dev token and what the backend said of it. */
94
106
  export const resetDevToken = () => {
95
107
  held = undefined;
108
+ described = undefined;
109
+ };
110
+ const reasonOf = (response, answer) => {
111
+ const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
112
+ return `${response.status}${why ? ` ${why}` : ""}`;
96
113
  };
97
114
  export const mintDevToken = async (backend, appId, apiKey) => {
98
115
  const response = await platformFetch(new Request(`${backend}/v1/start/apps/${encodeURIComponent(appId)}/dev-token`, {
99
116
  method: "POST",
100
117
  headers: { authorization: `Bearer ${apiKey}` },
101
- signal: AbortSignal.timeout(MINT_TIMEOUT_MS),
118
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
102
119
  }));
103
120
  const answer = (await response.json().catch(() => null));
104
- if (response.ok && typeof answer?.token === "string")
105
- return answer.token;
106
- const why = [answer?.message, answer?.error].find((text) => typeof text === "string");
107
- throw new Error(`The backend didn't mint a dev token for app ${appId} with ${LOCAL_ENV.apiKey}: ${response.status}${why ? ` ${why}` : ""}`);
121
+ if (response.ok && isExpiringToken(answer))
122
+ return { token: answer.token, expiresAt: answer.expiresAt };
123
+ throw new Error(`The backend didn't mint a dev token for app ${appId} with ${LOCAL_ENV.apiKey}: ${reasonOf(response, answer)}`);
124
+ };
125
+ const MODES = new Set(["live", "preview", "demo"]);
126
+ const isWhole = (value) => Number.isSafeInteger(value) && value >= 0;
127
+ const isText = (value) => typeof value === "string" && value !== "";
128
+ const isTextOrNull = (value) => value === null || isText(value);
129
+ /** The backend's `/context` answer, or undefined when it isn't one. */
130
+ const appContextOf = (answer) => {
131
+ const given = answer;
132
+ if (!given ||
133
+ !isText(given.appId) ||
134
+ !isWhole(given.buildId) ||
135
+ !isTextOrNull(given.baseId) ||
136
+ !MODES.has(given.mode) ||
137
+ !(given.orgSettingsVersion === null || isWhole(given.orgSettingsVersion)) ||
138
+ typeof given.showZiteBadge !== "boolean" ||
139
+ !isTextOrNull(given.appUrl)) {
140
+ return undefined;
141
+ }
142
+ return contextOf(given);
108
143
  };
109
- /** The app's dev token, minted with the developer's key, and minted again when it's about to expire. */
144
+ /**
145
+ * What the backend says of a dev token, from the claims it verified, as OAuth's token introspection answers: asked
146
+ * once per token, whose claims never change. Throws, saying why, when it won't say.
147
+ */
148
+ export const describeDevToken = async (backend, token) => {
149
+ const key = `${backend} ${token}`;
150
+ if (described?.key === key)
151
+ return described.context;
152
+ const response = await platformFetch(new Request(`${backend}/v1/start/app/context`, {
153
+ headers: { authorization: `Bearer ${token}` },
154
+ signal: AbortSignal.timeout(BACKEND_TIMEOUT_MS),
155
+ }));
156
+ const answer = await response.json().catch(() => null);
157
+ const context = response.ok ? appContextOf(answer) : undefined;
158
+ if (!context)
159
+ throw new Error(`The backend didn't say which app the dev token is for: ${reasonOf(response, answer)}`);
160
+ described = { key, context };
161
+ return context;
162
+ };
163
+ /** The app's dev token, minted with the developer's key, and minted again when the mint's expiry is near. */
110
164
  const mintedDevToken = (backend, appId, apiKey) => {
111
165
  const key = `${backend} ${appId} ${apiKey}`;
112
166
  let minting;
113
167
  return async () => {
114
- const current = held?.key === key ? held.token : undefined;
115
- if (current && !expiresWithin(current, RENEW_DEV_TOKEN_WITHIN_MS))
116
- return current;
168
+ const current = held?.key === key ? held.minted : undefined;
169
+ if (current && !expiresWithin(current.expiresAt, RENEW_DEV_TOKEN_WITHIN_MS))
170
+ return current.token;
117
171
  minting ??= mintDevToken(backend, appId, apiKey).finally(() => (minting = undefined));
118
172
  try {
119
- const token = await minting;
120
- held = { key, token };
121
- return token;
173
+ const minted = await minting;
174
+ held = { key, minted };
175
+ return minted.token;
122
176
  }
123
177
  catch (error) {
124
- if (!current || expiresWithin(current, 0))
178
+ if (!current || expiresWithin(current.expiresAt, 0))
125
179
  throw error;
126
180
  console.error("[zite] couldn't renew the dev token; using the one held until it expires", error);
127
- return current;
181
+ return current.token;
128
182
  }
129
183
  };
130
184
  };
@@ -146,5 +200,12 @@ export const localPlatform = (env = processEnv() ?? {}, appId = devAppId) => {
146
200
  return undefined;
147
201
  const urls = localUrls(env[LOCAL_ENV.urls]);
148
202
  const user = localUser(env[LOCAL_ENV.user]);
149
- return { kind: "local", urls, user: () => user, token: token(urls.backend) };
203
+ const tokenOf = token(urls.backend);
204
+ return {
205
+ kind: "local",
206
+ urls,
207
+ user: () => user,
208
+ token: tokenOf,
209
+ context: async () => describeDevToken(urls.backend, await tokenOf()),
210
+ };
150
211
  };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * What `axios` resolves to inside `@slack/web-api` in a Start server build, as classic's prebundle shims it: the axios
3
+ * surface Slack uses, on workerd's fetch. Real axios's fetch adapter sends Slack's `form-data` upload bodies as the text
4
+ * "[object FormData]". The app's own `axios` stays real axios.
5
+ */
6
+ type HeaderMap = Record<string, string>;
7
+ type Interceptor<T> = {
8
+ fulfilled: (value: T) => T | Promise<T>;
9
+ rejected?: (error: unknown) => unknown;
10
+ };
11
+ export type AxiosRequestConfig = {
12
+ url?: string;
13
+ baseURL?: string;
14
+ method?: string;
15
+ params?: string | URLSearchParams | Record<string, unknown>;
16
+ data?: unknown;
17
+ headers?: Record<string, unknown>;
18
+ transformRequest?: TransformRequest | TransformRequest[];
19
+ responseType?: "arraybuffer" | "blob" | "text" | "stream" | "json";
20
+ timeout?: number;
21
+ signal?: AbortSignal;
22
+ maxRedirects?: number;
23
+ validateStatus?: (status: number) => boolean;
24
+ [option: string]: unknown;
25
+ };
26
+ type TransformRequest = (data: unknown, headers: HeaderMap) => unknown;
27
+ export type AxiosResponse = {
28
+ data: unknown;
29
+ status: number;
30
+ statusText: string;
31
+ headers: HeaderMap;
32
+ config: AxiosRequestConfig;
33
+ request: RequestInit;
34
+ };
35
+ export declare class AxiosError extends Error {
36
+ readonly code?: string | undefined;
37
+ readonly config?: AxiosRequestConfig | undefined;
38
+ readonly request?: RequestInit | undefined;
39
+ readonly response?: AxiosResponse | undefined;
40
+ readonly isAxiosError = true;
41
+ constructor(message: string, code?: string | undefined, config?: AxiosRequestConfig | undefined, request?: RequestInit | undefined, response?: AxiosResponse | undefined);
42
+ }
43
+ declare class CanceledError extends AxiosError {
44
+ constructor(message?: string);
45
+ }
46
+ declare class InterceptorManager<T> {
47
+ readonly handlers: (Interceptor<T> | null)[];
48
+ use(fulfilled: Interceptor<T>["fulfilled"], rejected?: Interceptor<T>["rejected"]): number;
49
+ eject(id: number): void;
50
+ clear(): void;
51
+ }
52
+ type AxiosInstance = {
53
+ (configOrUrl: string | AxiosRequestConfig, config?: AxiosRequestConfig): Promise<AxiosResponse>;
54
+ defaults: AxiosRequestConfig & {
55
+ headers: Record<string, unknown>;
56
+ };
57
+ interceptors: {
58
+ request: InterceptorManager<AxiosRequestConfig>;
59
+ response: InterceptorManager<AxiosResponse>;
60
+ };
61
+ getUri(config?: AxiosRequestConfig): string;
62
+ request(configOrUrl: string | AxiosRequestConfig, config?: AxiosRequestConfig): Promise<AxiosResponse>;
63
+ get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
64
+ delete(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
65
+ head(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
66
+ options(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse>;
67
+ post(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<AxiosResponse>;
68
+ put(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<AxiosResponse>;
69
+ patch(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<AxiosResponse>;
70
+ create(config?: AxiosRequestConfig): AxiosInstance;
71
+ isAxiosError(value: unknown): value is AxiosError;
72
+ AxiosError: typeof AxiosError;
73
+ CanceledError: typeof CanceledError;
74
+ };
75
+ declare const axios: AxiosInstance;
76
+ export default axios;
@@ -0,0 +1,210 @@
1
+ /**
2
+ * What `axios` resolves to inside `@slack/web-api` in a Start server build, as classic's prebundle shims it: the axios
3
+ * surface Slack uses, on workerd's fetch. Real axios's fetch adapter sends Slack's `form-data` upload bodies as the text
4
+ * "[object FormData]". The app's own `axios` stays real axios.
5
+ */
6
+ export class AxiosError extends Error {
7
+ code;
8
+ config;
9
+ request;
10
+ response;
11
+ isAxiosError = true;
12
+ constructor(message, code, config, request, response) {
13
+ super(message);
14
+ this.code = code;
15
+ this.config = config;
16
+ this.request = request;
17
+ this.response = response;
18
+ this.name = "AxiosError";
19
+ }
20
+ }
21
+ class CanceledError extends AxiosError {
22
+ constructor(message) {
23
+ super(message ?? "canceled", "ERR_CANCELED");
24
+ }
25
+ }
26
+ // The per-method header buckets axios keeps beside the headers themselves.
27
+ const HEADER_BUCKETS = ["common", "get", "post", "put", "patch", "delete", "head", "options"];
28
+ const isRecord = (value) => typeof value === "object" && value !== null;
29
+ const isNodeFormData = (body) => isRecord(body) && typeof body.getHeaders === "function" && typeof body.getBuffer === "function";
30
+ const buildURL = (url, params) => {
31
+ if (!params)
32
+ return url;
33
+ const entries = typeof params === "string" || params instanceof URLSearchParams
34
+ ? new URLSearchParams(params)
35
+ : new URLSearchParams(Object.entries(params).flatMap(([key, value]) => (value === undefined || value === null ? [] : [[key, String(value)]])));
36
+ const query = entries.toString();
37
+ return query ? `${url}${url.includes("?") ? "&" : "?"}${query}` : url;
38
+ };
39
+ const mergeHeaders = (...sources) => {
40
+ const result = {};
41
+ for (const source of sources) {
42
+ if (!source)
43
+ continue;
44
+ const entries = source instanceof Headers ? [...source.entries()] : isRecord(source) ? Object.entries(source) : [];
45
+ for (const [key, value] of entries) {
46
+ if (value !== undefined && value !== null)
47
+ result[key.toLowerCase()] = value;
48
+ }
49
+ }
50
+ return result;
51
+ };
52
+ const joinURL = (baseURL, url = "") => baseURL && !url.startsWith("http") ? `${baseURL.replace(/\/$/, "")}/${url.replace(/^\//, "")}` : url;
53
+ const withCharset = (contentType) => (/charset=/i.test(contentType) ? contentType : `${contentType}; charset=utf-8`);
54
+ const dispatchRequest = async (config) => {
55
+ const url = buildURL(joinURL(config.baseURL, config.url), config.params);
56
+ const method = (config.method ?? "GET").toUpperCase();
57
+ const buckets = config.headers ?? {};
58
+ const merged = mergeHeaders(buckets.common, buckets[method.toLowerCase()], buckets);
59
+ const headers = {};
60
+ for (const [key, value] of Object.entries(merged)) {
61
+ if (!HEADER_BUCKETS.includes(key) && !isRecord(value))
62
+ headers[key] = String(value);
63
+ }
64
+ let body = config.data;
65
+ const transforms = config.transformRequest === undefined ? [] : [config.transformRequest].flat();
66
+ for (const transform of transforms)
67
+ body = transform(body, headers);
68
+ if (isNodeFormData(body)) {
69
+ Object.assign(headers, body.getHeaders());
70
+ if (headers["content-type"])
71
+ headers["content-type"] = withCharset(headers["content-type"]);
72
+ body = body.getBuffer();
73
+ }
74
+ else if (typeof body === "string") {
75
+ headers["content-type"] = withCharset(headers["content-type"] ?? "application/x-www-form-urlencoded");
76
+ }
77
+ else if (isRecord(body) &&
78
+ !(body instanceof ArrayBuffer) &&
79
+ !ArrayBuffer.isView(body) &&
80
+ !(body instanceof ReadableStream) &&
81
+ !(body instanceof Blob) &&
82
+ !(body instanceof FormData) &&
83
+ !(body instanceof URLSearchParams)) {
84
+ // As Slack's serializer would: its Web API reads form fields, with anything structured JSON-encoded.
85
+ const params = new URLSearchParams();
86
+ for (const [key, value] of Object.entries(body)) {
87
+ if (value === undefined || value === null)
88
+ continue;
89
+ params.append(key, typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value));
90
+ }
91
+ body = params.toString();
92
+ headers["content-type"] ??= "application/x-www-form-urlencoded; charset=utf-8";
93
+ }
94
+ const init = {
95
+ method,
96
+ headers,
97
+ body: method === "GET" || method === "HEAD" ? undefined : body,
98
+ signal: config.signal,
99
+ redirect: config.maxRedirects === 0 ? "manual" : "follow",
100
+ };
101
+ let timer;
102
+ if (config.timeout && config.timeout > 0 && !config.signal) {
103
+ const controller = new AbortController();
104
+ init.signal = controller.signal;
105
+ timer = setTimeout(() => controller.abort(), config.timeout);
106
+ }
107
+ try {
108
+ const res = await fetch(url, init);
109
+ const responseHeaders = {};
110
+ res.headers.forEach((value, key) => {
111
+ responseHeaders[key] = value;
112
+ });
113
+ let data;
114
+ if (config.responseType === "arraybuffer")
115
+ data = await res.arrayBuffer();
116
+ else if (config.responseType === "blob")
117
+ data = await res.blob();
118
+ else if (config.responseType === "text")
119
+ data = await res.text();
120
+ else if (config.responseType === "stream")
121
+ data = res.body;
122
+ else if ((res.headers.get("content-type") ?? "").includes("application/json"))
123
+ data = await res.json();
124
+ else {
125
+ const text = await res.text();
126
+ try {
127
+ data = JSON.parse(text);
128
+ }
129
+ catch {
130
+ data = text;
131
+ }
132
+ }
133
+ const response = { data, status: res.status, statusText: res.statusText, headers: responseHeaders, config, request: init };
134
+ const validateStatus = config.validateStatus ?? ((status) => status >= 200 && status < 300);
135
+ if (!validateStatus(res.status)) {
136
+ throw new AxiosError(`Request failed with status code ${res.status}`, "ERR_BAD_RESPONSE", config, init, response);
137
+ }
138
+ return response;
139
+ }
140
+ catch (error) {
141
+ if (error instanceof AxiosError)
142
+ throw error;
143
+ if (error instanceof Error && error.name === "AbortError")
144
+ throw new AxiosError("timeout exceeded", "ECONNABORTED", config);
145
+ throw new AxiosError(error instanceof Error ? error.message : "Network Error", "ERR_NETWORK", config);
146
+ }
147
+ finally {
148
+ if (timer)
149
+ clearTimeout(timer);
150
+ }
151
+ };
152
+ class InterceptorManager {
153
+ handlers = [];
154
+ use(fulfilled, rejected) {
155
+ this.handlers.push({ fulfilled, rejected });
156
+ return this.handlers.length - 1;
157
+ }
158
+ eject(id) {
159
+ this.handlers[id] = null;
160
+ }
161
+ clear() {
162
+ this.handlers.length = 0;
163
+ }
164
+ }
165
+ const createInstance = (defaultConfig = {}) => {
166
+ const defaults = { ...defaultConfig, headers: { ...defaultConfig.headers } };
167
+ // Slack clears `defaults.headers.post['Content-Type']`, so every bucket exists.
168
+ for (const bucket of HEADER_BUCKETS)
169
+ defaults.headers[bucket] ??= {};
170
+ const interceptors = { request: new InterceptorManager(), response: new InterceptorManager() };
171
+ const request = async (configOrUrl, config) => {
172
+ const given = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
173
+ let merged = { ...defaults, ...given, headers: mergeHeaders(defaults.headers, given.headers) };
174
+ // As axios: request interceptors run last-registered first. Slack serializes every request body in one.
175
+ for (const interceptor of [...interceptors.request.handlers].reverse()) {
176
+ if (interceptor)
177
+ merged = await interceptor.fulfilled(merged);
178
+ }
179
+ let response = await dispatchRequest(merged);
180
+ for (const interceptor of interceptors.response.handlers) {
181
+ if (interceptor)
182
+ response = await interceptor.fulfilled(response);
183
+ }
184
+ return response;
185
+ };
186
+ const withData = (method) => (url, data, config) => request({ ...config, method, url, data });
187
+ const withoutData = (method) => (url, config) => request({ ...config, method, url });
188
+ return Object.assign(request, {
189
+ defaults,
190
+ interceptors,
191
+ getUri: (config = {}) => {
192
+ const merged = { ...defaults, ...config };
193
+ return buildURL(joinURL(merged.baseURL, merged.url), merged.params);
194
+ },
195
+ request,
196
+ get: withoutData("get"),
197
+ delete: withoutData("delete"),
198
+ head: withoutData("head"),
199
+ options: withoutData("options"),
200
+ post: withData("post"),
201
+ put: withData("put"),
202
+ patch: withData("patch"),
203
+ create: (config = {}) => createInstance({ ...defaults, ...config }),
204
+ isAxiosError: (value) => isRecord(value) && value.isAxiosError === true,
205
+ AxiosError,
206
+ CanceledError,
207
+ });
208
+ };
209
+ const axios = createInstance();
210
+ export default axios;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What `node-fetch` resolves to in a Start server build: workerd's own fetch. node-fetch's Node transport doesn't survive
3
+ * workerd's `node:http`: v2 throws on a POST and v3 never sees a response header, so it hands back gzip bytes.
4
+ */
5
+ type NodeFetchResponse = Response & {
6
+ buffer(): Promise<Buffer>;
7
+ };
8
+ declare function nodeFetch(input: RequestInfo | URL, init?: RequestInit): Promise<NodeFetchResponse>;
9
+ declare class FetchError extends Error {
10
+ type: string;
11
+ code?: string;
12
+ constructor(message: string, type: string, systemError?: {
13
+ code?: string;
14
+ });
15
+ }
16
+ declare class AbortError extends Error {
17
+ type: string;
18
+ constructor(message: string);
19
+ }
20
+ declare const isRedirect: (status: number) => boolean;
21
+ declare const Headers: {
22
+ new (init?: HeadersInit): Headers;
23
+ prototype: Headers;
24
+ }, Request: {
25
+ new (input: RequestInfo | URL, init?: RequestInit): Request;
26
+ prototype: Request;
27
+ }, Response: {
28
+ new (body?: BodyInit | null, init?: ResponseInit): Response;
29
+ prototype: Response;
30
+ error(): Response;
31
+ json(data: any, init?: ResponseInit): Response;
32
+ redirect(url: string | URL, status?: number): Response;
33
+ }, Blob: {
34
+ new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
35
+ prototype: Blob;
36
+ }, FormData: {
37
+ new (form?: HTMLFormElement, submitter?: HTMLElement | null): FormData;
38
+ prototype: FormData;
39
+ };
40
+ export default nodeFetch;
41
+ export { AbortError, Blob, FetchError, FormData, Headers, isRedirect, Request, Response };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What `node-fetch` resolves to in a Start server build: workerd's own fetch. node-fetch's Node transport doesn't survive
3
+ * workerd's `node:http`: v2 throws on a POST and v3 never sees a response header, so it hands back gzip bytes.
4
+ */
5
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
6
+ // Looked up per call, so zitejs's outbound wrapper sees every request.
7
+ async function nodeFetch(input, init) {
8
+ const res = await globalThis.fetch(input, init);
9
+ // node-fetch 2's body reader, which HubSpot's binary responses call.
10
+ return Object.assign(res, { buffer: async () => Buffer.from(await res.arrayBuffer()) });
11
+ }
12
+ class FetchError extends Error {
13
+ type;
14
+ code;
15
+ constructor(message, type, systemError) {
16
+ super(message);
17
+ this.name = "FetchError";
18
+ this.type = type;
19
+ if (systemError?.code)
20
+ this.code = systemError.code;
21
+ }
22
+ }
23
+ class AbortError extends Error {
24
+ type = "aborted";
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "AbortError";
28
+ }
29
+ }
30
+ const isRedirect = (status) => REDIRECT_STATUSES.has(status);
31
+ const { Headers, Request, Response, Blob, FormData } = globalThis;
32
+ export default nodeFetch;
33
+ export { AbortError, Blob, FetchError, FormData, Headers, isRedirect, Request, Response };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What `undici` resolves to inside jsforce (3.13 and later) in a Start server build: the parts of its API jsforce uses, on
3
+ * workerd's fetch. undici's own fetch opens TLS sockets with options workerd's `node:tls` doesn't implement.
4
+ */
5
+ export declare const fetch: (input: RequestInfo | URL, init?: RequestInit & {
6
+ dispatcher?: unknown;
7
+ }) => Promise<Response>;
8
+ export declare class Agent {
9
+ constructor(_options?: unknown);
10
+ }
11
+ export declare class ProxyAgent extends Agent {
12
+ }
13
+ declare class SocketError extends Error {
14
+ }
15
+ export declare const errors: {
16
+ SocketError: typeof SocketError;
17
+ };
18
+ export declare const Headers: {
19
+ new (init?: HeadersInit): Headers;
20
+ prototype: Headers;
21
+ }, Request: {
22
+ new (input: RequestInfo | URL, init?: RequestInit): Request;
23
+ prototype: Request;
24
+ }, Response: {
25
+ new (body?: BodyInit | null, init?: ResponseInit): Response;
26
+ prototype: Response;
27
+ error(): Response;
28
+ json(data: any, init?: ResponseInit): Response;
29
+ redirect(url: string | URL, status?: number): Response;
30
+ }, FormData: {
31
+ new (form?: HTMLFormElement, submitter?: HTMLElement | null): FormData;
32
+ prototype: FormData;
33
+ };
34
+ export {};