lazypock 0.1.3 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,25 +4,37 @@ import {
4
4
  fieldTypeScriptType,
5
5
  generateTypes,
6
6
  schemaFieldType
7
- } from "./chunk-3MZJ5HCD.js";
7
+ } from "./chunk-Y6PMBL2S.js";
8
8
 
9
9
  // src/types.ts
10
10
  var ApiError = class extends Error {
11
- constructor(message, data, status) {
11
+ constructor(message, data, status, isAbort = false) {
12
12
  super(message);
13
13
  this.name = "ApiError";
14
14
  this.data = data;
15
15
  this.status = status;
16
+ this.isAbort = isAbort;
16
17
  }
17
18
  };
18
19
 
19
20
  // src/http.ts
21
+ function isAbortError(err) {
22
+ return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
23
+ }
20
24
  var HttpClient = class {
21
25
  /**
22
26
  * @param baseUrl The API base URL (e.g. `http://localhost:4000/api`). Trailing slash stripped.
23
27
  * @param authStore The auth store providing the token for Authorization headers.
24
28
  */
25
29
  constructor(baseUrl, authStore) {
30
+ /**
31
+ * Abort controllers for in-flight requests, keyed by their cancellation key
32
+ * (default `METHOD path`). A new request with the same key aborts the
33
+ * previous one — PocketBase-style auto-cancellation of duplicated requests.
34
+ */
35
+ this.cancelControllers = {};
36
+ /** Global toggle for the auto-cancellation behaviour (default: on). */
37
+ this.enableAutoCancellation = true;
26
38
  this.baseUrl = baseUrl.replace(/\/+$/, "");
27
39
  this.authStore = authStore;
28
40
  this.defaultFetch = globalThis.fetch.bind(globalThis);
@@ -59,20 +71,73 @@ var HttpClient = class {
59
71
  return null;
60
72
  }
61
73
  }
74
+ /**
75
+ * Globally enable or disable auto-cancellation of duplicated pending requests.
76
+ * Fluent — returns `this` for chaining.
77
+ */
78
+ autoCancellation(enable) {
79
+ this.enableAutoCancellation = !!enable;
80
+ return this;
81
+ }
82
+ /**
83
+ * Abort a pending request identified by its cancellation key
84
+ * (default `METHOD path`, e.g. `"GET /api/posts"`). No-op if not pending.
85
+ */
86
+ cancelRequest(requestKey) {
87
+ const controller = this.cancelControllers[requestKey];
88
+ if (controller) {
89
+ controller.abort();
90
+ delete this.cancelControllers[requestKey];
91
+ }
92
+ return this;
93
+ }
94
+ /** Abort all pending requests. */
95
+ cancelAllRequests() {
96
+ for (const key in this.cancelControllers) {
97
+ this.cancelControllers[key].abort();
98
+ }
99
+ this.cancelControllers = {};
100
+ return this;
101
+ }
62
102
  /**
63
103
  * Make an HTTP request with automatic auth token injection and optional auto-refresh.
64
104
  *
105
+ * Auto-cancellation: a request keyed by `options.requestKey` (default
106
+ * `METHOD path`) aborts any previous pending request with the same key,
107
+ * so only the last duplicate executes. Set `requestKey: null` or
108
+ * `autoCancel: false` to opt out per request.
109
+ *
65
110
  * @param method HTTP method.
66
111
  * @param path URL path (appended to baseUrl).
67
112
  * @param body JSON-serializable body, or FormData for file uploads.
68
113
  * @param options Optional request options.
69
114
  * @returns Parsed JSON response, or null for 204 No Content.
70
- * @throws {ApiError} On non-2xx responses.
115
+ * @throws {ApiError} On non-2xx responses or when the request is aborted
116
+ * (aborted requests throw an `ApiError` with `isAbort === true`).
71
117
  */
72
118
  async request(method, path, body, options) {
73
119
  if (this.authStore.isExpired && this.authStore.collectionName) {
74
120
  await this.refreshAuth();
75
121
  }
122
+ let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
123
+ if (options?.autoCancel === false) requestKey = null;
124
+ let controller = null;
125
+ const externalSignal = options?.signal;
126
+ if (requestKey !== null) {
127
+ if (this.enableAutoCancellation) {
128
+ this.cancelRequest(requestKey);
129
+ }
130
+ controller = new AbortController();
131
+ this.cancelControllers[requestKey] = controller;
132
+ if (externalSignal?.aborted) {
133
+ controller.abort();
134
+ } else if (externalSignal) {
135
+ externalSignal.addEventListener("abort", () => controller?.abort(), {
136
+ once: true
137
+ });
138
+ }
139
+ }
140
+ const signal = controller?.signal ?? externalSignal;
76
141
  let url = this.baseUrl + path;
77
142
  if (options?.params) {
78
143
  const qs = new URLSearchParams(options.params).toString();
@@ -92,7 +157,7 @@ var HttpClient = class {
92
157
  const init = {
93
158
  method,
94
159
  headers,
95
- signal: options?.signal
160
+ signal
96
161
  };
97
162
  if (body != null && method !== "GET" && method !== "DELETE") {
98
163
  if (body instanceof FormData) {
@@ -101,8 +166,25 @@ var HttpClient = class {
101
166
  init.body = JSON.stringify(body);
102
167
  }
103
168
  }
169
+ let res = null;
104
170
  const fetcher = options?.fetch ?? this.defaultFetch;
105
- const res = await fetcher(url, init);
171
+ try {
172
+ res = await fetcher(url, init);
173
+ } catch (err) {
174
+ if (isAbortError(err)) {
175
+ throw new ApiError(
176
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
177
+ {},
178
+ 0,
179
+ true
180
+ );
181
+ }
182
+ throw err;
183
+ } finally {
184
+ if (requestKey !== null && this.cancelControllers[requestKey] === controller) {
185
+ delete this.cancelControllers[requestKey];
186
+ }
187
+ }
106
188
  if (res.status === 204) return null;
107
189
  let bodyText = "";
108
190
  let data = {};
@@ -321,17 +403,68 @@ var CollectionService = class {
321
403
  return encodeURIComponent(id);
322
404
  }
323
405
  /**
324
- * List records with optional filter/sort/pagination.
325
- * @param params Query parameters including `filter`, `sort`, `page`, `perPage`, `expand`.
326
- * @param options Optional request options.
406
+ * Fetch a paginated list of records (PocketBase `getList`).
407
+ *
408
+ * @param page Page number (default 1).
409
+ * @param perPage Records per page (default 30).
410
+ * @param options Query params (`filter`, `sort`, `expand`, `fields`) + request options.
327
411
  */
328
- list(params, options) {
329
- const qs = params ? "?" + new URLSearchParams(params).toString() : "";
412
+ getList(page = 1, perPage = 30, options) {
413
+ const { requestKey, autoCancel, cancelKey, ...rest } = options ?? {};
414
+ const qs = new URLSearchParams(
415
+ Object.fromEntries(
416
+ Object.entries({
417
+ page: String(page),
418
+ perPage: String(perPage),
419
+ ...rest
420
+ }).map(([k, v]) => [k, String(v)])
421
+ )
422
+ ).toString();
330
423
  return this.http.get(
331
- "/" + this.encodeId(this.collectionName) + qs,
332
- options
424
+ "/" + this.encodeId(this.collectionName) + "?" + qs,
425
+ { requestKey, autoCancel, cancelKey }
333
426
  );
334
427
  }
428
+ /**
429
+ * Fetch all records at once (auto-paginates). Mirrors PocketBase's
430
+ * `pb.collection(name).getFullList()`.
431
+ *
432
+ * @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
433
+ */
434
+ async getFullList(options) {
435
+ const { batch = 1e3, ...rest } = options ?? {};
436
+ const items = [];
437
+ let page = 1;
438
+ for (; ; ) {
439
+ const res = await this.getList(
440
+ page,
441
+ batch,
442
+ {
443
+ // disable auto-cancellation across pages — each page request is unique
444
+ ...rest,
445
+ requestKey: null
446
+ }
447
+ );
448
+ if (!res || !res.items || res.items.length === 0) break;
449
+ items.push(...res.items);
450
+ if (page >= (res.totalPages ?? page)) break;
451
+ page += 1;
452
+ }
453
+ return items;
454
+ }
455
+ /**
456
+ * Fetch the first record matching a filter (PocketBase `getFirstListItem`).
457
+ *
458
+ * @param filter Filter expression (e.g. `title = 'x'`).
459
+ * @param options Optional request options.
460
+ */
461
+ async getFirstListItem(filter, options) {
462
+ const res = await this.getList(1, 1, {
463
+ ...options,
464
+ filter
465
+ });
466
+ return res?.items?.[0] ?? null;
467
+ }
335
468
  /**
336
469
  * Get a single record by ID.
337
470
  * @param id Record ID.
@@ -716,6 +849,12 @@ var RealtimeService = class {
716
849
  function getFileUrl(baseUrl, fileId) {
717
850
  return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId);
718
851
  }
852
+ function getThumbUrl(baseUrl, fileId, size) {
853
+ return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/thumbs/" + encodeURIComponent(size);
854
+ }
855
+ function getScaleUrl(baseUrl, fileId, size) {
856
+ return baseUrl.replace(/\/+$/, "") + "/files/" + encodeURIComponent(fileId) + "/scale/" + encodeURIComponent(size);
857
+ }
719
858
  var FilesService = class {
720
859
  constructor(http) {
721
860
  this.http = http;
@@ -747,6 +886,25 @@ var FilesService = class {
747
886
  );
748
887
  return data;
749
888
  }
889
+ /**
890
+ * List uploaded files (newest first), with optional filters.
891
+ *
892
+ * @param options Filters and pagination.
893
+ */
894
+ async list(options) {
895
+ const params = {};
896
+ if (options?.page !== void 0) params["page"] = String(options.page);
897
+ if (options?.perPage !== void 0) params["perPage"] = String(options.perPage);
898
+ if (options?.collectionName) params["collectionName"] = options.collectionName;
899
+ if (options?.fieldName) params["fieldName"] = options.fieldName;
900
+ if (options?.mime) params["mime"] = options.mime;
901
+ const data = await this.http.request("GET", "/files", void 0, { params });
902
+ return data ?? { items: [], page: 1, perPage: 50, total: 0 };
903
+ }
904
+ /**
905
+ * Fetch file metadata including URL.
906
+ * @param fileId The file ID.
907
+ */
750
908
  /**
751
909
  * Fetch file metadata including URL.
752
910
  * @param fileId The file ID.
@@ -776,6 +934,135 @@ var FilesService = class {
776
934
  }
777
935
  };
778
936
 
937
+ // src/collections.ts
938
+ var REGISTRY_TOPIC = "collections";
939
+ var CollectionsService = class {
940
+ /** @internal */
941
+ constructor(http, realtime) {
942
+ this.http = http;
943
+ this.realtime = realtime;
944
+ }
945
+ /**
946
+ * Fetch a paginated list of collections (admin).
947
+ *
948
+ * @param params Optional query params (`page`, `perPage`, `filter`, `sort`).
949
+ * @param options Optional request options.
950
+ */
951
+ async getList(params, options) {
952
+ const qs = params ? "?" + new URLSearchParams(
953
+ Object.fromEntries(
954
+ Object.entries(params).map(([k, v]) => [k, String(v)])
955
+ )
956
+ ).toString() : "";
957
+ return this.http?.get("/collections" + qs, options) ?? null;
958
+ }
959
+ /**
960
+ * Fetch all collections at once (auto-paginates). Mirrors PocketBase's
961
+ * `pb.collections.getFullList()` — defaults to listing everything.
962
+ *
963
+ * @param options Query params (`sort`, `batch`, etc.) or request options.
964
+ */
965
+ async getFullList(options) {
966
+ if (!this.http) return [];
967
+ const { batch = 1e3, ...rest } = options ?? {};
968
+ const items = [];
969
+ let page = 1;
970
+ for (; ; ) {
971
+ const res = await this.getList({
972
+ ...rest,
973
+ page,
974
+ perPage: batch
975
+ });
976
+ if (!res || !res.items || res.items.length === 0) break;
977
+ items.push(...res.items);
978
+ if (page >= (res.totalPages ?? page)) break;
979
+ page += 1;
980
+ }
981
+ return items;
982
+ }
983
+ /**
984
+ * Get a single collection by ID or name (admin).
985
+ *
986
+ * @param id Collection ID or name.
987
+ * @param options Optional request options.
988
+ */
989
+ async getOne(id, options) {
990
+ return this.http?.get("/collections/" + encodeURIComponent(id), options) ?? null;
991
+ }
992
+ /**
993
+ * Create a new collection (admin).
994
+ *
995
+ * @param data Collection definition (name, type, fields, options, rules, etc.).
996
+ * @param options Optional request options.
997
+ */
998
+ async create(data, options) {
999
+ return this.http?.post("/collections", data, options) ?? null;
1000
+ }
1001
+ /**
1002
+ * Update an existing collection (admin).
1003
+ *
1004
+ * @param id Collection ID or name.
1005
+ * @param data Updated collection fields.
1006
+ * @param options Optional request options.
1007
+ */
1008
+ async update(id, data, options) {
1009
+ return this.http?.patch(
1010
+ "/collections/" + encodeURIComponent(id),
1011
+ data,
1012
+ options
1013
+ ) ?? null;
1014
+ }
1015
+ /**
1016
+ * Delete a collection (admin).
1017
+ *
1018
+ * @param id Collection ID or name.
1019
+ * @param options Optional request options.
1020
+ */
1021
+ async delete(id, options) {
1022
+ const res = this.http?.delete(
1023
+ "/collections/" + encodeURIComponent(id),
1024
+ options
1025
+ );
1026
+ return res == null ? false : true;
1027
+ }
1028
+ /**
1029
+ * Subscribe to collection registry changes.
1030
+ *
1031
+ * @param callback Received on every collection create/update/delete.
1032
+ * @returns A function that unsubscribes this callback.
1033
+ */
1034
+ subscribe(callback) {
1035
+ if (!this.realtime) {
1036
+ console.warn("[lazypock] No realtime service configured.");
1037
+ return () => {
1038
+ };
1039
+ }
1040
+ const handler = (raw) => {
1041
+ callback({
1042
+ action: normalizeAction2(raw.event),
1043
+ collection: raw.payload ?? {},
1044
+ topic: raw.topic
1045
+ });
1046
+ };
1047
+ this.realtime.ensureConnected();
1048
+ this.realtime.subscribe(REGISTRY_TOPIC, handler);
1049
+ return () => this.realtime?.unsubscribe(REGISTRY_TOPIC, handler);
1050
+ }
1051
+ /**
1052
+ * Unsubscribe all callbacks from the registry channel.
1053
+ */
1054
+ unsubscribe() {
1055
+ this.realtime?.unsubscribe(REGISTRY_TOPIC);
1056
+ }
1057
+ };
1058
+ function normalizeAction2(event) {
1059
+ const e = event.toLowerCase();
1060
+ if (e === "create") return "create";
1061
+ if (e === "update") return "update";
1062
+ if (e === "delete") return "delete";
1063
+ return "update";
1064
+ }
1065
+
779
1066
  // src/lazypock.ts
780
1067
  var LazypockClient = class {
781
1068
  /**
@@ -792,6 +1079,7 @@ var LazypockClient = class {
792
1079
  this.realtime.setUrl(wsUrlFromBaseUrl(baseUrl));
793
1080
  }
794
1081
  this.files = new FilesService(this.http);
1082
+ this.collections = new CollectionsService(this.http, this.realtime);
795
1083
  if (options.types?.schemas) {
796
1084
  this.schemaByName = new Map(
797
1085
  options.types.schemas.map((s) => [s.name, s])
@@ -841,6 +1129,37 @@ var LazypockClient = class {
841
1129
  const schemas = this.schemaByName ? [...this.schemaByName.values()] : [];
842
1130
  return generateTypes(schemas, options);
843
1131
  }
1132
+ // ── Auto-cancellation (PocketBase `autoCancellation` parity) ──
1133
+ /**
1134
+ * Globally enable or disable auto-cancellation of duplicated pending requests.
1135
+ *
1136
+ * When enabled (default), a new request whose `requestKey` (default
1137
+ * `HTTP_METHOD + path`) matches a still-pending request aborts the previous
1138
+ * one — only the last duplicate executes.
1139
+ *
1140
+ * @example
1141
+ * ```ts
1142
+ * client.autoCancellation(false); // keep every request
1143
+ * ```
1144
+ */
1145
+ autoCancellation(enable) {
1146
+ this.http.autoCancellation(enable);
1147
+ return this;
1148
+ }
1149
+ /**
1150
+ * Abort a single pending request by its cancellation key
1151
+ * (default `HTTP_METHOD + path`, e.g. `"GET /api/posts?page=1"`).
1152
+ * The request rejects with an `ApiError` whose `isAbort` is `true`.
1153
+ */
1154
+ cancelRequest(requestKey) {
1155
+ this.http.cancelRequest(requestKey);
1156
+ return this;
1157
+ }
1158
+ /** Abort all pending requests. */
1159
+ cancelAllRequests() {
1160
+ this.http.cancelAllRequests();
1161
+ return this;
1162
+ }
844
1163
  // ── Auth ──
845
1164
  /** Check whether any superuser exists (for login vs setup screen routing). */
846
1165
  async checkSuperuser() {
@@ -952,129 +1271,6 @@ var LazypockClient = class {
952
1271
  health(options) {
953
1272
  return this.http.get("/health", options);
954
1273
  }
955
- // ── Collection Management (admin) ──
956
- /**
957
- * List all collections (admin).
958
- * @param q URL query string (e.g. `page=1&perPage=200`).
959
- * @param options Optional request options.
960
- */
961
- listCollections(q, options) {
962
- return this.http.get(
963
- "/collections" + (q ? "?" + q : ""),
964
- options
965
- );
966
- }
967
- /**
968
- * Get a single collection by ID or name.
969
- * @param id Collection ID or name.
970
- * @param options Optional request options.
971
- */
972
- getCollection(id, options) {
973
- return this.http.get(
974
- "/collections/" + encodeURIComponent(id),
975
- options
976
- );
977
- }
978
- /**
979
- * Create a new collection (admin).
980
- * @param data Collection definition (name, type, fields, options, rules, etc.).
981
- * @param options Optional request options.
982
- */
983
- createCollection(data, options) {
984
- return this.http.post("/collections", data, options);
985
- }
986
- /**
987
- * Update an existing collection (admin).
988
- * @param id Collection ID or name.
989
- * @param data Updated collection fields.
990
- * @param options Optional request options.
991
- */
992
- updateCollection(id, data, options) {
993
- return this.http.patch(
994
- "/collections/" + encodeURIComponent(id),
995
- data,
996
- options
997
- );
998
- }
999
- /**
1000
- * Delete a collection (admin).
1001
- * @param id Collection ID or name.
1002
- * @param options Optional request options.
1003
- */
1004
- deleteCollection(id, options) {
1005
- return this.http.delete("/collections/" + encodeURIComponent(id), options);
1006
- }
1007
- // ── Records (dynamic collection) ──
1008
- /**
1009
- * List records from a dynamic collection with optional filter/sort/pagination.
1010
- *
1011
- * @param coll Collection name.
1012
- * @param params Query parameters including:
1013
- * - `filter` — PocketBase filter syntax (e.g. `title~'hello' && published=true`)
1014
- * - `sort` — Comma-separated, `-` prefix for DESC (e.g. `-created,title`)
1015
- * - `page` — Page number (default: 1)
1016
- * - `perPage` — Items per page (default: 30, max: 200)
1017
- * - `expand` — Comma-separated relation fields (e.g. `author,category`)
1018
- * @param options Optional request options.
1019
- */
1020
- listRecords(coll, params, options) {
1021
- const qs = params ? "?" + new URLSearchParams(params).toString() : "";
1022
- return this.http.get(
1023
- "/" + encodeURIComponent(coll) + qs,
1024
- options
1025
- );
1026
- }
1027
- /**
1028
- * Get a single record by ID.
1029
- * @param coll Collection name.
1030
- * @param id Record ID.
1031
- * @param options Optional request options.
1032
- */
1033
- getRecord(coll, id, options) {
1034
- return this.http.get(
1035
- "/" + encodeURIComponent(coll) + "/" + encodeURIComponent(id),
1036
- options
1037
- );
1038
- }
1039
- /**
1040
- * Create a record in a dynamic collection.
1041
- * @param coll Collection name.
1042
- * @param data Record fields.
1043
- * @param options Optional request options.
1044
- */
1045
- createRecord(coll, data, options) {
1046
- return this.http.post(
1047
- "/" + encodeURIComponent(coll),
1048
- data,
1049
- options
1050
- );
1051
- }
1052
- /**
1053
- * Update a record in a dynamic collection.
1054
- * @param coll Collection name.
1055
- * @param id Record ID.
1056
- * @param data Updated record fields.
1057
- * @param options Optional request options.
1058
- */
1059
- updateRecord(coll, id, data, options) {
1060
- return this.http.patch(
1061
- "/" + encodeURIComponent(coll) + "/" + encodeURIComponent(id),
1062
- data,
1063
- options
1064
- );
1065
- }
1066
- /**
1067
- * Delete a record from a dynamic collection.
1068
- * @param coll Collection name.
1069
- * @param id Record ID.
1070
- * @param options Optional request options.
1071
- */
1072
- deleteRecord(coll, id, options) {
1073
- return this.http.delete(
1074
- "/" + encodeURIComponent(coll) + "/" + encodeURIComponent(id),
1075
- options
1076
- );
1077
- }
1078
1274
  };
1079
1275
 
1080
1276
  // src/client.ts
@@ -1090,7 +1286,9 @@ export {
1090
1286
  ApiError,
1091
1287
  AuthStore,
1092
1288
  CollectionService,
1289
+ CollectionsService,
1093
1290
  FilesService,
1291
+ HttpClient,
1094
1292
  LazypockClient,
1095
1293
  RealtimeService,
1096
1294
  TypedClient,
@@ -1100,6 +1298,8 @@ export {
1100
1298
  fieldTypeScriptType,
1101
1299
  generateTypes,
1102
1300
  getFileUrl,
1301
+ getScaleUrl,
1302
+ getThumbUrl,
1103
1303
  schemaFieldType,
1104
1304
  wsUrlFromBaseUrl
1105
1305
  };