go-better-auth 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 GoBetterAuth
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,323 @@
1
+ # GoBetterAuth Node.js SDK
2
+
3
+ Official GoBetterAuth SDK. This SDK provides seamless integration with GoBetterAuth authentication server for both client-side and server-side applications and is framework agnostic (React, Vue.js and more).
4
+
5
+ ## Features
6
+
7
+ - **Framework Agnostic**: Works with React, Vue.js, Angular, and more
8
+ - **Full TypeScript Support**: Complete TypeScript definitions with strict typing
9
+ - **SSR Safe**: Supports proper cookie handling for SSR apps
10
+ - **CSRF Protection**: Automatic CSRF token handling for mutating requests
11
+ - **Multiple Auth Methods**: Email/password, OAuth2, JWT-based authentication
12
+ - **Plugin Architecture**: Extensible plugin system for custom authentication flows
13
+ - **Automatic Token Refresh**: Built-in bearer token refresh mechanism
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install go-better-auth
19
+ # or
20
+ yarn add go-better-auth
21
+ # or
22
+ pnpm add go-better-auth
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ### Basic Setup
28
+
29
+ ```typescript
30
+ import { createClient } from "go-better-auth";
31
+ import { EmailPasswordPlugin } from "go-better-auth/plugins";
32
+
33
+ // Create a client instance
34
+ const goBetterAuthClient = createClient({
35
+ url: "http://localhost:8080", // Your GoBetterAuth server URL
36
+ plugins: [
37
+ new EmailPasswordPlugin()
38
+ ]
39
+ });
40
+
41
+ // Now you can use the client to perform authentication operations
42
+ ```
43
+
44
+ ### Using with Cookies (SSR Compatible)
45
+
46
+ For server-side rendering or applications that need to handle cookies properly:
47
+
48
+ ```typescript
49
+ import { cookies } from "next/headers";
50
+
51
+ import { createClient } from "go-better-auth";
52
+ import { EmailPasswordPlugin, CSRFPlugin } from "go-better-auth/plugins";
53
+
54
+ const goBetterAuthClient = createClient({
55
+ url: "http://localhost:8080/auth",
56
+ cookies: cookies, // Provide cookie store for SSR
57
+ plugins: [
58
+ new EmailPasswordPlugin(),
59
+ new CSRFPlugin({
60
+ cookieName: "csrf_token",
61
+ headerName: "X-CSRF-TOKEN"
62
+ })
63
+ ]
64
+ });
65
+ ```
66
+
67
+ ## Available Plugins
68
+
69
+ ### Email Password Plugin
70
+
71
+ Handles traditional email/password authentication flows.
72
+
73
+ ```typescript
74
+ import { EmailPasswordPlugin } from "go-better-auth/plugins";
75
+
76
+ const goBetterAuthClient = createClient({
77
+ url: "http://localhost:8080",
78
+ plugins: [
79
+ new EmailPasswordPlugin()
80
+ ]
81
+ });
82
+
83
+ // Sign up
84
+ await goBetterAuthClient.emailPassword.signUp({
85
+ name: "John Doe",
86
+ email: "john@example.com",
87
+ password: "securePassword123"
88
+ });
89
+
90
+ // Sign in
91
+ const response = await goBetterAuthClient.emailPassword.signIn({
92
+ email: "john@example.com",
93
+ password: "securePassword123"
94
+ });
95
+
96
+ // Send email verification
97
+ await goBetterAuthClient.emailPassword.sendEmailVerification({
98
+ email: "john@example.com"
99
+ });
100
+
101
+ // Request password reset
102
+ await goBetterAuthClient.emailPassword.requestPasswordReset({
103
+ email: "john@example.com"
104
+ });
105
+
106
+ // Change password
107
+ await goBetterAuthClient.emailPassword.changePassword({
108
+ token: "reset-token",
109
+ password: "newSecurePassword123"
110
+ });
111
+ ```
112
+
113
+ ### OAuth2 Plugin
114
+
115
+ Handles OAuth2 authentication with popular providers.
116
+
117
+ ```typescript
118
+ import { OAuth2Plugin } from "go-better-auth/plugins";
119
+
120
+ const goBetterAuthClient = createClient({
121
+ url: "http://localhost:8080/auth",
122
+ plugins: [
123
+ new OAuth2Plugin()
124
+ ]
125
+ });
126
+
127
+ // Redirect user to OAuth2 provider
128
+ const response = await goBetterAuthClient.oauth2.signIn({
129
+ provider: "google", // or "github", "discord"
130
+ redirect_to: "http://localhost:3000/callback"
131
+ });
132
+
133
+ // Redirect user to the authUrl
134
+ window.location.href = response.auth_url;
135
+ ```
136
+
137
+ ### CSRF Plugin
138
+
139
+ Provides automatic CSRF protection for mutating requests.
140
+
141
+ ```typescript
142
+ import { CSRFPlugin } from "go-better-auth/plugins";
143
+
144
+ const goBetterAuthClient = createClient({
145
+ url: "http://localhost:8080/auth",
146
+ cookies: ..., // Provide cookie store for SSR if needed, else omit for SPA/Mobile apps
147
+ plugins: [
148
+ new CSRFPlugin({
149
+ cookieName: "csrf_token", // Name of the CSRF token cookie
150
+ headerName: "X-CSRF-TOKEN" // Header name to send the token
151
+ })
152
+ ]
153
+ });
154
+
155
+ // CSRF tokens will be automatically added to mutating requests (POST, PUT, PATCH, DELETE)
156
+ ```
157
+
158
+ ### JWT Plugin
159
+
160
+ Handles JWT token operations including refresh.
161
+
162
+ ```typescript
163
+ import { JWTPlugin } from "go-better-auth/plugins";
164
+
165
+ const goBetterAuthClient = createClient({
166
+ url: "http://localhost:8080/auth",
167
+ plugins: [
168
+ new JWTPlugin()
169
+ ]
170
+ });
171
+
172
+ // Refresh JWT tokens
173
+ const tokens = await goBetterAuthClient.jwt.refreshToken({
174
+ refresh_token: "your-refresh-token"
175
+ });
176
+
177
+ // Get JWKS keys
178
+ const jwksKeys = await goBetterAuthClient.jwt.getJWKSKeys();
179
+ ```
180
+
181
+ ### Bearer Plugin
182
+
183
+ Provides automatic bearer token handling and refresh.
184
+
185
+ ```typescript
186
+ import { BearerPlugin, JWTPlugin } from "go-better-auth/plugins";
187
+
188
+ const goBetterAuthClient = createClient({
189
+ url: "http://localhost:8080/auth",
190
+ plugins: [
191
+ new JWTPlugin(),
192
+ new BearerPlugin({
193
+ headerName: "Authorization" // Can be omitted as default is Authorization
194
+ })
195
+ ]
196
+ });
197
+
198
+ // The Bearer plugin will automatically:
199
+ // 1. Add Authorization: Bearer <token> header to requests
200
+ // 2. Handle token refresh when receiving 401 responses
201
+ // 3. Store tokens in localStorage (access_token and refresh_token)
202
+ ```
203
+
204
+ ## Advanced Configuration
205
+
206
+ ### Fetch Options
207
+
208
+ Configure fetch behavior with timeout and other options:
209
+
210
+ ```typescript
211
+ const goBetterAuthClient = createClient({
212
+ url: "http://localhost:8080/auth",
213
+ fetchOptions: {
214
+ abortTimeout: 30 // Timeout in seconds
215
+ },
216
+ plugins: [
217
+ // your plugins
218
+ ]
219
+ });
220
+ ```
221
+
222
+ ### Custom Hooks
223
+
224
+ Add custom before/after fetch hooks for advanced customization:
225
+
226
+ ```typescript
227
+ const goBetterAuthClient = createClient({
228
+ url: "http://localhost:8080/auth",
229
+ plugins: [
230
+ new EmailPasswordPlugin()
231
+ ]
232
+ });
233
+
234
+ // Register a before fetch hook
235
+ goBetterAuthClient.registerBeforeFetch(async (ctx) => {
236
+ console.log(`Making request to: ${ctx.url}`);
237
+ // Modify context if needed
238
+ ctx.init.headers = {
239
+ ...ctx.init.headers,
240
+ "X-Custom-Header": "value"
241
+ };
242
+ });
243
+
244
+ // Register an after fetch hook
245
+ goBetterAuthClient.registerAfterFetch(async (ctx, response) => {
246
+ console.log(`Received response: ${response.status}`);
247
+ if (response.status >= 400) {
248
+ // Handle error
249
+ }
250
+ });
251
+ ```
252
+
253
+ ## API Reference
254
+
255
+ ### Client Configuration
256
+
257
+ ```typescript
258
+ {
259
+ // Base URL of your GoBetterAuth server
260
+ url: string,
261
+ // Optional fetch configuration
262
+ fetchOptions?: {
263
+ // Request timeout in seconds
264
+ abortTimeout?: number
265
+ },
266
+ // Cookie provider for SSR compatibility
267
+ cookies?: () => CookieStore
268
+ }
269
+ ```
270
+
271
+ ### Available Methods
272
+
273
+ Once plugins are initialized, they expose methods on the client:
274
+
275
+ ## API Reference
276
+
277
+ `EmailPassword Plugin`:
278
+
279
+ | Method | Description |
280
+ |---------------------------------------------|------------------------------|
281
+ | `client.emailPassword.signUp(data)` | Create a new user account |
282
+ | `client.emailPassword.signIn(data)` | Authenticate a user |
283
+ | `client.emailPassword.sendEmailVerification(data)` | Send email verification |
284
+ | `client.emailPassword.requestPasswordReset(data)` | Request password reset |
285
+ | `client.emailPassword.changePassword(data)` | Change user password |
286
+ | `client.emailPassword.requestEmailChange(data)` | Request email change |
287
+
288
+ `OAuth2 Plugin`:
289
+
290
+ | Method | Description |
291
+ |---------------------------------------------|------------------------------|
292
+ | `client.oauth2.signIn(data)` | Initiate OAuth2 flow |
293
+
294
+ `JWT Plugin`:
295
+
296
+ | Method | Description |
297
+ |---------------------------------------------|------------------------------|
298
+ | `client.jwt.refreshToken(data)` | Refresh JWT tokens |
299
+ | `client.jwt.getJWKSKeys()` | Get JWKS keys |
300
+
301
+ ## Error Handling
302
+
303
+ All methods return promises that can be caught for error handling:
304
+
305
+ ```typescript
306
+ try {
307
+ const response = await goBetterAuthClient.emailPassword.signIn({
308
+ email: "user@example.com",
309
+ password: "password"
310
+ });
311
+ console.log("Signed in successfully", response);
312
+ } catch (error) {
313
+ console.error("Sign in failed:", error);
314
+ }
315
+ ```
316
+
317
+ ## Contributing
318
+
319
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
320
+
321
+ ## License
322
+
323
+ This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
@@ -0,0 +1,68 @@
1
+ //#region src/fetch.ts
2
+ async function wrappedFetch(client, endpoint, options = {}) {
3
+ const headers = new Headers(options.headers || {});
4
+ let cookieStore = null;
5
+ if (client.config.cookies) {
6
+ cookieStore = await client.config.cookies();
7
+ const cookieHeader = cookieStore.getAll().map((c) => `${c.name}=${c.value}`).join("; ");
8
+ if (cookieHeader) headers.set("cookie", cookieHeader);
9
+ }
10
+ const controller = new AbortController();
11
+ const abortTimeout = client.config.fetchOptions?.abortTimeout;
12
+ if (abortTimeout) setTimeout(() => controller.abort(), abortTimeout * 1e3);
13
+ const ctx = {
14
+ url: `${client.config.url}${endpoint}`,
15
+ init: {
16
+ method: options.method ?? "GET",
17
+ headers,
18
+ body: options.body ? JSON.stringify(options.body) : void 0,
19
+ credentials: "include",
20
+ signal: controller.signal
21
+ },
22
+ meta: {}
23
+ };
24
+ await client.runBeforeFetch(ctx);
25
+ let res = await fetch(ctx.url, ctx.init);
26
+ if (await client.runAfterFetch(ctx, res) === "retry" && !ctx.meta.retry) {
27
+ ctx.meta.retry = true;
28
+ res = await fetch(ctx.url, ctx.init);
29
+ }
30
+ const setCookieHeaders = res.headers.getSetCookie?.() ?? res.headers.get("set-cookie")?.split(", ") ?? null;
31
+ if (!res.ok) throw new Error(await res.text());
32
+ const data = await res.json();
33
+ if (cookieStore && setCookieHeaders) for (const raw of setCookieHeaders) {
34
+ const [pair, ...attrs] = raw.split(";");
35
+ const [name, value] = pair.split("=");
36
+ if (!name || !value) continue;
37
+ const options = {};
38
+ for (const attr of attrs) {
39
+ const [k, v] = attr.trim().split("=");
40
+ switch (k.toLowerCase()) {
41
+ case "path":
42
+ options.path = v;
43
+ break;
44
+ case "expires":
45
+ options.expires = new Date(v);
46
+ break;
47
+ case "max-age":
48
+ options.maxAge = Number(v);
49
+ break;
50
+ case "httponly":
51
+ options.httpOnly = true;
52
+ break;
53
+ case "secure":
54
+ options.secure = true;
55
+ break;
56
+ case "samesite":
57
+ options.sameSite = v?.toLowerCase();
58
+ break;
59
+ }
60
+ }
61
+ cookieStore.set(name.trim(), decodeURIComponent(value.trim()), options);
62
+ }
63
+ return data;
64
+ }
65
+
66
+ //#endregion
67
+ export { wrappedFetch as t };
68
+ //# sourceMappingURL=fetch-Cp9z9f4v.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-Cp9z9f4v.js","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["import type { GoBetterAuthClient } from \"./client\";\nimport type { CookieStore, FetchContext, FetchRequestOptions } from \"./types\";\n\nexport async function wrappedFetch<T>(\n client: GoBetterAuthClient,\n endpoint: string,\n options: FetchRequestOptions = {},\n): Promise<T> {\n const headers = new Headers(options.headers || {});\n\n let cookieStore: CookieStore | null = null;\n\n if (client.config.cookies) {\n cookieStore = await client.config.cookies();\n\n const cookieHeader = cookieStore\n .getAll()\n .map((c) => `${c.name}=${c.value}`)\n .join(\"; \");\n\n if (cookieHeader) {\n headers.set(\"cookie\", cookieHeader);\n }\n }\n\n const controller = new AbortController();\n const abortTimeout = client.config.fetchOptions?.abortTimeout;\n\n if (abortTimeout) {\n setTimeout(() => controller.abort(), abortTimeout * 1000);\n }\n\n const ctx: FetchContext = {\n url: `${client.config.url}${endpoint}`,\n init: {\n method: options.method ?? \"GET\",\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n credentials: \"include\",\n signal: controller.signal,\n },\n meta: {},\n };\n\n await client.runBeforeFetch(ctx);\n\n let res = await fetch(ctx.url, ctx.init);\n\n const action = await client.runAfterFetch(ctx, res);\n if (action === \"retry\" && !ctx.meta.retry) {\n ctx.meta.retry = true;\n res = await fetch(ctx.url, ctx.init);\n }\n\n const setCookieHeaders =\n res.headers.getSetCookie?.() ??\n res.headers.get(\"set-cookie\")?.split(\", \") ??\n null;\n\n if (!res.ok) {\n throw new Error(await res.text());\n }\n\n const data = await res.json();\n\n // Apply Set-Cookie back into Next.js store (SSR only)\n if (cookieStore && setCookieHeaders) {\n for (const raw of setCookieHeaders) {\n const [pair, ...attrs] = raw.split(\";\");\n const [name, value] = pair.split(\"=\");\n\n if (!name || !value) continue;\n\n const options: Record<string, any> = {};\n\n for (const attr of attrs) {\n const [k, v] = attr.trim().split(\"=\");\n\n switch (k.toLowerCase()) {\n case \"path\":\n options.path = v;\n break;\n case \"expires\":\n options.expires = new Date(v);\n break;\n case \"max-age\":\n options.maxAge = Number(v);\n break;\n case \"httponly\":\n options.httpOnly = true;\n break;\n case \"secure\":\n options.secure = true;\n break;\n case \"samesite\":\n options.sameSite = v?.toLowerCase();\n break;\n }\n }\n\n cookieStore.set(name.trim(), decodeURIComponent(value.trim()), options);\n }\n }\n\n return data as T;\n}\n"],"mappings":";AAGA,eAAsB,aACpB,QACA,UACA,UAA+B,EAAE,EACrB;CACZ,MAAM,UAAU,IAAI,QAAQ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AAC,MAAO;EAErB,MAAM,UAA+B,EAAE;AAEvC,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,CAAC,GAAG,KAAK,KAAK,MAAM,CAAC,MAAM,IAAI;AAErC,WAAQ,EAAE,aAAa,EAAvB;IACE,KAAK;AACH,aAAQ,OAAO;AACf;IACF,KAAK;AACH,aAAQ,UAAU,IAAI,KAAK,EAAE;AAC7B;IACF,KAAK;AACH,aAAQ,SAAS,OAAO,EAAE;AAC1B;IACF,KAAK;AACH,aAAQ,WAAW;AACnB;IACF,KAAK;AACH,aAAQ,SAAS;AACjB;IACF,KAAK;AACH,aAAQ,WAAW,GAAG,aAAa;AACnC;;;AAIN,cAAY,IAAI,KAAK,MAAM,EAAE,mBAAmB,MAAM,MAAM,CAAC,EAAE,QAAQ;;AAI3E,QAAO"}
@@ -0,0 +1,74 @@
1
+
2
+ //#region src/fetch.ts
3
+ async function wrappedFetch(client, endpoint, options = {}) {
4
+ const headers = new Headers(options.headers || {});
5
+ let cookieStore = null;
6
+ if (client.config.cookies) {
7
+ cookieStore = await client.config.cookies();
8
+ const cookieHeader = cookieStore.getAll().map((c) => `${c.name}=${c.value}`).join("; ");
9
+ if (cookieHeader) headers.set("cookie", cookieHeader);
10
+ }
11
+ const controller = new AbortController();
12
+ const abortTimeout = client.config.fetchOptions?.abortTimeout;
13
+ if (abortTimeout) setTimeout(() => controller.abort(), abortTimeout * 1e3);
14
+ const ctx = {
15
+ url: `${client.config.url}${endpoint}`,
16
+ init: {
17
+ method: options.method ?? "GET",
18
+ headers,
19
+ body: options.body ? JSON.stringify(options.body) : void 0,
20
+ credentials: "include",
21
+ signal: controller.signal
22
+ },
23
+ meta: {}
24
+ };
25
+ await client.runBeforeFetch(ctx);
26
+ let res = await fetch(ctx.url, ctx.init);
27
+ if (await client.runAfterFetch(ctx, res) === "retry" && !ctx.meta.retry) {
28
+ ctx.meta.retry = true;
29
+ res = await fetch(ctx.url, ctx.init);
30
+ }
31
+ const setCookieHeaders = res.headers.getSetCookie?.() ?? res.headers.get("set-cookie")?.split(", ") ?? null;
32
+ if (!res.ok) throw new Error(await res.text());
33
+ const data = await res.json();
34
+ if (cookieStore && setCookieHeaders) for (const raw of setCookieHeaders) {
35
+ const [pair, ...attrs] = raw.split(";");
36
+ const [name, value] = pair.split("=");
37
+ if (!name || !value) continue;
38
+ const options = {};
39
+ for (const attr of attrs) {
40
+ const [k, v] = attr.trim().split("=");
41
+ switch (k.toLowerCase()) {
42
+ case "path":
43
+ options.path = v;
44
+ break;
45
+ case "expires":
46
+ options.expires = new Date(v);
47
+ break;
48
+ case "max-age":
49
+ options.maxAge = Number(v);
50
+ break;
51
+ case "httponly":
52
+ options.httpOnly = true;
53
+ break;
54
+ case "secure":
55
+ options.secure = true;
56
+ break;
57
+ case "samesite":
58
+ options.sameSite = v?.toLowerCase();
59
+ break;
60
+ }
61
+ }
62
+ cookieStore.set(name.trim(), decodeURIComponent(value.trim()), options);
63
+ }
64
+ return data;
65
+ }
66
+
67
+ //#endregion
68
+ Object.defineProperty(exports, 'wrappedFetch', {
69
+ enumerable: true,
70
+ get: function () {
71
+ return wrappedFetch;
72
+ }
73
+ });
74
+ //# sourceMappingURL=fetch-v3PWCtqe.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-v3PWCtqe.cjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["import type { GoBetterAuthClient } from \"./client\";\nimport type { CookieStore, FetchContext, FetchRequestOptions } from \"./types\";\n\nexport async function wrappedFetch<T>(\n client: GoBetterAuthClient,\n endpoint: string,\n options: FetchRequestOptions = {},\n): Promise<T> {\n const headers = new Headers(options.headers || {});\n\n let cookieStore: CookieStore | null = null;\n\n if (client.config.cookies) {\n cookieStore = await client.config.cookies();\n\n const cookieHeader = cookieStore\n .getAll()\n .map((c) => `${c.name}=${c.value}`)\n .join(\"; \");\n\n if (cookieHeader) {\n headers.set(\"cookie\", cookieHeader);\n }\n }\n\n const controller = new AbortController();\n const abortTimeout = client.config.fetchOptions?.abortTimeout;\n\n if (abortTimeout) {\n setTimeout(() => controller.abort(), abortTimeout * 1000);\n }\n\n const ctx: FetchContext = {\n url: `${client.config.url}${endpoint}`,\n init: {\n method: options.method ?? \"GET\",\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n credentials: \"include\",\n signal: controller.signal,\n },\n meta: {},\n };\n\n await client.runBeforeFetch(ctx);\n\n let res = await fetch(ctx.url, ctx.init);\n\n const action = await client.runAfterFetch(ctx, res);\n if (action === \"retry\" && !ctx.meta.retry) {\n ctx.meta.retry = true;\n res = await fetch(ctx.url, ctx.init);\n }\n\n const setCookieHeaders =\n res.headers.getSetCookie?.() ??\n res.headers.get(\"set-cookie\")?.split(\", \") ??\n null;\n\n if (!res.ok) {\n throw new Error(await res.text());\n }\n\n const data = await res.json();\n\n // Apply Set-Cookie back into Next.js store (SSR only)\n if (cookieStore && setCookieHeaders) {\n for (const raw of setCookieHeaders) {\n const [pair, ...attrs] = raw.split(\";\");\n const [name, value] = pair.split(\"=\");\n\n if (!name || !value) continue;\n\n const options: Record<string, any> = {};\n\n for (const attr of attrs) {\n const [k, v] = attr.trim().split(\"=\");\n\n switch (k.toLowerCase()) {\n case \"path\":\n options.path = v;\n break;\n case \"expires\":\n options.expires = new Date(v);\n break;\n case \"max-age\":\n options.maxAge = Number(v);\n break;\n case \"httponly\":\n options.httpOnly = true;\n break;\n case \"secure\":\n options.secure = true;\n break;\n case \"samesite\":\n options.sameSite = v?.toLowerCase();\n break;\n }\n }\n\n cookieStore.set(name.trim(), decodeURIComponent(value.trim()), options);\n }\n }\n\n return data as T;\n}\n"],"mappings":";;AAGA,eAAsB,aACpB,QACA,UACA,UAA+B,EAAE,EACrB;CACZ,MAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,EAAE,CAAC;CAElD,IAAI,cAAkC;AAEtC,KAAI,OAAO,OAAO,SAAS;AACzB,gBAAc,MAAM,OAAO,OAAO,SAAS;EAE3C,MAAM,eAAe,YAClB,QAA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