@ragable/sdk 0.6.12 → 0.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -322,6 +322,28 @@ interface Filter {
322
322
  column: string;
323
323
  value: unknown;
324
324
  }
325
+ /**
326
+ * Chainable SELECT (PostgREST / Supabase-style). Filters and modifiers apply to the **base**
327
+ * table of the query (the table passed to `client.from(...)`); the `select` string controls columns
328
+ * and **resource embedding** (joins).
329
+ *
330
+ * **Joins** use the same embedded `select` syntax as
331
+ * [Supabase `.select()`](https://supabase.com/docs/reference/javascript/select) / PostgREST, for example:
332
+ * - `*,related_table(*)` — include related rows
333
+ * - `related_table!inner(*)` — inner-style embed
334
+ * - `related_table!fkey_column_or_constraint(*)` — disambiguate when multiple FKs exist
335
+ * - `alias:related_table(*)` — rename the JSON key for the nested object/array
336
+ *
337
+ * **Ragable limits** (server-side): only **one level** of embedding is supported — no nested
338
+ * `relation(nested(...))`. Prefer embed aliases above; top-level column rename forms like
339
+ * `alias:column` may not be accepted for scalar columns.
340
+ *
341
+ * **API note:** Supabase’s second `select(columns, options?)` argument (`count`, `head`, etc.) is
342
+ * not supported in Ragable yet; joins use the **first** argument only.
343
+ *
344
+ * For nested result shapes, pass a type argument on {@link PostgrestTableApi.select}:
345
+ * `from('orders').select<OrderWithLines>(\`*, lines (*)\`)`.
346
+ */
325
347
  declare class PostgrestSelectBuilder<Row extends Record<string, unknown> = Record<string, unknown>, D extends RagableDatabase = DefaultRagableDatabase, T extends RagableTableNames<D> = RagableTableNames<D>> implements PromiseLike<PostgrestResult<Row[]>> {
326
348
  private readonly pgFetch;
327
349
  private readonly databaseInstanceId;
@@ -509,7 +531,14 @@ declare class PostgrestTableApi<Database extends RagableDatabase = DefaultRagabl
509
531
  private readonly databaseInstanceId;
510
532
  private readonly table;
511
533
  constructor(pgFetch: PostgRESTFetch, databaseInstanceId: string, table: TableName extends string ? string : string);
512
- select(columns?: string): PostgrestSelectBuilder<TableRow<Database, TableName>, Database, TableName>;
534
+ /**
535
+ * Start a SELECT. Pass a PostgREST `select` string; use embedded resources for joins — see
536
+ * {@link PostgrestSelectBuilder}.
537
+ *
538
+ * @param columns Column list and optional embeds (default `"*"`). Omitted or `"*"` means all base columns.
539
+ * @typeParam RowResult Row shape returned by the query; defaults to this table’s `Row`. Override when using joins.
540
+ */
541
+ select<RowResult extends Record<string, unknown> = TableRow<Database, TableName>>(columns?: string): PostgrestSelectBuilder<RowResult, Database, TableName>;
513
542
  insert(values: TableInsertRow<Database, TableName> | TableInsertRow<Database, TableName>[], ...rest: unknown[]): PostgrestInsertRootBuilder<TableRow<Database, TableName>>;
514
543
  update(patch: TableUpdatePatch<Database, TableName>): PostgrestUpdateRootBuilder<TableRow<Database, TableName>, Database, TableName>;
515
544
  delete(): PostgrestDeleteRootBuilder<TableRow<Database, TableName>, Database, TableName>;
@@ -914,6 +943,30 @@ declare class RagableBrowserDatabaseClient<Database extends RagableDatabase = De
914
943
  private toUrl;
915
944
  query: <Row extends Record<string, unknown> = Record<string, unknown>>(params: BrowserSqlQueryParams) => Promise<PostgrestResult<BrowserSqlQueryResult<Row>>>;
916
945
  private baseHeaders;
946
+ /**
947
+ * Postgres `LISTEN` / `NOTIFY` realtime via server-proxied SSE.
948
+ * Channels must be lowercase identifiers: `[a-z_][a-z0-9_]*` (max 63 chars).
949
+ */
950
+ realtime: {
951
+ subscribe: (params: BrowserRealtimeSubscribeParams) => Promise<{
952
+ unsubscribe: () => void;
953
+ }>;
954
+ };
955
+ }
956
+ interface BrowserRealtimeNotification {
957
+ channel: string;
958
+ payload: string | null;
959
+ processId: number;
960
+ }
961
+ interface BrowserRealtimeSubscribeParams {
962
+ databaseInstanceId?: string;
963
+ /** Channel names (normalized to lowercase on the server). */
964
+ channels: string[];
965
+ /** When aborted, the subscription stops (in addition to `unsubscribe()`). */
966
+ signal?: AbortSignal;
967
+ onNotify?: (msg: BrowserRealtimeNotification) => void;
968
+ onReady?: (channels: string[]) => void;
969
+ onError?: (message: string) => void;
917
970
  }
