@insforge/sdk 1.4.0 → 1.4.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/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
@@ -401,7 +414,7 @@ For Next.js Proxy/Middleware, refresh before Server Components render:
401
414
  ```typescript
402
415
  // proxy.ts on Next.js 16+, middleware.ts on Next.js 15 and earlier
403
416
  import { NextResponse, type NextRequest } from "next/server";
404
- import { updateSession } from "@insforge/sdk/ssr";
417
+ import { updateSession } from "@insforge/sdk/ssr/middleware";
405
418
 
406
419
  export async function proxy(request: NextRequest) {
407
420
  const response = NextResponse.next({ request });
@@ -415,6 +428,9 @@ export async function proxy(request: NextRequest) {
415
428
  }
416
429
  ```
417
430
 
431
+ Use the `/ssr/middleware` subpath in Proxy/Middleware files. It only includes
432
+ the session refresh helpers and avoids bundling the full SDK client.
433
+
418
434
  ## TypeScript Support
419
435
 
420
436
  The SDK is written in TypeScript and provides full type definitions:
package/SDK-REFERENCE.md CHANGED
@@ -124,10 +124,14 @@ export async function POST(request: Request) {
124
124
 
125
125
  ### `updateSession()`
126
126
 
127
+ Import `updateSession()` from `@insforge/sdk/ssr/middleware` in Proxy/Middleware
128
+ files. This subpath only includes the session refresh helpers and avoids
129
+ bundling the full SDK client.
130
+
127
131
  ```typescript
128
132
  // proxy.ts on Next.js 16+, middleware.ts on Next.js 15 and earlier
129
133
  import { NextResponse, type NextRequest } from "next/server";
130
- import { updateSession } from "@insforge/sdk/ssr";
134
+ import { updateSession } from "@insforge/sdk/ssr/middleware";
131
135
 
132
136
  export async function proxy(request: NextRequest) {
133
137
  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-NjykhyRq.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.
@@ -572,10 +465,57 @@ declare class StorageBucket {
572
465
  error: InsForgeError | null;
573
466
  }>;
574
467
  /**
575
- * Get public URL for a file
468
+ * Get the public URL for an object in a public bucket.
469
+ *
470
+ * Pure string construction — no network call, no auth. The URL only resolves
471
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
472
+ *
473
+ * @param path - The object key/path
474
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
475
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
476
+ */
477
+ getPublicUrl(path: string): StorageResponse<{
478
+ publicUrl: string;
479
+ }>;
480
+ /**
481
+ * Resolve a download strategy (signed or direct URL) for an object with a
482
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
483
+ * legacy POST alias so signed-URL creation still works against older backends
484
+ * that predate the GET route (they return 404/405 for it). A genuine
485
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
486
+ */
487
+ private requestDownloadStrategy;
488
+ /**
489
+ * Create a signed URL for an object.
490
+ *
491
+ * Returns a time-limited, credential-free URL that can be handed directly to
492
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
493
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
494
+ * caller must be allowed to read the object), so the resulting link is a
495
+ * pre-authorized capability scoped to this one object until it expires.
496
+ *
576
497
  * @param path - The object key/path
498
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
499
+ * Honored for private buckets; public buckets return their long-lived URL.
500
+ */
501
+ createSignedUrl(path: string, expiresIn?: number): Promise<StorageResponse<{
502
+ signedUrl: string;
503
+ expiresAt: string | null;
504
+ }>>;
505
+ /**
506
+ * Create signed URLs for multiple objects in a single call.
507
+ *
508
+ * Each entry resolves independently: a failure on one key (not found / not
509
+ * permitted) is reported on that entry's `error` without failing the rest.
510
+ *
511
+ * @param paths - The object keys/paths
512
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
577
513
  */
578
- getPublicUrl(path: string): string;
514
+ createSignedUrls(paths: string[], expiresIn?: number): Promise<StorageResponse<Array<{
515
+ path: string;
516
+ signedUrl: string | null;
517
+ error: string | null;
518
+ }>>>;
579
519
  /**
580
520
  * List objects in the bucket
581
521
  * @param prefix - Filter by key prefix
@@ -1165,4 +1105,4 @@ declare class InsForgeClient {
1165
1105
  setAccessToken(token: string | null): void;
1166
1106
  }
1167
1107
 
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 };
1108
+ 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-NjykhyRq.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.
@@ -572,10 +465,57 @@ declare class StorageBucket {
572
465
  error: InsForgeError | null;
573
466
  }>;
574
467
  /**
575
- * Get public URL for a file
468
+ * Get the public URL for an object in a public bucket.
469
+ *
470
+ * Pure string construction — no network call, no auth. The URL only resolves
471
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
472
+ *
473
+ * @param path - The object key/path
474
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
475
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
476
+ */
477
+ getPublicUrl(path: string): StorageResponse<{
478
+ publicUrl: string;
479
+ }>;
480
+ /**
481
+ * Resolve a download strategy (signed or direct URL) for an object with a
482
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
483
+ * legacy POST alias so signed-URL creation still works against older backends
484
+ * that predate the GET route (they return 404/405 for it). A genuine
485
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
486
+ */
487
+ private requestDownloadStrategy;
488
+ /**
489
+ * Create a signed URL for an object.
490
+ *
491
+ * Returns a time-limited, credential-free URL that can be handed directly to
492
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
493
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
494
+ * caller must be allowed to read the object), so the resulting link is a
495
+ * pre-authorized capability scoped to this one object until it expires.
496
+ *
576
497
  * @param path - The object key/path
498
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
499
+ * Honored for private buckets; public buckets return their long-lived URL.
500
+ */
501
+ createSignedUrl(path: string, expiresIn?: number): Promise<StorageResponse<{
502
+ signedUrl: string;
503
+ expiresAt: string | null;
504
+ }>>;
505
+ /**
506
+ * Create signed URLs for multiple objects in a single call.
507
+ *
508
+ * Each entry resolves independently: a failure on one key (not found / not
509
+ * permitted) is reported on that entry's `error` without failing the rest.
510
+ *
511
+ * @param paths - The object keys/paths
512
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
577
513
  */
578
- getPublicUrl(path: string): string;
514
+ createSignedUrls(paths: string[], expiresIn?: number): Promise<StorageResponse<Array<{
515
+ path: string;
516
+ signedUrl: string | null;
517
+ error: string | null;
518
+ }>>>;
579
519
  /**
580
520
  * List objects in the bucket
581
521
  * @param prefix - Filter by key prefix
@@ -1165,4 +1105,4 @@ declare class InsForgeClient {
1165
1105
  setAccessToken(token: string | null): void;
1166
1106
  }
1167
1107
 
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 };
1108
+ 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-hYdj36T6.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-hYdj36T6.mjs';
3
+ import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-NjykhyRq.mjs';
4
+ export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-NjykhyRq.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
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { I as InsForgeClient, a as InsForgeConfig, b as InsForgeAdminConfig } from './client-CqfpCc8Z.js';
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.js';
1
+ import { I as InsForgeClient } from './client-DoWwzWnh.js';
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-DoWwzWnh.js';
3
+ import { I as InsForgeConfig, a as InsForgeAdminConfig } from './types-NjykhyRq.js';
4
+ export { b as ApiError, A as AuthSession, d as InsForgeError, c as InsForgeErrorCode } from './types-NjykhyRq.js';
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
 
package/dist/index.js CHANGED
@@ -28,8 +28,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
33
  AI: () => AI,
34
34
  Auth: () => Auth,
35
35
  Database: () => Database,
@@ -46,9 +46,9 @@ __export(index_exports, {
46
46
  TokenManager: () => TokenManager,
47
47
  createAdminClient: () => createAdminClient,
48
48
  createClient: () => createClient,
49
- default: () => index_default
49
+ default: () => src_default
50
50
  });
51
- module.exports = __toCommonJS(index_exports);
51
+ module.exports = __toCommonJS(src_exports);
52
52
 
53
53
  // src/types.ts
54
54
  var InsForgeError = class _InsForgeError extends Error {
@@ -449,7 +449,7 @@ var HttpClient = class {
449
449
  return Math.round(jitter);
450
450
  }
451
451
  shouldRefreshAccessToken(statusCode, errorCode, authToken, options = {}) {
452
- return statusCode === 401 && REFRESHABLE_AUTH_ERROR_CODES.has(errorCode ?? "") && !this.config.isServerMode && !this.config.edgeFunctionToken && !options.skipAuthRefresh && authToken !== null;
452
+ return statusCode === 401 && REFRESHABLE_AUTH_ERROR_CODES.has(errorCode ?? "") && !this.config.isServerMode && !this.config.accessToken && !this.config.edgeFunctionToken && !options.skipAuthRefresh && authToken !== null;
453
453
  }
454
454
  async fetchWithRetry(args) {
455
455
  const {
@@ -1661,7 +1661,7 @@ var StorageBucket = class {
1661
1661
  size: file.size,
1662
1662
  mimeType: file.type || "application/octet-stream",
1663
1663
  uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
1664
- url: this.getPublicUrl(strategy.key)
1664
+ url: this.getPublicUrl(strategy.key).data.publicUrl
1665
1665
  },
1666
1666
  error: null
1667
1667
  };
@@ -1733,11 +1733,101 @@ var StorageBucket = class {
1733
1733
  }
1734
1734
  }
1735
1735
  /**
1736
- * Get public URL for a file
1736
+ * Get the public URL for an object in a public bucket.
1737
+ *
1738
+ * Pure string construction — no network call, no auth. The URL only resolves
1739
+ * if the bucket is public; for private objects use {@link createSignedUrl}.
1740
+ *
1737
1741
  * @param path - The object key/path
1742
+ * @returns `{ data: { publicUrl }, error }` — matches the external SDK pattern,
1743
+ * so `const { data } = getPublicUrl(path)` then `data.publicUrl`.
1738
1744
  */
1739
1745
  getPublicUrl(path) {
1740
- return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;
1746
+ const publicUrl = `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;
1747
+ return { data: { publicUrl }, error: null };
1748
+ }
1749
+ /**
1750
+ * Resolve a download strategy (signed or direct URL) for an object with a
1751
+ * caller-supplied TTL. Prefers the canonical GET route and falls back to the
1752
+ * legacy POST alias so signed-URL creation still works against older backends
1753
+ * that predate the GET route (they return 404/405 for it). A genuine
1754
+ * "object not found" (STORAGE_NOT_FOUND) is not retried.
1755
+ */
1756
+ async requestDownloadStrategy(path, expiresIn) {
1757
+ const encoded = encodeURIComponent(path);
1758
+ try {
1759
+ return await this.http.get(
1760
+ `/api/storage/buckets/${this.bucketName}/download-strategy/objects/${encoded}`,
1761
+ { params: { expiresIn: expiresIn.toString() } }
1762
+ );
1763
+ } catch (error) {
1764
+ const status = error instanceof InsForgeError ? error.statusCode : void 0;
1765
+ const isMissingRoute = (status === 404 || status === 405) && !(error instanceof InsForgeError && error.error === "STORAGE_NOT_FOUND");
1766
+ if (!isMissingRoute) throw error;
1767
+ return await this.http.post(
1768
+ `/api/storage/buckets/${this.bucketName}/objects/${encoded}/download-strategy`,
1769
+ { expiresIn }
1770
+ );
1771
+ }
1772
+ }
1773
+ /**
1774
+ * Create a signed URL for an object.
1775
+ *
1776
+ * Returns a time-limited, credential-free URL that can be handed directly to
1777
+ * a browser (`<img src>`), an email, or a third party — no SDK or session is
1778
+ * needed to fetch it. Authorization is enforced when the URL is minted (the
1779
+ * caller must be allowed to read the object), so the resulting link is a
1780
+ * pre-authorized capability scoped to this one object until it expires.
1781
+ *
1782
+ * @param path - The object key/path
1783
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d).
1784
+ * Honored for private buckets; public buckets return their long-lived URL.
1785
+ */
1786
+ async createSignedUrl(path, expiresIn = 3600) {
1787
+ try {
1788
+ const strategy = await this.requestDownloadStrategy(path, expiresIn);
1789
+ return {
1790
+ data: {
1791
+ signedUrl: strategy.url,
1792
+ expiresAt: strategy.expiresAt ? new Date(strategy.expiresAt).toISOString() : null
1793
+ },
1794
+ error: null
1795
+ };
1796
+ } catch (error) {
1797
+ return {
1798
+ data: null,
1799
+ error: error instanceof InsForgeError ? error : new InsForgeError("Failed to create signed URL", 500, "STORAGE_ERROR")
1800
+ };
1801
+ }
1802
+ }
1803
+ /**
1804
+ * Create signed URLs for multiple objects in a single call.
1805
+ *
1806
+ * Each entry resolves independently: a failure on one key (not found / not
1807
+ * permitted) is reported on that entry's `error` without failing the rest.
1808
+ *
1809
+ * @param paths - The object keys/paths
1810
+ * @param expiresIn - Lifetime in seconds (default 3600 = 1h, max 604800 = 7d)
1811
+ */
1812
+ async createSignedUrls(paths, expiresIn = 3600) {
1813
+ try {
1814
+ const data = await Promise.all(
1815
+ paths.map(async (path) => {
1816
+ const { data: signed, error } = await this.createSignedUrl(path, expiresIn);
1817
+ return {
1818
+ path,
1819
+ signedUrl: signed?.signedUrl ?? null,
1820
+ error: error ? error.message : null
1821
+ };
1822
+ })
1823
+ );
1824
+ return { data, error: null };
1825
+ } catch (error) {
1826
+ return {
1827
+ data: null,
1828
+ error: error instanceof InsForgeError ? error : new InsForgeError("Failed to create signed URLs", 500, "STORAGE_ERROR")
1829
+ };
1830
+ }
1741
1831
  }
