@emeryld/rrroutes-client 1.2.2 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +143 -76
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +143 -76
- package/dist/index.mjs.map +1 -1
- package/dist/routesV3.client.types.d.ts +11 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -97,19 +97,26 @@ var defaultDebugLogger = (event) => {
|
|
|
97
97
|
fn?.call(console, "[rrroutes-client]", event);
|
|
98
98
|
};
|
|
99
99
|
function createDebugEmitter(option) {
|
|
100
|
+
const disabled = { emit: noopDebugLogger, mode: "minimal" };
|
|
100
101
|
if (!option) {
|
|
101
|
-
return
|
|
102
|
+
return disabled;
|
|
102
103
|
}
|
|
103
|
-
if (option === true) {
|
|
104
|
-
return defaultDebugLogger;
|
|
104
|
+
if (option === true || option === "minimal") {
|
|
105
|
+
return { emit: defaultDebugLogger, mode: "minimal" };
|
|
106
|
+
}
|
|
107
|
+
if (option === "complete") {
|
|
108
|
+
return { emit: defaultDebugLogger, mode: "complete" };
|
|
105
109
|
}
|
|
106
110
|
if (typeof option === "function") {
|
|
107
|
-
return option;
|
|
111
|
+
return { emit: option, mode: "minimal" };
|
|
108
112
|
}
|
|
109
113
|
if (option.enabled === false) {
|
|
110
|
-
return noopDebugLogger;
|
|
114
|
+
return { emit: noopDebugLogger, mode: option.mode ?? "minimal" };
|
|
111
115
|
}
|
|
112
|
-
return
|
|
116
|
+
return {
|
|
117
|
+
emit: option.logger ?? defaultDebugLogger,
|
|
118
|
+
mode: option.mode ?? "minimal"
|
|
119
|
+
};
|
|
113
120
|
}
|
|
114
121
|
function extractArgs(args) {
|
|
115
122
|
return args[0];
|
|
@@ -119,7 +126,7 @@ function buildUrl(leaf, baseUrl, params, query) {
|
|
|
119
126
|
const normalizedQuery = zParse(query, leaf.cfg.querySchema);
|
|
120
127
|
const path = (0, import_rrroutes_contract.compilePath)(leaf.path, normalizedParams ?? {});
|
|
121
128
|
const url = `${baseUrl ?? ""}${path}${toSearchString(normalizedQuery)}`;
|
|
122
|
-
return { url, normalizedQuery };
|
|
129
|
+
return { url, normalizedQuery, normalizedParams };
|
|
123
130
|
}
|
|
124
131
|
function createRouteClient(opts) {
|
|
125
132
|
const queryClient = opts.queryClient;
|
|
@@ -127,7 +134,12 @@ function createRouteClient(opts) {
|
|
|
127
134
|
const baseUrl = opts.baseUrl;
|
|
128
135
|
const cursorParam = opts.cursorParam ?? "cursor";
|
|
129
136
|
const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;
|
|
130
|
-
const emitDebug = createDebugEmitter(opts.debug);
|
|
137
|
+
const { emit: emitDebug, mode: debugMode } = createDebugEmitter(opts.debug);
|
|
138
|
+
const isVerboseDebug = debugMode === "complete";
|
|
139
|
+
const decorateDebugEvent = (event, details) => {
|
|
140
|
+
if (!isVerboseDebug || !details) return event;
|
|
141
|
+
return { ...event, ...details };
|
|
142
|
+
};
|
|
131
143
|
async function invalidate(prefix, exact = false) {
|
|
132
144
|
const queryKey = prefix;
|
|
133
145
|
await queryClient.invalidateQueries({ queryKey, exact });
|
|
@@ -138,6 +150,7 @@ function createRouteClient(opts) {
|
|
|
138
150
|
const isFeed = !!leaf.cfg.feed;
|
|
139
151
|
const method = toUpper(leaf.method);
|
|
140
152
|
const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;
|
|
153
|
+
emitDebug({ type: "build", leaf: leafLabel });
|
|
141
154
|
const key = (...tuple) => {
|
|
142
155
|
const a = extractArgs(tuple);
|
|
143
156
|
const params = a?.params;
|
|
@@ -168,10 +181,11 @@ function createRouteClient(opts) {
|
|
|
168
181
|
};
|
|
169
182
|
if (isGet && isFeed) {
|
|
170
183
|
const useEndpoint2 = (...tuple) => {
|
|
184
|
+
emitDebug({ type: "useInfiniteGet", leaf: leafLabel });
|
|
171
185
|
const a = extractArgs(tuple);
|
|
172
186
|
const params = a?.params;
|
|
173
187
|
const query = a?.query;
|
|
174
|
-
const { normalizedQuery } = buildUrl(leaf, baseUrl, params, query);
|
|
188
|
+
const { normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
175
189
|
return (0, import_react_query.useInfiniteQuery)({
|
|
176
190
|
...rqOpts,
|
|
177
191
|
queryKey: key(...tuple),
|
|
@@ -185,28 +199,45 @@ function createRouteClient(opts) {
|
|
|
185
199
|
};
|
|
186
200
|
const { url } = buildUrl(leaf, baseUrl, params, pageQuery);
|
|
187
201
|
const startedAt = Date.now();
|
|
188
|
-
|
|
202
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: pageQuery } : void 0;
|
|
203
|
+
emitDebug(
|
|
204
|
+
decorateDebugEvent(
|
|
205
|
+
{ type: "fetch", stage: "start", method, url, leaf: leafLabel },
|
|
206
|
+
detail
|
|
207
|
+
)
|
|
208
|
+
);
|
|
189
209
|
try {
|
|
190
210
|
const out = await fetcher({ url, method });
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
211
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
212
|
+
emitDebug(
|
|
213
|
+
decorateDebugEvent(
|
|
214
|
+
{
|
|
215
|
+
type: "fetch",
|
|
216
|
+
stage: "success",
|
|
217
|
+
method,
|
|
218
|
+
url,
|
|
219
|
+
leaf: leafLabel,
|
|
220
|
+
durationMs: Date.now() - startedAt
|
|
221
|
+
},
|
|
222
|
+
isVerboseDebug ? { params: normalizedParams, query: pageQuery, output: parsed } : void 0
|
|
223
|
+
)
|
|
224
|
+
);
|
|
225
|
+
return parsed;
|
|
200
226
|
} catch (error) {
|
|
201
|
-
emitDebug(
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
227
|
+
emitDebug(
|
|
228
|
+
decorateDebugEvent(
|
|
229
|
+
{
|
|
230
|
+
type: "fetch",
|
|
231
|
+
stage: "error",
|
|
232
|
+
method,
|
|
233
|
+
url,
|
|
234
|
+
leaf: leafLabel,
|
|
235
|
+
durationMs: Date.now() - startedAt,
|
|
236
|
+
error
|
|
237
|
+
},
|
|
238
|
+
detail
|
|
239
|
+
)
|
|
240
|
+
);
|
|
210
241
|
throw error;
|
|
211
242
|
}
|
|
212
243
|
}
|
|
@@ -222,38 +253,56 @@ function createRouteClient(opts) {
|
|
|
222
253
|
}
|
|
223
254
|
if (isGet) {
|
|
224
255
|
const useEndpoint2 = (...tuple) => {
|
|
256
|
+
emitDebug({ type: "useGet", leaf: leafLabel });
|
|
225
257
|
const a = extractArgs(tuple);
|
|
226
258
|
const params = a?.params;
|
|
227
259
|
const query = a?.query;
|
|
228
|
-
const { url } = buildUrl(leaf, baseUrl, params, query);
|
|
260
|
+
const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
229
261
|
return (0, import_react_query.useQuery)({
|
|
230
262
|
...rqOpts,
|
|
231
263
|
queryKey: key(...tuple),
|
|
232
264
|
placeholderData: import_react_query.keepPreviousData,
|
|
233
265
|
queryFn: async () => {
|
|
234
266
|
const startedAt = Date.now();
|
|
235
|
-
|
|
267
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: normalizedQuery } : void 0;
|
|
268
|
+
emitDebug(
|
|
269
|
+
decorateDebugEvent(
|
|
270
|
+
{ type: "fetch", stage: "start", method, url, leaf: leafLabel },
|
|
271
|
+
detail
|
|
272
|
+
)
|
|
273
|
+
);
|
|
236
274
|
try {
|
|
237
275
|
const out = await fetcher({ url, method });
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
276
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
277
|
+
emitDebug(
|
|
278
|
+
decorateDebugEvent(
|
|
279
|
+
{
|
|
280
|
+
type: "fetch",
|
|
281
|
+
stage: "success",
|
|
282
|
+
method,
|
|
283
|
+
url,
|
|
284
|
+
leaf: leafLabel,
|
|
285
|
+
durationMs: Date.now() - startedAt
|
|
286
|
+
},
|
|
287
|
+
isVerboseDebug ? { params: normalizedParams, query: normalizedQuery, output: parsed } : void 0
|
|
288
|
+
)
|
|
289
|
+
);
|
|
290
|
+
return parsed;
|
|
247
291
|
} catch (error) {
|
|
248
|
-
emitDebug(
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
292
|
+
emitDebug(
|
|
293
|
+
decorateDebugEvent(
|
|
294
|
+
{
|
|
295
|
+
type: "fetch",
|
|
296
|
+
stage: "error",
|
|
297
|
+
method,
|
|
298
|
+
url,
|
|
299
|
+
leaf: leafLabel,
|
|
300
|
+
durationMs: Date.now() - startedAt,
|
|
301
|
+
error
|
|
302
|
+
},
|
|
303
|
+
detail
|
|
304
|
+
)
|
|
305
|
+
);
|
|
257
306
|
throw error;
|
|
258
307
|
}
|
|
259
308
|
}
|
|
@@ -267,10 +316,11 @@ function createRouteClient(opts) {
|
|
|
267
316
|
};
|
|
268
317
|
}
|
|
269
318
|
const useEndpoint = (...tuple) => {
|
|
319
|
+
emitDebug({ type: "useMutation", leaf: leafLabel });
|
|
270
320
|
const a = extractArgs(tuple);
|
|
271
321
|
const params = a?.params;
|
|
272
322
|
const query = a?.query;
|
|
273
|
-
const { url } = buildUrl(leaf, baseUrl, params, query);
|
|
323
|
+
const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
274
324
|
return (0, import_react_query.useMutation)({
|
|
275
325
|
...rqOpts,
|
|
276
326
|
mutationKey: key(...tuple),
|
|
@@ -279,36 +329,53 @@ function createRouteClient(opts) {
|
|
|
279
329
|
const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;
|
|
280
330
|
const payload = isMultipart ? toFormData(normalizedBody) : normalizedBody;
|
|
281
331
|
const startedAt = Date.now();
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
332
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: normalizedQuery } : void 0;
|
|
333
|
+
emitDebug(
|
|
334
|
+
decorateDebugEvent(
|
|
335
|
+
{
|
|
336
|
+
type: "fetch",
|
|
337
|
+
stage: "start",
|
|
338
|
+
method,
|
|
339
|
+
url,
|
|
340
|
+
leaf: leafLabel,
|
|
341
|
+
body: payload
|
|
342
|
+
},
|
|
343
|
+
detail
|
|
344
|
+
)
|
|
345
|
+
);
|
|
290
346
|
try {
|
|
291
347
|
const out = await fetcher({ url, method, body: payload });
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
348
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
349
|
+
emitDebug(
|
|
350
|
+
decorateDebugEvent(
|
|
351
|
+
{
|
|
352
|
+
type: "fetch",
|
|
353
|
+
stage: "success",
|
|
354
|
+
method,
|
|
355
|
+
url,
|
|
356
|
+
leaf: leafLabel,
|
|
357
|
+
durationMs: Date.now() - startedAt
|
|
358
|
+
},
|
|
359
|
+
isVerboseDebug ? { params: normalizedParams, query: normalizedQuery, output: parsed } : void 0
|
|
360
|
+
)
|
|
361
|
+
);
|
|
362
|
+
return parsed;
|
|
301
363
|
} catch (error) {
|
|
302
|
-
emitDebug(
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
364
|
+
emitDebug(
|
|
365
|
+
decorateDebugEvent(
|
|
366
|
+
{
|
|
367
|
+
type: "fetch",
|
|
368
|
+
stage: "error",
|
|
369
|
+
method,
|
|
370
|
+
url,
|
|
371
|
+
leaf: leafLabel,
|
|
372
|
+
durationMs: Date.now() - startedAt,
|
|
373
|
+
body: payload,
|
|
374
|
+
error
|
|
375
|
+
},
|
|
376
|
+
detail
|
|
377
|
+
)
|
|
378
|
+
);
|
|
312
379
|
throw error;
|
|
313
380
|
}
|
|
314
381
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/routesV3.client.fetch.ts","../src/routesV3.client.index.ts"],"sourcesContent":["/**\n * This package exports React Query hooks, so we mark it as client-only to keep Next.js happy.\n */\n'use client';\n\nexport * from './routesV3.client.types';\nexport * from './routesV3.client.fetch';\nexport * from './routesV3.client.index';\n","// routesV3.client.fetch.ts\n\nimport { Fetcher, FetchInput } from './routesV3.client.types';\n\n/**\n * Default fetch implementation used by the route client helper.\n * @param req Normalized request information (URL, method, body, headers).\n * @returns Parsed JSON (or text fallback) from the server response.\n */\nexport const defaultFetcher: Fetcher = async <T>(req: FetchInput): Promise<T> => {\n const headers: Record<string, string> = { ...(req.headers ?? {}) };\n const isFormData = typeof FormData !== 'undefined' && req.body instanceof FormData;\n if (!isFormData) {\n headers['Content-Type'] ||= 'application/json';\n headers['Accept'] ||= 'application/json';\n }\n\n const res = await fetch(req.url, {\n method: req.method,\n headers,\n body: isFormData ? (req.body as any) : req.body == null ? undefined : JSON.stringify(req.body),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const snippet = text.slice(0, 400);\n throw new Error(`[${res.status}] ${res.statusText} — ${snippet}`);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n};\n","// routesV3.client.ts\nimport {\n keepPreviousData,\n useInfiniteQuery,\n useMutation,\n useQuery,\n type InfiniteData,\n type QueryKey,\n} from '@tanstack/react-query';\nimport type { ZodType } from 'zod';\nimport {\n HttpMethod,\n buildCacheKey,\n compilePath,\n} from '@emeryld/rrroutes-contract';\nimport type {\n AnyLeaf,\n InferBody,\n InferOutput,\n InferParams,\n InferQuery,\n} from '@emeryld/rrroutes-contract';\nimport { defaultFetcher } from './routesV3.client.fetch';\nimport type {\n ArgsFor,\n ArgsTuple,\n BuiltForLeaf,\n BuiltInfinite,\n BuiltMutation,\n BuiltQuery,\n Cursor,\n DataShape,\n InfiniteBuildOptionsFor,\n MutationBuildOptionsFor,\n QueryBuildOptionsFor,\n RouteClient,\n RouteClientOptions,\n RouteClientDebugEvent,\n RouteClientDebugLogger,\n RouteClientDebugOptions,\n Updater,\n} from './routesV3.client.types';\n\n// -------------------------------------------------------------------------------------\n// Tiny helpers\n// -------------------------------------------------------------------------------------\n/**\n * Convert an HTTP method to uppercase (as expected by fetch).\n * @param m Lowercase HTTP method.\n * @returns Uppercase method string.\n */\nconst toUpper = (m: HttpMethod): Uppercase<HttpMethod> => m.toUpperCase() as Uppercase<HttpMethod>;\n\n/**\n * Parse the given value with the supplied schema (if present).\n * @param value Raw value to validate.\n * @param schema Optional Zod schema used for validation/coercion.\n * @returns The validated or original value.\n */\nfunction zParse<T>(value: unknown, schema?: ZodType): T {\n return schema ? (schema.parse(value) as T) : (value as T);\n}\n\n/**\n * Serialize a query object into a search string.\n * @param query Query params object (possibly undefined).\n * @returns Query string prefixed with `?`, or empty string.\n */\nfunction toSearchString(query: Record<string, unknown> | undefined) {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v == null) continue;\n if (Array.isArray(v)) {\n v.forEach((x) => {\n if (x == null) return;\n if (typeof x === 'object') {\n params.append(k, JSON.stringify(x));\n } else {\n params.append(k, String(x));\n }\n });\n continue;\n }\n if (typeof v === 'object') {\n params.set(k, JSON.stringify(v));\n continue;\n }\n params.set(k, String(v));\n }\n const s = params.toString();\n return s ? `?${s}` : '';\n}\n\n/**\n * Remove the given key from an object (used to drop cursors from cache keys).\n * @param obj Source object.\n * @param key Property name to omit.\n * @returns Copy of the object without the specified key.\n */\nfunction stripKey<Q extends Record<string, unknown> | undefined>(obj: Q, key: string): Q {\n if (!obj) return obj;\n const { [key]: _omit, ...rest } = obj as any;\n return rest as Q;\n}\n\n/**\n * Default cursor extractor used by infinite queries.\n * @param p Page result returned from the server.\n * @returns Next cursor string, if present.\n */\nconst defaultGetNextCursor = (p: unknown): Cursor =>\n p && typeof p === 'object' && 'nextCursor' in p ? (p as any).nextCursor : undefined;\n\n// Debug logging --------------------------------------------------------------\nconst noopDebugLogger: RouteClientDebugLogger = () => {};\n\nconst defaultDebugLogger: RouteClientDebugLogger = (event: RouteClientDebugEvent) => {\n if (typeof console === 'undefined') return;\n const fn = console.debug ?? console.log;\n fn?.call(console, '[rrroutes-client]', event);\n};\n\nfunction createDebugEmitter(option?: RouteClientDebugOptions): RouteClientDebugLogger {\n if (!option) {\n return noopDebugLogger;\n }\n if (option === true) {\n return defaultDebugLogger;\n }\n if (typeof option === 'function') {\n return option;\n }\n if (option.enabled === false) {\n return noopDebugLogger;\n }\n return option.logger ?? defaultDebugLogger;\n}\n\n// Split the variadic tuple at runtime\n/**\n * Extract the optional argument object from a variadic tuple.\n * @param args Tuple passed to a built endpoint helper.\n * @returns The argument object if present.\n */\nfunction extractArgs<L extends AnyLeaf>(args: ArgsTuple<L>): ArgsFor<L> | undefined {\n // At runtime ArgsTuple<L> is either [] or [obj]; we just pick the first if present.\n return (args as unknown as any[])[0] as any;\n}\n\n/**\n * Normalize params and query values, then construct a request URL for the given leaf.\n * @param leaf Leaf describing the endpoint.\n * @param baseUrl Optional base URL prepended to the path.\n * @param params Route parameters supplied by the caller.\n * @param query Query parameters supplied by the caller.\n * @returns Object containing the composed URL and normalized query payload.\n */\nfunction buildUrl<L extends AnyLeaf>(\n leaf: L,\n baseUrl: string,\n params: InferParams<L> | undefined,\n query: InferQuery<L> | undefined,\n) {\n const normalizedParams = zParse<InferParams<L>>(params, leaf.cfg.paramsSchema);\n const normalizedQuery = zParse<InferQuery<L>>(query, leaf.cfg.querySchema);\n const path = compilePath<L['path']>(leaf.path, (normalizedParams ?? {}) as any);\n const url = `${baseUrl ?? ''}${path}${toSearchString(normalizedQuery as any)}`;\n return { url, normalizedQuery };\n}\n\n// -------------------------------------------------------------------------------------\n// Client factory\n// -------------------------------------------------------------------------------------\n/**\n * Construct typed React Query helpers backed by a routes-v3 registry leaf.\n * @param opts Route client configuration (query client, fetcher overrides, etc).\n * @returns Object that can build endpoint hooks/mutations from leaves.\n */\nexport function createRouteClient(opts: RouteClientOptions): RouteClient {\n const queryClient = opts.queryClient;\n const fetcher = opts.fetcher ?? defaultFetcher;\n const baseUrl = opts.baseUrl;\n const cursorParam = opts.cursorParam ?? 'cursor';\n const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;\n const emitDebug = createDebugEmitter(opts.debug);\n\n /**\n * Invalidate a set of queries sharing the given prefix.\n * @param prefix Key parts shared by matching endpoints.\n * @param exact When true, invalidate only exact key matches.\n */\n async function invalidate(prefix: string[], exact = false) {\n const queryKey = prefix as unknown as QueryKey;\n await queryClient.invalidateQueries({ queryKey, exact });\n emitDebug({ type: 'invalidate', key: queryKey, exact });\n }\n\n /**\n * Build the client surface for a single leaf (query/mutation/infinite query).\n * @param leaf Leaf describing the endpoint.\n * @param rqOpts Optional React Query configuration.\n * @returns Helper object exposing key/invalidate/setData/useEndpoint.\n */\n function buildInternal<L extends AnyLeaf>(\n leaf: L,\n rqOpts?: QueryBuildOptionsFor<L> | InfiniteBuildOptionsFor<L> | MutationBuildOptionsFor<L>,\n ): BuiltForLeaf<L> {\n const isGet = leaf.method === 'get';\n const isFeed = !!leaf.cfg.feed;\n const method = toUpper(leaf.method);\n const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;\n\n // --- key/invalidate/setData shared helpers ---\n const key = (...tuple: ArgsTuple<L>): QueryKey => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n const qForKey = isGet && isFeed ? stripKey(query as any, cursorParam) : (query as any);\n return buildCacheKey({ leaf, params: params as any, query: qForKey }) as unknown as QueryKey;\n };\n\n /**\n * Invalidate the React Query cache for this exact leaf invocation.\n * @param tuple Optional params/query tuple.\n */\n const invalidateExact = async (...tuple: ArgsTuple<L>) => {\n const queryKey = key(...tuple);\n await queryClient.invalidateQueries({ queryKey, exact: true });\n emitDebug({ type: 'invalidate', key: queryKey, exact: true });\n };\n\n /**\n * Update the cache entries for this leaf.\n * @param args Tuple whose first entry is the updater and optional params/query follow.\n */\n const setData = (...args: [Updater<DataShape<L>>, ...rest: ArgsTuple<L>]) => {\n const [updater, ...rest] = args;\n const k = key(...(rest as ArgsTuple<L>));\n if (isGet && isFeed) {\n queryClient.setQueryData<InfiniteData<InferOutput<L>> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n } else {\n queryClient.setQueryData<InferOutput<L> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n }\n emitDebug({ type: 'setData', key: k });\n };\n\n // --- Infinite GET ---\n if (isGet && isFeed) {\n const useEndpoint: BuiltInfinite<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n // Normalize once; we’ll inject the cursor per page below.\n const { normalizedQuery } = buildUrl(leaf, baseUrl, params, query);\n return useInfiniteQuery<\n InferOutput<L>, // TQueryFnData (per page)\n unknown, // TError\n InfiniteData<InferOutput<L>>, // TData (returned by the hook)\n QueryKey,\n Cursor\n >({\n ...(rqOpts as InfiniteBuildOptionsFor<L>),\n queryKey: key(...tuple),\n initialPageParam: undefined,\n getNextPageParam: (lastPage) => getNextCursor(lastPage),\n placeholderData: keepPreviousData,\n queryFn: async ({ pageParam }) => {\n const pageQuery = {\n ...(normalizedQuery as any),\n ...(pageParam ? { [cursorParam]: pageParam } : {}),\n };\n const { url } = buildUrl(leaf, baseUrl, params, pageQuery);\n const startedAt = Date.now();\n emitDebug({ type: 'fetch', stage: 'start', method, url, leaf: leafLabel });\n try {\n const out = await fetcher<unknown>({ url, method });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n },\n // NOTE: TData is InfiniteData<T>, so we don't need a select here.\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Plain GET ---\n if (isGet) {\n const useEndpoint: BuiltQuery<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url } = buildUrl(leaf, baseUrl, params, query);\n return useQuery<InferOutput<L>, unknown, InferOutput<L>, QueryKey>({\n ...(rqOpts as QueryBuildOptionsFor<L>),\n queryKey: key(...tuple),\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const startedAt = Date.now();\n emitDebug({ type: 'fetch', stage: 'start', method, url, leaf: leafLabel });\n try {\n const out = await fetcher<unknown>({ url, method });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Mutation (POST/PUT/PATCH/DELETE) ---\n const useEndpoint: BuiltMutation<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url } = buildUrl(leaf, baseUrl, params, query);\n return useMutation<InferOutput<L>, unknown, InferBody<L>, unknown>({\n ...(rqOpts as MutationBuildOptionsFor<L>),\n mutationKey: key(...tuple),\n mutationFn: async (body: InferBody<L>) => {\n const normalizedBody = zParse<InferBody<L>>(body, leaf.cfg.bodySchema);\n\n // Optional: switch to FormData if your method declares bodyFiles\n const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;\n const payload = isMultipart ? toFormData(normalizedBody as any) : normalizedBody;\n\n const startedAt = Date.now();\n emitDebug({\n type: 'fetch',\n stage: 'start',\n method,\n url,\n leaf: leafLabel,\n body: payload,\n });\n try {\n const out = await fetcher<unknown>({ url, method, body: payload });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n body: payload,\n error,\n });\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n return {\n queryClient,\n invalidate,\n build: buildInternal as RouteClient['build'],\n };\n}\n\n// -------------------------------------------------------------------------------------\n// Multipart helper\n// -------------------------------------------------------------------------------------\nfunction toFormData(body: Record<string, any>): FormData {\n const fd = new FormData();\n for (const [k, v] of Object.entries(body ?? {})) {\n if (v == null) continue;\n if (Array.isArray(v)) v.forEach((item, i) => fd.append(`${k}[${i}]`, item as any));\n else fd.append(k, v as any);\n }\n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AAM;AAAA,cACN,YAAY,KAAK,IAAI,IAAI;AAAA,cACzB,MAAM;AAAA,cACN;AAAA,YACF,CAAC;AACD,kBAAM;AAAA,UACR;AAAA,QACF;AAAA,MACF,GAAG,WAAW;AAAA,IAChB;AAEA,WAAO;AAAA,MACL;AAAA,MACA,YAAY;AAAA,MACZ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO;AAAA,EACT;AACF;AAKA,SAAS,WAAW,MAAqC;AACvD,QAAM,KAAK,IAAI,SAAS;AACxB,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CAAC,GAAG;AAC/C,QAAI,KAAK,KAAM;AACf,QAAI,MAAM,QAAQ,CAAC,EAAG,GAAE,QAAQ,CAAC,MAAM,MAAM,GAAG,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,IAAW,CAAC;AAAA,QAC5E,IAAG,OAAO,GAAG,CAAQ;AAAA,EAC5B;AACA,SAAO;AACT;","names":["useEndpoint"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/routesV3.client.fetch.ts","../src/routesV3.client.index.ts"],"sourcesContent":["/**\n * This package exports React Query hooks, so we mark it as client-only to keep Next.js happy.\n */\n'use client';\n\nexport * from './routesV3.client.types';\nexport * from './routesV3.client.fetch';\nexport * from './routesV3.client.index';\n","// routesV3.client.fetch.ts\n\nimport { Fetcher, FetchInput } from './routesV3.client.types';\n\n/**\n * Default fetch implementation used by the route client helper.\n * @param req Normalized request information (URL, method, body, headers).\n * @returns Parsed JSON (or text fallback) from the server response.\n */\nexport const defaultFetcher: Fetcher = async <T>(req: FetchInput): Promise<T> => {\n const headers: Record<string, string> = { ...(req.headers ?? {}) };\n const isFormData = typeof FormData !== 'undefined' && req.body instanceof FormData;\n if (!isFormData) {\n headers['Content-Type'] ||= 'application/json';\n headers['Accept'] ||= 'application/json';\n }\n\n const res = await fetch(req.url, {\n method: req.method,\n headers,\n body: isFormData ? (req.body as any) : req.body == null ? undefined : JSON.stringify(req.body),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const snippet = text.slice(0, 400);\n throw new Error(`[${res.status}] ${res.statusText} — ${snippet}`);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n};\n","// routesV3.client.ts\nimport {\n keepPreviousData,\n useInfiniteQuery,\n useMutation,\n useQuery,\n type InfiniteData,\n type QueryKey,\n} from '@tanstack/react-query';\nimport type { ZodType } from 'zod';\nimport {\n HttpMethod,\n buildCacheKey,\n compilePath,\n} from '@emeryld/rrroutes-contract';\nimport type {\n AnyLeaf,\n InferBody,\n InferOutput,\n InferParams,\n InferQuery,\n} from '@emeryld/rrroutes-contract';\nimport { defaultFetcher } from './routesV3.client.fetch';\nimport type {\n ArgsFor,\n ArgsTuple,\n BuiltForLeaf,\n BuiltInfinite,\n BuiltMutation,\n BuiltQuery,\n Cursor,\n DataShape,\n InfiniteBuildOptionsFor,\n MutationBuildOptionsFor,\n QueryBuildOptionsFor,\n RouteClient,\n RouteClientOptions,\n RouteClientDebugEvent,\n RouteClientDebugLogger,\n RouteClientDebugMode,\n RouteClientDebugOptions,\n Updater,\n} from './routesV3.client.types';\n\n// -------------------------------------------------------------------------------------\n// Tiny helpers\n// -------------------------------------------------------------------------------------\n/**\n * Convert an HTTP method to uppercase (as expected by fetch).\n * @param m Lowercase HTTP method.\n * @returns Uppercase method string.\n */\nconst toUpper = (m: HttpMethod): Uppercase<HttpMethod> => m.toUpperCase() as Uppercase<HttpMethod>;\n\n/**\n * Parse the given value with the supplied schema (if present).\n * @param value Raw value to validate.\n * @param schema Optional Zod schema used for validation/coercion.\n * @returns The validated or original value.\n */\nfunction zParse<T>(value: unknown, schema?: ZodType): T {\n return schema ? (schema.parse(value) as T) : (value as T);\n}\n\n/**\n * Serialize a query object into a search string.\n * @param query Query params object (possibly undefined).\n * @returns Query string prefixed with `?`, or empty string.\n */\nfunction toSearchString(query: Record<string, unknown> | undefined) {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v == null) continue;\n if (Array.isArray(v)) {\n v.forEach((x) => {\n if (x == null) return;\n if (typeof x === 'object') {\n params.append(k, JSON.stringify(x));\n } else {\n params.append(k, String(x));\n }\n });\n continue;\n }\n if (typeof v === 'object') {\n params.set(k, JSON.stringify(v));\n continue;\n }\n params.set(k, String(v));\n }\n const s = params.toString();\n return s ? `?${s}` : '';\n}\n\n/**\n * Remove the given key from an object (used to drop cursors from cache keys).\n * @param obj Source object.\n * @param key Property name to omit.\n * @returns Copy of the object without the specified key.\n */\nfunction stripKey<Q extends Record<string, unknown> | undefined>(obj: Q, key: string): Q {\n if (!obj) return obj;\n const { [key]: _omit, ...rest } = obj as any;\n return rest as Q;\n}\n\n/**\n * Default cursor extractor used by infinite queries.\n * @param p Page result returned from the server.\n * @returns Next cursor string, if present.\n */\nconst defaultGetNextCursor = (p: unknown): Cursor =>\n p && typeof p === 'object' && 'nextCursor' in p ? (p as any).nextCursor : undefined;\n\n// Debug logging --------------------------------------------------------------\nconst noopDebugLogger: RouteClientDebugLogger = () => {};\n\nconst defaultDebugLogger: RouteClientDebugLogger = (event: RouteClientDebugEvent) => {\n if (typeof console === 'undefined') return;\n const fn = console.debug ?? console.log;\n fn?.call(console, '[rrroutes-client]', event);\n};\n\ntype DebugEmitter = {\n emit: RouteClientDebugLogger;\n mode: RouteClientDebugMode;\n};\n\nfunction createDebugEmitter(option?: RouteClientDebugOptions): DebugEmitter {\n const disabled: DebugEmitter = { emit: noopDebugLogger, mode: 'minimal' };\n\n if (!option) {\n return disabled;\n }\n if (option === true || option === 'minimal') {\n return { emit: defaultDebugLogger, mode: 'minimal' };\n }\n if (option === 'complete') {\n return { emit: defaultDebugLogger, mode: 'complete' };\n }\n if (typeof option === 'function') {\n return { emit: option, mode: 'minimal' };\n }\n if (option.enabled === false) {\n return { emit: noopDebugLogger, mode: option.mode ?? 'minimal' };\n }\n return {\n emit: option.logger ?? defaultDebugLogger,\n mode: option.mode ?? 'minimal',\n };\n}\n\n// Split the variadic tuple at runtime\n/**\n * Extract the optional argument object from a variadic tuple.\n * @param args Tuple passed to a built endpoint helper.\n * @returns The argument object if present.\n */\nfunction extractArgs<L extends AnyLeaf>(args: ArgsTuple<L>): ArgsFor<L> | undefined {\n // At runtime ArgsTuple<L> is either [] or [obj]; we just pick the first if present.\n return (args as unknown as any[])[0] as any;\n}\n\n/**\n * Normalize params and query values, then construct a request URL for the given leaf.\n * @param leaf Leaf describing the endpoint.\n * @param baseUrl Optional base URL prepended to the path.\n * @param params Route parameters supplied by the caller.\n * @param query Query parameters supplied by the caller.\n * @returns Object containing the composed URL plus normalized params/query payloads.\n */\nfunction buildUrl<L extends AnyLeaf>(\n leaf: L,\n baseUrl: string,\n params: InferParams<L> | undefined,\n query: InferQuery<L> | undefined,\n) {\n const normalizedParams = zParse<InferParams<L>>(params, leaf.cfg.paramsSchema);\n const normalizedQuery = zParse<InferQuery<L>>(query, leaf.cfg.querySchema);\n const path = compilePath<L['path']>(leaf.path, (normalizedParams ?? {}) as any);\n const url = `${baseUrl ?? ''}${path}${toSearchString(normalizedQuery as any)}`;\n return { url, normalizedQuery, normalizedParams };\n}\n\n// -------------------------------------------------------------------------------------\n// Client factory\n// -------------------------------------------------------------------------------------\n/**\n * Construct typed React Query helpers backed by a routes-v3 registry leaf.\n * @param opts Route client configuration (query client, fetcher overrides, etc).\n * @returns Object that can build endpoint hooks/mutations from leaves.\n */\nexport function createRouteClient(opts: RouteClientOptions): RouteClient {\n const queryClient = opts.queryClient;\n const fetcher = opts.fetcher ?? defaultFetcher;\n const baseUrl = opts.baseUrl;\n const cursorParam = opts.cursorParam ?? 'cursor';\n const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;\n const { emit: emitDebug, mode: debugMode } = createDebugEmitter(opts.debug);\n const isVerboseDebug = debugMode === 'complete';\n const decorateDebugEvent = <T extends RouteClientDebugEvent>(\n event: T,\n details?: Partial<RouteClientDebugEvent>,\n ): RouteClientDebugEvent => {\n if (!isVerboseDebug || !details) return event;\n return { ...event, ...details } as RouteClientDebugEvent;\n };\n\n /**\n * Invalidate a set of queries sharing the given prefix.\n * @param prefix Key parts shared by matching endpoints.\n * @param exact When true, invalidate only exact key matches.\n */\n async function invalidate(prefix: string[], exact = false) {\n const queryKey = prefix as unknown as QueryKey;\n await queryClient.invalidateQueries({ queryKey, exact });\n emitDebug({ type: 'invalidate', key: queryKey, exact });\n }\n\n /**\n * Build the client surface for a single leaf (query/mutation/infinite query).\n * @param leaf Leaf describing the endpoint.\n * @param rqOpts Optional React Query configuration.\n * @returns Helper object exposing key/invalidate/setData/useEndpoint.\n */\n function buildInternal<L extends AnyLeaf>(\n leaf: L,\n rqOpts?: QueryBuildOptionsFor<L> | InfiniteBuildOptionsFor<L> | MutationBuildOptionsFor<L>,\n ): BuiltForLeaf<L> {\n const isGet = leaf.method === 'get';\n const isFeed = !!leaf.cfg.feed;\n const method = toUpper(leaf.method);\n const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;\n emitDebug({ type: 'build', leaf: leafLabel });\n\n // --- key/invalidate/setData shared helpers ---\n const key = (...tuple: ArgsTuple<L>): QueryKey => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n const qForKey = isGet && isFeed ? stripKey(query as any, cursorParam) : (query as any);\n return buildCacheKey({ leaf, params: params as any, query: qForKey }) as unknown as QueryKey;\n };\n\n /**\n * Invalidate the React Query cache for this exact leaf invocation.\n * @param tuple Optional params/query tuple.\n */\n const invalidateExact = async (...tuple: ArgsTuple<L>) => {\n const queryKey = key(...tuple);\n await queryClient.invalidateQueries({ queryKey, exact: true });\n emitDebug({ type: 'invalidate', key: queryKey, exact: true });\n };\n\n /**\n * Update the cache entries for this leaf.\n * @param args Tuple whose first entry is the updater and optional params/query follow.\n */\n const setData = (...args: [Updater<DataShape<L>>, ...rest: ArgsTuple<L>]) => {\n const [updater, ...rest] = args;\n const k = key(...(rest as ArgsTuple<L>));\n if (isGet && isFeed) {\n queryClient.setQueryData<InfiniteData<InferOutput<L>> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n } else {\n queryClient.setQueryData<InferOutput<L> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n }\n emitDebug({ type: 'setData', key: k });\n };\n\n // --- Infinite GET ---\n if (isGet && isFeed) {\n const useEndpoint: BuiltInfinite<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useInfiniteGet', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n // Normalize once; we’ll inject the cursor per page below.\n const { normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useInfiniteQuery<\n InferOutput<L>, // TQueryFnData (per page)\n unknown, // TError\n InfiniteData<InferOutput<L>>, // TData (returned by the hook)\n QueryKey,\n Cursor\n >({\n ...(rqOpts as InfiniteBuildOptionsFor<L>),\n queryKey: key(...tuple),\n initialPageParam: undefined,\n getNextPageParam: (lastPage) => getNextCursor(lastPage),\n placeholderData: keepPreviousData,\n queryFn: async ({ pageParam }) => {\n const pageQuery = {\n ...(normalizedQuery as any),\n ...(pageParam ? { [cursorParam]: pageParam } : {}),\n };\n const { url } = buildUrl(leaf, baseUrl, params, pageQuery);\n const startedAt = Date.now();\n const detail = isVerboseDebug ? { params: normalizedParams, query: pageQuery } : undefined;\n emitDebug(\n decorateDebugEvent(\n { type: 'fetch', stage: 'start', method, url, leaf: leafLabel },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug ? { params: normalizedParams, query: pageQuery, output: parsed } : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n // NOTE: TData is InfiniteData<T>, so we don't need a select here.\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n // --- Plain GET ---\n if (isGet) {\n const useEndpoint: BuiltQuery<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useGet', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useQuery<InferOutput<L>, unknown, InferOutput<L>, QueryKey>({\n ...(rqOpts as QueryBuildOptionsFor<L>),\n queryKey: key(...tuple),\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const startedAt = Date.now();\n const detail = isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery }\n : undefined;\n emitDebug(\n decorateDebugEvent(\n { type: 'fetch', stage: 'start', method, url, leaf: leafLabel },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery, output: parsed }\n : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Mutation (POST/PUT/PATCH/DELETE) ---\n const useEndpoint: BuiltMutation<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useMutation', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useMutation<InferOutput<L>, unknown, InferBody<L>, unknown>({\n ...(rqOpts as MutationBuildOptionsFor<L>),\n mutationKey: key(...tuple),\n mutationFn: async (body: InferBody<L>) => {\n const normalizedBody = zParse<InferBody<L>>(body, leaf.cfg.bodySchema);\n\n // Optional: switch to FormData if your method declares bodyFiles\n const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;\n const payload = isMultipart ? toFormData(normalizedBody as any) : normalizedBody;\n\n const startedAt = Date.now();\n const detail = isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery }\n : undefined;\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'start',\n method,\n url,\n leaf: leafLabel,\n body: payload,\n },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method, body: payload });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery, output: parsed }\n : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n body: payload,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n return {\n queryClient,\n invalidate,\n build: buildInternal as RouteClient['build'],\n };\n}\n\n// -------------------------------------------------------------------------------------\n// Multipart helper\n// -------------------------------------------------------------------------------------\nfunction toFormData(body: Record<string, any>): FormData {\n const fd = new FormData();\n for (const [k, v] of Object.entries(body ?? {})) {\n if (v == null) continue;\n if (Array.isArray(v)) v.forEach((item, i) => fd.append(`${k}[${i}]`, item as any));\n else fd.append(k, v as any);\n }\n return fd;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,iBAA0B,OAAU,QAAgC;AAC/E,QAAM,UAAkC,EAAE,GAAI,IAAI,WAAW,CAAC,EAAG;AACjE,QAAM,aAAa,OAAO,aAAa,eAAe,IAAI,gBAAgB;AAC1E,MAAI,CAAC,YAAY;AACf,0DAA4B;AAC5B,8CAAsB;AAAA,EACxB;AAEA,QAAM,MAAM,MAAM,MAAM,IAAI,KAAK;AAAA,IAC/B,QAAQ,IAAI;AAAA,IACZ;AAAA,IACA,MAAM,aAAc,IAAI,OAAe,IAAI,QAAQ,OAAO,SAAY,KAAK,UAAU,IAAI,IAAI;AAAA,EAC/F,CAAC;AAED,QAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,UAAU,KAAK,MAAM,GAAG,GAAG;AACjC,UAAM,IAAI,MAAM,IAAI,IAAI,MAAM,KAAK,IAAI,UAAU,WAAM,OAAO,EAAE;AAAA,EAClE;AAEA,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACjCA,yBAOO;AAEP,+BAIO;AAsCP,IAAM,UAAU,CAAC,MAAyC,EAAE,YA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GAAG;AAC/C,QAAI,KAAK,KAAM;AACf,QAAI,MAAM,QAAQ,CAAC,EAAG,GAAE,QAAQ,CAAC,MAAM,MAAM,GAAG,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,IAAW,CAAC;AAAA,QAC5E,IAAG,OAAO,GAAG,CAAQ;AAAA,EAC5B;AACA,SAAO;AACT;","names":["useEndpoint"]}
|
package/dist/index.mjs
CHANGED
|
@@ -79,19 +79,26 @@ var defaultDebugLogger = (event) => {
|
|
|
79
79
|
fn?.call(console, "[rrroutes-client]", event);
|
|
80
80
|
};
|
|
81
81
|
function createDebugEmitter(option) {
|
|
82
|
+
const disabled = { emit: noopDebugLogger, mode: "minimal" };
|
|
82
83
|
if (!option) {
|
|
83
|
-
return
|
|
84
|
+
return disabled;
|
|
84
85
|
}
|
|
85
|
-
if (option === true) {
|
|
86
|
-
return defaultDebugLogger;
|
|
86
|
+
if (option === true || option === "minimal") {
|
|
87
|
+
return { emit: defaultDebugLogger, mode: "minimal" };
|
|
88
|
+
}
|
|
89
|
+
if (option === "complete") {
|
|
90
|
+
return { emit: defaultDebugLogger, mode: "complete" };
|
|
87
91
|
}
|
|
88
92
|
if (typeof option === "function") {
|
|
89
|
-
return option;
|
|
93
|
+
return { emit: option, mode: "minimal" };
|
|
90
94
|
}
|
|
91
95
|
if (option.enabled === false) {
|
|
92
|
-
return noopDebugLogger;
|
|
96
|
+
return { emit: noopDebugLogger, mode: option.mode ?? "minimal" };
|
|
93
97
|
}
|
|
94
|
-
return
|
|
98
|
+
return {
|
|
99
|
+
emit: option.logger ?? defaultDebugLogger,
|
|
100
|
+
mode: option.mode ?? "minimal"
|
|
101
|
+
};
|
|
95
102
|
}
|
|
96
103
|
function extractArgs(args) {
|
|
97
104
|
return args[0];
|
|
@@ -101,7 +108,7 @@ function buildUrl(leaf, baseUrl, params, query) {
|
|
|
101
108
|
const normalizedQuery = zParse(query, leaf.cfg.querySchema);
|
|
102
109
|
const path = compilePath(leaf.path, normalizedParams ?? {});
|
|
103
110
|
const url = `${baseUrl ?? ""}${path}${toSearchString(normalizedQuery)}`;
|
|
104
|
-
return { url, normalizedQuery };
|
|
111
|
+
return { url, normalizedQuery, normalizedParams };
|
|
105
112
|
}
|
|
106
113
|
function createRouteClient(opts) {
|
|
107
114
|
const queryClient = opts.queryClient;
|
|
@@ -109,7 +116,12 @@ function createRouteClient(opts) {
|
|
|
109
116
|
const baseUrl = opts.baseUrl;
|
|
110
117
|
const cursorParam = opts.cursorParam ?? "cursor";
|
|
111
118
|
const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;
|
|
112
|
-
const emitDebug = createDebugEmitter(opts.debug);
|
|
119
|
+
const { emit: emitDebug, mode: debugMode } = createDebugEmitter(opts.debug);
|
|
120
|
+
const isVerboseDebug = debugMode === "complete";
|
|
121
|
+
const decorateDebugEvent = (event, details) => {
|
|
122
|
+
if (!isVerboseDebug || !details) return event;
|
|
123
|
+
return { ...event, ...details };
|
|
124
|
+
};
|
|
113
125
|
async function invalidate(prefix, exact = false) {
|
|
114
126
|
const queryKey = prefix;
|
|
115
127
|
await queryClient.invalidateQueries({ queryKey, exact });
|
|
@@ -120,6 +132,7 @@ function createRouteClient(opts) {
|
|
|
120
132
|
const isFeed = !!leaf.cfg.feed;
|
|
121
133
|
const method = toUpper(leaf.method);
|
|
122
134
|
const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;
|
|
135
|
+
emitDebug({ type: "build", leaf: leafLabel });
|
|
123
136
|
const key = (...tuple) => {
|
|
124
137
|
const a = extractArgs(tuple);
|
|
125
138
|
const params = a?.params;
|
|
@@ -150,10 +163,11 @@ function createRouteClient(opts) {
|
|
|
150
163
|
};
|
|
151
164
|
if (isGet && isFeed) {
|
|
152
165
|
const useEndpoint2 = (...tuple) => {
|
|
166
|
+
emitDebug({ type: "useInfiniteGet", leaf: leafLabel });
|
|
153
167
|
const a = extractArgs(tuple);
|
|
154
168
|
const params = a?.params;
|
|
155
169
|
const query = a?.query;
|
|
156
|
-
const { normalizedQuery } = buildUrl(leaf, baseUrl, params, query);
|
|
170
|
+
const { normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
157
171
|
return useInfiniteQuery({
|
|
158
172
|
...rqOpts,
|
|
159
173
|
queryKey: key(...tuple),
|
|
@@ -167,28 +181,45 @@ function createRouteClient(opts) {
|
|
|
167
181
|
};
|
|
168
182
|
const { url } = buildUrl(leaf, baseUrl, params, pageQuery);
|
|
169
183
|
const startedAt = Date.now();
|
|
170
|
-
|
|
184
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: pageQuery } : void 0;
|
|
185
|
+
emitDebug(
|
|
186
|
+
decorateDebugEvent(
|
|
187
|
+
{ type: "fetch", stage: "start", method, url, leaf: leafLabel },
|
|
188
|
+
detail
|
|
189
|
+
)
|
|
190
|
+
);
|
|
171
191
|
try {
|
|
172
192
|
const out = await fetcher({ url, method });
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
193
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
194
|
+
emitDebug(
|
|
195
|
+
decorateDebugEvent(
|
|
196
|
+
{
|
|
197
|
+
type: "fetch",
|
|
198
|
+
stage: "success",
|
|
199
|
+
method,
|
|
200
|
+
url,
|
|
201
|
+
leaf: leafLabel,
|
|
202
|
+
durationMs: Date.now() - startedAt
|
|
203
|
+
},
|
|
204
|
+
isVerboseDebug ? { params: normalizedParams, query: pageQuery, output: parsed } : void 0
|
|
205
|
+
)
|
|
206
|
+
);
|
|
207
|
+
return parsed;
|
|
182
208
|
} catch (error) {
|
|
183
|
-
emitDebug(
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
209
|
+
emitDebug(
|
|
210
|
+
decorateDebugEvent(
|
|
211
|
+
{
|
|
212
|
+
type: "fetch",
|
|
213
|
+
stage: "error",
|
|
214
|
+
method,
|
|
215
|
+
url,
|
|
216
|
+
leaf: leafLabel,
|
|
217
|
+
durationMs: Date.now() - startedAt,
|
|
218
|
+
error
|
|
219
|
+
},
|
|
220
|
+
detail
|
|
221
|
+
)
|
|
222
|
+
);
|
|
192
223
|
throw error;
|
|
193
224
|
}
|
|
194
225
|
}
|
|
@@ -204,38 +235,56 @@ function createRouteClient(opts) {
|
|
|
204
235
|
}
|
|
205
236
|
if (isGet) {
|
|
206
237
|
const useEndpoint2 = (...tuple) => {
|
|
238
|
+
emitDebug({ type: "useGet", leaf: leafLabel });
|
|
207
239
|
const a = extractArgs(tuple);
|
|
208
240
|
const params = a?.params;
|
|
209
241
|
const query = a?.query;
|
|
210
|
-
const { url } = buildUrl(leaf, baseUrl, params, query);
|
|
242
|
+
const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
211
243
|
return useQuery({
|
|
212
244
|
...rqOpts,
|
|
213
245
|
queryKey: key(...tuple),
|
|
214
246
|
placeholderData: keepPreviousData,
|
|
215
247
|
queryFn: async () => {
|
|
216
248
|
const startedAt = Date.now();
|
|
217
|
-
|
|
249
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: normalizedQuery } : void 0;
|
|
250
|
+
emitDebug(
|
|
251
|
+
decorateDebugEvent(
|
|
252
|
+
{ type: "fetch", stage: "start", method, url, leaf: leafLabel },
|
|
253
|
+
detail
|
|
254
|
+
)
|
|
255
|
+
);
|
|
218
256
|
try {
|
|
219
257
|
const out = await fetcher({ url, method });
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
258
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
259
|
+
emitDebug(
|
|
260
|
+
decorateDebugEvent(
|
|
261
|
+
{
|
|
262
|
+
type: "fetch",
|
|
263
|
+
stage: "success",
|
|
264
|
+
method,
|
|
265
|
+
url,
|
|
266
|
+
leaf: leafLabel,
|
|
267
|
+
durationMs: Date.now() - startedAt
|
|
268
|
+
},
|
|
269
|
+
isVerboseDebug ? { params: normalizedParams, query: normalizedQuery, output: parsed } : void 0
|
|
270
|
+
)
|
|
271
|
+
);
|
|
272
|
+
return parsed;
|
|
229
273
|
} catch (error) {
|
|
230
|
-
emitDebug(
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
274
|
+
emitDebug(
|
|
275
|
+
decorateDebugEvent(
|
|
276
|
+
{
|
|
277
|
+
type: "fetch",
|
|
278
|
+
stage: "error",
|
|
279
|
+
method,
|
|
280
|
+
url,
|
|
281
|
+
leaf: leafLabel,
|
|
282
|
+
durationMs: Date.now() - startedAt,
|
|
283
|
+
error
|
|
284
|
+
},
|
|
285
|
+
detail
|
|
286
|
+
)
|
|
287
|
+
);
|
|
239
288
|
throw error;
|
|
240
289
|
}
|
|
241
290
|
}
|
|
@@ -249,10 +298,11 @@ function createRouteClient(opts) {
|
|
|
249
298
|
};
|
|
250
299
|
}
|
|
251
300
|
const useEndpoint = (...tuple) => {
|
|
301
|
+
emitDebug({ type: "useMutation", leaf: leafLabel });
|
|
252
302
|
const a = extractArgs(tuple);
|
|
253
303
|
const params = a?.params;
|
|
254
304
|
const query = a?.query;
|
|
255
|
-
const { url } = buildUrl(leaf, baseUrl, params, query);
|
|
305
|
+
const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);
|
|
256
306
|
return useMutation({
|
|
257
307
|
...rqOpts,
|
|
258
308
|
mutationKey: key(...tuple),
|
|
@@ -261,36 +311,53 @@ function createRouteClient(opts) {
|
|
|
261
311
|
const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;
|
|
262
312
|
const payload = isMultipart ? toFormData(normalizedBody) : normalizedBody;
|
|
263
313
|
const startedAt = Date.now();
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
314
|
+
const detail = isVerboseDebug ? { params: normalizedParams, query: normalizedQuery } : void 0;
|
|
315
|
+
emitDebug(
|
|
316
|
+
decorateDebugEvent(
|
|
317
|
+
{
|
|
318
|
+
type: "fetch",
|
|
319
|
+
stage: "start",
|
|
320
|
+
method,
|
|
321
|
+
url,
|
|
322
|
+
leaf: leafLabel,
|
|
323
|
+
body: payload
|
|
324
|
+
},
|
|
325
|
+
detail
|
|
326
|
+
)
|
|
327
|
+
);
|
|
272
328
|
try {
|
|
273
329
|
const out = await fetcher({ url, method, body: payload });
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
330
|
+
const parsed = zParse(out, leaf.cfg.outputSchema);
|
|
331
|
+
emitDebug(
|
|
332
|
+
decorateDebugEvent(
|
|
333
|
+
{
|
|
334
|
+
type: "fetch",
|
|
335
|
+
stage: "success",
|
|
336
|
+
method,
|
|
337
|
+
url,
|
|
338
|
+
leaf: leafLabel,
|
|
339
|
+
durationMs: Date.now() - startedAt
|
|
340
|
+
},
|
|
341
|
+
isVerboseDebug ? { params: normalizedParams, query: normalizedQuery, output: parsed } : void 0
|
|
342
|
+
)
|
|
343
|
+
);
|
|
344
|
+
return parsed;
|
|
283
345
|
} catch (error) {
|
|
284
|
-
emitDebug(
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
346
|
+
emitDebug(
|
|
347
|
+
decorateDebugEvent(
|
|
348
|
+
{
|
|
349
|
+
type: "fetch",
|
|
350
|
+
stage: "error",
|
|
351
|
+
method,
|
|
352
|
+
url,
|
|
353
|
+
leaf: leafLabel,
|
|
354
|
+
durationMs: Date.now() - startedAt,
|
|
355
|
+
body: payload,
|
|
356
|
+
error
|
|
357
|
+
},
|
|
358
|
+
detail
|
|
359
|
+
)
|
|
360
|
+
);
|
|
294
361
|
throw error;
|
|
295
362
|
}
|
|
296
363
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routesV3.client.fetch.ts","../src/routesV3.client.index.ts"],"sourcesContent":["// routesV3.client.fetch.ts\n\nimport { Fetcher, FetchInput } from './routesV3.client.types';\n\n/**\n * Default fetch implementation used by the route client helper.\n * @param req Normalized request information (URL, method, body, headers).\n * @returns Parsed JSON (or text fallback) from the server response.\n */\nexport const defaultFetcher: Fetcher = async <T>(req: FetchInput): Promise<T> => {\n const headers: Record<string, string> = { ...(req.headers ?? {}) };\n const isFormData = typeof FormData !== 'undefined' && req.body instanceof FormData;\n if (!isFormData) {\n headers['Content-Type'] ||= 'application/json';\n headers['Accept'] ||= 'application/json';\n }\n\n const res = await fetch(req.url, {\n method: req.method,\n headers,\n body: isFormData ? (req.body as any) : req.body == null ? undefined : JSON.stringify(req.body),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const snippet = text.slice(0, 400);\n throw new Error(`[${res.status}] ${res.statusText} — ${snippet}`);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n};\n","// routesV3.client.ts\nimport {\n keepPreviousData,\n useInfiniteQuery,\n useMutation,\n useQuery,\n type InfiniteData,\n type QueryKey,\n} from '@tanstack/react-query';\nimport type { ZodType } from 'zod';\nimport {\n HttpMethod,\n buildCacheKey,\n compilePath,\n} from '@emeryld/rrroutes-contract';\nimport type {\n AnyLeaf,\n InferBody,\n InferOutput,\n InferParams,\n InferQuery,\n} from '@emeryld/rrroutes-contract';\nimport { defaultFetcher } from './routesV3.client.fetch';\nimport type {\n ArgsFor,\n ArgsTuple,\n BuiltForLeaf,\n BuiltInfinite,\n BuiltMutation,\n BuiltQuery,\n Cursor,\n DataShape,\n InfiniteBuildOptionsFor,\n MutationBuildOptionsFor,\n QueryBuildOptionsFor,\n RouteClient,\n RouteClientOptions,\n RouteClientDebugEvent,\n RouteClientDebugLogger,\n RouteClientDebugOptions,\n Updater,\n} from './routesV3.client.types';\n\n// -------------------------------------------------------------------------------------\n// Tiny helpers\n// -------------------------------------------------------------------------------------\n/**\n * Convert an HTTP method to uppercase (as expected by fetch).\n * @param m Lowercase HTTP method.\n * @returns Uppercase method string.\n */\nconst toUpper = (m: HttpMethod): Uppercase<HttpMethod> => m.toUpperCase() as Uppercase<HttpMethod>;\n\n/**\n * Parse the given value with the supplied schema (if present).\n * @param value Raw value to validate.\n * @param schema Optional Zod schema used for validation/coercion.\n * @returns The validated or original value.\n */\nfunction zParse<T>(value: unknown, schema?: ZodType): T {\n return schema ? (schema.parse(value) as T) : (value as T);\n}\n\n/**\n * Serialize a query object into a search string.\n * @param query Query params object (possibly undefined).\n * @returns Query string prefixed with `?`, or empty string.\n */\nfunction toSearchString(query: Record<string, unknown> | undefined) {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v == null) continue;\n if (Array.isArray(v)) {\n v.forEach((x) => {\n if (x == null) return;\n if (typeof x === 'object') {\n params.append(k, JSON.stringify(x));\n } else {\n params.append(k, String(x));\n }\n });\n continue;\n }\n if (typeof v === 'object') {\n params.set(k, JSON.stringify(v));\n continue;\n }\n params.set(k, String(v));\n }\n const s = params.toString();\n return s ? `?${s}` : '';\n}\n\n/**\n * Remove the given key from an object (used to drop cursors from cache keys).\n * @param obj Source object.\n * @param key Property name to omit.\n * @returns Copy of the object without the specified key.\n */\nfunction stripKey<Q extends Record<string, unknown> | undefined>(obj: Q, key: string): Q {\n if (!obj) return obj;\n const { [key]: _omit, ...rest } = obj as any;\n return rest as Q;\n}\n\n/**\n * Default cursor extractor used by infinite queries.\n * @param p Page result returned from the server.\n * @returns Next cursor string, if present.\n */\nconst defaultGetNextCursor = (p: unknown): Cursor =>\n p && typeof p === 'object' && 'nextCursor' in p ? (p as any).nextCursor : undefined;\n\n// Debug logging --------------------------------------------------------------\nconst noopDebugLogger: RouteClientDebugLogger = () => {};\n\nconst defaultDebugLogger: RouteClientDebugLogger = (event: RouteClientDebugEvent) => {\n if (typeof console === 'undefined') return;\n const fn = console.debug ?? console.log;\n fn?.call(console, '[rrroutes-client]', event);\n};\n\nfunction createDebugEmitter(option?: RouteClientDebugOptions): RouteClientDebugLogger {\n if (!option) {\n return noopDebugLogger;\n }\n if (option === true) {\n return defaultDebugLogger;\n }\n if (typeof option === 'function') {\n return option;\n }\n if (option.enabled === false) {\n return noopDebugLogger;\n }\n return option.logger ?? defaultDebugLogger;\n}\n\n// Split the variadic tuple at runtime\n/**\n * Extract the optional argument object from a variadic tuple.\n * @param args Tuple passed to a built endpoint helper.\n * @returns The argument object if present.\n */\nfunction extractArgs<L extends AnyLeaf>(args: ArgsTuple<L>): ArgsFor<L> | undefined {\n // At runtime ArgsTuple<L> is either [] or [obj]; we just pick the first if present.\n return (args as unknown as any[])[0] as any;\n}\n\n/**\n * Normalize params and query values, then construct a request URL for the given leaf.\n * @param leaf Leaf describing the endpoint.\n * @param baseUrl Optional base URL prepended to the path.\n * @param params Route parameters supplied by the caller.\n * @param query Query parameters supplied by the caller.\n * @returns Object containing the composed URL and normalized query payload.\n */\nfunction buildUrl<L extends AnyLeaf>(\n leaf: L,\n baseUrl: string,\n params: InferParams<L> | undefined,\n query: InferQuery<L> | undefined,\n) {\n const normalizedParams = zParse<InferParams<L>>(params, leaf.cfg.paramsSchema);\n const normalizedQuery = zParse<InferQuery<L>>(query, leaf.cfg.querySchema);\n const path = compilePath<L['path']>(leaf.path, (normalizedParams ?? {}) as any);\n const url = `${baseUrl ?? ''}${path}${toSearchString(normalizedQuery as any)}`;\n return { url, normalizedQuery };\n}\n\n// -------------------------------------------------------------------------------------\n// Client factory\n// -------------------------------------------------------------------------------------\n/**\n * Construct typed React Query helpers backed by a routes-v3 registry leaf.\n * @param opts Route client configuration (query client, fetcher overrides, etc).\n * @returns Object that can build endpoint hooks/mutations from leaves.\n */\nexport function createRouteClient(opts: RouteClientOptions): RouteClient {\n const queryClient = opts.queryClient;\n const fetcher = opts.fetcher ?? defaultFetcher;\n const baseUrl = opts.baseUrl;\n const cursorParam = opts.cursorParam ?? 'cursor';\n const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;\n const emitDebug = createDebugEmitter(opts.debug);\n\n /**\n * Invalidate a set of queries sharing the given prefix.\n * @param prefix Key parts shared by matching endpoints.\n * @param exact When true, invalidate only exact key matches.\n */\n async function invalidate(prefix: string[], exact = false) {\n const queryKey = prefix as unknown as QueryKey;\n await queryClient.invalidateQueries({ queryKey, exact });\n emitDebug({ type: 'invalidate', key: queryKey, exact });\n }\n\n /**\n * Build the client surface for a single leaf (query/mutation/infinite query).\n * @param leaf Leaf describing the endpoint.\n * @param rqOpts Optional React Query configuration.\n * @returns Helper object exposing key/invalidate/setData/useEndpoint.\n */\n function buildInternal<L extends AnyLeaf>(\n leaf: L,\n rqOpts?: QueryBuildOptionsFor<L> | InfiniteBuildOptionsFor<L> | MutationBuildOptionsFor<L>,\n ): BuiltForLeaf<L> {\n const isGet = leaf.method === 'get';\n const isFeed = !!leaf.cfg.feed;\n const method = toUpper(leaf.method);\n const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;\n\n // --- key/invalidate/setData shared helpers ---\n const key = (...tuple: ArgsTuple<L>): QueryKey => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n const qForKey = isGet && isFeed ? stripKey(query as any, cursorParam) : (query as any);\n return buildCacheKey({ leaf, params: params as any, query: qForKey }) as unknown as QueryKey;\n };\n\n /**\n * Invalidate the React Query cache for this exact leaf invocation.\n * @param tuple Optional params/query tuple.\n */\n const invalidateExact = async (...tuple: ArgsTuple<L>) => {\n const queryKey = key(...tuple);\n await queryClient.invalidateQueries({ queryKey, exact: true });\n emitDebug({ type: 'invalidate', key: queryKey, exact: true });\n };\n\n /**\n * Update the cache entries for this leaf.\n * @param args Tuple whose first entry is the updater and optional params/query follow.\n */\n const setData = (...args: [Updater<DataShape<L>>, ...rest: ArgsTuple<L>]) => {\n const [updater, ...rest] = args;\n const k = key(...(rest as ArgsTuple<L>));\n if (isGet && isFeed) {\n queryClient.setQueryData<InfiniteData<InferOutput<L>> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n } else {\n queryClient.setQueryData<InferOutput<L> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n }\n emitDebug({ type: 'setData', key: k });\n };\n\n // --- Infinite GET ---\n if (isGet && isFeed) {\n const useEndpoint: BuiltInfinite<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n // Normalize once; we’ll inject the cursor per page below.\n const { normalizedQuery } = buildUrl(leaf, baseUrl, params, query);\n return useInfiniteQuery<\n InferOutput<L>, // TQueryFnData (per page)\n unknown, // TError\n InfiniteData<InferOutput<L>>, // TData (returned by the hook)\n QueryKey,\n Cursor\n >({\n ...(rqOpts as InfiniteBuildOptionsFor<L>),\n queryKey: key(...tuple),\n initialPageParam: undefined,\n getNextPageParam: (lastPage) => getNextCursor(lastPage),\n placeholderData: keepPreviousData,\n queryFn: async ({ pageParam }) => {\n const pageQuery = {\n ...(normalizedQuery as any),\n ...(pageParam ? { [cursorParam]: pageParam } : {}),\n };\n const { url } = buildUrl(leaf, baseUrl, params, pageQuery);\n const startedAt = Date.now();\n emitDebug({ type: 'fetch', stage: 'start', method, url, leaf: leafLabel });\n try {\n const out = await fetcher<unknown>({ url, method });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n },\n // NOTE: TData is InfiniteData<T>, so we don't need a select here.\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Plain GET ---\n if (isGet) {\n const useEndpoint: BuiltQuery<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url } = buildUrl(leaf, baseUrl, params, query);\n return useQuery<InferOutput<L>, unknown, InferOutput<L>, QueryKey>({\n ...(rqOpts as QueryBuildOptionsFor<L>),\n queryKey: key(...tuple),\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const startedAt = Date.now();\n emitDebug({ type: 'fetch', stage: 'start', method, url, leaf: leafLabel });\n try {\n const out = await fetcher<unknown>({ url, method });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Mutation (POST/PUT/PATCH/DELETE) ---\n const useEndpoint: BuiltMutation<L>['useEndpoint'] = (...tuple) => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url } = buildUrl(leaf, baseUrl, params, query);\n return useMutation<InferOutput<L>, unknown, InferBody<L>, unknown>({\n ...(rqOpts as MutationBuildOptionsFor<L>),\n mutationKey: key(...tuple),\n mutationFn: async (body: InferBody<L>) => {\n const normalizedBody = zParse<InferBody<L>>(body, leaf.cfg.bodySchema);\n\n // Optional: switch to FormData if your method declares bodyFiles\n const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;\n const payload = isMultipart ? toFormData(normalizedBody as any) : normalizedBody;\n\n const startedAt = Date.now();\n emitDebug({\n type: 'fetch',\n stage: 'start',\n method,\n url,\n leaf: leafLabel,\n body: payload,\n });\n try {\n const out = await fetcher<unknown>({ url, method, body: payload });\n emitDebug({\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n });\n return zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n } catch (error) {\n emitDebug({\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n body: payload,\n error,\n });\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n return {\n queryClient,\n invalidate,\n build: buildInternal as RouteClient['build'],\n };\n}\n\n// -------------------------------------------------------------------------------------\n// Multipart helper\n// -------------------------------------------------------------------------------------\nfunction toFormData(body: Record<string, any>): FormData {\n const fd = new FormData();\n for (const [k, v] of Object.entries(body ?? {})) {\n if (v == null) continue;\n if (Array.isArray(v)) v.forEach((item, i) => fd.append(`${k}[${i}]`, item as any));\n else fd.append(k, v as any);\n }\n return fd;\n}\n"],"mappings":";;;AASO,IAAM,iBAA0B,OAAU,QAAgC;AAC/E,QAAM,UAAkC,EAAE,GAAI,IAAI,WAAW,CAAC,EAAG;AACjE,QAAM,aAAa,OAAO,aAAa,eAAe,IAAI,gBAAgB;AAC1E,MAAI,CAAC,YAAY;AACf,0DAA4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AAA,MACZ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO;AAAA,EACT;AACF;AAKA,SAAS,WAAW,MAAqC;AACvD,QAAM,KAAK,IAAI,SAAS;AACxB,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CAAC,GAAG;AAC/C,QAAI,KAAK,KAAM;AACf,QAAI,MAAM,QAAQ,CAAC,EAAG,GAAE,QAAQ,CAAC,MAAM,MAAM,GAAG,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,IAAW,CAAC;AAAA,QAC5E,IAAG,OAAO,GAAG,CAAQ;AAAA,EAC5B;AACA,SAAO;AACT;","names":["useEndpoint"]}
|
|
1
|
+
{"version":3,"sources":["../src/routesV3.client.fetch.ts","../src/routesV3.client.index.ts"],"sourcesContent":["// routesV3.client.fetch.ts\n\nimport { Fetcher, FetchInput } from './routesV3.client.types';\n\n/**\n * Default fetch implementation used by the route client helper.\n * @param req Normalized request information (URL, method, body, headers).\n * @returns Parsed JSON (or text fallback) from the server response.\n */\nexport const defaultFetcher: Fetcher = async <T>(req: FetchInput): Promise<T> => {\n const headers: Record<string, string> = { ...(req.headers ?? {}) };\n const isFormData = typeof FormData !== 'undefined' && req.body instanceof FormData;\n if (!isFormData) {\n headers['Content-Type'] ||= 'application/json';\n headers['Accept'] ||= 'application/json';\n }\n\n const res = await fetch(req.url, {\n method: req.method,\n headers,\n body: isFormData ? (req.body as any) : req.body == null ? undefined : JSON.stringify(req.body),\n });\n\n const text = await res.text();\n if (!res.ok) {\n const snippet = text.slice(0, 400);\n throw new Error(`[${res.status}] ${res.statusText} — ${snippet}`);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n};\n","// routesV3.client.ts\nimport {\n keepPreviousData,\n useInfiniteQuery,\n useMutation,\n useQuery,\n type InfiniteData,\n type QueryKey,\n} from '@tanstack/react-query';\nimport type { ZodType } from 'zod';\nimport {\n HttpMethod,\n buildCacheKey,\n compilePath,\n} from '@emeryld/rrroutes-contract';\nimport type {\n AnyLeaf,\n InferBody,\n InferOutput,\n InferParams,\n InferQuery,\n} from '@emeryld/rrroutes-contract';\nimport { defaultFetcher } from './routesV3.client.fetch';\nimport type {\n ArgsFor,\n ArgsTuple,\n BuiltForLeaf,\n BuiltInfinite,\n BuiltMutation,\n BuiltQuery,\n Cursor,\n DataShape,\n InfiniteBuildOptionsFor,\n MutationBuildOptionsFor,\n QueryBuildOptionsFor,\n RouteClient,\n RouteClientOptions,\n RouteClientDebugEvent,\n RouteClientDebugLogger,\n RouteClientDebugMode,\n RouteClientDebugOptions,\n Updater,\n} from './routesV3.client.types';\n\n// -------------------------------------------------------------------------------------\n// Tiny helpers\n// -------------------------------------------------------------------------------------\n/**\n * Convert an HTTP method to uppercase (as expected by fetch).\n * @param m Lowercase HTTP method.\n * @returns Uppercase method string.\n */\nconst toUpper = (m: HttpMethod): Uppercase<HttpMethod> => m.toUpperCase() as Uppercase<HttpMethod>;\n\n/**\n * Parse the given value with the supplied schema (if present).\n * @param value Raw value to validate.\n * @param schema Optional Zod schema used for validation/coercion.\n * @returns The validated or original value.\n */\nfunction zParse<T>(value: unknown, schema?: ZodType): T {\n return schema ? (schema.parse(value) as T) : (value as T);\n}\n\n/**\n * Serialize a query object into a search string.\n * @param query Query params object (possibly undefined).\n * @returns Query string prefixed with `?`, or empty string.\n */\nfunction toSearchString(query: Record<string, unknown> | undefined) {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v == null) continue;\n if (Array.isArray(v)) {\n v.forEach((x) => {\n if (x == null) return;\n if (typeof x === 'object') {\n params.append(k, JSON.stringify(x));\n } else {\n params.append(k, String(x));\n }\n });\n continue;\n }\n if (typeof v === 'object') {\n params.set(k, JSON.stringify(v));\n continue;\n }\n params.set(k, String(v));\n }\n const s = params.toString();\n return s ? `?${s}` : '';\n}\n\n/**\n * Remove the given key from an object (used to drop cursors from cache keys).\n * @param obj Source object.\n * @param key Property name to omit.\n * @returns Copy of the object without the specified key.\n */\nfunction stripKey<Q extends Record<string, unknown> | undefined>(obj: Q, key: string): Q {\n if (!obj) return obj;\n const { [key]: _omit, ...rest } = obj as any;\n return rest as Q;\n}\n\n/**\n * Default cursor extractor used by infinite queries.\n * @param p Page result returned from the server.\n * @returns Next cursor string, if present.\n */\nconst defaultGetNextCursor = (p: unknown): Cursor =>\n p && typeof p === 'object' && 'nextCursor' in p ? (p as any).nextCursor : undefined;\n\n// Debug logging --------------------------------------------------------------\nconst noopDebugLogger: RouteClientDebugLogger = () => {};\n\nconst defaultDebugLogger: RouteClientDebugLogger = (event: RouteClientDebugEvent) => {\n if (typeof console === 'undefined') return;\n const fn = console.debug ?? console.log;\n fn?.call(console, '[rrroutes-client]', event);\n};\n\ntype DebugEmitter = {\n emit: RouteClientDebugLogger;\n mode: RouteClientDebugMode;\n};\n\nfunction createDebugEmitter(option?: RouteClientDebugOptions): DebugEmitter {\n const disabled: DebugEmitter = { emit: noopDebugLogger, mode: 'minimal' };\n\n if (!option) {\n return disabled;\n }\n if (option === true || option === 'minimal') {\n return { emit: defaultDebugLogger, mode: 'minimal' };\n }\n if (option === 'complete') {\n return { emit: defaultDebugLogger, mode: 'complete' };\n }\n if (typeof option === 'function') {\n return { emit: option, mode: 'minimal' };\n }\n if (option.enabled === false) {\n return { emit: noopDebugLogger, mode: option.mode ?? 'minimal' };\n }\n return {\n emit: option.logger ?? defaultDebugLogger,\n mode: option.mode ?? 'minimal',\n };\n}\n\n// Split the variadic tuple at runtime\n/**\n * Extract the optional argument object from a variadic tuple.\n * @param args Tuple passed to a built endpoint helper.\n * @returns The argument object if present.\n */\nfunction extractArgs<L extends AnyLeaf>(args: ArgsTuple<L>): ArgsFor<L> | undefined {\n // At runtime ArgsTuple<L> is either [] or [obj]; we just pick the first if present.\n return (args as unknown as any[])[0] as any;\n}\n\n/**\n * Normalize params and query values, then construct a request URL for the given leaf.\n * @param leaf Leaf describing the endpoint.\n * @param baseUrl Optional base URL prepended to the path.\n * @param params Route parameters supplied by the caller.\n * @param query Query parameters supplied by the caller.\n * @returns Object containing the composed URL plus normalized params/query payloads.\n */\nfunction buildUrl<L extends AnyLeaf>(\n leaf: L,\n baseUrl: string,\n params: InferParams<L> | undefined,\n query: InferQuery<L> | undefined,\n) {\n const normalizedParams = zParse<InferParams<L>>(params, leaf.cfg.paramsSchema);\n const normalizedQuery = zParse<InferQuery<L>>(query, leaf.cfg.querySchema);\n const path = compilePath<L['path']>(leaf.path, (normalizedParams ?? {}) as any);\n const url = `${baseUrl ?? ''}${path}${toSearchString(normalizedQuery as any)}`;\n return { url, normalizedQuery, normalizedParams };\n}\n\n// -------------------------------------------------------------------------------------\n// Client factory\n// -------------------------------------------------------------------------------------\n/**\n * Construct typed React Query helpers backed by a routes-v3 registry leaf.\n * @param opts Route client configuration (query client, fetcher overrides, etc).\n * @returns Object that can build endpoint hooks/mutations from leaves.\n */\nexport function createRouteClient(opts: RouteClientOptions): RouteClient {\n const queryClient = opts.queryClient;\n const fetcher = opts.fetcher ?? defaultFetcher;\n const baseUrl = opts.baseUrl;\n const cursorParam = opts.cursorParam ?? 'cursor';\n const getNextCursor = opts.getNextCursor ?? defaultGetNextCursor;\n const { emit: emitDebug, mode: debugMode } = createDebugEmitter(opts.debug);\n const isVerboseDebug = debugMode === 'complete';\n const decorateDebugEvent = <T extends RouteClientDebugEvent>(\n event: T,\n details?: Partial<RouteClientDebugEvent>,\n ): RouteClientDebugEvent => {\n if (!isVerboseDebug || !details) return event;\n return { ...event, ...details } as RouteClientDebugEvent;\n };\n\n /**\n * Invalidate a set of queries sharing the given prefix.\n * @param prefix Key parts shared by matching endpoints.\n * @param exact When true, invalidate only exact key matches.\n */\n async function invalidate(prefix: string[], exact = false) {\n const queryKey = prefix as unknown as QueryKey;\n await queryClient.invalidateQueries({ queryKey, exact });\n emitDebug({ type: 'invalidate', key: queryKey, exact });\n }\n\n /**\n * Build the client surface for a single leaf (query/mutation/infinite query).\n * @param leaf Leaf describing the endpoint.\n * @param rqOpts Optional React Query configuration.\n * @returns Helper object exposing key/invalidate/setData/useEndpoint.\n */\n function buildInternal<L extends AnyLeaf>(\n leaf: L,\n rqOpts?: QueryBuildOptionsFor<L> | InfiniteBuildOptionsFor<L> | MutationBuildOptionsFor<L>,\n ): BuiltForLeaf<L> {\n const isGet = leaf.method === 'get';\n const isFeed = !!leaf.cfg.feed;\n const method = toUpper(leaf.method);\n const leafLabel = `${leaf.method.toUpperCase()} ${String(leaf.path)}`;\n emitDebug({ type: 'build', leaf: leafLabel });\n\n // --- key/invalidate/setData shared helpers ---\n const key = (...tuple: ArgsTuple<L>): QueryKey => {\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n const qForKey = isGet && isFeed ? stripKey(query as any, cursorParam) : (query as any);\n return buildCacheKey({ leaf, params: params as any, query: qForKey }) as unknown as QueryKey;\n };\n\n /**\n * Invalidate the React Query cache for this exact leaf invocation.\n * @param tuple Optional params/query tuple.\n */\n const invalidateExact = async (...tuple: ArgsTuple<L>) => {\n const queryKey = key(...tuple);\n await queryClient.invalidateQueries({ queryKey, exact: true });\n emitDebug({ type: 'invalidate', key: queryKey, exact: true });\n };\n\n /**\n * Update the cache entries for this leaf.\n * @param args Tuple whose first entry is the updater and optional params/query follow.\n */\n const setData = (...args: [Updater<DataShape<L>>, ...rest: ArgsTuple<L>]) => {\n const [updater, ...rest] = args;\n const k = key(...(rest as ArgsTuple<L>));\n if (isGet && isFeed) {\n queryClient.setQueryData<InfiniteData<InferOutput<L>> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n } else {\n queryClient.setQueryData<InferOutput<L> | undefined>(k, (prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : (updater as any),\n );\n }\n emitDebug({ type: 'setData', key: k });\n };\n\n // --- Infinite GET ---\n if (isGet && isFeed) {\n const useEndpoint: BuiltInfinite<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useInfiniteGet', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n // Normalize once; we’ll inject the cursor per page below.\n const { normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useInfiniteQuery<\n InferOutput<L>, // TQueryFnData (per page)\n unknown, // TError\n InfiniteData<InferOutput<L>>, // TData (returned by the hook)\n QueryKey,\n Cursor\n >({\n ...(rqOpts as InfiniteBuildOptionsFor<L>),\n queryKey: key(...tuple),\n initialPageParam: undefined,\n getNextPageParam: (lastPage) => getNextCursor(lastPage),\n placeholderData: keepPreviousData,\n queryFn: async ({ pageParam }) => {\n const pageQuery = {\n ...(normalizedQuery as any),\n ...(pageParam ? { [cursorParam]: pageParam } : {}),\n };\n const { url } = buildUrl(leaf, baseUrl, params, pageQuery);\n const startedAt = Date.now();\n const detail = isVerboseDebug ? { params: normalizedParams, query: pageQuery } : undefined;\n emitDebug(\n decorateDebugEvent(\n { type: 'fetch', stage: 'start', method, url, leaf: leafLabel },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug ? { params: normalizedParams, query: pageQuery, output: parsed } : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n // NOTE: TData is InfiniteData<T>, so we don't need a select here.\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n // --- Plain GET ---\n if (isGet) {\n const useEndpoint: BuiltQuery<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useGet', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useQuery<InferOutput<L>, unknown, InferOutput<L>, QueryKey>({\n ...(rqOpts as QueryBuildOptionsFor<L>),\n queryKey: key(...tuple),\n placeholderData: keepPreviousData,\n queryFn: async () => {\n const startedAt = Date.now();\n const detail = isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery }\n : undefined;\n emitDebug(\n decorateDebugEvent(\n { type: 'fetch', stage: 'start', method, url, leaf: leafLabel },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery, output: parsed }\n : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n // --- Mutation (POST/PUT/PATCH/DELETE) ---\n const useEndpoint: BuiltMutation<L>['useEndpoint'] = (...tuple) => {\n emitDebug({ type: 'useMutation', leaf: leafLabel });\n const a = extractArgs<L>(tuple);\n const params = (a as any)?.params as InferParams<L> | undefined;\n const query = (a as any)?.query as InferQuery<L> | undefined;\n\n const { url, normalizedQuery, normalizedParams } = buildUrl(leaf, baseUrl, params, query);\n return useMutation<InferOutput<L>, unknown, InferBody<L>, unknown>({\n ...(rqOpts as MutationBuildOptionsFor<L>),\n mutationKey: key(...tuple),\n mutationFn: async (body: InferBody<L>) => {\n const normalizedBody = zParse<InferBody<L>>(body, leaf.cfg.bodySchema);\n\n // Optional: switch to FormData if your method declares bodyFiles\n const isMultipart = Array.isArray(leaf.cfg.bodyFiles) && leaf.cfg.bodyFiles.length > 0;\n const payload = isMultipart ? toFormData(normalizedBody as any) : normalizedBody;\n\n const startedAt = Date.now();\n const detail = isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery }\n : undefined;\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'start',\n method,\n url,\n leaf: leafLabel,\n body: payload,\n },\n detail,\n ),\n );\n try {\n const out = await fetcher<unknown>({ url, method, body: payload });\n const parsed = zParse<InferOutput<L>>(out, leaf.cfg.outputSchema);\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'success',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n },\n isVerboseDebug\n ? { params: normalizedParams, query: normalizedQuery, output: parsed }\n : undefined,\n ),\n );\n return parsed;\n } catch (error) {\n emitDebug(\n decorateDebugEvent(\n {\n type: 'fetch',\n stage: 'error',\n method,\n url,\n leaf: leafLabel,\n durationMs: Date.now() - startedAt,\n body: payload,\n error,\n },\n detail,\n ),\n );\n throw error;\n }\n },\n }, queryClient);\n };\n\n return {\n key,\n invalidate: invalidateExact,\n setData: setData as any,\n useEndpoint,\n } as BuiltForLeaf<L>;\n }\n\n return {\n queryClient,\n invalidate,\n build: buildInternal as RouteClient['build'],\n };\n}\n\n// -------------------------------------------------------------------------------------\n// Multipart helper\n// -------------------------------------------------------------------------------------\nfunction toFormData(body: Record<string, any>): FormData {\n const fd = new FormData();\n for (const [k, v] of Object.entries(body ?? {})) {\n if (v == null) contin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AAQ,CAAC;AACjE,kBAAM,SAAS,OAAuB,KAAK,KAAK,IAAI,YAAY;AAChE;AAAA,cACE;AAAA,gBACE;AAAA,kBACE,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP;AAAA,kBACA;AAAA,kBACA,MAAM;AAAA,kBACN,YAAY,KAAK,IAAI,IAAI;AAAA,gBAC3B;AAAA,gBACA,iBACI,EAAE,QAAQ,kBAAkB,OAAO,iBAAiB,QAAQ,OAAO,IACnE;AAAA,cACN;AAAA,YACF;AACA,mBAAO;AAAA,UACT,SAAS,OAAO;AACd;AAAA,cACE;AAAA,gBACE;AAAA,kBACE,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP;AAAA,kBACA;AAAA,kBACA,MAAM;AAAA,kBACN,YAAY,KAAK,IAAI,IAAI;AAAA,kBACzB,MAAM;AAAA,kBACN;AAAA,gBACF;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AACA,kBAAM;AAAA,UACR;AAAA,QACF;AAAA,MACF,GAAG,WAAW;AAAA,IAChB;AAEA,WAAO;AAAA,MACL;AAAA,MACA,YAAY;AAAA,MACZ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO;AAAA,EACT;AACF;AAKA,SAAS,WAAW,MAAqC;AACvD,QAAM,KAAK,IAAI,SAAS;AACxB,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CAAC,GAAG;AAC/C,QAAI,KAAK,KAAM;AACf,QAAI,MAAM,QAAQ,CAAC,EAAG,GAAE,QAAQ,CAAC,MAAM,MAAM,GAAG,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,IAAW,CAAC;AAAA,QAC5E,IAAG,OAAO,GAAG,CAAQ;AAAA,EAC5B;AACA,SAAO;AACT;","names":["useEndpoint"]}
|
|
@@ -17,6 +17,8 @@ export type FetchInput = {
|
|
|
17
17
|
};
|
|
18
18
|
/** Default signature for HTTP fetch implementations. */
|
|
19
19
|
export type Fetcher = <T>(req: FetchInput) => Promise<T>;
|
|
20
|
+
/** Debug verbosity levels supported by the client. */
|
|
21
|
+
export type RouteClientDebugMode = 'minimal' | 'complete';
|
|
20
22
|
/** Discrete debug events emitted by the client internals. */
|
|
21
23
|
export type RouteClientDebugEvent = {
|
|
22
24
|
type: 'fetch';
|
|
@@ -26,6 +28,9 @@ export type RouteClientDebugEvent = {
|
|
|
26
28
|
leaf: string;
|
|
27
29
|
durationMs?: number;
|
|
28
30
|
body?: unknown;
|
|
31
|
+
params?: unknown;
|
|
32
|
+
query?: unknown;
|
|
33
|
+
output?: unknown;
|
|
29
34
|
error?: unknown;
|
|
30
35
|
} | {
|
|
31
36
|
type: 'invalidate';
|
|
@@ -34,13 +39,17 @@ export type RouteClientDebugEvent = {
|
|
|
34
39
|
} | {
|
|
35
40
|
type: 'setData';
|
|
36
41
|
key: QueryKey;
|
|
42
|
+
} | {
|
|
43
|
+
type: 'build' | 'useInfiniteGet' | 'useGet' | 'useMutation';
|
|
44
|
+
leaf: string;
|
|
37
45
|
};
|
|
38
46
|
/** Logger signature invoked when debug logging is enabled. */
|
|
39
47
|
export type RouteClientDebugLogger = (event: RouteClientDebugEvent) => void;
|
|
40
48
|
/** Toggle or customize debug logging produced by the client. */
|
|
41
|
-
export type RouteClientDebugOptions = boolean | RouteClientDebugLogger | {
|
|
49
|
+
export type RouteClientDebugOptions = boolean | RouteClientDebugLogger | RouteClientDebugMode | {
|
|
42
50
|
enabled?: boolean;
|
|
43
51
|
logger?: RouteClientDebugLogger;
|
|
52
|
+
mode?: RouteClientDebugMode;
|
|
44
53
|
};
|
|
45
54
|
/** Configuration passed to `createRouteClient`. */
|
|
46
55
|
export type RouteClientOptions = {
|
|
@@ -54,7 +63,7 @@ export type RouteClientOptions = {
|
|
|
54
63
|
cursorParam?: string;
|
|
55
64
|
/** Function that extracts the next cursor from an infinite query page. */
|
|
56
65
|
getNextCursor?: (page: unknown) => Cursor;
|
|
57
|
-
/** Optional debug logger for verbose insights. */
|
|
66
|
+
/** Optional debug logger for verbose insights (supports minimal/complete modes). */
|
|
58
67
|
debug?: RouteClientDebugOptions;
|
|
59
68
|
};
|
|
60
69
|
type OutputOf<L extends AnyLeaf> = InferOutput<L>;
|