@mulmoclaude/core 3.5.0 → 3.7.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 (56) hide show
  1. package/assets/helps/collection-skills.md +49 -1
  2. package/assets/helps/error-recovery.md +53 -0
  3. package/dist/calendarGrid-CQ8MVSRb.js.map +1 -1
  4. package/dist/calendarGrid-DGILaVxI.cjs.map +1 -1
  5. package/dist/collection/core/schema.d.ts +8 -1
  6. package/dist/collection/core/schemaZ.d.ts +36 -26
  7. package/dist/collection/firestore.cjs +51 -0
  8. package/dist/collection/firestore.cjs.map +1 -0
  9. package/dist/collection/firestore.d.ts +1 -0
  10. package/dist/collection/firestore.js +50 -0
  11. package/dist/collection/firestore.js.map +1 -0
  12. package/dist/collection/registry/server/index.cjs +19 -19
  13. package/dist/collection/registry/server/index.cjs.map +1 -1
  14. package/dist/collection/registry/server/index.js +2 -2
  15. package/dist/collection/server/appManifest.d.ts +53 -0
  16. package/dist/collection/server/delete.d.ts +10 -0
  17. package/dist/collection/server/discoveredCollection.d.ts +10 -0
  18. package/dist/collection/server/discovery.d.ts +1 -0
  19. package/dist/collection/server/firestoreDocs.d.ts +39 -0
  20. package/dist/collection/server/firestoreStore.d.ts +14 -0
  21. package/dist/collection/server/host.d.ts +52 -0
  22. package/dist/collection/server/index.cjs +72 -52
  23. package/dist/collection/server/index.d.ts +8 -1
  24. package/dist/collection/server/index.js +3 -3
  25. package/dist/collection/server/manageTool.d.ts +4 -0
  26. package/dist/collection/server/publish.d.ts +56 -0
  27. package/dist/collection/server/publishChecks.d.ts +29 -0
  28. package/dist/collection/server/publishManifest.d.ts +181 -0
  29. package/dist/collection/server/publishProject.d.ts +86 -0
  30. package/dist/collection/server/validate.d.ts +12 -0
  31. package/dist/collection-watchers/index.cjs +143 -52
  32. package/dist/collection-watchers/index.cjs.map +1 -1
  33. package/dist/collection-watchers/index.js +132 -41
  34. package/dist/collection-watchers/index.js.map +1 -1
  35. package/dist/collection-watchers/reconciler.d.ts +1 -1
  36. package/dist/feeds/server/index.cjs +10 -10
  37. package/dist/feeds/server/index.cjs.map +1 -1
  38. package/dist/feeds/server/index.js +2 -2
  39. package/dist/google/index.cjs +12 -12
  40. package/dist/google/index.cjs.map +1 -1
  41. package/dist/google/index.js +1 -1
  42. package/dist/{server-BiRLLMpW.js → server-B48Jyxcj.js} +1100 -230
  43. package/dist/server-B48Jyxcj.js.map +1 -0
  44. package/dist/{server-5EMj3naj.cjs → server-CWZyg8fn.cjs} +1333 -385
  45. package/dist/server-CWZyg8fn.cjs.map +1 -0
  46. package/dist/{discovery-Ck4AqikY.cjs → store-5_P_NsGa.cjs} +2108 -1755
  47. package/dist/store-5_P_NsGa.cjs.map +1 -0
  48. package/dist/{discovery-DH9wweuj.js → store-_61sO8K8.js} +2333 -2022
  49. package/dist/store-_61sO8K8.js.map +1 -0
  50. package/dist/whisper/index.cjs +1 -1
  51. package/dist/whisper/index.js +1 -1
  52. package/package.json +7 -1
  53. package/dist/discovery-Ck4AqikY.cjs.map +0 -1
  54. package/dist/discovery-DH9wweuj.js.map +0 -1
  55. package/dist/server-5EMj3naj.cjs.map +0 -1
  56. package/dist/server-BiRLLMpW.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"calendarGrid-DGILaVxI.cjs","names":[],"sources":["../src/collection/core/fieldText.ts","../src/collection/core/schema.ts","../src/collection/core/ids.ts","../src/collection/core/collectionKey.ts","../src/collection/core/calendarGrid.ts"],"sourcesContent":["// Turning a record field into text.\n//\n// `CollectionItem` is `Record<string, unknown>`, so a field holds whatever the\n// record's JSON had — including arrays and objects (real workspace data has\n// plenty: weather `hourly`, GeoJSON `geometry`, `sites` lists). Bare\n// `String(value)` on one of those yields `\"[object Object]\"`, which then gets\n// compared, matched or displayed as if it were a value. Nothing throws; a\n// predicate just silently stops matching, or the UI shows `[object Object]`.\n//\n// These two helpers are the only sanctioned way to read a field as text. The\n// rule they encode was already in `itemLabelOf`: accept primitives, let\n// everything else fall through to the caller's fallback.\n\n/** A field value that has a meaningful text form. Dates are included because\n * a JSON record can carry one once it has been revived. */\nconst isTextable = (value: unknown): value is string | number | boolean | Date =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || value instanceof Date;\n\n/** The field's text, or `null` when it has no meaningful one (absent, or an\n * array/object that would stringify to `\"[object Object]\"`).\n *\n * Returning `null` rather than `\"\"` keeps \"the field is empty\" distinct from\n * \"the field can't be text\" — a matcher must not treat an object-valued field\n * as an empty string and match `\"\"`. */\nexport function fieldTextOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (!isTextable(value)) return null;\n if (value instanceof Date) {\n // `new Date(\"nonsense\")` is still `instanceof Date`, and `toISOString()`\n // throws `RangeError` on it. This helper sits on the match, sort and\n // display paths, so one unparseable date in one record would take the whole\n // render down — the loud version of the bug this module exists to prevent.\n return Number.isNaN(value.getTime()) ? null : value.toISOString();\n }\n return String(value);\n}\n\n/** The field's text, or `fallback` (default `\"\"`) when it has none. Use where\n * a string is required and an empty one is a safe stand-in — display, sort\n * keys, CSV cells. Where the distinction matters, use {@link fieldTextOrNull}. */\nexport function fieldText(value: unknown, fallback = \"\"): string {\n return fieldTextOrNull(value) ?? fallback;\n}\n","// Schema-driven collection types. A \"collection\" is a skill (under\n// .claude/skills/<slug>/) that also ships a sibling `schema.json`.\n// The host's <CollectionView> reads the schema + records and renders\n// a table/form; Claude reads SKILL.md and CRUDs the records as JSON\n// files.\n//\n// SINGLE SOURCE OF TRUTH: every type describing the schema.json contract is\n// derived (`z.infer`) from the zod definitions in `./schemaZ` — the shapes,\n// their doc comments, and the validation rules live THERE; this module only\n// re-derives the TypeScript names consumers import. The imports from\n// `./schemaZ` are type-only, so zod never reaches the browser bundle through\n// the isomorphic barrel; at runtime the dependency points the other way\n// (schemaZ imports this module's consts).\n//\n// Field specs are a DISCRIMINATED UNION on `type`: narrow with\n// `field.type === \"enum\"` (etc.) before reading a variant key like `values`,\n// `to`, `formula`, or `of`.\n\nimport { fieldText } from \"./fieldText\";\nimport type { z } from \"zod\";\nimport type {\n ActionSpecZ,\n CollectionSchemaZ,\n CustomViewZ,\n DataSourceZ,\n DynamicIconRuleZ,\n DynamicIconSourceZ,\n DynamicIconSpecZ,\n EveryFieldDrivenZ,\n EveryLiteralZ,\n EveryZ,\n FieldSpecZ,\n IngestZ,\n SpawnZ,\n StorageZ,\n SubFieldSpecZ,\n WhenZ,\n} from \"./schemaZ\";\n\n/** Minimal \"this collection is a feed\" descriptor carried on the schema.\n * Deliberately narrow — the canonical collection contract stays\n * independent of the host's feeds subsystem. The host's richer retrieval\n * spec (`IngestSpec` in `feeds/ingestTypes.ts`) is a subtype, so feed code\n * reads the extra fields by typing feed schemas with that subtype;\n * collection rendering only needs these three + the presence check. */\nexport interface CollectionIngest {\n kind: string;\n schedule: string;\n /** Optional time-of-day anchor for `schedule: \"daily\"` — the hour (0–23) to\n * refresh around (the host ticks hourly, so the run lands within that hour).\n * Ignored for non-daily schedules. Absent ⇒ elapsed-based daily (\"≥24 h since\n * the last run\"). NOTE: **UTC**, not local — compared via `getUTCHours()` for\n * an unambiguous, DST-free check (matching the rest of the scheduler), so\n * convert local times before writing (e.g. 07:00 JST → `atHour: 22`). */\n atHour?: number;\n /** Declarative retrievers (`rss`/`atom`/`http-json`) only — the host fetches\n * this URL on the schedule. Absent for `kind: \"agent\"`, where the agent owns\n * retrieval. */\n url?: string;\n /** `kind: \"agent\"` only: role id the scheduled hidden worker runs in. */\n role?: string;\n /** `kind: \"agent\"` only: skill-relative template path (under `templates/`)\n * whose prose tells the worker how to refresh the records. */\n template?: string;\n}\n\n/** Declarative retriever kinds a Feed's `ingest.kind` may declare. The host's\n * feeds engine dispatches on these; they live here (with the schema contract)\n * so the schema validator can enforce them. The host re-exports these from\n * `server/workspace/feeds/ingestTypes.ts`. */\nexport const INGEST_KINDS = [\"rss\", \"atom\", \"http-json\"] as const;\nexport type IngestKind = (typeof INGEST_KINDS)[number];\n\n/** The agent-performed ingest kind. Instead of a declarative fetch, the host\n * dispatches a hidden background chat (origin `system`) in `ingest.role`,\n * seeded with `ingest.template` + a summary of every record, on the\n * `ingest.schedule` cadence; the worker edits records via the collections io\n * layer. Kept separate from {@link INGEST_KINDS} (which the declarative\n * retriever registry keys on) so the schema validator can model `ingest` as a\n * discriminated union without the feeds engine gaining an \"agent\" retriever. */\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\n/** Refresh cadences a Feed's `ingest.schedule` may declare. */\nexport const FEED_SCHEDULES = [\"hourly\", \"daily\", \"weekly\", \"on-demand\"] as const;\nexport type FeedSchedule = (typeof FEED_SCHEDULES)[number];\n\n// \"feed\" collections live in the non-skill `<workspace>/feeds/` registry\n// and carry an `ingest` block; they reuse the same storage + rendering\n// as skill-backed collections but are never loaded into the agent prompt.\nexport type CollectionSource = \"user\" | \"project\" | \"feed\";\n\n/** One field of a record — a discriminated union on `type`; see the variant\n * docs in `./schemaZ` (`FieldSpecZ`). */\nexport type CollectionFieldSpec = z.infer<typeof FieldSpecZ>;\n\n/** A `table` field's row sub-schema entry — the field union minus `table` /\n * `derived` / display-only types (see `SubFieldSpecZ`). */\nexport type CollectionSubFieldSpec = z.infer<typeof SubFieldSpecZ>;\n\nexport type CollectionFieldType = CollectionFieldSpec[\"type\"];\n\n/** The computed-boolean variant — a `where` predicate bound to a field\n * name; see `FlagFieldZ`. */\nexport type CollectionFlagField = Extract<CollectionFieldSpec, { type: \"flag\" }>;\n\n/** derived/embed/backlinks/rollup/toggle/flag are host-computed or\n * projected — never written to the record JSON, so required / value\n * checks and edit-draft slots must not apply to them. THE single source\n * for \"computed\" — lives here (zod-free at runtime) so browser code\n * (`./draft`) and the zod record compiler (`./recordZ`, which re-exports\n * it) share one set instead of drifting copies. */\nexport const COMPUTED_TYPES: ReadonlySet<CollectionFieldType> = new Set<CollectionFieldType>([\"derived\", \"embed\", \"backlinks\", \"rollup\", \"toggle\", \"flag\"]);\n\n/** Optional visibility predicate: the target (an action button or a\n * field) renders only when the open record's `field` (stringified) is\n * one of `in`. Generic and domain-free — the host evaluates it against\n * the record with no knowledge of what the field means. Absent ⇒\n * always shown. */\nexport type CollectionWhen = z.infer<typeof WhenZ>;\n\n/** @deprecated Name retained for back-compat; use {@link CollectionWhen}.\n * Both actions and fields share the same predicate shape. No in-repo\n * consumers, but the package is public API (MulmoTerminal). */\n// eslint-disable-next-line sonarjs/redundant-type-aliases -- deliberate deprecated back-compat export\nexport type CollectionActionWhen = CollectionWhen;\n\n/** A schema-declared, per-record action rendered as a button in the\n * read-only detail view. Pure UI/behaviour directive — never stored,\n * never validated against record data. All domain specifics (label,\n * role, template — or the declarative `set`) live in the schema / skill\n * folder, so the host stays generic. A discriminated union on `kind`;\n * see `ActionSpecZ`. */\nexport type CollectionAction = z.infer<typeof ActionSpecZ>;\n\n/** The kind of work an action kicks off: `\"chat\"` (visible LLM chat),\n * `\"agent\"` (hidden LLM worker), or `\"mutate\"` (declarative host write,\n * no LLM). */\nexport type CollectionActionKind = CollectionAction[\"kind\"];\n\n/** The LLM-seeded action variants (`role` + `template`). */\nexport type CollectionSeededAction = Extract<CollectionAction, { kind: \"chat\" | \"agent\" }>;\n\n/** The declarative host-write variant (`set` + optional `require`/`params`). */\nexport type CollectionMutateAction = Extract<CollectionAction, { kind: \"mutate\" }>;\n\n/** A custom (LLM-authored) HTML view for a collection. The host renders\n * `file` in a sandboxed iframe over the collection's records; the view\n * reaches its data only through a slug- and capability-scoped token (see\n * `server/api/auth/viewToken.ts`). Pure data — the host holds no\n * view-specific code; meaning lives in the HTML file + this registration.\n * See `CustomViewZ` for the per-key contracts. */\nexport type CollectionCustomView = z.infer<typeof CustomViewZ>;\n\n/** What a custom view's capability token is allowed to do against the\n * collection's data endpoint. `read` returns enriched records (getItems\n * semantics); `write` validates-and-stores rows (putItems semantics).\n * There is deliberately no `delete` — a view can never do more than the\n * agent's own `manageCollection` tool.\n *\n * TWO HOST INVARIANTS ride on this token, and both are easy to break in a\n * multi-root host:\n *\n * 1. **The token carries an OPAQUE scope, never a path.** A collection's\n * identity is `(root, slug)`, so a token minted in a multi-root host has to\n * say which root — but the token is signed, not encrypted, and is handed to\n * an LLM-authored iframe. An absolute root in the payload publishes the\n * user's home directory to that iframe. Mint an opaque project id and\n * resolve it host-side.\n * 2. **The scope goes in the TOKEN, not on `dataUrl`.** `__MC_VIEW.dataUrl` is\n * a bare base URL that views concatenate onto (`+ \"?fields=…\"`,\n * `+ \"/query\"`, `+ \"/actions/…\"`, `+ \"/image?path=…\"` — see\n * `assets/helps/custom-view.md`). A host that appends its own query\n * parameter there to carry the project breaks every one of those calls. */\nexport type CollectionViewCapability = NonNullable<CollectionCustomView[\"capabilities\"]>[number];\n\n/** How a `spawn` advances the source item's `triggerField` date to\n * produce the successor's. All arithmetic is done on the civil\n * (year, month, day) triple — never by adding milliseconds — so month\n * lengths and leap years are handled correctly. */\nexport type CollectionEvery = z.infer<typeof EveryLiteralZ>;\n\n/** Recurrence unit for a `spawn.every` advance. */\nexport type CollectionRecurUnit = CollectionEvery[\"unit\"];\n\n/** Field-driven recurrence: the advance interval is selected PER RECORD by\n * the value of an `enum` field (`fromField`), looked up in `map`. See\n * `EveryFieldDrivenZ`. */\nexport type CollectionEveryFieldDriven = z.infer<typeof EveryFieldDrivenZ>;\n\n/** The `every` of a `spawn`: either a single literal interval applied to\n * every record, or a per-record interval selected by an `enum` field. The\n * literal arm is what `advanceTriggerDate` consumes — the field-driven arm\n * is resolved down to one of its `map` values before the date math runs. */\nexport type CollectionSpawnEvery = z.infer<typeof EveryZ>;\n\n/** Narrowing guard: true when `every` is the field-driven arm. */\nexport function isFieldDrivenEvery(every: CollectionSpawnEvery): every is CollectionEveryFieldDriven {\n return \"fromField\" in every;\n}\n\n/** Host-driven recurrence. See `SpawnZ`. */\nexport type CollectionSpawn = z.infer<typeof SpawnZ>;\n\n/** One rule in a `dynamicIcon.rules` list: when the resolved source\n * record matches `where` (an AND of typed conditions, see `./where`),\n * the collection's effective launcher icon becomes `icon`. Evaluated top\n * to bottom — the first match wins. */\nexport type DynamicIconRule = z.infer<typeof DynamicIconRuleZ>;\n\n/** Where a {@link DynamicIconSpec}'s source record comes from: a (possibly\n * cross-collection) pool of records, optionally narrowed by `where` and\n * reduced to a single record by `from`. */\nexport type DynamicIconSource = z.infer<typeof DynamicIconSourceZ>;\n\n/** Declarative \"data state → icon\" mapping for a collection's launcher\n * shortcut icon (see `CollectionSchema.dynamicIcon`). When absent, the\n * launcher icon is the static `schema.icon`. */\nexport type DynamicIconSpec = z.infer<typeof DynamicIconSpecZ>;\n\n/** The `ingest` block as the schema validator accepts it — a discriminated\n * union on `kind` (declarative retrievers | agent worker). The feeds\n * subsystem's `IngestSpec` is the same union under its historical name. */\nexport type CollectionIngestSpec = z.infer<typeof IngestZ>;\n\n/** The `dataSource` block: this collection's records are the rows of an\n * external read-only data file (v1: CSV). See `DataSourceZ`. */\nexport type CollectionDataSource = z.infer<typeof DataSourceZ>;\n\n/** The `storage` block: an alternative WRITABLE record backend (v1:\n * sqlite). See `StorageZ`. */\nexport type CollectionStorage = z.infer<typeof StorageZ>;\n\n/** Every storage backend a schema can select. `file` is the implicit\n * default (`dataPath`); `csv` is implied by `dataSource`; other kinds are\n * named explicitly via `storage.type`. The server's store factory registry\n * (`server/store.ts`) is keyed by this. */\nexport type CollectionStorageKind = \"file\" | \"csv\" | \"sqlite\";\n\n/** Which storage backend serves this schema's records. Derived, not stored:\n * existing schemas carry no `storage` key and must keep resolving exactly\n * as before (`dataSource` ⇒ csv, else file). */\nexport function storageKindFor(schema: Pick<CollectionSchema, \"dataSource\" | \"storage\">): CollectionStorageKind {\n if (schema.dataSource !== undefined) return \"csv\";\n return schema.storage?.type ?? \"file\";\n}\n\n/** The whole `schema.json` contract. Key-level docs live on\n * `CollectionSchemaZ` in `./schemaZ`. */\nexport type CollectionSchema = z.infer<typeof CollectionSchemaZ>;\n\n/** True when `schema` declares an external `dataSource` — i.e. the\n * collection is READ-ONLY through every UI/tool write path (updates\n * happen by editing/replacing the data file itself). Isomorphic: both\n * the server write guards and the client's control hiding key off this\n * one predicate. */\nexport function isReadOnlySchema(schema: Pick<CollectionSchema, \"dataSource\">): boolean {\n return schema.dataSource !== undefined;\n}\n\nexport interface CollectionSummary {\n slug: string;\n title: string;\n icon: string;\n source: CollectionSource;\n /** Present (true) when the collection is backed by an external\n * `dataSource` and therefore read-only in every UI/tool write path.\n * Absent-when-writable, matching the other optional summary flags. */\n readonly?: true;\n /** Slugs of the source collection(s) a `dynamicIcon` icon was computed\n * from — present only when `schema.dynamicIcon` is set. Lets a client\n * know which collection change-channel(s) to watch for a live icon\n * update (see `useDynamicShortcutIcons`). */\n iconSources?: string[];\n}\n\nexport interface CollectionDetail extends CollectionSummary {\n schema: CollectionSchema;\n}\n\nexport type CollectionItem = Record<string, unknown>;\n\n/** Resolve an `embed` field's target record id: the fixed `id`, or the value\n * of the sibling `idField` on this record (empty string when neither applies\n * — the caller renders that as \"no record\"). Pure + isomorphic so the server\n * projection (`derive.ts`) and the client preview (`useCollectionRendering`)\n * resolve embeds identically. Non-`embed` fields resolve to \"no record\". */\nexport function embedTargetId(field: CollectionFieldSpec, record: CollectionItem | null): string {\n if (field.type !== \"embed\") return \"\";\n if (field.id) return field.id;\n if (field.idField && record) return fieldText(record[field.idField]);\n return \"\";\n}\n","// Pure slug / record-id character rules. Shared by the isomorphic schema\n// validator (`./schemaZ`) — which must stay node-free — and the server-side\n// path sanitisers (`../server/paths`), which wrap these patterns with the\n// `path.basename` round-trip CodeQL recognises as a `js/path-injection`\n// sanitiser. Both layers MUST gate on the same patterns; importing them from\n// here is what keeps them in sync.\n\n// The ONE slug pattern — `server/workspace/skills/catalog.ts` imports it\n// for its own sanitiser, so there is no second copy to keep in sync.\n// Bounded character classes, no nested quantifiers; ReDoS-safe.\nimport { fieldText } from \"./fieldText\";\nimport type { CollectionItem } from \"./schema\";\n\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_SLUG_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$/;\n\n// Record ids are a superset of slugs: they're only ever filename stems\n// (`<id>.json`), never directory names or URL segments, so they may carry\n// dots — natural keys like a Slack ts (`1718900000.123456`), a SemVer\n// (`1.2.3`), or a decimal timestamp. The interior class adds `.` to the slug\n// set; the explicit `..` reject in `isSafeRecordId` keeps a\n// parent-dir-looking segment out while still allowing repeated `-`/`_`\n// (`a--b`, `a__b`). Start/end stay alphanumeric so leading/trailing dots\n// (hidden files, the special `.`/`..` names) and `..`-only ids are all\n// excluded.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_RECORD_ID_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;\n\n/** True when `value` is a well-formed collection slug (alphanumeric /\n * hyphen / underscore, no path separators). The pattern admits no `/`,\n * `\\`, or `.`, so a passing value is trivially also a safe basename —\n * validation callers need no `path.basename` round-trip (path-building\n * callers use `../server/paths#safeSlugName`, which adds it). */\nexport function isSafeSlug(value: string): boolean {\n return typeof value === \"string\" && SAFE_SLUG_PATTERN.test(value);\n}\n\n/** True when `value` is a well-formed record id (slug charset plus interior\n * dots), with any `..` substring rejected explicitly. Validation-only\n * counterpart of `../server/paths#safeRecordId`. */\nexport function isSafeRecordId(value: string): boolean {\n if (typeof value !== \"string\" || !SAFE_RECORD_ID_PATTERN.test(value)) return false;\n return !value.includes(\"..\");\n}\n\nconst DEFAULT_UNIQUE_ID_ATTEMPTS = 8;\n\n/** Pick an id not already in `existing`, re-rolling `generate()` up to\n * `maxAttempts` times before giving up and returning the last candidate.\n * Collisions on a wide id space are astronomically unlikely, so a caller's\n * own overwrite guard is the final backstop rather than an unbounded loop. */\nexport function generateUniqueId(existing: ReadonlySet<string>, generate: () => string, maxAttempts: number = DEFAULT_UNIQUE_ID_ATTEMPTS): string {\n let candidate = generate();\n for (let attempt = 0; attempt < maxAttempts && existing.has(candidate); attempt++) {\n candidate = generate();\n }\n return candidate;\n}\n\n/** An id not already used by any loaded record: collects the in-memory primary\n * keys and re-rolls `generate()` against them (see {@link generateUniqueId}).\n * The pure core of the view's create-form id prefill. */\nexport function nextUniqueItemId(\n items: readonly CollectionItem[],\n primaryKey: string,\n generate: () => string,\n maxAttempts: number = DEFAULT_UNIQUE_ID_ATTEMPTS,\n): string {\n const existing = new Set(items.map((item) => fieldText(item[primaryKey])));\n return generateUniqueId(existing, generate, maxAttempts);\n}\n","// What a collection IS, as a value.\n//\n// Until now a collection's identity was `(root, slug)` — see the INVARIANT on\n// `CollectionHost` — and that is still exactly right for a collection that\n// lives in a directory. A SHARED collection does not: it is published to\n// Firestore under `apps/{aid}/collections/{cid}`, several machines resolve it,\n// and no one of their paths is its name. Keying it by the path it happened to\n// be published from would make the same collection two collections.\n//\n// The two identities COEXIST. A local collection's behaviour must not change at\n// all, so this is a discriminated union rather than a widening of either one:\n// every surface the INVARIANT enumerates — a cache, a pubsub channel, a view\n// token, a notification id, a rendered card — keys on this type, and the\n// compiler then refuses the thing that keeps happening by hand, which is keying\n// on the NAME alone (`slug` / `cid`) and letting two collections that share a\n// name collide.\n//\n// Isomorphic on purpose: a card and a channel name are decided on both sides of\n// the wire, so this module imports nothing from node.\n\nimport { SAFE_SLUG_PATTERN } from \"./ids\";\n\n/** A collection in a directory. `root` must already be canonical\n * (`canonicalRoot`) — it is an identity here, not a path to read, and `/proj`\n * vs `/proj/` would be two collections. Server callers should build these\n * through `localCollectionKey` in `collection/server`, which canonicalises;\n * the arm is spelled out here so the type itself stays isomorphic. */\nexport interface LocalCollectionKey {\n kind: \"local\";\n root: string;\n slug: string;\n}\n\n/** A collection published to a shared app: `apps/{aid}/collections/{cid}`.\n * `aid` is committed in the repository, so every clone resolves the same\n * collection and an invitation is about authorization, never discovery. */\nexport interface SharedCollectionKey {\n kind: \"shared\";\n aid: string;\n cid: string;\n}\n\nexport type CollectionKey = LocalCollectionKey | SharedCollectionKey;\n\nexport const isLocalCollectionKey = (key: CollectionKey): key is LocalCollectionKey => key.kind === \"local\";\nexport const isSharedCollectionKey = (key: CollectionKey): key is SharedCollectionKey => key.kind === \"shared\";\n\n/** Build a local key from an ALREADY-CANONICAL root — and refuse one that is\n * not. See {@link scopePart}. */\nexport const localCollectionKeyOf = (root: string, slug: string): LocalCollectionKey => ({\n kind: \"local\",\n root: scopePart(root, \"root\"),\n slug: namePart(slug, \"slug\"),\n});\n\n/** Build a shared key. */\nexport const sharedCollectionKey = (aid: string, cid: string): SharedCollectionKey => ({\n kind: \"shared\",\n aid: namePart(aid, \"aid\"),\n cid: namePart(cid, \"cid\"),\n});\n\n/** The collection's NAME within its scope: the slug, or the shared `cid`.\n *\n * This is what a schema file, a URL segment and a label are keyed by, and it\n * is deliberately NOT enough to identify a collection — that is the whole\n * point of the union. Use it to look things up INSIDE a known scope, never as\n * a map key across scopes. */\nexport const collectionKeyName = (key: CollectionKey): string => (key.kind === \"local\" ? key.slug : key.cid);\n\n// NUL separates the parts: it cannot occur in a path, a slug, an app id or a\n// collection id, so the encoding is unambiguous and needs no escaping.\nconst SEP = \"\\u0000\";\n\n/** A ROOT: any non-empty string that can be encoded. A path's charset is the\n * filesystem's, so the only thing to require is that it survives the encoding.\n *\n * \"NUL cannot occur in a path\" is true of every real value and is the reason\n * the encoding needs no escaping — but a type whose whole job is to be an\n * identity must not take the claim on trust. Without this, `(\"a\\0b\", \"c\")`\n * and `(\"a\", \"b\\0c\")` encode to the SAME string, so `sameCollectionKey` calls\n * two different collections equal and the id parses back to nothing. Empty is\n * refused for the same reason: it makes the id ambiguous about which part was\n * missing.\n *\n * A throw, where `parseCollectionKeyId` returns null: building a key is code\n * making an identity, and a bad one there is a programming error. Parsing is\n * reading something off a disk or a wire, where an unrecognised entry is a\n * thing to skip. */\nfunction scopePart(value: string, field: string): string {\n if (value.length === 0) throw new Error(`CollectionKey: ${field} must not be empty`);\n if (value.includes(SEP)) throw new Error(`CollectionKey: ${field} must not contain NUL`);\n if (!isCanonicalRootShape(value)) throw new Error(`CollectionKey: ${field} \"${value}\" is not a canonical root`);\n return value;\n}\n\n/** Is this root ALREADY in the shape `canonicalRoot` (path.resolve) produces?\n *\n * This module cannot canonicalise — that needs `node:path` and this file is\n * isomorphic — so it does the other half: it REFUSES anything that is not\n * already canonical. Which is the part that matters, because the failure is\n * silent. `/work/proj/` and `/work/proj` are the same collection, and a key\n * built from the first compares unequal to a key built from the second: two\n * cache entries, two channels, two bells for one collection — exactly the\n * identity split this type exists to remove. A decoder reading ids off a disk\n * is where such a spelling arrives.\n *\n * The properties are `path.resolve`'s own: absolute, no `.` or `..` segment,\n * no doubled separator, no trailing one. The Windows drive form is allowed so\n * a canonical root there is not refused. */\nfunction isCanonicalRootShape(root: string): boolean {\n const windows = /^[A-Za-z]:\\\\/.test(root);\n const sep = windows ? \"\\\\\" : \"/\";\n if (!windows && !root.startsWith(\"/\")) return false;\n if (root.length > 1 && root.endsWith(sep)) return false;\n if (root.includes(sep + sep)) return false;\n return !root.split(sep).some((segment) => segment === \".\" || segment === \"..\");\n}\n\n/** A NAME — a slug, a shared `cid`, or an `aid`: the collection-slug charset,\n * `[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?`.\n *\n * THIS TYPE IS THE SINGLE SOURCE OF TRUTH for what a name may be, and that is\n * the point rather than a nicety. A name is re-encoded by every downstream\n * identity — the completion-bell id (`<scope>\\0<name>:<itemId>`, split at the\n * first colon), a pubsub channel (`collection:app/<aid>/<name>`), a cache key\n * — and each of those has a different character it cannot survive. With the\n * rule stated only downstream, the layers disagree: a cid of `sales:2026`\n * builds fine, then the bell id decodes as a DIFFERENT collection and the\n * channel name throws inside a publisher whose catch swallows it, so the live\n * update simply stops arriving. One rule here makes every encoding safe by\n * construction; the checks downstream stay as belt-and-braces for callers that\n * never went through a key.\n *\n * A local slug is already `safeSlugName`-validated upstream, so this changes\n * nothing for it. A shared `aid` / `cid` had no gate at all — they are\n * Firestore document ids under `apps/{aid}/collections/{cid}` AND the name the\n * same collection has on disk, so the slug charset is what they already are. */\nfunction namePart(value: string, field: string): string {\n if (!isValidCollectionName(value)) throw new Error(`CollectionKey: ${field} \"${value}\" is not a valid collection name`);\n return value;\n}\n\n/** The name rule as a predicate, for the encoders that take RAW strings rather\n * than a key (the completion-bell id, a channel name). They are reachable by a\n * caller that never built a key, and each has its own delimiter to be broken\n * by, so they need to apply the same rule — not a rule of their own, which is\n * how the layers came to disagree in the first place. */\nexport function isValidCollectionName(value: string): boolean {\n return SAFE_SLUG_PATTERN.test(value);\n}\n\n/** A stable string form, for the places that need a primitive key: a Map, a\n * pubsub channel name, a notification id, a card's reconciliation key.\n *\n * Round-trips through {@link parseCollectionKeyId}. The `kind` is written\n * first so a local key and a shared key can never collide however their parts\n * are spelled. */\nexport const collectionKeyId = (key: CollectionKey): string =>\n key.kind === \"local\" ? `local${SEP}${key.root}${SEP}${key.slug}` : `shared${SEP}${key.aid}${SEP}${key.cid}`;\n\n/** Decode a {@link collectionKeyId}, or `null` when the string did not come\n * from one — or carries values no key may hold.\n *\n * Decoding goes THROUGH the constructors. Building the union here directly\n * would let a string off a disk or a wire mint an identity the constructors\n * refuse: `shared\\0salon\\0sales:2026` would become a key whose name the\n * completion-bell id and the pubsub channel cannot represent, and the single\n * source of truth for a name would have a back door.\n *\n * Null rather than a throw, and a throw from a constructor caught here: these\n * strings are read back from storage, where an unrecognised or stale entry is\n * a thing to skip, not a crash.\n *\n * A non-canonical root is refused here too, for the same reason: `/work/proj/`\n * and `/work/proj` name one collection, and two keys that compare unequal are\n * two cache entries, two channels and two bells for it. This module cannot\n * canonicalise (that needs `node:path`), so it rejects instead — see\n * {@link scopePart}. */\nexport function parseCollectionKeyId(encoded: string): CollectionKey | null {\n const parts = encoded.split(SEP);\n if (parts.length !== 3) return null;\n const [kind, first, second] = parts;\n if (kind === undefined || first === undefined || second === undefined) return null;\n try {\n if (kind === \"local\") return localCollectionKeyOf(first, second);\n if (kind === \"shared\") return sharedCollectionKey(first, second);\n } catch {\n return null;\n }\n return null;\n}\n\n/** Do two keys name the same collection? */\nexport const sameCollectionKey = (one: CollectionKey, other: CollectionKey): boolean => collectionKeyId(one) === collectionKeyId(other);\n","// Pure, deterministic helpers for the collection calendar view: parse\n// `date`-field values, build a month grid, and bucket records onto the\n// days they cover. No `Date.now()` / `new Date()` (argless) here — every\n// function takes its inputs explicitly so the logic is unit-testable\n// without faking the clock. All internal arithmetic runs in UTC (which\n// has no DST), so fixed 86_400_000 ms steps never skip or double a day.\n\nconst MS_PER_DAY = 86_400_000;\nconst ISO_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n// A two-digit field (hours / minutes / seconds) of a clock value.\nconst TWO_DIGIT_RE = /^\\d{2}$/;\n// A single clock token inside a free-form `time` string field (e.g. the\n// \"14:00-17:00\" / \"17:00-\" / \"16:30\" / \"終日\" shapes seen in user data).\nconst CLOCK_RE = /(\\d{1,2}):(\\d{2})/g;\n// Range separators we tolerate between two clock tokens: ASCII hyphen, en/em\n// dash, tilde, and the Japanese wave dashes.\nconst RANGE_SEP_RE = /[-–—~〜~]/;\n\n/** Minutes in a full day — the timeline's vertical extent. */\nexport const MINUTES_PER_DAY = 1440;\n\n/** A civil date triple. `month` is 1-12 (NOT the 0-based `Date` month). */\nexport interface Ymd {\n year: number;\n month: number;\n day: number;\n}\n\n/** One cell of the 6×7 month grid. */\nexport interface DayCell {\n ymd: Ymd;\n /** False for the leading/trailing days that belong to the adjacent\n * month (rendered greyed). */\n inMonth: boolean;\n /** Canonical `YYYY-MM-DD` key for this cell. */\n key: string;\n}\n\n/** A record placed on the calendar: the inclusive `[start, end]` span of\n * days it covers. `end === start` for a single-day record. `startMin` /\n * `endMin` are minutes-of-day for the time-allocation (day) view, resolved\n * from either a `datetime` field's clock or a separate time-string field.\n * `null` means \"no clock\" — `startMin === null && endMin === null` is an\n * all-day record; a non-null `startMin` with a null `endMin` is a\n * point-in-time record (rendered as a single line). */\nexport interface RecordSpan<T> {\n item: T;\n start: Ymd;\n end: Ymd;\n startMin: number | null;\n endMin: number | null;\n}\n\nfunction pad2(value: number): string {\n return String(value).padStart(2, \"0\");\n}\n\n/** Canonical `YYYY-MM-DD` string for a civil date. */\nexport function ymdKey(ymd: Ymd): string {\n return `${String(ymd.year).padStart(4, \"0\")}-${pad2(ymd.month)}-${pad2(ymd.day)}`;\n}\n\n/** Strictly parse a `YYYY-MM-DD` string into a civil date, rejecting\n * anything that isn't a real calendar day (e.g. `2026-02-30`, `2026-13-01`).\n * Returns null for non-strings and malformed values so callers can route\n * records with no usable date into the \"no date\" tray rather than crash. */\nexport function parseIsoDate(value: unknown): Ymd | null {\n if (typeof value !== \"string\") return null;\n const match = ISO_DATE_RE.exec(value.trim());\n if (!match) return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n // Round-trip through a UTC Date to reject impossible days: a value the\n // Date constructor rolls over (Feb 30 → Mar 2) won't match back.\n const probe = new Date(Date.UTC(year, month - 1, day));\n if (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) return null;\n return { year, month, day };\n}\n\n/** Minutes-of-day for an `HH:MM` pair, or null when out of range. */\nfunction clockToMinutes(hours: number, minutes: number): number | null {\n if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;\n return hours * 60 + minutes;\n}\n\n/** Strictly parse a `YYYY-MM-DDTHH:MM` (optional `:SS`) datetime into its\n * civil date and minutes-of-day. Returns null for anything that isn't a real\n * calendar day or a valid 24h clock. */\nexport function parseIsoDateTime(value: unknown): { ymd: Ymd; minutes: number } | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n const tIndex = trimmed.indexOf(\"T\");\n if (tIndex === -1) return null;\n const ymd = parseIsoDate(trimmed.slice(0, tIndex));\n if (!ymd) return null;\n // `HH:MM` with an optional `:SS` the browser appends for non-zero seconds.\n const parts = trimmed.slice(tIndex + 1).split(\":\");\n if (parts.length < 2 || parts.length > 3 || !parts.every((part) => TWO_DIGIT_RE.test(part))) return null;\n const minutes = clockToMinutes(Number(parts[0]), Number(parts[1]));\n if (minutes === null) return null;\n return { ymd, minutes };\n}\n\n/** Civil date from either a `YYYY-MM-DD` or a `YYYY-MM-DDTHH:MM` value, so the\n * month grid buckets date-only and datetime anchors alike. */\nexport function dateOf(value: unknown): Ymd | null {\n return parseIsoDate(value) ?? parseIsoDateTime(value)?.ymd ?? null;\n}\n\n/** Minutes-of-day from a datetime value, or null for date-only / invalid. */\nfunction timeOf(value: unknown): number | null {\n return parseIsoDateTime(value)?.minutes ?? null;\n}\n\n/** Parse a free-form time-string field into start/end minutes-of-day.\n * Handles the common shapes in user data:\n * \"14:00-17:00\" → { start: 840, end: 1020 } (range → block)\n * \"17:00-\" → { start: 1020, end: null } (open end → single line)\n * \"16:30\" → { start: 990, end: null } (point in time → single line)\n * \"終日\" / \"\" → null (no clock → all-day)\n * Returns null when no clock token is parseable. */\nexport function parseTimeRange(value: unknown): { startMin: number | null; endMin: number | null } | null {\n if (typeof value !== \"string\") return null;\n const text = value.trim();\n if (!text) return null;\n const tokens = [...text.matchAll(CLOCK_RE)];\n if (tokens.length === 0) return null;\n const minutesOf = (match: RegExpMatchArray): number | null => clockToMinutes(Number(match[1]), Number(match[2]));\n // No separator → a single point in time (start only).\n if (!RANGE_SEP_RE.test(text)) {\n const [firstToken] = tokens;\n const startMin = firstToken ? minutesOf(firstToken) : null;\n return startMin === null ? null : { startMin, endMin: null };\n }\n // Separator present → assign each token to the side of the first separator.\n const sepIndex = text.search(RANGE_SEP_RE);\n let startMin: number | null = null;\n let endMin: number | null = null;\n for (const token of tokens) {\n if ((token.index ?? 0) < sepIndex) startMin = minutesOf(token);\n else endMin = minutesOf(token);\n }\n // A start-less range (\"-09:00\") has no anchor on the timeline → treat as\n // unparseable so the record falls back to the all-day strip.\n if (startMin === null) return null;\n return { startMin, endMin };\n}\n\nfunction ymdToUtcMs(ymd: Ymd): number {\n return Date.UTC(ymd.year, ymd.month - 1, ymd.day);\n}\n\nfunction utcMsToYmd(epochMs: number): Ymd {\n const date = new Date(epochMs);\n return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };\n}\n\n/** Chronological comparison: negative if `left` precedes `right`, 0 if the\n * same day, positive if after. */\nexport function compareYmd(left: Ymd, right: Ymd): number {\n return ymdToUtcMs(left) - ymdToUtcMs(right);\n}\n\n/** True iff `day` falls within the inclusive span `[span.start, span.end]`. */\nexport function spanCoversDay<T>(span: RecordSpan<T>, day: Ymd): boolean {\n return compareYmd(span.start, day) <= 0 && compareYmd(day, span.end) <= 0;\n}\n\n/** Build the 6×7 (42-cell) grid for the given month, including the\n * leading/trailing days of the adjacent months so every week is full.\n * `month` is 1-12. `weekStartsOn` is 0 (Sunday) … 6 (Saturday). */\nexport function buildMonthGrid(year: number, month: number, weekStartsOn = 0): DayCell[] {\n const firstWeekday = new Date(Date.UTC(year, month - 1, 1)).getUTCDay();\n const lead = (firstWeekday - weekStartsOn + 7) % 7;\n const startMs = Date.UTC(year, month - 1, 1) - lead * MS_PER_DAY;\n const cells: DayCell[] = [];\n for (let i = 0; i < 42; i++) {\n const ymd = utcMsToYmd(startMs + i * MS_PER_DAY);\n cells.push({ ymd, inMonth: ymd.year === year && ymd.month === month, key: ymdKey(ymd) });\n }\n return cells;\n}\n\n/** Resolve a record's calendar span from its date/datetime fields. Returns\n * null when the anchor date is missing/invalid (→ the caller's \"no date\"\n * tray). An end date that is missing, invalid, or earlier than the start\n * collapses to a single-day span — never an inverted range.\n *\n * Times for the day (time-allocation) view come from, in priority order:\n * 1. the clock on a `datetime` anchor/end value, else\n * 2. `timeField` — a separate free-form time-string column (e.g. \"14:00-17:00\").\n * A record with no resolvable clock has `startMin === endMin === null`. */\nexport function recordSpan<T extends Record<string, unknown>>(item: T, anchorField: string, endField?: string, timeField?: string): RecordSpan<T> | null {\n const startRaw = item[anchorField];\n const start = dateOf(startRaw);\n if (!start) return null;\n let end = start;\n let startMin = timeOf(startRaw);\n let endMin: number | null = null;\n if (endField) {\n const endRaw = item[endField];\n const parsedEnd = dateOf(endRaw);\n if (parsedEnd && compareYmd(parsedEnd, start) >= 0) {\n end = parsedEnd;\n endMin = timeOf(endRaw);\n }\n }\n // Fall back to a separate time-string field only when the date fields\n // carried no clock (the date-only anchor + `time` column shape).\n if (timeField && startMin === null && endMin === null) {\n const range = parseTimeRange(item[timeField]);\n if (range) {\n ({ startMin, endMin } = range);\n }\n }\n return { item, start, end, startMin, endMin };\n}\n\n/** Split records into those that land on the calendar (with their spans)\n * and those with no usable anchor date (the \"no date\" tray). Spans are\n * sorted by start day so same-day stacking is stable across renders. */\nexport function bucketRecords<T extends Record<string, unknown>>(\n items: readonly T[],\n anchorField: string,\n endField?: string,\n timeField?: string,\n): { spans: RecordSpan<T>[]; noDate: T[] } {\n const spans: RecordSpan<T>[] = [];\n const noDate: T[] = [];\n for (const item of items) {\n const span = recordSpan(item, anchorField, endField, timeField);\n if (span) spans.push(span);\n else noDate.push(item);\n }\n spans.sort((left, right) => compareYmd(left.start, right.start));\n return { spans, noDate };\n}\n\n/** Geometry for one record on one day of the time-allocation view.\n * `kind`:\n * \"allDay\" — no clock anywhere → render in the bottom all-day strip.\n * \"line\" — a single point in time → a 1px marker at `startMin`.\n * \"block\" — a [startMin, endMin) span, clamped to this day's [0, 1440).\n * `bleedsBefore` / `bleedsAfter` flag a multi-day span that began on an\n * earlier day or continues onto a later one (so the view can show arrows). */\nexport interface DaySlice {\n kind: \"allDay\" | \"line\" | \"block\";\n startMin: number;\n endMin: number;\n bleedsBefore: boolean;\n bleedsAfter: boolean;\n}\n\n/** Project a record's span onto a single day for the time-allocation view, or\n * null when the span doesn't cover that day. */\nexport function daySlice<T>(span: RecordSpan<T>, day: Ymd): DaySlice | null {\n if (!spanCoversDay(span, day)) return null;\n // Destructured so the `!== null` tests narrow the clocks where they are used;\n // reading them back off `span` each time would not.\n const { startMin: spanStart, endMin: spanEnd } = span;\n if (spanStart === null && spanEnd === null) {\n return { kind: \"allDay\", startMin: 0, endMin: MINUTES_PER_DAY, bleedsBefore: false, bleedsAfter: false };\n }\n const singleDay = compareYmd(span.start, span.end) === 0;\n const isStartDay = compareYmd(day, span.start) === 0;\n const isEndDay = compareYmd(day, span.end) === 0;\n // A point in time: a start clock with no end, all on one day.\n if (singleDay && spanStart !== null && spanEnd === null) {\n return { kind: \"line\", startMin: spanStart, endMin: spanStart, bleedsBefore: false, bleedsAfter: false };\n }\n const startMin = isStartDay && spanStart !== null ? spanStart : 0;\n const endMin = isEndDay && spanEnd !== null ? spanEnd : MINUTES_PER_DAY;\n // Zero-length or inverted same-day range → degrade to a line.\n if (singleDay && endMin <= startMin) {\n return { kind: \"line\", startMin, endMin: startMin, bleedsBefore: false, bleedsAfter: false };\n }\n return { kind: \"block\", startMin, endMin, bleedsBefore: !isStartDay, bleedsAfter: !isEndDay };\n}\n\n/** Side-by-side lane assignment for overlapping timeline blocks. Each input\n * is an `[startMin, endMin)` interval; the result (parallel to the input)\n * gives each item its `lane` (column index) and the `lanes` total of its\n * overlap cluster, so a renderer can size every block to `1 / lanes` width\n * and offset it by `lane / lanes`. Non-overlapping items get `lanes === 1`. */\nexport interface LaneSpan {\n startMin: number;\n endMin: number;\n}\nexport interface LaneAssignment {\n lane: number;\n lanes: number;\n}\n\n/** One input block paired with its position in the caller's array, so lane\n * assignment can sort freely and still report back in input order. */\ninterface PositionedSpan {\n index: number;\n span: LaneSpan;\n}\n\nfunction sortByStart(blocks: readonly LaneSpan[]): PositionedSpan[] {\n return [...blocks.entries()]\n .map(([index, span]) => ({ index, span }))\n .sort((left, right) => left.span.startMin - right.span.startMin || left.span.endMin - right.span.endMin);\n}\n\ninterface ClusterState {\n /** Clusters already closed. */\n done: PositionedSpan[][];\n /** The cluster still accepting blocks. */\n current: PositionedSpan[];\n /** Latest end minute seen in `current` — the cutoff for the next block. */\n end: number;\n}\n\n/** Cut the start-ordered blocks into overlap clusters: a new cluster begins at\n * the first block that starts at or after every earlier block has ended. */\nfunction splitClusters(ordered: readonly PositionedSpan[]): PositionedSpan[][] {\n // Appends into the accumulator's arrays rather than rebuilding them. The\n // spread form read well but copied both arrays on every block, so a day\n // whose blocks all overlap cost O(n²) allocations to lay out (#2765).\n const initial: ClusterState = { done: [], current: [], end: Number.NEGATIVE_INFINITY };\n const state = ordered.reduce<ClusterState>((acc, block) => {\n if (acc.current.length > 0 && block.span.startMin >= acc.end) {\n acc.done.push(acc.current);\n return { done: acc.done, current: [block], end: block.span.endMin };\n }\n acc.current.push(block);\n return { done: acc.done, current: acc.current, end: Math.max(acc.end, block.span.endMin) };\n }, initial);\n if (state.current.length > 0) state.done.push(state.current);\n return state.done;\n}\n\n/** Greedy lane packing inside one cluster: reuse the first lane already free at\n * this block's start, else open a new one. Every member reports the cluster's\n * final lane count so a renderer can size each block to `1 / lanes`. */\nfunction packCluster(cluster: readonly PositionedSpan[]): [number, LaneAssignment][] {\n const laneEnds: number[] = [];\n const placed = cluster.map(({ index, span }) => {\n const reusable = laneEnds.findIndex((end) => end <= span.startMin);\n const lane = reusable === -1 ? laneEnds.length : reusable;\n laneEnds[lane] = span.endMin;\n return { index, lane };\n });\n return placed.map(({ index, lane }) => [index, { lane, lanes: laneEnds.length }]);\n}\n\nexport function assignLanes(blocks: readonly LaneSpan[]): LaneAssignment[] {\n const clusters = splitClusters(sortByStart(blocks));\n const assignments = new Map<number, LaneAssignment>(clusters.flatMap(packCluster));\n return blocks.map((_, index) => assignments.get(index) ?? { lane: 0, lanes: 1 });\n}\n\n/** Month label key inputs — returns the 1st of the month as a `Date` so the\n * component can feed it to `Intl.DateTimeFormat(locale, …)` for a localized\n * \"April 2026\" header without this module taking a locale dependency. */\nexport function monthAnchorDate(year: number, month: number): Date {\n return new Date(Date.UTC(year, month - 1, 1));\n}\n"],"mappings":";;;AAeA,IAAM,cAAc,UAClB,OAAO,UAAU,Y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AM,OAAO,SAAS;CAAO,CAAC,CAAC;AAClF;AAEA,SAAgB,YAAY,QAA+C;CACzE,MAAM,WAAW,cAAc,YAAY,MAAM,CAAC;CAClD,MAAM,cAAc,IAAI,IAA4B,SAAS,QAAQ,WAAW,CAAC;CACjF,OAAO,OAAO,KAAK,GAAG,UAAU,YAAY,IAAI,KAAK,KAAK;EAAE,MAAM;EAAG,OAAO;CAAE,CAAC;AACjF;;;;AAKA,SAAgB,gBAAgB,MAAc,OAAqB;CACjE,OAAO,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,CAAC,CAAC;AAC9C"}
