Skip to content

feat(vite): live-reload .deco/blocks/*.json edits in dev - #188

Merged
guitavano merged 4 commits into
mainfrom
feat/watch-deco-blocks-dev
May 21, 2026
Merged

guitavano merged 4 commits into
mainfrom
feat/watch-deco-blocks-dev

Conversation

@vibe-dex

@vibe-dex vibe-dex commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes the gap where edits to .deco/blocks/*.json (manual, sync-decofile.ts, or daemon PATCH /fs/file/.deco/blocks/*) didn't propagate in vite dev because nothing rebuilt src/server/cms/blocks.gen.json.

decoVitePlugin() already had a watcher that invalidates the SSR module when blocks.gen.json changes — this PR closes the loop from the source dir to that artifact.

Changes

  • scripts/generate-blocks.ts: extract generateBlocks({ blocksDir, outFile, silent? }) as the programmatic entry; CLI shim preserved behind isMainModule() so npm run generate:blocks and migration scripts keep working.
  • src/vite/plugin.js configureServer:
    • Adds .deco/blocks/ to chokidar (it's outside Vite's default graph).
    • Listens for add / change / unlink of *.json inside it, debounces 150ms, calls generateBlocks (loaded via the existing tsx/esm/api tsImport pattern — no consumer dependency on tsx).
    • In-flight guard with queued-rerun bit so a writeAtomically rename burst collapses into one regen.
    • Cold-start bootstrap: runs once if blocks.gen.json is missing or older than the newest source file.
    • Logs [deco] regenerated N blocks in Xms.

Production builds are unaffected — all new code lives in configureServer, which only runs under vite dev.

Test plan

  • tsc --noEmit clean
  • npx tsx scripts/generate-blocks.ts --blocks-dir ... --out-file ... (CLI shim) regenerates a fixture
  • Programmatic generateBlocks(...) returns { count, collisions, jsonFile, outFile, empty } and respects silent: true
  • In a consuming site (e.g. casaevideo-storefront) after this lands as a release: run vite dev, edit a file in .deco/blocks/, refresh — change appears without npm run generate:blocks and without restart
  • Same with tsx node_modules/@decocms/start/scripts/sync-decofile.ts --site ... running against a live dev server — burst of writes triggers a single regen

Made with Cursor


Summary by cubic

Live-reload .deco/blocks/*.json in vite dev and fix HMR by regenerating blocks, posting them to a dev endpoint, and disabling the Cache API in dev. Changes apply immediately without generate:blocks or restarting.

  • New Features

    • Watch .deco/blocks/**/*.json and regenerate with a 150ms debounce and in-flight guard.
    • Lazy-load the generator via tsx/esm/api; cold-start if the artifact is missing or stale.
    • After regen, POST blocks to /.decofile and trigger a client full reload.
  • Bug Fixes

    • Prevent HMR breakage by avoiding SSR module invalidation; only rewrite the .ts stub when content changes.
    • Disable Cache API in dev to avoid stale responses; dev-mode now uses import.meta.env.DEV/NODE_ENV=development and supports DECO_PREVIEW=true; skip /.decofile auth only in dev; remove a leftover debug log.

Written for commit 5b65921. Summary will update on new commits. Review in cubic

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]>
@vibe-dex
vibe-dex requested a review from a team May 19, 2026 21:48

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/vite/plugin.js Resolved
Comment thread src/sdk/workerEntry.ts Resolved
…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
JonasJesus42 previously approved these changes May 21, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/sdk/env.ts Resolved
@guitavano
guitavano merged commit a1531e5 into main May 21, 2026
1 check passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 5.4.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants