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/README.md +36 -0
- package/dist/index.cjs +905 -674
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +232 -82
- package/dist/index.d.ts +232 -82
- package/dist/index.global.js +904 -674
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +904 -674
- package/dist/index.js.map +1 -1
- package/package.json +19 -2
- package/src/auth.ts +29 -0
- package/src/collection/auth.ts +289 -0
- package/src/collection/index.ts +754 -0
- package/src/collection/paths.ts +21 -0
- package/src/collection/query.ts +111 -0
- package/src/collection/realtime.ts +141 -0
- package/src/collection/session.ts +76 -0
- package/src/collections.ts +18 -52
- package/src/expand.ts +286 -0
- package/src/files.ts +15 -2
- package/src/filter.ts +2 -2
- package/src/http.ts +37 -6
- package/src/index.ts +12 -0
- package/src/lazypock.ts +65 -71
- package/src/mail.ts +290 -0
- package/src/paginate.ts +111 -0
- package/src/projection.ts +139 -0
- package/src/query-params.ts +74 -0
- package/src/realtime.ts +6 -0
- package/src/types.ts +1 -1
- package/src/collection.ts +0 -1412
package/src/mail.ts
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// ── Mail Service ────────────────────────────────────────
|
|
2
|
+
// Send application email through the deployment's SMTP settings, and manage
|
|
3
|
+
// the templates it renders (`POST /api/mail`, `/api/mail/templates`).
|
|
4
|
+
//
|
|
5
|
+
// Access via {@link LazypockClient.mail}.
|
|
6
|
+
//
|
|
7
|
+
// Sending **queues** a job rather than delivering inline: an SMTP provider that
|
|
8
|
+
// is slow or down must not hold a request open, and the queue already retries
|
|
9
|
+
// with backoff. The response therefore means "queued", not "delivered" —
|
|
10
|
+
// delivery failures surface on the job (`GET /api/logs`).
|
|
11
|
+
//
|
|
12
|
+
// A template is rendered against the *variables* of a message, and one of the
|
|
13
|
+
// built-ins renders a password-reset token. That is why templates are
|
|
14
|
+
// superuser-only and deliberately not API-keyable: whoever can write a template
|
|
15
|
+
// can mail themselves somebody else's token. Sending an already-defined
|
|
16
|
+
// template stays API-keyable.
|
|
17
|
+
|
|
18
|
+
import type { HttpClient } from "./http";
|
|
19
|
+
import type { RequestOptions } from "./types";
|
|
20
|
+
|
|
21
|
+
/** The three parts a mail template is made of. */
|
|
22
|
+
export type MailPart = "subject" | "html" | "text";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Which layer a template body came from, newest first.
|
|
26
|
+
*
|
|
27
|
+
* - `database` — saved through the API (or Studio), the one in effect
|
|
28
|
+
* - `file` — a file in the deployment's template directory
|
|
29
|
+
* - `builtin` — shipped with the server
|
|
30
|
+
*
|
|
31
|
+
* Reported because an edit that is in effect and one that is not look identical
|
|
32
|
+
* otherwise.
|
|
33
|
+
*/
|
|
34
|
+
export type MailTemplateLayer = "database" | "file" | "builtin";
|
|
35
|
+
|
|
36
|
+
/** The template context handed to a send or a preview. */
|
|
37
|
+
export type MailAssigns = Record<string, unknown>;
|
|
38
|
+
|
|
39
|
+
/** A template as the server resolves it. */
|
|
40
|
+
export interface MailTemplate {
|
|
41
|
+
/** The template name, e.g. `verification` or `receipt`. */
|
|
42
|
+
name: string;
|
|
43
|
+
/** The strongest layer across the three parts (`database` wins over `file`). */
|
|
44
|
+
source: MailTemplateLayer;
|
|
45
|
+
/** The layer each part resolved from. */
|
|
46
|
+
parts: Record<MailPart, MailTemplateLayer>;
|
|
47
|
+
/** The subject, as a template. */
|
|
48
|
+
subject: string;
|
|
49
|
+
/** The HTML body. */
|
|
50
|
+
html: string;
|
|
51
|
+
/** The plain-text alternative. */
|
|
52
|
+
text: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The bodies of one template. All three parts are required. */
|
|
56
|
+
export interface MailTemplateParts {
|
|
57
|
+
subject: string;
|
|
58
|
+
html: string;
|
|
59
|
+
text: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One message to queue. */
|
|
63
|
+
export type MailMessage =
|
|
64
|
+
| {
|
|
65
|
+
/** The recipient's address. */
|
|
66
|
+
to: string;
|
|
67
|
+
/** The recipient's display name, rendered as `name`. */
|
|
68
|
+
toName?: string;
|
|
69
|
+
/** A built-in or deployment-saved template name. */
|
|
70
|
+
template: string;
|
|
71
|
+
/** The template context. */
|
|
72
|
+
assigns?: MailAssigns;
|
|
73
|
+
}
|
|
74
|
+
| {
|
|
75
|
+
/** The recipient's address. */
|
|
76
|
+
to: string;
|
|
77
|
+
/** The recipient's display name. */
|
|
78
|
+
toName?: string;
|
|
79
|
+
/** A raw subject, instead of a template. */
|
|
80
|
+
subject: string;
|
|
81
|
+
/** The HTML body (required when `text` is omitted). */
|
|
82
|
+
html?: string;
|
|
83
|
+
/** The plain-text body (required when `html` is omitted). Derived from the HTML when omitted. */
|
|
84
|
+
text?: string;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** What `send()` answers: the queued job, not a delivery. */
|
|
88
|
+
export interface MailSendResult {
|
|
89
|
+
queued: boolean;
|
|
90
|
+
/** The job id — follow it in `GET /api/logs` for delivery failures. */
|
|
91
|
+
id: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A draft to render in place of the stored parts. Nothing is saved or sent. */
|
|
95
|
+
export interface MailPreviewDraft {
|
|
96
|
+
/** The template context. `name` and `app_name` are filled in when absent. */
|
|
97
|
+
assigns?: MailAssigns;
|
|
98
|
+
/** The recipient display name that `name` renders as. */
|
|
99
|
+
toName?: string;
|
|
100
|
+
/** A draft subject to render instead of the stored one. */
|
|
101
|
+
subject?: string;
|
|
102
|
+
/** A draft HTML body to render instead of the stored one. */
|
|
103
|
+
html?: string;
|
|
104
|
+
/** A draft text body to render instead of the stored one. */
|
|
105
|
+
text?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The rendered result of a preview. */
|
|
109
|
+
export interface MailPreviewResult {
|
|
110
|
+
name: string;
|
|
111
|
+
subject: string;
|
|
112
|
+
html: string;
|
|
113
|
+
text: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** What `deleteTemplate()` answers: how many stored parts went away. */
|
|
117
|
+
export interface MailTemplateDeleteResult {
|
|
118
|
+
name: string;
|
|
119
|
+
/** `0` when the template had never been saved (it was already at its default). */
|
|
120
|
+
deleted: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Path for one template, encoding a name so it survives the URL path. */
|
|
124
|
+
function templatePath(name: string): string {
|
|
125
|
+
return "/mail/templates/" + encodeURIComponent(name.trim());
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Service for application email.
|
|
130
|
+
* Access via {@link LazypockClient.mail}.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```ts
|
|
134
|
+
* await client.mail.send({ to: 'ada@example.com', template: 'verification', assigns: { token: '…' } });
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
export class MailService {
|
|
138
|
+
constructor(private http: HttpClient) {}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Queue one message for delivery.
|
|
142
|
+
*
|
|
143
|
+
* Either a `template` or a `subject` with a body. The type requires one of
|
|
144
|
+
* them — a message with neither does not compile — while the server refuses a
|
|
145
|
+
* message that carries both, and a template with a raw body.
|
|
146
|
+
*
|
|
147
|
+
* The address is shape-checked server-side; the SMTP server remains the
|
|
148
|
+
* authority on whether it exists.
|
|
149
|
+
*
|
|
150
|
+
* @param message The template or raw message to send.
|
|
151
|
+
* @param options Optional request options (signal, custom fetch).
|
|
152
|
+
* @returns The queued job (`{ queued: true, id }`).
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```ts
|
|
156
|
+
* // A template
|
|
157
|
+
* await client.mail.send({ to: 'ada@example.com', template: 'receipt', assigns: { total: 42 } });
|
|
158
|
+
*
|
|
159
|
+
* // A raw message
|
|
160
|
+
* await client.mail.send({ to: 'ada@example.com', subject: 'Hello', text: 'Hi there' });
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
async send(message: MailMessage, options?: RequestOptions): Promise<MailSendResult> {
|
|
164
|
+
const body =
|
|
165
|
+
"template" in message
|
|
166
|
+
? {
|
|
167
|
+
to: message.to,
|
|
168
|
+
toName: message.toName,
|
|
169
|
+
template: message.template,
|
|
170
|
+
assigns: message.assigns,
|
|
171
|
+
}
|
|
172
|
+
: {
|
|
173
|
+
to: message.to,
|
|
174
|
+
toName: message.toName,
|
|
175
|
+
subject: message.subject,
|
|
176
|
+
html: message.html,
|
|
177
|
+
text: message.text,
|
|
178
|
+
};
|
|
179
|
+
const data = await this.http.request<MailSendResult>("POST", "/mail", body, options);
|
|
180
|
+
return (data ?? { queued: false, id: "" }) as MailSendResult;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* List every template the server can send, with the body each part
|
|
185
|
+
* currently resolves to and the layer it came from (superuser).
|
|
186
|
+
*
|
|
187
|
+
* Unpaginated: there are as many templates as the deployment defined, not
|
|
188
|
+
* as many as it has sent.
|
|
189
|
+
*/
|
|
190
|
+
async listTemplates(options?: RequestOptions): Promise<MailTemplate[]> {
|
|
191
|
+
const data = await this.http.request<{ items: MailTemplate[] }>(
|
|
192
|
+
"GET",
|
|
193
|
+
"/mail/templates",
|
|
194
|
+
undefined,
|
|
195
|
+
options,
|
|
196
|
+
);
|
|
197
|
+
return data?.items ?? [];
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Fetch one template by name (superuser). */
|
|
201
|
+
async getTemplate(name: string, options?: RequestOptions): Promise<MailTemplate> {
|
|
202
|
+
const data = await this.http.request<MailTemplate>(
|
|
203
|
+
"GET",
|
|
204
|
+
templatePath(name),
|
|
205
|
+
undefined,
|
|
206
|
+
options,
|
|
207
|
+
);
|
|
208
|
+
return data as MailTemplate;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Save all three parts of a template, replacing whatever was stored for them.
|
|
213
|
+
*
|
|
214
|
+
* All three at once rather than one at a time: a template is only allowed to
|
|
215
|
+
* exist once it is complete, so a part-at-a-time write could leave a subject
|
|
216
|
+
* saved against a body that does not parse. The server parses the bodies
|
|
217
|
+
* before storing them, so a syntax error is a rejected save rather than a
|
|
218
|
+
* queued email that fails where nobody is watching (superuser).
|
|
219
|
+
*/
|
|
220
|
+
async saveTemplate(
|
|
221
|
+
name: string,
|
|
222
|
+
parts: MailTemplateParts,
|
|
223
|
+
options?: RequestOptions,
|
|
224
|
+
): Promise<MailTemplate> {
|
|
225
|
+
const data = await this.http.put<MailTemplate>(
|
|
226
|
+
templatePath(name),
|
|
227
|
+
{ subject: parts.subject, html: parts.html, text: parts.text },
|
|
228
|
+
options,
|
|
229
|
+
);
|
|
230
|
+
return data as MailTemplate;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Remove the stored bodies, so the template falls back to its file or its
|
|
235
|
+
* built-in (superuser).
|
|
236
|
+
*
|
|
237
|
+
* Deleting one that was never saved succeeds with `deleted: 0` — it is
|
|
238
|
+
* already at its default — but an unknown *name* is a 404, so a typo cannot
|
|
239
|
+
* look like a reset that worked.
|
|
240
|
+
*/
|
|
241
|
+
async deleteTemplate(
|
|
242
|
+
name: string,
|
|
243
|
+
options?: RequestOptions,
|
|
244
|
+
): Promise<MailTemplateDeleteResult> {
|
|
245
|
+
const data = await this.http.request<MailTemplateDeleteResult>(
|
|
246
|
+
"DELETE",
|
|
247
|
+
templatePath(name),
|
|
248
|
+
undefined,
|
|
249
|
+
options,
|
|
250
|
+
);
|
|
251
|
+
return (data ?? { name: name.trim(), deleted: 0 }) as MailTemplateDeleteResult;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Render a template the way a send would, without storing or sending
|
|
256
|
+
* anything (superuser).
|
|
257
|
+
*
|
|
258
|
+
* Any of `subject`/`html`/`text` given in `draft` is rendered in place of the
|
|
259
|
+
* stored part, which is what makes this useful while a body is still being
|
|
260
|
+
* written. A draft over a name the server does not know is previewed as the
|
|
261
|
+
* new template it is being written as, so such a draft has to arrive
|
|
262
|
+
* complete (all three parts).
|
|
263
|
+
*
|
|
264
|
+
* Previews share one auto-cancellation key (`POST /mail/templates/<name>/preview`),
|
|
265
|
+
* so a newer preview aborts an older one: the older promise rejects with an
|
|
266
|
+
* `ApiError` whose `isAbort` is `true`. That is what an editor wants when a
|
|
267
|
+
* keystroke supersedes the last render, but pass `{ requestKey: null }` to
|
|
268
|
+
* keep every preview if you would rather have them all.
|
|
269
|
+
*/
|
|
270
|
+
async preview(
|
|
271
|
+
name: string,
|
|
272
|
+
draft?: MailPreviewDraft,
|
|
273
|
+
options?: RequestOptions,
|
|
274
|
+
): Promise<MailPreviewResult> {
|
|
275
|
+
const body = {
|
|
276
|
+
assigns: draft?.assigns,
|
|
277
|
+
toName: draft?.toName,
|
|
278
|
+
subject: draft?.subject,
|
|
279
|
+
html: draft?.html,
|
|
280
|
+
text: draft?.text,
|
|
281
|
+
};
|
|
282
|
+
const data = await this.http.request<MailPreviewResult>(
|
|
283
|
+
"POST",
|
|
284
|
+
templatePath(name) + "/preview",
|
|
285
|
+
body,
|
|
286
|
+
options,
|
|
287
|
+
);
|
|
288
|
+
return data as MailPreviewResult;
|
|
289
|
+
}
|
|
290
|
+
}
|
package/src/paginate.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// ── Full-list pagination ────────────────────────────────
|
|
2
|
+
// `getFullList()` is implemented identically for records and for collections:
|
|
3
|
+
// split the option bag, clamp the batch to the server's ceiling, walk pages,
|
|
4
|
+
// and share one request key across the walk so concurrent identical fetches
|
|
5
|
+
// coalesce instead of duplicating.
|
|
6
|
+
|
|
7
|
+
import type { ListResult, RequestOptions } from "./types";
|
|
8
|
+
import { MAX_PER_PAGE, clampBatch, stableStringify } from "./query-params";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Options that control the transport rather than the query. They must never
|
|
12
|
+
* be serialised into the URL, and a caller passing them should not change the
|
|
13
|
+
* shape of the request.
|
|
14
|
+
*/
|
|
15
|
+
const TRANSPORT_KEYS = new Set([
|
|
16
|
+
"requestKey",
|
|
17
|
+
"autoCancel",
|
|
18
|
+
"cancelKey",
|
|
19
|
+
"singleFlight",
|
|
20
|
+
"fetch",
|
|
21
|
+
"headers",
|
|
22
|
+
"signal",
|
|
23
|
+
"params",
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
/** A `getFullList` option bag split into its query, transport and batch parts. */
|
|
27
|
+
export interface SplitListOptions {
|
|
28
|
+
/** Query params for the request (`filter`, `sort`, `expand`, …). */
|
|
29
|
+
query: Record<string, unknown>;
|
|
30
|
+
/** Transport options, forwarded to each page request. */
|
|
31
|
+
transport: RequestOptions;
|
|
32
|
+
/** Page size, already clamped to the server's maximum. */
|
|
33
|
+
batch: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Split a `getFullList` option bag.
|
|
38
|
+
*
|
|
39
|
+
* `batch` controls the page size and is never sent; query params are
|
|
40
|
+
* everything else that isn't a transport option.
|
|
41
|
+
*/
|
|
42
|
+
export function splitListOptions(
|
|
43
|
+
options?: (Record<string, unknown> & RequestOptions) | undefined,
|
|
44
|
+
): SplitListOptions {
|
|
45
|
+
// `page`/`perPage` are owned by the pagination loop, so they are dropped from
|
|
46
|
+
// the per-page params: passing them through verbatim would request a fixed
|
|
47
|
+
// page on every iteration (repeating page N's rows and never fetching the
|
|
48
|
+
// rest), and a raw `perPage` would bypass `clampBatch`. `batch` sizes pages.
|
|
49
|
+
const {
|
|
50
|
+
batch: requestedBatch = MAX_PER_PAGE,
|
|
51
|
+
page: _page,
|
|
52
|
+
perPage: _perPage,
|
|
53
|
+
...rest
|
|
54
|
+
} = (options ?? {}) as Record<string, unknown> & RequestOptions;
|
|
55
|
+
|
|
56
|
+
const query: Record<string, unknown> = {};
|
|
57
|
+
const transport: Record<string, unknown> = {};
|
|
58
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
59
|
+
if (TRANSPORT_KEYS.has(key)) transport[key] = value;
|
|
60
|
+
else query[key] = value;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
query,
|
|
64
|
+
transport: transport as RequestOptions,
|
|
65
|
+
batch: clampBatch(requestedBatch as number),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The stable request key for a whole full-list fetch.
|
|
71
|
+
*
|
|
72
|
+
* It is deliberately **not** per page — a per-page key would break dedup —
|
|
73
|
+
* and the pages still advance correctly because each page's URL differs
|
|
74
|
+
* (`page=N`), so the underlying default key is unique per page. Concurrent
|
|
75
|
+
* identical `getFullList()` calls share this key via single-flight and
|
|
76
|
+
* therefore fire one set of requests instead of two.
|
|
77
|
+
*
|
|
78
|
+
* @param scope Namespace for the key (the collection name, or `collections`).
|
|
79
|
+
* @param query The query params the key is derived from.
|
|
80
|
+
* @param requestKey A caller-supplied key, which always wins.
|
|
81
|
+
*/
|
|
82
|
+
export function fullListKey(
|
|
83
|
+
scope: string,
|
|
84
|
+
query: unknown,
|
|
85
|
+
requestKey?: string | null,
|
|
86
|
+
): string {
|
|
87
|
+
if (typeof requestKey === "string") return requestKey;
|
|
88
|
+
return `getFullList:${scope}:${stableStringify(query)}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Walk every page, collecting items until an empty page or the last page.
|
|
93
|
+
*
|
|
94
|
+
* Stops on an empty page even when `totalPages` claims more: a server that
|
|
95
|
+
* miscounts must not spin forever.
|
|
96
|
+
*/
|
|
97
|
+
export async function paginateAll<T>(
|
|
98
|
+
batch: number,
|
|
99
|
+
fetchPage: (page: number, perPage: number) => Promise<ListResult<T> | null>,
|
|
100
|
+
): Promise<T[]> {
|
|
101
|
+
const items: T[] = [];
|
|
102
|
+
let page = 1;
|
|
103
|
+
for (;;) {
|
|
104
|
+
const res = await fetchPage(page, batch);
|
|
105
|
+
if (!res || !res.items || res.items.length === 0) break;
|
|
106
|
+
items.push(...res.items);
|
|
107
|
+
if (page >= (res.totalPages ?? page)) break;
|
|
108
|
+
page += 1;
|
|
109
|
+
}
|
|
110
|
+
return items;
|
|
111
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// ── Field projection ────────────────────────────────────
|
|
2
|
+
// Decides which fields a read asks for. Both servers project strictly, so the
|
|
3
|
+
// implicit system keys must be requested explicitly and internal fields must
|
|
4
|
+
// never be — getting this wrong silently drops `id` from every response.
|
|
5
|
+
|
|
6
|
+
import type { CollectionSchema } from "./schema";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The implicit keys every record carries. They never appear in a collection
|
|
10
|
+
* schema, but MUST be listed explicitly when projecting — the server applies
|
|
11
|
+
* strict projection, so unrequested fields are dropped. Without them,
|
|
12
|
+
* `getList`/`getOne` responses lose `id` (and `created`/`updated`), breaking
|
|
13
|
+
* selection, edits and relation references.
|
|
14
|
+
*/
|
|
15
|
+
export const SYSTEM_FIELDS = [
|
|
16
|
+
"id",
|
|
17
|
+
"created",
|
|
18
|
+
"updated",
|
|
19
|
+
"collectionId",
|
|
20
|
+
"collectionName",
|
|
21
|
+
] as const;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Memoised per schema object. `visibleFields()` runs on every read, and the
|
|
25
|
+
* schema is immutable for the lifetime of a service, so the string is built
|
|
26
|
+
* once. A WeakMap keeps derived services (which share the schema object) in
|
|
27
|
+
* the same cache entry without leaking.
|
|
28
|
+
*/
|
|
29
|
+
const visibleFieldsCache = new WeakMap<CollectionSchema, string | undefined>();
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* All non-hidden, non-password, non-autodate field names from the schema,
|
|
33
|
+
* prefixed with the implicit system keys.
|
|
34
|
+
*
|
|
35
|
+
* `undefined` when no schema fields are available (server decides — its
|
|
36
|
+
* default returns every non-password field, including the system keys).
|
|
37
|
+
*/
|
|
38
|
+
export function visibleFields(schema: CollectionSchema | undefined): string | undefined {
|
|
39
|
+
if (!schema?.fields) return undefined;
|
|
40
|
+
const cached = visibleFieldsCache.get(schema);
|
|
41
|
+
if (cached !== undefined || visibleFieldsCache.has(schema)) return cached;
|
|
42
|
+
|
|
43
|
+
const visible = schema.fields
|
|
44
|
+
.filter(
|
|
45
|
+
(f) => !f.hidden && f.type !== "password" && f.type !== "autodate",
|
|
46
|
+
)
|
|
47
|
+
.map((f) => f.name);
|
|
48
|
+
const result =
|
|
49
|
+
visible.length === 0
|
|
50
|
+
? undefined
|
|
51
|
+
: // Dedupe in case a schema ever names a field after a system key.
|
|
52
|
+
[
|
|
53
|
+
...new Set([...SYSTEM_FIELDS, ...visible]),
|
|
54
|
+
].join(",");
|
|
55
|
+
|
|
56
|
+
visibleFieldsCache.set(schema, result);
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Fields to send with reads, in precedence order:
|
|
62
|
+
* 1. explicit `options.fields` (caller wins)
|
|
63
|
+
* 2. `select()` preset
|
|
64
|
+
* 3. schema default — all visible (non-hidden) fields plus the system keys
|
|
65
|
+
*/
|
|
66
|
+
export function effectiveFields(
|
|
67
|
+
schema: CollectionSchema | undefined,
|
|
68
|
+
preset: string | undefined,
|
|
69
|
+
optionsFields?: string,
|
|
70
|
+
): string | undefined {
|
|
71
|
+
if (optionsFields !== undefined) return optionsFields;
|
|
72
|
+
if (preset !== undefined) {
|
|
73
|
+
return preset === "*" ? visibleFields(schema) : preset;
|
|
74
|
+
}
|
|
75
|
+
return visibleFields(schema);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Normalised form of a caller's `expand` string (see `normalizeExpand`). */
|
|
79
|
+
export interface NormalizedExpand {
|
|
80
|
+
/** Rewritten `expand` query param (relation paths only). */
|
|
81
|
+
expand?: string;
|
|
82
|
+
/** `fields` entries that keep/narrow the expanded data. */
|
|
83
|
+
fieldSelectors: string[];
|
|
84
|
+
/**
|
|
85
|
+
* Top-level relation → leaf field names to keep on the expanded record.
|
|
86
|
+
* Applied client-side so field selection also works on servers that don't
|
|
87
|
+
* project expanded records (the LazyPock server, unlike PocketBase, always
|
|
88
|
+
* returns the full related record).
|
|
89
|
+
*/
|
|
90
|
+
narrow: Map<string, string[]>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Merge the expand-preserving selectors into the base field projection.
|
|
95
|
+
*
|
|
96
|
+
* Both servers are kept happy at once:
|
|
97
|
+
* - PocketBase drops the whole `expand` payload unless an `expand.<key>`
|
|
98
|
+
* entry is present in `fields`;
|
|
99
|
+
* - the LazyPock server projects first (strict, top-level only) and then
|
|
100
|
+
* expands, so the relation *field* itself must be present in `fields`.
|
|
101
|
+
*
|
|
102
|
+
* We therefore add both the relation field (`cate`) and the
|
|
103
|
+
* `expand.<key>` entry. When no projection is active, no `fields` param is
|
|
104
|
+
* sent at all — a value like `*` plus other tokens is not a wildcard on
|
|
105
|
+
* the LazyPock server (it is a strict take, yielding empty records) and
|
|
106
|
+
* the server keeps `expand` by default when `fields` is absent.
|
|
107
|
+
*/
|
|
108
|
+
export function mergeExpandFields(
|
|
109
|
+
base: string | undefined,
|
|
110
|
+
info: NormalizedExpand,
|
|
111
|
+
): string | undefined {
|
|
112
|
+
if (info.fieldSelectors.length === 0) return base;
|
|
113
|
+
if (base === undefined) return undefined;
|
|
114
|
+
|
|
115
|
+
const parts = base
|
|
116
|
+
.split(",")
|
|
117
|
+
.map((f) => f.trim())
|
|
118
|
+
.filter(Boolean);
|
|
119
|
+
const seen = new Set(parts);
|
|
120
|
+
const push = (value: string) => {
|
|
121
|
+
if (seen.has(value)) return;
|
|
122
|
+
seen.add(value);
|
|
123
|
+
parts.push(value);
|
|
124
|
+
};
|
|
125
|
+
// A full `expand.<key>` selector already includes any narrower
|
|
126
|
+
// `expand.<key>.<field>` selection — drop the redundant narrow ones.
|
|
127
|
+
const fullKeys = new Set<string>();
|
|
128
|
+
for (const selector of info.fieldSelectors) {
|
|
129
|
+
const seg = selector.split(".");
|
|
130
|
+
if (seg.length === 2) fullKeys.add(seg[1]);
|
|
131
|
+
}
|
|
132
|
+
for (const selector of info.fieldSelectors) {
|
|
133
|
+
const seg = selector.split(".");
|
|
134
|
+
if (seg.length > 2 && fullKeys.has(seg[1])) continue;
|
|
135
|
+
if (seg.length >= 2) push(seg[1]);
|
|
136
|
+
push(selector);
|
|
137
|
+
}
|
|
138
|
+
return parts.join(",");
|
|
139
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// ── Query-param helpers ─────────────────────────────────
|
|
2
|
+
// Shared by every service that builds list requests: the server's page-size
|
|
3
|
+
// ceiling, and the deterministic serialisation used as a cache/dedup key.
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Largest `perPage` the server accepts (`MAX_PER_PAGE` in lazypock's pagination).
|
|
7
|
+
* `getFullList()` pages at this size by default and never asks for more: a larger
|
|
8
|
+
* `perPage` is rejected with a 400 rather than clamped.
|
|
9
|
+
*/
|
|
10
|
+
export const MAX_PER_PAGE = 500;
|
|
11
|
+
|
|
12
|
+
/** Keep a requested page size within what the server accepts (1..MAX_PER_PAGE). */
|
|
13
|
+
export function clampBatch(batch: number): number {
|
|
14
|
+
if (!Number.isFinite(batch)) return MAX_PER_PAGE;
|
|
15
|
+
return Math.min(Math.max(1, Math.floor(batch)), MAX_PER_PAGE);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A recursively-normalized request value: object keys sorted and
|
|
20
|
+
* request-transport keys stripped, so functionally-identical calls share
|
|
21
|
+
* one stable serialization key.
|
|
22
|
+
*/
|
|
23
|
+
type StableRequestValue =
|
|
24
|
+
| string
|
|
25
|
+
| number
|
|
26
|
+
| boolean
|
|
27
|
+
| null
|
|
28
|
+
| StableRequestValue[]
|
|
29
|
+
| { [key: string]: StableRequestValue };
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Request-transport options. They don't change what the server returns, so
|
|
33
|
+
* they are excluded from the dedup key — but only at the top level: a record
|
|
34
|
+
* field that happens to be called `signal` is payload, not transport.
|
|
35
|
+
*/
|
|
36
|
+
const TRANSPORT_KEYS = new Set(["requestKey", "singleFlight", "fetch", "signal"]);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Deterministic JSON stringify for building a stable cache/dedup key.
|
|
40
|
+
* Object keys are sorted (so key order never changes the key) and the
|
|
41
|
+
* top-level transport options are stripped.
|
|
42
|
+
*
|
|
43
|
+
* Cycles are reported as `"[Circular]"`; the visited set is a *path* stack so a
|
|
44
|
+
* value referenced twice in a non-cyclic graph keeps its real content. Treating
|
|
45
|
+
* a shared reference as a cycle would collapse structurally different option
|
|
46
|
+
* bags onto one key, and single-flight would then hand a caller the wrong
|
|
47
|
+
* response.
|
|
48
|
+
*/
|
|
49
|
+
export function stableStringify(value: unknown): string {
|
|
50
|
+
const path = new Set<object>();
|
|
51
|
+
const sort = (v: unknown, topLevel: boolean): StableRequestValue => {
|
|
52
|
+
if (Array.isArray(v)) return v.map((el) => sort(el, false));
|
|
53
|
+
if (v && typeof v === "object") {
|
|
54
|
+
const obj = v as Record<string, unknown>;
|
|
55
|
+
if (path.has(obj)) return "[Circular]";
|
|
56
|
+
path.add(obj);
|
|
57
|
+
const out: Record<string, StableRequestValue> = {};
|
|
58
|
+
for (const k of Object.keys(obj).sort()) {
|
|
59
|
+
if (topLevel && TRANSPORT_KEYS.has(k)) continue;
|
|
60
|
+
out[k] = sort(obj[k], false);
|
|
61
|
+
}
|
|
62
|
+
path.delete(obj);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
// SAFETY: non-object values are JSON scalars (or undefined, which
|
|
66
|
+
// JSON.stringify omits from objects) — all representable here.
|
|
67
|
+
return v as StableRequestValue;
|
|
68
|
+
};
|
|
69
|
+
try {
|
|
70
|
+
return JSON.stringify(sort(value, true));
|
|
71
|
+
} catch {
|
|
72
|
+
return String(value);
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/realtime.ts
CHANGED
|
@@ -151,6 +151,12 @@ export class RealtimeService {
|
|
|
151
151
|
ensureConnected(): void {
|
|
152
152
|
if (this.open || this.controller || !this.url) return;
|
|
153
153
|
if (this.serverTopics().length === 0) return;
|
|
154
|
+
// An explicit disconnect() is not a one-way door. Subscribing again is
|
|
155
|
+
// intent to reconnect (PocketBase parity). LazypockClient wires realtime
|
|
156
|
+
// via setUrl()/setTokenProvider() and never calls connect(), so nothing
|
|
157
|
+
// else ever cleared `closed`: after a disconnect every later subscribe()
|
|
158
|
+
// no-op'd inside doConnect() — no stream, no events, no diagnostics.
|
|
159
|
+
this.closed = false;
|
|
154
160
|
this.doConnect();
|
|
155
161
|
}
|
|
156
162
|
|
package/src/types.ts
CHANGED
|
@@ -56,7 +56,7 @@ export interface ListResult<T = ApiRecord> {
|
|
|
56
56
|
}
|
|
57
57
|
|
|
58
58
|
/** HTTP method supported by the client. */
|
|
59
|
-
export type Method = "GET" | "POST" | "PATCH" | "DELETE";
|
|
59
|
+
export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
60
60
|
|
|
61
61
|
export interface RequestOptions {
|
|
62
62
|
/** Search/filter params */
|