@authsignal/browser 0.0.21 → 0.1.0

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.mjs CHANGED
@@ -3362,18 +3362,1112 @@ var PopupHandler = /** @class */ (function () {
3362
3362
  return PopupHandler;
3363
3363
  }());
3364
3364
 
3365
+ /******************************************************************************
3366
+ Copyright (c) Microsoft Corporation.
3367
+
3368
+ Permission to use, copy, modify, and/or distribute this software for any
3369
+ purpose with or without fee is hereby granted.
3370
+
3371
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
3372
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
3373
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
3374
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
3375
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3376
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3377
+ PERFORMANCE OF THIS SOFTWARE.
3378
+ ***************************************************************************** */
3379
+
3380
+ function __rest(s, e) {
3381
+ var t = {};
3382
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
3383
+ t[p] = s[p];
3384
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
3385
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
3386
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
3387
+ t[p[i]] = s[p[i]];
3388
+ }
3389
+ return t;
3390
+ }
3391
+
3392
+ function __awaiter(thisArg, _arguments, P, generator) {
3393
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3394
+ return new (P || (P = Promise))(function (resolve, reject) {
3395
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3396
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3397
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
3398
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3399
+ });
3400
+ }
3401
+
3402
+ function __generator(thisArg, body) {
3403
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3404
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
3405
+ function verb(n) { return function (v) { return step([n, v]); }; }
3406
+ function step(op) {
3407
+ if (f) throw new TypeError("Generator is already executing.");
3408
+ while (_) try {
3409
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3410
+ if (y = 0, t) op = [op[0] & 2, t.value];
3411
+ switch (op[0]) {
3412
+ case 0: case 1: t = op; break;
3413
+ case 4: _.label++; return { value: op[1], done: false };
3414
+ case 5: _.label++; y = op[1]; op = [0]; continue;
3415
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
3416
+ default:
3417
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
3418
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
3419
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
3420
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
3421
+ if (t[2]) _.ops.pop();
3422
+ _.trys.pop(); continue;
3423
+ }
3424
+ op = body.call(thisArg, _);
3425
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
3426
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
3427
+ }
3428
+ }
3429
+
3430
+ /* [@simplewebauthn/browser@7.2.0] */
3431
+ function utf8StringToBuffer(value) {
3432
+ return new TextEncoder().encode(value);
3433
+ }
3434
+
3435
+ function bufferToBase64URLString(buffer) {
3436
+ const bytes = new Uint8Array(buffer);
3437
+ let str = '';
3438
+ for (const charCode of bytes) {
3439
+ str += String.fromCharCode(charCode);
3440
+ }
3441
+ const base64String = btoa(str);
3442
+ return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
3443
+ }
3444
+
3445
+ function base64URLStringToBuffer(base64URLString) {
3446
+ const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');
3447
+ const padLength = (4 - (base64.length % 4)) % 4;
3448
+ const padded = base64.padEnd(base64.length + padLength, '=');
3449
+ const binary = atob(padded);
3450
+ const buffer = new ArrayBuffer(binary.length);
3451
+ const bytes = new Uint8Array(buffer);
3452
+ for (let i = 0; i < binary.length; i++) {
3453
+ bytes[i] = binary.charCodeAt(i);
3454
+ }
3455
+ return buffer;
3456
+ }
3457
+
3458
+ function browserSupportsWebAuthn() {
3459
+ return (window?.PublicKeyCredential !== undefined && typeof window.PublicKeyCredential === 'function');
3460
+ }
3461
+
3462
+ function toPublicKeyCredentialDescriptor(descriptor) {
3463
+ const { id } = descriptor;
3464
+ return {
3465
+ ...descriptor,
3466
+ id: base64URLStringToBuffer(id),
3467
+ transports: descriptor.transports,
3468
+ };
3469
+ }
3470
+
3471
+ function isValidDomain(hostname) {
3472
+ return (hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
3473
+ }
3474
+
3475
+ class WebAuthnError extends Error {
3476
+ code;
3477
+ constructor({ message, code, cause, name, }) {
3478
+ super(message, { cause });
3479
+ this.name = name ?? cause.name;
3480
+ this.code = code;
3481
+ }
3482
+ }
3483
+
3484
+ function identifyRegistrationError({ error, options, }) {
3485
+ const { publicKey } = options;
3486
+ if (!publicKey) {
3487
+ throw Error('options was missing required publicKey property');
3488
+ }
3489
+ if (error.name === 'AbortError') {
3490
+ if (options.signal instanceof AbortSignal) {
3491
+ return new WebAuthnError({
3492
+ message: 'Registration ceremony was sent an abort signal',
3493
+ code: 'ERROR_CEREMONY_ABORTED',
3494
+ cause: error,
3495
+ });
3496
+ }
3497
+ }
3498
+ else if (error.name === 'ConstraintError') {
3499
+ if (publicKey.authenticatorSelection?.requireResidentKey === true) {
3500
+ return new WebAuthnError({
3501
+ message: 'Discoverable credentials were required but no available authenticator supported it',
3502
+ code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',
3503
+ cause: error,
3504
+ });
3505
+ }
3506
+ else if (publicKey.authenticatorSelection?.userVerification === 'required') {
3507
+ return new WebAuthnError({
3508
+ message: 'User verification was required but no available authenticator supported it',
3509
+ code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',
3510
+ cause: error,
3511
+ });
3512
+ }
3513
+ }
3514
+ else if (error.name === 'InvalidStateError') {
3515
+ return new WebAuthnError({
3516
+ message: 'The authenticator was previously registered',
3517
+ code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
3518
+ cause: error
3519
+ });
3520
+ }
3521
+ else if (error.name === 'NotAllowedError') {
3522
+ return new WebAuthnError({
3523
+ message: error.message,
3524
+ code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
3525
+ cause: error,
3526
+ });
3527
+ }
3528
+ else if (error.name === 'NotSupportedError') {
3529
+ const validPubKeyCredParams = publicKey.pubKeyCredParams.filter(param => param.type === 'public-key');
3530
+ if (validPubKeyCredParams.length === 0) {
3531
+ return new WebAuthnError({
3532
+ message: 'No entry in pubKeyCredParams was of type "public-key"',
3533
+ code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',
3534
+ cause: error,
3535
+ });
3536
+ }
3537
+ return new WebAuthnError({
3538
+ message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',
3539
+ code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',
3540
+ cause: error,
3541
+ });
3542
+ }
3543
+ else if (error.name === 'SecurityError') {
3544
+ const effectiveDomain = window.location.hostname;
3545
+ if (!isValidDomain(effectiveDomain)) {
3546
+ return new WebAuthnError({
3547
+ message: `${window.location.hostname} is an invalid domain`,
3548
+ code: 'ERROR_INVALID_DOMAIN',
3549
+ cause: error
3550
+ });
3551
+ }
3552
+ else if (publicKey.rp.id !== effectiveDomain) {
3553
+ return new WebAuthnError({
3554
+ message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
3555
+ code: 'ERROR_INVALID_RP_ID',
3556
+ cause: error,
3557
+ });
3558
+ }
3559
+ }
3560
+ else if (error.name === 'TypeError') {
3561
+ if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
3562
+ return new WebAuthnError({
3563
+ message: 'User ID was not between 1 and 64 characters',
3564
+ code: 'ERROR_INVALID_USER_ID_LENGTH',
3565
+ cause: error,
3566
+ });
3567
+ }
3568
+ }
3569
+ else if (error.name === 'UnknownError') {
3570
+ return new WebAuthnError({
3571
+ message: 'The authenticator was unable to process the specified options, or could not create a new credential',
3572
+ code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
3573
+ cause: error,
3574
+ });
3575
+ }
3576
+ return error;
3577
+ }
3578
+
3579
+ class WebAuthnAbortService {
3580
+ controller;
3581
+ createNewAbortSignal() {
3582
+ if (this.controller) {
3583
+ const abortError = new Error('Cancelling existing WebAuthn API call for new one');
3584
+ abortError.name = 'AbortError';
3585
+ this.controller.abort(abortError);
3586
+ }
3587
+ const newController = new AbortController();
3588
+ this.controller = newController;
3589
+ return newController.signal;
3590
+ }
3591
+ }
3592
+ const webauthnAbortService = new WebAuthnAbortService();
3593
+
3594
+ const attachments = ['cross-platform', 'platform'];
3595
+ function toAuthenticatorAttachment(attachment) {
3596
+ if (!attachment) {
3597
+ return;
3598
+ }
3599
+ if (attachments.indexOf(attachment) < 0) {
3600
+ return;
3601
+ }
3602
+ return attachment;
3603
+ }
3604
+
3605
+ async function startRegistration(creationOptionsJSON) {
3606
+ if (!browserSupportsWebAuthn()) {
3607
+ throw new Error('WebAuthn is not supported in this browser');
3608
+ }
3609
+ const publicKey = {
3610
+ ...creationOptionsJSON,
3611
+ challenge: base64URLStringToBuffer(creationOptionsJSON.challenge),
3612
+ user: {
3613
+ ...creationOptionsJSON.user,
3614
+ id: utf8StringToBuffer(creationOptionsJSON.user.id),
3615
+ },
3616
+ excludeCredentials: creationOptionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),
3617
+ };
3618
+ const options = { publicKey };
3619
+ options.signal = webauthnAbortService.createNewAbortSignal();
3620
+ let credential;
3621
+ try {
3622
+ credential = (await navigator.credentials.create(options));
3623
+ }
3624
+ catch (err) {
3625
+ throw identifyRegistrationError({ error: err, options });
3626
+ }
3627
+ if (!credential) {
3628
+ throw new Error('Registration was not completed');
3629
+ }
3630
+ const { id, rawId, response, type } = credential;
3631
+ let transports = undefined;
3632
+ if (typeof response.getTransports === 'function') {
3633
+ transports = response.getTransports();
3634
+ }
3635
+ return {
3636
+ id,
3637
+ rawId: bufferToBase64URLString(rawId),
3638
+ response: {
3639
+ attestationObject: bufferToBase64URLString(response.attestationObject),
3640
+ clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
3641
+ transports,
3642
+ },
3643
+ type,
3644
+ clientExtensionResults: credential.getClientExtensionResults(),
3645
+ authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
3646
+ };
3647
+ }
3648
+
3649
+ function bufferToUTF8String(value) {
3650
+ return new TextDecoder('utf-8').decode(value);
3651
+ }
3652
+
3653
+ async function browserSupportsWebAuthnAutofill() {
3654
+ const globalPublicKeyCredential = window.PublicKeyCredential;
3655
+ return (globalPublicKeyCredential.isConditionalMediationAvailable !== undefined &&
3656
+ globalPublicKeyCredential.isConditionalMediationAvailable());
3657
+ }
3658
+
3659
+ function identifyAuthenticationError({ error, options, }) {
3660
+ const { publicKey } = options;
3661
+ if (!publicKey) {
3662
+ throw Error('options was missing required publicKey property');
3663
+ }
3664
+ if (error.name === 'AbortError') {
3665
+ if (options.signal instanceof AbortSignal) {
3666
+ return new WebAuthnError({
3667
+ message: 'Authentication ceremony was sent an abort signal',
3668
+ code: 'ERROR_CEREMONY_ABORTED',
3669
+ cause: error,
3670
+ });
3671
+ }
3672
+ }
3673
+ else if (error.name === 'NotAllowedError') {
3674
+ return new WebAuthnError({
3675
+ message: error.message,
3676
+ code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
3677
+ cause: error,
3678
+ });
3679
+ }
3680
+ else if (error.name === 'SecurityError') {
3681
+ const effectiveDomain = window.location.hostname;
3682
+ if (!isValidDomain(effectiveDomain)) {
3683
+ return new WebAuthnError({
3684
+ message: `${window.location.hostname} is an invalid domain`,
3685
+ code: 'ERROR_INVALID_DOMAIN',
3686
+ cause: error,
3687
+ });
3688
+ }
3689
+ else if (publicKey.rpId !== effectiveDomain) {
3690
+ return new WebAuthnError({
3691
+ message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
3692
+ code: 'ERROR_INVALID_RP_ID',
3693
+ cause: error,
3694
+ });
3695
+ }
3696
+ }
3697
+ else if (error.name === 'UnknownError') {
3698
+ return new WebAuthnError({
3699
+ message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',
3700
+ code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
3701
+ cause: error,
3702
+ });
3703
+ }
3704
+ return error;
3705
+ }
3706
+
3707
+ async function startAuthentication(requestOptionsJSON, useBrowserAutofill = false) {
3708
+ if (!browserSupportsWebAuthn()) {
3709
+ throw new Error('WebAuthn is not supported in this browser');
3710
+ }
3711
+ let allowCredentials;
3712
+ if (requestOptionsJSON.allowCredentials?.length !== 0) {
3713
+ allowCredentials = requestOptionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);
3714
+ }
3715
+ const publicKey = {
3716
+ ...requestOptionsJSON,
3717
+ challenge: base64URLStringToBuffer(requestOptionsJSON.challenge),
3718
+ allowCredentials,
3719
+ };
3720
+ const options = {};
3721
+ if (useBrowserAutofill) {
3722
+ if (!(await browserSupportsWebAuthnAutofill())) {
3723
+ throw Error('Browser does not support WebAuthn autofill');
3724
+ }
3725
+ const eligibleInputs = document.querySelectorAll("input[autocomplete*='webauthn']");
3726
+ if (eligibleInputs.length < 1) {
3727
+ throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');
3728
+ }
3729
+ options.mediation = 'conditional';
3730
+ publicKey.allowCredentials = [];
3731
+ }
3732
+ options.publicKey = publicKey;
3733
+ options.signal = webauthnAbortService.createNewAbortSignal();
3734
+ let credential;
3735
+ try {
3736
+ credential = (await navigator.credentials.get(options));
3737
+ }
3738
+ catch (err) {
3739
+ throw identifyAuthenticationError({ error: err, options });
3740
+ }
3741
+ if (!credential) {
3742
+ throw new Error('Authentication was not completed');
3743
+ }
3744
+ const { id, rawId, response, type } = credential;
3745
+ let userHandle = undefined;
3746
+ if (response.userHandle) {
3747
+ userHandle = bufferToUTF8String(response.userHandle);
3748
+ }
3749
+ return {
3750
+ id,
3751
+ rawId: bufferToBase64URLString(rawId),
3752
+ response: {
3753
+ authenticatorData: bufferToBase64URLString(response.authenticatorData),
3754
+ clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
3755
+ signature: bufferToBase64URLString(response.signature),
3756
+ userHandle,
3757
+ },
3758
+ type,
3759
+ clientExtensionResults: credential.getClientExtensionResults(),
3760
+ authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
3761
+ };
3762
+ }
3763
+
3764
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
3765
+ class HTTPError extends Error {
3766
+ constructor(response, request, options) {
3767
+ const code = (response.status || response.status === 0) ? response.status : '';
3768
+ const title = response.statusText || '';
3769
+ const status = `${code} ${title}`.trim();
3770
+ const reason = status ? `status code ${status}` : 'an unknown error';
3771
+ super(`Request failed with ${reason}`);
3772
+ Object.defineProperty(this, "response", {
3773
+ enumerable: true,
3774
+ configurable: true,
3775
+ writable: true,
3776
+ value: void 0
3777
+ });
3778
+ Object.defineProperty(this, "request", {
3779
+ enumerable: true,
3780
+ configurable: true,
3781
+ writable: true,
3782
+ value: void 0
3783
+ });
3784
+ Object.defineProperty(this, "options", {
3785
+ enumerable: true,
3786
+ configurable: true,
3787
+ writable: true,
3788
+ value: void 0
3789
+ });
3790
+ this.name = 'HTTPError';
3791
+ this.response = response;
3792
+ this.request = request;
3793
+ this.options = options;
3794
+ }
3795
+ }
3796
+
3797
+ class TimeoutError extends Error {
3798
+ constructor(request) {
3799
+ super('Request timed out');
3800
+ Object.defineProperty(this, "request", {
3801
+ enumerable: true,
3802
+ configurable: true,
3803
+ writable: true,
3804
+ value: void 0
3805
+ });
3806
+ this.name = 'TimeoutError';
3807
+ this.request = request;
3808
+ }
3809
+ }
3810
+
3811
+ // eslint-disable-next-line @typescript-eslint/ban-types
3812
+ const isObject = (value) => value !== null && typeof value === 'object';
3813
+
3814
+ const validateAndMerge = (...sources) => {
3815
+ for (const source of sources) {
3816
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
3817
+ throw new TypeError('The `options` argument must be an object');
3818
+ }
3819
+ }
3820
+ return deepMerge({}, ...sources);
3821
+ };
3822
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
3823
+ const result = new globalThis.Headers(source1);
3824
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
3825
+ const source = new globalThis.Headers(source2);
3826
+ for (const [key, value] of source.entries()) {
3827
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
3828
+ result.delete(key);
3829
+ }
3830
+ else {
3831
+ result.set(key, value);
3832
+ }
3833
+ }
3834
+ return result;
3835
+ };
3836
+ // TODO: Make this strongly-typed (no `any`).
3837
+ const deepMerge = (...sources) => {
3838
+ let returnValue = {};
3839
+ let headers = {};
3840
+ for (const source of sources) {
3841
+ if (Array.isArray(source)) {
3842
+ if (!Array.isArray(returnValue)) {
3843
+ returnValue = [];
3844
+ }
3845
+ returnValue = [...returnValue, ...source];
3846
+ }
3847
+ else if (isObject(source)) {
3848
+ for (let [key, value] of Object.entries(source)) {
3849
+ if (isObject(value) && key in returnValue) {
3850
+ value = deepMerge(returnValue[key], value);
3851
+ }
3852
+ returnValue = { ...returnValue, [key]: value };
3853
+ }
3854
+ if (isObject(source.headers)) {
3855
+ headers = mergeHeaders(headers, source.headers);
3856
+ returnValue.headers = headers;
3857
+ }
3858
+ }
3859
+ }
3860
+ return returnValue;
3861
+ };
3862
+
3863
+ const supportsRequestStreams = (() => {
3864
+ let duplexAccessed = false;
3865
+ let hasContentType = false;
3866
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
3867
+ const supportsRequest = typeof globalThis.Request === 'function';
3868
+ if (supportsReadableStream && supportsRequest) {
3869
+ hasContentType = new globalThis.Request('https://a.com', {
3870
+ body: new globalThis.ReadableStream(),
3871
+ method: 'POST',
3872
+ // @ts-expect-error - Types are outdated.
3873
+ get duplex() {
3874
+ duplexAccessed = true;
3875
+ return 'half';
3876
+ },
3877
+ }).headers.has('Content-Type');
3878
+ }
3879
+ return duplexAccessed && !hasContentType;
3880
+ })();
3881
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
3882
+ const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
3883
+ const supportsFormData = typeof globalThis.FormData === 'function';
3884
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
3885
+ const responseTypes = {
3886
+ json: 'application/json',
3887
+ text: 'text/*',
3888
+ formData: 'multipart/form-data',
3889
+ arrayBuffer: '*/*',
3890
+ blob: '*/*',
3891
+ };
3892
+ // The maximum value of a 32bit int (see issue #117)
3893
+ const maxSafeTimeout = 2147483647;
3894
+ const stop = Symbol('stop');
3895
+
3896
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
3897
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
3898
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
3899
+ const retryAfterStatusCodes = [413, 429, 503];
3900
+ const defaultRetryOptions = {
3901
+ limit: 2,
3902
+ methods: retryMethods,
3903
+ statusCodes: retryStatusCodes,
3904
+ afterStatusCodes: retryAfterStatusCodes,
3905
+ maxRetryAfter: Number.POSITIVE_INFINITY,
3906
+ backoffLimit: Number.POSITIVE_INFINITY,
3907
+ };
3908
+ const normalizeRetryOptions = (retry = {}) => {
3909
+ if (typeof retry === 'number') {
3910
+ return {
3911
+ ...defaultRetryOptions,
3912
+ limit: retry,
3913
+ };
3914
+ }
3915
+ if (retry.methods && !Array.isArray(retry.methods)) {
3916
+ throw new Error('retry.methods must be an array');
3917
+ }
3918
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
3919
+ throw new Error('retry.statusCodes must be an array');
3920
+ }
3921
+ return {
3922
+ ...defaultRetryOptions,
3923
+ ...retry,
3924
+ afterStatusCodes: retryAfterStatusCodes,
3925
+ };
3926
+ };
3927
+
3928
+ // `Promise.race()` workaround (#91)
3929
+ async function timeout(request, abortController, options) {
3930
+ return new Promise((resolve, reject) => {
3931
+ const timeoutId = setTimeout(() => {
3932
+ if (abortController) {
3933
+ abortController.abort();
3934
+ }
3935
+ reject(new TimeoutError(request));
3936
+ }, options.timeout);
3937
+ void options
3938
+ .fetch(request)
3939
+ .then(resolve)
3940
+ .catch(reject)
3941
+ .then(() => {
3942
+ clearTimeout(timeoutId);
3943
+ });
3944
+ });
3945
+ }
3946
+
3947
+ // DOMException is supported on most modern browsers and Node.js 18+.
3948
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException#browser_compatibility
3949
+ const isDomExceptionSupported = Boolean(globalThis.DOMException);
3950
+ // TODO: When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)
3951
+ function composeAbortError(signal) {
3952
+ /*
3953
+ NOTE: Use DomException with AbortError name as specified in MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)
3954
+ > When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.
3955
+ */
3956
+ if (isDomExceptionSupported) {
3957
+ return new DOMException(signal?.reason ?? 'The operation was aborted.', 'AbortError');
3958
+ }
3959
+ // DOMException not supported. Fall back to use of error and override name.
3960
+ const error = new Error(signal?.reason ?? 'The operation was aborted.');
3961
+ error.name = 'AbortError';
3962
+ return error;
3963
+ }
3964
+
3965
+ // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
3966
+ async function delay(ms, { signal }) {
3967
+ return new Promise((resolve, reject) => {
3968
+ if (signal) {
3969
+ if (signal.aborted) {
3970
+ reject(composeAbortError(signal));
3971
+ return;
3972
+ }
3973
+ signal.addEventListener('abort', handleAbort, { once: true });
3974
+ }
3975
+ function handleAbort() {
3976
+ reject(composeAbortError(signal));
3977
+ clearTimeout(timeoutId);
3978
+ }
3979
+ const timeoutId = setTimeout(() => {
3980
+ signal?.removeEventListener('abort', handleAbort);
3981
+ resolve();
3982
+ }, ms);
3983
+ });
3984
+ }
3985
+
3986
+ class Ky {
3987
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
3988
+ static create(input, options) {
3989
+ const ky = new Ky(input, options);
3990
+ const fn = async () => {
3991
+ if (ky._options.timeout > maxSafeTimeout) {
3992
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
3993
+ }
3994
+ // Delay the fetch so that body method shortcuts can set the Accept header
3995
+ await Promise.resolve();
3996
+ let response = await ky._fetch();
3997
+ for (const hook of ky._options.hooks.afterResponse) {
3998
+ // eslint-disable-next-line no-await-in-loop
3999
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
4000
+ if (modifiedResponse instanceof globalThis.Response) {
4001
+ response = modifiedResponse;
4002
+ }
4003
+ }
4004
+ ky._decorateResponse(response);
4005
+ if (!response.ok && ky._options.throwHttpErrors) {
4006
+ let error = new HTTPError(response, ky.request, ky._options);
4007
+ for (const hook of ky._options.hooks.beforeError) {
4008
+ // eslint-disable-next-line no-await-in-loop
4009
+ error = await hook(error);
4010
+ }
4011
+ throw error;
4012
+ }
4013
+ // If `onDownloadProgress` is passed, it uses the stream API internally
4014
+ /* istanbul ignore next */
4015
+ if (ky._options.onDownloadProgress) {
4016
+ if (typeof ky._options.onDownloadProgress !== 'function') {
4017
+ throw new TypeError('The `onDownloadProgress` option must be a function');
4018
+ }
4019
+ if (!supportsResponseStreams) {
4020
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
4021
+ }
4022
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
4023
+ }
4024
+ return response;
4025
+ };
4026
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
4027
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
4028
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
4029
+ result[type] = async () => {
4030
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
4031
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
4032
+ const awaitedResult = await result;
4033
+ const response = awaitedResult.clone();
4034
+ if (type === 'json') {
4035
+ if (response.status === 204) {
4036
+ return '';
4037
+ }
4038
+ const arrayBuffer = await response.clone().arrayBuffer();
4039
+ const responseSize = arrayBuffer.byteLength;
4040
+ if (responseSize === 0) {
4041
+ return '';
4042
+ }
4043
+ if (options.parseJson) {
4044
+ return options.parseJson(await response.text());
4045
+ }
4046
+ }
4047
+ return response[type]();
4048
+ };
4049
+ }
4050
+ return result;
4051
+ }
4052
+ // eslint-disable-next-line complexity
4053
+ constructor(input, options = {}) {
4054
+ Object.defineProperty(this, "request", {
4055
+ enumerable: true,
4056
+ configurable: true,
4057
+ writable: true,
4058
+ value: void 0
4059
+ });
4060
+ Object.defineProperty(this, "abortController", {
4061
+ enumerable: true,
4062
+ configurable: true,
4063
+ writable: true,
4064
+ value: void 0
4065
+ });
4066
+ Object.defineProperty(this, "_retryCount", {
4067
+ enumerable: true,
4068
+ configurable: true,
4069
+ writable: true,
4070
+ value: 0
4071
+ });
4072
+ Object.defineProperty(this, "_input", {
4073
+ enumerable: true,
4074
+ configurable: true,
4075
+ writable: true,
4076
+ value: void 0
4077
+ });
4078
+ Object.defineProperty(this, "_options", {
4079
+ enumerable: true,
4080
+ configurable: true,
4081
+ writable: true,
4082
+ value: void 0
4083
+ });
4084
+ this._input = input;
4085
+ this._options = {
4086
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
4087
+ credentials: this._input.credentials || 'same-origin',
4088
+ ...options,
4089
+ headers: mergeHeaders(this._input.headers, options.headers),
4090
+ hooks: deepMerge({
4091
+ beforeRequest: [],
4092
+ beforeRetry: [],
4093
+ beforeError: [],
4094
+ afterResponse: [],
4095
+ }, options.hooks),
4096
+ method: normalizeRequestMethod(options.method ?? this._input.method),
4097
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
4098
+ prefixUrl: String(options.prefixUrl || ''),
4099
+ retry: normalizeRetryOptions(options.retry),
4100
+ throwHttpErrors: options.throwHttpErrors !== false,
4101
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
4102
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
4103
+ };
4104
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
4105
+ throw new TypeError('`input` must be a string, URL, or Request');
4106
+ }
4107
+ if (this._options.prefixUrl && typeof this._input === 'string') {
4108
+ if (this._input.startsWith('/')) {
4109
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
4110
+ }
4111
+ if (!this._options.prefixUrl.endsWith('/')) {
4112
+ this._options.prefixUrl += '/';
4113
+ }
4114
+ this._input = this._options.prefixUrl + this._input;
4115
+ }
4116
+ if (supportsAbortController) {
4117
+ this.abortController = new globalThis.AbortController();
4118
+ if (this._options.signal) {
4119
+ const originalSignal = this._options.signal;
4120
+ this._options.signal.addEventListener('abort', () => {
4121
+ this.abortController.abort(originalSignal.reason);
4122
+ });
4123
+ }
4124
+ this._options.signal = this.abortController.signal;
4125
+ }
4126
+ if (supportsRequestStreams) {
4127
+ // @ts-expect-error - Types are outdated.
4128
+ this._options.duplex = 'half';
4129
+ }
4130
+ this.request = new globalThis.Request(this._input, this._options);
4131
+ if (this._options.searchParams) {
4132
+ // eslint-disable-next-line unicorn/prevent-abbreviations
4133
+ const textSearchParams = typeof this._options.searchParams === 'string'
4134
+ ? this._options.searchParams.replace(/^\?/, '')
4135
+ : new URLSearchParams(this._options.searchParams).toString();
4136
+ // eslint-disable-next-line unicorn/prevent-abbreviations
4137
+ const searchParams = '?' + textSearchParams;
4138
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
4139
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
4140
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
4141
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
4142
+ this.request.headers.delete('content-type');
4143
+ }
4144
+ // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
4145
+ this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
4146
+ }
4147
+ if (this._options.json !== undefined) {
4148
+ this._options.body = JSON.stringify(this._options.json);
4149
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
4150
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
4151
+ }
4152
+ }
4153
+ _calculateRetryDelay(error) {
4154
+ this._retryCount++;
4155
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
4156
+ if (error instanceof HTTPError) {
4157
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
4158
+ return 0;
4159
+ }
4160
+ const retryAfter = error.response.headers.get('Retry-After');
4161
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
4162
+ let after = Number(retryAfter);
4163
+ if (Number.isNaN(after)) {
4164
+ after = Date.parse(retryAfter) - Date.now();
4165
+ }
4166
+ else {
4167
+ after *= 1000;
4168
+ }
4169
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
4170
+ return 0;
4171
+ }
4172
+ return after;
4173
+ }
4174
+ if (error.response.status === 413) {
4175
+ return 0;
4176
+ }
4177
+ }
4178
+ const BACKOFF_FACTOR = 0.3;
4179
+ return Math.min(this._options.retry.backoffLimit, BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000);
4180
+ }
4181
+ return 0;
4182
+ }
4183
+ _decorateResponse(response) {
4184
+ if (this._options.parseJson) {
4185
+ response.json = async () => this._options.parseJson(await response.text());
4186
+ }
4187
+ return response;
4188
+ }
4189
+ async _retry(fn) {
4190
+ try {
4191
+ return await fn();
4192
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
4193
+ }
4194
+ catch (error) {
4195
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
4196
+ if (ms !== 0 && this._retryCount > 0) {
4197
+ await delay(ms, { signal: this._options.signal });
4198
+ for (const hook of this._options.hooks.beforeRetry) {
4199
+ // eslint-disable-next-line no-await-in-loop
4200
+ const hookResult = await hook({
4201
+ request: this.request,
4202
+ options: this._options,
4203
+ error: error,
4204
+ retryCount: this._retryCount,
4205
+ });
4206
+ // If `stop` is returned from the hook, the retry process is stopped
4207
+ if (hookResult === stop) {
4208
+ return;
4209
+ }
4210
+ }
4211
+ return this._retry(fn);
4212
+ }
4213
+ throw error;
4214
+ }
4215
+ }
4216
+ async _fetch() {
4217
+ for (const hook of this._options.hooks.beforeRequest) {
4218
+ // eslint-disable-next-line no-await-in-loop
4219
+ const result = await hook(this.request, this._options);
4220
+ if (result instanceof Request) {
4221
+ this.request = result;
4222
+ break;
4223
+ }
4224
+ if (result instanceof Response) {
4225
+ return result;
4226
+ }
4227
+ }
4228
+ if (this._options.timeout === false) {
4229
+ return this._options.fetch(this.request.clone());
4230
+ }
4231
+ return timeout(this.request.clone(), this.abortController, this._options);
4232
+ }
4233
+ /* istanbul ignore next */
4234
+ _stream(response, onDownloadProgress) {
4235
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
4236
+ let transferredBytes = 0;
4237
+ if (response.status === 204) {
4238
+ if (onDownloadProgress) {
4239
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
4240
+ }
4241
+ return new globalThis.Response(null, {
4242
+ status: response.status,
4243
+ statusText: response.statusText,
4244
+ headers: response.headers,
4245
+ });
4246
+ }
4247
+ return new globalThis.Response(new globalThis.ReadableStream({
4248
+ async start(controller) {
4249
+ const reader = response.body.getReader();
4250
+ if (onDownloadProgress) {
4251
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
4252
+ }
4253
+ async function read() {
4254
+ const { done, value } = await reader.read();
4255
+ if (done) {
4256
+ controller.close();
4257
+ return;
4258
+ }
4259
+ if (onDownloadProgress) {
4260
+ transferredBytes += value.byteLength;
4261
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
4262
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
4263
+ }
4264
+ controller.enqueue(value);
4265
+ await read();
4266
+ }
4267
+ await read();
4268
+ },
4269
+ }), {
4270
+ status: response.status,
4271
+ statusText: response.statusText,
4272
+ headers: response.headers,
4273
+ });
4274
+ }
4275
+ }
4276
+
4277
+ /*! MIT License © Sindre Sorhus */
4278
+ const createInstance = (defaults) => {
4279
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
4280
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
4281
+ for (const method of requestMethods) {
4282
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
4283
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
4284
+ }
4285
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
4286
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
4287
+ ky.stop = stop;
4288
+ return ky;
4289
+ };
4290
+ const ky = createInstance();
4291
+ var ky$1 = ky;
4292
+
4293
+ var PasskeyApiClient = /** @class */ (function () {
4294
+ function PasskeyApiClient(_a) {
4295
+ var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
4296
+ this.tenantId = tenantId;
4297
+ this.api = ky$1.create({
4298
+ prefixUrl: baseUrl
4299
+ });
4300
+ }
4301
+ PasskeyApiClient.prototype.registrationOptions = function (_a) {
4302
+ var token = _a.token, userName = _a.userName;
4303
+ return __awaiter(this, void 0, void 0, function () {
4304
+ var response;
4305
+ return __generator(this, function (_b) {
4306
+ switch (_b.label) {
4307
+ case 0: return [4 /*yield*/, this.api.post("user-authenticators/passkey/registration-options", {
4308
+ json: { userName: userName },
4309
+ headers: {
4310
+ Authorization: "Bearer ".concat(token)
4311
+ }
4312
+ })];
4313
+ case 1:
4314
+ response = _b.sent();
4315
+ return [2 /*return*/, response.json()];
4316
+ }
4317
+ });
4318
+ });
4319
+ };
4320
+ PasskeyApiClient.prototype.authenticationOptions = function (_a) {
4321
+ var token = _a.token;
4322
+ return __awaiter(this, void 0, void 0, function () {
4323
+ var authorizationHeader, response;
4324
+ return __generator(this, function (_b) {
4325
+ switch (_b.label) {
4326
+ case 0:
4327
+ authorizationHeader = token ? "Bearer ".concat(token) : "Basic ".concat(Buffer.from(this.tenantId).toString("base64"));
4328
+ return [4 /*yield*/, this.api.post("user-authenticators/passkey/authentication-options", {
4329
+ json: {},
4330
+ headers: {
4331
+ Authorization: authorizationHeader
4332
+ }
4333
+ })];
4334
+ case 1:
4335
+ response = _b.sent();
4336
+ return [2 /*return*/, response.json()];
4337
+ }
4338
+ });
4339
+ });
4340
+ };
4341
+ PasskeyApiClient.prototype.addAuthenticator = function (_a) {
4342
+ var token = _a.token, rest = __rest(_a, ["token"]);
4343
+ return __awaiter(this, void 0, void 0, function () {
4344
+ var response;
4345
+ return __generator(this, function (_b) {
4346
+ switch (_b.label) {
4347
+ case 0: return [4 /*yield*/, this.api.post("user-authenticators/passkey", {
4348
+ json: rest,
4349
+ headers: {
4350
+ Authorization: "Bearer ".concat(token)
4351
+ }
4352
+ })];
4353
+ case 1:
4354
+ response = _b.sent();
4355
+ return [2 /*return*/, response.json()];
4356
+ }
4357
+ });
4358
+ });
4359
+ };
4360
+ PasskeyApiClient.prototype.verify = function (_a) {
4361
+ var token = _a.token, rest = __rest(_a, ["token"]);
4362
+ return __awaiter(this, void 0, void 0, function () {
4363
+ var authorizationHeader, response;
4364
+ return __generator(this, function (_b) {
4365
+ switch (_b.label) {
4366
+ case 0:
4367
+ authorizationHeader = token ? "Bearer ".concat(token) : "Basic ".concat(Buffer.from(this.tenantId).toString("base64"));
4368
+ return [4 /*yield*/, this.api.post("verify/passkey", {
4369
+ json: rest,
4370
+ headers: {
4371
+ Authorization: authorizationHeader
4372
+ }
4373
+ })];
4374
+ case 1:
4375
+ response = _b.sent();
4376
+ return [2 /*return*/, response.json()];
4377
+ }
4378
+ });
4379
+ });
4380
+ };
4381
+ return PasskeyApiClient;
4382
+ }());
4383
+
4384
+ var Passkey = /** @class */ (function () {
4385
+ function Passkey(_a) {
4386
+ var baseUrl = _a.baseUrl, tenantId = _a.tenantId;
4387
+ this.api = new PasskeyApiClient({ baseUrl: baseUrl, tenantId: tenantId });
4388
+ }
4389
+ Passkey.prototype.signUp = function (_a) {
4390
+ var userName = _a.userName, token = _a.token;
4391
+ return __awaiter(this, void 0, void 0, function () {
4392
+ var optionsResponse, registrationResponse, addAuthenticatorResponse, error_1;
4393
+ return __generator(this, function (_b) {
4394
+ switch (_b.label) {
4395
+ case 0: return [4 /*yield*/, this.api.registrationOptions({ userName: userName, token: token })];
4396
+ case 1:
4397
+ optionsResponse = _b.sent();
4398
+ _b.label = 2;
4399
+ case 2:
4400
+ _b.trys.push([2, 5, , 6]);
4401
+ return [4 /*yield*/, startRegistration(optionsResponse.options)];
4402
+ case 3:
4403
+ registrationResponse = _b.sent();
4404
+ return [4 /*yield*/, this.api.addAuthenticator({
4405
+ challengeId: optionsResponse.challengeId,
4406
+ registrationCredential: registrationResponse,
4407
+ token: token
4408
+ })];
4409
+ case 4:
4410
+ addAuthenticatorResponse = _b.sent();
4411
+ return [2 /*return*/, addAuthenticatorResponse === null || addAuthenticatorResponse === void 0 ? void 0 : addAuthenticatorResponse.accessToken];
4412
+ case 5:
4413
+ error_1 = _b.sent();
4414
+ console.error(error_1);
4415
+ return [3 /*break*/, 6];
4416
+ case 6: return [2 /*return*/];
4417
+ }
4418
+ });
4419
+ });
4420
+ };
4421
+ Passkey.prototype.signIn = function (params) {
4422
+ return __awaiter(this, void 0, void 0, function () {
4423
+ var optionsResponse, authenticationResponse, verifyResponse, error_2;
4424
+ return __generator(this, function (_a) {
4425
+ switch (_a.label) {
4426
+ case 0:
4427
+ if ((params === null || params === void 0 ? void 0 : params.token) && params.autofill) {
4428
+ throw new Error("Autofill is not supported when providing a token");
4429
+ }
4430
+ return [4 /*yield*/, this.api.authenticationOptions({ token: params === null || params === void 0 ? void 0 : params.token })];
4431
+ case 1:
4432
+ optionsResponse = _a.sent();
4433
+ _a.label = 2;
4434
+ case 2:
4435
+ _a.trys.push([2, 5, , 6]);
4436
+ return [4 /*yield*/, startAuthentication(optionsResponse.options, params === null || params === void 0 ? void 0 : params.autofill)];
4437
+ case 3:
4438
+ authenticationResponse = _a.sent();
4439
+ return [4 /*yield*/, this.api.verify({
4440
+ challengeId: optionsResponse.challengeId,
4441
+ authenticationCredential: authenticationResponse,
4442
+ token: params === null || params === void 0 ? void 0 : params.token
4443
+ })];
4444
+ case 4:
4445
+ verifyResponse = _a.sent();
4446
+ return [2 /*return*/, verifyResponse === null || verifyResponse === void 0 ? void 0 : verifyResponse.accessToken];
4447
+ case 5:
4448
+ error_2 = _a.sent();
4449
+ console.error(error_2);
4450
+ return [3 /*break*/, 6];
4451
+ case 6: return [2 /*return*/];
4452
+ }
4453
+ });
4454
+ });
4455
+ };
4456
+ return Passkey;
4457
+ }());
4458
+
3365
4459
  var DEFAULT_COOKIE_NAME = "__as_aid";
