webspresso 0.0.108 → 0.0.109

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 (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -3
  3. package/bin/commands/add-esbuild.js +7 -3
  4. package/bin/commands/add-tailwind.js +9 -5
  5. package/bin/commands/build.js +20 -4
  6. package/bin/commands/dev.js +57 -7
  7. package/bin/commands/doctor.js +42 -1
  8. package/bin/commands/favicon-generate.js +10 -3
  9. package/bin/commands/new.js +8 -3
  10. package/bin/commands/start.js +3 -1
  11. package/bin/utils/add-command.js +16 -0
  12. package/core/app.js +45 -3
  13. package/core/auth/authenticate.js +3 -3
  14. package/core/auth/hash.js +167 -43
  15. package/core/auth/index.js +13 -1
  16. package/core/auth/jwt.js +21 -2
  17. package/core/auth/manager.js +63 -14
  18. package/core/auth/middleware.js +4 -2
  19. package/core/auth/oauth.js +5 -1
  20. package/core/auth/tokens.js +7 -2
  21. package/core/auth/totp.js +42 -6
  22. package/core/auth/user-agent.js +2 -0
  23. package/core/client/adapter/datastar.js +1254 -0
  24. package/core/client/api.js +1033 -0
  25. package/core/client/controller.js +1081 -0
  26. package/core/client/debug.js +367 -0
  27. package/core/client/forms.js +1021 -0
  28. package/core/client/fragments.js +738 -0
  29. package/core/client/index.d.ts +40 -0
  30. package/core/client/index.js +347 -0
  31. package/core/client/lite.js +164 -0
  32. package/core/client/server-fragments.js +859 -0
  33. package/core/client/utils.js +144 -0
  34. package/core/compression/middleware.js +277 -26
  35. package/core/context/app-context.js +25 -3
  36. package/core/context/request.js +32 -4
  37. package/core/errors/middleware.js +14 -0
  38. package/core/events/dispatcher.js +33 -0
  39. package/core/forms/flash.js +136 -102
  40. package/core/health/middleware.js +36 -6
  41. package/core/http/pipeline.js +45 -6
  42. package/core/index.js +21 -7
  43. package/core/kernel/view.js +41 -10
  44. package/core/metrics/middleware.js +30 -6
  45. package/core/metrics/registry.js +13 -5
  46. package/core/orm/cache/fingerprint.js +32 -11
  47. package/core/orm/cache/layer.js +19 -2
  48. package/core/orm/hidden.js +145 -0
  49. package/core/orm/model.js +48 -2
  50. package/core/orm/query-builder.js +343 -6
  51. package/core/orm/query-filters.js +14 -2
  52. package/core/orm/repository.js +64 -13
  53. package/core/orm/schema-helpers.js +9 -6
  54. package/core/orm/transaction.js +50 -6
  55. package/core/orm/types.js +4 -0
  56. package/core/queue/adapters/database.js +184 -2
  57. package/core/queue/adapters/memory.js +153 -5
  58. package/core/queue/adapters/redis.js +59 -4
  59. package/core/queue/job.js +14 -1
  60. package/core/queue/manager.js +115 -0
  61. package/core/resilience/circuit-breaker.js +27 -8
  62. package/core/services/builtins/exchange.js +174 -7
  63. package/core/services/builtins/file-manager.js +36 -0
  64. package/core/services/builtins/mail.js +27 -0
  65. package/core/services/builtins/queue.js +144 -0
  66. package/core/services/builtins/security.js +118 -0
  67. package/core/services/builtins/webhook.js +110 -0
  68. package/core/services/executor.js +38 -16
  69. package/core/services/index.js +4 -1
  70. package/core/sse/stream.js +28 -5
  71. package/core/utils/timeout.js +8 -1
  72. package/core/validation/compiler.js +10 -7
  73. package/index.d.ts +1127 -71
  74. package/index.js +124 -8
  75. package/package.json +75 -26
  76. package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
  77. package/plugins/admin-panel/index.js +19 -8
  78. package/plugins/csrf/index.js +3 -3
  79. package/plugins/data-exchange/export.js +214 -0
  80. package/plugins/data-exchange/import.js +48 -5
  81. package/plugins/data-exchange/index.js +70 -28
  82. package/plugins/data-exchange/preview.js +266 -0
  83. package/plugins/data-exchange/template.js +242 -0
  84. package/plugins/email/admin-component.js +783 -141
  85. package/plugins/email/api-handlers.js +51 -1
  86. package/plugins/email/index.js +5 -0
  87. package/plugins/email/service.js +48 -0
  88. package/plugins/file-manager/admin-component.js +1546 -70
  89. package/plugins/file-manager/api-handlers.js +166 -1
  90. package/plugins/file-manager/core.js +598 -8
  91. package/plugins/file-manager/index.js +8 -0
  92. package/plugins/index.js +7 -0
  93. package/plugins/mcp/auth.js +3 -3
  94. package/plugins/oauth/index.js +36 -3
  95. package/plugins/queue/admin-component.js +1092 -0
  96. package/plugins/queue/api-handlers.js +248 -0
  97. package/plugins/queue/index.js +69 -0
  98. package/plugins/rest-resources/index.js +7 -2
  99. package/plugins/security/admin-component.js +689 -0
  100. package/plugins/security/api-handlers.js +169 -0
  101. package/plugins/security/audit.js +153 -0
  102. package/plugins/security/bruteforce.js +244 -0
  103. package/plugins/security/firewall.js +459 -0
  104. package/plugins/security/headers.js +214 -0
  105. package/plugins/security/honeypot.js +234 -0
  106. package/plugins/security/incident-recorder.js +137 -0
  107. package/plugins/security/index.js +211 -0
  108. package/plugins/seo-checker/analyzer.js +20 -7
  109. package/plugins/upload/index.js +36 -0
  110. package/plugins/webhooks/admin-component.js +702 -175
  111. package/plugins/webhooks/api-handlers.js +75 -1
  112. package/plugins/webhooks/dispatcher.js +290 -11
  113. package/plugins/webhooks/index.js +37 -2
  114. package/plugins/webhooks/sender.js +56 -0
  115. package/plugins/xlsx/engine.js +19 -4
  116. package/src/api/api-loader.js +19 -1
  117. package/src/bundle/index.js +443 -17
  118. package/src/client-runtime/mount.js +9 -2
  119. package/src/dev/api-typegen.js +1300 -0
  120. package/src/dev/banner.js +10 -1
  121. package/src/dev/colors.js +1 -1
  122. package/src/dev/index.js +7 -1
  123. package/src/dev/typegen.js +173 -17
  124. package/src/dev-reload/index.js +1 -1
  125. package/src/discovery/file-route-parser.js +17 -3
  126. package/src/discovery/scan-routes.js +4 -1
  127. package/src/file-router.js +249 -69
  128. package/src/helpers.js +46 -26
  129. package/src/njk-frontmatter.js +30 -4
  130. package/src/routing/cascading.js +26 -8
  131. package/src/routing/mount-discovered-routes.js +69 -0
  132. package/src/server.js +237 -66
  133. package/.agents/ADMIN.md +0 -426
  134. package/.agents/AGENTS.md +0 -96
  135. package/.agents/ARCHITECTURE.md +0 -163
  136. package/.agents/AUTH.md +0 -581
  137. package/.agents/CACHE.md +0 -148
  138. package/.agents/CLI.md +0 -649
  139. package/.agents/COMPRESSION.md +0 -59
  140. package/.agents/CONTEXT.md +0 -152
  141. package/.agents/CONVENTIONS.md +0 -50
  142. package/.agents/EARLY_HINTS.md +0 -120
  143. package/.agents/EMAIL.md +0 -223
  144. package/.agents/ERRORS.md +0 -260
  145. package/.agents/EVENTS.md +0 -179
  146. package/.agents/FLAGS.md +0 -118
  147. package/.agents/HEALTH.md +0 -118
  148. package/.agents/LIMITS.md +0 -109
  149. package/.agents/LOGGING.md +0 -93
  150. package/.agents/MCP.md +0 -103
  151. package/.agents/METRICS.md +0 -127
  152. package/.agents/MIGRATION_JOBS.md +0 -95
  153. package/.agents/ORM.md +0 -700
  154. package/.agents/PLUGINS.md +0 -729
  155. package/.agents/QUEUE.md +0 -290
  156. package/.agents/RATE_LIMIT.md +0 -147
  157. package/.agents/REALTIME.md +0 -213
  158. package/.agents/RESILIENCE.md +0 -235
  159. package/.agents/ROUTING.md +0 -605
  160. package/.agents/SCALE_OUT.md +0 -109
  161. package/.agents/SECRETS.md +0 -117
  162. package/.agents/SERVICES.md +0 -341
  163. package/.agents/SHUTDOWN.md +0 -74
  164. package/.agents/STREAMING.md +0 -108
  165. package/.agents/WORKFLOW.md +0 -27
  166. package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
  167. package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
  168. package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
  169. package/.agents/skills/webspresso-framework/SKILL.md +0 -89
  170. package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
  171. package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
  172. package/.agents/skills/webspresso-services/SKILL.md +0 -134
  173. package/.cursorrules +0 -14
  174. package/AGENTS.md +0 -203
  175. package/CLAUDE.md +0 -54
  176. package/core/kernel/run-demo.js +0 -58
  177. package/plugins/admin-panel/styles.js +0 -9
  178. package/plugins/data-exchange/export-xlsx.js +0 -119
@@ -0,0 +1,1033 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Typed API Client & Request Coordinator
5
+ *
6
+ * Provides:
7
+ * - Explicit concurrency policies per request key: 'latest' | 'drop' | 'queue' | 'parallel'
8
+ * - Zero automatic retry on mutations (POST, PUT, PATCH, DELETE)
9
+ * - Structured error taxonomy: 'http' | 'network' | 'validation' | 'canceled'
10
+ * - Wire format modeling (Date -> ISO, undefined query stripping, 204/empty -> undefined, File/Blob/FormData)
11
+ * - Automatic CSRF token & same-origin credential attachment
12
+ * - Two-phase mutation -> invalidation dispatch where refresh failure never fails a succeeded mutation
13
+ * - Raw & streaming escape hatches (`api.raw`, `api.stream`)
14
+ */
15
+
16
+ const VALID_POLICIES = new Set(['latest', 'drop', 'queue', 'parallel']);
17
+ const MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
18
+ const RESERVED_OPTION_KEYS = new Set([
19
+ 'query',
20
+ 'params',
21
+ 'headers',
22
+ 'signal',
23
+ 'key',
24
+ 'policy',
25
+ 'concurrency',
26
+ 'credentials',
27
+ 'csrfToken',
28
+ 'parseResponse',
29
+ 'onRefreshError',
30
+ ]);
31
+
32
+ /**
33
+ * Structured Client Request Error
34
+ * Distinguishes 'http', 'network', 'validation', and 'canceled' failure modes.
35
+ */
36
+ class ClientRequestError extends Error {
37
+ /**
38
+ * @param {string} message
39
+ * @param {object} details
40
+ * @param {'http'|'network'|'validation'|'canceled'} details.kind
41
+ * @param {number|null} [details.status]
42
+ * @param {string} [details.code]
43
+ * @param {string} [details.method]
44
+ * @param {string} [details.url]
45
+ * @param {string} [details.key]
46
+ * @param {Record<string, string>} [details.fieldErrors]
47
+ * @param {Record<string, string[]>} [details.fieldErrorList]
48
+ * @param {Array<{path: string, message: string, code?: string}>} [details.issues]
49
+ * @param {string|null} [details.formError]
50
+ * @param {unknown} [details.data]
51
+ * @param {boolean} [details.isDropped]
52
+ * @param {boolean} [details.isSuperseded]
53
+ * @param {Error} [details.cause]
54
+ */
55
+ constructor(message, details = {}) {
56
+ super(message);
57
+ this.name = 'ClientRequestError';
58
+ this.kind = details.kind || 'http';
59
+ this.status = details.status !== undefined ? details.status : null;
60
+ this.code = details.code || defaultCodeForKind(this.kind, this.status);
61
+ this.method = details.method || 'GET';
62
+ this.url = details.url || '';
63
+ this.key = details.key || '';
64
+ this.fieldErrors = details.fieldErrors || {};
65
+ this.fieldErrorList = details.fieldErrorList || {};
66
+ this.issues = Array.isArray(details.issues) ? details.issues : [];
67
+ this.formError = details.formError || null;
68
+ this.data = details.data !== undefined ? details.data : null;
69
+ this.isCanceled = this.kind === 'canceled';
70
+ this.isValidation = this.kind === 'validation';
71
+ this.isNetwork = this.kind === 'network';
72
+ this.isHttp = this.kind === 'http';
73
+ this.isDropped = Boolean(details.isDropped);
74
+ this.isSuperseded = Boolean(details.isSuperseded);
75
+ this.serverRollbackGuaranteed = false;
76
+ if (this.isCanceled) {
77
+ this.note = 'Client request cancellation/abort does not roll back server-side execution.';
78
+ }
79
+ if (details.cause) {
80
+ this.cause = details.cause;
81
+ }
82
+ }
83
+ }
84
+
85
+ function defaultCodeForKind(kind, status) {
86
+ if (kind === 'validation') return 'VALIDATION_ERROR';
87
+ if (kind === 'canceled') return 'REQUEST_CANCELED';
88
+ if (kind === 'network') return 'NETWORK_ERROR';
89
+ if (status === 401) return 'UNAUTHORIZED';
90
+ if (status === 403) return 'FORBIDDEN';
91
+ if (status === 404) return 'NOT_FOUND';
92
+ if (status === 409) return 'CONFLICT';
93
+ if (status === 429) return 'RATE_LIMITED';
94
+ return 'HTTP_ERROR';
95
+ }
96
+
97
+ /**
98
+ * Discover CSRF token from DOM meta tag, hidden `_csrf` input, or cookies.
99
+ *
100
+ * @param {Document} [doc]
101
+ * @returns {string|null}
102
+ */
103
+ function discoverCsrfToken(doc) {
104
+ const targetDoc = doc || (typeof document !== 'undefined' ? document : null);
105
+ if (!targetDoc) return null;
106
+
107
+ if (typeof targetDoc.querySelector === 'function') {
108
+ const meta =
109
+ targetDoc.querySelector('meta[name="csrf-token"]') ||
110
+ targetDoc.querySelector('meta[name="xsrf-token"]');
111
+ if (meta && typeof meta.getAttribute === 'function') {
112
+ const content = meta.getAttribute('content');
113
+ if (content) return content.trim();
114
+ }
115
+
116
+ const input = targetDoc.querySelector('input[name="_csrf"]');
117
+ if (input && input.value) {
118
+ return String(input.value).trim();
119
+ }
120
+ }
121
+
122
+ if (typeof targetDoc.cookie === 'string' && targetDoc.cookie) {
123
+ const cookies = targetDoc.cookie.split(';');
124
+ for (const raw of cookies) {
125
+ const [rawName, ...rest] = raw.trim().split('=');
126
+ if (rawName === 'XSRF-TOKEN' || rawName === '_csrf' || rawName === 'csrf_token') {
127
+ try {
128
+ return decodeURIComponent(rest.join('='));
129
+ } catch (_e) {
130
+ return rest.join('=');
131
+ }
132
+ }
133
+ }
134
+ }
135
+
136
+ return null;
137
+ }
138
+
139
+ /**
140
+ * Interpolate `:param` or `[param]` segments in URL paths and append query parameters.
141
+ * Strips `undefined` values and formats `Date` instances as ISO strings.
142
+ *
143
+ * @param {string} urlTemplate
144
+ * @param {Record<string, unknown>} [params]
145
+ * @param {Record<string, unknown>} [query]
146
+ * @returns {string}
147
+ */
148
+ function buildRequestUrl(urlTemplate, params, query) {
149
+ let resolvedPath = String(urlTemplate || '');
150
+
151
+ if (params && typeof params === 'object') {
152
+ for (const [key, val] of Object.entries(params)) {
153
+ if (val === undefined || val === null) continue;
154
+ const encoded = encodeURIComponent(val instanceof Date ? val.toISOString() : String(val));
155
+ resolvedPath = resolvedPath
156
+ .replace(new RegExp(`:${key}(?=/|$|\\?)`, 'g'), encoded)
157
+ .replace(new RegExp(`\\[${key}\\]`, 'g'), encoded);
158
+ }
159
+ }
160
+
161
+ if (!query || typeof query !== 'object') {
162
+ return resolvedPath;
163
+ }
164
+
165
+ const searchParams = new URLSearchParams();
166
+ for (const [key, rawVal] of Object.entries(query)) {
167
+ if (rawVal === undefined) continue;
168
+ if (Array.isArray(rawVal)) {
169
+ for (const item of rawVal) {
170
+ if (item === undefined) continue;
171
+ searchParams.append(key, item instanceof Date ? item.toISOString() : String(item));
172
+ }
173
+ } else if (rawVal instanceof Date) {
174
+ searchParams.append(key, rawVal.toISOString());
175
+ } else if (rawVal === null) {
176
+ searchParams.append(key, '');
177
+ } else if (typeof rawVal === 'object') {
178
+ searchParams.append(key, JSON.stringify(rawVal));
179
+ } else {
180
+ searchParams.append(key, String(rawVal));
181
+ }
182
+ }
183
+
184
+ const qs = searchParams.toString();
185
+ if (!qs) return resolvedPath;
186
+ return resolvedPath.includes('?') ? `${resolvedPath}&${qs}` : `${resolvedPath}?${qs}`;
187
+ }
188
+
189
+ /**
190
+ * Check whether an object contains binary File or Blob instances that require FormData transport.
191
+ */
192
+ function containsBinaryValue(value) {
193
+ if (!value || typeof value !== 'object') return false;
194
+ if (typeof Blob !== 'undefined' && value instanceof Blob) return true;
195
+ if (typeof File !== 'undefined' && value instanceof File) return true;
196
+ if (typeof FormData !== 'undefined' && value instanceof FormData) return true;
197
+ if (Array.isArray(value)) {
198
+ return value.some(containsBinaryValue);
199
+ }
200
+ for (const v of Object.values(value)) {
201
+ if (containsBinaryValue(v)) return true;
202
+ }
203
+ return false;
204
+ }
205
+
206
+ /**
207
+ * Convert a plain object containing File/Blob values into FormData.
208
+ */
209
+ function objectToFormData(obj) {
210
+ const fd = new FormData();
211
+ for (const [key, val] of Object.entries(obj)) {
212
+ if (val === undefined) continue;
213
+ if (Array.isArray(val)) {
214
+ for (const item of val) {
215
+ if (item === undefined) continue;
216
+ if (typeof Blob !== 'undefined' && item instanceof Blob) {
217
+ fd.append(key, item);
218
+ } else if (item instanceof Date) {
219
+ fd.append(key, item.toISOString());
220
+ } else if (item !== null) {
221
+ fd.append(key, String(item));
222
+ }
223
+ }
224
+ } else if (typeof Blob !== 'undefined' && val instanceof Blob) {
225
+ fd.append(key, val);
226
+ } else if (val instanceof Date) {
227
+ fd.append(key, val.toISOString());
228
+ } else if (val === null) {
229
+ fd.append(key, '');
230
+ } else if (typeof val === 'object') {
231
+ fd.append(key, JSON.stringify(val));
232
+ } else {
233
+ fd.append(key, String(val));
234
+ }
235
+ }
236
+ return fd;
237
+ }
238
+
239
+ /**
240
+ * Serialize JSON payload while converting Date objects to ISO strings.
241
+ */
242
+ function serializeRequestBody(body, headers) {
243
+ if (body === undefined || body === null) {
244
+ return undefined;
245
+ }
246
+ if (typeof FormData !== 'undefined' && body instanceof FormData) {
247
+ return body;
248
+ }
249
+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
250
+ if (!headers['Content-Type'] && !headers['content-type']) {
251
+ headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
252
+ }
253
+ return body.toString();
254
+ }
255
+ if (typeof Blob !== 'undefined' && body instanceof Blob) {
256
+ return body;
257
+ }
258
+ if (typeof body === 'string') {
259
+ if (!headers['Content-Type'] && !headers['content-type']) {
260
+ headers['Content-Type'] = 'text/plain;charset=UTF-8';
261
+ }
262
+ return body;
263
+ }
264
+ if (containsBinaryValue(body) && typeof FormData !== 'undefined') {
265
+ return objectToFormData(body);
266
+ }
267
+ if (!headers['Content-Type'] && !headers['content-type']) {
268
+ headers['Content-Type'] = 'application/json';
269
+ }
270
+ return JSON.stringify(body);
271
+ }
272
+
273
+ /**
274
+ * Extract structured validation field errors from Webspresso / Zod error payloads.
275
+ *
276
+ * @param {unknown} payload
277
+ * @returns {{ fieldErrors: Record<string, string>, fieldErrorList: Record<string, string[]>, issues: Array<{path: string, message: string, code?: string}>, formError: string|null }}
278
+ */
279
+ function extractValidationErrors(payload) {
280
+ const fieldErrors = {};
281
+ const fieldErrorList = {};
282
+ const issues = [];
283
+ let formError = null;
284
+
285
+ if (!payload || typeof payload !== 'object') {
286
+ return { fieldErrors, fieldErrorList, issues, formError };
287
+ }
288
+
289
+ const errObj = payload.error && typeof payload.error === 'object' ? payload.error : payload;
290
+
291
+ if (typeof errObj.formError === 'string' && errObj.formError) {
292
+ formError = errObj.formError;
293
+ } else if (typeof payload.formError === 'string' && payload.formError) {
294
+ formError = payload.formError;
295
+ }
296
+
297
+ // 1. Direct fieldErrors map (e.g. { title: 'Required' } or { title: ['Required'] })
298
+ const rawFieldErrors = errObj.fieldErrors || payload.fieldErrors || errObj.fields || null;
299
+ if (rawFieldErrors && typeof rawFieldErrors === 'object' && !Array.isArray(rawFieldErrors)) {
300
+ for (const [field, msgOrArr] of Object.entries(rawFieldErrors)) {
301
+ const list = Array.isArray(msgOrArr) ? msgOrArr.map(String) : [String(msgOrArr)];
302
+ if (list.length > 0) {
303
+ fieldErrors[field] = list[0];
304
+ fieldErrorList[field] = list;
305
+ issues.push({ path: field, message: list[0] });
306
+ }
307
+ }
308
+ }
309
+
310
+ // 2. Zod / Webspresso `issues` or `details` array
311
+ const rawIssues =
312
+ (Array.isArray(errObj.issues) && errObj.issues) ||
313
+ (Array.isArray(payload.issues) && payload.issues) ||
314
+ (Array.isArray(errObj.details) && errObj.details) ||
315
+ (Array.isArray(payload.details) && payload.details) ||
316
+ (Array.isArray(errObj.errors) && errObj.errors) ||
317
+ [];
318
+
319
+ for (const issue of rawIssues) {
320
+ if (!issue || typeof issue !== 'object') continue;
321
+ let rawPath = '';
322
+ if (Array.isArray(issue.path)) {
323
+ // Strip leading 'body' / 'query' / 'params' prefix from route validation paths
324
+ const cleanParts =
325
+ issue.path.length > 1 &&
326
+ (issue.path[0] === 'body' || issue.path[0] === 'query' || issue.path[0] === 'params')
327
+ ? issue.path.slice(1)
328
+ : issue.path;
329
+ rawPath = cleanParts.join('.');
330
+ } else if (typeof issue.path === 'string') {
331
+ rawPath = issue.path.replace(/^(body|query|params)\./, '');
332
+ } else if (typeof issue.field === 'string') {
333
+ rawPath = issue.field.replace(/^(body|query|params)\./, '');
334
+ }
335
+
336
+ const message = issue.message ? String(issue.message) : 'Invalid value';
337
+ issues.push({ path: rawPath, message, code: issue.code });
338
+
339
+ if (rawPath) {
340
+ if (!fieldErrors[rawPath]) {
341
+ fieldErrors[rawPath] = message;
342
+ }
343
+ if (!fieldErrorList[rawPath]) {
344
+ fieldErrorList[rawPath] = [];
345
+ }
346
+ if (!fieldErrorList[rawPath].includes(message)) {
347
+ fieldErrorList[rawPath].push(message);
348
+ }
349
+ } else if (!formError) {
350
+ formError = message;
351
+ }
352
+ }
353
+
354
+ if (!formError && typeof errObj.message === 'string' && Object.keys(fieldErrors).length === 0) {
355
+ formError = errObj.message;
356
+ }
357
+
358
+ return { fieldErrors, fieldErrorList, issues, formError };
359
+ }
360
+
361
+ /**
362
+ * Separate invalidation infrastructure metadata from application data.
363
+ * Supports:
364
+ * - `X-Webspresso-Invalidate` response header
365
+ * - `{ data, invalidate }` mutation result envelope
366
+ */
367
+ function unwrapApiResultAndInvalidate(parsedBody, responseHeaders) {
368
+ const headerTags = [];
369
+ if (responseHeaders && typeof responseHeaders.get === 'function') {
370
+ const rawHeader = responseHeaders.get('x-webspresso-invalidate');
371
+ if (rawHeader) {
372
+ for (const tag of rawHeader.split(',')) {
373
+ const trimmed = tag.trim();
374
+ if (trimmed) headerTags.push(trimmed);
375
+ }
376
+ }
377
+ }
378
+
379
+ let data = parsedBody;
380
+ const bodyTags = [];
381
+
382
+ if (
383
+ parsedBody &&
384
+ typeof parsedBody === 'object' &&
385
+ !Array.isArray(parsedBody) &&
386
+ Array.isArray(parsedBody.invalidate) &&
387
+ 'data' in parsedBody
388
+ ) {
389
+ for (const tag of parsedBody.invalidate) {
390
+ if (typeof tag === 'string' && tag.trim()) {
391
+ bodyTags.push(tag.trim());
392
+ }
393
+ }
394
+ data = parsedBody.data;
395
+ // Provide non-enumerable `.data` self-reference on object payloads so both
396
+ // `result.id` and `result.data.id` work seamlessly.
397
+ if (data && typeof data === 'object' && !('data' in data)) {
398
+ Object.defineProperty(data, 'data', {
399
+ value: data,
400
+ enumerable: false,
401
+ configurable: true,
402
+ });
403
+ }
404
+ }
405
+
406
+ const invalidate = Array.from(new Set([...headerTags, ...bodyTags]));
407
+ return { data, invalidate };
408
+ }
409
+
410
+ /**
411
+ * Normalize arguments for `api.get(url, inputOrOptions?, options?)`.
412
+ */
413
+ function normalizeGetArgs(inputOrOptions, explicitOptions) {
414
+ if (explicitOptions && typeof explicitOptions === 'object') {
415
+ const inp = inputOrOptions && typeof inputOrOptions === 'object' ? inputOrOptions : {};
416
+ const query = inp.query && typeof inp.query === 'object' ? inp.query : inp;
417
+ const params = explicitOptions.params || inp.params;
418
+ return {
419
+ ...explicitOptions,
420
+ query,
421
+ params,
422
+ };
423
+ }
424
+
425
+ if (!inputOrOptions || typeof inputOrOptions !== 'object') {
426
+ return {};
427
+ }
428
+
429
+ const keys = Object.keys(inputOrOptions);
430
+ const hasExplicitWrapper =
431
+ 'query' in inputOrOptions ||
432
+ 'params' in inputOrOptions ||
433
+ 'policy' in inputOrOptions ||
434
+ 'key' in inputOrOptions ||
435
+ 'signal' in inputOrOptions ||
436
+ 'headers' in inputOrOptions;
437
+
438
+ if (hasExplicitWrapper && keys.every((k) => RESERVED_OPTION_KEYS.has(k))) {
439
+ return { ...inputOrOptions };
440
+ }
441
+
442
+ // Mix of query keys and reserved options or pure query object
443
+ const query = {};
444
+ const opts = {};
445
+ for (const [k, v] of Object.entries(inputOrOptions)) {
446
+ if (RESERVED_OPTION_KEYS.has(k)) {
447
+ opts[k] = v;
448
+ } else {
449
+ query[k] = v;
450
+ }
451
+ }
452
+ if (opts.query && typeof opts.query === 'object') {
453
+ Object.assign(query, opts.query);
454
+ }
455
+ opts.query = query;
456
+ return opts;
457
+ }
458
+
459
+ /**
460
+ * Create a Typed API Client instance.
461
+ *
462
+ * @param {object} [config]
463
+ * @param {typeof fetch} [config.fetch] - Custom fetch implementation
464
+ * @param {string} [config.baseUrl=''] - Optional base URL prefix
465
+ * @param {() => string|null} [config.getCsrfToken] - Custom CSRF token provider
466
+ * @param {(tags: string[], meta: object) => Promise<unknown>|unknown} [config.onInvalidate] - Fragment invalidation callback
467
+ * @param {(err: Error, meta: object) => void} [config.onRefreshError] - Callback if background fragment refresh fails after mutation
468
+ * @param {AbortSignal} [config.lifecycleSignal] - Controller lifecycle signal (aborts in-flight requests on unmount)
469
+ * @param {() => boolean} [config.isConnected] - Controller connection check
470
+ * @param {object} [config.debug] - Client debugger instance
471
+ */
472
+ function createApiClient(config = {}) {
473
+ const fetchImpl =
474
+ config.fetch || (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null);
475
+ const baseUrl = config.baseUrl ? String(config.baseUrl).replace(/\/+$/, '') : '';
476
+ const lifecycleSignal = config.lifecycleSignal || null;
477
+ const isConnected = typeof config.isConnected === 'function' ? config.isConnected : () => true;
478
+ const debug = config.debug || null;
479
+ const onInvalidate = typeof config.onInvalidate === 'function' ? config.onInvalidate : null;
480
+ const onRefreshError = typeof config.onRefreshError === 'function' ? config.onRefreshError : null;
481
+
482
+ // Concurrency state maps per request key
483
+ const latestMap = new Map(); // key -> { seq: number, controller: AbortController, requestId: string }
484
+ const inFlightMap = new Map(); // key -> Set<string> (active requestIds)
485
+ const queueMap = new Map(); // key -> Promise<unknown>
486
+ let reqCounter = 0;
487
+ let lastRefreshPromise = null;
488
+
489
+ function resolvePolicy(policy) {
490
+ if (!policy) return 'parallel';
491
+ const normalized = String(policy).toLowerCase();
492
+ if (!VALID_POLICIES.has(normalized)) {
493
+ throw new Error(
494
+ `Invalid request concurrency policy "${policy}". Expected one of: latest, drop, queue, parallel.`
495
+ );
496
+ }
497
+ return normalized;
498
+ }
499
+
500
+ /**
501
+ * Core request executor supporting concurrency policies.
502
+ */
503
+ async function executeRequest(method, urlTemplate, body, options = {}) {
504
+ if (!fetchImpl) {
505
+ throw new Error('Global fetch is not available in this environment.');
506
+ }
507
+
508
+ const upperMethod = String(method || 'GET').toUpperCase();
509
+ const policy = resolvePolicy(options.policy || options.concurrency);
510
+ const requestUrl = buildRequestUrl(
511
+ baseUrl ? `${baseUrl}${urlTemplate}` : urlTemplate,
512
+ options.params,
513
+ options.query
514
+ );
515
+ const baseKeyPath = String(urlTemplate || '').split('?')[0];
516
+ const requestKey = options.key ? String(options.key) : `${upperMethod}:${baseKeyPath}`;
517
+ const requestId = `req_${++reqCounter}_${Date.now()}`;
518
+
519
+ // Check controller lifecycle before starting
520
+ if (!isConnected() || (lifecycleSignal && lifecycleSignal.aborted)) {
521
+ throw new ClientRequestError(`Request canceled: controller is disconnected (${upperMethod} ${requestUrl})`, {
522
+ kind: 'canceled',
523
+ method: upperMethod,
524
+ url: requestUrl,
525
+ key: requestKey,
526
+ });
527
+ }
528
+
529
+ // Policy: 'drop' -> Do not start if another request with the same key is currently in flight
530
+ const activeSet = inFlightMap.get(requestKey);
531
+ if (policy === 'drop' && activeSet && activeSet.size > 0) {
532
+ if (debug) {
533
+ debug.trackDiscardedResponse({
534
+ source: 'api',
535
+ key: requestKey,
536
+ url: requestUrl,
537
+ reason: 'dropped-by-policy',
538
+ });
539
+ }
540
+ throw new ClientRequestError(
541
+ `Request dropped by 'drop' concurrency policy: "${requestKey}" is already in flight.`,
542
+ {
543
+ kind: 'canceled',
544
+ code: 'REQUEST_DROPPED',
545
+ method: upperMethod,
546
+ url: requestUrl,
547
+ key: requestKey,
548
+ isDropped: true,
549
+ }
550
+ );
551
+ }
552
+
553
+ // Policy: 'queue' -> Chain onto existing queue for this key
554
+ if (policy === 'queue') {
555
+ const prevTail = queueMap.get(requestKey) || Promise.resolve();
556
+ const nextTask = prevTail
557
+ .catch(() => {})
558
+ .then(() => runSingleRequest(upperMethod, requestUrl, body, options, requestKey, requestId, 'queue'));
559
+ queueMap.set(
560
+ requestKey,
561
+ nextTask.catch(() => {})
562
+ );
563
+ return nextTask;
564
+ }
565
+
566
+ return runSingleRequest(upperMethod, requestUrl, body, options, requestKey, requestId, policy);
567
+ }
568
+
569
+ async function runSingleRequest(upperMethod, requestUrl, body, options, requestKey, requestId, policy) {
570
+ const abortController = new AbortController();
571
+ let superseded = false;
572
+ let currentSeq = 1;
573
+
574
+ // Policy: 'latest' -> Abort previous in-flight request for this key and increment sequence
575
+ if (policy === 'latest') {
576
+ const prev = latestMap.get(requestKey);
577
+ if (prev) {
578
+ currentSeq = prev.seq + 1;
579
+ prev.superseded = true;
580
+ try {
581
+ prev.controller.abort();
582
+ } catch (_e) {
583
+ // Ignore
584
+ }
585
+ }
586
+ latestMap.set(requestKey, {
587
+ seq: currentSeq,
588
+ controller: abortController,
589
+ requestId,
590
+ superseded: false,
591
+ });
592
+ }
593
+
594
+ // Link caller AbortSignal and controller lifecycleSignal
595
+ const onCallerAbort = () => abortController.abort();
596
+ if (options.signal) {
597
+ if (options.signal.aborted) {
598
+ abortController.abort();
599
+ } else {
600
+ options.signal.addEventListener('abort', onCallerAbort, { once: true });
601
+ }
602
+ }
603
+ if (lifecycleSignal) {
604
+ if (lifecycleSignal.aborted) {
605
+ abortController.abort();
606
+ } else {
607
+ lifecycleSignal.addEventListener('abort', onCallerAbort, { once: true });
608
+ }
609
+ }
610
+
611
+ if (!inFlightMap.has(requestKey)) {
612
+ inFlightMap.set(requestKey, new Set());
613
+ }
614
+ inFlightMap.get(requestKey).add(requestId);
615
+
616
+ if (debug) {
617
+ debug.trackRequestStart({
618
+ requestId,
619
+ key: requestKey,
620
+ method: upperMethod,
621
+ url: requestUrl,
622
+ policy,
623
+ payload: body,
624
+ });
625
+ }
626
+
627
+ const headers = {
628
+ Accept: options.raw ? '*/*' : 'application/json',
629
+ 'X-Requested-With': 'XMLHttpRequest',
630
+ ...(options.headers || {}),
631
+ };
632
+
633
+ // Attach CSRF token on state-changing requests
634
+ if (MUTATION_METHODS.has(upperMethod)) {
635
+ const csrfToken =
636
+ options.csrfToken ||
637
+ (typeof config.getCsrfToken === 'function' ? config.getCsrfToken() : discoverCsrfToken());
638
+ if (csrfToken && !headers['X-CSRF-Token'] && !headers['x-csrf-token']) {
639
+ headers['X-CSRF-Token'] = csrfToken;
640
+ }
641
+ }
642
+
643
+ const serializedBody =
644
+ upperMethod === 'GET' || upperMethod === 'HEAD'
645
+ ? undefined
646
+ : serializeRequestBody(body, headers);
647
+
648
+ try {
649
+ let response;
650
+ try {
651
+ response = await fetchImpl(requestUrl, {
652
+ method: upperMethod,
653
+ headers,
654
+ body: serializedBody,
655
+ credentials: options.credentials || 'same-origin',
656
+ signal: abortController.signal,
657
+ });
658
+ } catch (fetchErr) {
659
+ const latestEntry = policy === 'latest' ? latestMap.get(requestKey) : null;
660
+ if (latestEntry && (latestEntry.seq !== currentSeq || latestEntry.superseded)) {
661
+ superseded = true;
662
+ }
663
+ const isAbort =
664
+ superseded ||
665
+ abortController.signal.aborted ||
666
+ (fetchErr && (fetchErr.name === 'AbortError' || fetchErr.code === 'ABORT_ERR'));
667
+
668
+ if (isAbort) {
669
+ if (debug) {
670
+ debug.trackDiscardedResponse({
671
+ source: 'api',
672
+ key: requestKey,
673
+ url: requestUrl,
674
+ reason: superseded ? 'superseded-by-latest' : 'aborted',
675
+ version: currentSeq,
676
+ currentVersion: latestEntry ? latestEntry.seq : currentSeq,
677
+ });
678
+ debug.trackRequestEnd(requestId, { status: 'canceled', errorKind: 'canceled' });
679
+ }
680
+ throw new ClientRequestError(
681
+ superseded
682
+ ? `Request superseded by newer '${requestKey}' request.`
683
+ : `Request canceled (${upperMethod} ${requestUrl}).`,
684
+ {
685
+ kind: 'canceled',
686
+ code: superseded ? 'REQUEST_SUPERSEDED' : 'REQUEST_CANCELED',
687
+ method: upperMethod,
688
+ url: requestUrl,
689
+ key: requestKey,
690
+ isSuperseded: superseded,
691
+ cause: fetchErr,
692
+ }
693
+ );
694
+ }
695
+
696
+ if (debug) {
697
+ debug.trackRequestEnd(requestId, { status: 'failed', errorKind: 'network' });
698
+ }
699
+ throw new ClientRequestError(
700
+ fetchErr && fetchErr.message ? fetchErr.message : `Network error (${upperMethod} ${requestUrl})`,
701
+ {
702
+ kind: 'network',
703
+ method: upperMethod,
704
+ url: requestUrl,
705
+ key: requestKey,
706
+ cause: fetchErr,
707
+ }
708
+ );
709
+ }
710
+
711
+ // Check if superseded by a newer 'latest' request while awaiting response/body
712
+ const checkSupersededOrDisconnected = () => {
713
+ if (policy === 'latest') {
714
+ const latestEntry = latestMap.get(requestKey);
715
+ if (latestEntry && (latestEntry.seq !== currentSeq || latestEntry.superseded)) {
716
+ if (debug) {
717
+ debug.trackDiscardedResponse({
718
+ source: 'api',
719
+ key: requestKey,
720
+ url: requestUrl,
721
+ reason: 'superseded-by-latest',
722
+ version: currentSeq,
723
+ currentVersion: latestEntry.seq,
724
+ });
725
+ debug.trackRequestEnd(requestId, {
726
+ status: 'discarded',
727
+ httpStatus: response.status,
728
+ errorKind: 'canceled',
729
+ });
730
+ }
731
+ throw new ClientRequestError(`Stale response discarded for '${requestKey}'.`, {
732
+ kind: 'canceled',
733
+ code: 'REQUEST_SUPERSEDED',
734
+ status: response.status,
735
+ method: upperMethod,
736
+ url: requestUrl,
737
+ key: requestKey,
738
+ isSuperseded: true,
739
+ });
740
+ }
741
+ }
742
+ if (!isConnected()) {
743
+ if (debug) {
744
+ debug.trackDiscardedResponse({
745
+ source: 'api',
746
+ key: requestKey,
747
+ url: requestUrl,
748
+ reason: 'controller-disconnected',
749
+ });
750
+ debug.trackRequestEnd(requestId, {
751
+ status: 'discarded',
752
+ httpStatus: response.status,
753
+ errorKind: 'canceled',
754
+ });
755
+ }
756
+ throw new ClientRequestError(
757
+ `Response discarded: controller disconnected (${upperMethod} ${requestUrl}).`,
758
+ {
759
+ kind: 'canceled',
760
+ code: 'CONTROLLER_DISCONNECTED',
761
+ status: response.status,
762
+ method: upperMethod,
763
+ url: requestUrl,
764
+ key: requestKey,
765
+ }
766
+ );
767
+ }
768
+ };
769
+
770
+ checkSupersededOrDisconnected();
771
+
772
+ // Escape hatch: return raw Response without body consumption
773
+ if (options.raw) {
774
+ if (!response.ok) {
775
+ throw new ClientRequestError(`HTTP ${response.status} (${upperMethod} ${requestUrl})`, {
776
+ kind: 'http',
777
+ status: response.status,
778
+ method: upperMethod,
779
+ url: requestUrl,
780
+ key: requestKey,
781
+ });
782
+ }
783
+ if (debug) {
784
+ debug.trackRequestEnd(requestId, { status: 'completed', httpStatus: response.status });
785
+ }
786
+ return response;
787
+ }
788
+
789
+ // Parse response body according to wire format
790
+ let parsedBody;
791
+ const status = response.status;
792
+ const contentType =
793
+ response.headers && typeof response.headers.get === 'function'
794
+ ? response.headers.get('content-type') || ''
795
+ : '';
796
+
797
+ if (status === 204 || status === 205) {
798
+ parsedBody = undefined;
799
+ } else if (typeof response.text === 'function') {
800
+ const rawText = await response.text();
801
+ checkSupersededOrDisconnected();
802
+ if (!rawText || !rawText.trim()) {
803
+ parsedBody = undefined;
804
+ } else if (contentType.includes('application/json') || rawText.trim().startsWith('{') || rawText.trim().startsWith('[')) {
805
+ try {
806
+ parsedBody = JSON.parse(rawText);
807
+ } catch (_jsonErr) {
808
+ parsedBody = rawText;
809
+ }
810
+ } else {
811
+ parsedBody = rawText;
812
+ }
813
+ } else if (typeof response.json === 'function') {
814
+ parsedBody = await response.json();
815
+ checkSupersededOrDisconnected();
816
+ }
817
+
818
+ // Handle non-2xx HTTP responses
819
+ if (!response.ok) {
820
+ const errPayload = parsedBody && typeof parsedBody === 'object' ? parsedBody : {};
821
+ const errBlock = errPayload.error && typeof errPayload.error === 'object' ? errPayload.error : errPayload;
822
+ const errCode = errBlock.code || errPayload.code || null;
823
+ const { fieldErrors, fieldErrorList, issues, formError } = extractValidationErrors(parsedBody);
824
+
825
+ const isValidationStatus =
826
+ status === 422 ||
827
+ errCode === 'VALIDATION_ERROR' ||
828
+ (status === 400 && (issues.length > 0 || Object.keys(fieldErrors).length > 0));
829
+
830
+ const errorKind = isValidationStatus ? 'validation' : 'http';
831
+ const message =
832
+ formError ||
833
+ (typeof errBlock.message === 'string' && errBlock.message) ||
834
+ (typeof errPayload.message === 'string' && errPayload.message) ||
835
+ `HTTP ${status} (${upperMethod} ${requestUrl})`;
836
+
837
+ if (debug) {
838
+ debug.trackRequestEnd(requestId, {
839
+ status: 'failed',
840
+ httpStatus: status,
841
+ errorKind,
842
+ });
843
+ }
844
+
845
+ throw new ClientRequestError(message, {
846
+ kind: errorKind,
847
+ status,
848
+ code: errCode || defaultCodeForKind(errorKind, status),
849
+ method: upperMethod,
850
+ url: requestUrl,
851
+ key: requestKey,
852
+ fieldErrors,
853
+ fieldErrorList,
854
+ issues,
855
+ formError,
856
+ data: parsedBody,
857
+ });
858
+ }
859
+
860
+ // 2xx Success: unwrap data and check for fragment invalidations
861
+ const { data, invalidate } = unwrapApiResultAndInvalidate(parsedBody, response.headers);
862
+
863
+ if (debug) {
864
+ debug.trackRequestEnd(requestId, { status: 'completed', httpStatus: status });
865
+ }
866
+
867
+ // Trigger two-phase fragment invalidation if tags are present.
868
+ // IMPORTANT: Refresh failure MUST NOT reject or fail the completed mutation!
869
+ if (invalidate.length > 0 && onInvalidate) {
870
+ const chainId = debug
871
+ ? debug.startCausalChain({
872
+ method: upperMethod,
873
+ url: requestUrl,
874
+ requestId,
875
+ tags: invalidate,
876
+ })
877
+ : null;
878
+
879
+ const refreshTask = Promise.resolve()
880
+ .then(() =>
881
+ onInvalidate(invalidate, {
882
+ method: upperMethod,
883
+ url: requestUrl,
884
+ requestId,
885
+ chainId,
886
+ })
887
+ )
888
+ .catch((refreshErr) => {
889
+ const notifyErr =
890
+ typeof options.onRefreshError === 'function' ? options.onRefreshError : onRefreshError;
891
+ if (notifyErr) {
892
+ try {
893
+ notifyErr(refreshErr, { tags: invalidate, method: upperMethod, url: requestUrl, chainId });
894
+ } catch (_e) {
895
+ // Ignore
896
+ }
897
+ }
898
+ return { ok: false, error: refreshErr };
899
+ });
900
+
901
+ lastRefreshPromise = refreshTask;
902
+
903
+ if (data && typeof data === 'object') {
904
+ Object.defineProperty(data, '__invalidate', {
905
+ value: invalidate,
906
+ enumerable: false,
907
+ configurable: true,
908
+ });
909
+ Object.defineProperty(data, '__refreshPromise', {
910
+ value: refreshTask,
911
+ enumerable: false,
912
+ configurable: true,
913
+ });
914
+ }
915
+ }
916
+
917
+ return data;
918
+ } finally {
919
+ const set = inFlightMap.get(requestKey);
920
+ if (set) {
921
+ set.delete(requestId);
922
+ if (set.size === 0) {
923
+ inFlightMap.delete(requestKey);
924
+ }
925
+ }
926
+ if (options.signal) {
927
+ options.signal.removeEventListener('abort', onCallerAbort);
928
+ }
929
+ if (lifecycleSignal) {
930
+ lifecycleSignal.removeEventListener('abort', onCallerAbort);
931
+ }
932
+ }
933
+ }
934
+
935
+ const client = {
936
+ get(url, inputOrOptions, explicitOptions) {
937
+ const opts = normalizeGetArgs(inputOrOptions, explicitOptions);
938
+ return executeRequest('GET', url, undefined, opts);
939
+ },
940
+
941
+ post(url, body, options = {}) {
942
+ return executeRequest('POST', url, body, options);
943
+ },
944
+
945
+ put(url, body, options = {}) {
946
+ return executeRequest('PUT', url, body, options);
947
+ },
948
+
949
+ patch(url, body, options = {}) {
950
+ return executeRequest('PATCH', url, body, options);
951
+ },
952
+
953
+ delete(url, bodyOrOptions, explicitOptions) {
954
+ if (explicitOptions && typeof explicitOptions === 'object') {
955
+ return executeRequest('DELETE', url, bodyOrOptions, explicitOptions);
956
+ }
957
+ if (
958
+ bodyOrOptions &&
959
+ typeof bodyOrOptions === 'object' &&
960
+ Object.keys(bodyOrOptions).every((k) => RESERVED_OPTION_KEYS.has(k))
961
+ ) {
962
+ return executeRequest('DELETE', url, undefined, bodyOrOptions);
963
+ }
964
+ return executeRequest('DELETE', url, bodyOrOptions, {});
965
+ },
966
+
967
+ request(method, url, body, options = {}) {
968
+ return executeRequest(method, url, body, options);
969
+ },
970
+
971
+ /**
972
+ * Escape hatch for arbitrary raw responses (blobs, downloads, custom headers).
973
+ */
974
+ raw(url, options = {}) {
975
+ const method = options.method || 'GET';
976
+ return executeRequest(method, url, options.body, { ...options, raw: true });
977
+ },
978
+
979
+ /**
980
+ * Escape hatch for streaming endpoints (chunked text / NDJSON / SSE).
981
+ * Yields decoded UTF-8 string chunks as an async generator.
982
+ */
983
+ async *stream(url, options = {}) {
984
+ const response = await client.raw(url, options);
985
+ if (!response.body) {
986
+ const text = await response.text();
987
+ if (text) yield text;
988
+ return;
989
+ }
990
+ const reader = response.body.getReader();
991
+ const decoder = new TextDecoder();
992
+ try {
993
+ while (true) {
994
+ const { done, value } = await reader.read();
995
+ if (done) break;
996
+ yield decoder.decode(value, { stream: true });
997
+ }
998
+ const tail = decoder.decode();
999
+ if (tail) yield tail;
1000
+ } finally {
1001
+ try {
1002
+ reader.releaseLock();
1003
+ } catch (_e) {
1004
+ // Ignore
1005
+ }
1006
+ }
1007
+ },
1008
+
1009
+ isInFlight(key) {
1010
+ if (key) {
1011
+ const set = inFlightMap.get(key);
1012
+ return Boolean(set && set.size > 0);
1013
+ }
1014
+ return inFlightMap.size > 0;
1015
+ },
1016
+
1017
+ get lastRefreshPromise() {
1018
+ return lastRefreshPromise;
1019
+ },
1020
+ };
1021
+
1022
+ return client;
1023
+ }
1024
+
1025
+ module.exports = {
1026
+ ClientRequestError,
1027
+ createApiClient,
1028
+ discoverCsrfToken,
1029
+ buildRequestUrl,
1030
+ extractValidationErrors,
1031
+ unwrapApiResultAndInvalidate,
1032
+ };
1033
+