@thomasfosterau/pulpit 0.0.0-stage → 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.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1272 -2
  3. package/dist/blobs.d.ts +249 -0
  4. package/dist/blobs.d.ts.map +1 -0
  5. package/dist/blobs.js +193 -0
  6. package/dist/blobs.js.map +1 -0
  7. package/dist/budgets.d.ts +255 -0
  8. package/dist/budgets.d.ts.map +1 -0
  9. package/dist/budgets.js +211 -0
  10. package/dist/budgets.js.map +1 -0
  11. package/dist/cache.d.ts +154 -0
  12. package/dist/cache.d.ts.map +1 -0
  13. package/dist/cache.js +118 -0
  14. package/dist/cache.js.map +1 -0
  15. package/dist/collections.d.ts +242 -0
  16. package/dist/collections.d.ts.map +1 -0
  17. package/dist/collections.js +215 -0
  18. package/dist/collections.js.map +1 -0
  19. package/dist/comments.d.ts +212 -0
  20. package/dist/comments.d.ts.map +1 -0
  21. package/dist/comments.js +192 -0
  22. package/dist/comments.js.map +1 -0
  23. package/dist/content.d.ts +231 -0
  24. package/dist/content.d.ts.map +1 -0
  25. package/dist/content.js +204 -0
  26. package/dist/content.js.map +1 -0
  27. package/dist/documents.d.ts +184 -0
  28. package/dist/documents.d.ts.map +1 -0
  29. package/dist/documents.js +190 -0
  30. package/dist/documents.js.map +1 -0
  31. package/dist/edges.d.ts +645 -0
  32. package/dist/edges.d.ts.map +1 -0
  33. package/dist/edges.js +558 -0
  34. package/dist/edges.js.map +1 -0
  35. package/dist/filter.d.ts +461 -0
  36. package/dist/filter.d.ts.map +1 -0
  37. package/dist/filter.js +387 -0
  38. package/dist/filter.js.map +1 -0
  39. package/dist/index.d.ts +133 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +133 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/internal/filter-columns.d.ts +8 -0
  44. package/dist/internal/filter-columns.d.ts.map +1 -0
  45. package/dist/internal/filter-columns.js +43 -0
  46. package/dist/internal/filter-columns.js.map +1 -0
  47. package/dist/internal/list-order.d.ts +26 -0
  48. package/dist/internal/list-order.d.ts.map +1 -0
  49. package/dist/internal/list-order.js +92 -0
  50. package/dist/internal/list-order.js.map +1 -0
  51. package/dist/internal/owned-columns.d.ts +93 -0
  52. package/dist/internal/owned-columns.d.ts.map +1 -0
  53. package/dist/internal/owned-columns.js +98 -0
  54. package/dist/internal/owned-columns.js.map +1 -0
  55. package/dist/internal/plain-rows.d.ts +32 -0
  56. package/dist/internal/plain-rows.d.ts.map +1 -0
  57. package/dist/internal/plain-rows.js +32 -0
  58. package/dist/internal/plain-rows.js.map +1 -0
  59. package/dist/internal/reference-columns.d.ts +80 -0
  60. package/dist/internal/reference-columns.d.ts.map +1 -0
  61. package/dist/internal/reference-columns.js +102 -0
  62. package/dist/internal/reference-columns.js.map +1 -0
  63. package/dist/moderation.d.ts +392 -0
  64. package/dist/moderation.d.ts.map +1 -0
  65. package/dist/moderation.js +375 -0
  66. package/dist/moderation.js.map +1 -0
  67. package/dist/paths.d.ts +204 -0
  68. package/dist/paths.d.ts.map +1 -0
  69. package/dist/paths.js +165 -0
  70. package/dist/paths.js.map +1 -0
  71. package/dist/proposals.d.ts +523 -0
  72. package/dist/proposals.d.ts.map +1 -0
  73. package/dist/proposals.js +505 -0
  74. package/dist/proposals.js.map +1 -0
  75. package/dist/publication.d.ts +148 -0
  76. package/dist/publication.d.ts.map +1 -0
  77. package/dist/publication.js +183 -0
  78. package/dist/publication.js.map +1 -0
  79. package/dist/purge.d.ts +224 -0
  80. package/dist/purge.d.ts.map +1 -0
  81. package/dist/purge.js +151 -0
  82. package/dist/purge.js.map +1 -0
  83. package/dist/reactions.d.ts +246 -0
  84. package/dist/reactions.d.ts.map +1 -0
  85. package/dist/reactions.js +183 -0
  86. package/dist/reactions.js.map +1 -0
  87. package/dist/registry.d.ts +316 -0
  88. package/dist/registry.d.ts.map +1 -0
  89. package/dist/registry.js +305 -0
  90. package/dist/registry.js.map +1 -0
  91. package/dist/search.d.ts +366 -0
  92. package/dist/search.d.ts.map +1 -0
  93. package/dist/search.js +273 -0
  94. package/dist/search.js.map +1 -0
  95. package/dist/social.d.ts +311 -0
  96. package/dist/social.d.ts.map +1 -0
  97. package/dist/social.js +205 -0
  98. package/dist/social.js.map +1 -0
  99. package/dist/subtype.d.ts +1613 -0
  100. package/dist/subtype.d.ts.map +1 -0
  101. package/dist/subtype.js +1300 -0
  102. package/dist/subtype.js.map +1 -0
  103. package/dist/testing.d.ts +675 -0
  104. package/dist/testing.d.ts.map +1 -0
  105. package/dist/testing.js +1022 -0
  106. package/dist/testing.js.map +1 -0
  107. package/dist/version-chain.d.ts +702 -0
  108. package/dist/version-chain.d.ts.map +1 -0
  109. package/dist/version-chain.js +489 -0
  110. package/dist/version-chain.js.map +1 -0
  111. package/dist/working-copy.d.ts +116 -0
  112. package/dist/working-copy.d.ts.map +1 -0
  113. package/dist/working-copy.js +95 -0
  114. package/dist/working-copy.js.map +1 -0
  115. package/package.json +145 -3
  116. package/src/blobs.ts +384 -0
  117. package/src/budgets.ts +338 -0
  118. package/src/cache.ts +218 -0
  119. package/src/collections.ts +427 -0
  120. package/src/comments.ts +392 -0
  121. package/src/content.ts +238 -0
  122. package/src/documents.ts +284 -0
  123. package/src/edges.ts +1185 -0
  124. package/src/filter.ts +523 -0
  125. package/src/index.ts +153 -0
  126. package/src/internal/filter-columns.ts +50 -0
  127. package/src/internal/list-order.ts +117 -0
  128. package/src/internal/owned-columns.ts +140 -0
  129. package/src/internal/plain-rows.ts +54 -0
  130. package/src/internal/reference-columns.ts +156 -0
  131. package/src/moderation.ts +728 -0
  132. package/src/paths.ts +267 -0
  133. package/src/proposals.ts +1014 -0
  134. package/src/publication.ts +225 -0
  135. package/src/purge.ts +313 -0
  136. package/src/reactions.ts +347 -0
  137. package/src/registry.ts +524 -0
  138. package/src/search.ts +540 -0
  139. package/src/social.ts +469 -0
  140. package/src/subtype.ts +3095 -0
  141. package/src/testing.ts +1873 -0
  142. package/src/version-chain.ts +1093 -0
  143. package/src/working-copy.ts +192 -0
