herald-auth-web 0.5.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/dist/index.js ADDED
@@ -0,0 +1,1526 @@
1
+ // src/generated/core/bodySerializer.gen.ts
2
+ var jsonBodySerializer = {
3
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
4
+ };
5
+
6
+ // src/generated/core/serverSentEvents.gen.ts
7
+ var createSseClient = ({
8
+ onRequest,
9
+ onSseError,
10
+ onSseEvent,
11
+ responseTransformer,
12
+ responseValidator,
13
+ sseDefaultRetryDelay,
14
+ sseMaxRetryAttempts,
15
+ sseMaxRetryDelay,
16
+ sseSleepFn,
17
+ url,
18
+ ...options
19
+ }) => {
20
+ let lastEventId;
21
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
22
+ const createStream = async function* () {
23
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
24
+ let attempt = 0;
25
+ const signal = options.signal ?? new AbortController().signal;
26
+ while (true) {
27
+ if (signal.aborted) break;
28
+ attempt++;
29
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
30
+ if (lastEventId !== void 0) {
31
+ headers.set("Last-Event-ID", lastEventId);
32
+ }
33
+ try {
34
+ const requestInit = {
35
+ redirect: "follow",
36
+ ...options,
37
+ body: options.serializedBody,
38
+ headers,
39
+ signal
40
+ };
41
+ let request = new Request(url, requestInit);
42
+ if (onRequest) {
43
+ request = await onRequest(url, requestInit);
44
+ }
45
+ const _fetch = options.fetch ?? globalThis.fetch;
46
+ const response = await _fetch(request);
47
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
48
+ if (!response.body) throw new Error("No body in SSE response");
49
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
50
+ let buffer = "";
51
+ const abortHandler = () => {
52
+ try {
53
+ reader.cancel();
54
+ } catch {
55
+ }
56
+ };
57
+ signal.addEventListener("abort", abortHandler);
58
+ try {
59
+ while (true) {
60
+ const { done, value } = await reader.read();
61
+ if (done) break;
62
+ buffer += value;
63
+ buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
64
+ const chunks = buffer.split("\n\n");
65
+ buffer = chunks.pop() ?? "";
66
+ for (const chunk of chunks) {
67
+ const lines = chunk.split("\n");
68
+ const dataLines = [];
69
+ let eventName;
70
+ for (const line of lines) {
71
+ if (line.startsWith("data:")) {
72
+ dataLines.push(line.replace(/^data:\s*/, ""));
73
+ } else if (line.startsWith("event:")) {
74
+ eventName = line.replace(/^event:\s*/, "");
75
+ } else if (line.startsWith("id:")) {
76
+ lastEventId = line.replace(/^id:\s*/, "");
77
+ } else if (line.startsWith("retry:")) {
78
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
79
+ if (!Number.isNaN(parsed)) {
80
+ retryDelay = parsed;
81
+ }
82
+ }
83
+ }
84
+ let data;
85
+ let parsedJson = false;
86
+ if (dataLines.length) {
87
+ const rawData = dataLines.join("\n");
88
+ try {
89
+ data = JSON.parse(rawData);
90
+ parsedJson = true;
91
+ } catch {
92
+ data = rawData;
93
+ }
94
+ }
95
+ if (parsedJson) {
96
+ if (responseValidator) {
97
+ await responseValidator(data);
98
+ }
99
+ if (responseTransformer) {
100
+ data = await responseTransformer(data);
101
+ }
102
+ }
103
+ onSseEvent?.({
104
+ data,
105
+ event: eventName,
106
+ id: lastEventId,
107
+ retry: retryDelay
108
+ });
109
+ if (dataLines.length) {
110
+ yield data;
111
+ }
112
+ }
113
+ }
114
+ } finally {
115
+ signal.removeEventListener("abort", abortHandler);
116
+ reader.releaseLock();
117
+ }
118
+ break;
119
+ } catch (error) {
120
+ onSseError?.(error);
121
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
122
+ break;
123
+ }
124
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
125
+ await sleep(backoff);
126
+ }
127
+ }
128
+ };
129
+ const stream = createStream();
130
+ return { stream };
131
+ };
132
+
133
+ // src/generated/core/pathSerializer.gen.ts
134
+ var separatorArrayExplode = (style) => {
135
+ switch (style) {
136
+ case "label":
137
+ return ".";
138
+ case "matrix":
139
+ return ";";
140
+ case "simple":
141
+ return ",";
142
+ default:
143
+ return "&";
144
+ }
145
+ };
146
+ var separatorArrayNoExplode = (style) => {
147
+ switch (style) {
148
+ case "form":
149
+ return ",";
150
+ case "pipeDelimited":
151
+ return "|";
152
+ case "spaceDelimited":
153
+ return "%20";
154
+ default:
155
+ return ",";
156
+ }
157
+ };
158
+ var separatorObjectExplode = (style) => {
159
+ switch (style) {
160
+ case "label":
161
+ return ".";
162
+ case "matrix":
163
+ return ";";
164
+ case "simple":
165
+ return ",";
166
+ default:
167
+ return "&";
168
+ }
169
+ };
170
+ var serializeArrayParam = ({
171
+ allowReserved,
172
+ explode,
173
+ name,
174
+ style,
175
+ value
176
+ }) => {
177
+ if (!explode) {
178
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
179
+ switch (style) {
180
+ case "label":
181
+ return `.${joinedValues2}`;
182
+ case "matrix":
183
+ return `;${name}=${joinedValues2}`;
184
+ case "simple":
185
+ return joinedValues2;
186
+ default:
187
+ return `${name}=${joinedValues2}`;
188
+ }
189
+ }
190
+ const separator = separatorArrayExplode(style);
191
+ const joinedValues = value.map((v) => {
192
+ if (style === "label" || style === "simple") {
193
+ return allowReserved ? v : encodeURIComponent(v);
194
+ }
195
+ return serializePrimitiveParam({
196
+ allowReserved,
197
+ name,
198
+ value: v
199
+ });
200
+ }).join(separator);
201
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
202
+ };
203
+ var serializePrimitiveParam = ({
204
+ allowReserved,
205
+ name,
206
+ value
207
+ }) => {
208
+ if (value === void 0 || value === null) {
209
+ return "";
210
+ }
211
+ if (typeof value === "object") {
212
+ throw new Error(
213
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
214
+ );
215
+ }
216
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
217
+ };
218
+ var serializeObjectParam = ({
219
+ allowReserved,
220
+ explode,
221
+ name,
222
+ style,
223
+ value,
224
+ valueOnly
225
+ }) => {
226
+ if (value instanceof Date) {
227
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
228
+ }
229
+ if (style !== "deepObject" && !explode) {
230
+ let values = [];
231
+ Object.entries(value).forEach(([key, v]) => {
232
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
233
+ });
234
+ const joinedValues2 = values.join(",");
235
+ switch (style) {
236
+ case "form":
237
+ return `${name}=${joinedValues2}`;
238
+ case "label":
239
+ return `.${joinedValues2}`;
240
+ case "matrix":
241
+ return `;${name}=${joinedValues2}`;
242
+ default:
243
+ return joinedValues2;
244
+ }
245
+ }
246
+ const separator = separatorObjectExplode(style);
247
+ const joinedValues = Object.entries(value).map(
248
+ ([key, v]) => serializePrimitiveParam({
249
+ allowReserved,
250
+ name: style === "deepObject" ? `${name}[${key}]` : key,
251
+ value: v
252
+ })
253
+ ).join(separator);
254
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
255
+ };
256
+
257
+ // src/generated/core/utils.gen.ts
258
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
259
+ var defaultPathSerializer = ({ path, url: _url }) => {
260
+ let url = _url;
261
+ const matches = _url.match(PATH_PARAM_RE);
262
+ if (matches) {
263
+ for (const match of matches) {
264
+ let explode = false;
265
+ let name = match.substring(1, match.length - 1);
266
+ let style = "simple";
267
+ if (name.endsWith("*")) {
268
+ explode = true;
269
+ name = name.substring(0, name.length - 1);
270
+ }
271
+ if (name.startsWith(".")) {
272
+ name = name.substring(1);
273
+ style = "label";
274
+ } else if (name.startsWith(";")) {
275
+ name = name.substring(1);
276
+ style = "matrix";
277
+ }
278
+ const value = path[name];
279
+ if (value === void 0 || value === null) {
280
+ continue;
281
+ }
282
+ if (Array.isArray(value)) {
283
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
284
+ continue;
285
+ }
286
+ if (typeof value === "object") {
287
+ url = url.replace(
288
+ match,
289
+ serializeObjectParam({
290
+ explode,
291
+ name,
292
+ style,
293
+ value,
294
+ valueOnly: true
295
+ })
296
+ );
297
+ continue;
298
+ }
299
+ if (style === "matrix") {
300
+ url = url.replace(
301
+ match,
302
+ `;${serializePrimitiveParam({
303
+ name,
304
+ value
305
+ })}`
306
+ );
307
+ continue;
308
+ }
309
+ const replaceValue = encodeURIComponent(
310
+ style === "label" ? `.${value}` : value
311
+ );
312
+ url = url.replace(match, replaceValue);
313
+ }
314
+ }
315
+ return url;
316
+ };
317
+ var getUrl = ({
318
+ baseUrl,
319
+ path,
320
+ query,
321
+ querySerializer,
322
+ url: _url
323
+ }) => {
324
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
325
+ let url = (baseUrl ?? "") + pathUrl;
326
+ if (path) {
327
+ url = defaultPathSerializer({ path, url });
328
+ }
329
+ let search = query ? querySerializer(query) : "";
330
+ if (search.startsWith("?")) {
331
+ search = search.substring(1);
332
+ }
333
+ if (search) {
334
+ url += `?${search}`;
335
+ }
336
+ return url;
337
+ };
338
+ function getValidRequestBody(options) {
339
+ const hasBody = options.body !== void 0;
340
+ const isSerializedBody = hasBody && options.bodySerializer;
341
+ if (isSerializedBody) {
342
+ if ("serializedBody" in options) {
343
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
344
+ return hasSerializedBody ? options.serializedBody : null;
345
+ }
346
+ return options.body !== "" ? options.body : null;
347
+ }
348
+ if (hasBody) {
349
+ return options.body;
350
+ }
351
+ return void 0;
352
+ }
353
+
354
+ // src/generated/core/auth.gen.ts
355
+ var getAuthToken = async (auth, callback) => {
356
+ const token = typeof callback === "function" ? await callback(auth) : callback;
357
+ if (!token) {
358
+ return;
359
+ }
360
+ if (auth.scheme === "bearer") {
361
+ return `Bearer ${token}`;
362
+ }
363
+ if (auth.scheme === "basic") {
364
+ return `Basic ${btoa(token)}`;
365
+ }
366
+ return token;
367
+ };
368
+
369
+ // src/generated/client/utils.gen.ts
370
+ var createQuerySerializer = ({
371
+ parameters = {},
372
+ ...args
373
+ } = {}) => {
374
+ const querySerializer = (queryParams) => {
375
+ const search = [];
376
+ if (queryParams && typeof queryParams === "object") {
377
+ for (const name in queryParams) {
378
+ const value = queryParams[name];
379
+ if (value === void 0 || value === null) {
380
+ continue;
381
+ }
382
+ const options = parameters[name] || args;
383
+ if (Array.isArray(value)) {
384
+ const serializedArray = serializeArrayParam({
385
+ allowReserved: options.allowReserved,
386
+ explode: true,
387
+ name,
388
+ style: "form",
389
+ value,
390
+ ...options.array
391
+ });
392
+ if (serializedArray) search.push(serializedArray);
393
+ } else if (typeof value === "object") {
394
+ const serializedObject = serializeObjectParam({
395
+ allowReserved: options.allowReserved,
396
+ explode: true,
397
+ name,
398
+ style: "deepObject",
399
+ value,
400
+ ...options.object
401
+ });
402
+ if (serializedObject) search.push(serializedObject);
403
+ } else {
404
+ const serializedPrimitive = serializePrimitiveParam({
405
+ allowReserved: options.allowReserved,
406
+ name,
407
+ value
408
+ });
409
+ if (serializedPrimitive) search.push(serializedPrimitive);
410
+ }
411
+ }
412
+ }
413
+ return search.join("&");
414
+ };
415
+ return querySerializer;
416
+ };
417
+ var getParseAs = (contentType) => {
418
+ if (!contentType) {
419
+ return "stream";
420
+ }
421
+ const cleanContent = contentType.split(";")[0]?.trim();
422
+ if (!cleanContent) {
423
+ return;
424
+ }
425
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
426
+ return "json";
427
+ }
428
+ if (cleanContent === "multipart/form-data") {
429
+ return "formData";
430
+ }
431
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
432
+ return "blob";
433
+ }
434
+ if (cleanContent.startsWith("text/")) {
435
+ return "text";
436
+ }
437
+ return;
438
+ };
439
+ var checkForExistence = (options, name) => {
440
+ if (!name) {
441
+ return false;
442
+ }
443
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
444
+ return true;
445
+ }
446
+ return false;
447
+ };
448
+ var setAuthParams = async ({
449
+ security,
450
+ ...options
451
+ }) => {
452
+ for (const auth of security) {
453
+ if (checkForExistence(options, auth.name)) {
454
+ continue;
455
+ }
456
+ const token = await getAuthToken(auth, options.auth);
457
+ if (!token) {
458
+ continue;
459
+ }
460
+ const name = auth.name ?? "Authorization";
461
+ switch (auth.in) {
462
+ case "query":
463
+ if (!options.query) {
464
+ options.query = {};
465
+ }
466
+ options.query[name] = token;
467
+ break;
468
+ case "cookie":
469
+ options.headers.append("Cookie", `${name}=${token}`);
470
+ break;
471
+ case "header":
472
+ default:
473
+ options.headers.set(name, token);
474
+ break;
475
+ }
476
+ }
477
+ };
478
+ var buildUrl = (options) => getUrl({
479
+ baseUrl: options.baseUrl,
480
+ path: options.path,
481
+ query: options.query,
482
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
483
+ url: options.url
484
+ });
485
+ var mergeConfigs = (a, b) => {
486
+ const config = { ...a, ...b };
487
+ if (config.baseUrl?.endsWith("/")) {
488
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
489
+ }
490
+ config.headers = mergeHeaders(a.headers, b.headers);
491
+ return config;
492
+ };
493
+ var headersEntries = (headers) => {
494
+ const entries = [];
495
+ headers.forEach((value, key) => {
496
+ entries.push([key, value]);
497
+ });
498
+ return entries;
499
+ };
500
+ var mergeHeaders = (...headers) => {
501
+ const mergedHeaders = new Headers();
502
+ for (const header of headers) {
503
+ if (!header) {
504
+ continue;
505
+ }
506
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
507
+ for (const [key, value] of iterator) {
508
+ if (value === null) {
509
+ mergedHeaders.delete(key);
510
+ } else if (Array.isArray(value)) {
511
+ for (const v of value) {
512
+ mergedHeaders.append(key, v);
513
+ }
514
+ } else if (value !== void 0) {
515
+ mergedHeaders.set(
516
+ key,
517
+ typeof value === "object" ? JSON.stringify(value) : value
518
+ );
519
+ }
520
+ }
521
+ }
522
+ return mergedHeaders;
523
+ };
524
+ var Interceptors = class {
525
+ constructor() {
526
+ this.fns = [];
527
+ }
528
+ clear() {
529
+ this.fns = [];
530
+ }
531
+ eject(id) {
532
+ const index = this.getInterceptorIndex(id);
533
+ if (this.fns[index]) {
534
+ this.fns[index] = null;
535
+ }
536
+ }
537
+ exists(id) {
538
+ const index = this.getInterceptorIndex(id);
539
+ return Boolean(this.fns[index]);
540
+ }
541
+ getInterceptorIndex(id) {
542
+ if (typeof id === "number") {
543
+ return this.fns[id] ? id : -1;
544
+ }
545
+ return this.fns.indexOf(id);
546
+ }
547
+ update(id, fn) {
548
+ const index = this.getInterceptorIndex(id);
549
+ if (this.fns[index]) {
550
+ this.fns[index] = fn;
551
+ return id;
552
+ }
553
+ return false;
554
+ }
555
+ use(fn) {
556
+ this.fns.push(fn);
557
+ return this.fns.length - 1;
558
+ }
559
+ };
560
+ var createInterceptors = () => ({
561
+ error: new Interceptors(),
562
+ request: new Interceptors(),
563
+ response: new Interceptors()
564
+ });
565
+ var defaultQuerySerializer = createQuerySerializer({
566
+ allowReserved: false,
567
+ array: {
568
+ explode: true,
569
+ style: "form"
570
+ },
571
+ object: {
572
+ explode: true,
573
+ style: "deepObject"
574
+ }
575
+ });
576
+ var defaultHeaders = {
577
+ "Content-Type": "application/json"
578
+ };
579
+ var createConfig = (override = {}) => ({
580
+ ...jsonBodySerializer,
581
+ headers: defaultHeaders,
582
+ parseAs: "auto",
583
+ querySerializer: defaultQuerySerializer,
584
+ ...override
585
+ });
586
+
587
+ // src/generated/client/client.gen.ts
588
+ var createClient = (config = {}) => {
589
+ let _config = mergeConfigs(createConfig(), config);
590
+ const getConfig = () => ({ ..._config });
591
+ const setConfig = (config2) => {
592
+ _config = mergeConfigs(_config, config2);
593
+ return getConfig();
594
+ };
595
+ const interceptors = createInterceptors();
596
+ const beforeRequest = async (options) => {
597
+ const opts = {
598
+ ..._config,
599
+ ...options,
600
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
601
+ headers: mergeHeaders(_config.headers, options.headers),
602
+ serializedBody: void 0
603
+ };
604
+ if (opts.security) {
605
+ await setAuthParams({
606
+ ...opts,
607
+ security: opts.security
608
+ });
609
+ }
610
+ if (opts.requestValidator) {
611
+ await opts.requestValidator(opts);
612
+ }
613
+ if (opts.body !== void 0 && opts.bodySerializer) {
614
+ opts.serializedBody = opts.bodySerializer(opts.body);
615
+ }
616
+ if (opts.body === void 0 || opts.serializedBody === "") {
617
+ opts.headers.delete("Content-Type");
618
+ }
619
+ const url = buildUrl(opts);
620
+ return { opts, url };
621
+ };
622
+ const request = async (options) => {
623
+ const { opts, url } = await beforeRequest(options);
624
+ const requestInit = {
625
+ redirect: "follow",
626
+ ...opts,
627
+ body: getValidRequestBody(opts)
628
+ };
629
+ let request2 = new Request(url, requestInit);
630
+ for (const fn of interceptors.request.fns) {
631
+ if (fn) {
632
+ request2 = await fn(request2, opts);
633
+ }
634
+ }
635
+ const _fetch = opts.fetch;
636
+ let response;
637
+ try {
638
+ response = await _fetch(request2);
639
+ } catch (error2) {
640
+ let finalError2 = error2;
641
+ for (const fn of interceptors.error.fns) {
642
+ if (fn) {
643
+ finalError2 = await fn(error2, void 0, request2, opts);
644
+ }
645
+ }
646
+ finalError2 = finalError2 || {};
647
+ if (opts.throwOnError) {
648
+ throw finalError2;
649
+ }
650
+ return opts.responseStyle === "data" ? void 0 : {
651
+ error: finalError2,
652
+ request: request2,
653
+ response: void 0
654
+ };
655
+ }
656
+ for (const fn of interceptors.response.fns) {
657
+ if (fn) {
658
+ response = await fn(response, request2, opts);
659
+ }
660
+ }
661
+ const result = {
662
+ request: request2,
663
+ response
664
+ };
665
+ if (response.ok) {
666
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
667
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
668
+ let emptyData;
669
+ switch (parseAs) {
670
+ case "arrayBuffer":
671
+ case "blob":
672
+ case "text":
673
+ emptyData = await response[parseAs]();
674
+ break;
675
+ case "formData":
676
+ emptyData = new FormData();
677
+ break;
678
+ case "stream":
679
+ emptyData = response.body;
680
+ break;
681
+ case "json":
682
+ default:
683
+ emptyData = {};
684
+ break;
685
+ }
686
+ return opts.responseStyle === "data" ? emptyData : {
687
+ data: emptyData,
688
+ ...result
689
+ };
690
+ }
691
+ let data;
692
+ switch (parseAs) {
693
+ case "arrayBuffer":
694
+ case "blob":
695
+ case "formData":
696
+ case "text":
697
+ data = await response[parseAs]();
698
+ break;
699
+ case "json": {
700
+ const text = await response.text();
701
+ data = text ? JSON.parse(text) : {};
702
+ break;
703
+ }
704
+ case "stream":
705
+ return opts.responseStyle === "data" ? response.body : {
706
+ data: response.body,
707
+ ...result
708
+ };
709
+ }
710
+ if (parseAs === "json") {
711
+ if (opts.responseValidator) {
712
+ await opts.responseValidator(data);
713
+ }
714
+ if (opts.responseTransformer) {
715
+ data = await opts.responseTransformer(data);
716
+ }
717
+ }
718
+ return opts.responseStyle === "data" ? data : {
719
+ data,
720
+ ...result
721
+ };
722
+ }
723
+ const textError = await response.text();
724
+ let jsonError;
725
+ try {
726
+ jsonError = JSON.parse(textError);
727
+ } catch {
728
+ }
729
+ const error = jsonError ?? textError;
730
+ let finalError = error;
731
+ for (const fn of interceptors.error.fns) {
732
+ if (fn) {
733
+ finalError = await fn(error, response, request2, opts);
734
+ }
735
+ }
736
+ finalError = finalError || {};
737
+ if (opts.throwOnError) {
738
+ throw finalError;
739
+ }
740
+ return opts.responseStyle === "data" ? void 0 : {
741
+ error: finalError,
742
+ ...result
743
+ };
744
+ };
745
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
746
+ const makeSseFn = (method) => async (options) => {
747
+ const { opts, url } = await beforeRequest(options);
748
+ return createSseClient({
749
+ ...opts,
750
+ body: opts.body,
751
+ headers: opts.headers,
752
+ method,
753
+ onRequest: async (url2, init) => {
754
+ let request2 = new Request(url2, init);
755
+ for (const fn of interceptors.request.fns) {
756
+ if (fn) {
757
+ request2 = await fn(request2, opts);
758
+ }
759
+ }
760
+ return request2;
761
+ },
762
+ serializedBody: getValidRequestBody(opts),
763
+ url
764
+ });
765
+ };
766
+ return {
767
+ buildUrl,
768
+ connect: makeMethodFn("CONNECT"),
769
+ delete: makeMethodFn("DELETE"),
770
+ get: makeMethodFn("GET"),
771
+ getConfig,
772
+ head: makeMethodFn("HEAD"),
773
+ interceptors,
774
+ options: makeMethodFn("OPTIONS"),
775
+ patch: makeMethodFn("PATCH"),
776
+ post: makeMethodFn("POST"),
777
+ put: makeMethodFn("PUT"),
778
+ request,
779
+ setConfig,
780
+ sse: {
781
+ connect: makeSseFn("CONNECT"),
782
+ delete: makeSseFn("DELETE"),
783
+ get: makeSseFn("GET"),
784
+ head: makeSseFn("HEAD"),
785
+ options: makeSseFn("OPTIONS"),
786
+ patch: makeSseFn("PATCH"),
787
+ post: makeSseFn("POST"),
788
+ put: makeSseFn("PUT"),
789
+ trace: makeSseFn("TRACE")
790
+ },
791
+ trace: makeMethodFn("TRACE")
792
+ };
793
+ };
794
+
795
+ // src/generated/client.gen.ts
796
+ var client = createClient(createConfig());
797
+
798
+ // src/generated/sdk.gen.ts
799
+ var refresh = (options) => (options.client ?? client).post({
800
+ url: "/api/auth/browser-token/refresh",
801
+ ...options,
802
+ headers: {
803
+ "Content-Type": "application/json",
804
+ ...options.headers
805
+ }
806
+ });
807
+ var logout = (options) => (options?.client ?? client).post({
808
+ security: [{ scheme: "bearer", type: "http" }],
809
+ url: "/api/auth/logout",
810
+ ...options
811
+ });
812
+ var status = (options) => (options?.client ?? client).get({
813
+ security: [{ scheme: "bearer", type: "http" }],
814
+ url: "/api/auth/status",
815
+ ...options
816
+ });
817
+ var login = (options) => (options.client ?? client).post({
818
+ url: "/api/auth/{realmId}/login",
819
+ ...options,
820
+ headers: {
821
+ "Content-Type": "application/json",
822
+ ...options.headers
823
+ }
824
+ });
825
+ var send = (options) => (options.client ?? client).post({
826
+ url: "/api/auth/{realmId}/login/email-otp/send",
827
+ ...options,
828
+ headers: {
829
+ "Content-Type": "application/json",
830
+ ...options.headers
831
+ }
832
+ });
833
+ var verify = (options) => (options.client ?? client).post({
834
+ url: "/api/auth/{realmId}/login/email-otp/verify",
835
+ ...options,
836
+ headers: {
837
+ "Content-Type": "application/json",
838
+ ...options.headers
839
+ }
840
+ });
841
+ var handlePasskey2FaOptions = (options) => (options.client ?? client).post({
842
+ url: "/api/auth/{realmId}/login/passkey/2fa/options",
843
+ ...options,
844
+ headers: {
845
+ "Content-Type": "application/json",
846
+ ...options.headers
847
+ }
848
+ });
849
+ var handlePasskey2FaVerify = (options) => (options.client ?? client).post({
850
+ url: "/api/auth/{realmId}/login/passkey/2fa/verify",
851
+ ...options,
852
+ headers: {
853
+ "Content-Type": "application/json",
854
+ ...options.headers
855
+ }
856
+ });
857
+ var handlePasskeyOptions = (options) => (options.client ?? client).post({
858
+ url: "/api/auth/{realmId}/login/passkey/options",
859
+ ...options,
860
+ headers: {
861
+ "Content-Type": "application/json",
862
+ ...options.headers
863
+ }
864
+ });
865
+ var handlePasskeyVerify = (options) => (options.client ?? client).post({
866
+ url: "/api/auth/{realmId}/login/passkey/verify",
867
+ ...options,
868
+ headers: {
869
+ "Content-Type": "application/json",
870
+ ...options.headers
871
+ }
872
+ });
873
+ var handleVerifyTotp = (options) => (options.client ?? client).post({
874
+ url: "/api/auth/{realmId}/login/verify-totp",
875
+ ...options,
876
+ headers: {
877
+ "Content-Type": "application/json",
878
+ ...options.headers
879
+ }
880
+ });
881
+ var register = (options) => (options.client ?? client).post({
882
+ url: "/api/auth/{realmId}/register",
883
+ ...options,
884
+ headers: {
885
+ "Content-Type": "application/json",
886
+ ...options.headers
887
+ }
888
+ });
889
+ var resetPasswordRequest = (options) => (options.client ?? client).post({
890
+ url: "/api/auth/{realmId}/reset_password/request",
891
+ ...options,
892
+ headers: {
893
+ "Content-Type": "application/json",
894
+ ...options.headers
895
+ }
896
+ });
897
+ var verifyEmailTrigger = (options) => (options.client ?? client).post({
898
+ url: "/api/auth/{realmId}/verify_email/trigger",
899
+ ...options,
900
+ headers: {
901
+ "Content-Type": "application/json",
902
+ ...options.headers
903
+ }
904
+ });
905
+
906
+ // src/errors.ts
907
+ var HeraldError = class extends Error {
908
+ constructor(init) {
909
+ super(init.message ?? init.kind);
910
+ this.name = "HeraldError";
911
+ this.kind = init.kind;
912
+ this.status = init.status;
913
+ this.code = init.code;
914
+ this.requestId = init.requestId;
915
+ this.details = init.details;
916
+ }
917
+ };
918
+ function kindForStatus(status2) {
919
+ switch (status2) {
920
+ case 400:
921
+ return "validation";
922
+ case 401:
923
+ return "unauthorized";
924
+ case 403:
925
+ return "forbidden";
926
+ case 404:
927
+ return "not-found";
928
+ case 429:
929
+ return "rate-limited";
930
+ default:
931
+ return "api";
932
+ }
933
+ }
934
+ function toHeraldError(error, response) {
935
+ if (!response) {
936
+ return new HeraldError({
937
+ kind: "network",
938
+ message: "Network request failed. For cross-origin integrations, ensure the page origin is pre-registered on the Client App (allowed_origins).",
939
+ details: error
940
+ });
941
+ }
942
+ const body = error ?? {};
943
+ return new HeraldError({
944
+ kind: kindForStatus(response.status),
945
+ status: response.status,
946
+ message: body.message ?? body.error ?? `HTTP ${response.status}`,
947
+ code: body.code,
948
+ requestId: body.requestId ?? void 0,
949
+ details: body.details
950
+ });
951
+ }
952
+
953
+ // src/transport.ts
954
+ var RETRY_HEADER = "X-Herald-Refresh-Retried";
955
+ var REFRESH_PATH = "/api/auth/browser-token/refresh";
956
+ function refreshTokens(client2, deps) {
957
+ const rt = deps.storage.getRefreshToken();
958
+ if (!rt) {
959
+ deps.session.emit({ type: "session-expired", reason: "refresh-failed" });
960
+ return Promise.resolve(null);
961
+ }
962
+ const inFlight = client2.__heraldRefresh;
963
+ if (inFlight) return inFlight;
964
+ const promise = (async () => {
965
+ try {
966
+ const { data, error } = await refresh({ client: client2, body: { refreshToken: rt } });
967
+ if (error || !data) {
968
+ deps.session.emit({ type: "session-expired", reason: "family-revoked" });
969
+ return null;
970
+ }
971
+ deps.accessTokenHolder.set(data.accessToken);
972
+ deps.storage.setRefreshToken(data.refreshToken);
973
+ return data;
974
+ } catch {
975
+ deps.session.emit({ type: "session-expired", reason: "refresh-failed" });
976
+ return null;
977
+ } finally {
978
+ client2.__heraldRefresh = null;
979
+ }
980
+ })();
981
+ client2.__heraldRefresh = promise;
982
+ return promise;
983
+ }
984
+ async function replayRequest(client2, options) {
985
+ const result = await client2.request(options);
986
+ if (!result.response) {
987
+ return new Response(null, { status: 401 });
988
+ }
989
+ const headers = new Headers(result.response.headers);
990
+ const payload = result.data !== void 0 ? result.data : result.error;
991
+ const body = payload !== void 0 && payload !== null ? JSON.stringify(payload) : null;
992
+ return new Response(body, { status: result.response.status, headers });
993
+ }
994
+ function createTransport(deps) {
995
+ const client2 = createClient({ baseUrl: deps.baseUrl });
996
+ client2.interceptors.request.use((request, options) => {
997
+ if (options.url === REFRESH_PATH) {
998
+ return request;
999
+ }
1000
+ const accessToken = deps.accessTokenHolder.get();
1001
+ if (!accessToken) {
1002
+ return request;
1003
+ }
1004
+ const headers = new Headers(request.headers);
1005
+ if (!headers.has("Authorization")) {
1006
+ headers.set("Authorization", `Bearer ${accessToken}`);
1007
+ }
1008
+ return new Request(request, { headers });
1009
+ });
1010
+ client2.interceptors.response.use(
1011
+ async (response, request, options) => {
1012
+ if (response.status !== 401) {
1013
+ return response;
1014
+ }
1015
+ if (options.url === REFRESH_PATH) {
1016
+ return response;
1017
+ }
1018
+ if (request.headers.get(RETRY_HEADER)) {
1019
+ return response;
1020
+ }
1021
+ const refreshed = await refreshTokens(client2, deps) !== null;
1022
+ if (!refreshed) {
1023
+ return response;
1024
+ }
1025
+ const replayOptions = { ...options };
1026
+ const headers = new Headers(
1027
+ replayOptions.headers ?? void 0
1028
+ );
1029
+ headers.set(RETRY_HEADER, "1");
1030
+ replayOptions.headers = headers;
1031
+ return replayRequest(client2, replayOptions);
1032
+ }
1033
+ );
1034
+ return { client: client2, refreshTokens: () => refreshTokens(client2, deps) };
1035
+ }
1036
+ async function resolveOp(promise) {
1037
+ const { data, error, response } = await promise;
1038
+ if (data === void 0) {
1039
+ throw toHeraldError(error, response);
1040
+ }
1041
+ return data;
1042
+ }
1043
+
1044
+ // src/auth.ts
1045
+ function applyTokens(tokens, deps) {
1046
+ deps.accessTokenHolder.set(tokens.accessToken);
1047
+ deps.storage.setRefreshToken(tokens.refreshToken);
1048
+ }
1049
+ function sessionFromLoginSuccess(deps) {
1050
+ return {
1051
+ authenticated: true,
1052
+ realmId: deps.realmId,
1053
+ userId: null,
1054
+ clientAppId: null,
1055
+ clientId: deps.clientId,
1056
+ credentialClass: "custom_user_ui",
1057
+ permissions: [],
1058
+ scopes: []
1059
+ };
1060
+ }
1061
+ function sessionFromStatus(s, deps) {
1062
+ return {
1063
+ authenticated: s.authenticated,
1064
+ realmId: s.realmId ?? deps.realmId,
1065
+ userId: s.userId ?? null,
1066
+ clientAppId: s.clientAppId ?? null,
1067
+ clientId: s.clientId ?? deps.clientId,
1068
+ credentialClass: s.credentialClass ?? null,
1069
+ permissions: s.permissions ?? [],
1070
+ scopes: s.scopes ?? []
1071
+ };
1072
+ }
1073
+ function normalizeAgreements(raw) {
1074
+ if (!Array.isArray(raw)) return [];
1075
+ return raw.map((a) => {
1076
+ const o = a ?? {};
1077
+ return {
1078
+ agreementType: String(o["agreementType"] ?? o["agreement_type"] ?? ""),
1079
+ versionId: String(o["versionId"] ?? o["version_id"] ?? ""),
1080
+ // Display passthrough for host apps that render the consent list.
1081
+ ...a && typeof a === "object" ? { raw: o } : {}
1082
+ };
1083
+ });
1084
+ }
1085
+ function filterSecondFactors(arr) {
1086
+ return arr.filter((f) => f === "totp" || f === "passkey");
1087
+ }
1088
+ function toLoginResult(body, deps) {
1089
+ const b = body ?? null;
1090
+ if (b && typeof b["accessToken"] === "string") {
1091
+ applyTokens(b, deps);
1092
+ const session = sessionFromLoginSuccess(deps);
1093
+ deps.session.emit({ type: "authenticated", session });
1094
+ return { kind: "success", session };
1095
+ }
1096
+ if (b && b["consentRequired"] === true) {
1097
+ return { kind: "consent-required", agreements: normalizeAgreements(b["agreements"]) };
1098
+ }
1099
+ if (b && Array.isArray(b["secondFactors"]) && b["secondFactors"].length > 0) {
1100
+ return {
1101
+ kind: "requires-second-factor",
1102
+ tempToken: String(b["tempToken"] ?? ""),
1103
+ expiresInSeconds: Number(b["expiresInSeconds"] ?? 0),
1104
+ secondFactors: filterSecondFactors(b["secondFactors"]),
1105
+ userId: String(b["userId"] ?? ""),
1106
+ realmId: String(b["realmId"] ?? deps.realmId)
1107
+ };
1108
+ }
1109
+ if (b && typeof b["redirectTo"] === "string") {
1110
+ return { kind: "oauth-redirect", redirectTo: b["redirectTo"] };
1111
+ }
1112
+ throw new HeraldError({ kind: "api", message: "Unrecognized login response shape." });
1113
+ }
1114
+ function createAuth(deps) {
1115
+ const { realmId, client: client2 } = deps;
1116
+ return {
1117
+ async register(payload) {
1118
+ const data = await resolveOp(
1119
+ register({
1120
+ client: client2,
1121
+ path: { realmId },
1122
+ body: {
1123
+ clientId: deps.clientId,
1124
+ email: payload.email,
1125
+ password: payload.password,
1126
+ ...payload.username ? { username: payload.username } : {},
1127
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {}
1128
+ }
1129
+ })
1130
+ );
1131
+ return { message: data.message, verificationRequired: data.verificationRequired };
1132
+ },
1133
+ async triggerVerifyEmail(payload) {
1134
+ const data = await resolveOp(
1135
+ verifyEmailTrigger({
1136
+ client: client2,
1137
+ path: { realmId },
1138
+ body: {
1139
+ clientId: deps.clientId,
1140
+ email: payload.email,
1141
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {}
1142
+ }
1143
+ })
1144
+ );
1145
+ return { message: data.message };
1146
+ },
1147
+ async requestPasswordReset(payload) {
1148
+ const data = await resolveOp(
1149
+ resetPasswordRequest({
1150
+ client: client2,
1151
+ path: { realmId },
1152
+ body: {
1153
+ clientId: deps.clientId,
1154
+ email: payload.email,
1155
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {}
1156
+ }
1157
+ })
1158
+ );
1159
+ return { message: data.message };
1160
+ },
1161
+ async login(payload) {
1162
+ const body = await resolveOp(
1163
+ login({
1164
+ client: client2,
1165
+ path: { realmId },
1166
+ body: {
1167
+ clientId: deps.clientId,
1168
+ password: payload.password,
1169
+ ...payload.username ? { username: payload.username } : {},
1170
+ ...payload.email ? { email: payload.email } : {},
1171
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {},
1172
+ ...payload.agreements ? { agreements: payload.agreements } : {},
1173
+ ...payload.oauthClientId ? { oauthClientId: payload.oauthClientId } : {},
1174
+ ...payload.redirectUri ? { redirectUri: payload.redirectUri } : {},
1175
+ ...payload.state ? { state: payload.state } : {}
1176
+ }
1177
+ })
1178
+ );
1179
+ return toLoginResult(body, deps);
1180
+ },
1181
+ async verifyTotp(payload) {
1182
+ const body = await resolveOp(
1183
+ handleVerifyTotp({
1184
+ client: client2,
1185
+ path: { realmId },
1186
+ body: {
1187
+ tempToken: payload.tempToken,
1188
+ ...payload.code ? { code: payload.code } : {},
1189
+ ...payload.backupCode ? { backupCode: payload.backupCode } : {},
1190
+ ...payload.agreements ? { agreements: payload.agreements } : {}
1191
+ }
1192
+ })
1193
+ );
1194
+ return toLoginResult(body, deps);
1195
+ },
1196
+ passkey: {
1197
+ async loginBegin(payload) {
1198
+ const data = payload.tempToken !== void 0 ? await resolveOp(
1199
+ handlePasskey2FaOptions({
1200
+ client: client2,
1201
+ path: { realmId },
1202
+ body: { tempToken: payload.tempToken }
1203
+ })
1204
+ ) : await resolveOp(
1205
+ handlePasskeyOptions({
1206
+ client: client2,
1207
+ path: { realmId },
1208
+ body: {
1209
+ clientId: deps.clientId,
1210
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {},
1211
+ ...payload.oauth ? { oauth: payload.oauth } : {}
1212
+ }
1213
+ })
1214
+ );
1215
+ return { authToken: data.authToken, options: data.options };
1216
+ },
1217
+ async loginFinish(payload) {
1218
+ const body = await resolveOp(
1219
+ payload.tempToken !== void 0 ? handlePasskey2FaVerify({
1220
+ client: client2,
1221
+ path: { realmId },
1222
+ body: {
1223
+ tempToken: payload.tempToken,
1224
+ authToken: payload.authToken,
1225
+ assertion: payload.assertion,
1226
+ ...payload.agreements ? { agreements: payload.agreements } : {}
1227
+ }
1228
+ }) : handlePasskeyVerify({
1229
+ client: client2,
1230
+ path: { realmId },
1231
+ body: {
1232
+ authToken: payload.authToken,
1233
+ assertion: payload.assertion,
1234
+ ...payload.agreements ? { agreements: payload.agreements } : {}
1235
+ }
1236
+ })
1237
+ );
1238
+ return toLoginResult(body, deps);
1239
+ }
1240
+ },
1241
+ loginWithEmailOtp: {
1242
+ /**
1243
+ * Send a passwordless login code. The two 409 control-flow outcomes
1244
+ * (DEC-js-sdk-014) — `consent_required` (auto-register consent gate) and
1245
+ * `email_not_registered` (auto-register off) — resolve as
1246
+ * `{ kind: 'conflict' }` instead of throwing, mirroring the multi-branch
1247
+ * normalization `login()` applies to its 200 bodies. All other HTTP
1248
+ * failures throw `HeraldError`.
1249
+ */
1250
+ async send(payload) {
1251
+ const { data, error, response } = await send({
1252
+ client: client2,
1253
+ path: { realmId },
1254
+ body: {
1255
+ clientId: deps.clientId,
1256
+ email: payload.email,
1257
+ ...payload.turnstileToken ? { turnstileToken: payload.turnstileToken } : {},
1258
+ ...payload.agreements ? { agreements: payload.agreements } : {}
1259
+ }
1260
+ });
1261
+ if (data) {
1262
+ return { kind: "sent", message: data.message, expiresInSeconds: data.expiresInSeconds };
1263
+ }
1264
+ const body = error ?? {};
1265
+ const code = body["code"];
1266
+ if (response?.status === 409 && (code === "consent_required" || code === "email_not_registered")) {
1267
+ return {
1268
+ kind: "conflict",
1269
+ code: String(code),
1270
+ message: String(body["message"] ?? ""),
1271
+ consentRequired: body["consentRequired"] === true,
1272
+ agreements: normalizeAgreements(body["agreements"])
1273
+ };
1274
+ }
1275
+ throw toHeraldError(error, response);
1276
+ },
1277
+ async verify(payload) {
1278
+ const body = await resolveOp(
1279
+ verify({
1280
+ client: client2,
1281
+ path: { realmId },
1282
+ body: {
1283
+ clientId: deps.clientId,
1284
+ email: payload.email,
1285
+ code: payload.code,
1286
+ ...payload.agreements ? { agreements: payload.agreements } : {}
1287
+ }
1288
+ })
1289
+ );
1290
+ return toLoginResult(body, deps);
1291
+ }
1292
+ },
1293
+ async getStatus() {
1294
+ const data = await resolveOp(status({ client: client2 }));
1295
+ deps.session.emit({ type: "authenticated", session: sessionFromStatus(data, deps) });
1296
+ return data;
1297
+ },
1298
+ /**
1299
+ * Explicitly refresh the Bearer token family (startup restore, proactive
1300
+ * refresh). Single-flight: concurrent calls share one HTTP request with the
1301
+ * 401 auto-refresh interceptor. On success both the in-memory access token
1302
+ * and the stored refresh token are rotated.
1303
+ *
1304
+ * @throws {HeraldError} `kind: 'session-expired'` when no refresh token is
1305
+ * stored or the refresh failed (reuse / expiry / family revocation); a
1306
+ * `session-expired` event is emitted either way.
1307
+ */
1308
+ async refresh() {
1309
+ const tokens = await deps.refreshTokens();
1310
+ if (!tokens) {
1311
+ throw new HeraldError({
1312
+ kind: "session-expired",
1313
+ message: "Session refresh failed; sign in again."
1314
+ });
1315
+ }
1316
+ return tokens;
1317
+ },
1318
+ async logout() {
1319
+ const data = await resolveOp(logout({ client: client2 }));
1320
+ deps.accessTokenHolder.clear();
1321
+ deps.storage.setRefreshToken(null);
1322
+ deps.session.emit({ type: "logged-out" });
1323
+ return { message: data?.message ?? "Logged out" };
1324
+ }
1325
+ };
1326
+ }
1327
+
1328
+ // src/session.ts
1329
+ function createAccessTokenHolder() {
1330
+ let token = null;
1331
+ return {
1332
+ get: () => token,
1333
+ set: (t) => {
1334
+ token = t;
1335
+ },
1336
+ clear: () => {
1337
+ token = null;
1338
+ }
1339
+ };
1340
+ }
1341
+ var UNAUTHENTICATED_SESSION = {
1342
+ authenticated: false,
1343
+ realmId: null,
1344
+ userId: null,
1345
+ clientAppId: null,
1346
+ clientId: null,
1347
+ credentialClass: null,
1348
+ permissions: [],
1349
+ scopes: []
1350
+ };
1351
+ function createSessionStore(onChange) {
1352
+ let session = { ...UNAUTHENTICATED_SESSION };
1353
+ const listeners = /* @__PURE__ */ new Set();
1354
+ return {
1355
+ getSession: () => session,
1356
+ setSession: (s) => {
1357
+ session = s ?? { ...UNAUTHENTICATED_SESSION };
1358
+ },
1359
+ subscribe: (fn) => {
1360
+ listeners.add(fn);
1361
+ return () => {
1362
+ listeners.delete(fn);
1363
+ };
1364
+ },
1365
+ emit: (event) => {
1366
+ if (event.type === "authenticated") {
1367
+ session = event.session;
1368
+ } else if (event.type === "session-expired" || event.type === "logged-out") {
1369
+ session = { ...UNAUTHENTICATED_SESSION };
1370
+ }
1371
+ for (const fn of listeners) {
1372
+ fn(event);
1373
+ }
1374
+ onChange?.(event);
1375
+ }
1376
+ };
1377
+ }
1378
+
1379
+ // src/storage.ts
1380
+ function memoryStorage() {
1381
+ let token = null;
1382
+ return {
1383
+ getRefreshToken: () => token,
1384
+ setRefreshToken: (t) => {
1385
+ token = t;
1386
+ }
1387
+ };
1388
+ }
1389
+ function localStorageStorage(key) {
1390
+ if (typeof localStorage === "undefined" || localStorage === null) {
1391
+ throw new HeraldError({
1392
+ kind: "ssr-no-storage",
1393
+ message: "localStorage is unavailable in this environment. Inject a TokenStorage adapter via `storage`, or use memoryStorage()."
1394
+ });
1395
+ }
1396
+ return {
1397
+ getRefreshToken: () => localStorage.getItem(key),
1398
+ setRefreshToken: (t) => {
1399
+ if (t === null) {
1400
+ localStorage.removeItem(key);
1401
+ } else {
1402
+ localStorage.setItem(key, t);
1403
+ }
1404
+ }
1405
+ };
1406
+ }
1407
+
1408
+ // src/config.ts
1409
+ function createHeraldClient(config) {
1410
+ const hasLocalStorage = typeof localStorage !== "undefined" && localStorage !== null;
1411
+ let storage = config.storage;
1412
+ if (!storage) {
1413
+ if (!hasLocalStorage) {
1414
+ throw new HeraldError({
1415
+ kind: "ssr-no-storage",
1416
+ message: "No TokenStorage adapter was provided and localStorage is unavailable (SSR/Node). Inject a `storage` adapter or use memoryStorage()."
1417
+ });
1418
+ }
1419
+ storage = localStorageStorage(config.storageKey ?? "herald.refreshToken");
1420
+ }
1421
+ const accessTokenHolder = createAccessTokenHolder();
1422
+ const session = createSessionStore(config.onSessionChange);
1423
+ const transport = createTransport({
1424
+ baseUrl: config.baseUrl,
1425
+ accessTokenHolder,
1426
+ storage,
1427
+ session
1428
+ });
1429
+ const authDeps = {
1430
+ realmId: config.realmId,
1431
+ clientId: config.clientId,
1432
+ client: transport.client,
1433
+ accessTokenHolder,
1434
+ storage,
1435
+ session,
1436
+ refreshTokens: transport.refreshTokens
1437
+ };
1438
+ const auth = createAuth(authDeps);
1439
+ return {
1440
+ ...auth,
1441
+ storage,
1442
+ session: {
1443
+ getSession: () => session.getSession(),
1444
+ subscribe: (listener) => session.subscribe(listener)
1445
+ },
1446
+ tokens: {
1447
+ getAccessToken: () => accessTokenHolder.get(),
1448
+ setTokens: (tokens) => {
1449
+ accessTokenHolder.set(tokens.accessToken);
1450
+ storage.setRefreshToken(tokens.refreshToken);
1451
+ if (tokens.clientId !== void 0) {
1452
+ authDeps.clientId = tokens.clientId;
1453
+ }
1454
+ },
1455
+ clear: () => {
1456
+ accessTokenHolder.clear();
1457
+ storage.setRefreshToken(null);
1458
+ },
1459
+ bindClientId: (clientId) => {
1460
+ authDeps.clientId = clientId;
1461
+ }
1462
+ }
1463
+ };
1464
+ }
1465
+
1466
+ // src/webauthn.ts
1467
+ function base64urlToBuffer(input) {
1468
+ const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
1469
+ const padded = b64 + "===".slice((b64.length + 3) % 4);
1470
+ const binary = atob(padded);
1471
+ const bytes = new Uint8Array(binary.length);
1472
+ for (let i = 0; i < binary.length; i += 1) {
1473
+ bytes[i] = binary.charCodeAt(i);
1474
+ }
1475
+ return bytes.buffer;
1476
+ }
1477
+ function bufferToBase64url(buffer) {
1478
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
1479
+ let binary = "";
1480
+ for (let i = 0; i < bytes.length; i += 1) {
1481
+ binary += String.fromCharCode(bytes[i] ?? 0);
1482
+ }
1483
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/[=]/g, "");
1484
+ }
1485
+ async function performPasskeyAssertion(options) {
1486
+ if (typeof navigator === "undefined" || !navigator.credentials?.get) {
1487
+ throw new Error("WebAuthn (navigator.credentials.get) is not available in this environment.");
1488
+ }
1489
+ const publicKey = {
1490
+ challenge: base64urlToBuffer(options.challenge),
1491
+ ...options.rpId ? { rpId: options.rpId } : {},
1492
+ ...options.timeout !== void 0 ? { timeout: options.timeout } : {},
1493
+ ...options.userVerification ? { userVerification: options.userVerification } : {},
1494
+ ...options.allowCredentials ? {
1495
+ allowCredentials: options.allowCredentials.map((c) => ({
1496
+ type: "public-key",
1497
+ id: base64urlToBuffer(c.id),
1498
+ ...c.transports ? { transports: c.transports } : {}
1499
+ }))
1500
+ } : {}
1501
+ };
1502
+ const credential = await navigator.credentials.get({ publicKey });
1503
+ if (!credential) {
1504
+ throw new Error("Passkey assertion returned no credential.");
1505
+ }
1506
+ const response = credential.response;
1507
+ const result = {
1508
+ id: credential.id,
1509
+ rawId: bufferToBase64url(credential.rawId),
1510
+ type: "public-key",
1511
+ response: {
1512
+ authenticatorData: bufferToBase64url(response.authenticatorData),
1513
+ clientDataJSON: bufferToBase64url(response.clientDataJSON),
1514
+ signature: bufferToBase64url(response.signature),
1515
+ ...response.userHandle ? { userHandle: bufferToBase64url(response.userHandle) } : {}
1516
+ }
1517
+ };
1518
+ if (typeof credential.getClientExtensionResults === "function") {
1519
+ result.clientExtensionResults = credential.getClientExtensionResults();
1520
+ }
1521
+ return result;
1522
+ }
1523
+
1524
+ export { HeraldError, createHeraldClient, localStorageStorage, memoryStorage, performPasskeyAssertion };
1525
+ //# sourceMappingURL=index.js.map
1526
+ //# sourceMappingURL=index.js.map