Repository navigation
chore(types): typecheck the integration lane (#606 Phase 2) - #613
Merged
Merged
Conversation
Phase 1 (#607) scoped `tsconfig.test.json` to `tests/unit/**` + `tests/utils/**`. Widen `include` to `tests/**` and collapse the editor-only `tests/tsconfig.json` into a one-line re-export, so the editor and `pnpm typecheck:tests` read one set of options. Both configs resolve the same 153 files. Dropping the local `types: ["vitest/globals"]` is safe — every Vitest spec imports its globals explicitly, and the e2e specs take theirs from `@playwright/test`. This commit turns the gate red (158 errors / 26 files, all `tests/int/**`); the rest of the branch clears them. Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Five int specs hand-rolled the same "call a task handler without the queue" block and typed its args with `Parameters<typeof SomeTask.handler>[0]`. That never compiled: `TaskConfig['handler']` is `string | TaskHandler<TSlug>` (a task may point at a module path), and `Parameters<T>` rejects the union — 20 of #606 Phase 2's errors, plus the 11 downstream casts they forced. `tests/utils/taskRunner.ts` narrows the union with a `typeof` guard, so `TaskHandlerArgs<TSlug>` is available for the queue-plumbing stubs and no cast is needed. Its return type comes from the generated `TypedJobs` output schema, which retires five hand-maintained duplicates of the job output shapes (`ExpireResult`, `DigestResult`, `SyncOutput`, …) — those are now checked against the job's real contract instead of drifting from it. `inlineTask` throws instead of no-op'ing: no task under test uses sub-tasks, and returning `undefined` where an output is expected is the kind of lie the old cast was hiding. 158 -> 127 errors. expire-events + sync-lecture-metadata pass locally. Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two shared type faults, ~50 of #606 Phase 2's errors between them. `Partial<Doc>` on the factory `overrides` params relaxes only the top level, so passing a group or an array row obliged the test to supply that subtree's required keys in full — `default: { title, image }` on an app card was rejected for omitting aspectRatio/textColor/alignment, which AppCards fills from `defaultValue` anyway. `FixtureOverrides<T>` recurses, and the checks worth keeping stay: an unknown property, or a real property at the wrong type, still errors at any depth, and unions distribute so relationships keep taking a bare id. Ten factories passed `data:` straight to `payload.create` rather than through `createData`, so deep-partial values had nowhere to widen. Routed through the same seam as the other nine. `CapturedLogger` typed each method `ReturnType<typeof vi.fn>`, which resolves the generic to its *constraint* (`Mock<Procedure | Constructable>`) instead of its default — so the mock wasn't callable as `(obj: object) => void` and every `handleStreamWebhook({ logger })` call failed. Mapping over `WebhookLogger` fixes it and makes a new method on the interface break `makeLogger` instead of going unmocked. Both are type-only: no runtime behaviour changes. 127 -> 95 errors, `tests/utils/` back to clean. Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…hema
Clears role-based-access.int.spec.ts (26 errors, the worst file) plus
the shared causes behind it.
`RegionFixture` was `Record<string, unknown> & { level?: RegionLevel }`.
Its doc comment noted the narrowing was inert because tsc never read
the file — Phase 2 makes it live, so it's now `FixtureOverrides<Region>`
and checks the whole fixture, not just `level`. `createEvent`'s
`Record<string, unknown>` gets the same treatment, and `managerUser` /
`createRegion` take the real manager-fixture type instead of
`{ id: number }` (which dropped every other field and so wasn't a
`Manager`).
`FixtureOverrides` and `createData` are now exported: specs building
inline `payload.create` helpers need the same seam. Without `createData`
here, an omitted `slug` pushes TS onto the *draft* create overload and
it reports "Property 'draft' is missing" — 8 errors that read as
nothing to do with the actual cause.
`createTestLexicalContent` gets a return-type annotation; inferred, its
`direction`/`format` widen to `string` and no `richText` field accepts
the result (7 errors).
`select: { id: true }` (11 sites) doesn't typecheck because Payload
omits `id` from the generated `…Select` types — it's always returned.
Replaced with an `idOnlySelect()` helper carrying one documented
assertion. Note `select: {}` is NOT equivalent: `validateClientQuery`
rejects an empty select with a 400, which the first attempt at this hit
(7 failures). Verified by running the spec, not by reading the types.
158 -> 68 errors. role-based-access + pages: 73 tests pass.
Refs #606
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Eight `payload.create({...} as any)` calls cast away the argument type,
which also collapsed the *return* type to a union over every collection
— so `lecture.title` / `.metadata` / `.thumbnail` didn't exist on it
(7 errors that read like missing fields but were self-inflicted). The
cast was there to dodge the create-data type; `createData<'lectures'>`
handles that properly and keeps the result a Lecture.
The eight `fetchNirmalaVidyaVideo` mocks were also each missing
`duration`, required on `NirmalaVidyaVideoData` and read by
`populateFromNirmalaVidya` — the mocks were passing `undefined` where
the contract says `number | null`. Real rot the exclusion was hiding.
68 -> 53 errors. 32 tests pass.
Refs #606
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… keys
The bulk of the remaining tail was one shape: a spec building its own
`payload.create` call with a plain object literal. Because Payload
derives the create-data type from the *output* doc, an omitted
auto-filled field (`slug`) makes TS pick the draft overload and
complain about `draft`. `createData<'slug'>` is the seam for that;
applied to the region, event and audience fixtures across 10 specs.
Two pieces of real rot fall out:
- `rules: { logic: 'AND', pathProgress: … }` on 7 audience fixtures.
Audiences has no `rules` field — it was flattened into top-level
range groups — so Payload has been silently dropping it. Removed
rather than translated: `/lectures/for-audience` matches on audience
*id* overlap, never on rule evaluation, so no test reads it.
- The five `SCHEDULE` fixtures pinned `recurrenceType` with `as const`
but left `firstDate_tz` widening to `string`, so none of them
satisfied `SupportedTimezones`. Whole object is `as const` now.
68 -> 22 errors.
Refs #606
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per-spec tail. Several were real defects the exclusion had been hiding:
- api: `createMeditation(payload, { title })` put the title in the
factory's `deps` slot (2nd param) instead of `overrides` (3rd), so
the meditation got a random label; and `populate` was keyed on the
field name rather than the target collection, making it a no-op.
- audiences: `createAppCard(payload, { title })` — AppCard's title
lives under the `default` group, so it was silently dropped.
- app-cards-for-audience: `toHaveLength(1, 'message')` — the matcher
takes one argument and the message was discarded.
- wemeditateAppStatus: the invariant fixture omitted `label` and
`description`, both required on SectionSpec.
The rest are honest typing: `LIST_VIEW_SELECT` annotated so `true`
stops widening to `boolean` (and the column names get checked),
`common` in events-geojson annotated rather than `as const` (which
froze `languages` to a readonly tuple), `Event`/`Video`/`Region`
imported where the DOM globals were resolving instead, and a documented
`schedule: null` sentinel type in event-verification's fixture helper.
Casts kept only where a test is deliberately out-of-contract — videos'
malformed subtitle row, meditations' `locale: 'all'` (real Payload
value, absent from the generated union), and events' `_status`
assertion (left out of the select on purpose, to prove the plugin
injects it).
`pnpm typecheck:tests` now exits 0 over the whole suite. Full lane
verified green: 54 int files / 885 tests, 85 unit files / 978 tests.
Refs #606
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The tier tables in AGENTS.md and testing-reqs.md described
`typecheck:tests` as unit-lane-only; it now covers `tests/**`.
Adds a "Typed fixtures" section to `.claude/rules/tests.md` (the rule
that auto-loads when editing a spec) covering `createData` /
`FixtureOverrides` — including *why* each exists, since both failure
modes are non-obvious: an omitted auto-filled field makes tsc report
"Property 'draft' is missing", and `Partial<Doc>` silently stops
relaxing one level down. Also notes `runTaskHandler`, and that
`idOnlySelect()` is not interchangeable with `select: {}`.
Refs #606
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Per /simplify. Payload generates every date field as an ISO `string` (`grep -cE ':\s*Date\b' src/payload-types.ts` -> 0), so the branch could never be taken. Noted the assumption in the doc comment instead. Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
check.sh still told the reader the test typecheck was "scoped to the unit lane" and named `tests/unit + tests/utils` in its failure hint. Points at the fixture helpers on failure, which is what a spec author who trips it needs next. Refs #606 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚅 Deployed to the SahajCloud-pr-613 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-613
August 3, 2026 23:55
Destroyed
Ardnived
added a commit
that referenced
this pull request
Aug 4, 2026
origin/main #613 (#606 Phase 2) widened tsconfig.test.json to tests/int/**, and CI type-checks this PR merged with latest main — surfacing two dormant errors in my additions: - createGatingEvent omitted the required `schedule`, so the create fell to the draft overload. Wrap it in main's `createData<'events'>` helper and give it a default `schedule` (every gating case overrides it). - registrations-fullness FUTURE_ONE_OFF had `firstDate_tz: string`; make it a `SupportedTimezones` literal (`as const`) and wrap the create in `createData`. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived
added a commit
that referenced
this pull request
Aug 4, 2026
* refactor(schedule): extract shouldFinish into a shared module Move `shouldFinish` + `FinishCheckInput` out of the ExpireEvents job into `src/lib/schedule/scheduleStatus.ts` so the registration endpoint can reuse the same "schedule has run out" check without cross-importing a job's internals. Behaviour is unchanged; the unit cases move alongside it. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(events): denormalized registrationsFull fullness signal Add a stored `registrationsFull` boolean on Events so `sahaj-atlas-client` can read an event's "Full" state on by-id/list reads and the geojson feed without a per-event COUNT (feed stays O(1)) and without exposing raw registration numbers. True only for `sahaj-atlas` mode with a set limit the count has reached; false for external mode or a blank (unlimited) limit. Maintained by the Registrations create/delete hooks (recompute + write only on a real flip, so version churn stays negligible) and recomputed on an Events save when registrationMode / registrationLimit changes. `isEventFull` is the single shared definition of "full", reused by the registration gate. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * chore(migrations): add events.registrations_full column Adds the denormalized `registrations_full` boolean (and its `_events_v` version companion), nullable with default false — existing rows read false until a registration change or capacity edit recomputes them. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(events): gate registration by schedule state + capacity POST /api/events/:id/register now refuses a registration the event's state won't accept — external mode, an ended schedule (reuses shouldFinish), a started limited-run course, or a full event — with a stable machine-readable `code` (external_registration / event_ended / registration_closed / event_full, all 409) the Atlas widget maps to its registration-state UI. The capacity check is enforced against a live count (authoritative); the published/visible 404 and the open-event 201 path are unchanged. The gate is a pure, unit-tested helper; the error-code union is typed in the cross-repo responseTypes contract. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(openapi): document register 409 rejection codes Add the `409` response and its four machine-readable `errors[0].code` values to the hand-authored register-endpoint shim, and guard them in the custom-endpoints spec so the Atlas contract stays in lockstep. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(events): pin the finished-event read contract Document the contract the Atlas widget relies on: a schedule-elapsed event is marked finished + `_status: 'draft'` by ExpireEvents, so `sahaj-atlas-client` reads a 404 (finished ⇒ 404, not an readable "Ended" doc). The pre-job window — past but still published — stays readable so the widget derives "Ended" client-side, and the register gate closes the matching registration hole. Stated in the Events collection JSDoc + finishEvent, with an Atlas read/registration summary in the architecture doc. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(events): gating + fullness integration specs Cover each registration rejection (external / ended / started course / full) plus the boundary (an open-ended recurring class never closes) and the preserved 404, and the fullness signal (flip at the limit, free on delete, never-full for blank/external, capacity-edit recompute, client by-id + geojson selectability with no raw count). Elevate the fullness recompute's event write with asTrustedReq so the nested region filterOptions validation isn't rejected by the client query gate. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * refactor: simplify per /simplify pass - Parallelize the independent event read + registration count in syncEventRegistrationsFull (write-path latency). - Drop redundant .getTime() in the started-course instant comparison. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(events): note the capacity gate is a soft cap under concurrency Per code review: the count→create window isn't transactional, so concurrent registrations can overshoot registrationLimit by a few. Acceptable for a meditation class (not ticketed inventory); documented rather than adding a row lock / DB constraint. Behaviour unchanged. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(migrations): idempotent registrations_full add for the merged chain The origin/main merge regenerated the registrations_full migration as 20260803 (replacing the pre-merge 20260722, so the snapshot chain stays cumulative on top of schedule_last_date). The PR-601 Railway preview DB persists across deploys and had already applied the old 20260722 migration, so a plain `ADD COLUMN` re-add threw "column already exists" and aborted the in-process boot migration → deploy 502 → all smoke specs down. Guard the DDL with IF NOT EXISTS / IF EXISTS: a no-op where the column is already present (identical boolean DEFAULT false), a clean add on a fresh prod DB. The out-of-order snapshot trap in .claude/rules/migrations.md (#566). Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(events): typecheck the int specs under the widened test config origin/main #613 (#606 Phase 2) widened tsconfig.test.json to tests/int/**, and CI type-checks this PR merged with latest main — surfacing two dormant errors in my additions: - createGatingEvent omitted the required `schedule`, so the create fell to the draft overload. Wrap it in main's `createData<'events'>` helper and give it a default `schedule` (every gating case overrides it). - registrations-fullness FUTURE_ONE_OFF had `firstDate_tz: string`; make it a `SupportedTimezones` literal (`as const`) and wrap the create in `createData`. Refs #599 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
tsconfig.test.jsonnow covers all oftests/**, not just the unit lane. Phase 1 (chore(types): typecheck the test suite, starting with the unit lane #607) closed the gap fortests/unit/**+tests/utils/**; this closes it for the 26 int specs, clearing all 158 remaining errors.level: 'center'surviving thecenter→venuerename in feat(atlas): groom legacy event listings and group shared venues before import #605 — is caught bytsc, verified by mutation below.src/files change. Tests, tsconfig and docs only.Changes
The ticket asked for the concentrated patterns to be fixed at their source. Four shared seams do most of the work:
tests/utils/taskRunner.ts(new) —runTaskHandler(task, { payload, input, context }). Five specs hand-rolled the same queue-less job invocation and typed itParameters<typeof Task.handler>[0], which cannot compile:TaskConfig['handler']isstring | TaskHandler<TSlug>andParameters<T>rejects the union. Atypeofguard narrows it properly. Return type comes from the generatedTypedJobsoutput schema, retiring five hand-maintained copies of the job output shapes.tests/utils/testData.ts—FixtureOverrides<T>(exported): every field optional at every depth.Partial<Doc>relaxes only the top level, so passing a group obliged the test to fill in subfields the collection supplies fromdefaultValue. Unknown/mistyped properties still error at any depth.createData<TSlug>()is now exported too — without it an omitted auto-filled field (slug) pushestsconto the draft create overload, which reports the unrelated-lookingProperty 'draft' is missing.tests/utils/testHelpers.ts—idOnlySelect().select: { id: true }(11 sites) can't typecheck because Payload omitsidfrom the generated…Selecttypes. Noteselect: {}is not equivalent —validateClientQueryrejects an empty select with a 400 (the first attempt at this failed 7 tests; caught by running them, not by reading types).tests/tsconfig.jsoncollapsed to a one-line re-export oftsconfig.test.json, so the editor and the gate read one set of options.Rot the exclusion was hiding
Not just typing noise — these were live defects:
tests/int/api.int.spec.ts—createMeditation(payload, { title })put the title in the factory'sdepsslot (2nd param) instead ofoverrides(3rd), so the meditation silently got a random label. Itspopulatewas also keyed on the field name rather than the target collection, making it a no-op.tests/int/lectures.int.spec.ts— all eightfetchNirmalaVidyaVideomocks omittedduration, which is required onNirmalaVidyaVideoDataand read bypopulateFromNirmalaVidya; they were passingundefinedwhere the contract saysnumber | null. Fifteenas anycasts also collapsed the result type to a union over every collection, solecture.title/.metadatadidn't exist on it.lectures-for-audience/meditation-lectures— seven audience fixtures passedrules: { logic: 'AND', … }.Audiencehas norulesfield (it was flattened into top-level range groups), so Payload had been dropping it. Removed rather than translated:/lectures/for-audiencematches on audience id overlap and never evaluates rules, so nothing read it.tests/int/audiences.int.spec.ts—createAppCard(payload, { title }); AppCard's title lives under thedefaultgroup, so it was dropped.tests/int/app-cards-for-audience.int.spec.ts—toHaveLength(1, 'message'); the matcher takes one argument and the message was discarded.tests/int/wemeditateAppStatus.int.spec.ts— the invariant fixture omittedlabelanddescription, both required onSectionSpec.SCHEDULEfixtures pinnedrecurrenceTypewithas constbut leftfirstDate_tzwidening tostring, so none satisfiedSupportedTimezones.Mutation check (ticket AC)
Three mutations introduced against the finished branch, each caught, then reverted to 0 errors:
level: 'venue'→'center'(the #605 escape)TS2322: Type '"center"' is not assignable to type '"region" | "country" | "city" | "venue"'default: { title: … }→titelon a nested groupTS2561: … 'titel' does not exist in type …const bad: string = result.processedon a job outputTS2322: Type 'number' is not assignable to type 'string'Test Results
pnpm test:int, greenpnpm typecheck(src): ✓ ·pnpm typecheck:tests: ✓ 0 errors overtests/**·pnpm lint: ✓.tsbuildinfo): 27 s — inside its 45 s budget.typecheck:testsalone is 16.7 s cold / 3.5 s warm, 320k type instantiations.Notes for reviewer
idOnlySelectswap, therulesdeletion,duration: null, theas constschedules, theEventFixturesentinel, thecreateMeditationarg fix, the throwinginlineTask, the_statuscast) were each verified against source and by running their specs.locale: 'all'(a real Payload value absent from the generated union), and events'_statusassertion (omitted from the select on purpose, to prove the plugin injects it).FixtureOverrideshas noDatebranch — Payload generates every date field as an ISOstring, verified by grep.types: ["vitest/globals"]fromtests/tsconfig.jsonis safe: every Vitest spec imports its globals explicitly and all six e2e specs take theirs from@playwright/test.src/files changed. The path grep matches onlycloudflare-stream-webhook.int.spec.ts, on the substringwebhook, and that diff is a type alias plus comments.Closes #606
🤖 Generated with Claude Code