Skip to content

refactor(fields): adopt jsonSchema for structured json fields - #618

Closed
Ardnived wants to merge 7 commits into
mainfrom
refactor/json-schema-fields
Closed

Ardnived wants to merge 7 commits into
mainfrom
refactor/json-schema-fields

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Every type: 'json' field with a known structure now carries a jsonSchema derived from its source of truth, so Payload validates it on write (400, not a silently-stored blob) and generates its TypeScript type instead of unknown.
  • Retires the Cloudflare-Workers rationale that kept jsonSchema off these fields — new Function()/Ajv run fine on Railway/Node.
  • No new dependency: Zod 4 ships z.toJSONSchema() natively, so zod-to-json-schema wasn't needed.

Changes

Field Schema derived from
translations leaf groups (all 3 globals) the group's own properties — plural keys expanded to their CLDR family
Managers.notificationPreferences NOTIFICATION_TYPES (each frequency confined to its own options)
Videos.subtitles, Lessons.introSubtitles, Lessons.panels.*.subtitles subtitleCue via z.toJSONSchema(…, { target: 'draft-7' })
Events.notificationLog the entry builders + VERIFICATION_STAGES / VERIFICATION_METHODS
Registrations.reminderLog ReminderLogEntry
Meditations.subtleSystemNodeWeights Record<slug, seconds> | null