4460
+ var DEFAULT_BASE_URL = "https://challenge.authsignal.com/v1";
3366
4461
  var Authsignal = /** @class */ (function () {
3367
4462
  function Authsignal(_a) {
3368
- var publishableKey = _a.publishableKey, cookieDomain = _a.cookieDomain, cookieName = _a.cookieName;
4463
+ var cookieDomain = _a.cookieDomain, _b = _a.cookieName, cookieName = _b === void 0 ? DEFAULT_COOKIE_NAME : _b, _c = _a.baseUrl, baseUrl = _c === void 0 ? DEFAULT_BASE_URL : _c, tenantId = _a.tenantId;
3369
4464
  this.anonymousId = "";
3370
4465
  this.cookieDomain = "";
3371
4466
  this.anonymousIdCookieName = "";
3372
- this.publishableKey = "";
3373
4467
  this._token = undefined;
3374
- this.publishableKey = publishableKey;
3375
4468
  this.cookieDomain = cookieDomain || getCookieDomain();
3376
- this.anonymousIdCookieName = cookieName || DEFAULT_COOKIE_NAME;
4469
+ this.anonymousIdCookieName = cookieName;
4470
+ this.passkey = new Passkey({ tenantId: tenantId, baseUrl: baseUrl });
3377
4471
  var idCookie = getCookie(this.anonymousIdCookieName);
3378
4472
  if (idCookie) {
3379
4473
  this.anonymousId = idCookie;