@insforge/sdk 1.4.0 → 1.4.2

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/README.md CHANGED
@@ -56,6 +56,19 @@ const admin = createAdminClient({
56
56
 
57
57
  `apiKey` belongs in `createAdminClient()`. Public and user-scoped clients use `anonKey`.
58
58
 
59
+ ### Acting as a User on the Server
60
+
61
+ In edge functions or other server code that receives a user's JWT, seed the client with it via `accessToken`:
62
+
63
+ ```javascript
64
+ const insforge = createClient({
65
+ baseUrl: "http://localhost:7130",
66
+ accessToken: userJwt, // e.g. from the request's Authorization header
67
+ });
68
+ ```
69
+
70
+ All requests run as that user (RLS applies). The token is used as-is — the SDK does not refresh it. `edgeFunctionToken` is a deprecated alias for this option.
71
+
59
72
  ### Authentication
60
73
 
61
74
  ```javascript
@@ -353,6 +366,11 @@ import { createBrowserClient } from "@insforge/sdk/ssr";
353
366
  export const insforge = createBrowserClient();
354
367
  ```
355
368
 
369
+ `createBrowserClient()` is for Client Components that consume an existing SSR
370
+ session. Its TypeScript surface does not include auth mutations such as
371
+ `signInWithPassword()`, `signUp()`, or `signOut()`. Run auth mutations on the
372
+ server so the app can write server-owned auth cookies.
373
+
356
374
  ```typescript
357
375
  // app/lib/insforge/server.ts
358
376
  import { cookies } from "next/headers";
@@ -370,18 +388,126 @@ import { createRefreshAuthRouter } from "@insforge/sdk/ssr";
370
388
  export const { POST } = createRefreshAuthRouter();
371
389
  ```
372
390
 
373
- For server-owned refresh cookies, run sign-in in a Route Handler or Server Action and use `setAuthCookies()` from `@insforge/sdk/ssr` with the framework cookie writer. In Next.js Route Handlers, pass `response.cookies`:
391
+ For sign-in, sign-up, and sign-out, use `createAuthActions()` in a Server
392
+ Action file. Server Actions are stable in Next.js 14+. Do not return raw auth
393
+ responses from Server Actions; return only the user or app-specific safe fields
394
+ so access and refresh tokens stay server-owned.
374
395
 
375
396
  ```typescript
376
- import { NextResponse } from "next/server";
377
- import { setAuthCookies } from "@insforge/sdk/ssr";
397
+ // app/actions.ts
398
+ "use server";
378
399
 
379
- const response = NextResponse.json({ user: data.user });
380
- setAuthCookies(response.cookies, {
381
- accessToken: data.accessToken,
382
- refreshToken: data.refreshToken,
383
- });
384
- return response;
400
+ import { cookies } from "next/headers";
401
+ import { createAuthActions } from "@insforge/sdk/ssr";
402
+
403
+ export async function signIn(formData: FormData) {
404
+ const auth = createAuthActions({ cookies: await cookies() });
405
+
406
+ const { data, error } = await auth.signInWithPassword({
407
+ email: String(formData.get("email")),
408
+ password: String(formData.get("password")),
409
+ });
410
+
411
+ return { user: data?.user ?? null, error };
412
+ }
413
+ ```
414
+
415
+ For OAuth in SSR apps, start and finish the flow on the server. Store the PKCE
416
+ verifier in an httpOnly app cookie and exchange the callback code with
417
+ `createAuthActions()`:
418
+
419
+ ```typescript
420
+ // app/actions.ts
421
+ "use server";
422
+
423
+ import { cookies } from "next/headers";
424
+ import { redirect } from "next/navigation";
425
+ import { createAuthActions } from "@insforge/sdk/ssr";
426
+
427
+ export async function signInWithGoogle() {
428
+ const cookieStore = await cookies();
429
+ const auth = createAuthActions({ cookies: cookieStore });
430
+ const { data, error } = await auth.signInWithOAuth("google", {
431
+ redirectTo: new URL(
432
+ "/api/auth/callback",
433
+ process.env.NEXT_PUBLIC_APP_URL
434
+ ).toString(),
435
+ skipBrowserRedirect: true,
436
+ });
437
+
438
+ if (error || !data.url || !data.codeVerifier) {
439
+ throw new Error(error?.message ?? "OAuth init failed");
440
+ }
441
+
442
+ cookieStore.set("insforge_code_verifier", data.codeVerifier, {
443
+ httpOnly: true,
444
+ secure: process.env.NODE_ENV === "production",
445
+ sameSite: "lax",
446
+ path: "/",
447
+ maxAge: 600,
448
+ });
449
+
450
+ redirect(data.url);
451
+ }
452
+ ```
453
+
454
+ ```typescript
455
+ // app/api/auth/callback/route.ts
456
+ import { cookies } from "next/headers";
457
+ import { NextResponse, type NextRequest } from "next/server";
458
+ import { createAuthActions } from "@insforge/sdk/ssr";
459
+
460
+ export async function GET(request: NextRequest) {
461
+ const code = request.nextUrl.searchParams.get("insforge_code");
462
+ const verifier = (await cookies()).get("insforge_code_verifier")?.value;
463
+ if (!code || !verifier) {
464
+ return NextResponse.redirect(new URL("/login?error=oauth", request.url));
465
+ }
466
+
467
+ const response = NextResponse.redirect(new URL("/dashboard", request.url));
468
+ const auth = createAuthActions({
469
+ requestCookies: request.cookies,
470
+ responseCookies: response.cookies,
471
+ });
472
+ const { error } = await auth.exchangeOAuthCode(code, verifier);
473
+ if (error) {
474
+ return NextResponse.redirect(new URL("/login?error=oauth", request.url));
475
+ }
476
+
477
+ response.cookies.delete("insforge_code_verifier");
478
+ return response;
479
+ }
480
+ ```
481
+
482
+ SSR browser clients do not exchange OAuth callbacks automatically. OAuth
483
+ callbacks must be completed on the server so the refresh token lands in the
484
+ httpOnly app cookie.
485
+
486
+ For Route Handlers, pass request cookies for reading the current session and
487
+ response cookies for writing the next session:
488
+
489
+ ```typescript
490
+ // app/api/auth/sign-out/route.ts
491
+ import { NextResponse, type NextRequest } from "next/server";
492
+ import { createAuthActions } from "@insforge/sdk/ssr";
493
+
494
+ export async function POST(request: NextRequest) {
495
+ const response = NextResponse.json({ ok: true });
496
+ const auth = createAuthActions({
497
+ requestCookies: request.cookies,
498
+ responseCookies: response.cookies,
499
+ });
500
+
501
+ const { error } = await auth.signOut();
502
+ if (error) {
503
+ return NextResponse.json(
504
+ { error: error.error, message: error.message },
505
+ { status: error.statusCode }
506
+ );
507
+ }
508
+
509
+ return response;
510
+ }
385
511
  ```
386
512
 
387
513
  If your refresh route needs custom side effects:
@@ -401,7 +527,7 @@ For Next.js Proxy/Middleware, refresh before Server Components render:
401
527
  ```typescript
402
528
  // proxy.ts on Next.js 16+, middleware.ts on Next.js 15 and earlier
403
529
  import { NextResponse, type NextRequest } from "next/server";
404
- import { updateSession } from "@insforge/sdk/ssr";
530
+ import { updateSession } from "@insforge/sdk/ssr/middleware";
405
531
 
406
532
  export async function proxy(request: NextRequest) {
407
533
  const response = NextResponse.next({ request });
@@ -415,6 +541,9 @@ export async function proxy(request: NextRequest) {
415
541
  }
416
542
  ```
417
543
 
544
+ Use the `/ssr/middleware` subpath in Proxy/Middleware files. It only includes
545
+ the session refresh helpers and avoids bundling the full SDK client.
546
+
418
547
  ## TypeScript Support
419
548
 
420
549
  The SDK is written in TypeScript and provides full type definitions:
package/SDK-REFERENCE.md CHANGED
@@ -59,6 +59,10 @@ const insforge = createBrowserClient({
59
59
 
60
60
  The browser client reads the access-token cookie, uses it for Database, Storage, Functions, and Realtime, and calls the refresh route when the access token is missing or near expiry.
61
61
 
62
+ The browser client consumes an existing SSR session. Its TypeScript surface does
63
+ not include auth mutations such as `signInWithPassword()`, `signUp()`, or
64
+ `signOut()`.
65
+
62
66
  ### `createServerClient()`
63
67
 
64
68
  ```typescript
@@ -81,34 +85,40 @@ import { createRefreshAuthRouter } from "@insforge/sdk/ssr";
81
85
  export const { POST } = createRefreshAuthRouter();
82
86
  ```
83
87
 
84
- For server-owned refresh cookies, sign-in should also run through a Route Handler or Server Action that can set cookies:
88
+ For server-owned refresh cookies, sign-in, sign-up, and sign-out should run
89
+ through a Server Action or Route Handler that can set cookies. Do not return
90
+ raw auth responses from Server Actions; return only the user or app-specific
91
+ safe fields.
85
92
 
86
93
  ```typescript
87
- import { NextResponse } from "next/server";
88
- import { createServerClient, setAuthCookies } from "@insforge/sdk/ssr";
94
+ // app/actions.ts
95
+ "use server";
89
96
 
90
- export async function POST(request: Request) {
91
- const client = createServerClient();
92
- const { data, error } = await client.auth.signInWithPassword(
93
- await request.json(),
94
- );
95
- if (error || !data?.accessToken) {
96
- return Response.json(error, { status: error?.statusCode ?? 400 });
97
- }
97
+ import { cookies } from "next/headers";
98
+ import { createAuthActions } from "@insforge/sdk/ssr";
98
99
 
99
- const response = NextResponse.json({
100
- accessToken: data.accessToken,
101
- user: data.user,
102
- });
103
- setAuthCookies(response.cookies, {
104
- accessToken: data.accessToken,
105
- refreshToken: data.refreshToken,
100
+ export async function signIn(formData: FormData) {
101
+ const auth = createAuthActions({ cookies: await cookies() });
102
+
103
+ const { data, error } = await auth.signInWithPassword({
104
+ email: String(formData.get("email")),
105
+ password: String(formData.get("password")),
106
106
  });
107
107
 
108
- return response;
108
+ return { user: data?.user ?? null, error };
109
109
  }
110
110
  ```
111
111
 
112
+ In Route Handlers, pass `requestCookies` and `responseCookies` to the same
113
+ helper when request and response cookie stores are separate.
114
+
115
+ For OAuth, initiate and exchange on the server. Use
116
+ `createAuthActions().signInWithOAuth(provider, { redirectTo, skipBrowserRedirect: true })`
117
+ in a Server Action, store the returned `codeVerifier` in an httpOnly app cookie,
118
+ redirect to `data.url`, then call `createAuthActions().exchangeOAuthCode(code,
119
+ codeVerifier)` from the callback Route Handler. SSR browser clients do not
120
+ auto-exchange OAuth callbacks.
121
+
112
122
  Use `refreshAuth()` directly when the route needs app-specific logic:
113
123
 
114
124
  ```typescript
@@ -124,10 +134,14 @@ export async function POST(request: Request) {
124
134
 
125
135
  ### `updateSession()`
126
136
 
137
+ Import `updateSession()` from `@insforge/sdk/ssr/middleware` in Proxy/Middleware
138
+ files. This subpath only includes the session refresh helpers and avoids
139
+ bundling the full SDK client.
140
+
127
141
  ```typescript
128
142
  // proxy.ts on Next.js 16+, middleware.ts on Next.js 15 and earlier
129
143
  import { NextResponse, type NextRequest } from "next/server";
130
- import { updateSession } from "@insforge/sdk/ssr";
144
+ import { updateSession } from "@insforge/sdk/ssr/middleware";
131
145
 
132
146
  export async function proxy(request: NextRequest) {
133
147
  const response = NextResponse.next({ request });
@@ -1,114 +1,7 @@
1
- import { UserSchema, ErrorCode, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
1
+ import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-Dk-44JJf.js';
2
+ import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
2
3
  import * as _supabase_postgrest_js from '@supabase/postgrest-js';
3
4
 
4
- /**
5
- * InsForge SDK Types - only SDK-specific types here
6
- * Use @insforge/shared-schemas directly for API types
7
- */
8
-
9
- type InsForgeErrorCode = ErrorCode | (string & {});
10
- interface InsForgeConfig {
11
- /**
12
- * The base URL of the InsForge backend API
13
- * @default "http://localhost:7130"
14
- */
15
- baseUrl?: string;
16
- /**
17
- * Anonymous API key (optional)
18
- * Used for public/unauthenticated requests when no user token is set
19
- */
20
- anonKey?: string;
21
- /**
22
- * Edge Function Token (optional)
23
- * Use this when running in edge functions/serverless with a user's JWT token
24
- * This token will be used for all authenticated requests
25
- */
26
- edgeFunctionToken?: string;
27
- /**
28
- * Direct URL to Deno Subhosting functions (optional)
29
- * When provided, SDK will try this URL first for function invocations.
30
- * Falls back to proxy URL if subhosting returns 404.
31
- * @example "https://{appKey}.functions.insforge.app"
32
- */
33
- functionsUrl?: string;
34
- /**
35
- * Custom fetch implementation (useful for Node.js environments)
36
- */
37
- fetch?: typeof fetch;
38
- /**
39
- * Enable server-side auth mode (SSR/Node runtime)
40
- * In this mode auth endpoints use `client_type=mobile` and refresh_token body flow.
41
- *
42
- * @deprecated Use `createServerClient()`, `createBrowserClient()`, and
43
- * `updateSession()` from `@insforge/sdk/ssr` for SSR apps.
44
- * @default false
45
- */
46
- isServerMode?: boolean;
47
- /**
48
- * Custom headers to include with every request
49
- */
50
- headers?: Record<string, string>;
51
- /**
52
- * Enable debug logging for HTTP requests and responses.
53
- * When true, request/response details are logged to the console.
54
- * Can also be a custom log function for advanced use cases.
55
- * @default false
56
- */
57
- debug?: boolean | ((message: string, ...args: any[]) => void);
58
- /**
59
- * Request timeout in milliseconds.
60
- * Requests that exceed this duration will be aborted.
61
- * Set to 0 to disable timeout.
62
- * @default 30000
63
- */
64
- timeout?: number;
65
- /**
66
- * Maximum number of retry attempts for failed requests.
67
- * Retries are triggered on network errors and server errors (5xx).
68
- * Client errors (4xx) are never retried.
69
- * Set to 0 to disable retries.
70
- * @default 3
71
- */
72
- retryCount?: number;
73
- /**
74
- * Initial delay in milliseconds before the first retry.
75
- * The delay doubles with each subsequent attempt (exponential backoff)
76
- * with ±15% jitter to prevent thundering herd.
77
- * @default 500
78
- */
79
- retryDelay?: number;
80
- }
81
- type InsForgeAdminConfig = Omit<InsForgeConfig, 'anonKey' | 'edgeFunctionToken' | 'isServerMode'> & {
82
- /**
83
- * Project admin API key. Keep this server-side only.
84
- */
85
- apiKey: string;
86
- };
87
- interface AuthSession {
88
- user: UserSchema;
89
- accessToken: string;
90
- expiresAt?: Date;
91
- }
92
- interface AuthRefreshResponse {
93
- user: UserSchema;
94
- accessToken: string;
95
- csrfToken?: string;
96
- refreshToken?: string;
97
- }
98
- interface ApiError {
99
- error: InsForgeErrorCode;
100
- message: string;
101
- statusCode: number;
102
- nextActions?: string;
103
- }
104
- declare class InsForgeError extends Error {
105
- statusCode: number;
106
- error: InsForgeErrorCode;
107
- nextActions?: string;
108
- constructor(message: string, statusCode: number, error: InsForgeErrorCode, nextActions?: string);
109
- static fromApiError(apiError: ApiError): InsForgeError;
110
- }
111
-
112
5
  type LogFunction = (message: string, ...args: any[]) => void;
113
6
  /**
114
7
  * Debug logger for the InsForge SDK.
@@ -311,6 +204,7 @@ declare class HttpClient {
311
204
 
312
205
  interface AuthOptions {
313
206
  isServerMode?: boolean;
207
+ detectOAuthCallback?: boolean;
314
208
  }
315
209
  type OAuthSignInOptions = {
316
210
  redirectTo: string;
@@ -572,10 +466,57 @@ declare class StorageBucket {
572
466
  error: InsForgeError | null;
573
467
  }>;
574
468
  /**
575
- * Get public URL for a file
469
+ * Get the public URL for an object in a public bucket.
470
+ *
471
+ * Pure string construction — no network call, no auth. The URL only resolves
472
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
473
+ *
474
+ * @param path - The object key/path
475
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
476
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
477
+ */
478
+ getPublicUrl(path: string): StorageResponse<{
479
+ publicUrl: string;
480
+ }>;
481
+ /**
482
+ * Resolve a download strategy (signed or direct URL) for an object with a
483
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
484
+ * legacy POST alias so signed-URL creation still works against older backends
485
+ * that predate the GET route (they return 404/405 for it). A genuine
486
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
487
+ */
488
+ private requestDownloadStrategy;
489
+ /**
490
+ * Create a signed URL for an object.
491
+ *
492
+ * Returns a time-limited, credential-free URL that can be handed directly to
493
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
494
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
495
+ * caller must be allowed to read the object), so the resulting link is a
496
+ * pre-authorized capability scoped to this one object until it expires.
497
+ *
576
498
  * @param path - The object key/path
499
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
500
+ * Honored for private buckets; public buckets return their long-lived URL.
501
+ */
502
+ createSignedUrl(path: string, expiresIn?: number): Promise<StorageResponse<{
503
+ signedUrl: string;
504
+ expiresAt: string | null;
505
+ }>>;
506
+ /**
507
+ * Create signed URLs for multiple objects in a single call.
508
+ *
509
+ * Each entry resolves independently: a failure on one key (not found / not
510
+ * permitted) is reported on that entry's `error` without failing the rest.
511
+ *
512
+ * @param paths - The object keys/paths
513
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
577
514
  */
578
- getPublicUrl(path: string): string;
515
+ createSignedUrls(paths: string[], expiresIn?: number): Promise<StorageResponse<Array<{
516
+ path: string;
517
+ signedUrl: string | null;
518
+ error: string | null;
519
+ }>>>;
579
520
  /**
580
521
  * List objects in the bucket
581
522
  * @param prefix - Filter by key prefix
@@ -1165,4 +1106,4 @@ declare class InsForgeClient {
1165
1106
  setAccessToken(token: string | null): void;
1166
1107
  }
1167
1108
 
1168
- export { type AuthSession as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, type InsForgeConfig as a, type InsForgeAdminConfig as b, type ApiError as c, type InsForgeErrorCode as d, InsForgeError as e, Auth as f, StorageBucket as g, type StorageResponse as h, AI as i, type FunctionInvokeOptions as j, type PaymentsResponse as k, type EventCallback as l, type AuthRefreshResponse as m };
1109
+ export { Auth as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, StorageBucket as a, type StorageResponse as b, AI as c, type FunctionInvokeOptions as d, type PaymentsResponse as e, type EventCallback as f };
@@ -1,114 +1,7 @@
1
- import { UserSchema, ErrorCode, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
1
+ import { A as AuthSession, I as InsForgeConfig, e as AuthRefreshResponse, d as InsForgeError } from './types-Dk-44JJf.mjs';
2
+ import { UserSchema, CreateUserRequest, CreateUserResponse, CreateSessionRequest, CreateSessionResponse, OAuthProvidersSchema, RefreshSessionResponse, GetProfileResponse, SendVerificationEmailRequest, VerifyEmailRequest, VerifyEmailResponse, SendResetPasswordEmailRequest, ExchangeResetPasswordTokenRequest, ExchangeResetPasswordTokenResponse, ResetPasswordResponse, GetPublicAuthConfigResponse, StorageFileSchema, ListObjectsResponseSchema, ChatCompletionRequest, ImageGenerationRequest, EmbeddingsRequest, SubscribeResponse, SocketMessage, SendRawEmailRequest, SendEmailResponse, StripeEnvironment, CreateCheckoutSessionBody, CreateCheckoutSessionResponse, CreateCustomerPortalSessionBody, CreateCustomerPortalSessionResponse, RazorpayEnvironment, CreateRazorpayOrderBody, CreateRazorpayOrderResponse, VerifyRazorpayOrderBody, VerifyRazorpayOrderResponse, CreateRazorpaySubscriptionBody, CreateRazorpaySubscriptionResponse, VerifyRazorpaySubscriptionBody, VerifyRazorpaySubscriptionResponse, CancelRazorpaySubscriptionBodyInput, CancelRazorpaySubscriptionResponse, PauseRazorpaySubscriptionResponse, ResumeRazorpaySubscriptionResponse } from '@insforge/shared-schemas';
2
3
  import * as _supabase_postgrest_js from '@supabase/postgrest-js';
3
4
 
4
- /**
5
- * InsForge SDK Types - only SDK-specific types here
6
- * Use @insforge/shared-schemas directly for API types
7
- */
8
-
9
- type InsForgeErrorCode = ErrorCode | (string & {});
10
- interface InsForgeConfig {
11
- /**
12
- * The base URL of the InsForge backend API
13
- * @default "http://localhost:7130"
14
- */
15
- baseUrl?: string;
16
- /**
17
- * Anonymous API key (optional)
18
- * Used for public/unauthenticated requests when no user token is set
19
- */
20
- anonKey?: string;
21
- /**
22
- * Edge Function Token (optional)
23
- * Use this when running in edge functions/serverless with a user's JWT token
24
- * This token will be used for all authenticated requests
25
- */
26
- edgeFunctionToken?: string;
27
- /**
28
- * Direct URL to Deno Subhosting functions (optional)
29
- * When provided, SDK will try this URL first for function invocations.
30
- * Falls back to proxy URL if subhosting returns 404.
31
- * @example "https://{appKey}.functions.insforge.app"
32
- */
33
- functionsUrl?: string;
34
- /**
35
- * Custom fetch implementation (useful for Node.js environments)
36
- */
37
- fetch?: typeof fetch;
38
- /**
39
- * Enable server-side auth mode (SSR/Node runtime)
40
- * In this mode auth endpoints use `client_type=mobile` and refresh_token body flow.
41
- *
42
- * @deprecated Use `createServerClient()`, `createBrowserClient()`, and
43
- * `updateSession()` from `@insforge/sdk/ssr` for SSR apps.
44
- * @default false
45
- */
46
- isServerMode?: boolean;
47
- /**
48
- * Custom headers to include with every request
49
- */
50
- headers?: Record<string, string>;
51
- /**
52
- * Enable debug logging for HTTP requests and responses.
53
- * When true, request/response details are logged to the console.
54
- * Can also be a custom log function for advanced use cases.
55
- * @default false
56
- */
57
- debug?: boolean | ((message: string, ...args: any[]) => void);
58
- /**
59
- * Request timeout in milliseconds.
60
- * Requests that exceed this duration will be aborted.
61
- * Set to 0 to disable timeout.
62
- * @default 30000
63
- */
64
- timeout?: number;
65
- /**
66
- * Maximum number of retry attempts for failed requests.
67
- * Retries are triggered on network errors and server errors (5xx).
68
- * Client errors (4xx) are never retried.
69
- * Set to 0 to disable retries.
70
- * @default 3
71
- */
72
- retryCount?: number;
73
- /**
74
- * Initial delay in milliseconds before the first retry.
75
- * The delay doubles with each subsequent attempt (exponential backoff)
76
- * with ±15% jitter to prevent thundering herd.
77
- * @default 500
78
- */
79
- retryDelay?: number;
80
- }
81
- type InsForgeAdminConfig = Omit<InsForgeConfig, 'anonKey' | 'edgeFunctionToken' | 'isServerMode'> & {
82
- /**
83
- * Project admin API key. Keep this server-side only.
84
- */
85
- apiKey: string;
86
- };
87
- interface AuthSession {
88
- user: UserSchema;
89
- accessToken: string;
90
- expiresAt?: Date;
91
- }
92
- interface AuthRefreshResponse {
93
- user: UserSchema;
94
- accessToken: string;
95
- csrfToken?: string;
96
- refreshToken?: string;
97
- }
98
- interface ApiError {
99
- error: InsForgeErrorCode;
100
- message: string;
101
- statusCode: number;
102
- nextActions?: string;
103
- }
104
- declare class InsForgeError extends Error {
105
- statusCode: number;
106
- error: InsForgeErrorCode;
107
- nextActions?: string;
108
- constructor(message: string, statusCode: number, error: InsForgeErrorCode, nextActions?: string);
109
- static fromApiError(apiError: ApiError): InsForgeError;
110
- }
111
-
112
5
  type LogFunction = (message: string, ...args: any[]) => void;
113
6
  /**
114
7
  * Debug logger for the InsForge SDK.
@@ -311,6 +204,7 @@ declare class HttpClient {
311
204
 
312
205
  interface AuthOptions {
313
206
  isServerMode?: boolean;
207
+ detectOAuthCallback?: boolean;
314
208
  }
315
209
  type OAuthSignInOptions = {
316
210
  redirectTo: string;
@@ -572,10 +466,57 @@ declare class StorageBucket {
572
466
  error: InsForgeError | null;
573
467
  }>;
574
468
  /**
575
- * Get public URL for a file
469
+ * Get the public URL for an object in a public bucket.
470
+ *
471
+ * Pure string construction — no network call, no auth. The URL only resolves
472
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
473
+ *
474
+ * @param path - The object key/path
475
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
476
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
477
+ */
478
+ getPublicUrl(path: string): StorageResponse<{
479
+ publicUrl: string;
480
+ }>;
481
+ /**
482
+ * Resolve a download strategy (signed or direct URL) for an object with a
483
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
484
+ * legacy POST alias so signed-URL creation still works against older backends
485
+ * that predate the GET route (they return 404/405 for it). A genuine
486
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
487
+ */
488
+ private requestDownloadStrategy;
489
+ /**
490
+ * Create a signed URL for an object.
491
+ *
492
+ * Returns a time-limited, credential-free URL that can be handed directly to
493
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
494
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
495
+ * caller must be allowed to read the object), so the resulting link is a
496
+ * pre-authorized capability scoped to this one object until it expires.
497
+ *
576
498
  * @param path - The object key/path
499
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
500
+ * Honored for private buckets; public buckets return their long-lived URL.
501
+ */
502
+ createSignedUrl(path: string, expiresIn?: number): Promise<StorageResponse<{
503
+ signedUrl: string;
504
+ expiresAt: string | null;
505
+ }>>;
506
+ /**
507
+ * Create signed URLs for multiple objects in a single call.
508
+ *
509
+ * Each entry resolves independently: a failure on one key (not found / not
510
+ * permitted) is reported on that entry's `error` without failing the rest.
511
+ *
512
+ * @param paths - The object keys/paths
513
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
577
514
  */
578
- getPublicUrl(path: string): string;
515
+ createSignedUrls(paths: string[], expiresIn?: number): Promise<StorageResponse<Array<{
516
+ path: string;
517
+ signedUrl: string | null;
518
+ error: string | null;
519
+ }>>>;
579
520
  /**
580
521
  * List objects in the bucket
581
522
  * @param prefix - Filter by key prefix
@@ -1165,4 +1106,4 @@ declare class InsForgeClient {
1165
1106
  setAccessToken(token: string | null): void;
1166
1107
  }
1167
1108
 
1168
- export { type AuthSession as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, type InsForgeConfig as a, type InsForgeAdminConfig as b, type ApiError as c, type InsForgeErrorCode as d, InsForgeError as e, Auth as f, StorageBucket as g, type StorageResponse as h, AI as i, type FunctionInvokeOptions as j, type PaymentsResponse as k, type EventCallback as l, type AuthRefreshResponse as m };
1109
+ export { Auth as A, type ConnectionState as C, Database as D, Emails as E, Functions as F, HttpClient as H, InsForgeClient as I, Logger as L, Payments as P, Realtime as R, Storage as S, TokenManager as T, StorageBucket as a, type StorageResponse as b, AI as c, type FunctionInvokeOptions as d, type PaymentsResponse as e, type EventCallback as f };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
- import { I as InsForgeClient, a as InsForgeConfig, b as InsForgeAdminConfig } from './client-CqfpCc8Z.mjs';
2
- export { i as AI, c as ApiError, f as Auth, A as AuthSession, C as ConnectionState, D as Database, E as Emails, l as EventCallback, j as FunctionInvokeOptions, F as Functions, H as HttpClient, e as InsForgeError, d as InsForgeErrorCode, L as Logger, P as Payments, k as PaymentsResponse, R as Realtime, S as Storage, g as StorageBucket, h as StorageResponse, T as TokenManager } from './client-CqfpCc8Z.mjs';
1
+ import { I as InsForgeClient } from './client-C-qBRoea.mjs';
2
+ export { c as AI, A as Auth, C as ConnectionState, D as Database, E as Emails, f as EventCallback, d as FunctionInvokeOptions, F as Functions, H as HttpClient, L as Logger, P as Payments, e as PaymentsResponse, R as Realtime, S as Storage, a as StorageBucket, b as StorageResponse, T as TokenManager } from './client-C-qBRoea.mjs';
3
+ import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-Dk-44JJf.mjs';
4
+ export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-Dk-44JJf.mjs';
3
5
  export { AuthErrorResponse, CreateSessionRequest, CreateUserRequest, RealtimeErrorPayload, SendRawEmailRequest as SendEmailOptions, SendEmailResponse, SocketMessage, SubscribeResponse, UserSchema } from '@insforge/shared-schemas';
4
6
  import '@supabase/postgrest-js';
5
7