@djangocfg/api 2.1.332 → 2.1.334

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/clients.mjs CHANGED
@@ -2,805 +2,6 @@
2
2
  var __defProp = Object.defineProperty;
3
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
4
 
5
- // src/_api/generated/core/bodySerializer.gen.ts
6
- var jsonBodySerializer = {
7
- bodySerializer: /* @__PURE__ */ __name((body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value), "bodySerializer")
8
- };
9
-
10
- // src/_api/generated/core/params.gen.ts
11
- var extraPrefixesMap = {
12
- $body_: "body",
13
- $headers_: "headers",
14
- $path_: "path",
15
- $query_: "query"
16
- };
17
- var extraPrefixes = Object.entries(extraPrefixesMap);
18
-
19
- // src/_api/generated/core/serverSentEvents.gen.ts
20
- function createSseClient({
21
- onRequest,
22
- onSseError,
23
- onSseEvent,
24
- responseTransformer,
25
- responseValidator,
26
- sseDefaultRetryDelay,
27
- sseMaxRetryAttempts,
28
- sseMaxRetryDelay,
29
- sseSleepFn,
30
- url,
31
- ...options
32
- }) {
33
- let lastEventId;
34
- const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
35
- const createStream = /* @__PURE__ */ __name(async function* () {
36
- let retryDelay = sseDefaultRetryDelay ?? 3e3;
37
- let attempt = 0;
38
- const signal = options.signal ?? new AbortController().signal;
39
- while (true) {
40
- if (signal.aborted) break;
41
- attempt++;
42
- const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
43
- if (lastEventId !== void 0) {
44
- headers.set("Last-Event-ID", lastEventId);
45
- }
46
- try {
47
- const requestInit = {
48
- redirect: "follow",
49
- ...options,
50
- body: options.serializedBody,
51
- headers,
52
- signal
53
- };
54
- let request = new Request(url, requestInit);
55
- if (onRequest) {
56
- request = await onRequest(url, requestInit);
57
- }
58
- const _fetch = options.fetch ?? globalThis.fetch;
59
- const response = await _fetch(request);
60
- if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
61
- if (!response.body) throw new Error("No body in SSE response");
62
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
63
- let buffer = "";
64
- const abortHandler = /* @__PURE__ */ __name(() => {
65
- try {
66
- reader.cancel();
67
- } catch {
68
- }
69
- }, "abortHandler");
70
- signal.addEventListener("abort", abortHandler);
71
- try {
72
- while (true) {
73
- const { done, value } = await reader.read();
74
- if (done) break;
75
- buffer += value;
76
- buffer = buffer.replace(/\r\n?/g, "\n");
77
- const chunks = buffer.split("\n\n");
78
- buffer = chunks.pop() ?? "";
79
- for (const chunk of chunks) {
80
- const lines = chunk.split("\n");
81
- const dataLines = [];
82
- let eventName;
83
- for (const line of lines) {
84
- if (line.startsWith("data:")) {
85
- dataLines.push(line.replace(/^data:\s*/, ""));
86
- } else if (line.startsWith("event:")) {
87
- eventName = line.replace(/^event:\s*/, "");
88
- } else if (line.startsWith("id:")) {
89
- lastEventId = line.replace(/^id:\s*/, "");
90
- } else if (line.startsWith("retry:")) {
91
- const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
92
- if (!Number.isNaN(parsed)) {
93
- retryDelay = parsed;
94
- }
95
- }
96
- }
97
- let data;
98
- let parsedJson = false;
99
- if (dataLines.length) {
100
- const rawData = dataLines.join("\n");
101
- try {
102
- data = JSON.parse(rawData);
103
- parsedJson = true;
104
- } catch {
105
- data = rawData;
106
- }
107
- }
108
- if (parsedJson) {
109
- if (responseValidator) {
110
- await responseValidator(data);
111
- }
112
- if (responseTransformer) {
113
- data = await responseTransformer(data);
114
- }
115
- }
116
- onSseEvent?.({
117
- data,
118
- event: eventName,
119
- id: lastEventId,
120
- retry: retryDelay
121
- });
122
- if (dataLines.length) {
123
- yield data;
124
- }
125
- }
126
- }
127
- } finally {
128
- signal.removeEventListener("abort", abortHandler);
129
- reader.releaseLock();
130
- }
131
- break;
132
- } catch (error) {
133
- onSseError?.(error);
134
- if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
135
- break;
136
- }
137
- const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
138
- await sleep(backoff);
139
- }
140
- }
141
- }, "createStream");
142
- const stream = createStream();
143
- return { stream };
144
- }
145
- __name(createSseClient, "createSseClient");
146
-
147
- // src/_api/generated/core/pathSerializer.gen.ts
148
- var separatorArrayExplode = /* @__PURE__ */ __name((style) => {
149
- switch (style) {
150
- case "label":
151
- return ".";
152
- case "matrix":
153
- return ";";
154
- case "simple":
155
- return ",";
156
- default:
157
- return "&";
158
- }
159
- }, "separatorArrayExplode");
160
- var separatorArrayNoExplode = /* @__PURE__ */ __name((style) => {
161
- switch (style) {
162
- case "form":
163
- return ",";
164
- case "pipeDelimited":
165
- return "|";
166
- case "spaceDelimited":
167
- return "%20";
168
- default:
169
- return ",";
170
- }
171
- }, "separatorArrayNoExplode");
172
- var separatorObjectExplode = /* @__PURE__ */ __name((style) => {
173
- switch (style) {
174
- case "label":
175
- return ".";
176
- case "matrix":
177
- return ";";
178
- case "simple":
179
- return ",";
180
- default:
181
- return "&";
182
- }
183
- }, "separatorObjectExplode");
184
- var serializeArrayParam = /* @__PURE__ */ __name(({
185
- allowReserved,
186
- explode,
187
- name,
188
- style,
189
- value
190
- }) => {
191
- if (!explode) {
192
- const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
193
- switch (style) {
194
- case "label":
195
- return `.${joinedValues2}`;
196
- case "matrix":
197
- return `;${name}=${joinedValues2}`;
198
- case "simple":
199
- return joinedValues2;
200
- default:
201
- return `${name}=${joinedValues2}`;
202
- }
203
- }
204
- const separator = separatorArrayExplode(style);
205
- const joinedValues = value.map((v) => {
206
- if (style === "label" || style === "simple") {
207
- return allowReserved ? v : encodeURIComponent(v);
208
- }
209
- return serializePrimitiveParam({
210
- allowReserved,
211
- name,
212
- value: v
213
- });
214
- }).join(separator);
215
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
216
- }, "serializeArrayParam");
217
- var serializePrimitiveParam = /* @__PURE__ */ __name(({
218
- allowReserved,
219
- name,
220
- value
221
- }) => {
222
- if (value === void 0 || value === null) {
223
- return "";
224
- }
225
- if (typeof value === "object") {
226
- throw new Error(
227
- "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
228
- );
229
- }
230
- return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
231
- }, "serializePrimitiveParam");
232
- var serializeObjectParam = /* @__PURE__ */ __name(({
233
- allowReserved,
234
- explode,
235
- name,
236
- style,
237
- value,
238
- valueOnly
239
- }) => {
240
- if (value instanceof Date) {
241
- return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
242
- }
243
- if (style !== "deepObject" && !explode) {
244
- let values = [];
245
- Object.entries(value).forEach(([key, v]) => {
246
- values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
247
- });
248
- const joinedValues2 = values.join(",");
249
- switch (style) {
250
- case "form":
251
- return `${name}=${joinedValues2}`;
252
- case "label":
253
- return `.${joinedValues2}`;
254
- case "matrix":
255
- return `;${name}=${joinedValues2}`;
256
- default:
257
- return joinedValues2;
258
- }
259
- }
260
- const separator = separatorObjectExplode(style);
261
- const joinedValues = Object.entries(value).map(
262
- ([key, v]) => serializePrimitiveParam({
263
- allowReserved,
264
- name: style === "deepObject" ? `${name}[${key}]` : key,
265
- value: v
266
- })
267
- ).join(separator);
268
- return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
269
- }, "serializeObjectParam");
270
-
271
- // src/_api/generated/core/utils.gen.ts
272
- var PATH_PARAM_RE = /\{[^{}]+\}/g;
273
- var defaultPathSerializer = /* @__PURE__ */ __name(({ path, url: _url }) => {
274
- let url = _url;
275
- const matches = _url.match(PATH_PARAM_RE);
276
- if (matches) {
277
- for (const match of matches) {
278
- let explode = false;
279
- let name = match.substring(1, match.length - 1);
280
- let style = "simple";
281
- if (name.endsWith("*")) {
282
- explode = true;
283
- name = name.substring(0, name.length - 1);
284
- }
285
- if (name.startsWith(".")) {
286
- name = name.substring(1);
287
- style = "label";
288
- } else if (name.startsWith(";")) {
289
- name = name.substring(1);
290
- style = "matrix";
291
- }
292
- const value = path[name];
293
- if (value === void 0 || value === null) {
294
- continue;
295
- }
296
- if (Array.isArray(value)) {
297
- url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
298
- continue;
299
- }
300
- if (typeof value === "object") {
301
- url = url.replace(
302
- match,
303
- serializeObjectParam({
304
- explode,
305
- name,
306
- style,
307
- value,
308
- valueOnly: true
309
- })
310
- );
311
- continue;
312
- }
313
- if (style === "matrix") {
314
- url = url.replace(
315
- match,
316
- `;${serializePrimitiveParam({
317
- name,
318
- value
319
- })}`
320
- );
321
- continue;
322
- }
323
- const replaceValue = encodeURIComponent(
324
- style === "label" ? `.${value}` : value
325
- );
326
- url = url.replace(match, replaceValue);
327
- }
328
- }
329
- return url;
330
- }, "defaultPathSerializer");
331
- var getUrl = /* @__PURE__ */ __name(({
332
- baseUrl,
333
- path,
334
- query,
335
- querySerializer,
336
- url: _url
337
- }) => {
338
- const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
339
- let url = (baseUrl ?? "") + pathUrl;
340
- if (path) {
341
- url = defaultPathSerializer({ path, url });
342
- }
343
- let search = query ? querySerializer(query) : "";
344
- if (search.startsWith("?")) {
345
- search = search.substring(1);
346
- }
347
- if (search) {
348
- url += `?${search}`;
349
- }
350
- return url;
351
- }, "getUrl");
352
- function getValidRequestBody(options) {
353
- const hasBody = options.body !== void 0;
354
- const isSerializedBody = hasBody && options.bodySerializer;
355
- if (isSerializedBody) {
356
- if ("serializedBody" in options) {
357
- const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
358
- return hasSerializedBody ? options.serializedBody : null;
359
- }
360
- return options.body !== "" ? options.body : null;
361
- }
362
- if (hasBody) {
363
- return options.body;
364
- }
365
- return void 0;
366
- }
367
- __name(getValidRequestBody, "getValidRequestBody");
368
-
369
- // src/_api/generated/core/auth.gen.ts
370
- var getAuthToken = /* @__PURE__ */ __name(async (auth2, callback) => {
371
- const token = typeof callback === "function" ? await callback(auth2) : callback;
372
- if (!token) {
373
- return;
374
- }
375
- if (auth2.scheme === "bearer") {
376
- return `Bearer ${token}`;
377
- }
378
- if (auth2.scheme === "basic") {
379
- return `Basic ${btoa(token)}`;
380
- }
381
- return token;
382
- }, "getAuthToken");
383
-
384
- // src/_api/generated/client/utils.gen.ts
385
- var createQuerySerializer = /* @__PURE__ */ __name(({
386
- parameters = {},
387
- ...args
388
- } = {}) => {
389
- const querySerializer = /* @__PURE__ */ __name((queryParams) => {
390
- const search = [];
391
- if (queryParams && typeof queryParams === "object") {
392
- for (const name in queryParams) {
393
- const value = queryParams[name];
394
- if (value === void 0 || value === null) {
395
- continue;
396
- }
397
- const options = parameters[name] || args;
398
- if (Array.isArray(value)) {
399
- const serializedArray = serializeArrayParam({
400
- allowReserved: options.allowReserved,
401
- explode: true,
402
- name,
403
- style: "form",
404
- value,
405
- ...options.array
406
- });
407
- if (serializedArray) search.push(serializedArray);
408
- } else if (typeof value === "object") {
409
- const serializedObject = serializeObjectParam({
410
- allowReserved: options.allowReserved,
411
- explode: true,
412
- name,
413
- style: "deepObject",
414
- value,
415
- ...options.object
416
- });
417
- if (serializedObject) search.push(serializedObject);
418
- } else {
419
- const serializedPrimitive = serializePrimitiveParam({
420
- allowReserved: options.allowReserved,
421
- name,
422
- value
423
- });
424
- if (serializedPrimitive) search.push(serializedPrimitive);
425
- }
426
- }
427
- }
428
- return search.join("&");
429
- }, "querySerializer");
430
- return querySerializer;
431
- }, "createQuerySerializer");
432
- var getParseAs = /* @__PURE__ */ __name((contentType) => {
433
- if (!contentType) {
434
- return "stream";
435
- }
436
- const cleanContent = contentType.split(";")[0]?.trim();
437
- if (!cleanContent) {
438
- return;
439
- }
440
- if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
441
- return "json";
442
- }
443
- if (cleanContent === "multipart/form-data") {
444
- return "formData";
445
- }
446
- if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
447
- return "blob";
448
- }
449
- if (cleanContent.startsWith("text/")) {
450
- return "text";
451
- }
452
- return;
453
- }, "getParseAs");
454
- var checkForExistence = /* @__PURE__ */ __name((options, name) => {
455
- if (!name) {
456
- return false;
457
- }
458
- if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
459
- return true;
460
- }
461
- return false;
462
- }, "checkForExistence");
463
- var setAuthParams = /* @__PURE__ */ __name(async ({
464
- security,
465
- ...options
466
- }) => {
467
- for (const auth2 of security) {
468
- if (checkForExistence(options, auth2.name)) {
469
- continue;
470
- }
471
- const token = await getAuthToken(auth2, options.auth);
472
- if (!token) {
473
- continue;
474
- }
475
- const name = auth2.name ?? "Authorization";
476
- switch (auth2.in) {
477
- case "query":
478
- if (!options.query) {
479
- options.query = {};
480
- }
481
- options.query[name] = token;
482
- break;
483
- case "cookie":
484
- options.headers.append("Cookie", `${name}=${token}`);
485
- break;
486
- case "header":
487
- default:
488
- options.headers.set(name, token);
489
- break;
490
- }
491
- }
492
- }, "setAuthParams");
493
- var buildUrl = /* @__PURE__ */ __name((options) => getUrl({
494
- baseUrl: options.baseUrl,
495
- path: options.path,
496
- query: options.query,
497
- querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
498
- url: options.url
499
- }), "buildUrl");
500
- var mergeConfigs = /* @__PURE__ */ __name((a, b) => {
501
- const config = { ...a, ...b };
502
- if (config.baseUrl?.endsWith("/")) {
503
- config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
504
- }
505
- config.headers = mergeHeaders(a.headers, b.headers);
506
- return config;
507
- }, "mergeConfigs");
508
- var headersEntries = /* @__PURE__ */ __name((headers) => {
509
- const entries = [];
510
- headers.forEach((value, key) => {
511
- entries.push([key, value]);
512
- });
513
- return entries;
514
- }, "headersEntries");
515
- var mergeHeaders = /* @__PURE__ */ __name((...headers) => {
516
- const mergedHeaders = new Headers();
517
- for (const header of headers) {
518
- if (!header) {
519
- continue;
520
- }
521
- const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
522
- for (const [key, value] of iterator) {
523
- if (value === null) {
524
- mergedHeaders.delete(key);
525
- } else if (Array.isArray(value)) {
526
- for (const v of value) {
527
- mergedHeaders.append(key, v);
528
- }
529
- } else if (value !== void 0) {
530
- mergedHeaders.set(
531
- key,
532
- typeof value === "object" ? JSON.stringify(value) : value
533
- );
534
- }
535
- }
536
- }
537
- return mergedHeaders;
538
- }, "mergeHeaders");
539
- var Interceptors = class {
540
- static {
541
- __name(this, "Interceptors");
542
- }
543
- fns = [];
544
- clear() {
545
- this.fns = [];
546
- }
547
- eject(id) {
548
- const index = this.getInterceptorIndex(id);
549
- if (this.fns[index]) {
550
- this.fns[index] = null;
551
- }
552
- }
553
- exists(id) {
554
- const index = this.getInterceptorIndex(id);
555
- return Boolean(this.fns[index]);
556
- }
557
- getInterceptorIndex(id) {
558
- if (typeof id === "number") {
559
- return this.fns[id] ? id : -1;
560
- }
561
- return this.fns.indexOf(id);
562
- }
563
- update(id, fn) {
564
- const index = this.getInterceptorIndex(id);
565
- if (this.fns[index]) {
566
- this.fns[index] = fn;
567
- return id;
568
- }
569
- return false;
570
- }
571
- use(fn) {
572
- this.fns.push(fn);
573
- return this.fns.length - 1;
574
- }
575
- };
576
- var createInterceptors = /* @__PURE__ */ __name(() => ({
577
- error: new Interceptors(),
578
- request: new Interceptors(),
579
- response: new Interceptors()
580
- }), "createInterceptors");
581
- var defaultQuerySerializer = createQuerySerializer({
582
- allowReserved: false,
583
- array: {
584
- explode: true,
585
- style: "form"
586
- },
587
- object: {
588
- explode: true,
589
- style: "deepObject"
590
- }
591
- });
592
- var defaultHeaders = {
593
- "Content-Type": "application/json"
594
- };
595
- var createConfig = /* @__PURE__ */ __name((override = {}) => ({
596
- ...jsonBodySerializer,
597
- headers: defaultHeaders,
598
- parseAs: "auto",
599
- querySerializer: defaultQuerySerializer,
600
- ...override
601
- }), "createConfig");
602
-
603
- // src/_api/generated/client/client.gen.ts
604
- var createClient = /* @__PURE__ */ __name((config = {}) => {
605
- let _config = mergeConfigs(createConfig(), config);
606
- const getConfig = /* @__PURE__ */ __name(() => ({ ..._config }), "getConfig");
607
- const setConfig = /* @__PURE__ */ __name((config2) => {
608
- _config = mergeConfigs(_config, config2);
609
- return getConfig();
610
- }, "setConfig");
611
- const interceptors = createInterceptors();
612
- const beforeRequest = /* @__PURE__ */ __name(async (options) => {
613
- const opts = {
614
- ..._config,
615
- ...options,
616
- fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
617
- headers: mergeHeaders(_config.headers, options.headers),
618
- serializedBody: void 0
619
- };
620
- if (opts.security) {
621
- await setAuthParams({
622
- ...opts,
623
- security: opts.security
624
- });
625
- }
626
- if (opts.requestValidator) {
627
- await opts.requestValidator(opts);
628
- }
629
- if (opts.body !== void 0 && opts.bodySerializer) {
630
- opts.serializedBody = opts.bodySerializer(opts.body);
631
- }
632
- if (opts.body === void 0 || opts.serializedBody === "") {
633
- opts.headers.delete("Content-Type");
634
- }
635
- const resolvedOpts = opts;
636
- const url = buildUrl(resolvedOpts);
637
- return { opts: resolvedOpts, url };
638
- }, "beforeRequest");
639
- const request = /* @__PURE__ */ __name(async (options) => {
640
- const throwOnError = options.throwOnError ?? _config.throwOnError;
641
- const responseStyle = options.responseStyle ?? _config.responseStyle;
642
- let request2;
643
- let response;
644
- try {
645
- const { opts, url } = await beforeRequest(options);
646
- const requestInit = {
647
- redirect: "follow",
648
- ...opts,
649
- body: getValidRequestBody(opts)
650
- };
651
- request2 = new Request(url, requestInit);
652
- for (const fn of interceptors.request.fns) {
653
- if (fn) {
654
- request2 = await fn(request2, opts);
655
- }
656
- }
657
- const _fetch = opts.fetch;
658
- response = await _fetch(request2);
659
- for (const fn of interceptors.response.fns) {
660
- if (fn) {
661
- response = await fn(response, request2, opts);
662
- }
663
- }
664
- const result = {
665
- request: request2,
666
- response
667
- };
668
- if (response.ok) {
669
- const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
670
- if (response.status === 204 || response.headers.get("Content-Length") === "0") {
671
- let emptyData;
672
- switch (parseAs) {
673
- case "arrayBuffer":
674
- case "blob":
675
- case "text":
676
- emptyData = await response[parseAs]();
677
- break;
678
- case "formData":
679
- emptyData = new FormData();
680
- break;
681
- case "stream":
682
- emptyData = response.body;
683
- break;
684
- case "json":
685
- default:
686
- emptyData = {};
687
- break;
688
- }
689
- return opts.responseStyle === "data" ? emptyData : {
690
- data: emptyData,
691
- ...result
692
- };
693
- }
694
- let data;
695
- switch (parseAs) {
696
- case "arrayBuffer":
697
- case "blob":
698
- case "formData":
699
- case "text":
700
- data = await response[parseAs]();
701
- break;
702
- case "json": {
703
- const text = await response.text();
704
- data = text ? JSON.parse(text) : {};
705
- break;
706
- }
707
- case "stream":
708
- return opts.responseStyle === "data" ? response.body : {
709
- data: response.body,
710
- ...result
711
- };
712
- }
713
- if (parseAs === "json") {
714
- if (opts.responseValidator) {
715
- await opts.responseValidator(data);
716
- }
717
- if (opts.responseTransformer) {
718
- data = await opts.responseTransformer(data);
719
- }
720
- }
721
- return opts.responseStyle === "data" ? data : {
722
- data,
723
- ...result
724
- };
725
- }
726
- const textError = await response.text();
727
- let jsonError;
728
- try {
729
- jsonError = JSON.parse(textError);
730
- } catch {
731
- }
732
- throw jsonError ?? textError;
733
- } catch (error) {
734
- let finalError = error;
735
- for (const fn of interceptors.error.fns) {
736
- if (fn) {
737
- finalError = await fn(finalError, response, request2, options);
738
- }
739
- }
740
- finalError = finalError || {};
741
- if (throwOnError) {
742
- throw finalError;
743
- }
744
- return responseStyle === "data" ? void 0 : {
745
- error: finalError,
746
- request: request2,
747
- response
748
- };
749
- }
750
- }, "request");
751
- const makeMethodFn = /* @__PURE__ */ __name((method) => (options) => request({ ...options, method }), "makeMethodFn");
752
- const makeSseFn = /* @__PURE__ */ __name((method) => async (options) => {
753
- const { opts, url } = await beforeRequest(options);
754
- return createSseClient({
755
- ...opts,
756
- body: opts.body,
757
- method,
758
- onRequest: /* @__PURE__ */ __name(async (url2, init) => {
759
- let request2 = new Request(url2, init);
760
- for (const fn of interceptors.request.fns) {
761
- if (fn) {
762
- request2 = await fn(request2, opts);
763
- }
764
- }
765
- return request2;
766
- }, "onRequest"),
767
- serializedBody: getValidRequestBody(opts),
768
- url
769
- });
770
- }, "makeSseFn");
771
- const _buildUrl = /* @__PURE__ */ __name((options) => buildUrl({ ..._config, ...options }), "_buildUrl");
772
- return {
773
- buildUrl: _buildUrl,
774
- connect: makeMethodFn("CONNECT"),
775
- delete: makeMethodFn("DELETE"),
776
- get: makeMethodFn("GET"),
777
- getConfig,
778
- head: makeMethodFn("HEAD"),
779
- interceptors,
780
- options: makeMethodFn("OPTIONS"),
781
- patch: makeMethodFn("PATCH"),
782
- post: makeMethodFn("POST"),
783
- put: makeMethodFn("PUT"),
784
- request,
785
- setConfig,
786
- sse: {
787
- connect: makeSseFn("CONNECT"),
788
- delete: makeSseFn("DELETE"),
789
- get: makeSseFn("GET"),
790
- head: makeSseFn("HEAD"),
791
- options: makeSseFn("OPTIONS"),
792
- patch: makeSseFn("PATCH"),
793
- post: makeSseFn("POST"),
794
- put: makeSseFn("PUT"),
795
- trace: makeSseFn("TRACE")
796
- },
797
- trace: makeMethodFn("TRACE")
798
- };
799
- }, "createClient");
800
-
801
- // src/_api/generated/client.gen.ts
802
- var client = createClient(createConfig({ baseUrl: "http://localhost:8000" }));
803
-
804
5
  // src/_api/generated/helpers/auth.ts