1742
1832
  /**
1743
1833
  * List objects in the bucket
@@ -2716,12 +2806,13 @@ var InsForgeClient = class {
2716
2806
  const logger = new Logger(config.debug);
2717
2807
  this.tokenManager = new TokenManager();
2718
2808
  this.http = new HttpClient(config, this.tokenManager, logger);
2719
- if (config.edgeFunctionToken) {
2720
- this.http.setAuthToken(config.edgeFunctionToken);
2721
- this.tokenManager.setAccessToken(config.edgeFunctionToken);
2809
+ const accessToken = config.accessToken ?? config.edgeFunctionToken;
2810
+ if (accessToken) {
2811
+ this.http.setAuthToken(accessToken);
2812
+ this.tokenManager.setAccessToken(accessToken);
2722
2813
  }
2723
2814
  this.auth = new Auth(this.http, this.tokenManager, {
2724
- isServerMode: config.isServerMode ?? !!config.edgeFunctionToken
2815
+ isServerMode: config.isServerMode ?? !!accessToken
2725
2816
  });
2726
2817
  this.database = new Database(this.http);
2727
2818
  this.storage = new Storage(this.http);
@@ -2800,11 +2891,11 @@ function createAdminClient(config) {
2800
2891
  }
2801
2892
  return new InsForgeClient({
2802
2893
  ...clientConfig,
2803
- edgeFunctionToken: apiKey,
2894
+ accessToken: apiKey,
2804
2895
  isServerMode: true
2805
2896
  });
2806
2897
  }
2807
- var index_default = InsForgeClient;
2898
+ var src_default = InsForgeClient;
2808
2899
  // Annotate the CommonJS export names for ESM import in node:
2809
2900
  0 && (module.exports = {
2810
2901
  AI,