lazypock 0.18.0 → 0.19.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/dist/index.js CHANGED
@@ -19,6 +19,7 @@ var ApiError = class extends Error {
19
19
  };
20
20
 
21
21
  // src/http.ts
22
+ var SUPERUSERS = "_superusers";
22
23
  function isAbortError(err) {
23
24
  return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
24
25
  }
@@ -45,6 +46,8 @@ var HttpClient = class {
45
46
  this.inflight = {};
46
47
  /** Global toggle for the auto-cancellation behaviour (default: on). */
47
48
  this.enableAutoCancellation = true;
49
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
50
+ this.refreshInFlight = null;
48
51
  this._baseUrl = baseUrl.replace(/\/+$/, "");
49
52
  this.authStore = authStore;
50
53
  this.connectionId = connectionId;
@@ -54,37 +57,84 @@ var HttpClient = class {
54
57
  get baseUrl() {
55
58
  return this._baseUrl;
56
59
  }
60
+ /**
61
+ * Exchange the stored refresh token for a new access token.
62
+ *
63
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
64
+ * bearer — not the access token this used to send, which is why every refresh
65
+ * attempt 401'd and cleared the session. The collection is the one the session
66
+ * belongs to, or `_superusers` when the store has none (a superuser login).
67
+ *
68
+ * A network failure keeps the session (the next request can retry); only a refusal
69
+ * by the server ends it.
70
+ */
57
71
  async refreshAuth() {
58
- const collection = this.authStore.collectionName;
59
- if (!collection) return null;
72
+ const refreshToken = this.authStore.refreshToken;
73
+ if (!refreshToken) return null;
74
+ if (this.refreshInFlight) {
75
+ const refreshed = await this.refreshInFlight;
76
+ return refreshed ? this.currentAuthResponse() : null;
77
+ }
78
+ this.refreshInFlight = this.performRefresh(refreshToken);
60
79
  try {
61
- const url = this.baseUrl + "/" + encodeURIComponent(collection) + "/auth-refresh";
62
- const headers = {
63
- "Content-Type": "application/json"
64
- };
65
- if (this.authStore.token) {
66
- headers["Authorization"] = "Bearer " + this.authStore.token;
67
- }
68
- const res = await this.defaultFetch(url, {
69
- method: "POST",
70
- headers
71
- });
80
+ const refreshed = await this.refreshInFlight;
81
+ return refreshed ? this.currentAuthResponse() : null;
82
+ } finally {
83
+ this.refreshInFlight = null;
84
+ }
85
+ }
86
+ /** The store's current session, in the shape the old refresh returned. */
87
+ currentAuthResponse() {
88
+ return {
89
+ token: this.authStore.token,
90
+ record: this.authStore.model ?? {}
91
+ };
92
+ }
93
+ async performRefresh(refreshToken) {
94
+ const collection = this.refreshCollection();
95
+ try {
96
+ const res = await this.defaultFetch(
97
+ this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
98
+ {
99
+ method: "POST",
100
+ headers: { "Content-Type": "application/json" },
101
+ body: JSON.stringify({ refreshToken })
102
+ }
103
+ );
72
104
  if (!res.ok) {
73
- this.authStore.clear();
74
- return null;
105
+ if (res.status === 400 || res.status === 401) {
106
+ this.authStore.clear();
107
+ }
108
+ return false;
75
109
  }
76
110
  const data = await res.json();
77
- if (data && typeof data.token === "string") {
78
- const record = data["record"];
79
- const model = record && typeof record === "object" ? record : null;
80
- this.authStore.set(data.token, model);
81
- return data;
111
+ if (!data || typeof data.token !== "string") {
112
+ this.authStore.clear();
113
+ return false;
82
114
  }
83
- return null;
115
+ const record = data["record"];
116
+ const model = record && typeof record === "object" ? record : null;
117
+ this.authStore.setCollectionName(
118
+ collection === SUPERUSERS ? null : collection
119
+ );
120
+ this.authStore.setSession(data.token, model, {
121
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
122
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
123
+ });
124
+ return true;
84
125
  } catch {
85
- return null;
126
+ return false;
86
127
  }
87
128
  }
129
+ /** The auth collection a refresh is addressed to, including superusers. */
130
+ refreshCollection() {
131
+ if (this.authStore.collectionName) return this.authStore.collectionName;
132
+ const model = this.authStore.model;
133
+ if (model && typeof model.collectionName === "string" && model.collectionName) {
134
+ return model.collectionName;
135
+ }
136
+ return SUPERUSERS;
137
+ }
88
138
  /**
89
139
  * Globally enable or disable auto-cancellation of duplicated pending requests.
90
140
  * Fluent — returns `this` for chaining.
@@ -130,7 +180,7 @@ var HttpClient = class {
130
180
  * (aborted requests throw an `ApiError` with `isAbort === true`).
131
181
  */
132
182
  async request(method, path, body, options) {
133
- if (this.authStore.isExpired && this.authStore.collectionName) {
183
+ if (this.authStore.isExpired && this.authStore.refreshToken) {
134
184
  await this.refreshAuth();
135
185
  }
136
186
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
@@ -221,8 +271,9 @@ var HttpClient = class {
221
271
  }
222
272
  let res = null;
223
273
  const fetcher = options?.fetch ?? this.defaultFetch;
274
+ const send = async () => fetcher(url, init);
224
275
  try {
225
- res = await fetcher(url, init);
276
+ res = await send();
226
277
  } catch (err) {
227
278
  if (isAbortError(err)) {
228
279
  throw new ApiError(
@@ -238,6 +289,27 @@ var HttpClient = class {
238
289
  delete this.cancelControllers[requestKey];
239
290
  }
240
291
  }
292
+ if (res.status === 401 && this.authStore.refreshToken) {
293
+ await res.text().catch(() => {
294
+ });
295
+ const refreshed = await this.refreshAuth();
296
+ if (refreshed) {
297
+ headers["Authorization"] = "Bearer " + this.authStore.token;
298
+ try {
299
+ res = await send();
300
+ } catch (err) {
301
+ if (isAbortError(err)) {
302
+ throw new ApiError(
303
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
304
+ {},
305
+ 0,
306
+ true
307
+ );
308
+ }
309
+ throw err;
310
+ }
311
+ }
312
+ }
241
313
  if (res.status === 204) return null;
242
314
  let bodyText = "";
243
315
  let data = {};
@@ -312,6 +384,7 @@ var AuthStore = class {
312
384
  this._token = "";
313
385
  this._model = null;
314
386
  this._tokenExpiresAt = null;
387
+ this._refreshToken = "";
315
388
  this._collectionName = null;
316
389
  this.listeners = /* @__PURE__ */ new Set();
317
390
  this.storage = storage ?? {
@@ -326,6 +399,15 @@ var AuthStore = class {
326
399
  get token() {
327
400
  return this._token;
328
401
  }
402
+ /**
403
+ * The refresh token for the current session, or empty string.
404
+ *
405
+ * Kept by the store so a session can outlive the access token (15 minutes on the
406
+ * server) even across a reload. Persisted under `auth_refresh_token`.
407
+ */
408
+ get refreshToken() {
409
+ return this._refreshToken;
410
+ }
329
411
  /** The current authenticated user record, or null. */
330
412
  get model() {
331
413
  return this._model;
@@ -360,14 +442,16 @@ var AuthStore = class {
360
442
  * Should be called once at application startup.
361
443
  */
362
444
  async init() {
363
- const [token, model, expiresAt, collectionName] = await Promise.all([
445
+ const [token, model, expiresAt, collectionName, refreshToken] = await Promise.all([
364
446
  this.storage.get("auth_token"),
365
447
  this.storage.get("auth_model"),
366
448
  this.storage.get("auth_expires_at"),
367
- this.storage.get("auth_collection")
449
+ this.storage.get("auth_collection"),
450
+ this.storage.get("auth_refresh_token")
368
451
  ]);
369
452
  if (token) this._token = token;
370
453
  if (expiresAt) this._tokenExpiresAt = parseInt(expiresAt, 10) || null;
454
+ if (refreshToken) this._refreshToken = refreshToken;
371
455
  if (model) {
372
456
  try {
373
457
  this._model = JSON.parse(model);
@@ -382,6 +466,10 @@ var AuthStore = class {
382
466
  }
383
467
  /**
384
468
  * Update the current auth token and model, persist to storage, and notify listeners.
469
+ *
470
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
471
+ * which carries the real `expiresIn` and the refresh token.
472
+ *
385
473
  * @param token The JWT token string.
386
474
  * @param model The authenticated user record, or null for superusers.
387
475
  */
@@ -401,18 +489,44 @@ var AuthStore = class {
401
489
  this.notify();
402
490
  }
403
491
  /**
404
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
492
+ * Record a complete auth response: token, model, refresh token and the access
493
+ * token's real lifetime.
494
+ *
495
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
496
+ * it (an older server) falls back to the historical 7-day assumption.
497
+ *
498
+ * @param token The JWT access token.
499
+ * @param model The authenticated record, or null for a superuser.
500
+ * @param options `refreshToken` and `expiresIn` from the same response.
501
+ */
502
+ setSession(token, model, options) {
503
+ this.set(token, model);
504
+ if (options?.refreshToken) {
505
+ this._refreshToken = options.refreshToken;
506
+ void this.storage.set("auth_refresh_token", options.refreshToken);
507
+ }
508
+ const expiresIn = options?.expiresIn;
509
+ if (typeof expiresIn === "number" && expiresIn > 0) {
510
+ this._tokenExpiresAt = Date.now() + expiresIn * 1e3;
511
+ void this.storage.set("auth_expires_at", String(this._tokenExpiresAt));
512
+ }
513
+ }
514
+ /**
515
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
516
+ * notify listeners.
405
517
  */
406
518
  clear() {
407
519
  this._token = "";
408
520
  this._model = null;
409
521
  this._tokenExpiresAt = null;
522
+ this._refreshToken = "";
410
523
  this._collectionName = null;
411
524
  void Promise.all([
412
525
  this.storage.remove("auth_token"),
413
526
  this.storage.remove("auth_expires_at"),
414
527
  this.storage.remove("auth_model"),
415
- this.storage.remove("auth_collection")
528
+ this.storage.remove("auth_collection"),
529
+ this.storage.remove("auth_refresh_token")
416
530
  ]);
417
531
  this.notify();
418
532
  }
@@ -434,6 +548,13 @@ var AuthStore = class {
434
548
  }
435
549
  }
436
550
  };
551
+ function rememberAuthResponse(store, data, model) {
552
+ if (!data || typeof data.token !== "string" || !data.token) return;
553
+ store.setSession(data.token, model, {
554
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
555
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
556
+ });
557
+ }
437
558
  var memoryStorage = {
438
559
  get(key) {
439
560
  try {
@@ -841,6 +962,19 @@ var CollectionService = class _CollectionService {
841
962
  encodeId(id) {
842
963
  return encodeURIComponent(id);
843
964
  }
965
+ /**
966
+ * The records endpoint for this collection.
967
+ *
968
+ * Centralised because the server's shape is `/api/collections/<name>/records`,
969
+ * and a path repeated eighteen times is a path that drifts.
970
+ */
971
+ recordsPath() {
972
+ return "/collections/" + this.encodeId(this.collectionName) + "/records";
973
+ }
974
+ /** The collection's own endpoint, which is where its auth routes live. */
975
+ collectionPath() {
976
+ return "/collections/" + this.encodeId(this.collectionName);
977
+ }
844
978
  // ── Field projection (`.select`) ──
845
979
  /**
846
980
  * Project list/read responses to the given fields (PocketBase `fields`
@@ -1248,7 +1382,7 @@ var CollectionService = class _CollectionService {
1248
1382
  }).map(([k, v]) => [k, String(v)])
1249
1383
  )
1250
1384
  ).toString();
1251
- const result = await this.http.get("/" + this.encodeId(this.collectionName) + "?" + qs, {
1385
+ const result = await this.http.get(this.recordsPath() + "?" + qs, {
1252
1386
  requestKey,
1253
1387
  autoCancel,
1254
1388
  cancelKey,
@@ -1333,7 +1467,7 @@ var CollectionService = class _CollectionService {
1333
1467
  }
1334
1468
  const qsStr = qs.toString();
1335
1469
  const record = await this.http.get(
1336
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1470
+ this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1337
1471
  options
1338
1472
  );
1339
1473
  if (record && expandInfo.narrow.size > 0) {
@@ -1349,7 +1483,7 @@ var CollectionService = class _CollectionService {
1349
1483
  */
1350
1484
  create(data, options) {
1351
1485
  return this.http.post(
1352
- "/" + this.encodeId(this.collectionName),
1486
+ this.recordsPath(),
1353
1487
  data,
1354
1488
  options
1355
1489
  );
@@ -1363,7 +1497,7 @@ var CollectionService = class _CollectionService {
1363
1497
  */
1364
1498
  update(id, data, options) {
1365
1499
  return this.http.patch(
1366
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1500
+ this.recordsPath() + "/" + this.encodeId(id),
1367
1501
  data,
1368
1502
  options
1369
1503
  );
@@ -1375,7 +1509,7 @@ var CollectionService = class _CollectionService {
1375
1509
  */
1376
1510
  delete(id, options) {
1377
1511
  return this.http.delete(
1378
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1512
+ this.recordsPath() + "/" + this.encodeId(id),
1379
1513
  options
1380
1514
  );
1381
1515
  }
@@ -1483,13 +1617,17 @@ var CollectionService = class _CollectionService {
1483
1617
  */
1484
1618
  async authWithPassword(identity, password, options) {
1485
1619
  const data = await this.http.post(
1486
- "/" + this.encodeId(this.collectionName) + "/auth-with-password",
1620
+ this.collectionPath() + "/auth-with-password",
1487
1621
  { identity, password },
1488
1622
  options
1489
1623
  );
1490
1624
  if (data && this.authStore) {
1491
1625
  this.authStore.setCollectionName(this.collectionName);
1492
- this.authStore.set(data.token, data.record);
1626
+ rememberAuthResponse(
1627
+ this.authStore,
1628
+ data,
1629
+ data.record
1630
+ );
1493
1631
  }
1494
1632
  return data;
1495
1633
  }
@@ -1499,13 +1637,17 @@ var CollectionService = class _CollectionService {
1499
1637
  */
1500
1638
  async authRefresh(options) {
1501
1639
  const data = await this.http.post(
1502
- "/" + this.encodeId(this.collectionName) + "/auth-refresh",
1503
- void 0,
1640
+ this.collectionPath() + "/auth-refresh",
1641
+ { refreshToken: this.authStore?.refreshToken },
1504
1642
  options
1505
1643
  );
1506
1644
  if (data && this.authStore) {
1507
1645
  this.authStore.setCollectionName(this.collectionName);
1508
- this.authStore.set(data.token, data.record);
1646
+ rememberAuthResponse(
1647
+ this.authStore,
1648
+ data,
1649
+ data.record
1650
+ );
1509
1651
  }
1510
1652
  return data;
1511
1653
  }
@@ -1516,7 +1658,7 @@ var CollectionService = class _CollectionService {
1516
1658
  */
1517
1659
  async listAuthMethods(options) {
1518
1660
  return this.http.get(
1519
- "/" + this.encodeId(this.collectionName) + "/auth-methods",
1661
+ this.collectionPath() + "/auth-methods",
1520
1662
  options
1521
1663
  );
1522
1664
  }
@@ -1535,7 +1677,7 @@ var CollectionService = class _CollectionService {
1535
1677
  */
1536
1678
  async requestPasswordReset(email, options) {
1537
1679
  await this.http.post(
1538
- "/" + this.encodeId(this.collectionName) + "/request-password-reset",
1680
+ this.collectionPath() + "/request-password-reset",
1539
1681
  { email },
1540
1682
  options
1541
1683
  );
@@ -1550,7 +1692,7 @@ var CollectionService = class _CollectionService {
1550
1692
  */
1551
1693
  async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1552
1694
  await this.http.post(
1553
- "/" + this.encodeId(this.collectionName) + "/confirm-password-reset",
1695
+ this.collectionPath() + "/confirm-password-reset",
1554
1696
  { token: passwordResetToken, password, passwordConfirm },
1555
1697
  options
1556
1698
  );
@@ -1563,7 +1705,7 @@ var CollectionService = class _CollectionService {
1563
1705
  */
1564
1706
  async requestVerification(email, options) {
1565
1707
  await this.http.post(
1566
- "/" + this.encodeId(this.collectionName) + "/request-verification",
1708
+ this.collectionPath() + "/request-verification",
1567
1709
  { email },
1568
1710
  options
1569
1711
  );
@@ -1575,7 +1717,7 @@ var CollectionService = class _CollectionService {
1575
1717
  */
1576
1718
  async confirmVerification(verificationToken, options) {
1577
1719
  const data = await this.http.post(
1578
- "/" + this.encodeId(this.collectionName) + "/confirm-verification",
1720
+ this.collectionPath() + "/confirm-verification",
1579
1721
  { token: verificationToken },
1580
1722
  options
1581
1723
  );
@@ -1587,7 +1729,7 @@ var CollectionService = class _CollectionService {
1587
1729
  */
1588
1730
  async requestEmailChange(newEmail, options) {
1589
1731
  await this.http.post(
1590
- "/" + this.encodeId(this.collectionName) + "/request-email-change",
1732
+ this.collectionPath() + "/request-email-change",
1591
1733
  { newEmail },
1592
1734
  options
1593
1735
  );
@@ -1600,7 +1742,7 @@ var CollectionService = class _CollectionService {
1600
1742
  */
1601
1743
  async confirmEmailChange(emailChangeToken, password, options) {
1602
1744
  const data = await this.http.post(
1603
- "/" + this.encodeId(this.collectionName) + "/confirm-email-change",
1745
+ this.collectionPath() + "/confirm-email-change",
1604
1746
  { token: emailChangeToken, password },
1605
1747
  options
1606
1748
  );
@@ -1668,7 +1810,7 @@ var CollectionService = class _CollectionService {
1668
1810
  async authWithOAuth2Code(options) {
1669
1811
  const { provider, code, codeVerifier, redirectUrl, createData } = options;
1670
1812
  const data = await this.http.post(
1671
- "/" + this.encodeId(this.collectionName) + "/auth-with-oauth2",
1813
+ this.collectionPath() + "/auth-with-oauth2",
1672
1814
  {
1673
1815
  provider,
1674
1816
  code,
@@ -1688,266 +1830,256 @@ var CollectionService = class _CollectionService {
1688
1830
  }
1689
1831
  if (this.authStore) {
1690
1832
  this.authStore.setCollectionName(this.collectionName);
1691
- this.authStore.set(data.token, data.record);
1833
+ rememberAuthResponse(
1834
+ this.authStore,
1835
+ data,
1836
+ data.record
1837
+ );
1692
1838
  }
1693
1839
  return data;
1694
1840
  }
1695
1841
  };
1696
1842
 
1697
1843
  // src/realtime.ts
1698
- function wsUrlFromBaseUrl(baseUrl) {
1699
- try {
1700
- const url = new URL(baseUrl);
1701
- const protocol = url.protocol === "https:" ? "wss:" : "ws:";
1702
- return `${protocol}//${url.host}/socket/websocket`;
1703
- } catch {
1704
- return `${baseUrl.replace(/^http/, "ws").replace(/\/api$/, "")}/socket/websocket`;
1705
- }
1844
+ function sseUrlFromBaseUrl(baseUrl) {
1845
+ return `${baseUrl.replace(/\/+$/, "")}/realtime`;
1846
+ }
1847
+ function serverTopic(topic) {
1848
+ if (topic === "collections") return "collections";
1849
+ if (!topic.startsWith("collection:")) return null;
1850
+ const rest = topic.slice("collection:".length);
1851
+ const [name, recordId] = rest.split(":");
1852
+ if (!name) return null;
1853
+ return recordId ? `${name}/${recordId}` : name;
1706
1854
  }
1707
1855
  var RealtimeService = class {
1708
1856
  constructor() {
1709
- this.ws = null;
1710
- this.refCounter = 0;
1857
+ this.controller = null;
1858
+ this.open = false;
1859
+ this.closed = false;
1711
1860
  this.subscriptions = /* @__PURE__ */ new Map();
1712
1861
  this.reconnectTimer = null;
1862
+ this.resubscribeTimer = null;
1713
1863
  this.reconnectAttempt = 0;
1714
1864
  this.maxReconnectDelay = 5e3;
1715
1865
  this.url = "";
1716
1866
  this.tokenProvider = null;
1717
- // ── Heartbeat ──
1718
- this.heartbeatInterval = null;
1719
1867
  }
1720
- /** Whether the WebSocket is currently open. */
1868
+ /** Whether the stream is currently open. */
1721
1869
  get isOpen() {
1722
- return this.ws?.readyState === WebSocket.OPEN;
1870
+ return this.open;
1723
1871
  }
1724
- /**
1725
- * The most recently used WebSocket URL (set on {@link connect}).
1726
- * Useful for SDK convenience methods that auto-connect before subscribing.
1727
- */
1872
+ /** The most recently used SSE URL (set on {@link connect}/{@link setUrl}). */
1728
1873
  get lastUrl() {
1729
1874
  return this.url;
1730
1875
  }
1731
- /** The auth token configured for this connection (set on connect). */
1876
+ /** The auth token configured for this connection. */
1732
1877
  get lastToken() {
1733
1878
  return this.token;
1734
1879
  }
1735
- /**
1736
- * Set the per-client connection id (browser tab / device). The SDK
1737
- * appends it as the `connectionId` socket query param at connect time
1738
- * (unless the URL already carries one), matching the `X-Connection-Id`
1739
- * header the HTTP client sends — together they let the server exclude
1740
- * the originating connection from its own realtime broadcasts.
1741
- */
1880
+ /** Set the per-client connection id (browser tab / device). */
1742
1881
  setConnectionId(id) {
1743
1882
  this.connectionId = id;
1744
1883
  }
1745
- /**
1746
- * Set the socket URL. Useful before subscribing so the SDK can
1747
- * auto-connect on the first {@link subscribe}.
1748
- */
1884
+ /** Set the stream URL. Useful before subscribing so the SDK auto-connects. */
1749
1885
  setUrl(url) {
1750
1886
  this.url = url;
1751
1887
  }
1752
- /**
1753
- * Register a token provider consulted at every (re)connect.
1754
- * When set, it takes precedence over the token passed to {@link connect}.
1755
- */
1888
+ /** Register a token provider consulted at every (re)connect. */
1756
1889
  setTokenProvider(provider) {
1757
1890
  this.tokenProvider = provider;
1758
1891
  }
1759
1892
  /**
1760
- * Reconnect the socket immediately with the current token.
1761
- * Called by the SDK when auth changes (login/logout/token refresh) so
1762
- * private-channel joins are authorized with the new credentials. No-op
1763
- * when the socket has never been opened and nothing is subscribed.
1893
+ * Reconnect immediately with the current token, so auth changes
1894
+ * (login/logout/refresh) re-authorize private subscriptions.
1764
1895
  */
1765
1896
  refresh() {
1766
- if (typeof WebSocket === "undefined") return;
1767
- if (!this.ws && this.subscriptions.size === 0) return;
1768
- this.clearReconnectTimer();
1769
- const ws = this.ws;
1770
- this.ws = null;
1771
- if (ws) {
1772
- ws.onclose = null;
1773
- ws.close();
1774
- }
1897
+ if (this.closed) return;
1898
+ if (!this.open && this.subscriptions.size === 0) return;
1775
1899
  this.reconnectAttempt = 0;
1776
1900
  this.doConnect();
1777
1901
  }
1778
- /*
1779
- * Ensure the socket is connected, then subscribe.
1780
- * Used by collection-level convenience wrappers so a connection is opened
1781
- * automatically on the first subscribe (matching PocketBase behaviour —
1782
- * works for anonymous/public collections too).
1783
- */
1902
+ /** Ensure a connection is open, then subscribe. */
1784
1903
  ensureConnected() {
1785
- if (this.isOpen || !this.url) return;
1786
- if (typeof WebSocket === "undefined") return;
1904
+ if (this.open || this.controller || !this.url) return;
1905
+ if (this.serverTopics().length === 0) return;
1787
1906
  this.doConnect();
1788
1907
  }
1789
1908
  connect(opts) {
1790
1909
  this.url = opts.url;
1791
1910
  this.token = opts.token;
1911
+ this.closed = false;
1792
1912
  this.reconnectAttempt = 0;
1793
1913
  this.doConnect();
1794
1914
  }
1795
1915
  disconnect() {
1916
+ this.closed = true;
1796
1917
  this.clearReconnectTimer();
1797
- this.ws?.close();
1798
- this.ws = null;
1918
+ this.closeStream();
1799
1919
  }
1800
1920
  /**
1801
- * Subscribe to a topic (e.g. "collection:posts" or "custom:chat-room").
1802
- * The backend Channel authorizes via listRule on join.
1803
- *
1804
- * @param joinPayload Optional payload forwarded with the channel join
1805
- * (available to the server's join callback / hooks, e.g. `expand`).
1921
+ * Subscribe to a topic (`collection:posts`, `collection:posts:ID`, or the
1922
+ * registry topic `collections`).
1806
1923
  */
1807
1924
  subscribe(topic, callback, joinPayload) {
1808
1925
  const subs = this.subscriptions.get(topic) || [];
1809
1926
  subs.push({ topic, callback, joinPayload });
1810
1927
  this.subscriptions.set(topic, subs);
1811
- if (this.ws?.readyState === WebSocket.OPEN) {
1812
- this.joinTopic(topic, joinPayload);
1813
- }
1928
+ this.resubscribe();
1814
1929
  }
1815
- /**
1816
- * Remove all subscriptions for topics under `prefix` (the topic itself or
1817
- * any topic starting with `prefix + ":"`). Used by collection-level
1818
- * `unsubscribe()` to drop every subscription of a collection.
1819
- */
1930
+ /** Remove every subscription under `prefix` (the topic or `prefix:...`). */
1820
1931
  unsubscribeByPrefix(prefix) {
1932
+ let changed = false;
1821
1933
  for (const topic of [...this.subscriptions.keys()]) {
1822
1934
  if (topic === prefix || topic.startsWith(prefix + ":")) {
1823
1935
  this.subscriptions.delete(topic);
1936
+ changed = true;
1824
1937
  }
1825
1938
  }
1939
+ if (changed) this.resubscribe();
1826
1940
  }
1827
- /**
1828
- * Unsubscribe a specific callback from a topic.
1829
- */
1941
+ /** Remove a specific callback from a topic, or the whole topic. */
1830
1942
  unsubscribe(topic, callback) {
1831
1943
  if (!callback) {
1832
- this.subscriptions.delete(topic);
1944
+ if (this.subscriptions.delete(topic)) this.resubscribe();
1833
1945
  return;
1834
1946
  }
1835
1947
  const subs = this.subscriptions.get(topic)?.filter((s) => s.callback !== callback);
1836
1948
  if (subs && subs.length > 0) {
1837
1949
  this.subscriptions.set(topic, subs);
1838
- } else {
1839
- this.subscriptions.delete(topic);
1950
+ return;
1840
1951
  }
1952
+ this.subscriptions.delete(topic);
1953
+ this.resubscribe();
1841
1954
  }
1842
- resubscribeAll() {
1843
- const seen = /* @__PURE__ */ new Set();
1844
- for (const entries of this.subscriptions.values()) {
1845
- for (const entry of entries) {
1846
- if (seen.has(entry.topic)) continue;
1847
- seen.add(entry.topic);
1848
- if (this.ws?.readyState === WebSocket.OPEN) {
1849
- this.joinTopic(entry.topic, entry.joinPayload);
1850
- }
1851
- }
1955
+ // ── Internals ────────────────────────────────────
1956
+ /** The distinct server topics the current subscriptions need. */
1957
+ serverTopics() {
1958
+ const topics = /* @__PURE__ */ new Set();
1959
+ for (const topic of this.subscriptions.keys()) {
1960
+ const server = serverTopic(topic);
1961
+ if (server) topics.add(server);
1852
1962
  }
1963
+ return [...topics];
1964
+ }
1965
+ /**
1966
+ * The subscription set is part of the connection URL, so a change needs a new
1967
+ * connection. Coalesced, because mounting a page subscribes to several
1968
+ * collections in one tick.
1969
+ */
1970
+ resubscribe() {
1971
+ if (this.resubscribeTimer) clearTimeout(this.resubscribeTimer);
1972
+ this.resubscribeTimer = setTimeout(() => {
1973
+ this.resubscribeTimer = null;
1974
+ if (this.controller) {
1975
+ this.doConnect();
1976
+ } else {
1977
+ this.ensureConnected();
1978
+ }
1979
+ }, 0);
1853
1980
  }
1854
1981
  doConnect() {
1855
- if (typeof WebSocket === "undefined") {
1856
- console.warn(
1857
- "[lazypock] WebSocket not available \u2014 realtime subscriptions disabled"
1858
- );
1859
- return;
1860
- }
1861
- let url = this.url;
1982
+ if (this.closed) return;
1983
+ const topics = this.serverTopics();
1984
+ if (topics.length === 0 || !this.url) return;
1985
+ this.closeStream();
1986
+ const params = new URLSearchParams();
1987
+ params.set("subscribe", topics.join(","));
1988
+ const url = this.url + (this.url.includes("?") ? "&" : "?") + params.toString();
1862
1989
  const token = this.tokenProvider ? this.tokenProvider() : this.token;
1863
- if (token) {
1864
- url += (url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(token);
1865
- }
1866
- if (this.connectionId && !url.includes("connectionId=")) {
1867
- url += (url.includes("?") ? "&" : "?") + "connectionId=" + encodeURIComponent(this.connectionId);
1868
- }
1869
- this.ws = new WebSocket(url);
1870
- this.ws.onopen = () => {
1990
+ const headers = { Accept: "text/event-stream" };
1991
+ if (token) headers.Authorization = `Bearer ${token}`;
1992
+ if (this.connectionId) headers["X-Connection-Id"] = this.connectionId;
1993
+ const controller = new AbortController();
1994
+ this.controller = controller;
1995
+ void this.read(url, headers, controller);
1996
+ }
1997
+ async read(url, headers, controller) {
1998
+ try {
1999
+ const response = await fetch(url, { headers, signal: controller.signal });
2000
+ if (!response.ok || !response.body) {
2001
+ throw new Error(`realtime connection failed (${response.status})`);
2002
+ }
2003
+ this.open = true;
1871
2004
  this.reconnectAttempt = 0;
1872
- this.resubscribeAll();
1873
- this.startHeartbeat();
1874
- };
1875
- this.ws.onmessage = (msg) => {
1876
- this.handleMessage(msg.data);
1877
- };
1878
- this.ws.onclose = () => {
1879
- this.stopHeartbeat();
1880
- this.onDisconnect?.();
1881
- this.scheduleReconnect();
1882
- };
1883
- this.ws.onerror = (err) => {
2005
+ this.onReconnect?.();
2006
+ const reader = response.body.getReader();
2007
+ const decoder = new TextDecoder();
2008
+ let buffer = "";
2009
+ for (; ; ) {
2010
+ const { done, value } = await reader.read();
2011
+ if (done) break;
2012
+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(
2013
+ /\r\n/g,
2014
+ "\n"
2015
+ );
2016
+ let index;
2017
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
2018
+ this.handleFrame(buffer.slice(0, index));
2019
+ buffer = buffer.slice(index + 2);
2020
+ }
2021
+ }
2022
+ throw new Error("realtime stream ended");
2023
+ } catch (err) {
2024
+ if (controller.signal.aborted) return;
1884
2025
  this.onError?.(err);
1885
- };
2026
+ } finally {
2027
+ if (this.controller === controller) {
2028
+ this.open = false;
2029
+ this.controller = null;
2030
+ this.onDisconnect?.();
2031
+ this.scheduleReconnect();
2032
+ }
2033
+ }
1886
2034
  }
1887
- handleMessage(data) {
1888
- let parsed;
2035
+ handleFrame(frame) {
2036
+ const dataLines = [];
2037
+ for (const line of frame.split("\n")) {
2038
+ if (line.startsWith("data:")) {
2039
+ dataLines.push(line.slice(5).replace(/^ /, ""));
2040
+ }
2041
+ }
2042
+ if (dataLines.length === 0) return;
2043
+ let data;
1889
2044
  try {
1890
- parsed = JSON.parse(data);
2045
+ data = JSON.parse(dataLines.join("\n"));
1891
2046
  } catch {
1892
2047
  return;
1893
2048
  }
1894
- if (typeof parsed !== "object" || !parsed.topic || !parsed.event) return;
1895
- const topic = parsed.topic;
1896
- const event = parsed.event;
1897
- const payload = parsed.payload || {};
1898
- if (event === "phx_reply") return;
1899
- const subs = this.subscriptions.get(topic);
1900
- if (subs) {
1901
- const e = {
1902
- event,
1903
- topic,
1904
- payload
1905
- };
1906
- for (const s of subs) {
1907
- try {
1908
- s.callback(e);
1909
- } catch {
1910
- }
1911
- }
2049
+ this.dispatch(data);
2050
+ }
2051
+ dispatch(data) {
2052
+ const action = typeof data.action === "string" ? data.action : "update";
2053
+ if (data.collection === "collections") {
2054
+ this.emit("collections", action, data.record ?? {});
2055
+ return;
2056
+ }
2057
+ if (!data.collection) return;
2058
+ const payload = { record: data.record ?? {}, action };
2059
+ this.emit(`collection:${data.collection}`, action, payload);
2060
+ if (data.id) {
2061
+ this.emit(`collection:${data.collection}:${data.id}`, action, payload);
1912
2062
  }
1913
2063
  }
1914
- joinTopic(topic, joinPayload) {
1915
- const ref = this.nextRef();
1916
- const msg = JSON.stringify({
1917
- topic,
1918
- event: "phx_join",
1919
- payload: joinPayload ?? {},
1920
- ref
1921
- });
1922
- this.ws?.send(msg);
1923
- }
1924
- nextRef() {
1925
- this.refCounter++;
1926
- return this.refCounter.toString();
1927
- }
1928
- startHeartbeat() {
1929
- this.stopHeartbeat();
1930
- this.heartbeatInterval = setInterval(() => {
1931
- if (this.ws?.readyState === WebSocket.OPEN) {
1932
- const ref = this.nextRef();
1933
- const msg = JSON.stringify({
1934
- topic: "phoenix",
1935
- event: "heartbeat",
1936
- payload: {},
1937
- ref
1938
- });
1939
- this.ws.send(msg);
2064
+ emit(topic, event, payload) {
2065
+ const subs = this.subscriptions.get(topic);
2066
+ if (!subs) return;
2067
+ const e = { event, topic, payload };
2068
+ for (const s of subs) {
2069
+ try {
2070
+ s.callback(e);
2071
+ } catch {
1940
2072
  }
1941
- }, 3e4);
1942
- }
1943
- stopHeartbeat() {
1944
- if (this.heartbeatInterval) {
1945
- clearInterval(this.heartbeatInterval);
1946
- this.heartbeatInterval = null;
1947
2073
  }
1948
2074
  }
1949
- // ── Reconnect ──
2075
+ closeStream() {
2076
+ const controller = this.controller;
2077
+ this.controller = null;
2078
+ this.open = false;
2079
+ controller?.abort();
2080
+ }
1950
2081
  scheduleReconnect() {
2082
+ if (this.closed) return;
1951
2083
  this.clearReconnectTimer();
1952
2084
  const delay = Math.min(
1953
2085
  1e3 * 2 ** this.reconnectAttempt,
@@ -1956,7 +2088,6 @@ var RealtimeService = class {
1956
2088
  this.reconnectAttempt++;
1957
2089
  this.reconnectTimer = setTimeout(() => {
1958
2090
  this.reconnectTimer = null;
1959
- this.onReconnect?.();
1960
2091
  this.doConnect();
1961
2092
  }, delay);
1962
2093
  }
@@ -1969,14 +2100,18 @@ var RealtimeService = class {
1969
2100
  };
1970
2101
 
1971
2102
  // src/files.ts
1972
- function getFileUrl(baseUrl, fileId) {
1973
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId);
2103
+ function encodeKey(key) {
2104
+ return key.split("/").map(encodeURIComponent).join("/");
2105
+ }
2106
+ function getFileUrl(baseUrl, key) {
2107
+ return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
1974
2108
  }
1975
- function getThumbUrl(baseUrl, fileId, size) {
1976
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/thumbs/" + encodeURIComponent(size);
2109
+ function getThumbUrl(baseUrl, key, size) {
2110
+ return getFileUrl(baseUrl, key) + "?thumb=" + encodeURIComponent(size);
1977
2111
  }
1978
- function getScaleUrl(baseUrl, fileId, size) {
1979
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/scale/" + encodeURIComponent(size);
2112
+ function getScaleUrl(baseUrl, key, size) {
2113
+ const parameter = size.includes("x") ? "thumb" : "preset";
2114
+ return getFileUrl(baseUrl, key) + "?" + parameter + "=" + encodeURIComponent(size);
1980
2115
  }
1981
2116
  function getVariantUrl(baseUrl, fileId, preset) {
1982
2117
  return getScaleUrl(baseUrl, fileId, preset);
@@ -2307,7 +2442,7 @@ var LazypockClient = class {
2307
2442
  this.http = new HttpClient(baseUrl, this.authStore, connectionId);
2308
2443
  this.realtime = options.realtime ?? new RealtimeService();
2309
2444
  if (!options.realtime) {
2310
- this.realtime.setUrl(wsUrlFromBaseUrl(baseUrl));
2445
+ this.realtime.setUrl(sseUrlFromBaseUrl(baseUrl));
2311
2446
  }
2312
2447
  this.realtime.setConnectionId(connectionId);
2313
2448
  this.realtime.setTokenProvider(() => this.authStore.token);
@@ -2420,7 +2555,7 @@ var LazypockClient = class {
2420
2555
  const data = await this.http.post("/superusers/setup", { email, password });
2421
2556
  if (data) {
2422
2557
  this.authStore.setCollectionName(null);
2423
- this.authStore.set(data.token, null);
2558
+ rememberAuthResponse(this.authStore, data, null);
2424
2559
  }
2425
2560
  return data;
2426
2561
  }
@@ -2438,17 +2573,21 @@ var LazypockClient = class {
2438
2573
  async login(email, password, collection) {
2439
2574
  let data;
2440
2575
  if (collection) {
2441
- data = await this.http.post("/" + encodeURIComponent(collection) + "/auth-with-password", {
2576
+ data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
2442
2577
  identity: email,
2443
2578
  password
2444
2579
  });
2445
2580
  if (data && data.record) {
2446
2581
  this.authStore.setCollectionName(collection);
2447
- this.authStore.set(data.token, data.record);
2582
+ rememberAuthResponse(
2583
+ this.authStore,
2584
+ data,
2585
+ data.record
2586
+ );
2448
2587
  }
2449
2588
  } else {
2450
2589
  try {
2451
- data = await this.http.post("/_superusers/auth-with-password", {
2590
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
2452
2591
  identity: email,
2453
2592
  password
2454
2593
  });
@@ -2460,7 +2599,7 @@ var LazypockClient = class {
2460
2599
  }
2461
2600
  if (data) {
2462
2601
  this.authStore.setCollectionName(null);
2463
- this.authStore.set(data.token, null);
2602
+ rememberAuthResponse(this.authStore, data, null);
2464
2603
  }
2465
2604
  }
2466
2605
  return data;
@@ -2488,13 +2627,13 @@ var LazypockClient = class {
2488
2627
  */
2489
2628
  async authWithPassword(collection, identity, password, options) {
2490
2629
  const data = await this.http.post(
2491
- "/" + encodeURIComponent(collection) + "/auth-with-password",
2630
+ "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
2492
2631
  { identity, password },
2493
2632
  options
2494
2633
  );
2495
2634
  if (data) {
2496
2635
  this.authStore.setCollectionName(collection);
2497
- this.authStore.set(data.token, data.record);
2636
+ rememberAuthResponse(this.authStore, data, data.record);
2498
2637
  }
2499
2638
  return data;
2500
2639
  }
@@ -2507,13 +2646,13 @@ var LazypockClient = class {
2507
2646
  */
2508
2647
  async authRefresh(collection, options) {
2509
2648
  const data = await this.http.post(
2510
- "/" + encodeURIComponent(collection) + "/auth-refresh",
2511
- void 0,
2649
+ "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2650
+ { refreshToken: this.authStore.refreshToken },
2512
2651
  options
2513
2652
  );
2514
2653
  if (data) {
2515
2654
  this.authStore.setCollectionName(collection);
2516
- this.authStore.set(data.token, data.record);
2655
+ rememberAuthResponse(this.authStore, data, data.record);
2517
2656
  }
2518
2657
  return data;
2519
2658
  }
@@ -2559,6 +2698,6 @@ export {
2559
2698
  getThumbUrl,
2560
2699
  getVariantUrl,
2561
2700
  schemaFieldType,
2562
- wsUrlFromBaseUrl
2701
+ sseUrlFromBaseUrl
2563
2702
  };
2564
2703
  //# sourceMappingURL=index.js.map