1
+ {"version":3,"file":"calendarGrid-DGILaVxI.cjs","names":[],"sources":["../src/collection/core/fieldText.ts","../src/collection/core/schema.ts","../src/collection/core/ids.ts","../src/collection/core/collectionKey.ts","../src/collection/core/calendarGrid.ts"],"sourcesContent":["// Turning a record field into text.\n//\n// `CollectionItem` is `Record<string, unknown>`, so a field holds whatever the\n// record's JSON had — including arrays and objects (real workspace data has\n// plenty: weather `hourly`, GeoJSON `geometry`, `sites` lists). Bare\n// `String(value)` on one of those yields `\"[object Object]\"`, which then gets\n// compared, matched or displayed as if it were a value. Nothing throws; a\n// predicate just silently stops matching, or the UI shows `[object Object]`.\n//\n// These two helpers are the only sanctioned way to read a field as text. The\n// rule they encode was already in `itemLabelOf`: accept primitives, let\n// everything else fall through to the caller's fallback.\n\n/** A field value that has a meaningful text form. Dates are included because\n * a JSON record can carry one once it has been revived. */\nconst isTextable = (value: unknown): value is string | number | boolean | Date =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || value instanceof Date;\n\n/** The field's text, or `null` when it has no meaningful one (absent, or an\n * array/object that would stringify to `\"[object Object]\"`).\n *\n * Returning `null` rather than `\"\"` keeps \"the field is empty\" distinct from\n * \"the field can't be text\" — a matcher must not treat an object-valued field\n * as an empty string and match `\"\"`. */\nexport function fieldTextOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (!isTextable(value)) return null;\n if (value instanceof Date) {\n // `new Date(\"nonsense\")` is still `instanceof Date`, and `toISOString()`\n // throws `RangeError` on it. This helper sits on the match, sort and\n // display paths, so one unparseable date in one record would take the whole\n // render down — the loud version of the bug this module exists to prevent.\n return Number.isNaN(value.getTime()) ? null : value.toISOString();\n }\n return String(value);\n}\n\n/** The field's text, or `fallback` (default `\"\"`) when it has none. Use where\n * a string is required and an empty one is a safe stand-in — display, sort\n * keys, CSV cells. Where the distinction matters, use {@link fieldTextOrNull}. */\nexport function fieldText(value: unknown, fallback = \"\"): string {\n return fieldTextOrNull(value) ?? fallback;\n}\n","// Schema-driven collection types. A \"collection\" is a skill (under\n// .claude/skills/<slug>/) that also ships a sibling `schema.json`.\n// The host's <CollectionView> reads the schema + records and renders\n// a table/form; Claude reads SKILL.md and CRUDs the records as JSON\n// files.\n//\n// SINGLE SOURCE OF TRUTH: every type describing the schema.json contract is\n// derived (`z.infer`) from the zod definitions in `./schemaZ` — the shapes,\n// their doc comments, and the validation rules live THERE; this module only\n// re-derives the TypeScript names consumers import. The imports from\n// `./schemaZ` are type-only, so zod never reaches the browser bundle through\n// the isomorphic barrel; at runtime the dependency points the other way\n// (schemaZ imports this module's consts).\n//\n// Field specs are a DISCRIMINATED UNION on `type`: narrow with\n// `field.type === \"enum\"` (etc.) before reading a variant key like `values`,\n// `to`, `formula`, or `of`.\n\nimport { fieldText } from \"./fieldText\";\nimport type { z } from \"zod\";\nimport type {\n ActionSpecZ,\n CollectionSchemaZ,\n CustomViewZ,\n DataSourceZ,\n DynamicIconRuleZ,\n DynamicIconSourceZ,\n DynamicIconSpecZ,\n EveryFieldDrivenZ,\n EveryLiteralZ,\n EveryZ,\n FieldSpecZ,\n IngestZ,\n SpawnZ,\n StorageZ,\n SubFieldSpecZ,\n WhenZ,\n} from \"./schemaZ\";\n\n/** Minimal \"this collection is a feed\" descriptor carried on the schema.\n * Deliberately narrow — the canonical collection contract stays\n * independent of the host's feeds subsystem. The host's richer retrieval\n * spec (`IngestSpec` in `feeds/ingestTypes.ts`) is a subtype, so feed code\n * reads the extra fields by typing feed schemas with that subtype;\n * collection rendering only needs these three + the presence check. */\nexport interface CollectionIngest {\n kind: string;\n schedule: string;\n /** Optional time-of-day anchor for `schedule: \"daily\"` — the hour (0–23) to\n * refresh around (the host ticks hourly, so the run lands within that hour).\n * Ignored for non-daily schedules. Absent ⇒ elapsed-based daily (\"≥24 h since\n * the last run\"). NOTE: **UTC**, not local — compared via `getUTCHours()` for\n * an unambiguous, DST-free check (matching the rest of the scheduler), so\n * convert local times before writing (e.g. 07:00 JST → `atHour: 22`). */\n atHour?: number;\n /** Declarative retrievers (`rss`/`atom`/`http-json`) only — the host fetches\n * this URL on the schedule. Absent for `kind: \"agent\"`, where the agent owns\n * retrieval. */\n url?: string;\n /** `kind: \"agent\"` only: role id the scheduled hidden worker runs in. */\n role?: string;\n /** `kind: \"agent\"` only: skill-relative template path (under `templates/`)\n * whose prose tells the worker how to refresh the records. */\n template?: string;\n}\n\n/** Declarative retriever kinds a Feed's `ingest.kind` may declare. The host's\n * feeds engine dispatches on these; they live here (with the schema contract)\n * so the schema validator can enforce them. The host re-exports these from\n * `server/workspace/feeds/ingestTypes.ts`. */\nexport const INGEST_KINDS = [\"rss\", \"atom\", \"http-json\"] as const;\nexport type IngestKind = (typeof INGEST_KINDS)[number];\n\n/** The agent-performed ingest kind. Instead of a declarative fetch, the host\n * dispatches a hidden background chat (origin `system`) in `ingest.role`,\n * seeded with `ingest.template` + a summary of every record, on the\n * `ingest.schedule` cadence; the worker edits records via the collections io\n * layer. Kept separate from {@link INGEST_KINDS} (which the declarative\n * retriever registry keys on) so the schema validator can model `ingest` as a\n * discriminated union without the feeds engine gaining an \"agent\" retriever. */\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\n/** Refresh cadences a Feed's `ingest.schedule` may declare. */\nexport const FEED_SCHEDULES = [\"hourly\", \"daily\", \"weekly\", \"on-demand\"] as const;\nexport type FeedSchedule = (typeof FEED_SCHEDULES)[number];\n\n// \"feed\" collections live in the non-skill `<workspace>/feeds/` registry\n// and carry an `ingest` block; they reuse the same storage + rendering\n// as skill-backed collections but are never loaded into the agent prompt.\nexport type CollectionSource = \"user\" | \"project\" | \"feed\";\n\n/** One field of a record — a discriminated union on `type`; see the variant\n * docs in `./schemaZ` (`FieldSpecZ`). */\nexport type CollectionFieldSpec = z.infer<typeof FieldSpecZ>;\n\n/** A `table` field's row sub-schema entry — the field union minus `table` /\n * `derived` / display-only types (see `SubFieldSpecZ`). */\nexport type CollectionSubFieldSpec = z.infer<typeof SubFieldSpecZ>;\n\nexport type CollectionFieldType = CollectionFieldSpec[\"type\"];\n\n/** The computed-boolean variant — a `where` predicate bound to a field\n * name; see `FlagFieldZ`. */\nexport type CollectionFlagField = Extract<CollectionFieldSpec, { type: \"flag\" }>;\n\n/** derived/embed/backlinks/rollup/toggle/flag are host-computed or\n * projected — never written to the record JSON, so required / value\n * checks and edit-draft slots must not apply to them. THE single source\n * for \"computed\" — lives here (zod-free at runtime) so browser code\n * (`./draft`) and the zod record compiler (`./recordZ`, which re-exports\n * it) share one set instead of drifting copies. */\nexport const COMPUTED_TYPES: ReadonlySet<CollectionFieldType> = new Set<CollectionFieldType>([\"derived\", \"embed\", \"backlinks\", \"rollup\", \"toggle\", \"flag\"]);\n\n/** Optional visibility predicate: the target (an action button or a\n * field) renders only when the open record's `field` (stringified) is\n * one of `in`. Generic and domain-free — the host evaluates it against\n * the record with no knowledge of what the field means. Absent ⇒\n * always shown. */\nexport type CollectionWhen = z.infer<typeof WhenZ>;\n\n/** @deprecated Name retained for back-compat; use {@link CollectionWhen}.\n * Both actions and fields share the same predicate shape. No in-repo\n * consumers, but the package is public API (MulmoTerminal). */\n// eslint-disable-next-line sonarjs/redundant-type-aliases -- deliberate deprecated back-compat export\nexport type CollectionActionWhen = CollectionWhen;\n\n/** A schema-declared, per-record action rendered as a button in the\n * read-only detail view. Pure UI/behaviour directive — never stored,\n * never validated against record data. All domain specifics (label,\n * role, template — or the declarative `set`) live in the schema / skill\n * folder, so the host stays generic. A discriminated union on `kind`;\n * see `ActionSpecZ`. */\nexport type CollectionAction = z.infer<typeof ActionSpecZ>;\n\n/** The kind of work an action kicks off: `\"chat\"` (visible LLM chat),\n * `\"agent\"` (hidden LLM worker), or `\"mutate\"` (declarative host write,\n * no LLM). */\nexport type CollectionActionKind = CollectionAction[\"kind\"];\n\n/** The LLM-seeded action variants (`role` + `template`). */\nexport type CollectionSeededAction = Extract<CollectionAction, { kind: \"chat\" | \"agent\" }>;\n\n/** The declarative host-write variant (`set` + optional `require`/`params`). */\nexport type CollectionMutateAction = Extract<CollectionAction, { kind: \"mutate\" }>;\n\n/** A custom (LLM-authored) HTML view for a collection. The host renders\n * `file` in a sandboxed iframe over the collection's records; the view\n * reaches its data only through a slug- and capability-scoped token (see\n * `server/api/auth/viewToken.ts`). Pure data — the host holds no\n * view-specific code; meaning lives in the HTML file + this registration.\n * See `CustomViewZ` for the per-key contracts. */\nexport type CollectionCustomView = z.infer<typeof CustomViewZ>;\n\n/** What a custom view's capability token is allowed to do against the\n * collection's data endpoint. `read` returns enriched records (getItems\n * semantics); `write` validates-and-stores rows (putItems semantics).\n * There is deliberately no `delete` — a view can never do more than the\n * agent's own `manageCollection` tool.\n *\n * TWO HOST INVARIANTS ride on this token, and both are easy to break in a\n * multi-root host:\n *\n * 1. **The token carries an OPAQUE scope, never a path.** A collection's\n * identity is `(root, slug)`, so a token minted in a multi-root host has to\n * say which root — but the token is signed, not encrypted, and is handed to\n * an LLM-authored iframe. An absolute root in the payload publishes the\n * user's home directory to that iframe. Mint an opaque project id and\n * resolve it host-side.\n * 2. **The scope goes in the TOKEN, not on `dataUrl`.** `__MC_VIEW.dataUrl` is\n * a bare base URL that views concatenate onto (`+ \"?fields=…\"`,\n * `+ \"/query\"`, `+ \"/actions/…\"`, `+ \"/image?path=…\"` — see\n * `assets/helps/custom-view.md`). A host that appends its own query\n * parameter there to carry the project breaks every one of those calls. */\nexport type CollectionViewCapability = NonNullable<CollectionCustomView[\"capabilities\"]>[number];\n\n/** How a `spawn` advances the source item's `triggerField` date to\n * produce the successor's. All arithmetic is done on the civil\n * (year, month, day) triple — never by adding milliseconds — so month\n * lengths and leap years are handled correctly. */\nexport type CollectionEvery = z.infer<typeof EveryLiteralZ>;\n\n/** Recurrence unit for a `spawn.every` advance. */\nexport type CollectionRecurUnit = CollectionEvery[\"unit\"];\n\n/** Field-driven recurrence: the advance interval is selected PER RECORD by\n * the value of an `enum` field (`fromField`), looked up in `map`. See\n * `EveryFieldDrivenZ`. */\nexport type CollectionEveryFieldDriven = z.infer<typeof EveryFieldDrivenZ>;\n\n/** The `every` of a `spawn`: either a single literal interval applied to\n * every record, or a per-record interval selected by an `enum` field. The\n * literal arm is what `advanceTriggerDate` consumes — the field-driven arm\n * is resolved down to one of its `map` values before the date math runs. */\nexport type CollectionSpawnEvery = z.infer<typeof EveryZ>;\n\n/** Narrowing guard: true when `every` is the field-driven arm. */\nexport function isFieldDrivenEvery(every: CollectionSpawnEvery): every is CollectionEveryFieldDriven {\n return \"fromField\" in every;\n}\n\n/** Host-driven recurrence. See `SpawnZ`. */\nexport type CollectionSpawn = z.infer<typeof SpawnZ>;\n\n/** One rule in a `dynamicIcon.rules` list: when the resolved source\n * record matches `where` (an AND of typed conditions, see `./where`),\n * the collection's effective launcher icon becomes `icon`. Evaluated top\n * to bottom — the first match wins. */\nexport type DynamicIconRule = z.infer<typeof DynamicIconRuleZ>;\n\n/** Where a {@link DynamicIconSpec}'s source record comes from: a (possibly\n * cross-collection) pool of records, optionally narrowed by `where` and\n * reduced to a single record by `from`. */\nexport type DynamicIconSource = z.infer<typeof DynamicIconSourceZ>;\n\n/** Declarative \"data state → icon\" mapping for a collection's launcher\n * shortcut icon (see `CollectionSchema.dynamicIcon`). When absent, the\n * launcher icon is the static `schema.icon`. */\nexport type DynamicIconSpec = z.infer<typeof DynamicIconSpecZ>;\n\n/** The `ingest` block as the schema validator accepts it — a discriminated\n * union on `kind` (declarative retrievers | agent worker). The feeds\n * subsystem's `IngestSpec` is the same union under its historical name. */\nexport type CollectionIngestSpec = z.infer<typeof IngestZ>;\n\n/** The `dataSource` block: this collection's records are the rows of an\n * external read-only data file (v1: CSV). See `DataSourceZ`. */\nexport type CollectionDataSource = z.infer<typeof DataSourceZ>;\n\n/** The `storage` block: an alternative WRITABLE record backend (v1:\n * sqlite). See `StorageZ`. */\nexport type CollectionStorage = z.infer<typeof StorageZ>;\n\n/** Every storage backend a schema can select. `file` is the implicit\n * default (`dataPath`); `csv` is implied by `dataSource`; other kinds are\n * named explicitly via `storage.type`. The server's store factory registry\n * (`server/store.ts`) is keyed by this. */\nexport type CollectionStorageKind = \"file\" | \"csv\" | \"sqlite\" | \"firestore\";\n\n/** Which storage backend serves this schema's records. Derived, not stored:\n * existing schemas carry no `storage` key and must keep resolving exactly\n * as before (`dataSource` ⇒ csv, else file). */\nexport function storageKindFor(schema: Pick<CollectionSchema, \"dataSource\" | \"storage\">): CollectionStorageKind {\n if (schema.dataSource !== undefined) return \"csv\";\n return schema.storage?.type ?? \"file\";\n}\n\n/** The whole `schema.json` contract. Key-level docs live on\n * `CollectionSchemaZ` in `./schemaZ`. */\nexport type CollectionSchema = z.infer<typeof CollectionSchemaZ>;\n\n/** True when `schema` declares an external `dataSource` — i.e. the\n * collection is READ-ONLY through every UI/tool write path (updates\n * happen by editing/replacing the data file itself). Isomorphic: both\n * the server write guards and the client's control hiding key off this\n * one predicate. */\nexport function isReadOnlySchema(schema: Pick<CollectionSchema, \"dataSource\">): boolean {\n return schema.dataSource !== undefined;\n}\n\nexport interface CollectionSummary {\n slug: string;\n title: string;\n icon: string;\n source: CollectionSource;\n /** Present (true) when the collection is backed by an external\n * `dataSource` and therefore read-only in every UI/tool write path.\n * Absent-when-writable, matching the other optional summary flags. */\n readonly?: true;\n /** Slugs of the source collection(s) a `dynamicIcon` icon was computed\n * from — present only when `schema.dynamicIcon` is set. Lets a client\n * know which collection change-channel(s) to watch for a live icon\n * update (see `useDynamicShortcutIcons`). */\n iconSources?: string[];\n /** The app a SHARED collection belongs to — present iff the schema declares\n * `storage.type: \"firestore\"`. A client needs it to subscribe to the right\n * live-change channel: a shared collection publishes on\n * `collection:app/<aid>/<cid>`, and a subscriber that keys on the name alone\n * listens to the LOCAL channel, so the refetch never arrives. Not a secret —\n * it is committed in the repository every clone reads. */\n appId?: string;\n}\n\nexport interface CollectionDetail extends CollectionSummary {\n schema: CollectionSchema;\n}\n\nexport type CollectionItem = Record<string, unknown>;\n\n/** Resolve an `embed` field's target record id: the fixed `id`, or the value\n * of the sibling `idField` on this record (empty string when neither applies\n * — the caller renders that as \"no record\"). Pure + isomorphic so the server\n * projection (`derive.ts`) and the client preview (`useCollectionRendering`)\n * resolve embeds identically. Non-`embed` fields resolve to \"no record\". */\nexport function embedTargetId(field: CollectionFieldSpec, record: CollectionItem | null): string {\n if (field.type !== \"embed\") return \"\";\n if (field.id) return field.id;\n if (field.idField && record) return fieldText(record[field.idField]);\n return \"\";\n}\n","// Pure slug / record-id character rules. Shared by the isomorphic schema\n// validator (`./schemaZ`) — which must stay node-free — and the server-side\n// path sanitisers (`../server/paths`), which wrap these patterns with the\n// `path.basename` round-trip CodeQL recognises as a `js/path-injection`\n// sanitiser. Both layers MUST gate on the same patterns; importing them from\n// here is what keeps them in sync.\n\n// The ONE slug pattern — `server/workspace/skills/catalog.ts` imports it\n// for its own sanitiser, so there is no second copy to keep in sync.\n// Bounded character classes, no nested quantifiers; ReDoS-safe.\nimport { fieldText } from \"./fieldText\";\nimport type { CollectionItem } from \"./schema\";\n\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_SLUG_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$/;\n\n// Record ids are a superset of slugs: they're only ever filename stems\n// (`<id>.json`), never directory names or URL segments, so they may carry\n// dots — natural keys like a Slack ts (`1718900000.123456`), a SemVer\n// (`1.2.3`), or a decimal timestamp. The interior class adds `.` to the slug\n// set; the explicit `..` reject in `isSafeRecordId` keeps a\n// parent-dir-looking segment out while still allowing repeated `-`/`_`\n// (`a--b`, `a__b`). Start/end stay alphanumeric so leading/trailing dots\n// (hidden files, the special `.`/`..` names) and `..`-only ids are all\n// excluded.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_RECORD_ID_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;\n\n/** True when `value` is a well-formed collection slug (alphanumeric /\n * hyphen / underscore, no path separators). The pattern admits no `/`,\n * `\\`, or `.`, so a passing value is trivially also a safe basename —\n * validation callers need no `path.basename` round-trip (path-building\n * callers use `../server/paths#safeSlugName`, which adds it). */\nexport function isSafeSlug(value: string): boolean {\n return typeof value === \"string\" && SAFE_SLUG_PATTERN.test(value);\n}\n\n/** True when `value` is a well-formed record id (slug charset plus interior\n * dots), with any `..` substring rejected explicitly. Validation-only\n * counterpart of `../server/paths#safeRecordId`. */\nexport function isSafeRecordId(value: string): boolean {\n if (typeof value !== \"string\" || !SAFE_RECORD_ID_PATTERN.test(value)) return false;\n return !value.includes(\"..\");\n}\n\nconst DEFAULT_UNIQUE_ID_ATTEMPTS = 8;\n\n/** Pick an id not already in `existing`, re-rolling `generate()` up to\n * `maxAttempts` times before giving up and returning the last candidate.\n * Collisions on a wide id space are astronomically unlikely, so a caller's\n * own overwrite guard is the final backstop rather than an unbounded loop. */\nexport function generateUniqueId(existing: ReadonlySet<string>, generate: () => string, maxAttempts: number = DEFAULT_UNIQUE_ID_ATTEMPTS): string {\n let candidate = generate();\n for (let attempt = 0; attempt < maxAttempts && existing.has(candidate); attempt++) {\n candidate = generate();\n }\n return candidate;\n}\n\n/** An id not already used by any loaded record: collects the in-memory primary\n * keys and re-rolls `generate()` against them (see {@link generateUniqueId}).\n * The pure core of the view's create-form id prefill. */\nexport function nextUniqueItemId(\n items: readonly CollectionItem[],\n primaryKey: string,\n generate: () => string,\n maxAttempts: number = DEFAULT_UNIQUE_ID_ATTEMPTS,\n): string {\n const existing = new Set(items.map((item) => fieldText(item[primaryKey])));\n return generateUniqueId(existing, generate, maxAttempts);\n}\n","// What a collection IS, as a value.\n//\n// Until now a collection's identity was `(root, slug)` — see the INVARIANT on\n// `CollectionHost` — and that is still exactly right for a collection that\n// lives in a directory. A SHARED collection does not: it is published to\n// Firestore under `apps/{aid}/collections/{cid}`, several machines resolve it,\n// and no one of their paths is its name. Keying it by the path it happened to\n// be published from would make the same collection two collections.\n//\n// The two identities COEXIST. A local collection's behaviour must not change at\n// all, so this is a discriminated union rather than a widening of either one:\n// every surface the INVARIANT enumerates — a cache, a pubsub channel, a view\n// token, a notification id, a rendered card — keys on this type, and the\n// compiler then refuses the thing that keeps happening by hand, which is keying\n// on the NAME alone (`slug` / `cid`) and letting two collections that share a\n// name collide.\n//\n// Isomorphic on purpose: a card and a channel name are decided on both sides of\n// the wire, so this module imports nothing from node.\n\nimport { SAFE_SLUG_PATTERN } from \"./ids\";\n\n/** A collection in a directory. `root` must already be canonical\n * (`canonicalRoot`) — it is an identity here, not a path to read, and `/proj`\n * vs `/proj/` would be two collections. Server callers should build these\n * through `localCollectionKey` in `collection/server`, which canonicalises;\n * the arm is spelled out here so the type itself stays isomorphic. */\nexport interface LocalCollectionKey {\n kind: \"local\";\n root: string;\n slug: string;\n}\n\n/** A collection published to a shared app: `apps/{aid}/collections/{cid}`.\n * `aid` is committed in the repository, so every clone resolves the same\n * collection and an invitation is about authorization, never discovery. */\nexport interface SharedCollectionKey {\n kind: \"shared\";\n aid: string;\n cid: string;\n}\n\nexport type CollectionKey = LocalCollectionKey | SharedCollectionKey;\n\nexport const isLocalCollectionKey = (key: CollectionKey): key is LocalCollectionKey => key.kind === \"local\";\nexport const isSharedCollectionKey = (key: CollectionKey): key is SharedCollectionKey => key.kind === \"shared\";\n\n/** Build a local key from an ALREADY-CANONICAL root — and refuse one that is\n * not. See {@link scopePart}. */\nexport const localCollectionKeyOf = (root: string, slug: string): LocalCollectionKey => ({\n kind: \"local\",\n root: scopePart(root, \"root\"),\n slug: namePart(slug, \"slug\"),\n});\n\n/** Build a shared key. */\nexport const sharedCollectionKey = (aid: string, cid: string): SharedCollectionKey => ({\n kind: \"shared\",\n aid: namePart(aid, \"aid\"),\n cid: namePart(cid, \"cid\"),\n});\n\n/** The collection's NAME within its scope: the slug, or the shared `cid`.\n *\n * This is what a schema file, a URL segment and a label are keyed by, and it\n * is deliberately NOT enough to identify a collection — that is the whole\n * point of the union. Use it to look things up INSIDE a known scope, never as\n * a map key across scopes. */\nexport const collectionKeyName = (key: CollectionKey): string => (key.kind === \"local\" ? key.slug : key.cid);\n\n// NUL separates the parts: it cannot occur in a path, a slug, an app id or a\n// collection id, so the encoding is unambiguous and needs no escaping.\nconst SEP = \"\\u0000\";\n\n/** A ROOT: any non-empty string that can be encoded. A path's charset is the\n * filesystem's, so the only thing to require is that it survives the encoding.\n *\n * \"NUL cannot occur in a path\" is true of every real value and is the reason\n * the encoding needs no escaping — but a type whose whole job is to be an\n * identity must not take the claim on trust. Without this, `(\"a\\0b\", \"c\")`\n * and `(\"a\", \"b\\0c\")` encode to the SAME string, so `sameCollectionKey` calls\n * two different collections equal and the id parses back to nothing. Empty is\n * refused for the same reason: it makes the id ambiguous about which part was\n * missing.\n *\n * A throw, where `parseCollectionKeyId` returns null: building a key is code\n * making an identity, and a bad one there is a programming error. Parsing is\n * reading something off a disk or a wire, where an unrecognised entry is a\n * thing to skip. */\nfunction scopePart(value: string, field: string): string {\n if (value.length === 0) throw new Error(`CollectionKey: ${field} must not be empty`);\n if (value.includes(SEP)) throw new Error(`CollectionKey: ${field} must not contain NUL`);\n if (!isCanonicalRootShape(value)) throw new Error(`CollectionKey: ${field} \"${value}\" is not a canonical root`);\n return value;\n}\n\n/** Is this root ALREADY in the shape `canonicalRoot` (path.resolve) produces?\n *\n * This module cannot canonicalise — that needs `node:path` and this file is\n * isomorphic — so it does the other half: it REFUSES anything that is not\n * already canonical. Which is the part that matters, because the failure is\n * silent. `/work/proj/` and `/work/proj` are the same collection, and a key\n * built from the first compares unequal to a key built from the second: two\n * cache entries, two channels, two bells for one collection — exactly the\n * identity split this type exists to remove. A decoder reading ids off a disk\n * is where such a spelling arrives.\n *\n * The properties are `path.resolve`'s own: absolute, no `.` or `..` segment,\n * no doubled separator, no trailing one. The Windows drive form is allowed so\n * a canonical root there is not refused. */\nfunction isCanonicalRootShape(root: string): boolean {\n const windows = /^[A-Za-z]:\\\\/.test(root);\n const sep = windows ? \"\\\\\" : \"/\";\n if (!windows && !root.startsWith(\"/\")) return false;\n if (root.length > 1 && root.endsWith(sep)) return false;\n if (root.includes(sep + sep)) return false;\n return !root.split(sep).some((segment) => segment === \".\" || segment === \"..\");\n}\n\n/** A NAME — a slug, a shared `cid`, or an `aid`: the collection-slug charset,\n * `[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?`.\n *\n * THIS TYPE IS THE SINGLE SOURCE OF TRUTH for what a name may be, and that is\n * the point rather than a nicety. A name is re-encoded by every downstream\n * identity — the completion-bell id (`<scope>\\0<name>:<itemId>`, split at the\n * first colon), a pubsub channel (`collection:app/<aid>/<name>`), a cache key\n * — and each of those has a different character it cannot survive. With the\n * rule stated only downstream, the layers disagree: a cid of `sales:2026`\n * builds fine, then the bell id decodes as a DIFFERENT collection and the\n * channel name throws inside a publisher whose catch swallows it, so the live\n * update simply stops arriving. One rule here makes every encoding safe by\n * construction; the checks downstream stay as belt-and-braces for callers that\n * never went through a key.\n *\n * A local slug is already `safeSlugName`-validated upstream, so this changes\n * nothing for it. A shared `aid` / `cid` had no gate at all — they are\n * Firestore document ids under `apps/{aid}/collections/{cid}` AND the name the\n * same collection has on disk, so the slug charset is what they already are. */\nfunction namePart(value: string, field: string): string {\n if (!isValidCollectionName(value)) throw new Error(`CollectionKey: ${field} \"${value}\" is not a valid collection name`);\n return value;\n}\n\n/** The name rule as a predicate, for the encoders that take RAW strings rather\n * than a key (the completion-bell id, a channel name). They are reachable by a\n * caller that never built a key, and each has its own delimiter to be broken\n * by, so they need to apply the same rule — not a rule of their own, which is\n * how the layers came to disagree in the first place. */\nexport function isValidCollectionName(value: string): boolean {\n return SAFE_SLUG_PATTERN.test(value);\n}\n\n/** A stable string form, for the places that need a primitive key: a Map, a\n * pubsub channel name, a notification id, a card's reconciliation key.\n *\n * Round-trips through {@link parseCollectionKeyId}. The `kind` is written\n * first so a local key and a shared key can never collide however their parts\n * are spelled. */\nexport const collectionKeyId = (key: CollectionKey): string =>\n key.kind === \"local\" ? `local${SEP}${key.root}${SEP}${key.slug}` : `shared${SEP}${key.aid}${SEP}${key.cid}`;\n\n/** Decode a {@link collectionKeyId}, or `null` when the string did not come\n * from one — or carries values no key may hold.\n *\n * Decoding goes THROUGH the constructors. Building the union here directly\n * would let a string off a disk or a wire mint an identity the constructors\n * refuse: `shared\\0salon\\0sales:2026` would become a key whose name the\n * completion-bell id and the pubsub channel cannot represent, and the single\n * source of truth for a name would have a back door.\n *\n * Null rather than a throw, and a throw from a constructor caught here: these\n * strings are read back from storage, where an unrecognised or stale entry is\n * a thing to skip, not a crash.\n *\n * A non-canonical root is refused here too, for the same reason: `/work/proj/`\n * and `/work/proj` name one collection, and two keys that compare unequal are\n * two cache entries, two channels and two bells for it. This module cannot\n * canonicalise (that needs `node:path`), so it rejects instead — see\n * {@link scopePart}. */\nexport function parseCollectionKeyId(encoded: string): CollectionKey | null {\n const parts = encoded.split(SEP);\n if (parts.length !== 3) return null;\n const [kind, first, second] = parts;\n if (kind === undefined || first === undefined || second === undefined) return null;\n try {\n if (kind === \"local\") return localCollectionKeyOf(first, second);\n if (kind === \"shared\") return sharedCollectionKey(first, second);\n } catch {\n return null;\n }\n return null;\n}\n\n/** Do two keys name the same collection? */\nexport const sameCollectionKey = (one: CollectionKey, other: CollectionKey): boolean => collectionKeyId(one) === collectionKeyId(other);\n","// Pure, deterministic helpers for the collection calendar view: parse\n// `date`-field values, build a month grid, and bucket records onto the\n// days they cover. No `Date.now()` / `new Date()` (argless) here — every\n// function takes its inputs explicitly so the logic is unit-testable\n// without faking the clock. All internal arithmetic runs in UTC (which\n// has no DST), so fixed 86_400_000 ms steps never skip or double a day.\n\nconst MS_PER_DAY = 86_400_000;\nconst ISO_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n// A two-digit field (hours / minutes / seconds) of a clock value.\nconst TWO_DIGIT_RE = /^\\d{2}$/;\n// A single clock token inside a free-form `time` string field (e.g. the\n// \"14:00-17:00\" / \"17:00-\" / \"16:30\" / \"終日\" shapes seen in user data).\nconst CLOCK_RE = /(\\d{1,2}):(\\d{2})/g;\n// Range separators we tolerate between two clock tokens: ASCII hyphen, en/em\n// dash, tilde, and the Japanese wave dashes.\nconst RANGE_SEP_RE = /[-–—~〜~]/;\n\n/** Minutes in a full day — the timeline's vertical extent. */\nexport const MINUTES_PER_DAY = 1440;\n\n/** A civil date triple. `month` is 1-12 (NOT the 0-based `Date` month). */\nexport interface Ymd {\n year: number;\n month: number;\n day: number;\n}\n\n/** One cell of the 6×7 month grid. */\nexport interface DayCell {\n ymd: Ymd;\n /** False for the leading/trailing days that belong to the adjacent\n * month (rendered greyed). */\n inMonth: boolean;\n /** Canonical `YYYY-MM-DD` key for this cell. */\n key: string;\n}\n\n/** A record placed on the calendar: the inclusive `[start, end]` span of\n * days it covers. `end === start` for a single-day record. `startMin` /\n * `endMin` are minutes-of-day for the time-allocation (day) view, resolved\n * from either a `datetime` field's clock or a separate time-string field.\n * `null` means \"no clock\" — `startMin === null && endMin === null` is an\n * all-day record; a non-null `startMin` with a null `endMin` is a\n * point-in-time record (rendered as a single line). */\nexport interface RecordSpan<T> {\n item: T;\n start: Ymd;\n end: Ymd;\n startMin: number | null;\n endMin: number | null;\n}\n\nfunction pad2(value: number): string {\n return String(value).padStart(2, \"0\");\n}\n\n/** Canonical `YYYY-MM-DD` string for a civil date. */\nexport function ymdKey(ymd: Ymd): string {\n return `${String(ymd.year).padStart(4, \"0\")}-${pad2(ymd.month)}-${pad2(ymd.day)}`;\n}\n\n/** Strictly parse a `YYYY-MM-DD` string into a civil date, rejecting\n * anything that isn't a real calendar day (e.g. `2026-02-30`, `2026-13-01`).\n * Returns null for non-strings and malformed values so callers can route\n * records with no usable date into the \"no date\" tray rather than crash. */\nexport function parseIsoDate(value: unknown): Ymd | null {\n if (typeof value !== \"string\") return null;\n const match = ISO_DATE_RE.exec(value.trim());\n if (!match) return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n // Round-trip through a UTC Date to reject impossible days: a value the\n // Date constructor rolls over (Feb 30 → Mar 2) won't match back.\n const probe = new Date(Date.UTC(year, month - 1, day));\n if (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) return null;\n return { year, month, day };\n}\n\n/** Minutes-of-day for an `HH:MM` pair, or null when out of range. */\nfunction clockToMinutes(hours: number, minutes: number): number | null {\n if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;\n return hours * 60 + minutes;\n}\n\n/** Strictly parse a `YYYY-MM-DDTHH:MM` (optional `:SS`) datetime into its\n * civil date and minutes-of-day. Returns null for anything that isn't a real\n * calendar day or a valid 24h clock. */\nexport function parseIsoDateTime(value: unknown): { ymd: Ymd; minutes: number } | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n const tIndex = trimmed.indexOf(\"T\");\n if (tIndex === -1) return null;\n const ymd = parseIsoDate(trimmed.slice(0, tIndex));\n if (!ymd) return null;\n // `HH:MM` with an optional `:SS` the browser appends for non-zero seconds.\n const parts = trimmed.slice(tIndex + 1).split(\":\");\n if (parts.length < 2 || parts.length > 3 || !parts.every((part) => TWO_DIGIT_RE.test(part))) return null;\n const minutes = clockToMinutes(Number(parts[0]), Number(parts[1]));\n if (minutes === null) return null;\n return { ymd, minutes };\n}\n\n/** Civil date from either a `YYYY-MM-DD` or a `YYYY-MM-DDTHH:MM` value, so the\n * month grid buckets date-only and datetime anchors alike. */\nexport function dateOf(value: unknown): Ymd | null {\n return parseIsoDate(value) ?? parseIsoDateTime(value)?.ymd ?? null;\n}\n\n/** Minutes-of-day from a datetime value, or null for date-only / invalid. */\nfunction timeOf(value: unknown): number | null {\n return parseIsoDateTime(value)?.minutes ?? null;\n}\n\n/** Parse a free-form time-string field into start/end minutes-of-day.\n * Handles the common shapes in user data:\n * \"14:00-17:00\" → { start: 840, end: 1020 } (range → block)\n * \"17:00-\" → { start: 1020, end: null } (open end → single line)\n * \"16:30\" → { start: 990, end: null } (point in time → single line)\n * \"終日\" / \"\" → null (no clock → all-day)\n * Returns null when no clock token is parseable. */\nexport function parseTimeRange(value: unknown): { startMin: number | null; endMin: number | null } | null {\n if (typeof value !== \"string\") return null;\n const text = value.trim();\n if (!text) return null;\n const tokens = [...text.matchAll(CLOCK_RE)];\n if (tokens.length === 0) return null;\n const minutesOf = (match: RegExpMatchArray): number | null => clockToMinutes(Number(match[1]), Number(match[2]));\n // No separator → a single point in time (start only).\n if (!RANGE_SEP_RE.test(text)) {\n const [firstToken] = tokens;\n const startMin = firstToken ? minutesOf(firstToken) : null;\n return startMin === null ? null : { startMin, endMin: null };\n }\n // Separator present → assign each token to the side of the first separator.\n const sepIndex = text.search(RANGE_SEP_RE);\n let startMin: number | null = null;\n let endMin: number | null = null;\n for (const token of tokens) {\n if ((token.index ?? 0) < sepIndex) startMin = minutesOf(token);\n else endMin = minutesOf(token);\n }\n // A start-less range (\"-09:00\") has no anchor on the timeline → treat as\n // unparseable so the record falls back to the all-day strip.\n if (startMin === null) return null;\n return { startMin, endMin };\n}\n\nfunction ymdToUtcMs(ymd: Ymd): number {\n return Date.UTC(ymd.year, ymd.month - 1, ymd.day);\n}\n\nfunction utcMsToYmd(epochMs: number): Ymd {\n const date = new Date(epochMs);\n return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };\n}\n\n/** Chronological comparison: negative if `left` precedes `right`, 0 if the\n * same day, positive if after. */\nexport function compareYmd(left: Ymd, right: Ymd): number {\n return ymdToUtcMs(left) - ymdToUtcMs(right);\n}\n\n/** True iff `day` falls within the inclusive span `[span.start, span.end]`. */\nexport function spanCoversDay<T>(span: RecordSpan<T>, day: Ymd): boolean {\n return compareYmd(span.start, day) <= 0 && compareYmd(day, span.end) <= 0;\n}\n\n/** Build the 6×7 (42-cell) grid for the given month, including the\n * leading/trailing days of the adjacent months so every week is full.\n * `month` is 1-12. `weekStartsOn` is 0 (Sunday) … 6 (Saturday). */\nexport function buildMonthGrid(year: number, month: number, weekStartsOn = 0): DayCell[] {\n const firstWeekday = new Date(Date.UTC(year, month - 1, 1)).getUTCDay();\n const lead = (firstWeekday - weekStartsOn + 7) % 7;\n const startMs = Date.UTC(year, month - 1, 1) - lead * MS_PER_DAY;\n const cells: DayCell[] = [];\n for (let i = 0; i < 42; i++) {\n const ymd = utcMsToYmd(startMs + i * MS_PER_DAY);\n cells.push({ ymd, inMonth: ymd.year === year && ymd.month === month, key: ymdKey(ymd) });\n }\n return cells;\n}\n\n/** Resolve a record's calendar span from its date/datetime fields. Returns\n * null when the anchor date is missing/invalid (→ the caller's \"no date\"\n * tray). An end date that is missing, invalid, or earlier than the start\n * collapses to a single-day span — never an inverted range.\n *\n * Times for the day (time-allocation) view come from, in priority order:\n * 1. the clock on a `datetime` anchor/end value, else\n * 2. `timeField` — a separate free-form time-string column (e.g. \"14:00-17:00\").\n * A record with no resolvable clock has `startMin === endMin === null`. */\nexport function recordSpan<T extends Record<string, unknown>>(item: T, anchorField: string, endField?: string, timeField?: string): RecordSpan<T> | null {\n const startRaw = item[anchorField];\n const start = dateOf(startRaw);\n if (!start) return null;\n let end = start;\n let startMin = timeOf(startRaw);\n let endMin: number | null = null;\n if (endField) {\n const endRaw = item[endField];\n const parsedEnd = dateOf(endRaw);\n if (parsedEnd && compareYmd(parsedEnd, start) >= 0) {\n end = parsedEnd;\n endMin = timeOf(endRaw);\n }\n }\n // Fall back to a separate time-string field only when the date fields\n // carried no clock (the date-only anchor + `time` column shape).\n if (timeField && startMin === null && endMin === null) {\n const range = parseTimeRange(item[timeField]);\n if (range) {\n ({ startMin, endMin } = range);\n }\n }\n return { item, start, end, startMin, endMin };\n}\n\n/** Split records into those that land on the calendar (with their spans)\n * and those with no usable anchor date (the \"no date\" tray). Spans are\n * sorted by start day so same-day stacking is stable across renders. */\nexport function bucketRecords<T extends Record<string, unknown>>(\n items: readonly T[],\n anchorField: string,\n endField?: string,\n timeField?: string,\n): { spans: RecordSpan<T>[]; noDate: T[] } {\n const spans: RecordSpan<T>[] = [];\n const noDate: T[] = [];\n for (const item of items) {\n const span = recordSpan(item, anchorField, endField, timeField);\n if (span) spans.push(span);\n else noDate.push(item);\n }\n spans.sort((left, right) => compareYmd(left.start, right.start));\n return { spans, noDate };\n}\n\n/** Geometry for one record on one day of the time-allocation view.\n * `kind`:\n * \"allDay\" — no clock anywhere → render in the bottom all-day strip.\n * \"line\" — a single point in time → a 1px marker at `startMin`.\n * \"block\" — a [startMin, endMin) span, clamped to this day's [0, 1440).\n * `bleedsBefore` / `bleedsAfter` flag a multi-day span that began on an\n * earlier day or continues onto a later one (so the view can show arrows). */\nexport interface DaySlice {\n kind: \"allDay\" | \"line\" | \"block\";\n startMin: number;\n endMin: number;\n bleedsBefore: boolean;\n bleedsAfter: boolean;\n}\n\n/** Project a record's span onto a single day for the time-allocation view, or\n * null when the span doesn't cover that day. */\nexport function daySlice<T>(span: RecordSpan<T>, day: Ymd): DaySlice | null {\n if (!spanCoversDay(span, day)) return null;\n // Destructured so the `!== null` tests narrow the clocks where they are used;\n // reading them back off `span` each time would not.\n const { startMin: spanStart, endMin: spanEnd } = span;\n if (spanStart === null && spanEnd === null) {\n return { kind: \"allDay\", startMin: 0, endMin: MINUTES_PER_DAY, bleedsBefore: false, bleedsAfter: false };\n }\n const singleDay = compareYmd(span.start, span.end) === 0;\n const isStartDay = compareYmd(day, span.start) === 0;\n const isEndDay = compareYmd(day, span.end) === 0;\n // A point in time: a start clock with no end, all on one day.\n if (singleDay && spanStart !== null && spanEnd === null) {\n return { kind: \"line\", startMin: spanStart, endMin: spanStart, bleedsBefore: false, bleedsAfter: false };\n }\n const startMin = isStartDay && spanStart !== null ? spanStart : 0;\n const endMin = isEndDay && spanEnd !== null ? spanEnd : MINUTES_PER_DAY;\n // Zero-length or inverted same-day range → degrade to a line.\n if (singleDay && endMin <= startMin) {\n return { kind: \"line\", startMin, endMin: startMin, bleedsBefore: false, bleedsAfter: false };\n }\n return { kind: \"block\", startMin, endMin, bleedsBefore: !isStartDay, bleedsAfter: !isEndDay };\n}\n\n/** Side-by-side lane assignment for overlapping timeline blocks. Each input\n * is an `[startMin, endMin)` interval; the result (parallel to the input)\n * gives each item its `lane` (column index) and the `lanes` total of its\n * overlap cluster, so a renderer can size every block to `1 / lanes` width\n * and offset it by `lane / lanes`. Non-overlapping items get `lanes === 1`. */\nexport interface LaneSpan {\n startMin: number;\n endMin: number;\n}\nexport interface LaneAssignment {\n lane: number;\n lanes: number;\n}\n\n/** One input block paired with its position in the caller's array, so lane\n * assignment can sort freely and still report back in input order. */\ninterface PositionedSpan {\n index: number;\n span: LaneSpan;\n}\n\nfunction sortByStart(blocks: readonly LaneSpan[]): PositionedSpan[] {\n return [...blocks.entries()]\n .map(([index, span]) => ({ index, span }))\n .sort((left, right) => left.span.startMin - right.span.startMin || left.span.endMin - right.span.endMin);\n}\n\ninterface ClusterState {\n /** Clusters already closed. */\n done: PositionedSpan[][];\n /** The cluster still accepting blocks. */\n current: PositionedSpan[];\n /** Latest end minute seen in `current` — the cutoff for the next block. */\n end: number;\n}\n\n/** Cut the start-ordered blocks into overlap clusters: a new cluster begins at\n * the first block that starts at or after every earlier block has ended. */\nfunction splitClusters(ordered: readonly PositionedSpan[]): PositionedSpan[][] {\n // Appends into the accumulator's arrays rather than rebuilding them. The\n // spread form read well but copied both arrays on every block, so a day\n // whose blocks all overlap cost O(n²) allocations to lay out (#2765).\n const initial: ClusterState = { done: [], current: [], end: Number.NEGATIVE_INFINITY };\n const state = ordered.reduce<ClusterState>((acc, block) => {\n if (acc.current.length > 0 && block.span.startMin >= acc.end) {\n acc.done.push(acc.current);\n return { done: acc.done, current: [block], end: block.span.endMin };\n }\n acc.current.push(block);\n return { done: acc.done, current: acc.current, end: Math.max(acc.end, block.span.endMin) };\n }, initial);\n if (state.current.length > 0) state.done.push(state.current);\n return state.done;\n}\n\n/** Greedy lane packing inside one cluster: reuse the first lane already free at\n * this block's start, else open a new one. Every member reports the cluster's\n * final lane count so a renderer can size each block to `1 / lanes`. */\nfunction packCluster(cluster: readonly PositionedSpan[]): [number, LaneAssignment][] {\n const laneEnds: number[] = [];\n const placed = cluster.map(({ index, span }) => {\n const reusable = laneEnds.findIndex((end) => end <= span.startMin);\n const lane = reusable === -1 ? laneEnds.length : reusable;\n laneEnds[lane] = span.endMin;\n return { index, lane };\n });\n return placed.map(({ index, lane }) => [index, { lane, lanes: laneEnds.length }]);\n}\n\nexport function assignLanes(blocks: readonly LaneSpan[]): LaneAssignment[] {\n const clusters = splitClusters(sortByStart(blocks));\n const assignments = new Map<number, LaneAssignment>(clusters.flatMap(packCluster));\n return blocks.map((_, index) => assignments.get(index) ?? { lane: 0, lanes: 1 });\n}\n\n/** Month label key inputs — returns the 1st of the month as a `Date` so the\n * component can feed it to `Intl.DateTimeFormat(locale, …)` for a localized\n * \"April 2026\" header without this module taking a locale dependency. */\nexport function monthAnchorDate(year: number, month: number): Date {\n return new Date(Date.UTC(year, month - 1, 1));\n}\n"],"mappings":";;;AAeA,IAAM,cAAc,UAClB,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,iBAAiB;;;;;;;AAQ3G,SAAgB,gBAAgB,OAA+B;CAC7D,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,IAAI,CAAC,WAAW,KAAK,GAAG,OAAO;C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O,KAAK,GAAG,UAAU,YAAY,IAAI,KAAK,KAAK;EAAE,MAAM;EAAG,OAAO;CAAE,CAAC;AACjF;;;;AAKA,SAAgB,gBAAgB,MAAc,OAAqB;CACjE,OAAO,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,CAAC,CAAC;AAC9C"}
@@ -168,7 +168,7 @@ export type CollectionStorage = z.infer<typeof StorageZ>;
168
168
  * default (`dataPath`); `csv` is implied by `dataSource`; other kinds are
