Skip to content

fix(wm-app-translations): replace Ajv-compiled jsonSchema with pure-JS validate (Workers-safe) - #407

Merged
Ardnived merged 1 commit into
mainfrom
fix/wm-app-translations-ajv-on-workers
May 25, 2026
Merged

Ardnived merged 1 commit into
mainfrom
fix/wm-app-translations-ajv-on-workers

Conversation

@antontcymbal

Copy link
Copy Markdown
Contributor

The problem

Writes to the wm-app-translations JSON fields fail on prod (Cloudflare Workers) with:

ValidationError: The following field is invalid: Navigation > Navigation
→ "Code generation from strings disallowed for this context"
  at beforeChange (worker.js)

The error reproduces against https://cloud.sydevelopers.com against every JSON field on every translations global (40 leaves on wm-app-translations, plus the corresponding fields on wm-web-translations and sy-atlas-translations).

Root cause

The JSON-field jsonSchema option I added to createStringsJsonField in #190 (long before #404) compiles to an Ajv validator in Payload's beforeChange field validation:

// node_modules/payload/dist/fields/validations.js
import Ajv from 'ajv'
…
const ajv = new Ajv()
if (!ajv.validate(schema, value)) {
  return getJSONValidationError(ajv.errors)
}

Ajv uses new Function() for performance, which Cloudflare Workers' V8 isolate blocks with the CSP-style error above.

