kizunacms 0.0.0 → 0.1.0

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.
@@ -0,0 +1,1274 @@
1
+ import { Kizuna } from "kizunajs";
2
+ import { z } from "zod";
3
+ import pluralize from "pluralize";
4
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
5
+ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, join } from "node:path";
7
+ import slugify from "@sindresorhus/slugify";
8
+ //#region src/storage.ts
9
+ /**
10
+ * The fields the CMS keeps on every file.
11
+ */
12
+ const FILE_RECORD_FIELDS = [
13
+ "key",
14
+ "filename",
15
+ "contentType",
16
+ "fileSize",
17
+ "width",
18
+ "height",
19
+ "alt",
20
+ "focalPoint",
21
+ "uploadedBy"
22
+ ];
23
+ /**
24
+ * The collection a store's file records are saved in.
25
+ */
26
+ const fileCollectionOf = (storage) => `storage:${storage.name}`;
27
+ const storesByName = /* @__PURE__ */ new Map();
28
+ /**
29
+ * Keeps stores by name so a field can find the one it names.
30
+ */
31
+ const registerStores = (declared) => {
32
+ for (const store of declared) storesByName.set(store.name, store);
33
+ };
34
+ /**
35
+ * A store's own fields as `kizuna generate` writes them into `Config`.
36
+ */
37
+ const storeFieldTypesOf = (store) => Object.fromEntries((store.fields ?? []).map((field) => {
38
+ return [field.name, {
39
+ type: [field.type],
40
+ required: [String(field.required === true)],
41
+ ...field.type === "select" ? {
42
+ options: field.options.map((option) => typeof option === "string" ? option : option.value),
43
+ many: [String(field.many === true)]
44
+ } : {}
45
+ }];
46
+ }));
47
+ const storeNamed = (name) => {
48
+ const store = storesByName.get(name);
49
+ if (store === void 0) throw new Error(`No store is named '${name}'. Declare it with \`k.storage\`, and list it under \`storage\` in the config.`);
50
+ return store;
51
+ };
52
+ /**
53
+ * Checks a store's definition and returns the store, for `k.storage`.
54
+ */
55
+ const defineStorage = (definition) => {
56
+ checkDefinition(`Storage '${definition.name}'`, definition.name, definition.fields ?? [], "`images` or `documents`");
57
+ const taken = (definition.fields ?? []).find((field) => [
58
+ ...FILE_RECORD_FIELDS,
59
+ "url",
60
+ "original"
61
+ ].includes(field.name));
62
+ if (taken !== void 0) throw new Error(`Storage '${definition.name}' has a field named '${taken.name}', which every file already carries.`);
63
+ const store = {
64
+ ...definition,
65
+ kind: "storage"
66
+ };
67
+ registerStores([store]);
68
+ return store;
69
+ };
70
+ /**
71
+ * Creates a storage adapter that keeps files in memory, for tests.
72
+ *
73
+ * @example
74
+ * adapter: memoryStorage(),
75
+ */
76
+ const memoryStorage = (uploadBase = "memory://uploads") => {
77
+ const files = /* @__PURE__ */ new Map();
78
+ return {
79
+ files,
80
+ put: async (key, bytes, contentType) => {
81
+ files.set(key, {
82
+ bytes,
83
+ contentType
84
+ });
85
+ },
86
+ presignUpload: async ({ key, contentType }) => ({
87
+ url: `${uploadBase}/${key}`,
88
+ headers: { "content-type": contentType }
89
+ }),
90
+ head: async (key) => {
91
+ const file = files.get(key);
92
+ return file === void 0 ? void 0 : {
93
+ fileSize: file.bytes.byteLength,
94
+ contentType: file.contentType
95
+ };
96
+ },
97
+ read: async (key, length) => files.get(key)?.bytes.slice(0, length),
98
+ delete: async (key) => {
99
+ files.delete(key);
100
+ },
101
+ url: async (key) => `${uploadBase}/${key}`
102
+ };
103
+ };
104
+ const CONTENT_TYPES_BY_EXTENSION = {
105
+ jpg: "image/jpeg",
106
+ jpeg: "image/jpeg",
107
+ png: "image/png",
108
+ gif: "image/gif",
109
+ webp: "image/webp",
110
+ avif: "image/avif",
111
+ heic: "image/heic",
112
+ pdf: "application/pdf"
113
+ };
114
+ /**
115
+ * Reads a request's body, or returns `undefined` when it holds more than `limit` bytes. It stops reading past the limit.
116
+ */
117
+ const bodyWithin = async (request, limit) => {
118
+ const declared = Number(request.headers.get("content-length") ?? NaN);
119
+ if (Number.isFinite(declared) && declared > limit) return void 0;
120
+ if (request.body === null) return new Uint8Array();
121
+ const reader = request.body.getReader();
122
+ const chunks = [];
123
+ let length = 0;
124
+ for (;;) {
125
+ const { done, value } = await reader.read();
126
+ if (done) break;
127
+ length += value.byteLength;
128
+ if (length > limit) {
129
+ await reader.cancel();
130
+ return;
131
+ }
132
+ chunks.push(value);
133
+ }
134
+ const bytes = new Uint8Array(length);
135
+ let offset = 0;
136
+ for (const chunk of chunks) {
137
+ bytes.set(chunk, offset);
138
+ offset += chunk.byteLength;
139
+ }
140
+ return bytes;
141
+ };
142
+ /**
143
+ * Creates a storage adapter that keeps files on disk, for development. Send the requests under `publicUrl` to its
144
+ * `handle`, which answers uploads and downloads.
145
+ *
146
+ * An upload URL is signed for one key, one content type and a largest size, until it expires. Its PUT writes a key
147
+ * once, so a recorded file is never replaced. Every file is served with a sandboxing Content Security Policy, and a
148
+ * file that isn't an image is served as a download.
149
+ *
150
+ * @example
151
+ * adapter: diskStorage({
152
+ * directory: '.data/uploads',
153
+ * publicUrl: 'http://localhost:3100/uploads',
154
+ * secret: process.env.UPLOADS_SECRET,
155
+ * }),
156
+ */
157
+ const diskStorage = (options) => {
158
+ if (!/^https?:\/\/[^/?#]+(\/[^?#]*[^/?#])?$/.test(options.publicUrl)) throw new Error(`\`publicUrl\` is '${options.publicUrl}'. Write it whole, like \`http://localhost:3100/uploads\`, with no trailing slash.`);
159
+ const publicPath = new URL(options.publicUrl).pathname.replace(/\/$/, "");
160
+ const isValidKey = (key) => /^[A-Za-z0-9._/-]+$/.test(key) && !key.includes("..");
161
+ const pathOf = (key) => {
162
+ if (!isValidKey(key)) throw new Error(`'${key}' is not a file key.`);
163
+ return join(options.directory, key);
164
+ };
165
+ const signatureOf = (upload) => createHmac("sha256", options.secret).update(JSON.stringify([
166
+ upload.key,
167
+ upload.expires,
168
+ upload.contentType,
169
+ upload.fileSize
170
+ ])).digest("base64url");
171
+ const isSignatureValid = (key, url, contentType) => {
172
+ const expires = Number(url.searchParams.get("expires") ?? NaN);
173
+ const fileSize = Number(url.searchParams.get("size") ?? NaN);
174
+ const given = url.searchParams.get("signature");
175
+ if (given === null || contentType === null || !Number.isSafeInteger(expires) || expires < Date.now()) return false;
176
+ if (!Number.isSafeInteger(fileSize) || fileSize < 0) return false;
177
+ const expected = Buffer.from(signatureOf({
178
+ key,
179
+ expires,
180
+ contentType,
181
+ fileSize
182
+ }));
183
+ const provided = Buffer.from(given);
184
+ return expected.length === provided.length && timingSafeEqual(expected, provided);
185
+ };
186
+ const status = (code) => new Response(null, { status: code });
187
+ return {
188
+ presignUpload: async ({ key, contentType, fileSize, expiresIn }) => {
189
+ const expires = Date.now() + expiresIn * 1e3;
190
+ const signature = signatureOf({
191
+ key,
192
+ expires,
193
+ contentType,
194
+ fileSize
195
+ });
196
+ return {
197
+ url: `${options.publicUrl}/${key}?expires=${expires}&size=${fileSize}&signature=${signature}`,
198
+ headers: { "content-type": contentType }
199
+ };
200
+ },
201
+ head: async (key) => {
202
+ const found = await stat(pathOf(key)).catch(() => void 0);
203
+ return found === void 0 ? void 0 : { fileSize: found.size };
204
+ },
205
+ read: async (key, length) => {
206
+ const bytes = await readFile(pathOf(key)).catch(() => void 0);
207
+ return bytes === void 0 ? void 0 : new Uint8Array(bytes.subarray(0, length));
208
+ },
209
+ put: async (key, bytes) => {
210
+ await mkdir(dirname(pathOf(key)), { recursive: true });
211
+ await writeFile(pathOf(key), bytes);
212
+ },
213
+ delete: async (key) => {
214
+ await rm(pathOf(key), { force: true });
215
+ },
216
+ url: async (key) => `${options.publicUrl}/${key}`,
217
+ handle: async (request) => {
218
+ const url = new URL(request.url);
219
+ if (!url.pathname.startsWith(`${publicPath}/`)) return status(404);
220
+ const key = url.pathname.slice(publicPath.length + 1);
221
+ if (!isValidKey(key)) return status(404);
222
+ if (request.method === "PUT") {
223
+ if (!isSignatureValid(key, url, request.headers.get("content-type"))) return status(403);
224
+ const bytes = await bodyWithin(request, Number(url.searchParams.get("size")));
225
+ if (bytes === void 0) return status(413);
226
+ await mkdir(dirname(pathOf(key)), { recursive: true });
227
+ return status(await writeFile(pathOf(key), bytes, { flag: "wx" }).then(() => true, (error) => {
228
+ if (error.code === "EEXIST") return false;
229
+ throw error;
230
+ }) ? 200 : 409);
231
+ }
232
+ const bytes = await readFile(pathOf(key)).catch(() => void 0);
233
+ if (bytes === void 0) return status(404);
234
+ const contentType = CONTENT_TYPES_BY_EXTENSION[/\.([a-z0-9]+)$/.exec(key)?.[1] ?? ""] ?? "application/octet-stream";
235
+ return new Response(new Uint8Array(bytes), {
236
+ status: 200,
237
+ headers: {
238
+ "content-type": contentType,
239
+ "x-content-type-options": "nosniff",
240
+ "content-security-policy": "default-src 'none'; sandbox",
241
+ ...contentType.startsWith("image/") ? {} : { "content-disposition": "attachment" }
242
+ }
243
+ });
244
+ }
245
+ };
246
+ };
247
+ /**
248
+ * A new key for an upload, which keeps the file's extension.
249
+ */
250
+ const newFileKey = (storage, filename) => {
251
+ const extension = /\.([A-Za-z0-9]{1,8})$/.exec(filename)?.[1]?.toLowerCase();
252
+ return `${storage.name}/${randomUUID()}${extension === void 0 ? "" : `.${extension}`}`;
253
+ };
254
+ /**
255
+ * Whether the store takes a file of this type, where `image/*` matches every image type.
256
+ */
257
+ const acceptsType = (storage, contentType) => {
258
+ if (storage.contentTypes === void 0) return true;
259
+ const type = contentType?.split(";", 1)[0].trim().toLowerCase();
260
+ if (type === void 0 || type === "") return false;
261
+ return storage.contentTypes.some((allowed) => {
262
+ const pattern = allowed.toLowerCase();
263
+ return pattern.endsWith("/*") ? type.startsWith(pattern.slice(0, -1)) : type === pattern;
264
+ });
265
+ };
266
+ //#endregion
267
+ //#region src/images.ts
268
+ const isFileField = (field) => field.type === "image" || field.type === "file";
269
+ const capitalized = (name) => name.charAt(0).toUpperCase() + name.slice(1);
270
+ const ImageVersionSchema = Kizuna.model({
271
+ title: "ImageVersion",
272
+ schema: z.object({
273
+ url: z.string(),
274
+ width: z.int(),
275
+ height: z.int()
276
+ })
277
+ });
278
+ /**
279
+ * What an image or file field takes on write: the file's id.
280
+ */
281
+ const fileWriteSchemaOf = (field) => z.strictObject({ file: TextSchema.describe(`The id of ${field.type === "image" ? "an image" : "a file"} in \`${field.storage}\`.`) });
282
+ const readSchemas = /* @__PURE__ */ new WeakMap();
283
+ /**
284
+ * What an image or file field reads as, built once per field so its model has one definition.
285
+ */
286
+ const fileReadSchemaOf = (field, owner, storeFields) => {
287
+ const existing = readSchemas.get(field);
288
+ if (existing !== void 0) return existing;
289
+ const schema = buildReadSchema(field, owner, storeFields());
290
+ readSchemas.set(field, schema);
291
+ return schema;
292
+ };
293
+ const buildReadSchema = (field, owner, storeFields) => {
294
+ const title = `${owner}${capitalized(field.name)}`;
295
+ if (field.type === "file") return Kizuna.model({
296
+ title,
297
+ schema: z.object({
298
+ id: z.string(),
299
+ url: z.string(),
300
+ filename: z.string(),
301
+ contentType: z.string(),
302
+ fileSize: z.int(),
303
+ ...storeFields
304
+ })
305
+ });
306
+ return Kizuna.model({
307
+ title,
308
+ schema: z.object({
309
+ id: z.string(),
310
+ alt: z.string().optional(),
311
+ filename: z.string(),
312
+ contentType: z.string(),
313
+ fileSize: z.int(),
314
+ focalPoint: FocalPointSchema,
315
+ original: ImageVersionSchema,
316
+ ...storeFields
317
+ })
318
+ });
319
+ };
320
+ /**
321
+ * Where an image stays in view when a site crops it, in percent from its top left corner.
322
+ */
323
+ const FocalPointSchema = Kizuna.model({
324
+ title: "FocalPoint",
325
+ schema: z.object({
326
+ x: z.number().min(0).max(100),
327
+ y: z.number().min(0).max(100)
328
+ })
329
+ });
330
+ /**
331
+ * An image's focal point, or its center when none is set.
332
+ */
333
+ const focalPointOf = (record) => record["focalPoint"] ?? {
334
+ x: 50,
335
+ y: 50
336
+ };
337
+ /**
338
+ * Why a document's files can't be written, or `undefined` when they can.
339
+ */
340
+ const fileProblemOf = async (db, fields, values) => {
341
+ for (const field of fields) {
342
+ if (!isFileField(field)) continue;
343
+ const value = values[field.name];
344
+ if (value === void 0 || value === null) continue;
345
+ if (await db.get(fileCollectionOf(storeNamed(field.storage)), value.file) === void 0) return `'${field.name}' points at '${value.file}', and '${field.storage}' has no file with that id.`;
346
+ }
347
+ };
348
+ /**
349
+ * Documents with their image and file fields read as the files they point at.
350
+ */
351
+ const resolveFiles = async (db, fields, documents) => {
352
+ const fileFields = fields.filter(isFileField);
353
+ if (fileFields.length === 0 || documents.length === 0) return [...documents];
354
+ const wanted = /* @__PURE__ */ new Map();
355
+ for (const document of documents) for (const field of fileFields) {
356
+ const value = document[field.name];
357
+ if (value?.file === void 0) continue;
358
+ const storage = storeNamed(field.storage);
359
+ const ids = wanted.get(storage) ?? /* @__PURE__ */ new Set();
360
+ ids.add(value.file);
361
+ wanted.set(storage, ids);
362
+ }
363
+ const found = /* @__PURE__ */ new Map();
364
+ for (const [storage, ids] of wanted) {
365
+ const { items } = await db.list(fileCollectionOf(storage), {
366
+ offset: 0,
367
+ limit: ids.size
368
+ }, { ids: [...ids] });
369
+ for (const record of items) {
370
+ const url = await storage.adapter.url(record["key"]);
371
+ found.set(`${storage.name}:${record.id}`, {
372
+ ...record,
373
+ url
374
+ });
375
+ }
376
+ }
377
+ return documents.map((document) => {
378
+ const resolved = { ...document };
379
+ for (const field of fileFields) {
380
+ const value = document[field.name];
381
+ if (value?.file === void 0) continue;
382
+ const record = found.get(`${field.storage}:${value.file}`);
383
+ if (record === void 0) {
384
+ delete resolved[field.name];
385
+ continue;
386
+ }
387
+ resolved[field.name] = field.type === "image" ? imageValueOf(field, record) : fileValueOf(field, record);
388
+ }
389
+ return resolved;
390
+ });
391
+ };
392
+ const storeFieldValuesOf = (field, record) => Object.fromEntries((storeNamed(field.storage).fields ?? []).filter((own) => record[own.name] !== void 0).map((own) => [own.name, record[own.name]]));
393
+ const fileValueOf = (field, record) => ({
394
+ id: record["id"],
395
+ url: record["url"],
396
+ filename: record["filename"],
397
+ contentType: record["contentType"],
398
+ fileSize: record["fileSize"],
399
+ ...storeFieldValuesOf(field, record)
400
+ });
401
+ /**
402
+ * A stored image's original as a document reads it.
403
+ */
404
+ const originalImageOf = async (storage, record) => ({
405
+ url: await storage.adapter.url(record["key"]),
406
+ width: record["width"] ?? 0,
407
+ height: record["height"] ?? 0
408
+ });
409
+ const imageValueOf = (field, record) => ({
410
+ id: record["id"],
411
+ ...record["alt"] === void 0 ? {} : { alt: record["alt"] },
412
+ filename: record["filename"],
413
+ contentType: record["contentType"],
414
+ fileSize: record["fileSize"],
415
+ focalPoint: focalPointOf(record),
416
+ original: {
417
+ url: record["url"],
418
+ width: record["width"] ?? 0,
419
+ height: record["height"] ?? 0
420
+ },
421
+ ...storeFieldValuesOf(field, record)
422
+ });
423
+ //#endregion
424
+ //#region src/limits.ts
425
+ const MINUTE = 60 * 1e3;
426
+ const HOUR = 60 * MINUTE;
427
+ const DAY = 24 * HOUR;
428
+ /**
429
+ * The largest upload in bytes when a store sets no `maxBytes`.
430
+ */
431
+ const DEFAULT_MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
432
+ /**
433
+ * The most pixels an uploaded image may have.
434
+ */
435
+ const MAX_IMAGE_PIXELS = 1e8;
436
+ /**
437
+ * How long a session lasts after logging in, in milliseconds.
438
+ */
439
+ const SESSION_LIFETIME = 30 * DAY;
440
+ /**
441
+ * How long a password reset link works, in milliseconds.
442
+ */
443
+ const PASSWORD_RESET_LIFETIME = HOUR;
444
+ /**
445
+ * How long an invite link works, in milliseconds.
446
+ */
447
+ const INVITE_LIFETIME = 7 * DAY;
448
+ /**
449
+ * The time {@link LOGIN_ATTEMPT_LIMIT} counts failed logins over, in milliseconds.
450
+ */
451
+ const LOGIN_WINDOW = 15 * MINUTE;
452
+ /**
453
+ * The time {@link PASSWORD_RESET_LIMIT} counts reset requests over, in milliseconds.
454
+ */
455
+ const PASSWORD_RESET_WINDOW = HOUR;
456
+ //#endregion
457
+ //#region src/fields.ts
458
+ const NUL_MESSAGE = "Text can’t hold the NUL character (U+0000).";
459
+ /**
460
+ * Whether a text is free of the NUL character, which Postgres can't store in text.
461
+ */
462
+ const isWithoutNul = (text) => !text.includes("\0");
463
+ /**
464
+ * Refuses the NUL character (U+0000) in a string schema, since Postgres can't store it in text.
465
+ */
466
+ const withoutNul = (schema) => schema.refine(isWithoutNul, NUL_MESSAGE);
467
+ /**
468
+ * The schema text passes: any string without the NUL character (U+0000).
469
+ */
470
+ const TextSchema = withoutNul(z.string());
471
+ const YEAR_MESSAGE = "Use a year from 0001 to 9999.";
472
+ /**
473
+ * Whether an ISO date or date-time names a year Postgres can store. ISO allows the year 0000, and Postgres has no
474
+ * year 0.
475
+ */
476
+ const isStorableYear = (value) => !value.startsWith("0000");
477
+ /**
478
+ * The schema a slug passes: lowercase letters and digits, with single hyphens between them, at most
479
+ * {@link MAX_SLUG_LENGTH} characters.
480
+ */
481
+ const SlugSchema = z.string().max(200).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase letters, digits and single hyphens.");
482
+ const optionValuesOf = (options) => {
483
+ const values = options.map((option) => typeof option === "string" ? option : option.value);
484
+ if (values.length === 0) throw new Error("A `select` field needs at least one option.");
485
+ return values;
486
+ };
487
+ const builtInSchemaOf = (field) => {
488
+ switch (field.type) {
489
+ case "text": {
490
+ let schema = TextSchema;
491
+ if (field.minLength !== void 0) schema = schema.min(field.minLength);
492
+ if (field.maxLength !== void 0) schema = schema.max(field.maxLength);
493
+ return schema;
494
+ }
495
+ case "number": {
496
+ let schema = field.integer === true ? z.int() : z.number();
497
+ if (field.min !== void 0) schema = schema.min(field.min);
498
+ if (field.max !== void 0) schema = schema.max(field.max);
499
+ return schema;
500
+ }
501
+ case "boolean": return z.boolean();
502
+ case "url": return withoutNul(z.url());
503
+ case "email": return withoutNul(z.email().max(254));
504
+ case "slug": return SlugSchema;
505
+ case "select": {
506
+ const choice = z.enum(optionValuesOf(field.options));
507
+ return field.many === true ? z.array(choice) : choice;
508
+ }
509
+ case "date": return z.iso.date().refine(isStorableYear, YEAR_MESSAGE);
510
+ case "dateTime": return z.iso.datetime().refine(isStorableYear, YEAR_MESSAGE);
511
+ case "relationship": return field.many === true ? z.array(TextSchema) : TextSchema;
512
+ case "image":
513
+ case "file": return z.unknown();
514
+ }
515
+ };
516
+ const builtInColumnOf = (field) => {
517
+ switch (field.type) {
518
+ case "number": return "number";
519
+ case "boolean": return "boolean";
520
+ case "select":
521
+ case "relationship": return field.many === true ? "json" : "text";
522
+ default: return "text";
523
+ }
524
+ };
525
+ /**
526
+ * The description that says where a relationship's or file's id points.
527
+ */
528
+ const referenceDescriptionOf = (field) => {
529
+ if (isFileField(field)) return `The id of a file in the store \`${field.storage}\`.`;
530
+ if (field.type !== "relationship") return void 0;
531
+ return field.many === true ? `The ids of documents in \`${field.to}\`.` : `The id of a document in \`${field.to}\`.`;
532
+ };
533
+ /**
534
+ * Returns the schema a field's value passes, with a description that says where a relationship's id points.
535
+ */
536
+ const schemaOf = (field, owner = "") => {
537
+ if (isFileField(field)) {
538
+ const storeFields = () => Object.fromEntries((storeNamed(field.storage).fields ?? []).map((own) => [own.name, wrappedSchemaOf(own, (schema) => schema.optional())]));
539
+ return fileReadSchemaOf(field, owner, storeFields);
540
+ }
541
+ const schema = builtInSchemaOf(field);
542
+ const description = [field.description, referenceDescriptionOf(field)].filter((line) => line !== void 0).join("\n\n");
543
+ return description === "" ? schema : schema.describe(description);
544
+ };
545
+ /**
546
+ * A field's schema wrapped in `optional` or `nullable`, with its description moved to the outer schema.
547
+ */
548
+ const wrappedSchemaOf = (field, wrap, owner = "") => {
549
+ const schema = schemaOf(field, owner);
550
+ const outer = wrap(schema);
551
+ return schema.description === void 0 ? outer : outer.describe(schema.description);
552
+ };
553
+ /**
554
+ * Returns how a field's value is stored in the database.
555
+ */
556
+ const columnOf = (field) => builtInColumnOf(field);
557
+ /**
558
+ * The schema a field's value passes on write, where an image or file is its id.
559
+ */
560
+ const writeSchemaOf = (field) => isFileField(field) ? fileWriteSchemaOf(field) : schemaOf(field);
561
+ /**
562
+ * {@link writeSchemaOf} with a wrap, like {@link wrappedSchemaOf}.
563
+ */
564
+ const wrappedWriteSchemaOf = (field, wrap) => {
565
+ const schema = writeSchemaOf(field);
566
+ const outer = wrap(schema);
567
+ return schema.description === void 0 ? outer : outer.describe(schema.description);
568
+ };
569
+ /**
570
+ * Puts a field's read schema into a shape, as a getter for image and file fields whose store loads later.
571
+ */
572
+ const setReadSchema = (shape, field, schemaFor) => {
573
+ if (!isFileField(field)) {
574
+ shape[field.name] = schemaFor();
575
+ return;
576
+ }
577
+ let schema;
578
+ Object.defineProperty(shape, field.name, {
579
+ enumerable: true,
580
+ get: () => schema ??= schemaFor()
581
+ });
582
+ };
583
+ //#endregion
584
+ //#region src/titles.ts
585
+ /**
586
+ * Fills in `titleField` as the default `generateFrom` of each slug and of the `meta` title.
587
+ */
588
+ const withTitleDefaults = (label, definition) => {
589
+ const title = definition.titleField;
590
+ if (title === void 0) return definition;
591
+ const field = definition.fields.find((candidate) => candidate.name === title);
592
+ if (field === void 0 || field.type !== "text") throw new Error(`${label} is titled by '${title}', which is no text field of it.`);
593
+ const meta = definition.meta === true ? {} : definition.meta;
594
+ return {
595
+ ...definition,
596
+ fields: definition.fields.map((candidate) => candidate.type === "slug" && candidate.generateFrom === void 0 ? {
597
+ ...candidate,
598
+ generateFrom: title
599
+ } : candidate),
600
+ ...meta === void 0 ? {} : { meta: {
601
+ ...meta,
602
+ title: {
603
+ generateFrom: title,
604
+ ...meta.title
605
+ }
606
+ } }
607
+ };
608
+ };
609
+ //#endregion
610
+ //#region src/meta.ts
611
+ /**
612
+ * A definition's `meta` options, where `true` reads as `{}`.
613
+ */
614
+ const metaOptionsOf = (definition) => definition.meta === true ? {} : definition.meta;
615
+ const titleOptions = /* @__PURE__ */ new WeakMap();
616
+ const setTitleSuffix = (definition, options) => {
617
+ titleOptions.set(definition, options);
618
+ };
619
+ const fieldNamed = (definition, name) => definition.fields.find((field) => field.name === name);
620
+ /**
621
+ * The store an editor's own share image comes from: `image.storage`, or the image field's store.
622
+ */
623
+ const metaImageStoreOf = (definition) => {
624
+ const meta = metaOptionsOf(definition);
625
+ if (meta?.image?.storage !== void 0) return meta.image.storage;
626
+ const source = meta?.image?.generateFrom;
627
+ if (source === void 0) return void 0;
628
+ const field = fieldNamed(definition, source);
629
+ return field !== void 0 && field.type === "image" ? field.storage : void 0;
630
+ };
631
+ /**
632
+ * Checks what `meta` points at when the collection is declared.
633
+ */
634
+ const checkMeta = (label, definition) => {
635
+ const meta = metaOptionsOf(definition);
636
+ if (meta === void 0) return;
637
+ for (const key of ["title", "description"]) {
638
+ const name = meta[key]?.generateFrom;
639
+ if (name === void 0) continue;
640
+ const field = fieldNamed(definition, name);
641
+ if (field === void 0 || field.type !== "text") throw new Error(`${label} takes its meta ${key} from '${name}', which is no text field of it.`);
642
+ }
643
+ const source = meta.image?.generateFrom;
644
+ if (source !== void 0) {
645
+ const field = fieldNamed(definition, source);
646
+ if (field === void 0 || field.type !== "image") throw new Error(`${label} takes its meta image from '${source}', which is no image field of it.`);
647
+ }
648
+ };
649
+ const MetaImageSchema = Kizuna.model({
650
+ title: "MetaImage",
651
+ schema: z.object({
652
+ id: z.string(),
653
+ url: z.string(),
654
+ width: z.int(),
655
+ height: z.int()
656
+ })
657
+ });
658
+ const metaSchemas = /* @__PURE__ */ new WeakMap();
659
+ /**
660
+ * The schema a document's `meta` reads as, where each value is the editor's, the field's or `null`.
661
+ */
662
+ const metaReadSchemaOf = (definition, owner) => {
663
+ const existing = metaSchemas.get(definition);
664
+ if (existing !== void 0) return existing;
665
+ const schema = Kizuna.model({
666
+ title: `${owner}Meta`,
667
+ schema: z.object({
668
+ title: z.string().nullable(),
669
+ description: z.string().nullable(),
670
+ ...metaImageStoreOf(definition) === void 0 ? {} : { image: MetaImageSchema.nullable() },
671
+ absoluteTitle: z.boolean().describe("The title as written, without the site’s suffix."),
672
+ robots: z.object({
673
+ index: z.boolean().describe("Show the page in search results."),
674
+ follow: z.boolean().describe("Let search engines follow the page's links.")
675
+ }).describe("What search engines may do with the page, in the shape `robots` takes in Next.js metadata."),
676
+ canonical: z.string().nullable().describe("Another address that is the original of this page.")
677
+ })
678
+ });
679
+ metaSchemas.set(definition, schema);
680
+ return schema;
681
+ };
682
+ /**
683
+ * The editor's own `meta` values a write takes, where `null` falls back to the field.
684
+ */
685
+ const metaWriteSchemaOf = (definition) => z.strictObject({
686
+ title: TextSchema.min(1).max(70).nullable().optional().describe(`Up to 60 characters show in full.`),
687
+ description: TextSchema.min(1).max(200).nullable().optional().describe(`Up to 160 characters show in full.`),
688
+ ...metaImageStoreOf(definition) === void 0 ? {} : { image: z.strictObject({ file: TextSchema }).nullable().optional() },
689
+ ...titleOptions.has(definition) ? { absoluteTitle: z.boolean().optional() } : {},
690
+ robots: z.strictObject({
691
+ index: z.boolean().optional(),
692
+ follow: z.boolean().optional()
693
+ }).optional(),
694
+ canonical: withoutNul(z.url()).nullable().optional()
695
+ }).optional();
696
+ /**
697
+ * Returns the editor's own `robots` values from a stored `meta`.
698
+ */
699
+ const robotsOf = (meta) => typeof meta["robots"] === "object" && meta["robots"] !== null ? meta["robots"] : {};
700
+ /**
701
+ * An update's `meta` merged over the stored one, where `null` removes a value.
702
+ */
703
+ const mergeMetaChange = (change, stored) => {
704
+ const next = change["meta"];
705
+ if (next === void 0) return change;
706
+ const merged = { ...stored?.["meta"] ?? {} };
707
+ for (const [key, value] of Object.entries(next)) if (value === null) delete merged[key];
708
+ else if (key === "robots") merged[key] = {
709
+ ...robotsOf(merged),
710
+ ...value
711
+ };
712
+ else merged[key] = value;
713
+ return {
714
+ ...change,
715
+ meta: merged
716
+ };
717
+ };
718
+ /**
719
+ * Why a write's own share image can't be used, or `undefined`.
720
+ */
721
+ const metaImageProblemOf = async (db, definition, values) => {
722
+ const image = values["meta"]?.image;
723
+ const store = metaImageStoreOf(definition);
724
+ if (image === void 0 || image === null || store === void 0) return void 0;
725
+ return await db.get(fileCollectionOf(storeNamed(store)), image.file) === void 0 ? `The meta image '${image.file}' is no file of '${store}'.` : void 0;
726
+ };
727
+ /**
728
+ * Documents with their `meta` filled in for search results, once their image fields are resolved.
729
+ */
730
+ const resolveMeta = async (db, definition, documents) => {
731
+ const meta = metaOptionsOf(definition);
732
+ if (meta === void 0) return [...documents];
733
+ const storeName = metaImageStoreOf(definition);
734
+ const storage = storeName === void 0 ? void 0 : storeNamed(storeName);
735
+ const ownIds = documents.map((document) => document["meta"]?.image?.file).filter((id) => id !== void 0);
736
+ const ownImages = /* @__PURE__ */ new Map();
737
+ if (storage !== void 0 && ownIds.length > 0) {
738
+ const { items } = await db.list(fileCollectionOf(storage), {
739
+ offset: 0,
740
+ limit: ownIds.length
741
+ }, { ids: [...new Set(ownIds)] });
742
+ for (const record of items) ownImages.set(record.id, record);
743
+ }
744
+ const source = meta.image?.generateFrom;
745
+ return Promise.all(documents.map(async (document) => {
746
+ const own = document["meta"] ?? {};
747
+ const absolute = own["absoluteTitle"] === true;
748
+ const text = (key) => {
749
+ if (typeof own[key] === "string") return own[key];
750
+ const name = meta[key]?.generateFrom;
751
+ const value = name === void 0 ? void 0 : document[name];
752
+ return typeof value === "string" && value !== "" ? value : null;
753
+ };
754
+ const image = async () => {
755
+ const ownFile = own["image"]?.file;
756
+ const ownRecord = ownFile === void 0 ? void 0 : ownImages.get(ownFile);
757
+ if (ownRecord !== void 0 && storage !== void 0) return {
758
+ id: ownRecord.id,
759
+ ...await originalImageOf(storage, ownRecord)
760
+ };
761
+ if (source === void 0) return null;
762
+ const pointed = document[source];
763
+ return pointed === void 0 ? null : {
764
+ id: pointed.id,
765
+ ...pointed.original
766
+ };
767
+ };
768
+ const title = () => {
769
+ const written = text("title");
770
+ const ending = titleOptions.get(definition);
771
+ if (written === null || ending === void 0 || absolute || written.endsWith(ending.suffix)) return written;
772
+ return `${written} ${ending.separator ?? "-"} ${ending.suffix}`;
773
+ };
774
+ return {
775
+ ...document,
776
+ meta: {
777
+ title: title(),
778
+ description: text("description"),
779
+ ...storeName === void 0 ? {} : { image: await image() },
780
+ absoluteTitle: absolute,
781
+ robots: {
782
+ index: robotsOf(own)["index"] !== false,
783
+ follow: robotsOf(own)["follow"] !== false
784
+ },
785
+ canonical: typeof own["canonical"] === "string" ? own["canonical"] : null
786
+ }
787
+ };
788
+ }));
789
+ };
790
+ /**
791
+ * Documents read with their files and their `meta`.
792
+ */
793
+ const resolveDocuments = async (db, definition, documents) => resolveEditors(db, await resolveMeta(db, definition, await resolveFiles(db, definition.fields, documents)));
794
+ const editorsCollections = /* @__PURE__ */ new WeakMap();
795
+ /**
796
+ * Names the collection a database's `createdBy` and `updatedBy` editors are kept in.
797
+ */
798
+ const setEditorsCollection = (db, collection) => {
799
+ editorsCollections.set(db, {
800
+ collection: collection.name,
801
+ titleField: collection.titleField
802
+ });
803
+ };
804
+ /**
805
+ * Turns each `createdBy` and `updatedBy` id into the editor's id and name. It leaves out editors who are gone, and
806
+ * editors with no name, so an email never stands in for one.
807
+ */
808
+ const resolveEditors = async (db, documents) => {
809
+ const ids = new Set(documents.flatMap((document) => [document["createdBy"], document["updatedBy"]].filter((id) => typeof id === "string")));
810
+ const editors = editorsCollections.get(db);
811
+ const names = /* @__PURE__ */ new Map();
812
+ for (const id of editors === void 0 ? [] : ids) {
813
+ const editor = await db.get(editors.collection, id);
814
+ if (editor === void 0) continue;
815
+ const title = editors.titleField === void 0 ? void 0 : editor[editors.titleField];
816
+ if (typeof title === "string" && title !== "") names.set(id, title);
817
+ }
818
+ return documents.map((document) => {
819
+ const resolved = { ...document };
820
+ for (const key of ["createdBy", "updatedBy"]) {
821
+ const id = document[key];
822
+ if (typeof id !== "string") continue;
823
+ const name = names.get(id);
824
+ if (name === void 0) delete resolved[key];
825
+ else resolved[key] = {
826
+ id,
827
+ name
828
+ };
829
+ }
830
+ return resolved;
831
+ });
832
+ };
833
+ /**
834
+ * Returns the document without `createdBy` and `updatedBy`, as a read anyone may make shows it.
835
+ */
836
+ const withoutEditorReferences = (document) => {
837
+ const { createdBy: _createdBy, updatedBy: _updatedBy, ...rest } = document;
838
+ return rest;
839
+ };
840
+ /**
841
+ * Returns who made and last changed a stored document, as `createdBy` and `updatedBy` with each editor's id and name.
842
+ */
843
+ const editorReferencesOf = async (db, stored) => {
844
+ const [resolved] = await resolveEditors(db, [{
845
+ createdBy: stored["createdBy"],
846
+ updatedBy: stored["updatedBy"]
847
+ }]);
848
+ return resolved;
849
+ };
850
+ /**
851
+ * A document's `meta` as the editor wrote it, without fallbacks.
852
+ */
853
+ const writtenMetaOf = (stored) => stored?.["meta"] ?? {};
854
+ /**
855
+ * The schema of the `meta` an editor wrote, which a hidden route returns.
856
+ */
857
+ const WrittenMetaSchema = z.record(z.string(), z.unknown());
858
+ //#endregion
859
+ //#region src/slugs.ts
860
+ const slugOptions = /* @__PURE__ */ new WeakMap();
861
+ const setSlugOptions = (definition, options) => {
862
+ slugOptions.set(definition, options);
863
+ };
864
+ /**
865
+ * The slug a text makes, in the definition's style. A text with no letters or digits makes `''`.
866
+ */
867
+ const slugOf = (definition, text) => {
868
+ const options = slugOptions.get(definition);
869
+ return slugify(text, {
870
+ ...options?.locale === void 0 ? {} : { locale: options.locale },
871
+ ...options?.replacements === void 0 ? {} : { customReplacements: options.replacements.map(([from, to]) => [from, to]) }
872
+ });
873
+ };
874
+ const generatedSlugFieldsOf = (fields) => fields.filter((field) => field.type === "slug" && field.generateFrom !== void 0);
875
+ /**
876
+ * Checks that a slug's `generateFrom` names a text field beside it.
877
+ */
878
+ const checkSlugs = (label, fields) => {
879
+ for (const slug of generatedSlugFieldsOf(fields)) {
880
+ if (typeof slug.generateFrom === "function") continue;
881
+ const source = fields.find((field) => field.name === slug.generateFrom);
882
+ if (source === void 0 || source.type !== "text") throw new Error(`${label} makes the slug '${slug.name}' from '${slug.generateFrom}', which is no text field of it.`);
883
+ }
884
+ };
885
+ /**
886
+ * Fills each empty slug in a new document from its `generateFrom`. A made slug that comes out empty counts as no slug,
887
+ * so a required one answers 422.
888
+ */
889
+ const withGeneratedSlugs = (definition, values) => {
890
+ const filled = { ...values };
891
+ for (const slug of generatedSlugFieldsOf(definition.fields)) {
892
+ const current = filled[slug.name];
893
+ if (current !== void 0 && current !== "") continue;
894
+ const source = typeof slug.generateFrom === "function" ? slug.generateFrom(filled) : filled[slug.generateFrom];
895
+ const made = typeof source === "string" ? slugOf(definition, source) : "";
896
+ if (made === "") delete filled[slug.name];
897
+ else filled[slug.name] = made;
898
+ }
899
+ return filled;
900
+ };
901
+ /**
902
+ * Whether the CMS fills in the slug when a new document leaves it out.
903
+ */
904
+ const isGeneratedSlug = (field) => field.type === "slug" && field.generateFrom !== void 0;
905
+ //#endregion
906
+ //#region src/collection.ts
907
+ const NAME_PATTERN = /^[a-z][a-zA-Z0-9]*$/;
908
+ /**
909
+ * Names no collection may take, because the CMS's own routes sit at these paths.
910
+ */
911
+ const RESERVED_COLLECTION_NAMES = new Set(["globals", "storage"]);
912
+ const MODEL_NAME_PATTERN = /^[A-Z][a-zA-Z0-9]*$/;
913
+ const RESERVED_FIELDS = new Set([
914
+ "id",
915
+ "createdAt",
916
+ "updatedAt",
917
+ "createdBy",
918
+ "updatedBy",
919
+ "meta"
920
+ ]);
921
+ /**
922
+ * Checks the name and fields of a collection, global or store.
923
+ */
924
+ const checkDefinition = (label, name, fields, example) => {
925
+ if (!NAME_PATTERN.test(name)) throw new Error(`${label} needs a camelCase name that starts with a letter, like ${example}.`);
926
+ const seen = /* @__PURE__ */ new Set();
927
+ for (const field of fields) {
928
+ if (RESERVED_FIELDS.has(field.name)) throw new Error(`${label} has a field named '${field.name}', which every document already carries.`);
929
+ if (seen.has(field.name)) throw new Error(`${label} has two fields named '${field.name}'.`);
930
+ seen.add(field.name);
931
+ }
932
+ checkSlugs(label, fields);
933
+ };
934
+ /**
935
+ * `blogPosts` as "Blog posts".
936
+ */
937
+ const sentenceCaseOf = (name) => {
938
+ const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
939
+ return words.charAt(0).toUpperCase() + words.slice(1);
940
+ };
941
+ /**
942
+ * Returns what a collection calls one document and the whole collection, from its `labels` or its name.
943
+ */
944
+ const labelsOf = (collection) => ({
945
+ singular: collection.labels?.singular ?? sentenceCaseOf(pluralize.singular(collection.name)),
946
+ plural: collection.labels?.plural ?? sentenceCaseOf(collection.name)
947
+ });
948
+ /**
949
+ * The document's type name: `model`, or the singular of `name` with a capital letter.
950
+ */
951
+ const modelNameOf = (collection) => {
952
+ const singular = pluralize.singular(collection.name);
953
+ return collection.model ?? singular.charAt(0).toUpperCase() + singular.slice(1);
954
+ };
955
+ /**
956
+ * Checks a collection's definition and returns the collection, for `k.collection`.
957
+ */
958
+ const defineCollection = (declared) => {
959
+ const definition = withTitleDefaults(`Collection '${declared.name}'`, declared);
960
+ checkDefinition(`Collection '${definition.name}'`, definition.name, definition.fields, "`stores` or `blogPosts`");
961
+ if (RESERVED_COLLECTION_NAMES.has(definition.name)) throw new Error(`Collection '${definition.name}' takes the path /${definition.name}, where the CMS's own routes sit. Pick another name.`);
962
+ checkMeta(`Collection '${definition.name}'`, definition);
963
+ if (definition.model !== void 0 && !MODEL_NAME_PATTERN.test(definition.model)) throw new Error(`Collection '${definition.name}' needs a \`model\` that starts with a capital letter, like \`Employee\`.`);
964
+ const title = modelNameOf(definition);
965
+ return {
966
+ ...definition,
967
+ ...definition.meta === true ? { meta: {} } : {},
968
+ kind: "collection",
969
+ schema: Kizuna.model({
970
+ title,
971
+ schema: documentSchemaOf(definition)
972
+ })
973
+ };
974
+ };
975
+ /**
976
+ * The editor a document's `createdBy` or `updatedBy` names.
977
+ */
978
+ const EditorReferenceSchema = Kizuna.model({
979
+ title: "EditorRef",
980
+ schema: z.object({
981
+ id: z.string(),
982
+ name: z.string()
983
+ })
984
+ });
985
+ const DocumentMetaShape = {
986
+ id: z.string().describe("The document's id."),
987
+ createdAt: z.iso.datetime().describe("When the document was made."),
988
+ updatedAt: z.iso.datetime().describe("When the document last changed."),
989
+ createdBy: EditorReferenceSchema.optional().describe("Who made it."),
990
+ updatedBy: EditorReferenceSchema.optional().describe("Who changed it last.")
991
+ };
992
+ /**
993
+ * Returns the schema of one stored document of a collection.
994
+ */
995
+ const documentSchemaOf = (collection) => {
996
+ const owner = modelNameOf(collection);
997
+ const shape = { ...DocumentMetaShape };
998
+ for (const field of collection.fields) setReadSchema(shape, field, () => field.required === true ? schemaOf(field, owner) : wrappedSchemaOf(field, (schema) => schema.optional(), owner));
999
+ if (collection.meta !== void 0) shape["meta"] = metaReadSchemaOf(collection, owner);
1000
+ return z.object(shape);
1001
+ };
1002
+ /**
1003
+ * The schema a create's body passes, without the read-only fields.
1004
+ */
1005
+ const createSchemaOf = (collection) => {
1006
+ const shape = {};
1007
+ for (const field of collection.fields) {
1008
+ if (field.readOnly === true) continue;
1009
+ shape[field.name] = field.required === true && !isGeneratedSlug(field) ? writeSchemaOf(field) : wrappedWriteSchemaOf(field, (schema) => schema.optional());
1010
+ }
1011
+ if (collection.meta !== void 0) shape["meta"] = metaWriteSchemaOf(collection);
1012
+ return z.strictObject(shape);
1013
+ };
1014
+ /**
1015
+ * The schema an update's body passes, where every writable field is optional and `null` clears an optional one.
1016
+ */
1017
+ const updateSchemaOf = (collection) => {
1018
+ const shape = {};
1019
+ for (const field of collection.fields) {
1020
+ if (field.readOnly === true) continue;
1021
+ shape[field.name] = wrappedWriteSchemaOf(field, (schema) => field.required === true ? schema.optional() : schema.nullable().optional());
1022
+ }
1023
+ if (collection.meta !== void 0) shape["meta"] = metaWriteSchemaOf(collection);
1024
+ return z.strictObject(shape);
1025
+ };
1026
+ //#endregion
1027
+ //#region src/where.ts
1028
+ const OPERATORS = new Set([
1029
+ "equals",
1030
+ "not",
1031
+ "in",
1032
+ "notIn",
1033
+ "exists",
1034
+ "contains",
1035
+ "hasAll",
1036
+ "greaterThan",
1037
+ "atLeast",
1038
+ "lessThan",
1039
+ "atMost"
1040
+ ]);
1041
+ /**
1042
+ * Each field's conditions. Throws on an operator the CMS doesn't know.
1043
+ */
1044
+ const conditionsOf = (where) => {
1045
+ const conditions = [];
1046
+ for (const [field, operators] of Object.entries(where)) {
1047
+ if (field === "and" || field === "or" || operators === void 0) continue;
1048
+ for (const [operator, value] of Object.entries(operators)) {
1049
+ if (!OPERATORS.has(operator)) throw new Error(`'${operator}' on '${field}' is not an operator. Use one of: ${[...OPERATORS].join(", ")}.`);
1050
+ if (value === void 0) continue;
1051
+ conditions.push({
1052
+ field,
1053
+ operator,
1054
+ value
1055
+ });
1056
+ }
1057
+ }
1058
+ return conditions;
1059
+ };
1060
+ /**
1061
+ * The sort as field names and directions, in turn.
1062
+ */
1063
+ const sortOrderOf = (sort) => (sort === void 0 ? [] : typeof sort === "string" ? [sort] : sort).map((key) => key.startsWith("-") ? {
1064
+ field: key.slice(1),
1065
+ descending: true
1066
+ } : {
1067
+ field: key,
1068
+ descending: false
1069
+ });
1070
+ const isPresent = (value) => value !== void 0 && value !== null;
1071
+ const matchesCondition = (actual, operator, expected) => {
1072
+ switch (operator) {
1073
+ case "equals": return actual === expected;
1074
+ case "not": return actual !== expected;
1075
+ case "in": return Array.isArray(actual) ? actual.some((item) => expected.includes(item)) : expected.includes(actual);
1076
+ case "notIn": return !expected.includes(actual);
1077
+ case "exists": return isPresent(actual) === expected;
1078
+ case "contains": return Array.isArray(actual) ? actual.includes(expected) : typeof actual === "string" && actual.toLowerCase().includes(String(expected).toLowerCase());
1079
+ case "hasAll": return Array.isArray(actual) && expected.every((item) => actual.includes(item));
1080
+ case "greaterThan": return isPresent(actual) && actual > expected;
1081
+ case "atLeast": return isPresent(actual) && actual >= expected;
1082
+ case "lessThan": return isPresent(actual) && actual < expected;
1083
+ case "atMost": return isPresent(actual) && actual <= expected;
1084
+ default: return false;
1085
+ }
1086
+ };
1087
+ /**
1088
+ * A field's value, following a dotted path like `cover.file` into a stored object.
1089
+ */
1090
+ const valueAt = (document, path) => path.split(".").reduce((value, key) => value !== null && typeof value === "object" ? value[key] : void 0, document);
1091
+ /**
1092
+ * Whether a document matches a `where`.
1093
+ */
1094
+ const matchesWhere = (document, where) => conditionsOf(where).every(({ field, operator, value }) => matchesCondition(valueAt(document, field), operator, value)) && (where.and ?? []).every((part) => matchesWhere(document, part)) && (where.or === void 0 || where.or.some((part) => matchesWhere(document, part)));
1095
+ /**
1096
+ * Orders documents by a sort. A document without the value comes last.
1097
+ */
1098
+ const compareBySort = (sort) => (first, second) => {
1099
+ for (const { field, descending } of sort) {
1100
+ const left = first[field];
1101
+ const right = second[field];
1102
+ if (left === right) continue;
1103
+ if (!isPresent(left)) return 1;
1104
+ if (!isPresent(right)) return -1;
1105
+ const order = left < right ? -1 : 1;
1106
+ return descending ? -order : order;
1107
+ }
1108
+ return 0;
1109
+ };
1110
+ //#endregion
1111
+ //#region src/db.ts
1112
+ /**
1113
+ * The collection that holds globals, one document each with the global's name as its id.
1114
+ */
1115
+ const GLOBALS_COLLECTION = "globals";
1116
+ /**
1117
+ * The error an adapter throws when another document blocks a write, which routes answer with a 409.
1118
+ */
1119
+ var ConflictError = class extends Error {};
1120
+ const withoutNulls = (values) => Object.fromEntries(Object.entries(values).filter(([, value]) => value !== null && value !== void 0));
1121
+ /**
1122
+ * Creates a database adapter that keeps everything in memory, for tests. Nothing survives a restart.
1123
+ *
1124
+ * @example
1125
+ * export default defineConfig({
1126
+ * name: 'Example',
1127
+ * db: memoryAdapter(),
1128
+ * collections: [Articles, Users],
1129
+ * users: Users,
1130
+ * roles: ['editor'],
1131
+ * });
1132
+ */
1133
+ const memoryAdapter = () => {
1134
+ const collections = /* @__PURE__ */ new Map();
1135
+ const passwordHashes = /* @__PURE__ */ new Map();
1136
+ const sessions = /* @__PURE__ */ new Map();
1137
+ const passwordTokens = /* @__PURE__ */ new Map();
1138
+ const failedLogins = /* @__PURE__ */ new Map();
1139
+ const passwordResetRequests = /* @__PURE__ */ new Map();
1140
+ /**
1141
+ * The collections that hold a store's file records, where one key has one record.
1142
+ */
1143
+ const stores = /* @__PURE__ */ new Set();
1144
+ const withoutTimesBefore = (times, before) => {
1145
+ for (const [key, kept] of times) {
1146
+ const recent = kept.filter((at) => at >= before);
1147
+ if (recent.length === 0) times.delete(key);
1148
+ else times.set(key, recent);
1149
+ }
1150
+ };
1151
+ const documentsOf = (collection) => {
1152
+ const existing = collections.get(collection);
1153
+ if (existing !== void 0) return existing;
1154
+ const created = /* @__PURE__ */ new Map();
1155
+ collections.set(collection, created);
1156
+ return created;
1157
+ };
1158
+ const createGlobalIfMissing = (name) => {
1159
+ const globals = documentsOf(GLOBALS_COLLECTION);
1160
+ if (globals.has(name)) return;
1161
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1162
+ globals.set(name, {
1163
+ id: name,
1164
+ createdAt: now,
1165
+ updatedAt: now
1166
+ });
1167
+ };
1168
+ const db = {
1169
+ prepare: (definitions) => {
1170
+ for (const store of definitions.storage) stores.add(fileCollectionOf(store));
1171
+ },
1172
+ list: async (collection, page, options) => {
1173
+ const where = options?.where;
1174
+ const ids = options?.ids;
1175
+ const readable = [...documentsOf(collection).values()].filter((document) => ids === void 0 || ids.includes(document.id)).filter((document) => where === void 0 || matchesWhere(document, where)).sort(compareBySort(sortOrderOf(options?.sort)));
1176
+ return {
1177
+ items: readable.slice(page.offset, page.offset + page.limit),
1178
+ total: readable.length
1179
+ };
1180
+ },
1181
+ get: async (collection, id) => documentsOf(collection).get(id),
1182
+ create: async (collection, values, by) => {
1183
+ if (stores.has(collection) && [...documentsOf(collection).values()].some((document) => document["key"] === values["key"])) throw new ConflictError(`Another file has the key '${String(values["key"])}'.`);
1184
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1185
+ const document = {
1186
+ ...values,
1187
+ id: crypto.randomUUID(),
1188
+ createdAt: now,
1189
+ updatedAt: now,
1190
+ ...by === void 0 ? {} : {
1191
+ createdBy: by,
1192
+ updatedBy: by
1193
+ }
1194
+ };
1195
+ documentsOf(collection).set(document.id, document);
1196
+ return document;
1197
+ },
1198
+ update: async (collection, id, values, by) => {
1199
+ const documents = documentsOf(collection);
1200
+ const existing = documents.get(id);
1201
+ if (existing === void 0) return void 0;
1202
+ const updated = {
1203
+ ...withoutNulls({
1204
+ ...existing,
1205
+ ...values
1206
+ }),
1207
+ id,
1208
+ createdAt: existing.createdAt,
1209
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1210
+ ...by === void 0 ? {} : { updatedBy: by }
1211
+ };
1212
+ documents.set(id, updated);
1213
+ return updated;
1214
+ },
1215
+ delete: async (collection, id) => {
1216
+ passwordHashes.delete(`${collection}\u0000${id}`);
1217
+ for (const [tokenHash, session] of sessions) if (session.accountId === id) sessions.delete(tokenHash);
1218
+ for (const [tokenHash, token] of passwordTokens) if (token.accountId === id) passwordTokens.delete(tokenHash);
1219
+ return documentsOf(collection).delete(id);
1220
+ },
1221
+ getGlobal: (name) => db.get(GLOBALS_COLLECTION, name),
1222
+ updateGlobal: async (name, values, by) => {
1223
+ createGlobalIfMissing(name);
1224
+ return await db.update(GLOBALS_COLLECTION, name, values, by);
1225
+ },
1226
+ passwordHashOf: async (collection, id) => passwordHashes.get(`${collection}\u0000${id}`),
1227
+ setPasswordHash: async (collection, id, hash) => {
1228
+ if (documentsOf(collection).has(id)) passwordHashes.set(`${collection}\u0000${id}`, hash);
1229
+ },
1230
+ createSession: async (session) => {
1231
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1232
+ for (const [tokenHash, stored] of sessions) if (stored.expiresAt <= now) sessions.delete(tokenHash);
1233
+ sessions.set(session.tokenHash, { ...session });
1234
+ },
1235
+ getSession: async (tokenHash) => sessions.get(tokenHash),
1236
+ deleteSession: async (tokenHash) => {
1237
+ sessions.delete(tokenHash);
1238
+ },
1239
+ deleteSessionsOf: async (accountId, keep) => {
1240
+ for (const [tokenHash, session] of sessions) if (session.accountId === accountId && tokenHash !== keep) sessions.delete(tokenHash);
1241
+ },
1242
+ createPasswordToken: async (token) => {
1243
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1244
+ for (const [tokenHash, stored] of passwordTokens) if (stored.expiresAt <= now) passwordTokens.delete(tokenHash);
1245
+ passwordTokens.set(token.tokenHash, { ...token });
1246
+ },
1247
+ takePasswordToken: async (tokenHash) => {
1248
+ const token = passwordTokens.get(tokenHash);
1249
+ passwordTokens.delete(tokenHash);
1250
+ return token;
1251
+ },
1252
+ deletePasswordTokensOf: async (accountId) => {
1253
+ for (const [tokenHash, token] of passwordTokens) if (token.accountId === accountId) passwordTokens.delete(tokenHash);
1254
+ },
1255
+ recordFailedLogin: async (collection, email) => {
1256
+ withoutTimesBefore(failedLogins, new Date(Date.now() - LOGIN_WINDOW).toISOString());
1257
+ const key = `${collection}\u0000${email}`;
1258
+ failedLogins.set(key, [...failedLogins.get(key) ?? [], (/* @__PURE__ */ new Date()).toISOString()]);
1259
+ },
1260
+ failedLoginsSince: async (collection, email, since) => (failedLogins.get(`${collection}\u0000${email}`) ?? []).filter((at) => at >= since).length,
1261
+ clearFailedLogins: async (collection, email) => {
1262
+ failedLogins.delete(`${collection}\u0000${email}`);
1263
+ },
1264
+ recordPasswordResetRequest: async (collection, email) => {
1265
+ withoutTimesBefore(passwordResetRequests, new Date(Date.now() - PASSWORD_RESET_WINDOW).toISOString());
1266
+ const key = `${collection}\u0000${email}`;
1267
+ passwordResetRequests.set(key, [...passwordResetRequests.get(key) ?? [], (/* @__PURE__ */ new Date()).toISOString()]);
1268
+ },
1269
+ passwordResetRequestsSince: async (collection, email, since) => (passwordResetRequests.get(`${collection}\u0000${email}`) ?? []).filter((at) => at >= since).length
1270
+ };
1271
+ return db;
1272
+ };
1273
+ //#endregion
1274
+ export { schemaOf as A, FocalPointSchema as B, setEditorsCollection as C, SlugSchema as D, writtenMetaOf as E, LOGIN_WINDOW as F, diskStorage as G, isFileField as H, MAX_IMAGE_PIXELS as I, newFileKey as J, fileCollectionOf as K, PASSWORD_RESET_LIFETIME as L, wrappedSchemaOf as M, DEFAULT_MAX_UPLOAD_BYTES as N, TextSchema as O, INVITE_LIFETIME as P, PASSWORD_RESET_WINDOW as R, resolveDocuments as S, withoutEditorReferences as T, acceptsType as U, fileProblemOf as V, defineStorage as W, storeFieldTypesOf as X, registerStores as Y, WrittenMetaSchema as _, sortOrderOf as a, metaImageProblemOf as b, createSchemaOf as c, labelsOf as d, modelNameOf as f, withGeneratedSlugs as g, setSlugOptions as h, conditionsOf as i, setReadSchema as j, columnOf as k, defineCollection as l, isGeneratedSlug as m, GLOBALS_COLLECTION as n, EditorReferenceSchema as o, updateSchemaOf as p, memoryStorage as q, memoryAdapter as r, checkDefinition as s, ConflictError as t, documentSchemaOf as u, editorReferencesOf as v, setTitleSuffix as w, metaImageStoreOf as x, mergeMetaChange as y, SESSION_LIFETIME as z };