@bounded-sh/core 0.0.4 → 0.0.6

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
@@ -4257,6 +4257,91 @@ const pendingRequests = {};
4257
4257
  const GET_CACHE_TTL = 500; // Adjust this value as needed (in milliseconds)
4258
4258
  // Last time we cleaned up the cache
4259
4259
  let lastCacheCleanup = Date.now();
4260
+ /**
4261
+ * Return the leaf document key (last path segment) for a document path.
4262
+ *
4263
+ * Bounded rows carry `_id` (and `pathId`) set to the FULL document path
4264
+ * (e.g. `"rooms/r1/prompts/8rd49se3sg"`). Apps that build a child path from a
4265
+ * row naturally want the bare doc key, not the whole path — using the full path
4266
+ * doubles it (`rooms/r1/prompts/rooms/r1/prompts/8rd.../votes/...`) → 403/404.
4267
+ * `docId` extracts that leaf key. Tolerates leading slashes and a trailing `*`.
4268
+ *
4269
+ * @example docId("rooms/r1/prompts/8rd49se3sg") // "8rd49se3sg"
4270
+ */
4271
+ function docId(path) {
4272
+ if (typeof path !== 'string')
4273
+ return '';
4274
+ let p = path.startsWith('/') ? path.slice(1) : path;
4275
+ if (p.endsWith('*') && p.length > 1)
4276
+ p = p.slice(0, -1);
4277
+ if (p.endsWith('/'))
4278
+ p = p.slice(0, -1);
4279
+ const segments = p.split('/').filter(Boolean);
4280
+ return segments.length ? segments[segments.length - 1] : '';
4281
+ }
4282
+ /**
4283
+ * Additively attach a convenience bare `id` (the leaf doc key) to a returned row.
4284
+ *
4285
+ * Rows already carry `_id`/`pathId` = the full document path; this leaves those
4286
+ * untouched and adds `id` = the last path segment so `row.id` is the doc key apps
4287
+ * expect. No-ops for non-objects, arrays, and rows that already define `id`
4288
+ * (never clobber a user field named `id`). Source for the leaf is `_id` (falling
4289
+ * back to `pathId`/`relativePath`/`absolutePath`).
4290
+ */
4291
+ function withBareId(row) {
4292
+ var _a, _b, _c;
4293
+ if (!row || typeof row !== 'object' || Array.isArray(row))
4294
+ return row;
4295
+ const r = row;
4296
+ if ('id' in r)
4297
+ return row; // don't clobber an explicit user field
4298
+ const source = (_c = (_b = (_a = r._id) !== null && _a !== void 0 ? _a : r.pathId) !== null && _b !== void 0 ? _b : r.relativePath) !== null && _c !== void 0 ? _c : r.absolutePath;
4299
+ if (typeof source !== 'string' || source.length === 0)
4300
+ return row;
4301
+ const leaf = docId(source);
4302
+ if (!leaf)
4303
+ return row;
4304
+ return Object.assign(Object.assign({}, r), { id: leaf });
4305
+ }
4306
+ /**
4307
+ * Normalize a raw read response from the worker into the SDK's stable shape and
4308
+ * attach the bare `id` to every returned row (Bug 1 + Bug 2).
4309
+ *
4310
+ * - Single-document path: returns EXACTLY ONE shape — the resolved document, or
4311
+ * `null` if missing (Firebase/Mongo convention). Unwraps the ambiguous
4312
+ * `{ data, status }` envelope the worker sometimes emits for a single doc so a
4313
+ * single-doc `get` never sometimes-returns the doc and sometimes the envelope.
4314
+ * - Collection path: preserves the `{ data, nextCursor, ... }` envelope and maps
4315
+ * the bare `id` onto each row in `data`.
4316
+ */
4317
+ function normalizeReadResult(responseData, pathIsDocument) {
4318
+ if (pathIsDocument) {
4319
+ let doc = responseData;
4320
+ // Unwrap the single-doc envelope `{ data, status }` (Bug 2). A real document
4321
+ // never has the exact shape `{ data, status }` with nothing else meaningful,
4322
+ // so detect the envelope by `data` + numeric `status` AND the absence of a
4323
+ // top-level `_id` (a real stored doc always carries `_id`/`pathId` from the
4324
+ // worker; the envelope wrapper does not). This avoids unwrapping a genuine
4325
+ // document that merely happens to own `data`/`status` fields.
4326
+ if (doc && typeof doc === 'object' && !Array.isArray(doc) &&
4327
+ 'data' in doc && 'status' in doc && typeof doc.status === 'number' &&
4328
+ !('_id' in doc) && !('pathId' in doc)) {
4329
+ doc = doc.data;
4330
+ }
4331
+ if (doc === undefined || doc === null)
4332
+ return null;
4333
+ return withBareId(doc);
4334
+ }
4335
+ // Collection read. The worker body is `{ data: rows[], nextCursor?, status? }`.
4336
+ if (responseData && typeof responseData === 'object' && !Array.isArray(responseData) && Array.isArray(responseData.data)) {
4337
+ return Object.assign(Object.assign({}, responseData), { data: responseData.data.map((row) => withBareId(row)) });
4338
+ }
4339
+ // Some paths return a bare array of rows — map id onto each.
4340
+ if (Array.isArray(responseData)) {
4341
+ return responseData.map((row) => withBareId(row));
4342
+ }
4343
+ return responseData;
4344
+ }
4260
4345
  function hashForKey$1(value) {
4261
4346
  let h = 5381;
4262
4347
  for (let i = 0; i < value.length; i++) {
@@ -4681,7 +4766,7 @@ async function get(path, opts = {}) {
4681
4766
  if (hasActiveConnection()) {
4682
4767
  if (pathIsDocument) {
4683
4768
  const wsResult = await wsGet(normalizedPath);
4684
- const responseData = wsResult;
4769
+ const responseData = normalizeReadResult(wsResult, true);
4685
4770
  if (!opts.bypassCache) {
4686
4771
  getCache[cacheKey] = { data: responseData, expiresAt: now + GET_CACHE_TTL };
4687
4772
  }
@@ -4693,7 +4778,7 @@ async function get(path, opts = {}) {
4693
4778
  sort: undefined,
4694
4779
  includeSubPaths: opts.includeSubPaths,
4695
4780
  });
4696
- const responseData = wsResult;
4781
+ const responseData = normalizeReadResult(wsResult, false);
4697
4782
  if (!opts.bypassCache) {
4698
4783
  getCache[cacheKey] = { data: responseData, expiresAt: now + GET_CACHE_TTL };
4699
4784
  }
@@ -4724,7 +4809,11 @@ async function get(path, opts = {}) {
4724
4809
  const apiPath = `items?path=${path}${promptQueryParam}${filterParam}${sortParam}${includeSubPathsParam}${shapeParam}${limitParam}${cursorParam}`;
4725
4810
  response = await makeApiRequest('GET', apiPath, null, opts._overrides);
4726
4811
  }
4727
- const responseData = response.data;
4812
+ // Normalize the worker's raw body into the SDK's stable shape:
4813
+ // - single-doc path → the resolved document or null (Bug 2), and
4814
+ // - collection path → `{ data, nextCursor }` preserved,
4815
+ // with the bare `id` (leaf doc key) attached to every returned row (Bug 1).
4816
+ const responseData = normalizeReadResult(response.data, pathIsDocument);
4728
4817
  // Cache the response (unless bypassing cache)
4729
4818
  if (!opts.bypassCache) {
4730
4819
  getCache[cacheKey] = {
@@ -4822,11 +4911,16 @@ async function getMany(paths, opts = {}) {
4822
4911
  const normalizedPath = uncachedPaths[i];
4823
4912
  const serverResult = serverResultsMap.get(normalizedPath);
4824
4913
  if (serverResult) {
4825
- results[originalIndex] = serverResult;
4826
- if (!serverResult.error && !opts.bypassCache) {
4914
+ // getMany batches single-doc paths — attach the bare `id` (leaf doc
4915
+ // key) to each returned doc, additive (Bug 1), matching get().
4916
+ const normalizedResult = serverResult.error
4917
+ ? serverResult
4918
+ : Object.assign(Object.assign({}, serverResult), { data: withBareId(serverResult.data) });
4919
+ results[originalIndex] = normalizedResult;
4920
+ if (!normalizedResult.error && !opts.bypassCache) {
4827
4921
  const cacheKey = `${principalKey}|${normalizedPath}:`;
4828
4922
  getCache[cacheKey] = {
4829
- data: serverResult.data,
4923
+ data: normalizedResult.data,
4830
4924
  expiresAt: now + GET_CACHE_TTL
4831
4925
  };
4832
4926
  }
@@ -5371,6 +5465,7 @@ var operations = /*#__PURE__*/Object.freeze({
5371
5465
  aggregate: aggregate,
5372
5466
  clearReadCacheForAuthChange: clearReadCacheForAuthChange,
5373
5467
  count: count,
5468
+ docId: docId,
5374
5469
  get: get,
5375
5470
  getFiles: getFiles,
5376
5471
  getMany: getMany,
@@ -5958,14 +6053,46 @@ function handleServerMessage(connection, message) {
5958
6053
  }
5959
6054
  }
5960
6055
  }
6056
+ /**
6057
+ * Additively attach the bare `id` (leaf doc key) to a subscription row (Bug 1).
6058
+ * Rows carry `_id`/`pathId` = the full document path; this leaves those as-is and
6059
+ * adds `id` = the last path segment so `row.id` is the doc key apps expect. No-ops
6060
+ * for non-objects and rows that already define `id`.
6061
+ */
6062
+ function withSubscriptionId(row) {
6063
+ var _a, _b, _c;
6064
+ if (!row || typeof row !== 'object' || Array.isArray(row))
6065
+ return row;
6066
+ if ('id' in row)
6067
+ return row;
6068
+ const source = (_c = (_b = (_a = row._id) !== null && _a !== void 0 ? _a : row.pathId) !== null && _b !== void 0 ? _b : row.relativePath) !== null && _c !== void 0 ? _c : row.absolutePath;
6069
+ if (typeof source !== 'string' || source.length === 0)
6070
+ return row;
6071
+ const leaf = docId(source);
6072
+ if (!leaf)
6073
+ return row;
6074
+ return Object.assign(Object.assign({}, row), { id: leaf });
6075
+ }
6076
+ /**
6077
+ * The `onData` payload follows the path: a collection delivers a bare array of
6078
+ * rows, a single-doc path delivers the document (or null). Attach the bare `id`
6079
+ * to each returned row in either case, additive (Bug 1).
6080
+ */
6081
+ function addIdsToSubscriptionData(data) {
6082
+ if (Array.isArray(data))
6083
+ return data.map(withSubscriptionId);
6084
+ return withSubscriptionId(data);
6085
+ }
5961
6086
  function notifyCallbacks(subscription, data) {
5962
6087
  var _a;
6088
+ // Attach the bare `id` (leaf doc key) to every delivered row (Bug 1).
6089
+ const decorated = addIdsToSubscriptionData(data);
5963
6090
  // Snapshot the callbacks array so that unsubscriptions during
5964
6091
  // notification don't cause callbacks to be skipped.
5965
6092
  const callbacks = subscription.callbacks.slice();
5966
6093
  for (const callback of callbacks) {
5967
6094
  try {
5968
- (_a = callback.onData) === null || _a === void 0 ? void 0 : _a.call(callback, data);
6095
+ (_a = callback.onData) === null || _a === void 0 ? void 0 : _a.call(callback, decorated);
5969
6096
  }
5970
6097
  catch (error) {
5971
6098
  console.error('[WS v2] Error in subscription callback:', error);
@@ -6056,7 +6183,7 @@ async function subscribeV2(path, subscriptionOptions, roomRoutePath) {
6056
6183
  if (cachedEntry && Date.now() - cachedEntry.timestamp < CACHE_TTL && subscriptionOptions.onData) {
6057
6184
  setTimeout(() => {
6058
6185
  var _a;
6059
- (_a = subscriptionOptions.onData) === null || _a === void 0 ? void 0 : _a.call(subscriptionOptions, cachedEntry.data);
6186
+ (_a = subscriptionOptions.onData) === null || _a === void 0 ? void 0 : _a.call(subscriptionOptions, addIdsToSubscriptionData(cachedEntry.data));
6060
6187
  }, 0);
6061
6188
  }
6062
6189
  // Get or create connection for this routing target (room-scoped when a
@@ -6086,7 +6213,7 @@ async function subscribeV2(path, subscriptionOptions, roomRoutePath) {
6086
6213
  if (existingSubscription.lastData !== undefined && subscriptionOptions.onData) {
6087
6214
  setTimeout(() => {
6088
6215
  var _a;
6089
- (_a = subscriptionOptions.onData) === null || _a === void 0 ? void 0 : _a.call(subscriptionOptions, existingSubscription.lastData);
6216
+ (_a = subscriptionOptions.onData) === null || _a === void 0 ? void 0 : _a.call(subscriptionOptions, addIdsToSubscriptionData(existingSubscription.lastData));
6090
6217
  }, 0);
6091
6218
  }
6092
6219
  return async () => {
@@ -7845,5 +7972,5 @@ function defineLiveModule(mod) {
7845
7972
  return mod;
7846
7973
  }
7847
7974
 
7848
- export { EFFECT_INTENT_ADDRESS, FunctionInvokeError, InsufficientBalanceError, LiveIntentError, ReactNativeSessionManager, RealtimeStore, ServerSessionManager, WebSessionManager, aggregate, buildSetDocumentsTransaction, clearCache, closeAllSubscriptions, convertRemainingAccounts, count, createSessionWithSignature, defineLiveModule, deriveUserIdentityFromIdToken, functions, genAuthNonce, genSolanaMessage, get, getActiveSessionManager, getCachedData, getConfig, getFiles, getIdToken, getMany, getRealtimeStore, getWebhookKeysUrl, hasActiveConnection, increment, init, invoke as invokeFunction, isEffectResult, live, intent as liveIntent, status as liveStatus, now, queryAggregate, reconnectWithNewAuth, refreshSession, resetRealtimeStore, revokeSession, runExpression, runExpressionMany, runQuery, runQueryMany, search, serverTimestamp, set, setFile, setMany, signAndSubmitTransaction, signMessage, signSessionCreateMessage, signTransaction, subscribe, subscribeView as subscribeLiveView, toMillis, toSeconds, withEffects, wsDelete, wsGet, wsGetMany, wsQuery, wsSet };
7975
+ export { EFFECT_INTENT_ADDRESS, FunctionInvokeError, InsufficientBalanceError, LiveIntentError, ReactNativeSessionManager, RealtimeStore, ServerSessionManager, WebSessionManager, aggregate, buildSetDocumentsTransaction, clearCache, closeAllSubscriptions, convertRemainingAccounts, count, createSessionWithSignature, defineLiveModule, deriveUserIdentityFromIdToken, docId, functions, genAuthNonce, genSolanaMessage, get, getActiveSessionManager, getCachedData, getConfig, getFiles, getIdToken, getMany, getRealtimeStore, getWebhookKeysUrl, hasActiveConnection, increment, init, invoke as invokeFunction, isEffectResult, live, intent as liveIntent, status as liveStatus, now, queryAggregate, reconnectWithNewAuth, refreshSession, resetRealtimeStore, revokeSession, runExpression, runExpressionMany, runQuery, runQueryMany, search, serverTimestamp, set, setFile, setMany, signAndSubmitTransaction, signMessage, signSessionCreateMessage, signTransaction, subscribe, subscribeView as subscribeLiveView, toMillis, toSeconds, withEffects, wsDelete, wsGet, wsGetMany, wsQuery, wsSet };
7849
7976
  //# sourceMappingURL=index.mjs.map