[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6P3HG936A2ZYB3KPJQKEWND":3,"skill-same:01M6P3HG936A2ZYB3KPJQKEWND":76},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":27,"publishedAt":48,"linkOnly":49,"markdownContent":50,"markdownBody":51,"frontMatter":52,"refName":39,"commitSha":57,"skillDirectory":58,"forksCount":13,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":61,"install":62,"resources":75},"01M6P3HG936A2ZYB3KPJQKEWND","frontend-data-contracts",null,"A portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app.","duc-duy-1612\u002FOnline-Delivery-Systems-Web","duc-duy-1612","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F192231384?v=4","01M6NSDKQQDKVTHZ8DZMZ1VYY6","01M6NSDKW8DDVTQHBT1HBDDJPT",0,"MIT","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Ffrontend-data-contracts\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"contracts","data contracts","frontend data contracts","frontend data","frontend","data","Type Safety","Safety","react native","discipline","community","main","wed","network","app","critical","native","architecture","at","react","2026-11-10 10:12:30",false,"---\nname: frontend-data-contracts\ndescription: \"A portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app.\"\nrisk: critical\nsource: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-data-contracts\nsource_repo: stareezy-1\u002Ffrontend-architecture-skill\nsource_type: community\ndate_added: 2026-07-01\nlicense: MIT\nlicense_source: https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE\n---\n\n# Frontend Data Contracts (typed network boundary)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app. Establishes one typed API client as the single fetch boundary, a parse-don't-validate rule that turns wire JSON into trusted domain types before it enters the app, a single...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes a **discipline at the network edge** — one client, one envelope, one error\n> type, validated types — not a state library or a styling system. It pairs with the\n> **frontend-architecture** skill (the client lives in `shared\u002Fapi-client\u002F`) and is the foundation\n> the **frontend-optimistic-mutations** skill builds on.\n\nThe goal: the moment data crosses from the network into the app, it stops being `any`-shaped wire\nJSON and becomes a **trusted, typed domain value** — or it becomes a **single, typed error**.\nThere is exactly one place this transformation happens, and nothing untyped escapes it.\n\n---\n\n## 0. The five core ideas\n\n1. **One client is the only fetch boundary.** A single typed `apiClient` wraps `fetch`. Components and hooks never call `fetch`\u002F`axios` directly — the boundary is enforceable in review and lint.\n2. **Parse, don't validate.** Wire JSON is parsed into domain types at the boundary. After the client returns, the value is trusted everywhere downstream — no defensive `?.` chains, no re-checking shapes in components.\n3. **One envelope.** Every response is `{ data }` on success or `{ error }` on failure. The client unwraps `data` and throws on `error`, so callers receive the payload directly or a typed throw.\n4. **One normalized error type.** Server error envelope, non-2xx status, malformed body, network failure, and abort all become a single `ApiError` with a machine code, status, and optional per-field errors. Callers handle one shape.\n5. **Identifiers are branded.** Domain IDs are nominal types (`InvoiceId`, `CustomerId`) so the compiler rejects passing one where another is expected — the most common silent bug in data-heavy UIs.\n\n---\n\n## 1. Directory layout\n\nThe boundary is one folder in `shared\u002F` (per the frontend-architecture skill).\n\n```\nsrc\u002Fshared\u002Fapi-client\u002F\n├── index.ts        ← barrel: apiClient, ApiError, types\n├── client.ts       ← the fetch wrapper: buildUrl, headers, parse, verbs\n├── config.ts       ← base URL resolution, default headers\n├── error.ts        ← the ApiError class + code→message-key mapping\n├── types.ts        ← envelope types, HttpMethod, RequestOptions, field errors\n└── client.test.ts  ← boundary behavior tests (envelope, errors, network)\n```\n\nDomain entity types and their **schemas** live with their feature module\n(`modules\u002F{feature}\u002Ftypes\u002F`) or a shared contract package; the client is generic over `T`.\n\n---\n\n## 2. One client, the only fetch boundary\n\nEvery verb returns the **unwrapped** `data` payload typed by the caller, and **throws** an\n`ApiError` on any failure. Components never see envelopes or raw responses.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Fclient.ts (essence)\nexport const apiClient = {\n  get\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"GET\", path, undefined, options);\n  },\n  post\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"POST\", path, body, options);\n  },\n  patch\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  put\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  delete\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n} as const;\n\nexport type ApiClient = typeof apiClient;\n```\n\n```ts\n\u002F\u002F CORRECT — a feature hook wraps the client, typed by the caller\nconst invoice = await apiClient.get\u003CInvoice>(`\u002Finvoices\u002F${id}`, { signal });\n\n\u002F\u002F WRONG — a raw fetch in a component bypasses the boundary entirely\nconst res = await fetch(`\u002Fapi\u002Finvoices\u002F${id}`); \u002F\u002F untyped, unhandled errors, no envelope\n```\n\n**Hard rules:**\n\n- No `fetch`\u002F`axios`\u002F`XMLHttpRequest` outside `shared\u002Fapi-client\u002F` — enforce with an ESLint `no-restricted-imports`\u002F`no-restricted-globals` rule.\n- The client is **framework-free**: no toasts, no router, no React. Side effects (toasts, redirects) live in the query layer's `onError` (see §6).\n- Pass `AbortSignal` through `RequestOptions` so the query layer can cancel (wired by TanStack Query).\n\n---\n\n## 3. Parse, don't validate (the boundary transform)\n\n\"Validate\" leaves you with the same untyped value and a boolean. \"Parse\" returns a **new, typed\nvalue** — so downstream code is guaranteed correct by the type system. Run a schema parse at the\nboundary; after that, the value is trusted.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Ftypes\u002Finvoice.schema.ts\nimport { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n  id: z.string().transform(toInvoiceId), \u002F\u002F brand it (see §5)\n  number: z.string(),\n  status: z.nativeEnum(InvoiceStatus),\n  total: z.number().int(), \u002F\u002F minor units — never float money\n  issuedAt: z.string().datetime(),\n});\nexport type Invoice = z.infer\u003Ctypeof invoiceSchema>;\n```\n\n```ts\n\u002F\u002F the client (or a thin per-entity wrapper) parses at the edge\nconst raw = await apiClient.get\u003Cunknown>(`\u002Finvoices\u002F${id}`, { signal });\nreturn invoiceSchema.parse(raw); \u002F\u002F throws on contract drift → surfaces as a typed failure\n```\n\n**Why this matters:** a backend that renames a field or sends a `null` it shouldn't is caught **at\nthe boundary**, with a clear error, instead of producing `undefined` three components deep where\nthe stack trace is useless. Components downstream never write `invoice?.total ?? 0` defensively.\n\n> Validation library is your choice — **Zod**, **Valibot**, **ArkType**, **io-ts**. The rule is\n> constant: a parse step converts `unknown` wire data into a typed domain value at one boundary.\n\n---\n\n## 4. One response envelope\n\nMirror the backend's single envelope in the client and unwrap it once.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ftypes.ts\nexport interface ApiSuccessEnvelope\u003CT> {\n  data: T;\n}\nexport interface ApiErrorEnvelope {\n  error: ApiErrorBody;\n}\nexport type ApiEnvelope\u003CT> = ApiSuccessEnvelope\u003CT> | ApiErrorEnvelope;\n\nexport function isApiErrorEnvelope\u003CT>(\n  e: ApiEnvelope\u003CT>,\n): e is ApiErrorEnvelope {\n  return typeof e === \"object\" && e !== null && \"error\" in e;\n}\n\nexport interface ApiErrorBody {\n  code: ServerErrorCode; \u002F\u002F machine-readable, stable\n  message: string; \u002F\u002F server message (NOT shown to users directly)\n  fields?: Record\u003Cstring, string[]>; \u002F\u002F per-field validation errors\n}\n```\n\nThe parse step handles every shape: `204 No Content` → `undefined`; `{ error }` → throw; non-2xx\nwith no well-formed envelope → synthesize an error; `{ data }` → return `data`. The caller only\never sees a typed payload or a throw.\n\n---\n\n## 5. Branded (nominal) identifiers\n\nStrings are interchangeable; domain IDs are not. Brand them so the compiler stops you passing a\n`CustomerId` where an `InvoiceId` is required.\n\n```ts\n\u002F\u002F shared\u002Ftypes\u002Fid.ts\ndeclare const brand: unique symbol;\nexport type Brand\u003CT, B extends string> = T & { readonly [brand]: B };\n\nexport type InvoiceId = Brand\u003Cstring, \"InvoiceId\">;\nexport type CustomerId = Brand\u003Cstring, \"CustomerId\">;\n\nexport const toInvoiceId = (s: string): InvoiceId => s as InvoiceId;\nexport const toCustomerId = (s: string): CustomerId => s as CustomerId;\n```\n\n```ts\nfunction loadInvoice(id: InvoiceId) {\n  \u002F* … *\u002F\n}\nloadInvoice(customerId); \u002F\u002F ❌ compile error — exactly the bug you want caught\nloadInvoice(invoiceId); \u002F\u002F ✅\n```\n\nBrand IDs at the parse boundary (§3) so every ID in the app is already nominal. The runtime cost is\nzero — brands erase at compile time.\n\n---\n\n## 6. One normalized error type\n\nCollapse every failure mode into a single `ApiError` so callers handle one shape. It carries a\nmachine `code`, the HTTP `status`, optional per-field errors, and a stable key for localized\nmessages (it does **not** localize — that's the UI's job).\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ferror.ts (essence)\nexport class ApiError extends Error {\n  readonly code: ServerErrorCode;\n  readonly status: number; \u002F\u002F 0 when no response (network\u002Fabort)\n  readonly fields?: Record\u003Cstring, string[]>;\n\n  get isNetworkError() {\n    return this.status === 0;\n  }\n  get hasFieldErrors() {\n    return !!this.fields && Object.keys(this.fields).length > 0;\n  }\n  \u002F** Stable key under an `errors` i18n namespace — never a raw server string. *\u002F\n  get messageKey() {\n    if (this.isNetworkError) return \"network\";\n    return ERROR_CODE_MESSAGE_KEYS[this.code] ?? \"generic\";\n  }\n\n  static fromEnvelope(body: ApiErrorBody, status: number) {\n    \u002F* server { error } *\u002F\n  }\n  static fromNetwork(cause: unknown) {\n    \u002F* offline \u002F CORS \u002F abort → status 0 *\u002F\n  }\n}\n```\n\n### 6.1 Where side effects live\n\nThe client throws; the **query layer** decides what the user sees. Keep toasts\u002Fredirects out of the\nclient.\n\n```ts\n\u002F\u002F a TanStack Query mutation maps the typed error to a localized toast\nuseMutation({\n  mutationFn: (input) => apiClient.post\u003CInvoice>(\"\u002Finvoices\", input),\n  onError: (error: ApiError) => notifyError(error), \u002F\u002F looks up error.messageKey in i18n\n});\n```\n\n### 6.2 Per-field errors → form fields\n\nServer validation (`fields`) maps straight onto form-field errors — one place, typed.\n\n```ts\nif (error.hasFieldErrors) {\n  for (const [field, messages] of Object.entries(error.fields!)) {\n    form.setError(field as Path\u003CFormValues>, { message: messages[0] });\n  }\n}\n```\n\n**Hard rules:**\n\n- Never `throw new Error(string)` from the data layer — always `ApiError` with a `code`.\n- Never show `error.message` (a server\u002Fdev string) directly to users — resolve `messageKey` through i18n.\n- A 2xx with an unparseable body is a **contract violation** → throw `INVALID_RESPONSE`, don't silently return `undefined`.\n\n---\n\n## 7. Library adapters\n\nThe discipline is constant; the data-fetching library only changes where `onError`\u002Fparsing hangs.\n\n| Library                    | Where the client is called                                                | Where `ApiError` is handled                                                      |\n| -------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |\n| **TanStack Query**         | `queryFn`\u002F`mutationFn` call `apiClient.*`                                 | `onError` per query\u002Fmutation, or a global `QueryCache`\u002F`MutationCache` `onError` |\n| **RTK Query**              | `baseQuery` wraps `apiClient`, parses + returns `{ data }` or `{ error }` | `transformErrorResponse` → `ApiError`; handle in component or middleware         |\n| **SWR**                    | `fetcher = (key) => apiClient.get(key)`                                   | `onError` in `SWRConfig` or per-hook                                             |\n| **Plain fetch hooks (RN)** | a `useAsync` wrapper calls `apiClient.*`                                  | try\u002Fcatch sets a typed error state                                               |\n\nFor **React Native**, the client is unchanged — `fetch` and `AbortController` exist in RN. Only\n`credentials: \"include\"` (cookie auth) may need swapping for a token header depending on your auth.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Exactly one `apiClient` in `shared\u002Fapi-client\u002F`; no `fetch`\u002F`axios` anywhere else (lint-enforced).\n- [ ] The client is framework-free — no toasts, router, or React inside it.\n- [ ] Responses are parsed into typed domain values at the boundary (parse, don't validate).\n- [ ] One `{ data } \u002F { error }` envelope, unwrapped once in the client.\n- [ ] Every failure becomes one `ApiError` (code + status + optional fields); no bare `throw new Error`.\n- [ ] Domain IDs are branded; IDs are branded at the parse boundary.\n- [ ] `error.messageKey` resolves through i18n — server `message` is never shown to users.\n- [ ] Per-field server errors map onto form fields via the typed `fields` map.\n- [ ] `AbortSignal` flows through `RequestOptions` for cancellation.\n- [ ] A 2xx with a malformed body throws a contract-violation error, not `undefined`.\n\n---\n\n## 9. How to apply this skill\n\n**Adding the boundary to a project:** create `shared\u002Fapi-client\u002F` with `client.ts`, `error.ts`,\n`types.ts`, `config.ts`. Add the lint rule banning `fetch`\u002F`axios` elsewhere. Define your envelope\nto match the backend, and your `ApiError` codes.\n\n**Adding a new entity:** define its schema (Zod\u002FValibot) and `z.infer` type in the feature module,\nbrand its ID at parse time, and wrap `apiClient` in typed query\u002Fmutation hooks — never call the\nclient from a component.\n\n**Debugging \"undefined three components deep\":** add\u002Frepair the boundary parse so contract drift\nfails loudly at the edge with a typed error, instead of leaking `undefined` downstream.\n\n**Reviewing the data layer:** run the checklist in §8. The highest-value catches are raw `fetch` in\ncomponents (boundary bypass) and `throw new Error(string)` from the data layer (untyped failures).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-data-contracts\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-data-contracts\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n","# Frontend Data Contracts (typed network boundary)\n## When to Use\n\nUse this skill when you need a portable, framework-agnostic discipline for type safety at the network edge of any React or React Native app. Establishes one typed API client as the single fetch boundary, a parse-don't-validate rule that turns wire JSON into trusted domain types before it enters the app, a single...\n\n\n> Portable skill — readable by Claude Code, OpenCode, Codex, Cursor, Windsurf, and others.\n> This skill describes a **discipline at the network edge** — one client, one envelope, one error\n> type, validated types — not a state library or a styling system. It pairs with the\n> **frontend-architecture** skill (the client lives in `shared\u002Fapi-client\u002F`) and is the foundation\n> the **frontend-optimistic-mutations** skill builds on.\n\nThe goal: the moment data crosses from the network into the app, it stops being `any`-shaped wire\nJSON and becomes a **trusted, typed domain value** — or it becomes a **single, typed error**.\nThere is exactly one place this transformation happens, and nothing untyped escapes it.\n\n---\n\n## 0. The five core ideas\n\n1. **One client is the only fetch boundary.** A single typed `apiClient` wraps `fetch`. Components and hooks never call `fetch`\u002F`axios` directly — the boundary is enforceable in review and lint.\n2. **Parse, don't validate.** Wire JSON is parsed into domain types at the boundary. After the client returns, the value is trusted everywhere downstream — no defensive `?.` chains, no re-checking shapes in components.\n3. **One envelope.** Every response is `{ data }` on success or `{ error }` on failure. The client unwraps `data` and throws on `error`, so callers receive the payload directly or a typed throw.\n4. **One normalized error type.** Server error envelope, non-2xx status, malformed body, network failure, and abort all become a single `ApiError` with a machine code, status, and optional per-field errors. Callers handle one shape.\n5. **Identifiers are branded.** Domain IDs are nominal types (`InvoiceId`, `CustomerId`) so the compiler rejects passing one where another is expected — the most common silent bug in data-heavy UIs.\n\n---\n\n## 1. Directory layout\n\nThe boundary is one folder in `shared\u002F` (per the frontend-architecture skill).\n\n```\nsrc\u002Fshared\u002Fapi-client\u002F\n├── index.ts        ← barrel: apiClient, ApiError, types\n├── client.ts       ← the fetch wrapper: buildUrl, headers, parse, verbs\n├── config.ts       ← base URL resolution, default headers\n├── error.ts        ← the ApiError class + code→message-key mapping\n├── types.ts        ← envelope types, HttpMethod, RequestOptions, field errors\n└── client.test.ts  ← boundary behavior tests (envelope, errors, network)\n```\n\nDomain entity types and their **schemas** live with their feature module\n(`modules\u002F{feature}\u002Ftypes\u002F`) or a shared contract package; the client is generic over `T`.\n\n---\n\n## 2. One client, the only fetch boundary\n\nEvery verb returns the **unwrapped** `data` payload typed by the caller, and **throws** an\n`ApiError` on any failure. Components never see envelopes or raw responses.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Fclient.ts (essence)\nexport const apiClient = {\n  get\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"GET\", path, undefined, options);\n  },\n  post\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    return request\u003CT>(\"POST\", path, body, options);\n  },\n  patch\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  put\u003CT>(path: string, body?: unknown, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n  delete\u003CT>(path: string, options?: RequestOptions): Promise\u003CT> {\n    \u002F* … *\u002F\n  },\n} as const;\n\nexport type ApiClient = typeof apiClient;\n```\n\n```ts\n\u002F\u002F CORRECT — a feature hook wraps the client, typed by the caller\nconst invoice = await apiClient.get\u003CInvoice>(`\u002Finvoices\u002F${id}`, { signal });\n\n\u002F\u002F WRONG — a raw fetch in a component bypasses the boundary entirely\nconst res = await fetch(`\u002Fapi\u002Finvoices\u002F${id}`); \u002F\u002F untyped, unhandled errors, no envelope\n```\n\n**Hard rules:**\n\n- No `fetch`\u002F`axios`\u002F`XMLHttpRequest` outside `shared\u002Fapi-client\u002F` — enforce with an ESLint `no-restricted-imports`\u002F`no-restricted-globals` rule.\n- The client is **framework-free**: no toasts, no router, no React. Side effects (toasts, redirects) live in the query layer's `onError` (see §6).\n- Pass `AbortSignal` through `RequestOptions` so the query layer can cancel (wired by TanStack Query).\n\n---\n\n## 3. Parse, don't validate (the boundary transform)\n\n\"Validate\" leaves you with the same untyped value and a boolean. \"Parse\" returns a **new, typed\nvalue** — so downstream code is guaranteed correct by the type system. Run a schema parse at the\nboundary; after that, the value is trusted.\n\n```ts\n\u002F\u002F modules\u002Finvoice\u002Ftypes\u002Finvoice.schema.ts\nimport { z } from \"zod\";\n\nexport const invoiceSchema = z.object({\n  id: z.string().transform(toInvoiceId), \u002F\u002F brand it (see §5)\n  number: z.string(),\n  status: z.nativeEnum(InvoiceStatus),\n  total: z.number().int(), \u002F\u002F minor units — never float money\n  issuedAt: z.string().datetime(),\n});\nexport type Invoice = z.infer\u003Ctypeof invoiceSchema>;\n```\n\n```ts\n\u002F\u002F the client (or a thin per-entity wrapper) parses at the edge\nconst raw = await apiClient.get\u003Cunknown>(`\u002Finvoices\u002F${id}`, { signal });\nreturn invoiceSchema.parse(raw); \u002F\u002F throws on contract drift → surfaces as a typed failure\n```\n\n**Why this matters:** a backend that renames a field or sends a `null` it shouldn't is caught **at\nthe boundary**, with a clear error, instead of producing `undefined` three components deep where\nthe stack trace is useless. Components downstream never write `invoice?.total ?? 0` defensively.\n\n> Validation library is your choice — **Zod**, **Valibot**, **ArkType**, **io-ts**. The rule is\n> constant: a parse step converts `unknown` wire data into a typed domain value at one boundary.\n\n---\n\n## 4. One response envelope\n\nMirror the backend's single envelope in the client and unwrap it once.\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ftypes.ts\nexport interface ApiSuccessEnvelope\u003CT> {\n  data: T;\n}\nexport interface ApiErrorEnvelope {\n  error: ApiErrorBody;\n}\nexport type ApiEnvelope\u003CT> = ApiSuccessEnvelope\u003CT> | ApiErrorEnvelope;\n\nexport function isApiErrorEnvelope\u003CT>(\n  e: ApiEnvelope\u003CT>,\n): e is ApiErrorEnvelope {\n  return typeof e === \"object\" && e !== null && \"error\" in e;\n}\n\nexport interface ApiErrorBody {\n  code: ServerErrorCode; \u002F\u002F machine-readable, stable\n  message: string; \u002F\u002F server message (NOT shown to users directly)\n  fields?: Record\u003Cstring, string[]>; \u002F\u002F per-field validation errors\n}\n```\n\nThe parse step handles every shape: `204 No Content` → `undefined`; `{ error }` → throw; non-2xx\nwith no well-formed envelope → synthesize an error; `{ data }` → return `data`. The caller only\never sees a typed payload or a throw.\n\n---\n\n## 5. Branded (nominal) identifiers\n\nStrings are interchangeable; domain IDs are not. Brand them so the compiler stops you passing a\n`CustomerId` where an `InvoiceId` is required.\n\n```ts\n\u002F\u002F shared\u002Ftypes\u002Fid.ts\ndeclare const brand: unique symbol;\nexport type Brand\u003CT, B extends string> = T & { readonly [brand]: B };\n\nexport type InvoiceId = Brand\u003Cstring, \"InvoiceId\">;\nexport type CustomerId = Brand\u003Cstring, \"CustomerId\">;\n\nexport const toInvoiceId = (s: string): InvoiceId => s as InvoiceId;\nexport const toCustomerId = (s: string): CustomerId => s as CustomerId;\n```\n\n```ts\nfunction loadInvoice(id: InvoiceId) {\n  \u002F* … *\u002F\n}\nloadInvoice(customerId); \u002F\u002F ❌ compile error — exactly the bug you want caught\nloadInvoice(invoiceId); \u002F\u002F ✅\n```\n\nBrand IDs at the parse boundary (§3) so every ID in the app is already nominal. The runtime cost is\nzero — brands erase at compile time.\n\n---\n\n## 6. One normalized error type\n\nCollapse every failure mode into a single `ApiError` so callers handle one shape. It carries a\nmachine `code`, the HTTP `status`, optional per-field errors, and a stable key for localized\nmessages (it does **not** localize — that's the UI's job).\n\n```ts\n\u002F\u002F shared\u002Fapi-client\u002Ferror.ts (essence)\nexport class ApiError extends Error {\n  readonly code: ServerErrorCode;\n  readonly status: number; \u002F\u002F 0 when no response (network\u002Fabort)\n  readonly fields?: Record\u003Cstring, string[]>;\n\n  get isNetworkError() {\n    return this.status === 0;\n  }\n  get hasFieldErrors() {\n    return !!this.fields && Object.keys(this.fields).length > 0;\n  }\n  \u002F** Stable key under an `errors` i18n namespace — never a raw server string. *\u002F\n  get messageKey() {\n    if (this.isNetworkError) return \"network\";\n    return ERROR_CODE_MESSAGE_KEYS[this.code] ?? \"generic\";\n  }\n\n  static fromEnvelope(body: ApiErrorBody, status: number) {\n    \u002F* server { error } *\u002F\n  }\n  static fromNetwork(cause: unknown) {\n    \u002F* offline \u002F CORS \u002F abort → status 0 *\u002F\n  }\n}\n```\n\n### 6.1 Where side effects live\n\nThe client throws; the **query layer** decides what the user sees. Keep toasts\u002Fredirects out of the\nclient.\n\n```ts\n\u002F\u002F a TanStack Query mutation maps the typed error to a localized toast\nuseMutation({\n  mutationFn: (input) => apiClient.post\u003CInvoice>(\"\u002Finvoices\", input),\n  onError: (error: ApiError) => notifyError(error), \u002F\u002F looks up error.messageKey in i18n\n});\n```\n\n### 6.2 Per-field errors → form fields\n\nServer validation (`fields`) maps straight onto form-field errors — one place, typed.\n\n```ts\nif (error.hasFieldErrors) {\n  for (const [field, messages] of Object.entries(error.fields!)) {\n    form.setError(field as Path\u003CFormValues>, { message: messages[0] });\n  }\n}\n```\n\n**Hard rules:**\n\n- Never `throw new Error(string)` from the data layer — always `ApiError` with a `code`.\n- Never show `error.message` (a server\u002Fdev string) directly to users — resolve `messageKey` through i18n.\n- A 2xx with an unparseable body is a **contract violation** → throw `INVALID_RESPONSE`, don't silently return `undefined`.\n\n---\n\n## 7. Library adapters\n\nThe discipline is constant; the data-fetching library only changes where `onError`\u002Fparsing hangs.\n\n| Library                    | Where the client is called                                                | Where `ApiError` is handled                                                      |\n| -------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |\n| **TanStack Query**         | `queryFn`\u002F`mutationFn` call `apiClient.*`                                 | `onError` per query\u002Fmutation, or a global `QueryCache`\u002F`MutationCache` `onError` |\n| **RTK Query**              | `baseQuery` wraps `apiClient`, parses + returns `{ data }` or `{ error }` | `transformErrorResponse` → `ApiError`; handle in component or middleware         |\n| **SWR**                    | `fetcher = (key) => apiClient.get(key)`                                   | `onError` in `SWRConfig` or per-hook                                             |\n| **Plain fetch hooks (RN)** | a `useAsync` wrapper calls `apiClient.*`                                  | try\u002Fcatch sets a typed error state                                               |\n\nFor **React Native**, the client is unchanged — `fetch` and `AbortController` exist in RN. Only\n`credentials: \"include\"` (cookie auth) may need swapping for a token header depending on your auth.\n\n---\n\n## 8. Conventions checklist (enforce in review)\n\n- [ ] Exactly one `apiClient` in `shared\u002Fapi-client\u002F`; no `fetch`\u002F`axios` anywhere else (lint-enforced).\n- [ ] The client is framework-free — no toasts, router, or React inside it.\n- [ ] Responses are parsed into typed domain values at the boundary (parse, don't validate).\n- [ ] One `{ data } \u002F { error }` envelope, unwrapped once in the client.\n- [ ] Every failure becomes one `ApiError` (code + status + optional fields); no bare `throw new Error`.\n- [ ] Domain IDs are branded; IDs are branded at the parse boundary.\n- [ ] `error.messageKey` resolves through i18n — server `message` is never shown to users.\n- [ ] Per-field server errors map onto form fields via the typed `fields` map.\n- [ ] `AbortSignal` flows through `RequestOptions` for cancellation.\n- [ ] A 2xx with a malformed body throws a contract-violation error, not `undefined`.\n\n---\n\n## 9. How to apply this skill\n\n**Adding the boundary to a project:** create `shared\u002Fapi-client\u002F` with `client.ts`, `error.ts`,\n`types.ts`, `config.ts`. Add the lint rule banning `fetch`\u002F`axios` elsewhere. Define your envelope\nto match the backend, and your `ApiError` codes.\n\n**Adding a new entity:** define its schema (Zod\u002FValibot) and `z.infer` type in the feature module,\nbrand its ID at parse time, and wrap `apiClient` in typed query\u002Fmutation hooks — never call the\nclient from a component.\n\n**Debugging \"undefined three components deep\":** add\u002Frepair the boundary parse so contract drift\nfails loudly at the edge with a typed error, instead of leaking `undefined` downstream.\n\n**Reviewing the data layer:** run the checklist in §8. The highest-value catches are raw `fetch` in\ncomponents (boundary bypass) and `throw new Error(string)` from the data layer (untyped failures).\n\n---\n\n## Publishing \u002F installing this skill\n\nThis skill follows the Anthropic `SKILL.md` format and is portable across agents.\n\n1. Keep it under `skills\u002Ffrontend-data-contracts\u002FSKILL.md` in a public GitHub repo.\n2. Keep the frontmatter `name` and high-signal `description` — discovery indexes match against it.\n3. Install with: `npx skills add \u003Corg>\u002F\u003Crepo> --skill \"frontend-data-contracts\"`.\n4. Non-`SKILL.md` agents can be pointed here from `AGENTS.md` \u002F `CLAUDE.md`; Kiro can mirror it as a steering file.\n\n## Limitations\n\n- Use this skill only when the task clearly matches its upstream source and local project context.\n- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.\n- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.\n",{"name":5,"risk":43,"source":53,"license":14,"date_added":54,"description":7,"source_repo":55,"source_type":38,"license_source":56},"https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Ftree\u002Fmain\u002Fskills\u002Ffrontend-data-contracts",1782864000000,"stareezy-1\u002Ffrontend-architecture-skill","https:\u002F\u002Fgithub.com\u002Fstareezy-1\u002Ffrontend-architecture-skill\u002Fblob\u002Fmain\u002FLICENSE","f3312ba749561b6159f477dbfc9313c875d40a56",".agents\u002Fskills_archive\u002Ffrontend-data-contracts","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612","2026-10-25 23:50:58",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":74},[64,67,70],{"tool":65,"command":66},"npx","npx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill frontend-data-contracts",{"tool":68,"command":69},"bunx","bunx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill frontend-data-contracts",{"tool":71,"command":72},"pnpm","pnpm dlx skills add duc-duy-1612\u002FOnline-Delivery-Systems-Web --skill frontend-data-contracts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Ffrontend-data-contracts\u002FSKILL.md",true,[],[77,102,125,150,176,200],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":86,"publishedAt":48},"01M6Q0FA5FZ410Z33Z3TFQ4DBA","zero-trust","Implement zero-trust network architecture. Configure identity-based access, micro-segmentation, and continuous verification. Use when implementing modern security architectures.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzero-trust\u002FSKILL.md",[83],{"categoryNo":84,"categoryName":85,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000011","运维与部署",[87,88,89,45,90,91,79,92,93,94,95,96,38,39,97,43,98,99,100,101],"ZeRO","trust","zero trust","assessment","verification","segmentation","devops-security","access","configure","only","active","scope","scripts","relevant","implementing",{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":48},"01M6Q0F1YZJW3KX5FBKEVZ8CV4","zcode-delegate","Delegate coding tasks to the Z.AI ZCode CLI only when the user explicitly requests it, while the orchestrator retains review and landing responsibility.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fzcode-delegate\u002FSKILL.md",[],[109,110,111,112,113,114,115,116,117,118,119,120,121,96,122,38,123,42,43,124],"delegate","zcode","zcode delegate","review","cli","orchestration","tasks","run","Bash","model","node","read","orchestrator","files","desktop app","agent-orchestration",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":48},"01M6Q0ETK41VGNMYEXW0T00AJN","youtube-transcript","Fetch YouTube transcripts through DeepAPI or local fallback tooling and save clean text output.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript\u002FSKILL.md",[],[132,133,134,135,136,137,138,139,140,141,142,143,144,38,39,145,146,147,148,149],"transcript","youtube transcript","youtube","safe","github","codex","research","license","https","text","fetch","tooling","clean","local","output","deepapi","youtube transcripts","blob",{"skillNo":151,"name":152,"nameZh":6,"description":153,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":154,"categories":155,"keywords":165,"publishedAt":48},"01M6Q0EPPH2PVMDW40017F8WX0","youtube-transcript-skills","Fetch YouTube video transcripts, search videos\u002Fchannels, browse channels, and extract playlists via the getyoutubetranscript.com API - free tier, no card required.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-transcript-skills\u002FSKILL.md",[156,159,162],{"categoryNo":157,"categoryName":158,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":160,"categoryName":161,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":163,"categoryName":164,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000030","开发工程师",[132,133,134,166,135,167,136,137,139,168,169,170,171,142,172,38,39,173,174,175],"youtube transcript skills","gemini","search","api","Video","browse","api-integration","free","card","channels",{"skillNo":177,"name":178,"nameZh":6,"description":179,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":180,"categories":181,"keywords":186,"publishedAt":48},"01M6Q0EAB96PX83W5PTE8A0R8D","youtube-notetaker","Turn YouTube talks into local study notes with slides, transcripts, editable annotations, and a markdown-backed viewer.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-notetaker\u002FSKILL.md",[182,185],{"categoryNo":183,"categoryName":184,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000003","演示文稿",{"categoryNo":160,"categoryName":161,"taxonomyType":20,"taxonomyTypeDesc":21},[134,187,188,113,135,189,190,191,192,139,170,193,194,195,196,39,197,145,198,199],"youtube notetaker","notetaker","workflow","official","notes","code","markdown","slides","annotations","README","study","dair-academy","viewer",{"skillNo":201,"name":202,"nameZh":6,"description":203,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":204,"categories":205,"keywords":207,"publishedAt":48},"01M6Q0E55F0GW5MX48V8HXS8B5","youtube-full","Fetch YouTube transcripts, search videos, browse channels, and extract playlists via TranscriptAPI — no yt-dlp, no Google API key, works from any cloud server.","https:\u002F\u002Fgithub.com\u002Fduc-duy-1612\u002FOnline-Delivery-Systems-Web\u002Fblob\u002Fmain\u002F.agents\u002Fskills_archive\u002Fyoutube-full\u002FSKILL.md",[206],{"categoryNo":157,"categoryName":158,"taxonomyType":20,"taxonomyTypeDesc":21},[208,134,209,210,135,167,168,211,212,169,170,171,142,213,172,38,39,173,214,148],"youtube full","full","google","server","dlp","credits","automatic"]