foldkit-cms 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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1150 @@
1
+ import { Effect, Option, Schema } from "effect";
2
+ import { Derived, Entity, Expr, Order, Relation } from "foldkit-entity";
3
+ import { Metadata } from "foldkit-metadata";
4
+ import { Mutation, Query, Remote } from "foldkit-remote";
5
+ import { Bundle } from "foldkit-bundle";
6
+ import { defineMessageUnion } from "foldkit/message";
7
+ import * as Submodel from "foldkit/submodel";
8
+ import { Display } from "foldkit-crud";
9
+ import { Input } from "foldkit-form";
10
+ //#region src/lifecycle.ts
11
+ const scheduleOf$1 = (draft, now) => draft === null || draft.scheduledFor === null ? null : {
12
+ at: draft.scheduledFor,
13
+ overdue: new Date(draft.scheduledFor).getTime() <= now.getTime(),
14
+ error: draft.scheduleError
15
+ };
16
+ const state = (facts, now) => {
17
+ if (facts.archivedAt !== null) return {
18
+ _tag: "Archived",
19
+ schedule: null
20
+ };
21
+ const schedule = scheduleOf$1(facts.draft, now);
22
+ if (facts.row === "hidden") return {
23
+ _tag: "Unpublished",
24
+ schedule
25
+ };
26
+ if (facts.row === "none") return {
27
+ _tag: "New",
28
+ schedule
29
+ };
30
+ return facts.draft === null ? {
31
+ _tag: "Published",
32
+ schedule: null
33
+ } : {
34
+ _tag: "Changed",
35
+ schedule
36
+ };
37
+ };
38
+ /**
39
+ * The transitions a state offers, before anyone asks who is asking. `facts` says
40
+ * whether there is a draft, which a state alone does not: an unpublished entry
41
+ * may or may not have one. `unpublishes` is whether the content type declared a
42
+ * `published` role: without one a row cannot be hidden, so it is not offered.
43
+ */
44
+ const offers = (facts, now, capabilities) => {
45
+ const current = state(facts, now);
46
+ if (current._tag === "Archived") return ["unarchive"];
47
+ const drafted = facts.draft !== null;
48
+ return [
49
+ "save",
50
+ ...drafted ? ["discard", "publish"] : [],
51
+ ...drafted && current.schedule === null ? ["schedule"] : [],
52
+ ...current.schedule !== null ? ["unschedule"] : [],
53
+ ...facts.row === "visible" && capabilities.unpublishes ? ["unpublish"] : [],
54
+ ...facts.row !== "none" ? ["restore"] : [],
55
+ "archive"
56
+ ];
57
+ };
58
+ //#endregion
59
+ //#region src/slug.ts
60
+ /**
61
+ * How a server says a slug is taken, and how a client reads it back. It is a
62
+ * mutation's error, which is a message and no more, so the key it is about rides
63
+ * in a prefix: `CmsSlugTaken: <key>: ...`.
64
+ */
65
+ const slugTaken = {
66
+ message: (key, slug) => `CmsSlugTaken: ${key}: "${slug}" is already used`,
67
+ /** The form key the error names, or `undefined` for an error about something else. */
68
+ key: (message) => /CmsSlugTaken: ([^:]+): /.exec(message)?.[1],
69
+ /** What to show on that key: the reason, without the prefix that addressed it. */
70
+ reason: (message) => message.replace(/^.*?CmsSlugTaken: [^:]+: /, "That address is taken: ")
71
+ };
72
+ /**
73
+ * A form check that says, while the author types, what a publish would refuse:
74
+ * this address belongs to something else. It asks the content type's `bySlug`
75
+ * query, which an author reads through the same binding as everyone else — so it
76
+ * sees unpublished rows too, and an address taken by work not yet shown is taken.
77
+ *
78
+ * It is named by the content type, not given it, so a form can be made with it
79
+ * before the content type that nests the form exists.
80
+ *
81
+ * Put it in the form's `checks` under the slug key:
82
+ * `checks: { slug: Cms.addressFree('posts') }`. The form must know which row it
83
+ * is editing for the row to keep its own address; `Cms.editor` tells it.
84
+ *
85
+ * This is advice, and deliberately not the rule. Two authors can both be told an
86
+ * address is free and both publish; the server refuses the second on the same
87
+ * key, through `Form.Message.Refused`. Asking earlier makes that rarer, never
88
+ * impossible.
89
+ */
90
+ const addressFree = (content) => {
91
+ const descriptor = Query.make(`${content}BySlug`, {
92
+ Input: { slug: Schema.String },
93
+ Result: Schema.Unknown
94
+ });
95
+ return (slug, context) => Remote.query(descriptor.ref({ slug })).pipe(Effect.map((result) => result.edges.some((edge) => edge.id !== context.subject.id) ? `"${slug}" is already used` : void 0), Effect.orElseSucceed(() => void 0));
96
+ };
97
+ //#endregion
98
+ //#region src/editor.ts
99
+ /**
100
+ * The authoring editor: a form, the entry it belongs to, and the draft that
101
+ * keeps what the author has entered.
102
+ *
103
+ * Saving is automatic and is not publishing. Each edit starts a rest, and the
104
+ * edit that is still the last one when its rest ends saves the form as it
105
+ * stands, valid or not. Publishing submits the form, so its rules and checks
106
+ * decide; what is published is the saved draft, so a publish saves first.
107
+ *
108
+ * The Bundle holds what is the editor's own: the form's Model and how far the
109
+ * saves have got. What the server holds is read from Remote, never copied: the
110
+ * draft's `updatedAt` a save is based on, and the entry's `revision` a publish is.
111
+ */
112
+ const isEdit = (message) => message._tag === "Nested" ? isEdit(message.message) : [
113
+ "Changed",
114
+ "RowAdded",
115
+ "RowRemoved",
116
+ "Reset"
117
+ ].includes(message._tag);
118
+ const held = (read) => read?._tag === "Ready" || read?._tag === "Refreshing" ? read.value : void 0;
119
+ /** Read, and not being read again: what the server said last, not what it said before. */
120
+ const fresh = (read) => read?._tag === "Ready" || read?._tag === "NotFound";
121
+ const Own = defineMessageUnion({
122
+ Rested: { edit: Schema.Number },
123
+ PublishAsked: {},
124
+ /** Lays what is in the form over the store, until `PreviewHidden`. Nothing is sent. */
125
+ PreviewShown: {},
126
+ PreviewHidden: {},
127
+ /** Publishes later: the form is submitted and saved now, and the server keeps the promise. */
128
+ ScheduleAsked: { at: Schema.String },
129
+ UnscheduleAsked: {},
130
+ ArchiveAsked: {},
131
+ UnarchiveAsked: {},
132
+ DiscardAsked: {},
133
+ /** Makes a revision's value the working copy. It replaces what is here, and publishes nothing. */
134
+ RestoreAsked: { revision: Schema.Number },
135
+ UnpublishAsked: {},
136
+ /** After a conflict: drop what is here and show the server's copy. */
137
+ ReloadAsked: {},
138
+ /** After a conflict: save what is here over the server's copy. */
139
+ OverwriteAsked: {}
140
+ });
141
+ /**
142
+ * A form's Submodel view as the view of the editor that wraps it, for
143
+ * `Bundle.withView`: the editor's Model holds the form's under `form`, and what
144
+ * the form's view sends is among the editor's Messages.
145
+ *
146
+ * ```ts
147
+ * Editor.bundle.pipe(Bundle.withView(Cms.editorView(FormView.submodel(form, view))))
148
+ * ```
149
+ */
150
+ const editorView = (view) => Submodel.defineView(((model, inputs, h) => view(model.form, inputs, h)));
151
+ const makeEditor = (cms) => (name, config) => {
152
+ const { content } = config;
153
+ const { form } = content;
154
+ const rest = config.rest ?? "1 second";
155
+ const formTag = `${form.name}@${config.version ?? "1"}`;
156
+ const closed = {
157
+ form: form.initial,
158
+ mode: "closed",
159
+ entry: null,
160
+ filled: false,
161
+ resumed: null,
162
+ edits: 0,
163
+ savedEdit: 0,
164
+ saveId: null,
165
+ saveWanted: false,
166
+ publishId: null,
167
+ publishWanted: false,
168
+ scheduleAt: null,
169
+ otherId: null,
170
+ previewing: false,
171
+ previewedAs: null,
172
+ settling: null
173
+ };
174
+ const Model = Schema.Struct({
175
+ form: form.bundle.Model,
176
+ mode: Schema.Literals([
177
+ "closed",
178
+ "new",
179
+ "edit"
180
+ ]),
181
+ entry: Schema.NullOr(Schema.String),
182
+ filled: Schema.Boolean,
183
+ resumed: Schema.NullOr(Schema.Literals([
184
+ "Model",
185
+ "Values",
186
+ "Published",
187
+ "Lost",
188
+ "Blank"
189
+ ])),
190
+ edits: Schema.Number,
191
+ savedEdit: Schema.Number,
192
+ saveId: Schema.NullOr(Schema.String),
193
+ saveWanted: Schema.Boolean,
194
+ publishId: Schema.NullOr(Schema.String),
195
+ publishWanted: Schema.Boolean,
196
+ scheduleAt: Schema.NullOr(Schema.String),
197
+ otherId: Schema.NullOr(Schema.String),
198
+ previewing: Schema.Boolean,
199
+ previewedAs: Schema.NullOr(Schema.String),
200
+ settling: Schema.NullOr(Schema.Literals(["reload", "overwrite"]))
201
+ });
202
+ const Message = Schema.Union([form.bundle.Message, Own]);
203
+ const own = /* @__PURE__ */ new Set([
204
+ "Rested",
205
+ "PublishAsked",
206
+ "PreviewShown",
207
+ "PreviewHidden",
208
+ "ScheduleAsked",
209
+ "UnscheduleAsked",
210
+ "ArchiveAsked",
211
+ "UnarchiveAsked",
212
+ "DiscardAsked",
213
+ "RestoreAsked",
214
+ "UnpublishAsked",
215
+ "ReloadAsked",
216
+ "OverwriteAsked"
217
+ ]);
218
+ const isOwn = (message) => own.has(message._tag);
219
+ const asks = {
220
+ DiscardAsked: { _tag: "Discard" },
221
+ UnpublishAsked: { _tag: "Unpublish" },
222
+ UnscheduleAsked: { _tag: "Unschedule" },
223
+ ArchiveAsked: { _tag: "Archive" },
224
+ UnarchiveAsked: { _tag: "Unarchive" },
225
+ ReloadAsked: { _tag: "Reload" },
226
+ OverwriteAsked: { _tag: "Overwrite" }
227
+ };
228
+ const viaForm = (model, message) => {
229
+ const next = form.bundle.update(model.form, message, void 0);
230
+ const edited = isEdit(message);
231
+ const edits = edited ? model.edits + 1 : model.edits;
232
+ const commands = [...next.commands ?? [], ...edited ? [{
233
+ name: `${name}.rest`,
234
+ args: { edit: edits },
235
+ effect: Effect.sleep(rest).pipe(Effect.as(Own.Rested({ edit: edits })))
236
+ }] : []];
237
+ const result = {
238
+ model: {
239
+ ...model,
240
+ form: next.model,
241
+ edits
242
+ },
243
+ commands
244
+ };
245
+ return next.outMessage === void 0 ? result : {
246
+ ...result,
247
+ outMessage: { _tag: "Publish" }
248
+ };
249
+ };
250
+ const bundle = Bundle.make(name, {
251
+ Model,
252
+ Message,
253
+ init: () => ({ model: closed }),
254
+ update: (model, message) => {
255
+ if (model.mode === "closed") return { model };
256
+ if (!isOwn(message)) return viaForm(message._tag === "Submitted" ? {
257
+ ...model,
258
+ scheduleAt: null
259
+ } : model, message);
260
+ switch (message._tag) {
261
+ case "Rested": return message.edit === model.edits && model.edits > model.savedEdit ? {
262
+ model,
263
+ outMessage: { _tag: "Save" }
264
+ } : { model };
265
+ case "PublishAsked": return viaForm({
266
+ ...model,
267
+ scheduleAt: null
268
+ }, form.Message.Submitted());
269
+ case "PreviewShown": return content.preview === void 0 ? { model } : { model: {
270
+ ...model,
271
+ previewing: true,
272
+ previewedAs: null
273
+ } };
274
+ case "PreviewHidden": return { model: {
275
+ ...model,
276
+ previewing: false
277
+ } };
278
+ case "RestoreAsked": return {
279
+ model,
280
+ outMessage: {
281
+ _tag: "Restore",
282
+ revision: message.revision
283
+ }
284
+ };
285
+ case "ScheduleAsked": return viaForm({
286
+ ...model,
287
+ scheduleAt: message.at
288
+ }, form.Message.Submitted());
289
+ default: return {
290
+ model,
291
+ outMessage: asks[message._tag]
292
+ };
293
+ }
294
+ },
295
+ helpers: {
296
+ /** Opens an entry: its draft is resumed, or what is published is shown. */
297
+ open: (_, entry) => ({ model: {
298
+ ...closed,
299
+ mode: "edit",
300
+ entry
301
+ } }),
302
+ /**
303
+ * Something new, under an id made where this is called (`Cms.newEntryId()`,
304
+ * in a Command or an event handler): the first save makes the entry.
305
+ */
306
+ create: (_, entry) => ({ model: {
307
+ ...closed,
308
+ mode: "new",
309
+ entry,
310
+ filled: true,
311
+ resumed: "Blank"
312
+ } }),
313
+ close: () => ({ model: closed })
314
+ }
315
+ });
316
+ const EntryRead = Entity.select(cms.Entities.Entry, {
317
+ type: true,
318
+ targetId: true,
319
+ revision: true,
320
+ archivedAt: true
321
+ });
322
+ const EntryState = Entity.select(cms.Entities.Entry, { state: true });
323
+ const DraftRead = Entity.select(cms.Entities.Draft, {
324
+ values: true,
325
+ model: true,
326
+ form: true,
327
+ updatedAt: true
328
+ });
329
+ const RowRead = Entity.selectFor(form.input);
330
+ const decodeModel = Schema.decodeUnknownOption(form.bundle.Model);
331
+ const encodeModel = Schema.encodeUnknownSync(form.bundle.Model);
332
+ /** The keys of some saved values the form still accepts. */
333
+ const fitting = (values) => {
334
+ if (typeof values !== "object" || values === null) return {};
335
+ const fields = form.input.schema.fields;
336
+ return Object.fromEntries(Object.entries(values).filter(([key, value]) => fields[key] !== void 0 && Schema.is(fields[key])(value)));
337
+ };
338
+ return {
339
+ bundle,
340
+ Message: Own,
341
+ /** What is saved as a draft's `form`: the form's name and the version given. */
342
+ formTag,
343
+ at: (where) => {
344
+ const { data, model: slice } = where;
345
+ const entryOf = (root) => {
346
+ const { mode, entry, saveId } = slice.get(root);
347
+ return entry === null || mode === "closed" || mode === "new" && saveId === null ? void 0 : entry;
348
+ };
349
+ const projections = {
350
+ entry: (root) => {
351
+ const entry = entryOf(root);
352
+ return entry === void 0 ? void 0 : data.get(EntryRead, entry);
353
+ },
354
+ state: (root) => {
355
+ const entry = entryOf(root);
356
+ return entry === void 0 ? void 0 : data.get(EntryState, entry);
357
+ },
358
+ draft: (root) => {
359
+ const entry = entryOf(root);
360
+ return entry === void 0 ? void 0 : data.get(DraftRead, entry);
361
+ },
362
+ row: (root) => {
363
+ const target = held(projections.entry(root)?.read(root))?.targetId;
364
+ return target == null ? void 0 : data.get(RowRead, target);
365
+ }
366
+ };
367
+ const read = (root, part) => projections[part](root)?.read(root);
368
+ const statusOf = (root, requestId) => requestId === null ? { _tag: "Unknown" } : data.mutation(root, requestId);
369
+ /** Shows what was loaded, once: the draft by the ladder, else what is published. */
370
+ const fill = (root) => {
371
+ const editor = slice.get(root);
372
+ if (editor.filled || editor.mode !== "edit") return root;
373
+ if (statusOf(root, editor.otherId)._tag === "Pending") return root;
374
+ const entry = read(root, "entry");
375
+ const draft = read(root, "draft");
376
+ const arrived = editor.settling === "reload" ? fresh : (r) => held(r) !== void 0 || r?._tag === "NotFound";
377
+ if (!arrived(entry) || !arrived(draft)) return root;
378
+ const entryValue = held(entry);
379
+ if (entryValue === void 0) return root;
380
+ const shown = (resumed, next) => slice.set(root, {
381
+ ...closed,
382
+ mode: "edit",
383
+ entry: editor.entry,
384
+ form: next,
385
+ filled: true,
386
+ resumed,
387
+ otherId: editor.otherId
388
+ });
389
+ const saved = held(draft);
390
+ if (saved !== void 0) {
391
+ const model = saved.form === formTag ? decodeModel(saved.model) : Option.none();
392
+ if (Option.isSome(model)) return shown("Model", form.settled(model.value));
393
+ const values = fitting(saved.values);
394
+ if (Object.keys(values).length > 0) return shown("Values", form.fill(form.initial, values).model);
395
+ }
396
+ const lost = saved === void 0 ? "Published" : "Lost";
397
+ if (entryValue.targetId === null) return shown(saved === void 0 ? "Blank" : "Lost", form.initial);
398
+ const row = read(root, "row");
399
+ if (!arrived(row)) return root;
400
+ const rowValue = held(row);
401
+ return rowValue === void 0 ? shown(lost, form.initial) : shown(lost, form.fill(form.initial, Entity.valuesFor(form.input, rowValue)).model);
402
+ };
403
+ const startSave = (root) => {
404
+ const editor = slice.get(root);
405
+ const values = form.partial(editor.form);
406
+ const labelKey = content.roles.label?.key;
407
+ const typed = labelKey === void 0 ? "" : form.field(editor.form, labelKey).value;
408
+ const label = typeof typed === "string" ? typed.trim() : "";
409
+ const basedOn = held(read(root, "draft"))?.updatedAt ?? null;
410
+ const started = data.mutate(root, cms.Operations.SaveDraft, {
411
+ entry: editor.entry,
412
+ type: content.name,
413
+ label: label === "" ? config.untitled ?? "Untitled" : label,
414
+ values,
415
+ model: encodeModel(editor.form),
416
+ form: formTag,
417
+ basedOn
418
+ });
419
+ return {
420
+ model: slice.set(started.model, {
421
+ ...slice.get(started.model),
422
+ saveId: started.requestId,
423
+ publishId: null,
424
+ otherId: null,
425
+ savedEdit: editor.edits,
426
+ saveWanted: false,
427
+ settling: null
428
+ }),
429
+ commands: [started.command]
430
+ };
431
+ };
432
+ /** An operation that names the entry and nothing else. The server's patches say what it did. */
433
+ const simple = (operation) => (root) => {
434
+ const editor = slice.get(root);
435
+ if (editor.entry === null) return { model: root };
436
+ const started = data.mutate(root, cms.Operations[operation], { entry: editor.entry });
437
+ return {
438
+ model: slice.set(started.model, {
439
+ ...slice.get(started.model),
440
+ otherId: started.requestId
441
+ }),
442
+ commands: [started.command]
443
+ };
444
+ };
445
+ /**
446
+ * A discarded draft takes what is on screen with it, the edits still resting
447
+ * included. What is published is shown again once the discard has settled;
448
+ * something never published has nothing left, and the editor closes.
449
+ */
450
+ const discard = (root) => {
451
+ const editor = slice.get(root);
452
+ if (editor.entry === null) return { model: root };
453
+ if (editor.mode === "new" && editor.saveId === null) return { model: slice.set(root, closed) };
454
+ const unpublished = held(read(root, "entry"))?.targetId == null;
455
+ const started = data.mutate(root, cms.Operations.DiscardDraft, { entry: editor.entry });
456
+ return {
457
+ model: slice.set(started.model, unpublished ? closed : {
458
+ ...closed,
459
+ mode: "edit",
460
+ entry: editor.entry,
461
+ otherId: started.requestId,
462
+ settling: "reload"
463
+ }),
464
+ commands: [started.command]
465
+ };
466
+ };
467
+ /** The form is emptied, and filled from the restored draft once the restore has settled. */
468
+ const restore = (revision) => (root) => {
469
+ const editor = slice.get(root);
470
+ if (editor.entry === null) return { model: root };
471
+ const started = data.mutate(root, cms.Operations.Restore, {
472
+ entry: editor.entry,
473
+ revision
474
+ });
475
+ return {
476
+ model: slice.set(started.model, {
477
+ ...closed,
478
+ mode: "edit",
479
+ entry: editor.entry,
480
+ otherId: started.requestId,
481
+ settling: "reload"
482
+ }),
483
+ commands: [started.command]
484
+ };
485
+ };
486
+ /**
487
+ * What follows from what has arrived: the loaded value is shown, a save
488
+ * that waited its turn starts, and a publish goes once its draft is saved.
489
+ */
490
+ const overlayId = `${name}.preview`;
491
+ /**
492
+ * What is in the form, over the store, while preview is on: made again when
493
+ * the form has moved on, and lifted the moment it is off, however that came
494
+ * about (a close, a discard, a reload).
495
+ */
496
+ const previewed = (root) => {
497
+ const editor = slice.get(root);
498
+ if (!editor.previewing || content.preview === void 0 || editor.entry === null) return data.lift(root, overlayId);
499
+ const id = held(read(root, "entry"))?.targetId ?? editor.entry;
500
+ const as = `${editor.edits}:${id}`;
501
+ if (editor.previewedAs === as) return root;
502
+ const shown = data.overlay(root, overlayId, content.preview(form.partial(editor.form), id));
503
+ return slice.set(shown, {
504
+ ...slice.get(shown),
505
+ previewedAs: as
506
+ });
507
+ };
508
+ /**
509
+ * A server's word about one key, on that key. A publish refused for a taken
510
+ * address is about the address, and belongs beside it rather than in a
511
+ * status line. Saying it again while it already stands would be noise.
512
+ */
513
+ const refused = (root) => {
514
+ const editor = slice.get(root);
515
+ const failure = statusOf(root, editor.publishId);
516
+ if (failure._tag !== "Failed") return root;
517
+ const key = slugTaken.key(failure.error.message);
518
+ if (key === void 0 || content.roles.slug?.key !== key) return root;
519
+ const reason = slugTaken.reason(failure.error.message);
520
+ const field = form.field(editor.form, key);
521
+ if (field._tag === "Invalid" && (field.errors ?? []).includes(reason)) return root;
522
+ return slice.set(root, {
523
+ ...editor,
524
+ form: form.bundle.update(editor.form, form.Message.Refused({
525
+ key,
526
+ error: reason
527
+ }), void 0).model
528
+ });
529
+ };
530
+ /**
531
+ * Tells the form which row it is editing, so a check that asks the server
532
+ * about a key can pass over what this row already holds: an address is not
533
+ * taken by the post that owns it. A form that creates something is about
534
+ * nothing, which is the subject it starts with.
535
+ */
536
+ const about = (root) => {
537
+ const editor = slice.get(root);
538
+ const target = held(read(root, "entry"))?.targetId;
539
+ const subject = target === null || target === void 0 ? {} : { id: target };
540
+ if (form.subject(editor.form).id === subject.id) return root;
541
+ return slice.set(root, {
542
+ ...editor,
543
+ form: form.bundle.update(editor.form, form.Message.About({ subject }), void 0).model
544
+ });
545
+ };
546
+ const sync = (given) => {
547
+ let root = refused(previewed(about(fill(given))));
548
+ const commands = [];
549
+ const run = (step) => {
550
+ const next = step(root);
551
+ root = next.model;
552
+ commands.push(...next.commands ?? []);
553
+ };
554
+ const editor = () => slice.get(root);
555
+ if (editor().mode === "closed" || !editor().filled) return { model: root };
556
+ const saving = () => statusOf(root, editor().saveId)._tag === "Pending";
557
+ if (editor().settling === "overwrite" && fresh(read(root, "draft"))) run(startSave);
558
+ if (editor().saveWanted && !saving() && editor().settling === null) run(startSave);
559
+ if (editor().publishWanted && statusOf(root, editor().publishId)._tag === "Pending") root = slice.set(root, {
560
+ ...editor(),
561
+ publishWanted: false
562
+ });
563
+ if (editor().publishWanted && !saving() && editor().settling === null) {
564
+ const save = statusOf(root, editor().saveId);
565
+ const resumedDraft = editor().resumed === "Model" || editor().resumed === "Values";
566
+ const saved = editor().edits === editor().savedEdit && (editor().saveId === null ? resumedDraft : save._tag === "Applied");
567
+ if (save._tag === "Failed" && editor().edits === editor().savedEdit) root = slice.set(root, {
568
+ ...editor(),
569
+ publishWanted: false
570
+ });
571
+ else if (!saved) run(startSave);
572
+ else {
573
+ const basedOn = held(read(root, "entry"))?.revision ?? null;
574
+ const at = editor().scheduleAt;
575
+ const started = at === null ? data.mutate(root, cms.Operations.Publish, {
576
+ entry: editor().entry,
577
+ basedOn
578
+ }) : data.mutate(root, cms.Operations.Schedule, {
579
+ entry: editor().entry,
580
+ at
581
+ });
582
+ root = slice.set(started.model, {
583
+ ...slice.get(started.model),
584
+ publishId: started.requestId,
585
+ publishWanted: false
586
+ });
587
+ commands.push(started.command);
588
+ }
589
+ }
590
+ return {
591
+ model: root,
592
+ commands
593
+ };
594
+ };
595
+ const failure = (root) => {
596
+ const editor = slice.get(root);
597
+ for (const id of [
598
+ editor.publishId,
599
+ editor.saveId,
600
+ editor.otherId
601
+ ]) {
602
+ const status = statusOf(root, id);
603
+ if (status._tag === "Failed") return status.error;
604
+ }
605
+ };
606
+ const active = (part) => ({
607
+ name: `${name}.${part}`,
608
+ owner: data.contract.owner ?? {},
609
+ projectionOf: projections[part]
610
+ });
611
+ return {
612
+ /** For the placement: what the editor asked becomes the mutation, or waits its turn. */
613
+ onOut: (out) => (root) => {
614
+ const editor = slice.get(root);
615
+ switch (out._tag) {
616
+ case "Save": return sync(slice.set(root, {
617
+ ...editor,
618
+ saveWanted: true
619
+ }));
620
+ case "Publish": return sync(slice.set(root, {
621
+ ...editor,
622
+ publishWanted: true
623
+ }));
624
+ case "Restore": return restore(out.revision)(root);
625
+ case "Discard": return discard(root);
626
+ case "Unpublish": return simple("Unpublish")(root);
627
+ case "Unschedule": return simple("Unschedule")(root);
628
+ case "Archive": return simple("Archive")(root);
629
+ case "Unarchive": return simple("Unarchive")(root);
630
+ case "Reload": {
631
+ const refreshed = [
632
+ "entry",
633
+ "draft",
634
+ "row"
635
+ ].reduce((next, part) => {
636
+ const projection = projections[part](next);
637
+ return projection === void 0 ? next : data.refresh(next, projection);
638
+ }, root);
639
+ return { model: slice.set(refreshed, {
640
+ ...closed,
641
+ mode: "edit",
642
+ entry: editor.entry,
643
+ settling: "reload"
644
+ }) };
645
+ }
646
+ case "Overwrite": {
647
+ const projection = projections.draft(root);
648
+ const refreshed = projection === void 0 ? root : data.refresh(root, projection);
649
+ return { model: slice.set(refreshed, {
650
+ ...slice.get(refreshed),
651
+ settling: "overwrite"
652
+ }) };
653
+ }
654
+ }
655
+ },
656
+ /**
657
+ * For `Data.subscriptions`, spread beside the application's own: the entry,
658
+ * its state, its draft, and the row what is published is shown from. Each
659
+ * is a requirement while an entry is open, so Remote fetches and retains it.
660
+ */
661
+ actives: {
662
+ [`${name}.entry`]: active("entry"),
663
+ [`${name}.state`]: active("state"),
664
+ [`${name}.draft`]: active("draft"),
665
+ [`${name}.row`]: active("row")
666
+ },
667
+ sync,
668
+ /**
669
+ * Saves what has not been saved, now, without waiting for the rest to end.
670
+ * Run it before `close` or `open`, which drop what is in the form: an
671
+ * author who types and leaves within the rest would otherwise lose it.
672
+ */
673
+ flush: ((root) => {
674
+ const editor = slice.get(root);
675
+ return editor.mode === "closed" || !editor.filled || editor.edits === editor.savedEdit ? { model: root } : sync(slice.set(root, {
676
+ ...editor,
677
+ saveWanted: true
678
+ }));
679
+ }),
680
+ /**
681
+ * Wraps the application's `update` so `sync` runs after every Message: a
682
+ * value may arrive, or a save settle, with any of them.
683
+ */
684
+ after: (update) => (model, message) => {
685
+ const next = update(model, message);
686
+ const synced = sync(next.model);
687
+ return {
688
+ ...next,
689
+ model: synced.model,
690
+ commands: [...next.commands ?? [], ...synced.commands ?? []]
691
+ };
692
+ },
693
+ /** Whether this content type can be previewed, and whether it is being. */
694
+ canPreview: content.preview !== void 0,
695
+ previewing: (root) => slice.get(root).previewing,
696
+ /**
697
+ * The id the application's own pages know this content by: the row's, or
698
+ * the entry's while there is no row. It is what a preview is shown under.
699
+ */
700
+ pageId: (root) => held(read(root, "entry"))?.targetId ?? slice.get(root).entry,
701
+ /** The entry being edited; `null` while closed. */
702
+ entry: (root) => slice.get(root).entry,
703
+ /** How the form came to hold what it holds; `Lost` is worth telling the author. */
704
+ resumed: (root) => slice.get(root).resumed,
705
+ /** The entry's lifecycle state, as the server last derived it. */
706
+ state: (root) => held(read(root, "state"))?.state,
707
+ /** Why the last publish, save, discard or unpublish failed. */
708
+ error: failure,
709
+ status: (root) => {
710
+ const editor = slice.get(root);
711
+ if (editor.mode === "closed") return "Closed";
712
+ if (!editor.filled) {
713
+ const entry = read(root, "entry");
714
+ if (entry?._tag === "NotFound") return "NotFound";
715
+ return [
716
+ entry,
717
+ read(root, "draft"),
718
+ read(root, "row")
719
+ ].some((part) => part?._tag === "Failed") ? "LoadFailed" : "Loading";
720
+ }
721
+ const publish = statusOf(root, editor.publishId);
722
+ const save = statusOf(root, editor.saveId);
723
+ const later = editor.scheduleAt !== null;
724
+ if (publish._tag === "Pending") return later ? "Scheduling" : "Publishing";
725
+ if (save._tag === "Pending" || editor.settling === "overwrite") return "Saving";
726
+ const conflicted = (status) => status._tag === "Failed" && status.error.message.includes("CmsConflict");
727
+ if (editor.edits > editor.savedEdit) return "Editing";
728
+ if (conflicted(save) || conflicted(publish)) return "Conflict";
729
+ if (save._tag === "Failed") return "SaveFailed";
730
+ if (publish._tag === "Failed") return later ? "ScheduleFailed" : "PublishFailed";
731
+ if (publish._tag === "Applied") return later ? "Scheduled" : "Published";
732
+ if (save._tag === "Applied") return "Saved";
733
+ return editor.resumed === "Model" || editor.resumed === "Values" ? "Saved" : "Opened";
734
+ }
735
+ };
736
+ }
737
+ };
738
+ };
739
+ //#endregion
740
+ //#region src/kinds.ts
741
+ /**
742
+ * The kinds a CMS adds: two controls and two displays, made with `Input.kind`
743
+ * and `Display.kind` exactly as an application makes its own, and a renderer for
744
+ * each to spread beside `foldkit-mixins-form`'s and `foldkit-mixins-crud`'s.
745
+ * There is no CMS view package: a kind and its renderer are all a view needs.
746
+ */
747
+ /** Text as an address: lower case, unaccented, words joined by `-`. */
748
+ const slugify = (text) => text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
749
+ /** A slug: text, shown after the address it completes. */
750
+ const Slug = Input.kind("CmsSlug", { draft: "text" });
751
+ /** A moment: the text of a `datetime-local` input, submitted as an ISO string. */
752
+ const DateTime = Input.kind("CmsDateTime", {
753
+ draft: "text",
754
+ parse: (draft) => {
755
+ const at = new Date(draft);
756
+ return Number.isNaN(at.getTime()) ? void 0 : at.toISOString();
757
+ },
758
+ unparsed: "Enter a date and a time"
759
+ });
760
+ const stateWords = {
761
+ New: "New",
762
+ Published: "Published",
763
+ Changed: "Changed",
764
+ Unpublished: "Unpublished",
765
+ Archived: "Archived",
766
+ scheduled: "scheduled",
767
+ overdue: "overdue"
768
+ };
769
+ const isState = (value) => typeof value === "object" && value !== null && "_tag" in value && "schedule" in value;
770
+ /** What a state's schedule adds to it: nothing, `scheduled`, or `overdue`. */
771
+ const scheduleOf = (state) => state.schedule === null ? void 0 : state.schedule.overdue ? "overdue" : "scheduled";
772
+ /** An entry's lifecycle state, as words. A publish that did not happen says so. */
773
+ const StateDisplay = Display.kind("CmsState", { text: (data, value) => {
774
+ if (!isState(value)) return String(value);
775
+ const words = {
776
+ ...stateWords,
777
+ ...data.words
778
+ };
779
+ const schedule = scheduleOf(value);
780
+ return schedule === void 0 ? words[value._tag] : `${words[value._tag]}, ${words[schedule]}`;
781
+ } });
782
+ const units = [
783
+ ["year", 31536e6],
784
+ ["month", 2592e6],
785
+ ["day", 864e5],
786
+ ["hour", 36e5],
787
+ ["minute", 6e4]
788
+ ];
789
+ /**
790
+ * A time. Given a clock it reads relative to it ("3 days ago"), and the view
791
+ * decides how often that clock moves; given none it is the date and the time.
792
+ */
793
+ const Moment = Display.kind("CmsMoment", { text: (data, value) => {
794
+ const at = new Date(String(value));
795
+ if (Number.isNaN(at.getTime())) return String(value);
796
+ if (data.now === void 0) return new Intl.DateTimeFormat(data.locale ?? "en", {
797
+ dateStyle: "medium",
798
+ timeStyle: "short",
799
+ timeZone: "UTC"
800
+ }).format(at);
801
+ const delta = at.getTime() - data.now().getTime();
802
+ const relative = new Intl.RelativeTimeFormat(data.locale ?? "en", { numeric: "auto" });
803
+ const unit = units.find(([, size]) => Math.abs(delta) >= size);
804
+ return unit === void 0 ? relative.format(0, "minute") : relative.format(Math.trunc(delta / unit[1]), unit[0]);
805
+ } });
806
+ /** An ISO moment as a `datetime-local` input writes one, in the viewer's zone; other text as it is. */
807
+ const localText = (draft) => {
808
+ const at = new Date(draft);
809
+ if (!/Z$|[+-]\d\d:\d\d$/.test(draft) || Number.isNaN(at.getTime())) return draft;
810
+ return (/* @__PURE__ */ new Date(at.getTime() - at.getTimezoneOffset() * 6e4)).toISOString().slice(0, 16);
811
+ };
812
+ const Kinds = {
813
+ /** The control kinds: `Cms.Input.Slug.is(control)` narrows one, as `Input.Text.is` does. */
814
+ Input: {
815
+ Slug,
816
+ DateTime
817
+ },
818
+ /** The display kinds. */
819
+ Display: {
820
+ State: StateDisplay,
821
+ Moment
822
+ },
823
+ slugify,
824
+ /**
825
+ * Under a form's `inputs`: the key is a slug that follows `from` until the
826
+ * author writes it, and is shown after `prefix`. A form filled with a published
827
+ * slug does not follow: an address must not move because its title did.
828
+ */
829
+ slug: (from, options = {}) => ({ change: (resolved, inputKey) => {
830
+ const following = Input.following(from, options.through ?? slugify).change(resolved, inputKey);
831
+ return Object.freeze({
832
+ ...Slug.of({ prefix: options.prefix ?? "/" }),
833
+ follows: following.follows
834
+ });
835
+ } }),
836
+ /** Under a form's `inputs`, or as Entity metadata with `Input.of`: a moment. */
837
+ dateTime: () => DateTime.of({}),
838
+ /** For `FormView`'s `renderers`, beside its own. */
839
+ controlRenderers: () => ({
840
+ [Slug.kind]: ({ control, state, draft, change, blurred, slots, h }) => h.span([], [h.span([h.DataAttribute("cms-slug-prefix", "")], [Slug.is(control) ? control.data.prefix : ""]), h.input(slots.text.attrs([
841
+ ...state,
842
+ h.Type("text"),
843
+ h.Value(String(draft)),
844
+ h.OnInput(change),
845
+ h.OnBlur(blurred)
846
+ ]))]),
847
+ [DateTime.kind]: ({ state, draft, change, blurred, slots, h }) => h.input(slots.text.attrs([
848
+ ...state,
849
+ h.Type("datetime-local"),
850
+ h.Value(localText(String(draft))),
851
+ h.OnInput(change),
852
+ h.OnBlur(blurred)
853
+ ]))
854
+ }),
855
+ /** For `ListView`'s and `DetailView`'s `renderers`: a state as a badge, a moment as a `time`. */
856
+ displayRenderers: () => ({
857
+ [StateDisplay.kind]: ({ display, value, words, h }) => h.span(isState(value) ? [h.DataAttribute("cms-state", value._tag), ...scheduleOf(value) === void 0 ? [] : [h.DataAttribute("cms-schedule", scheduleOf(value))]] : [], [display.text(value, words)]),
858
+ [Moment.kind]: ({ display, value, words, h }) => h.time([h.Attribute("datetime", String(value))], [display.text(value, words)])
859
+ })
860
+ };
861
+ //#endregion
862
+ //#region src/index.ts
863
+ /**
864
+ * `foldkit-cms` — what a CMS adds to a domain that is already declared: audience
865
+ * (who may see it), time (drafts, revisions, a schedule), and address (a slug).
866
+ *
867
+ * A draft is an unsent form, kept beside the content row and never in it. The
868
+ * row holds what is published; publishing is the application's own mutation,
869
+ * run with the draft's value. This package is the declarations and the pure
870
+ * rules. It reads no database and owns no state; `foldkit-cms-drizzle` is the
871
+ * server, and the screens are `foldkit-crud`'s.
872
+ */
873
+ const rolesKey = Metadata.key("foldkit-cms/roles", {
874
+ merge: (roles) => [Object.assign({}, ...roles)],
875
+ summarize: (roles) => Object.keys(roles).join(",")
876
+ });
877
+ const isText = (ast) => ast._tag === "String" || ast._tag === "TemplateLiteral" || ast._tag === "Literal" && typeof ast.literal === "string" || ast._tag === "Union" && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText);
878
+ const fail = (message) => {
879
+ throw new Error(`foldkit-cms: ${message}`);
880
+ };
881
+ /** An entry's id. Branded, so an entry is not opened with a post's id. */
882
+ const EntryId = Schema.String.pipe(Schema.brand("CmsEntryId"));
883
+ const StateSchema = Schema.Struct({
884
+ _tag: Schema.Literals([
885
+ "New",
886
+ "Published",
887
+ "Changed",
888
+ "Unpublished",
889
+ "Archived"
890
+ ]),
891
+ schedule: Schema.NullOr(Schema.Struct({
892
+ at: Schema.String,
893
+ overdue: Schema.Boolean,
894
+ error: Schema.NullOr(Schema.String)
895
+ }))
896
+ }).annotate({ title: "State" });
897
+ const Entry = Entity.define("CmsEntry", Schema.Struct({
898
+ id: EntryId,
899
+ /** The content type's name: `Cms.content('posts', ...)`. */
900
+ type: Schema.String,
901
+ /** The content row's id, once there is one. */
902
+ targetId: Schema.NullOr(Schema.String),
903
+ label: Schema.String.annotate({ title: "Title" }),
904
+ createdAt: Schema.String,
905
+ archivedAt: Schema.NullOr(Schema.String),
906
+ /** The number of the latest published revision: what the next publish is based on. */
907
+ revision: Schema.NullOr(Schema.Number)
908
+ })).pipe(Entity.derived({ state: Derived.make(StateSchema) }), Entity.annotateMembers({
909
+ id: Display.of(Display.hidden()),
910
+ state: Display.of(Kinds.Display.State.of({})),
911
+ createdAt: Display.of(Kinds.Display.Moment.of({})),
912
+ archivedAt: Display.of(Kinds.Display.Moment.of({}))
913
+ }));
914
+ const Draft$1 = Entity.define("CmsDraft", Schema.Struct({
915
+ /** The entry's id: an entry has at most one draft. */
916
+ id: EntryId,
917
+ /** The keys of the form's value that decode, as the operation's input encodes them. */
918
+ values: Schema.Unknown,
919
+ /** The form's whole Model, encoded: what resumes unfinished work. */
920
+ model: Schema.Unknown,
921
+ /** Which form made it, and at which version, so a Model is only resumed by the form that wrote it. */
922
+ form: Schema.String,
923
+ updatedAt: Schema.String,
924
+ updatedBy: Schema.NullOr(Schema.String),
925
+ /** The revision this draft was started from; publishing over a newer one is a conflict. */
926
+ baseRevision: Schema.NullOr(Schema.Number),
927
+ scheduledFor: Schema.NullOr(Schema.String),
928
+ scheduleError: Schema.NullOr(Schema.String)
929
+ }));
930
+ const Revision = Entity.define("CmsRevision", Schema.Struct({
931
+ id: Schema.String,
932
+ n: Schema.Number.annotate({ title: "Revision" }),
933
+ values: Schema.Unknown,
934
+ publishedAt: Schema.String.annotate({ title: "Published" }),
935
+ publishedBy: Schema.NullOr(Schema.String)
936
+ })).pipe(Entity.annotateMembers({ publishedAt: Display.of(Kinds.Display.Moment.of({})) }));
937
+ const Entities = Entity.relate({
938
+ Entry,
939
+ Draft: Draft$1,
940
+ Revision
941
+ }, { Entry: {
942
+ draft: Relation.one(Draft$1, { optional: true }),
943
+ revisions: Relation.many(Revision)
944
+ } });
945
+ const entryInput = { entry: EntryId };
946
+ /**
947
+ * What an author may ask, as Remote mutations. They are the same for every
948
+ * content type; the entry says which type it is. The server runs each after
949
+ * asking the application's `allow`.
950
+ */
951
+ const Operations = {
952
+ /**
953
+ * Saves the working copy, valid or not. The first save of an id nobody has
954
+ * makes the entry, so a client names something new itself (`Cms.newEntryId`) and
955
+ * need not wait to be told what it is called. `basedOn` is the `updatedAt` this
956
+ * save was made from: a newer one on the server is a conflict, not an overwrite.
957
+ */
958
+ SaveDraft: Mutation.make("CmsSaveDraft", {
959
+ Input: {
960
+ entry: EntryId,
961
+ type: Schema.String,
962
+ label: Schema.String,
963
+ values: Schema.Unknown,
964
+ model: Schema.Unknown,
965
+ form: Schema.String,
966
+ basedOn: Schema.NullOr(Schema.String)
967
+ },
968
+ Output: {
969
+ entry: EntryId,
970
+ updatedAt: Schema.String
971
+ }
972
+ }),
973
+ DiscardDraft: Mutation.make("CmsDiscardDraft", {
974
+ Input: entryInput,
975
+ Output: {}
976
+ }),
977
+ /**
978
+ * Publishes the saved draft through the content type's own mutation. `basedOn`
979
+ * is the revision the draft was started from.
980
+ */
981
+ Publish: Mutation.make("CmsPublish", {
982
+ Input: {
983
+ entry: EntryId,
984
+ basedOn: Schema.NullOr(Schema.Number)
985
+ },
986
+ Output: {
987
+ entry: EntryId,
988
+ targetId: Schema.String,
989
+ revision: Schema.Number
990
+ }
991
+ }),
992
+ Unpublish: Mutation.make("CmsUnpublish", {
993
+ Input: entryInput,
994
+ Output: {}
995
+ }),
996
+ Schedule: Mutation.make("CmsSchedule", {
997
+ Input: {
998
+ entry: EntryId,
999
+ at: Schema.String
1000
+ },
1001
+ Output: {}
1002
+ }),
1003
+ Unschedule: Mutation.make("CmsUnschedule", {
1004
+ Input: entryInput,
1005
+ Output: {}
1006
+ }),
1007
+ Archive: Mutation.make("CmsArchive", {
1008
+ Input: entryInput,
1009
+ Output: {}
1010
+ }),
1011
+ Unarchive: Mutation.make("CmsUnarchive", {
1012
+ Input: entryInput,
1013
+ Output: {}
1014
+ }),
1015
+ /** Makes a revision's value the working copy. It publishes nothing. */
1016
+ Restore: Mutation.make("CmsRestore", {
1017
+ Input: {
1018
+ entry: EntryId,
1019
+ revision: Schema.Number
1020
+ },
1021
+ Output: { updatedAt: Schema.String }
1022
+ })
1023
+ };
1024
+ /**
1025
+ * What an author works on: the entries of one content type, searched by what
1026
+ * they are called. `archived` chooses the put-away ones or the rest. It lists
1027
+ * entries, not content rows, so something never published is here too.
1028
+ */
1029
+ /**
1030
+ * The worklist: a content type's entries, archived or not, narrowed by a
1031
+ * search. Declared by what it means, so the server compiles it rather than
1032
+ * being told the same three questions again in SQL.
1033
+ *
1034
+ * Both of the conditions an author changes are asked without a branch, because
1035
+ * a body is built once and its inputs are placeholders. "Archived or not" is
1036
+ * *is-archived equals what you asked for*; "search or everything" is *the label
1037
+ * contains what you asked for*, and containing the empty string is everything.
1038
+ * `label` is not nullable, which is what makes the second of those exactly no
1039
+ * filter when the box is empty.
1040
+ */
1041
+ const Entries = Query.define("CmsEntries", {
1042
+ type: Schema.String,
1043
+ search: Schema.String,
1044
+ archived: Schema.Boolean
1045
+ }, ({ input }) => Query.from(Entities.Entry).pipe(Query.where(Expr.eq(Entities.Entry.fields.type, input.type), Expr.eq(Expr.isNotNull(Entities.Entry.fields.archivedAt), input.archived), Expr.contains(Entities.Entry.fields.label, input.search)), Query.orderBy(Order.desc(Entities.Entry.fields.createdAt))));
1046
+ const editor = makeEditor({
1047
+ Entities,
1048
+ Operations
1049
+ });
1050
+ const Cms = {
1051
+ /**
1052
+ * A pipe step naming the members of an Entity that play a CMS part. It is
1053
+ * metadata: the Entity is the same Entity, and anything may read it with
1054
+ * `Cms.rolesOf`. A member that cannot play the part is refused here.
1055
+ */
1056
+ roles: (roles) => (entity) => {
1057
+ const given = roles;
1058
+ const fields = entity.fields;
1059
+ for (const [role, key] of Object.entries(given)) {
1060
+ if (key === void 0) continue;
1061
+ const field = fields[key] ?? fail(`"${key}" is not a field of ${entity.name}, so it cannot be its ${role}`);
1062
+ const type = Schema.toType(field.schema);
1063
+ if (role === "published") {
1064
+ if (!Schema.is(type)(null)) fail(`"${key}" of ${entity.name} admits no null, so it cannot say a row is unpublished`);
1065
+ } else if (!isText(type.ast)) fail(`"${key}" of ${entity.name} is not text, so it cannot be its ${role}`);
1066
+ }
1067
+ const named = Object.fromEntries(Object.entries(given).filter((entry) => entry[1] !== void 0));
1068
+ return entity.pipe(Entity.annotate(rolesKey.of(named)));
1069
+ },
1070
+ /** The roles an Entity was given, as its Fields. A part nobody named is `undefined`. */
1071
+ rolesOf: (entity) => {
1072
+ const [named = {}] = rolesKey.get(entity.metadata);
1073
+ const fields = entity.fields;
1074
+ const field = (role) => named[role] === void 0 ? void 0 : fields[named[role]];
1075
+ return {
1076
+ label: field("label"),
1077
+ slug: field("slug"),
1078
+ published: field("published")
1079
+ };
1080
+ },
1081
+ /**
1082
+ * A type of content: the Entity it is, the form that edits it, the operations
1083
+ * that publish it, and what it is called. The form is an ordinary form; the
1084
+ * operations are the application's own. It adds no fields and generates nothing.
1085
+ */
1086
+ content: (name, config) => {
1087
+ if (!Entity.same(config.form.input.entity, config.entity)) fail(`content "${name}" is of ${config.entity.name}, but its form edits ${config.form.input.entity.name}`);
1088
+ return Object.freeze({
1089
+ name,
1090
+ ...config,
1091
+ roles: Cms.rolesOf(config.entity)
1092
+ });
1093
+ },
1094
+ /** An id for something new, made where it is written: the first save of it makes the entry. */
1095
+ newEntryId: () => globalThis.crypto.randomUUID(),
1096
+ /** `Entry`, `Draft` and `Revision`: register them with Remote beside the application's own. */
1097
+ Entities,
1098
+ /** The operations, to register with Remote's `mutations`. */
1099
+ Operations,
1100
+ operations: Object.values(Operations),
1101
+ /** The worklist query, to register with Remote's `queries` and list with `Crud.list`. */
1102
+ Entries,
1103
+ /**
1104
+ * The query that finds a piece of content by its address: `<name>BySlug`, a
1105
+ * connection of one or none. It throws for a content type with no `slug` role:
1106
+ * a capability is declared, never implied.
1107
+ */
1108
+ bySlug: (content) => {
1109
+ const address = content.roles.slug;
1110
+ if (address === void 0) return fail(`content "${content.name}" has no slug role, so nothing is found by slug`);
1111
+ const entity = content.entity;
1112
+ return Query.define(`${content.name}BySlug`, { slug: Schema.String }, ({ input }) => Query.from(entity).pipe(Query.where(Expr.eq(address, input.slug)), Query.orderBy(Order.asc(entity.fields.id))));
1113
+ },
1114
+ /**
1115
+ * How a server says a slug is taken, as a mutation's error: `CmsSlugTaken: <key>: ...`.
1116
+ * `slugTaken.key(message)` is the form key it names, or `undefined` for another error.
1117
+ */
1118
+ slugTaken,
1119
+ /**
1120
+ * A form check that asks, while the author types, whether an address is already
1121
+ * used: `checks: { slug: Cms.addressFree('posts') }`. Named by the content type,
1122
+ * so a form can be made with it before the content type exists. It needs that
1123
+ * type's `bySlug` query registered, which `CmsServer` does for a content type
1124
+ * with a slug role.
1125
+ */
1126
+ addressFree,
1127
+ /**
1128
+ * The kinds a CMS adds, and a renderer for each: `Cms.slug('title')` and
1129
+ * `Cms.dateTime()` for a form's `inputs`; `Cms.Display.State` and
1130
+ * `Cms.Display.Moment` for a list's columns; `Cms.controlRenderers()` and `Cms.displayRenderers()` to spread
1131
+ * beside the mixins' own.
1132
+ */
1133
+ ...Kinds,
1134
+ /**
1135
+ * The authoring editor of a content type: its form, the entry, and the draft
1136
+ * that keeps what the author has entered. Saving is automatic and is not
1137
+ * publishing; publishing submits the form.
1138
+ */
1139
+ editor,
1140
+ /** A form's Submodel view as its editor's, for `Bundle.withView`. */
1141
+ editorView,
1142
+ /** The state of an entry, from what is known of it and a clock. */
1143
+ state: (facts, now) => state(facts, now),
1144
+ /** The transitions an entry offers now, before anyone asks who is asking. */
1145
+ offers: (facts, now, content) => offers(facts, now, { unpublishes: content.roles.published !== void 0 })
1146
+ };
1147
+ //#endregion
1148
+ export { Cms, EntryId };
1149
+
1150
+ //# sourceMappingURL=index.mjs.map