169
169
  * named explicitly via `storage.type`. The server's store factory registry
170
170
  * (`server/store.ts`) is keyed by this. */
171
- export type CollectionStorageKind = "file" | "csv" | "sqlite";
171
+ export type CollectionStorageKind = "file" | "csv" | "sqlite" | "firestore";
172
172
  /** Which storage backend serves this schema's records. Derived, not stored:
173
173
  * existing schemas carry no `storage` key and must keep resolving exactly
174
174
  * as before (`dataSource` ⇒ csv, else file). */
@@ -196,6 +196,13 @@ export interface CollectionSummary {
196
196
  * know which collection change-channel(s) to watch for a live icon
197
197
  * update (see `useDynamicShortcutIcons`). */
198
198
  iconSources?: string[];
199
+ /** The app a SHARED collection belongs to — present iff the schema declares
200
+ * `storage.type: "firestore"`. A client needs it to subscribe to the right
201
+ * live-change channel: a shared collection publishes on
202
+ * `collection:app/<aid>/<cid>`, and a subscriber that keys on the name alone
203
+ * listens to the LOCAL channel, so the refetch never arrives. Not a secret —
204
+ * it is committed in the repository every clone reads. */
205
+ appId?: string;
199
206
  }
200
207
  export interface CollectionDetail extends CollectionSummary {
201
208
  schema: CollectionSchema;
@@ -59,9 +59,9 @@ export declare const SubFieldSpecZ: z.ZodDiscriminatedUnion<[z.ZodObject<{
59
59
  string: "string";
60
60
  number: "number";
61
61
  boolean: "boolean";
62
+ date: "date";
62
63
  text: "text";
63
64
  email: "email";
64
- date: "date";
65
65
  datetime: "datetime";
66
66
  markdown: "markdown";
67
67
  }>;
@@ -94,13 +94,13 @@ export declare const FieldSpecZ: z.ZodDiscriminatedUnion<[z.ZodObject<{
94
94
  string: "string";
95
95
  number: "number";
96
96
  boolean: "boolean";
97
+ date: "date";
98
+ file: "file";
97
99
  text: "text";
98
100
  email: "email";
99
- date: "date";
100
101
  datetime: "datetime";
101
102
  markdown: "markdown";
102
103
  image: "image";
103
- file: "file";
104
104
  }>;
105
105
  }, z.core.$strip>, z.ZodObject<{
106
106
  to: z.ZodString;
@@ -141,9 +141,9 @@ export declare const FieldSpecZ: z.ZodDiscriminatedUnion<[z.ZodObject<{
141
141
  string: "string";
142
142
  number: "number";
143
143
  boolean: "boolean";
144
+ date: "date";
144
145
  text: "text";
145
146
  email: "email";
146
- date: "date";
147
147
  datetime: "datetime";
148
148
  markdown: "markdown";
149
149
  }>;
@@ -308,9 +308,9 @@ export declare const ActionSpecZ: z.ZodDiscriminatedUnion<[z.ZodObject<{
308
308
  string: "string";
309
309
  number: "number";
310
310
  boolean: "boolean";
311
+ date: "date";
311
312
  text: "text";
312
313
  email: "email";
313
- date: "date";
314
314
  datetime: "datetime";
315
315
  markdown: "markdown";
316
316
  }>;
@@ -672,15 +672,21 @@ export declare const DataSourceZ: z.ZodObject<{
672
672
  /** Alternative WRITABLE storage backend for a collection's records —
673
673
  * unlike `dataSource` (external read-only file), a `storage` collection
674
674
  * behaves like a normal writable collection; only where the rows live
675
- * changes. v1: `sqlite` — records in a single SQLite database file
676
- * (`node:sqlite`, one JSON record per row keyed by the primaryKey).
677
- * `path` is workspace-relative and containment-checked exactly like
678
- * `dataPath`. The store factory registry (`server/store.ts`) picks the
679
- * implementation by `type` (plans/done/refactor-storage-virtualization.md). */
680
- export declare const StorageZ: z.ZodObject<{
675
+ * changes. The store factory registry (`server/store.ts`) picks the
676
+ * implementation by `type` (plans/done/refactor-storage-virtualization.md).
677
+ *
678
+ * A discriminated union rather than one shape with optional keys, because
679
+ * only the sqlite variant is a workspace FILE: its `path` is
680
+ * workspace-relative and containment-checked exactly like `dataPath`, while
681
+ * the firestore variant has no path to check — its records are not on this
682
+ * machine at all. Optional keys would let each arm accept the other's, and
683
+ * the compiler would stop being the thing that tells you which. */
684
+ export declare const StorageZ: z.ZodDiscriminatedUnion<[z.ZodObject<{
681
685
  type: z.ZodLiteral<"sqlite">;
682
686
  path: z.ZodString;
683
- }, z.core.$strip>;
687
+ }, z.core.$strip>, z.ZodObject<{
688
+ type: z.ZodLiteral<"firestore">;
689
+ }, z.core.$strict>], "type">;
684
690
  /** The schema's SHAPE, before any cross-field rule runs. Named so the rules in
685
691
  * `./schemaRules` can type their argument against it — they receive whatever
686
692
  * this parses to, and nothing narrower. */
@@ -692,10 +698,12 @@ declare const CollectionObjectZ: z.ZodObject<{
692
698
  type: z.ZodLiteral<"csv">;
693
699
  path: z.ZodString;
694
700
  }, z.core.$strip>>;
695
- storage: z.ZodOptional<z.ZodObject<{
701
+ storage: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
696
702
  type: z.ZodLiteral<"sqlite">;
697
703
  path: z.ZodString;
698
- }, z.core.$strip>>;
704
+ }, z.core.$strip>, z.ZodObject<{
705
+ type: z.ZodLiteral<"firestore">;
706
+ }, z.core.$strict>], "type">>;
699
707
  primaryKey: z.ZodString;
700
708
  singleton: z.ZodOptional<z.ZodString>;
701
709
  fields: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -710,13 +718,13 @@ declare const CollectionObjectZ: z.ZodObject<{
710
718
  string: "string";
711
719
  number: "number";
712
720
  boolean: "boolean";
721
+ date: "date";
722
+ file: "file";
713
723
  text: "text";
714
724
  email: "email";
715
- date: "date";
716
725
  datetime: "datetime";
717
726
  markdown: "markdown";
718
727
  image: "image";
719
- file: "file";
720
728
  }>;
721
729
  }, z.core.$strip>, z.ZodObject<{
722
730
  to: z.ZodString;
@@ -757,9 +765,9 @@ declare const CollectionObjectZ: z.ZodObject<{
757
765
  string: "string";
758
766
  number: "number";
759
767
  boolean: "boolean";
768
+ date: "date";
760
769
  text: "text";
761
770
  email: "email";
762
- date: "date";
763
771
  datetime: "datetime";
764
772
  markdown: "markdown";
765
773
  }>;
@@ -920,9 +928,9 @@ declare const CollectionObjectZ: z.ZodObject<{
920
928
  string: "string";
921
929
  number: "number";
922
930
  boolean: "boolean";
931
+ date: "date";
923
932
  text: "text";
924
933
  email: "email";
925
- date: "date";
926
934
  datetime: "datetime";
927
935
  markdown: "markdown";
928
936
  }>;
@@ -975,9 +983,9 @@ declare const CollectionObjectZ: z.ZodObject<{
975
983
  string: "string";
976
984
  number: "number";
977
985
  boolean: "boolean";
986
+ date: "date";
978
987
  text: "text";
979
988
  email: "email";
980
- date: "date";
981
989
  datetime: "datetime";
982
990
  markdown: "markdown";
983
991
  }>;
@@ -1171,10 +1179,12 @@ export declare const CollectionSchemaZ: z.ZodPreprocess<z.ZodObject<{
1171
1179
  type: z.ZodLiteral<"csv">;
1172
1180
  path: z.ZodString;
1173
1181
  }, z.core.$strip>>;
1174
- storage: z.ZodOptional<z.ZodObject<{
1182
+ storage: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
1175
1183
  type: z.ZodLiteral<"sqlite">;
1176
1184
  path: z.ZodString;
1177
- }, z.core.$strip>>;
1185
+ }, z.core.$strip>, z.ZodObject<{
1186
+ type: z.ZodLiteral<"firestore">;
1187
+ }, z.core.$strict>], "type">>;
1178
1188
  primaryKey: z.ZodString;
1179
1189
  singleton: z.ZodOptional<z.ZodString>;
1180
1190
  fields: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
@@ -1189,13 +1199,13 @@ export declare const CollectionSchemaZ: z.ZodPreprocess<z.ZodObject<{
1189
1199
  string: "string";
1190
1200
  number: "number";
1191
1201
  boolean: "boolean";
1202
+ date: "date";
1203
+ file: "file";
1192
1204
  text: "text";
1193
1205
  email: "email";
1194
- date: "date";
1195
1206
  datetime: "datetime";
1196
1207
  markdown: "markdown";
1197
1208
  image: "image";
1198
- file: "file";
1199
1209
  }>;
1200
1210
  }, z.core.$strip>, z.ZodObject<{
1201
1211
  to: z.ZodString;
@@ -1236,9 +1246,9 @@ export declare const CollectionSchemaZ: z.ZodPreprocess<z.ZodObject<{
1236
1246
  string: "string";
1237
1247
  number: "number";
1238
1248
  boolean: "boolean";
1249
+ date: "date";
1239
1250
  text: "text";
1240
1251
  email: "email";
1241
- date: "date";
1242
1252
  datetime: "datetime";
1243
1253
  markdown: "markdown";
1244
1254
  }>;
@@ -1399,9 +1409,9 @@ export declare const CollectionSchemaZ: z.ZodPreprocess<z.ZodObject<{
1399
1409
  string: "string";
1400
1410
  number: "number";
1401
1411
  boolean: "boolean";
1412
+ date: "date";
1402
1413
  text: "text";
1403
1414
  email: "email";
1404
- date: "date";
1405
1415
  datetime: "datetime";
1406
1416
  markdown: "markdown";
1407
1417
  }>;
@@ -1454,9 +1464,9 @@ export declare const CollectionSchemaZ: z.ZodPreprocess<z.ZodObject<{
1454
1464
  string: "string";
1455
1465
  number: "number";
1456
1466
  boolean: "boolean";
1467
+ date: "date";
1457
1468
  text: "text";
1458
1469
  email: "email";
1459
- date: "date";
1460
1470
  datetime: "datetime";
1461
1471
  markdown: "markdown";
1462
1472
  }>;
@@ -0,0 +1,51 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let firebase_firestore = require("firebase/firestore");
3
+ //#region src/collection/server/firestoreDocs.ts
4
+ /** The real implementation over the modular SDK.
5
+ *
6
+ * THE RECORD IS THE DOCUMENT. Its fields are written at the top level, not
7
+ * nested under a `data` key. This is not a matter of taste: the deployed
8
+ * security rules read `request.resource.data.<field>` and
9
+ * `resource.data[submit.emailField]` — a wrapper would put every field one
10
+ * level down, so the required-field checks, the status state machine and the
11
+ * "your own row" predicate would all read absent values and fail closed. A
12
+ * shared record's shape is part of the authorization contract.
13
+ *
14
+ * `orderBy("__name__")` orders by DOCUMENT ID. Ordering by a record field
15
+ * would silently EXCLUDE documents missing that field (the trap
16
+ * `remote-host/server/hostRunner.ts:158-169` documents), turning a read into a
17
+ * partial one; the document id is always present and gives the stable order
18
+ * the store contract requires. */
19
+ function createFirestoreDocs(database) {
20
+ return {
21
+ list: async (collectionPath) => {
22
+ return (await (0, firebase_firestore.getDocs)((0, firebase_firestore.query)((0, firebase_firestore.collection)(database, collectionPath), (0, firebase_firestore.orderBy)("__name__")))).docs.map((entry) => ({
23
+ id: entry.id,
24
+ data: entry.data()
25
+ }));
26
+ },
27
+ get: async (collectionPath, docId) => {
28
+ const snapshot = await (0, firebase_firestore.getDoc)((0, firebase_firestore.doc)(database, collectionPath, docId));
29
+ return snapshot.exists() ? snapshot.data() : null;
30
+ },
31
+ set: async (collectionPath, docId, data) => {
32
+ await (0, firebase_firestore.setDoc)((0, firebase_firestore.doc)(database, collectionPath, docId), data);
33
+ },
34
+ create: (collectionPath, docId, data) => (0, firebase_firestore.runTransaction)(database, async (transaction) => {
35
+ const ref = (0, firebase_firestore.doc)(database, collectionPath, docId);
36
+ if ((await transaction.get(ref)).exists()) return false;
37
+ transaction.set(ref, data);
38
+ return true;
39
+ }),
40
+ delete: (collectionPath, docId) => (0, firebase_firestore.runTransaction)(database, async (transaction) => {
41
+ const ref = (0, firebase_firestore.doc)(database, collectionPath, docId);
42
+ if (!(await transaction.get(ref)).exists()) return false;
43
+ transaction.delete(ref);
44
+ return true;
45
+ })
46
+ };
47
+ }
48
+ //#endregion
49
+ exports.createFirestoreDocs = createFirestoreDocs;
50
+
51
+ //# sourceMappingURL=firestore.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"firestore.cjs","names":[],"sources":["../../src/collection/server/firestoreDocs.ts"],"sourcesContent":["// The seam between the firestore store and the Firestore SDK.\n//\n// The modular SDK is function-based (`getDocs(query(collection(db, …)))`), so a\n// store that imported those functions directly could not be tested without a\n// real backend — a fake `db` would still be handed to the real functions.\n// Narrowing to this interface makes the backend swappable: core ships\n// `createFirestoreDocs` over the real SDK, and the tests inject an in-memory\n// fake that satisfies the same shape. That is what lets this repository's tests\n// run with no API key and no network.\n//\n// Deliberately minimal and id-keyed: no query builder, no field ordering, no\n// cursors. Everything the store needs is \"the documents of one collection path,\n// ordered by document id\" — see the store header for why field ordering is\n// avoided entirely.\n//\n// The collection path is an ARGUMENT, not something this module composes. It\n// owns the SDK calls; `firestoreStore` owns where the documents live.\n\nimport {\n collection as firestoreCollection,\n doc,\n getDoc,\n getDocs,\n orderBy,\n query as firestoreQuery,\n runTransaction,\n setDoc,\n type Firestore,\n} from \"firebase/firestore\";\n\n/** One stored record document. `data` is the document's own fields — the\n * record itself, not a wrapper around it; see `set` below. The store\n * validates its shape, because a document written by hand could be\n * anything. */\nexport interface FirestoreDoc {\n id: string;\n data: unknown;\n}\n\nexport interface FirestoreDocs {\n /** Every document under `collectionPath`, ordered by document id. */\n list: (collectionPath: string) => Promise<FirestoreDoc[]>;\n /** One document's fields, or null when it doesn't exist. */\n get: (collectionPath: string, docId: string) => Promise<unknown | null>;\n /** Create or replace. */\n set: (collectionPath: string, docId: string, data: Record<string, unknown>) => Promise<void>;\n /** Create only. Returns false when the id already exists — atomic, so two\n * concurrent creates can't both observe \"missing\". */\n create: (collectionPath: string, docId: string, data: Record<string, unknown>) => Promise<boolean>;\n /** Delete. Returns false when the id didn't exist, so a caller can tell a\n * real delete from a typo'd id. */\n delete: (collectionPath: string, docId: string) => Promise<boolean>;\n}\n\n/** The real implementation over the modular SDK.\n *\n * THE RECORD IS THE DOCUMENT. Its fields are written at the top level, not\n * nested under a `data` key. This is not a matter of taste: the deployed\n * security rules read `request.resource.data.<field>` and\n * `resource.data[submit.emailField]` — a wrapper would put every field one\n * level down, so the required-field checks, the status state machine and the\n * \"your own row\" predicate would all read absent values and fail closed. A\n * shared record's shape is part of the authorization contract.\n *\n * `orderBy(\"__name__\")` orders by DOCUMENT ID. Ordering by a record field\n * would silently EXCLUDE documents missing that field (the trap\n * `remote-host/server/hostRunner.ts:158-169` documents), turning a read into a\n * partial one; the document id is always present and gives the stable order\n * the store contract requires. */\nexport function createFirestoreDocs(database: Firestore): FirestoreDocs {\n return {\n list: async (collectionPath) => {\n const snapshot = await getDocs(firestoreQuery(firestoreCollection(database, collectionPath), orderBy(\"__name__\")));\n return snapshot.docs.map((entry) => ({ id: entry.id, data: entry.data() }));\n },\n get: async (collectionPath, docId) => {\n const snapshot = await getDoc(doc(database, collectionPath, docId));\n return snapshot.exists() ? snapshot.data() : null;\n },\n set: async (collectionPath, docId, data) => {\n await setDoc(doc(database, collectionPath, docId), data);\n },\n create: (collectionPath, docId, data) =>\n runTransaction(database, async (transaction) => {\n const ref = doc(database, collectionPath, docId);\n const existing = await transaction.get(ref);\n if (existing.exists()) return false;\n transaction.set(ref, data);\n return true;\n }),\n // Firestore's deleteDoc succeeds on a missing document, so an existence\n // check is what makes \"deleted\" distinguishable from \"there was nothing\".\n // It runs INSIDE the transaction (like `create`): a plain get-then-delete\n // would report `true` for a document a concurrent client had already\n // removed, i.e. claim a delete this call never performed.\n delete: (collectionPath, docId) =>\n runTransaction(database, async (transaction) => {\n const ref = doc(database, collectionPath, docId);\n const existing = await transaction.get(ref);\n if (!existing.exists()) return false;\n transaction.delete(ref);\n return true;\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqEA,SAAgB,oBAAoB,UAAoC;CACtE,OAAO;EACL,MAAM,OAAO,mBAAmB;GAE9B,QAAO,OAAA,GADgB,mBAAA,QAAA,EAAA,GAAQ,mBAAA,MAAA,EAAA,GAAe,mBAAA,WAAA,CAAoB,UAAU,cAAc,IAAA,GAAG,mBAAA,QAAA,CAAQ,UAAU,CAAC,CAAC,EAAA,CACjG,KAAK,KAAK,WAAW;IAAE,IAAI,MAAM;IAAI,MAAM,MAAM,KAAK;GAAE,EAAE;EAC5E;EACA,KAAK,OAAO,gBAAgB,UAAU;GACpC,MAAM,WAAW,OAAA,GAAM,mBAAA,OAAA,EAAA,GAAO,mBAAA,IAAA,CAAI,UAAU,gBAAgB,KAAK,CAAC;GAClE,OAAO,SAAS,OAAO,IAAI,SAAS,KAAK,IAAI;EAC/C;EACA,KAAK,OAAO,gBAAgB,OAAO,SA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