Como Corrigir a Quebra do Runtime do Cloudflare Workers pela IA
Agentes de IA importam módulos embutidos do Node.js como fs, crypto e path para o Cloudflare Workers, causando erros em tempo de execução porque o runtime do Workers não é Node.js.
O agente escreve código que funciona localmente com Node.js, mas falha ao fazer deploy ou em tempo de execução no Cloudflare Workers porque o runtime do Workers é um isolado V8 — não Node.js.
O sintoma
O agente importa módulos embutidos do Node.js ou pacotes npm que internamente requerem APIs do Node.js.
// worker.ts — WRONGimport { createHash } from "crypto"; // Node built-in — not availableimport { readFileSync } from "fs"; // Node built-in — not availableimport { resolve } from "path"; // Node built-in — not availableimport { IncomingMessage } from "http"; // Node built-in — not available
export default { async fetch(request: Request, env: Env) { const hash = createHash("sha256").update("data").digest("hex"); return new Response(hash); },};// Error at runtime: Cannot read properties of undefined (reading 'createHash')Por que isso acontece
A maioria dos dados de treinamento do agente tem como alvo o Node.js. O modelo sabe que crypto, fs e path funcionam para hash, acesso a arquivos e manipulação de caminhos, então ele os utiliza. Ele não distingue o runtime do Workers do Node.js a menos que seja explicitamente instruído.
Como identificar
import ... from "crypto"/"fs"/"path"/"http"/"stream"em arquivos Worker.wrangler devfunciona, maswrangler deploylança um aviso de empacotamento sobre módulos Node.js não resolvidos.- A seção de flags de compatibilidade do Wrangler em
wrangler.tomlestá ausente ou usa uma data anterior a2022-11-30. - Dependências que internamente usam
require("node:...")sem um shim de compatibilidade do Workers.
Como corrigir
Use APIs Web Standard — elas estão disponíveis nativamente no Workers.
// worker.ts — CORRECTexport default { async fetch(request: Request, env: Env) { // Web Crypto API — standard, available in Workers const encoder = new TextEncoder(); const data = encoder.encode("data"); const hashBuffer = await crypto.subtle.digest("SHA-256", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); return new Response(hash); },};# wrangler.toml — enable Node.js compat shims for packages that need themcompatibility_date = "2024-09-23"compatibility_flags = ["nodejs_compat"][ ] No imports from "crypto", "fs", "path", "http", "stream", "os", "buffer" (use node: prefix + nodejs_compat flag if unavoidable)[ ] Use crypto.subtle for hashing/signing (Web Crypto API)[ ] Use env bindings (KV, R2, D1) instead of fs for storage[ ] Set compatibility_date to a recent date in wrangler.toml[ ] Add nodejs_compat flag only for third-party packages that require it[ ] Run "wrangler deploy --dry-run" to catch bundling errors before deployingPrompt de Correção
This code imports Node.js built-in modules (crypto, fs, path, http) that arenot available in the Cloudflare Workers runtime. Rewrite it using Web StandardAPIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, andCloudflare bindings (KV, R2, D1) for storage. If a third-party dependencyrequires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.tomland note that in a comment.Teste
# Dry-run deploy to catch Node.js module errorswrangler deploy --dry-run --outdir dist 2>&1 | grep -i "error\|unresolved\|node:" && echo "FAIL" || echo "OK"
# Check for raw Node built-in importsgrep -rn '^import.*from "(crypto|fs|path|http|stream|os)"' src/ \ && echo "FAIL: Node.js built-in import found" || echo "OK"