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.
@@ -42,7 +42,7 @@ var Lazypock = (() => {
42
42
  getThumbUrl: () => getThumbUrl,
43
43
  getVariantUrl: () => getVariantUrl,
44
44
  schemaFieldType: () => schemaFieldType,
45
- wsUrlFromBaseUrl: () => wsUrlFromBaseUrl
45
+ sseUrlFromBaseUrl: () => sseUrlFromBaseUrl
46
46
  });
47
47
 
48
48
  // src/types.ts
@@ -58,6 +58,7 @@ var Lazypock = (() => {
58
58
  };
59
59
 
60
60
  // src/http.ts
61
+ var SUPERUSERS = "_superusers";
61
62
  function isAbortError(err) {
62
63
  return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
63
64
  }
@@ -84,6 +85,8 @@ var Lazypock = (() => {
84
85
  this.inflight = {};
85
86
  /** Global toggle for the auto-cancellation behaviour (default: on). */
86
87
  this.enableAutoCancellation = true;
88
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
89
+ this.refreshInFlight = null;
87
90
  this._baseUrl = baseUrl.replace(/\/+$/, "");
88
91
  this.authStore = authStore;
89
92
  this.connectionId = connectionId;
@@ -93,37 +96,84 @@ var Lazypock = (() => {
93
96
  get baseUrl() {
94
97
  return this._baseUrl;
95
98
  }
99
+ /**
100
+ * Exchange the stored refresh token for a new access token.
101
+ *
102
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
103
+ * bearer — not the access token this used to send, which is why every refresh
104
+ * attempt 401'd and cleared the session. The collection is the one the session
105
+ * belongs to, or `_superusers` when the store has none (a superuser login).
106
+ *
107
+ * A network failure keeps the session (the next request can retry); only a refusal
108
+ * by the server ends it.
109
+ */
96
110
  async refreshAuth() {
97
- const collection = this.authStore.collectionName;
98
- if (!collection) return null;
111
+ const refreshToken = this.authStore.refreshToken;
112
+ if (!refreshToken) return null;
113
+ if (this.refreshInFlight) {
114
+ const refreshed = await this.refreshInFlight;
115
+ return refreshed ? this.currentAuthResponse() : null;
116
+ }
117
+ this.refreshInFlight = this.performRefresh(refreshToken);
99
118
  try {
100
- const url = this.baseUrl + "/" + encodeURIComponent(collection) + "/auth-refresh";
101
- const headers = {
102
- "Content-Type": "application/json"
103
- };
104
- if (this.authStore.token) {
105
- headers["Authorization"] = "Bearer " + this.authStore.token;
106
- }
107
- const res = await this.defaultFetch(url, {
108
- method: "POST",
109
- headers
110
- });
119
+ const refreshed = await this.refreshInFlight;
120
+ return refreshed ? this.currentAuthResponse() : null;
121
+ } finally {
122
+ this.refreshInFlight = null;
123
+ }
124
+ }
125
+ /** The store's current session, in the shape the old refresh returned. */
126
+ currentAuthResponse() {
127
+ return {
128
+ token: this.authStore.token,
129
+ record: this.authStore.model ?? {}
130
+ };
131
+ }
132
+ async performRefresh(refreshToken) {
133
+ const collection = this.refreshCollection();
134
+ try {
135
+ const res = await this.defaultFetch(
136
+ this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
137
+ {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify({ refreshToken })
141
+ }
142
+ );
111
143
  if (!res.ok) {
112
- this.authStore.clear();
113
- return null;
144
+ if (res.status === 400 || res.status === 401) {
145
+ this.authStore.clear();
146
+ }
147
+ return false;
114
148
  }
115
149
  const data = await res.json();
116
- if (data && typeof data.token === "string") {
117
- const record = data["record"];
118
- const model = record && typeof record === "object" ? record : null;
119
- this.authStore.set(data.token, model);
120
- return data;
150
+ if (!data || typeof data.token !== "string") {
151
+ this.authStore.clear();
152
+ return false;
121
153
  }
122
- return null;
154
+ const record = data["record"];
155
+ const model = record && typeof record === "object" ? record : null;
156
+ this.authStore.setCollectionName(
157
+ collection === SUPERUSERS ? null : collection
158
+ );
159
+ this.authStore.setSession(data.token, model, {
160
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
161
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
162
+ });
163
+ return true;
123
164
  } catch {
124
- return null;
165
+ return false;
125
166
  }
126
167
  }
168
+ /** The auth collection a refresh is addressed to, including superusers. */
169
+ refreshCollection() {
170
+ if (this.authStore.collectionName) return this.authStore.collectionName;
171
+ const model = this.authStore.model;
172
+ if (model && typeof model.collectionName === "string" && model.collectionName) {
173
+ return model.collectionName;
174
+ }
175
+ return SUPERUSERS;
176
+ }
127
177
  /**
128
178
  * Globally enable or disable auto-cancellation of duplicated pending requests.
129
179
  * Fluent — returns `this` for chaining.
@@ -169,7 +219,7 @@ var Lazypock = (() => {
169
219
  * (aborted requests throw an `ApiError` with `isAbort === true`).
170
220
  */
171
221
  async request(method, path, body, options) {
172
- if (this.authStore.isExpired && this.authStore.collectionName) {
222
+ if (this.authStore.isExpired && this.authStore.refreshToken) {
173
223
  await this.refreshAuth();
174
224
  }
175
225
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
@@ -260,8 +310,9 @@ var Lazypock = (() => {
260
310
  }
261
311
  let res = null;
262
312
  const fetcher = options?.fetch ?? this.defaultFetch;
313
+ const send = async () => fetcher(url, init);
263
314
  try {
264
- res = await fetcher(url, init);
315
+ res = await send();
265
316
  } catch (err) {
266
317
  if (isAbortError(err)) {
267
318
  throw new ApiError(
@@ -277,6 +328,27 @@ var Lazypock = (() => {
277
328
  delete this.cancelControllers[requestKey];
278
329
  }
279
330
  }
331
+ if (res.status === 401 && this.authStore.refreshToken) {
332
+ await res.text().catch(() => {
333
+ });
334
+ const refreshed = await this.refreshAuth();
335
+ if (refreshed) {
336
+ headers["Authorization"] = "Bearer " + this.authStore.token;
337
+ try {
338
+ res = await send();
339
+ } catch (err) {
340
+ if (isAbortError(err)) {
341
+ throw new ApiError(
342
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
343
+ {},
344
+ 0,
345
+ true
346
+ );
347
+ }
348
+ throw err;
349
+ }
350
+ }
351
+ }
280
352
  if (res.status === 204) return null;
281
353
  let bodyText = "";
282
354
  let data = {};
@@ -351,6 +423,7 @@ var Lazypock = (() => {
351
423
  this._token = "";
352
424
  this._model = null;
353
425
  this._tokenExpiresAt = null;
426
+ this._refreshToken = "";
354
427
  this._collectionName = null;
355
428
  this.listeners = /* @__PURE__ */ new Set();
356
429
  this.storage = storage ?? {
@@ -365,6 +438,15 @@ var Lazypock = (() => {
365
438
  get token() {
366
439
  return this._token;
367
440
  }
441
+ /**
442
+ * The refresh token for the current session, or empty string.
443
+ *
444
+ * Kept by the store so a session can outlive the access token (15 minutes on the
445
+ * server) even across a reload. Persisted under `auth_refresh_token`.
446
+ */
447
+ get refreshToken() {
448
+ return this._refreshToken;
449
+ }
368
450
  /** The current authenticated user record, or null. */
369
451
  get model() {
370
452
  return this._model;
@@ -399,14 +481,16 @@ var Lazypock = (() => {
399
481
  * Should be called once at application startup.
400
482
  */
401
483
  async init() {
402
- const [token, model, expiresAt, collectionName] = await Promise.all([
484
+ const [token, model, expiresAt, collectionName, refreshToken] = await Promise.all([
403
485
  this.storage.get("auth_token"),
404
486
  this.storage.get("auth_model"),
405
487
  this.storage.get("auth_expires_at"),
406
- this.storage.get("auth_collection")
488
+ this.storage.get("auth_collection"),
489
+ this.storage.get("auth_refresh_token")
407
490
  ]);
408
491
  if (token) this._token = token;
409
492
  if (expiresAt) this._tokenExpiresAt = parseInt(expiresAt, 10) || null;
493
+ if (refreshToken) this._refreshToken = refreshToken;
410
494
  if (model) {
411
495
  try {
412
496
  this._model = JSON.parse(model);
@@ -421,6 +505,10 @@ var Lazypock = (() => {
421
505
  }
422
506
  /**
423
507
  * Update the current auth token and model, persist to storage, and notify listeners.
508
+ *
509
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
510
+ * which carries the real `expiresIn` and the refresh token.
511
+ *
424
512
  * @param token The JWT token string.
425
513
  * @param model The authenticated user record, or null for superusers.
426
514
  */
@@ -440,18 +528,44 @@ var Lazypock = (() => {
440
528
  this.notify();
441
529
  }
442
530
  /**
443
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
531
+ * Record a complete auth response: token, model, refresh token and the access
532
+ * token's real lifetime.
533
+ *
534
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
535
+ * it (an older server) falls back to the historical 7-day assumption.
536
+ *
537
+ * @param token The JWT access token.
538
+ * @param model The authenticated record, or null for a superuser.
539
+ * @param options `refreshToken` and `expiresIn` from the same response.
540
+ */
541
+ setSession(token, model, options) {
542
+ this.set(token, model);
543
+ if (options?.refreshToken) {
544
+ this._refreshToken = options.refreshToken;
545
+ void this.storage.set("auth_refresh_token", options.refreshToken);
546
+ }
547
+ const expiresIn = options?.expiresIn;
548
+ if (typeof expiresIn === "number" && expiresIn > 0) {
549
+ this._tokenExpiresAt = Date.now() + expiresIn * 1e3;
550
+ void this.storage.set("auth_expires_at", String(this._tokenExpiresAt));
551
+ }
552
+ }
553
+ /**
554
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
555
+ * notify listeners.
444
556
  */
445
557
  clear() {
446
558
  this._token = "";
447
559
  this._model = null;
448
560
  this._tokenExpiresAt = null;
561
+ this._refreshToken = "";
449
562
  this._collectionName = null;
450
563
  void Promise.all([
451
564
  this.storage.remove("auth_token"),
452
565
  this.storage.remove("auth_expires_at"),
453
566
  this.storage.remove("auth_model"),
454
- this.storage.remove("auth_collection")
567
+ this.storage.remove("auth_collection"),
568
+ this.storage.remove("auth_refresh_token")
455
569
  ]);
456
570
  this.notify();
457
571
  }
@@ -473,6 +587,13 @@ var Lazypock = (() => {
473
587
  }
474
588
  }
475
589
  };
590
+ function rememberAuthResponse(store, data, model) {
591
+ if (!data || typeof data.token !== "string" || !data.token) return;
592
+ store.setSession(data.token, model, {
593
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
594
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
595
+ });
596
+ }
476
597
  var memoryStorage = {
477
598
  get(key) {
478
599
  try {
@@ -880,6 +1001,19 @@ var Lazypock = (() => {
880
1001
  encodeId(id) {
881
1002
  return encodeURIComponent(id);
882
1003
  }
1004
+ /**
1005
+ * The records endpoint for this collection.
1006
+ *
1007
+ * Centralised because the server's shape is `/api/collections/<name>/records`,
1008
+ * and a path repeated eighteen times is a path that drifts.
1009
+ */
1010
+ recordsPath() {
1011
+ return "/collections/" + this.encodeId(this.collectionName) + "/records";
1012
+ }
1013
+ /** The collection's own endpoint, which is where its auth routes live. */
1014
+ collectionPath() {
1015
+ return "/collections/" + this.encodeId(this.collectionName);
1016
+ }
883
1017
  // ── Field projection (`.select`) ──
884
1018
  /**
885
1019
  * Project list/read responses to the given fields (PocketBase `fields`
@@ -1287,7 +1421,7 @@ var Lazypock = (() => {
1287
1421
  }).map(([k, v]) => [k, String(v)])
1288
1422
  )
1289
1423
  ).toString();
1290
- const result = await this.http.get("/" + this.encodeId(this.collectionName) + "?" + qs, {
1424
+ const result = await this.http.get(this.recordsPath() + "?" + qs, {
1291
1425
  requestKey,
1292
1426
  autoCancel,
1293
1427
  cancelKey,
@@ -1372,7 +1506,7 @@ var Lazypock = (() => {
1372
1506
  }
1373
1507
  const qsStr = qs.toString();
1374
1508
  const record = await this.http.get(
1375
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1509
+ this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1376
1510
  options
1377
1511
  );
1378
1512
  if (record && expandInfo.narrow.size > 0) {
@@ -1388,7 +1522,7 @@ var Lazypock = (() => {
1388
1522
  */
1389
1523
  create(data, options) {
1390
1524
  return this.http.post(
1391
- "/" + this.encodeId(this.collectionName),
1525
+ this.recordsPath(),
1392
1526
  data,
1393
1527
  options
1394
1528
  );
@@ -1402,7 +1536,7 @@ var Lazypock = (() => {
1402
1536
  */
1403
1537
  update(id, data, options) {
1404
1538
  return this.http.patch(
1405
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1539
+ this.recordsPath() + "/" + this.encodeId(id),
1406
1540
  data,
1407
1541
  options
1408
1542
  );
@@ -1414,7 +1548,7 @@ var Lazypock = (() => {
1414
1548
  */
1415
1549
  delete(id, options) {
1416
1550
  return this.http.delete(
1417
- "/" + this.encodeId(this.collectionName) + "/" + this.encodeId(id),
1551
+ this.recordsPath() + "/" + this.encodeId(id),
1418
1552
  options
1419
1553
  );
1420
1554
  }
@@ -1522,13 +1656,17 @@ var Lazypock = (() => {
1522
1656
  */
1523
1657
  async authWithPassword(identity, password, options) {
1524
1658
  const data = await this.http.post(
1525
- "/" + this.encodeId(this.collectionName) + "/auth-with-password",
1659
+ this.collectionPath() + "/auth-with-password",
1526
1660
  { identity, password },
1527
1661
  options
1528
1662
  );
1529
1663
  if (data && this.authStore) {
1530
1664
  this.authStore.setCollectionName(this.collectionName);
1531
- this.authStore.set(data.token, data.record);
1665
+ rememberAuthResponse(
1666
+ this.authStore,
1667
+ data,
1668
+ data.record
1669
+ );
1532
1670
  }
1533
1671
  return data;
1534
1672
  }
@@ -1538,13 +1676,17 @@ var Lazypock = (() => {
1538
1676
  */
1539
1677
  async authRefresh(options) {
1540
1678
  const data = await this.http.post(
1541
- "/" + this.encodeId(this.collectionName) + "/auth-refresh",
1542
- void 0,
1679
+ this.collectionPath() + "/auth-refresh",
1680
+ { refreshToken: this.authStore?.refreshToken },
1543
1681
  options
1544
1682
  );
1545
1683
  if (data && this.authStore) {
1546
1684
  this.authStore.setCollectionName(this.collectionName);
1547
- this.authStore.set(data.token, data.record);
1685
+ rememberAuthResponse(
1686
+ this.authStore,
1687
+ data,
1688
+ data.record
1689
+ );
1548
1690
  }
1549
1691
  return data;
1550
1692
  }
@@ -1555,7 +1697,7 @@ var Lazypock = (() => {
1555
1697
  */
1556
1698
  async listAuthMethods(options) {
1557
1699
  return this.http.get(
1558
- "/" + this.encodeId(this.collectionName) + "/auth-methods",
1700
+ this.collectionPath() + "/auth-methods",
1559
1701
  options
1560
1702
  );
1561
1703
  }
@@ -1574,7 +1716,7 @@ var Lazypock = (() => {
1574
1716
  */
1575
1717
  async requestPasswordReset(email, options) {
1576
1718
  await this.http.post(
1577
- "/" + this.encodeId(this.collectionName) + "/request-password-reset",
1719
+ this.collectionPath() + "/request-password-reset",
1578
1720
  { email },
1579
1721
  options
1580
1722
  );
@@ -1589,7 +1731,7 @@ var Lazypock = (() => {
1589
1731
  */
1590
1732
  async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1591
1733
  await this.http.post(
1592
- "/" + this.encodeId(this.collectionName) + "/confirm-password-reset",
1734
+ this.collectionPath() + "/confirm-password-reset",
1593
1735
  { token: passwordResetToken, password, passwordConfirm },
1594
1736
  options
1595
1737
  );
@@ -1602,7 +1744,7 @@ var Lazypock = (() => {
1602
1744
  */
1603
1745
  async requestVerification(email, options) {
1604
1746
  await this.http.post(
1605
- "/" + this.encodeId(this.collectionName) + "/request-verification",
1747
+ this.collectionPath() + "/request-verification",
1606
1748
  { email },
1607
1749
  options
1608
1750
  );
@@ -1614,7 +1756,7 @@ var Lazypock = (() => {
1614
1756
  */
1615
1757
  async confirmVerification(verificationToken, options) {
1616
1758
  const data = await this.http.post(
1617
- "/" + this.encodeId(this.collectionName) + "/confirm-verification",
1759
+ this.collectionPath() + "/confirm-verification",
1618
1760
  { token: verificationToken },
1619
1761
  options
1620
1762
  );
@@ -1626,7 +1768,7 @@ var Lazypock = (() => {
1626
1768
  */
1627
1769
  async requestEmailChange(newEmail, options) {
1628
1770
  await this.http.post(
1629
- "/" + this.encodeId(this.collectionName) + "/request-email-change",
1771
+ this.collectionPath() + "/request-email-change",
1630
1772
  { newEmail },
1631
1773
  options
1632
1774
  );
@@ -1639,7 +1781,7 @@ var Lazypock = (() => {
1639
1781
  */
1640
1782
  async confirmEmailChange(emailChangeToken, password, options) {
1641
1783
  const data = await this.http.post(
1642
- "/" + this.encodeId(this.collectionName) + "/confirm-email-change",
1784
+ this.collectionPath() + "/confirm-email-change",
1643
1785
  { token: emailChangeToken, password },
1644
1786
  options
1645
1787
  );
@@ -1707,7 +1849,7 @@ var Lazypock = (() => {
1707
1849
  async authWithOAuth2Code(options) {
1708
1850
  const { provider, code, codeVerifier, redirectUrl, createData } = options;
1709
1851
  const data = await this.http.post(
1710
- "/" + this.encodeId(this.collectionName) + "/auth-with-oauth2",
1852
+ this.collectionPath() + "/auth-with-oauth2",
1711
1853
  {
1712
1854
  provider,
1713
1855
  code,
@@ -1727,266 +1869,256 @@ var Lazypock = (() => {
1727
1869
  }
1728
1870
  if (this.authStore) {
1729
1871
  this.authStore.setCollectionName(this.collectionName);
1730
- this.authStore.set(data.token, data.record);
1872
+ rememberAuthResponse(
1873
+ this.authStore,
1874
+ data,
1875
+ data.record
1876
+ );
1731
1877
  }
1732
1878
  return data;
1733
1879
  }
1734
1880
  };
1735
1881
 
1736
1882
  // src/realtime.ts
1737
- function wsUrlFromBaseUrl(baseUrl) {
1738
- try {
1739
- const url = new URL(baseUrl);
1740
- const protocol = url.protocol === "https:" ? "wss:" : "ws:";
1741
- return `${protocol}//${url.host}/socket/websocket`;
1742
- } catch {
1743
- return `${baseUrl.replace(/^http/, "ws").replace(/\/api$/, "")}/socket/websocket`;
1744
- }
1883
+ function sseUrlFromBaseUrl(baseUrl) {
1884
+ return `${baseUrl.replace(/\/+$/, "")}/realtime`;
1885
+ }
1886
+ function serverTopic(topic) {
1887
+ if (topic === "collections") return "collections";
1888
+ if (!topic.startsWith("collection:")) return null;
1889
+ const rest = topic.slice("collection:".length);
1890
+ const [name, recordId] = rest.split(":");
1891
+ if (!name) return null;
1892
+ return recordId ? `${name}/${recordId}` : name;
1745
1893
  }
1746
1894
  var RealtimeService = class {
1747
1895
  constructor() {
1748
- this.ws = null;
1749
- this.refCounter = 0;
1896
+ this.controller = null;
1897
+ this.open = false;
1898
+ this.closed = false;
1750
1899
  this.subscriptions = /* @__PURE__ */ new Map();
1751
1900
  this.reconnectTimer = null;
1901
+ this.resubscribeTimer = null;
1752
1902
  this.reconnectAttempt = 0;
1753
1903
  this.maxReconnectDelay = 5e3;
1754
1904
  this.url = "";
1755
1905
  this.tokenProvider = null;
1756
- // ── Heartbeat ──
1757
- this.heartbeatInterval = null;
1758
1906
  }
1759
- /** Whether the WebSocket is currently open. */
1907
+ /** Whether the stream is currently open. */
1760
1908
  get isOpen() {
1761
- return this.ws?.readyState === WebSocket.OPEN;
1909
+ return this.open;
1762
1910
  }
1763
- /**
1764
- * The most recently used WebSocket URL (set on {@link connect}).
1765
- * Useful for SDK convenience methods that auto-connect before subscribing.
1766
- */
1911
+ /** The most recently used SSE URL (set on {@link connect}/{@link setUrl}). */
1767
1912
  get lastUrl() {
1768
1913
  return this.url;
1769
1914
  }
1770
- /** The auth token configured for this connection (set on connect). */
1915
+ /** The auth token configured for this connection. */
1771
1916
  get lastToken() {
1772
1917
  return this.token;
1773
1918
  }
1774
- /**
1775
- * Set the per-client connection id (browser tab / device). The SDK
1776
- * appends it as the `connectionId` socket query param at connect time
1777
- * (unless the URL already carries one), matching the `X-Connection-Id`
1778
- * header the HTTP client sends — together they let the server exclude
1779
- * the originating connection from its own realtime broadcasts.
1780
- */
1919
+ /** Set the per-client connection id (browser tab / device). */
1781
1920
  setConnectionId(id) {
1782
1921
  this.connectionId = id;
1783
1922
  }
1784
- /**
1785
- * Set the socket URL. Useful before subscribing so the SDK can
1786
- * auto-connect on the first {@link subscribe}.
1787
- */
1923
+ /** Set the stream URL. Useful before subscribing so the SDK auto-connects. */
1788
1924
  setUrl(url) {
1789
1925
  this.url = url;
1790
1926
  }
1791
- /**
1792
- * Register a token provider consulted at every (re)connect.
1793
- * When set, it takes precedence over the token passed to {@link connect}.
1794
- */
1927
+ /** Register a token provider consulted at every (re)connect. */
1795
1928
  setTokenProvider(provider) {
1796
1929
  this.tokenProvider = provider;
1797
1930
  }
1798
1931
  /**
1799
- * Reconnect the socket immediately with the current token.
1800
- * Called by the SDK when auth changes (login/logout/token refresh) so
1801
- * private-channel joins are authorized with the new credentials. No-op
1802
- * when the socket has never been opened and nothing is subscribed.
1932
+ * Reconnect immediately with the current token, so auth changes
1933
+ * (login/logout/refresh) re-authorize private subscriptions.
1803
1934
  */
1804
1935
  refresh() {
1805
- if (typeof WebSocket === "undefined") return;
1806
- if (!this.ws && this.subscriptions.size === 0) return;
1807
- this.clearReconnectTimer();
1808
- const ws = this.ws;
1809
- this.ws = null;
1810
- if (ws) {
1811
- ws.onclose = null;
1812
- ws.close();
1813
- }
1936
+ if (this.closed) return;
1937
+ if (!this.open && this.subscriptions.size === 0) return;
1814
1938
  this.reconnectAttempt = 0;
1815
1939
  this.doConnect();
1816
1940
  }
1817
- /*
1818
- * Ensure the socket is connected, then subscribe.
1819
- * Used by collection-level convenience wrappers so a connection is opened
1820
- * automatically on the first subscribe (matching PocketBase behaviour —
1821
- * works for anonymous/public collections too).
1822
- */
1941
+ /** Ensure a connection is open, then subscribe. */
1823
1942
  ensureConnected() {
1824
- if (this.isOpen || !this.url) return;
1825
- if (typeof WebSocket === "undefined") return;
1943
+ if (this.open || this.controller || !this.url) return;
1944
+ if (this.serverTopics().length === 0) return;
1826
1945
  this.doConnect();
1827
1946
  }
1828
1947
  connect(opts) {
1829
1948
  this.url = opts.url;
1830
1949
  this.token = opts.token;
1950
+ this.closed = false;
1831
1951
  this.reconnectAttempt = 0;
1832
1952
  this.doConnect();
1833
1953
  }
1834
1954
  disconnect() {
1955
+ this.closed = true;
1835
1956
  this.clearReconnectTimer();
1836
- this.ws?.close();
1837
- this.ws = null;
1957
+ this.closeStream();
1838
1958
  }
1839
1959
  /**
1840
- * Subscribe to a topic (e.g. "collection:posts" or "custom:chat-room").
1841
- * The backend Channel authorizes via listRule on join.
1842
- *
1843
- * @param joinPayload Optional payload forwarded with the channel join
1844
- * (available to the server's join callback / hooks, e.g. `expand`).
1960
+ * Subscribe to a topic (`collection:posts`, `collection:posts:ID`, or the
1961
+ * registry topic `collections`).
1845
1962
  */
1846
1963
  subscribe(topic, callback, joinPayload) {
1847
1964
  const subs = this.subscriptions.get(topic) || [];
1848
1965
  subs.push({ topic, callback, joinPayload });
1849
1966
  this.subscriptions.set(topic, subs);
1850
- if (this.ws?.readyState === WebSocket.OPEN) {
1851
- this.joinTopic(topic, joinPayload);
1852
- }
1967
+ this.resubscribe();
1853
1968
  }
1854
- /**
1855
- * Remove all subscriptions for topics under `prefix` (the topic itself or
1856
- * any topic starting with `prefix + ":"`). Used by collection-level
1857
- * `unsubscribe()` to drop every subscription of a collection.
1858
- */
1969
+ /** Remove every subscription under `prefix` (the topic or `prefix:...`). */
1859
1970
  unsubscribeByPrefix(prefix) {
1971
+ let changed = false;
1860
1972
  for (const topic of [...this.subscriptions.keys()]) {
1861
1973
  if (topic === prefix || topic.startsWith(prefix + ":")) {
1862
1974
  this.subscriptions.delete(topic);
1975
+ changed = true;
1863
1976
  }
1864
1977
  }
1978
+ if (changed) this.resubscribe();
1865
1979
  }
1866
- /**
1867
- * Unsubscribe a specific callback from a topic.
1868
- */
1980
+ /** Remove a specific callback from a topic, or the whole topic. */
1869
1981
  unsubscribe(topic, callback) {
1870
1982
  if (!callback) {
1871
- this.subscriptions.delete(topic);
1983
+ if (this.subscriptions.delete(topic)) this.resubscribe();
1872
1984
  return;
1873
1985
  }
1874
1986
  const subs = this.subscriptions.get(topic)?.filter((s) => s.callback !== callback);
1875
1987
  if (subs && subs.length > 0) {
1876
1988
  this.subscriptions.set(topic, subs);
1877
- } else {
1878
- this.subscriptions.delete(topic);
1989
+ return;
1879
1990
  }
1991
+ this.subscriptions.delete(topic);
1992
+ this.resubscribe();
1880
1993
  }
1881
- resubscribeAll() {
1882
- const seen = /* @__PURE__ */ new Set();
1883
- for (const entries of this.subscriptions.values()) {
1884
- for (const entry of entries) {
1885
- if (seen.has(entry.topic)) continue;
1886
- seen.add(entry.topic);
1887
- if (this.ws?.readyState === WebSocket.OPEN) {
1888
- this.joinTopic(entry.topic, entry.joinPayload);
1889
- }
1890
- }
1994
+ // ── Internals ────────────────────────────────────
1995
+ /** The distinct server topics the current subscriptions need. */
1996
+ serverTopics() {
1997
+ const topics = /* @__PURE__ */ new Set();
1998
+ for (const topic of this.subscriptions.keys()) {
1999
+ const server = serverTopic(topic);
2000
+ if (server) topics.add(server);
1891
2001
  }
2002
+ return [...topics];
2003
+ }
2004
+ /**
2005
+ * The subscription set is part of the connection URL, so a change needs a new
2006
+ * connection. Coalesced, because mounting a page subscribes to several
2007
+ * collections in one tick.
2008
+ */
2009
+ resubscribe() {
2010
+ if (this.resubscribeTimer) clearTimeout(this.resubscribeTimer);
2011
+ this.resubscribeTimer = setTimeout(() => {
2012
+ this.resubscribeTimer = null;
2013
+ if (this.controller) {
2014
+ this.doConnect();
2015
+ } else {
2016
+ this.ensureConnected();
2017
+ }
2018
+ }, 0);
1892
2019
  }
1893
2020
  doConnect() {
1894
- if (typeof WebSocket === "undefined") {
1895
- console.warn(
1896
- "[lazypock] WebSocket not available \u2014 realtime subscriptions disabled"
1897
- );
1898
- return;
1899
- }
1900
- let url = this.url;
2021
+ if (this.closed) return;
2022
+ const topics = this.serverTopics();
2023
+ if (topics.length === 0 || !this.url) return;
2024
+ this.closeStream();
2025
+ const params = new URLSearchParams();
2026
+ params.set("subscribe", topics.join(","));
2027
+ const url = this.url + (this.url.includes("?") ? "&" : "?") + params.toString();
1901
2028
  const token = this.tokenProvider ? this.tokenProvider() : this.token;
1902
- if (token) {
1903
- url += (url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(token);
1904
- }
1905
- if (this.connectionId && !url.includes("connectionId=")) {
1906
- url += (url.includes("?") ? "&" : "?") + "connectionId=" + encodeURIComponent(this.connectionId);
1907
- }
1908
- this.ws = new WebSocket(url);
1909
- this.ws.onopen = () => {
2029
+ const headers = { Accept: "text/event-stream" };
2030
+ if (token) headers.Authorization = `Bearer ${token}`;
2031
+ if (this.connectionId) headers["X-Connection-Id"] = this.connectionId;
2032
+ const controller = new AbortController();
2033
+ this.controller = controller;
2034
+ void this.read(url, headers, controller);
2035
+ }
2036
+ async read(url, headers, controller) {
2037
+ try {
2038
+ const response = await fetch(url, { headers, signal: controller.signal });
2039
+ if (!response.ok || !response.body) {
2040
+ throw new Error(`realtime connection failed (${response.status})`);
2041
+ }
2042
+ this.open = true;
1910
2043
  this.reconnectAttempt = 0;
1911
- this.resubscribeAll();
1912
- this.startHeartbeat();
1913
- };
1914
- this.ws.onmessage = (msg) => {
1915
- this.handleMessage(msg.data);
1916
- };
1917
- this.ws.onclose = () => {
1918
- this.stopHeartbeat();
1919
- this.onDisconnect?.();
1920
- this.scheduleReconnect();
1921
- };
1922
- this.ws.onerror = (err) => {
2044
+ this.onReconnect?.();
2045
+ const reader = response.body.getReader();
2046
+ const decoder = new TextDecoder();
2047
+ let buffer = "";
2048
+ for (; ; ) {
2049
+ const { done, value } = await reader.read();
2050
+ if (done) break;
2051
+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(
2052
+ /\r\n/g,
2053
+ "\n"
2054
+ );
2055
+ let index;
2056
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
2057
+ this.handleFrame(buffer.slice(0, index));
2058
+ buffer = buffer.slice(index + 2);
2059
+ }
2060
+ }
2061
+ throw new Error("realtime stream ended");
2062
+ } catch (err) {
2063
+ if (controller.signal.aborted) return;
1923
2064
  this.onError?.(err);
1924
- };
2065
+ } finally {
2066
+ if (this.controller === controller) {
2067
+ this.open = false;
2068
+ this.controller = null;
2069
+ this.onDisconnect?.();
2070
+ this.scheduleReconnect();
2071
+ }
2072
+ }
1925
2073
  }
1926
- handleMessage(data) {
1927
- let parsed;
2074
+ handleFrame(frame) {
2075
+ const dataLines = [];
2076
+ for (const line of frame.split("\n")) {
2077
+ if (line.startsWith("data:")) {
2078
+ dataLines.push(line.slice(5).replace(/^ /, ""));
2079
+ }
2080
+ }
2081
+ if (dataLines.length === 0) return;
2082
+ let data;
1928
2083
  try {
1929
- parsed = JSON.parse(data);
2084
+ data = JSON.parse(dataLines.join("\n"));
1930
2085
  } catch {
1931
2086
  return;
1932
2087
  }
1933
- if (typeof parsed !== "object" || !parsed.topic || !parsed.event) return;
1934
- const topic = parsed.topic;
1935
- const event = parsed.event;
1936
- const payload = parsed.payload || {};
1937
- if (event === "phx_reply") return;
1938
- const subs = this.subscriptions.get(topic);
1939
- if (subs) {
1940
- const e = {
1941
- event,
1942
- topic,
1943
- payload
1944
- };
1945
- for (const s of subs) {
1946
- try {
1947
- s.callback(e);
1948
- } catch {
1949
- }
1950
- }
2088
+ this.dispatch(data);
2089
+ }
2090
+ dispatch(data) {
2091
+ const action = typeof data.action === "string" ? data.action : "update";
2092
+ if (data.collection === "collections") {
2093
+ this.emit("collections", action, data.record ?? {});
2094
+ return;
2095
+ }
2096
+ if (!data.collection) return;
2097
+ const payload = { record: data.record ?? {}, action };
2098
+ this.emit(`collection:${data.collection}`, action, payload);
2099
+ if (data.id) {
2100
+ this.emit(`collection:${data.collection}:${data.id}`, action, payload);
1951
2101
  }
1952
2102
  }
1953
- joinTopic(topic, joinPayload) {
1954
- const ref = this.nextRef();
1955
- const msg = JSON.stringify({
1956
- topic,
1957
- event: "phx_join",
1958
- payload: joinPayload ?? {},
1959
- ref
1960
- });
1961
- this.ws?.send(msg);
1962
- }
1963
- nextRef() {
1964
- this.refCounter++;
1965
- return this.refCounter.toString();
1966
- }
1967
- startHeartbeat() {
1968
- this.stopHeartbeat();
1969
- this.heartbeatInterval = setInterval(() => {
1970
- if (this.ws?.readyState === WebSocket.OPEN) {
1971
- const ref = this.nextRef();
1972
- const msg = JSON.stringify({
1973
- topic: "phoenix",
1974
- event: "heartbeat",
1975
- payload: {},
1976
- ref
1977
- });
1978
- this.ws.send(msg);
2103
+ emit(topic, event, payload) {
2104
+ const subs = this.subscriptions.get(topic);
2105
+ if (!subs) return;
2106
+ const e = { event, topic, payload };
2107
+ for (const s of subs) {
2108
+ try {
2109
+ s.callback(e);
2110
+ } catch {
1979
2111
  }
1980
- }, 3e4);
1981
- }
1982
- stopHeartbeat() {
1983
- if (this.heartbeatInterval) {
1984
- clearInterval(this.heartbeatInterval);
1985
- this.heartbeatInterval = null;
1986
2112
  }
1987
2113
  }
1988
- // ── Reconnect ──
2114
+ closeStream() {
2115
+ const controller = this.controller;
2116
+ this.controller = null;
2117
+ this.open = false;
2118
+ controller?.abort();
2119
+ }
1989
2120
  scheduleReconnect() {
2121
+ if (this.closed) return;
1990
2122
  this.clearReconnectTimer();
1991
2123
  const delay = Math.min(
1992
2124
  1e3 * 2 ** this.reconnectAttempt,
@@ -1995,7 +2127,6 @@ var Lazypock = (() => {
1995
2127
  this.reconnectAttempt++;
1996
2128
  this.reconnectTimer = setTimeout(() => {
1997
2129
  this.reconnectTimer = null;
1998
- this.onReconnect?.();
1999
2130
  this.doConnect();
2000
2131
  }, delay);
2001
2132
  }
@@ -2008,14 +2139,18 @@ var Lazypock = (() => {
2008
2139
  };
2009
2140
 
2010
2141
  // src/files.ts
2011
- function getFileUrl(baseUrl, fileId) {
2012
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId);
2142
+ function encodeKey(key) {
2143
+ return key.split("/").map(encodeURIComponent).join("/");
2144
+ }
2145
+ function getFileUrl(baseUrl, key) {
2146
+ return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
2013
2147
  }
2014
- function getThumbUrl(baseUrl, fileId, size) {
2015
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/thumbs/" + encodeURIComponent(size);
2148
+ function getThumbUrl(baseUrl, key, size) {
2149
+ return getFileUrl(baseUrl, key) + "?thumb=" + encodeURIComponent(size);
2016
2150
  }
2017
- function getScaleUrl(baseUrl, fileId, size) {
2018
- return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/scale/" + encodeURIComponent(size);
2151
+ function getScaleUrl(baseUrl, key, size) {
2152
+ const parameter = size.includes("x") ? "thumb" : "preset";
2153
+ return getFileUrl(baseUrl, key) + "?" + parameter + "=" + encodeURIComponent(size);
2019
2154
  }
2020
2155
  function getVariantUrl(baseUrl, fileId, preset) {
2021
2156
  return getScaleUrl(baseUrl, fileId, preset);
@@ -2686,7 +2821,7 @@ ${opts.body}
2686
2821
  this.http = new HttpClient(baseUrl, this.authStore, connectionId);
2687
2822
  this.realtime = options.realtime ?? new RealtimeService();
2688
2823
  if (!options.realtime) {
2689
- this.realtime.setUrl(wsUrlFromBaseUrl(baseUrl));
2824
+ this.realtime.setUrl(sseUrlFromBaseUrl(baseUrl));
2690
2825
  }
2691
2826
  this.realtime.setConnectionId(connectionId);
2692
2827
  this.realtime.setTokenProvider(() => this.authStore.token);
@@ -2799,7 +2934,7 @@ ${opts.body}
2799
2934
  const data = await this.http.post("/superusers/setup", { email, password });
2800
2935
  if (data) {
2801
2936
  this.authStore.setCollectionName(null);
2802
- this.authStore.set(data.token, null);
2937
+ rememberAuthResponse(this.authStore, data, null);
2803
2938
  }
2804
2939
  return data;
2805
2940
  }
@@ -2817,17 +2952,21 @@ ${opts.body}
2817
2952
  async login(email, password, collection) {
2818
2953
  let data;
2819
2954
  if (collection) {
2820
- data = await this.http.post("/" + encodeURIComponent(collection) + "/auth-with-password", {
2955
+ data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
2821
2956
  identity: email,
2822
2957
  password
2823
2958
  });
2824
2959
  if (data && data.record) {
2825
2960
  this.authStore.setCollectionName(collection);
2826
- this.authStore.set(data.token, data.record);
2961
+ rememberAuthResponse(
2962
+ this.authStore,
2963
+ data,
2964
+ data.record
2965
+ );
2827
2966
  }
2828
2967
  } else {
2829
2968
  try {
2830
- data = await this.http.post("/_superusers/auth-with-password", {
2969
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
2831
2970
  identity: email,
2832
2971
  password
2833
2972
  });
@@ -2839,7 +2978,7 @@ ${opts.body}
2839
2978
  }
2840
2979
  if (data) {
2841
2980
  this.authStore.setCollectionName(null);
2842
- this.authStore.set(data.token, null);
2981
+ rememberAuthResponse(this.authStore, data, null);
2843
2982
  }
2844
2983
  }
2845
2984
  return data;
@@ -2867,13 +3006,13 @@ ${opts.body}
2867
3006
  */
2868
3007
  async authWithPassword(collection, identity, password, options) {
2869
3008
  const data = await this.http.post(
2870
- "/" + encodeURIComponent(collection) + "/auth-with-password",
3009
+ "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
2871
3010
  { identity, password },
2872
3011
  options
2873
3012
  );
2874
3013
  if (data) {
2875
3014
  this.authStore.setCollectionName(collection);
2876
- this.authStore.set(data.token, data.record);
3015
+ rememberAuthResponse(this.authStore, data, data.record);
2877
3016
  }
2878
3017
  return data;
2879
3018
  }
@@ -2886,13 +3025,13 @@ ${opts.body}
2886
3025
  */
2887
3026
  async authRefresh(collection, options) {
2888
3027
  const data = await this.http.post(
2889
- "/" + encodeURIComponent(collection) + "/auth-refresh",
2890
- void 0,
3028
+ "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
3029
+ { refreshToken: this.authStore.refreshToken },
2891
3030
  options
2892
3031
  );
2893
3032
  if (data) {
2894
3033
  this.authStore.setCollectionName(collection);
2895
- this.authStore.set(data.token, data.record);
3034
+ rememberAuthResponse(this.authStore, data, data.record);
2896
3035
  }
2897
3036
  return data;
2898
3037
  }