The bug has been latent since the wm-app-translations global was first introduced (#188 / #190), but nothing had ever written to its JSON fields on prod — translators hadn't started yet and the admin UI just showed empty rows. The #393 seed import (the very first thing trying to write data) is what surfaced it.

The fix

Drop jsonSchema from createStringsJsonField. Reimplement the same validation contract (required keys, additionalProperties: false, per-key string-type checks) as a pure-JS validate function. No more Ajv compilation, no more dynamic code generation.

Before:

return {
  name: fieldName,
  type: 'json',
  …
  jsonSchema: {
    uri: `a://${globalSlug}/${slug}.json`,
    fileMatch: […],
    schema: { type: 'object', properties, required, additionalProperties: false },
  },
}

After:

return {
  name: fieldName,
  type: 'json',
  …
  validate: (value): true | string => {
    if (value === null || value === undefined) return true
    if (typeof value !== 'object' || Array.isArray(value)) {
      return 'Value must be a JSON object'
    }
    const obj = value as Record<string, unknown>
    if (!allowAdditional) {
      for (const key of Object.keys(obj)) {
        if (!allowedKeys.has(key)) return `Unknown key "${key}" (not in schema)`
      }
    }
    for (const key of requiredKeys) {
      if (!(key in obj)) return `Missing required key "${key}"`
      if (typeof obj[key] !== 'string') return `Key "${key}" must be a string`
    }
    return true
  },
}

Why this is safe

  • Admin UX is unaffected. These JSON fields are rendered by the custom TranslationsTable component (key/value rows), not Monaco. Losing Monaco's schema-aware hints costs nothing on this surface.
  • Validation coverage is the same. Every error class the old Ajv schema caught (additionalProperties: false, required, type: string) is now caught by the pure-JS validator with comparable error messages. Verified by 8 new unit-style integration tests.
  • Generated types lose inner-key types for these JSON fields. Payload was deriving those from jsonSchema. The runtime code (TranslationsTable + the seed converter) reads the field by name at runtime — both work on the live data shape, not the generated TS type. So this is a type-permissiveness regression with no runtime impact.

Verified locally

$ pnpm test:int -- tests/int/translations-globals.int.spec.ts tests/int/translations-field.int.spec.ts
Test Files  40 passed (40)
     Tests  728 passed (728)     # +4 new validate tests vs main

The 33 "errors" vitest reports are pre-existing @payloadcms/[email protected] vs [email protected] peer-dep mismatch unhandled rejections — unrelated to this change, present on main.

Lint clean (no new warnings). Typecheck clean for changed files. pnpm generate:types re-run — diff is the expected generic-JSON-field shape.

Verified against prod

The actual prod failure was reproduced just before this PR with a minimal direct write:

$ curl -X POST "https://cloud.sydevelopers.com/api/globals/wm-app-translations?locale=en" \
    -H "Authorization: JWT $TOKEN" \
    -d '{"navigation":{"daily":"Daily","path":"Path","explore":"Explore","profile":"Profile"}}'

{"errors":[{
  "name":"ValidationError",
  "data":{"errors":[{
    "label":"Navigation > Navigation",
    "message":"Code generation from strings disallowed for this context",
    "path":"navigation"
  }]},
  "message":"The following field is invalid: Navigation > Navigation"
}]}

That's exactly what this PR fixes. Once merged + deployed (pnpm run deploy:prod), the #393 seed import (pnpm seed:prod wm-app-translations or the SSE endpoint) writes successfully.

Bonus wire-up

This PR also adds 'wm-app-translations' to seeds/run.ts (the CLI runner's local ScriptName union, VALID_SCRIPTS, SCRIPT_RUN_ORDER, SCRIPT_DESCRIPTIONS, usage text). The API route already knew about the seed (#404), but the CLI rejected it as "Unknown script" — that gap was a leftover from #404.

Note that seeds/run.ts's cookie-forwarding auth is known to be fragile against prod's Workers runtime (per session-handoff notes — Set-Cookie reattachment via Node fetch isn't reliable when Secure=true; SameSite=None). The JWT-header path via direct fetch('/api/seed/<name>?dryRun=…', { headers: { Authorization: 'JWT ...' } }) is the verified production-safe import path. Porting seeds/run.ts off cookies is a separate, larger change that affects all five seeds (tags, wemeditate, meditations, storyblok, wm-app-translations).

Test plan for reviewer

🤖 Generated with Claude Code

…S validate (Workers-safe)

Writes to wm-app-translations JSON fields fail on prod (Cloudflare
Workers) with:

  ValidationError: The following field is invalid: Navigation > Navigation
  → "Code generation from strings disallowed for this context"
    at beforeChange (worker.js)

Root cause: the JSON-field `jsonSchema` option compiles to an Ajv
validator (`new Ajv() + ajv.validate`) in payload's beforeChange field
validation. Ajv uses `new Function()` for performance, which Cloudflare
Workers' V8 isolate blocks with the CSP-style error above. The bug has
existed since the global was first introduced (#188 / #190) but was
latent because nothing ever wrote to these JSON fields on prod — the
admin UI showed empty fields and translators hadn't yet started. The
#393 seed import is the first thing to hit it.

Fix: drop `jsonSchema` from `createStringsJsonField` and reimplement the
same validation contract (required keys, additionalProperties,
per-key string-type checks) as a pure-JS `validate` function. No more
Ajv compilation, no more dynamic code generation. The admin UX is
unaffected because these JSON fields are rendered by the custom
TranslationsTable component (key/value rows), not Monaco, so the loss
of Monaco's schema hints costs nothing.

Generated types: `pnpm generate:types` produces a more generic shape
for the JSON fields (no inner-key types) since Payload was deriving
those from the jsonSchema. TranslationsTable + the seed converter both
work on the runtime data shape, not the generated TS types, so this is
purely a type-permissiveness regression with no runtime impact.

Wire-up: also adds 'wm-app-translations' to seeds/run.ts's local CLI
registry (ScriptName, VALID_SCRIPTS, SCRIPT_RUN_ORDER, SCRIPT_DESCRIPTIONS,
usage text). This was missed in #404 — the API route already knew about
the seed but the CLI rejected it as Unknown script. Note that the CLI's
cookie-forwarding auth is known-fragile against prod's Workers runtime
(per .claude session-handoff notes); the JWT-header path via direct
fetch to the API endpoint is the verified production-safe import path.

Tests:
- tests/int/translations-field.int.spec.ts — replace the 5 jsonSchema-
  assertion tests with 8 pure-JS validate tests covering: null/undefined
  passes, non-object rejection, missing-required-key rejection,
  unknown-key rejection (when additionalProperties is not true),
  unknown-key acceptance (when additionalProperties is true),
  non-string-value rejection for declared keys, well-formed object
  acceptance.
- tests/int/translations-globals.int.spec.ts — replace the 2 jsonSchema-
  assertion tests with assertions that jsonSchema is undefined and
  validate is a function on every JSON field of all three translation
  globals (wm-web-translations, wm-app-translations, sy-atlas-translations).
- All 728 integration tests + 26 unit tests pass; lint clean; typecheck
  clean for changed files. The 33 "errors" reported by vitest are
  pre-existing unhandled rejections from a payload package-version
  mismatch (@payloadcms/[email protected] vs [email protected]),
  not caused by this change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@antontcymbal
antontcymbal requested a review from Ardnived May 25, 2026 16:11
@Ardnived
Ardnived merged commit 19e0a36 into main May 25, 2026
@Ardnived
Ardnived deleted the fix/wm-app-translations-ajv-on-workers branch May 25, 2026 16:22
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.

2 participants