918
971
  declare class RagableBrowserAgentsClient {
919
972
  private readonly options;
@@ -1015,4 +1068,4 @@ declare function createClient(options: RagableClientOptions): Ragable;
1015
1068
  declare function createClient<Database extends RagableDatabase = DefaultRagableDatabase, AuthUser extends Record<string, unknown> = Record<string, unknown>>(options: RagableBrowserClientOptions): RagableBrowser<Database, AuthUser>;
1016
1069
  declare function createRagableServerClient(options: RagableClientOptions): Ragable;
1017
1070
 
1018
- export { type AgentChatMessage, type AgentChatParams, type AgentChatResult, type AgentPublicChatParams, type AgentStreamEvent, type AgentSummary, AgentsClient, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type BrowserAuthSession, type BrowserAuthTokens, type BrowserDataAuthMode, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultRagableDatabase, type FormatContextOptions, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, type RagClientForPipeline, type RagPipeline, type RagPipelineOptions, Ragable, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, type RagableClientOptions, type RagableDatabase, RagableError, RagableNetworkError, RagableRequestClient, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetrieveParams, type RetryOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type ShiftAddDocumentParams, ShiftClient, type ShiftCreateIndexParams, type ShiftEntry, type ShiftIndex, type ShiftIngestResponse, type ShiftListEntriesParams, type ShiftListEntriesResponse, type ShiftSearchParams, type ShiftSearchResult, type ShiftUpdateIndexParams, type ShiftUploadFileParams, type ShiftUploadableFile, type SseJsonEvent, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, Transport, type TransportOptions, type TransportRequest, asPostgrestResponse, bindFetch, createBrowserClient, createClient, createRagPipeline, createRagableBrowserClient, createRagableServerClient, detectStorage, effectiveDataAuth, extractErrorMessage, formatPostgrestError, formatRetrievalContext, formatSdkError, generateIdempotencyKey, normalizeBrowserApiBase, parseSseDataLine, parseTransportResponse, readSseStream };
1071
+ export { type AgentChatMessage, type AgentChatParams, type AgentChatResult, type AgentPublicChatParams, type AgentStreamEvent, type AgentSummary, AgentsClient, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type BrowserAuthSession, type BrowserAuthTokens, type BrowserDataAuthMode, type BrowserRealtimeNotification, type BrowserRealtimeSubscribeParams, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultRagableDatabase, type FormatContextOptions, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, type RagClientForPipeline, type RagPipeline, type RagPipelineOptions, Ragable, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, type RagableClientOptions, type RagableDatabase, RagableError, RagableNetworkError, RagableRequestClient, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetrieveParams, type RetryOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type ShiftAddDocumentParams, ShiftClient, type ShiftCreateIndexParams, type ShiftEntry, type ShiftIndex, type ShiftIngestResponse, type ShiftListEntriesParams, type ShiftListEntriesResponse, type ShiftSearchParams, type ShiftSearchResult, type ShiftUpdateIndexParams, type ShiftUploadFileParams, type ShiftUploadableFile, type SseJsonEvent, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, Transport, type TransportOptions, type TransportRequest, asPostgrestResponse, bindFetch, createBrowserClient, createClient, createRagPipeline, createRagableBrowserClient, createRagableServerClient, detectStorage, effectiveDataAuth, extractErrorMessage, formatPostgrestError, formatRetrievalContext, formatSdkError, generateIdempotencyKey, normalizeBrowserApiBase, parseSseDataLine, parseTransportResponse, readSseStream };
package/dist/index.d.ts CHANGED
@@ -322,6 +322,28 @@ interface Filter {
322
322
  column: string;
323
323
  value: unknown;
324
324
  }
325
+ /**
326
+ * Chainable SELECT (PostgREST / Supabase-style). Filters and modifiers apply to the **base**
327
+ * table of the query (the table passed to `client.from(...)`); the `select` string controls columns
328
+ * and **resource embedding** (joins).
329
+ *
330
+ * **Joins** use the same embedded `select` syntax as
331
+ * [Supabase `.select()`](https://supabase.com/docs/reference/javascript/select) / PostgREST, for example:
332
+ * - `*,related_table(*)` — include related rows
333
+ * - `related_table!inner(*)` — inner-style embed
334
+ * - `related_table!fkey_column_or_constraint(*)` — disambiguate when multiple FKs exist
335
+ * - `alias:related_table(*)` — rename the JSON key for the nested object/array
336
+ *
337
+ * **Ragable limits** (server-side): only **one level** of embedding is supported — no nested
338
+ * `relation(nested(...))`. Prefer embed aliases above; top-level column rename forms like
339
+ * `alias:column` may not be accepted for scalar columns.
340
+ *
341
+ * **API note:** Supabase’s second `select(columns, options?)` argument (`count`, `head`, etc.) is
342
+ * not supported in Ragable yet; joins use the **first** argument only.
343
+ *
344
+ * For nested result shapes, pass a type argument on {@link PostgrestTableApi.select}:
345
+ * `from('orders').select<OrderWithLines>(\`*, lines (*)\`)`.
346
+ */
325
347
  declare class PostgrestSelectBuilder<Row extends Record<string, unknown> = Record<string, unknown>, D extends RagableDatabase = DefaultRagableDatabase, T extends RagableTableNames<D> = RagableTableNames<D>> implements PromiseLike<PostgrestResult<Row[]>> {
326
348
  private readonly pgFetch;
327
349
  private readonly databaseInstanceId;
@@ -509,7 +531,14 @@ declare class PostgrestTableApi<Database extends RagableDatabase = DefaultRagabl
509
531
  private readonly databaseInstanceId;
510
532
  private readonly table;
511
533
  constructor(pgFetch: PostgRESTFetch, databaseInstanceId: string, table: TableName extends string ? string : string);
512
- select(columns?: string): PostgrestSelectBuilder<TableRow<Database, TableName>, Database, TableName>;
534
+ /**
535
+ * Start a SELECT. Pass a PostgREST `select` string; use embedded resources for joins — see
536
+ * {@link PostgrestSelectBuilder}.
537
+ *
538
+ * @param columns Column list and optional embeds (default `"*"`). Omitted or `"*"` means all base columns.
539
+ * @typeParam RowResult Row shape returned by the query; defaults to this table’s `Row`. Override when using joins.
540
+ */
541
+ select<RowResult extends Record<string, unknown> = TableRow<Database, TableName>>(columns?: string): PostgrestSelectBuilder<RowResult, Database, TableName>;
513
542
  insert(values: TableInsertRow<Database, TableName> | TableInsertRow<Database, TableName>[], ...rest: unknown[]): PostgrestInsertRootBuilder<TableRow<Database, TableName>>;
514
543
  update(patch: TableUpdatePatch<Database, TableName>): PostgrestUpdateRootBuilder<TableRow<Database, TableName>, Database, TableName>;
515
544
  delete(): PostgrestDeleteRootBuilder<TableRow<Database, TableName>, Database, TableName>;
@@ -914,6 +943,30 @@ declare class RagableBrowserDatabaseClient<Database extends RagableDatabase = De
914
943
  private toUrl;
915
944
  query: <Row extends Record<string, unknown> = Record<string, unknown>>(params: BrowserSqlQueryParams) => Promise<PostgrestResult<BrowserSqlQueryResult<Row>>>;
916
945
  private baseHeaders;
946
+ /**
947
+ * Postgres `LISTEN` / `NOTIFY` realtime via server-proxied SSE.
948
+ * Channels must be lowercase identifiers: `[a-z_][a-z0-9_]*` (max 63 chars).
949
+ */
950
+ realtime: {
951
+ subscribe: (params: BrowserRealtimeSubscribeParams) => Promise<{
952
+ unsubscribe: () => void;
953
+ }>;
954
+ };
955
+ }
956
+ interface BrowserRealtimeNotification {
957
+ channel: string;
958
+ payload: string | null;
959
+ processId: number;
960
+ }
961
+ interface BrowserRealtimeSubscribeParams {
962
+ databaseInstanceId?: string;
963
+ /** Channel names (normalized to lowercase on the server). */
964
+ channels: string[];
965
+ /** When aborted, the subscription stops (in addition to `unsubscribe()`). */
966
+ signal?: AbortSignal;
967
+ onNotify?: (msg: BrowserRealtimeNotification) => void;
968
+ onReady?: (channels: string[]) => void;
969
+ onError?: (message: string) => void;
917
970
  }
918
971
  declare class RagableBrowserAgentsClient {
919
972
  private readonly options;
@@ -1015,4 +1068,4 @@ declare function createClient(options: RagableClientOptions): Ragable;
1015
1068
  declare function createClient<Database extends RagableDatabase = DefaultRagableDatabase, AuthUser extends Record<string, unknown> = Record<string, unknown>>(options: RagableBrowserClientOptions): RagableBrowser<Database, AuthUser>;
1016
1069
  declare function createRagableServerClient(options: RagableClientOptions): Ragable;
1017
1070
 
1018
- export { type AgentChatMessage, type AgentChatParams, type AgentChatResult, type AgentPublicChatParams, type AgentStreamEvent, type AgentSummary, AgentsClient, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type BrowserAuthSession, type BrowserAuthTokens, type BrowserDataAuthMode, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultRagableDatabase, type FormatContextOptions, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, type RagClientForPipeline, type RagPipeline, type RagPipelineOptions, Ragable, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, type RagableClientOptions, type RagableDatabase, RagableError, RagableNetworkError, RagableRequestClient, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetrieveParams, type RetryOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type ShiftAddDocumentParams, ShiftClient, type ShiftCreateIndexParams, type ShiftEntry, type ShiftIndex, type ShiftIngestResponse, type ShiftListEntriesParams, type ShiftListEntriesResponse, type ShiftSearchParams, type ShiftSearchResult, type ShiftUpdateIndexParams, type ShiftUploadFileParams, type ShiftUploadableFile, type SseJsonEvent, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, Transport, type TransportOptions, type TransportRequest, asPostgrestResponse, bindFetch, createBrowserClient, createClient, createRagPipeline, createRagableBrowserClient, createRagableServerClient, detectStorage, effectiveDataAuth, extractErrorMessage, formatPostgrestError, formatRetrievalContext, formatSdkError, generateIdempotencyKey, normalizeBrowserApiBase, parseSseDataLine, parseTransportResponse, readSseStream };
1071
+ export { type AgentChatMessage, type AgentChatParams, type AgentChatResult, type AgentPublicChatParams, type AgentStreamEvent, type AgentSummary, AgentsClient, AuthBroadcastChannel, type AuthBroadcastMessage, type AuthChangeEvent, type AuthOptions, type AuthSession, type BrowserAuthSession, type BrowserAuthTokens, type BrowserDataAuthMode, type BrowserRealtimeNotification, type BrowserRealtimeSubscribeParams, type BrowserSqlExecParams, type BrowserSqlExecResult, type BrowserSqlQueryParams, type BrowserSqlQueryResult, type ColumnName, type ColumnValue, CookieStorageAdapter, DEFAULT_RAGABLE_API_BASE, type DefaultRagableDatabase, type FormatContextOptions, type HttpMethod, type Json, LocalStorageAdapter, MemoryStorageAdapter, type PostgRESTFetch, type PostgRESTFetchParams, PostgrestDeleteReturningBuilder, PostgrestDeleteRootBuilder, PostgrestInsertReturningBuilder, PostgrestInsertRootBuilder, PostgrestInsertSdkErrorReturning, PostgrestInsertSdkErrorRoot, type PostgrestResult, PostgrestSelectBuilder, PostgrestTableApi, PostgrestUpdateReturningBuilder, PostgrestUpdateRootBuilder, type PostgrestUpsertOptions, PostgrestUpsertReturningBuilder, PostgrestUpsertRootBuilder, type RagClientForPipeline, type RagPipeline, type RagPipelineOptions, Ragable, RagableAbortError, RagableAuth, type RagableAuthConfig, RagableBrowser, RagableBrowserAgentsClient, RagableBrowserAuthClient, type RagableBrowserClientOptions, RagableBrowserDatabaseClient, type RagableClientOptions, type RagableDatabase, RagableError, RagableNetworkError, RagableRequestClient, RagableSdkError, type RagableTableDefinition, type RagableTableNames, RagableTimeoutError, type RequestOptions, type RetrieveParams, type RetryOptions, type RunQuery, type SessionStorage, SessionStorageAdapter, type ShiftAddDocumentParams, ShiftClient, type ShiftCreateIndexParams, type ShiftEntry, type ShiftIndex, type ShiftIngestResponse, type ShiftListEntriesParams, type ShiftListEntriesResponse, type ShiftSearchParams, type ShiftSearchResult, type ShiftUpdateIndexParams, type ShiftUploadFileParams, type ShiftUploadableFile, type SseJsonEvent, type SupabaseCompatSession, type TableInsertRow, type TableRow, type TableUpdatePatch, type Tables, type TablesInsert, type TablesUpdate, Transport, type TransportOptions, type TransportRequest, asPostgrestResponse, bindFetch, createBrowserClient, createClient, createRagPipeline, createRagableBrowserClient, createRagableServerClient, detectStorage, effectiveDataAuth, extractErrorMessage, formatPostgrestError, formatRetrievalContext, formatSdkError, generateIdempotencyKey, normalizeBrowserApiBase, parseSseDataLine, parseTransportResponse, readSseStream };
package/dist/index.js CHANGED
@@ -1531,6 +1531,13 @@ var PostgrestTableApi = class {
1531
1531
  this.databaseInstanceId = databaseInstanceId;
1532
1532
  this.table = table;
1533
1533
  }
1534
+ /**
1535
+ * Start a SELECT. Pass a PostgREST `select` string; use embedded resources for joins — see
1536
+ * {@link PostgrestSelectBuilder}.
1537
+ *
1538
+ * @param columns Column list and optional embeds (default `"*"`). Omitted or `"*"` means all base columns.
1539
+ * @typeParam RowResult Row shape returned by the query; defaults to this table’s `Row`. Override when using joins.
1540
+ */
1534
1541
  select(columns = "*") {
1535
1542
  return new PostgrestSelectBuilder(
1536
1543
  this.pgFetch,
@@ -2361,6 +2368,18 @@ var RagableBrowserDatabaseClient = class {
2361
2368
  return payload;
2362
2369
  });
2363
2370
  });
2371
+ /**
2372
+ * Postgres `LISTEN` / `NOTIFY` realtime via server-proxied SSE.
2373
+ * Channels must be lowercase identifiers: `[a-z_][a-z0-9_]*` (max 63 chars).
2374
+ */
2375
+ __publicField(this, "realtime", {
2376
+ subscribe: (params) => subscribeBrowserRealtime(
2377
+ this.options,
2378
+ this.ragableAuth,
2379
+ this.fetchImpl,
2380
+ params
2381
+ )
2382
+ });
2364
2383
  this.fetchImpl = bindFetch(options.fetch);
2365
2384
  }
