Skip to content

feat(cli): KV sync for Fresh + deco sites (one-pass block keys, keep emptied redirect blocks) [7.x] - #830

Open
hugo-ccabral wants to merge 3 commits into
7.xfrom
feat/kv-sync-fresh-sites
Open

hugo-ccabral wants to merge 3 commits into
7.xfrom
feat/kv-sync-fresh-sites

Conversation

@hugo-ccabral

@hugo-ccabral hugo-ccabral commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Why

Fast deploy is coming to Fresh + deco sites running on Cloudflare Workers (deco-cx/deco @deco/deco/workerd). They will read their decofile from the same KV contract the TanStack sites use, written by this CLI, which the cfworkers-builder and the operator's decofile-syncer already run for every site. Context: decocms/control-plane#373.

Two things in today's output break a Fresh reader:

  1. Block keys. The CLI decodes file names until no % is left. Fresh's parseBlockId decodes once, and blocks reference each other by that key. Home%2520Page.json becomes Home Page here and Home%20Page on Fresh.
  2. Dropped redirect blocks. When every rule of a redirect block moves to redirect:<id>:<path> keys, the block is deleted. Fresh resolves blocks by name, so a routes config that references a std/x/redirects block would fail to resolve.

What

readKvDecofile (in lib/kv-snapshot.ts) is now the one place both deco-sync-blocks-to-kv and deco-migrate-blocks-to-kv build the decofile and its exact redirects. On a Fresh repo (deno.json(c) and no package.json, the same rule as the cfworkers-builder's isDenoSite), it:

  • decodes block keys once (singleDecodeBlockName, which already existed for this reason);
  • keeps an emptied redirect block as { ...block, redirects: [] };
  • adds no synthetic __csv_redirects__* blocks, because Fresh loads CSVs at runtime (redirectsFromCsv);
  • and sync skips the /_cache/purge call, an endpoint only the TanStack worker has.

Exact redirects still move to per-key KV entries on Fresh, as on TanStack. Detecting the framework from the repo means the builder and the syncer call the CLI unchanged.

TanStack repos: same output as before.

Tests

  • New scripts/lib/kv-snapshot.test.ts: a Fresh repo gets one-pass keys, the emptied block kept, the glob left in the decofile, and the exact rule in exact. A TanStack repo gets the old output. Also covers isFreshRepo.
  • vitest run packages/blocks-cli/scripts/lib/: 61 passed.
  • tsc --noEmit on blocks-cli: no errors in the changed files. 6 errors exist in scripts/migrate/*.test.ts (TailwindConfigExtract/MigrationContext fixtures), which this PR doesn't touch.

🤖 Generated with Claude Code


Summary by cubic

Makes deco-sync-blocks-to-kv and deco-migrate-blocks-to-kv write a decofile a Fresh + deco site can read, so fast deploy works for those sites without changing how the builder or syncer call the CLI. TanStack repos get the same output as before.

  • On a Fresh repo (deno.json(c), no package.json), block keys are decoded once to match Fresh's parseBlockId, and no synthetic CSV redirect blocks are written.
  • Only exact sources of website/loaders/redirect.ts blocks move to KV, and only when the website/loaders/redirects.ts collector is in the decofile; other Fresh redirect blocks stay verbatim, since a KV key applies to every request and would trigger rules Fresh never applied.
  • Blocks whose rules all moved stay in the decofile rule-free, so name references in a routes config still resolve; kept blocks remain exactly as written, so singular props.redirect shapes, /:param sources, and absolute URLs keep working.
  • Sync skips the /_cache/purge call for Fresh sites, since only the TanStack worker exposes that endpoint.
  • Both scripts now share readKvDecofile, so a one-shot seed and a CI sync can't produce different snapshots.

Written for commit 7a48102. Summary will update on new commits.

View guided diff Turn on auto-fix

…emptied redirect blocks)

`deco-sync-blocks-to-kv` / `deco-migrate-blocks-to-kv` now detect a Fresh +
deco repo (deno.json(c), no package.json — the cfworkers-builder's rule) and
write a decofile Fresh's runtime can read:

- block keys are decoded once, like deco's `parseBlockId`; decoding further
  turns `a%2520b.json` into `a b` where Fresh expects `a%20b`;
- a redirect block whose rules all moved to `redirect:<id>:<path>` keys is
  kept with `redirects: []` instead of dropped, because Fresh resolves blocks
  by name and a routes config may reference it;
- no synthetic `__csv_redirects__*` blocks (Fresh loads CSVs at runtime);
- no `/_cache/purge` call (Fresh has no such endpoint).

TanStack repos produce the same output as before. Both scripts now share
`readKvDecofile`, so a seed and a sync can't disagree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@hugo-ccabral

Copy link
Copy Markdown
Contributor Author

Verdict: BLOCK — the Fresh branch passes through splitExactRedirects' TanStack-shaped rewrites, which silently drops two kinds of singular-redirect rules on Fresh (round 1)

Blocking

  • packages/blocks-cli/scripts/lib/kv-snapshot.ts:76-79 (Fresh branch of readKvDecofile): singular redirect blocks that split keeps get reshaped, and Fresh can't read the new shape. For a block it keeps, splitExactRedirects (packages/blocks/src/sdk/redirects.ts:571-572) rewrites { redirect: {...} } into { redirects: [entry] } and drops redirect. TanStack's loadRedirects reads redirects ?? redirect, so this is fine there. On Fresh, website/loaders/redirect.ts returns props.redirect, which is now undefined. website/loaders/redirects.ts#getAllRedirects then removes it with .filter((item) => item && item.redirect). The Fresh branch copies split.blocks[key] as-is (if (key in split.blocks)), so the rewritten block is what gets shipped.
    Trigger: on a Fresh repo, .deco/blocks/blog.json = {"__resolveType":"website/loaders/redirect.ts","redirect":{"from":"/blog/*","to":"/news","type":"permanent"}}. The KV decofile gets {"__resolveType":"website/loaders/redirect.ts","redirects":[{"from":"/blog/*",...}]}, and /blog/anything stops redirecting. The rule is a glob, so it isn't in KV either. The same thing happens to any query-scoped (?) rule and any rule over 400 bytes, since those also stay in the decofile.
    Fix: in the Fresh branch, if the original block used the singular redirect form and split kept it, emit the original block unchanged. The current test covers only the plural shape; add a singular-glob case. → fix here

  • packages/blocks/src/sdk/redirects.ts:543-546, reached for Fresh through readKvDecofile: Fresh's /:param URLPattern rules get classified as exact and moved to KV under a literal key. The pattern check only looks for * and ?. Fresh's website/loaders/redirects.ts routes anything containing /: as a URLPattern (isHref = !from.includes("*") && !from.includes("/:")).
    Trigger: on a Fresh repo, {"__resolveType":"website/loaders/redirect.ts","redirect":{"from":"/p/:id","to":"/produto/:id"}} ends up in KV as redirect:<id>:/p/:id, and the block is emptied to redirects: []. A request for /p/123 never matches that key, so the redirect is gone.
    Fix: on Fresh, keep /: rules in the decofile. Either pass an option to splitExactRedirects or post-filter in readKvDecofile. Whether TanStack has the same gap is pre-existing and out of scope here. → fix here

Worth fixing

  • Cross-repo contract. On Fresh, exact rules leave the decofile, so the Fresh KV reader has to do the per-request redirect:<id>:<path> lookup with the same normalizePath key: lower-cased, trailing slash dropped. Fresh's own href matching doesn't fold case, so /Old and /old with different targets collapse into one shadowed entry. I couldn't find a Fresh KV reader in deco-cx/deco yet (#1260/#1261/#1273 cover the workerd runtime and CSV embedding, not KV). Nothing breaks today, but that reader has to ship with this behaviour, and someone has to decide whether Fresh wants case-folding. Worth a line in decocms/control-plane#373. → file an issue
  • kv-snapshot.ts:76: key in split.blocks walks the prototype chain. A redirect block named constructor.json or toString.json whose rules all moved to KV would be replaced by Object.prototype.constructor and then disappear in JSON.stringify. The trigger is improbable, so this isn't blocking, but Object.hasOwn(split.blocks, key) is the one-word fix. → fix here if you're already touching the line

Checked, fine

  • TanStack output is byte-identical. With no fresh option, readDecofileFromDir uses the same multi-pass decoded.name and the same CSV merge, and readKvDecofile returns split.blocks unchanged, so key order and the djb2 revision match the old path.
  • TanStack purge paths are unchanged. purgePathsForChangedKeys(split.blocks, ...) replaces (blocks, ...), but split passes non-redirect blocks through by reference, and only page blocks with a path contribute. Purge is still gated on purgeUrl && purgeToken.
  • Fresh keys match parseBlockId. singleDecodeBlockName matches parseBlockId (single decodeURIComponent, deco engine/decofile/fsFolder.ts:34). Malformed % names diverge harmlessly: Fresh skips them, and the CLI keeps an unreferenced block under the raw stem.
  • Emptied redirect.ts blocks are safe on Fresh. {..., redirects: []} gets removed by getAllRedirects' item.redirect filter instead of throwing.
  • CSV handling. redirectsFromCsv blocks keep their from, and fix(workerd): embed the site CSVs the decofile reads (redirects) deco-cx/deco#1273 embeds the CSVs, so skipping the synthetic __csv_redirects__* blocks is correct.
  • Repo detection. isFreshRepo is identical to the builder's isDenoSite (images/cfworkers-builder/scripts/deno-site.ts:34). The builder and the syncer both run the CLI with cwd = repo root.
  • No CI ran on this PR (0 checks). The new vitest file has only been run locally.

…intact

Review of #830:
- a kept singular `website/loaders/redirect.ts` block was rewritten by the
  split to `redirects: [entry]`; Fresh's loader reads `props.redirect`, so a
  glob, query or long-path rule silently stopped redirecting. Fresh now gets
  the original block back.
- Fresh treats a `/:param` source as a URLPattern. It was moved to KV as a
  literal path and never matched. `splitExactRedirects` takes an optional
  `keepInDecofile`, and the Fresh sync keeps `/:` sources in the decofile.
  TanStack calls it without the option: same output as before.
- `Object.hasOwn` instead of `in` for the kept-block check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@hugo-ccabral

Copy link
Copy Markdown
Contributor Author

Triage of the review, fixed in 502601e:

  • Singular redirect rewritten to redirects: [..] (blocking): fixed. On a Fresh repo, a kept singular block is now emitted unchanged. Test added for a singular glob and a singular exact rule (the exact rule moves to KV and leaves an empty block).
  • /:param sources moved to KV as literal paths (blocking): fixed. splitExactRedirects takes an optional keepInDecofile(from), and the Fresh sync keeps /: sources in the decofile. TanStack calls it without the option, so its output doesn't change. Whether TanStack has the same gap is a separate question and out of scope here.
  • in vs Object.hasOwn: fixed.
  • "No Fresh KV reader in deco": it's being written now, in a deco-cx/deco PR I'll link here. On case: the key stays the folded normalizePath (the shared contract), but the Fresh reader only uses it to narrow the candidates. It then matches the stored from against the request path byte for byte, as Fresh's hrefRoutes does. So Fresh stays case-sensitive and no key-format change is needed.

Tests: vitest run packages/blocks-cli/scripts/lib/ packages/blocks/src/sdk/ gives 565 passed and 1 failed. The failure is crypto.test.ts > decrypts using DECO_CRYPTO_KEY from the RequestContext env binding, and it fails the same way with this PR's changes stashed, so it's pre-existing and unrelated. tsc --noEmit on packages/blocks is clean.

Found by an end-to-end run on a real Fresh site: Fresh applies a redirect
block only when the routes config references it, except
`website/loaders/redirect.ts` blocks, which the `website/loaders/redirects.ts`
collector gathers by type. A KV key applies to every request, so moving a
`std/x/redirects` block made an orphan rule (never applied on Fresh today)
start redirecting.

On a Fresh repo, only exact sources of `website/loaders/redirect.ts` blocks
move, and only when the collector is in the decofile. Everything else stays
exactly as Fresh resolves it, verbatim. Also kept: `/:param` (URLPatterns in
Fresh) and absolute URLs (Fresh keys those by the full URL, so they never
match). `keepInDecofile` now gets the source as written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@hugo-ccabral

Copy link
Copy Markdown
Contributor Author

The Fresh KV reader is deco-cx/deco#1280, and the router side is deco-cx/apps#1709. The control-plane side is decocms/control-plane#377. Rollout order: this PR is released first, because the syncer and builder call npx -p @decocms/blocks-cli.

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.

1 participant