@spfn/core 0.1.0-alpha.88 → 0.2.0-beta.10

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 (97) hide show
  1. package/README.md +298 -466
  2. package/dist/boss-DI1r4kTS.d.ts +244 -0
  3. package/dist/cache/index.d.ts +13 -33
  4. package/dist/cache/index.js +14 -703
  5. package/dist/cache/index.js.map +1 -1
  6. package/dist/codegen/index.d.ts +214 -17
  7. package/dist/codegen/index.js +231 -1420
  8. package/dist/codegen/index.js.map +1 -1
  9. package/dist/config/index.d.ts +1227 -0
  10. package/dist/config/index.js +273 -0
  11. package/dist/config/index.js.map +1 -0
  12. package/dist/db/index.d.ts +741 -59
  13. package/dist/db/index.js +1063 -1226
  14. package/dist/db/index.js.map +1 -1
  15. package/dist/env/index.d.ts +658 -308
  16. package/dist/env/index.js +503 -928
  17. package/dist/env/index.js.map +1 -1
  18. package/dist/env/loader.d.ts +87 -0
  19. package/dist/env/loader.js +70 -0
  20. package/dist/env/loader.js.map +1 -0
  21. package/dist/errors/index.d.ts +417 -29
  22. package/dist/errors/index.js +359 -98
  23. package/dist/errors/index.js.map +1 -1
  24. package/dist/event/index.d.ts +41 -0
  25. package/dist/event/index.js +131 -0
  26. package/dist/event/index.js.map +1 -0
  27. package/dist/event/sse/client.d.ts +82 -0
  28. package/dist/event/sse/client.js +115 -0
  29. package/dist/event/sse/client.js.map +1 -0
  30. package/dist/event/sse/index.d.ts +40 -0
  31. package/dist/event/sse/index.js +92 -0
  32. package/dist/event/sse/index.js.map +1 -0
  33. package/dist/job/index.d.ts +218 -0
  34. package/dist/job/index.js +410 -0
  35. package/dist/job/index.js.map +1 -0
  36. package/dist/logger/index.d.ts +20 -79
  37. package/dist/logger/index.js +82 -387
  38. package/dist/logger/index.js.map +1 -1
  39. package/dist/middleware/index.d.ts +102 -20
  40. package/dist/middleware/index.js +51 -705
  41. package/dist/middleware/index.js.map +1 -1
  42. package/dist/nextjs/index.d.ts +120 -0
  43. package/dist/nextjs/index.js +448 -0
  44. package/dist/nextjs/index.js.map +1 -0
  45. package/dist/{client/nextjs/index.d.ts → nextjs/server.d.ts} +335 -262
  46. package/dist/nextjs/server.js +637 -0
  47. package/dist/nextjs/server.js.map +1 -0
  48. package/dist/route/index.d.ts +879 -25
  49. package/dist/route/index.js +697 -1271
  50. package/dist/route/index.js.map +1 -1
  51. package/dist/route/types.d.ts +9 -0
  52. package/dist/route/types.js +3 -0
  53. package/dist/route/types.js.map +1 -0
  54. package/dist/router-Di7ENoah.d.ts +151 -0
  55. package/dist/server/index.d.ts +345 -64
  56. package/dist/server/index.js +1174 -3233
  57. package/dist/server/index.js.map +1 -1
  58. package/dist/types-B-e_f2dQ.d.ts +121 -0
  59. package/dist/types-BGl4QL1w.d.ts +77 -0
  60. package/dist/types-BOPTApC2.d.ts +245 -0
  61. package/docs/cache.md +133 -0
  62. package/docs/codegen.md +74 -0
  63. package/docs/database.md +346 -0
  64. package/docs/entity.md +539 -0
  65. package/docs/env.md +477 -0
  66. package/docs/errors.md +319 -0
  67. package/docs/event.md +116 -0
  68. package/docs/file-upload.md +717 -0
  69. package/docs/job.md +131 -0
  70. package/docs/logger.md +108 -0
  71. package/docs/middleware.md +337 -0
  72. package/docs/nextjs.md +241 -0
  73. package/docs/repository.md +496 -0
  74. package/docs/route.md +497 -0
  75. package/docs/server.md +307 -0
  76. package/package.json +68 -48
  77. package/dist/auto-loader-JFaZ9gON.d.ts +0 -80
  78. package/dist/client/index.d.ts +0 -358
  79. package/dist/client/index.js +0 -357
  80. package/dist/client/index.js.map +0 -1
  81. package/dist/client/nextjs/index.js +0 -371
  82. package/dist/client/nextjs/index.js.map +0 -1
  83. package/dist/codegen/generators/index.d.ts +0 -19
  84. package/dist/codegen/generators/index.js +0 -1404
  85. package/dist/codegen/generators/index.js.map +0 -1
  86. package/dist/database-errors-BNNmLTJE.d.ts +0 -86
  87. package/dist/events/index.d.ts +0 -183
  88. package/dist/events/index.js +0 -77
  89. package/dist/events/index.js.map +0 -1
  90. package/dist/index-DHiAqhKv.d.ts +0 -101
  91. package/dist/index.d.ts +0 -8
  92. package/dist/index.js +0 -3674
  93. package/dist/index.js.map +0 -1
  94. package/dist/types/index.d.ts +0 -121
  95. package/dist/types/index.js +0 -38
  96. package/dist/types/index.js.map +0 -1
  97. package/dist/types-BXibIEyj.d.ts +0 -60
