@rebasepro/client 0.30.0 → 0.31.0-canary.g902a0ce

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.
@@ -12,5 +12,11 @@ export declare function dehydrateRow<T extends Record<string, unknown>>(row: T):
12
12
  export declare function hydrateRow<T extends Record<string, unknown>>(row: Record<string, unknown>): T;
13
13
  /** Prepare a queued write for the store. */
14
14
  export declare function dehydrateMutation(op: PendingMutation): PendingMutation;
15
- /** Restore a queued write read back from the store. */
15
+ /**
16
+ * Restore a queued write read back from the store. An entry of layout 1 —
17
+ * written before the client held wire values only — has its view-model values
18
+ * converted to wire values and is stamped with the current layout, so it
19
+ * replays as the server stored such a write and is persisted that way the
20
+ * next time the entry is written back.
21
+ */
16
22
  export declare function hydrateMutation(op: PendingMutation): PendingMutation;
@@ -1,8 +1,8 @@
1
- import { type SDKCollectionClient } from "@rebasepro/types";
2
- import type { CollectionClient } from "./collection.js";
1
+ import { type SDKTableClient } from "@rebasepro/types";
2
+ import type { TableClient } from "./table.js";
3
3
  import type { OfflineApi, OfflineConfig } from "./offline.js";
4
4
  type AnyRow = Record<string, unknown>;
5
- type InnerFactory = (slug: string) => SDKCollectionClient<AnyRow>;
5
+ type InnerFactory = (slug: string) => SDKTableClient<AnyRow>;
6
6
  /**
7
7
  * `createRebaseClient({ offline })`'s handle on the sync engine, which it
8
8
  * fetches with `import()` the moment the client is created.
@@ -17,7 +17,7 @@ type InnerFactory = (slug: string) => SDKCollectionClient<AnyRow>;
17
17
  *
18
18
  * - Calls made before the engine has arrived are queued and run, in the order
19
19
  * they were made, the moment it does — the scope changes the factory makes
20
- * from auth events, and every collection a client wrapped meanwhile.
20
+ * from auth events, and every table a client wrapped meanwhile.
21
21
  * - What answers with a promise waits for the engine and then asks it.
22
22
  * - What answers synchronously answers what the engine would have before
23
23
  * anything ran: `status()` is the initial status, a subscription is
@@ -54,6 +54,6 @@ export declare class LazyOfflineManager {
54
54
  * The engine's wrapper around `inner` — itself once the engine is there,
55
55
  * and until then a client of the same shape that hands each call to it.
56
56
  */
57
- wrap<M extends AnyRow>(slug: string, inner: CollectionClient<M>): CollectionClient<M>;
57
+ wrap<M extends AnyRow>(slug: string, inner: TableClient<M>): TableClient<M>;
58
58
  }
59
59
  export {};
@@ -1,109 +1,5 @@
1
- import { EntityReference, EntityRelation, GeoPoint, IMPERSONATE_HEADER, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, RebaseClientError as RebaseClientError$1, SCHEMA_VERSION_HEADER, Vector, isUnsupported, sortKeyToString, unsupportedMethod } from "@rebasepro/types";
1
+ import { IMPERSONATE_HEADER, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, RebaseClientError as RebaseClientError$1, SCHEMA_VERSION_HEADER, isUnsupported, sortKeyToString, unsupportedMethod } from "@rebasepro/types";
2
2
  import { RESERVED_QUERY_KEYS, collectAllPages, etagOf, mergeIncludeSpecs, normalizeOrderBy, paginateFind, resolveFindWindow, serializeFilter, serializeInclude, serializeLogicalCondition, serializeOrderBy, withETag } from "@rebasepro/common";