805
6
  var ACCESS_KEY = "cfg.access_token";
806
7
  var REFRESH_KEY = "cfg.refresh_token";
@@ -893,15 +94,21 @@ var _apiKeyOverride = null;
893
94
  var _baseUrlOverride = null;
894
95
  var _withCredentials = true;
895
96
  var _onUnauthorized = null;
97
+ var _refreshHandler = null;
98
+ var _client = null;
99
+ function pushClientConfig() {
100
+ if (!_client) return;
101
+ _client.setConfig({
102
+ baseUrl: auth.getBaseUrl(),
103
+ credentials: _withCredentials ? "include" : "same-origin"
104
+ });
105
+ }
106
+ __name(pushClientConfig, "pushClientConfig");
896
107
  var auth = {
897
108
  // ── Storage mode ──────────────────────────────────────────────────
898
109
  getStorageMode() {
899
110
  return _storageMode;
900
111
  },
901
- /**
902
- * Switch the storage backend. Existing values in the *previous*
903
- * backend are NOT migrated — set fresh values after switching.
904
- */
905
112
  setStorageMode(mode) {
906
113
  _storageMode = mode;
907
114
  _storage = mode === "cookie" ? cookieBackend : localStorageBackend;
@@ -927,15 +134,12 @@ var auth = {
927
134
  return _storage.get(ACCESS_KEY) !== null;
928
135
  },
929
136
  // ── API key ───────────────────────────────────────────────────────
930
- /** In-memory API key. Falls back to storage, then NEXT_PUBLIC_API_KEY. */
931
137
  getApiKey() {
932
138
  return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
933
139
  },
934
- /** In-memory only (cleared on reload). */
935
140
  setApiKey(key) {
936
141
  _apiKeyOverride = key;
937
142
  },
938
- /** Persist to active storage backend (localStorage or cookie). */
939
143
  setApiKeyPersist(key) {
940
144
  _apiKeyOverride = key;
941
145
  _storage.set(API_KEY_KEY, key);
@@ -945,7 +149,6 @@ var auth = {
945
149
  _storage.set(API_KEY_KEY, null);
946
150
  },
947
151
  // ── Locale ────────────────────────────────────────────────────────
948
- /** Override locale → falls back to NEXT_LOCALE cookie / navigator.language. */
949
152
  getLocale() {
950
153
  return _localeOverride ?? detectLocale();
951
154
  },
@@ -959,48 +162,43 @@ var auth = {
959
162
  },
960
163
  setBaseUrl(url) {
961
164
  _baseUrlOverride = url ? url.replace(/\/$/, "") : null;
962
- client.setConfig({ baseUrl: this.getBaseUrl() });
165
+ pushClientConfig();
963
166
  },
964
- // ── Credentials toggle (Django session/CSRF cross-origin) ─────────
167
+ // ── Credentials toggle ────────────────────────────────────────────
965
168
  getWithCredentials() {
966
169
  return _withCredentials;
967
170
  },
968
171
  setWithCredentials(value) {
969
172
  _withCredentials = value;
970
- client.setConfig({ credentials: value ? "include" : "same-origin" });
173
+ pushClientConfig();
971
174
  },
972
175
  // ── 401 handler ───────────────────────────────────────────────────
973
176
  /**
974
- * Register a callback fired on every 401 response. Use this to wire
975
- * a token-refresh flow or a forced logout. Setting `null` removes
976
- * the handler.
177
+ * Fired when the server returns 401 AND no refresh path recovers it
178
+ * (no refresh token, no refresh handler, refresh failed, or retry
179
+ * still 401). The app should clear local state and redirect to login.
180
+ *
181
+ * NOT fired for 401 that gets transparently recovered by the refresh
182
+ * handler — those are invisible to callers.
977
183
  */
978
184
  onUnauthorized(cb) {
979
185
  _onUnauthorized = cb;
186
+ },
187
+ /**
188
+ * Register the refresh strategy. The handler receives the current
189
+ * refresh token and must call your refresh endpoint, returning
190
+ * `{ access, refresh? }` on success or `null` on failure.
191
+ *
192
+ * @example
193
+ * auth.setRefreshHandler(async (refresh) => {
194
+ * const { data } = await Auth.tokenRefreshCreate({ body: { refresh } });
195
+ * return data ? { access: data.access, refresh: data.refresh } : null;
196
+ * });
197
+ */
198
+ setRefreshHandler(fn) {
199
+ _refreshHandler = fn;
980
200
  }
981
201
  };
982
- client.setConfig({
983
- baseUrl: auth.getBaseUrl(),
984
- credentials: _withCredentials ? "include" : "same-origin"
985
- });
986
- client.interceptors.request.use((request) => {
987
- const token = auth.getToken();
988
- if (token) request.headers.set("Authorization", `Bearer ${token}`);
989
- const locale = auth.getLocale();
990
- if (locale) request.headers.set("Accept-Language", locale);
991
- const apiKey = auth.getApiKey();
992
- if (apiKey) request.headers.set("X-API-Key", apiKey);
993
- return request;
994
- });
995
- client.interceptors.response.use((response) => {
996
- if (response.status === 401 && _onUnauthorized) {
997
- try {
998
- _onUnauthorized(response);
999
- } catch {
1000
- }
1001
- }
1002
- return response;
1003
- });
1004
202
 
1005
203
  // src/_api/generated/helpers/logger.ts
1006
204
  import { createConsola } from "consola";
@@ -1148,6 +346,15 @@ var API = class {
1148
346
  setApiKey(key) {
1149
347
  auth.setApiKey(key);
1150
348
  }
349
+ // ── 401 handling ────────────────────────────────────────────────────────
350
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
351
+ onUnauthorized(cb) {
352
+ auth.onUnauthorized(cb);
353
+ }
354
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
355
+ setRefreshHandler(fn) {
356
+ auth.setRefreshHandler(fn);
357
+ }
1151
358
  };
1152
359
 
1153
360
  // src/_api/generated/_cfg_centrifugo/api.ts
@@ -1202,6 +409,15 @@ var API2 = class {
1202
409
  setApiKey(key) {
1203
410
  auth.setApiKey(key);
1204
411
  }
412
+ // ── 401 handling ────────────────────────────────────────────────────────
413
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
414
+ onUnauthorized(cb) {
415
+ auth.onUnauthorized(cb);
416
+ }
417
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
418
+ setRefreshHandler(fn) {
419
+ auth.setRefreshHandler(fn);
420
+ }
1205
421
  };
1206
422
 
1207
423
  // src/_api/generated/_cfg_totp/api.ts
@@ -1256,6 +472,15 @@ var API3 = class {
1256
472
  setApiKey(key) {
1257
473
  auth.setApiKey(key);
1258
474
  }
475
+ // ── 401 handling ────────────────────────────────────────────────────────
476
+ /** Fired only on terminal 401 (after refresh+retry path is exhausted). */
477
+ onUnauthorized(cb) {
478
+ auth.onUnauthorized(cb);
479
+ }
480
+ /** Provide a refresh strategy. See `auth.setRefreshHandler` for the contract. */
481
+ setRefreshHandler(fn) {
482
+ auth.setRefreshHandler(fn);
483
+ }
1259
484
  };
1260
485
 
1261
486
  // src/_api/generated/index.ts