@@ -0,0 +1,448 @@
1
+ import { env } from '@spfn/core/config';
2
+ import { ErrorRegistry, errorRegistry } from '@spfn/core/errors';
3
+ import { logger } from '@spfn/core/logger';
4
+
5
+ // src/nextjs/client/core.ts
6
+
7
+ // src/nextjs/client/debug-logs.ts
8
+ function logCookieAutoDetection(logger2, cookies) {
9
+ logger2.debug("Auto-detected server environment, forwarding cookies", {
10
+ cookieCount: cookies.length,
11
+ cookieNames: cookies.map((c) => c.name)
12
+ });
13
+ }
14
+ function logRequest(logger2, routeName, method, url, hasBody) {
15
+ logger2.debug("\u2192 Request", {
16
+ route: routeName,
17
+ method,
18
+ url,
19
+ hasBody
20
+ });
21
+ }
22
+ function logResponse(logger2, routeName, status, hasBody) {
23
+ logger2.debug("\u2190 Response", {
24
+ route: routeName,
25
+ status,
26
+ hasBody
27
+ });
28
+ }
29
+ function logErrorResponse(logger2, status, body) {
30
+ logger2.debug("Error response received", {
31
+ status,
32
+ hasBody: !!body,
33
+ bodyType: typeof body,
34
+ hasTypeField: body && typeof body === "object" && "__type" in body,
35
+ typeValue: body?.__type
36
+ });
37
+ }
38
+ function logErrorDeserializationAttempt(logger2, errorType, registeredTypes) {
39
+ logger2.debug("Attempting error deserialization", {
40
+ errorType,
41
+ hasRegistry: true,
42
+ registeredTypes
43
+ });
44
+ }
45
+ function logErrorDeserializationSuccess(logger2, error) {
46
+ logger2.debug("Error deserialized successfully", {
47
+ errorName: error?.name,
48
+ errorConstructor: error?.constructor.name,
49
+ message: error?.message
50
+ });
51
+ }
52
+ function logErrorDeserializationFailure(logger2, error) {
53
+ logger2.debug("Deserialization failed", {
54
+ errorName: error instanceof Error ? error.name : "unknown",
55
+ errorMessage: error instanceof Error ? error.message : String(error)
56
+ });
57
+ }
58
+ function logErrorDeserializationSkipped(logger2, errorRegistry, body) {
59
+ const reason = !errorRegistry ? "no registry" : !body ? "no body" : typeof body !== "object" ? "body not object" : !("__type" in body) ? "no __type field" : "unknown";
60
+ logger2.debug("Skipping error deserialization", { reason });
61
+ }
62
+ function logThrowingDeserializedError(logger2, error) {
63
+ logger2.debug("Throwing deserialized error", {
64
+ errorName: error.name,
65
+ errorConstructorName: error.constructor.name,
66
+ prototype: Object.getPrototypeOf(error).constructor.name
67
+ });
68
+ }
69
+
70
+ // src/nextjs/client/errors.ts
71
+ var ApiError = class extends Error {
72
+ constructor(message, status, url, response, errorType) {
73
+ super(message);
74
+ this.status = status;
75
+ this.url = url;
76
+ this.response = response;
77
+ this.errorType = errorType;
78
+ this.name = "ApiError";
79
+ }
80
+ };
81
+
82
+ // src/nextjs/shared.ts
83
+ function buildCookieHeader(cookies) {
84
+ return Object.entries(cookies).map(([key, value]) => `${key}=${value}`).join("; ");
85
+ }
86
+ async function parseResponseBody(response) {
87
+ if (response.status === 204) {
88
+ return null;
89
+ }
90
+ const contentType = response.headers.get("content-type");
91
+ if (contentType?.includes("application/json")) {
92
+ const text = await response.text();
93
+ return text ? JSON.parse(text) : null;
94
+ } else {
95
+ return await response.text();
96
+ }
97
+ }
98
+
99
+ // src/nextjs/client/helpers.ts
100
+ async function autoDetectServerCookies() {
101
+ try {
102
+ const { cookies } = await import('next/headers');
103
+ const cookieStore = await cookies();
104
+ const allCookies = cookieStore.getAll();
105
+ return Object.fromEntries(
106
+ allCookies.map((cookie) => [cookie.name, cookie.value])
107
+ );
108
+ } catch (error) {
109
+ return {};
110
+ }
111
+ }
112
+ async function executeFetchWithTimeout(url, init, timeout, customFetch = fetch) {
113
+ const controller = new AbortController();
114
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
115
+ try {
116
+ const response = await customFetch(url, {
117
+ ...init,
118
+ signal: controller.signal
119
+ });
120
+ clearTimeout(timeoutId);
121
+ return response;
122
+ } catch (error) {
123
+ clearTimeout(timeoutId);
124
+ throw error;
125
+ }
126
+ }
127
+ async function handleErrorResponse(response, body, fullUrl, errorRegistry, debug, logger2) {
128
+ if (debug) {
129
+ logErrorResponse(logger2, response.status, body);
130
+ }
131
+ let deserializedError = null;
132
+ if (errorRegistry && body && typeof body === "object" && "__type" in body) {
133
+ if (debug) {
134
+ logErrorDeserializationAttempt(logger2, body.__type, errorRegistry.getRegisteredTypes());
135
+ }
136
+ try {
137
+ deserializedError = errorRegistry.deserialize(body);
138
+ if (debug) {
139
+ logErrorDeserializationSuccess(logger2, deserializedError);
140
+ }
141
+ } catch (deserializeError) {
142
+ if (debug) {
143
+ logErrorDeserializationFailure(logger2, deserializeError);
144
+ }
145
+ }
146
+ } else if (debug) {
147
+ logErrorDeserializationSkipped(logger2, errorRegistry, body);
148
+ }
149
+ if (deserializedError) {
150
+ if (debug) {
151
+ logThrowingDeserializedError(logger2, deserializedError);
152
+ }
153
+ throw deserializedError;
154
+ }
155
+ if (response.status === 404 && process.env.NODE_ENV !== "production") {
156
+ logger2.warn(
157
+ "\n\u26A0\uFE0F 404 Not Found\n\nCheck the following:\n 1. Routes are registered in server.config.ts:\n \u2192 defineServerConfig().routes(appRouter)\n 2. Delete .spfn cache if you recently added new routes:\n \u2192 rm -rf .spfn\n"
158
+ );
159
+ }
160
+ throw new ApiError(
161
+ body?.message || `HTTP ${response.status}: ${response.statusText}`,
162
+ response.status,
163
+ fullUrl,
164
+ body,
165
+ "http"
166
+ );
167
+ }
168
+
169
+ // src/nextjs/client/builder.ts
170
+ var RouteCallBuilder = class _RouteCallBuilder {
171
+ constructor(executor, routeName) {
172
+ this.executor = executor;
173
+ this.routeName = routeName;
174
+ }
175
+ _headers;
176
+ _cookies;
177
+ _fetchOptions;
178
+ _onRequest;
179
+ _onResponse;
180
+ /**
181
+ * Clone builder
182
+ */
183
+ clone() {
184
+ const builder = new _RouteCallBuilder(
185
+ this.executor,
186
+ this.routeName
187
+ );
188
+ builder._headers = this._headers;
189
+ builder._cookies = this._cookies;
190
+ builder._fetchOptions = this._fetchOptions;
191
+ builder._onRequest = this._onRequest;
192
+ builder._onResponse = this._onResponse;
193
+ return builder;
194
+ }
195
+ /**
196
+ * Set request headers
197
+ */
198
+ headers(headers) {
199
+ const builder = this.clone();
200
+ builder._headers = { ...this._headers, ...headers };
201
+ return builder;
202
+ }
203
+ /**
204
+ * Set cookies
205
+ */
206
+ cookies(cookies) {
207
+ const builder = this.clone();
208
+ builder._cookies = { ...this._cookies, ...cookies };
209
+ return builder;
210
+ }
211
+ /**
212
+ * Set Next.js fetch options
213
+ */
214
+ fetchOptions(options) {
215
+ const builder = this.clone();
216
+ builder._fetchOptions = { ...this._fetchOptions, ...options };
217
+ return builder;
218
+ }
219
+ /**
220
+ * Set request interceptor
221
+ */
222
+ onRequest(interceptor) {
223
+ const builder = this.clone();
224
+ builder._onRequest = interceptor;
225
+ return builder;
226
+ }
227
+ /**
228
+ * Set response interceptor
229
+ */
230
+ onResponse(interceptor) {
231
+ const builder = this.clone();
232
+ builder._onResponse = interceptor;
233
+ return builder;
234
+ }
235
+ /**
236
+ * Execute the API call with structured input
237
+ *
238
+ * Input structure matches the server-side route definition:
239
+ * - params: Path parameters (e.g., { id: '123' } for /users/:id)
240
+ * - query: Query string parameters
241
+ * - body: Request body (for POST, PUT, PATCH)
242
+ */
243
+ call(input) {
244
+ const options = {};
245
+ if (this._headers) {
246
+ options.headers = this._headers;
247
+ }
248
+ if (this._cookies) {
249
+ options.cookies = this._cookies;
250
+ }
251
+ if (this._fetchOptions) {
252
+ options.fetchOptions = this._fetchOptions;
253
+ }
254
+ if (this._onRequest) {
255
+ options.onRequest = this._onRequest;
256
+ }
257
+ if (this._onResponse) {
258
+ options.onResponse = this._onResponse;
259
+ }
260
+ return this.executor(input || {}, options);
261
+ }
262
+ };
263
+
264
+ // src/nextjs/client/core.ts
265
+ var apiLogger = logger.child("@spfn/core:api-client");
266
+ function createApi(config = {}) {
267
+ const {
268
+ baseUrl = "/api/rpc",
269
+ headers: defaultHeaders = {},
270
+ timeout = 3e4,
271
+ fetch: customFetch = fetch,
272
+ onRequest: globalOnRequest,
273
+ onResponse: globalOnResponse,
274
+ errorRegistry: errorRegistryConfig,
275
+ debug = false
276
+ } = config;
277
+ const errorRegistry$1 = Array.isArray(errorRegistryConfig) ? new ErrorRegistry([errorRegistry, ...errorRegistryConfig]) : errorRegistryConfig ?? errorRegistry;
278
+ if (debug) {
279
+ apiLogger.debug("API client initialized", { baseUrl });
280
+ }
281
+ async function executeCall(routeName, input = {}, options = {}) {
282
+ const hasBody = input.body !== void 0;
283
+ const hasFormData = input.formData !== void 0 && Object.keys(input.formData).length > 0;
284
+ const method = hasBody || hasFormData ? "POST" : "GET";
285
+ let appUrl = env.SPFN_APP_URL || "";
286
+ if (!appUrl && typeof window === "undefined") {
287
+ try {
288
+ const { headers: headers2 } = await import('next/headers');
289
+ const headersList = await headers2();
290
+ const host = headersList.get("host");
291
+ const protocol = headersList.get("x-forwarded-proto") || "http";
292
+ if (host) {
293
+ appUrl = `${protocol}://${host}`;
294
+ if (debug) {
295
+ apiLogger.debug(`Auto-detected app URL from headers: ${appUrl}`);
296
+ }
297
+ }
298
+ } catch {
299
+ if (debug) {
300
+ apiLogger.warn("Could not determine app URL in SSR environment, using relative URL");
301
+ }
302
+ }
303
+ }
304
+ let fullUrl;
305
+ if (method === "GET") {
306
+ const inputParam = encodeURIComponent(JSON.stringify(input));
307
+ fullUrl = `${appUrl}${baseUrl}/${routeName}?input=${inputParam}`;
308
+ } else {
309
+ fullUrl = `${appUrl}${baseUrl}/${routeName}`;
310
+ }
311
+ const headers = {
312
+ ...hasFormData ? {} : { "Content-Type": "application/json" },
313
+ ...defaultHeaders,
314
+ ...options.headers
315
+ };
316
+ const autoDetectedCookies = await autoDetectServerCookies();
317
+ const cookiesToSend = {
318
+ ...autoDetectedCookies,
319
+ ...options.cookies || {}
320
+ };
321
+ if (Object.keys(cookiesToSend).length > 0) {
322
+ headers["Cookie"] = buildCookieHeader(cookiesToSend);
323
+ }
324
+ if (debug && Object.keys(autoDetectedCookies).length > 0) {
325
+ const cookieArray = Object.entries(autoDetectedCookies).map(([name, value]) => ({ name, value }));
326
+ logCookieAutoDetection(apiLogger, cookieArray);
327
+ }
328
+ const requestInit = {
329
+ method,
330
+ headers,
331
+ ...options.fetchOptions
332
+ };
333
+ if (method === "POST") {
334
+ if (hasFormData) {
335
+ const formData = new FormData();
336
+ const metadata = {};
337
+ if (input.params) metadata.params = input.params;
338
+ if (input.query) metadata.query = input.query;
339
+ if (input.headers) metadata.headers = input.headers;
340
+ if (input.cookies) metadata.cookies = input.cookies;
341
+ if (Object.keys(metadata).length > 0) {
342
+ formData.append("__metadata", JSON.stringify(metadata));
343
+ }
344
+ for (const [key, value] of Object.entries(input.formData)) {
345
+ if (value instanceof File) {
346
+ formData.append(key, value);
347
+ } else if (Array.isArray(value)) {
348
+ for (const item of value) {
349
+ if (item instanceof File) {
350
+ formData.append(key, item);
351
+ } else {
352
+ formData.append(key, String(item));
353
+ }
354
+ }
355
+ } else if (value !== void 0 && value !== null) {
356
+ formData.append(key, String(value));
357
+ }
358
+ }
359
+ requestInit.body = formData;
360
+ } else {
361
+ requestInit.body = JSON.stringify(input);
362
+ }
363
+ }
364
+ let init = requestInit;
365
+ if (globalOnRequest) {
366
+ init = await globalOnRequest(fullUrl, init);
367
+ }
368
+ if (options.onRequest) {
369
+ init = await options.onRequest(fullUrl, init);
370
+ }
371
+ if (debug) {
372
+ logRequest(apiLogger, routeName, method, fullUrl, !!init.body);
373
+ }
374
+ let response;
375
+ let body;
376
+ try {
377
+ response = await executeFetchWithTimeout(fullUrl, init, timeout, customFetch);
378
+ body = await parseResponseBody(response);
379
+ if (globalOnResponse) {
380
+ const result = await globalOnResponse(response, body);
381
+ response = result.response;
382
+ body = result.body;
383
+ }
384
+ if (options.onResponse) {
385
+ const result = await options.onResponse(response, body);
386
+ response = result.response;
387
+ body = result.body;
388
+ }
389
+ if (debug) {
390
+ logResponse(apiLogger, routeName, response.status, !!body);
391
+ }
392
+ } catch (error) {
393
+ if (error instanceof Error && error.name === "AbortError") {
394
+ apiLogger.error("Request timeout", {
395
+ route: routeName,
396
+ method,
397
+ url: fullUrl,
398
+ timeout
399
+ });
400
+ throw new ApiError(
401
+ `Request timeout after ${timeout}ms`,
402
+ 408,
403
+ fullUrl,
404
+ void 0,
405
+ "timeout"
406
+ );
407
+ }
408
+ const errorMessage = error instanceof Error ? error.message : "Network error";
409
+ apiLogger.error("Network error", {
410
+ route: routeName,
411
+ method,
412
+ url: fullUrl,
413
+ error: errorMessage,
414
+ errorName: error instanceof Error ? error.name : "unknown"
415
+ });
416
+ throw new ApiError(
417
+ errorMessage,
418
+ 0,
419
+ fullUrl,
420
+ void 0,
421
+ "network"
422
+ );
423
+ }
424
+ if (!response.ok) {
425
+ await handleErrorResponse(response, body, fullUrl, errorRegistry$1, debug, apiLogger);
426
+ }
427
+ return body;
428
+ }
429
+ function buildProxy(prefix = "") {
430
+ return new Proxy(
431
+ {},
432
+ {
433
+ get(_target, prop) {
434
+ const currentPath = prefix ? `${prefix}.${prop}` : prop;
435
+ return new RouteCallBuilder(
436
+ (input, options) => executeCall(currentPath, input, options),
437
+ currentPath
438
+ );
439
+ }
440
+ }
441
+ );
442
+ }
443
+ return buildProxy();
444
+ }
445
+
446
+ export { ApiError, createApi };
447
+ //# sourceMappingURL=index.js.map
448
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/nextjs/client/debug-logs.ts","../../src/nextjs/client/errors.ts","../../src/nextjs/shared.ts","../../src/nextjs/client/helpers.ts","../../src/nextjs/client/builder.ts","../../src/nextjs/client/core.ts"],"names":["logger","errorRegistry","coreErrorRegistry","headers"],"mappings":";;;;;;;AAMO,SAAS,sBAAA,CACZA,SACA,OAAA,EAEJ;AACI,EAAAA,OA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,OAAO,SAAS,CAAA;AAAA,IACtF;AAEA,IAAA,OAAO,IAAA;AAAA,EACX;AAQA,EAAA,SAAS,UAAA,CAAW,SAAS,EAAA,EAC7B;AACI,IAAA,OAAO,IAAI,KAAA;AAAA,MACP,EAAC;AAAA,MACD;AAAA,QACI,GAAA,CAAI,SAAS,IAAA,EACb;AACI,UAAA,MAAM,cAAc,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,GAAK,IAAA;AAGnD,UAAA,OAAO,IAAI,gBAAA;AAAA,YACP,CAAC,KAAA,EAAY,OAAA,KAAyB,WAAA,CAAY,WAAA,EAAa,OAAO,OAAO,CAAA;AAAA,YAC7E;AAAA,WACJ;AAAA,QACJ;AAAA;AACJ,KACJ;AAAA,EACJ;AAEA,EAAA,OAAO,UAAA,EAAW;AACtB","file":"index.js","sourcesContent":["/**\n * Debug logging utilities for API client\n * Separates debug logging logic from main client code for better maintainability\n */\nimport type { Logger } from '@spfn/core/logger';\n\nexport function logCookieAutoDetection(\n logger: Logger,\n cookies: Array<{ name: string; value: string }>\n): void\n{\n logger.debug('Auto-detected server environment, forwarding cookies', {\n cookieCount: cookies.length,\n cookieNames: cookies.map(c => c.name),\n });\n}\n\nexport function logRequest(\n logger: Logger,\n routeName: string,\n method: string,\n url: string,\n hasBody: boolean\n): void\n{\n logger.debug('→ Request', {\n route: routeName,\n method,\n url,\n hasBody,\n });\n}\n\nexport function logResponse(\n logger: Logger,\n routeName: string,\n status: number,\n hasBody: boolean\n): void\n{\n logger.debug('← Response', {\n route: routeName,\n status,\n hasBody,\n });\n}\n\nexport function logErrorResponse(\n logger: Logger,\n status: number,\n body: any\n): void\n{\n logger.debug('Error response received', {\n status,\n hasBody: !!body,\n bodyType: typeof body,\n hasTypeField: body && typeof body === 'object' && '__type' in body,\n typeValue: body?.__type,\n });\n}\n\nexport function logErrorDeserializationAttempt(\n logger: Logger,\n errorType: string,\n registeredTypes: string[]\n): void\n{\n logger.debug('Attempting error deserialization', {\n errorType,\n hasRegistry: true,\n registeredTypes,\n });\n}\n\nexport function logErrorDeserializationSuccess(\n logger: Logger,\n error: Error | null\n): void\n{\n logger.debug('Error deserialized successfully', {\n errorName: error?.name,\n errorConstructor: error?.constructor.name,\n message: error?.message,\n });\n}\n\nexport function logErrorDeserializationFailure(\n logger: Logger,\n error: unknown\n): void\n{\n logger.debug('Deserialization failed', {\n errorName: error instanceof Error ? error.name : 'unknown',\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n}\n\nexport function logErrorDeserializationSkipped(\n logger: Logger,\n errorRegistry: any,\n body: any\n): void\n{\n const reason = !errorRegistry\n ? 'no registry'\n : !body\n ? 'no body'\n : typeof body !== 'object'\n ? 'body not object'\n : !('__type' in body)\n ? 'no __type field'\n : 'unknown';\n\n logger.debug('Skipping error deserialization', { reason });\n}\n\nexport function logThrowingDeserializedError(\n logger: Logger,\n error: Error\n): void\n{\n logger.debug('Throwing deserialized error', {\n errorName: error.name,\n errorConstructorName: error.constructor.name,\n prototype: Object.getPrototypeOf(error).constructor.name,\n });\n}","// ============================================================================\n// Client Error\n// ============================================================================\n\n/**\n * Typed client error\n */\nexport class ApiError extends Error\n{\n constructor(\n message: string,\n public readonly status: number,\n public readonly url: string,\n public readonly response?: unknown,\n public readonly errorType?: 'http' | 'network' | 'timeout'\n )\n {\n super(message);\n this.name = 'ApiError';\n }\n}","/**\n * Shared utilities for Next.js client and proxy modules\n *\n * Contains common functions used by both client and proxy to avoid code duplication.\n */\n\n/**\n * Build URL with path parameters replaced\n *\n * @example\n * buildUrlWithParams('/users/:id/posts/:postId', { id: '123', postId: '456' })\n * // Returns: '/users/123/posts/456'\n */\nexport function buildUrlWithParams(path: string, params: Record<string, any>): string\n{\n let url = path;\n for (const [key, value] of Object.entries(params))\n {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n return url;\n}\n\n/**\n * Build query string from object\n *\n * @example\n * buildQueryString({ page: '1', limit: '10', tags: ['foo', 'bar'] })\n * // Returns: '?page=1&limit=10&tags=foo&tags=bar'\n */\nexport function buildQueryString(query: Record<string, any>): string\n{\n if (Object.keys(query).length === 0)\n {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query))\n {\n if (Array.isArray(value))\n {\n value.forEach((v) => searchParams.append(key, String(v)));\n }\n else\n {\n searchParams.append(key, String(value));\n }\n }\n\n return `?${searchParams.toString()}`;\n}\n\n/**\n * Build Cookie header string from cookies object\n *\n * @example\n * buildCookieHeader({ session: 'abc123', theme: 'dark' })\n * // Returns: 'session=abc123; theme=dark'\n */\nexport function buildCookieHeader(cookies: Record<string, string>): string\n{\n return Object.entries(cookies)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n}\n\n/**\n * Parse response body based on content type\n *\n * Handles:\n * - 204 No Content: returns null (no body expected)\n * - application/json: parses JSON body\n * - Other content types: returns raw text\n */\nexport async function parseResponseBody(response: Response): Promise<any>\n{\n // 204 No Content has no body\n if (response.status === 204)\n {\n return null;\n }\n\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json'))\n {\n const text = await response.text();\n return text ? JSON.parse(text) : null;\n }\n else\n {\n return await response.text();\n }\n}","import type { Logger } from '@spfn/core/logger';\nimport type { ErrorRegistry } from '@spfn/core/errors';\nimport { ApiError } from './errors';\nimport * as debugLogs from './debug-logs';\n\n// Re-export shared utilities\nexport { buildCookieHeader, parseResponseBody } from '../shared';\n\n/**\n * Auto-detect cookies from Next.js server environment\n * Returns empty object if not in server environment or if cookies are not accessible\n */\nexport async function autoDetectServerCookies(): Promise<Record<string, string>>\n{\n try\n {\n // Next.js cookies() API is only available in server environment\n const { cookies } = await import('next/headers');\n const cookieStore = await cookies();\n const allCookies = cookieStore.getAll();\n\n return Object.fromEntries(\n allCookies.map(cookie => [cookie.name, cookie.value])\n );\n }\n catch (error)\n {\n // Client environment or cookies not accessible\n // Browser automatically sends cookies in client components\n return {};\n }\n}\n\n/**\n * Execute fetch with timeout and abort controller\n */\nexport async function executeFetchWithTimeout(\n url: string,\n init: RequestInit,\n timeout: number,\n customFetch: typeof fetch = fetch\n): Promise<Response>\n{\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try\n {\n const response = await customFetch(url, {\n ...init,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n return response;\n }\n catch (error)\n {\n clearTimeout(timeoutId);\n throw error;\n }\n}\n\n/**\n * Handle error response with deserialization support\n * Attempts to deserialize custom errors if errorRegistry is provided\n * Falls back to ApiError if deserialization fails or is not available\n */\nexport async function handleErrorResponse(\n response: Response,\n body: any,\n fullUrl: string,\n errorRegistry: ErrorRegistry | undefined,\n debug: boolean,\n logger: Logger\n): Promise<never>\n{\n if (debug)\n {\n debugLogs.logErrorResponse(logger, response.status, body);\n }\n\n // Try to deserialize error if registry is provided\n let deserializedError: Error | null = null;\n\n if (errorRegistry && body && typeof body === 'object' && '__type' in body)\n {\n if (debug)\n {\n debugLogs.logErrorDeserializationAttempt(logger, body.__type, errorRegistry.getRegisteredTypes());\n }\n\n try\n {\n deserializedError = errorRegistry.deserialize(body as any);\n\n if (debug)\n {\n debugLogs.logErrorDeserializationSuccess(logger, deserializedError);\n }\n }\n catch (deserializeError)\n {\n // Deserialization itself failed (type not found, invalid data, etc.)\n if (debug)\n {\n debugLogs.logErrorDeserializationFailure(logger, deserializeError);\n }\n // Fall through to ApiError below\n }\n }\n else if (debug)\n {\n debugLogs.logErrorDeserializationSkipped(logger, errorRegistry, body);\n }\n\n // If deserialization succeeded, throw the deserialized error\n if (deserializedError)\n {\n if (debug)\n {\n debugLogs.logThrowingDeserializedError(logger, deserializedError);\n }\n\n throw deserializedError;\n }\n\n // Fallback to generic ApiError\n if (response.status === 404 && process.env.NODE_ENV !== 'production')\n {\n logger.warn(\n '\\n⚠️ 404 Not Found\\n\\n' +\n 'Check the following:\\n' +\n ' 1. Routes are registered in server.config.ts:\\n' +\n ' → defineServerConfig().routes(appRouter)\\n' +\n ' 2. Delete .spfn cache if you recently added new routes:\\n' +\n ' → rm -rf .spfn\\n'\n );\n }\n\n throw new ApiError(\n body?.message || `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n fullUrl,\n body,\n 'http'\n );\n}","// ============================================================================\n// Route Call Builder (Structured Input API)\n// ============================================================================\n\nimport type { RouteDef, Router } from \"@spfn/core/route\";\nimport type {\n CallOptions,\n InferRouteInput,\n InferRouteOutput,\n RequestInterceptor,\n ResponseInterceptor,\n} from \"./types\";\n\n/**\n * Pick only non-empty fields from StructuredInput\n *\n * This removes fields that are empty objects `{}` from the input type,\n * so users only need to provide fields that are actually defined in the route.\n */\ntype PickNonEmpty<T> = {\n [K in keyof T as T[K] extends Record<string, never> ? never : K]: T[K];\n};\n\n/**\n * Make fields that can be undefined into optional fields\n *\n * When a field is defined as `Type.Optional(Type.Object({...}))`,\n * the resulting type is `T | undefined`. This utility converts such fields\n * into proper optional fields (`field?: T`) so users don't need to pass them.\n */\ntype MakeOptionalIfUndefinable<T> =\n // Required fields (undefined is not assignable)\n { [K in keyof T as undefined extends T[K] ? never : K]: T[K] }\n // Optional fields (undefined is assignable)\n & { [K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined> };\n\n/**\n * Clean structured input - only include fields that have actual schema,\n * and make fields optional if they accept undefined\n */\ntype CleanStructuredInput<TInput> = MakeOptionalIfUndefinable<PickNonEmpty<TInput>>;\n\n/**\n * Check if input has any required fields\n *\n * Returns false if all fields are optional (i.e., {} is assignable to the input type)\n */\ntype HasAnyRequiredFields<TInput> = {} extends CleanStructuredInput<TInput> ? false : true;\n\n/**\n * Route call builder with structured input API\n *\n * Input is structured with explicit params, query, body fields\n * that match the server-side route definition.\n *\n * @example\n * ```typescript\n * // GET /users/:id - params only\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // GET /users/:id?include=posts - params + query\n * const user = await api.getUser.call({\n * params: { id: '1' },\n * query: { include: 'posts' }\n * });\n *\n * // POST /users - body only\n * const user = await api.createUser.call({\n * body: { name: 'John', email: 'john@example.com' }\n * });\n *\n * // PUT /users/:id - params + body\n * const user = await api.updateUser.call({\n * params: { id: '1' },\n * body: { name: 'Jane' }\n * });\n *\n * // With options (headers, cookies, Next.js caching)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nexport class RouteCallBuilder<\n TInput,\n TOutput\n>\n{\n private _headers?: Record<string, string>;\n private _cookies?: Record<string, string>;\n private _fetchOptions?: RequestInit;\n private _onRequest?: RequestInterceptor;\n private _onResponse?: ResponseInterceptor;\n\n constructor(\n private readonly executor: (input: any, options: CallOptions) => Promise<TOutput>,\n private readonly routeName: string\n ) {}\n\n /**\n * Clone builder\n */\n private clone(): RouteCallBuilder<TInput, TOutput>\n {\n const builder = new RouteCallBuilder<TInput, TOutput>(\n this.executor,\n this.routeName\n );\n builder._headers = this._headers;\n builder._cookies = this._cookies;\n builder._fetchOptions = this._fetchOptions;\n builder._onRequest = this._onRequest;\n builder._onResponse = this._onResponse;\n return builder;\n }\n\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._headers = { ...this._headers, ...headers };\n return builder;\n }\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._cookies = { ...this._cookies, ...cookies };\n return builder;\n }\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._fetchOptions = { ...this._fetchOptions, ...options };\n return builder;\n }\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onRequest = interceptor;\n return builder;\n }\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onResponse = interceptor;\n return builder;\n }\n\n /**\n * Execute the API call with structured input\n *\n * Input structure matches the server-side route definition:\n * - params: Path parameters (e.g., { id: '123' } for /users/:id)\n * - query: Query string parameters\n * - body: Request body (for POST, PUT, PATCH)\n */\n call(input?: CleanStructuredInput<TInput>): Promise<TOutput>\n {\n const options: CallOptions = {};\n\n if (this._headers)\n {\n options.headers = this._headers;\n }\n\n if (this._cookies)\n {\n options.cookies = this._cookies;\n }\n\n if (this._fetchOptions)\n {\n options.fetchOptions = this._fetchOptions;\n }\n\n if (this._onRequest)\n {\n options.onRequest = this._onRequest;\n }\n\n if (this._onResponse)\n {\n options.onResponse = this._onResponse;\n }\n\n return this.executor(input || {}, options);\n }\n}\n\n/**\n * Individual route client with structured input API\n */\nexport type RouteClient<TRoute extends RouteDef<any, any>> = {\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteClient<TRoute>;\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteClient<TRoute>;\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteClient<TRoute>;\n\n /**\n * Execute the API call with structured input\n *\n * @example\n * ```typescript\n * // GET /users/:id\n * api.getUser.call({ params: { id: '123' } });\n *\n * // PUT /users/:id\n * api.updateUser.call({ params: { id: '123' }, body: { name: 'Jane' } });\n * ```\n */\n call: HasAnyRequiredFields<InferRouteInput<TRoute>> extends true\n ? (input: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>\n : (input?: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>;\n};\n\n/**\n * Typed client for entire router\n */\nexport type Client<TRouter extends Router<any>> = {\n [K in keyof TRouter['routes']]: TRouter['routes'][K] extends RouteDef<any, any, any>\n ? RouteClient<TRouter['routes'][K]>\n : TRouter['routes'][K] extends Router<any>\n ? Client<TRouter['routes'][K]>\n : never;\n};","/**\n * Type-Safe RPC-Style Client with Structured Input API\n *\n * Provides full end-to-end type safety from server routes to client calls.\n * No metadata codegen required - method/path resolution happens at the proxy layer.\n *\n * @example\n * ```typescript\n * // Server\n * export const appRouter = defineRouter({\n * getUser: route.get('/users/:id')\n * .input({ params: Type.Object({ id: Type.String() }) })\n * .handler(async (c) => { ... }),\n * createUser: route.post('/users')\n * .input({ body: Type.Object({ name: Type.String() }) })\n * .handler(async (c) => { ... }),\n * });\n *\n * export type AppRouter = typeof appRouter;\n *\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // ✅ GET (no body) - becomes GET /api/rpc/getUser?input={...}\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // ✅ POST (has body) - becomes POST /api/rpc/createUser\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n *\n * // ✅ With options (headers, cookies, interceptors)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .cookies({ session: 'xxx' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nimport { env } from '@spfn/core/config';\nimport { ErrorRegistry, errorRegistry as coreErrorRegistry } from '@spfn/core/errors';\nimport { logger } from '@spfn/core/logger';\nimport type { Router } from '@spfn/core/route';\nimport * as debugLogs from './debug-logs';\nimport { ApiError } from \"./errors\";\nimport {\n parseResponseBody,\n executeFetchWithTimeout,\n handleErrorResponse,\n buildCookieHeader,\n autoDetectServerCookies,\n} from './helpers';\nimport { RouteCallBuilder } from './builder';\nimport type { ApiConfig, CallOptions } from \"./types\";\nimport type { Client } from \"./builder\";\n\nconst apiLogger = logger.child('@spfn/core:api-client');\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\n/**\n * Create type-safe RPC client\n *\n * No metadata required - the client sends routeName + input to the proxy,\n * and the proxy resolves the actual HTTP method and path from the router.\n *\n * @example\n * ```typescript\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // GET request (no body) - browser cacheable\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // POST request (has body)\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n * ```\n */\nexport function createApi<TRouter extends Router<any>>(\n config: ApiConfig = {}\n): Client<TRouter>\n{\n const {\n baseUrl = '/api/rpc',\n headers: defaultHeaders = {},\n timeout = 30000,\n fetch: customFetch = fetch,\n onRequest: globalOnRequest,\n onResponse: globalOnResponse,\n errorRegistry: errorRegistryConfig,\n debug = false,\n } = config;\n\n // Normalize errorRegistry: always include coreErrorRegistry\n const errorRegistry = Array.isArray(errorRegistryConfig)\n ? new ErrorRegistry([coreErrorRegistry, ...errorRegistryConfig])\n : errorRegistryConfig ?? coreErrorRegistry;\n\n if (debug)\n {\n apiLogger.debug('API client initialized', { baseUrl });\n }\n\n /**\n * Execute API call\n *\n * Determines GET vs POST based on body/formData presence:\n * - No body/formData → GET /api/rpc/{routeName}?input={...}\n * - Has body → POST /api/rpc/{routeName} with JSON body\n * - Has formData → POST /api/rpc/{routeName} with multipart/form-data\n */\n async function executeCall(\n routeName: string,\n input: any = {},\n options: CallOptions = {}\n ): Promise<any>\n {\n const hasBody = input.body !== undefined;\n const hasFormData = input.formData !== undefined && Object.keys(input.formData).length > 0;\n const method = (hasBody || hasFormData) ? 'POST' : 'GET';\n\n // Build full URL - handle SSR case where SPFN_APP_URL might not be set\n let appUrl = env.SPFN_APP_URL || '';\n\n // In SSR environment, if SPFN_APP_URL is not set, try to get host from request headers\n if (!appUrl && typeof window === 'undefined')\n {\n try\n {\n const { headers } = await import('next/headers');\n const headersList = await headers();\n const host = headersList.get('host');\n const protocol = headersList.get('x-forwarded-proto') || 'http';\n if (host)\n {\n appUrl = `${protocol}://${host}`;\n if (debug)\n {\n apiLogger.debug(`Auto-detected app URL from headers: ${appUrl}`);\n }\n }\n }\n catch\n {\n // Fallback: use relative URL and let fetch handle it\n if (debug)\n {\n apiLogger.warn('Could not determine app URL in SSR environment, using relative URL');\n }\n }\n }\n\n // Build URL based on method\n let fullUrl: string;\n if (method === 'GET')\n {\n // GET: encode input in query string\n const inputParam = encodeURIComponent(JSON.stringify(input));\n fullUrl = `${appUrl}${baseUrl}/${routeName}?input=${inputParam}`;\n }\n else\n {\n // POST: input goes in body\n fullUrl = `${appUrl}${baseUrl}/${routeName}`;\n }\n\n // Prepare headers\n // Note: Don't set Content-Type for formData - browser sets it with boundary\n const headers: Record<string, string> = {\n ...(hasFormData ? {} : { 'Content-Type': 'application/json' }),\n ...defaultHeaders,\n ...options.headers,\n };\n\n // Auto-detect server cookies and merge with user-provided cookies\n const autoDetectedCookies = await autoDetectServerCookies();\n const cookiesToSend = {\n ...autoDetectedCookies,\n ...(options.cookies || {}),\n };\n\n // Add Cookie header if we have cookies to send\n if (Object.keys(cookiesToSend).length > 0)\n {\n headers['Cookie'] = buildCookieHeader(cookiesToSend);\n }\n\n // Log cookie auto-detection if debug enabled\n if (debug && Object.keys(autoDetectedCookies).length > 0)\n {\n const cookieArray = Object.entries(autoDetectedCookies).map(([name, value]) => ({ name, value }));\n debugLogs.logCookieAutoDetection(apiLogger, cookieArray);\n }\n\n // Build request init\n const requestInit: RequestInit = {\n method,\n headers,\n ...options.fetchOptions,\n };\n\n // Add body for POST\n if (method === 'POST')\n {\n if (hasFormData)\n {\n // Build FormData for file uploads\n const formData = new FormData();\n\n // Add non-formData fields (params, query, headers, cookies) as JSON metadata\n const metadata: Record<string, any> = {};\n if (input.params) metadata.params = input.params;\n if (input.query) metadata.query = input.query;\n if (input.headers) metadata.headers = input.headers;\n if (input.cookies) metadata.cookies = input.cookies;\n\n if (Object.keys(metadata).length > 0)\n {\n formData.append('__metadata', JSON.stringify(metadata));\n }\n\n // Add formData fields\n for (const [key, value] of Object.entries(input.formData))\n {\n if (value instanceof File)\n {\n formData.append(key, value);\n }\n else if (Array.isArray(value))\n {\n // Handle array of files or values\n for (const item of value)\n {\n if (item instanceof File)\n {\n formData.append(key, item);\n }\n else\n {\n formData.append(key, String(item));\n }\n }\n }\n else if (value !== undefined && value !== null)\n {\n formData.append(key, String(value));\n }\n }\n\n requestInit.body = formData;\n }\n else\n {\n requestInit.body = JSON.stringify(input);\n }\n }\n\n // Execute request interceptors\n let init = requestInit;\n if (globalOnRequest)\n {\n init = await globalOnRequest(fullUrl, init);\n }\n if (options.onRequest)\n {\n init = await options.onRequest(fullUrl, init);\n }\n\n if (debug)\n {\n debugLogs.logRequest(apiLogger, routeName, method, fullUrl, !!init.body);\n }\n\n // Execute fetch with timeout\n let response: Response;\n let body: any;\n\n try\n {\n response = await executeFetchWithTimeout(fullUrl, init, timeout, customFetch);\n\n // Parse response\n body = await parseResponseBody(response);\n\n // Execute global + local response interceptors\n if (globalOnResponse)\n {\n const result = await globalOnResponse(response, body);\n response = result.response;\n body = result.body;\n }\n if (options.onResponse)\n {\n const result = await options.onResponse(response, body);\n response = result.response;\n body = result.body;\n }\n\n if (debug)\n {\n debugLogs.logResponse(apiLogger, routeName, response.status, !!body);\n }\n }\n catch (error)\n {\n // Handle timeout specifically\n if (error instanceof Error && error.name === 'AbortError')\n {\n apiLogger.error('Request timeout', {\n route: routeName,\n method,\n url: fullUrl,\n timeout,\n });\n\n throw new ApiError(\n `Request timeout after ${timeout}ms`,\n 408,\n fullUrl,\n undefined,\n 'timeout'\n );\n }\n\n // Network error\n const errorMessage = error instanceof Error ? error.message : 'Network error';\n apiLogger.error('Network error', {\n route: routeName,\n method,\n url: fullUrl,\n error: errorMessage,\n errorName: error instanceof Error ? error.name : 'unknown',\n });\n\n throw new ApiError(\n errorMessage,\n 0,\n fullUrl,\n undefined,\n 'network'\n );\n }\n\n // Handle error responses\n if (!response.ok)\n {\n await handleErrorResponse(response, body, fullUrl, errorRegistry, debug, apiLogger);\n }\n\n return body;\n }\n\n /**\n * Build client proxy\n *\n * Every property access returns a RouteCallBuilder.\n * Nested routers are supported via dot notation in routeName.\n */\n function buildProxy(prefix = ''): any\n {\n return new Proxy(\n {},\n {\n get(_target, prop: string)\n {\n const currentPath = prefix ? `${prefix}.${prop}` : prop;\n\n // Return RouteCallBuilder that can either be called or chained\n return new RouteCallBuilder(\n (input: any, options: CallOptions) => executeCall(currentPath, input, options),\n currentPath\n );\n },\n }\n );\n }\n\n return buildProxy() as Client<TRouter>;\n}"]}