[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECJRN94TRRQKA1WGA9C8Y6":3,"skill-same:01M7ECJRN94TRRQKA1WGA9C8Y6":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECJRN94TRRQKA1WGA9C8Y6","node-api-gateway",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fnode-api-gateway\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# node-api-gateway\n\n# Node API Gateway (TS \u002F Fastify \u002F Prisma)\n\nClass-level skill for building a production-grade, deployable API gateway as a\n**modular monolith** — no microservices, no premature abstraction. The hard\npart is not the business logic; it's the six boot-blocking scaffolding traps\nbelow. Hit them once, internalize, never debug them again.\n\n## When to use\n- User asks for an API server in TypeScript\u002FNode (Fastify, Express, Nest all\n  qualify, but this skill's pitfall set is Fastify-tuned).\n- OpenAI-compatible `\u002Fv1\u002Fchat\u002Fcompletions`, provider abstraction + smart\n  routing, API-key auth, rate limiting, usage metering, x402 payments.\n- \"Build the foundation \u002F MVP of our platform\" style specs.\n\n## Stack defaults (proven bootable)\n- Fastify 4 (`^4.29`) + `@fastify\u002Fhelmet@^11`, `@fastify\u002Fcors@^9`,\n  `@fastify\u002Frate-limit@^9`. **Do NOT pull helmet v12 \u002F ratelimit v10 \u002F swagger\n  v9 — those require Fastify 5 and throw `FST_ERR_PLUGIN_VERSION_MISMATCH`.**\n- Prisma 5 + Postgres, Zod for validation, Pino for JSON logging.\n- Run with `tsx` in dev (`tsx watch src\u002Fapp.ts`), `tsc` for build.\n\n## Scaffold checklist\n1. `package.json` with pinned Fastify-4-compatible `@fastify\u002F*` majors (above).\n2. `tsconfig.json`: `module: NodeNext`, `moduleResolution: NodeNext`,\n   `esModuleInterop: true`, `allowSyntheticDefaultImports: true`, `strict: true`.\n3. `src\u002Fenv.ts` — Zod-validate all env at boot (fail fast).\n4. `src\u002Fdb.ts` — `export const prisma = new PrismaClient()` (lazy singleton;\n   health endpoint must NOT require DB so the server boots without one).\n5. Plugins as small files: logging, errors, auth, ratelimit, x402.\n6. Routes: `chat`, `health`. App entry wires `buildApp()`.\n\n## THE SIX PITFALLS (all hit in one session, all avoidable)\n\n### P1 — write_file lint reports phantom TS errors. IGNORE THEM.\nThe `write_file` lint harness runs `tsc` **without your tsconfig** (no\nesModuleInterop, wrong `module`), so it flags `import pino from \"pino\"` as\n`TS1259`, `import.meta`\u002Ftop-level-await as errors, etc. These are FALSE under\nyour real config. **Authority = `npx tsc -p tsconfig.json --noEmit`.** If that\nexits 0, the code is fine. Never chase the harness's phantom errors.\n\n### P2 — NodeNext import rules.\n- Relative imports MUST include the `.js` extension: `import { x } from \"..\u002Fdb.js\"`\n  (not `..\u002Fdb`). Missing it → `TS2307 Cannot find module`.\n- CJS default exports (pino, pino-http, ioredis) under NodeNext need\n  `esModuleInterop`+`allowSyntheticDefaultImports` (set in tsconfig). If a lib's\n  types still resolve to a namespace (e.g. `pino-http` default import fails the\n  `app.register` overload), cast at the call site: `app.register(pinoHttp as any, opts)`.\n\n### P3 — DO NOT use pino-http. Use a plain pino hook.\n`app.addHook(\"onRequest\", pinoHttp)` → `TypeError: res.on is not a function`.\nBut the \"correct\" `app.register(pinoHttp, opts)` ALSO fails under `tsx`:\npino-http's default import resolves to the *module namespace*, so registering\nit as a Fastify plugin hangs with `Plugin did not start in time: 'pinoLogger'`\n(AVV_ERR_PLUGIN_EXEC_TIMEOUT). The reliable fix is to skip pino-http entirely\nand log via a plain hook with `pino` directly — ~12 lines, one fewer dep:\n```ts\nexport async function registerLogger(app: FastifyInstance) {\n  app.addHook(\"onRequest\", (req, _r, d) => { (req as any).id = crypto.randomUUID(); (req as any).t0 = Date.now(); d(); });\n  app.addHook(\"onResponse\", (req, rep, d) => {\n    log.info({ rid: (req as any).id, method: req.method, url: req.url, status: rep.statusCode, ms: Date.now() - (req as any).t0 });\n    d();\n  });\n}\n```\n`genReqId` must import crypto (`import * as crypto from \"node:crypto\"`),\nelse `crypto.randomUUID` is undefined. Call `await registerLogger(app)` in buildApp.\n\n### P4 — Fastify plugin version pinning.\n`@fastify\u002Fhelmet@12`, `@fastify\u002Frate-limit@10`, `@fastify\u002Fswagger@9` require\nFastify 5. On Fastify 4 pin `@fastify\u002Fhelmet@^11`, `@fastify\u002Frate-limit@^9`.\nMismatch throws at boot. Pick Fastify 4 OR 5 deliberately; align all `@fastify\u002F*`.\n\n### P5 — Prisma relation back-fields are mandatory.\nIf model `User` has `apiKeys ApiKey[]`, model `ApiKey` MUST declare the\nopposite relation (`user User @relation(...)`) or Prisma validation fails\n(`P1012 ... missing an opposite relation field`). Remove the forward field or\nadd the back-relation. `prisma generate` will not run until fixed.\n\n### P6 — tsx does NOT auto-load `.env`.\n`npx tsx src\u002Fapp.ts` starts with empty env → Zod throws \"Required\" for\n`DATABASE_URL`\u002F`OPENROUTER_API_KEY`. Fix: `npx tsx --env-file=.env src\u002Fapp.ts`,\nor `import \"dotenv\u002Fconfig\"`. `prisma generate` needs `DATABASE_URL` in the real\nenv too (`export DATABASE_URL=...` before the command, inline prefix is flaky).\n**Gotcha:** writing `.env` via a shell `cat > .env \u003C\u003C'EOF'` heredoc inside a\ncommand that also uses `&` backgrounding gets rejected (exit -1) and the file is\nNEVER written — then `--env-file=.env` says \"node: .env: not found\". Create\n`.env` with the `write_file` tool, never a heredoc in a backgrounded command.\n\n### P7 — DB-down must fail CLOSED (401), never 500.\nAuth resolves the key via `prisma.apiKey.findUnique` in a `preHandler`. If\nPostgres is down, that throws and escapes as **500 on every protected route**\n(including the bad-body 422 test). Wrap the resolve in try\u002Fcatch → return null\n→ 401. This also makes `\u002Fhealth\u002Fready` degradation graceful. Same pattern for\nany preHandler that touches the DB.\n\n### P8 — ioredis down = unhandled error spam.\n`new Redis(url, { lazyConnect: true })` still emits unhandled `ECONNREFUSED`\nevents when Redis is absent, spamming logs (non-fatal; rate-limit just\ndegrades). Silence: `redis.on(\"error\", () => {})`.\n\n## Verification (headless, no DB)\nBoot the server, then:\n```\ncurl -s localhost:8000\u002Fhealth            # 200 {status:ok}\ncurl -s -o \u002Fdev\u002Fnull -w '%{http_code}' localhost:8000\u002Fhealth\u002Fready   # 503 (DB\u002Fredis down — expected)\ncurl -s -o \u002Fdev\u002Fnull -w '%{http_code}' -X POST localhost:8000\u002Fv1\u002Fchat\u002Fcompletions -H content-type:application\u002Fjson -d '{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}'   # 401 (no key)\ncurl -s -o \u002Fdev\u002Fnull -w '%{http_code}' -X POST ... -H 'x-api-key: cc_dummy' -d '{\"model\":\"\",\"messages\":[]}'   # 422 (bad body)\n```\nIf \u002Fhealth returns 500, the crypto import (P3) is the cause.\n**Verification nuance:** with DB down, the bad-body test (`-H 'x-api-key: cc_dummy'`\n+ `{\"model\":\"\",\"messages\":[]}`) returns **401**, NOT 422 — auth runs before body\nparse and DB-down auth fails closed (P7). The 422 path is only observable with\nPostgres up and a valid key. So the headless (no-DB) smoke asserts: \u002Fhealth 200,\n\u002Fhealth\u002Fready 503, any chat without key 401, any chat with key 401 (DB down).\n422\u002F402\u002Fhappy-path need `docker compose up -d db redis` + a real provider key.\n\n## Agent discoverability (the \"First Mission\" surface)\nThe gateway's real product is being *found by agents*. Beyond the API, expose a\nself-describing discovery surface so an agent needs zero human explanation:\n- `GET \u002Fv1\u002Fmodels` — OpenAI-style model list (`{object:\"list\",data:[{id,context_window,...}]}`).\n- `GET \u002Fcapabilities` — booleans: chat, streaming, x402, modelRouting, openaiCompatible, auth scheme, `spec` URL.\n- `GET \u002Fpricing` — `per_1k_tokens: {model:{input,output}}` in USD.\n- `GET \u002Fversion` — name, version, OpenAPI pointer.\n- `GET \u002Fstatus` — operational status.\n- `GET \u002F.well-known\u002Fai-plugin.json` — agent manifest: `auth`, `api.openapi` URL, `description_for_model`.\n- `GET \u002Fopenapi.yaml` — served as `application\u002Fyaml` (bump to `openapi: 3.1.0`).\n- `GET \u002F` — minimal HTML index linking the above + meta `well-known` link.\nAll discovery routes are PUBLIC: exempt them from auth + rate-limit preHandlers\n(match prefix list: `\u002Fhealth`, `\u002Fv1\u002Fmodels`, `\u002Fcapabilities`, `\u002Fpricing`,\n`\u002Fversion`, `\u002Fstatus`, `\u002F.well-known`, `\u002F`, `\u002Fopenapi.yaml`). Keep the model\u002Fpricing\ncatalog as a static curated list (`ponytail:` upgrade to cached live provider fetch\nonly when dynamic availability matters). This surface is the 80% of the\ndiscoverability mission; SDKs\u002FSEO\u002FMCP docs are the 20% that follow once it's live.\n\n## Build rules (from the user's spec, enforced)\n- No placeholder code, no TODOs, no fake implementations, no unrequested\n  abstractions (interface-with-one-impl, factory-for-one-product).\n- Mark deliberate simplifications with a `ponytail:` comment naming the ceiling\n  and upgrade path (e.g. `# ponytail: streamed-token metering deferred; record\n  prompt tokens only until a usage endpoint lands`).\n- Auth: store only `sha256(rawKey)`; show raw key once at creation.\n- x402: emit `402` + payment payload, `POST \u002Fv1\u002Fsettle` with `{txHash,payer}`,\n  pluggable `verifyPayment`. On-chain settlement may live in another service —\n  keep `verifyPayment` swappable.\n\nSee `references\u002Ffastify-ts-pitfalls.md` for exact error transcripts → fix.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002F.archive\u002Fnode-api-gateway","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill node-api-gateway",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill node-api-gateway",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill node-api-gateway","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fnode-api-gateway\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",592,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002F.archive\u002Fnode-api-gateway\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]