@mulmoclaude/core 3.14.0 → 4.0.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 (28) hide show
  1. package/dist/collection/registry/server/index.cjs +24 -7
  2. package/dist/collection/registry/server/index.cjs.map +1 -1
  3. package/dist/collection/registry/server/index.js +25 -8
  4. package/dist/collection/registry/server/index.js.map +1 -1
  5. package/dist/collection/server/index.cjs +2 -32
  6. package/dist/collection/server/index.d.ts +0 -4
  7. package/dist/collection/server/index.js +3 -3
  8. package/dist/collection-watchers/index.cjs +2 -2
  9. package/dist/collection-watchers/index.js +2 -2
  10. package/dist/{discovery-B9zdNkgW.js → discovery-CQp0wi-n.js} +2 -2
  11. package/dist/{discovery-B9zdNkgW.js.map → discovery-CQp0wi-n.js.map} +1 -1
  12. package/dist/{discovery-BsXiDZBR.cjs → discovery-C_3gXoin.cjs} +2 -2
  13. package/dist/{discovery-BsXiDZBR.cjs.map → discovery-C_3gXoin.cjs.map} +1 -1
  14. package/dist/feeds/server/index.cjs +2 -2
  15. package/dist/feeds/server/index.js +2 -2
  16. package/dist/google/index.cjs +1 -1
  17. package/dist/google/index.js +1 -1
  18. package/dist/{server-CQSF5fHe.js → server-BIewQYpC.js} +4 -1477
  19. package/dist/server-BIewQYpC.js.map +1 -0
  20. package/dist/{server-DknYbXBo.cjs → server-CF_tGCGP.cjs} +2 -1655
  21. package/dist/server-CF_tGCGP.cjs.map +1 -0
  22. package/package.json +1 -1
  23. package/dist/collection/server/appViews.d.ts +0 -97
  24. package/dist/collection/server/publishChecks.d.ts +0 -58
  25. package/dist/collection/server/publishManifest.d.ts +0 -257
  26. package/dist/collection/server/publishProject.d.ts +0 -304
  27. package/dist/server-CQSF5fHe.js.map +0 -1
  28. package/dist/server-DknYbXBo.cjs.map +0 -1
@@ -1,1488 +1,15 @@
1
1
  import { a as isErrorWithCode, c as isStringArray, l as isUnknownArray, s as isRecord, t as errorMessage } from "./dist-D8zokgGo.js";
2
2
  import { n as writeFileAtomic } from "./root-BMroU_mB.js";
3
3
  import { n as toPosixRelPath } from "./relPath-DW8MC8VO.js";
4
- import { B as fieldText, I as embedTargetId, L as isFieldDrivenEvery, N as COMPUTED_TYPES, V as fieldTextOrNull, d as parseIsoDate, f as parseIsoDateTime, x as isValidCollectionName, z as storageKindFor } from "./itemId-DfTm08jm.js";
4
+ import { B as fieldText, I as embedTargetId, L as isFieldDrivenEvery, N as COMPUTED_TYPES, V as fieldTextOrNull, d as parseIsoDate, f as parseIsoDateTime, z as storageKindFor } from "./itemId-DfTm08jm.js";
5
5
  import { C as actionVisible, _ as uniqueRefTargets, b as projectBacklinkRow, c as selectDynamicRecord, f as itemIsDone, g as uniqueEmbedTargets, h as uniqueBacklinkSources, i as ownProp, n as deriveAll, o as firstDateField, s as resolveIcon, t as defangForPrompt, v as backlinkRows, x as rollupValue, y as coerceNumeric } from "./promptSafety-CSdyp7RF.js";
6
- import { B as SCHEMA_FILE$1, C as CollectionQueryZ, I as parseAppManifest, J as isBackendUnavailable, K as safeSlugName, O as isRegularFile, S as compileJsonlQuery, U as resolveDataDir, V as isContainedInRoot, W as resolveTemplatePath, X as archiveDir, b as queryCsv, c as resolveMutateSet, d as storeFor, f as checkpointSqliteDatabase, ht as stagingSkillDir, i as resolvePrimaryField, it as isPresetSlug$1, j as resolveCreateItemId, m as cacheDir, n as discoverCollections, nt as getWorkspaceRoot, ot as log, r as loadCollection, s as CollectionSchemaZ, u as readOnlyRefusal, y as normalizeCsvValue } from "./discovery-B9zdNkgW.js";
7
- import { r as isSafeCustomViewPath } from "./templatePath-k_WNbL_Q.js";
6
+ import { B as SCHEMA_FILE$1, C as CollectionQueryZ, J as isBackendUnavailable, K as safeSlugName, O as isRegularFile, S as compileJsonlQuery, U as resolveDataDir, V as isContainedInRoot, W as resolveTemplatePath, X as archiveDir, b as queryCsv, c as resolveMutateSet, d as storeFor, f as checkpointSqliteDatabase, ht as stagingSkillDir, i as resolvePrimaryField, it as isPresetSlug$1, j as resolveCreateItemId, m as cacheDir, n as discoverCollections, nt as getWorkspaceRoot, ot as log, r as loadCollection, s as CollectionSchemaZ, u as readOnlyRefusal, y as normalizeCsvValue } from "./discovery-CQp0wi-n.js";
8
7
  import { ingestStatePath } from "./feeds/paths.js";
9
8
  import { mirrorSkillWrite } from "./skill-bridge/index.js";
10
9
  import path from "node:path";
11
10
  import { randomBytes, randomUUID } from "node:crypto";