@@ -0,0 +1,392 @@
1
+ /**
2
+ * **The comments family** — threaded comments on any node, as versioned
3
+ * owned leaves, behind the target's own read gate and the moderation gate.
4
+ *
5
+ * The behavioural spec is gardeneria's `apps/api/src/operations/comments.ts`
6
+ * (`isCommentReadableBy`, `moderationVisibilityFilter`,
7
+ * `targetVisibilityFilter`) and its tests
8
+ * (`comment-visibility.test.ts`, `comment-target-visibility-flip.test.ts`);
9
+ * a `#NNN` here names a gardeneria issue.
10
+ *
11
+ * ## The model (owner decisions on pulpit#50)
12
+ *
13
+ * - **A comment is a versioned owned leaf**, built with `./subtype`'s
14
+ * `defineSubtype`: edits append versions, a delete tombstones, and its
15
+ * history is gated like any leaf's. Its moderation state is
16
+ * `./moderation`'s, so the leaf's hooks carry `moderationHook` (a new
17
+ * comment starts `pending`).
18
+ * - **Reply depth is the family's `maxDepth`**, default `1` (gardeneria):
19
+ * `0` is flat (website), `N` threads `N` deep. A reply past it fails
20
+ * {@link CommentDepthExceeded}. Each comment stores its `targetType`,
21
+ * `targetId`, `parentId` (`null` at the top) and `depth` (`0` at the
22
+ * top), written by `create`.
23
+ *
24
+ * ## The read gates (all three, `SEC-AUTH-ENUM-001`)
25
+ *
26
+ * A comment reads to a viewer only when:
27
+ *
28
+ * 1. the comment leaf's own `get` serves it (its owned visibility, and a
29
+ * tombstone only to the view-deleted rung);
30
+ * 2. it is `approved`, or the viewer wrote it, or holds the moderate rung
31
+ * ({@link canViewModerated} / {@link moderationListFilter}, one rule in
32
+ * two readings): moderation is not ownership, so the target's owner
33
+ * does not see a pending comment on their own row;
34
+ * 3. the viewer can read its target, through the target leaf's own `get`:
35
+ * a comment on a target they can't read is missing to them, whatever
36
+ * its own state, and listing by target checks the target first.
37
+ *
38
+ * Anything else is `NodeNotFound`, never `Forbidden`. Writes to an
39
+ * existing comment are the comment leaf's own (its author, or the moderate
40
+ * rung).
41
+ *
42
+ * @copyright Thomas Foster
43
+ * @module pulpit/comments
44
+ * @since 0.1.0
45
+ */
46
+
47
+ import * as Effect from "effect/Effect";
48
+ import * as Option from "effect/Option";
49
+ import * as Predicate from "effect/Predicate";
50
+ import * as Schema from "effect/Schema";
51
+ import { always, and, eq, or, type ListFilter } from "./filter.ts";
52
+ import type { ModerationDeclaration } from "./moderation.ts";
53
+ import {
54
+ MAX_PAGE_LIMIT,
55
+ type AccessPolicy,
56
+ type Forbidden,
57
+ type InvalidListOrder,
58
+ type LeafRow,
59
+ type LeafStore,
60
+ type ListOrder,
61
+ type Page,
62
+ type SubtypeOps,
63
+ type Unauthorized,
64
+ type Viewer,
65
+ type WriteRejected,
66
+ } from "./subtype.ts";
67
+ import {
68
+ NodeNotFound,
69
+ type ChainState,
70
+ type ChainWrite,
71
+ type NodeAlreadyExists,
72
+ type VersionConflict,
73
+ } from "./version-chain.ts";
74
+
75
+ // ── Errors ────────────────────────────────────────────────────────────
76
+
77
+ /**
78
+ * A reply that would nest deeper than the family's `maxDepth`: the wire's
79
+ * 422.
80
+ *
81
+ * @since 0.1.0
82
+ */
83
+ export class CommentDepthExceeded extends Schema.TaggedError<
84
+ CommentDepthExceeded,
85
+ { readonly brand: unique symbol }
86
+ >()("CommentDepthExceeded", {
87
+ type: Schema.String,
88
+ parentId: Schema.String,
89
+ maxDepth: Schema.Finite,
90
+ }) {}
91
+
92
+ /**
93
+ * A comments family declared against the rules: a `maxDepth` that is not
94
+ * a non-negative safe integer. Thrown by {@link defineComments} when the
95
+ * family is declared, never an Effect failure.
96
+ *
97
+ * @since 0.1.0
98
+ */
99
+ export class CommentDeclarationError extends Schema.TaggedError<
100
+ CommentDeclarationError,
101
+ { readonly brand: unique symbol }
102
+ >()("CommentDeclarationError", { message: Schema.String }) {}
103
+
104
+ // ── The moderation gate ───────────────────────────────────────────────
105
+
106
+ /**
107
+ * The columns the moderation gate reads: the comment's author (its owner
108
+ * column) and its moderation state.
109
+ *
110
+ * @since 0.1.0
111
+ */
112
+ export interface ModeratedColumns {
113
+ readonly authorColumn: string;
114
+ readonly stateColumn: string;
115
+ }
116
+
117
+ /**
118
+ * The moderation gate on one comment row: the moderate rung reads every
119
+ * state, a signed-in viewer their own comments in every state, and
120
+ * everyone else only an exactly `approved` one. The single-row reading of
121
+ * {@link moderationListFilter}; the two never disagree. Never fails.
122
+ *
123
+ * @since 0.1.0
124
+ */
125
+ export const canViewModerated = (
126
+ viewer: Viewer,
127
+ policy: AccessPolicy,
128
+ columns: ModeratedColumns,
129
+ row: LeafRow,
130
+ ): boolean =>
131
+ row[columns.stateColumn] === "approved" ||
132
+ Option.exists(
133
+ viewer,
134
+ (account) =>
135
+ policy.canModerate(account) ||
136
+ (Predicate.isString(row[columns.authorColumn]) && row[columns.authorColumn] === account.id),
137
+ );
138
+
139
+ /**
140
+ * The moderation gate as a list filter: {@link canViewModerated}'s three
141
+ * arms.
142
+ *
143
+ * @since 0.1.0
144
+ */
145
+ export const moderationListFilter = <Following>(
146
+ viewer: Viewer,
147
+ policy: AccessPolicy,
148
+ columns: ModeratedColumns,
149
+ ): ListFilter<Following> =>
150
+ Option.match(viewer, {
151
+ onNone: (): ListFilter<Following> => eq(columns.stateColumn, "approved"),
152
+ onSome: (account): ListFilter<Following> =>
153
+ policy.canModerate(account)
154
+ ? always
155
+ : or<Following>(eq(columns.stateColumn, "approved"), eq(columns.authorColumn, account.id)),
156
+ });
157
+
158
+ // ── The family ────────────────────────────────────────────────────────
159
+
160
+ /**
161
+ * A target leaf a comment may hang off: its read, which the target gate
162
+ * runs as the viewer.
163
+ *
164
+ * @since 0.1.0
165
+ */
166
+ export interface CommentTarget<E, R> {
167
+ /** The target leaf's own `get`: `NodeNotFound` for a target the viewer can't read. */
168
+ readonly get: (id: string) => Effect.Effect<unknown, NodeNotFound | E, R>;
169
+ }
170
+
171
+ /**
172
+ * A comments family's declaration.
173
+ *
174
+ * @since 0.1.0
175
+ */
176
+ export interface CommentsDefinition<Resource, Following, E, R> {
177
+ /**
178
+ * The comment leaf's operations (`defineSubtype` over an owned access,
179
+ * with `moderationHook` among its hooks).
180
+ */
181
+ readonly comments: SubtypeOps<Resource, E, R>;
182
+ /** The comment leaf's current-version view: the rows the gates read their facts from. */
183
+ readonly leaves: LeafStore<LeafRow, Following, E, R>;
184
+ /** The leaves a comment may target, by wire type; any other type is `NodeNotFound`. */
185
+ readonly targets: { readonly [type: string]: CommentTarget<E, R> };
186
+ readonly viewer: Effect.Effect<Viewer, never, R>;
187
+ readonly policy: AccessPolicy;
188
+ /** The moderation declaration the comment leaf's hook uses; its `column` is the state the gate reads. */
189
+ readonly moderation: ModerationDeclaration;
190
+ /** The comment's author column: the leaf's `ownerColumn` (conventionally `ownerId`). */
191
+ readonly authorColumn: string;
192
+ /**
193
+ * How deep replies nest: `0` flat, `1` (the default) one level of
194
+ * replies, `N` deeper. A non-negative safe integer, or
195
+ * {@link defineComments} throws {@link CommentDeclarationError}.
196
+ */
197
+ // oxlint-disable-next-line effect/prefer-option-over-null -- an optional field is `?: T | undefined` (AGENTS.md → Conventions); the omitted key is the default depth of 1
198
+ readonly maxDepth?: number | undefined;
199
+ }
200
+
201
+ /**
202
+ * A comment create: its target, its parent comment (none for a top-level
203
+ * comment), and the leaf's own columns (its body, its visibility).
204
+ *
205
+ * @since 0.1.0
206
+ */
207
+ export interface CommentCreate {
208
+ readonly id: Option.Option<string>;
209
+ readonly targetType: string;
210
+ readonly targetId: string;
211
+ readonly parentId: Option.Option<string>;
212
+ readonly state: ChainState;
213
+ }
214
+
215
+ /**
216
+ * One page of a target's comments.
217
+ *
218
+ * @since 0.1.0
219
+ */
220
+ export interface CommentListRequest {
221
+ readonly targetType: string;
222
+ readonly targetId: string;
223
+ /**
224
+ * None: every comment on the target; some none: the top-level comments
225
+ * (`depth = 0`); some parent: that comment's replies.
226
+ */
227
+ readonly parentId: Option.Option<Option.Option<string>>;
228
+ readonly limit: number;
229
+ readonly offset: number;
230
+ /** Tombstoned comments too, for the view-deleted rung (as the leaf's own `list` takes it). */
231
+ readonly includeDeleted: boolean;
232
+ // oxlint-disable-next-line effect/prefer-option-over-null -- an optional field is `?: T | undefined` (AGENTS.md → Conventions); the omitted key is the leaf's default order
233
+ readonly orderBy?: ReadonlyArray<ListOrder> | undefined;
234
+ }
235
+
236
+ /**
237
+ * The operations {@link defineComments} produces.
238
+ *
239
+ * @since 0.1.0
240
+ */
241
+ export interface CommentOps<Resource, E, R> {
242
+ /**
243
+ * Comment on a target the viewer can read, as a reply to `parentId`
244
+ * when given (a comment on the same target the viewer can read). Fails
245
+ * `NodeNotFound` for an unreadable target or parent, a parent on another
246
+ * target included; {@link CommentDepthExceeded} past `maxDepth`; and as
247
+ * the comment leaf's `create` does (`Unauthorized` when anonymous).
248
+ */
249
+ readonly create: (
250
+ input: CommentCreate,
251
+ ) => Effect.Effect<
252
+ ChainWrite,
253
+ | NodeNotFound
254
+ | CommentDepthExceeded
255
+ | Unauthorized
256
+ | Forbidden
257
+ | WriteRejected
258
+ | NodeAlreadyExists
259
+ | VersionConflict
260
+ | E,
261
+ R
262
+ >;
263
+ /** One comment, through all three read gates; `NodeNotFound` otherwise. */
264
+ readonly get: (id: string) => Effect.Effect<Resource, NodeNotFound | E, R>;
265
+ /**
266
+ * A target's comments, after its target gate (`NodeNotFound` for a target
267
+ * the viewer can't read), through the comment leaf's own list and the
268
+ * moderation gate. The page is clamped to `MAX_PAGE_LIMIT`; an unsortable
269
+ * order fails `InvalidListOrder`, as the comment leaf's `list` does.
270
+ */
271
+ readonly listByTarget: (
272
+ request: CommentListRequest,
273
+ ) => Effect.Effect<Page<Resource>, NodeNotFound | InvalidListOrder | E, R>;
274
+ }
275
+
276
+ /**
277
+ * Bind a comments family over its comment leaf. Edits, deletes and history
278
+ * stay the comment leaf's own operations.
279
+ *
280
+ * @since 0.1.0
281
+ */
282
+ export const defineComments = <Resource, Following, E, R>(
283
+ definition: CommentsDefinition<Resource, Following, E, R>,
284
+ ): CommentOps<Resource, E, R> => {
285
+ const { comments, leaves, policy } = definition;
286
+ const type = comments.type;
287
+ const maxDepth = definition.maxDepth ?? 1;
288
+ if (!Number.isSafeInteger(maxDepth) || maxDepth < 0) {
289
+ throw new CommentDeclarationError({
290
+ message: `${type}: maxDepth must be a non-negative safe integer, not ${maxDepth}`,
291
+ });
292
+ }
293
+ const columns: ModeratedColumns = {
294
+ authorColumn: definition.authorColumn,
295
+ stateColumn: definition.moderation.column,
296
+ };
297
+
298
+ /** The target gate: the target leaf's own read, as the viewer. */
299
+ const targetReadable = (targetType: string, targetId: string) =>
300
+ Option.match(Option.fromUndefinedOr(definition.targets[targetType]), {
301
+ onNone: () => Effect.fail(new NodeNotFound({ type: targetType, id: targetId })),
302
+ onSome: (target) => Effect.asVoid(target.get(targetId)),
303
+ });
304
+
305
+ /** The comment row a viewer may read, through all three gates, or `NodeNotFound`. */
306
+ const readableRow = (viewer: Viewer, id: string) =>
307
+ Effect.gen(function* () {
308
+ const resource = yield* comments.get(id);
309
+ const row = yield* leaves.get(id);
310
+ if (Option.isNone(row) || !canViewModerated(viewer, policy, columns, row.value)) {
311
+ return yield* new NodeNotFound({ type, id });
312
+ }
313
+ const targetType = row.value["targetType"];
314
+ const targetId = row.value["targetId"];
315
+ if (!Predicate.isString(targetType) || !Predicate.isString(targetId)) {
316
+ return yield* new NodeNotFound({ type, id });
317
+ }
318
+ // A comment on a target the viewer can't read is missing to them.
319
+ yield* Effect.mapError(
320
+ targetReadable(targetType, targetId),
321
+ () => new NodeNotFound({ type, id }),
322
+ );
323
+ return { resource, row: row.value };
324
+ });
325
+
326
+ /** A row's stored depth: `0` for a top-level comment; a value that is no number reads as past every limit. */
327
+ const depthOf = (row: LeafRow): number => {
328
+ const depth = row["depth"];
329
+ return Predicate.isNumber(depth) ? depth : Number.POSITIVE_INFINITY;
330
+ };
331
+
332
+ const create = Effect.fn(`${type}.comments.create`)(function* (input: CommentCreate) {
333
+ const viewer = yield* definition.viewer;
334
+ yield* targetReadable(input.targetType, input.targetId);
335
+ let depth = 0;
336
+ if (Option.isSome(input.parentId)) {
337
+ const parentId = input.parentId.value;
338
+ const parent = yield* readableRow(viewer, parentId);
339
+ if (
340
+ parent.row["targetId"] !== input.targetId ||
341
+ parent.row["targetType"] !== input.targetType
342
+ ) {
343
+ return yield* new NodeNotFound({ type, id: parentId });
344
+ }
345
+ depth = depthOf(parent.row) + 1;
346
+ if (depth > maxDepth) return yield* new CommentDepthExceeded({ type, parentId, maxDepth });
347
+ }
348
+ return yield* comments.create({
349
+ id: input.id,
350
+ state: {
351
+ ...input.state,
352
+ targetType: input.targetType,
353
+ targetId: input.targetId,
354
+ parentId: Option.getOrNull(input.parentId),
355
+ depth,
356
+ },
357
+ });
358
+ });
359
+
360
+ const get = Effect.fn(`${type}.comments.get`)(function* (id: string) {
361
+ return (yield* readableRow(yield* definition.viewer, id)).resource;
362
+ });
363
+
364
+ const listByTarget = Effect.fn(`${type}.comments.listByTarget`)(function* (
365
+ request: CommentListRequest,
366
+ ) {
367
+ const viewer = yield* definition.viewer;
368
+ yield* targetReadable(request.targetType, request.targetId);
369
+ const parent = Option.match(request.parentId, {
370
+ onNone: (): ListFilter<never> => always,
371
+ onSome: (parentId) =>
372
+ Option.match(parentId, {
373
+ onNone: (): ListFilter<never> => eq("depth", 0),
374
+ onSome: (id) => eq("parentId", id),
375
+ }),
376
+ });
377
+ return yield* comments.list({
378
+ where: and<never>(
379
+ eq("targetType", request.targetType),
380
+ eq("targetId", request.targetId),
381
+ moderationListFilter<never>(viewer, policy, columns),
382
+ parent,
383
+ ),
384
+ includeDeleted: request.includeDeleted,
385
+ limit: Math.min(request.limit, MAX_PAGE_LIMIT),
386
+ offset: request.offset,
387
+ orderBy: request.orderBy,
388
+ });
389
+ });
390
+
391
+ return { create, get, listByTarget };
392
+ };
package/src/content.ts ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * **The Content model half of the kernel** — the shared Content-axis field
3
+ * spreads and the base `content` resource, defined via
4
+ * `@thomasfosterau/effect-jsonapi`'s `Resource.make`.
5
+ *
6
+ * Ported from gardeneria's `packages/models/src/models/content.ts` (the
7
+ * three-state `Visibility`; website's copy is the older two-state one) and the
8
+ * timestamp / tombstone spreads of its `packages/models/src/utilities.ts`. A
9
+ * `#NNN` here names a gardeneria issue.
10
+ *
11
+ * Every spread is a plain `const` field map a Content subtype spreads into its
12
+ * own `Resource.make({ attributes })`, so one declaration drives the resource
13
+ * object, its documents and the create / update projections (the tri-state
14
+ * rule: a value sets, `null` clears a nullable column, `undefined` carries
15
+ * forward — declared on the descriptor, never re-spelled at a call site).
16
+ *
17
+ * @copyright Thomas Foster
18
+ * @module pulpit/content
19
+ * @since 0.1.0
20
+ */
21
+
22
+ import { Relationship, Resource } from "@thomasfosterau/effect-jsonapi";
23
+ import * as Schema from "effect/Schema";
24
+
25
+ /**
26
+ * Visibility — the explicit access axis the publication policy reads,
27
+ * independent of soft-delete and the draft flag. Three states, because the
28
+ * kernel is multi-tenant:
29
+ *
30
+ * - `public` — anyone, signed in or not; the only state the KV read-through
31
+ * cache may ever hold (`isPubliclyServeable` in `./publication`);
32
+ * - `followers` — the owner, the owner's followers (the follower seam in
33
+ * `./subtype`), and the privileged rung;
34
+ * - `private` — the owner and the privileged rung only.
35
+ *
36
+ * The predicate lives in ONE place — `canViewOwned` in `./subtype` — and
37
+ * every read of an owned row goes through it. Content carries it on the
38
+ * Content branch's version row; owned Entity / File leaves carry the same
39
+ * column on their own version row, declared with
40
+ * {@link ownedVisibilityResourceFields}.
41
+ *
42
+ * @since 0.1.0
43
+ */
44
+ export const Visibility = Schema.Literals(["public", "followers", "private"]);
45
+ /**
46
+ * The {@link Visibility} literal union: `"public" | "followers" | "private"`.
47
+ *
48
+ * @since 0.1.0
49
+ */
50
+ export type Visibility = typeof Visibility.Type;
51
+
52
+ /**
53
+ * The two orthogonal Content-branch axes every Content subtype carries on its
54
+ * version row: `visibility` (three-state, above) and the binary `draft` flag
55
+ * (`PUB-009` / `PUB-010`). Both are required on the resource but optional to
56
+ * supply at create / update (a DB default applies, updates carry forward);
57
+ * neither is ever cleared.
58
+ *
59
+ * `Resource.attribute(schema, { create: "optional" })` is the
60
+ * required-on-resource, optional-at-both-inputs, never-cleared descriptor.
61
+ *
62
+ * @since 0.1.0
63
+ */
64
+ export const contentVisibilityResourceFields = {
65
+ visibility: Resource.attribute(Visibility, { create: "optional" }),
66
+ draft: Resource.attribute(Schema.Boolean, { create: "optional" }),
67
+ } as const;
68
+
69
+ /**
70
+ * The visibility / draft fields as **create-input** shapes (`Schema.optional`,
71
+ * non-null), for Content subtypes' hand-written `Create` structs — a form
72
+ * adapter passes `value | undefined`, which `createInput`'s strict
73
+ * `optionalKey` rejects, so the create struct is hand-written.
74
+ *
75
+ * @since 0.1.0
76
+ */
77
+ export const contentVisibilityCreateFields = {
78
+ visibility: Schema.optional(Visibility),
79
+ draft: Schema.optional(Schema.Boolean),
80
+ } as const;
81
+
82
+ /**
83
+ * The visibility axis alone, for **owned Entity / File leaves** (a garden, an
84
+ * organism, an image): they carry `visibility` on their own version row but
85
+ * no `draft` flag — a garden is not a draft of anything. Same descriptor as
86
+ * the Content pair: required on the resource, optional at both inputs, never
87
+ * cleared.
88
+ *
89
+ * @since 0.1.0
90
+ */
91
+ export const ownedVisibilityResourceFields = {
92
+ visibility: Resource.attribute(Visibility, { create: "optional" }),
93
+ } as const;
94
+
95
+ /**
96
+ * The version-chain timestamps every node-family resource carries:
97
+ * `createdAt` (the node's version-0 commit time) and `updatedAt` (its current
98
+ * version's), server-computed and present on the resource only
99
+ * (`readOnlyAttribute`), never accepted as command input.
100
+ *
101
+ * @since 0.1.0
102
+ */
103
+ export const nodeTimestampResourceFields = {
104
+ createdAt: Resource.readOnlyAttribute(Schema.Date),
105
+ updatedAt: Resource.readOnlyAttribute(Schema.Date),
106
+ } as const;
107
+
108
+ /**
109
+ * The soft-delete tombstone: `deletedAt` is present only on a tombstoned row
110
+ * (`resource: "optional"` — emitters omit the key entirely while live, #691)
111
+ * and is in no write projection. A tombstone is written by the chain's
112
+ * `delete` operation (`./version-chain`), never by an input.
113
+ *
114
+ * @since 0.1.0
115
+ */
116
+ export const tombstoneResourceFields = {
117
+ deletedAt: Resource.attribute(Schema.Date, {
118
+ resource: "optional",
119
+ create: false,
120
+ update: false,
121
+ }),
122
+ } as const;
123
+
124
+ /**
125
+ * The attribute spread every **reference-data** leaf carries: the two
126
+ * timestamps and the tombstone. Reference data has no visibility axis of its
127
+ * own — the corpus is publicly readable; a Content-branch reference leaf reads
128
+ * `visibility` off the branch row like every other Content subtype, and shows
129
+ * only a `public` row below the view-private rung.
130
+ *
131
+ * @since 0.1.0
132
+ */
133
+ export const referenceLeafResourceFields = {
134
+ ...nodeTimestampResourceFields,
135
+ ...tombstoneResourceFields,
136
+ } as const;
137
+
138
+ /**
139
+ * The attribute spread every **owned Content leaf** opens its attributes with:
140
+ * the timestamps, the tombstone, and the access axis —
141
+ * {@link referenceLeafResourceFields} plus {@link ownedVisibilityResourceFields}.
142
+ *
143
+ * `draft` is deliberately absent from THIS shared spread. The family that
144
+ * actually wants a bare boolean "come back and finish this later" flag
145
+ * declares it directly through {@link contentVisibilityResourceFields};
146
+ * folding it in here would put an unused, always-`false` `draft` attribute on
147
+ * every other owned Content leaf's wire contract. A leaf gated by a
148
+ * publication *stamp* (`publishedAt`, the axis `./publication` reads) carries
149
+ * that on its own row instead — a different axis from `draft`'s hard gate
150
+ * (#1118).
151
+ *
152
+ * @since 0.1.0
153
+ */
154
+ export const ownedContentLeafResourceFields = {
155
+ ...referenceLeafResourceFields,
156
+ ...ownedVisibilityResourceFields,
157
+ } as const;
158
+
159
+ /**
160
+ * The `owner` relationship every **owned** leaf carries — the account family
161
+ * the application supplies (its `users` resource) that owns the row.
162
+ *
163
+ * Server-assigned from the authenticated caller at creation and never
164
+ * re-parented: the operation layer stamps the owner from the viewer rather
165
+ * than from the payload (`stampOwner` in `./subtype`), so an application's
166
+ * hand-written create / update structs omit it. Spread into a leaf's
167
+ * `Resource.make({ relationships })` to opt in — the registry flags the same
168
+ * leaf `owned`, and the subtype factory's `access: { kind: "owned", … }`
169
+ * names the column the linkage reads.
170
+ *
171
+ * `Relationship.one`: every owned row has an owner. The target may still fail
172
+ * to resolve (deleting an account does not cascade to its rows); consumers
173
+ * degrade to a neutral label rather than erroring.
174
+ *
175
+ * Note that effect-jsonapi lists a `one` relationship as **required** in
176
+ * the generated `createPayload`; an application serving the generated payload
177
+ * strips the linkage at its handler seam. effect-jsonapi has no read-only
178
+ * linkage descriptor (effect-jsonapi#172 closed without one; 0.17.0 has
179
+ * none), and `tests/content.test.ts` pins the required linkage so the day one
180
+ * ships is visible.
181
+ *
182
+ * @since 0.1.0
183
+ */
184
+ export const ownerRef = <Owner extends Resource.Any>(owner: () => Owner) => ({
185
+ owner: Relationship.one(owner),
186
+ });
187
+
188
+ /**
189
+ * The base Content resource's attributes: the timestamps and the tombstone —
190
+ * exactly {@link referenceLeafResourceFields}, named for the resource that
191
+ * carries them so a subtype extending the base and a leaf spreading the
192
+ * fields declare the same wire shape.
193
+ *
194
+ * @since 0.1.0
195
+ */
196
+ export const contentResourceAttributeFields = referenceLeafResourceFields;
197
+
198
+ /**
199
+ * Build the base `content` resource with the application's own id brand
200
+ * (`makeContentResource(ContentId)`) — the shape {@link ContentResource}
201
+ * carries with the auto-derived `Resource.Id<"content">`. An application whose
202
+ * ids are branded hierarchically (a `PostId` that is also a `ContentId` and a
203
+ * `NodeId`) declares the base with its own brand so the two agree.
204
+ *
205
+ * @since 0.1.0
206
+ */
207
+ export const makeContentResource = <IdSchema extends Schema.Codec<any, string>>(id: IdSchema) =>
208
+ Resource.make("content", { id, attributes: contentResourceAttributeFields });
209
+
210
+ /**
211
+ * The base Content resource with the auto-derived id (timestamps + soft-delete tombstone).
212
+ *
213
+ * @since 0.1.0
214
+ */
215
+ export const ContentResource = Resource.make("content", {
216
+ attributes: contentResourceAttributeFields,
217
+ });
218
+
219
+ /**
220
+ * Inferred type for a base content resource.
221
+ *
222
+ * @since 0.1.0
223
+ */
224
+ export type Content = typeof ContentResource.Type;
225
+
226
+ /**
227
+ * Lightweight `{ type, id }` reference to content.
228
+ *
229
+ * @since 0.1.0
230
+ */
231
+ export const ContentRef = ContentResource.identifier;
232
+
233
+ /**
234
+ * Inferred type for a content reference.
235
+ *
236
+ * @since 0.1.0
237
+ */
238
+ export type ContentRef = typeof ContentRef.Type;