lazypock 0.19.2 → 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.cjs CHANGED
@@ -29,6 +29,7 @@ __export(index_exports, {
29
29
  FilterExpr: () => FilterExpr,
30
30
  HttpClient: () => HttpClient,
31
31
  LazypockClient: () => LazypockClient,
32
+ MailService: () => MailService,
32
33
  RealtimeService: () => RealtimeService,
33
34
  TypedClient: () => TypedClient,
34
35
  collectionTypeName: () => collectionTypeName,
@@ -106,15 +107,20 @@ var HttpClient = class {
106
107
  *
107
108
  * A network failure keeps the session (the next request can retry); only a refusal
108
109
  * by the server ends it.
110
+ *
111
+ * `fetcher` is the per-request `options.fetch` override, so a caller (or a test)
112
+ * that injected its own transport also intercepts the refresh. Falling back to
113
+ * the global fetch here meant those callers — React Native and the test suite —
114
+ * silently did not cover this path at all.
109
115
  */
110
- async refreshAuth() {
116
+ async refreshAuth(fetcher) {
111
117
  const refreshToken = this.authStore.refreshToken;
112
118
  if (!refreshToken) return null;
113
119
  if (this.refreshInFlight) {
114
120
  const refreshed = await this.refreshInFlight;
115
121
  return refreshed ? this.currentAuthResponse() : null;
116
122
  }
117
- this.refreshInFlight = this.performRefresh(refreshToken);
123
+ this.refreshInFlight = this.performRefresh(refreshToken, fetcher);
118
124
  try {
119
125
  const refreshed = await this.refreshInFlight;
120
126
  return refreshed ? this.currentAuthResponse() : null;
@@ -126,13 +132,18 @@ var HttpClient = class {
126
132
  currentAuthResponse() {
127
133
  return {
128
134
  token: this.authStore.token,
135
+ // SAFETY: `AuthModel` is an index-signature interface (`[key: string]:
136
+ // unknown`), so its values are readable as a plain property bag; the
137
+ // `{}` fallback preserves the "no model, empty record" contract of the
138
+ // response shape this mirrors. The cast only bridges the empty-object
139
+ // literal, which TypeScript gives no index signature.
129
140
  record: this.authStore.model ?? {}
130
141
  };
131
142
  }
132
- async performRefresh(refreshToken) {
143
+ async performRefresh(refreshToken, fetcher) {
133
144
  const collection = this.refreshCollection();
134
145
  try {
135
- const res = await this.defaultFetch(
146
+ const res = await (fetcher ?? this.defaultFetch)(
136
147
  this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
137
148
  {
138
149
  method: "POST",
@@ -220,7 +231,7 @@ var HttpClient = class {
220
231
  */
221
232
  async request(method, path, body, options) {
222
233
  if (this.authStore.isExpired && this.authStore.refreshToken) {
223
- await this.refreshAuth();
234
+ await this.refreshAuth(options?.fetch);
224
235
  }
225
236
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
226
237
  if (options?.autoCancel === false) requestKey = null;
@@ -331,7 +342,7 @@ var HttpClient = class {
331
342
  if (res.status === 401 && this.authStore.refreshToken) {
332
343
  await res.text().catch(() => {
333
344
  });
334
- const refreshed = await this.refreshAuth();
345
+ const refreshed = await this.refreshAuth(options?.fetch);
335
346
  if (refreshed) {
336
347
  headers["Authorization"] = "Bearer " + this.authStore.token;
337
348
  try {
@@ -393,6 +404,17 @@ var HttpClient = class {
393
404
  post(path, body, options) {
394
405
  return this.request("POST", path, body, options);
395
406
  }
407
+ /**
408
+ * HTTP PUT — a full replacement. Used where the server models a resource as a
409
+ * complete unit rather than a set of patches (e.g. a mail template, which only
410
+ * exists once all three of its parts do).
411
+ * @param path URL path.
412
+ * @param body Request body.
413
+ * @param options Optional request options.
414
+ */
415
+ put(path, body, options) {
416
+ return this.request("PUT", path, body, options);
417
+ }
396
418
  /**
397
419
  * HTTP PATCH.
398
420
  * @param path URL path.
@@ -527,6 +549,29 @@ var AuthStore = class {
527
549
  ]);
528
550
  this.notify();
529
551
  }
552
+ /**
553
+ * Replace the cached auth model **without** touching the token, its recorded
554
+ * expiry, or the refresh token.
555
+ *
556
+ * Use this when a read refreshes the identity record (e.g. `me()`, or the
557
+ * server echoing the record back). Routing that through {@link set} would
558
+ * overwrite the access token's real `expiresIn` with the 7-day fallback TTL,
559
+ * so `isExpired` stays false long past the real 15-minute lifetime and the
560
+ * proactive refresh never fires — every request then pays a 401 + retry.
561
+ *
562
+ * @param model The authenticated user record, or null for superusers.
563
+ */
564
+ setModel(model) {
565
+ this._model = model;
566
+ if (!this._collectionName && model && typeof model.collectionName === "string") {
567
+ this._collectionName = model.collectionName;
568
+ }
569
+ void Promise.all([
570
+ model ? this.storage.set("auth_model", JSON.stringify(model)) : this.storage.remove("auth_model"),
571
+ this.persistCollectionName()
572
+ ]);
573
+ this.notify();
574
+ }
530
575
  /**
531
576
  * Record a complete auth response: token, model, refresh token and the access
532
577
  * token's real lifetime.
@@ -754,6 +799,377 @@ var FilterBuilder = class {
754
799
  }
755
800
  };
756
801
 
802
+ // src/projection.ts
803
+ var SYSTEM_FIELDS = [
804
+ "id",
805
+ "created",
806
+ "updated",
807
+ "collectionId",
808
+ "collectionName"
809
+ ];
810
+ var visibleFieldsCache = /* @__PURE__ */ new WeakMap();
811
+ function visibleFields(schema) {
812
+ if (!schema?.fields) return void 0;
813
+ const cached = visibleFieldsCache.get(schema);
814
+ if (cached !== void 0 || visibleFieldsCache.has(schema)) return cached;
815
+ const visible = schema.fields.filter(
816
+ (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
817
+ ).map((f) => f.name);
818
+ const result = visible.length === 0 ? void 0 : (
819
+ // Dedupe in case a schema ever names a field after a system key.
820
+ [
821
+ .../* @__PURE__ */ new Set([...SYSTEM_FIELDS, ...visible])
822
+ ].join(",")
823
+ );
824
+ visibleFieldsCache.set(schema, result);
825
+ return result;
826
+ }
827
+ function effectiveFields(schema, preset, optionsFields) {
828
+ if (optionsFields !== void 0) return optionsFields;
829
+ if (preset !== void 0) {
830
+ return preset === "*" ? visibleFields(schema) : preset;
831
+ }
832
+ return visibleFields(schema);
833
+ }
834
+ function mergeExpandFields(base, info) {
835
+ if (info.fieldSelectors.length === 0) return base;
836
+ if (base === void 0) return void 0;
837
+ const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
838
+ const seen = new Set(parts);
839
+ const push = (value) => {
840
+ if (seen.has(value)) return;
841
+ seen.add(value);
842
+ parts.push(value);
843
+ };
844
+ const fullKeys = /* @__PURE__ */ new Set();
845
+ for (const selector of info.fieldSelectors) {
846
+ const seg = selector.split(".");
847
+ if (seg.length === 2) fullKeys.add(seg[1]);
848
+ }
849
+ for (const selector of info.fieldSelectors) {
850
+ const seg = selector.split(".");
851
+ if (seg.length > 2 && fullKeys.has(seg[1])) continue;
852
+ if (seg.length >= 2) push(seg[1]);
853
+ push(selector);
854
+ }
855
+ return parts.join(",");
856
+ }
857
+
858
+ // src/expand.ts
859
+ function pickFields(value, fields) {
860
+ if (!value || typeof value !== "object") return {};
861
+ const src = value;
862
+ const out = {};
863
+ for (const f of fields) {
864
+ if (f in src) out[f] = src[f];
865
+ }
866
+ return out;
867
+ }
868
+ function resolveTargetCollection(field, ctx) {
869
+ const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
870
+ if (!key) return void 0;
871
+ return ctx.resolveCollection(String(key));
872
+ }
873
+ function resolveRelationChain(segments, ctx) {
874
+ let currentFields = ctx.schema?.fields;
875
+ if (!currentFields) return { depth: 0, canInspect: false };
876
+ for (let i = 0; i < segments.length; i++) {
877
+ const field = currentFields.find((f) => f.name === segments[i]);
878
+ if (!field || field.type !== "relation") {
879
+ return { depth: i, canInspect: true };
880
+ }
881
+ if (i === segments.length - 1) {
882
+ return { depth: segments.length, canInspect: true };
883
+ }
884
+ const target = resolveTargetCollection(field, ctx);
885
+ if (!target?.fields) {
886
+ return { depth: i + 1, canInspect: false };
887
+ }
888
+ currentFields = target.fields;
889
+ }
890
+ return { depth: segments.length, canInspect: true };
891
+ }
892
+ function warnNonRelation(name, ctx) {
893
+ console.warn(
894
+ `[lazypock] expand("${name}"): field is not a relation on collection "${ctx.collectionName}"`
895
+ );
896
+ }
897
+ function normalizeExpand(expand, ctx) {
898
+ const narrow = /* @__PURE__ */ new Map();
899
+ if (!expand) return { fieldSelectors: [], narrow };
900
+ const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
901
+ if (tokens.length === 0) return { fieldSelectors: [], narrow };
902
+ const relations = ctx.schema?.fields ? new Set(
903
+ ctx.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
904
+ ) : void 0;
905
+ const parsed = [];
906
+ for (const token of tokens) {
907
+ const segments = token.split(".").filter(Boolean);
908
+ const base = segments[0] ?? token;
909
+ if (segments.length <= 1) {
910
+ if (relations && !relations.has(base)) {
911
+ warnNonRelation(base, ctx);
912
+ }
913
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
914
+ continue;
915
+ }
916
+ if (!relations) {
917
+ parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
918
+ continue;
919
+ }
920
+ const { depth, canInspect } = resolveRelationChain(segments, ctx);
921
+ if (depth === 0) {
922
+ warnNonRelation(base, ctx);
923
+ parsed.push({ token, base, segments, kind: "plain", depth: 0 });
924
+ } else if (depth === segments.length) {
925
+ parsed.push({ token, base, segments, kind: "nested", depth });
926
+ } else if (canInspect) {
927
+ parsed.push({ token, base, segments, kind: "narrow", depth });
928
+ } else {
929
+ parsed.push({ token, base, segments, kind: "unknown", depth });
930
+ }
931
+ }
932
+ const byBase = /* @__PURE__ */ new Map();
933
+ for (const t of parsed) {
934
+ const arr = byBase.get(t.base);
935
+ if (arr) arr.push(t);
936
+ else byBase.set(t.base, [t]);
937
+ }
938
+ for (const [base, group] of byBase) {
939
+ const unknowns = group.filter((t) => t.kind === "unknown");
940
+ if (unknowns.length === 0) continue;
941
+ const distinct = new Set(unknowns.map((t) => t.token));
942
+ const hasNarrow = group.some((t) => t.kind === "narrow");
943
+ if (!hasNarrow && distinct.size < 2) {
944
+ for (const t of unknowns) {
945
+ t.kind = "nested";
946
+ console.warn(
947
+ `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
948
+ );
949
+ }
950
+ } else {
951
+ for (const t of unknowns) t.kind = "narrow";
952
+ }
953
+ }
954
+ const expandParams = [];
955
+ const expandSeen = /* @__PURE__ */ new Set();
956
+ const fieldSelectors = [];
957
+ const selectorSeen = /* @__PURE__ */ new Set();
958
+ const pushParam = (p) => {
959
+ if (!expandSeen.has(p)) {
960
+ expandSeen.add(p);
961
+ expandParams.push(p);
962
+ }
963
+ };
964
+ const pushSelector = (s) => {
965
+ if (!selectorSeen.has(s)) {
966
+ selectorSeen.add(s);
967
+ fieldSelectors.push(s);
968
+ }
969
+ };
970
+ for (const t of parsed) {
971
+ if (t.kind === "plain") {
972
+ pushParam(t.token);
973
+ pushSelector(`expand.${t.token}`);
974
+ } else if (t.kind === "nested") {
975
+ for (let i = 1; i <= t.segments.length; i++) {
976
+ pushParam(t.segments.slice(0, i).join("."));
977
+ }
978
+ pushSelector(`expand.${t.segments[0]}`);
979
+ } else {
980
+ const depth = Math.max(1, t.depth);
981
+ const relationPath = t.segments.slice(0, depth).join(".");
982
+ pushParam(relationPath);
983
+ pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
984
+ if (t.segments.length === depth + 1) {
985
+ const base = t.segments[0];
986
+ const leaf = t.segments[depth];
987
+ const leaves = narrow.get(base) ?? [];
988
+ if (!leaves.includes(leaf)) leaves.push(leaf);
989
+ narrow.set(base, leaves);
990
+ }
991
+ }
992
+ }
993
+ return {
994
+ expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
995
+ fieldSelectors,
996
+ narrow
997
+ };
998
+ }
999
+ function applyExpandNarrowing(record, narrow) {
1000
+ if (narrow.size === 0) return record;
1001
+ const rec = record;
1002
+ const expand = rec.expand;
1003
+ if (!expand || typeof expand !== "object") return record;
1004
+ const next = { ...expand };
1005
+ for (const [relation, leaves] of narrow) {
1006
+ const value = next[relation];
1007
+ if (value === void 0 || value === null) continue;
1008
+ next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
1009
+ }
1010
+ return { ...rec, expand: next };
1011
+ }
1012
+
1013
+ // src/query-params.ts
1014
+ var MAX_PER_PAGE = 500;
1015
+ function clampBatch(batch) {
1016
+ if (!Number.isFinite(batch)) return MAX_PER_PAGE;
1017
+ return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
1018
+ }
1019
+ var TRANSPORT_KEYS = /* @__PURE__ */ new Set(["requestKey", "singleFlight", "fetch", "signal"]);
1020
+ function stableStringify(value) {
1021
+ const path = /* @__PURE__ */ new Set();
1022
+ const sort = (v, topLevel) => {
1023
+ if (Array.isArray(v)) return v.map((el) => sort(el, false));
1024
+ if (v && typeof v === "object") {
1025
+ const obj = v;
1026
+ if (path.has(obj)) return "[Circular]";
1027
+ path.add(obj);
1028
+ const out = {};
1029
+ for (const k of Object.keys(obj).sort()) {
1030
+ if (topLevel && TRANSPORT_KEYS.has(k)) continue;
1031
+ out[k] = sort(obj[k], false);
1032
+ }
1033
+ path.delete(obj);
1034
+ return out;
1035
+ }
1036
+ return v;
1037
+ };
1038
+ try {
1039
+ return JSON.stringify(sort(value, true));
1040
+ } catch {
1041
+ return String(value);
1042
+ }
1043
+ }
1044
+
1045
+ // src/paginate.ts
1046
+ var TRANSPORT_KEYS2 = /* @__PURE__ */ new Set([
1047
+ "requestKey",
1048
+ "autoCancel",
1049
+ "cancelKey",
1050
+ "singleFlight",
1051
+ "fetch",
1052
+ "headers",
1053
+ "signal",
1054
+ "params"
1055
+ ]);
1056
+ function splitListOptions(options) {
1057
+ const {
1058
+ batch: requestedBatch = MAX_PER_PAGE,
1059
+ page: _page,
1060
+ perPage: _perPage,
1061
+ ...rest
1062
+ } = options ?? {};
1063
+ const query = {};
1064
+ const transport = {};
1065
+ for (const [key, value] of Object.entries(rest)) {
1066
+ if (TRANSPORT_KEYS2.has(key)) transport[key] = value;
1067
+ else query[key] = value;
1068
+ }
1069
+ return {
1070
+ query,
1071
+ transport,
1072
+ batch: clampBatch(requestedBatch)
1073
+ };
1074
+ }
1075
+ function fullListKey(scope, query, requestKey) {
1076
+ if (typeof requestKey === "string") return requestKey;
1077
+ return `getFullList:${scope}:${stableStringify(query)}`;
1078
+ }
1079
+ async function paginateAll(batch, fetchPage) {
1080
+ const items = [];
1081
+ let page = 1;
1082
+ for (; ; ) {
1083
+ const res = await fetchPage(page, batch);
1084
+ if (!res || !res.items || res.items.length === 0) break;
1085
+ items.push(...res.items);
1086
+ if (page >= (res.totalPages ?? page)) break;
1087
+ page += 1;
1088
+ }
1089
+ return items;
1090
+ }
1091
+
1092
+ // src/collection/query.ts
1093
+ function buildListQuery(ctx, page, perPage, queryParams) {
1094
+ if (Array.isArray(queryParams.sort)) {
1095
+ queryParams.sort = queryParams.sort.join(",");
1096
+ }
1097
+ if (Array.isArray(queryParams.expand)) {
1098
+ queryParams.expand = queryParams.expand.join(",");
1099
+ }
1100
+ if (typeof queryParams.filter === "function") {
1101
+ queryParams.filter = ctx.resolveFilter(queryParams.filter);
1102
+ }
1103
+ const expandInfo = normalizeExpand(
1104
+ typeof queryParams.expand === "string" ? queryParams.expand : void 0,
1105
+ ctx.expand
1106
+ );
1107
+ if (expandInfo.expand !== void 0) {
1108
+ queryParams.expand = expandInfo.expand;
1109
+ }
1110
+ const fields = mergeExpandFields(
1111
+ ctx.effectiveFields(queryParams.fields),
1112
+ expandInfo
1113
+ );
1114
+ if (fields !== void 0) {
1115
+ queryParams.fields = fields;
1116
+ }
1117
+ const qs = new URLSearchParams(
1118
+ Object.fromEntries(
1119
+ Object.entries({
1120
+ // `page`/`perPage` are spread LAST so the call's positional arguments
1121
+ // win: with the caller's keys last, `getList(2, 30, { page: 5 })`
1122
+ // silently requested page 5, and `getFullList({ perPage: 1000 })`
1123
+ // slipped a >500 `perPage` past `clampBatch`.
1124
+ ...queryParams,
1125
+ page: String(page),
1126
+ perPage: String(perPage)
1127
+ }).map(([k, v]) => [k, String(v)])
1128
+ )
1129
+ ).toString();
1130
+ return { qs, narrow: expandInfo.narrow };
1131
+ }
1132
+ function buildReadQuery(ctx, options) {
1133
+ const rawExpand = Array.isArray(options?.expand) ? options.expand.join(",") : typeof options?.expand === "string" ? options.expand : void 0;
1134
+ const expandInfo = normalizeExpand(rawExpand, ctx.expand);
1135
+ const fields = mergeExpandFields(
1136
+ ctx.effectiveFields(options?.fields),
1137
+ expandInfo
1138
+ );
1139
+ const qs = new URLSearchParams();
1140
+ if (fields !== void 0) qs.set("fields", fields);
1141
+ if (rawExpand !== void 0) qs.set("expand", expandInfo.expand ?? rawExpand);
1142
+ return { qs: qs.toString(), narrow: expandInfo.narrow };
1143
+ }
1144
+
1145
+ // src/collection/paths.ts
1146
+ function encodeId(id) {
1147
+ return encodeURIComponent(id);
1148
+ }
1149
+ function recordsPath(collectionName) {
1150
+ return "/collections/" + encodeId(collectionName) + "/records";
1151
+ }
1152
+ function collectionPath(collectionName) {
1153
+ return "/collections/" + encodeId(collectionName);
1154
+ }
1155
+
1156
+ // src/collection/session.ts
1157
+ function rememberSession(ctx, data, model) {
1158
+ if (!data || !ctx.authStore) return;
1159
+ ctx.authStore.setCollectionName(ctx.collectionName);
1160
+ rememberAuthResponse(ctx.authStore, data, model);
1161
+ }
1162
+ function rememberSessionRecord(ctx, data) {
1163
+ const record = data?.["record"];
1164
+ const model = record && typeof record === "object" ? record : null;
1165
+ rememberSession(ctx, data, model);
1166
+ }
1167
+ async function postWithSession(ctx, path, body, options) {
1168
+ const data = await ctx.http.post(path, body, options);
1169
+ rememberSessionRecord(ctx, data);
1170
+ return data;
1171
+ }
1172
+
757
1173
  // src/oauth2.ts
758
1174
  var DEFAULT_POPUP_WIDTH = 500;
759
1175
  var DEFAULT_POPUP_HEIGHT = 700;
@@ -942,35 +1358,140 @@ function authorizeWithOAuth2Popup(opts) {
942
1358
  });
943
1359
  }
944
1360
 
945
- // src/collection.ts
946
- var MAX_PER_PAGE = 500;
947
- function clampBatch(batch) {
948
- if (!Number.isFinite(batch)) return MAX_PER_PAGE;
949
- return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
1361
+ // src/collection/auth.ts
1362
+ function authWithPassword(ctx, identity, password, options) {
1363
+ return postWithSession(
1364
+ ctx,
1365
+ collectionPath(ctx.collectionName) + "/auth-with-password",
1366
+ { identity, password },
1367
+ options
1368
+ );
950
1369
  }
951
- function stableStringify(value) {
952
- const seen = /* @__PURE__ */ new Set();
953
- const sort = (v) => {
954
- if (Array.isArray(v)) return v.map(sort);
955
- if (v && typeof v === "object") {
956
- if (seen.has(v)) return "[Circular]";
957
- seen.add(v);
958
- const out = {};
959
- for (const k of Object.keys(v).sort()) {
960
- if (k === "requestKey" || k === "singleFlight" || k === "fetch" || k === "signal") {
961
- continue;
962
- }
963
- out[k] = sort(v[k]);
964
- }
965
- return out;
1370
+ function authRefresh(ctx, options) {
1371
+ return postWithSession(
1372
+ ctx,
1373
+ collectionPath(ctx.collectionName) + "/auth-refresh",
1374
+ { refreshToken: ctx.authStore?.refreshToken },
1375
+ options
1376
+ );
1377
+ }
1378
+ function listAuthMethods(ctx, options) {
1379
+ return ctx.http.get(
1380
+ collectionPath(ctx.collectionName) + "/auth-methods",
1381
+ options
1382
+ );
1383
+ }
1384
+ async function requestPasswordReset(ctx, email, options) {
1385
+ await ctx.http.post(
1386
+ collectionPath(ctx.collectionName) + "/request-password-reset",
1387
+ { email },
1388
+ options
1389
+ );
1390
+ return true;
1391
+ }
1392
+ async function confirmPasswordReset(ctx, passwordResetToken, password, passwordConfirm, options) {
1393
+ await ctx.http.post(
1394
+ collectionPath(ctx.collectionName) + "/confirm-password-reset",
1395
+ { token: passwordResetToken, password, passwordConfirm },
1396
+ options
1397
+ );
1398
+ return true;
1399
+ }
1400
+ async function requestVerification(ctx, email, options) {
1401
+ await ctx.http.post(
1402
+ collectionPath(ctx.collectionName) + "/request-verification",
1403
+ { email },
1404
+ options
1405
+ );
1406
+ return true;
1407
+ }
1408
+ async function confirmVerification(ctx, verificationToken, options) {
1409
+ const data = await ctx.http.post(
1410
+ collectionPath(ctx.collectionName) + "/confirm-verification",
1411
+ { token: verificationToken },
1412
+ options
1413
+ );
1414
+ return data?.record ?? null;
1415
+ }
1416
+ async function requestEmailChange(ctx, newEmail, options) {
1417
+ await ctx.http.post(
1418
+ collectionPath(ctx.collectionName) + "/request-email-change",
1419
+ { newEmail },
1420
+ options
1421
+ );
1422
+ return true;
1423
+ }
1424
+ async function confirmEmailChange(ctx, emailChangeToken, password, options) {
1425
+ const data = await ctx.http.post(
1426
+ collectionPath(ctx.collectionName) + "/confirm-email-change",
1427
+ { token: emailChangeToken, password },
1428
+ options
1429
+ );
1430
+ return data?.record ?? null;
1431
+ }
1432
+ async function authWithOAuth2(ctx, options) {
1433
+ const {
1434
+ provider,
1435
+ createData,
1436
+ urlCallback,
1437
+ popup,
1438
+ timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1439
+ } = options;
1440
+ const methods = await listAuthMethods(ctx);
1441
+ const providerInfo = methods?.oauth2?.providers?.find(
1442
+ (p) => p.name === provider
1443
+ );
1444
+ if (!providerInfo) {
1445
+ throw new ApiError(
1446
+ `OAuth2 provider "${provider}" is not enabled for this collection.`,
1447
+ methods ?? {},
1448
+ 400,
1449
+ false,
1450
+ "oauth2_unknown_provider"
1451
+ );
1452
+ }
1453
+ const { code } = await authorizeWithOAuth2Popup({
1454
+ authURL: providerInfo.authURL,
1455
+ expectedOrigin: oauth2RedirectOrigin(ctx.http.baseUrl),
1456
+ urlCallback,
1457
+ popup,
1458
+ timeoutMs
1459
+ });
1460
+ return authWithOAuth2Code(ctx, {
1461
+ provider,
1462
+ code,
1463
+ codeVerifier: providerInfo.codeVerifier,
1464
+ createData
1465
+ });
1466
+ }
1467
+ async function authWithOAuth2Code(ctx, options) {
1468
+ const { provider, code, codeVerifier, redirectUrl, createData } = options;
1469
+ const data = await ctx.http.post(
1470
+ collectionPath(ctx.collectionName) + "/auth-with-oauth2",
1471
+ {
1472
+ provider,
1473
+ code,
1474
+ codeVerifier,
1475
+ redirectUrl: redirectUrl ?? ctx.http.baseUrl + "/oauth2-redirect",
1476
+ createData: createData ?? {}
966
1477
  }
967
- return v;
968
- };
969
- try {
970
- return JSON.stringify(sort(value));
971
- } catch {
972
- return String(value);
1478
+ );
1479
+ if (!data) {
1480
+ throw new ApiError(
1481
+ "OAuth2 code exchange returned no data.",
1482
+ {},
1483
+ 0,
1484
+ false,
1485
+ "oauth2_exchange_failed"
1486
+ );
973
1487
  }
1488
+ rememberSessionRecord(ctx, data);
1489
+ return data;
1490
+ }
1491
+
1492
+ // src/collection/realtime.ts
1493
+ function collectionTopic(collectionName) {
1494
+ return "collection:" + collectionName;
974
1495
  }
975
1496
  function normalizeAction(event, rawAction) {
976
1497
  if (typeof rawAction === "string") {
@@ -984,15 +1505,49 @@ function normalizeAction(event, rawAction) {
984
1505
  if (event === "delete" || event === "record_delete") return "delete";
985
1506
  return "update";
986
1507
  }
987
- function pickFields(value, fields) {
988
- if (!value || typeof value !== "object") return {};
989
- const src = value;
990
- const out = {};
991
- for (const f of fields) {
992
- if (f in src) out[f] = src[f];
1508
+ function subscribeToCollection(ctx, topicOrCallback, maybeCallback, options) {
1509
+ const { realtime, collectionName } = ctx;
1510
+ if (!realtime) {
1511
+ console.warn("[lazypock] No realtime service configured.");
1512
+ return () => {
1513
+ };
993
1514
  }
994
- return out;
1515
+ let recordId;
1516
+ let callback;
1517
+ let joinPayload;
1518
+ if (typeof topicOrCallback === "function") {
1519
+ callback = topicOrCallback;
1520
+ if (typeof maybeCallback === "string") recordId = maybeCallback;
1521
+ } else {
1522
+ callback = maybeCallback;
1523
+ recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1524
+ const { headers: _ignored, ...rest } = options ?? {};
1525
+ if (Object.keys(rest).length > 0) joinPayload = rest;
1526
+ }
1527
+ const topic = collectionTopic(collectionName) + (recordId ? ":" + recordId : "");
1528
+ const handler = (raw) => {
1529
+ const record = raw.payload?.["record"] ?? {};
1530
+ callback({
1531
+ action: normalizeAction(raw.event, raw.payload?.["action"]),
1532
+ record,
1533
+ topic: raw.topic
1534
+ });
1535
+ };
1536
+ realtime.ensureConnected();
1537
+ realtime.subscribe(topic, handler, joinPayload);
1538
+ return () => realtime.unsubscribe(topic, handler);
995
1539
  }
1540
+ function unsubscribeFromCollection(ctx, recordId) {
1541
+ const { realtime, collectionName } = ctx;
1542
+ if (recordId === void 0) {
1543
+ realtime?.unsubscribeByPrefix(collectionTopic(collectionName));
1544
+ return;
1545
+ }
1546
+ const topic = collectionTopic(collectionName) + (recordId === "*" ? "" : ":" + recordId);
1547
+ realtime?.unsubscribe(topic);
1548
+ }
1549
+
1550
+ // src/collection/index.ts
996
1551
  var CollectionService = class _CollectionService {
997
1552
  /** @internal */
998
1553
  constructor(http, collectionName, authStore, realtime, schema, schemaResolver) {
@@ -1003,21 +1558,42 @@ var CollectionService = class _CollectionService {
1003
1558
  this.schema = schema;
1004
1559
  this.schemaResolver = schemaResolver;
1005
1560
  }
1006
- encodeId(id) {
1007
- return encodeURIComponent(id);
1008
- }
1009
1561
  /**
1010
- * The records endpoint for this collection.
1562
+ * A copy of this service with the given overrides applied.
1011
1563
  *
1012
- * Centralised because the server's shape is `/api/collections/<name>/records`,
1013
- * and a path repeated eighteen times is a path that drifts.
1564
+ * Every field is listed exactly once, so a new service-level field can't be
1565
+ * silently dropped by `select()` or `withSchema()`.
1014
1566
  */
1567
+ derive(patch = {}) {
1568
+ const derived = new _CollectionService(
1569
+ this.http,
1570
+ this.collectionName,
1571
+ this.authStore,
1572
+ this.realtime,
1573
+ patch.schema ?? this.schema,
1574
+ this.schemaResolver
1575
+ );
1576
+ derived.fieldsPreset = patch.fieldsPreset ?? this.fieldsPreset;
1577
+ return derived;
1578
+ }
1579
+ /** The records endpoint for this collection. */
1015
1580
  recordsPath() {
1016
- return "/collections/" + this.encodeId(this.collectionName) + "/records";
1581
+ return recordsPath(this.collectionName);
1017
1582
  }
1018
1583
  /** The collection's own endpoint, which is where its auth routes live. */
1019
1584
  collectionPath() {
1020
- return "/collections/" + this.encodeId(this.collectionName);
1585
+ return collectionPath(this.collectionName);
1586
+ }
1587
+ encodeId(id) {
1588
+ return encodeId(id);
1589
+ }
1590
+ /** What the auth routes need: transport, collection name, session store. */
1591
+ sessionContext() {
1592
+ return {
1593
+ http: this.http,
1594
+ collectionName: this.collectionName,
1595
+ authStore: this.authStore
1596
+ };
1021
1597
  }
1022
1598
  // ── Field projection (`.select`) ──
1023
1599
  /**
@@ -1032,10 +1608,10 @@ var CollectionService = class _CollectionService {
1032
1608
  * const t = await client.collection("posts").select("id", "title").getList();
1033
1609
  * // GET /api/posts?fields=id,title
1034
1610
  *
1035
- * // All visible fields (implicit system keys id/created/updated/… are
1611
+ * // All visible fields (implicit system keys id/created/updated/... are
1036
1612
  * // kept; hidden fields are excluded via the projection)
1037
1613
  * const all = await client.collection("posts").select("*").getList();
1038
- * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,… (schema known)
1614
+ * // GET /api/posts?fields=id,created,updated,collectionId,collectionName,title,published,... (schema known)
1039
1615
  * ```
1040
1616
  *
1041
1617
  * When no schema is known, the default (no `select()` call) sends no
@@ -1044,17 +1620,12 @@ var CollectionService = class _CollectionService {
1044
1620
  */
1045
1621
  select(...fields) {
1046
1622
  const preset = fields.length === 0 ? "*" : fields.join(",");
1047
- const derived = new _CollectionService(
1048
- this.http,
1049
- this.collectionName,
1050
- this.authStore,
1051
- this.realtime,
1052
- this.schema,
1053
- this.schemaResolver
1054
- );
1055
- derived.fieldsPreset = preset;
1623
+ const derived = this.derive({ fieldsPreset: preset });
1056
1624
  if (this.schema && preset !== "*") {
1057
- const known = new Set(this.schema.fields?.map((f) => f.name) ?? []);
1625
+ const known = /* @__PURE__ */ new Set([
1626
+ ...SYSTEM_FIELDS,
1627
+ ...this.schema.fields?.map((f) => f.name) ?? []
1628
+ ]);
1058
1629
  for (const f of fields) {
1059
1630
  if (!known.has(f)) {
1060
1631
  console.warn(
@@ -1073,14 +1644,7 @@ var CollectionService = class _CollectionService {
1073
1644
  * system keys (`id`, `created`, `updated`, `collectionId`, `collectionName`)
1074
1645
  */
1075
1646
  effectiveFields(optionsFields) {
1076
- if (optionsFields !== void 0) return optionsFields;
1077
- if (this.fieldsPreset !== void 0) {
1078
- if (this.fieldsPreset === "*") {
1079
- return this.visibleFields();
1080
- }
1081
- return this.fieldsPreset;
1082
- }
1083
- return this.visibleFields();
1647
+ return effectiveFields(this.schema, this.fieldsPreset, optionsFields);
1084
1648
  }
1085
1649
  /**
1086
1650
  * All non-hidden, non-password, non-autodate field names from the schema,
@@ -1097,21 +1661,23 @@ var CollectionService = class _CollectionService {
1097
1661
  * default returns every non-password field, including the system keys).
1098
1662
  */
1099
1663
  visibleFields() {
1100
- if (!this.schema?.fields) return void 0;
1101
- const visible = this.schema.fields.filter(
1102
- (f) => !f.hidden && f.type !== "password" && f.type !== "autodate"
1103
- ).map((f) => f.name);
1104
- if (visible.length === 0) return void 0;
1105
- return [
1106
- .../* @__PURE__ */ new Set([
1107
- "id",
1108
- "created",
1109
- "updated",
1110
- "collectionId",
1111
- "collectionName",
1112
- ...visible
1113
- ])
1114
- ].join(",");
1664
+ return visibleFields(this.schema);
1665
+ }
1666
+ /** Service state that query building needs. */
1667
+ queryContext() {
1668
+ return {
1669
+ expand: this.expandContext(),
1670
+ effectiveFields: (optionsFields) => this.effectiveFields(optionsFields),
1671
+ resolveFilter: (filter) => this.resolveFilter(filter)
1672
+ };
1673
+ }
1674
+ /** Context for the schema-aware expand helpers. */
1675
+ expandContext() {
1676
+ return {
1677
+ collectionName: this.collectionName,
1678
+ schema: this.schema,
1679
+ resolveCollection: (key) => this.schemaResolver?.(key)
1680
+ };
1115
1681
  }
1116
1682
  // ── Typed filter builder ──
1117
1683
  /**
@@ -1124,7 +1690,7 @@ var CollectionService = class _CollectionService {
1124
1690
  * await posts.getList(1, 20, {
1125
1691
  * filter: q("title").contains("x").and(q("published").eq(true)),
1126
1692
  * });
1127
- * // → filter=(title ~ '%x%' && published = true)
1693
+ * // → filter=(title ~ 'x' && published = true)
1128
1694
  *
1129
1695
  * // PocketBase `?` array operators (multi-select / multi-relation):
1130
1696
  * posts.getList(1, 20, { filter: q("tags").anyEq("news") });
@@ -1150,230 +1716,6 @@ var CollectionService = class _CollectionService {
1150
1716
  }
1151
1717
  return filter((field) => this.where(field));
1152
1718
  }
1153
- /**
1154
- * Resolve the leading relation chain of an expand token against the
1155
- * (optionally schema-aware) collection graph.
1156
- *
1157
- * Walks `segments` from this collection: each segment that is a relation
1158
- * advances to its target collection. Stops at the first non-relation
1159
- * segment or when the target schema is unknown.
1160
- *
1161
- * @returns `depth` — how many leading segments are relations; and
1162
- * `canInspect` — whether the schema at `depth` is known (so the next
1163
- * segment can be classified as a field selection vs a nested relation).
1164
- */
1165
- resolveRelationChain(segments) {
1166
- let currentFields = this.schema?.fields;
1167
- if (!currentFields) return { depth: 0, canInspect: false };
1168
- for (let i = 0; i < segments.length; i++) {
1169
- const field = currentFields.find((f) => f.name === segments[i]);
1170
- if (!field || field.type !== "relation") {
1171
- return { depth: i, canInspect: true };
1172
- }
1173
- if (i === segments.length - 1) {
1174
- return { depth: segments.length, canInspect: true };
1175
- }
1176
- const target = this.resolveTargetCollection(field);
1177
- if (!target?.fields) {
1178
- return { depth: i + 1, canInspect: false };
1179
- }
1180
- currentFields = target.fields;
1181
- }
1182
- return { depth: segments.length, canInspect: true };
1183
- }
1184
- /** Follow a relation field to its target collection, if resolvable. */
1185
- resolveTargetCollection(field) {
1186
- const key = field.options?.collection ?? field.options?.collectionId ?? field.collectionId ?? void 0;
1187
- if (!key || !this.schemaResolver) return void 0;
1188
- return this.schemaResolver(String(key));
1189
- }
1190
- /** Warn once when an expand field is not a relation (schema known). */
1191
- warnNonRelation(name) {
1192
- console.warn(
1193
- `[lazypock] expand("${name}"): field is not a relation on collection "${this.collectionName}"`
1194
- );
1195
- }
1196
- /**
1197
- * Validate and normalise a caller's `expand` string.
1198
- *
1199
- * PocketBase only expands *relations*: a dotted token like `author.user`
1200
- * walks into the related record. Callers often use a dotted token to mean
1201
- * "only these fields of the expanded record" (`owner.name,owner.email`),
1202
- * which PocketBase silently drops. When the trailing segment is not a
1203
- * relation — resolved from the schema graph — the token is rewritten as a
1204
- * field selection:
1205
- *
1206
- * ```
1207
- * expand: 'owner.name,owner.email'
1208
- * → expand=owner&fields=<base>,expand.owner.name,expand.owner.email
1209
- * ```
1210
- *
1211
- * Tokens whose whole path is relations keep their existing nested-expand
1212
- * behaviour. Without a schema the two are indistinguishable, so a lone
1213
- * dotted token stays a nested expand (with a warning) while two or more
1214
- * dotted tokens sharing the same relation are treated as field selection.
1215
- */
1216
- normalizeExpand(expand) {
1217
- const narrow = /* @__PURE__ */ new Map();
1218
- if (!expand) return { fieldSelectors: [], narrow };
1219
- const tokens = expand.split(",").map((t) => t.trim()).filter(Boolean);
1220
- if (tokens.length === 0) return { fieldSelectors: [], narrow };
1221
- const relations = this.schema?.fields ? new Set(
1222
- this.schema.fields.filter((f) => f.type === "relation").map((f) => f.name)
1223
- ) : void 0;
1224
- const parsed = [];
1225
- for (const token of tokens) {
1226
- const segments = token.split(".").filter(Boolean);
1227
- const base = segments[0] ?? token;
1228
- if (segments.length <= 1) {
1229
- if (relations && !relations.has(base)) {
1230
- this.warnNonRelation(base);
1231
- }
1232
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1233
- continue;
1234
- }
1235
- if (!relations) {
1236
- parsed.push({ token, base, segments, kind: "unknown", depth: 1 });
1237
- continue;
1238
- }
1239
- const { depth, canInspect } = this.resolveRelationChain(segments);
1240
- if (depth === 0) {
1241
- this.warnNonRelation(base);
1242
- parsed.push({ token, base, segments, kind: "plain", depth: 0 });
1243
- } else if (depth === segments.length) {
1244
- parsed.push({ token, base, segments, kind: "nested", depth });
1245
- } else if (canInspect) {
1246
- parsed.push({ token, base, segments, kind: "narrow", depth });
1247
- } else {
1248
- parsed.push({ token, base, segments, kind: "unknown", depth });
1249
- }
1250
- }
1251
- const byBase = /* @__PURE__ */ new Map();
1252
- for (const t of parsed) {
1253
- const arr = byBase.get(t.base);
1254
- if (arr) arr.push(t);
1255
- else byBase.set(t.base, [t]);
1256
- }
1257
- for (const [base, group] of byBase) {
1258
- const unknowns = group.filter((t) => t.kind === "unknown");
1259
- if (unknowns.length === 0) continue;
1260
- const distinct = new Set(unknowns.map((t) => t.token));
1261
- const hasNarrow = group.some((t) => t.kind === "narrow");
1262
- if (!hasNarrow && distinct.size < 2) {
1263
- for (const t of unknowns) {
1264
- t.kind = "nested";
1265
- console.warn(
1266
- `[lazypock] expand("${t.token}"): treated as a nested relation. Pass types.schemas (or use fields=) to select fields of "${base}".`
1267
- );
1268
- }
1269
- } else {
1270
- for (const t of unknowns) t.kind = "narrow";
1271
- }
1272
- }
1273
- const expandParams = [];
1274
- const expandSeen = /* @__PURE__ */ new Set();
1275
- const fieldSelectors = [];
1276
- const selectorSeen = /* @__PURE__ */ new Set();
1277
- const pushParam = (p) => {
1278
- if (!expandSeen.has(p)) {
1279
- expandSeen.add(p);
1280
- expandParams.push(p);
1281
- }
1282
- };
1283
- const pushSelector = (s) => {
1284
- if (!selectorSeen.has(s)) {
1285
- selectorSeen.add(s);
1286
- fieldSelectors.push(s);
1287
- }
1288
- };
1289
- for (const t of parsed) {
1290
- if (t.kind === "plain") {
1291
- pushParam(t.token);
1292
- pushSelector(`expand.${t.token}`);
1293
- } else if (t.kind === "nested") {
1294
- for (let i = 1; i <= t.segments.length; i++) {
1295
- pushParam(t.segments.slice(0, i).join("."));
1296
- }
1297
- pushSelector(`expand.${t.segments[0]}`);
1298
- } else {
1299
- const depth = Math.max(1, t.depth);
1300
- const relationPath = t.segments.slice(0, depth).join(".");
1301
- pushParam(relationPath);
1302
- pushSelector(`expand.${t.segments.slice(0, depth + 1).join(".")}`);
1303
- if (t.segments.length === depth + 1) {
1304
- const base = t.segments[0];
1305
- const leaf = t.segments[depth];
1306
- const leaves = narrow.get(base) ?? [];
1307
- if (!leaves.includes(leaf)) leaves.push(leaf);
1308
- narrow.set(base, leaves);
1309
- }
1310
- }
1311
- }
1312
- return {
1313
- expand: expandParams.length > 0 ? expandParams.join(",") : void 0,
1314
- fieldSelectors,
1315
- narrow
1316
- };
1317
- }
1318
- /**
1319
- * Keep only the requested leaf fields on `record.expand.<relation>`.
1320
- *
1321
- * Mirrors PocketBase's server-side `fields=expand.<rel>.<field>` projection
1322
- * for servers that don't support it (the LazyPock server), so field
1323
- * selection behaves the same against both. A no-op when the server already
1324
- * narrowed the record. Multi-relations are narrowed element-wise.
1325
- */
1326
- applyExpandNarrowing(record, narrow) {
1327
- if (narrow.size === 0) return record;
1328
- const rec = record;
1329
- const expand = rec.expand;
1330
- if (!expand || typeof expand !== "object") return record;
1331
- const next = { ...expand };
1332
- for (const [relation, leaves] of narrow) {
1333
- const value = next[relation];
1334
- if (value === void 0 || value === null) continue;
1335
- next[relation] = Array.isArray(value) ? value.map((el) => pickFields(el, leaves)) : pickFields(value, leaves);
1336
- }
1337
- return { ...rec, expand: next };
1338
- }
1339
- /**
1340
- * Merge the expand-preserving selectors into the base field projection.
1341
- *
1342
- * Both servers are kept happy at once:
1343
- * - PocketBase drops the whole `expand` payload unless an `expand.<key>`
1344
- * entry is present in `fields`;
1345
- * - the LazyPock server projects first (strict, top-level only) and then
1346
- * expands, so the relation *field* itself must be present in `fields`.
1347
- *
1348
- * We therefore add both the relation field (`cate`) and the
1349
- * `expand.<key>` entry. When no projection is active, no `fields` param is
1350
- * sent at all — a value like `*` plus other tokens is not a wildcard on
1351
- * the LazyPock server (it is a strict take, yielding empty records) and
1352
- * the server keeps `expand` by default when `fields` is absent.
1353
- */
1354
- mergeExpandFields(base, info) {
1355
- if (info.fieldSelectors.length === 0) return base;
1356
- if (base === void 0) return void 0;
1357
- const parts = base.split(",").map((f) => f.trim()).filter(Boolean);
1358
- const seen = new Set(parts);
1359
- const push = (value) => {
1360
- if (seen.has(value)) return;
1361
- seen.add(value);
1362
- parts.push(value);
1363
- };
1364
- const fullKeys = /* @__PURE__ */ new Set();
1365
- for (const selector of info.fieldSelectors) {
1366
- const seg = selector.split(".");
1367
- if (seg.length === 2) fullKeys.add(seg[1]);
1368
- }
1369
- for (const selector of info.fieldSelectors) {
1370
- const seg = selector.split(".");
1371
- if (seg.length > 2 && fullKeys.has(seg[1])) continue;
1372
- if (seg.length >= 2) push(seg[1]);
1373
- push(selector);
1374
- }
1375
- return parts.join(",");
1376
- }
1377
1719
  /**
1378
1720
  * Fetch a paginated list of records (PocketBase `getList`).
1379
1721
  *
@@ -1382,50 +1724,13 @@ var CollectionService = class _CollectionService {
1382
1724
  * @param options Query params (`filter`, `sort`, `expand`, `fields`) + request options.
1383
1725
  */
1384
1726
  async getList(page = 1, perPage = 30, options) {
1385
- const {
1386
- requestKey,
1387
- autoCancel,
1388
- cancelKey,
1389
- fetch: fetch2,
1390
- headers,
1391
- signal,
1392
- singleFlight,
1393
- params,
1394
- ...queryParams
1395
- } = options ?? {};
1396
- if (Array.isArray(queryParams.sort)) {
1397
- queryParams.sort = queryParams.sort.join(",");
1398
- }
1399
- if (Array.isArray(queryParams.expand)) {
1400
- queryParams.expand = queryParams.expand.join(",");
1401
- }
1402
- if (typeof queryParams.filter === "function") {
1403
- queryParams.filter = this.resolveFilter(
1404
- queryParams.filter
1405
- );
1406
- }
1407
- const expandInfo = this.normalizeExpand(
1408
- typeof queryParams.expand === "string" ? queryParams.expand : void 0
1727
+ const { requestKey, autoCancel, cancelKey, fetch: fetch2, headers, signal, singleFlight, params, ...queryParams } = options ?? {};
1728
+ const { qs, narrow } = buildListQuery(
1729
+ this.queryContext(),
1730
+ page,
1731
+ perPage,
1732
+ queryParams
1409
1733
  );
1410
- if (expandInfo.expand !== void 0) {
1411
- queryParams.expand = expandInfo.expand;
1412
- }
1413
- const fields = this.mergeExpandFields(
1414
- this.effectiveFields(queryParams.fields),
1415
- expandInfo
1416
- );
1417
- if (fields !== void 0) {
1418
- queryParams.fields = fields;
1419
- }
1420
- const qs = new URLSearchParams(
1421
- Object.fromEntries(
1422
- Object.entries({
1423
- page: String(page),
1424
- perPage: String(perPage),
1425
- ...queryParams
1426
- }).map(([k, v]) => [k, String(v)])
1427
- )
1428
- ).toString();
1429
1734
  const result = await this.http.get(this.recordsPath() + "?" + qs, {
1430
1735
  requestKey,
1431
1736
  autoCancel,
@@ -1436,44 +1741,41 @@ var CollectionService = class _CollectionService {
1436
1741
  singleFlight,
1437
1742
  params
1438
1743
  });
1439
- if (result && expandInfo.narrow.size > 0) {
1744
+ if (result && narrow.size > 0) {
1440
1745
  result.items = result.items.map(
1441
- (item) => this.applyExpandNarrowing(item, expandInfo.narrow)
1746
+ (item) => applyExpandNarrowing(item, narrow)
1442
1747
  );
1443
1748
  }
1444
1749
  return result;
1445
1750
  }
1446
1751
  /**
1447
- * Fetch all records at once (auto-paginates; `batch` defaults to and is capped at 500, the server max `perPage`). Mirrors PocketBase's
1752
+ * Fetch all records at once (auto-paginates; `batch` defaults to and is
1753
+ * capped at 500, the server max `perPage`). Mirrors PocketBase's
1448
1754
  * `pb.collection(name).getFullList()`.
1449
1755
  *
1450
1756
  * @param options Query params (`sort`, `filter`, `batch`, etc.) + request options.
1451
1757
  */
1452
1758
  async getFullList(options) {
1453
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
1454
- const batch = clampBatch(requestedBatch);
1455
- if (typeof rest.filter === "function") {
1456
- rest.filter = this.resolveFilter(rest.filter);
1457
- }
1458
- const effectiveKey = typeof rest.requestKey === "string" ? rest.requestKey : `getFullList:${this.collectionName}:${stableStringify(rest)}`;
1459
- const items = [];
1460
- let page = 1;
1461
- for (; ; ) {
1462
- const res = await this.getList(
1463
- page,
1464
- batch,
1465
- {
1466
- ...rest,
1467
- requestKey: effectiveKey,
1468
- singleFlight: true
1469
- }
1470
- );
1471
- if (!res || !res.items || res.items.length === 0) break;
1472
- items.push(...res.items);
1473
- if (page >= (res.totalPages ?? page)) break;
1474
- page += 1;
1759
+ const { query, transport, batch } = splitListOptions(
1760
+ options
1761
+ );
1762
+ if (typeof query.filter === "function") {
1763
+ query.filter = this.resolveFilter(query.filter);
1475
1764
  }
1476
- return items;
1765
+ const effectiveKey = fullListKey(
1766
+ this.collectionName,
1767
+ query,
1768
+ transport.requestKey
1769
+ );
1770
+ return paginateAll(
1771
+ batch,
1772
+ (page) => this.getList(page, batch, {
1773
+ ...query,
1774
+ ...transport,
1775
+ requestKey: effectiveKey,
1776
+ singleFlight: true
1777
+ })
1778
+ );
1477
1779
  }
1478
1780
  /**
1479
1781
  * Fetch the first record matching a filter (PocketBase `getFirstListItem`).
@@ -1494,29 +1796,13 @@ var CollectionService = class _CollectionService {
1494
1796
  * @param options Optional request options.
1495
1797
  */
1496
1798
  async getOne(id, options) {
1497
- let rawExpand;
1498
- if (Array.isArray(options?.expand)) {
1499
- rawExpand = options.expand.join(",");
1500
- } else if (typeof options?.expand === "string") {
1501
- rawExpand = options.expand;
1502
- }
1503
- const expandInfo = this.normalizeExpand(rawExpand);
1504
- const fields = this.mergeExpandFields(
1505
- this.effectiveFields(options?.fields),
1506
- expandInfo
1507
- );
1508
- const qs = new URLSearchParams();
1509
- if (fields !== void 0) qs.set("fields", fields);
1510
- if (rawExpand !== void 0) {
1511
- qs.set("expand", expandInfo.expand ?? rawExpand);
1512
- }
1513
- const qsStr = qs.toString();
1799
+ const { qs, narrow } = buildReadQuery(this.queryContext(), options);
1514
1800
  const record = await this.http.get(
1515
- this.recordsPath() + "/" + this.encodeId(id) + (qsStr ? "?" + qsStr : ""),
1801
+ this.recordsPath() + "/" + this.encodeId(id) + (qs ? "?" + qs : ""),
1516
1802
  options
1517
1803
  );
1518
- if (record && expandInfo.narrow.size > 0) {
1519
- return this.applyExpandNarrowing(record, expandInfo.narrow);
1804
+ if (record && narrow.size > 0) {
1805
+ return applyExpandNarrowing(record, narrow);
1520
1806
  }
1521
1807
  return record;
1522
1808
  }
@@ -1558,13 +1844,12 @@ var CollectionService = class _CollectionService {
1558
1844
  options
1559
1845
  );
1560
1846
  }
1561
- // ── Expand / Relation Fields ──
1562
1847
  /**
1563
1848
  * Get a list of expandable (relation) fields for this collection.
1564
1849
  * Useful for constructing `expand` query parameters.
1565
1850
  */
1566
1851
  async expandFields(options) {
1567
- const data = await this.http.get("/collections/" + this.encodeId(this.collectionName), options);
1852
+ const data = await this.http.get(this.collectionPath(), options);
1568
1853
  if (!data?.fields) return null;
1569
1854
  return data.fields.filter((f) => f.type === "relation" && f.options?.collection).map((f) => ({
1570
1855
  field: f.name,
@@ -1597,47 +1882,15 @@ var CollectionService = class _CollectionService {
1597
1882
  * excluded from responses, select/expand are validated.
1598
1883
  */
1599
1884
  withSchema(schema) {
1600
- const derived = new _CollectionService(
1601
- this.http,
1602
- this.collectionName,
1603
- this.authStore,
1604
- this.realtime,
1605
- schema,
1606
- this.schemaResolver
1607
- );
1608
- derived.fieldsPreset = this.fieldsPreset;
1609
- return derived;
1885
+ return this.derive({ schema });
1610
1886
  }
1611
1887
  subscribe(topicOrCallback, maybeCallback, options) {
1612
- if (!this.realtime) {
1613
- console.warn("[lazypock] No realtime service configured.");
1614
- return () => {
1615
- };
1616
- }
1617
- let recordId;
1618
- let callback;
1619
- let joinPayload;
1620
- if (typeof topicOrCallback === "function") {
1621
- callback = topicOrCallback;
1622
- if (typeof maybeCallback === "string") recordId = maybeCallback;
1623
- } else {
1624
- callback = maybeCallback;
1625
- recordId = topicOrCallback === "*" ? void 0 : topicOrCallback;
1626
- const { headers: _ignored, ...rest } = options ?? {};
1627
- if (Object.keys(rest).length > 0) joinPayload = rest;
1628
- }
1629
- const topic = "collection:" + this.collectionName + (recordId ? ":" + recordId : "");
1630
- const handler = (raw) => {
1631
- const record = raw.payload?.["record"] ?? {};
1632
- callback({
1633
- action: normalizeAction(raw.event, raw.payload?.["action"]),
1634
- record,
1635
- topic: raw.topic
1636
- });
1637
- };
1638
- this.realtime.ensureConnected();
1639
- this.realtime.subscribe(topic, handler, joinPayload);
1640
- return () => this.realtime?.unsubscribe(topic, handler);
1888
+ return subscribeToCollection(
1889
+ { realtime: this.realtime, collectionName: this.collectionName },
1890
+ topicOrCallback,
1891
+ maybeCallback,
1892
+ options
1893
+ );
1641
1894
  }
1642
1895
  /**
1643
1896
  * Unsubscribe from realtime changes (PocketBase-compatible):
@@ -1646,66 +1899,33 @@ var CollectionService = class _CollectionService {
1646
1899
  * - `unsubscribe('RECORD_ID')` — remove that record's subscriptions
1647
1900
  */
1648
1901
  unsubscribe(recordId) {
1649
- if (recordId === void 0) {
1650
- this.realtime?.unsubscribeByPrefix(
1651
- "collection:" + this.collectionName
1652
- );
1653
- return;
1654
- }
1655
- const topic = "collection:" + this.collectionName + (recordId === "*" ? "" : ":" + recordId);
1656
- this.realtime?.unsubscribe(topic);
1902
+ unsubscribeFromCollection(
1903
+ { realtime: this.realtime, collectionName: this.collectionName },
1904
+ recordId
1905
+ );
1657
1906
  }
1658
1907
  // ── Auth Collection Methods ──
1659
1908
  /**
1660
1909
  * Authenticate with email/password against this auth collection.
1661
1910
  * Stores the returned token and user model in the auth store.
1662
1911
  */
1663
- async authWithPassword(identity, password, options) {
1664
- const data = await this.http.post(
1665
- this.collectionPath() + "/auth-with-password",
1666
- { identity, password },
1667
- options
1668
- );
1669
- if (data && this.authStore) {
1670
- this.authStore.setCollectionName(this.collectionName);
1671
- rememberAuthResponse(
1672
- this.authStore,
1673
- data,
1674
- data.record
1675
- );
1676
- }
1677
- return data;
1912
+ authWithPassword(identity, password, options) {
1913
+ return authWithPassword(this.sessionContext(), identity, password, options);
1678
1914
  }
1679
1915
  /**
1680
1916
  * Refresh the auth token for the currently authenticated user.
1681
1917
  * Updates the stored token and user model.
1682
1918
  */
1683
- async authRefresh(options) {
1684
- const data = await this.http.post(
1685
- this.collectionPath() + "/auth-refresh",
1686
- { refreshToken: this.authStore?.refreshToken },
1687
- options
1688
- );
1689
- if (data && this.authStore) {
1690
- this.authStore.setCollectionName(this.collectionName);
1691
- rememberAuthResponse(
1692
- this.authStore,
1693
- data,
1694
- data.record
1695
- );
1696
- }
1697
- return data;
1919
+ authRefresh(options) {
1920
+ return authRefresh(this.sessionContext(), options);
1698
1921
  }
1699
1922
  /**
1700
1923
  * Get available auth methods for this collection (PocketBase `listAuthMethods`).
1701
1924
  * Returns `password`, `oauth2.providers` (each with `name`, `authURL`,
1702
1925
  * `state`, `codeVerifier`), and `mfa`.
1703
1926
  */
1704
- async listAuthMethods(options) {
1705
- return this.http.get(
1706
- this.collectionPath() + "/auth-methods",
1707
- options
1708
- );
1927
+ listAuthMethods(options) {
1928
+ return listAuthMethods(this.sessionContext(), options);
1709
1929
  }
1710
1930
  /**
1711
1931
  * Get available auth methods for this collection.
@@ -1720,13 +1940,8 @@ var CollectionService = class _CollectionService {
1720
1940
  * `requestPasswordReset`). The backend always answers 204 to avoid
1721
1941
  * revealing whether the address exists.
1722
1942
  */
1723
- async requestPasswordReset(email, options) {
1724
- await this.http.post(
1725
- this.collectionPath() + "/request-password-reset",
1726
- { email },
1727
- options
1728
- );
1729
- return true;
1943
+ requestPasswordReset(email, options) {
1944
+ return requestPasswordReset(this.sessionContext(), email, options);
1730
1945
  }
1731
1946
  /**
1732
1947
  * Confirm a password reset (PocketBase `confirmPasswordReset`).
@@ -1735,63 +1950,49 @@ var CollectionService = class _CollectionService {
1735
1950
  * @param password The new password (min 8 chars server-side).
1736
1951
  * @param passwordConfirm Must equal `password`.
1737
1952
  */
1738
- async confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1739
- await this.http.post(
1740
- this.collectionPath() + "/confirm-password-reset",
1741
- { token: passwordResetToken, password, passwordConfirm },
1953
+ confirmPasswordReset(passwordResetToken, password, passwordConfirm, options) {
1954
+ return confirmPasswordReset(
1955
+ this.sessionContext(),
1956
+ passwordResetToken,
1957
+ password,
1958
+ passwordConfirm,
1742
1959
  options
1743
1960
  );
1744
- return true;
1745
1961
  }
1746
1962
  /**
1747
1963
  * Send a verification email to the given address (PocketBase
1748
1964
  * `requestVerification`). The backend always answers 204 to avoid
1749
1965
  * revealing whether the address exists.
1750
1966
  */
1751
- async requestVerification(email, options) {
1752
- await this.http.post(
1753
- this.collectionPath() + "/request-verification",
1754
- { email },
1755
- options
1756
- );
1757
- return true;
1967
+ requestVerification(email, options) {
1968
+ return requestVerification(this.sessionContext(), email, options);
1758
1969
  }
1759
1970
  /**
1760
1971
  * Confirm an email verification (PocketBase `confirmVerification`).
1761
1972
  * Resolves with the verified auth record.
1762
1973
  */
1763
- async confirmVerification(verificationToken, options) {
1764
- const data = await this.http.post(
1765
- this.collectionPath() + "/confirm-verification",
1766
- { token: verificationToken },
1767
- options
1768
- );
1769
- return data?.record ?? null;
1974
+ confirmVerification(verificationToken, options) {
1975
+ return confirmVerification(this.sessionContext(), verificationToken, options);
1770
1976
  }
1771
1977
  /**
1772
1978
  * Send an email-change confirmation email to a new address (PocketBase
1773
1979
  * `requestEmailChange`). Requires an authenticated auth-collection user.
1774
1980
  */
1775
- async requestEmailChange(newEmail, options) {
1776
- await this.http.post(
1777
- this.collectionPath() + "/request-email-change",
1778
- { newEmail },
1779
- options
1780
- );
1781
- return true;
1981
+ requestEmailChange(newEmail, options) {
1982
+ return requestEmailChange(this.sessionContext(), newEmail, options);
1782
1983
  }
1783
1984
  /**
1784
1985
  * Confirm an email change (PocketBase `confirmEmailChange`). Requires the
1785
1986
  * currently authenticated user's password. Resolves with the updated auth
1786
1987
  * record.
1787
1988
  */
1788
- async confirmEmailChange(emailChangeToken, password, options) {
1789
- const data = await this.http.post(
1790
- this.collectionPath() + "/confirm-email-change",
1791
- { token: emailChangeToken, password },
1989
+ confirmEmailChange(emailChangeToken, password, options) {
1990
+ return confirmEmailChange(
1991
+ this.sessionContext(),
1992
+ emailChangeToken,
1993
+ password,
1792
1994
  options
1793
1995
  );
1794
- return data?.record ?? null;
1795
1996
  }
1796
1997
  /**
1797
1998
  * Sign in with an OAuth2 provider (PocketBase `authWithOAuth2` parity).
@@ -1808,40 +2009,8 @@ var CollectionService = class _CollectionService {
1808
2009
  * `window.postMessage`. Use {@link listAuthMethods} + {@link authWithOAuth2Code}
1809
2010
  * instead.
1810
2011
  */
1811
- async authWithOAuth2(options) {
1812
- const {
1813
- provider,
1814
- createData,
1815
- urlCallback,
1816
- popup,
1817
- timeoutMs = DEFAULT_OAUTH2_TIMEOUT_MS
1818
- } = options;
1819
- const methods = await this.listAuthMethods();
1820
- const providerInfo = methods?.oauth2?.providers?.find(
1821
- (p) => p.name === provider
1822
- );
1823
- if (!providerInfo) {
1824
- throw new ApiError(
1825
- `OAuth2 provider "${provider}" is not enabled for this collection.`,
1826
- methods ?? {},
1827
- 400,
1828
- false,
1829
- "oauth2_unknown_provider"
1830
- );
1831
- }
1832
- const { code } = await authorizeWithOAuth2Popup({
1833
- authURL: providerInfo.authURL,
1834
- expectedOrigin: oauth2RedirectOrigin(this.http.baseUrl),
1835
- urlCallback,
1836
- popup,
1837
- timeoutMs
1838
- });
1839
- return this.authWithOAuth2Code({
1840
- provider,
1841
- code,
1842
- codeVerifier: providerInfo.codeVerifier,
1843
- createData
1844
- });
2012
+ authWithOAuth2(options) {
2013
+ return authWithOAuth2(this.sessionContext(), options);
1845
2014
  }
1846
2015
  /**
1847
2016
  * Exchange an OAuth2 authorization code directly (PocketBase
@@ -1852,36 +2021,8 @@ var CollectionService = class _CollectionService {
1852
2021
  * capture the `code` from your redirect/deep link, then call this to
1853
2022
  * finish and populate the auth store.
1854
2023
  */
1855
- async authWithOAuth2Code(options) {
1856
- const { provider, code, codeVerifier, redirectUrl, createData } = options;
1857
- const data = await this.http.post(
1858
- this.collectionPath() + "/auth-with-oauth2",
1859
- {
1860
- provider,
1861
- code,
1862
- codeVerifier,
1863
- redirectUrl: redirectUrl ?? this.http.baseUrl + "/oauth2-redirect",
1864
- createData: createData ?? {}
1865
- }
1866
- );
1867
- if (!data) {
1868
- throw new ApiError(
1869
- "OAuth2 code exchange returned no data.",
1870
- {},
1871
- 0,
1872
- false,
1873
- "oauth2_exchange_failed"
1874
- );
1875
- }
1876
- if (this.authStore) {
1877
- this.authStore.setCollectionName(this.collectionName);
1878
- rememberAuthResponse(
1879
- this.authStore,
1880
- data,
1881
- data.record
1882
- );
1883
- }
1884
- return data;
2024
+ authWithOAuth2Code(options) {
2025
+ return authWithOAuth2Code(this.sessionContext(), options);
1885
2026
  }
1886
2027
  };
1887
2028
 
@@ -1948,6 +2089,7 @@ var RealtimeService = class {
1948
2089
  ensureConnected() {
1949
2090
  if (this.open || this.controller || !this.url) return;
1950
2091
  if (this.serverTopics().length === 0) return;
2092
+ this.closed = false;
1951
2093
  this.doConnect();
1952
2094
  }
1953
2095
  connect(opts) {
@@ -2148,6 +2290,10 @@ var RealtimeService = class {
2148
2290
  function encodeKey(key) {
2149
2291
  return key.split("/").map(encodeURIComponent).join("/");
2150
2292
  }
2293
+ function uploadFileName(file, fallback = "file") {
2294
+ if (typeof File !== "undefined" && file instanceof File) return file.name;
2295
+ return fallback;
2296
+ }
2151
2297
  function getFileUrl(baseUrl, key) {
2152
2298
  return baseUrl.replace(/\/+$/, "") + "/files/" + encodeKey(key);
2153
2299
  }
@@ -2194,7 +2340,7 @@ var FilesService = class {
2194
2340
  throw new Error("FormData is not available in this environment");
2195
2341
  }
2196
2342
  const formData = new FormData();
2197
- const name = filename || (file instanceof File ? file.name : "file");
2343
+ const name = filename || uploadFileName(file);
2198
2344
  formData.append("file", file, name);
2199
2345
  if (meta?.collectionName)
2200
2346
  formData.append("collection_name", meta.collectionName);
@@ -2217,7 +2363,7 @@ var FilesService = class {
2217
2363
  * `upload()` when the server has no direct-upload support configured.
2218
2364
  */
2219
2365
  async uploadDirect(file, opts) {
2220
- const filename = opts?.filename || (file instanceof File ? file.name : "file");
2366
+ const filename = opts?.filename || uploadFileName(file);
2221
2367
  const mime = file.type || "application/octet-stream";
2222
2368
  const presigned = await this.presign({
2223
2369
  filename,
@@ -2344,42 +2490,15 @@ var CollectionsService = class {
2344
2490
  */
2345
2491
  async getFullList(options) {
2346
2492
  if (!this.http) return [];
2347
- const { batch: requestedBatch = MAX_PER_PAGE, ...rest } = options ?? {};
2348
- const batch = clampBatch(requestedBatch);
2349
- const {
2350
- requestKey: reqKey,
2351
- singleFlight: _singleFlight,
2352
- fetch: fetchFn,
2353
- headers: hdrs,
2354
- signal: sig,
2355
- params: passthroughParams,
2356
- ...queryParams
2357
- } = rest;
2358
- const effectiveKey = typeof reqKey === "string" ? reqKey : `getFullList:collections:${stableStringify(rest)}`;
2359
- const items = [];
2360
- let page = 1;
2361
- for (; ; ) {
2362
- const res = await this.getList(
2363
- {
2364
- ...queryParams,
2365
- ...passthroughParams ?? {},
2366
- page,
2367
- perPage: batch
2368
- },
2369
- {
2370
- requestKey: effectiveKey,
2371
- singleFlight: true,
2372
- ...fetchFn ? { fetch: fetchFn } : {},
2373
- ...hdrs ? { headers: hdrs } : {},
2374
- ...sig ? { signal: sig } : {}
2375
- }
2376
- );
2377
- if (!res || !res.items || res.items.length === 0) break;
2378
- items.push(...res.items);
2379
- if (page >= (res.totalPages ?? page)) break;
2380
- page += 1;
2381
- }
2382
- return items;
2493
+ const { query, transport, batch } = splitListOptions(options);
2494
+ const requestKey = fullListKey("collections", query, transport.requestKey);
2495
+ return paginateAll(
2496
+ batch,
2497
+ (page, perPage) => this.getList(
2498
+ { ...query, page, perPage },
2499
+ { ...transport, requestKey, singleFlight: true }
2500
+ )
2501
+ );
2383
2502
  }
2384
2503
  /**
2385
2504
  * Get a single collection by ID or name (admin).
@@ -2420,11 +2539,9 @@ var CollectionsService = class {
2420
2539
  * @param options Optional request options.
2421
2540
  */
2422
2541
  async delete(id, options) {
2423
- const res = this.http?.delete(
2424
- "/collections/" + encodeURIComponent(id),
2425
- options
2426
- );
2427
- return res == null ? false : true;
2542
+ if (!this.http) return false;
2543
+ await this.http.delete("/collections/" + encodeURIComponent(id), options);
2544
+ return true;
2428
2545
  }
2429
2546
  /**
2430
2547
  * Subscribe to collection registry changes.
@@ -2464,6 +2581,147 @@ function normalizeAction2(event) {
2464
2581
  return "update";
2465
2582
  }
2466
2583
 
2584
+ // src/mail.ts
2585
+ function templatePath(name) {
2586
+ return "/mail/templates/" + encodeURIComponent(name.trim());
2587
+ }
2588
+ var MailService = class {
2589
+ constructor(http) {
2590
+ this.http = http;
2591
+ }
2592
+ /**
2593
+ * Queue one message for delivery.
2594
+ *
2595
+ * Either a `template` or a `subject` with a body. The type requires one of
2596
+ * them — a message with neither does not compile — while the server refuses a
2597
+ * message that carries both, and a template with a raw body.
2598
+ *
2599
+ * The address is shape-checked server-side; the SMTP server remains the
2600
+ * authority on whether it exists.
2601
+ *
2602
+ * @param message The template or raw message to send.
2603
+ * @param options Optional request options (signal, custom fetch).
2604
+ * @returns The queued job (`{ queued: true, id }`).
2605
+ *
2606
+ * @example
2607
+ * ```ts
2608
+ * // A template
2609
+ * await client.mail.send({ to: 'ada@example.com', template: 'receipt', assigns: { total: 42 } });
2610
+ *
2611
+ * // A raw message
2612
+ * await client.mail.send({ to: 'ada@example.com', subject: 'Hello', text: 'Hi there' });
2613
+ * ```
2614
+ */
2615
+ async send(message, options) {
2616
+ const body = "template" in message ? {
2617
+ to: message.to,
2618
+ toName: message.toName,
2619
+ template: message.template,
2620
+ assigns: message.assigns
2621
+ } : {
2622
+ to: message.to,
2623
+ toName: message.toName,
2624
+ subject: message.subject,
2625
+ html: message.html,
2626
+ text: message.text
2627
+ };
2628
+ const data = await this.http.request("POST", "/mail", body, options);
2629
+ return data ?? { queued: false, id: "" };
2630
+ }
2631
+ /**
2632
+ * List every template the server can send, with the body each part
2633
+ * currently resolves to and the layer it came from (superuser).
2634
+ *
2635
+ * Unpaginated: there are as many templates as the deployment defined, not
2636
+ * as many as it has sent.
2637
+ */
2638
+ async listTemplates(options) {
2639
+ const data = await this.http.request(
2640
+ "GET",
2641
+ "/mail/templates",
2642
+ void 0,
2643
+ options
2644
+ );
2645
+ return data?.items ?? [];
2646
+ }
2647
+ /** Fetch one template by name (superuser). */
2648
+ async getTemplate(name, options) {
2649
+ const data = await this.http.request(
2650
+ "GET",
2651
+ templatePath(name),
2652
+ void 0,
2653
+ options
2654
+ );
2655
+ return data;
2656
+ }
2657
+ /**
2658
+ * Save all three parts of a template, replacing whatever was stored for them.
2659
+ *
2660
+ * All three at once rather than one at a time: a template is only allowed to
2661
+ * exist once it is complete, so a part-at-a-time write could leave a subject
2662
+ * saved against a body that does not parse. The server parses the bodies
2663
+ * before storing them, so a syntax error is a rejected save rather than a
2664
+ * queued email that fails where nobody is watching (superuser).
2665
+ */
2666
+ async saveTemplate(name, parts, options) {
2667
+ const data = await this.http.put(
2668
+ templatePath(name),
2669
+ { subject: parts.subject, html: parts.html, text: parts.text },
2670
+ options
2671
+ );
2672
+ return data;
2673
+ }
2674
+ /**
2675
+ * Remove the stored bodies, so the template falls back to its file or its
2676
+ * built-in (superuser).
2677
+ *
2678
+ * Deleting one that was never saved succeeds with `deleted: 0` — it is
2679
+ * already at its default — but an unknown *name* is a 404, so a typo cannot
2680
+ * look like a reset that worked.
2681
+ */
2682
+ async deleteTemplate(name, options) {
2683
+ const data = await this.http.request(
2684
+ "DELETE",
2685
+ templatePath(name),
2686
+ void 0,
2687
+ options
2688
+ );
2689
+ return data ?? { name: name.trim(), deleted: 0 };
2690
+ }
2691
+ /**
2692
+ * Render a template the way a send would, without storing or sending
2693
+ * anything (superuser).
2694
+ *
2695
+ * Any of `subject`/`html`/`text` given in `draft` is rendered in place of the
2696
+ * stored part, which is what makes this useful while a body is still being
2697
+ * written. A draft over a name the server does not know is previewed as the
2698
+ * new template it is being written as, so such a draft has to arrive
2699
+ * complete (all three parts).
2700
+ *
2701
+ * Previews share one auto-cancellation key (`POST /mail/templates/<name>/preview`),
2702
+ * so a newer preview aborts an older one: the older promise rejects with an
2703
+ * `ApiError` whose `isAbort` is `true`. That is what an editor wants when a
2704
+ * keystroke supersedes the last render, but pass `{ requestKey: null }` to
2705
+ * keep every preview if you would rather have them all.
2706
+ */
2707
+ async preview(name, draft, options) {
2708
+ const body = {
2709
+ assigns: draft?.assigns,
2710
+ toName: draft?.toName,
2711
+ subject: draft?.subject,
2712
+ html: draft?.html,
2713
+ text: draft?.text
2714
+ };
2715
+ const data = await this.http.request(
2716
+ "POST",
2717
+ templatePath(name) + "/preview",
2718
+ body,
2719
+ options
2720
+ );
2721
+ return data;
2722
+ }
2723
+ };
2724
+
2467
2725
  // src/typegen.ts
2468
2726
  function fieldTypeScriptType(field, fallback = "unknown") {
2469
2727
  const opts = field.options ?? {};
@@ -2835,6 +3093,7 @@ var LazypockClient = class {
2835
3093
  this.authStore.onChange(() => this.realtime.refresh());
2836
3094
  this.authReady.then(() => this.realtime.refresh());
2837
3095
  this.files = new FilesService(this.http);
3096
+ this.mail = new MailService(this.http);
2838
3097
  this.collections = new CollectionsService(this.http, this.realtime);
2839
3098
  if (options.types?.schemas) {
2840
3099
  this.schemaByName = new Map(
@@ -2957,36 +3216,25 @@ var LazypockClient = class {
2957
3216
  * @param collection Optional auth collection name.
2958
3217
  */
2959
3218
  async login(email, password, collection) {
2960
- let data;
2961
3219
  if (collection) {
2962
- data = await this.http.post("/collections/" + encodeURIComponent(collection) + "/auth-with-password", {
3220
+ return this.collection(collection).authWithPassword(email, password);
3221
+ }
3222
+ let data = null;
3223
+ try {
3224
+ data = await this.http.post("/collections/_superusers/auth-with-password", {
2963
3225
  identity: email,
2964
3226
  password
2965
3227
  });
2966
- if (data && data.record) {
2967
- this.authStore.setCollectionName(collection);
2968
- rememberAuthResponse(
2969
- this.authStore,
2970
- data,
2971
- data.record
2972
- );
2973
- }
2974
- } else {
2975
- try {
2976
- data = await this.http.post("/collections/_superusers/auth-with-password", {
2977
- identity: email,
2978
- password
2979
- });
2980
- } catch {
2981
- data = null;
2982
- }
2983
- if (!data) {
2984
- data = await this.http.post("/superusers/login", { email, password });
2985
- }
2986
- if (data) {
2987
- this.authStore.setCollectionName(null);
2988
- rememberAuthResponse(this.authStore, data, null);
2989
- }
3228
+ } catch (err) {
3229
+ if (!(err instanceof ApiError) || err.status !== 404) throw err;
3230
+ data = null;
3231
+ }
3232
+ if (!data) {
3233
+ data = await this.http.post("/superusers/login", { email, password });
3234
+ }
3235
+ if (data) {
3236
+ this.authStore.setCollectionName(null);
3237
+ rememberAuthResponse(this.authStore, data, null);
2990
3238
  }
2991
3239
  return data;
2992
3240
  }
@@ -2998,7 +3246,7 @@ var LazypockClient = class {
2998
3246
  async me(options) {
2999
3247
  const data = await this.http.get("/me", options);
3000
3248
  if (data) {
3001
- this.authStore.set(this.authStore.token, data);
3249
+ this.authStore.setModel(data);
3002
3250
  }
3003
3251
  return data;
3004
3252
  }
@@ -3011,17 +3259,8 @@ var LazypockClient = class {
3011
3259
  * @param password Password.
3012
3260
  * @param options Optional request options.
3013
3261
  */
3014
- async authWithPassword(collection, identity, password, options) {
3015
- const data = await this.http.post(
3016
- "/collections/" + encodeURIComponent(collection) + "/auth-with-password",
3017
- { identity, password },
3018
- options
3019
- );
3020
- if (data) {
3021
- this.authStore.setCollectionName(collection);
3022
- rememberAuthResponse(this.authStore, data, data.record);
3023
- }
3024
- return data;
3262
+ authWithPassword(collection, identity, password, options) {
3263
+ return this.collection(collection).authWithPassword(identity, password, options);
3025
3264
  }
3026
3265
  /**
3027
3266
  * Refresh an auth collection token.
@@ -3030,17 +3269,8 @@ var LazypockClient = class {
3030
3269
  * @param collection The auth collection name.
3031
3270
  * @param options Optional request options.
3032
3271
  */
3033
- async authRefresh(collection, options) {
3034
- const data = await this.http.post(
3035
- "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
3036
- { refreshToken: this.authStore.refreshToken },
3037
- options
3038
- );
3039
- if (data) {
3040
- this.authStore.setCollectionName(collection);
3041
- rememberAuthResponse(this.authStore, data, data.record);
3042
- }
3043
- return data;
3272
+ authRefresh(collection, options) {
3273
+ return this.collection(collection).authRefresh(options);
3044
3274
  }
3045
3275
  /** Clear the current auth state and remove persisted tokens. */
3046
3276
  logout() {
@@ -3073,6 +3303,7 @@ function createClient(options) {
3073
3303
  FilterExpr,
3074
3304
  HttpClient,
3075
3305
  LazypockClient,
3306
+ MailService,
3076
3307
  RealtimeService,
3077
3308
  TypedClient,
3078
3309
  collectionTypeName,