3
- //#region src/reviver.ts
4
- function rebaseReviver(_key, value) {
5
- if (value && typeof value === "object" && "__type" in value) {
6
- const record = value;
7
- switch (record.__type) {
8
- case "date":
9
- case "Date": {
10
- if (typeof record.value !== "string") return value;
11
- const date = new Date(record.value);
12
- return isNaN(date.getTime()) ? null : date;
13
- }
14
- case "reference":
15
- case "EntityReference": return new EntityReference({
16
- id: String(record.id),
17
- path: record.path,
18
- driver: record.driver,
19
- databaseId: record.databaseId
20
- });
21
- case "relation":
22
- case "EntityRelation": return new EntityRelation(record.id, record.path, record.data);
23
- case "GeoPoint": return new GeoPoint(record.latitude, record.longitude);
24
- case "Vector": return new Vector(record.value);
25
- default: return value;
26
- }
27
- }
28
- return value;
29
- }
30
- /**
31
- * Could `text` hold an object with a `__type` key — the only values
32
- * {@link rebaseReviver} changes?
33
- *
34
- * A key is spelled either literally or with `\u` escapes, so a body with
35
- * neither cannot contain one. The check is two substring scans, which run at
36
- * memory speed; a false positive only costs the walk below.
37
- */
38
- function mayHoldTypedValues(text) {
39
- return text.includes("\"__type\"") || text.includes("\\u");
40
- }
41
- /**
42
- * Set a property the way `JSON.parse`'s reviver does: as an own data property.
43
- * A plain assignment to a key named `__proto__` would call the setter and swap
44
- * the object's prototype instead.
45
- */
46
- function setRevived(target, key, value) {
47
- if (key === "__proto__") Object.defineProperty(target, key, {
48
- value,
49
- writable: true,
50
- enumerable: true,
51
- configurable: true
52
- });
53
- else target[key] = value;
54
- }
55
- /**
56
- * {@link rebaseReviver}, applied bottom-up to an already parsed value, in
57
- * place: every child is revived before its parent, so a relation's `data` holds
58
- * its own revived values by the time the relation is built from it — the order
59
- * `JSON.parse` calls a reviver in. Primitives are never visited; the reviver
60
- * hands every one of them back unchanged.
61
- */
62
- function reviveTree(value) {
63
- if (value === null || typeof value !== "object") return value;
64
- if (Array.isArray(value)) {
65
- for (let i = 0; i < value.length; i++) {
66
- const item = value[i];
67
- if (item !== null && typeof item === "object") {
68
- const revived = reviveTree(item);
69
- if (revived !== item) value[i] = revived;
70
- }
71
- }
72
- return value;
73
- }
74
- const record = value;
75
- for (const key of Object.keys(record)) {
76
- const item = record[key];
77
- if (item !== null && typeof item === "object") {
78
- const revived = reviveTree(item);
79
- if (revived !== item) setRevived(record, key, revived);
80
- }
81
- }
82
- return rebaseReviver("", record);
83
- }
84
- /**
85
- * `JSON.parse(text, rebaseReviver)`, without the reviver's cost where it has
86
- * nothing to do.
87
- *
88
- * Handing `JSON.parse` a reviver takes V8 off its fast path and calls back for
89
- * every key and every value, primitives included: about 7× a plain parse on a
90
- * 1,000-row page, 10 ms of main thread per 600 KB. The reviver only ever
91
- * changes objects carrying `__type`, and a REST page of flat rows has none. So
92
- * this parses plainly and walks the result only when the text can hold one —
93
- * and the walk visits objects, never primitives.
94
- *
95
- * Same result, instance for instance: the same values revived, bottom-up, as
96
- * own data properties, and nothing deleted (the reviver never answers
97
- * `undefined`).
98
- *
99
- * @throws SyntaxError exactly where `JSON.parse` does.
100
- */
101
- function parseRebaseJson(text) {
102
- const parsed = JSON.parse(text);
103
- if (!mayHoldTypedValues(text)) return parsed;
104
- return reviveTree(parsed);
105
- }
106
- //#endregion
107
3
  //#region src/transport.ts
