lazypock 0.20.0 → 0.20.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
@@ -67,15 +67,20 @@ var HttpClient = class {
67
67
  *
68
68
  * A network failure keeps the session (the next request can retry); only a refusal
69
69
  * by the server ends it.
70
+ *
71
+ * `fetcher` is the per-request `options.fetch` override, so a caller (or a test)
72
+ * that injected its own transport also intercepts the refresh. Falling back to
73
+ * the global fetch here meant those callers — React Native and the test suite —
74
+ * silently did not cover this path at all.
70
75
  */
71
- async refreshAuth() {
76
+ async refreshAuth(fetcher) {
72
77
  const refreshToken = this.authStore.refreshToken;
73
78
  if (!refreshToken) return null;
74
79
  if (this.refreshInFlight) {
75
80
  const refreshed = await this.refreshInFlight;
76
81
  return refreshed ? this.currentAuthResponse() : null;
77
82
  }
78
- this.refreshInFlight = this.performRefresh(refreshToken);
83
+ this.refreshInFlight = this.performRefresh(refreshToken, fetcher);
79
84
  try {
80
85
  const refreshed = await this.refreshInFlight;
81
86
  return refreshed ? this.currentAuthResponse() : null;
@@ -87,13 +92,18 @@ var HttpClient = class {
87
92
  currentAuthResponse() {
88
93
  return {
89
94
  token: this.authStore.token,
95
+ // SAFETY: `AuthModel` is an index-signature interface (`[key: string]:
96
+ // unknown`), so its values are readable as a plain property bag; the
97
+ // `{}` fallback preserves the "no model, empty record" contract of the
98
+ // response shape this mirrors. The cast only bridges the empty-object
99
+ // literal, which TypeScript gives no index signature.
90
100
  record: this.authStore.model ?? {}
91
101
  };
92
102
  }
93
- async performRefresh(refreshToken) {
103
+ async performRefresh(refreshToken, fetcher) {
94
104
  const collection = this.refreshCollection();
95
105
  try {
96
- const res = await this.defaultFetch(
106
+ const res = await (fetcher ?? this.defaultFetch)(
97
107
  this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
98
108
  {
99
109
  method: "POST",
@@ -181,7 +191,7 @@ var HttpClient = class {
181
191
  */
182
192
  async request(method, path, body, options) {
183
193
  if (this.authStore.isExpired && this.authStore.refreshToken) {
184
- await this.refreshAuth();
194
+ await this.refreshAuth(options?.fetch);
185
195
  }
186
196
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
187
197
  if (options?.autoCancel === false) requestKey = null;
@@ -292,7 +302,7 @@ var HttpClient = class {
292
302
  if (res.status === 401 && this.authStore.refreshToken) {
293
303
  await res.text().catch(() => {
294
304
  });
295
- const refreshed = await this.refreshAuth();
305
+ const refreshed = await this.refreshAuth(options?.fetch);
296
306
  if (refreshed) {
297
307
  headers["Authorization"] = "Bearer " + this.authStore.token;
298
308
  try {
@@ -499,6 +509,29 @@ var AuthStore = class {
499
509
  ]);
500
510
  this.notify();
501
511
  }
512
+ /**
513
+ * Replace the cached auth model **without** touching the token, its recorded
514
+ * expiry, or the refresh token.
515
+ *
516
+ * Use this when a read refreshes the identity record (e.g. `me()`, or the
517
+ * server echoing the record back). Routing that through {@link set} would
518
+ * overwrite the access token's real `expiresIn` with the 7-day fallback TTL,
519
+ * so `isExpired` stays false long past the real 15-minute lifetime and the
520
+ * proactive refresh never fires — every request then pays a 401 + retry.
521
+ *
522
+ * @param model The authenticated user record, or null for superusers.
523
+ */
524
+ setModel(model) {
525
+ this._model = model;
526
+ if (!this._collectionName && model && typeof model.collectionName === "string") {
527
+ this._collectionName = model.collectionName;
528
+ }
529
+ void Promise.all([
530
+ model ? this.storage.set("auth_model", JSON.stringify(model)) : this.storage.remove("auth_model"),
531
+ this.persistCollectionName()
532
+ ]);
533
+ this.notify();
534
+ }
502
535
  /**
503
536
  * Record a complete auth response: token, model, refresh token and the access
504
537
  * token's real lifetime.
@@ -726,6 +759,377 @@ var FilterBuilder = class {
726
759
  }
727
760
  };
728
761
 
762
+ // src/projection.ts
763
+ var SYSTEM_FIELDS = [
764
+ "id",
765
+ "created",
766
+ "updated",
767
+ "collectionId",
768
+ "collectionName"
769
+ ];
770
+ var visibleFieldsCache = /* @__PURE__ */ new WeakMap();
771
+ function visibleFields(schema) {
772
+ if (!schema?.fields) return void 0;
773
+ const cached = visibleFieldsCache.get(schema);
774
+ if (cached !== void 0 || visibleFieldsCache.has(schema)) return cached;
775
+ const visible = schema.fields.filter(
776
+ (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
777
+ ).map((f) => f.name);
778
+ const result = visible.length === 0 ? void 0 : (
779
+ // Dedupe in case a schema ever names a field after a system key.
780
+ [
781
+ .../* @__PURE__ */ new Set([...SYSTEM_FIELDS, ...visible])
782
+ ].join(",")
783
+ );
784
+ visibleFieldsCache.set(schema, result);
785
+ return result;
786
+ }
787
+ function effectiveFields(schema, preset, optionsFields) {
788
+ if (optionsFields !== void 0) return optionsFields;
789
+ if (preset !== void 0) {
790
+ return preset === "*" ? visibleFields(schema) : preset;
791
+ }
792
+ return visibleFields(schema);
793
+ }
794
+ function mergeExpandFields(base, info) {
795
+ if (info.fieldSelectors.length === 0) return base;
796
+ if (base === void 0) return void 0;
797
+ const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
798
+ const seen = new Set(parts);
799
+ const push = (value) => {
800
+ if (seen.has(value)) return;
801
+ seen.add(value);
802
+ parts.push(value);
803
+ };
804
+ const fullKeys = /* @__PURE__ */ new Set();
805
+ for (const selector of info.fieldSelectors) {
806
+ const seg = selector.split(".");
807
+ if (seg.length === 2) fullKeys.add(seg[1]);
808
+ }
809
+ for (const selector of info.fieldSelectors) {
810
+ const seg = selector.split(".");
811
+ if (seg.length > 2 && fullKeys.has(seg[1])) continue;
812
+ if (seg.length >= 2) push(seg[1]);
813
+ push(selector);
814
+ }
815
+ return parts.join(",");
816
+ }
817
+
818
+ // src/expand.ts
819
+ function pickFields(value, fields) {
820
+ if (!value || typeof value !== "object") return {};
821
+ const src = value;
822
+ const out = {};
823
+ for (const f of fields) {
824
+ if (f in src) out[f] = src[f];
825
+ }
826
+ return out;
827
+ }
828
+ function resolveTargetCollection(field, ctx) {
829
+ const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
830
+ if (!key) return void 0;
831
+ return ctx.resolveCollection(String(key));
832
+ }
833
+ function resolveRelationChain(segments, ctx) {
834
+ let currentFields = ctx.schema?.fields;
835
+ if (!currentFields) return { depth: 0, canInspect: false };
836
+ for (let i = 0; i < segments.length; i++) {
837
+ const field = currentFields.find((f) => f.name === segments[i]);
838
+ if (!field || field.type !== "relation") {
839
+ return { depth: i, canInspect: true };
840
+ }
841
+ if (i === segments.length - 1) {
842
+ return { depth: segments.length, canInspect: true };
843
+ }
844
+ const target = resolveTargetCollection(field, ctx);
845
+ if (!target?.fields) {
846
+ return { depth: i + 1, canInspect: false };
847
+ }
848
+ currentFields = target.fields;
849
+ }
850
+ return { depth: segments.length, canInspect: true };
851
+ }
852
+ function warnNonRelation(name, ctx) {
853
+ console.warn(
854
+ `[lazypock] expand("${name}"): field is not a relation on collection "${ctx.collectionName}"`
855
+ );
856
+ }
857
+ function normalizeExpand(expand, ctx) {
858
+ const narrow = /* @__PURE__ */ new Map();
859
+ if (!expand) return { fieldSelectors: [], narrow };
860
+ const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
861
+ if (tokens.length === 0) return { fieldSelectors: [], narrow };
862
+ const relations = ctx.schema?.fields ? new Set(
863
+ ctx.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
864
+ ) : void 0;
865
+ const parsed = [];
866
+ for (const token of tokens) {
867
+ const segments = token.split(".").filter(Boolean);
868
+ const base = segments[0] ?? token;
869
+ if (segments.length <= 1) {
870
+ if (relations && !relations.has(base)) {
871
+ warnNonRelation(base, ctx);
872
+ }
873
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
874
+ continue;
875
+ }
876
+ if (!relations) {
877
+ parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
878
+ continue;
879
+ }
880
+ const { depth, canInspect } = resolveRelationChain(segments, ctx);
881
+ if (depth === 0) {
882
+ warnNonRelation(base, ctx);
883
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
884
+ } else if (depth === segments.length) {
885
+ parsed.push({ token, base, segments, kind: "nested", depth });
886
+ } else if (canInspect) {
887
+ parsed.push({ token, base, segments, kind: "narrow", depth });
888
+ } else {
889
+ parsed.push({ token, base, segments, kind: "unknown", depth });
890
+ }
891
+ }
892
+ const byBase = /* @__PURE__ */ new Map();
893
+ for (const t of parsed) {
894
+ const arr = byBase.get(t.base);
895
+ if (arr) arr.push(t);
896
+ else byBase.set(t.base, [t]);
897
+ }
898
+ for (const [base, group] of byBase) {
899
+ const unknowns = group.filter((t) => t.kind === "unknown");
900
+ if (unknowns.length === 0) continue;
901
+ const distinct = new Set(unknowns.map((t) => t.token));
902
+ const hasNarrow = group.some((t) => t.kind === "narrow");
903
+ if (!hasNarrow && distinct.size < 2) {
904
+ for (const t of unknowns) {
905
+ t.kind = "nested";
906
+ console.warn(
907
+ `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
908
+ );
909
+ }
910
+ } else {
911
+ for (const t of unknowns) t.kind = "narrow";
912
+ }
913
+ }
914
+ const expandParams = [];
915
+ const expandSeen = /* @__PURE__ */ new Set();
916
+ const fieldSelectors = [];
917
+ const selectorSeen = /* @__PURE__ */ new Set();
918
+ const pushParam = (p) => {
919
+ if (!expandSeen.has(p)) {
920
+ expandSeen.add(p);
921
+ expandParams.push(p);
922
+ }
923
+ };
924
+ const pushSelector = (s) => {
925
+ if (!selectorSeen.has(s)) {
926
+ selectorSeen.add(s);
927
+ fieldSelectors.push(s);
928
+ }
929
+ };
930
+ for (const t of parsed) {
931
+ if (t.kind === "plain") {
932
+ pushParam(t.token);
933
+ pushSelector(`expand.${t.token}`);
934
+ } else if (t.kind === "nested") {
935
+ for (let i = 1; i <= t.segments.length; i++) {
936
+ pushParam(t.segments.slice(0, i).join("."));
937
+ }
938
+ pushSelector(`expand.${t.segments[0]}`);
939
+ } else {
940
+ const depth = Math.max(1, t.depth);
941
+ const relationPath = t.segments.slice(0, depth).join(".");
942
+ pushParam(relationPath);
943
+ pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
944
+ if (t.segments.length === depth + 1) {
945
+ const base = t.segments[0];
946
+ const leaf = t.segments[depth];
947
+ const leaves = narrow.get(base) ?? [];
948
+ if (!leaves.includes(leaf)) leaves.push(leaf);
949
+ narrow.set(base, leaves);
950
+ }
951
+ }
952
+ }
953
+ return {
954
+ expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
955
+ fieldSelectors,
956
+ narrow
957
+ };
958
+ }
959
+ function applyExpandNarrowing(record, narrow) {
960
+ if (narrow.size === 0) return record;
961
+ const rec = record;
962
+ const expand = rec.expand;
963
+ if (!expand || typeof expand !== "object") return record;
964
+ const next = { ...expand };
965
+ for (const [relation, leaves] of narrow) {
966
+ const value = next[relation];
967
+ if (value === void 0 || value === null) continue;
968
+ next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
969
+ }
970
+ return { ...rec, expand: next };
971
+ }
972
+
973
+ // src/query-params.ts
974
+ var MAX_PER_PAGE = 500;
975
+ function clampBatch(batch) {
976
+ if (!Number.isFinite(batch)) return MAX_PER_PAGE;
977
+ return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
978
+ }
979
+ var TRANSPORT_KEYS = /* @__PURE__ */ new Set(["requestKey", "singleFlight", "fetch", "signal"]);
980
+ function stableStringify(value) {
981
+ const path = /* @__PURE__ */ new Set();
982
+ const sort = (v, topLevel) => {
983
+ if (Array.isArray(v)) return v.map((el) => sort(el, false));
984
+ if (v && typeof v === "object") {
985
+ const obj = v;
986
+ if (path.has(obj)) return "[Circular]";
987
+ path.add(obj);
988
+ const out = {};
989
+ for (const k of Object.keys(obj).sort()) {
990
+ if (topLevel && TRANSPORT_KEYS.has(k)) continue;
991
+ out[k] = sort(obj[k], false);
992
+ }
993
+ path.delete(obj);
994
+ return out;
995
+ }
996
+ return v;
997
+ };
998
+ try {
999
+ return JSON.stringify(sort(value, true));
1000
+ } catch {
1001
+ return String(value);
1002
+ }
1003
+ }
1004
+
1005
+ // src/paginate.ts
1006
+ var TRANSPORT_KEYS2 = /* @__PURE__ */ new Set([
1007
+ "requestKey",
1008
+ "autoCancel",
1009
+ "cancelKey",
1010
+ "singleFlight",
1011
+ "fetch",
1012
+ "headers",
1013
+ "signal",
1014
+ "params"
1015
+ ]);
1016
+ function splitListOptions(options) {
1017
+ const {
1018
+ batch: requestedBatch = MAX_PER_PAGE,
1019
+ page: _page,
1020
+ perPage: _perPage,
1021
+ ...rest
1022
+ } = options ?? {};
1023
+ const query = {};
1024
+ const transport = {};
1025
+ for (const [key, value] of Object.entries(rest)) {
1026
+ if (TRANSPORT_KEYS2.has(key)) transport[key] = value;
1027
+ else query[key] = value;
1028
+ }
1029
+ return {
1030
+ query,
1031
+ transport,
1032
+ batch: clampBatch(requestedBatch)
1033
+ };
1034
+ }
1035
+ function fullListKey(scope, query, requestKey) {
1036
+ if (typeof requestKey === "string") return requestKey;
1037
+ return `getFullList:${scope}:${stableStringify(query)}`;
1038
+ }
1039
+ async function paginateAll(batch, fetchPage) {
1040
+ const items = [];
1041
+ let page = 1;
1042
+ for (; ; ) {
1043
+ const res = await fetchPage(page, batch);
1044
+ if (!res || !res.items || res.items.length === 0) break;
1045
+ items.push(...res.items);
1046
+ if (page >= (res.totalPages ?? page)) break;
1047
+ page += 1;
1048
+ }
1049
+ return items;
1050
+ }
1051
+
1052
+ // src/collection/query.ts
1053
+ function buildListQuery(ctx, page, perPage, queryParams) {
1054
+ if (Array.isArray(queryParams.sort)) {
1055
+ queryParams.sort = queryParams.sort.join(",");
1056
+ }
1057
+ if (Array.isArray(queryParams.expand)) {
1058
+ queryParams.expand = queryParams.expand.join(",");
1059
+ }
1060
+ if (typeof queryParams.filter === "function") {
1061
+ queryParams.filter = ctx.resolveFilter(queryParams.filter);
1062
+ }
1063
+ const expandInfo = normalizeExpand(
1064
+ typeof queryParams.expand === "string" ? queryParams.expand : void 0,
1065
+ ctx.expand
1066
+ );
1067
+ if (expandInfo.expand !== void 0) {
1068
+ queryParams.expand = expandInfo.expand;
1069
+ }
1070
+ const fields = mergeExpandFields(
1071
+ ctx.effectiveFields(queryParams.fields),
1072
+ expandInfo
1073
+ );
1074
+ if (fields !== void 0) {
1075
+ queryParams.fields = fields;
1076
+ }
1077
+ const qs = new URLSearchParams(
1078
+ Object.fromEntries(
1079
+ Object.entries({
1080
+ // `page`/`perPage` are spread LAST so the call's positional arguments
1081
+ // win: with the caller's keys last, `getList(2, 30, { page: 5 })`
1082
+ // silently requested page 5, and `getFullList({ perPage: 1000 })`
1083
+ // slipped a >500 `perPage` past `clampBatch`.
1084
+ ...queryParams,
1085
+ page: String(page),
1086
+ perPage: String(perPage)
1087
+ }).map(([k, v]) => [k, String(v)])
1088
+ )
1089
+ ).toString();
1090
+ return { qs, narrow: expandInfo.narrow };
1091
+ }
1092
+ function buildReadQuery(ctx, options) {
1093
+ const rawExpand = Array.isArray(options?.expand) ? options.expand.join(",") : typeof options?.expand === "string" ? options.expand : void 0;
1094
+ const expandInfo = normalizeExpand(rawExpand, ctx.expand);
1095
+ const fields = mergeExpandFields(
1096
+ ctx.effectiveFields(options?.fields),
1097
+ expandInfo
1098
+ );
1099
+ const qs = new URLSearchParams();
1100
+ if (fields !== void 0) qs.set("fields", fields);
1101
+ if (rawExpand !== void 0) qs.set("expand", expandInfo.expand ?? rawExpand);
1102
+ return { qs: qs.toString(), narrow: expandInfo.narrow };
1103
+ }
1104
+
1105
+ // src/collection/paths.ts
1106
+ function encodeId(id) {
1107
+ return encodeURIComponent(id);
1108
+ }
1109
+ function recordsPath(collectionName) {
1110
+ return "/collections/" + encodeId(collectionName) + "/records";
1111
+ }
1112
+ function collectionPath(collectionName) {
1113
+ return "/collections/" + encodeId(collectionName);
1114
+ }
1115
+
1116
+ // src/collection/session.ts
1117
+ function rememberSession(ctx, data, model) {
1118
+ if (!data || !ctx.authStore) return;
1119
+ ctx.authStore.setCollectionName(ctx.collectionName);
1120
+ rememberAuthResponse(ctx.authStore, data, model);
1121
+ }
1122
+ function rememberSessionRecord(ctx, data) {
1123
+ const record = data?.["record"];
1124
+ const model = record && typeof record === "object" ? record : null;
1125
+ rememberSession(ctx, data, model);
1126
+ }
1127
+ async function postWithSession(ctx, path, body, options) {
1128
+ const data = await ctx.http.post(path, body, options);
1129
+ rememberSessionRecord(ctx, data);
1130
+ return data;
1131
+ }
1132
+
729
1133
  // src/oauth2.ts
730
1134
  var DEFAULT_POPUP_WIDTH = 500;
731
1135
  var DEFAULT_POPUP_HEIGHT = 700;
@@ -914,35 +1318,140 @@ function authorizeWithOAuth2Popup(opts) {
914
1318
  });
915
1319
  }
916
1320
 
917
- // src/collection.ts
918
- var MAX_PER_PAGE = 500;
919
- function clampBatch(batch) {
920
- if (!Number.isFinite(batch)) return MAX_PER_PAGE;
921
- return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
1321
+ // src/collection/auth.ts
1322
+ function authWithPassword(ctx, identity, password, options) {
1323
+ return postWithSession(
1324
+ ctx,
1325
+ collectionPath(ctx.collectionName) + "/auth-with-password",
1326
+ { identity, password },
1327
+ options
1328
+ );
922
1329
  }
923
- function stableStringify(value) {
924
- const seen = /* @__PURE__ */ new Set();
925
- const sort = (v) => {
926
- if (Array.isArray(v)) return v.map(sort);
927
- if (v && typeof v === "object") {
928
- if (seen.has(v)) return "[Circular]";
929
- seen.add(v);
930
- const out = {};
931
- for (const k of Object.keys(v).sort()) {
932
- if (k === "requestKey" || k === "singleFlight" || k === "fetch" || k === "signal") {
933
- continue;
934
- }
935
- out[k] = sort(v[k]);
936
- }
937
- return out;
1330
+ function authRefresh(ctx, options) {
1331
+ return postWithSession(
1332
+ ctx,
1333
+ collectionPath(ctx.collectionName) + "/auth-refresh",
1334
+ { refreshToken: ctx.authStore?.refreshToken },
1335
+ options
1336
+ );
1337
+ }
1338
+ function listAuthMethods(ctx, options) {
1339
+ return ctx.http.get(
1340
+ collectionPath(ctx.collectionName) + "/auth-methods",
1341
+ options
1342
+ );
1343
+ }
1344
+ async function requestPasswordReset(ctx, email, options) {
1345
+ await ctx.http.post(
1346
+ collectionPath(ctx.collectionName) + "/request-password-reset",
1347
+ { email },
1348
+ options
1349
+ );
1350
+ return true;
1351
+ }
1352
+ async function confirmPasswordReset(ctx, passwordResetToken, password, passwordConfirm, options) {
1353
+ await ctx.http.post(
1354
+ collectionPath(ctx.collectionName) + "/confirm-password-reset",
1355
+ { token: passwordResetToken, password, passwordConfirm },
1356
+ options
1357
+ );
1358
+ return true;
1359
+ }
1360
+ async function requestVerification(ctx, email, options) {
1361
+ await ctx.http.post(
1362
+ collectionPath(ctx.collectionName) + "/request-verification",
1363
+ { email },
1364
+ options
1365
+ );
1366
+ return true;
1367
+ }
1368
+ async function confirmVerification(ctx, verificationToken, options) {
1369
+ const data = await ctx.http.post(
1370
+ collectionPath(ctx.collectionName) + "/confirm-verification",
1371
+ { token: verificationToken },
1372
+ options
1373
+ );
1374
+ return data?.record ?? null;
1375
+ }
1376
+ async function requestEmailChange(ctx, newEmail, options) {
1377
+ await ctx.http.post(
1378
+ collectionPath(ctx.collectionName) + "/request-email-change",
1379
+ { newEmail },
1380
+ options
1381
+ );
1382
+ return true;
1383
+ }
1384
+ async function confirmEmailChange(ctx, emailChangeToken, password, options) {
1385
+ const data = await ctx.http.post(
1386
+ collectionPath(ctx.collectionName) + "/confirm-email-change",
1387
+ { token: emailChangeToken, password },
1388
+ options
1389
+ );
1390
+ return data?.record ?? null;
1391
+ }
1392
+ async function authWithOAuth2(ctx, options) {
1393
+ const {
1394
+ provider,
1395
+ createData,
1396
+ urlCallback,
1397
+ popup,
1398
+ timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1399
+ } = options;
1400
+ const methods = await listAuthMethods(ctx);
1401
+ const providerInfo = methods?.oauth2?.providers?.find(
1402
+ (p) => p.name === provider
1403
+ );
1404
+ if (!providerInfo) {
1405
+ throw new ApiError(
1406
+ `OAuth2 provider "${provider}" is not enabled for this collection.`,
1407
+ methods ?? {},
1408
+ 400,
1409
+ false,
1410
+ "oauth2_unknown_provider"
1411
+ );
1412
+ }
1413
+ const { code } = await authorizeWithOAuth2Popup({
1414
+ authURL: providerInfo.authURL,
1415
+ expectedOrigin: oauth2RedirectOrigin(ctx.http.baseUrl),
1416
+ urlCallback,
1417
+ popup,
1418
+ timeoutMs
1419
+ });
1420
+ return authWithOAuth2Code(ctx, {
1421
+ provider,
1422
+ code,
1423
+ codeVerifier: providerInfo.codeVerifier,
1424
+ createData
1425
+ });
1426
+ }
1427
+ async function authWithOAuth2Code(ctx, options) {
1428
+ const { provider, code, codeVerifier, redirectUrl, createData } = options;
1429
+ const data = await ctx.http.post(
1430
+ collectionPath(ctx.collectionName) + "/auth-with-oauth2",
1431
+ {
1432
+ provider,
1433
+ code,
1434
+ codeVerifier,
1435
+ redirectUrl: redirectUrl ?? ctx.http.baseUrl + "/oauth2-redirect",
1436
+ createData: createData ?? {}
938
1437
  }
939
- return v;
940
- };
941
- try {
942
- return JSON.stringify(sort(value));
943
- } catch {
944
- return String(value);
1438
+ );
1439
+ if (!data) {
1440
+ throw new ApiError(
1441
+ "OAuth2 code exchange returned no data.",
1442
+ {},
1443
+ 0,
1444
+ false,
1445
+ "oauth2_exchange_failed"
1446
+ );
945
1447
  }
1448
+ rememberSessionRecord(ctx, data);
1449
+ return data;
1450
+ }
1451
+
1452
+ // src/collection/realtime.ts
1453
+ function collectionTopic(collectionName) {
1454
+ return "collection:" + collectionName;
946
1455
  }
947
1456
  function normalizeAction(event, rawAction) {
948
1457
  if (typeof rawAction === "string") {
@@ -956,15 +1465,49 @@ function normalizeAction(event, rawAction) {
956
1465
  if (event === "delete" || event === "record_delete") return "delete";
957
1466
  return "update";
958
1467
  }
959
- function pickFields(value, fields) {
960
- if (!value || typeof value !== "object") return {};
961
- const src = value;
962
- const out = {};
963
- for (const f of fields) {
964
- if (f in src) out[f] = src[f];
1468
+ function subscribeToCollection(ctx, topicOrCallback, maybeCallback, options) {
1469
+ const { realtime, collectionName } = ctx;
1470
+ if (!realtime) {
1471
+ console.warn("[lazypock] No realtime service configured.");
1472
+ return () => {
1473
+ };
965
1474
  }
966
- return out;
1475
+ let recordId;
1476
+ let callback;
1477
+ let joinPayload;
1478
+ if (typeof topicOrCallback === "function") {
1479
+ callback = topicOrCallback;
1480
+ if (typeof maybeCallback === "string") recordId = maybeCallback;
1481
+ } else {
1482
+ callback = maybeCallback;
1483
+ recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1484
+ const { headers: _ignored, ...rest } = options ?? {};
1485
+ if (Object.keys(rest).length > 0) joinPayload = rest;
1486
+ }
1487
+ const topic = collectionTopic(collectionName) + (recordId ? ":" + recordId : "");
1488
+ const handler = (raw) => {
1489
+ const record = raw.payload?.["record"] ?? {};
1490
+ callback({
1491
+ action: normalizeAction(raw.event, raw.payload?.["action"]),
1492
+ record,
1493
+ topic: raw.topic
1494
+ });
1495
+ };
1496
+ realtime.ensureConnected();
1497
+ realtime.subscribe(topic, handler, joinPayload);
1498
+ return () => realtime.unsubscribe(topic, handler);
1499
+ }
1500
+ function unsubscribeFromCollection(ctx, recordId) {
1501
+ const { realtime, collectionName } = ctx;
1502
+ if (recordId === void 0) {
1503
+ realtime?.unsubscribeByPrefix(collectionTopic(collectionName));
1504
+ return;
1505
+ }
1506
+ const topic = collectionTopic(collectionName) + (recordId === "*" ? "" : ":" + recordId);
1507
+ realtime?.unsubscribe(topic);
967
1508
  }
1509
+
1510
+ // src/collection/index.ts
968
1511
  var CollectionService = class _CollectionService {
969
1512
  /** @internal */
970
1513
  constructor(http, collectionName, authStore, realtime, schema, schemaResolver) {
@@ -975,21 +1518,42 @@ var CollectionService = class _CollectionService {
975
1518
  this.schema = schema;
976
1519
  this.schemaResolver = schemaResolver;
977
1520
  }
978
- encodeId(id) {
979
- return encodeURIComponent(id);
980
- }
981
1521
  /**
982
- * The records endpoint for this collection.
1522
+ * A copy of this service with the given overrides applied.
983
1523
  *
984
- * Centralised because the server's shape is `/api/collections/<name>/records`,
985
- * and a path repeated eighteen times is a path that drifts.
1524
+ * Every field is listed exactly once, so a new service-level field can't be
1525
+ * silently dropped by `select()` or `withSchema()`.
986
1526
  */
1527
+ derive(patch = {}) {
1528
+ const derived = new _CollectionService(
1529
+ this.http,
1530
+ this.collectionName,
1531
+ this.authStore,
1532
+ this.realtime,
1533
+ patch.schema ?? this.schema,
1534
+ this.schemaResolver
1535
+ );
1536
+ derived.fieldsPreset = patch.fieldsPreset ?? this.fieldsPreset;
1537
+ return derived;
1538
+ }
1539
+ /** The records endpoint for this collection. */
987
1540
  recordsPath() {
988
- return "/collections/" + this.encodeId(this.collectionName) + "/records";
1541
+ return recordsPath(this.collectionName);
989
1542
  }
990
1543
  /** The collection's own endpoint, which is where its auth routes live. */
991
1544
  collectionPath() {
992
- return "/collections/" + this.encodeId(this.collectionName);
1545
+ return collectionPath(this.collectionName);
1546
+ }
1547
+ encodeId(id) {
1548
+ return encodeId(id);
1549
+ }
1550
+ /** What the auth routes need: transport, collection name, session store. */
1551
+ sessionContext() {
1552
+ return {
1553
+ http: this.http,
1554
+ collectionName: this.collectionName,
1555
+ authStore: this.authStore
1556
+ };
993
1557
  }
994
1558
  // ── Field projection (`.select`) ──
995
1559
  /**
@@ -1004,10 +1568,10 @@ var CollectionService = class _CollectionService {
1004
1568
  * const t = await client.collection("posts").select("id", "title").getList();
1005
1569
  * // GET /api/posts?fields=id,title
1006
1570
  *
1007
- * // All visible fields (implicit system keys id/created/updated/… are
1571
+ * // All visible fields (implicit system keys id/created/updated/... are
1008
1572
  * // kept; hidden fields are excluded via the projection)
1009
1573
  * const all = await client.collection("posts").select("*").getList();
1010
- * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,… (schema known)
1574
+ * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,... (schema known)
1011
1575
  * ```
1012
1576
  *
1013
1577
  * When no schema is known, the default (no `select()` call) sends no
@@ -1016,17 +1580,12 @@ var CollectionService = class _CollectionService {
1016
1580
  */
1017
1581
  select(...fields) {
1018
1582
  const preset = fields.length === 0 ? "*" : fields.join(",");
1019
- const derived = new _CollectionService(
1020
- this.http,
1021
- this.collectionName,
1022
- this.authStore,
1023
- this.realtime,
1024
- this.schema,
1025
- this.schemaResolver
1026
- );
1027
- derived.fieldsPreset = preset;
1583
+ const derived = this.derive({ fieldsPreset: preset });
1028
1584
  if (this.schema && preset !== "*") {
1029
- const known = new Set(this.schema.fields?.map((f) => f.name) ?? []);
1585
+ const known = /* @__PURE__ */ new Set([
1586
+ ...SYSTEM_FIELDS,
1587
+ ...this.schema.fields?.map((f) => f.name) ?? []
1588
+ ]);
1030
1589
  for (const f of fields) {
1031
1590
  if (!known.has(f)) {
1032
1591
  console.warn(
@@ -1045,14 +1604,7 @@ var CollectionService = class _CollectionService {
1045
1604
  * system keys (`id`, `created`, `updated`, `collectionId`, `collectionName`)
1046
1605
  */
1047
1606
  effectiveFields(optionsFields) {
1048
- if (optionsFields !== void 0) return optionsFields;
1049
- if (this.fieldsPreset !== void 0) {
1050
- if (this.fieldsPreset === "*") {
1051
- return this.visibleFields();
1052
- }
1053
- return this.fieldsPreset;
1054
- }
1055
- return this.visibleFields();
1607
+ return effectiveFields(this.schema, this.fieldsPreset, optionsFields);
1056
1608
  }
1057
1609
  /**
1058
1610
  * All non-hidden, non-password, non-autodate field names from the schema,
@@ -1069,21 +1621,23 @@ var CollectionService = class _CollectionService {
1069
1621
  * default returns every non-password field, including the system keys).
1070
1622
  */
1071
1623
  visibleFields() {
1072
- if (!this.schema?.fields) return void 0;
1073
- const visible = this.schema.fields.filter(
1074
- (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
1075
- ).map((f) => f.name);
1076
- if (visible.length === 0) return void 0;
1077
- return [
1078
- .../* @__PURE__ */ new Set([
1079
- "id",
1080
- "created",
1081
- "updated",
1082
- "collectionId",
1083
- "collectionName",
1084
- ...visible
1085
- ])
1086
- ].join(",");
1624
+ return visibleFields(this.schema);
1625
+ }
1626
+ /** Service state that query building needs. */
1627
+ queryContext() {
1628
+ return {
1629
+ expand: this.expandContext(),
1630
+ effectiveFields: (optionsFields) => this.effectiveFields(optionsFields),
1631
+ resolveFilter: (filter) => this.resolveFilter(filter)
1632
+ };
1633
+ }
1634
+ /** Context for the schema-aware expand helpers. */
1635
+ expandContext() {
1636
+ return {
1637
+ collectionName: this.collectionName,
1638
+ schema: this.schema,
1639
+ resolveCollection: (key) => this.schemaResolver?.(key)
1640
+ };
1087
1641
  }
1088
1642
  // ── Typed filter builder ──
1089
1643
  /**
@@ -1096,7 +1650,7 @@ var CollectionService = class _CollectionService {
1096
1650
  * await posts.getList(1, 20, {
1097
1651
  * filter: q("title").contains("x").and(q("published").eq(true)),
1098
1652
  * });
1099
- * // → filter=(title ~ '%x%' && published = true)
1653
+ * // → filter=(title ~ 'x' && published = true)
1100
1654
  *
1101
1655
  * // PocketBase `?` array operators (multi-select / multi-relation):
1102
1656
  * posts.getList(1, 20, { filter: q("tags").anyEq("news") });
@@ -1122,230 +1676,6 @@ var CollectionService = class _CollectionService {
1122
1676
  }
1123
1677
  return filter((field) => this.where(field));
1124
1678
  }
1125
- /**
1126
- * Resolve the leading relation chain of an expand token against the
1127
- * (optionally schema-aware) collection graph.
1128
- *
1129
- * Walks `segments` from this collection: each segment that is a relation
1130
- * advances to its target collection. Stops at the first non-relation
1131
- * segment or when the target schema is unknown.
1132
- *
1133
- * @returns `depth` — how many leading segments are relations; and
1134
- * `canInspect` — whether the schema at `depth` is known (so the next
1135
- * segment can be classified as a field selection vs a nested relation).
1136
- */
1137
- resolveRelationChain(segments) {
1138
- let currentFields = this.schema?.fields;
1139
- if (!currentFields) return { depth: 0, canInspect: false };
1140
- for (let i = 0; i < segments.length; i++) {
1141
- const field = currentFields.find((f) => f.name === segments[i]);
1142
- if (!field || field.type !== "relation") {
1143
- return { depth: i, canInspect: true };
1144
- }
1145
- if (i === segments.length - 1) {
1146
- return { depth: segments.length, canInspect: true };
1147
- }
1148
- const target = this.resolveTargetCollection(field);
1149
- if (!target?.fields) {
1150
- return { depth: i + 1, canInspect: false };
1151
- }
1152
- currentFields = target.fields;
1153
- }
1154
- return { depth: segments.length, canInspect: true };
1155
- }
1156
- /** Follow a relation field to its target collection, if resolvable. */
1157
- resolveTargetCollection(field) {
1158
- const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
1159
- if (!key || !this.schemaResolver) return void 0;
1160
- return this.schemaResolver(String(key));
1161
- }
1162
- /** Warn once when an expand field is not a relation (schema known). */
1163
- warnNonRelation(name) {
1164
- console.warn(
1165
- `[lazypock] expand("${name}"): field is not a relation on collection "${this.collectionName}"`
1166
- );
1167
- }
1168
- /**
1169
- * Validate and normalise a caller's `expand` string.
1170
- *
1171
- * PocketBase only expands *relations*: a dotted token like `author.user`
1172
- * walks into the related record. Callers often use a dotted token to mean
1173
- * "only these fields of the expanded record" (`owner.name,owner.email`),
1174
- * which PocketBase silently drops. When the trailing segment is not a
1175
- * relation — resolved from the schema graph — the token is rewritten as a
1176
- * field selection:
1177
- *
1178
- * ```
1179
- * expand: 'owner.name,owner.email'
1180
- * → expand=owner&fields=<base>,expand.owner.name,expand.owner.email
1181
- * ```
1182
- *
1183
- * Tokens whose whole path is relations keep their existing nested-expand
1184
- * behaviour. Without a schema the two are indistinguishable, so a lone
1185
- * dotted token stays a nested expand (with a warning) while two or more
1186
- * dotted tokens sharing the same relation are treated as field selection.
1187
- */
1188
- normalizeExpand(expand) {
1189
- const narrow = /* @__PURE__ */ new Map();
1190
- if (!expand) return { fieldSelectors: [], narrow };
1191
- const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
1192
- if (tokens.length === 0) return { fieldSelectors: [], narrow };
1193
- const relations = this.schema?.fields ? new Set(
1194
- this.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
1195
- ) : void 0;
1196
- const parsed = [];
1197
- for (const token of tokens) {
1198
- const segments = token.split(".").filter(Boolean);
1199
- const base = segments[0] ?? token;
1200
- if (segments.length <= 1) {
1201
- if (relations && !relations.has(base)) {
1202
- this.warnNonRelation(base);
1203
- }
1204
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1205
- continue;
1206
- }
1207
- if (!relations) {
1208
- parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
1209
- continue;
1210
- }
1211
- const { depth, canInspect } = this.resolveRelationChain(segments);
1212
- if (depth === 0) {
1213
- this.warnNonRelation(base);
1214
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1215
- } else if (depth === segments.length) {
1216
- parsed.push({ token, base, segments, kind: "nested", depth });
1217
- } else if (canInspect) {
1218
- parsed.push({ token, base, segments, kind: "narrow", depth });
1219
- } else {
1220
- parsed.push({ token, base, segments, kind: "unknown", depth });
1221
- }
1222
- }
1223
- const byBase = /* @__PURE__ */ new Map();
1224
- for (const t of parsed) {
1225
- const arr = byBase.get(t.base);
1226
- if (arr) arr.push(t);
1227
- else byBase.set(t.base, [t]);
1228
- }
1229
- for (const [base, group] of byBase) {
1230
- const unknowns = group.filter((t) => t.kind === "unknown");
1231
- if (unknowns.length === 0) continue;
1232
- const distinct = new Set(unknowns.map((t) => t.token));
1233
- const hasNarrow = group.some((t) => t.kind === "narrow");
1234
- if (!hasNarrow && distinct.size < 2) {
1235
- for (const t of unknowns) {
1236
- t.kind = "nested";
1237
- console.warn(
1238
- `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
1239
- );
1240
- }
1241
- } else {
1242
- for (const t of unknowns) t.kind = "narrow";
1243
- }
1244
- }
1245
- const expandParams = [];
1246
- const expandSeen = /* @__PURE__ */ new Set();
1247
- const fieldSelectors = [];
1248
- const selectorSeen = /* @__PURE__ */ new Set();
1249
- const pushParam = (p) => {
1250
- if (!expandSeen.has(p)) {
1251
- expandSeen.add(p);
1252
- expandParams.push(p);
1253
- }
1254
- };
1255
- const pushSelector = (s) => {
1256
- if (!selectorSeen.has(s)) {
1257
- selectorSeen.add(s);
1258
- fieldSelectors.push(s);
1259
- }
1260
- };
1261
- for (const t of parsed) {
1262
- if (t.kind === "plain") {
1263
- pushParam(t.token);
1264
- pushSelector(`expand.${t.token}`);
1265
- } else if (t.kind === "nested") {
1266
- for (let i = 1; i <= t.segments.length; i++) {
1267
- pushParam(t.segments.slice(0, i).join("."));
1268
- }
1269
- pushSelector(`expand.${t.segments[0]}`);
1270
- } else {
1271
- const depth = Math.max(1, t.depth);
1272
- const relationPath = t.segments.slice(0, depth).join(".");
1273
- pushParam(relationPath);
1274
- pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
1275
- if (t.segments.length === depth + 1) {
1276
- const base = t.segments[0];
1277
- const leaf = t.segments[depth];
1278
- const leaves = narrow.get(base) ?? [];
1279
- if (!leaves.includes(leaf)) leaves.push(leaf);
1280
- narrow.set(base, leaves);
1281
- }
1282
- }
1283
- }
1284
- return {
1285
- expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
1286
- fieldSelectors,
1287
- narrow
1288
- };
1289
- }
1290
- /**
1291
- * Keep only the requested leaf fields on `record.expand.<relation>`.
1292
- *
1293
- * Mirrors PocketBase's server-side `fields=expand.<rel>.<field>` projection
1294
- * for servers that don't support it (the LazyPock server), so field
1295
- * selection behaves the same against both. A no-op when the server already
1296
- * narrowed the record. Multi-relations are narrowed element-wise.
1297
- */
1298
- applyExpandNarrowing(record, narrow) {
1299
- if (narrow.size === 0) return record;
1300
- const rec = record;
1301
- const expand = rec.expand;
1302
- if (!expand || typeof expand !== "object") return record;
1303
- const next = { ...expand };
1304
- for (const [relation, leaves] of narrow) {
1305
- const value = next[relation];
1306
- if (value === void 0 || value === null) continue;
1307
- next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
1308
- }
1309
- return { ...rec, expand: next };
1310
- }
1311
- /**
1312
- * Merge the expand-preserving selectors into the base field projection.
1313
- *
1314
- * Both servers are kept happy at once:
1315
- * - PocketBase drops the whole `expand` payload unless an `expand.<key>`
1316
- * entry is present in `fields`;
1317
- * - the LazyPock server projects first (strict, top-level only) and then
1318
- * expands, so the relation *field* itself must be present in `fields`.
1319
- *
1320
- * We therefore add both the relation field (`cate`) and the
1321
- * `expand.<key>` entry. When no projection is active, no `fields` param is
1322
- * sent at all — a value like `*` plus other tokens is not a wildcard on
1323
- * the LazyPock server (it is a strict take, yielding empty records) and
1324
- * the server keeps `expand` by default when `fields` is absent.
1325
- */
1326
- mergeExpandFields(base, info) {
1327
- if (info.fieldSelectors.length === 0) return base;
1328
- if (base === void 0) return void 0;
1329
- const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
1330
- const seen = new Set(parts);
1331
- const push = (value) => {
1332
- if (seen.has(value)) return;
1333
- seen.add(value);
1334
- parts.push(value);
1335
- };
1336
- const fullKeys = /* @__PURE__ */ new Set();
1337
- for (const selector of info.fieldSelectors) {
1338
- const seg = selector.split(".");
1339
- if (seg.length === 2) fullKeys.add(seg[1]);
1340
- }
1341
- for (const selector of info.fieldSelectors) {
1342
- const seg = selector.split(".");
1343
- if (seg.length > 2 && fullKeys.has(seg[1])) continue;
1344
- if (seg.length >= 2) push(seg[1]);
1345
- push(selector);
1346
- }
1347
- return parts.join(",");
1348
- }
1349
1679
  /**
1350
1680
  * Fetch a paginated list of records (PocketBase `getList`).
1351
1681
  *
@@ -1354,50 +1684,13 @@ var CollectionService = class _CollectionService {
1354
1684
  * @param options Query params (`filter`, `sort`, `expand`, `fields`) + request options.
1355
1685
  */
1356
1686
  async getList(page = 1, perPage = 30, options) {
1357
- const {
1358
- requestKey,
1359
- autoCancel,
1360
- cancelKey,
1361
- fetch: fetch2,
1362
- headers,
1363
- signal,
1364
- singleFlight,
1365
- params,
1366
- ...queryParams
1367
- } = options ?? {};
1368
- if (Array.isArray(queryParams.sort)) {
1369
- queryParams.sort = queryParams.sort.join(",");
1370
- }
1371
- if (Array.isArray(queryParams.expand)) {
1372
- queryParams.expand = queryParams.expand.join(",");
1373
- }
1374
- if (typeof queryParams.filter === "function") {
1375
- queryParams.filter = this.resolveFilter(
1376
- queryParams.filter
1377
- );
1378
- }
1379
- const expandInfo = this.normalizeExpand(
1380
- typeof queryParams.expand === "string" ? queryParams.expand : void 0
1381
- );
1382
- if (expandInfo.expand !== void 0) {
1383
- queryParams.expand = expandInfo.expand;
1384
- }
1385
- const fields = this.mergeExpandFields(
1386
- this.effectiveFields(queryParams.fields),
1387
- expandInfo
1687
+ const { requestKey, autoCancel, cancelKey, fetch: fetch2, headers, signal, singleFlight, params, ...queryParams } = options ?? {};
1688
+ const { qs, narrow } = buildListQuery(
1689
+ this.queryContext(),
1690
+ page,
1691
+ perPage,
1692
+ queryParams
1388
1693
  );
1389
- if (fields !== void 0) {
1390
- queryParams.fields = fields;
1391
- }
1392
- const qs = new URLSearchParams(
1393
- Object.fromEntries(
1394
- Object.entries({
1395
- page: String(page),
1396
- perPage: String(perPage),
1397
- ...queryParams
1398
- }).map(([k, v]) => [k, String(v)])
1399
- )
1400
- ).toString();
1401
1694
  const result = await this.http.get(this.recordsPath() + "?" + qs, {
1402
1695
  requestKey,
1403
1696
  autoCancel,
@@ -1408,44 +1701,41 @@ var CollectionService = class _CollectionService {
1408
1701
  singleFlight,
1409
1702
  params
1410
1703
  });
1411
- if (result && expandInfo.narrow.size > 0) {
1704
+ if (result && narrow.size > 0) {
1412
1705
  result.items = result.items.map(
1413
- (item) => this.applyExpandNarrowing(item, expandInfo.narrow)
1706
+ (item) => applyExpandNarrowing(item, narrow)
1414
1707
  );
1415
1708
  }
1416
1709
  return result;
1417
1710
  }
1418
1711
  /**
1419
- * Fetch all records at once (auto-paginates; `batch` defaults to and is capped at 500, the server max `perPage`). Mirrors PocketBase's
1712
+ * Fetch all records at once (auto-paginates; `batch` defaults to and is
1713
+ * capped at 500, the server max `perPage`). Mirrors PocketBase's
1420
1714
  * `pb.collection(name).getFullList()`.
1421
1715
  *
1422
1716
  * @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
1423
1717
  */
1424
1718
  async getFullList(options) {
1425
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
1426
- const batch = clampBatch(requestedBatch);
1427
- if (typeof rest.filter === "function") {
1428
- rest.filter = this.resolveFilter(rest.filter);
1429
- }
1430
- const effectiveKey = typeof rest.requestKey === "string" ? rest.requestKey : `getFullList:${this.collectionName}:${stableStringify(rest)}`;
1431
- const items = [];
1432
- let page = 1;
1433
- for (; ; ) {
1434
- const res = await this.getList(
1435
- page,
1436
- batch,
1437
- {
1438
- ...rest,
1439
- requestKey: effectiveKey,
1440
- singleFlight: true
1441
- }
1442
- );
1443
- if (!res || !res.items || res.items.length === 0) break;
1444
- items.push(...res.items);
1445
- if (page >= (res.totalPages ?? page)) break;
1446
- page += 1;
1719
+ const { query, transport, batch } = splitListOptions(
1720
+ options
1721
+ );
1722
+ if (typeof query.filter === "function") {
1723
+ query.filter = this.resolveFilter(query.filter);
1447
1724
  }
1448
- return items;
1725
+ const effectiveKey = fullListKey(
1726
+ this.collectionName,
1727
+ query,
1728
+ transport.requestKey
1729
+ );
1730
+ return paginateAll(
1731
+ batch,
1732
+ (page) => this.getList(page, batch, {
1733
+ ...query,
1734
+ ...transport,
1735
+ requestKey: effectiveKey,
1736
+ singleFlight: true
1737
+ })
1738
+ );
1449
1739
  }
1450
1740
  /**
1451
1741
  * Fetch the first record matching a filter (PocketBase `getFirstListItem`).
@@ -1466,29 +1756,13 @@ var CollectionService = class _CollectionService {
1466
1756
  * @param options Optional request options.
1467
1757
  */
1468
1758
  async getOne(id, options) {
1469
- let rawExpand;
1470
- if (Array.isArray(options?.expand)) {
1471
- rawExpand = options.expand.join(",");
1472
- } else if (typeof options?.expand === "string") {
1473
- rawExpand = options.expand;
1474
- }
1475
- const expandInfo = this.normalizeExpand(rawExpand);
1476
- const fields = this.mergeExpandFields(
1477
- this.effectiveFields(options?.fields),
1478
- expandInfo
1479
- );
1480
- const qs = new URLSearchParams();
1481
- if (fields !== void 0) qs.set("fields", fields);
1482
- if (rawExpand !== void 0) {
1483
- qs.set("expand", expandInfo.expand ?? rawExpand);
1484
- }
1485
- const qsStr = qs.toString();
1759
+ const { qs, narrow } = buildReadQuery(this.queryContext(), options);
1486
1760
  const record = await this.http.get(
1487
- this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1761
+ this.recordsPath() + "/" + this.encodeId(id) + (qs ? "?" + qs : ""),
1488
1762
  options
1489
1763
  );
1490
- if (record && expandInfo.narrow.size > 0) {
1491
- return this.applyExpandNarrowing(record, expandInfo.narrow);
1764
+ if (record && narrow.size > 0) {
1765
+ return applyExpandNarrowing(record, narrow);
1492
1766
  }
1493
1767
  return record;
1494
1768
  }
@@ -1530,13 +1804,12 @@ var CollectionService = class _CollectionService {
1530
1804
  options
1531
1805
  );
1532
1806
  }
1533
- // ── Expand / Relation Fields ──
1534
1807
  /**
1535
1808
  * Get a list of expandable (relation) fields for this collection.
1536
1809
  * Useful for constructing `expand` query parameters.
1537
1810
  */
1538
1811
  async expandFields(options) {
1539
- const data = await this.http.get("/collections/" + this.encodeId(this.collectionName), options);
1812
+ const data = await this.http.get(this.collectionPath(), options);
1540
1813
  if (!data?.fields) return null;
1541
1814
  return data.fields.filter((f) => f.type === "relation" && f.options?.collection).map((f) => ({
1542
1815
  field: f.name,
@@ -1569,47 +1842,15 @@ var CollectionService = class _CollectionService {
1569
1842
  * excluded from responses, select/expand are validated.
1570
1843
  */
1571
1844
  withSchema(schema) {
1572
- const derived = new _CollectionService(
1573
- this.http,
1574
- this.collectionName,
1575
- this.authStore,
1576
- this.realtime,
1577
- schema,
1578
- this.schemaResolver
1579
- );
1580
- derived.fieldsPreset = this.fieldsPreset;
1581
- return derived;
1845
+ return this.derive({ schema });
1582
1846
  }
1583
1847
  subscribe(topicOrCallback, maybeCallback, options) {
1584
- if (!this.realtime) {
1585
- console.warn("[lazypock] No realtime service configured.");
1586
- return () => {
1587
- };
1588
- }
1589
- let recordId;
1590
- let callback;
1591
- let joinPayload;
1592
- if (typeof topicOrCallback === "function") {
1593
- callback = topicOrCallback;
1594
- if (typeof maybeCallback === "string") recordId = maybeCallback;
1595
- } else {
1596
- callback = maybeCallback;
1597
- recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1598
- const { headers: _ignored, ...rest } = options ?? {};
1599
- if (Object.keys(rest).length > 0) joinPayload = rest;
1600
- }
1601
- const topic = "collection:" + this.collectionName + (recordId ? ":" + recordId : "");
1602
- const handler = (raw) => {
1603
- const record = raw.payload?.["record"] ?? {};
1604
- callback({
1605
- action: normalizeAction(raw.event, raw.payload?.["action"]),
1606
- record,
1607
- topic: raw.topic
1608
- });
1609
- };
1610
- this.realtime.ensureConnected();
1611
- this.realtime.subscribe(topic, handler, joinPayload);
1612
- return () => this.realtime?.unsubscribe(topic, handler);
1848
+ return subscribeToCollection(
1849
+ { realtime: this.realtime, collectionName: this.collectionName },
1850
+ topicOrCallback,
1851
+ maybeCallback,
1852
+ options
1853
+ );
1613
1854
  }
1614
1855
  /**
1615
1856
  * Unsubscribe from realtime changes (PocketBase-compatible):
@@ -1618,66 +1859,33 @@ var CollectionService = class _CollectionService {
1618
1859
  * - `unsubscribe('RECORD_ID')` — remove that record's subscriptions
1619
1860
  */
1620
1861
  unsubscribe(recordId) {
1621
- if (recordId === void 0) {
1622
- this.realtime?.unsubscribeByPrefix(
1623
- "collection:" + this.collectionName
1624
- );
1625
- return;
1626
- }
1627
- const topic = "collection:" + this.collectionName + (recordId === "*" ? "" : ":" + recordId);
1628
- this.realtime?.unsubscribe(topic);
1862
+ unsubscribeFromCollection(
1863
+ { realtime: this.realtime, collectionName: this.collectionName },
1864
+ recordId
1865
+ );
1629
1866
  }
1630
1867
  // ── Auth Collection Methods ──
1631
1868
  /**
1632
1869
  * Authenticate with email/password against this auth collection.
1633
1870
  * Stores the returned token and user model in the auth store.
1634
1871
  */
1635
- async authWithPassword(identity, password, options) {
1636
- const data = await this.http.post(
1637
- this.collectionPath() + "/auth-with-password",
1638
- { identity, password },
1639
- options
1640
- );
1641
- if (data && this.authStore) {
1642
- this.authStore.setCollectionName(this.collectionName);
1643
- rememberAuthResponse(
1644
- this.authStore,
1645
- data,
1646
- data.record
1647
- );
1648
- }
1649
- return data;
1872
+ authWithPassword(identity, password, options) {
1873
+ return authWithPassword(this.sessionContext(), identity, password, options);
1650
1874
  }
1651
1875
  /**
1652
1876
  * Refresh the auth token for the currently authenticated user.
1653
1877
  * Updates the stored token and user model.
1654
1878
  */
1655
- async authRefresh(options) {
1656
- const data = await this.http.post(
1657
- this.collectionPath() + "/auth-refresh",
1658
- { refreshToken: this.authStore?.refreshToken },
1659
- options
1660
- );
1661
- if (data && this.authStore) {
1662
- this.authStore.setCollectionName(this.collectionName);
1663
- rememberAuthResponse(
1664
- this.authStore,
1665
- data,
1666
- data.record
1667
- );
1668
- }
1669
- return data;
1879
+ authRefresh(options) {
1880
+ return authRefresh(this.sessionContext(), options);
1670
1881
  }
1671
1882
  /**
1672
1883
  * Get available auth methods for this collection (PocketBase `listAuthMethods`).
1673
1884
  * Returns `password`, `oauth2.providers` (each with `name`, `authURL`,
1674
1885
  * `state`, `codeVerifier`), and `mfa`.
1675
1886
  */
1676
- async listAuthMethods(options) {
1677
- return this.http.get(
1678
- this.collectionPath() + "/auth-methods",
1679
- options
1680
- );
1887
+ listAuthMethods(options) {
1888
+ return listAuthMethods(this.sessionContext(), options);
1681
1889
  }
1682
1890
  /**
1683
1891
  * Get available auth methods for this collection.
@@ -1692,13 +1900,8 @@ var CollectionService = class _CollectionService {
1692
1900
  * `requestPasswordReset`). The backend always answers 204 to avoid
1693
1901
  * revealing whether the address exists.
1694
1902
  */
1695
- async requestPasswordReset(email, options) {
1696
- await this.http.post(
1697
- this.collectionPath() + "/request-password-reset",
1698
- { email },
1699
- options
1700
- );
1701
- return true;
1903
+ requestPasswordReset(email, options) {
1904
+ return requestPasswordReset(this.sessionContext(), email, options);
1702
1905
  }
1703
1906
  /**
1704
1907
  * Confirm a password reset (PocketBase `confirmPasswordReset`).
@@ -1707,63 +1910,49 @@ var CollectionService = class _CollectionService {
1707
1910
  * @param password The new password (min 8 chars server-side).
1708
1911
  * @param passwordConfirm Must equal `password`.
1709
1912
  */
1710
- async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1711
- await this.http.post(
1712
- this.collectionPath() + "/confirm-password-reset",
1713
- { token: passwordResetToken, password, passwordConfirm },
1913
+ confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1914
+ return confirmPasswordReset(
1915
+ this.sessionContext(),
1916
+ passwordResetToken,
1917
+ password,
1918
+ passwordConfirm,
1714
1919
  options
1715
1920
  );
1716
- return true;
1717
1921
  }
1718
1922
  /**
1719
1923
  * Send a verification email to the given address (PocketBase
1720
1924
  * `requestVerification`). The backend always answers 204 to avoid
1721
1925
  * revealing whether the address exists.
1722
1926
  */
1723
- async requestVerification(email, options) {
1724
- await this.http.post(
1725
- this.collectionPath() + "/request-verification",
1726
- { email },
1727
- options
1728
- );
1729
- return true;
1927
+ requestVerification(email, options) {
1928
+ return requestVerification(this.sessionContext(), email, options);
1730
1929
  }
1731
1930
  /**
1732
1931
  * Confirm an email verification (PocketBase `confirmVerification`).
1733
1932
  * Resolves with the verified auth record.
1734
1933
  */
1735
- async confirmVerification(verificationToken, options) {
1736
- const data = await this.http.post(
1737
- this.collectionPath() + "/confirm-verification",
1738
- { token: verificationToken },
1739
- options
1740
- );
1741
- return data?.record ?? null;
1934
+ confirmVerification(verificationToken, options) {
1935
+ return confirmVerification(this.sessionContext(), verificationToken, options);
1742
1936
  }
1743
1937
  /**
1744
1938
  * Send an email-change confirmation email to a new address (PocketBase
1745
1939
  * `requestEmailChange`). Requires an authenticated auth-collection user.
1746
1940
  */
1747
- async requestEmailChange(newEmail, options) {
1748
- await this.http.post(
1749
- this.collectionPath() + "/request-email-change",
1750
- { newEmail },
1751
- options
1752
- );
1753
- return true;
1941
+ requestEmailChange(newEmail, options) {
1942
+ return requestEmailChange(this.sessionContext(), newEmail, options);
1754
1943
  }
1755
1944
  /**
1756
1945
  * Confirm an email change (PocketBase `confirmEmailChange`). Requires the
1757
1946
  * currently authenticated user's password. Resolves with the updated auth
1758
1947
  * record.
1759
1948
  */
1760
- async confirmEmailChange(emailChangeToken, password, options) {
1761
- const data = await this.http.post(
1762
- this.collectionPath() + "/confirm-email-change",
1763
- { token: emailChangeToken, password },
1949
+ confirmEmailChange(emailChangeToken, password, options) {
1950
+ return confirmEmailChange(
1951
+ this.sessionContext(),
1952
+ emailChangeToken,
1953
+ password,
1764
1954
  options
1765
1955
  );
1766
- return data?.record ?? null;
1767
1956
  }
1768
1957
  /**
1769
1958
  * Sign in with an OAuth2 provider (PocketBase `authWithOAuth2` parity).
@@ -1780,40 +1969,8 @@ var CollectionService = class _CollectionService {
1780
1969
  * `window.postMessage`. Use {@link listAuthMethods} + {@link authWithOAuth2Code}
1781
1970
  * instead.
1782
1971
  */
1783
- async authWithOAuth2(options) {
1784
- const {
1785
- provider,
1786
- createData,
1787
- urlCallback,
1788
- popup,
1789
- timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1790
- } = options;
1791
- const methods = await this.listAuthMethods();
1792
- const providerInfo = methods?.oauth2?.providers?.find(
1793
- (p) => p.name === provider
1794
- );
1795
- if (!providerInfo) {
1796
- throw new ApiError(
1797
- `OAuth2 provider "${provider}" is not enabled for this collection.`,
1798
- methods ?? {},
1799
- 400,
1800
- false,
1801
- "oauth2_unknown_provider"
1802
- );
1803
- }
1804
- const { code } = await authorizeWithOAuth2Popup({
1805
- authURL: providerInfo.authURL,
1806
- expectedOrigin: oauth2RedirectOrigin(this.http.baseUrl),
1807
- urlCallback,
1808
- popup,
1809
- timeoutMs
1810
- });
1811
- return this.authWithOAuth2Code({
1812
- provider,
1813
- code,
1814
- codeVerifier: providerInfo.codeVerifier,
1815
- createData
1816
- });
1972
+ authWithOAuth2(options) {
1973
+ return authWithOAuth2(this.sessionContext(), options);
1817
1974
  }
1818
1975
  /**
1819
1976
  * Exchange an OAuth2 authorization code directly (PocketBase
@@ -1824,36 +1981,8 @@ var CollectionService = class _CollectionService {
1824
1981
  * capture the `code` from your redirect/deep link, then call this to
1825
1982
  * finish and populate the auth store.
1826
1983
  */
1827
- async authWithOAuth2Code(options) {
1828
- const { provider, code, codeVerifier, redirectUrl, createData } = options;
1829
- const data = await this.http.post(
1830
- this.collectionPath() + "/auth-with-oauth2",
1831
- {
1832
- provider,
1833
- code,
1834
- codeVerifier,
1835
- redirectUrl: redirectUrl ?? this.http.baseUrl + "/oauth2-redirect",
1836
- createData: createData ?? {}
1837
- }
1838
- );
1839
- if (!data) {
1840
- throw new ApiError(
1841
- "OAuth2 code exchange returned no data.",
1842
- {},
1843
- 0,
1844
- false,
1845
- "oauth2_exchange_failed"
1846
- );
1847
- }
1848
- if (this.authStore) {
1849
- this.authStore.setCollectionName(this.collectionName);
1850
- rememberAuthResponse(
1851
- this.authStore,
1852
- data,
1853
- data.record
1854
- );
1855
- }
1856
- return data;
1984
+ authWithOAuth2Code(options) {
1985
+ return authWithOAuth2Code(this.sessionContext(), options);
1857
1986
  }
1858
1987
  };
1859
1988
 
@@ -1920,6 +2049,7 @@ var RealtimeService = class {
1920
2049
  ensureConnected() {
1921
2050
  if (this.open || this.controller || !this.url) return;
1922
2051
  if (this.serverTopics().length === 0) return;
2052
+ this.closed = false;
1923
2053
  this.doConnect();
1924
2054
  }
1925
2055
  connect(opts) {
@@ -2120,6 +2250,10 @@ var RealtimeService = class {
2120
2250
  function encodeKey(key) {
2121
2251
  return key.split("/").map(encodeURIComponent).join("/");
2122
2252
  }
2253
+ function uploadFileName(file, fallback = "file") {
2254
+ if (typeof File !== "undefined" && file instanceof File) return file.name;
2255
+ return fallback;
2256
+ }
2123
2257
  function getFileUrl(baseUrl, key) {
2124
2258
  return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
2125
2259
  }
@@ -2166,7 +2300,7 @@ var FilesService = class {
2166
2300
  throw new Error("FormData is not available in this environment");
2167
2301
  }
2168
2302
  const formData = new FormData();
2169
- const name = filename || (file instanceof File ? file.name : "file");
2303
+ const name = filename || uploadFileName(file);
2170
2304
  formData.append("file", file, name);
2171
2305
  if (meta?.collectionName)
2172
2306
  formData.append("collection_name", meta.collectionName);
@@ -2189,7 +2323,7 @@ var FilesService = class {
2189
2323
  * `upload()` when the server has no direct-upload support configured.
2190
2324
  */
2191
2325
  async uploadDirect(file, opts) {
2192
- const filename = opts?.filename || (file instanceof File ? file.name : "file");
2326
+ const filename = opts?.filename || uploadFileName(file);
2193
2327
  const mime = file.type || "application/octet-stream";
2194
2328
  const presigned = await this.presign({
2195
2329
  filename,
@@ -2316,42 +2450,15 @@ var CollectionsService = class {
2316
2450
  */
2317
2451
  async getFullList(options) {
2318
2452
  if (!this.http) return [];
2319
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
2320
- const batch = clampBatch(requestedBatch);
2321
- const {
2322
- requestKey: reqKey,
2323
- singleFlight: _singleFlight,
2324
- fetch: fetchFn,
2325
- headers: hdrs,
2326
- signal: sig,
2327
- params: passthroughParams,
2328
- ...queryParams
2329
- } = rest;
2330
- const effectiveKey = typeof reqKey === "string" ? reqKey : `getFullList:collections:${stableStringify(rest)}`;
2331
- const items = [];
2332
- let page = 1;
2333
- for (; ; ) {
2334
- const res = await this.getList(
2335
- {
2336
- ...queryParams,
2337
- ...passthroughParams ?? {},
2338
- page,
2339
- perPage: batch
2340
- },
2341
- {
2342
- requestKey: effectiveKey,
2343
- singleFlight: true,
2344
- ...fetchFn ? { fetch: fetchFn } : {},
2345
- ...hdrs ? { headers: hdrs } : {},
2346
- ...sig ? { signal: sig } : {}
2347
- }
2348
- );
2349
- if (!res || !res.items || res.items.length === 0) break;
2350
- items.push(...res.items);
2351
- if (page >= (res.totalPages ?? page)) break;
2352
- page += 1;
2353
- }
2354
- return items;
2453
+ const { query, transport, batch } = splitListOptions(options);
2454
+ const requestKey = fullListKey("collections", query, transport.requestKey);
2455
+ return paginateAll(
2456
+ batch,
2457
+ (page, perPage) => this.getList(
2458
+ { ...query, page, perPage },
2459
+ { ...transport, requestKey, singleFlight: true }
2460
+ )
2461
+ );
2355
2462
  }
2356
2463
  /**
2357
2464
  * Get a single collection by ID or name (admin).
@@ -2392,11 +2499,9 @@ var CollectionsService = class {
2392
2499
  * @param options Optional request options.
2393
2500
  */
2394
2501
  async delete(id, options) {
2395
- const res = this.http?.delete(
2396
- "/collections/" + encodeURIComponent(id),
2397
- options
2398
- );
2399
- return res == null ? false : true;
2502
+ if (!this.http) return false;
2503
+ await this.http.delete("/collections/" + encodeURIComponent(id), options);
2504
+ return true;
2400
2505
  }
2401
2506
  /**
2402
2507
  * Subscribe to collection registry changes.
@@ -2731,36 +2836,25 @@ var LazypockClient = class {
2731
2836
  * @param collection Optional auth collection name.
2732
2837
  */
2733
2838
  async login(email, password, collection) {
2734
- let data;
2735
2839
  if (collection) {
2736
- data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
2840
+ return this.collection(collection).authWithPassword(email, password);
2841
+ }
2842
+ let data = null;
2843
+ try {
2844
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
2737
2845
  identity: email,
2738
2846
  password
2739
2847
  });
2740
- if (data && data.record) {
2741
- this.authStore.setCollectionName(collection);
2742
- rememberAuthResponse(
2743
- this.authStore,
2744
- data,
2745
- data.record
2746
- );
2747
- }
2748
- } else {
2749
- try {
2750
- data = await this.http.post("/collections/_superusers/auth-with-password", {
2751
- identity: email,
2752
- password
2753
- });
2754
- } catch {
2755
- data = null;
2756
- }
2757
- if (!data) {
2758
- data = await this.http.post("/superusers/login", { email, password });
2759
- }
2760
- if (data) {
2761
- this.authStore.setCollectionName(null);
2762
- rememberAuthResponse(this.authStore, data, null);
2763
- }
2848
+ } catch (err) {
2849
+ if (!(err instanceof ApiError) || err.status !== 404) throw err;
2850
+ data = null;
2851
+ }
2852
+ if (!data) {
2853
+ data = await this.http.post("/superusers/login", { email, password });
2854
+ }
2855
+ if (data) {
2856
+ this.authStore.setCollectionName(null);
2857
+ rememberAuthResponse(this.authStore, data, null);
2764
2858
  }
2765
2859
  return data;
2766
2860
  }
@@ -2772,7 +2866,7 @@ var LazypockClient = class {
2772
2866
  async me(options) {
2773
2867
  const data = await this.http.get("/me", options);
2774
2868
  if (data) {
2775
- this.authStore.set(this.authStore.token, data);
2869
+ this.authStore.setModel(data);
2776
2870
  }
2777
2871
  return data;
2778
2872
  }
@@ -2785,17 +2879,8 @@ var LazypockClient = class {
2785
2879
  * @param password Password.
2786
2880
  * @param options Optional request options.
2787
2881
  */
2788
- async authWithPassword(collection, identity, password, options) {
2789
- const data = await this.http.post(
2790
- "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
2791
- { identity, password },
2792
- options
2793
- );
2794
- if (data) {
2795
- this.authStore.setCollectionName(collection);
2796
- rememberAuthResponse(this.authStore, data, data.record);
2797
- }
2798
- return data;
2882
+ authWithPassword(collection, identity, password, options) {
2883
+ return this.collection(collection).authWithPassword(identity, password, options);
2799
2884
  }
2800
2885
  /**
2801
2886
  * Refresh an auth collection token.
@@ -2804,17 +2889,8 @@ var LazypockClient = class {
2804
2889
  * @param collection The auth collection name.
2805
2890
  * @param options Optional request options.
2806
2891
  */
2807
- async authRefresh(collection, options) {
2808
- const data = await this.http.post(
2809
- "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2810
- { refreshToken: this.authStore.refreshToken },
2811
- options
2812
- );
2813
- if (data) {
2814
- this.authStore.setCollectionName(collection);
2815
- rememberAuthResponse(this.authStore, data, data.record);
2816
- }
2817
- return data;
2892
+ authRefresh(collection, options) {
2893
+ return this.collection(collection).authRefresh(options);
2818
2894
  }
2819
2895
  /** Clear the current auth state and remove persisted tokens. */
2820
2896
  logout() {