2366
2385
  /** @internal Called by RagableBrowser to share the Transport instance. */
@@ -2374,6 +2393,89 @@ var RagableBrowserDatabaseClient = class {
2374
2393
  return new Headers(this.options.headers);
2375
2394
  }
2376
2395
  };
2396
+ function followAbortSignal(parent, child) {
2397
+ if (!parent) return;
2398
+ if (parent.aborted) {
2399
+ child.abort();
2400
+ return;
2401
+ }
2402
+ parent.addEventListener("abort", () => child.abort(), { once: true });
2403
+ }
2404
+ async function subscribeBrowserRealtime(options, ragableAuth, fetchImpl, params) {
2405
+ const gid = requireAuthGroupId(options);
2406
+ const token = await resolveDatabaseAuthBearer(options, ragableAuth);
2407
+ const databaseInstanceId = params.databaseInstanceId?.trim() || options.databaseInstanceId?.trim();
2408
+ if (!databaseInstanceId) {
2409
+ throw new RagableError(
2410
+ "realtime.subscribe requires databaseInstanceId in params or on createBrowserClient({ databaseInstanceId })",
2411
+ 400,
2412
+ { code: "SDK_MISSING_DATABASE_INSTANCE_ID" }
2413
+ );
2414
+ }
2415
+ if (!Array.isArray(params.channels) || params.channels.length === 0) {
2416
+ throw new RagableError(
2417
+ "realtime.subscribe requires a non-empty channels array",
2418
+ 400,
2419
+ { code: "SDK_REALTIME_CHANNELS_REQUIRED" }
2420
+ );
2421
+ }
2422
+ const ac = new AbortController();
2423
+ followAbortSignal(params.signal, ac);
2424
+ const headers = new Headers(options.headers);
2425
+ headers.set("Authorization", `Bearer ${token}`);
2426
+ headers.set("Content-Type", "application/json");
2427
+ const response = await fetchImpl(
2428
+ `${normalizeBrowserApiBase()}/auth-groups/${gid}/data/realtime/stream`,
2429
+ {
2430
+ method: "POST",
2431
+ headers,
2432
+ body: JSON.stringify({
2433
+ databaseInstanceId,
2434
+ channels: params.channels
2435
+ }),
2436
+ signal: ac.signal
2437
+ }
2438
+ );
2439
+ const payload = await parseMaybeJsonBody(response);
2440
+ if (!response.ok) {
2441
+ const message = extractErrorMessage(payload, response.statusText);
2442
+ throw new RagableError(message, response.status, payload);
2443
+ }
2444
+ const streamBody = response.body;
2445
+ if (!streamBody) {
2446
+ throw new RagableError(
2447
+ "Realtime stream has no body",
2448
+ 502,
2449
+ { code: "SDK_REALTIME_NO_BODY" }
2450
+ );
2451
+ }
2452
+ void (async () => {
2453
+ try {
2454
+ for await (const evt of readSseStream(streamBody)) {
2455
+ if (evt.type === "realtime:ready") {
2456
+ const ch = evt.channels;
2457
+ params.onReady?.(
2458
+ Array.isArray(ch) ? ch.map((c) => String(c)) : []
2459
+ );
2460
+ } else if (evt.type === "notify") {
2461
+ params.onNotify?.({
2462
+ channel: String(evt.channel ?? ""),
2463
+ payload: evt.payload === void 0 || evt.payload === null ? null : String(evt.payload),
2464
+ processId: Number(evt.processId ?? 0)
2465
+ });
2466
+ } else if (evt.type === "realtime:error") {
2467
+ params.onError?.(String(evt.message ?? "Realtime error"));
2468
+ }
2469
+ }
2470
+ } catch (e) {
2471
+ if (e.name === "AbortError") return;
2472
+ params.onError?.(e.message);
2473
+ }
2474
+ })();
2475
+ return {
2476
+ unsubscribe: () => ac.abort()
2477
+ };
2478
+ }
2377
2479
  var RagableBrowserAgentsClient = class {
2378
2480
  constructor(options) {
2379
2481
  this.options = options;