108
4
  /**
109
5
  * True when there is no browser to have signed a user in — a Node script, a
@@ -214,7 +110,7 @@ function buildQueryString(params, deleted) {
214
110
  return encodePairs(findParamPairs(params, deleted));
215
111
  }
216
112
  /**
217
- * The body of `POST /data/<collection>/query`: the parameters
113
+ * The body of `POST /data/<table>/query`: the parameters
218
114
  * {@link buildQueryString} puts in the URL, spelled as the URL spells them —
219
115
  * each value a string, and a parameter the URL repeats (a filter with two
220
116
  * conditions on one field) a list of them. The server reads it back into the
@@ -253,7 +149,7 @@ function writeFilterBody(query) {
253
149
  * such a column sent as its own parameter is read as that parameter, and the
254
150
  * filter is never applied. Those conditions go inside `?where=` instead, in the
255
151
  * same dot-string spelling, which the server decodes through the same codec and
256
- * merges in. A collection with no such column sends exactly what it did before.
152
+ * merges in. A table with no such column sends exactly what it did before.
257
153
  */
258
154
  function appendWhere(pairs, where) {
259
155
  assertNoUndefinedFilterValues(where);
@@ -269,7 +165,7 @@ function appendWhere(pairs, where) {
269
165
  if (Object.keys(reserved).length > 0) pairs.push(["where", JSON.stringify(reserved)]);
270
166
  }
271
167
  /**
272
- * The query string for `GET /<collection>/aggregate`.
168
+ * The query string for `GET /<table>/aggregate`.
273
169
  *
274
170
  * `?select=sum(total),count()` is SQL's spelling, because whoever writes an
275
171
  * aggregate is thinking in SQL and any other spelling has to be learned first —
@@ -579,7 +475,7 @@ function createTransport(config, environment) {
579
475
  function parseBody(text) {
580
476
  if (!text) return {};
581
477
  try {
582
- return parseRebaseJson(text);
478
+ return JSON.parse(text);
583
479
  } catch (e) {
584
480
  return;
585
481
  }
@@ -628,7 +524,7 @@ function createTransport(config, environment) {
628
524
  if (!res.ok) {
629
525
  const text = readText ?? await res.text().catch(() => "");
630
526
  let fallbackMessage = res.statusText;
631
- if (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
527
+ if (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || "GET"} ${path}). This usually means the table is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;
632
528
  throw errorFrom(res, parseBody(text) ?? {}, fallbackMessage);
633
529
  }
634
530
  return res;
@@ -701,10 +597,10 @@ function createTransport(config, environment) {
701
597
  * console.log(data[0].title); // flat access
702
598
  */
703
599
  var SDKQueryBuilder = class {
704
- collection;
600
+ table;
705
601
  params = { where: {} };
706
- constructor(collection) {
707
- this.collection = collection;
602
+ constructor(table) {
603
+ this.table = table;
708
604
  }
709
605
  where(columnOrCondition, operator, value) {
710
606
  if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
@@ -764,8 +660,8 @@ var SDKQueryBuilder = class {
764
660
  /**
765
661
  * Set a free-text search string if supported by the backend.
766
662
  *
767
- * By default this is a substring match across the collection's top-level
768
- * string properties. A Postgres collection that declares a `search` block
663
+ * By default this is a substring match across the table's top-level
664
+ * string columns. A Postgres table that declares a `search` block
769
665
  * gets ranked full-text matching over the fields it named instead, and each
770
666
  * row comes back with a `_score` you can sort on:
771
667
  *
@@ -833,7 +729,7 @@ var SDKQueryBuilder = class {
833
729
  * ```
834
730
  *
835
731
  * Up to three hops deep, and `"*"` still loads every relation one hop
836
- * deep. A name that is not a relation of the collection is a 400
732
+ * deep. A name that is not a relation of the table is a 400
837
733
  * `UNKNOWN_RELATION` — it used to be ignored, which answers 200 with the
838
734
  * field missing and reads exactly like a row that has no related row.
839
735
  *
@@ -889,7 +785,7 @@ var SDKQueryBuilder = class {
889
785
  * Execute the find query and return the results as flat rows.
890
786
  */
891
787
  async find() {
892
- return this.collection.find(this.params);
788
+ return this.table.find(this.params);
893
789
  }
894
790
  /**
895
791
  * Aggregate the rows this query matches instead of returning them.
@@ -907,7 +803,7 @@ var SDKQueryBuilder = class {
907
803
  * ```
908
804
  */
909
805
  async aggregate(params) {
910
- return this.collection.aggregate({
806
+ return this.table.aggregate({
911
807
  ...params,
912
808
  where: this.params.where,
913
809
  logical: this.params.logical,
@@ -921,7 +817,7 @@ var SDKQueryBuilder = class {
921
817
  * single `find()` is not a ceiling on what the query can read.
922
818
  */
923
819
  iterate(options) {
924
- return this.collection.iterate({
820
+ return this.table.iterate({
925
821
  ...this.params,
926
822
  ...this.params.limit !== void 0 && { pageSize: this.params.limit },
927
823
  ...options
@@ -929,7 +825,7 @@ var SDKQueryBuilder = class {
929
825
  }
930
826
  /** Collect everything this query matches into one array. */
931
827
  findAll(options) {
932
- return this.collection.findAll({
828
+ return this.table.findAll({
933
829
  ...this.params,
934
830
  ...this.params.limit !== void 0 && { pageSize: this.params.limit },
935
831
  ...options
@@ -939,23 +835,23 @@ var SDKQueryBuilder = class {
939
835
  * Count the records matching this query.
940
836
  */
941
837
  async count() {
942
- return this.collection.count(this.params);
838
+ return this.table.count(this.params);
943
839
  }
944
840
  /**
945
841
  * Listen to realtime updates matching this query.
946
842
  *
947
- * The guard that used to stand here — `if (!this.collection.listen) throw`
843
+ * The guard that used to stand here — `if (!this.table.listen) throw`
948
844
  * — has moved onto the client itself, which is where the same failure had
949
845
  * to be diagnosed anyway: `client.data.posts.listen(…)`, one call short of
950
846
  * this builder, answered `undefined is not a function`. The message is now
951
847
  * the same either way.
952
848
  */
953
849
  listen(onUpdate, onError) {
954
- return this.collection.listen(this.params, onUpdate, onError);
850
+ return this.table.listen(this.params, onUpdate, onError);
955
851
  }
956
852
  };
957
853
  //#endregion
958
- //#region src/collection.ts
854
+ //#region src/table.ts
959
855
  /**
960
856
  * What `listen`/`listenById` say on a client that has no socket.
961
857
  *
@@ -995,7 +891,7 @@ function listenRefusal(params) {
995
891
  * request key is a path and a query string: it says nothing about *who* is
996
892
  * asking. So two clients holding different credentials — an admin panel beside
997
893
  * a signed-in user's client, a per-request server client in a Node process, a
998
- * test asserting one client's calls — counting the same collection would share
894
+ * test asserting one client's calls — counting the same table would share
999
895
  * one request, and whichever arrived second was answered with the first one's
1000
896
  * total. Row-level security makes those genuinely different numbers.
1001
897
  *
@@ -1027,7 +923,7 @@ function inflightCountsFor(transport) {
1027
923
  var serversWithoutCountParam = /* @__PURE__ */ new WeakSet();
1028
924
  /**
1029
925
  * The longest URL a `find()` sends as a `GET`. Past it the parameters go in
1030
- * the body of `POST /data/<collection>/query` instead.
926
+ * the body of `POST /data/<table>/query` instead.
1031
927
  *
1032
928
  * Not the server's own ceiling but the one in front of it: nginx refuses a
1033
929
  * request line over 8 KB by default (414), and a proxy or CDN is in front of
@@ -1064,7 +960,7 @@ function sendsQueryBody(transport, path, queryString, params, serversWithoutRout
1064
960
  *
1065
961
  * Against a server without the twin (404, or a proxy's 405) the `GET` is sent
1066
962
  * instead, and the transport remembers — unless the `GET` 404s as well, which
1067
- * is the collection's answer, not the route's.
963
+ * is the table's answer, not the route's.
1068
964
  */
1069
965
  /**
1070
966
  * A success whose body is not the shape the method reads: no body at all (a
@@ -1154,18 +1050,18 @@ function isDotSegment(segment) {
1154
1050
  return /^(?:\.|%2e){1,2}$/i.test(segment);
1155
1051
  }
1156
1052
  /**
1157
- * A collection path as the URL path under `/data/`, refused when one of its
1053
+ * A table path as the URL path under `/data/`, refused when one of its
1158
1054
  * segments is `.` or `..`.
1159
1055
  *
1160
- * The path may hold slashes (a nested collection), so it is not encoded whole,
1056
+ * The path may hold slashes (a nested table), so it is not encoded whole,
1161
1057
  * and `fetch` resolves a dot segment before the request leaves: `../admin/users`
1162
1058
  * would read another route, as whoever this client is. The URL parser also
1163
1059
  * reads `\` as `/` and drops tabs and newlines, so the path is split as it
1164
1060
  * will.
1165
1061
  */
1166
- function collectionPathSegment(slug) {
1167
- if (slug.replace(/[\t\n\r]/g, "").split(/[/\\]/).some(isDotSegment)) throw new RebaseClientError(`Invalid collection path ${JSON.stringify(slug)}: a \`.\` or \`..\` segment would leave /data.`, {
1168
- code: "INVALID_COLLECTION_PATH",
1062
+ function tablePathSegment(slug) {
1063
+ if (slug.replace(/[\t\n\r]/g, "").split(/[/\\]/).some(isDotSegment)) throw new RebaseClientError(`Invalid table path ${JSON.stringify(slug)}: a \`.\` or \`..\` segment would leave /data.`, {
1064
+ code: "INVALID_TABLE_PATH",
1169
1065
  details: { path: slug }
1170
1066
  });
1171
1067
  return slug;
@@ -1177,14 +1073,14 @@ function collectionPathSegment(slug) {
1177
1073
  */
1178
1074
  function rowIdSegment(id) {
1179
1075
  const segment = encodeURIComponent(String(id));
1180
- if (isDotSegment(segment)) throw new RebaseClientError(`Invalid row id ${JSON.stringify(String(id))}: it would address the collection, not a row.`, {
1076
+ if (isDotSegment(segment)) throw new RebaseClientError(`Invalid row id ${JSON.stringify(String(id))}: it would address the table, not a row.`, {
1181
1077
  code: "INVALID_ID",
1182
1078
  details: { id }
1183
1079
  });
1184
1080
  return segment;
1185
1081
  }
1186
- function createCollectionClient(transport, slug, ws) {
1187
- const basePath = `/data/${collectionPathSegment(slug)}`;
1082
+ function createTableClient(transport, slug, ws) {
1083
+ const basePath = `/data/${tablePathSegment(slug)}`;
1188
1084
  /**
1189
1085
  * A listing — the live rows, or with `deleted` the trash's. One reader for
1190
1086
  * both, so the trash takes every parameter, and every fallback for an
@@ -1530,7 +1426,7 @@ function createCollectionClient(transport, slug, ws) {
1530
1426
  },
1531
1427
  /**
1532
1428
  * `count`/`sum`/`avg`/`min`/`max` over the matching rows, optionally
1533
- * grouped — `GET /<collection>/aggregate`.
1429
+ * grouped — `GET /<table>/aggregate`.
1534
1430
  *
1535
1431
  * The REST route has served this since aggregates landed and the SDK
1536
1432
  * had no method for it, so the only way to reach it from a typed client
@@ -1547,7 +1443,7 @@ function createCollectionClient(transport, slug, ws) {
1547
1443
  });
1548
1444
  return rows;
1549
1445
  },
1550
- /** Recompute a materialized view's rows — `POST /<collection>/refresh`. */
1446
+ /** Recompute a materialized view's rows — `POST /<table>/refresh`. */
1551
1447
  async refresh(options) {
1552
1448
  await transport.request(`${basePath}/refresh`, {
1553
1449
  method: "POST",
@@ -1754,14 +1650,23 @@ var MemoryOfflineStore = class {
1754
1650
  };
1755
1651
  var IDB_NAME = "rebase-offline";
1756
1652
  /**
1757
- * v2 introduced the normalized row cache and string mutation ids. A v1
1758
- * database holds whole-response blobs under keys this version cannot read and
1759
- * queue entries ordered by a numeric `seq` this version no longer writes, so
1760
- * the upgrade drops both stores rather than trying to translate them. Offline
1761
- * support had not shipped in a release when v2 landed, so nothing in the wild
1762
- * loses a queued write to this.
1653
+ * The layout of the database, bumped whenever a store's contents change shape.
1654
+ *
1655
+ * - v2 introduced the normalized row cache and string mutation ids. A v1
1656
+ * database holds whole-response blobs under keys this version cannot read
1657
+ * and queue entries ordered by a numeric `seq` this version no longer
1658
+ * writes, so the upgrade drops both stores rather than trying to translate
1659
+ * them. Offline support had not shipped in a release when v2 landed, so
1660
+ * nothing in the wild loses a queued write to this.
1661
+ * - v3: cached rows are the server's wire rows. A v2 cache holds rows the
1662
+ * previous SDK wrote with the admin's value classes tagged in
1663
+ * (`{ __type: "GeoPoint" }`, `{ __type: "relation" }`, …), which nothing
1664
+ * revives any more — rendered, they would show the tags. Cached rows are a
1665
+ * copy of what the server serves, so the upgrade drops the cache and the
1666
+ * next read fetches them again. The queue is kept: its entries carry their
1667
+ * own layout (`QUEUE_SCHEMA_VERSION`) and older ones are converted when read.
1763
1668
  */
1764
- var IDB_VERSION = 2;
1669
+ var IDB_VERSION = 3;
1765
1670
  var CACHE_STORE = "cache";
1766
1671
  var QUEUE_STORE = "queue";
1767
1672
  /** The exclusive upper bound of an IDBKeyRange covering every key under `prefix`. */
@@ -1828,6 +1733,7 @@ var IndexedDBOfflineStore = class {
1828
1733
  if (db.objectStoreNames.contains(CACHE_STORE)) db.deleteObjectStore(CACHE_STORE);
1829
1734
  if (db.objectStoreNames.contains(QUEUE_STORE)) db.deleteObjectStore(QUEUE_STORE);
1830
1735
  }
1736
+ if (event.oldVersion === 2 && db.objectStoreNames.contains(CACHE_STORE)) db.deleteObjectStore(CACHE_STORE);
1831
1737
  if (!db.objectStoreNames.contains(CACHE_STORE)) db.createObjectStore(CACHE_STORE);
1832
1738
  if (!db.objectStoreNames.contains(QUEUE_STORE)) db.createObjectStore(QUEUE_STORE);
1833
1739
  };
@@ -1926,6 +1832,6 @@ var IndexedDBOfflineStore = class {
1926
1832
  }
1927
1833
  };
1928
1834
  //#endregion
1929
- export { byIdRead as a, invalidBulkBody as c, RebaseApiError$1 as d, buildQueryString as f, rebaseReviver as g, parseRebaseJson as h, isOfflineError as i, SDKQueryBuilder as l, defaultCodeForStatus as m, MemoryOfflineStore as n, createCollectionClient as o, createTransport as p, createMutationId as r, etagOf as s, IndexedDBOfflineStore as t, RebaseClientError$1 as u };
1835
+ export { byIdRead as a, invalidBulkBody as c, RebaseApiError$1 as d, buildQueryString as f, isOfflineError as i, SDKQueryBuilder as l, defaultCodeForStatus as m, MemoryOfflineStore as n, createTableClient as o, createTransport as p, createMutationId as r, etagOf as s, IndexedDBOfflineStore as t, RebaseClientError$1 as u };
1930
1836
 
1931
- //# sourceMappingURL=offline-store-B7F5mimt.js.map
1837
+ //# sourceMappingURL=offline-store-DtmBwmKE.js.map