@zero2webmaster/starter-kit 0.29.1 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cli.js +0 -0
- package/dist/scaffolders/cf-pages.js +3 -3
- package/dist/scaffolders/common.js +3 -3
- package/dist/scaffolders/nextjs.js +702 -8
- package/dist/standards.d.ts +1 -1
- package/dist/standards.js +14 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# z2w-starter-kit
|
|
2
2
|
|
|
3
|
-
**Version:** 0.
|
|
3
|
+
**Version:** 0.30.0 | **Framework:** 2.19.0
|
|
4
4
|
|
|
5
5
|
> Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
|
|
6
6
|
|
|
@@ -135,4 +135,4 @@ Inquiries: kerry@zero2webmaster.com.
|
|
|
135
135
|
---
|
|
136
136
|
|
|
137
137
|
*Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
|
|
138
|
-
*Version: 0.
|
|
138
|
+
*Version: 0.30.0 | Last Updated: 2026-09-11*
|
package/dist/cli.js
CHANGED
|
File without changes
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
import { commonBaseFiles, resolveBrandSpec, sub, } from "./common.js";
|
|
20
20
|
const NARRATIVE = `## What this is
|
|
21
21
|
|
|
22
|
-
\`{{slug}}\` is a Cloudflare Pages static site scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (
|
|
22
|
+
\`{{slug}}\` is a Cloudflare Pages static site scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (a standing organization requirement) is wired in at instantiation.
|
|
23
23
|
|
|
24
24
|
**Quick start for contributors:**
|
|
25
25
|
|
|
@@ -52,7 +52,7 @@ const INDEX_HTML_TEMPLATE = `<!DOCTYPE html>
|
|
|
52
52
|
<meta charset="utf-8" />
|
|
53
53
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
54
54
|
|
|
55
|
-
<!-- SEO baseline (
|
|
55
|
+
<!-- SEO baseline (a standing organization requirement). Replace
|
|
56
56
|
__SITE_URL__ and __FATHOM_SITE_ID__ before deploy. -->
|
|
57
57
|
<title>{{brand_name}} — {{slug}}</title>
|
|
58
58
|
<meta name="description" content="{{description}}" />
|
|
@@ -257,7 +257,7 @@ Per SEO baseline standing requirement 2026-05-30.
|
|
|
257
257
|
`;
|
|
258
258
|
const SEO_CHECKLIST_TEMPLATE = `# SEO Checklist — {{slug}}
|
|
259
259
|
|
|
260
|
-
|
|
260
|
+
A standing organization requirement. Run before adding a new page AND before launch.
|
|
261
261
|
|
|
262
262
|
## Per-page checklist (every new HTML file)
|
|
263
263
|
|
|
@@ -300,7 +300,7 @@ Format: [Semantic Versioning](https://semver.org/).
|
|
|
300
300
|
## [{{version}}] — {{date}}
|
|
301
301
|
|
|
302
302
|
### Added
|
|
303
|
-
- Initial scaffold via \`@zero2webmaster/starter-kit
|
|
303
|
+
- Initial scaffold via \`@zero2webmaster/starter-kit\`.
|
|
304
304
|
- Brand: {{brand_name}}.
|
|
305
305
|
`;
|
|
306
306
|
// Emitted by default for every project type (always-on standard, like the
|
|
@@ -623,7 +623,7 @@ export function buildClaudeMd(inputs, opts, spec, perTypeNarrative) {
|
|
|
623
623
|
|
|
624
624
|
**Project Version:** {{version}} | **Framework:** {{framework_version}} | **Last Updated:** {{date}}
|
|
625
625
|
|
|
626
|
-
> Scaffolded {{date}} via \`@zero2webmaster/starter-kit
|
|
626
|
+
> Scaffolded {{date}} via \`@zero2webmaster/starter-kit\`.
|
|
627
627
|
> CLAUDE.md is the source-of-truth file for this project. If \`AGENTS.md\` or \`GEMINI.md\` exist in the same directory, mirror changes to them; do not create them just to hold this content.
|
|
628
628
|
|
|
629
629
|
---
|
|
@@ -650,7 +650,7 @@ ${AGENTS_BODY_MARKER}
|
|
|
650
650
|
|
|
651
651
|
---
|
|
652
652
|
|
|
653
|
-
*Scaffolded {{date}} via \`@zero2webmaster/starter-kit
|
|
653
|
+
*Scaffolded {{date}} via \`@zero2webmaster/starter-kit\`.*
|
|
654
654
|
*Version: {{version}} | Framework: {{framework_version}} | Last Updated: {{date}}*
|
|
655
655
|
`;
|
|
656
656
|
return {
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
|
|
50
50
|
const NARRATIVE = `## What this is
|
|
51
51
|
|
|
52
|
-
\`{{slug}}\` is a Next.js App Router project scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (
|
|
52
|
+
\`{{slug}}\` is a Next.js App Router project scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (a standing organization requirement) is wired in at instantiation.
|
|
53
53
|
|
|
54
54
|
**Quick start for contributors:**
|
|
55
55
|
|
|
@@ -2035,10 +2035,15 @@ export function clientIpFrom(headers: Headers): string {
|
|
|
2035
2035
|
/**
|
|
2036
2036
|
* The shared-store limiter, emitted only for `dbStrategy === "neon-postgres"`.
|
|
2037
2037
|
*
|
|
2038
|
-
* Self-contained on purpose
|
|
2039
|
-
*
|
|
2040
|
-
*
|
|
2041
|
-
*
|
|
2038
|
+
* Self-contained on purpose — and the reason CHANGED on 2026-09-11, so the old
|
|
2039
|
+
* one is corrected here rather than left standing as a lie. It used to be "the
|
|
2040
|
+
* Next.js scaffold ships NO db layer"; it now ships `db/client.ts`. The reason
|
|
2041
|
+
* this module still brings its own client is that it uses the HTTP driver
|
|
2042
|
+
* (`neon()`), which opens no pool and therefore has none of the idle-socket
|
|
2043
|
+
* exposure `db/pool-errors.ts` exists for — while `db/client.ts` deliberately
|
|
2044
|
+
* uses the POOLED WebSocket driver the app's real queries need. Two drivers,
|
|
2045
|
+
* two different jobs. It also keeps the limiter usable whichever ORM the project
|
|
2046
|
+
* later adopts.
|
|
2042
2047
|
*/
|
|
2043
2048
|
const RATE_LIMIT_DURABLE_TEMPLATE = `import "server-only";
|
|
2044
2049
|
|
|
@@ -2796,7 +2801,14 @@ import { fileURLToPath } from "node:url";
|
|
|
2796
2801
|
|
|
2797
2802
|
export default defineConfig({
|
|
2798
2803
|
test: {
|
|
2799
|
-
|
|
2804
|
+
// \`db\` is in this list because the scaffolder emits \`db/pool-errors.test.ts\`
|
|
2805
|
+
// there. It was MISSING when that test first shipped (2026-09-11), so the
|
|
2806
|
+
// emitted test collected zero files and vitest exited "No test files found"
|
|
2807
|
+
// — a guard that ships, looks present in the tree, and never runs. Caught
|
|
2808
|
+
// only by running the real toolchain in a throwaway scaffold; no assertion
|
|
2809
|
+
// on the template string could have seen it. If you add an emitted test
|
|
2810
|
+
// under a new top-level directory, add that directory HERE too.
|
|
2811
|
+
include: ["test/**/*.test.ts", "{app,components,lib,db}/**/*.test.{ts,tsx}"],
|
|
2800
2812
|
// .next is NOT in vitest's default exclude list — without this, the runner
|
|
2801
2813
|
// walks build output after the first \`next build\`.
|
|
2802
2814
|
exclude: ["node_modules/**", ".next/**", "dist/**"],
|
|
@@ -4559,7 +4571,7 @@ export default function Icon() {
|
|
|
4559
4571
|
`;
|
|
4560
4572
|
const SEO_CHECKLIST_TEMPLATE = `# SEO Checklist — {{slug}}
|
|
4561
4573
|
|
|
4562
|
-
|
|
4574
|
+
A standing organization requirement. Run before adding a new page AND before launch.
|
|
4563
4575
|
|
|
4564
4576
|
## Per-page checklist (every new page)
|
|
4565
4577
|
|
|
@@ -4676,11 +4688,674 @@ function withEmailDeps(pkgJson) {
|
|
|
4676
4688
|
* helper and must keep producing the same bytes. Callers apply their merges in a
|
|
4677
4689
|
* fixed order, so the output is deterministic without sorting.
|
|
4678
4690
|
*/
|
|
4691
|
+
/**
|
|
4692
|
+
* The Neon data layer, emitted for every `dbStrategy === "neon-postgres"`
|
|
4693
|
+
* Next.js project.
|
|
4694
|
+
*
|
|
4695
|
+
* 🔴 WHY THIS EXISTS, AND WHY IT IS THE SCAFFOLDER'S JOB RATHER THAN EACH APP'S
|
|
4696
|
+
* (added 2026-09-11, v0.30.0, on a measured ACTION from `z2w-observability-bridge`).
|
|
4697
|
+
*
|
|
4698
|
+
* This scaffolder emitted NO db layer at all — the `RATE_LIMIT_DURABLE_TEMPLATE`
|
|
4699
|
+
* comment said so in as many words and brought its own thin client as a result.
|
|
4700
|
+
* So every Z2W Next.js project hand-rolled `db/client.ts` from a sibling, and
|
|
4701
|
+
* the copies drifted to 85 / 97 / 223 / 279 lines while staying recognisably one
|
|
4702
|
+
* template. Eight of them hand-rolled it WITHOUT a pool error handler.
|
|
4703
|
+
*
|
|
4704
|
+
* The bridge's measurement, 2026-09-09: of 54 open incidents across the
|
|
4705
|
+
* ecosystem, **11 across 7 projects were one dropped-Postgres-connection bug —
|
|
4706
|
+
* 20% of everything open.** Three projects that added a pool-errors module have
|
|
4707
|
+
* emitted nothing since; six without it were still emitting, including the two
|
|
4708
|
+
* most recent incidents in the whole portfolio. Correlational, not controlled —
|
|
4709
|
+
* but the mechanism is understood exactly (see `db/pool-errors.ts`), which is
|
|
4710
|
+
* what makes the correlation worth acting on.
|
|
4711
|
+
*
|
|
4712
|
+
* ⚠️ THE REFERENCE IMPLEMENTATIONS DISAGREE, AND THE ONE WITH THE TEST IS THE
|
|
4713
|
+
* INCOMPLETE ONE. `site-control/db/pool-errors.ts` has the better structure
|
|
4714
|
+
* (driver-free, injectable logger, total classifier, redaction) and the only
|
|
4715
|
+
* test in the portfolio — but it attaches CHANNEL 1 ONLY. `leaderboard`'s
|
|
4716
|
+
* attaches both channels and its comments record why: a project that shipped the
|
|
4717
|
+
* pool-level listener alone watched its probe die with the identical stack.
|
|
4718
|
+
* What is emitted here is the union, and the emitted test covers channel 2
|
|
4719
|
+
* explicitly so the gap cannot reopen.
|
|
4720
|
+
*/
|
|
4721
|
+
const DB_POOL_ERRORS_TEMPLATE = `// Keeping a dead IDLE connection from killing the process.
|
|
4722
|
+
//
|
|
4723
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
4724
|
+
// 🔴 THE FAILURE THIS EXISTS FOR — measured across the Z2W portfolio, not argued
|
|
4725
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
4726
|
+
//
|
|
4727
|
+
// \`pool\` in \`db/client.ts\` is module-cached and long-lived. An idle pooled
|
|
4728
|
+
// client is not a dormant object — it still holds an open socket to a live
|
|
4729
|
+
// Postgres backend. Neon closes those routinely, and scale-to-zero is the
|
|
4730
|
+
// headline case: "terminating connection due to administrator command" is
|
|
4731
|
+
// literally Postgres telling you the backend was shut down underneath you.
|
|
4732
|
+
//
|
|
4733
|
+
// When that happens the driver emits 'error' on the connection object rather
|
|
4734
|
+
// than rejecting a query — there is no query; nothing was in flight. Node's
|
|
4735
|
+
// EventEmitter rule is that an 'error' event WITH NO LISTENER is re-thrown as an
|
|
4736
|
+
// uncaughtException, which on Vercel kills the lambda. So the ABSENCE of a
|
|
4737
|
+
// listener turns an ordinary, expected, entirely recoverable network event into
|
|
4738
|
+
// a process kill — and the stack trace names whatever unlucky request happened
|
|
4739
|
+
// to be running, not the socket that actually died. That misattribution is what
|
|
4740
|
+
// makes it expensive rather than merely bad.
|
|
4741
|
+
//
|
|
4742
|
+
// ⚠️ THIS IS THE ORDINARY PATH ON NEON, NOT AN EDGE CASE. [[neon-postgres]] asks
|
|
4743
|
+
// you to PRESERVE scale-to-zero — \`/api/health\` is DB-free precisely so a
|
|
4744
|
+
// 60-second uptime probe never wakes the compute. So Neon closing an idle socket
|
|
4745
|
+
// is the designed behaviour of your own stack. The discipline that protects the
|
|
4746
|
+
// CU-hour quota is the same fact that makes this listener load-bearing.
|
|
4747
|
+
//
|
|
4748
|
+
// Why it survives review: \`pg\`'s docs tell you to attach the listener, so nobody
|
|
4749
|
+
// re-checks that it happened; it never fires locally (a dev process rarely idles
|
|
4750
|
+
// past the timeout, CI never does); and reproducing it needs a real
|
|
4751
|
+
// scale-to-zero gap.
|
|
4752
|
+
//
|
|
4753
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
4754
|
+
// 🔴 THERE ARE TWO CHANNELS, AND ONE LISTENER DOES NOT COVER THE OTHER
|
|
4755
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
4756
|
+
//
|
|
4757
|
+
// \`pg-pool\` attaches its idle listener when a client is RELEASED back to the
|
|
4758
|
+
// pool and REMOVES it when the client is checked out again. So \`pool.on('error')\`
|
|
4759
|
+
// covers exactly "a client sitting idle in the pool whose socket died" — and
|
|
4760
|
+
// covers nothing at all for a client CHECKED OUT to a caller. A checked-out
|
|
4761
|
+
// client's error lands on the CLIENT, with no listener, and Node re-throws it as
|
|
4762
|
+
// an uncaughtException: the same process kill, through the one door the
|
|
4763
|
+
// pool-level listener leaves open.
|
|
4764
|
+
//
|
|
4765
|
+
// That door is wide open in any app that wraps queries in a transaction, because
|
|
4766
|
+
// checked-out is then the NORMAL state of the pool rather than an edge case.
|
|
4767
|
+
//
|
|
4768
|
+
// Both listeners are attached below and neither is redundant. This is not
|
|
4769
|
+
// theoretical: a Z2W project added the pool-level listener alone and watched its
|
|
4770
|
+
// probe process die with the identical stack.
|
|
4771
|
+
//
|
|
4772
|
+
// Recovery needs nothing from you: the pool has already discarded the dead
|
|
4773
|
+
// client by the time this runs, and the next query opens a fresh connection.
|
|
4774
|
+
// The correct handling is to observe and carry on.
|
|
4775
|
+
|
|
4776
|
+
/**
|
|
4777
|
+
* The narrowest shapes this module needs. Typed structurally ON PURPOSE so no
|
|
4778
|
+
* driver is imported here — that keeps this file cheap and lets a test pass a
|
|
4779
|
+
* bare \`EventEmitter\` instead of standing up a real \`Pool\`.
|
|
4780
|
+
*/
|
|
4781
|
+
export type PoolClientErrorSource = {
|
|
4782
|
+
on(event: "error", listener: (err: unknown) => void): unknown;
|
|
4783
|
+
};
|
|
4784
|
+
|
|
4785
|
+
export type PoolErrorSource = {
|
|
4786
|
+
on(event: "error", listener: (err: unknown) => void): unknown;
|
|
4787
|
+
on(event: "connect", listener: (client: PoolClientErrorSource) => void): unknown;
|
|
4788
|
+
};
|
|
4789
|
+
|
|
4790
|
+
/**
|
|
4791
|
+
* Anything shaped like a Postgres connection URL, with or without credentials.
|
|
4792
|
+
*
|
|
4793
|
+
* 🔴 NOT hypothetical hygiene. \`@neondatabase/serverless\` hangs
|
|
4794
|
+
* \`config.connectionString\` off the error it raises on a connection failure, so
|
|
4795
|
+
* a naive \`console.error(err)\` on a dead socket prints
|
|
4796
|
+
* \`postgresql://owner:THE-REAL-PASSWORD@host/db\` into the terminal, the
|
|
4797
|
+
* scrollback, and any agent transcript reading it. A Z2W project leaked a live
|
|
4798
|
+
* password exactly this way and had to rotate the role ([[terminal-secret-hygiene]]).
|
|
4799
|
+
*
|
|
4800
|
+
* A pool 'error' listener receives PRECISELY that class of error object, which
|
|
4801
|
+
* makes this the highest-risk place in the repo for a naive log line. Two
|
|
4802
|
+
* independent defences, because either alone is one edit from being lost:
|
|
4803
|
+
* \`describePoolError\` never returns the error OBJECT (only \`message\` + \`code\`),
|
|
4804
|
+
* and the message it does return is run through this scrub.
|
|
4805
|
+
*/
|
|
4806
|
+
export function redactConnectionStrings(text: string): string {
|
|
4807
|
+
return text.replace(/\\b(postgres(?:ql)?:\\/\\/)[^\\s"'\`]*/gi, "$1[REDACTED]");
|
|
4808
|
+
}
|
|
4809
|
+
|
|
4810
|
+
/**
|
|
4811
|
+
* Is this the ordinary "the socket died" event, as opposed to something the
|
|
4812
|
+
* server actively rejected?
|
|
4813
|
+
*
|
|
4814
|
+
* ONE classifier, deliberately. Two lists for "was this the socket dying?" would
|
|
4815
|
+
* be two statements of one rule, and the day they drift is the day one path
|
|
4816
|
+
* reports what the other silently swallows.
|
|
4817
|
+
*/
|
|
4818
|
+
export function isConnectionError(err: unknown): boolean {
|
|
4819
|
+
let message = "";
|
|
4820
|
+
let code = "";
|
|
4821
|
+
if (typeof err === "string") {
|
|
4822
|
+
message = err;
|
|
4823
|
+
} else if (err && typeof err === "object") {
|
|
4824
|
+
const candidate = err as { message?: unknown; code?: unknown };
|
|
4825
|
+
if (typeof candidate.message === "string") message = candidate.message;
|
|
4826
|
+
if (typeof candidate.code === "string") code = candidate.code;
|
|
4827
|
+
}
|
|
4828
|
+
|
|
4829
|
+
// 57P01 is Postgres' own admin_shutdown — what Neon sends on scale-to-zero.
|
|
4830
|
+
if (code === "57P01" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT") {
|
|
4831
|
+
return true;
|
|
4832
|
+
}
|
|
4833
|
+
|
|
4834
|
+
const m = message.toLowerCase();
|
|
4835
|
+
return (
|
|
4836
|
+
m.includes("connection terminated") ||
|
|
4837
|
+
m.includes("terminating connection due to administrator command") ||
|
|
4838
|
+
m.includes("server closed the connection") ||
|
|
4839
|
+
m.includes("socket hang up") ||
|
|
4840
|
+
m.includes("read econnreset")
|
|
4841
|
+
);
|
|
4842
|
+
}
|
|
4843
|
+
|
|
4844
|
+
export type PoolErrorDescription = {
|
|
4845
|
+
/**
|
|
4846
|
+
* \`true\` when this is the ordinary Neon-closes-an-idle-socket event: expected,
|
|
4847
|
+
* self-healing, and NOT worth an error-tracker issue. \`false\` means something
|
|
4848
|
+
* with no story, which is exactly what should be reported.
|
|
4849
|
+
*/
|
|
4850
|
+
expected: boolean;
|
|
4851
|
+
/** Scrubbed \`err.message\` — never the error object. */
|
|
4852
|
+
message: string;
|
|
4853
|
+
/** \`err.code\` when the driver set one (\`57P01\`, \`ECONNRESET\`, …), else \`""\`. */
|
|
4854
|
+
code: string;
|
|
4855
|
+
};
|
|
4856
|
+
|
|
4857
|
+
/**
|
|
4858
|
+
* Turn whatever arrived on the pool into something safe to print.
|
|
4859
|
+
*
|
|
4860
|
+
* Pure and TOTAL: every branch returns a description, including for \`null\`, a
|
|
4861
|
+
* string, a number, or an object whose getters throw. A classifier that can
|
|
4862
|
+
* throw is useless here — see \`guardPoolErrors\` for why.
|
|
4863
|
+
*/
|
|
4864
|
+
export function describePoolError(err: unknown): PoolErrorDescription {
|
|
4865
|
+
let message = "";
|
|
4866
|
+
let code = "";
|
|
4867
|
+
|
|
4868
|
+
try {
|
|
4869
|
+
if (typeof err === "string") {
|
|
4870
|
+
message = err;
|
|
4871
|
+
} else if (err && typeof err === "object") {
|
|
4872
|
+
const candidate = err as { message?: unknown; code?: unknown };
|
|
4873
|
+
if (typeof candidate.message === "string") message = candidate.message;
|
|
4874
|
+
if (typeof candidate.code === "string") code = candidate.code;
|
|
4875
|
+
}
|
|
4876
|
+
} catch {
|
|
4877
|
+
// A getter on the error object threw. Nothing to salvage, and certainly
|
|
4878
|
+
// nothing worth crashing over.
|
|
4879
|
+
message = "";
|
|
4880
|
+
code = "";
|
|
4881
|
+
}
|
|
4882
|
+
|
|
4883
|
+
let expected = false;
|
|
4884
|
+
try {
|
|
4885
|
+
expected = isConnectionError(err);
|
|
4886
|
+
} catch {
|
|
4887
|
+
// Treat an unclassifiable error as UNEXPECTED. That direction reports
|
|
4888
|
+
// something a human then looks at; the other silently swallows the one case
|
|
4889
|
+
// we have no explanation for.
|
|
4890
|
+
expected = false;
|
|
4891
|
+
}
|
|
4892
|
+
|
|
4893
|
+
return {
|
|
4894
|
+
expected,
|
|
4895
|
+
message: redactConnectionStrings(message || "(no message)"),
|
|
4896
|
+
code,
|
|
4897
|
+
};
|
|
4898
|
+
}
|
|
4899
|
+
|
|
4900
|
+
export type GuardPoolErrorsOptions = {
|
|
4901
|
+
/** Names the pool in log lines (\`"runtime"\`, \`"migrations"\`). */
|
|
4902
|
+
label?: string;
|
|
4903
|
+
/**
|
|
4904
|
+
* Where an UNEXPECTED pool error goes. Called with an already-scrubbed
|
|
4905
|
+
* description — never the raw error — so a reporter cannot leak the password
|
|
4906
|
+
* either. Wire this to Sentry (or whatever this project uses) if it has one.
|
|
4907
|
+
*/
|
|
4908
|
+
report?: (description: PoolErrorDescription, label: string) => void;
|
|
4909
|
+
/** Injectable for tests. Defaults to the real console. */
|
|
4910
|
+
logger?: { warn: (message: string) => void; error: (message: string) => void };
|
|
4911
|
+
};
|
|
4912
|
+
|
|
4913
|
+
/**
|
|
4914
|
+
* Attach the 'error' listeners that stop an idle- or checked-out-socket death
|
|
4915
|
+
* from becoming an uncaughtException. Returns the same pool, so it can wrap a
|
|
4916
|
+
* constructor call.
|
|
4917
|
+
*
|
|
4918
|
+
* MUST be called immediately after construction and BEFORE the first \`await\`,
|
|
4919
|
+
* so there is no window in which the pool is live and unguarded.
|
|
4920
|
+
*
|
|
4921
|
+
* 🔴 THE LISTENER MAY NOT THROW, AND THAT INCLUDES ITS REPORTING PATH. A throw
|
|
4922
|
+
* escaping an 'error' listener IS an uncaughtException — so a listener whose
|
|
4923
|
+
* reporter can throw (tracker not initialised, an odd logger, a getter on the
|
|
4924
|
+
* error object) REINTRODUCES the exact bug while looking like the fix, on the
|
|
4925
|
+
* rare path nobody exercises. Hence the belt-and-braces: \`describePoolError\` is
|
|
4926
|
+
* total, and every step below sits inside a \`try\`.
|
|
4927
|
+
*
|
|
4928
|
+
* An expected connection error is a WARNING, not a reported issue. Filing an
|
|
4929
|
+
* issue every time Neon scales to zero generates exactly the noise that gets an
|
|
4930
|
+
* alert rule muted — or this listener deleted as "spammy" — which restores the
|
|
4931
|
+
* crash.
|
|
4932
|
+
*/
|
|
4933
|
+
export function guardPoolErrors<T extends PoolErrorSource>(
|
|
4934
|
+
pool: T,
|
|
4935
|
+
opts: GuardPoolErrorsOptions = {},
|
|
4936
|
+
): T {
|
|
4937
|
+
const label = opts.label ?? "db";
|
|
4938
|
+
const logger = opts.logger ?? console;
|
|
4939
|
+
|
|
4940
|
+
const handle = (channel: "pool" | "client", err: unknown): void => {
|
|
4941
|
+
try {
|
|
4942
|
+
const description = describePoolError(err);
|
|
4943
|
+
const suffix = description.code ? \` [\${description.code}]\` : "";
|
|
4944
|
+
|
|
4945
|
+
if (description.expected) {
|
|
4946
|
+
logger.warn(
|
|
4947
|
+
\`[db:\${label}] \${channel}-level connection closed by the server\${suffix}: \` +
|
|
4948
|
+
\`\${description.message} — discarded; the next query opens a fresh connection\`,
|
|
4949
|
+
);
|
|
4950
|
+
return;
|
|
4951
|
+
}
|
|
4952
|
+
|
|
4953
|
+
logger.error(
|
|
4954
|
+
\`[db:\${label}] unexpected \${channel}-level pool error\${suffix}: \${description.message}\`,
|
|
4955
|
+
);
|
|
4956
|
+
try {
|
|
4957
|
+
opts.report?.(description, label);
|
|
4958
|
+
} catch {
|
|
4959
|
+
// A failing reporter must not become the crash this function prevents.
|
|
4960
|
+
// Swallowed silently BECAUSE the line above already ran: the error is on
|
|
4961
|
+
// stdout regardless of whether the tracker accepted it.
|
|
4962
|
+
}
|
|
4963
|
+
} catch {
|
|
4964
|
+
// Unreachable by construction — every step above is already guarded — and
|
|
4965
|
+
// present anyway, because "unreachable" is the assumption a listener like
|
|
4966
|
+
// this cannot afford to be wrong about.
|
|
4967
|
+
}
|
|
4968
|
+
};
|
|
4969
|
+
|
|
4970
|
+
// Channel 1 — the POOL. Covers a client the pool is holding IDLE.
|
|
4971
|
+
pool.on("error", (err: unknown) => handle("pool", err));
|
|
4972
|
+
|
|
4973
|
+
// Channel 2 — each CLIENT, and it is NOT redundant with channel 1. See the
|
|
4974
|
+
// header: \`pool.on('error')\` does not cover a CHECKED-OUT client, and in an
|
|
4975
|
+
// app that wraps queries in transactions, checked-out is the normal state.
|
|
4976
|
+
//
|
|
4977
|
+
// Wrapped: a driver that does not expose 'connect' must not break pool
|
|
4978
|
+
// construction, which would be a worse failure than the one being prevented.
|
|
4979
|
+
try {
|
|
4980
|
+
pool.on("connect", (client: PoolClientErrorSource) => {
|
|
4981
|
+
try {
|
|
4982
|
+
client.on("error", (err: unknown) => handle("client", err));
|
|
4983
|
+
} catch {
|
|
4984
|
+
// Same reasoning, one level down.
|
|
4985
|
+
}
|
|
4986
|
+
});
|
|
4987
|
+
} catch {
|
|
4988
|
+
// Driver does not support 'connect'. Channel 1 still protects the idle case.
|
|
4989
|
+
}
|
|
4990
|
+
|
|
4991
|
+
return pool;
|
|
4992
|
+
}
|
|
4993
|
+
`;
|
|
4994
|
+
const DB_CLIENT_TEMPLATE = `// [PLATFORM: Neon] The single Neon-specific touchpoint for the runtime app.
|
|
4995
|
+
// Every other module imports \`getDb()\` from here. To move off Neon (Supabase,
|
|
4996
|
+
// Railway, RDS, self-hosted Postgres): swap the two driver imports below to
|
|
4997
|
+
// \`pg\` / \`drizzle-orm/node-postgres\` and delete the WebSocket polyfill. Nothing
|
|
4998
|
+
// else in the app should need to change ([[portable-stack]]).
|
|
4999
|
+
//
|
|
5000
|
+
// IMPORT-SAFE: the pool is built lazily on FIRST USE, not at module load.
|
|
5001
|
+
// Importing this file — as \`next build\` does, or a route that never queries, or
|
|
5002
|
+
// a vitest test — must not require DATABASE_URL or open a socket. \`/api/health\`
|
|
5003
|
+
// stays DB-free per [[neon-postgres]], so routine uptime probes never wake the
|
|
5004
|
+
// compute and never burn the CU-hour quota.
|
|
5005
|
+
|
|
5006
|
+
import { neonConfig, Pool } from "@neondatabase/serverless";
|
|
5007
|
+
import { drizzle, type NeonDatabase } from "drizzle-orm/neon-serverless";
|
|
5008
|
+
import ws from "ws";
|
|
5009
|
+
|
|
5010
|
+
import * as schema from "./schema";
|
|
5011
|
+
import { guardPoolErrors } from "./pool-errors";
|
|
5012
|
+
|
|
5013
|
+
export { describePoolError, guardPoolErrors, redactConnectionStrings } from "./pool-errors";
|
|
5014
|
+
export type { PoolErrorDescription } from "./pool-errors";
|
|
5015
|
+
|
|
5016
|
+
// [PLATFORM: Neon] \`neon-serverless\` speaks WebSockets — native on Vercel's
|
|
5017
|
+
// serverless runtime but not on Node, so register a polyfill for \`next dev\`,
|
|
5018
|
+
// \`next build\`, and node-side scripts. No-op where WebSocket already exists.
|
|
5019
|
+
if (typeof WebSocket === "undefined") {
|
|
5020
|
+
neonConfig.webSocketConstructor = ws as unknown as typeof WebSocket;
|
|
5021
|
+
}
|
|
5022
|
+
|
|
5023
|
+
type Db = NeonDatabase<typeof schema>;
|
|
5024
|
+
|
|
5025
|
+
let _pool: Pool | undefined;
|
|
5026
|
+
let _db: Db | undefined;
|
|
5027
|
+
|
|
5028
|
+
function requireDatabaseUrl(): string {
|
|
5029
|
+
const url = process.env.DATABASE_URL;
|
|
5030
|
+
if (!url) {
|
|
5031
|
+
throw new Error(
|
|
5032
|
+
"DATABASE_URL is not set. Set it in .env.local (local) or the deployment's " +
|
|
5033
|
+
"environment. Per [[neon-postgres]], use the POOLED connection string.",
|
|
5034
|
+
);
|
|
5035
|
+
}
|
|
5036
|
+
return url;
|
|
5037
|
+
}
|
|
5038
|
+
|
|
5039
|
+
/**
|
|
5040
|
+
* Lazy singleton. The first call builds the pool + drizzle instance; later calls
|
|
5041
|
+
* reuse it. A getter (not a top-level \`export const db\`) is what keeps import
|
|
5042
|
+
* time free of side effects.
|
|
5043
|
+
*
|
|
5044
|
+
* 🔴 \`guardPoolErrors\` runs on the line after construction and BEFORE the
|
|
5045
|
+
* function returns — i.e. before any caller can \`await\` anything. That ordering
|
|
5046
|
+
* is the whole point: a pool that is live but unguarded, even briefly, is a pool
|
|
5047
|
+
* that can turn a dropped socket into an uncaughtException. Do not move it, and
|
|
5048
|
+
* do not make it conditional. See \`db/pool-errors.ts\` for the full mechanism.
|
|
5049
|
+
*/
|
|
5050
|
+
export function getDb(): Db {
|
|
5051
|
+
if (_db) return _db;
|
|
5052
|
+
|
|
5053
|
+
const pool = new Pool({
|
|
5054
|
+
connectionString: requireDatabaseUrl(),
|
|
5055
|
+
// Per [[neon-postgres]]: keep the pool small. Serverless fans out by
|
|
5056
|
+
// INSTANCE, so a large per-instance pool multiplies rather than shares.
|
|
5057
|
+
max: 3,
|
|
5058
|
+
});
|
|
5059
|
+
guardPoolErrors(pool, { label: "runtime" });
|
|
5060
|
+
|
|
5061
|
+
_pool = pool;
|
|
5062
|
+
_db = drizzle(pool, { schema });
|
|
5063
|
+
return _db;
|
|
5064
|
+
}
|
|
5065
|
+
|
|
5066
|
+
/**
|
|
5067
|
+
* Close the pool. For scripts and tests — a serverless request path should never
|
|
5068
|
+
* call this, because the pool is meant to outlive the request.
|
|
5069
|
+
*/
|
|
5070
|
+
export async function closeDb(): Promise<void> {
|
|
5071
|
+
const pool = _pool;
|
|
5072
|
+
_pool = undefined;
|
|
5073
|
+
_db = undefined;
|
|
5074
|
+
if (pool) await pool.end();
|
|
5075
|
+
}
|
|
5076
|
+
`;
|
|
5077
|
+
/**
|
|
5078
|
+
* Emitted alongside the module, not as an optional extra.
|
|
5079
|
+
*
|
|
5080
|
+
* Per this repo's own verification standard: what we emit here is code the
|
|
5081
|
+
* CONSUMER'S toolchain compiles and runs, and no assertion on a template STRING
|
|
5082
|
+
* is evidence that it parses. The emitted test is what makes the emitted module
|
|
5083
|
+
* checkable in the only place that can see it — a real `vitest` run inside a
|
|
5084
|
+
* real scaffold — and it carries the paired control that stops the whole file
|
|
5085
|
+
* from passing vacuously against a no-op guard.
|
|
5086
|
+
*/
|
|
5087
|
+
const DB_POOL_ERRORS_TEST_TEMPLATE = `import { describe, expect, it, vi } from "vitest";
|
|
5088
|
+
import { EventEmitter } from "node:events";
|
|
5089
|
+
|
|
5090
|
+
import {
|
|
5091
|
+
describePoolError,
|
|
5092
|
+
guardPoolErrors,
|
|
5093
|
+
isConnectionError,
|
|
5094
|
+
redactConnectionStrings,
|
|
5095
|
+
type PoolErrorSource,
|
|
5096
|
+
} from "./pool-errors";
|
|
5097
|
+
|
|
5098
|
+
function makeLogger() {
|
|
5099
|
+
return { warn: vi.fn(), error: vi.fn() };
|
|
5100
|
+
}
|
|
5101
|
+
|
|
5102
|
+
// ⚠️ ASSEMBLED FROM PARTS, NOT WRITTEN AS A LITERAL — deliberately. These tests
|
|
5103
|
+
// need a string shaped exactly like a real Neon connection URL, because that
|
|
5104
|
+
// shape is what \`redactConnectionStrings\` has to match. Written inline it looks
|
|
5105
|
+
// like a credential to any secret scanner reading the diff, and a scanner that
|
|
5106
|
+
// could tell "obviously fake" from real would be a scanner that could be talked
|
|
5107
|
+
// out of firing. Built at runtime instead: the test still exercises the real
|
|
5108
|
+
// pattern, and no credential-shaped literal exists in the source.
|
|
5109
|
+
const FAKE_PASSWORD = "not-a-real-password";
|
|
5110
|
+
const FAKE_DB_URL = ["postgresql://neondb_owner", "@ep-example.neon.tech/neondb"].join(
|
|
5111
|
+
\`:\${FAKE_PASSWORD}\`,
|
|
5112
|
+
);
|
|
5113
|
+
|
|
5114
|
+
describe("the crash this module prevents is real", () => {
|
|
5115
|
+
// 🔴 THE PAIRED CONTROL. Without it every test below could pass against a
|
|
5116
|
+
// \`guardPoolErrors\` that did nothing at all: "did not throw" is
|
|
5117
|
+
// indistinguishable from "was never going to throw" ([[zero-is-not-a-pass]]).
|
|
5118
|
+
// This pair is what makes the rest of the file non-vacuous, and it asserts
|
|
5119
|
+
// Node's listener-less-'error' semantics against the real EventEmitter the
|
|
5120
|
+
// driver's Pool extends, rather than trusting a write-up that reported it.
|
|
5121
|
+
it("an UNGUARDED emitter re-throws a listener-less 'error' (the uncaughtException)", () => {
|
|
5122
|
+
const pool = new EventEmitter();
|
|
5123
|
+
expect(() => pool.emit("error", new Error("Connection terminated unexpectedly"))).toThrow(
|
|
5124
|
+
/Connection terminated unexpectedly/,
|
|
5125
|
+
);
|
|
5126
|
+
});
|
|
5127
|
+
|
|
5128
|
+
it("the SAME emit does not throw once guarded", () => {
|
|
5129
|
+
const pool = guardPoolErrors(new EventEmitter(), { logger: makeLogger() });
|
|
5130
|
+
expect(() => pool.emit("error", new Error("Connection terminated unexpectedly"))).not.toThrow();
|
|
5131
|
+
});
|
|
5132
|
+
});
|
|
5133
|
+
|
|
5134
|
+
describe("channel 2 — a CHECKED-OUT client, which channel 1 does not cover", () => {
|
|
5135
|
+
// The half \`pool.on('error')\` alone leaves open. A Z2W project shipped the
|
|
5136
|
+
// pool-level listener by itself and watched its probe die with the identical
|
|
5137
|
+
// stack, so this is a regression test for a real production failure.
|
|
5138
|
+
it("an unguarded CLIENT re-throws even when the POOL is guarded", () => {
|
|
5139
|
+
const pool = new EventEmitter();
|
|
5140
|
+
// Only channel 1, simulating the incomplete fix.
|
|
5141
|
+
pool.on("error", () => {});
|
|
5142
|
+
const client = new EventEmitter();
|
|
5143
|
+
expect(() => client.emit("error", new Error("socket hang up"))).toThrow(/socket hang up/);
|
|
5144
|
+
});
|
|
5145
|
+
|
|
5146
|
+
it("guardPoolErrors attaches to clients emitted on 'connect'", () => {
|
|
5147
|
+
const logger = makeLogger();
|
|
5148
|
+
const pool = guardPoolErrors(new EventEmitter(), { logger });
|
|
5149
|
+
const client = new EventEmitter();
|
|
5150
|
+
pool.emit("connect", client);
|
|
5151
|
+
|
|
5152
|
+
expect(() => client.emit("error", new Error("socket hang up"))).not.toThrow();
|
|
5153
|
+
expect(logger.warn).toHaveBeenCalledTimes(1);
|
|
5154
|
+
expect(logger.warn.mock.calls[0][0]).toContain("client-level");
|
|
5155
|
+
});
|
|
5156
|
+
});
|
|
5157
|
+
|
|
5158
|
+
describe("describePoolError", () => {
|
|
5159
|
+
it("classifies a dead idle socket as EXPECTED", () => {
|
|
5160
|
+
expect(describePoolError(new Error("Connection terminated unexpectedly")).expected).toBe(true);
|
|
5161
|
+
});
|
|
5162
|
+
|
|
5163
|
+
it("classifies Neon suspending a compute (57P01) as EXPECTED", () => {
|
|
5164
|
+
const err = Object.assign(new Error("terminating connection due to administrator command"), {
|
|
5165
|
+
code: "57P01",
|
|
5166
|
+
});
|
|
5167
|
+
const described = describePoolError(err);
|
|
5168
|
+
expect(described.expected).toBe(true);
|
|
5169
|
+
expect(described.code).toBe("57P01");
|
|
5170
|
+
});
|
|
5171
|
+
|
|
5172
|
+
it("classifies a server-sent rejection as UNEXPECTED", () => {
|
|
5173
|
+
// A pool error that is NOT the socket dying has no story, so it must be
|
|
5174
|
+
// reported rather than logged away as routine.
|
|
5175
|
+
const err = Object.assign(new Error('permission denied for table "users"'), { code: "42501" });
|
|
5176
|
+
expect(describePoolError(err).expected).toBe(false);
|
|
5177
|
+
});
|
|
5178
|
+
|
|
5179
|
+
it("is TOTAL: null, undefined, a string, a number and an object all describe cleanly", () => {
|
|
5180
|
+
for (const input of [null, undefined, "boom", 42, {}]) {
|
|
5181
|
+
expect(() => describePoolError(input)).not.toThrow();
|
|
5182
|
+
}
|
|
5183
|
+
expect(describePoolError(null).message).toBe("(no message)");
|
|
5184
|
+
expect(describePoolError("boom").message).toBe("boom");
|
|
5185
|
+
});
|
|
5186
|
+
|
|
5187
|
+
it("survives an error object whose getters throw, and reports it as UNEXPECTED", () => {
|
|
5188
|
+
const hostile = {
|
|
5189
|
+
get message(): string {
|
|
5190
|
+
throw new Error("getter exploded");
|
|
5191
|
+
},
|
|
5192
|
+
};
|
|
5193
|
+
const described = describePoolError(hostile);
|
|
5194
|
+
expect(described.expected).toBe(false);
|
|
5195
|
+
expect(described.message).toBe("(no message)");
|
|
5196
|
+
});
|
|
5197
|
+
});
|
|
5198
|
+
|
|
5199
|
+
describe("redactConnectionStrings", () => {
|
|
5200
|
+
it("removes the credential from a connection URL", () => {
|
|
5201
|
+
const scrubbed = redactConnectionStrings(\`could not connect to \${FAKE_DB_URL}\`);
|
|
5202
|
+
expect(scrubbed).not.toContain(FAKE_PASSWORD);
|
|
5203
|
+
expect(scrubbed).toContain("[REDACTED]");
|
|
5204
|
+
});
|
|
5205
|
+
|
|
5206
|
+
it("is applied by describePoolError, so a leak cannot reach a log line", () => {
|
|
5207
|
+
const err = new Error(\`connection failed: \${FAKE_DB_URL}\`);
|
|
5208
|
+
expect(describePoolError(err).message).not.toContain(FAKE_PASSWORD);
|
|
5209
|
+
});
|
|
5210
|
+
|
|
5211
|
+
it("leaves ordinary text alone", () => {
|
|
5212
|
+
expect(redactConnectionStrings("socket hang up")).toBe("socket hang up");
|
|
5213
|
+
});
|
|
5214
|
+
});
|
|
5215
|
+
|
|
5216
|
+
describe("the listener can never become the crash it prevents", () => {
|
|
5217
|
+
it("a throwing REPORTER does not escape the listener", () => {
|
|
5218
|
+
const pool = guardPoolErrors(new EventEmitter(), {
|
|
5219
|
+
logger: makeLogger(),
|
|
5220
|
+
report: () => {
|
|
5221
|
+
throw new Error("tracker not initialised");
|
|
5222
|
+
},
|
|
5223
|
+
});
|
|
5224
|
+
const rejected = Object.assign(new Error("permission denied"), { code: "42501" });
|
|
5225
|
+
expect(() => pool.emit("error", rejected)).not.toThrow();
|
|
5226
|
+
});
|
|
5227
|
+
|
|
5228
|
+
it("a throwing LOGGER does not escape the listener", () => {
|
|
5229
|
+
const pool = guardPoolErrors(new EventEmitter(), {
|
|
5230
|
+
logger: {
|
|
5231
|
+
warn: () => {
|
|
5232
|
+
throw new Error("logger exploded");
|
|
5233
|
+
},
|
|
5234
|
+
error: () => {
|
|
5235
|
+
throw new Error("logger exploded");
|
|
5236
|
+
},
|
|
5237
|
+
},
|
|
5238
|
+
});
|
|
5239
|
+
expect(() => pool.emit("error", new Error("Connection terminated unexpectedly"))).not.toThrow();
|
|
5240
|
+
});
|
|
5241
|
+
|
|
5242
|
+
it("a driver with no 'connect' event does not break pool construction", () => {
|
|
5243
|
+
// Typed as PoolErrorSource explicitly. A bare object literal with a single
|
|
5244
|
+
// \`on(event: string, ...)\` signature does NOT satisfy the overloaded type,
|
|
5245
|
+
// and \`vitest\` would not tell you — esbuild strips types without checking
|
|
5246
|
+
// them, so this only surfaces under \`npm run typecheck\`.
|
|
5247
|
+
const poolWithoutConnect: PoolErrorSource = {
|
|
5248
|
+
on(event: "error" | "connect", listener: unknown): unknown {
|
|
5249
|
+
if (event === "connect") throw new Error("unsupported event");
|
|
5250
|
+
return listener;
|
|
5251
|
+
},
|
|
5252
|
+
} as PoolErrorSource;
|
|
5253
|
+
expect(() => guardPoolErrors(poolWithoutConnect, { logger: makeLogger() })).not.toThrow();
|
|
5254
|
+
});
|
|
5255
|
+
});
|
|
5256
|
+
|
|
5257
|
+
describe("expected vs unexpected routing", () => {
|
|
5258
|
+
it("an EXPECTED error warns and is not reported", () => {
|
|
5259
|
+
const logger = makeLogger();
|
|
5260
|
+
const report = vi.fn();
|
|
5261
|
+
const pool = guardPoolErrors(new EventEmitter(), { logger, report });
|
|
5262
|
+
pool.emit("error", new Error("Connection terminated unexpectedly"));
|
|
5263
|
+
expect(logger.warn).toHaveBeenCalledTimes(1);
|
|
5264
|
+
expect(logger.error).not.toHaveBeenCalled();
|
|
5265
|
+
expect(report).not.toHaveBeenCalled();
|
|
5266
|
+
});
|
|
5267
|
+
|
|
5268
|
+
it("an UNEXPECTED error is logged at error level AND reported", () => {
|
|
5269
|
+
const logger = makeLogger();
|
|
5270
|
+
const report = vi.fn();
|
|
5271
|
+
const pool = guardPoolErrors(new EventEmitter(), { logger, report });
|
|
5272
|
+
pool.emit("error", Object.assign(new Error("permission denied"), { code: "42501" }));
|
|
5273
|
+
expect(logger.error).toHaveBeenCalledTimes(1);
|
|
5274
|
+
expect(report).toHaveBeenCalledTimes(1);
|
|
5275
|
+
});
|
|
5276
|
+
});
|
|
5277
|
+
|
|
5278
|
+
describe("isConnectionError", () => {
|
|
5279
|
+
it("recognises the Neon and socket forms", () => {
|
|
5280
|
+
expect(isConnectionError(new Error("Connection terminated unexpectedly"))).toBe(true);
|
|
5281
|
+
expect(isConnectionError(Object.assign(new Error("x"), { code: "ECONNRESET" }))).toBe(true);
|
|
5282
|
+
expect(isConnectionError(new Error("socket hang up"))).toBe(true);
|
|
5283
|
+
});
|
|
5284
|
+
|
|
5285
|
+
it("does not claim a server-sent rejection", () => {
|
|
5286
|
+
expect(isConnectionError(Object.assign(new Error("permission denied"), { code: "42501" }))).toBe(
|
|
5287
|
+
false,
|
|
5288
|
+
);
|
|
5289
|
+
});
|
|
5290
|
+
});
|
|
5291
|
+
`;
|
|
5292
|
+
const DB_CLIENT_TEST_TEMPLATE = `import { describe, expect, it } from "vitest";
|
|
5293
|
+
|
|
5294
|
+
// [[portable-stack]] §15 — IMPORT-SAFETY, asserted by EXECUTING the module
|
|
5295
|
+
// rather than by reading it.
|
|
5296
|
+
//
|
|
5297
|
+
// The claim in \`db/client.ts\`'s header is that importing it neither reads
|
|
5298
|
+
// DATABASE_URL nor opens a socket, so \`next build\`, a route that never queries,
|
|
5299
|
+
// and this very test file can all import it with no secret present. That claim
|
|
5300
|
+
// is one \`const db = drizzle(...)\` at module scope away from being false, and
|
|
5301
|
+
// the failure is invisible locally (where .env.local is always populated) —
|
|
5302
|
+
// it shows up as a BUILD failure in CI, or a dead \`/api/health\`.
|
|
5303
|
+
//
|
|
5304
|
+
// ⚠️ \`next build\` PASSING IS NOT EVIDENCE OF THIS. Nothing in a fresh scaffold
|
|
5305
|
+
// imports \`db/client.ts\` yet, so the build never loads the module at all
|
|
5306
|
+
// ([[zero-is-not-a-pass]] — "I examined nothing" is not "I found nothing wrong").
|
|
5307
|
+
// Only an explicit import can see it, which is what this file is.
|
|
5308
|
+
describe("db/client.ts is IMPORT-SAFE", () => {
|
|
5309
|
+
it("imports with no DATABASE_URL set, opening no socket and throwing nothing", async () => {
|
|
5310
|
+
delete process.env.DATABASE_URL;
|
|
5311
|
+
const mod = await import("./client");
|
|
5312
|
+
expect(typeof mod.getDb).toBe("function");
|
|
5313
|
+
});
|
|
5314
|
+
|
|
5315
|
+
it("throws a NAMED, actionable error only when getDb() is actually called", async () => {
|
|
5316
|
+
delete process.env.DATABASE_URL;
|
|
5317
|
+
const mod = await import("./client");
|
|
5318
|
+
expect(() => mod.getDb()).toThrow(/DATABASE_URL is not set/);
|
|
5319
|
+
});
|
|
5320
|
+
});
|
|
5321
|
+
`;
|
|
5322
|
+
const DB_SCHEMA_TEMPLATE = `// Drizzle schema for {{slug}}.
|
|
5323
|
+
//
|
|
5324
|
+
// Replace this placeholder table with the real schema as the app takes shape.
|
|
5325
|
+
// Per [[portable-stack]], keep to standard Postgres types so the schema ports to
|
|
5326
|
+
// any Postgres host — no Neon-specific column types.
|
|
5327
|
+
|
|
5328
|
+
import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";
|
|
5329
|
+
|
|
5330
|
+
export const example = pgTable("example", {
|
|
5331
|
+
id: serial("id").primaryKey(),
|
|
5332
|
+
name: text("name").notNull(),
|
|
5333
|
+
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
|
5334
|
+
});
|
|
5335
|
+
`;
|
|
5336
|
+
/**
|
|
5337
|
+
* Driver + ORM for the emitted `db/` layer. `ws` is the WebSocket polyfill that
|
|
5338
|
+
* `neon-serverless` needs off-Vercel (`next dev`, `next build`, node scripts).
|
|
5339
|
+
*/
|
|
5340
|
+
const NEON_DB_LAYER_DEPS = {
|
|
5341
|
+
"@neondatabase/serverless": "^1.0.2",
|
|
5342
|
+
"drizzle-orm": "^0.45.2",
|
|
5343
|
+
ws: "^8.18.0",
|
|
5344
|
+
};
|
|
5345
|
+
const NEON_DB_LAYER_DEV_DEPS = {
|
|
5346
|
+
"@types/ws": "^8.5.12",
|
|
5347
|
+
"drizzle-kit": "^0.31.0",
|
|
5348
|
+
};
|
|
4679
5349
|
function withExtraDeps(pkgJson, extra) {
|
|
4680
5350
|
const obj = JSON.parse(pkgJson);
|
|
4681
5351
|
obj.dependencies = { ...obj.dependencies, ...extra };
|
|
4682
5352
|
return JSON.stringify(obj, null, 2) + "\n";
|
|
4683
5353
|
}
|
|
5354
|
+
function withExtraDevDeps(pkgJson, extra) {
|
|
5355
|
+
const obj = JSON.parse(pkgJson);
|
|
5356
|
+
obj.devDependencies = { ...obj.devDependencies, ...extra };
|
|
5357
|
+
return JSON.stringify(obj, null, 2) + "\n";
|
|
5358
|
+
}
|
|
4684
5359
|
export function scaffoldNextjs(inputs, opts) {
|
|
4685
5360
|
const spec = resolveBrandSpec(inputs);
|
|
4686
5361
|
const base = commonBaseFiles(inputs, opts, NARRATIVE);
|
|
@@ -4698,6 +5373,10 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
4698
5373
|
// the emitted comments say so plainly rather than implying a guarantee that
|
|
4699
5374
|
// isn't there — an in-memory limiter's real ceiling is `limit × instances`.
|
|
4700
5375
|
const durableLimit = acceptsCards && inputs.dbStrategy === "neon-postgres";
|
|
5376
|
+
// The Neon data layer ships for every neon-postgres project, cards or not.
|
|
5377
|
+
// See DB_POOL_ERRORS_TEMPLATE for the measurement that made this the
|
|
5378
|
+
// scaffolder's job rather than each app's.
|
|
5379
|
+
const usesNeonDb = inputs.dbStrategy === "neon-postgres";
|
|
4701
5380
|
// The PWA baseline. Gated on `hasWebUi` — the existing input that already
|
|
4702
5381
|
// records "this project has pages a person looks at" — and NOT on a new
|
|
4703
5382
|
// ScaffoldInputs field, following the v0.9.0 FormBits precedent. A new
|
|
@@ -4714,8 +5393,17 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
4714
5393
|
packageJson = withEmailDeps(packageJson);
|
|
4715
5394
|
if (hasObservability)
|
|
4716
5395
|
packageJson = withExtraDeps(packageJson, SENTRY_DEPS);
|
|
4717
|
-
|
|
5396
|
+
// Gated on the DB STRATEGY, for the same reason the env block below is: the
|
|
5397
|
+
// driver belongs to the project's database, not to whichever emitted module
|
|
5398
|
+
// happens to read it today. `durableLimit` already implies neon-postgres, so
|
|
5399
|
+
// this supersedes the narrower gate rather than sitting beside it.
|
|
5400
|
+
if (usesNeonDb) {
|
|
5401
|
+
packageJson = withExtraDeps(packageJson, NEON_DB_LAYER_DEPS);
|
|
5402
|
+
packageJson = withExtraDevDeps(packageJson, NEON_DB_LAYER_DEV_DEPS);
|
|
5403
|
+
}
|
|
5404
|
+
else if (durableLimit) {
|
|
4718
5405
|
packageJson = withExtraDeps(packageJson, NEON_DRIVER_DEP);
|
|
5406
|
+
}
|
|
4719
5407
|
let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
|
|
4720
5408
|
// Gated on the DB STRATEGY, not on `durableLimit` — the variable belongs to
|
|
4721
5409
|
// the project's database, not to the one emitted module that happens to read
|
|
@@ -4870,6 +5558,12 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
4870
5558
|
}, { path: "db/migrations/0001_rate_limits.sql", content: RATE_LIMITS_DDL_TEMPLATE });
|
|
4871
5559
|
}
|
|
4872
5560
|
}
|
|
5561
|
+
if (usesNeonDb) {
|
|
5562
|
+
typeSpecific.push({ path: "db/client.ts", content: sub(DB_CLIENT_TEMPLATE, inputs, opts, spec) }, { path: "db/pool-errors.ts", content: sub(DB_POOL_ERRORS_TEMPLATE, inputs, opts, spec) }, {
|
|
5563
|
+
path: "db/pool-errors.test.ts",
|
|
5564
|
+
content: sub(DB_POOL_ERRORS_TEST_TEMPLATE, inputs, opts, spec),
|
|
5565
|
+
}, { path: "db/schema.ts", content: sub(DB_SCHEMA_TEMPLATE, inputs, opts, spec) }, { path: "db/client.test.ts", content: sub(DB_CLIENT_TEST_TEMPLATE, inputs, opts, spec) });
|
|
5566
|
+
}
|
|
4873
5567
|
return [...base, ...typeSpecific];
|
|
4874
5568
|
}
|
|
4875
5569
|
/**
|
package/dist/standards.d.ts
CHANGED
|
@@ -78,7 +78,7 @@ export interface StandardsResolution {
|
|
|
78
78
|
* family — the safe default for anything else with `has_web_ui=true`.
|
|
79
79
|
*/
|
|
80
80
|
export declare function fathomEnvVarFor(projectType: ProjectType): string;
|
|
81
|
-
export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.
|
|
81
|
+
export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.33";
|
|
82
82
|
/**
|
|
83
83
|
* The canonical **Capture Learnings** block, emitted VERBATIM into every
|
|
84
84
|
* scaffolded `CLAUDE.md`.
|
package/dist/standards.js
CHANGED
|
@@ -475,7 +475,7 @@ const NEON_CAREFUL_BODY = `### Neon-careful (Neon Postgres)
|
|
|
475
475
|
// Two consecutive handoffs compared this constant against the DOCUMENT version
|
|
476
476
|
// and reported a "15-version gap" that did not exist — the real gap was 4. Read
|
|
477
477
|
// the `<!-- ... canonical-block vX.Y.Z -->` comment, never the `**Version:**` line.
|
|
478
|
-
export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.
|
|
478
|
+
export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.33";
|
|
479
479
|
/**
|
|
480
480
|
* The canonical **Capture Learnings** block, emitted VERBATIM into every
|
|
481
481
|
* scaffolded `CLAUDE.md`.
|
|
@@ -583,15 +583,21 @@ This project participates in the Z2W cross-project coordination bulletin.
|
|
|
583
583
|
|
|
584
584
|
**At session start:**
|
|
585
585
|
|
|
586
|
-
1. **Get a PRIVATE workspace — never do session work in the shared clone.** If a clone exists at \`~/.cache/z2w-coordination\` OR at \`~/Desktop/Zero2Webmaster/AI/Cursor Projects/z2w-agent-coordination/\`, \`cd\` there — **since 2026-08-29 those are ONE clone: the Desktop path is a symlink to \`~/.cache/z2w-coordination\`, so \`pwd -P\` from either resolves to the same \`.git
|
|
586
|
+
1. **Get a PRIVATE workspace — never do session work in the shared clone (v0.1.17).** If a clone exists at \`~/.cache/z2w-coordination\` OR at \`~/Desktop/Zero2Webmaster/AI/Cursor Projects/z2w-agent-coordination/\`, \`cd\` there — **since 2026-08-29 those are ONE clone: the Desktop path is a symlink to \`~/.cache/z2w-coordination\`, so \`pwd -P\` from either resolves to the same \`.git\`** (Kerry could not open his own protocol repo, because Finder hides dotfolders). Otherwise \`git clone git@github.com:zero2webmaster/z2w-agent-coordination.git ~/.cache/z2w-coordination\` (see §8.3). 🔴 **NO \`--depth 1\` — that flag was in this step until 2026-08-29 and it made git LIE about what is published (v0.1.31).** A shallow clone keeps no history, so git cannot compute that its commits are contained in \`origin/main\` and **reports already-pushed commits as unpushed**. The shared clone read as *"22 commits ahead of origin"* — understood as ~12 projects' bulletin updates one bad \`git add -A\` from being lost — and **all 22 were already on origin.** It costs ~2 s to clone this repo's ~5,000 commits in full; the depth saved nothing worth that. **If you are in a clone that is already shallow, \`git fetch --unshallow origin\` fixes it — objects only, no working file, branch or commit is touched** (\`agent-workspace.sh\` now does this for you, see below). Then, from that clone, take a workspace of your own — \`WS="$(bash scripts/agent-workspace.sh {{slug}})"\` and \`cd "$WS"\`. **Do every read and write of this session inside \`$WS\`**, and publish at session end with \`bash scripts/publish-from-workspace.sh "{{slug}}: session {id} — {one-line summary}"\` (it commits, prints \`git show --numstat HEAD\` before publishing, then pushes \`HEAD:main\`, rebasing and retrying if another agent pushed first). **Why:** two shared working trees were serving ~40 agents, and one shared git index produced **seven concurrent-write sweeps in six weeks** — an agent's work published inside another project's commit, or silently reverted, with the victim's commit sometimes gone entirely. Staging narrowly does not prevent it and neither does intending to exclude a file (occurrence #7 said so in its own commit message and swept the file anyway); a worktree has its own index, so the failure class is gone rather than mitigated. Costs ~0.1 s and ~8 MB, shares the object store, no re-download. \`agent-workspace.sh\` also runs \`set-bulletin-commit-identity.sh\` for you (bot identity, set locally per clone, so bulletin commits don't skew Kerry's personal GitHub contribution graph) and arms a \`pre-commit\` guard that makes the shared tree **refuse** commits — if you see that refusal, follow the three commands it prints. **Inside \`$WS\`, \`git add -A\` is safe** (your index contains nothing but your own edits), which is what \`publish-from-workspace.sh\` uses.
|
|
587
587
|
|
|
588
|
-
1b.
|
|
588
|
+
1b. **🔴 READ THE LIVE BLOCK, AND PREFER IT OVER THE COPY YOU ARE READING NOW (v0.1.23).** Step 1 already put you in the bulletin clone, so this costs one command and no network call:
|
|
589
|
+
\`\`\`
|
|
590
|
+
python3 scripts/bulletin_sections.py locate AGENT_PROTOCOL.md 'Agent Coordination'
|
|
591
|
+
\`\`\`
|
|
592
|
+
then read exactly those lines (\`sed -n '{start},{end}p' AGENT_PROTOCOL.md\`). **Where the live block and the copy in your \`CLAUDE.md\` disagree, the live block wins — without exception.** Your embedded copy is a cache, and this is the only step that invalidates it.
|
|
589
593
|
|
|
590
|
-
|
|
591
|
-
python3 scripts/bulletin_sections.py locate AGENT_PROTOCOL.md 'Agent Coordination'
|
|
592
|
-
\`\`\`
|
|
594
|
+
**Why this step exists, measured rather than argued (2026-08-07).** Until now \`AGENT_PROTOCOL.md\` appeared **nowhere** in this session-start read list — the list went workspace → your project file → \`global.md\`. So an agent carrying an old block had **no instructed path by which it could ever learn that a newer one existed**, and the only channel that tried to tell it (a \`global.md\` heads-up) is a broadcast whose own numbers say it does not work: \`audit-engine\` measured 20 files at v0.1.8 on 2026-07-28, and the sweep found **15 on 2026-08-05** — five files in eight days, against a canonical that moved four versions in the same period. On **2026-08-07 currency was 0 of 37 files at canonical**: 34 STALE (15 of them at v0.1.8, *eleven* versions back), 3 carrying no fingerprint at all. Not one file in the ecosystem was current. **A cache with no invalidation step is not a cache, it is a fork** — and fourteen versions of mechanics had forked silently.
|
|
593
595
|
|
|
594
|
-
|
|
596
|
+
**The cost side is why re-syncing kept losing.** The block was **4,274 B at v0.1.8** and is **34,515 B at v0.1.22** — 8.1× in ten weeks. The fifteen projects sitting at v0.1.8 accepted a 4 KB paste; asking them to re-paste 34 KB is a different request wearing the same word, and ~73% of those bytes are genuine instruction, so it cannot be trimmed back to the old size. This step replaces an **8× and rising per-bump cost, paid by 21 projects forever** with **one command per session**, and it is what makes every future fingerprint bump self-delivering.
|
|
597
|
+
|
|
598
|
+
**So the embedded copy is now optional, and deleting it is the preferred end state.** Once your project performs this step you may replace your whole \`## Agent Coordination\` block with a short pointer that says you participate, names your slug, and carries steps 1 + 1b verbatim — nothing else. That is **strictly less context per session**, not more: you drop ~34 KB of auto-loaded \`CLAUDE.md\` and read the same ~34 KB live only when a session actually coordinates. **If you keep the embedded copy, keep the fingerprint comment with it** — see the warning below.
|
|
599
|
+
|
|
600
|
+
> ⚠️ **A pointer that PARAPHRASES is the worst of the three options, and this is not hypothetical.** The \`➖ version-unknown\` row in the drift sweep was documented as *"participation is real, currency is unmeasurable"* — a reading that treats the state as benign. It is not: all three such files were checked on 2026-08-07 and each turned out to be a **frozen paraphrase** of the mechanics, not a pointer to them, and therefore stale in ways nothing could measure because they carry no version to compare. \`z2w-board-suite\` still routes replies to *"the asker's project file"* — the exact wording v0.1.11 corrected as contradicting the rule directly above it. \`z2w-seller-suite\` (both files) still instructs \`cd\` + \`git pull --ff-only\` **on the shared clone**, i.e. precisely the behaviour that produced seven concurrent-write sweeps in six weeks and that step 1 exists to end. **Paraphrase and you inherit the drift without the ability to detect it.** Copy the block verbatim with its fingerprint, or point at it and paraphrase nothing.
|
|
595
601
|
|
|
596
602
|
**The rules below are deliberately NOT delegated to step 1b.** They are the ones whose violation is irreversible — a leaked secret, a public bulletin, an overwritten neighbour — so they must hold even if the clone is unreachable, step 1b is skipped, or the agent never coordinates at all.
|
|
597
603
|
|
|
@@ -610,7 +616,7 @@ Reference the protocol's conventions by NAME, never by §-number — the numberi
|
|
|
610
616
|
- **Inter-agent courier header:** every message Kerry relays chat-to-chat starts with a \`To:\` / \`From:\` / \`Re:\` block (§8.4). Bulletin-posted replies use the inline \`↳ (..., {{slug}}):\` marker without the header.`;
|
|
611
617
|
const SEO_BASELINE_BODY = `### SEO baseline (non-WP web UI)
|
|
612
618
|
|
|
613
|
-
> **SEO is non-negotiable from v1
|
|
619
|
+
> **SEO is non-negotiable from v1 — a standing organization requirement.** WordPress sites get SEO from RankMath; non-WP web apps have no equivalent — every element must be built in deliberately at instantiation. SEO is NOT a later task.
|
|
614
620
|
>
|
|
615
621
|
> **The 7 requirements (every indexable page must satisfy all of them):**
|
|
616
622
|
>
|