@ragable/sdk 0.6.20 → 0.6.22

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.mjs CHANGED
@@ -627,6 +627,17 @@ async function parseTransportResponse(response) {
627
627
  }
628
628
 
629
629
  // src/browser-postgrest.ts
630
+ function toRagableResult(r) {
631
+ if (r.error) return { ok: false, error: r.error };
632
+ return { ok: true, value: r.data };
633
+ }
634
+ function assertPostgrestSuccess(r) {
635
+ if (r.error) throw r.error;
636
+ }
637
+ function unwrapPostgrest(r) {
638
+ if (r.error) throw r.error;
639
+ return r.data;
640
+ }
630
641
  async function asPostgrestResponse(fn) {
631
642
  try {
632
643
  const data = await fn();
@@ -2212,24 +2223,71 @@ var RagableBrowserAuthClient = class {
2212
2223
  return this.auth.getSession();
2213
2224
  }
2214
2225
  };
2226
+ function collectionRecordToRowWithMeta(record) {
2227
+ const { data, id, createdAt, updatedAt } = record;
2228
+ return { ...data, meta: { id, createdAt, updatedAt } };
2229
+ }
2230
+ function collectionRecordsToRowWithMeta(records) {
2231
+ return records.map(collectionRecordToRowWithMeta);
2232
+ }
2233
+ var FIND_QUERY_KEYS = [
2234
+ "where",
2235
+ "filters",
2236
+ "limit",
2237
+ "offset",
2238
+ "orderBy",
2239
+ "orderDirection",
2240
+ "return"
2241
+ ];
2215
2242
  var BrowserCollectionApi = class {
2216
2243
  constructor(database, name, databaseInstanceId) {
2217
2244
  this.database = database;
2218
2245
  this.name = name;
2219
2246
  this.databaseInstanceId = databaseInstanceId;
2220
- __publicField(this, "find", (whereOrParams = {}) => {
2221
- const hasQueryKeys = ["where", "filters", "limit", "offset", "orderBy", "orderDirection"].some(
2222
- (key) => Object.prototype.hasOwnProperty.call(whereOrParams, key)
2223
- );
2224
- const body = hasQueryKeys ? whereOrParams : { where: whereOrParams };
2225
- return asPostgrestResponse(
2226
- () => this.database._requestCollection(
2227
- "POST",
2228
- `/${encodeURIComponent(this.name)}/find`,
2229
- body,
2230
- this.databaseInstanceId
2231
- )
2232
- );
2247
+ __publicField(this, "requestFind", (body) => asPostgrestResponse(
2248
+ () => this.database._requestCollection(
2249
+ "POST",
2250
+ `/${encodeURIComponent(this.name)}/find`,
2251
+ body,
2252
+ this.databaseInstanceId
2253
+ )
2254
+ ));
2255
+ /**
2256
+ * Query collection rows. Prefer this over the deprecated `find` alias.
2257
+ * Use `return: "flat"` to get {@link CollectionRowWithMeta} without nested `.data`.
2258
+ */
2259
+ __publicField(this, "findMany", async (whereOrParams = {}) => {
2260
+ const { returnMode, body } = this.normalizeFindArgs(whereOrParams);
2261
+ const res = await this.requestFind(body);
2262
+ if (res.error) return res;
2263
+ if (returnMode === "flat") {
2264
+ return {
2265
+ data: collectionRecordsToRowWithMeta(res.data),
2266
+ error: null
2267
+ };
2268
+ }
2269
+ return res;
2270
+ });
2271
+ /**
2272
+ * @deprecated Use {@link BrowserCollectionApi.findMany} — same behavior.
2273
+ */
2274
+ __publicField(this, "find", (whereOrParams = {}) => this.findMany(whereOrParams));
2275
+ /**
2276
+ * At most one row, `data` is the record or `null` if none match (not an error).
2277
+ */
2278
+ __publicField(this, "findFirst", async (whereOrParams = {}) => {
2279
+ const { body } = this.normalizeFindArgs(whereOrParams);
2280
+ const withCap = { ...body, limit: 1, offset: body["offset"] ?? 0 };
2281
+ const res = await this.requestFind(withCap);
2282
+ if (res.error) return res;
2283
+ return { data: res.data[0] ?? null, error: null };
2284
+ });
2285
+ /**
2286
+ * Lookup by primary key `id` (envelope). Equivalent to
2287
+ * `findFirst({ where: { id }, limit: 1 })` with a typed `where.id`.
2288
+ */
2289
+ __publicField(this, "findUnique", async (args) => {
2290
+ return this.findFirst({ where: args.where });
2233
2291
  });
2234
2292
  __publicField(this, "insert", (data) => asPostgrestResponse(
2235
2293
  () => this.database._requestCollection(
@@ -2239,6 +2297,9 @@ var BrowserCollectionApi = class {
2239
2297
  this.databaseInstanceId
2240
2298
  )
2241
2299
  ));
2300
+ /**
2301
+ * Update rows matching `where` (JSON fields, plus envelope `id` / `createdAt` / `updatedAt`).
2302
+ */
2242
2303
  __publicField(this, "update", (where, patch, options) => asPostgrestResponse(
2243
2304
  () => this.database._requestCollection(
2244
2305
  "PATCH",
@@ -2247,6 +2308,15 @@ var BrowserCollectionApi = class {
2247
2308
  this.databaseInstanceId
2248
2309
  )
2249
2310
  ));
2311
+ /**
2312
+ * Like {@link BrowserCollectionApi.update} but the success payload includes
2313
+ * `meta.count` (number of rows returned from the update, bounded by `limit`).
2314
+ */
2315
+ __publicField(this, "updateMany", async (where, patch, options) => {
2316
+ const r = await this.update(where, patch, options);
2317
+ if (r.error) return r;
2318
+ return { data: { records: r.data, meta: { count: r.data.length } }, error: null };
2319
+ });
2250
2320
  __publicField(this, "delete", (where, options) => asPostgrestResponse(
2251
2321
  () => this.database._requestCollection(
2252
2322
  "DELETE",
@@ -2256,6 +2326,15 @@ var BrowserCollectionApi = class {
2256
2326
  )
2257
2327
  ));
2258
2328
  }
2329
+ normalizeFindArgs(whereOrParams) {
2330
+ const hasQueryKeys = typeof whereOrParams === "object" && whereOrParams !== null && FIND_QUERY_KEYS.some(
2331
+ (key) => Object.prototype.hasOwnProperty.call(whereOrParams, key)
2332
+ );
2333
+ const raw = hasQueryKeys ? { ...whereOrParams } : { where: whereOrParams };
2334
+ const returnMode = raw["return"] === "flat" ? "flat" : "envelope";
2335
+ delete raw["return"];
2336
+ return { returnMode, body: raw };
2337
+ }
2259
2338
  };
2260
2339
  var RagableBrowserDatabaseClient = class {
2261
2340
  constructor(options, ragableAuth = null) {
@@ -2650,6 +2729,31 @@ var RagableBrowserAgentsClient = class {
2650
2729
  toUrl(path) {
2651
2730
  return `${normalizeBrowserApiBase()}${path.startsWith("/") ? path : `/${path}`}`;
2652
2731
  }
2732
+ requireWebsiteId() {
2733
+ const websiteId = this.options.websiteId?.trim();
2734
+ if (!websiteId) {
2735
+ throw new RagableError(
2736
+ "websiteId is required for project agent conversation APIs. Use the generated createWebsiteRagableClient() or pass createBrowserClient({ websiteId, ... }).",
2737
+ 400,
2738
+ { code: "SDK_MISSING_WEBSITE_ID" }
2739
+ );
2740
+ }
2741
+ return websiteId;
2742
+ }
2743
+ websiteAgentPath(path) {
2744
+ const websiteId = this.requireWebsiteId();
2745
+ return `/public/organizations/${this.options.organizationId}/websites/${websiteId}${path}`;
2746
+ }
2747
+ async requestJson(path, init = {}) {
2748
+ const response = await this.fetchImpl(this.toUrl(path), init);
2749
+ const payload = await parseMaybeJsonBody(response);
2750
+ if (!response.ok) {
2751
+ const message = extractErrorMessage(payload, response.statusText);
2752
+ throw new RagableError(message, response.status, payload);
2753
+ }
2754
+ return payload;
2755
+ }
2756
+ /** @deprecated Prefer `chatStreamByName(agentName, params)` for project-local `/agents/*.json` agents. */
2653
2757
  async *chatStream(agentId, params) {
2654
2758
  const orgId = this.options.organizationId;
2655
2759
  const body = {
@@ -2679,6 +2783,107 @@ var RagableBrowserAgentsClient = class {
2679
2783
  }
2680
2784
  yield* readSseStream(streamBody);
2681
2785
  }
2786
+ async *chatStreamByName(agentName, params) {
2787
+ const headers = new Headers(this.options.headers);
2788
+ headers.set("Content-Type", "application/json");
2789
+ const response = await this.fetchImpl(
2790
+ this.toUrl(
2791
+ this.websiteAgentPath(
2792
+ `/agents/${encodeURIComponent(agentName)}/chat/stream`
2793
+ )
2794
+ ),
2795
+ {
2796
+ method: "POST",
2797
+ headers,
2798
+ body: JSON.stringify({
2799
+ message: params.message,
2800
+ ...params.history !== void 0 ? { history: params.history } : {}
2801
+ })
2802
+ }
2803
+ );
2804
+ if (!response.ok) {
2805
+ const payload = await parseMaybeJsonBody(response);
2806
+ const message = extractErrorMessage(payload, response.statusText);
2807
+ throw new RagableError(message, response.status, payload);
2808
+ }
2809
+ if (!response.body) return;
2810
+ yield* readSseStream(response.body);
2811
+ }
2812
+ createConversation(params) {
2813
+ const headers = new Headers(this.options.headers);
2814
+ headers.set("Content-Type", "application/json");
2815
+ return this.requestJson(
2816
+ this.websiteAgentPath("/agent-conversations"),
2817
+ {
2818
+ method: "POST",
2819
+ headers,
2820
+ body: JSON.stringify(params)
2821
+ }
2822
+ );
2823
+ }
2824
+ listConversations(params = {}) {
2825
+ const agentName = params.agent_name ?? params.agentName;
2826
+ const qs = agentName ? `?agentName=${encodeURIComponent(agentName)}` : "";
2827
+ return this.requestJson(
2828
+ this.websiteAgentPath(`/agent-conversations${qs}`)
2829
+ );
2830
+ }
2831
+ getConversation(conversationId) {
2832
+ return this.requestJson(
2833
+ this.websiteAgentPath(
2834
+ `/agent-conversations/${encodeURIComponent(conversationId)}`
2835
+ )
2836
+ );
2837
+ }
2838
+ updateConversation(conversationId, data) {
2839
+ const headers = new Headers(this.options.headers);
2840
+ headers.set("Content-Type", "application/json");
2841
+ return this.requestJson(
2842
+ this.websiteAgentPath(
2843
+ `/agent-conversations/${encodeURIComponent(conversationId)}`
2844
+ ),
2845
+ {
2846
+ method: "PATCH",
2847
+ headers,
2848
+ body: JSON.stringify(data)
2849
+ }
2850
+ );
2851
+ }
2852
+ addMessage(conversationOrId, message) {
2853
+ const conversationId = typeof conversationOrId === "string" ? conversationOrId : conversationOrId.id;
2854
+ const headers = new Headers(this.options.headers);
2855
+ headers.set("Content-Type", "application/json");
2856
+ return this.requestJson(
2857
+ this.websiteAgentPath(
2858
+ `/agent-conversations/${encodeURIComponent(conversationId)}/messages`
2859
+ ),
2860
+ {
2861
+ method: "POST",
2862
+ headers,
2863
+ body: JSON.stringify(message)
2864
+ }
2865
+ );
2866
+ }
2867
+ subscribeToConversation(conversationId, callback, options = {}) {
2868
+ let stopped = false;
2869
+ let timer = null;
2870
+ const intervalMs = Math.max(500, options.intervalMs ?? 1500);
2871
+ const tick = async () => {
2872
+ if (stopped) return;
2873
+ try {
2874
+ callback(await this.getConversation(conversationId));
2875
+ } finally {
2876
+ if (!stopped) timer = setTimeout(tick, intervalMs);
2877
+ }
2878
+ };
2879
+ void tick();
2880
+ return {
2881
+ unsubscribe: () => {
2882
+ stopped = true;
2883
+ if (timer) clearTimeout(timer);
2884
+ }
2885
+ };
2886
+ }
2682
2887
  };
2683
2888
  var RagableBrowser = class {
2684
2889
  constructor(options) {
@@ -2848,7 +3053,10 @@ export {
2848
3053
  ShiftClient,
2849
3054
  Transport,
2850
3055
  asPostgrestResponse,
3056
+ assertPostgrestSuccess,
2851
3057
  bindFetch,
3058
+ collectionRecordToRowWithMeta,
3059
+ collectionRecordsToRowWithMeta,
2852
3060
  createBrowserClient,
2853
3061
  createClient,
2854
3062
  createRagPipeline,
@@ -2864,6 +3072,8 @@ export {
2864
3072
  normalizeBrowserApiBase,
2865
3073
  parseSseDataLine,
2866
3074
  parseTransportResponse,
2867
- readSseStream
3075
+ readSseStream,
3076
+ toRagableResult,
3077
+ unwrapPostgrest
2868
3078
  };
2869
3079
  //# sourceMappingURL=index.mjs.map