@dim24/servin 0.0.0-stage → 0.2.1

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/src/tree.js ADDED
@@ -0,0 +1,703 @@
1
+ import { StaticRouteDescriptor, RedirectDescriptor } from './utils.js';
2
+
3
+ const GUARD_META = Symbol('servin.guard');
4
+ const PARAM_META = Symbol('servin.param');
5
+
6
+ const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
7
+ const META_KEYS = new Set([
8
+ 'expect',
9
+ 'cache',
10
+ 'coalesce',
11
+ 'idempotent',
12
+ 'limit',
13
+ 'webhook',
14
+ 'wsConfig',
15
+ 'priority',
16
+ 'sunset',
17
+ 'rawBody'
18
+ ]);
19
+
20
+ const AsyncGeneratorFunction = (async function* () { }).constructor;
21
+
22
+ const BUILTIN_PARAM_TYPES = {
23
+ int(raw) {
24
+ if (!/^\d+$/.test(raw)) return { ok: false };
25
+ const val = Number(raw);
26
+ if (!Number.isSafeInteger(val)) return { ok: false };
27
+ return { ok: true, value: val };
28
+ },
29
+ number(raw) {
30
+ if (!/^-?\d+(?:\.\d+)?$/.test(raw)) return { ok: false };
31
+ const val = Number(raw);
32
+ if (!Number.isFinite(val)) return { ok: false };
33
+ return { ok: true, value: val };
34
+ },
35
+ float(raw) {
36
+ return BUILTIN_PARAM_TYPES.number(raw);
37
+ },
38
+ bigint(raw) {
39
+ if (!/^-?\d+$/.test(raw)) return { ok: false };
40
+ try {
41
+ return { ok: true, value: BigInt(raw) };
42
+ } catch {
43
+ return { ok: false };
44
+ }
45
+ },
46
+ uuid(raw) {
47
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(raw)) {
48
+ return { ok: false };
49
+ }
50
+ return { ok: true, value: raw.toLowerCase() };
51
+ },
52
+ alpha(raw) {
53
+ if (!/^[a-zA-Z]+$/.test(raw)) return { ok: false };
54
+ return { ok: true, value: raw };
55
+ },
56
+ alnum(raw) {
57
+ if (!/^[a-zA-Z0-9]+$/.test(raw)) return { ok: false };
58
+ return { ok: true, value: raw };
59
+ },
60
+ slug(raw) {
61
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(raw)) return { ok: false };
62
+ return { ok: true, value: raw };
63
+ },
64
+ bool(raw) {
65
+ const lower = raw.toLowerCase();
66
+ if (lower === 'true' || lower === '1') return { ok: true, value: true };
67
+ if (lower === 'false' || lower === '0') return { ok: true, value: false };
68
+ return { ok: false };
69
+ },
70
+ boolean(raw) {
71
+ return BUILTIN_PARAM_TYPES.bool(raw);
72
+ },
73
+ string(raw) {
74
+ return { ok: true, value: raw };
75
+ }
76
+ };
77
+
78
+ function resolveParamParser(rule, customTypes = {}, rawSegment = '') {
79
+ if (rule === Number) return BUILTIN_PARAM_TYPES.number;
80
+ if (rule === Boolean) return BUILTIN_PARAM_TYPES.bool;
81
+ if (rule === BigInt) return BUILTIN_PARAM_TYPES.bigint;
82
+ if (rule === String) return BUILTIN_PARAM_TYPES.string;
83
+
84
+ if (rule instanceof RegExp) {
85
+ const rx = new RegExp(rule.source, rule.flags.replace(/[gy]/g, ''));
86
+ return (raw) => (rx.test(raw) ? { ok: true, value: raw } : { ok: false });
87
+ }
88
+
89
+ if (typeof rule === 'function') {
90
+ return (raw) => {
91
+ try {
92
+ const parsed = rule(raw);
93
+ if (parsed === undefined || parsed === null || parsed === false) {
94
+ return { ok: false };
95
+ }
96
+ return { ok: true, value: parsed };
97
+ } catch {
98
+ return { ok: false };
99
+ }
100
+ };
101
+ }
102
+
103
+ if (typeof rule === 'string') {
104
+ if (customTypes && Object.prototype.hasOwnProperty.call(customTypes, rule)) {
105
+ return resolveParamParser(customTypes[rule], {}, rawSegment);
106
+ }
107
+ if (Object.prototype.hasOwnProperty.call(BUILTIN_PARAM_TYPES, rule)) {
108
+ return BUILTIN_PARAM_TYPES[rule];
109
+ }
110
+ }
111
+
112
+ throw new Error(`[servin] Invalid parameter rule "${String(rule)}" on segment "${rawSegment}"`);
113
+ }
114
+
115
+ function attachMeta(branch, { addGuard, setParam }) {
116
+ const existingGuards = branch?.[GUARD_META] || [];
117
+ const existingParam = branch?.[PARAM_META] || null;
118
+ const nextGuards = addGuard ? [addGuard, ...existingGuards] : existingGuards;
119
+ const nextParam = setParam !== undefined ? setParam : existingParam;
120
+
121
+ let target;
122
+ if (typeof branch === 'function') {
123
+ if (branch instanceof AsyncGeneratorFunction) {
124
+ target = async function* (...args) {
125
+ return yield* branch(...args);
126
+ };
127
+ } else {
128
+ target = function (...args) {
129
+ return branch.apply(this, args);
130
+ };
131
+ }
132
+ } else if (branch instanceof StaticRouteDescriptor || branch instanceof RedirectDescriptor) {
133
+ target = Object.assign(Object.create(Object.getPrototypeOf(branch)), branch);
134
+ } else if (branch && typeof branch === 'object') {
135
+ target = { ...branch };
136
+ } else {
137
+ throw new TypeError('Branch must be a route object, descriptor, or handler function');
138
+ }
139
+
140
+ if (nextGuards.length > 0) {
141
+ Object.defineProperty(target, GUARD_META, {
142
+ value: nextGuards,
143
+ enumerable: false,
144
+ configurable: true
145
+ });
146
+ }
147
+ if (nextParam) {
148
+ Object.defineProperty(target, PARAM_META, {
149
+ value: nextParam,
150
+ enumerable: false,
151
+ configurable: true
152
+ });
153
+ }
154
+ return target;
155
+ }
156
+
157
+ export function guard(policyFn, branch) {
158
+ if (typeof policyFn !== 'function') {
159
+ throw new TypeError('guard(policyFn, branch) requires a policy function');
160
+ }
161
+ return attachMeta(branch, { addGuard: policyFn });
162
+ }
163
+
164
+ export function param(rule, branch) {
165
+ if (rule === undefined || rule === null) {
166
+ throw new TypeError('param(rule, branch) requires a type name, constructor, RegExp, or validator function');
167
+ }
168
+ return attachMeta(branch, { setParam: rule });
169
+ }
170
+
171
+ export function serveStatic(targetPath, options = {}) {
172
+ return new StaticRouteDescriptor(targetPath, options);
173
+ }
174
+
175
+ export function redirect(target, status = 301) {
176
+ return new RedirectDescriptor(target, status);
177
+ }
178
+
179
+ function parseVerbKey(key) {
180
+ if (key === 'ws') return ['WS'];
181
+ const parts = key.split('|').map((s) => s.trim().toUpperCase());
182
+ if (parts.length > 0 && parts.every((p) => HTTP_VERBS.has(p))) {
183
+ return parts;
184
+ }
185
+ return null;
186
+ }
187
+
188
+ function classifySegment(seg, customTypes = {}, paramRule = null) {
189
+ if (seg === '$path') {
190
+ return { type: 'wild', priority: 3, param: 'path', parse: null, raw: seg };
191
+ }
192
+ if (seg.startsWith('$') && seg.length > 1) {
193
+ const paramName = seg.slice(1);
194
+ if (paramRule !== null && paramRule !== undefined) {
195
+ const parse = resolveParamParser(paramRule, customTypes, seg);
196
+ return { type: 'param', priority: 1, param: paramName, parse, raw: seg };
197
+ }
198
+ return { type: 'param', priority: 2, param: paramName, parse: null, raw: seg };
199
+ }
200
+ if (paramRule !== null && paramRule !== undefined) {
201
+ throw new Error(`[servin] param() can only be applied to dynamic "$" segments, got "${seg}"`);
202
+ }
203
+ return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
204
+ }
205
+
206
+ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null) {
207
+ const routes = [];
208
+ let nodeCounter = 0;
209
+
210
+ function registerStaticDescriptor(descriptor, baseSegments, dotPath, inheritedGuards, inheritedMeta, isRootFallback = false) {
211
+ const wildSeg = {
212
+ type: 'wild',
213
+ priority: isRootFallback ? 4 : 3,
214
+ param: 'subpath',
215
+ optionalWild: true,
216
+ parse: null,
217
+ raw: '$subpath'
218
+ };
219
+ const fullSegments = [...baseSegments, wildSeg];
220
+ const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
221
+ const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
222
+
223
+ routes.push({
224
+ nodeId: `static_${++nodeCounter}`,
225
+ dotPath: dotPath.join('.'),
226
+ segments: fullSegments,
227
+ paramNames,
228
+ verbs: ['GET', 'HEAD'],
229
+ staticDescriptor: descriptor,
230
+ handler: null,
231
+ isAsyncGen: false,
232
+ guards: descGuards,
233
+ meta: inheritedMeta,
234
+ nodeCache: null,
235
+ ancestorCaches: [],
236
+ nodeInFlight: null,
237
+ nodeIdempotency: null
238
+ });
239
+ }
240
+
241
+ function registerRedirectDescriptor(descriptor, fullSegments, dotPath, inheritedGuards, inheritedMeta, verbs = ['GET', 'HEAD']) {
242
+ const paramNames = fullSegments.filter((s) => s.type !== 'static').map((s) => s.param);
243
+ const descGuards = [...inheritedGuards, ...(descriptor[GUARD_META] || [])];
244
+
245
+ routes.push({
246
+ nodeId: `redirect_${++nodeCounter}`,
247
+ dotPath: dotPath.join('.'),
248
+ segments: fullSegments,
249
+ paramNames,
250
+ verbs,
251
+ redirectDescriptor: descriptor,
252
+ handler: null,
253
+ isAsyncGen: false,
254
+ guards: descGuards,
255
+ meta: inheritedMeta,
256
+ nodeCache: null,
257
+ ancestorCaches: [],
258
+ nodeInFlight: null,
259
+ nodeIdempotency: null
260
+ });
261
+ }
262
+
263
+ function walk(node, segments, dotPath, inheritedGuards, inheritedMeta, ancestorCaches) {
264
+ if (!node || typeof node !== 'object') return;
265
+
266
+ const nodeId = `node_${++nodeCounter}`;
267
+ const guards = [...inheritedGuards, ...(node[GUARD_META] || [])];
268
+ const meta = { ...inheritedMeta };
269
+
270
+ for (const mk of META_KEYS) {
271
+ if (mk in node) meta[mk] = node[mk];
272
+ }
273
+
274
+ const nodeCache = node.cache ? new Map() : null;
275
+ const nextAncestorCaches = nodeCache ? [...ancestorCaches, nodeCache] : ancestorCaches;
276
+ const nodeInFlight = meta.coalesce ? new Map() : null;
277
+ const nodeIdempotency = meta.idempotent ? new Map() : null;
278
+
279
+ const hasExplicitDynamicChild = Object.keys(node).some(
280
+ (k) => !META_KEYS.has(k) && k.startsWith('$')
281
+ );
282
+
283
+ for (const [key, value] of Object.entries(node)) {
284
+ if (META_KEYS.has(key)) continue;
285
+
286
+ const verbs = parseVerbKey(key);
287
+ if (verbs && value instanceof RedirectDescriptor) {
288
+ registerRedirectDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
289
+ continue;
290
+ }
291
+
292
+ if (verbs && typeof value === 'function') {
293
+ const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
294
+ routes.push({
295
+ nodeId,
296
+ dotPath: [...dotPath, key].join('.'),
297
+ segments,
298
+ paramNames,
299
+ verbs,
300
+ handler: value,
301
+ isAsyncGen: value instanceof AsyncGeneratorFunction,
302
+ guards,
303
+ meta,
304
+ nodeCache,
305
+ ancestorCaches,
306
+ nodeInFlight,
307
+ nodeIdempotency
308
+ });
309
+
310
+ if (!hasExplicitDynamicChild) {
311
+ const directChildSeg = {
312
+ type: 'wild',
313
+ priority: 5,
314
+ param: 'id',
315
+ optionalWild: true,
316
+ directNodeParam: true,
317
+ parse: null,
318
+ raw: '$direct'
319
+ };
320
+ routes.push({
321
+ nodeId: `${nodeId}_direct_${key}`,
322
+ dotPath: [...dotPath, key].join('.'),
323
+ segments: [...segments, directChildSeg],
324
+ paramNames: [],
325
+ verbs,
326
+ handler: value,
327
+ isAsyncGen: value instanceof AsyncGeneratorFunction,
328
+ guards,
329
+ meta,
330
+ nodeCache,
331
+ ancestorCaches,
332
+ nodeInFlight,
333
+ nodeIdempotency
334
+ });
335
+ }
336
+ continue;
337
+ }
338
+
339
+ const paramRule = value?.[PARAM_META] ?? null;
340
+
341
+ if (value instanceof StaticRouteDescriptor) {
342
+ const seg = classifySegment(key, customTypes, paramRule);
343
+ registerStaticDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
344
+ continue;
345
+ }
346
+
347
+ if (value instanceof RedirectDescriptor) {
348
+ const seg = classifySegment(key, customTypes, paramRule);
349
+ registerRedirectDescriptor(value, [...segments, seg], [...dotPath, key], guards, meta);
350
+ continue;
351
+ }
352
+
353
+ if (typeof value === 'function') {
354
+ const seg = classifySegment(key, customTypes, paramRule);
355
+ const childSegments = [...segments, seg];
356
+ const paramNames = childSegments.filter((s) => s.type !== 'static').map((s) => s.param);
357
+ const isAsyncGen = value instanceof AsyncGeneratorFunction;
358
+ const fnGuards = [...guards, ...(value[GUARD_META] || [])];
359
+ routes.push({
360
+ nodeId: `${nodeId}_${key}`,
361
+ dotPath: [...dotPath, key].join('.'),
362
+ segments: childSegments,
363
+ paramNames,
364
+ verbs: [isAsyncGen ? 'GET' : 'POST'],
365
+ handler: value,
366
+ isAsyncGen,
367
+ guards: fnGuards,
368
+ meta,
369
+ nodeCache: null,
370
+ ancestorCaches: nextAncestorCaches,
371
+ nodeInFlight: meta.coalesce ? new Map() : null,
372
+ nodeIdempotency: meta.idempotent ? new Map() : null
373
+ });
374
+ continue;
375
+ }
376
+
377
+ if (value && typeof value === 'object') {
378
+ const seg = classifySegment(key, customTypes, paramRule);
379
+ walk(value, [...segments, seg], [...dotPath, key], guards, meta, nextAncestorCaches);
380
+ }
381
+ }
382
+ }
383
+
384
+ walk(apiRoot, [], [], [], {}, []);
385
+
386
+ if (staticConfig) {
387
+ if (typeof staticConfig === 'string' || staticConfig instanceof StaticRouteDescriptor) {
388
+ const desc = staticConfig instanceof StaticRouteDescriptor
389
+ ? staticConfig
390
+ : new StaticRouteDescriptor(staticConfig);
391
+ registerStaticDescriptor(desc, [], ['static'], [], {}, true);
392
+ } else if (typeof staticConfig === 'object') {
393
+ for (const [mountPrefix, target] of Object.entries(staticConfig)) {
394
+ const desc = target instanceof StaticRouteDescriptor
395
+ ? target
396
+ : new StaticRouteDescriptor(target);
397
+ const cleanPrefix = mountPrefix.replace(/^\/+|\/+$/g, '');
398
+ const prefixSegs = cleanPrefix
399
+ ? cleanPrefix.split('/').map((s) => classifySegment(s, customTypes))
400
+ : [];
401
+ registerStaticDescriptor(desc, prefixSegs, ['static', ...prefixSegs.map((s) => s.raw)], [], {}, prefixSegs.length === 0);
402
+ }
403
+ }
404
+ }
405
+
406
+ routes.sort((a, b) => {
407
+ const minLen = Math.min(a.segments.length, b.segments.length);
408
+ for (let i = 0; i < minLen; i++) {
409
+ if (a.segments[i].priority !== b.segments[i].priority) {
410
+ return a.segments[i].priority - b.segments[i].priority;
411
+ }
412
+ }
413
+ return a.segments.length - b.segments.length;
414
+ });
415
+
416
+ return routes;
417
+ }
418
+
419
+ export function matchDomainRoute(routes, method, pathname) {
420
+ const clean = pathname.replace(/^\/+|\/+$/g, '');
421
+ const parts = clean ? clean.split('/') : [];
422
+ const allowedVerbs = new Set();
423
+
424
+ for (const route of routes) {
425
+ const params = {};
426
+ let matched = true;
427
+
428
+ for (let i = 0; i < route.segments.length; i++) {
429
+ const seg = route.segments[i];
430
+ if (seg.type === 'wild') {
431
+ if (i >= parts.length && !seg.optionalWild) {
432
+ matched = false;
433
+ break;
434
+ }
435
+ try {
436
+ const decodedParts = parts.slice(i).map(decodeURIComponent);
437
+ if (seg.directNodeParam) {
438
+ if (decodedParts.length === 1) {
439
+ params.id = decodedParts[0];
440
+ } else if (decodedParts.length > 1) {
441
+ params.rest = decodedParts;
442
+ params.id = decodedParts[0];
443
+ }
444
+ } else {
445
+ params[seg.param] = decodedParts.join('/');
446
+ }
447
+ } catch {
448
+ matched = false;
449
+ }
450
+ break;
451
+ }
452
+ if (i >= parts.length) {
453
+ matched = false;
454
+ break;
455
+ }
456
+ if (seg.type === 'param') {
457
+ let decoded;
458
+ try {
459
+ decoded = decodeURIComponent(parts[i]);
460
+ } catch {
461
+ matched = false;
462
+ break;
463
+ }
464
+ if (seg.parse) {
465
+ const res = seg.parse(decoded);
466
+ if (!res.ok) {
467
+ matched = false;
468
+ break;
469
+ }
470
+ params[seg.param] = res.value;
471
+ } else {
472
+ params[seg.param] = decoded;
473
+ }
474
+ } else if (seg.value !== parts[i]) {
475
+ matched = false;
476
+ break;
477
+ }
478
+ }
479
+
480
+ const lastSeg = route.segments[route.segments.length - 1];
481
+ if (matched && lastSeg?.type !== 'wild' && parts.length !== route.segments.length) {
482
+ matched = false;
483
+ }
484
+
485
+ if (matched) {
486
+ for (const v of route.verbs) {
487
+ if (v !== 'WS') allowedVerbs.add(v);
488
+ }
489
+ if (route.verbs.includes(method)) {
490
+ return { status: 200, route, params };
491
+ }
492
+ }
493
+ }
494
+
495
+ if (allowedVerbs.size > 0) {
496
+ return { status: 405, allow: [...allowedVerbs].join(', ') };
497
+ }
498
+ return { status: 404 };
499
+ }
500
+
501
+ export function generateVirtualClientModule(routes) {
502
+ const manifest = routes
503
+ .filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
504
+ .map((r) => ({
505
+ dotPath: r.dotPath,
506
+ verbs: r.verbs,
507
+ isAsyncGen: r.isAsyncGen
508
+ }));
509
+
510
+ return `// Auto-generated Zero-Build Virtual ESM Client by servin
511
+ const MANIFEST = ${JSON.stringify(manifest, null, 2)};
512
+ const ORIGIN = new URL(import.meta.url).origin;
513
+ const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
514
+
515
+ function parseMethod(key) {
516
+ if (key === 'ws') return 'WS';
517
+ const upper = key.split('|')[0].toUpperCase();
518
+ return HTTP_VERBS.has(upper) ? upper : null;
519
+ }
520
+
521
+ function isOptionsBag(arg) {
522
+ return Boolean(
523
+ arg &&
524
+ typeof arg === 'object' &&
525
+ !Array.isArray(arg) &&
526
+ !(arg instanceof FormData) &&
527
+ !(arg instanceof URLSearchParams) &&
528
+ !(arg instanceof Blob) &&
529
+ Object.prototype.hasOwnProperty.call(arg, 'headers')
530
+ );
531
+ }
532
+
533
+ function createNode(chain) {
534
+ return new Proxy(function () {}, {
535
+ get(_, prop) {
536
+ if (typeof prop === 'symbol') return undefined;
537
+ return createNode([...chain, prop]);
538
+ },
539
+ apply(_, __, args) {
540
+ const argQueue = [...args];
541
+ const dotKey = chain.join('.');
542
+ const entry = MANIFEST.find((m) => m.dotPath === dotKey);
543
+ const lastKey = chain[chain.length - 1];
544
+ let method = parseMethod(lastKey);
545
+ const pathSegments = method ? chain.slice(0, -1) : [...chain];
546
+
547
+ if (!method) {
548
+ method = entry?.verbs?.[0] || 'POST';
549
+ }
550
+
551
+ const resolvedParts = [];
552
+ for (const seg of pathSegments) {
553
+ if (seg.startsWith('$')) {
554
+ const val = argQueue.shift();
555
+ resolvedParts.push(encodeURIComponent(String(val ?? '')));
556
+ } else {
557
+ resolvedParts.push(encodeURIComponent(seg));
558
+ }
559
+ }
560
+
561
+ const pathname = '/' + resolvedParts.join('/');
562
+
563
+ if (method === 'WS') {
564
+ const wsOrigin = ORIGIN.replace(/^http/, 'ws');
565
+ const ws = new WebSocket(wsOrigin + pathname);
566
+ const queue = [];
567
+ let notify = null;
568
+ let closed = false;
569
+
570
+ ws.onmessage = (ev) => {
571
+ let data = ev.data;
572
+ if (typeof data === 'string') {
573
+ try { data = JSON.parse(data); } catch {}
574
+ }
575
+ queue.push(data);
576
+ if (notify) { notify(); notify = null; }
577
+ };
578
+ ws.onclose = () => {
579
+ closed = true;
580
+ if (notify) { notify(); notify = null; }
581
+ };
582
+
583
+ return {
584
+ send(data) {
585
+ const payload = (data instanceof Uint8Array || typeof data === 'string')
586
+ ? data
587
+ : JSON.stringify(data);
588
+ if (ws.readyState === WebSocket.OPEN) ws.send(payload);
589
+ else ws.addEventListener('open', () => ws.send(payload), { once: true });
590
+ },
591
+ close(code, reason) {
592
+ ws.close(code, reason);
593
+ },
594
+ async *[Symbol.asyncIterator]() {
595
+ while (!closed || queue.length > 0) {
596
+ if (queue.length > 0) {
597
+ yield queue.shift();
598
+ } else {
599
+ await new Promise((r) => { notify = r; });
600
+ }
601
+ }
602
+ }
603
+ };
604
+ }
605
+
606
+ let customHeaders = {};
607
+ let payload;
608
+ let queryObj;
609
+
610
+ const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
611
+
612
+ if (hasBody) {
613
+ const first = argQueue.shift();
614
+ if (isOptionsBag(first)) {
615
+ customHeaders = { ...first.headers };
616
+ payload = first.body !== undefined ? first.body : argQueue.shift();
617
+ queryObj = first.query !== undefined ? first.query : argQueue.shift();
618
+ } else {
619
+ payload = first;
620
+ const second = argQueue.shift();
621
+ if (isOptionsBag(second)) {
622
+ customHeaders = { ...second.headers };
623
+ queryObj = second.query !== undefined ? second.query : argQueue.shift();
624
+ } else {
625
+ queryObj = second;
626
+ }
627
+ }
628
+ } else {
629
+ const first = argQueue.shift();
630
+ if (isOptionsBag(first)) {
631
+ customHeaders = { ...first.headers };
632
+ queryObj = first.query !== undefined ? first.query : argQueue.shift();
633
+ } else {
634
+ queryObj = first;
635
+ const second = argQueue.shift();
636
+ if (isOptionsBag(second)) {
637
+ customHeaders = { ...second.headers };
638
+ }
639
+ }
640
+ }
641
+
642
+ const url = new URL(ORIGIN + pathname);
643
+ if (queryObj && typeof queryObj === 'object') {
644
+ for (const [k, v] of Object.entries(queryObj)) {
645
+ if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
646
+ }
647
+ }
648
+
649
+ if (entry?.isAsyncGen) {
650
+ return (async function* () {
651
+ const res = await fetch(url, {
652
+ method,
653
+ headers: { Accept: 'text/event-stream', ...customHeaders },
654
+ credentials: 'include'
655
+ });
656
+ if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
657
+ const reader = res.body.getReader();
658
+ const decoder = new TextDecoder();
659
+ let buffer = '';
660
+ while (true) {
661
+ const { done, value } = await reader.read();
662
+ if (done) break;
663
+ buffer += decoder.decode(value, { stream: true });
664
+ const blocks = buffer.split('\\n\\n');
665
+ buffer = blocks.pop() || '';
666
+ for (const block of blocks) {
667
+ const line = block.split('\\n').find((l) => l.startsWith('data:'));
668
+ if (line) yield JSON.parse(line.slice(5).trim());
669
+ }
670
+ }
671
+ })();
672
+ }
673
+
674
+ return (async () => {
675
+ const headers = { ...customHeaders };
676
+ let body;
677
+ if (hasBody && payload !== undefined) {
678
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) {
679
+ headers['Content-Type'] = 'application/json';
680
+ }
681
+ body = typeof payload === 'string' ? payload : JSON.stringify(payload);
682
+ }
683
+ const res = await fetch(url, { method, headers, body, credentials: 'include' });
684
+ if (res.status === 204) return null;
685
+ const text = await res.text();
686
+ let data = text;
687
+ try { data = JSON.parse(text); } catch {}
688
+ if (!res.ok) {
689
+ throw Object.assign(new Error(data?.error || text || 'Request failed'), {
690
+ status: res.status,
691
+ data
692
+ });
693
+ }
694
+ return data;
695
+ })();
696
+ }
697
+ });
698
+ }
699
+
700
+ export const api = createNode([]);
701
+ export default api;
702
+ `;
703
+ }