12
11
  import { cp, lstat, mkdir, open, readFile, readdir, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
13
12
  import { z } from "zod";
14
- //#region src/collection/server/appViews.ts
15
- /** The audiences a view may be written for. A CLOSED set: each one names a
16
- * tier with a rule behind it, so an unknown value has nowhere to be
17
- * published to and is refused before it gets there. */
18
- var VIEW_AUDIENCES = [
19
- "public",
20
- "member",
21
- "participant"
22
- ];
23
- /** Where each audience's documents live under `apps/{aid}`. `public` is not
24
- * here: it keeps `config/public` + `config/view`, which are already published
25
- * and already read by a deployed runtime. */
26
- var VIEW_TIER = {
27
- member: "member",
28
- participant: "roster"
29
- };
30
- /** The id `public.view` normalizes to. Fixed rather than derived, so two
31
- * implementations of the same normalization cannot pick different ones. */
32
- var PUBLIC_VIEW_ID = "public";
33
- /** `config` is the projection's own document in every tier (`live:config`),
34
- * so a view may not be called that — the two would be the same document. */
35
- var RESERVED_VIEW_IDS = ["config"];
36
- /** What an id may be.
37
- *
38
- * Narrow on purpose: this value is written by the author, and it becomes a
39
- * Firestore document id under a `live:` / `staged:` prefix. Excluding `:`
40
- * keeps the prefix and the id from running together; excluding `/`, `.` and
41
- * `__…__` keeps it a legal document id that addresses the path it says. */
42
- var VIEW_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
43
- var VIEW_ID_SHAPE = "must be lowercase letters, digits and hyphens, start with a letter or digit, and be at most 64 characters (e.g. front-desk)";
44
- /** Both declarations of the same thing, in one file.
45
- *
46
- * Refused rather than merged or preferred: whichever way it were resolved,
47
- * the author would have written two answers and been shown neither. */
48
- var BOTH_FORMS = "app.json declares both `views` and `public.view`. These are the same thing — `public.view` is the older spelling — and publishing would have to choose one silently. Move the `public.view` entry into `views` as { id: \"public\", audience: \"public\", … } and delete it.";
49
- /** The two declarations, as one list, or the refusal that they are both there.
50
- *
51
- * `public.view` becomes an entry under the reserved id, so everything
52
- * downstream reads one shape and "which spelling was used" is decided once. */
53
- function declaredViews(app) {
54
- const legacy = app.public?.view;
55
- const authored = app.views;
56
- if (legacy !== void 0 && authored !== void 0) return {
57
- ok: false,
58
- problems: [BOTH_FORMS]
59
- };
60
- const views = (authored ?? []).map((view, index) => ({
61
- id: view.id,
62
- audience: view.audience,
63
- path: view.path,
64
- collections: view.collections,
65
- where: `views[${index}]`
66
- }));
67
- if (legacy === void 0) return {
68
- ok: true,
69
- views
70
- };
71
- if (views.some((view) => view.id === "public")) return {
72
- ok: false,
73
- problems: [`views declares id '${PUBLIC_VIEW_ID}', which is reserved for the older \`public.view\` spelling. ${BOTH_FORMS}`]
74
- };
75
- return {
76
- ok: true,
77
- views: [...views, {
78
- id: PUBLIC_VIEW_ID,
79
- audience: "public",
80
- path: legacy.path,
81
- collections: legacy.collections,
82
- where: "public.view"
83
- }]
84
- };
85
- }
86
- /** Whether one id may be used, and what to say when it may not. */
87
- function viewIdProblems(view) {
88
- if (RESERVED_VIEW_IDS.includes(view.id)) return [`${view.where}.id is '${view.id}', which is reserved: each audience's own declaration is published at that document id.`];
89
- if (!VIEW_ID_PATTERN.test(view.id)) return [`${view.where}.id is '${view.id}': a view id ${VIEW_ID_SHAPE}. It becomes the document id this view is published at.`];
90
- if (view.id === "public" && view.audience !== "public") return [`${view.where}.id is '${PUBLIC_VIEW_ID}' with audience '${view.audience}': that id belongs to the public page.`];
91
- return [];
92
- }
93
- /** ONE public page per app, and the reason is the wire rather than taste.
94
- *
95
- * The public runtime reads a single `config/view` document and a single
96
- * `config/public.view` declaration beside it. A second `audience: "public"`
97
- * entry would pass every other check and then be published nowhere — and
98
- * which of the two became the live page would depend on declaration order,
99
- * silently. The member tiers have no such limit: `id` is their address, and
100
- * each one gets its own document.
101
- *
102
- * The refusal is here rather than "one day we will support it" precisely
103
- * because the failure is invisible: nothing errors, and the author sees a
104
- * successful publish of a page nobody is served. */
105
- function singlePublicProblems(views) {
106
- const [first, ...rest] = views.filter((view) => view.audience === "public");
107
- if (first === void 0) return [];
108
- return rest.map((view) => `${view.where} is a second audience "public" view, after ${first.where}. The public page is published at ONE document (config/view), so only one of them could ever be served — and which, would depend on the order they were written in. Give the others audience "member" or "participant", which are addressed by id and may have as many as the app needs.`);
109
- }
110
- /** The one shape everything downstream reads.
111
- *
112
- * Every caller — the publish gate, the projection, the host that writes the
113
- * documents — goes through this, so "which declaration was used" is decided
114
- * exactly once. */
115
- function normalizeViews(app) {
116
- const declared = declaredViews(app);
117
- if (!declared.ok) return declared;
118
- const problems = [...singlePublicProblems(declared.views)];
119
- const seen = /* @__PURE__ */ new Map();
120
- for (const view of declared.views) {
121
- problems.push(...viewIdProblems(view));
122
- const first = seen.get(view.id);
123
- if (first === void 0) {
124
- seen.set(view.id, view.where);
125
- continue;
126
- }
127
- problems.push(`${view.where}.id is '${view.id}', which ${first} already uses. The id is the document a view is published at, so two of them are one page — whichever was written second would silently replace the first, in staging and again at publish.`);
128
- }
129
- return problems.length > 0 ? {
130
- ok: false,
131
- problems
132
- } : {
133
- ok: true,
134
- views: declared.views
135
- };
136
- }
137
- /** How a participant reaches `cid`, or null if they cannot.
138
- *
139
- * Mirrors the rules' read branches for someone holding no role:
140
- * `partRead` (the whole collection) and `ownRow` (their own record, found
141
- * by the submit declaration's `emailField` or by a uid-derived id).
142
- *
143
- * `participantRead` is a PARAMETER rather than read off the manifest, and
144
- * that is the whole point of the signature. Publish does not promote the
145
- * manifest's value: `projectPublish` overwrites `participantRead` with what
146
- * the STAGED schemas carry, so a cid added since the last deploy is in the
147
- * manifest and not in the rules. Deriving the scope from the manifest would
148
- * publish `scope: "all"` for a collection the promoted rules then deny —
149
- * and removing one gives the mirror-image false refusal. The caller passes
150
- * the set that will actually be in force. */
151
- function participantScope(app, cid, participantRead) {
152
- if (participantRead.includes(cid)) return {
153
- cid,
154
- scope: "all"
155
- };
156
- const submit = app.public?.submit?.[cid];
157
- if (submit?.emailField !== void 0) return {
158
- cid,
159
- scope: "own",
160
- emailField: submit.emailField
161
- };
162
- if (submit?.idFrom === "auth.uid") return {
163
- cid,
164
- scope: "own",
165
- ownDocId: "auth.uid"
166
- };
167
- return null;
168
- }
169
- /** The document ids one tier uses. `live:` and `staged:` are the only two
170
- * prefixes, so a single `match` covers the projection and every view. */
171
- var viewDocId = (stage, viewId) => `${stage}:${viewId}`;
172
- var VIEW_CONFIG_ID = "config";
173
- //#endregion
174
- //#region src/collection/server/publishManifest.ts
175
- /** A collection id / app id, held to the one name rule (`SAFE_SLUG_PATTERN`)
176
- * that `sharedCollectionKey` applies. Stated once so a path built later
177
- * cannot be a way around it. */
178
- var NameZ = z.string().refine(isValidCollectionName, { message: "is not a valid id (letters, digits, '-' and '_' only)" });
179
- /** An address on the roster. Not validated as an email beyond "has an @":
180
- * the rules compare it to `request.auth.token.email` verbatim, so any
181
- * narrowing here would refuse addresses Firebase itself accepts. */
182
- var EmailZ = z.string().trim().min(3).includes("@");
183
- /** The roles the deployed rules understand.
184
- *
185
- * Two of them are row-scoped, in opposite directions, and the pair is what
186
- * the four-way split could not express:
187
- *
188
- * `participant` — the layer that is NAMED but reads only its OWN rows (the
189
- * rows it submitted). See `readerOf` vs `listedIn`.
190
- *
191
- * `assignee` — reads EVERY row and writes only the rows ASSIGNED to it. The
192
- * stylist who approves their own bookings and not a colleague's; the marker
193
- * who grades their own students. Which rows are theirs is
194
- * `collections[cid].assigneeField`, a field on the record holding the
195
- * member's address. Reads are deliberately unscoped: a stylist needs the
196
- * whole day's schedule, and scoping the read makes the app unusable.
197
- *
198
- * The names are permanent. The deployed rules compare these strings directly
199
- * and they are written into `app.json` files people commit, so a rename is a
200
- * migration over published apps rather than an edit. */
201
- var APP_ROLES = [
202
- "owner",
203
- "editor",
204
- "viewer",
205
- "participant",
206
- "assignee"
207
- ];
208
- var RoleZ = z.enum(APP_ROLES);
209
- /** `{ email: { "*" | cid: role } }`. The `"*"` key is the app-wide role; a
210
- * member may hold per-collection roles only (the stylist who is editor of
211
- * bookings and viewer of everything else). */
212
- var MembersZ = z.record(EmailZ, z.record(z.union([z.literal("*"), NameZ]), RoleZ));
213
- /** The declarative mail queue, as the rules re-derive it: a transition of the
214
- * status field, a recipient read off the RECORD, and a fixed template. */
215
- var MailZ = z.object({
216
- toField: z.string().trim().min(1),
217
- on: z.record(z.string().trim().min(1), z.object({
218
- from: z.array(z.string().trim().min(1)).min(1),
219
- to: z.string().trim().min(1)
220
- }).strict()),
221
- dataFields: z.array(z.string().trim().min(1)).optional()
222
- }).strict();
223
- /** What the rules read out of `collections[cid]`. NOT the schema — the schema
224
- * is published beside it, untouched, for clients to render from. */
225
- var CollectionConfigZ = z.object({
226
- statusField: z.string().trim().min(1).optional(),
227
- /** `{ initial: [...], <status>: [<status>...] }`. Binds writers too, and
228
- * binds `create` — that is the point of publishing it. */
229
- transitions: z.record(z.string().trim().min(1), z.array(z.string().trim().min(1))).optional(),
230
- immutable: z.boolean().optional(),
231
- submitOnly: z.boolean().optional(),
232
- /** The field naming the member a row belongs to, for the `assignee` role.
233
- *
234
- * Holds an ADDRESS, because that is the only thing the rules can compare
235
- * a member against (`request.auth.token.email`). A `ref` to a staff
236
- * collection stores the target's primary-key slug, not an address, so it
237
- * cannot be this field — declare a plain field beside the ref and let the
238
- * ref stay the thing the UI renders. The alternative, having the rules
239
- * `get()` the staff record to read an address off it, costs a document
240
- * access on every write and puts a second document between an
241
- * authorization decision and its answer.
242
- *
243
- * Only meaningful with a member holding `assignee` on this cid; a
244
- * declaration with the role and no field is refused (`assigneeProblems`),
245
- * because that member would silently hold nothing. */
246
- assigneeField: z.string().trim().min(1).optional(),
247
- /** This collection is the public projection of `mirrorOf` — the other
248
- * half of `public.submit[...].mirror`, declared here because the rules
249
- * read it when the PROJECTION is written rather than when the record is.
250
- *
251
- * What it buys: `state` may be written by anybody, and only to the value
252
- * the authority actually says, so a visitor who was refused a slot can
253
- * repair the stale row that offered it to them. */
254
- mirrorOf: NameZ.optional(),
255
- peerVisibility: z.enum(["public", "hidden"]).optional(),
256
- revealGated: z.boolean().optional(),
257
- gatedFrom: NameZ.optional(),
258
- revealBy: z.string().trim().min(1).optional(),
259
- mail: MailZ.optional(),
260
- /** Which fields an aggregate groups by. Declared here rather than in the
261
- * schema for the same reason as everything else in this file — the schema
262
- * has no `aggregate` key yet — and it is here at all because the
263
- * invariant that guards it ("every aggregation key is a CHECKED field")
264
- * is about `public.submit`, which is an app-level declaration. Published
265
- * as-is; the rules never read it. */
266
- aggregate: z.object({ by: z.array(z.string().trim().min(1)).min(1) }).strict().optional()
267
- }).strict();
268
- /** An authored submit window. ISO strings, because `app.json` is JSON and a
269
- * Firestore `Timestamp` has no JSON form. Publish lowers it to epoch millis —
270
- * the rules do not coerce strings, so an ISO string reaching Firestore is a
271
- * type error that fails CLOSED (`inWindow` refuses every submission and the
272
- * author sees "nobody can submit", not an error). */
273
- /** A window bound that lives on ANOTHER record, read at write time.
274
- *
275
- * `window.from` is one absolute instant for the whole collection, which is
276
- * enough for a survey and useless for anything recurring: "each class opens
277
- * three days before it starts, at 08:00" is a bound PER RECORD. So the bound
278
- * is not computed in the rules — they have no usable date arithmetic and
279
- * `request.time` is UTC, which is the wrong answer for "08:00" — it is
280
- * computed by whoever schedules the class, stored on the class record as
281
- * epoch millis, and merely COMPARED here.
282
- *
283
- * `ref` is the field on the record being written that names the target
284
- * (`classId`); `collection` is the cid the target lives in, fixed in the
285
- * declaration so that a path is never built out of a value a submitter wrote;
286
- * `field` is the epoch-millis field on the target.
287
- *
288
- * Not spelled `in` — that is an operator in the rules language, and
289
- * `w.fromField.in` does not parse there. */
290
- var WindowRefZ = z.object({
291
- ref: z.string().trim().min(1),
292
- collection: NameZ,
293
- field: z.string().trim().min(1)
294
- }).strict();
295
- /** The closing bound's per-record twin, and it ships WITH `fromField` rather
296
- * than as a symmetric extra: a booking desk that opens per slot and never
297
- * closes is not a booking desk. Same shape, opposite comparison — and
298
- * EXCLUSIVE where `fromField` is inclusive, so one slot's closing instant and
299
- * the next one's opening instant may be the same number. */
300
- var WindowZ = z.object({
301
- from: z.iso.datetime().optional(),
302
- until: z.iso.datetime().optional(),
303
- fromField: WindowRefZ.optional(),
304
- untilField: WindowRefZ.optional()
305
- }).strict();
306
- /** Which record a `field` document id must name, and what state it must be in.
307
- *
308
- * `idFrom: "field"` alone only stops the same string being written twice —
309
- * nothing stops a client bypassing the page and inventing a slot, so the
310
- * rules check the referenced record themselves. `exists()` is a FLOOR: a
311
- * cancelled slot and a slot nobody may book any more exist too, which is what
312
- * `where` is for.
313
- *
314
- * Always the object form, never a bare collection name. Two shapes for one
315
- * key is the kind of thing a generator gets right once and wrong afterwards,
316
- * and the rules read `s.idIn.collection` either way. */
317
- var IdInZ = z.object({
318
- collection: NameZ,
319
- where: z.object({
320
- field: z.string().trim().min(1),
321
- equals: z.union([
322
- z.string(),
323
- z.number(),
324
- z.boolean()
325
- ])
326
- }).strict().optional()
327
- }).strict();
328
- var ValidateZ = z.object({
329
- required: z.array(z.string().trim().min(1)).optional(),
330
- /** Capped at two by the rules themselves: rules have no iteration, so
331
- * `keyFieldsOk` is unrolled. A third would be accepted here and silently
332
- * unchecked there. */
333
- keyFields: z.array(z.object({
334
- field: z.string().trim().min(1),
335
- values: z.array(z.union([
336
- z.string(),
337
- z.number(),
338
- z.boolean()
339
- ])).min(1)
340
- }).strict()).optional()
341
- }).strict();
342
- var SubmitZ = z.object({
343
- auth: z.enum([
344
- "none",
345
- "anonymous",
346
- "verifiedEmail"
347
- ]),
348
- emailField: z.string().trim().min(1).optional(),
349
- createFields: z.array(z.string().trim().min(1)).min(1),
350
- initialStatus: z.string().trim().min(1).optional(),
351
- /** `field` is the mode that makes a CONTESTED resource exclusive: the
352
- * booking's document id IS the slot's id, so the second person to want
353
- * that slot is writing a document that already exists — an update, which
354
- * the public submission path never allows. Firestore decides that
355
- * atomically, so unlike a countable capacity (see `stampField`) this is
356
- * first-come ENFORCED rather than first-come read off a rank. */
357
- idFrom: z.enum([
358
- "auto",
359
- "auth.uid",
360
- "auth.uid+field",
361
- "field"
362
- ]).optional(),
363
- idField: z.string().trim().min(1).optional(),
364
- /** Required by `idFrom: "field"` — see {@link IdInZ}. */
365
- idIn: IdInZ.optional(),
366
- /** The collection holding this record's PUBLIC PROJECTION, one row per
367
- * contested thing, sharing its document id.
368
- *
369
- * A booking carries a name, an address and a phone number, and Firestore
370
- * rules cannot hide a field, so the public page must not read bookings at
371
- * all. It reads the projection instead, whose `state` is a copy of "does
372
- * a booking with this id exist" — and the rules accept the two writes
373
- * only as one batch, in both directions, so the copy cannot drift into
374
- * advertising a slot that is gone. */
375
- mirror: NameZ.optional(),
376
- validate: ValidateZ.optional(),
377
- window: WindowZ.optional(),
378
- /** A field the rules PIN to the server clock on create: the record must
379
- * carry `request.time` in it, and may never change it afterwards.
380
- *
381
- * What it buys is an order nobody can jump. A first-come app takes its
382
- * capacity from rank rather than from a count — the rules cannot count
383
- * documents, so "the first 8" can only ever be a reading of the rows —
384
- * and a rank is only as honest as the timestamp it sorts by. `idFrom`
385
- * stops a person holding two places; nothing else stops them writing
386
- * yesterday's date into the field that decides who got there first.
387
- *
388
- * Binds EVERY create, the writer branch included, so a staff-entered row
389
- * cannot be back-dated into the queue either. */
390
- stampField: z.string().trim().min(1).optional(),
391
- /** Per CURRENT STATUS, never a flat list: a flat list lets a customer move
392
- * an approved booking's `startAt` without anyone re-approving it. */
393
- selfUpdate: z.record(z.string().trim().min(1), z.array(z.string().trim().min(1))).optional(),
394
- selfTransitions: z.record(z.string().trim().min(1), z.array(z.string().trim().min(1))).optional(),
395
- finalize: z.boolean().optional(),
396
- audience: z.literal("participant").optional(),
397
- gateOn: z.object({
398
- phase: z.string().trim().min(1),
399
- match: z.string().trim().min(1)
400
- }).strict().optional()
401
- }).strict();
402
- var PublicZ = z.object({
403
- /** The master switch. Anonymous submission (`auth: "none"`) needs it as
404
- * well as its own declaration. */
405
- enabled: z.boolean().optional(),
406
- read: z.array(NameZ).optional(),
407
- /** The page the public sees, instead of the generated form.
408
- *
409
- * A form is enough to ANSWER something and not enough to CHOOSE from
410
- * what is available — a stylist-by-hour grid is not the far end of a
411
- * table. So the app may name one HTML file, which the host publishes to
412
- * `config/view` and the public page renders in a sandboxed iframe.
413
- *
414
- * `submit` stays declared alongside: the view sends an INTENT, and the
415
- * page it is embedded in performs the write against these rules.
416
- *
417
- * `collections` is declared rather than inferred from `read`. Inferring
418
- * it produces the worst failure this feature has — the view renders, the
419
- * data it wanted was never sent, and it draws an empty grid with no error
420
- * anywhere. */
421
- view: z.object({
422
- path: z.string().trim().min(1),
423
- collections: z.array(NameZ).min(1)
424
- }).strict().optional(),
425
- submit: z.record(NameZ, SubmitZ).optional()
426
- }).strict();
427
- /** One page the app shows, and who it is for.
428
- *
429
- * Generalised from `public.view` (which is still accepted, and normalizes
430
- * into this — see `appViews.ts`). The audience is what decides which document
431
- * the HTML is published to, and therefore who may read it: a rule cannot hide
432
- * a field, so "the front desk sees this" is a place, not a filter.
433
- *
434
- * `id` is not decoration. It becomes the document id the page is published
435
- * at, which is what lets one audience have more than one page — the front
436
- * desk and the stock room — and what lets a withdrawn view be found and
437
- * deleted. Its grammar is enforced at the gate, not here, so the refusal can
438
- * say what the value is used for.
439
- *
440
- * `collections` is declared rather than inferred, for the reason `public.view`
441
- * gives: an inferred list renders a perfect page with no data in it, and
442
- * nothing anywhere says why. */
443
- var ViewZ = z.object({
444
- id: z.string().trim().min(1),
445
- audience: z.enum(VIEW_AUDIENCES),
446
- path: z.string().trim().min(1),
447
- collections: z.array(NameZ).min(1)
448
- }).strict();
449
- /** The URL name an app is handed out under: `https://<host>/{slug}`.
450
- *
451
- * A SEPARATE name from the `aid`, and that separation is the point (design
452
- * D2b). `apps/{aid}` is a shelf every user of the deployment shares and the
453
- * rules' `allow create` asks only that you name yourself owner — so a
454
- * memorable aid is first-come-first-served, cannot be checked for
455
- * availability, and frees up again when an app is deleted. The aid is
456
- * therefore a UUID, and the thing people can fight over is moved to the name
457
- * that costs nothing to change.
458
- *
459
- * Declared here rather than kept beside `app.json` because a RESERVATION has
460
- * to travel with the repository: `appSlugs/{slug}` is unreadable until the app
461
- * is published (`allow read: if resource.data.published == true`), so nothing
462
- * can recover which slug an app holds by asking Firestore. A second file to
463
- * keep in step with the declaration is the alternative, and it is the kind of
464
- * pair that goes out of step silently.
465
- *
466
- * The shape is stricter than `NameZ` on purpose: it is BOTH a URL path
467
- * segment people read aloud and a Firestore document id. Lowercase
468
- * alphanumerics separated by single hyphens covers both without a case rule
469
- * that would make two slugs collide in one place and not the other.
470
- *
471
- * Which slug an app ended up with is the HOST's business — a wanted slug can
472
- * be taken, and the host writes the one it reserved back here. Nothing in this
473
- * package reads the key; it is declared so that writing it back does not make
474
- * the file unparseable. */
475
- var SLUG_SHAPE = "must be lowercase letters, digits and single hyphens, and must not start or end with one (e.g. sakura-hair)";
476
- var SlugZ = z.string().trim().max(64).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/, SLUG_SHAPE).refine((slug) => !slug.includes("--"), SLUG_SHAPE);
477
- /** The whole authored declaration.
478
- *
479
- * `owner` is accepted but is NOT the published value — publish stamps the
480
- * publisher's uid (or carries the existing one forward, which is what the
481
- * rules require on update) and refuses a declaration that disagrees. It is
482
- * accepted rather than banned because the sample app.json in the design note
483
- * shows it, and a hard refusal on a key the samples contain would be a worse
484
- * first experience than a message naming the mismatch. */
485
- var AuthoredAppZ = z.object({
486
- aid: NameZ,
487
- name: z.string().trim().min(1).optional(),
488
- /** The wanted (or reserved) URL name — see {@link SlugZ}. */
489
- slug: SlugZ.optional(),
490
- /** Per-worktree app id (design D6, implementation order 7). Accepted so a
491
- * repository already carrying it parses; nothing reads it yet. */
492
- aidEnv: z.string().trim().min(1).optional(),
493
- owner: z.string().trim().min(1).optional(),
494
- members: MembersZ,
495
- collections: z.record(NameZ, CollectionConfigZ).optional(),
496
- participantRead: z.array(NameZ).optional(),
497
- public: PublicZ.optional(),
498
- /** The app's pages, per audience. See {@link ViewZ}; `public.view` is the
499
- * older spelling of the `public` one and normalizes into this list. */
500
- views: z.array(ViewZ).optional()
501
- }).strict();
502
- /** Parse the authored declaration out of `app.json`'s text.
503
- *
504
- * Returns a LIST of problems rather than throwing, for the same reason
505
- * `loadAppManifest` returns a failure: the caller is a gate whose entire job
506
- * is to hand the author something to act on. Every problem is reported at
507
- * once — publish is a manual step, and a parser that stops at the first key
508
- * makes it N round trips. */
509
- function parseAuthoredApp(raw) {
510
- const manifest = parseAppManifest(raw);
511
- if (!manifest.ok) return {
512
- ok: false,
513
- problems: [manifest.kind === "missing" ? "app.json is missing" : manifest.detail]
514
- };
515
- const parsed = AuthoredAppZ.safeParse(JSON.parse(raw));
516
- if (!parsed.success) return {
517
- ok: false,
518
- problems: authoredProblems(parsed.error)
519
- };
520
- return {
521
- ok: true,
522
- app: parsed.data
523
- };
524
- }
525
- /** zod issues as one actionable line each: `public.submit.responses.auth: …`. */
526
- function authoredProblems(error) {
527
- return error.issues.map((issue) => {
528
- return `${issue.path.length > 0 ? issue.path.join(".") : "app.json"}: ${issue.message}`;
529
- });
530
- }
531
- //#endregion
532
- //#region src/collection/server/publishProject.ts
533
- /** The document id under `apps/{aid}/config`. One document, named, rather than
534
- * a spread of them: a second public document is a second thing to keep in
535
- * step, and nothing yet needs one. */
536
- var PUBLIC_CONFIG_DOC = "public";
537
- /** Drop keys whose value is `undefined`. Firestore rejects an undefined field
538
- * value outright, and `"k" in c` — which every optional key in the rules is
539
- * read through — must mean "the author declared it". */
540
- function compact(entries) {
541
- return Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== void 0));
542
- }
543
- /** ISO → epoch millis, the one conversion the rules cannot do for themselves.
544
- * The caller has already refused an unparseable string (the authored parser
545
- * requires `z.iso.datetime()`), so a NaN here would be a programming error;
546
- * it is still checked, because a NaN written to Firestore fails closed in the
547
- * same silent way an ISO string does. */
548
- function windowMillis(window) {
549
- if (!window) return void 0;
550
- const out = {};
551
- if (window.from !== void 0) out.fromMs = Date.parse(window.from);
552
- if (window.until !== void 0) out.untilMs = Date.parse(window.until);
553
- if (Object.values(out).some((value) => !Number.isFinite(value))) throw new Error(`publish: window bound is not a parseable timestamp (${JSON.stringify(window)})`);
554
- const projected = {
555
- ...out,
556
- ...window.fromField === void 0 ? {} : { fromField: window.fromField },
557
- ...window.untilField === void 0 ? {} : { untilField: window.untilField }
558
- };
559
- return Object.keys(projected).length > 0 ? projected : void 0;
560
- }
561
- /** One `public.submit[cid]`, with its window lowered. Everything else passes
562
- * through: the rules read these keys by the names the author wrote. */
563
- function projectSubmit(submit) {
564
- const { window, ...rest } = submit;
565
- return compact({
566
- ...rest,
567
- window: windowMillis(window)
568
- });
569
- }
570
- /** The roster's addresses as a set, in a stable order.
571
- *
572
- * Sorted so two publishes of the same declaration produce the same document
573
- * — idempotence is a property this step is tested for, and Firestore compares
574
- * arrays by ORDER. `membersConsistent()` compares as sets and would accept
575
- * any order; the test that would notice is the one asserting a second publish
576
- * changes nothing but `publishedAt`. */
577
- function memberEmailsOf(members) {
578
- return Object.keys(members).sort();
579
- }
580
- /** The previous document, kept for rollback, with its OWN `previousPublished`
581
- * stripped.
582
- *
583
- * One level, deliberately. Chaining would make every publish carry the entire
584
- * history of the app inside a single document, which grows without bound and
585
- * meets Firestore's 1 MiB document limit as a permission-shaped failure at
586
- * some unpredictable publish. One level answers the question rollback
587
- * actually asks — "put back what was there before I broke it" — and the
588
- * further history is in git, which is where the declaration came from. */
589
- function previousOf(existing) {
590
- if (!existing) return void 0;
591
- const { previousPublished: __dropped, ...rest } = existing;
592
- return rest;
593
- }
594
- /** Project the authored declaration into the documents publish writes.
595
- *
596
- * `existing` is the app document as it is in Firestore right now, or null on
597
- * a first publish. Two things need it, both required by the rules:
598
- * - `owner` must be UNCHANGED on update. Re-stamping the publisher's uid
599
- * would be refused for any app whose owner ever signed in as a different
600
- * account, and would silently transfer ownership if it were not.
601
- * - `previousPublished` is that document, so a rollback has something to
602
- * put back.
603
- *
604
- * Pure: no clock, no filesystem, no Firestore. Everything variable arrives as
605
- * a parameter, which is what makes the conversion table testable as a table. */
606
- function projectApp(authored, schemas, stamp, existing) {
607
- const owner = typeof existing?.owner === "string" ? existing.owner : stamp.uid;
608
- const submit = Object.fromEntries(Object.entries(authored.public?.submit ?? {}).map(([cid, spec]) => [cid, projectSubmit(spec)]));
609
- const publicBlock = authored.public ? compact({
610
- enabled: authored.public.enabled,
611
- read: authored.public.read,
612
- submit: Object.keys(submit).length > 0 ? submit : void 0
613
- }) : void 0;
614
- const app = compact({
615
- aid: authored.aid,
616
- name: authored.name,
617
- owner,
618
- members: authored.members,
619
- memberEmails: memberEmailsOf(authored.members),
620
- collections: authored.collections,
621
- participantRead: authored.participantRead,
622
- public: publicBlock,
623
- publishedAt: stamp.publishedAt,
624
- publishedBy: stamp.email,
625
- publishedCommit: stamp.commit,
626
- publishedDirty: stamp.dirty === true ? true : void 0,
627
- previousPublished: previousOf(existing)
628
- });
629
- const normalized = normalizeViews(authored);
630
- if (!normalized.ok) throw new Error(`publish: views declaration is not publishable (${normalized.problems.join(" ")})`);
631
- const publicView = normalized.views.find((view) => view.audience === "public");
632
- const config = {
633
- enabled: authored.public?.enabled === true,
634
- read: authored.public?.read ?? [],
635
- submit,
636
- ...publicView === void 0 ? {} : { view: { collections: publicView.collections } },
637
- publishedAt: stamp.publishedAt
638
- };
639
- if (authored.name !== void 0) config.name = authored.name;
640
- return {
641
- app,
642
- schemas: schemas.map(({ cid, schema }) => ({
643
- cid,
644
- doc: schemaDoc(schema, stamp)
645
- })),
646
- config
647
- };
648
- }
649
- /** Keys on the app document that publish owns: what is PUBLIC right now, and
650
- * the rule-facing configuration anonymous access is judged against. Deploy
651
- * carries them through from the existing document and never authors them. */
652
- var PUBLISH_OWNED_KEYS = [
653
- "public",
654
- "collections",
655
- "participantRead",
656
- "publishedAt",
657
- "publishedBy",
658
- "publishedCommit",
659
- "publishedDirty",
660
- "previousPublished"
661
- ];
662
- var isPublishOwned = (key) => PUBLISH_OWNED_KEYS.includes(key);
663
- function projectDeploy(authored, schemas, stamp, existing) {
664
- const { app } = projectApp(authored, schemas, stamp, existing);
665
- const deployed = Object.fromEntries(Object.entries(app).filter(([key]) => !isPublishOwned(key)));
666
- for (const key of PUBLISH_OWNED_KEYS) {
667
- const live = existing?.[key];
668
- if (live !== void 0) deployed[key] = live;
669
- }
670
- deployed.deployedAt = stamp.publishedAt;
671
- deployed.deployedBy = stamp.email;
672
- if (stamp.commit !== void 0) deployed.deployedCommit = stamp.commit;
673
- return {
674
- app: deployed,
675
- staging: schemas.map(({ cid, schema }) => ({
676
- cid,
677
- doc: stagedDoc(schema, stamp, authored, cid)
678
- }))
679
- };
680
- }
681
- /** One staged schema document, carrying this cid's rule-facing configuration
682
- * alongside the schema so publish can promote them together. */
683
- function stagedDoc(schema, stamp, authored, cid) {
684
- const doc = {
685
- publishedSchema: schema,
686
- deployedAt: stamp.publishedAt,
687
- deployedBy: stamp.email
688
- };
689
- const config = authored.collections?.[cid];
690
- if (config !== void 0) doc.config = config;
691
- if (authored.participantRead?.includes(cid) === true) doc.participantRead = true;
692
- if (stamp.commit !== void 0) doc.deployedCommit = stamp.commit;
693
- return doc;
694
- }
695
- /** The rule-facing configuration to promote, read from the STAGED documents
696
- * rather than from the manifest as it reads right now.
697
- *
698
- * Otherwise: deploy revision A, edit `app.json` to revision B, publish — and
699
- * the promoted schema is A's while the authorization behaviour is B's, a
700
- * combination nobody exercised through `/staging/{aid}`.
701
- *
702
- * (`public` is deliberately NOT part of this: it is not staged, because it is
703
- * the decision being made AT publish rather than something under test.) */
704
- function stagedRuleConfig(staged) {
705
- const entries = [];
706
- const participantRead = [];
707
- for (const entry of staged) {
708
- const { config } = entry.doc;
709
- if (config !== void 0) entries.push([entry.cid, config]);
710
- if (entry.doc.participantRead === true) participantRead.push(entry.cid);
711
- }
712
- return {
713
- collections: entries.length > 0 ? Object.fromEntries(entries) : void 0,
714
- participantRead: participantRead.length > 0 ? participantRead : void 0
715
- };
716
- }
717
- function projectPublish(authored, staged, stamp, existing) {
718
- const { app, config } = projectApp(authored, [], stamp, existing);
719
- const staging = stagedRuleConfig(staged);
720
- app.collections = staging.collections;
721
- app.participantRead = staging.participantRead;
722
- const published = Object.fromEntries(Object.entries(existing ?? app).filter(([key]) => !isPublishOwned(key)));
723
- for (const key of PUBLISH_OWNED_KEYS) if (key !== "public" && app[key] !== void 0) published[key] = app[key];
724
- const publicBlock = app.public;
725
- return {
726
- app: published,
727
- config,
728
- public: isRecord(publicBlock) ? publicBlock : void 0
729
- };
730
- }
731
- /** Re-stamp a staged schema document as it is promoted to `collections/{cid}`.
732
- *
733
- * The stamp answers "which version is PUBLIC right now, and who made it so",
734
- * so it is written by the operation that changes the answer — publish — not
735
- * carried over from the deploy that staged it. */
736
- function promoteSchema(staged, stamp) {
737
- const doc = {
738
- publishedSchema: staged.publishedSchema,
739
- publishedAt: stamp.publishedAt,
740
- publishedBy: stamp.email
741
- };
742
- if (stamp.commit !== void 0) doc.publishedCommit = stamp.commit;
743
- return doc;
744
- }
745
- /** One published schema document. Written key by key rather than through
746
- * `compact`, so the declared type is the type — an optional commit is the
747
- * only variable part. */
748
- function schemaDoc(schema, stamp) {
749
- const doc = {
750
- publishedSchema: schema,
751
- publishedAt: stamp.publishedAt,
752
- publishedBy: stamp.email
753
- };
754
- if (stamp.commit !== void 0) doc.publishedCommit = stamp.commit;
755
- return doc;
756
- }
757
- /** The app documents' parent path — the `FirestoreDocs` seam takes a
758
- * collection path plus a document id, and the app document's id is the aid. */
759
- var APPS_COLLECTION = "apps";
760
- /** The collection (schema) documents' parent path — what the PUBLIC page
761
- * reads, written only by publish (promotion). */
762
- var appSchemasPath = (aid) => `apps/${aid}/collections`;
763
- /** The URL-slug reservations — `appSlugs/{slug}` → `{ aid, published }`.
764
- *
765
- * A TOP-LEVEL collection, not a field on the app: the public page resolves a
766
- * slug to an aid BEFORE it can read anything under `apps/{aid}`, and a slug
767
- * has to be claimable atomically (create-if-absent) so two apps cannot hold
768
- * the same URL.
769
- *
770
- * `published` is what makes the reservation invisible until publish. The slug
771
- * is human-readable, so a readable reservation would let anyone guess the URL
772
- * and get the aid — and the aid is the `/staging/{aid}` entrance. The rule is
773
- * `allow read: if resource.data.published == true`, which needs no `get()` and
774
- * so costs nothing against the rules' expression budget. */
775
- var APP_SLUGS_COLLECTION = "appSlugs";
776
- var appSlugDoc = (aid, published) => ({
777
- aid,
778
- published
779
- });
780
- /** The staged schema documents' parent path — what `/staging/{aid}` reads,
781
- * written by deploy. A separate DOCUMENT rather than a field beside
782
- * `publishedSchema`, because the rules cannot hide a field: anything inside a
783
- * document the public page may read is public. */
784
- var appStagingPath = (aid) => `apps/${aid}/staging`;
785
- /** The public-config documents' parent path. */
786
- var appConfigPath = (aid) => `apps/${aid}/config`;
787
- /** Where one audience's pages live. `member` is read by anyone holding a role;
788
- * `roster` by anyone on the roster, participants included. */
789
- var appViewTierPath = (aid, tier) => `apps/${aid}/${tier}`;
790
- /** What one audience may see of one collection.
791
- *
792
- * For `member` this is always the whole collection: every read branch a role
793
- * opens (`readerOf`) is unscoped. Whether THIS member holds the role is not
794
- * knowable here — one projection is read by every member of the tier — and is
795
- * settled where it can be, by the entrance trying the read.
796
- *
797
- * For `participant` it is the rules' own answer, which is why it can be null:
798
- * a participant with neither `participantRead` nor an own-row submit path
799
- * cannot read the collection at all, and a page handed it would fail rather
800
- * than render less. */
801
- function scopeFor(authored, audience, cid, participantRead) {
802
- return audience === "member" ? {
803
- cid,
804
- scope: "all"
805
- } : participantScope(authored, cid, participantRead);
806
- }
807
- /** Project the declaration into the per-audience documents.
808
- *
809
- * Pure, like `projectApp`: the HTML is not here (the host reads the files),
810
- * and neither is the clock. What is here is the answer to "what may this
811
- * audience read, and how" — computed once, so the page never has to guess and
812
- * never has to discover it from a denial. */
813
- function projectAppViews(authored, stamp, promoted) {
814
- const participantRead = promoted?.participantRead ?? authored.participantRead ?? [];
815
- const normalized = normalizeViews(authored);
816
- if (!normalized.ok) throw new Error(`publish: views declaration is not publishable (${normalized.problems.join(" ")})`);
817
- return ["member", "participant"].map((audience) => {
818
- const views = normalized.views.filter((view) => view.audience === audience);
819
- const cids = [...new Set(views.flatMap((view) => view.collections))];
820
- const declaredSubmit = authored.public?.submit ?? {};
821
- const submit = Object.fromEntries(cids.flatMap((cid) => {
822
- const spec = declaredSubmit[cid];
823
- return spec === void 0 ? [] : [[cid, projectSubmit(spec)]];
824
- }));
825
- const config = {
826
- views: views.map((view) => ({
827
- id: view.id,
828
- collections: view.collections.map((cid) => scopeFor(authored, audience, cid, participantRead)).filter((scope) => scope !== null)
829
- })),
830
- submit,
831
- publishedAt: stamp.publishedAt
832
- };
833
- if (authored.name !== void 0) config.name = authored.name;
834
- return {
835
- tier: VIEW_TIER[audience],
836
- audience,
837
- config,
838
- views
839
- };
840
- });
841
- }
842
- /** The document a tier's projection is published at. Beside the views
843
- * themselves, under one `match` — see `firestore.rules`. */
844
- var viewConfigDocId = (stage) => viewDocId(stage, VIEW_CONFIG_ID);
845
- //#endregion
846
- //#region src/collection/server/publishChecks.ts
847
- /** Does this submit declaration bind a record to the submitter's identity?
848
- *
849
- * The condition for requiring `submitOnly`, and deliberately NOT "declares an
850
- * `audience`": `audience` appears only in the rules' public-create branch, so
851
- * an owner or editor never meets it and can add records freely. `immutable`
852
- * is the wrong condition too — a survey's responses are not immutable and
853
- * can be padded exactly the same way.
854
- *
855
- * What these four have in common is that each one makes the record MEAN "the
856
- * person who submitted it said this": a per-uid id, a per-uid+field id, a
857
- * row stamped with the submitter's verified address, or a submission
858
- * restricted to a named participant. A record created through the writer
859
- * branch carries the same shape and none of that meaning. */
860
- function bindsSubmitterIdentity(submit) {
861
- return submit.idFrom === "auth.uid" || submit.idFrom === "auth.uid+field" || submit.emailField !== void 0 || submit.audience === "participant";
862
- }
863
- /** The fields a rule actually CHECKS the value of, for one collection.
864
- *
865
- * `keyFields` pins a value against a declared set, `gateOn.match` pins it
866
- * against the session's current question, and the status field is pinned by
867
- * the transition machine. An aggregation grouped by anything else is grouped
868
- * by a field any submitter may write anything into — so the published
869
- * aggregate is whatever the noisiest respondent decided it should be. */
870
- function checkedFields(collection, submit) {
871
- const fields = /* @__PURE__ */ new Set();
872
- for (const keyField of submit?.validate?.keyFields ?? []) fields.add(keyField.field);
873
- if (submit?.gateOn) fields.add(submit.gateOn.match);
874
- if (collection?.statusField) fields.add(collection.statusField);
875
- return fields;
876
- }
877
- /** INVARIANT 1 — a submission bound to its submitter needs `submitOnly`. */
878
- function submitOnlyProblems(app) {
879
- const problems = [];
880
- for (const [cid, submit] of Object.entries(app.public?.submit ?? {})) {
881
- if (!bindsSubmitterIdentity(submit)) continue;
882
- if (app.collections?.[cid]?.submitOnly === true) continue;
883
- problems.push(`collections.${cid}.submitOnly must be true: public.submit.${cid} binds each record to its submitter (${identityBindings(submit).join(", ")}), so a record created any other way would carry that meaning without having earned it. Without submitOnly the rules let an owner or editor write rows directly into ${cid}.`);
884
- }
885
- return problems;
886
- }
887
- function identityBindings(submit) {
888
- const bindings = [];
889
- if (submit.idFrom === "auth.uid" || submit.idFrom === "auth.uid+field") bindings.push(`idFrom: "${submit.idFrom}"`);
890
- if (submit.emailField !== void 0) bindings.push(`emailField: "${submit.emailField}"`);
891
- if (submit.audience === "participant") bindings.push(`audience: "participant"`);
892
- return bindings;
893
- }
894
- /** INVARIANT 2 — every aggregation key is a field some rule checks. */
895
- function aggregateProblems(app) {
896
- const problems = [];
897
- for (const [cid, collection] of Object.entries(app.collections ?? {})) {
898
- const keys = collection.aggregate?.by;
899
- if (!keys) continue;
900
- const checked = checkedFields(collection, app.public?.submit?.[cid]);
901
- const loose = keys.filter((field) => !checked.has(field));
902
- const spelled = loose.map((field) => `'${field}'`).join(", ");
903
- if (loose.length > 0) problems.push(`collections.${cid}.aggregate.by names ${spelled}, which no rule checks the value of. An aggregation key must appear in public.submit.${cid}.validate.keyFields, in gateOn.match, or be the statusField — otherwise a submitter chooses their own bucket and the published aggregate is not a count of anything.`);
904
- }
905
- return problems;
906
- }
907
- /** INVARIANT 3 — `auth: "verifiedEmail"` only.
908
- *
909
- * A product decision, not a rules limitation: the rules keep all three stages
910
- * and the emulator tests keep exercising them, because deleting a stage from
911
- * the rules turns a change of mind into a cross-repo deploy. Publish is where
912
- * the current decision is expressed, and it is one line to move. */
913
- function authProblems(app) {
914
- return Object.entries(app.public?.submit ?? {}).filter(([, submit]) => submit.auth !== "verifiedEmail").map(([cid, submit]) => `public.submit.${cid}.auth is "${submit.auth}": only "verifiedEmail" may be published. The rules still implement "none" and "anonymous" — this is a product decision, and lifting it is a change here, not a rules deploy.`);
915
- }
916
- /** INVARIANT 5 — a mail transition's origins and destination must be disjoint.
917
- *
918
- * Overlap means the same write can satisfy the same template twice over, and
919
- * the deterministic mail id is the only other thing stopping a duplicate
920
- * send. The rules also require the status to have CHANGED, so an overlapping
921
- * declaration is not merely redundant: `from` containing `to` is a transition
922
- * that can never fire, which is a mail nobody ever receives. */
923
- function mailProblems(app) {
924
- return Object.entries(app.collections ?? {}).flatMap(([cid, collection]) => collectionMailProblems(cid, collection));
925
- }
926
- function collectionMailProblems(cid, collection) {
927
- const { mail } = collection;
928
- if (!mail) return [];
929
- const problems = [];
930
- if (!collection.statusField) problems.push(`collections.${cid}.mail needs collections.${cid}.statusField: the rules read the status before and after the write to decide the mail is warranted.`);
931
- for (const [template, transition] of Object.entries(mail.on)) problems.push(...templateMailProblems(cid, collection, template, transition));
932
- return problems;
933
- }
934
- function templateMailProblems(cid, collection, template, transition) {
935
- const problems = [];
936
- if (transition.from.includes(transition.to)) problems.push(`collections.${cid}.mail.on.${template} lists "${transition.to}" in both \`from\` and \`to\`. The rules require the status to CHANGE in the same write, so this template can never send.`);
937
- const allowed = collection.transitions;
938
- if (allowed) {
939
- const unreachable = transition.from.filter((from) => !(allowed[from] ?? []).includes(transition.to));
940
- const spelled = unreachable.map((from) => `'${from}' -> '${transition.to}'`).join(", ");
941
- if (unreachable.length > 0) problems.push(`collections.${cid}.mail.on.${template} sends on ${spelled}, which collections.${cid}.transitions does not allow. The record write is refused first, so the mail never fires.`);
942
- }
943
- return problems;
944
- }
945
- /** INVARIANTS 6 and 7 — the window is a real interval, and `keyFields` fits
946
- * the unrolled check in the rules. */
947
- function submitShapeProblems(app) {
948
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => [...windowProblems(cid, submit), ...keyFieldCountProblems(cid, submit)]);
949
- }
950
- function windowProblems(cid, submit) {
951
- const { window } = submit;
952
- if (window?.from === void 0 || window.until === void 0) return [];
953
- if (Date.parse(window.until) > Date.parse(window.from)) return [];
954
- return [`public.submit.${cid}.window closes at or before it opens (${window.from} -> ${window.until}): nothing could ever be submitted.`];
955
- }
956
- function keyFieldCountProblems(cid, submit) {
957
- const keyFields = submit.validate?.keyFields ?? [];
958
- if (keyFields.length <= 2) return [];
959
- return [`public.submit.${cid}.validate.keyFields declares ${keyFields.length}; the rules check at most 2. Rules have no iteration, so the check is unrolled — a third would be published and never enforced.`];
960
- }
961
- /** The fail-closed traps: declarations the rules read together, where the
962
- * missing half denies every write instead of loosening one. */
963
- function coherenceProblems(app) {
964
- const fromSubmits = Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => submitCoherenceProblems(app, cid, submit));
965
- const fromCollections = Object.entries(app.collections ?? {}).flatMap(([cid, collection]) => gateCoherenceProblems(cid, collection));
966
- return [...fromSubmits, ...fromCollections];
967
- }
968
- /** `initialStatus` is read together with the collection's `statusField` and
969
- * with `createFields`; miss either and every submission is refused. */
970
- function statusCoherenceProblems(cid, submit, collection) {
971
- if (submit.initialStatus === void 0) return [];
972
- if (!collection?.statusField) return [`public.submit.${cid}.initialStatus needs collections.${cid}.statusField: the rules look the status up by that name, and refuse every submission without it.`];
973
- if (new Set(submit.createFields).has(collection.statusField)) return [];
974
- return [`public.submit.${cid}.createFields must include "${collection.statusField}": a submission may carry ONLY the createFields, and the rules also require the status field to be present and equal to initialStatus. As written, every submission is refused.`];
975
- }
976
- /** Every field a RULE reads off a submitted record, other than the status
977
- * field (which `statusCoherenceProblems` words for itself).
978
- *
979
- * `emailField` and `idField` belong here for exactly the reason `required`
980
- * and `keyFields` do, and forgetting them was the same oversight twice: the
981
- * rules read `request.resource.data[s.emailField]` and rebuild the document
982
- * id from `s.idField`, while `hasOnly(createFields)` decides what a
983
- * submission may carry at all. A field in one list and not the other is a
984
- * contradiction the submitter cannot resolve — including it is refused,
985
- * omitting it fails the check. */
986
- function ruleReadFields(submit) {
987
- const fields = [];
988
- if (submit.emailField !== void 0) fields.push({
989
- field: submit.emailField,
990
- why: `public.submit.<cid>.emailField — the rules compare it to the submitter's verified address`
991
- });
992
- if ((submit.idFrom === "auth.uid+field" || submit.idFrom === "field") && submit.idField !== void 0) fields.push({
993
- field: submit.idField,
994
- why: `public.submit.<cid>.idField — the rules rebuild the document id from it`
995
- });
996
- return fields;
997
- }
998
- /** A checked field a submission is not allowed to carry can never be
999
- * satisfied: carrying it fails `hasOnly`, omitting it fails the check. */
1000
- function createFieldProblems(cid, submit) {
1001
- const createFields = new Set(submit.createFields);
1002
- const ruleRead = ruleReadFields(submit).filter((entry) => !createFields.has(entry.field)).map((entry) => `public.submit.${cid}.createFields must include "${entry.field}" (${entry.why.replace("<cid>", cid)}): a submission may carry only the createFields, so as written every submission is refused whether or not it carries the field.`);
1003
- const required = (submit.validate?.required ?? []).filter((field) => !createFields.has(field)).map((field) => `public.submit.${cid}.validate.required names "${field}", which is not in createFields: a submission may carry only the createFields, so the requirement can never be met.`);
1004
- const keyFields = (submit.validate?.keyFields ?? []).filter((keyField) => !createFields.has(keyField.field)).map((keyField) => `public.submit.${cid}.validate.keyFields checks "${keyField.field}", which is not in createFields: a submission carrying it is refused, and one omitting it fails the check.`);
1005
- return [
1006
- ...ruleRead,
1007
- ...required,
1008
- ...keyFields
1009
- ];
1010
- }
1011
- function submitCoherenceProblems(app, cid, submit) {
1012
- const collection = app.collections?.[cid];
1013
- const problems = [...statusCoherenceProblems(cid, submit, collection), ...createFieldProblems(cid, submit)];
1014
- if (submit.idFrom === "auth.uid+field" && submit.idField === void 0) problems.push(`public.submit.${cid}.idFrom is "auth.uid+field" but no idField is declared: the rules rebuild the document id from that field and refuse every create.`);
1015
- problems.push(...fieldIdProblems(cid, submit));
1016
- if ((submit.selfUpdate !== void 0 || submit.selfTransitions !== void 0) && !collection?.statusField) problems.push(`public.submit.${cid}.selfUpdate / selfTransitions are declared per CURRENT STATUS, but collections.${cid} declares no statusField: the rules read the current status first and refuse every self-edit without it.`);
1017
- if (submit.audience === "participant" && Object.keys(app.members).length === 0) problems.push(`public.submit.${cid}.audience is "participant" but the roster is empty: the rules resolve the submitter's role from members, so every submission is refused.`);
1018
- return problems;
1019
- }
1020
- /** `idFrom: "field"` makes the document id a CLAIM ABOUT ANOTHER RECORD, and
1021
- * the claim is only worth what is checked.
1022
- *
1023
- * `idIn` is required rather than optional, and that is the whole point of
1024
- * refusing here: without it the id is any string a stranger likes, so the app
1025
- * quietly accepts bookings for slots that do not exist. Nothing downstream
1026
- * ever notices — the booking is real, its slot is not — which is exactly the
1027
- * kind of hole a gate is for and a rule cannot state.
1028
- *
1029
- * `idIn` without the mode is refused for the opposite reason: the rules read
1030
- * it only in that branch, so an author who wrote it believes a check is
1031
- * running that is not. */
1032
- function fieldIdProblems(cid, submit) {
1033
- const problems = [];
1034
- if (submit.idFrom === "field") {
1035
- if (submit.idField === void 0) problems.push(`public.submit.${cid}.idFrom is "field" but no idField is declared: the rules take the document id from that field and refuse every create.`);
1036
- if (submit.idIn === void 0) problems.push(`public.submit.${cid}.idFrom is "field" but no idIn is declared: the document id is then any string a submitter chooses, so the app accepts records pointing at things that do not exist. Name the collection the id must be found in — and, when only some of those records may be claimed, the state they must be in: "idIn": { "collection": "slots", "where": { "field": "state", "equals": "open" } }.`);
1037
- } else if (submit.idIn !== void 0) {
1038
- const mode = submit.idFrom === void 0 ? "absent" : JSON.stringify(submit.idFrom);
1039
- problems.push(`public.submit.${cid}.idIn is declared but idFrom is ${mode}: the rules read idIn only for idFrom "field", so as written nothing checks the referenced record and the declaration promises a check it does not perform.`);
1040
- }
1041
- return problems;
1042
- }
1043
- /** Every `idIn` target, checked against the collections this repository has.
1044
- *
1045
- * Separate from {@link fieldIdProblems} for the reason the file is split at
1046
- * all: that one reads the declaration alone, this one needs to know what
1047
- * exists. */
1048
- function idTargetProblems(app, collections) {
1049
- const known = new Set(collections.map((collection) => collection.cid));
1050
- const names = known.size > 0 ? [...known].sort().join(", ") : "(none)";
1051
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => idInTargetProblems(cid, submit, known, names));
1052
- }
1053
- /** Where a `field` id says its record must be found.
1054
- *
1055
- * A typo passes every other check: the rules look the record up in a
1056
- * collection that does not exist, the lookup can never succeed, and every
1057
- * submission is refused with no explanation anywhere. A collection pointing
1058
- * at ITSELF is worse than a typo — on a create the document being written
1059
- * does not exist yet, so it is a declaration that can never accept anything. */
1060
- function idInTargetProblems(cid, submit, known, names) {
1061
- const target = submit.idIn?.collection;
1062
- if (target === void 0) return [];
1063
- if (target === cid) return [`public.submit.${cid}.idIn.collection names '${cid}' itself: a create writes a document that does not exist yet, so the record can never be found and every submission is refused. Name the collection of the thing being claimed (the slots, the seats, the assets).`];
1064
- if (!known.has(target)) return [`public.submit.${cid}.idIn.collection names '${target}', which is not a shared collection in this repository. The rules look the record up there, so nothing can ever be submitted. Shared collections here: ${names}.`];
1065
- return [];
1066
- }
1067
- /** The staged reveal reads its flag off the PARENT record, so the path to that
1068
- * parent is not optional decoration — without it the gate never opens. */
1069
- function gateCoherenceProblems(cid, collection) {
1070
- if (collection.revealGated !== true) return [];
1071
- if (collection.gatedFrom !== void 0 && collection.revealBy !== void 0) return [];
1072
- return [`collections.${cid}.revealGated needs both gatedFrom and revealBy: the flag is read off the PARENT record, and without the path the gate never opens.`];
1073
- }
1074
- /** The publisher must be able to write what they are about to write.
1075
- *
1076
- * On a first publish the rules require the creator to name themselves owner,
1077
- * in the roster, under `'*'`. Getting this wrong produces a bare permission
1078
- * error from Firestore with nothing in it about rosters — worth one line
1079
- * here instead. */
1080
- function publisherProblems(app, publisherEmail) {
1081
- if (app.members[publisherEmail]?.["*"] === "owner") return [];
1082
- return [`members must give you app-wide owner: add "${publisherEmail}": { "*": "owner" }. The rules require the publisher to hold that role (and to name themselves owner when the app is first created); otherwise the write is refused with no explanation.`];
1083
- }
1084
- /** Every cid the declaration mentions must be a collection that exists.
1085
- *
1086
- * A typo'd cid is not an error anywhere else: the app document simply carries
1087
- * a configuration for a collection nobody publishes, and the collection the
1088
- * author meant is published with no configuration at all — i.e. with the
1089
- * status machine and the submit path silently absent. */
1090
- function unknownCidProblems(app, collections) {
1091
- const known = new Set(collections.map((collection) => collection.cid));
1092
- return [
1093
- ["collections", Object.keys(app.collections ?? {})],
1094
- ["public.read", app.public?.read ?? []],
1095
- ["public.submit", Object.keys(app.public?.submit ?? {})],
1096
- ["participantRead", app.participantRead ?? []],
1097
- ["members", [...new Set(Object.values(app.members).flatMap((roles) => Object.keys(roles)))].filter((key) => key !== "*")]
1098
- ].flatMap(([where, cids]) => cids.filter((cid) => !known.has(cid)).map((cid) => `${where} names '${cid}', which is not a shared collection in this repository. Shared collections here: ${known.size > 0 ? [...known].sort().join(", ") : "(none - a schema needs storage.type \"firestore\")"}.`));
1099
- }
1100
- /** Everything publish refuses, as lines the author can act on.
1101
- *
1102
- * All of them, every time. Publish is a manual step with a human waiting on
1103
- * it; stopping at the first problem turns one review into five. */
1104
- function publishProblems(app, collections, publisherEmail) {
1105
- return [
1106
- ...unknownCidProblems(app, collections),
1107
- ...publisherProblems(app, publisherEmail),
1108
- ...submitOnlyProblems(app),
1109
- ...aggregateProblems(app),
1110
- ...authProblems(app),
1111
- ...mailProblems(app),
1112
- ...submitShapeProblems(app),
1113
- ...coherenceProblems(app),
1114
- ...primaryKeyProblems(app, collections),
1115
- ...assigneeProblems(app),
1116
- ...stampProblems(app),
1117
- ...windowRefProblems(app, collections),
1118
- ...idTargetProblems(app, collections),
1119
- ...mirrorProblems(app, collections),
1120
- ...viewProblems(app, collections)
1121
- ];
1122
- }
1123
- /** A public submission must NOT be allowed to name its own primary key.
1124
- *
1125
- * The rules constrain the DOCUMENT ID (`idFrom`) and cannot constrain the
1126
- * value of a field — nothing compares `request.resource.data[primaryKey]`
1127
- * with the path being written. So a submit path that accepts the primary key
1128
- * as a `createField` lets a submitter write at their one permitted document
1129
- * id while CLAIMING another record's identity, or a duplicate.
1130
- *
1131
- * It is refused rather than tolerated because there is nothing for the field
1132
- * to do: `firestoreStore` takes a shared record's identity from the document
1133
- * id and overwrites the field on read, so a submitted value is either equal
1134
- * to the id (noise) or a lie (silently discarded). Publishing a form field
1135
- * whose value is thrown away is worse than not having it — the author will
1136
- * believe submitters choose their ids.
1137
- *
1138
- * This is the second answer to the same question. The first was the reverse —
1139
- * REQUIRE the key, because a record without one was rejected by every reader
1140
- * — and it was right about the symptom and wrong about the cure: the identity
1141
- * belongs to the id the rules can pin, not to a field they cannot. */
1142
- function primaryKeyProblems(app, collections) {
1143
- const primaryKeyOf = new Map(collections.map((collection) => [collection.cid, collection.primaryKey]));
1144
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => {
1145
- const primaryKey = primaryKeyOf.get(cid);
1146
- if (primaryKey === void 0 || !submit.createFields.includes(primaryKey)) return [];
1147
- return [`public.submit.${cid}.createFields must NOT include "${primaryKey}", the schema's primaryKey: the rules can pin the document id but not the value of a field, so a submitter could write at their own id while claiming another record's. A shared record's identity is its document id — the store fills the field from it, and a submitted value is either the same thing or a lie that is thrown away.`];
1148
- });
1149
- }
1150
- /** `assignee` without the field that says which rows are theirs.
1151
- *
1152
- * A FAIL-CLOSED trap of the worst kind, because it fails closed for one
1153
- * person and nobody else: the rules ask `collections[cid].assigneeField` for
1154
- * the field to compare, find nothing, and refuse every write that member
1155
- * makes. The app works for the owner who set it up, and the member it was set
1156
- * up for is told only "permission denied".
1157
- *
1158
- * `'*': "assignee"` is refused outright rather than checked against every
1159
- * collection. The role means "the rows assigned to you", and what counts as
1160
- * assigned is per collection — an app-wide one would need the same field name
1161
- * to be right everywhere, and where it is missing it silently means "no
1162
- * access to this collection" rather than "no scoping here".
1163
- */
1164
- function assigneeProblems(app) {
1165
- return Object.entries(app.members).flatMap(([email, roles]) => Object.entries(roles).flatMap(([cid, role]) => {
1166
- if (role !== "assignee") return [];
1167
- if (cid === "*") return [`members["${email}"] holds "assignee" under "*", and the role cannot be app-wide: which rows are yours is declared per collection (\`collections.<cid>.assigneeField\`). Name the collections instead — { "bookings": "assignee" }.`];
1168
- if (app.collections?.[cid]?.assigneeField !== void 0) return [];
1169
- return [`members["${email}"] holds "assignee" on '${cid}', but collections.${cid}.assigneeField does not say which field names the member a row belongs to. Add it (assigneeField: "<a field holding an address>"), or give a role that is not row-scoped. Without it the rules have nothing to compare and refuse every write that member makes, while the app keeps working for everybody else.`];
1170
- }));
1171
- }
1172
- /** A server-stamped field the submitter cannot write, or can rewrite later.
1173
- *
1174
- * Both failures are silent in opposite directions. Left out of
1175
- * `createFields`, the rules refuse every submission (`hasOnly(createFields)`
1176
- * rejects the key the stamp check requires) — an app nobody can use. Left IN
1177
- * a `selfUpdate` list, the field the queue is ordered by becomes editable by
1178
- * the person standing in the queue. */
1179
- function stampProblems(app) {
1180
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => {
1181
- const stamp = submit.stampField;
1182
- if (stamp === void 0) return [];
1183
- const problems = [];
1184
- if (!submit.createFields.includes(stamp)) problems.push(`public.submit.${cid}.stampField names '${stamp}', which is not in createFields. The rules require the record to CARRY the server time in that field, and refuse any key outside createFields — so every submission is denied. Add it to createFields; the page fills it in, not the person.`);
1185
- for (const [status, fields] of Object.entries(submit.selfUpdate ?? {})) {
1186
- if (!fields.includes(stamp)) continue;
1187
- problems.push(`public.submit.${cid}.selfUpdate.${status} lets the submitter write '${stamp}', which is the field stampField pins to the server clock. Whatever that field orders — a first-come queue, an audit trail — could then be rewritten by the person it ranks. Remove it from selfUpdate.`);
1188
- }
1189
- return problems;
1190
- });
1191
- }
1192
- /** A per-record window bound pointing at a collection or a field the submitter
1193
- * never writes.
1194
- *
1195
- * `fromField` makes the rules read another record, and every part of that
1196
- * read is fail-closed: an unknown collection, or a `ref` the submission does
1197
- * not carry, means the bound can never be satisfied and the form is shut for
1198
- * good. */
1199
- function windowRefProblems(app, collections) {
1200
- const known = new Set(collections.map((collection) => collection.cid));
1201
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => [...windowBoundProblems(cid, submit, known, "fromField", submit.window?.fromField, "opening"), ...windowBoundProblems(cid, submit, known, "untilField", submit.window?.untilField, "closing")]);
1202
- }
1203
- /** Both bounds, checked identically. `untilField` arrived with the booking
1204
- * desk and reads exactly like its twin, so a check that knew only about
1205
- * `fromField` would let the closing half through unchecked — and a closing
1206
- * bound that names nothing does not leave the door ajar, it refuses every
1207
- * submission with no explanation. */
1208
- function windowBoundProblems(cid, submit, known, key, ref, which) {
1209
- if (ref === void 0) return [];
1210
- const problems = [];
1211
- if (!known.has(ref.collection)) problems.push(`public.submit.${cid}.window.${key}.collection names '${ref.collection}', which is not a shared collection in this repository. The rules read the ${which} time off a record there, so nothing can ever be submitted. Shared collections here: ${known.size > 0 ? [...known].sort().join(", ") : "(none)"}.`);
1212
- if (!submit.createFields.includes(ref.ref)) problems.push(`public.submit.${cid}.window.${key}.ref names '${ref.ref}', which is not in createFields. The rules take the target record's id from that field ON THE SUBMISSION — if the submitter never writes it, there is nothing to look up and every submission is refused.`);
1213
- return problems;
1214
- }
1215
- /** The two halves of a mirror, checked as the pair they only work as.
1216
- *
1217
- * `mirror` on the submission and `mirrorOf` on the projection are separate
1218
- * keys in separate places, and each is inert without the other: a booking
1219
- * whose slot declares no `mirrorOf` can never be created (the rules demand a
1220
- * paired write that the projection's own rule will refuse), and a projection
1221
- * whose authority declares no `mirror` drifts unbounded because nothing makes
1222
- * the two move together. Both failures are silent, and one of them —
1223
- * advertising a slot somebody already holds — is the exact thing the mirror
1224
- * exists to prevent.
1225
- *
1226
- * Also refuses a collection mirroring ITSELF, which reads as a typo and
1227
- * behaves as an unwritable collection: every create would have to prove its
1228
- * own document is simultaneously taken and open. */
1229
- function mirrorProblems(app, collections) {
1230
- const known = new Set(collections.map((collection) => collection.cid));
1231
- const names = known.size > 0 ? [...known].sort().join(", ") : "(none)";
1232
- return [...Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => mirrorClaimProblems(app, cid, submit, known, names)), ...Object.entries(app.collections ?? {}).flatMap(([cid, collection]) => mirrorOfProblems(app, cid, collection, known, names))];
1233
- }
1234
- /** The submission side: `public.submit[cid].mirror`. */
1235
- function mirrorClaimProblems(app, cid, submit, known, names) {
1236
- const { mirror } = submit;
1237
- if (mirror === void 0) return [];
1238
- if (mirror === cid) return [`public.submit.${cid}.mirror names its own collection: the projection is a SEPARATE record, and as written no create can satisfy the rules.`];
1239
- if (!known.has(mirror)) return [`public.submit.${cid}.mirror names '${mirror}', which is not a shared collection in this repository. The rules require the projection to move in the same write, so every submission is refused. Shared collections here: ${names}.`];
1240
- if (app.collections?.[mirror]?.mirrorOf !== cid) return [`public.submit.${cid}.mirror names '${mirror}', but collections.${mirror} does not declare mirrorOf: "${cid}". The two halves only work as a pair — the submission side demands the projection move with it, and the projection side is what allows that move — so as written every submission is refused.`];
1241
- return [];
1242
- }
1243
- /** The projection side: `collections[cid].mirrorOf`. */
1244
- function mirrorOfProblems(app, cid, collection, known, names) {
1245
- const authority = collection.mirrorOf;
1246
- if (authority === void 0) return [];
1247
- if (!known.has(authority)) return [`collections.${cid}.mirrorOf names '${authority}', which is not a shared collection in this repository. Nothing can then be true of it, so the projection's state may never be written. Shared collections here: ${names}.`];
1248
- if (app.public?.submit?.[authority]?.mirror !== cid) return [`collections.${cid}.mirrorOf names '${authority}', but public.submit.${authority} does not declare mirror: "${cid}". Only the pair keeps the projection honest: without the other half a record can be created without moving this one, and the public page goes on offering something that is already taken.`];
1249
- return [];
1250
- }
1251
- /** What each view is handed, and whether its audience can actually read it.
1252
- *
1253
- * Declared, never inferred — a view whose datasets were guessed from
1254
- * `public.read` renders perfectly and draws an empty grid, with nothing in
1255
- * the page, the rules or the log to say why.
1256
- *
1257
- * The reachability check below is that same failure, once per audience. A
1258
- * `public` view naming a collection outside `public.read` draws nothing; a
1259
- * `participant` view naming one the participant reaches by neither
1260
- * `participantRead` nor their own row is worse, because an unscoped list on
1261
- * an own-row collection is DENIED rather than narrowed — the page does not
1262
- * render less, it fails.
1263
- *
1264
- * There is deliberately no such check for `member`. Every read a role opens
1265
- * is unscoped, and WHICH role a given member holds is not a property of the
1266
- * declaration: a stylist scoped to `bookings` and an owner read the same
1267
- * projection. That one is settled at the entrance, by trying the read. */
1268
- /** The path, for one view. The SAME validator the host's own custom views use,
1269
- * rather than a second opinion about what a safe view path is.
1270
- *
1271
- * Two ad-hoc attempts were wrong here in the same afternoon: a prefix-and-
1272
- * suffix test let `views/../../secrets.html` through, and `views/[^/]+\.html`
1273
- * still let `views/..\..\secrets.html` through, because a backslash is not a
1274
- * slash on this side of the check and IS a separator on Windows. This one
1275
- * rejects `..`, backslashes, leading slashes and anything outside
1276
- * `[A-Za-z0-9._-]` per segment.
1277
- *
1278
- * It matters more here than for a host view: the host reads this path to
1279
- * decide which file to copy onto a document other people read — for a public
1280
- * view, a document whose rule is `allow read: if true`, so the blast radius of
1281
- * a bad path is the world rather than the author's own iframe. Nested paths
1282
- * ARE allowed by the shared validator; the extra `views/<one name>.html` shape
1283
- * is this publisher's own narrowing, kept because there is no reason for a
1284
- * published view to live in a subdirectory. */
1285
- function viewPathProblems(view) {
1286
- if (isSafeCustomViewPath(view.path) && view.path.split("/").length === 2) return [];
1287
- return [`${view.where}.path is '${view.path}': a published view is exactly one HTML file directly inside the collection's own views/ directory (e.g. views/booking.html) — no sub-directories, and no segments that climb out of it. The host reads this as a file to publish.`];
1288
- }
1289
- /** One dataset, for one view: does it exist here, and can the audience it is
1290
- * handed to actually read it? */
1291
- function viewCollectionProblems(app, view, cid, known) {
1292
- if (!known.has(cid)) return [`${view.where}.collections names '${cid}', which is not a shared collection in this repository. Shared collections here: ${known.size > 0 ? [...known].sort().join(", ") : "(none)"}.`];
1293
- if (view.audience === "public" && !(app.public?.read ?? []).includes(cid)) return [`${view.where}.collections names '${cid}', which is not in public.read: the page reads these with the VISITOR's permissions, so the rules refuse the read and the view draws an empty page. Nothing errors — this is the failure that looks like a working view with no data.`];
1294
- return [];
1295
- }
1296
- function viewProblems(app, collections) {
1297
- const normalized = normalizeViews(app);
1298
- if (!normalized.ok) return normalized.problems;
1299
- const known = new Set(collections.map((collection) => collection.cid));
1300
- return normalized.views.flatMap((view) => [...viewPathProblems(view), ...view.collections.flatMap((cid) => viewCollectionProblems(app, view, cid, known))]);
1301
- }
1302
- /** What publish will actually promote, checked as the PAIR it becomes.
1303
- *
1304
- * `publishProblems` reads the manifest, where `members` and `collections` sit
1305
- * side by side and agree. Publish does not write that pair. It writes the
1306
- * roster from the manifest and the collection configuration from what DEPLOY
1307
- * staged, so the app that lands is one half of each — and no check has ever
1308
- * looked at that combination.
1309
- *
1310
- * The sequence that gets through: deploy revision A with no `assigneeField`,
1311
- * add the field AND the member in revision B, publish without redeploying.
1312
- * Every manifest-level check passes on a declaration that is internally sound,
1313
- * while what lands is A's field-less configuration beside B's roster — an
1314
- * assignee with nothing to be compared against, refused every write, in an app
1315
- * that keeps working for everybody else. That is the precise trap
1316
- * `assigneeProblems` exists to prevent, reached by the one route it cannot
1317
- * see.
1318
- *
1319
- * Separate from `publishProblems` because it needs what deploy staged, which
1320
- * is a Firestore read the host makes and this package does not. It is checked
1321
- * against `stagedRuleConfig` — the same function the projection uses — rather
1322
- * than against a re-derivation, so the value validated is the value written.
1323
- *
1324
- * Only the staged half can be stale, so only that half is named and the fix is
1325
- * "deploy again" rather than "fix the declaration". */
1326
- function promotedRoleProblems(app, staged) {
1327
- const promoted = stagedRuleConfig(staged).collections ?? {};
1328
- const stagedCids = new Set(staged.map((entry) => entry.cid));
1329
- return [
1330
- ...promotedAssigneeProblems(app, promoted, stagedCids),
1331
- ...promotedMirrorProblems(app, promoted, stagedCids),
1332
- ...promotedRefFieldProblems(app, staged),
1333
- ...promotedParticipantViewProblems(app, staged)
1334
- ];
1335
- }
1336
- /** A participant's page, checked against the `participantRead` publish will
1337
- * actually PROMOTE.
1338
- *
1339
- * Not against the manifest's. `projectPublish` overwrites `participantRead`
1340
- * with what the staged schemas carry, so a cid added to the manifest since the
1341
- * last deploy is not in the rules — and a page written for it would be
1342
- * published, offered, and then refused the read. The manifest half of this
1343
- * file cannot see that; the promoted half can, which is why the check lives
1344
- * here rather than beside the other view checks. */
1345
- function promotedParticipantViewProblems(app, staged) {
1346
- const normalized = normalizeViews(app);
1347
- if (!normalized.ok) return [];
1348
- const participantRead = stagedRuleConfig(staged).participantRead ?? [];
1349
- return normalized.views.filter((view) => view.audience === "participant").flatMap((view) => view.collections.filter((cid) => participantScope(app, cid, participantRead) === null).map((cid) => `${view.where}.collections names '${cid}', which a participant cannot read once this publishes: it is not in the participantRead that DEPLOY staged, and public.submit.${cid} declares neither an emailField nor idFrom "auth.uid", so there is no row the rules would call theirs. The page would be refused the read, not handed fewer records. (Adding it to participantRead in app.json is not enough — deploy first.)`));
1350
- }
1351
- /** The FIELDS a rule reads off another record — `idIn.where.field` and the two
1352
- * window bounds — checked against the schema publish is about to promote.
1353
- *
1354
- * These are checked here rather than in `publishProblems` because that gate
1355
- * is given a cid and a primary key per collection and nothing else, on
1356
- * purpose: it reads the DECLARATION. A field name can only be judged against
1357
- * a schema, and the schema that matters is the STAGED one — the version
1358
- * publish promotes — not whatever the working tree says now.
1359
- *
1360
- * What a typo costs: `where: { field: "staet" }` publishes cleanly, the
1361
- * rules' comparison can never match, and every submission is denied with no
1362
- * message. The author's own app looks broken with nothing to read.
1363
- *
1364
- * Only fields the schema DECLARES are accepted. A record may carry more than
1365
- * its schema does, but a shared collection's records are written through it,
1366
- * and "the field exists on some rows" is not something a gate can promise. */
1367
- function promotedRefFieldProblems(app, staged) {
1368
- const schemaOf = new Map(staged.map((entry) => [entry.cid, entry.doc.publishedSchema]));
1369
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => submitRefProblems(schemaOf, cid, submit));
1370
- }
1371
- function submitRefProblems(schemaOf, cid, submit) {
1372
- return [
1373
- ...idInRefProblems(schemaOf, cid, submit),
1374
- ...boundRefProblems(schemaOf, cid, "fromField", submit.window?.fromField),
1375
- ...boundRefProblems(schemaOf, cid, "untilField", submit.window?.untilField)
1376
- ];
1377
- }
1378
- function idInRefProblems(schemaOf, cid, submit) {
1379
- const where = submit.idIn?.where;
1380
- if (where === void 0) return [];
1381
- return [...refFieldProblem(schemaOf, cid, "idIn.where.field", submit.idIn?.collection, where.field), ...comparableProblem(schemaOf, cid, submit.idIn?.collection, where)];
1382
- }
1383
- function boundRefProblems(schemaOf, cid, key, ref) {
1384
- if (ref === void 0) return [];
1385
- return [...refFieldProblem(schemaOf, cid, `window.${key}.field`, ref.collection, ref.field), ...millisProblem(schemaOf, cid, `window.${key}.field`, ref)];
1386
- }
1387
- /** The field spec a reference points at, or undefined when there is nothing
1388
- * staged to judge it against (the host refuses that separately, naming every
1389
- * missing collection at once). */
1390
- function referencedField(schemaOf, target, field) {
1391
- if (target === void 0 || field === void 0) return void 0;
1392
- return schemaOf.get(target)?.fields?.[field];
1393
- }
1394
- /** An enum's domain, or undefined for every other kind. Narrowed by the key
1395
- * rather than asserted: `fields` is a discriminated union and only some of
1396
- * its members carry `values`. */
1397
- function enumValues(spec) {
1398
- return spec.type === "enum" ? spec.values : void 0;
1399
- }
1400
- function refFieldProblem(schemaOf, cid, key, target, field) {
1401
- if (target === void 0 || field === void 0) return [];
1402
- const schema = schemaOf.get(target);
1403
- if (schema === void 0 || referencedField(schemaOf, target, field) !== void 0) return [];
1404
- const known = Object.keys(schema.fields ?? {}).sort().join(", ");
1405
- return [`public.submit.${cid}.${key} names '${field}', which the STAGED schema of '${target}' — the one publish promotes — does not declare. The rules read that field off the record and compare it, so as written every submission is refused with nothing to explain it. Fields on '${target}': ${known.length > 0 ? known : "(none)"}.`];
1406
- }
1407
- /** A comparison the rules can never satisfy is as dead as a missing field, and
1408
- * looks even more correct on the page: an `enum` whose domain does not contain
1409
- * the value, or a boolean field compared with a string. */
1410
- function comparableProblem(schemaOf, cid, target, where) {
1411
- const spec = referencedField(schemaOf, target, where.field);
1412
- if (spec === void 0) return [];
1413
- const said = JSON.stringify(where.equals);
1414
- const values = enumValues(spec);
1415
- if (values !== void 0) {
1416
- if (values.includes(String(where.equals))) return [];
1417
- return [`public.submit.${cid}.idIn.where.equals is ${said}, which is not one of the values '${where.field}' can hold on '${String(target)}' (${values.join(", ") || "(none)"}). The comparison can never be true, so every submission is refused.`];
1418
- }
1419
- const wanted = spec.type === "number" ? "number" : spec.type === "boolean" ? "boolean" : "string";
1420
- if (typeof where.equals === wanted) return [];
1421
- return [`public.submit.${cid}.idIn.where.equals is ${said}, and '${where.field}' on '${String(target)}' is a ${spec.type} field. The rules compare the stored value with this one and never coerce, so the comparison can never be true and every submission is refused.`];
1422
- }
1423
- /** A per-record window bound is EPOCH MILLIS, because the rules have no date
1424
- * arithmetic and do not coerce: they compare `request.time.toMillis()` with
1425
- * whatever is stored. A `datetime` field holds an ISO string, which is a type
1426
- * error that fails closed — the window never opens, and nothing says so. */
1427
- function millisProblem(schemaOf, cid, key, ref) {
1428
- const spec = referencedField(schemaOf, ref?.collection, ref?.field);
1429
- if (spec === void 0 || spec.type === "number") return [];
1430
- return [`public.submit.${cid}.${key} names '${String(ref?.field)}' on '${String(ref?.collection)}', which is a ${spec.type} field. A per-record bound is EPOCH MILLIS: the rules compare it with request.time.toMillis() and never coerce, so anything else is a type error that refuses every submission — the window simply never opens. Store the instant as a number.`];
1431
- }
1432
- function promotedAssigneeProblems(app, promoted, stagedCids) {
1433
- return Object.entries(app.members).flatMap(([email, roles]) => Object.entries(roles).flatMap(([cid, role]) => {
1434
- if (role !== "assignee" || cid === "*" || !stagedCids.has(cid)) return [];
1435
- if (promoted[cid]?.assigneeField !== void 0) return [];
1436
- return [`members["${email}"] holds "assignee" on '${cid}', and the STAGED version of '${cid}' — the one publish promotes — carries no assigneeField, even if app.json declares one now. Publish writes the roster from app.json and the collection configuration from the deploy, so that member would land with nothing to be compared against: refused every write, while the app keeps working for everybody else. Run deploy again, so the version being published is the one the declaration describes.`];
1437
- }));
1438
- }
1439
- /** The mirror's other half, checked against what publish will actually
1440
- * promote — the same trap as the assignee's field, reached by the same route.
1441
- *
1442
- * `mirror` is published from the MANIFEST (it lives in `public.submit`) while
1443
- * `mirrorOf` is promoted from what DEPLOY staged. Add both halves to
1444
- * `app.json` and publish without redeploying, and what lands is a submission
1445
- * demanding a paired projection write beside a projection whose rule config
1446
- * does not allow it: every booking is refused, and the declaration on disk
1447
- * looks perfectly sound.
1448
- *
1449
- * Refused in the reverse direction too. Removing `mirrorOf` from a live app
1450
- * and publishing without a deploy leaves the projection accepting nothing —
1451
- * and removing it FROM the staged side while the submission still demands it
1452
- * is the drift this pair exists to prevent. */
1453
- function promotedMirrorProblems(app, promoted, stagedCids) {
1454
- return [...addedMirrorProblems(app, promoted, stagedCids), ...strandedMirrorProblems(app, promoted)];
1455
- }
1456
- /** The manifest asks for a projection the promoted configuration will not
1457
- * allow: every submission denied, and nothing on the page to say why. */
1458
- function addedMirrorProblems(app, promoted, stagedCids) {
1459
- return Object.entries(app.public?.submit ?? {}).flatMap(([cid, submit]) => {
1460
- const { mirror } = submit;
1461
- if (mirror === void 0 || !stagedCids.has(mirror)) return [];
1462
- if (promoted[mirror]?.mirrorOf === cid) return [];
1463
- return [`public.submit.${cid}.mirror names '${mirror}', and the STAGED version of '${mirror}' — the one publish promotes — does not declare mirrorOf: "${cid}", even if app.json declares it now. Publish writes the submission side from app.json and the collection side from the deploy, so what lands is a booking that must move its projection beside a projection that refuses to move: every submission is denied, with nothing on the page to say why. Run deploy again, so the version being published is the one the declaration describes.`];
1464
- });
1465
- }
1466
- /** The other direction, and the DANGEROUS one.
1467
- *
1468
- * Take a live pair, delete BOTH halves from `app.json`, and publish without
1469
- * redeploying. The submission side comes from the manifest, so nothing
1470
- * requires the projection to move any more; the collection side comes from
1471
- * staging, which still says `mirrorOf`, so the projection stays writable.
1472
- * Bookings are then created while the public row goes on saying `open` — the
1473
- * precise failure the pair exists to prevent, arrived at by removing it.
1474
- *
1475
- * Refused rather than tolerated because the app keeps WORKING: submissions
1476
- * succeed. Only the public page is wrong, and only to the people reading it. */
1477
- function strandedMirrorProblems(app, promoted) {
1478
- return Object.entries(promoted).flatMap(([cid, config]) => {
1479
- const authority = config.mirrorOf;
1480
- if (authority === void 0) return [];
1481
- if (app.public?.submit?.[authority]?.mirror === cid) return [];
1482
- return [`the STAGED version of '${cid}' — the one publish promotes — declares mirrorOf: "${authority}", and app.json no longer declares public.submit.${authority}.mirror: "${cid}". What lands is a projection that is still writable beside submissions that no longer have to move it, so records can be created while '${cid}' goes on advertising them as available. Nothing fails: the app works and the public page lies. Run deploy again, so the version being published is the one the declaration describes.`];
1483
- });
1484
- }
1485
- //#endregion
1486
13
  //#region src/collection/server/skillAssets.ts
