Repository navigation
feat(vite): live-reload .deco/blocks/*.json edits in dev - #188
Merged
Merged
Conversation
Watch `.deco/blocks/**/*.json` from `decoVitePlugin()` and regenerate
`src/server/cms/blocks.gen.json` on change with a 150ms debounce. The
existing watcher on the generated artifact already invalidates the SSR
module — this closes the loop from the source dir, so manual edits,
`sync-decofile.ts` snapshots, and daemon `PATCH /fs/file/.deco/blocks/*`
edits all land without `npm run generate:blocks` or a dev restart.
- `scripts/generate-blocks.ts`: extract `generateBlocks({ blocksDir,
outFile, silent? })` programmatic entry; preserve the CLI shim behind
an `isMainModule()` guard so `npm run generate:blocks` and migration
scripts keep working.
- `src/vite/plugin.js`: lazy-load the generator via the existing
`tsx/esm/api` `tsImport` pattern, debounce + in-flight-guard the
regen so a `writeAtomically` burst collapses to one run, log
`[deco] regenerated N blocks in Xms`. Cold-start bootstrap runs
once if `blocks.gen.json` is missing or older than the newest
source file.
Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
2 issues found across 7 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/vite/plugin.js">
<violation number="1" location="src/vite/plugin.js:253">
P2: Reload POST can run before dev server has a real address. Then it falls back to 5173 and the blocks sync can fail silently. Add a listen-ready guard before sending request.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…ction - Remove leftover console.log in workerEntry serverFn cache path - Remove DECO_CACHE_DISABLE from isDevMode() — it is a cache tuning flag, not a dev-mode signal, and must not bypass auth - Use import.meta.env.DEV directly in decofile auth bypass instead of isDevMode() to avoid any future coupling with cache flags Co-Authored-By: Claude Opus 4.6 <[email protected]>
JonasJesus42
previously approved these changes
May 21, 2026
There was a problem hiding this comment.
1 issue found across 3 files (changes from recent commits).
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
JonasJesus42
approved these changes
May 21, 2026
|
🎉 This PR is included in version 5.4.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
4 tasks done
JonasJesus42
added a commit
that referenced
this pull request
Sep 9, 2026
## Problema
Ligar o fast-deploy **aumentava** o consumo de memória do isolate em vez
de reduzir. O site passa a segurar o decofile duas vezes.
O plugin vite emite, para SSR, `export const blocks =
JSON.parse("<json>")` (`packages/tanstack/src/vite/plugin.js`). O site
importa isso num binding de módulo:
```ts
import { blocks as generatedBlocks } from "../.deco/blocks.gen";
```
Esse binding fica alcançável pela vida inteira do isolate. Quando
`ensureBlocksHydrated` roda, `setBlocks(JSON.parse(kvSnapshot))` cria um
**segundo** grafo — o bundlado nunca fica coletável.
Medido com o decofile de 9.2 MB da granado.com.br (`node --expose-gc`,
`JSON.parse` do mesmo arquivo duas vezes):
| | heap |
|---|---|
| 1º grafo (bundlado) | +13.6 MB |
| 2º grafo (KV) | +13.4 MB |
| **total com os dois** | **27.0 MB** |
Além disso o bundle server carrega a string JSON escapada de 9.2 MB, que
também ocupa memória.
Contexto: a granado.com.br está com `DECO_FAST_DEPLOY=1` desde #188 e
vinha batendo no limite de memória do CF (P90 em 147 MB, limite de 128
MB). Ao semear o snapshot no KV para testar, o consumo pioraria — foi o
que levou a investigar.
## Mudanças
**1. `decoVitePlugin({ fastDeploy: true })` stuba `blocks.gen` no bundle
SSR também**, deixando a cópia do KV como única. Opt-in e default
inalterado, porque remove o fallback bundlado.
**2. `ensureBlocksHydrated` falha alto quando não existe snapshot
bundlado.**
Isso é o que torna o item 1 seguro. Antes, qualquer falha caía em "warn
+ serve bundled". Com o bundle stubado, esse caminho serviria um site
**vazio com 200** — que seria cacheado no edge e sobreviveria à falha de
KV que o causou. Agora joga erro (5xx visível, propaga: `handleRequest`
não tem try/catch e `instrumentWorker` é try/finally sem catch) e não
trava `kvHydrated`, então o request seguinte tenta de novo em vez de
fixar o isolate num decofile vazio.
A detecção lê o mapa em memória (`loadBlocks()` vazio) em vez de uma
flag de build. Isso vale nas duas configurações e garante que sites que
ainda bundlam o decofile — o default — se comportem exatamente como
antes.
## Test plan
- [x] 9 testes novos: stub SSR sob a flag, client ainda stubado, default
SSR preservado, módulos alheios intactos, e as transições de falha sem
fallback (snapshot ausente, KV fora, sem deployment id, retry após seed)
+ não-regressão do caminho com bundled presente
- [x] `vitest run packages/tanstack/src/sdk/kvHydration.test.ts
packages/tanstack/src/vite/plugin.test.ts` → 32 passed
- [x] `typecheck` do `@decocms/tanstack` → exit 0
- [x] Suíte do pacote: 225 passed / 2 failed — as 2 falhas (`draft
preview`) foram confirmadas **pré-existentes** em `origin/main` limpa,
sem relação com este diff
## Como um site adota
Requer os três juntos, e o pipeline precisa semear
`decofile:<deployment-id>` **antes** da nova versão ativar:
```ts
// vite.config.ts
decoVitePlugin({ fastDeploy: true })
```
```jsonc
// wrangler.jsonc
"vars": { "DECO_FAST_DEPLOY": "1" },
"kv_namespaces": [{ "binding": "DECO_KV", "id": "..." }]
```
```bash
deco-sync-blocks-to-kv --write --all --deployment-id "$SHA"
wrangler deploy --var DECO_DEPLOYMENT_ID:"$SHA"
deco-sync-blocks-to-kv --set-live --deployment-id "$SHA"
```
Sem o seed, a nova versão sobe e joga 5xx — de propósito, é preferível a
servir vazio. Vale documentar isso no guia de fast-deploy.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes fast-deploy holding the decofile twice in isolate memory, so
enabling it now reduces memory instead of increasing it (measured +27 MB
for a 9.2 MB decofile). `decoVitePlugin({ fastDeploy: true })` stubs
`blocks.gen` in the SSR bundle, and `ensureBlocksHydrated` throws when
no bundled fallback exists instead of serving an empty site with 200
that gets edge-cached.
**Migration**
- Seed `decofile:<deployment-id>` in KV before the new version
activates; without it, requests fail with 5xx on purpose.
<sup>Written for commit d9e841c.
Summary will update on new commits.</sup>
<a href="https://cubic.dev/pr/decocms/blocks/pull/542?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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
Closes the gap where edits to
.deco/blocks/*.json(manual,sync-decofile.ts, or daemonPATCH /fs/file/.deco/blocks/*) didn't propagate invite devbecause nothing rebuiltsrc/server/cms/blocks.gen.json.decoVitePlugin()already had a watcher that invalidates the SSR module whenblocks.gen.jsonchanges — this PR closes the loop from the source dir to that artifact.Changes
scripts/generate-blocks.ts: extractgenerateBlocks({ blocksDir, outFile, silent? })as the programmatic entry; CLI shim preserved behindisMainModule()sonpm run generate:blocksand migration scripts keep working.src/vite/plugin.jsconfigureServer:.deco/blocks/to chokidar (it's outside Vite's default graph).add/change/unlinkof*.jsoninside it, debounces 150ms, callsgenerateBlocks(loaded via the existingtsx/esm/apitsImportpattern — no consumer dependency ontsx).writeAtomicallyrename burst collapses into one regen.blocks.gen.jsonis missing or older than the newest source file.[deco] regenerated N blocks in Xms.Production builds are unaffected — all new code lives in
configureServer, which only runs undervite dev.Test plan
tsc --noEmitcleannpx tsx scripts/generate-blocks.ts --blocks-dir ... --out-file ...(CLI shim) regenerates a fixturegenerateBlocks(...)returns{ count, collisions, jsonFile, outFile, empty }and respectssilent: truecasaevideo-storefront) after this lands as a release: runvite dev, edit a file in.deco/blocks/, refresh — change appears withoutnpm run generate:blocksand without restarttsx node_modules/@decocms/start/scripts/sync-decofile.ts --site ...running against a live dev server — burst of writes triggers a single regenMade with Cursor
Summary by cubic
Live-reload
.deco/blocks/*.jsoninvite devand fix HMR by regenerating blocks, posting them to a dev endpoint, and disabling the Cache API in dev. Changes apply immediately withoutgenerate:blocksor restarting.New Features
.deco/blocks/**/*.jsonand regenerate with a 150ms debounce and in-flight guard.tsx/esm/api; cold-start if the artifact is missing or stale./.decofileand trigger a client full reload.Bug Fixes
.tsstub when content changes.import.meta.env.DEV/NODE_ENV=developmentand supportsDECO_PREVIEW=true; skip/.decofileauth only in dev; remove a leftover debug log.Written for commit 5b65921. Summary will update on new commits. Review in cubic