@andco/sdk-script 0.0.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/LICENSE +202 -0
- package/README.md +130 -0
- package/dist/andco.js +3 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +156 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Andco
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# `@andco/sdk-script`
|
|
2
|
+
|
|
3
|
+
Classic-script and ESM distribution of `@andco/sdk`, built around one custom
|
|
4
|
+
element: `<andco-button>`.
|
|
5
|
+
|
|
6
|
+
Use this package when an integration has no application bundler. React, Vue,
|
|
7
|
+
and Svelte applications should use their native bindings instead of wrapping
|
|
8
|
+
the Web Component.
|
|
9
|
+
|
|
10
|
+
## Classic script
|
|
11
|
+
|
|
12
|
+
```html
|
|
13
|
+
<script src="https://unpkg.com/@andco/sdk-script@0.0.1/dist/andco.js"></script>
|
|
14
|
+
|
|
15
|
+
<andco-button
|
|
16
|
+
client-id="client_123"
|
|
17
|
+
redirect-to="https://app.example.com/auth/callback"
|
|
18
|
+
scopes="openid email profile"
|
|
19
|
+
locale="es-CL"
|
|
20
|
+
></andco-button>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Loading the script registers `<andco-button>` as a side effect of the
|
|
24
|
+
import — there is no separate registration call, and none is needed. The
|
|
25
|
+
same effect happens with the ESM build (below); nothing about registration
|
|
26
|
+
differs between the two.
|
|
27
|
+
|
|
28
|
+
The IIFE also exposes the module on `window.Andco`
|
|
29
|
+
(`Andco.andcoInstance`, `Andco.andcoSessionFor`, `Andco.AndcoButtonElement`).
|
|
30
|
+
There is no `window.AndCo` and no popup-callback function to call yourself: an
|
|
31
|
+
`<andco-button>` resolves its own client from its attributes the moment it
|
|
32
|
+
connects, and that client relays a popup callback and exchanges an
|
|
33
|
+
authorization code left in the URL on its own.
|
|
34
|
+
|
|
35
|
+
Page code that needs the same client — to read `andco.session`, call
|
|
36
|
+
`andco.auth.signOut()`, or use `andco.rest` directly — resolves the shared
|
|
37
|
+
instance by declaring the identical configuration:
|
|
38
|
+
|
|
39
|
+
```html
|
|
40
|
+
<script>
|
|
41
|
+
const andco = Andco.andcoInstance({
|
|
42
|
+
clientId: "client_123",
|
|
43
|
+
redirectTo: location.href,
|
|
44
|
+
initialScopes: ["openid", "email", "profile"],
|
|
45
|
+
});
|
|
46
|
+
andco.session.subscribe((session) => console.log(session));
|
|
47
|
+
</script>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Several `<andco-button>` elements on one page that describe the same
|
|
51
|
+
configuration resolve to this same instance too, so they share one session
|
|
52
|
+
and one storage listener rather than each running its own.
|
|
53
|
+
|
|
54
|
+
## ESM
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
pnpm add @andco/sdk-script
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { andcoInstance, andcoSessionFor, AndcoButtonElement } from "@andco/sdk-script";
|
|
62
|
+
|
|
63
|
+
const andco = andcoInstance({
|
|
64
|
+
clientId: "client_123",
|
|
65
|
+
redirectTo: location.href,
|
|
66
|
+
initialScopes: ["openid", "email", "profile"],
|
|
67
|
+
});
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Importing the package registers `<andco-button>` immediately, exactly as the
|
|
71
|
+
classic-script build does — there is no `registerAndCoElements()` or
|
|
72
|
+
equivalent to call afterwards.
|
|
73
|
+
|
|
74
|
+
`andcoInstance(options)` resolves the same shared `AndcoClient` an
|
|
75
|
+
`<andco-button>` element with matching attributes resolves to.
|
|
76
|
+
`andcoSessionFor(element)` reads that instance's current session snapshot
|
|
77
|
+
directly off an element reference, for page code that needs it without going
|
|
78
|
+
through `andcoInstance` itself.
|
|
79
|
+
|
|
80
|
+
## Attributes
|
|
81
|
+
|
|
82
|
+
`<andco-button>` observes and reacts to:
|
|
83
|
+
|
|
84
|
+
- `client-id` (required), `redirect-to`, `scopes` (space-separated), and `locale`
|
|
85
|
+
- `endpoint-auth`, `endpoint-api`, and `endpoint-widget`
|
|
86
|
+
- `theme-mode`
|
|
87
|
+
- `flow` — `"authorization"` (the default) or `"intent"`, which switches the hosted iframe to the Intent presentation
|
|
88
|
+
- `disabled` and `busy`
|
|
89
|
+
|
|
90
|
+
Changing any of these rebuilds the element. `title` is also read, to label the
|
|
91
|
+
iframe for assistive technology, but is not itself reactive — set it once,
|
|
92
|
+
before the element connects, or alongside another attribute change.
|
|
93
|
+
|
|
94
|
+
Use the `authorizations` property for a Resource Server Definition's authorization
|
|
95
|
+
contribution — it is not serializable as an attribute, so it does not have an
|
|
96
|
+
attribute counterpart:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const button = document.querySelector<AndcoButtonElement>("andco-button")!;
|
|
100
|
+
button.authorizations = [resourceServer.authorization({ scopes: ["..."] })];
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
(`resourceServer` above is a Resource Server Definition — an object implementing
|
|
104
|
+
`AndcoResourceServer` from `@andco/sdk` — and `.authorization(...)` is the method each such
|
|
105
|
+
definition exposes to produce this contribution.)
|
|
106
|
+
|
|
107
|
+
## Events
|
|
108
|
+
|
|
109
|
+
The element dispatches bubbling, composed `CustomEvent`s:
|
|
110
|
+
|
|
111
|
+
- `andco-ready`
|
|
112
|
+
- `andco-activate`
|
|
113
|
+
- `andco-complete`
|
|
114
|
+
- `andco-dismiss`
|
|
115
|
+
- `andco-error`, whose `detail` is the `Error` itself
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
button.addEventListener("andco-error", (event) => {
|
|
119
|
+
const error = (event as CustomEvent<Error>).detail;
|
|
120
|
+
console.error(error);
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`<andco-button>` renders its iframe directly into its own light DOM — it does
|
|
125
|
+
not use a shadow root. That iframe is Andco-deployed and cross-origin: it is
|
|
126
|
+
the trusted authorization and financial confirmation surface, and its code
|
|
127
|
+
and DOM are not the Project's.
|
|
128
|
+
|
|
129
|
+
See [`apps/example-js`](../../apps/example-js/README.md) for the complete session
|
|
130
|
+
→ Grant → resource flow.
|
package/dist/andco.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var Andco=(function(we){Object.defineProperty(we,Symbol.toStringTag,{value:"Module"});var Ie,Hr={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Nt(e){return!e&&!Ie?Hr:{lang:e?.lang??Ie?.lang,message:e?.message,abortEarly:e?.abortEarly??Ie?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Ie?.abortPipeEarly}}var Br;function Vr(e){return Br?.get(e)}var Wr;function qr(e){return Wr?.get(e)}var Fr;function Jr(e,t){return Fr?.get(e)?.get(t)}function Fe(e){const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function C(e,t,r,n,i){const s=i&&"input"in i?i.input:r.value,o=i?.expected??e.expects??null,a=i?.received??Fe(s),c={kind:e.kind,type:e.type,input:s,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=e.kind==="schema",f=i?.message??e.message??Jr(e.reference,c.lang)??(u?qr(c.lang):null)??n.message??Vr(c.lang);f!==void 0&&(c.message=typeof f=="function"?f(c):f),u&&(r.typed=!1),r.issues?r.issues.push(c):r.issues=[c]}function Gr(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function Ut(e,t){const r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function G(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},Nt())},e}function Lt(e,t){return{kind:"validation",type:"check",reference:Lt,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&C(this,"input",r,n),r}}}function K(e,t){return{kind:"validation",type:"max_length",reference:K,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function he(e,t){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&C(this,"length",r,n,{received:`${r.value.length}`}),r}}}function Je(e,t){return{kind:"validation",type:"regex",reference:Je,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&C(this,"format",r,n),r}}}var Kr={abortEarly:!0};function Ct(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function Ge(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function k(e,t){return G({kind:"schema",type:"literal",reference:k,expects:Fe(e),async:!1,literal:e,message:t,"~run"(r,n){return Gr(r.value,this.literal)?r.typed=!0:C(this,"type",r,n),r}})}function Ke(e,t){return G({kind:"schema",type:"object",reference:Ke,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ge(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=Ct(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else C(this,"type",r,n);return r}})}function fe(e,t){return G({kind:"schema",type:"optional",reference:fe,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=Ge(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}})}function Ze(e,t){return G({kind:"schema",type:"picklist",reference:Ze,expects:Ut(e.map(Fe),"|"),async:!1,options:e,message:t,"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:C(this,"type",r,n),r}})}function x(e,t){return G({kind:"schema",type:"strict_object",reference:x,expects:"Object",async:!1,entries:e,message:t,"~run"(r,n){const i=r.value;if(i&&typeof i=="object"){r.typed=!0,r.value={};for(const s in this.entries){const o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){const a=s in i?i[s]:Ge(o),c=o["~run"]({value:a},n);if(c.issues){const u={type:"object",origin:"value",input:i,key:s,value:a};for(const f of c.issues)f.path?f.path.unshift(u):f.path=[u],r.issues?.push(f);if(r.issues||(r.issues=c.issues),n.abortEarly){r.typed=!1;break}}c.typed||(r.typed=!1),r.value[s]=c.value}else if(o.fallback!==void 0)r.value[s]=Ct(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(C(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly){for(const s in i)if(!Object.prototype.hasOwnProperty.call(this.entries,s)){C(this,"key",r,n,{input:s,expected:"never",path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]});break}}}else C(this,"type",r,n);return r}})}function Z(e){return G({kind:"schema",type:"string",reference:Z,expects:"string",async:!1,message:e,"~run"(t,r){return typeof t.value=="string"?t.typed=!0:C(this,"type",t,r),t}})}function Dt(e,t,r){return G({kind:"schema",type:"variant",reference:Dt,expects:"Object",async:!1,key:e,options:t,message:r,"~run"(n,i){const s=n.value;if(s&&typeof s=="object"){let o,a=0,c=this.key,u=[];const f=(_,h)=>{for(const d of _.options){if(d.type==="variant")f(d,new Set(h).add(d.key));else{let w=!0,R=0;for(const T of h){const N=d.entries[T];if(T in s?N["~run"]({typed:!1,value:s[T]},Kr).issues:N.type!=="exact_optional"&&N.type!=="optional"&&N.type!=="nullish"){w=!1,c!==T&&(a<R||a===R&&T in s&&!(c in s))&&(a=R,c=T,u=[]),c===T&&u.push(d.entries[T].expects);break}R++}if(w){const T=d["~run"]({value:s},i);(!o||!o.typed&&T.typed)&&(o=T)}}if(o&&!o.issues)break}};if(f(this,new Set([this.key])),o)return o;C(this,"type",n,i,{input:s[c],expected:Ut(u,"|"),path:[{type:"object",origin:"value",input:s,key:c,value:s[c]}]})}else C(this,"type",n,i);return n}})}function te(...e){return G({...e[0],pipe:e,"~run"(t,r){for(const n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}})}function Ye(e,t,r){const n=e["~run"]({value:t},Nt(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}function xt(e){const t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="[::1]"||t==="::1"?!0:/^127(?:\.\d{1,3}){3}$/.test(t)}var Zr=["hash","host","hostname","password","pathname","port","protocol","search","username"],Yr=class extends URL{constructor(e,t,r){try{super(e,t)}catch(n){throw new Error(`${n instanceof Error?n.message:String(n)} — new BetterURL('${e}', '${t}')`)}r&&this.assign(r)}get isLoopback(){return xt(this.hostname)}assign(e){if(e.replace){let{pathname:t}=this;for(const[r,n]of Object.entries(e.replace))t=t.replaceAll(`[${r}]`,encodeURIComponent(String(n)));this.pathname=t}for(const t of Zr){const r=e[t];r!==void 0&&(this[t]=r)}if(e.params)for(const[t,r]of Object.entries(e.params))r===void 0||(r===null?this.searchParams.delete(t):this.searchParams.set(t,r));return this}format(e){if(!e)return this.href;let t="";return e.protocol&&(t+=`${this.protocol}//`),e.hostname&&(t+=this.hostname),e.port&&this.port&&(t+=`:${this.port}`),e.pathname&&(t+=this.pathname),e.search&&(t+=this.search),e.hash&&(t+=this.hash),t}get hashParams(){return new URLSearchParams(this.hash.slice(1))}},Y=class extends Yr{constructor(e,t,r){if(super(e,t,r),!(this.protocol==="https:"||this.protocol==="http:"&&xt(this.hostname))||this.username||this.password||this.hash)throw new TypeError("AndCo URLs require HTTPS, except for loopback development hosts, and cannot contain credentials or a fragment")}},pe="andco:sdk",Hs="https://auth.andco.cl",Bs="https://api.andco.cl",Vs="https://widgets.andco.cl";function Qr(e,t="_"){return new URL(`/oauth/api/versions/${t}`,e).href}var j={protocol:k(pe),version:k(2)},Ws=te(Z(),he(1),K(128),Je(/^[A-Za-z0-9_-]+$/)),W=te(Z(),he(1),K(128),Je(/^[A-Za-z0-9_-]+$/)),re;(function(e){e.BROWSER_UNAVAILABLE="BROWSER_UNAVAILABLE",e.AUTH_CANCELLED="AUTH_CANCELLED",e.AUTH_EXCHANGE_FAILED="AUTH_EXCHANGE_FAILED",e.AUTH_TIMEOUT="AUTH_TIMEOUT",e.INVALID_ENDPOINT_AUTH="INVALID_ENDPOINT_AUTH",e.INVALID_ENDPOINT_API="INVALID_ENDPOINT_API",e.INVALID_ENDPOINT_BUTTON="INVALID_ENDPOINT_BUTTON",e.INVALID_IFRAME="INVALID_IFRAME",e.INVALID_AUTH_MODE="INVALID_AUTH_MODE",e.INVALID_CLIENT_ID="INVALID_CLIENT_ID",e.INVALID_REDIRECT_TO="INVALID_REDIRECT_TO",e.INVALID_CALLBACK="INVALID_CALLBACK",e.INVALID_SCOPE="INVALID_SCOPE",e.INVALID_VERSION="INVALID_VERSION",e.FETCH_UNAVAILABLE="FETCH_UNAVAILABLE",e.POPUP_BLOCKED="POPUP_BLOCKED",e.POPUP_NAVIGATION_FAILED="POPUP_NAVIGATION_FAILED",e.POPUP_TIMEOUT="POPUP_TIMEOUT",e.INTENT_CALLBACK_REQUIRED="INTENT_CALLBACK_REQUIRED",e.SAME_ORIGIN_ENDPOINT="SAME_ORIGIN_ENDPOINT",e.UNSUPPORTED_PRESENTATION="UNSUPPORTED_PRESENTATION",e.UNSUPPORTED_THEME="UNSUPPORTED_THEME",e.UNSUPPORTED_THEME_MODE="UNSUPPORTED_THEME_MODE",e.UNTRUSTED_ORIGIN="UNTRUSTED_ORIGIN",e.WEB_CRYPTO_UNAVAILABLE="WEB_CRYPTO_UNAVAILABLE",e.HANDSHAKE_TIMEOUT="HANDSHAKE_TIMEOUT",e.UNKNOWN_ERROR="UNKNOWN_ERROR"})(re||(re={}));var Xr=class extends Error{constructor(e,t){super(e,t),Object.setPrototypeOf(this,new.target.prototype),this.name=this.constructor.name}static is(e,t){return e instanceof t}},zt=class extends Xr{code;payload;constructor(e,t,r){super(e,r),this.code=e,this.payload=t}};function en(e){const t=new TextEncoder().encode(e);let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function tn(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"="),n=atob(r),i=Uint8Array.from(n,s=>s.charCodeAt(0));return new TextDecoder().decode(i)}function Qe(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(!e||typeof e.getRandomValues!="function")throw new zt(re.WEB_CRYPTO_UNAVAILABLE,{missing:["crypto.getRandomValues"]});const t=e.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const r=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function rn(e,t=Qe()){if(!Ye(W,t).success)throw new TypeError("Invalid AndCo presentation identifier");const r=new Y(e).origin;return`${en(r)}.${t}`}function nn(e){const t=e.indexOf("."),r=e.slice(t+1);if(t<1||t===e.length-1||!Ye(W,r).success)return null;try{const n=tn(e.slice(0,t));return{openerOrigin:new Y(n).origin,presentationId:r}}catch{return null}}var sn=x({...j,type:k("authorization-response"),presentationId:W,authorizationUrl:fe(te(Z(),he(1),K(8192)))}),on=x({...j,type:k("click"),presentationId:fe(W)}),an=Ze(Object.values(re)),cn=x({...j,type:k("error"),error:x({code:an})}),un=x({...j,type:k("init")}),ln=x({...j,type:k("oauth.authorization_code"),presentationId:W,authorizationCode:te(Z(),he(1),K(8192))}),dn=x({...j,type:k("oauth.complete"),presentationId:W}),hn=x({...j,type:k("oauth.dismiss"),presentationId:W}),fn=Ke({...j,type:k("intent.complete"),presentationId:W}),pn=Ke({...j,type:k("intent.dismiss"),presentationId:W}),mn=x({...j,type:k("oauth.error"),presentationId:W,error:x({code:te(Z(),he(1),K(256)),description:fe(te(Z(),K(2048)))})}),yn=x({...j,type:k("ready")}),wn=te(Z(),K(35),Lt(e=>{try{return Intl.getCanonicalLocales(e),!0}catch{return!1}})),_n=Ze(["dark","light","system"]),gn=x({...j,type:k("set-preferences"),themeMode:fe(_n),locale:fe(wn)}),vn=Dt("type",[sn,yn,on,cn,un,gn,ln,dn,hn,mn,fn,pn]);function bn(e){return Ye(vn,e).success}var qs=1780358400,Mt="andco-popup-",A=class qe extends Error{code;status;details;constructor(t,r={}){super(r.message??t,r.cause===void 0?void 0:{cause:r.cause}),this.name="AndcoError",this.code=t,this.status=r.status,this.details=r.details}static from(t,r){if(qe.is(t))return t;const n=t instanceof Error?t.message:void 0;return new qe(r,{message:n,cause:t})}static is(t){return t instanceof qe}},An=class ye extends A{error;response;constructor(t,r){super(t,r),this.name="AndcoAPIError",this.error=t,this.response=r.response}static fromOpenAPIFetch(t,r){const{message:n,details:i}=ye.bodyOf(t),s=new ye(ye.codeOf(t),{response:r,status:ye.statusOf(r),message:n,details:i,cause:t});for(const[o,a]of Object.entries(i??{}))ye.OWN_FIELDS.has(o)||(s[o]=a);return s}static OWN_FIELDS=new Set(["name","message","stack","cause","code","error","status","response","details"]);static codeOf(t){if(t&&typeof t=="object"){const{error:r}=t;if(typeof r=="string")return r}return"request_failed"}static bodyOf(t){if(!t||typeof t!="object")return{message:void 0,details:void 0};const{error:r,message:n,...i}=t,s=Object.keys(i).length>0;return{message:typeof n=="string"?n:void 0,details:s?i:void 0}}static statusOf(t){if(t.type!=="error")return t.status}},l={ok(e){return{data:e,error:null}},fail(e,t={}){return{data:null,error:typeof e=="string"?new A(e,t):e}}},g={BROWSER_REQUIRED:"browser_required",BROWSER_UNAVAILABLE:"browser_unavailable",BROWSER_FORBIDDEN:"browser_forbidden",INVALID_CALLBACK:"invalid_callback",INVALID_CONFIGURATION:"invalid_configuration",HANDSHAKE_TIMEOUT:"handshake_timeout",INVALID_IFRAME:"invalid_iframe",INVALID_INTENT_ID:"invalid_intent_id",INVALID_RESPONSE:"invalid_response",POPUP_BLOCKED:"popup_blocked",POPUP_TIMEOUT:"popup_timeout",PRESENTATION_UNSUPPORTED:"presentation_unsupported",SAME_ORIGIN_ENDPOINT:"same_origin_endpoint",SESSION_MISSING:"session_missing",STORAGE_FAILED:"storage_failed",UNTRUSTED_ORIGIN:"untrusted_origin"},jt=class{#e;constructor(e){this.#e=e}async signIn(e={}){const{oauth:t,presenter:r,store:n}=this.#e,i=this.#e.randomId?this.#e.randomId():Qe(this.#e.crypto),s=await t.createAuthorizationRequest(e);if(s.error)return l.fail(s.error);await this.#e.persistTransaction?.(s.data);const o=new URL(s.data.redirectTo),a=await r.present({url:s.data.authorizationUrl,presentation:e.presentation??"popup",returnTo:o,presentationId:i});if(a.error)return l.fail(a.error);if(!a.data)return l.ok(null);const c=await t.exchangeCallback({callbackUrl:a.data,request:s.data});if(c.error)return l.fail(c.error);const u=await n.set(c.data);return u.error?l.fail(u.error):l.ok(c.data)}async signOut(){return this.#e.store.set(null)}onChange(e){const t=this.#e.store;return t.subscribe(()=>e(t.getSnapshot()??null))}async getSession(){const e=this.#e.store,t=await e.ready;return t.error?l.fail(t.error):l.ok(e.getSnapshot()??null)}async refresh(){const e=this.#e.store;await e.ready;const t=e.getSnapshot();if(!t?.refreshToken)return l.fail(g.SESSION_MISSING);const r=await this.#e.oauth.refresh(t.refreshToken);if(r.error)return l.fail(r.error);const n=await e.set(r.data);return n.error?l.fail(n.error):l.ok(r.data)}},En=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{2,8})*$/,Tn=/^[A-Za-z0-9_-]{1,80}$/,In=/^\d{10}$/,Sn=class Ot{clientId;endpoints;apiVersion;redirectTo;locale;theme;themeMode;initialScopes;allowedPopupOrigins;constructor(t){if(!Tn.test(t.clientId??""))throw new A(g.INVALID_CONFIGURATION,{message:"clientId is missing or malformed"});if(this.clientId=t.clientId,this.endpoints=Object.freeze({auth:new Y(t.endpointAuth??"https://auth.andco.cl"),api:new Y(t.endpointApi??"https://api.andco.cl"),widget:new Y(t.endpointWidget??"https://widgets.andco.cl")}),this.apiVersion=String(t.apiVersion??"_"),this.apiVersion!=="_"&&!In.test(this.apiVersion))throw new A(g.INVALID_CONFIGURATION,{message:"apiVersion must be `_` or a ten-digit Unix timestamp"});if(this.redirectTo=t.redirectTo===void 0?void 0:new Y(t.redirectTo),this.locale=t.locale??"es",!En.test(this.locale))throw new A(g.INVALID_CONFIGURATION,{message:"locale must be a BCP 47 tag"});this.theme=t.theme??"base",this.themeMode=t.themeMode??"system",this.initialScopes=Object.freeze([...new Set(t.initialScopes??[])]);const r=t.allowedPopupOrigins??[];this.allowedPopupOrigins=Object.freeze(new Set([this.endpoints.widget.origin,...r.map(n=>new Y(n).origin)]))}static from(t){return new Ot(t)}with(t){return Ot.from({...this.toJSON(),...t})}authURL(t){const r=this.endpoints.auth,n=new URL(r.href);return n.pathname=`${r.pathname.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,n}apiURL(){return new URL(`/oauth/api/versions/${this.apiVersion}/`,this.endpoints.api)}widgetURL(t,r="button"){return new URL(`/embedded/versions/${t}/${r}`,this.endpoints.widget)}allowsPopupOrigin(t){return this.allowedPopupOrigins.has(t)}toJSON(){return{clientId:this.clientId,endpointAuth:this.endpoints.auth.href,endpointApi:this.endpoints.api.href,endpointWidget:this.endpoints.widget.href,apiVersion:this.apiVersion,redirectTo:this.redirectTo?.href,locale:this.locale,theme:this.theme,themeMode:this.themeMode,initialScopes:[...this.initialScopes],allowedPopupOrigins:[...this.allowedPopupOrigins]}}},Fs=30;function $t(e,t=Math.floor(Date.now()/1e3)){return e.expiresAt<=t+30}function Xe(e,t){const r=e.resourceAccessTokens;if(r){if(r[t])return r[t]??null}else return e.accessToken;try{return r[new URL(t).href]??e.accessToken}catch{return e.accessToken}}function Pn(e){return{accessTokenFor:async t=>Xe(e,t)}}function Rn(e){return typeof e.accessTokenFor=="function"}function kn(e,t,r,n,i){const s=n.pollIntervalMs??1e3;if(!Number.isSafeInteger(s)||s<100)throw new TypeError("Invalid event polling interval");if(typeof n.onError!="function")throw new TypeError("An event error handler is required");const o=`v1:${i.kind}:${i.id.toLowerCase()}:`,a=h=>{if(typeof h!="string"||!h.startsWith(o)||!/^(0|[1-9][0-9]{0,18})$/.test(h.slice(o.length)))throw new TypeError("invalid_or_unsupported_event_cursor");const d=BigInt(h.slice(o.length));if(d>9223372036854775807n)throw new TypeError("invalid_or_unsupported_event_cursor");return d},c=new AbortController;let u=n.after,f;const _=async()=>{if(c.signal.aborted)return;let h=s;try{let d=u===void 0?0n:a(u);const w=await e(u,c.signal);if(c.signal.aborted)return;if(!w||!Array.isArray(w.events)||w.events.length>100||typeof w.has_more!="boolean"||!Ht(w.server_time))throw new TypeError("invalid_event_response");const R=a(w.next_cursor),T=new Map;let N=-1n;const U=w.events.map(y=>{if(!y||y.version!==1||typeof y.id!="string"||!y.id||y.id.length>128||typeof y.type!="string"||!y.type||!y.payload||typeof y.payload!="object"||Array.isArray(y.payload)||!Ht(y.occurred_at))throw new TypeError("invalid_event_response");const I=a(y.cursor);if(I===0n||I<N)throw new TypeError("invalid_event_response");const b=JSON.stringify(y);if(T.has(y.id)&&T.get(y.id)!==b||I===N&&T.get(y.id)!==b)throw new TypeError("invalid_event_response");return T.set(y.id,b),N=I,I});if(w.events.length?R!==U.at(-1):R!==d||w.has_more)throw new TypeError("invalid_event_response");if(w.has_more&&R<=d)throw new TypeError("invalid_event_response");for(let y=0;y<w.events.length;y++){if(c.signal.aborted)return;const I=w.events[y],b=U[y];if(b<=d)continue;const le=t(I);le!==null&&await r(le),u=I.cursor,d=b}u===void 0&&(u=w.next_cursor),w.has_more&&(h=0)}catch(d){if(c.signal.aborted)return;try{await n.onError(d)}catch{c.abort()}}finally{c.signal.aborted||(f=setTimeout(()=>{_()},h))}};return _(),{unsubscribe(){c.abort(),clearTimeout(f)},get checkpoint(){return u}}}function Ht(e){return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(e)&&Number.isFinite(Date.parse(e))}var On=/\{[^{}]+\}/g,Nn=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function Un(){return Math.random().toString(36).slice(2,11)}function Ln(e){let{baseUrl:t="",Request:r=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:s,pathSerializer:o,headers:a,requestInitExt:c=void 0,...u}={...e};c=Nn()?c:void 0,t=Ft(t);const f=[];async function _(h,d){const{baseUrl:w,fetch:R=n,Request:T=r,headers:N,params:U={},parseAs:y="json",querySerializer:I,bodySerializer:b=s??Dn,pathSerializer:le,body:He,middleware:Tt=[],...It}=d||{};let St=t;w&&(St=Ft(w)??t);let Pt=typeof i=="function"?i:Wt(i);I&&(Pt=typeof I=="function"?I:Wt({...typeof i=="object"?i:{},...I}));const Mr=le||o||Cn,Rt=He===void 0?void 0:b(He,qt(a,N,U.header)),js=qt(Rt===void 0||Rt instanceof FormData?{}:{"Content-Type":"application/json"},a,N,U.header),X=[...f,...Tt],$s={redirect:"follow",...u,...It,body:Rt,headers:js};let Be,Ve,ee=new T(xn(h,{baseUrl:St,params:U,querySerializer:Pt,pathSerializer:Mr}),$s),S;for(const L in It)L in ee||(ee[L]=It[L]);if(X.length){Be=Un(),Ve=Object.freeze({baseUrl:St,fetch:R,parseAs:y,querySerializer:Pt,bodySerializer:b,pathSerializer:Mr});for(const L of X)if(L&&typeof L=="object"&&typeof L.onRequest=="function"){const P=await L.onRequest({request:ee,schemaPath:h,params:U,options:Ve,id:Be});if(P)if(P instanceof T)ee=P;else if(P instanceof Response){S=P;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!S){try{S=await R(ee,c)}catch(L){let P=L;if(X.length)for(let de=X.length-1;de>=0;de--){const We=X[de];if(We&&typeof We=="object"&&typeof We.onError=="function"){const Te=await We.onError({request:ee,error:P,schemaPath:h,params:U,options:Ve,id:Be});if(Te){if(Te instanceof Response){P=void 0,S=Te;break}if(Te instanceof Error){P=Te;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(P)throw P}if(X.length)for(let L=X.length-1;L>=0;L--){const P=X[L];if(P&&typeof P=="object"&&typeof P.onResponse=="function"){const de=await P.onResponse({request:ee,response:S,schemaPath:h,params:U,options:Ve,id:Be});if(de){if(!(de instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");S=de}}}}const jr=S.headers.get("Content-Length");if(S.status===204||ee.method==="HEAD"||jr==="0"&&!S.headers.get("Transfer-Encoding")?.includes("chunked"))return S.ok?{data:void 0,response:S}:{error:void 0,response:S};if(S.ok)return{data:await(async()=>{if(y==="stream")return S.body;if(y==="json"&&!jr){const P=await S.text();return P?JSON.parse(P):void 0}return await S[y]()})(),response:S};let kt=await S.text();try{kt=JSON.parse(kt)}catch{}return{error:kt,response:S}}return{request(h,d,w){return _(d,{...w,method:h.toUpperCase()})},GET(h,d){return _(h,{...d,method:"GET"})},PUT(h,d){return _(h,{...d,method:"PUT"})},POST(h,d){return _(h,{...d,method:"POST"})},DELETE(h,d){return _(h,{...d,method:"DELETE"})},OPTIONS(h,d){return _(h,{...d,method:"OPTIONS"})},HEAD(h,d){return _(h,{...d,method:"HEAD"})},PATCH(h,d){return _(h,{...d,method:"PATCH"})},TRACE(h,d){return _(h,{...d,method:"TRACE"})},use(...h){for(const d of h)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d||"onError"in d))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");f.push(d)}},eject(...h){for(const d of h){const w=f.indexOf(d);w!==-1&&f.splice(w,1)}}}}function Se(e,t,r){if(t==null)return"";if(typeof t=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${e}=${r?.allowReserved===!0?t:encodeURIComponent(t)}`}function Bt(e,t,r){if(!t||typeof t!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[r.style]||"&";if(r.style!=="deepObject"&&r.explode===!1){for(const a in t)n.push(a,r.allowReserved===!0?t[a]:encodeURIComponent(t[a]));const o=n.join(",");switch(r.style){case"form":return`${e}=${o}`;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return o}}for(const o in t){const a=r.style==="deepObject"?`${e}[${o}]`:o;n.push(Se(a,t[o],r))}const s=n.join(i);return r.style==="label"||r.style==="matrix"?`${i}${s}`:s}function Vt(e,t,r){if(!Array.isArray(t))return"";if(r.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[r.style]||",",o=(r.allowReserved===!0?t:t.map(a=>encodeURIComponent(a))).join(s);switch(r.style){case"simple":return o;case"label":return`.${o}`;case"matrix":return`;${e}=${o}`;default:return`${e}=${o}`}}const n={simple:",",label:".",matrix:";"}[r.style]||"&",i=[];for(const s of t)r.style==="simple"||r.style==="label"?i.push(r.allowReserved===!0?s:encodeURIComponent(s)):i.push(Se(e,s,r));return r.style==="label"||r.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Wt(e){return function(r){const n=[];if(r&&typeof r=="object")for(const i in r){const s=r[i];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;n.push(Vt(i,s,{style:"form",explode:!0,...e?.array,allowReserved:e?.allowReserved||!1}));continue}if(typeof s=="object"){n.push(Bt(i,s,{style:"deepObject",explode:!0,...e?.object,allowReserved:e?.allowReserved||!1}));continue}n.push(Se(i,s,e))}}return n.join("&")}}function Cn(e,t){let r=e;for(const n of e.match(On)??[]){let i=n.substring(1,n.length-1),s=!1,o="simple";if(i.endsWith("*")&&(s=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(o="label",i=i.substring(1)):i.startsWith(";")&&(o="matrix",i=i.substring(1)),!t||t[i]===void 0||t[i]===null)continue;const a=t[i];if(Array.isArray(a)){r=r.replace(n,Vt(i,a,{style:o,explode:s}));continue}if(typeof a=="object"){r=r.replace(n,Bt(i,a,{style:o,explode:s}));continue}if(o==="matrix"){r=r.replace(n,`;${Se(i,a)}`);continue}r=r.replace(n,o==="label"?`.${encodeURIComponent(a)}`:encodeURIComponent(a))}return r}function Dn(e,t){return e instanceof FormData?e:t&&(t.get instanceof Function?t.get("Content-Type")??t.get("content-type"):t["Content-Type"]??t["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(e).toString():JSON.stringify(e)}function xn(e,t){let r=`${t.baseUrl}${e}`;t.params?.path&&(r=t.pathSerializer(r,t.params.path));let n=t.querySerializer(t.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(r+=`?${n}`),r}function qt(...e){const t=new Headers;for(const r of e){if(!r||typeof r!="object")continue;const n=r instanceof Headers?r.entries():Object.entries(r);for(const[i,s]of n)if(s===null)t.delete(i);else if(Array.isArray(s))for(const o of s)t.append(i,o);else s!==void 0&&t.set(i,s)}return t}function Ft(e){return e.endsWith("/")?e.substring(0,e.length-1):e}function zn(e){return((t,r)=>{const n=e??globalThis.fetch;return typeof n!="function"?Promise.reject(new zt(re.FETCH_UNAVAILABLE,{missing:["fetch"]})):n(t,r)})}function Mn(e={}){const t=String(e.apiVersion??"_");if(t!=="_"&&!/^\d{10}$/.test(t))throw new TypeError("apiVersion must be `_` or a Unix timestamp in seconds");const r=new Y(e.endpoint??"https://api.andco.cl"),n=Ln({baseUrl:Qr(r,t),fetch:e.fetch??zn()});return n.use({async onRequest({request:i}){let s;return typeof e.accessToken=="function"?s=await e.accessToken():s=e.accessToken,s&&i.headers.set("Authorization",`Bearer ${s}`),i}}),n}var jn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$n=/^[A-Za-z0-9._:-]{1,128}$/,Jt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async create(e,t,r={}){const n=r.idempotencyKey??Qe(this.#t);if(!$n.test(n))return l.fail(g.INVALID_CONFIGURATION,{message:"malformed Idempotency-Key"});let i;try{({data:i}=await this.#e.http.POST("/intents",{params:{header:{"Idempotency-Key":n}},body:{...t,type:e}}).throwOnError())}catch(s){return l.fail(s)}return i?.type!==e?l.fail(g.INVALID_RESPONSE,{message:`expected a ${e} intent`}):l.ok(i)}async get(e){const t=et(e);if(t)return l.fail(t);try{const{data:r}=await this.#e.http.GET("/intents/{intent_id}",{params:{path:{intent_id:e}}}).throwOnError();return l.ok(r)}catch(r){return l.fail(r)}}async execute(e){const t=et(e);if(t)return l.fail(t);try{return await this.#e.http.POST("/intents/{intent_id}/execute",{params:{path:{intent_id:e}}}).throwOnError(),l.ok(void 0)}catch(r){return l.fail(r)}}async events(e,t,r){const n=et(e);if(n)return l.fail(n);try{const{data:i}=await this.#e.http.GET("/intents/{intent_id}/events",{params:{path:{intent_id:e},query:{after:t,limit:100}},signal:r}).throwOnError();return l.ok(i)}catch(i){return l.fail(i)}}subscribe(e,t,r,n,i){const s=kn(async(o,a)=>{const c=await t(o,a);if(c.error)throw c.error;return c.data},r,async o=>{await n(o),i.onCheckpoint?.(o.cursor)},{...i.after===void 0?{}:{after:i.after},onError:i.onError,...i.pollIntervalMs===void 0?{}:{pollIntervalMs:i.pollIntervalMs}},e);return()=>s.unsubscribe()}};function et(e){return jn.test(e)?null:new A(g.INVALID_INTENT_ID,{message:`${e} is not a valid identifier`})}var tt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(tt="oauth4webapi/v3.8.8");function ne(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var z="ERR_INVALID_ARG_VALUE",$="ERR_INVALID_ARG_TYPE";function v(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}var H=Symbol(),Pe=Symbol(),rt=Symbol(),q=Symbol(),F=Symbol(),Hn=new TextEncoder,Bn=new TextDecoder;function nt(e){return typeof e=="string"?Hn.encode(e):Bn.decode(e)}var it;Uint8Array.prototype.toBase64?it=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):it=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var st;Uint8Array.fromBase64?st=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw v("The input to be decoded is not correctly encoded.",z,t)}}:st=e=>{try{const t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch(t){throw v("The input to be decoded is not correctly encoded.",z,t)}};function Re(e){return typeof e=="string"?st(e):it(e)}var _e=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=mt,Error.captureStackTrace?.(this,this.constructor)}},ot=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,t?.code&&(this.code=t?.code),Error.captureStackTrace?.(this,this.constructor)}};function p(e,t,r){return new ot(e,{code:t,cause:r})}function ke(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function ge(e){ne(e,Headers)&&(e=Object.fromEntries(e.entries()));const t=new Headers(e??{});if(tt&&!t.has("user-agent")&&t.set("user-agent",tt),t.has("authorization"))throw v('"options.headers" must not include the "authorization" header name',z);return t}function Gt(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw v('"options.signal" must return or be an instance of AbortSignal',$);return t}}function ie(e,t,r,n,i){try{if(typeof e!="number"||!Number.isFinite(e))throw v(`${r} must be a number`,$,i);if(e>0)return;if(t){if(e!==0)throw v(`${r} must be a non-negative number`,z,i);return}throw v(`${r} must be a positive number`,z,i)}catch(s){throw n?p(s.message,n,i):s}}function E(e,t,r,n){try{if(typeof e!="string")throw v(`${t} must be a string`,$,n);if(e.length===0)throw v(`${t} must not be empty`,z,n)}catch(i){throw r?p(i.message,r,n):i}}function Kt(e){Wn(e,"application/json")}function Vn(e,...t){let r='"response" content-type must be ';if(t.length>2){const n=t.pop();r+=`${t.join(", ")}, or ${n}`}else t.length===2?r+=`${t[0]} or ${t[1]}`:r+=t[0];return p(r,mr,e)}function Wn(e,t){if(Ue(e)!==t)throw Vn(e,t)}function Zt(){return Re(crypto.getRandomValues(new Uint8Array(32)))}function qn(){return Zt()}function Fn(){return Zt()}async function Jn(e){return E(e,"codeVerifier"),Re(await crypto.subtle.digest("SHA-256",nt(e)))}function Oe(e){const t=e?.[Pe];return typeof t=="number"&&Number.isFinite(t)?t:0}function at(e){const t=e?.[rt];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Yt(){return Math.floor(Date.now()/1e3)}function B(e){if(typeof e!="object"||e===null)throw v('"as" must be an object',$);E(e.issuer,'"as.issuer"')}function V(e){if(typeof e!="object"||e===null)throw v('"client" must be an object',$);E(e.client_id,'"client.client_id"')}function Qt(e){return encodeURIComponent(e).replace(/(?:[-_.!~*'()]|%20)/g,t=>{switch(t){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${t.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Xt(e){return E(e,'"clientSecret"'),(t,r,n,i)=>{n.set("client_id",r.client_id),n.set("client_secret",e)}}function er(e){return E(e,'"clientSecret"'),(t,r,n,i)=>{const s=Qt(r.client_id),o=Qt(e),a=btoa(`${s}:${o}`);i.set("authorization",`Basic ${a}`)}}function Gn(){return(e,t,r,n)=>{r.set("client_id",t.client_id)}}var Kn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function tr(e,t){if(t&&e.protocol!=="https:")throw p("only requests to HTTPS are allowed",yr,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw p("only HTTP and HTTPS requests are allowed",wr,e)}function rr(e,t,r,n){let i;if(typeof e!="string"||!(i=Kn(e)))throw p(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Si:Pi,{attribute:r?`mtls_endpoint_aliases.${t}`:t});return tr(i,n),i}function ve(e,t,r,n){return r&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?rr(e.mtls_endpoint_aliases[t],t,r,n):rr(e[t],t,r,n)}async function Zn(e,t,r,n,i){B(e),V(t);const s=ve(e,"pushed_authorization_request_endpoint",t.use_mtls_endpoint_aliases,i?.[H]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=ge(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(lt(i.DPoP),await i.DPoP.addProof(s,a,"POST"));const c=await dt(e,t,r,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}function Yn(e){return e instanceof ct?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof Ne?e.error==="use_dpop_nonce":!1}var Ne=class extends Error{cause;code;error;status;error_description;response;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ei,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:t.response}),Error.captureStackTrace?.(this,this.constructor)}},nr=class extends Error{cause;code;error;error_description;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ti,this.cause=t.cause,this.error=t.cause.get("error"),this.error_description=t.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},ct=class extends Error{cause;code;response;status;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=Ai,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Qn=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),Xn=new RegExp('^[,\\s]*([a-zA-Z0-9!#$%&\\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)'),ei=new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),ti=new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");function ri(e){if(!ne(e,Response))throw v('"response" must be an instance of Response',$);const t=e.headers.get("www-authenticate");if(t===null)return;const r=[];let n=t;for(;n;){let i=n.match(Qn);const s=i?.[1].toLowerCase();if(!s)return;const o=n.substring(i[0].length);if(o&&!o.match(/^[\s,]/))return;const a=o.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;const u={};let f;if(c)for(;n;){let h,d;if(i=n.match(Xn)){[,h,d,n]=i,d.includes("\\")&&(d=d.replace(/\\([\s\S])/g,"$1")),u[h.toLowerCase()]=d;continue}if(i=n.match(ei)){[,h,d,n]=i,u[h.toLowerCase()]=d;continue}if(i=n.match(ti)){if(Object.keys(u).length)break;[,f,n]=i;break}return}else n=o||void 0;const _={scheme:s,parameters:u};f&&(_.token68=f),r.push(_)}if(r.length)return r}async function ni(e,t,r){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,201,"Pushed Authorization Request Endpoint"),be(r);const n=await Me(r);E(n.request_uri,'"response" body "request_uri" property',m,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',m,{body:n}),n.expires_in=i,n}async function ii(e){if(e.status>399&&e.status<500){be(e),Kt(e);try{const t=await e.clone().json();if(ke(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function ut(e,t,r){if(e.status!==t){ar(e);let n;throw(n=await ii(e))?(await e.body?.cancel(),new Ne("server responded with an error in the response body",{cause:n,response:e})):p(`"response" is not a conform ${r} response (unexpected HTTP status code)`,yt,e)}}function lt(e){if(!pt.has(e))throw v('"options.DPoP" is not a valid DPoPHandle',z)}async function si(e,t,r,n,i,s){if(E(e,'"accessToken"'),!(r instanceof URL))throw v('"url" must be an instance of URL',$);tr(r,s?.[H]!==!0),n=ge(n),s?.DPoP&&(lt(s.DPoP),await s.DPoP.addProof(r,n,t.toUpperCase(),e)),n.set("authorization",`${n.has("dpop")?"DPoP":"Bearer"} ${e}`);const o=await(s?.[q]||fetch)(r.href,{duplex:ne(i,ReadableStream)?"half":void 0,body:i,headers:Object.fromEntries(n.entries()),method:t,redirect:"manual",signal:Gt(r,s?.signal)});return s?.DPoP?.cacheNonce(o,r),o}async function oi(e,t,r,n){B(e),V(t);const i=ve(e,"userinfo_endpoint",t.use_mtls_endpoint_aliases,n?.[H]!==!0),s=ge(n?.headers);return t.userinfo_signed_response_alg?s.set("accept","application/jwt"):(s.set("accept","application/json"),s.append("accept","application/jwt")),si(r,"GET",i,s,null,{...n,[Pe]:Oe(t)})}var ir=Symbol();function Ue(e){return e.headers.get("content-type")?.split(";")[0]}async function ai(e,t,r,n,i){if(B(e),V(t),!ne(n,Response))throw v('"response" must be an instance of Response',$);if(ar(n),n.status!==200)throw p('"response" is not a conform UserInfo Endpoint response (unexpected HTTP status code)',yt,n);be(n);let s;if(Ue(n)==="application/jwt"){const{claims:o,jwt:a}=await gr(await n.text(),vr.bind(void 0,t.userinfo_signed_response_alg,e.userinfo_signing_alg_values_supported,void 0),Oe(t),at(t),i?.[F]).then(li.bind(void 0,t.client_id)).then(di.bind(void 0,e));or.set(n,a),s=o}else{if(t.userinfo_signed_response_alg)throw p("JWT UserInfo Response expected",Ii,n);s=await Me(n)}switch(E(s.sub,'"response" body "sub" property',m,{body:s}),r){case ir:break;default:if(E(r,'"expectedSubject"'),s.sub!==r)throw p('unexpected "response" body "sub" property value',_r,{expected:r,body:s,attribute:"sub"})}return s}async function dt(e,t,r,n,i,s,o){return await r(e,t,i,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(o?.[q]||fetch)(n.href,{body:i,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Gt(n,o?.signal)})}async function ht(e,t,r,n,i,s){const o=ve(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[H]!==!0);i.set("grant_type",n);const a=ge(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(lt(s.DPoP),await s.DPoP.addProof(o,a,"POST"));const c=await dt(e,t,r,o,i,a,s);return s?.DPoP?.cacheNonce(c,o),c}async function ci(e,t,r,n,i){B(e),V(t),E(n,'"refreshToken"');const s=new URLSearchParams(i?.additionalParameters);return s.set("refresh_token",n),ht(e,t,r,"refresh_token",s,i)}var sr=new WeakMap,or=new WeakMap;function ft(e){if(!e.id_token)return;const t=sr.get(e);if(!t)throw v('"ref" was already garbage collected or did not resolve from the proper sources',z);return t}async function Le(e,t,r,n,i,s){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,200,"Token Endpoint"),be(r);const o=await Me(r);if(E(o.access_token,'"response" body "access_token" property',m,{body:o}),E(o.token_type,'"response" body "token_type" property',m,{body:o}),o.token_type=o.token_type.toLowerCase(),o.expires_in!==void 0){let a=typeof o.expires_in!="number"?parseFloat(o.expires_in):o.expires_in;ie(a,!0,'"response" body "expires_in" property',m,{body:o}),o.expires_in=a}if(o.refresh_token!==void 0&&E(o.refresh_token,'"response" body "refresh_token" property',m,{body:o}),o.scope!==void 0&&typeof o.scope!="string")throw p('"response" body "scope" property must be a string',m,{body:o});if(o.id_token!==void 0){E(o.id_token,'"response" body "id_token" property',m,{body:o});const a=[];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(ie(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);const{claims:c,jwt:u}=await yi(e,t,o.id_token,a,i);_i(t,c),wi(c),or.set(r,u),sr.set(o,c)}if(s?.[o.token_type]!==void 0)s[o.token_type](r,o);else if(o.token_type!=="dpop"&&o.token_type!=="bearer")throw new _e("unsupported `token_type` value",{cause:{body:o}});return o}function ar(e){let t;if(t=ri(e))throw new ct("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function ui(e,t,r,n){return Le(e,t,r,void 0,n?.[F],n?.recognizedTokenTypes)}function li(e,t){return t.claims.aud!==void 0?cr(e,t):t}function cr(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw p('unexpected JWT "aud" (audience) claim value',se,{expected:e,claims:t.claims,claim:"aud"});return t}function di(e,t){return t.claims.iss!==void 0?ur(e,t):t}function ur(e,t){const r=e[br]?.(t)??e.issuer;if(t.claims.iss!==r)throw p('unexpected JWT "iss" (issuer) claim value',se,{expected:r,claims:t.claims,claim:"iss"});return t}var pt=new WeakSet;function hi(e){return pt.add(e),e}var lr=Symbol();async function fi(e,t,r,n,i,s,o){if(B(e),V(t),!pt.has(n))throw v('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',z);E(i,'"redirectUri"');const a=oe(n,"code");if(!a)throw p('no authorization code in "callbackParameters"',m);const c=new URLSearchParams(o?.additionalParameters);return c.set("redirect_uri",i),c.set("code",a),s!==lr&&(E(s,'"codeVerifier"'),c.set("code_verifier",s)),ht(e,t,r,"authorization_code",c,o)}var dr={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function pi(e,t){for(const r of e)if(t.claims[r]===void 0)throw p(`JWT "${r}" (${dr[r]}) claim missing`,m,{claims:t.claims});return t}function mi(e,t){if(typeof t.claims[e]!="string")throw p(`unexpected JWT "${e}" (${dr[e]}) claim type`,m,{claims:t.claims});return t}function yi(e,t,r,n,i){return gr(r,vr.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Oe(t),at(t),i).then(pi.bind(void 0,["aud","exp","iat","iss","sub",...n])).then(ur.bind(void 0,e)).then(cr.bind(void 0,t.client_id)).then(mi.bind(void 0,"sub"))}function hr(e,t){if(t===De)return t;const r=t===void 0;return r&&(t=e.default_max_age),t===void 0?De:(ie(t,!0,r?'"client.default_max_age"':'"maxAge" argument'),t)}function wi(e){e.auth_time!==void 0&&ie(e.auth_time,!0,'ID Token "auth_time" (authentication time)',m,{claims:e})}function fr(e,t,r){if(r===De)return;const n=Yt()+Oe(e),i=at(e);if(t.auth_time+r<n-i)throw p("too much time has elapsed since the last End-User authentication",ze,{claims:t,now:n,tolerance:i,claim:"auth_time"})}function pr(e,t){const r=t===Ce?void 0:t;if(e.nonce!==r)throw p('unexpected ID Token "nonce" claim value',se,{expected:r,claims:e,claim:"nonce"})}function _i(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw p('ID Token "aud" (audience) claim includes additional untrusted audiences',se,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw p('unexpected ID Token "azp" (authorized party) claim value',se,{expected:e.client_id,claims:t,claim:"azp"})}}var Ce=Symbol(),De=Symbol();async function gi(e,t,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?vi(e,t,r,n.expectedNonce,n.maxAge,n[F],n.recognizedTokenTypes):bi(e,t,r,n?.maxAge,n?.[F],n?.recognizedTokenTypes)}async function vi(e,t,r,n,i,s,o){const a=[];switch(n){case void 0:n=Ce;break;case Ce:break;default:E(n,'"expectedNonce" argument'),a.push("nonce")}i=hr(t,i),i!==De&&a.push("auth_time");const c=await Le(e,t,r,a,s,o);E(c.id_token,'"response" body "id_token" property',m,{body:c});const u=ft(c);return fr(t,u,i),pr(u,n),c}async function bi(e,t,r,n,i,s){const o=await Le(e,t,r,void 0,i,s),a=ft(o);return a&&(fr(t,a,hr(t,n)),pr(a,Ce)),o}var Ai="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ei="OAUTH_RESPONSE_BODY_ERROR",mt="OAUTH_UNSUPPORTED_OPERATION",Ti="OAUTH_AUTHORIZATION_RESPONSE_ERROR",Ii="OAUTH_JWT_USERINFO_EXPECTED",xe="OAUTH_PARSE_ERROR",m="OAUTH_INVALID_RESPONSE",mr="OAUTH_RESPONSE_IS_NOT_JSON",yt="OAUTH_RESPONSE_IS_NOT_CONFORM",yr="OAUTH_HTTP_REQUEST_FORBIDDEN",wr="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",ze="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",se="OAUTH_JWT_CLAIM_COMPARISON_FAILED",_r="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",Si="OAUTH_MISSING_SERVER_METADATA",Pi="OAUTH_INVALID_SERVER_METADATA";function be(e){if(e.bodyUsed)throw v('"response" body has been used already',z)}async function gr(e,t,r,n,i){let{0:s,1:o,length:a}=e.split(".");if(a===5)if(i!==void 0)e=await i(e),{0:s,1:o,length:a}=e.split(".");else throw new _e("JWE decryption is not configured",{cause:e});if(a!==3)throw p("Invalid JWT",m,e);let c;try{c=JSON.parse(nt(Re(s)))}catch(_){throw p("failed to parse JWT Header body as base64url encoded JSON",xe,_)}if(!ke(c))throw p("JWT Header must be a top level object",m,e);if(t(c),c.crit!==void 0)throw new _e('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(nt(Re(o)))}catch(_){throw p("failed to parse JWT Payload body as base64url encoded JSON",xe,_)}if(!ke(u))throw p("JWT Payload must be a top level object",m,e);const f=Yt()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw p('unexpected JWT "exp" (expiration time) claim type',m,{claims:u});if(u.exp<=f-n)throw p('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',ze,{claims:u,now:f,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw p('unexpected JWT "iat" (issued at) claim type',m,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw p('unexpected JWT "iss" (issuer) claim type',m,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw p('unexpected JWT "nbf" (not before) claim type',m,{claims:u});if(u.nbf>f+n)throw p('unexpected JWT "nbf" (not before) claim value',ze,{claims:u,now:f,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw p('unexpected JWT "aud" (audience) claim type',m,{claims:u});return{header:c,claims:u,jwt:e}}async function Ri(e){if(e.bodyUsed)throw v("form_post Request instances must contain a readable body",z,{cause:e});return e.text()}async function ki(e){if(e.method!=="POST")throw v("form_post responses are expected to use the POST method",z,{cause:e});if(Ue(e)!=="application/x-www-form-urlencoded")throw v("form_post responses are expected to use the application/x-www-form-urlencoded content-type",z,{cause:e});return Ri(e)}function vr(e,t,r,n){if(e!==void 0){if(typeof e=="string"?n.alg!==e:!e.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:t,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw p('unexpected JWT "alg" header parameter',m,{header:n,expected:r,reason:"default value"});return}throw p('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:r})}function oe(e,t){const{0:r,length:n}=e.getAll(t);if(n>1)throw p(`"${t}" parameter must be provided only once`,m);return r}var Oi=Symbol(),Ni=Symbol();function Ui(e,t,r,n){if(B(e),V(t),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw v('"parameters" must be an instance of URLSearchParams, or URL',$);if(oe(r,"response"))throw p('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',m,{parameters:r});const i=oe(r,"iss"),s=oe(r,"state");if(!i&&e.authorization_response_iss_parameter_supported)throw p('response parameter "iss" (issuer) missing',m,{parameters:r});if(i&&i!==e.issuer)throw p('unexpected "iss" (issuer) response parameter value',m,{expected:e.issuer,parameters:r});switch(n){case void 0:case Ni:if(s!==void 0)throw p('unexpected "state" response parameter encountered',m,{expected:void 0,parameters:r});break;case Oi:break;default:if(E(n,'"expectedState" argument'),s!==n)throw p(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',m,{expected:n,parameters:r})}if(oe(r,"error"))throw new nr("authorization response from the server is an error",{cause:r});const o=oe(r,"id_token"),a=oe(r,"token");if(o!==void 0||a!==void 0)throw new _e("implicit and hybrid flows are not supported");return hi(new URLSearchParams(r))}async function Li(e,t,r,n,i){B(e),V(t);const s=ve(e,"device_authorization_endpoint",t.use_mtls_endpoint_aliases,i?.[H]!==!0),o=new URLSearchParams(n);o.set("client_id",t.client_id);const a=ge(i?.headers);return a.set("accept","application/json"),dt(e,t,r,s,o,a,i)}async function Ci(e,t,r){if(B(e),V(t),!ne(r,Response))throw v('"response" must be an instance of Response',$);await ut(r,200,"Device Authorization Endpoint"),be(r);const n=await Me(r);E(n.device_code,'"response" body "device_code" property',m,{body:n}),E(n.user_code,'"response" body "user_code" property',m,{body:n}),E(n.verification_uri,'"response" body "verification_uri" property',m,{body:n});let i=typeof n.expires_in!="number"?parseFloat(n.expires_in):n.expires_in;return ie(i,!0,'"response" body "expires_in" property',m,{body:n}),n.expires_in=i,n.verification_uri_complete!==void 0&&E(n.verification_uri_complete,'"response" body "verification_uri_complete" property',m,{body:n}),n.interval!==void 0&&ie(n.interval,!1,'"response" body "interval" property',m,{body:n}),n}async function Di(e,t,r,n,i){B(e),V(t),E(n,'"deviceCode"');const s=new URLSearchParams(i?.additionalParameters);return s.set("device_code",n),ht(e,t,r,"urn:ietf:params:oauth:grant-type:device_code",s,i)}async function xi(e,t,r,n){return Le(e,t,r,void 0,n?.[F],n?.recognizedTokenTypes)}async function Me(e,t=Kt){let r;try{r=await e.json()}catch(n){throw t(e),p('failed to parse "response" body as JSON',xe,n)}if(!ke(r))throw p('"response" body must be a top level object',m,{body:r});return r}var br=Symbol(),ae,Ar;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ar="openid-client/v6.8.8",ae={"user-agent":Ar});var D=e=>wt.get(e),wt;function zi(e){if(e!==void 0)return Xt(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Er(n.client_secret,'"metadata.client_secret"'),o=Xt(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Er(e,t){if(typeof e!="string")throw J(`${t} must be a string`,je);if(e.length===0)throw J(`${t} must not be empty`,Ae)}function Mi(e){if(e!==void 0)return er(e);const t=new WeakMap;return(r,n,i,s)=>{let o;return(o=t.get(n))||(Er(n.client_secret,'"metadata.client_secret"'),o=er(n.client_secret),t.set(n,o)),o(r,n,i,s)}}function Tr(){return Gn()}var ji=ir,_t=q,Ae="ERR_INVALID_ARG_VALUE",je="ERR_INVALID_ARG_TYPE";function J(e,t,r){const n=new TypeError(e,{cause:r});return Object.assign(n,{code:t}),n}function $i(e){return Jn(e)}function Hi(){return qn()}function Bi(){return Fn()}var gt=class extends Error{code;constructor(e,t){super(e,t),this.name=this.constructor.name,this.code=t?.code,Error.captureStackTrace?.(this,this.constructor)}},Js=new TextDecoder;function O(e,t,r){return new gt(e,{cause:t,code:r})}function M(e){if(e instanceof TypeError||e instanceof gt||e instanceof Ne||e instanceof nr||e instanceof ct)throw e;if(e instanceof ot)switch(e.code){case yr:throw O("only requests to HTTPS are allowed",e,e.code);case wr:throw O("only requests to HTTP or HTTPS are allowed",e,e.code);case yt:throw O("unexpected HTTP response status code",e.cause,e.code);case mr:throw O("unexpected response content-type",e.cause,e.code);case xe:throw O("parsing error occured",e,e.code);case m:throw O("invalid response encountered",e,e.code);case se:throw O("unexpected JWT claim value encountered",e,e.code);case _r:throw O("unexpected JSON attribute value encountered",e,e.code);case ze:throw O("JWT timestamp claim value failed validation",e,e.code);default:throw O(e.message,e,e.code)}if(e instanceof _e)throw O("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw O("runtime operation error",e,mt);case"NotSupportedError":throw O("runtime unsupported operation",e,mt);case"TimeoutError":throw O("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw O("operation aborted",e,"OAUTH_ABORT")}throw new gt("something went wrong",{cause:e})}function Vi(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Wi(e){Object.defineProperties(e,Vi(e))}var qi=Symbol(),$e=class{constructor(e,t,r,n){if(typeof t!="string"||!t.length)throw J('"clientId" must be a non-empty string',je);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&t!==r.client_id)throw J('"clientId" and "metadata.client_id" must be the same',Ae);const i={...structuredClone(r),client_id:t};i[Pe]=r?.[Pe]??0,i[rt]=r?.[rt]??30;let s;n?s=n:typeof i.client_secret=="string"&&i.client_secret.length?s=zi(i.client_secret):s=Tr();let o=Object.freeze(i);const a=structuredClone(e);qi in e&&(a[br]=({claims:{tid:u}})=>e.issuer.replace("{tenantid}",u));let c=Object.freeze(a);wt||=new WeakMap,wt.set(this,{__proto__:null,as:c,c:o,auth:s,tlsOnly:!0,timeout:30,jwksCache:{}})}serverMetadata(){const e=structuredClone(D(this).as);return Wi(e),e}clientMetadata(){return structuredClone(D(this).c)}get timeout(){return D(this).timeout}set timeout(e){D(this).timeout=e}get[_t](){return D(this).fetch}set[_t](e){D(this).fetch=e}};Object.freeze($e.prototype);function Fi(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){const r=Date.now();return t>r?Math.floor((t-r)/1e3):0}}},claims:{__proto__:null,value(){return ft(e)}}}}function vt(e){Object.defineProperties(e,Fi(e))}async function Ir(e,t,r,n=!1){const i=e.headers.get("retry-after")?.trim();if(i===void 0)return;let s;if(/^\d+$/.test(i))s=parseInt(i,10);else{const o=new Date(i);if(Number.isFinite(o.getTime())){const a=new Date,c=o.getTime()-a.getTime();c>0&&(s=Math.ceil(c/1e3))}}if(n&&!Number.isFinite(s))throw new ot("invalid Retry-After header value",{cause:e});s>t&&await Sr(s-t,r)}function Sr(e,t){return new Promise((r,n)=>{const i=s=>{try{t.throwIfAborted()}catch(a){n(a);return}if(s<=0){r();return}const o=Math.min(s,5);setTimeout(()=>i(s-o),o*1e3)};i(e)})}function Ji(e,t){const r=me(t);if(!r)return{signal:e,cleanup(){}};const n=new AbortController,i=s=>{const o=s.target;n.abort(o.reason)};return e.aborted?n.abort(e.reason):r.aborted?n.abort(r.reason):(e.addEventListener("abort",i,{once:!0}),r.addEventListener("abort",i,{once:!0})),{signal:n.signal,cleanup(){e.removeEventListener("abort",i),r.removeEventListener("abort",i)}}}async function Gi(e,t,r,n,i,s,o){const a=new URLSearchParams(s);let c=t.interval??5;const u=o?.signal??AbortSignal.timeout(t.expires_in*1e3);for(;;){try{await Sr(c,u)}catch(y){M(y)}const{as:f,c:_,auth:h,fetch:d,tlsOnly:w,nonRepudiation:R,timeout:T,decrypt:N}=D(e),U=Ji(u,T);try{const y=await n(f,_,h,r,{[q]:d,[H]:!w,additionalParameters:a,DPoP:o?.DPoP,headers:new Headers(ae),signal:U.signal}).catch(M);if(y.status===503&&y.headers.has("retry-after")){await y.body?.cancel(),await Ir(y,c,u,!0),o={...o,flag:void 0};continue}let I;try{I=await i(f,_,y,{[F]:N})}catch(b){if(Ee(b,o)){o={...o,flag:Q};continue}if(b instanceof Ne&&(b.error==="slow_down"||b.error==="authorization_pending")){b.error==="slow_down"&&(c+=5),await Ir(b.response,c,u),o={...o,flag:void 0};continue}M(b)}return I.id_token&&await R?.(y),vt(I),I}finally{U.cleanup()}}}async function Ki(e,t,r,n){return ce(e),Gi(e,t,t.device_code,Di,xi,r,n)}async function Zi(e,t){ce(e);const{as:r,c:n,auth:i,fetch:s,tlsOnly:o,timeout:a}=D(e);return Li(r,n,i,t,{[q]:s,[H]:!o,headers:new Headers(ae),signal:me(a)}).then(c=>Ci(r,n,c)).catch(M)}function Yi(e){D(e).tlsOnly=!1}function Qi(e){return e=new URL(e),e.search="",e.hash="",e.href}function Xi(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Pr(e,t,r,n,i){if(ce(e),i?.flag!==Q&&!(t instanceof URL)&&!Xi(t,"Request"))throw J('"currentUrl" must be an instance of URL, or Request',je);let s,o;const{as:a,c,auth:u,fetch:f,tlsOnly:_,jarm:h,hybrid:d,nonRepudiation:w,timeout:R,decrypt:T,implicit:N}=D(e);if(i?.flag===Q)s=i.authResponse,o=i.redirectUri;else{if(!(t instanceof URL)){const b=t;switch(t=new URL(t.url),b.method){case"GET":break;case"POST":const le=new URLSearchParams(await ki(b));if(d)t.hash=le.toString();else for(const[He,Tt]of le.entries())t.searchParams.append(He,Tt);break;default:throw J("unexpected Request HTTP method",Ae)}}switch(o=Qi(t),!0){case!!h:s=await h(t,r?.expectedState);break;case!!d:s=await d(t,r?.expectedNonce,r?.expectedState,r?.maxAge);break;case!!N:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{s=Ui(a,c,t.searchParams,r?.expectedState)}catch(b){M(b)}}}const U=await fi(a,c,u,s,o,r?.pkceCodeVerifier||lr,{additionalParameters:n,[q]:f,[H]:!_,DPoP:i?.DPoP,headers:new Headers(ae),signal:me(R)}).catch(M);(typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number")&&(r.idTokenExpected=!0);const y=gi(a,c,U,{expectedNonce:r?.expectedNonce,maxAge:r?.maxAge,requireIdToken:r?.idTokenExpected,[F]:T});let I;try{I=await y}catch(b){if(Ee(b,i))return Pr(e,void 0,r,n,{...i,flag:Q,authResponse:s,redirectUri:o});M(b)}return I.id_token&&await w?.(U),vt(I),I}async function Rr(e,t,r,n){ce(e),r=new URLSearchParams(r);const{as:i,c:s,auth:o,fetch:a,tlsOnly:c,nonRepudiation:u,timeout:f,decrypt:_}=D(e),h=await ci(i,s,o,t,{[q]:a,[H]:!c,additionalParameters:r,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(f)}).catch(M),d=ui(i,s,h,{[F]:_});let w;try{w=await d}catch(R){if(Ee(R,n))return Rr(e,t,r,{...n,flag:Q});M(R)}return w.id_token&&await u?.(h),vt(w),w}function bt(e,t){ce(e);const{as:r,c:n,tlsOnly:i,hybrid:s,jarm:o,implicit:a}=D(e),c=ve(r,"authorization_endpoint",!1,i);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",n.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",s?"code id_token":a?"id_token":"code"),a&&!t.has("nonce"))throw J("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",Ae);o&&t.set("response_mode","jwt")}for(const[u,f]of t.entries())c.searchParams.append(u,f);return c}async function kr(e,t,r){ce(e);const n=bt(e,t),{as:i,c:s,auth:o,fetch:a,tlsOnly:c,timeout:u}=D(e),f=await Zn(i,s,o,n.searchParams,{[q]:a,[H]:!c,DPoP:r?.DPoP,headers:new Headers(ae),signal:me(u)}).catch(M),_=ni(i,s,f);let h;try{h=await _}catch(d){if(Ee(d,r))return kr(e,t,{...r,flag:Q});M(d)}return bt(e,{request_uri:h.request_uri})}function ce(e){if(!(e instanceof $e))throw J('"config" must be an instance of Configuration',je);if(Object.getPrototypeOf(e)!==$e.prototype)throw J("subclassing Configuration is not allowed",Ae)}function me(e){return e?AbortSignal.timeout(e*1e3):void 0}async function Or(e,t,r,n){ce(e);const{as:i,c:s,fetch:o,tlsOnly:a,nonRepudiation:c,timeout:u,decrypt:f}=D(e),_=await oi(i,s,t,{[q]:o,[H]:!a,DPoP:n?.DPoP,headers:new Headers(ae),signal:me(u)}).catch(M);let h=ai(i,s,r,_,{[F]:f}),d;try{d=await h}catch(w){if(Ee(w,n))return Or(e,t,r,{...n,flag:Q});M(w)}return Ue(_)==="application/jwt"&&await c?.(_),d}function Ee(e,t){return t?.DPoP&&t.flag!==Q?Yn(e):!1}var Q=Symbol(),es={issuer:"{issuer}",authorization_endpoint:"{issuer}/oauth/authorize",token_endpoint:"{issuer}/oauth/token",device_authorization_endpoint:"{issuer}/oauth/device/authorize",jwks_uri:"{issuer}/.well-known/jwks.json",userinfo_endpoint:"{issuer}/oauth/userinfo",registration_endpoint:"{issuer}/oauth/clients/register",scopes_supported:["openid","profile","email","phone","offline_access"],response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:device_code"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256","HS256","ES256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],claims_supported:["sub","aud","iss","exp","iat","auth_time","nonce","email","email_verified","phone_number","phone_number_verified","name","picture","preferred_username","updated_at"],code_challenge_methods_supported:["S256","plain"],pushed_authorization_request_endpoint:"{issuer}/oauth/par"};function ts(e){return JSON.parse(JSON.stringify(es).replaceAll("{issuer}",e))}var rs=6e5,ns=2048,is=["authorization_details","login_hint"],ss=class{#e;#t;#i;#s;#r;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#i=e.clientSecret??null,this.#s=e.transport??"auto"}get isConfidential(){return this.#i!==null}async createAuthorizationRequest(e={}){try{const t=this.#c(e.redirectTo),r=Hi(),n=await $i(r),i=e.state??Bi(),s=this.#h(e,t,i,n),o=await this.#l(s);return l.ok({authorizationUrl:o,codeVerifier:r,state:i,redirectTo:t,createdAt:Date.now()})}catch(t){return l.fail(A.from(t,"authorization_request_failed"))}}async exchangeCallback(e){try{const t=new URL(e.callbackUrl),{request:r}=e;if(!Number.isSafeInteger(r.createdAt)||Date.now()-r.createdAt>rs)return l.fail(g.INVALID_CALLBACK,{message:"the authorization transaction expired"});if(as(t,new URL(r.redirectTo))){if(t.searchParams.get("state")!==r.state)return l.fail(g.INVALID_CALLBACK,{message:"the callback state does not correlate"})}else return l.fail(g.INVALID_CALLBACK,{message:"the callback does not match redirectTo"});const n=t.searchParams.get("error");if(n)return l.fail(n.slice(0,256),{message:t.searchParams.get("error_description")?.slice(0,2048)??n});if(!t.searchParams.has("code"))return l.fail(g.INVALID_CALLBACK,{message:"the callback carries no authorization code"});const i=await Pr(this.#n(),t,{pkceCodeVerifier:r.codeVerifier,expectedState:r.state});return await this.#o(i)}catch(t){return l.fail(A.from(t,"authorization_exchange_failed"))}}async resolveAuthorizationUrl(e,t){try{return l.ok(await this.#l(e,t))}catch(r){return l.fail(A.from(r,"authorization_request_failed"))}}async refresh(e){try{const t=await Rr(this.#n(),e);return await this.#o(t)}catch(t){return l.fail(A.from(t,"refresh_failed"))}}async userInfo(e){try{const t=Nr(e),r=await Or(this.#n(),e,t?t.sub:ji);return l.ok({id:String(r.sub),name:r.name,email:r.email,avatarUrl:r.picture})}catch(t){return l.fail(A.from(t,"userinfo_failed"))}}async createDeviceAuthorizationRequest(e={}){try{const t=await Zi(this.#n(),{scope:this.#u(e).join(" ")});return l.ok({deviceCode:t.device_code,userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete??t.verification_uri,expiresIn:t.expires_in,interval:t.interval??5,raw:t})}catch(t){return l.fail(A.from(t,"device_authorization_failed"))}}async awaitDeviceAuthorization(e,t={}){try{const r=await Ki(this.#n(),e.raw,void 0,{signal:t.signal});return await this.#o(r)}catch(r){return l.fail(A.from(r,"device_exchange_failed"))}}configuration(){return this.#n()}#n(){return this.#r??=this.#a(),this.#r}#a(){const e=this.#e,t=e.endpoints.auth,r=`${t.origin}${t.pathname.replace(/\/+$/,"")}`,n=this.#i,i=new $e(ts(r),e.clientId,n??void 0,n?Mi(n):Tr());return i[_t]=((s,o)=>this.#t(s,o)),Yi(i),i}#c(e){const t=e??this.#e.redirectTo;if(!t)throw new A(g.INVALID_CONFIGURATION,{message:"redirectTo is required, on the instance or on the request"});return new URL(t).href}#u(e){const t=(e.authorizations??[]).flatMap(n=>[...n.scopes]),r=e.scopes??this.#e.initialScopes;return[...new Set([...r,...t])]}#h(e,t,r,n){const i=new URLSearchParams({client_id:this.#e.clientId,response_type:"code",redirect_uri:t,state:r,code_challenge:n,code_challenge_method:"S256"}),s=this.#u(e);s.length&&i.set("scope",s.join(" "));const o=new Set;for(const u of os(e.resource))o.add(u);for(const u of e.authorizations??[])o.add(u.resource);for(const u of o)i.append("resource",u);const a=[...e.authorizationDetails??[],...(e.authorizations??[]).flatMap(u=>[...u.authorizationDetails??[]])];a.length&&i.set("authorization_details",JSON.stringify(a));const c=e.orgId??(e.authorizations??[]).find(u=>u.orgId)?.orgId;return c&&i.set("org_id",c),e.externalId&&i.set("external_id",e.externalId),i}async#l(e,t){const r=this.#n(),n=bt(r,e),i=is.some(o=>e.has(o)),s=t??this.#s;return(s==="auto"?i||n.href.length>ns?"par":"get":s)==="get"?n:await kr(r,e)}async#o(e){if(e.token_type&&e.token_type.toLowerCase()!=="bearer")return l.fail(g.INVALID_RESPONSE,{message:"unsupported token type"});const t=e.claims?.()?.sub??Nr(e.access_token)?.sub;if(!t)return l.fail(g.INVALID_RESPONSE,{message:"the response carries no subject"});const r={accessToken:e.access_token,refreshToken:e.refresh_token??null,tokenType:e.token_type??"bearer",expiresAt:Math.floor(Date.now()/1e3)+(e.expires_in??0),scopes:(e.scope??"").split(/\s+/).filter(Boolean),user:{id:t,name:null,email:null,avatarUrl:null}},n=await this.userInfo(r.accessToken);return l.ok(n.data?{...r,user:n.data}:r)}};function os(e){return e===void 0?[]:typeof e=="string"?[e]:e}function as(e,t){return e.origin!==t.origin||e.pathname!==t.pathname?!1:[...t.searchParams].every(([r,n])=>e.searchParams.getAll(r).includes(n))}function Nr(e){const t=e.split(".");if(t.length<2||!t[1])return null;try{const r=JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")),n=>n.charCodeAt(0))));return r&&typeof r=="object"&&typeof r.sub=="string"?{sub:r.sub}:null}catch{return null}}var cs=new Set(["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE","request"]);function us(e,t){return new Proxy(e,{get(r,n,i){const s=Reflect.get(r,n,i);if(typeof n!="string"||!cs.has(n)||typeof s!="function")return s;const o=s;return(...a)=>ls(o.apply(r,a),t)}})}function ls(e,t){const r=e.then(n=>n.error===void 0?{data:n.data,response:n.response}:{error:t(n.error,n.response),response:n.response},n=>{const i=Response.error();return{error:t(n,i),response:i}});return Object.assign(r,{throwOnError:()=>r.then(n=>{if(n.error!==void 0)throw n.error;return n})})}var Ur=class{#e;#t;#i;#s;http;raw;constructor(e){this.#e=e.config,this.#t=e.fetch,this.#i=e.credentials,this.#s=e.resource??e.config.endpoints.api.origin,this.raw=Mn({endpoint:this.#e.endpoints.api,apiVersion:this.#e.apiVersion,accessToken:()=>this.#i.accessTokenFor(this.#s),fetch:this.#t}),this.http=us(this.raw,An.fromOpenAPIFetch)}},ds=class{#e=new Map;getItem(e){return this.#e.get(e)??null}setItem(e,t){this.#e.set(e,t)}removeItem(e){this.#e.delete(e)}},hs=class{storage;constructor(e){this.storage=e}getItem(e){return this.storage.getItem(e)}setItem(e,t){this.storage.setItem(e,t)}removeItem(e){this.storage.removeItem(e)}},fs=class{#e=new Map;async acquire(e,t){const r=(this.#e.get(e)??Promise.resolve()).then(t,t),n=r.then(()=>{},()=>{});this.#e.set(e,n);try{return await r}finally{this.#e.get(e)===n&&this.#e.delete(e)}}},Lr=class{#e;#t;#i;#s=new Set;#r;#n;#a;#c;constructor(e){this.#e=e,this.#t=e.storage??new ds,this.#i=e.lock??new fs,this.#r=`andco.session.${e.config.clientId}`,this.#n=e.initialSession,this.#a=e.initialSession}getSnapshot(){return this.#a}getServerSnapshot(){return this.#n}subscribe(e){return this.#s.add(e),this.#u(),()=>{this.#s.delete(e)}}get ready(){return this.#u()}async accessTokenFor(e){await this.#u();const t=this.#a;if(!t)return null;if(!$t(t))return Xe(t,e);const r=await this.#i.acquire(`${this.#r}:${e}`,async()=>{const n=this.#a;if(!n)return null;if(!$t(n))return n;if(!n.refreshToken)return null;const i=await this.#e.oauth.refresh(n.refreshToken);return i.error?null:(await this.#l(i.data),i.data)});return r?Xe(r,e):null}async set(e){this.#c??=Promise.resolve(l.ok(void 0));try{return await this.#l(e),l.ok(void 0)}catch(t){return l.fail(A.from(t,g.STORAGE_FAILED))}}#u(){return this.#c??=this.#h(),this.#c}async#h(){try{const e=this.#e.source?await this.#e.source():null;if(e?.error)return this.#o(this.#a??null),l.fail(e.error);if(e?.data)return await this.#l(e.data),l.ok(void 0);if(this.#n!==void 0)return this.#o(this.#n),l.ok(void 0);const t=await this.#t.getItem(this.#r);return this.#o(t?ps(t):null),l.ok(void 0)}catch(e){return this.#o(this.#a??null),l.fail(A.from(e,g.STORAGE_FAILED))}}async#l(e){this.#e.persist!==!1&&(e?await this.#t.setItem(this.#r,JSON.stringify(e)):await this.#t.removeItem(this.#r)),this.#o(e)}#o(e){this.#a=e;for(const t of[...this.#s])t()}};function ps(e){try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;const r=t;return typeof r.accessToken!="string"||typeof r.expiresAt!="number"||!r.user||typeof r.user.id!="string"?null:r}catch{return null}}function ms(){return new A(g.BROWSER_REQUIRED)}var ys=class $r{config;clientSecret;globals;oauth;rest;intents;auth;session;isAuthed=!1;constructor(t){this.config=Sn.from(t),this.clientSecret=t.clientSecret??null,this.globals={fetch:t.globals?.fetch??globalThis.fetch.bind(globalThis),crypto:t.globals?.crypto??globalThis.crypto},this.oauth=new ss({config:this.config,fetch:this.globals.fetch,clientSecret:this.clientSecret,transport:t.transport}),this.session=new Lr({config:this.config,oauth:this.oauth,storage:t.storage,initialSession:t.initialSession,lock:t.lock,source:t.source,persist:t.persist}),this.auth=new jt({oauth:this.oauth,store:this.session,presenter:t.presenter??Cr(),persistTransaction:t.persistTransaction,crypto:this.globals.crypto}),this.rest=new Ur({config:this.config,fetch:this.globals.fetch,credentials:this.session}),this.intents=new Jt(this.rest,this.globals.crypto)}with(t){return new ws(this,$r.resolveCredentials(t))}authorized(){return new _s(this)}static resolveCredentials(t){return typeof t=="string"?{accessTokenFor:async()=>t}:Rn(t)?t:Pn(t)}};function Cr(){return{async present(){return l.fail(ms())}}}var ws=class{credentials;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e,t){this.credentials=t,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=new Ur({config:e.config,fetch:e.globals.fetch,credentials:t}),this.intents=new Jt(this.rest,e.globals.crypto),this.session=new Lr({config:e.config,oauth:e.oauth,persist:!1}),this.auth=new jt({oauth:e.oauth,store:this.session,presenter:Cr(),crypto:e.globals.crypto})}accessTokenFor(e){return this.credentials.accessTokenFor(e)}},_s=class{owner;isAuthed=!0;config;clientSecret;globals;oauth;rest;intents;auth;session;constructor(e){this.owner=e,this.config=e.config,this.clientSecret=e.clientSecret,this.globals=e.globals,this.oauth=e.oauth,this.rest=e.rest,this.intents=e.intents,this.auth=e.auth,this.session=e.session}accessTokenFor(e){return this.owner.session.accessTokenFor(e)}},gs=/^[A-Za-z0-9_-]{8,128}$/,vs=6e5,bs=400;function As(){return typeof window<"u"&&window.__ANDCO_NATIVE_HOST__===!0&&typeof window.ReactNativeWebView?.postMessage=="function"}function Dr(){if(typeof window>"u"||!window.opener||window.opener===window||!window.name.startsWith("andco-popup-"))return null;const e=window.name.slice(Mt.length);return gs.test(e)?e:null}function Es(e,t={}){if(typeof window>"u")return{status:"not_callback"};const r=t.callbackUrl?new URL(t.callbackUrl,window.location.href):new URL(window.location.href);if(!(t.callbackUrl||r.searchParams.has("code")||r.searchParams.has("error")))return{status:"not_callback"};const n=Dr();if(!n)return{status:"not_popup"};const i=r.searchParams.get("state"),s=(i?nn(i)?.openerOrigin:null)??window.location.origin;if(s!==window.location.origin&&!e.has(s))return{status:"rejected",error:new A(g.UNTRUSTED_ORIGIN)};const o=s===window.location.origin?Ts(n,r):Is(n,r);for(const a of["code","state","error","error_description"])r.searchParams.delete(a);return window.history.replaceState(window.history.state,"",r),window.name="",window.opener?.postMessage(o,s),window.close(),{status:"relayed",presentationId:n}}function Ts(e,t){return{protocol:"andco",version:1,presentationId:e,callbackUrl:t.href}}function Is(e,t){const r={protocol:pe,version:2,presentationId:e},n=t.searchParams.get("code");if(n)return{...r,type:"oauth.authorization_code",authorizationCode:n};const i=t.searchParams.get("error")??"invalid_request";if(i==="access_denied")return{...r,type:"oauth.dismiss"};const s=t.searchParams.get("error_description");return{...r,type:"oauth.error",error:{code:i.slice(0,256),description:s?s.slice(0,2048):void 0}}}function Ss(e){const t=window.open(e.url?.href??"about:blank",`${Mt}${e.presentationId}`,Rs({width:620,height:720}));return t?{blocked:!1,navigate:r=>t.location.assign(r.href),result:new Promise(r=>{let n=!1;const i=c=>{n||(n=!0,window.removeEventListener("message",s),window.clearInterval(o),window.clearTimeout(a),r(c))},s=c=>{if(c.origin!==e.expectedOrigin||c.source!==t)return;const u=c.data;if(!(!u||u.protocol!=="andco"||u.presentationId!==e.presentationId)&&typeof u.callbackUrl=="string"){t.close();try{i(l.ok(new URL(u.callbackUrl)))}catch{i(l.fail(g.INVALID_CALLBACK))}}};window.addEventListener("message",s);const o=window.setInterval(()=>{t.closed&&i(l.ok(null))},bs),a=window.setTimeout(()=>{t.close(),i(l.fail(g.POPUP_TIMEOUT))},vs);e.signal?.addEventListener("abort",()=>{t.close(),i(l.ok(null))})}),close:()=>t.close()}:{blocked:!0,navigate:()=>{},result:Promise.resolve(l.fail(g.POPUP_BLOCKED)),close:()=>{}}}function Ps(e){return Ss(e).result}function Rs(e){const t=Math.max(0,Math.round((window.screen.width-e.width)/2)),r=Math.max(0,Math.round((window.screen.height-e.height)/2));return`popup=1,width=${e.width},height=${e.height},left=${t},top=${r}`}var ks=class{iframe;options;url;settled=!1;transport="pending";port;handshakeTimer;handshakeTimeout;handshakeAttempts=0;handshakeStartedAt=0;destroyed=!1;constructor(e,t){if(this.iframe=e,this.options=t,typeof window>"u"||typeof document>"u")throw new A(g.BROWSER_UNAVAILABLE);if(!(e instanceof HTMLIFrameElement))throw new A(g.INVALID_IFRAME,{details:{iframe:e}});if(this.url=new URL(t.endpointButton),this.url.origin===window.location.origin)throw new A(g.SAME_ORIGIN_ENDPOINT,{details:{endpointButton:this.url.href}});console.debug("[AndcoButtonBridge] created: %o",{endpointButton:this.url.href}),e.addEventListener("load",this.startHandshake),this.startHandshake()}stopHandshake(){this.handshakeTimer!==void 0&&window.clearInterval(this.handshakeTimer),this.handshakeTimeout!==void 0&&window.clearTimeout(this.handshakeTimeout),this.handshakeTimer=void 0,this.handshakeTimeout=void 0}closePort(){this.port?.close(),this.port=void 0}receive(e){if(bn(e))switch(e.type){case"ready":if(this.settled)return;this.settled=!0,this.stopHandshake(),console.debug("[AndcoButtonBridge] handshake settled: %o",{attempts:this.handshakeAttempts,transport:this.transport,elapsedMs:Date.now()-this.handshakeStartedAt}),this.options.onReady?.(e);return;case"error":this.settled||(this.settled=!0,this.stopHandshake()),console.warn("[AndcoButtonBridge] hosted surface reported an error: %o",e.error),this.options.onError?.(e);return;case"oauth.authorization_code":case"oauth.complete":case"intent.complete":if(!this.settled)return;this.options.onComplete?.(e);return;case"oauth.dismiss":case"intent.dismiss":this.settled&&this.options.onDismiss?.(e);return;case"oauth.error":this.settled&&this.options.onAuthorizationError?.(e);return;case"click":this.settled&&this.options.onActivate?.(e);return}}receiveWindow=e=>{this.transport==="port"||e.origin!==this.url.origin||e.source!==this.iframe.contentWindow||(this.transport="window",this.receive(e.data))};initialize=()=>{const e=this.iframe.contentWindow;if(!e)return;this.handshakeAttempts+=1,this.closePort();const t=new MessageChannel;this.port=t.port1,this.port.onmessage=n=>{this.transport!=="window"&&(this.transport="port",window.removeEventListener("message",this.receiveWindow),this.receive(n.data))};const r={protocol:pe,version:2,type:"init"};try{e.postMessage(r,this.url.origin,[t.port2])}catch(n){console.debug("[AndcoButtonBridge] init attempt %d could not post yet, retrying: %o",this.handshakeAttempts,{cause:n})}};startHandshake=()=>{this.stopHandshake(),this.settled=!1,this.transport="pending",this.handshakeAttempts=0,this.handshakeStartedAt=Date.now(),window.addEventListener("message",this.receiveWindow),this.initialize(),this.handshakeTimer=window.setInterval(this.initialize,250),this.handshakeTimeout=window.setTimeout(()=>{this.settled=!0,this.stopHandshake(),this.closePort(),console.error("[AndcoButtonBridge] handshake timed out: %o",{attempts:this.handshakeAttempts,endpointButton:this.url.href});const e={protocol:pe,version:2,type:"error",error:{code:re.HANDSHAKE_TIMEOUT}};this.options.onError?.(e)},1e4)};post(e){if(!(this.destroyed||!this.settled)){if(this.transport==="port"&&this.port){this.port.postMessage(e);return}this.iframe.contentWindow?.postMessage(e,this.url.origin)}}resolveAuthorization(e,t){const r={protocol:pe,version:2,type:"authorization-response",presentationId:e,authorizationUrl:t?.toString()};this.post(r)}forwardAuthorizationResult(e){this.post(e)}setPreferences(e){const t={protocol:pe,version:2,type:"set-preferences",...e};this.post(t)}destroy(){this.destroyed||(console.debug("[AndcoButtonBridge] destroyed: %o",{settled:this.settled,attempts:this.handshakeAttempts}),this.destroyed=!0,window.removeEventListener("message",this.receiveWindow),this.iframe.removeEventListener("load",this.startHandshake),this.stopHandshake(),this.closePort())}},Os=class{#e;#t=new Set;#i;#s;#r;#n;#a;#c=0;#u=!1;constructor(e){this.#e=e,this.#r={status:"idle",iframeURL:this.#f(),ready:!1,error:null}}get snapshot(){return this.#r}subscribe(e){return this.#t.add(e),e(this.#r),()=>{this.#t.delete(e)}}connect(e){this.disconnect(),this.#s=e,console.debug("[AndcoButtonController] connecting: %o",{iframeURL:this.#r.iframeURL}),this.#d({status:"connecting",ready:!1,error:null});try{this.#i=new ks(e,{endpointButton:this.#f(),onReady:t=>{this.#d({status:"ready",ready:!0}),this.#e.onReady?.(t)},onActivate:t=>{this.#a=t.presentationId,this.#e.onActivate?.(t),this.#h()},onComplete:t=>{this.#l(t)},onDismiss:()=>{this.#d({status:"dismissed"}),this.#e.onDismiss?.()},onAuthorizationError:t=>this.#o(new A(t.error.code,{message:t.error.description})),onError:t=>{if(t.error.code===re.HANDSHAKE_TIMEOUT&&!this.#u&&this.#s){this.#u=!0,console.debug("[AndcoButtonController] handshake timed out",{action:"reconnect",retry:1}),this.connect(this.#s);return}this.#o(new A(t.error.code),t)}})}catch(t){this.#o(A.from(t,g.INVALID_IFRAME))}return()=>this.disconnect()}disconnect(){this.#i?.destroy(),this.#i=void 0}restart(){if(this.#c+=1,this.#n=void 0,this.#r.status==="error"&&this.#s){this.#u=!1,console.debug("[AndcoButtonController] restarting after an error, reconnecting: %o",{code:this.#r.error?.code}),this.connect(this.#s);return}this.#d({status:this.#i?"ready":"idle",error:null})}destroy(){this.disconnect(),this.#s=void 0,this.#t.clear()}async#h(){const e=++this.#c;this.#d({status:"authorizing",error:null});const t=await this.#e.client.oauth.createAuthorizationRequest({...this.#e.authorization??{},state:rn(this.#e.client.config.endpoints.widget.origin,this.#a)});if(e===this.#c){if(t.error)return this.#o(t.error);this.#n=t.data,this.#i?.resolveAuthorization(this.#a,t.data.authorizationUrl.href)}}async#l(e){const t=this.#c,r=this.#n;if(this.#n=void 0,e.type==="oauth.authorization_code"&&r){const n=new URL(r.redirectTo);n.searchParams.set("code",e.authorizationCode),n.searchParams.set("state",r.state);const i=await this.#e.client.oauth.exchangeCallback({callbackUrl:n,request:r});if(t!==this.#c)return;if(i.error)return this.#o(i.error);const s=await this.#e.client.session.set(i.data);if(s.error)return this.#o(s.error)}t===this.#c&&(this.#d({status:"complete",error:null}),this.#e.onComplete?.())}#o(e,t){console.error("[AndcoButtonController] %s: %o",e.code,{message:e.message,details:e.details}),this.#d({status:"error",error:e}),this.#e.onError?.(e,t)}#f(){const e=this.#e.client.config,t=e.widgetURL(this.#e.release??1780358400);return t.searchParams.set("themeMode",this.#e.themeMode??e.themeMode),t.searchParams.set("locale",this.#e.locale??e.locale),t.searchParams.set("theme",e.theme),t.searchParams.set("flow",this.#e.flow??"authorization"),t.searchParams.set("presentation",this.#e.presentation??"popup"),t.searchParams.set("endpointAuth",e.endpoints.auth.href),t.searchParams.set("clientId",e.clientId),e.redirectTo&&t.searchParams.set("redirectTo",e.redirectTo.href),this.#e.disabled!==void 0&&t.searchParams.set("disabled",String(this.#e.disabled)),this.#e.busy!==void 0&&t.searchParams.set("busy",String(this.#e.busy)),t.href}#d(e){this.#r={...this.#r,...e,iframeURL:this.#f()};for(const t of[...this.#t])t(this.#r)}};function Ns(){return{async present(e){return typeof window>"u"?l.fail(g.BROWSER_REQUIRED):e.presentation==="redirect"?(window.location.assign(e.url.href),l.ok(null)):As()&&window.__ANDCO_NATIVE_POPUP_HANDLER__!==!0?l.fail(g.PRESENTATION_UNSUPPORTED,{message:"the native Host cannot present a popup without navigating the Miniapp"}):Ps({url:e.url,presentationId:e.presentationId,expectedOrigin:e.returnTo.origin,signal:e.signal})}}}var At="andco.transaction";function Us(e){const t=e.presenter??Ns(),r=e.storage??(typeof window>"u"?void 0:new hs(window.sessionStorage)),n=new ys({...e,presenter:t,storage:r,source:()=>Ls(n.config,n.oauth,e),persistTransaction:i=>Cs(n.config.clientId,i,e.transactionStorage)});return e.relayPopupCallback!==!1&&typeof window<"u"&&Es(n.config.allowedPopupOrigins),n}async function Ls(e,t,r){if(r.detectSessionInUrl===!1||typeof window>"u"||Dr())return l.ok(null);const n=new URL(window.location.href);if(!n.searchParams.has("code")&&!n.searchParams.has("error"))return l.ok(null);const i=r.transactionStorage??window.sessionStorage,s=i.getItem(`${At}.${e.clientId}`);if(!s)return l.ok(null);i.removeItem(`${At}.${e.clientId}`);let o;try{const c=JSON.parse(s);o={...c,authorizationUrl:new URL(c.authorizationUrl)}}catch{return l.fail(g.INVALID_CALLBACK)}const a=await t.exchangeCallback({callbackUrl:n,request:o});for(const c of["code","state","error","error_description"])n.searchParams.delete(c);return(r.replaceUrl??(c=>window.history.replaceState(window.history.state,"",c)))(n),a.error?l.fail(a.error):l.ok(a.data)}function Cs(e,t,r){(r??window.sessionStorage).setItem(`${At}.${e}`,JSON.stringify({...t,authorizationUrl:t.authorizationUrl.href}))}var Et=new Map;function xr(e){const t=JSON.stringify(e,Object.keys(e).sort()),r=Et.get(t);if(r)return r;const n=Us(e);return Et.set(t,n),n}function Ds(){const e="andco-button-default-style";if(typeof document>"u"||document.getElementById(e))return;const t=document.createElement("style");t.id=e,t.textContent="@layer andco { andco-button { display: block; height: 3rem; width: 18rem } }",document.head.append(t)}var xs=["client-id","endpoint-auth","endpoint-api","endpoint-widget","redirect-to","locale","theme-mode","scopes","flow","disabled","busy"],zr=class extends HTMLElement{static observedAttributes=xs;#e;#t;#i;#s;authorizations;connectedCallback(){Ds(),this.#n()}disconnectedCallback(){this.#r()}attributeChangedCallback(){this.isConnected&&this.#n()}#r(){this.#t?.(),this.#i?.(),this.#e?.destroy(),this.#t=void 0,this.#i=void 0,this.#e=void 0}#n(){this.#r();const e=this.getAttribute("client-id");if(!e)return;const t=xr({clientId:e,...ue("endpointAuth",this.getAttribute("endpoint-auth")),...ue("endpointApi",this.getAttribute("endpoint-api")),...ue("endpointWidget",this.getAttribute("endpoint-widget")),...ue("redirectTo",this.getAttribute("redirect-to")),...ue("locale",this.getAttribute("locale")),initialScopes:this.getAttribute("scopes")?.split(/\s+/).filter(Boolean)}),r=this.getAttribute("scopes")?.split(/\s+/).filter(Boolean);this.#e=new Os({client:t,flow:this.getAttribute("flow")??void 0,...ue("themeMode",this.getAttribute("theme-mode")),...ue("locale",this.getAttribute("locale")),disabled:this.hasAttribute("disabled"),busy:this.hasAttribute("busy"),authorization:{...r?.length?{scopes:r}:{},authorizations:this.authorizations},onReady:()=>this.dispatchEvent(new CustomEvent("andco-ready")),onActivate:()=>this.dispatchEvent(new CustomEvent("andco-activate")),onComplete:()=>this.dispatchEvent(new CustomEvent("andco-complete")),onDismiss:()=>this.dispatchEvent(new CustomEvent("andco-dismiss")),onError:i=>this.dispatchEvent(new CustomEvent("andco-error",{detail:i}))});const n=this.#s??document.createElement("iframe");this.#s=n,n.referrerPolicy="no-referrer",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"),n.title=this.getAttribute("title")??"Andco",n.style.cssText="border:0;display:block;height:100%;width:100%",n.isConnected||this.append(n),this.#i=this.#e.subscribe(i=>{n.src!==i.iframeURL&&(n.src=i.iframeURL),n.hidden=!i.ready}),this.#t=this.#e.connect(n)}};function zs(e){const t=e.getAttribute("client-id");for(const[r,n]of Et)if(t&&r.includes(`"${t}"`))return n.session.getSnapshot()}function Ms(e){return xr(e)}function ue(e,t){return t?{[e]:t}:{}}return typeof customElements<"u"&&!customElements.get("andco-button")&&customElements.define("andco-button",zr),we.AndcoButtonElement=zr,we.andcoInstance=Ms,we.andcoSessionFor=zs,we})({});
|
|
2
|
+
|
|
3
|
+
//# sourceMappingURL=andco.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { AndcoClient, AndcoSession } from "@andco/sdk";
|
|
2
|
+
/**
|
|
3
|
+
* The hosted Andco control as a custom element.
|
|
4
|
+
*
|
|
5
|
+
* Configuration arrives through attributes and there is no registration step, so a plain HTML page
|
|
6
|
+
* needs no module-level setup. Anything that is not a scalar — a Resource Server's authorization
|
|
7
|
+
* contribution, for instance — is set as a property, which is the standard Web Components split.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```html
|
|
11
|
+
* <andco-button client-id="…" redirect-to="…" scopes="openid email profile"></andco-button>
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare class AndcoButtonElement extends HTMLElement {
|
|
15
|
+
#private;
|
|
16
|
+
static readonly observedAttributes: readonly ["client-id", "endpoint-auth", "endpoint-api", "endpoint-widget", "redirect-to", "locale", "theme-mode", "scopes", "flow", "disabled", "busy"];
|
|
17
|
+
/** Resource Server contributions. An object, so it arrives as a property rather than an attribute. */
|
|
18
|
+
authorizations: unknown[] | undefined;
|
|
19
|
+
connectedCallback(): void;
|
|
20
|
+
disconnectedCallback(): void;
|
|
21
|
+
attributeChangedCallback(): void;
|
|
22
|
+
}
|
|
23
|
+
/** Reads the session of the instance an element resolves to, for pages that need it. */
|
|
24
|
+
export declare function andcoSessionFor(element: AndcoButtonElement): AndcoSession | null | undefined;
|
|
25
|
+
/** Resolves the instance a set of options describes, for page code that needs one directly. */
|
|
26
|
+
export declare function andcoInstance(options: Record<string, unknown>): AndcoClient;
|
|
27
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { AndcoButtonController, createAndcoInstanceForBrowser, } from "@andco/sdk/browser";
|
|
2
|
+
/**
|
|
3
|
+
* Instances shared by normalized configuration.
|
|
4
|
+
*
|
|
5
|
+
* Several elements on one page describe the same OAuth client, and several instances would mean
|
|
6
|
+
* several sessions and several storage listeners for one user. Keying by the configuration they
|
|
7
|
+
* declare makes them resolve the same one.
|
|
8
|
+
*/
|
|
9
|
+
const instances = new Map();
|
|
10
|
+
function instanceFor(options) {
|
|
11
|
+
const key = JSON.stringify(options, Object.keys(options).sort());
|
|
12
|
+
const existing = instances.get(key);
|
|
13
|
+
if (existing)
|
|
14
|
+
return existing;
|
|
15
|
+
const created = createAndcoInstanceForBrowser(options);
|
|
16
|
+
instances.set(key, created);
|
|
17
|
+
return created;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Default box for the element.
|
|
21
|
+
*
|
|
22
|
+
* A bare iframe is 300x150 with a border and the hosted control fills whatever box it is given, so
|
|
23
|
+
* without this a plain page sees a bordered grey slab. It is a cascade layer because unlayered
|
|
24
|
+
* author CSS beats a layer whatever the order, so a page that styles `andco-button` still wins.
|
|
25
|
+
*/
|
|
26
|
+
function installDefaultStyle() {
|
|
27
|
+
const id = "andco-button-default-style";
|
|
28
|
+
if (typeof document === "undefined" || document.getElementById(id))
|
|
29
|
+
return;
|
|
30
|
+
const style = document.createElement("style");
|
|
31
|
+
style.id = id;
|
|
32
|
+
style.textContent = "@layer andco { andco-button { display: block; height: 3rem; width: 18rem } }";
|
|
33
|
+
document.head.append(style);
|
|
34
|
+
}
|
|
35
|
+
const SCALAR_ATTRIBUTES = [
|
|
36
|
+
"client-id",
|
|
37
|
+
"endpoint-auth",
|
|
38
|
+
"endpoint-api",
|
|
39
|
+
"endpoint-widget",
|
|
40
|
+
"redirect-to",
|
|
41
|
+
"locale",
|
|
42
|
+
"theme-mode",
|
|
43
|
+
"scopes",
|
|
44
|
+
"flow",
|
|
45
|
+
"disabled",
|
|
46
|
+
"busy",
|
|
47
|
+
];
|
|
48
|
+
/**
|
|
49
|
+
* The hosted Andco control as a custom element.
|
|
50
|
+
*
|
|
51
|
+
* Configuration arrives through attributes and there is no registration step, so a plain HTML page
|
|
52
|
+
* needs no module-level setup. Anything that is not a scalar — a Resource Server's authorization
|
|
53
|
+
* contribution, for instance — is set as a property, which is the standard Web Components split.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```html
|
|
57
|
+
* <andco-button client-id="…" redirect-to="…" scopes="openid email profile"></andco-button>
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export class AndcoButtonElement extends HTMLElement {
|
|
61
|
+
static observedAttributes = SCALAR_ATTRIBUTES;
|
|
62
|
+
#controller;
|
|
63
|
+
#disconnect;
|
|
64
|
+
#unsubscribe;
|
|
65
|
+
#iframe;
|
|
66
|
+
/** Resource Server contributions. An object, so it arrives as a property rather than an attribute. */
|
|
67
|
+
authorizations;
|
|
68
|
+
connectedCallback() {
|
|
69
|
+
installDefaultStyle();
|
|
70
|
+
this.#build();
|
|
71
|
+
}
|
|
72
|
+
disconnectedCallback() {
|
|
73
|
+
this.#teardown();
|
|
74
|
+
}
|
|
75
|
+
attributeChangedCallback() {
|
|
76
|
+
if (this.isConnected)
|
|
77
|
+
this.#build();
|
|
78
|
+
}
|
|
79
|
+
#teardown() {
|
|
80
|
+
this.#disconnect?.();
|
|
81
|
+
this.#unsubscribe?.();
|
|
82
|
+
this.#controller?.destroy();
|
|
83
|
+
this.#disconnect = undefined;
|
|
84
|
+
this.#unsubscribe = undefined;
|
|
85
|
+
this.#controller = undefined;
|
|
86
|
+
}
|
|
87
|
+
#build() {
|
|
88
|
+
this.#teardown();
|
|
89
|
+
const clientId = this.getAttribute("client-id");
|
|
90
|
+
if (!clientId)
|
|
91
|
+
return;
|
|
92
|
+
const client = instanceFor({
|
|
93
|
+
clientId,
|
|
94
|
+
...optional("endpointAuth", this.getAttribute("endpoint-auth")),
|
|
95
|
+
...optional("endpointApi", this.getAttribute("endpoint-api")),
|
|
96
|
+
...optional("endpointWidget", this.getAttribute("endpoint-widget")),
|
|
97
|
+
...optional("redirectTo", this.getAttribute("redirect-to")),
|
|
98
|
+
...optional("locale", this.getAttribute("locale")),
|
|
99
|
+
initialScopes: this.getAttribute("scopes")?.split(/\s+/).filter(Boolean),
|
|
100
|
+
});
|
|
101
|
+
const scopes = this.getAttribute("scopes")?.split(/\s+/).filter(Boolean);
|
|
102
|
+
this.#controller = new AndcoButtonController({
|
|
103
|
+
client,
|
|
104
|
+
flow: this.getAttribute("flow") ?? undefined,
|
|
105
|
+
...optional("themeMode", this.getAttribute("theme-mode")),
|
|
106
|
+
...optional("locale", this.getAttribute("locale")),
|
|
107
|
+
disabled: this.hasAttribute("disabled"),
|
|
108
|
+
busy: this.hasAttribute("busy"),
|
|
109
|
+
authorization: {
|
|
110
|
+
...(scopes?.length ? { scopes } : {}),
|
|
111
|
+
authorizations: this.authorizations,
|
|
112
|
+
},
|
|
113
|
+
// Namespaced because a custom element dispatching a bare `error` shadows the platform's own
|
|
114
|
+
// ErrorEvent, and a listener cannot tell the two apart.
|
|
115
|
+
onReady: () => this.dispatchEvent(new CustomEvent("andco-ready")),
|
|
116
|
+
onActivate: () => this.dispatchEvent(new CustomEvent("andco-activate")),
|
|
117
|
+
onComplete: () => this.dispatchEvent(new CustomEvent("andco-complete")),
|
|
118
|
+
onDismiss: () => this.dispatchEvent(new CustomEvent("andco-dismiss")),
|
|
119
|
+
onError: (error) => this.dispatchEvent(new CustomEvent("andco-error", { detail: error })),
|
|
120
|
+
});
|
|
121
|
+
const iframe = this.#iframe ?? document.createElement("iframe");
|
|
122
|
+
this.#iframe = iframe;
|
|
123
|
+
iframe.referrerPolicy = "no-referrer";
|
|
124
|
+
iframe.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox");
|
|
125
|
+
iframe.title = this.getAttribute("title") ?? "Andco";
|
|
126
|
+
iframe.style.cssText = "border:0;display:block;height:100%;width:100%";
|
|
127
|
+
if (!iframe.isConnected)
|
|
128
|
+
this.append(iframe);
|
|
129
|
+
this.#unsubscribe = this.#controller.subscribe((snapshot) => {
|
|
130
|
+
if (iframe.src !== snapshot.iframeURL)
|
|
131
|
+
iframe.src = snapshot.iframeURL;
|
|
132
|
+
iframe.hidden = !snapshot.ready;
|
|
133
|
+
});
|
|
134
|
+
this.#disconnect = this.#controller.connect(iframe);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Reads the session of the instance an element resolves to, for pages that need it. */
|
|
138
|
+
export function andcoSessionFor(element) {
|
|
139
|
+
const clientId = element.getAttribute("client-id");
|
|
140
|
+
for (const [key, client] of instances) {
|
|
141
|
+
if (clientId && key.includes(`"${clientId}"`))
|
|
142
|
+
return client.session.getSnapshot();
|
|
143
|
+
}
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
/** Resolves the instance a set of options describes, for page code that needs one directly. */
|
|
147
|
+
export function andcoInstance(options) {
|
|
148
|
+
return instanceFor(options);
|
|
149
|
+
}
|
|
150
|
+
// TODO: is this actually necessary? If not i prefer to delete it.
|
|
151
|
+
function optional(key, value) {
|
|
152
|
+
return value ? { [key]: value } : {};
|
|
153
|
+
}
|
|
154
|
+
if (typeof customElements !== "undefined" && !customElements.get("andco-button")) {
|
|
155
|
+
customElements.define("andco-button", AndcoButtonElement);
|
|
156
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@andco/sdk-script",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"sideEffects": true,
|
|
10
|
+
"unpkg": "./dist/andco.js",
|
|
11
|
+
"jsdelivr": "./dist/andco.js",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./andco.js": "./dist/andco.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"!dist/*.map"
|
|
23
|
+
],
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@andco/sdk": "0.0.1"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^6.0.3",
|
|
29
|
+
"vite": "^8.3.0"
|
|
30
|
+
},
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"description": "Standalone browser bundle of the Andco SDK, for loading with a <script> tag.",
|
|
33
|
+
"scripts": {
|
|
34
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
35
|
+
"build": "pnpm run clean && tsc && vite build",
|
|
36
|
+
"dev": "tsc --watch --preserveWatchOutput & vite build --watch",
|
|
37
|
+
"check-types": "tsc --noEmit",
|
|
38
|
+
"lint": "tsc --noEmit",
|
|
39
|
+
"test": "vitest run"
|
|
40
|
+
}
|
|
41
|
+
}
|