Also: reminderLedger.ts → src/lib/registrations/reminderLog.ts (the Registrations collection now shares it with the job, and a collection may not import a job folder's internals); registrationQuestionsJsonSchema reshaped so every field passes a complete jsonSchema object from its owning module.

The remaining json fields are recorded as deliberately unschema'd, with a one-line reason each, in .claude/rules/collections.md.

Notes for reviewer

Three findings worth your attention, all resolved:

  1. A custom validate silently disables jsonSchema. sanitize.js only installs Payload's built-in json validation when validate is undefined. So translationsField's hand-rolled validator had to go, and Managers.notificationPreferences — which keeps a cross-field rule JSON Schema can't express with a readable message — delegates to validations.json(value, options) first. The int case "rejects a frequency outside the type's own options" is what proves that delegation runs.
  2. additionalProperties: false is a claim about rows already in the database. Subtitles hit this: the Zod validator being replaced stripped unknown cue keys and passed, and lessons.int.spec.ts documents that tolerance as intentional. Rejecting them would have 400'd every later save of any lesson/video holding a legacy startOfParagraph. The cue schema is therefore derived from a loose variant of the same shared object — strict for the seed parser, tolerant for the field. Every other new additionalProperties: false / required was checked against each writer in src/, seeds/, scripts/ and against git history (NOTIFICATION_TYPES options and the log-entry shapes are unchanged since introduction), so none can reject stored data.
  3. The stricter types caught a lying fixture — an int fixture wrote a reminder entry with no level/role, hidden by an as NotificationLogEntry[] cast. Filled in to match what buildReminderEntry actually produces.

No migration: jsonSchema is config-only, the jsonb columns are unchanged (db:migrations:create --skip-empty generates nothing).

Pre-existing and left alone: src/components/admin/NotificationPreferences/config.ts is pure business logic imported by two collections, so by project-structure.md it belongs in src/lib/. Moving it is a separate refactor — happy to open a follow-up if you'd like.

Test Results

  • Lint: ✓ · Typecheck (src + tests): ✓ · Unit: 1023 passed
  • New: tests/int/json-schema-fields.int.spec.ts — 11 cases, one per newly-schema'd field (malformed write → 400, well-formed → round-trips). The rejection cases can't pass vacuously: the helper throws when a write succeeds, which is how the conditional Lessons.panels.*.subtitles field was caught skipping validation until its panel has media.
  • Targeted integration specs green: translations-globals, translations-field, lessons, videos, meditations, collections-smoke, event-verification, event-registration, session-reminders, registration-digests, meditation-lectures

Manual verification

  1. Admin → any translations global: edit a key, save. Rows still render and save normally (the fields keep their TranslationsRow component; only validation changed).
  2. Admin → Managers → Notifications: set a non-Never frequency and clear the method — the error should still name the type ("Select a notification method for: Event Registration"), not an Ajv message.

Closes #597

🤖 Generated with Claude Code

Ardnived and others added 7 commits August 4, 2026 12:00
Derive the field's JSON Schema from `subtitlesZodSchema` with Zod 4's
native `z.toJSONSchema` (no new dependency), and wire it as the fields'
`jsonSchema` on Videos and Lessons. Payload now runs it through Ajv on
write and generates the TypeScript type from the same schema, so the
hand-maintained mirror — and the Workers-era `validate`/`typescriptSchema`
pair it existed to feed — are both gone.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Project each leaf group's own schema onto its JSON field as a `jsonSchema`
(keys → optional strings, plural keys expanded to their CLDR family,
`additionalProperties` honoured) and drop the hand-rolled `validate` it
replaces — a custom validate would override Payload's built-in json
validation and silently disable the schema.

Every translations global now carries a real per-group TypeScript type
with each key's description as JSDoc, where it was `unknown` before.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nSchema

- `Managers.notificationPreferences` gets a schema derived from
  NOTIFICATION_TYPES (each type's frequency confined to its own options).
  Its `validate` now delegates to Payload's built-in json validation before
  applying the cross-field "method unless Never" rule — a custom validate
  replaces the built-in outright, so without the delegation the schema
  would never run.
- `Events.notificationLog` gets the verification/reminder entry union, and
  `Registrations.reminderLog` its occurrence-ledger shape. Both read back
  typed instead of `unknown`.

`reminderLedger.ts` moves to `src/lib/registrations/reminderLog.ts`: the
Registrations collection now shares it with the job, and a collection may
not import a job folder's internals.

The stricter types surfaced an int fixture writing a reminder entry with
no `level`/`role`, which the `as NotificationLogEntry[]` cast had been
hiding — filled in to match what `buildReminderEntry` actually produces.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
One int case per newly-schema'd field: a malformed write is a 400, and a
well-formed one round-trips. The rejection cases can't pass vacuously —
the helper throws when the write succeeds, which is how the conditional
`Lessons.panels.*.subtitles` field was caught skipping validation until
its panel has media.

Also types `Meditations.subtleSystemNodeWeights` as
`{ [slug]: seconds } | null`, spelling out the null that clearing the
cache really writes.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds a "reach for jsonSchema" section to the collections rule with the
four things that bite (a custom validate silently disables the schema,
empty values skip validation, Ajv wants draft-07, typescriptSchema is
redundant) plus the full audit: every json field, with either the source
its schema derives from or a one-line reason it has none.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Fold the `questions` uri/fileMatch into `registrationQuestionsJsonSchema`
so every json field now passes a complete `jsonSchema` object from its
owning module, rather than one field wrapping a bare schema at the call
site with a hardcoded URI.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`additionalProperties: false` on the cue would have rejected the extra
keys stored rows carry (`startOfParagraph`, …) — not once, but on every
later save of an otherwise untouched lesson or video. The Zod validator
this schema replaces accepted them, and `lessons.int.spec.ts` documents
that tolerance as intentional.

Derive the field schema from a loose variant of the same shared cue, so
the declared fields still can't drift from the strict parser the seed
importer uses. The generated type gains `[k: string]: unknown`, which is
the honest shape for data that really does carry more.

Refs #597

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-618 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 4, 2026 at 9:03 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-618 August 4, 2026 21:01 Destroyed
@Ardnived

Copy link
Copy Markdown
Contributor Author

Closing as superseded. The jsonSchema adoption for Events.notificationLog (array root, entry union keyed on kind) is carried forward in the verification-simplification follow-up on top of the #624→#626 stack, along with the enum derivation from VERIFICATION_STAGES, a compile-time drift guard against the hand-written entry types, and an integration case proving malformed writes are rejected. The rest of this PR (Lessons/Managers/Meditations/Videos, translationsField, subtitles, Registrations.reminderLog) is not carried over and can be reopened as a fresh PR if still wanted — this branch has drifted well behind main.

@Ardnived Ardnived closed this Aug 14, 2026
Ardnived added a commit that referenced this pull request Aug 19, 2026
…on lifecycle (#638)

* refactor(events): derive per-stage semantics from one attention level

Five simplifications across the verification lifecycle, all removing a
second encoding of a fact the stage table already knows:

- `relationId` had two implementations; 7 of 10 call sites imported the
  one that can't parse a string id. Consolidated onto the complete one.
- Every stage now declares an `attention` level. The sidebar bucket, the
  admin notice severity and the quality-check skip derive from it instead
  of each keeping their own per-stage table; `bucketForEvent`'s `default:`
  case (which silently labelled unfamiliar stages "verified") is gone,
  and the three tables that remain are exhaustive Records.
- Deleted the `eventVerification` barrel (no importers) and the
  `UNMANAGED_STAGES` / `daysUntilUnpublish` exports nothing outside the
  module read.
- `DAY_MS` is declared once in `lib/utilities/time` rather than inline in
  nine modules.
- `addMonths` clamped: 31 Aug + 6 months was rolling into 3 March, so a
  finished event's retention ran a few days long.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(tokens): sign every email link through one HMAC module

There were three near-identical hand-rolled HMAC token modules —
eventVerification/token, registrations/unsubscribeToken, and the generic
utilities/signedToken written for #625 — with the same twenty lines of
crypto and subtly different validity checks. The two older ones are now
thin wrappers that supply their claims, TTL and `kind`.

Beyond the duplication, this closes a real gap: all four link kinds are
signed with the same Payload secret, and only the envelope's `kind`
discriminator (which the two older modules lacked) stops a token issued
for one link from being replayed against another. Pinned by a test.

`signToken` gains `ttlMs: null` for never-expiring tokens, which is what
the unsubscribe link needs — it may legitimately be clicked months into
a course, and the action it authorizes is narrow and idempotent.

Existing verify / unsubscribe links in already-sent emails stop
validating, since the envelope shape changed. Accepted: the events being
reminded about are re-notified on the job's next run.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(events): validate notificationLog with a JSON Schema

`notificationLog` was a bare JSON array with a hand-written narrower
(`Array.isArray(value) ? value as Entry[] : []`) — a cast, not a check,
so a malformed entry landed in the column and every reader had to hope.

It now carries a JSON Schema, which Payload uses to generate
`Event['notificationLog']` AND to reject a bad write with a
ValidationError. The stored shape is unchanged (still a bare array), so
no data migration is needed. Adopted from the approach in #618, which
this supersedes.

The schema's enums are derived from VERIFICATION_STAGES and, for the two
unions declared in an email template, from a `completeList` helper that
makes an incomplete restatement a compile error — the types are imported
type-only, so no react-email code reaches the admin client bundle. A pair
of assignments in the unit spec fails to compile if the schema and the
hand-written entry types drift apart; both guards were verified by
mutation, as was the validation itself (an int case asserts a missing
key, an undeclared key and an out-of-enum value are all rejected).

Registrations.reminderLog is the same pattern and has NOT followed — its
comments now say so rather than claiming a mirror that no longer holds.

Co-Authored-By: Claude Opus 5 <[email protected]>

* chore(migrations): one payload entry point, and document why commands go quiet

`db:migrate` and `db:migrations:create` were aliases for `payload migrate`
and `payload migrate:create`, and `payload` was a passthrough to a binary
pnpm already resolves from node_modules/.bin. Three names for two
commands meant docs used them interchangeably, and whenever a command
failed the wrapper looked like the suspect. All removed; everything is
`pnpm payload <command>`.

The wrappers were never the problem. Three real causes, each traced to
library source and now written up in .claude/rules/migrations.md:

- Dev email calls `nodemailer.createTestAccount()` — a live request to
  ethereal.email — on every config load, so on every CLI invocation. When
  it fails the adapter throws, and payload's `bin.js` runs the CLI under a
  bare `void start()` with no `.catch()`, so the process dies with exit 0
  and NO output. This is the intermittent one: `pnpm payload
  migrate:status` alternates between a full table and zero lines on
  successive runs. Documented, not yet fixed — killing the network call
  costs the ethereal preview URL, so it needs a decision first.

- `generate:types` logs "Compiling TS types…" then returns early and
  silently when the compiled output matches the file on disk. Silence
  means "no schema change", not a hang.

- A `src/migrations/index.ts` referencing a missing migration file breaks
  EVERY payload command, because payload.config.ts imports the index for
  `prodMigrations` and the index statically imports all 44 files. The
  ERR_MODULE_NOT_FOUND sits at the top of a long stack trace, so it
  scrolls away — and vanishes entirely when piped through head/tail.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Ardnived added a commit that referenced this pull request Nov 5, 2026
`notificationLog` was a bare JSON array with a hand-written narrower
(`Array.isArray(value) ? value as Entry[] : []`) — a cast, not a check,
so a malformed entry landed in the column and every reader had to hope.

It now carries a JSON Schema, which Payload uses to generate
`Event['notificationLog']` AND to reject a bad write with a
ValidationError. The stored shape is unchanged (still a bare array), so
no data migration is needed. Adopted from the approach in #618, which
this supersedes.

The schema's enums are derived from VERIFICATION_STAGES and, for the two
unions declared in an email template, from a `completeList` helper that
makes an incomplete restatement a compile error — the types are imported
type-only, so no react-email code reaches the admin client bundle. A pair
of assignments in the unit spec fails to compile if the schema and the
hand-written entry types drift apart; both guards were verified by
mutation, as was the validation itself (an int case asserts a missing
key, an undeclared key and an out-of-enum value are all rejected).

Registrations.reminderLog is the same pattern and has NOT followed — its
comments now say so rather than claiming a mirror that no longer holds.

Co-Authored-By: Claude Opus 5 <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-618 — e9ea5df2 Deployed Aug 4, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(fields): adopt jsonSchema for structured json fields

1 participant