1487
14
  /** Read a collection's custom-view HTML, path-safely. `viewFile` is a
1488
15
  * schema-validated `views/*.html` path, resolved with realpath containment.
@@ -3552,6 +2079,6 @@ function makeManageCollectionTool(deps = {}) {
3552
2079
  };
3553
2080
  }
3554
2081
  //#endregion
3555
- export { stagedRuleConfig as $, runQueryOverRows as A, APPS_COLLECTION as B, STORE_UNREADABLE as C, recordFieldProblem as D, compileRecordZ as E, readCustomViewI18n as F, appSlugDoc as G, PUBLIC_CONFIG_DOC as H, readSkillTemplate as I, projectApp as J, appStagingPath as K, bindsSubmitterIdentity as L, buildCollectionActionSeedPrompt as M, promptPathsFor as N, runCollectionQuery as O, readCustomViewHtml as P, promoteSchema as Q, promotedRoleProblems as R, MAX_RECORD_ISSUES as S, validateRecordObject as T, appConfigPath as U, APP_SLUGS_COLLECTION as V, appSchemasPath as W, projectDeploy as X, projectAppViews as Y, projectPublish as Z, computeCollectionIcon as _, deleteCollection as a, RESERVED_VIEW_IDS as at, applyMutateAction as b, computeSuccessor as c, VIEW_ID_PATTERN as ct, isTriggerDue as d, participantScope as dt, viewConfigDocId as et, maybeSpawnSuccessor as f, viewDocId as ft, ONE_SECOND_MS as g, successorId as h, deleteCustomView as i, PUBLIC_VIEW_ID as it, buildActionSeedPrompt as j, enrichItems as k, daysInMonth as l, VIEW_TIER as lt, resolveEvery as m, MAX_UNSELECTIVE_ITEMS as n, AuthoredAppZ as nt, deleteCollectionRefusalMessage as o, VIEW_AUDIENCES as ot, parseCivil as p, appViewTierPath as q, makeManageCollectionTool as r, parseAuthoredApp as rt, advanceTriggerDate as s, VIEW_CONFIG_ID as st, MAX_SCHEMA_ISSUES as t, APP_ROLES as tt, formatCivil as u, normalizeViews as ut, buildWorkspaceOntology as v, validateCollectionRecords as w, firstMutateParamProblem as x, schemaRelations as y, publishProblems as z };
2082
+ export { runQueryOverRows as A, STORE_UNREADABLE as C, recordFieldProblem as D, compileRecordZ as E, readCustomViewI18n as F, readSkillTemplate as I, buildCollectionActionSeedPrompt as M, promptPathsFor as N, runCollectionQuery as O, readCustomViewHtml as P, MAX_RECORD_ISSUES as S, validateRecordObject as T, computeCollectionIcon as _, deleteCollection as a, applyMutateAction as b, computeSuccessor as c, isTriggerDue as d, maybeSpawnSuccessor as f, ONE_SECOND_MS as g, successorId as h, deleteCustomView as i, buildActionSeedPrompt as j, enrichItems as k, daysInMonth as l, resolveEvery as m, MAX_UNSELECTIVE_ITEMS as n, deleteCollectionRefusalMessage as o, parseCivil as p, makeManageCollectionTool as r, advanceTriggerDate as s, MAX_SCHEMA_ISSUES as t, formatCivil as u, buildWorkspaceOntology as v, validateCollectionRecords as w, firstMutateParamProblem as x, schemaRelations as y };
3556
2083
 
3557
- //# sourceMappingURL=server-CQSF5fHe.js.map
2084
+ //# sourceMappingURL=server-BIewQYpC.js.map