diff --git a/AGENTS.md b/AGENTS.md index b80d7c5b7d..d6ab41cfc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -264,7 +264,7 @@ import { EntityFetcherProvider, EntityGrid } from "@metaobjectsdev/tanstack"; - **TS runtime**: Bun-first for development (zero-config TS, native test runner). Node-compatible for distribution; users install via npm/pnpm/bun without lock-in to Bun's runtime. - **Module system**: ESM only. No CommonJS, no transpile step required. - **Storage format**: JSON files in `metaobjects/meta..json` at project root. `.metaobjects/.gen-state/` holds the codegen merge base: the snapshot **bodies are gitignored** (a second full copy of all generated output), but **`.hashes/` (one file per model package) is COMMITTED** — one hash per generated path, and the only thing that lets `meta gen` tell "this file is exactly what I wrote" from "somebody edited this" on a machine that did not generate it. Ignore it and a fresh clone or CI runner silently overwrites hand edits; commit it and an edited file is refused by name instead. -- **Codegen substrate**: the vendored ts-poet printer (`codegen-ts/src/poet.ts`) for greenfield emit, ts-morph for in-place edits, Biome for format pass, `git merge-file --diff3` for hand-edit-preserving regen. +- **Codegen substrate**: the vendored ts-poet printer (`codegen-ts/src/poet.ts`) for greenfield emit, ts-morph for in-place edits, no formatter in generation (the generator's writer lays out the text, ADR-0063), `git merge-file --diff3` for hand-edit-preserving regen. - **Runtime substrate**: Kysely for TS (user-provided connection, async-only). - **Migration substrate**: Postgres + SQLite for TS v0.3. - **Metadata location**: resolved via `resolveCollection()` (`@metaobjectsdev/sdk`) — the single authority. `metaobjects/` is the **default value of `sources`** and nothing else: no other module, command or user-facing message may assert that a directory of that name exists or is where metadata lives. Exactly five sites may name it — `sdk/src/metadata-files.ts` (`DEFAULT_METADATA_DIR`, its single definition), `sdk/src/sources.ts` (`DEFAULT_SOURCES`, **the** default), `sdk/src/collection.ts` (inside `resolveCollection`, *applying* that default), `sdk/src/index.ts` (the barrel re-export of the constant, no use), and `cli/src/commands/init.ts` (the scaffolder **writing** the layout). Enforced by `sdk/test/no-hardcoded-metadata-dir.test.ts`, whose allowlist demands a written reason per entry. See [docs/features/metadata-sources.md](docs/features/metadata-sources.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a7ba7d7fc..a817abd8e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,31 @@ Each item below is described in full under Security, Added, Changed or Fixed; th integer. - **C# and Java: a names class no longer extends its base's** when that would make a base constant that is not a column of its own table reachable through it. It is emitted complete instead. +- **TypeScript generation runs no formatter.** `meta gen` used to pass every generated `.ts` file + through Biome after the template had laid it out; it no longer does, so `@metaobjectsdev/codegen-ts` + no longer depends on `@biomejs/js-api` or `@biomejs/wasm-nodejs`. Each file keeps the layout its + generator writes (the ts-poet printer's 120 columns, where a template used it), so the **first + `meta gen` rewrites most generated files once, in layout only**; a hand edit in a generated + file meets the three-way merge against a base with the new layout. The Hono routes no longer + carry a `// biome-ignore` line above `registerAllRoutes` and each `mount...Routes` function; a + project that lints generated code with Biome adds its own ignore. `formatTs` is still exported from + `@metaobjectsdev/codegen-ts` and now returns its input unchanged, so a generator ejected in 1.2 + keeps loading and running. Run your formatter over the generated tree if you want your layout. +- **`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`.** Installing the + CLI no longer installs the ORM (about 17 MB); only the code `meta gen` writes imports it. A + project installs both when it takes a generator that writes code importing them: `meta eject` + and `meta gen --list` print the install set. A project that relied on the CLI pulling them in + adds `drizzle-orm` and `zod` to its own `package.json`. A check installs the packed CLI, fails + when the ORM or a formatter comes back, and holds the install to a size budget that only moves + down (`scripts/check-install-size.mjs`, in the full CI run). +- **The SQLite driver is no longer installed with the CLI.** `@libsql/kysely-libsql` is an + optional peer of `@metaobjectsdev/cli`: it brought its own HTTP client, a polyfill and a native + binary for each libc (about 28 MB), which a Postgres or D1 project never used. `meta init` + now adds it to the `dependencies` of a SQLite project (the default dialect) and says so; a + project that already ran `init` adds it with its package manager. Without it, `meta migrate` and + `meta verify --db` against a SQLite URL stop with the install command. Postgres, MySQL and D1 + projects install nothing new. With the ORM and the formatter gone as well, installing the CLI is + about 51 MB. - **`metamodelVersion` is `1.3`.** Upgrade every port together. ### Security @@ -440,7 +465,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th lists what the approach cannot do. It is an example on the TypeScript port, not a package. - **A working loop first in the agent context.** The always-on file `meta init` scaffolds - (`.metaobjects/AGENTS.md` and `CLAUDE.md`) now opens with the whole loop for the declared + (`.metaobjects/AGENTS.md`) now opens with the whole loop for the declared stack, in order: configure and run the generators (one step per declared server, with the import or class names to wire, plus the web client when one is declared), the schema (`meta migrate --from-db` for the first migration, `apply-pending` at boot, and a later @@ -556,7 +581,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - **A view the lowering cannot express is refused, not shortened.** The TypeScript view extractor skipped any origin it could not lower, so a projection loaded clean and `meta migrate` created a view missing a column its generated type declares. Each such shape now fails, naming the - projection and the field: an aggregate-derived entity field read where a row-level value is + projection and the field, at load where the loader can see it and in the view extractor for a + model built another way: an aggregate-derived entity field read where a row-level value is needed, a computed reference cycle, a relative date on a field that is not temporal, and an unknown origin or aggregate. - **The view vocabulary lowers to SQL.** `meta migrate` builds every port's views, and it now @@ -580,7 +606,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th `error-origin-passthrough-reverse-hop` (new) and `error-origin-passthrough-to-many` pin the message. -- **An int-backed enum can be an array.** `@intValueMap` together with `isArray: true` (the +- **An int-backed enum array loads in every port, and stores in TypeScript, C# and Python.** + `@intValueMap` together with `isArray: true` (the map on the field, or inherited from a shared enum) now loads in every port instead of failing with `ERR_ENUM_INT_VALUE_MAP_ARRAY`, which is removed. Each element is stored as its declared integer and read back as its member: `integer[]` on Postgres, and a JSON array of @@ -786,7 +813,12 @@ Each item below is described in full under Security, Added, Changed or Fixed; th parameters, the error envelope, and those shapes as components. The output follows the REST contract and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen` - (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. + (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. The + document also states this release's own API behaviour: a list's `limit` carries the project's + `api.pagination` default and maximum, a write's body says an undeclared key is refused with + `unknown_fields` (or dropped under `api.unknownFields: drop`), the error envelope carries + `issues`, `fields` and `maxLimit`, and a read-only resource says a write answers `405`. A project + that wires `openApiFile()` sees `openapi.json` change on the next `meta gen`. - **The data spine for a model explorer.** These changes are data only. No screen reads the new data yet. - `meta export --effective` writes the effective canonical JSON. Every field, child and attribute @@ -1710,7 +1742,7 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - **`@metaobjectsdev/cli` no longer installs the native Biome binary.** `codegen-ts-react`, `codegen-ts-tanstack` and the source-only `codegen-ts-angular` declared `@biomejs/biome` as a peer dependency, which npm installs automatically, so every CLI install carried the ~94 MB - `@biomejs/cli-` binary that nothing runs: codegen formats through the WebAssembly + `@biomejs/cli-` binary that nothing runs: the CLI used the WebAssembly build (`@biomejs/wasm-nodejs`). The peer is gone (it stays a devDependency for this repo's own lint gate), and a fresh npm install of the CLI drops from 245 MB to 151 MB of `node_modules`. `scripts/check-peer-ranges.ts` now fails a publishable package that requires `@biomejs/biome` diff --git a/agent-context/skills/metaobjects-codegen/references/typescript.md b/agent-context/skills/metaobjects-codegen/references/typescript.md index 588e061158..92401736a4 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript.md @@ -48,7 +48,7 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`, and `formatTs` for TypeScript output. The config's `apiPrefix` is +`pluralize`, and `formatTs` (a no-op kept so an owned copy still loads). The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. @@ -59,6 +59,11 @@ npm install --save-dev @metaobjectsdev/cli @metaobjectsdev/codegen-ts npm install @metaobjectsdev/metadata @metaobjectsdev/runtime-ts ``` +`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`, so npm does not install +them with the CLI. Install them when a generator you take writes code that imports them. +`meta gen --list --format json` gives each generator's `install.dev` and `install.runtime`, and +`meta eject ...` prints the consolidated install set. + For the React + TanStack codegen packages, also: ```bash diff --git a/bun.lock b/bun.lock index 985f139383..8a5ac3b437 100644 --- a/bun.lock +++ b/bun.lock @@ -178,7 +178,6 @@ "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", - "@libsql/kysely-libsql": "^0.4.0", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/codegen-ts-react": "workspace:*", "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", @@ -193,6 +192,7 @@ }, "devDependencies": { "@libsql/client": "^0.14.0", + "@libsql/kysely-libsql": "^0.4.1", "@metaobjectsdev/test-generators": "workspace:*", "@types/node": "^22.0.0", "@types/pg": "^8.0.0", @@ -208,10 +208,12 @@ "zod": "^4.4.3", }, "peerDependencies": { + "@libsql/kysely-libsql": ">=0.4.0 <0.5.0", "kysely": ">=0.27.0 <0.30.0", "pg": ">=8.0.0 <9.0.0", }, "optionalPeers": [ + "@libsql/kysely-libsql", "pg", ], }, @@ -219,8 +221,6 @@ "name": "@metaobjectsdev/codegen-ts", "version": "1.3.0", "dependencies": { - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1", "@metaobjectsdev/docs-site": "workspace:*", @@ -246,6 +246,10 @@ "drizzle-orm": ">=0.38.0 <1.0.0", "zod": ">=3.23.0 <5.0.0", }, + "optionalPeers": [ + "drizzle-orm", + "zod", + ], }, "server/typescript/packages/codegen-ts-angular": { "name": "@metaobjectsdev/codegen-ts-angular", diff --git a/docs/features/cli.md b/docs/features/cli.md index 63efac777f..2cb7085229 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -25,7 +25,7 @@ command surface splits in two: | Capability | Tool | Invocation | Notes | |---|---|---|---| -| Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); `--force` over an existing config does not add it | +| Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); for `--dialect sqlite` it also adds `@libsql/kysely-libsql` to the project's `dependencies`, the SQLite driver the CLI's optional peer names (run your package manager's install afterwards); `--force` over an existing config does not add it | | **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); non-Node CLIs redirect here | | **Schema migrate** | **Node `meta`** | `meta migrate` | **any backend** — schema is Node-only (ADR-0015) | | **Schema drift** (`verify --db`) | **Node `meta`** | `meta verify --db` | **any backend** — live-DB drift, Node-only | diff --git a/docs/features/contract-emitters.md b/docs/features/contract-emitters.md index fa016e75d7..ac56bd8c13 100644 --- a/docs/features/contract-emitters.md +++ b/docs/features/contract-emitters.md @@ -19,8 +19,8 @@ port actually send and take, under the project's [`wire` setting](api-contract.m **What they do not do.** They generate no client and no server, and they do not validate anything at runtime. Run openapi-generator, Kiota or orval on the document for a client. The protobuf emitter in -the [design](../superpowers/specs/2026-06-11-fr-022-contract-emitters-design.md) is not built; it is -planned with binary protocols for 1.3. +the [design](../superpowers/specs/2026-06-11-fr-022-contract-emitters-design.md) is not built, and no +release is planned for it. **Entirely opt-in.** `meta init` wires no generator. A project that does not list them gets no file. @@ -160,6 +160,21 @@ field's allowed operators, `sort`, `limit`, `offset` and `withCount`, M:N traver and per-subtype mounts, projections, reports (with the `format` parameter when `report-export` is wired), and the error envelope. +It also states what the routes do beyond the happy path: + +- **Page size.** When the project sets `api.pagination`, a list's `limit` carries that `default` and + `maximum`, and the description names the `limit_too_large` answer. Without the setting `limit` + states neither, because the server serves what it always did. A report keeps its own row cap and + states neither either. +- **Undeclared body keys.** A create, `PUT` or `PATCH` body description says an undeclared key is + refused with `400 unknown_fields` (the default) or dropped under `api.unknownFields: drop`. + The shapes stay open: the server still drops a declared key a client may not set, such as the + generated key, so a client that echoes back a row it read keeps working. +- **Validation issues.** `ApiError` carries `issues` (every problem, as `code`, `path` and + `message`), `fields` (the undeclared keys) and `maxLimit`. +- **Read-only resources.** A projection or a report has no write operations, and each of its + operations says a write answers `405 method_not_allowed`. + A list answers an array, or `{ rows, total }` with `withCount=1`, so its response is a `oneOf` of `List` and `Page`. @@ -187,7 +202,8 @@ openApiFile({ - `readOnly` and `writeOnly`: the shapes are separate. - The TypeScript-only `search`, `filter[or]` and `filter[and]` extensions: the document states the cross-port contract ([api-contract.md](api-contract.md)). -- 405 answers: a verb a read-only surface does not serve is absent from the document. +- 405 answers as operations: a verb a read-only surface does not serve is absent from the document, + and the surface's operations say so in prose. - Routes you wrote by hand. Eject `openapi` and add them in `buildOpenApiDocument` if you want them documented. diff --git a/docs/features/migrations/commit-the-gen-state-hash-manifest.md b/docs/features/migrations/commit-the-gen-state-hash-manifest.md index 215343f1b4..542cdf5df2 100644 --- a/docs/features/migrations/commit-the-gen-state-hash-manifest.md +++ b/docs/features/migrations/commit-the-gen-state-hash-manifest.md @@ -48,7 +48,7 @@ meta gen # the regeneration, now on its own ``` **Why `--baseline=adopt` and not a plain `meta gen`.** A plain run works only if your -committed output still matches fresh output. If it does not — an engine or formatter moved +committed output still matches fresh output. If it does not — an engine moved it, which is the usual state of a project that has not regenerated in a few releases — every such file is refused, and a run where *everything* refuses writes **no manifest at all**: there is then nothing to commit, and the next run refuses identically. `--baseline=adopt` @@ -84,7 +84,7 @@ two people who both regenerated do not conflict over ordering. | situation | before | after | |---|---|---| -| File matches its recorded hash (a formatter or engine bump moved the output) | overwritten, reported `NEW` | overwritten, reported `overwrite` | +| File matches its recorded hash (an engine bump moved the output) | overwritten, reported `NEW` | overwritten, reported `overwrite` | | File carries a hand edit | **overwritten silently** | `refused`, path named, exit code 1 | | File we have no record of writing | **overwritten silently** | `refused`, path named, exit code 1 | | Snapshot body present (the machine that generated it) | three-way merge | three-way merge, unchanged | diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index ae0af49d13..06add2c7ee 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -84,11 +84,18 @@ npm install --save-dev @metaobjectsdev/codegen-ts-react @metaobjectsdev/codegen- npm install @metaobjectsdev/react @metaobjectsdev/tanstack @metaobjectsdev/runtime-web ``` -`@metaobjectsdev/codegen-ts` declares `drizzle-orm` and `zod` as non-optional -peer dependencies, so npm installs both automatically. The default Fastify -routes generator (`routesFile()`) additionally needs `fastify` at runtime — it -is an **optional** peer of `@metaobjectsdev/runtime-ts` (so it is *not* -auto-installed); add it explicitly: +`@metaobjectsdev/codegen-ts` declares `drizzle-orm` and `zod` as **optional** peer +dependencies, so npm installs neither with it. Install them when the generators you +take write code that imports them; `meta gen --list --format json` gives each +generator's install set. The stock `entity`, `queries` and `routes` pair needs both: + +```bash +npm install drizzle-orm zod +``` + +The default Fastify routes generator (`routesFile()`) additionally needs `fastify` +at runtime — it is an **optional** peer of `@metaobjectsdev/runtime-ts` (so it is +*not* auto-installed); add it explicitly: ```bash npm install fastify diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json index c67f9bf9ad..b960c50d96 100644 --- a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json @@ -5,22 +5,22 @@ "sourceNode": "acme::learn::Author" }, "src/generated/Author.queries.ts": { - "hash": "42cc1ab2fd442559e1e9c5c3f14978f306efcda5472f8b5370d3339753e5a36f", + "hash": "bea4d154f02ed1b93679acde9ece817be80c625b65f5b4efa2d6aaba712b9185", "generatedBy": "queries-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.routes.ts": { - "hash": "38d9a39b2fc93dc63ba0bc11d91d151f2a24b0af808a10dfdddf61a2d58356de", + "hash": "777c863287967d273a91afc4c1b706ab87c6c178fb995fe911ffce3360b53747", "generatedBy": "routes-file", "sourceNode": "acme::learn::Author" }, "src/generated/Author.ts": { - "hash": "36f28e09c3633848bf3bdb45372e03ae8b036792dec05f503a6f0d3abc1bb1cc", + "hash": "a1669e4eec814446e5da4561636312698cce75d2ee5c8afd1d38016a616d2f98", "generatedBy": "entity-file", "sourceNode": "acme::learn::Author" }, "src/generated/InstructorProfile.ts": { - "hash": "2643b88401edf303789461d7d05bafd7cb1979b0ff19c27958d156192265986a", + "hash": "3559df25112ecb00911c2668a2fce07770b213fee9455fce80906162814b2c17", "generatedBy": "entity-file", "sourceNode": "acme::learn::InstructorProfile" }, @@ -30,17 +30,17 @@ "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.queries.ts": { - "hash": "bc8e9bff3cb70c2c47ecfd07619f90d3f26a3981aca8ce6828f75e2a80fb9273", + "hash": "d6fa0b0c29b65afd52e69423e79dc478b3dcde505fac55bca7057cb00f46eb1a", "generatedBy": "queries-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.routes.ts": { - "hash": "a706159a09e459f44f1dd0721cf26320862768a4305363d94cf66b5fb8b5ae2a", + "hash": "b57f413c9b5582fee2cf9150064f879d106b0e94c0b4e75448b0a1fce3e7e708", "generatedBy": "routes-file", "sourceNode": "acme::learn::Lesson" }, "src/generated/Lesson.ts": { - "hash": "404b7d27b2ec7a6158c6915dbe289c09e36b8fafe8ed82b14871a3bbfa117db8", + "hash": "c699a4d4a0584e9206d7562ea16116c34c5dc85ee4027acaf9cb0b01d2222f06", "generatedBy": "entity-file", "sourceNode": "acme::learn::Lesson" }, @@ -50,17 +50,17 @@ "sourceNode": "acme::learn::Program" }, "src/generated/Program.queries.ts": { - "hash": "07bde6eda6ec265f3b9b61b73b379ed2a066a9b852ecbda2c6bf7ee5d5d079cf", + "hash": "d0b4b7d598cf4da0c7200e78198cf81fc807edf5563f83028b31a01b1da0288b", "generatedBy": "queries-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.routes.ts": { - "hash": "c0b0b5cf1761371480aa90d613c5170212b4b4ef63fd265f1362ff4051b50af9", + "hash": "a0b184a3475fbe3c5f06cc88007a76fa298e375f4c1be8b6037a781f2aef7860", "generatedBy": "routes-file", "sourceNode": "acme::learn::Program" }, "src/generated/Program.ts": { - "hash": "a658aad738aa33578fa5e5091494137f0268ea497a6daf5c61422861cdf04806", + "hash": "95c5f5a951d1b219b4f3a4cef6dfc5fc0ea4612c3b18529fc3defaf27aa7e952", "generatedBy": "entity-file", "sourceNode": "acme::learn::Program" }, @@ -71,17 +71,17 @@ "sourceNode": "acme::learn::ProgramDescriptionPayload" }, "src/generated/ProgramSummary.queries.ts": { - "hash": "743e8ce74eee85bb821cf3d909957fae630085fb1f5a7567dd6bfdcae4364910", + "hash": "8902cbac50396109867e90d2e973d850e0d1e211d9d2f21c0e5f4b2882fd0dd9", "generatedBy": "queries-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.routes.ts": { - "hash": "995e893a6b21e65d7bc031761c18bb7bb0c790abb31cb72546bf95573c980099", + "hash": "3aa58a1722e50378410e05e43e797b67f7ef80ab16ec0bc6711c222787a16578", "generatedBy": "routes-file", "sourceNode": "acme::learn::ProgramSummary" }, "src/generated/ProgramSummary.ts": { - "hash": "181f48ed374dfdf2f5b3213e0064833f071fd7029ed9357a6eef764616c2429c", + "hash": "615eb82032aaf686bc3e5b1484bf2b70174ded81da0310c5a6939e6fdb33bc8d", "generatedBy": "entity-file", "sourceNode": "acme::learn::ProgramSummary" }, @@ -91,22 +91,22 @@ "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.queries.ts": { - "hash": "ae7896ebdf3a57332e2c79dc9dd99fef9547054371547d6a469a752a7fc64ad6", + "hash": "9527a9cae7157415d78c64d21164779272d731827efa807505dc3552728be1e9", "generatedBy": "queries-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.routes.ts": { - "hash": "7590c063acdabcd86eec67d3d8abc6390dde576aca733944dbb1edaf1dfde5bb", + "hash": "9d634c477225b01f3873815e01423f8ae06673830b4f63f1c19df4e3222dda3f", "generatedBy": "routes-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/Purchase.ts": { - "hash": "fa88def0af1a85b18a1d9d7bb99588f0d71273ce0ee4ce633615ab0724a6bf69", + "hash": "ee57e04fa03ff23675e1a80be5beb984fee268b423ac1ecd80452d857a22d30a", "generatedBy": "entity-file", "sourceNode": "acme::learn::Purchase" }, "src/generated/SyllabusSection.ts": { - "hash": "655f1fdd3c2f104fe48e8fb9a4147c3977a820f82e2b0a6ce1db8e4bd1b3ca2c", + "hash": "d57e6668f79f6577986b2558fe57badc3f87ce8e5d55340f3063c3db57d7d367", "generatedBy": "entity-file", "sourceNode": "acme::learn::SyllabusSection" } diff --git a/examples/advanced-modeling/codegen/generators/barrel.ts b/examples/advanced-modeling/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/advanced-modeling/codegen/generators/barrel.ts +++ b/examples/advanced-modeling/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/entity.ts b/examples/advanced-modeling/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/advanced-modeling/codegen/generators/entity.ts +++ b/examples/advanced-modeling/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/advanced-modeling/codegen/generators/queries.ts b/examples/advanced-modeling/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/advanced-modeling/codegen/generators/queries.ts +++ b/examples/advanced-modeling/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index e687d1acdb..026d00f5be 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/examples/advanced-modeling/codegen/templates/routes-index.ts b/examples/advanced-modeling/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/advanced-modeling/codegen/templates/routes-index.ts +++ b/examples/advanced-modeling/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/advanced-modeling/codegen/templates/view-decl.ts b/examples/advanced-modeling/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/advanced-modeling/codegen/templates/view-decl.ts +++ b/examples/advanced-modeling/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/advanced-modeling/src/generated/Author.queries.ts b/examples/advanced-modeling/src/generated/Author.queries.ts index b365185b65..e19d0d8624 100644 --- a/examples/advanced-modeling/src/generated/Author.queries.ts +++ b/examples/advanced-modeling/src/generated/Author.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Author, - AuthorInsertSchema, - type AuthorPatch, - authors, - AuthorUpdateSchema, -} from "./Author"; -export async function findAuthorById( - db: Db, - id: string, -): Promise { - const [author] = await db - .select() - .from(authors) - .where(eq(authors.id, id)) - .limit(1); +import { type Author, AuthorInsertSchema, type AuthorPatch, authors, AuthorUpdateSchema } from "./Author"; +export async function findAuthorById(db: Db, id: string): Promise { + const [author] = await db.select().from(authors).where(eq(authors.id, id)).limit(1); return author ?? null; } -export async function listAuthors( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listAuthors(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(authors).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listAuthors( } return q; } -export async function createAuthor( - db: Db, - data: z.input, -): Promise { +export async function createAuthor(db: Db, data: z.input): Promise { const validated = AuthorInsertSchema.parse(data); const [author] = await db.insert(authors).values(validated).returning(); return author!; } -export async function updateAuthor( - db: Db, - id: string, - patch: AuthorPatch, -): Promise { +export async function updateAuthor(db: Db, id: string, patch: AuthorPatch): Promise { const validated = AuthorUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findAuthorById(db, id); } - const [author] = await db - .update(authors) - .set(validated) - .where(eq(authors.id, id)) - .returning(); + const [author] = await db.update(authors).set(validated).where(eq(authors.id, id)).returning(); return author ?? null; } export async function deleteAuthorById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(authors) - .where(eq(authors.id, id)) - .returning(); + const deleted = await db.delete(authors).where(eq(authors.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/advanced-modeling/src/generated/Author.routes.ts b/examples/advanced-modeling/src/generated/Author.routes.ts index e2a9645ce0..d61cfcb331 100644 --- a/examples/advanced-modeling/src/generated/Author.routes.ts +++ b/examples/advanced-modeling/src/generated/Author.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function authorRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Author.$path, - db, - table: authors, - insertSchema: AuthorInsertSchema, - updateSchema: AuthorUpdateSchema, - filterAllowlist: AuthorFilterAllowlist, - sortAllowlist: AuthorSortAllowlist, - dialect: "postgres", - knownFields: ["id", "name", "email", "bio"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Author.$path, + db, + table: authors, + insertSchema: AuthorInsertSchema, + updateSchema: AuthorUpdateSchema, + filterAllowlist: AuthorFilterAllowlist, + sortAllowlist: AuthorSortAllowlist, + dialect: "postgres", + knownFields: ["id", "name", "email", "bio"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Author.ts b/examples/advanced-modeling/src/generated/Author.ts index 94dd4d81e7..68e7d8db5b 100644 --- a/examples/advanced-modeling/src/generated/Author.ts +++ b/examples/advanced-modeling/src/generated/Author.ts @@ -22,12 +22,7 @@ export const AuthorInsertSchema = z.object({ export const AuthorUpdateSchema = z.object({ name: z.string().min(1).max(120).optional(), - email: z - .string() - .min(1) - .max(320) - .regex(new RegExp("^(?:[^@]+@[^@]+)$")) - .optional(), + email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(), bio: z.string().max(500).optional().nullable(), }); @@ -71,10 +66,7 @@ export const Author = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, email: { name: "email", diff --git a/examples/advanced-modeling/src/generated/InstructorProfile.ts b/examples/advanced-modeling/src/generated/InstructorProfile.ts index 4ee0b9bb91..169c326d7b 100644 --- a/examples/advanced-modeling/src/generated/InstructorProfile.ts +++ b/examples/advanced-modeling/src/generated/InstructorProfile.ts @@ -34,17 +34,13 @@ export const InstructorProfile = { label: "Bio", view: "text", htmlType: "text", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, credentialsSummary: { name: "credentialsSummary", label: "Credentials Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 300, message: "Must be 300 characters or fewer" }, - }, + rules: { maxLength: { value: 300, message: "Must be 300 characters or fewer" } }, }, } as const; diff --git a/examples/advanced-modeling/src/generated/Lesson.queries.ts b/examples/advanced-modeling/src/generated/Lesson.queries.ts index 787d1dfaf5..1f01305eae 100644 --- a/examples/advanced-modeling/src/generated/Lesson.queries.ts +++ b/examples/advanced-modeling/src/generated/Lesson.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Lesson, - LessonInsertSchema, - type LessonPatch, - lessons, - LessonUpdateSchema, -} from "./Lesson"; -export async function findLessonById( - db: Db, - id: string, -): Promise { - const [lesson] = await db - .select() - .from(lessons) - .where(eq(lessons.id, id)) - .limit(1); +import { type Lesson, LessonInsertSchema, type LessonPatch, lessons, LessonUpdateSchema } from "./Lesson"; +export async function findLessonById(db: Db, id: string): Promise { + const [lesson] = await db.select().from(lessons).where(eq(lessons.id, id)).limit(1); return lesson ?? null; } -export async function listLessons( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listLessons(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(lessons).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listLessons( } return q; } -export async function createLesson( - db: Db, - data: z.input, -): Promise { +export async function createLesson(db: Db, data: z.input): Promise { const validated = LessonInsertSchema.parse(data); const [lesson] = await db.insert(lessons).values(validated).returning(); return lesson!; } -export async function updateLesson( - db: Db, - id: string, - patch: LessonPatch, -): Promise { +export async function updateLesson(db: Db, id: string, patch: LessonPatch): Promise { const validated = LessonUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findLessonById(db, id); } - const [lesson] = await db - .update(lessons) - .set(validated) - .where(eq(lessons.id, id)) - .returning(); + const [lesson] = await db.update(lessons).set(validated).where(eq(lessons.id, id)).returning(); return lesson ?? null; } export async function deleteLessonById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(lessons) - .where(eq(lessons.id, id)) - .returning(); + const deleted = await db.delete(lessons).where(eq(lessons.id, id)).returning(); return deleted.length > 0; } -export async function findLessonsByProgram( - db: Db, - programId: string, -): Promise { +export async function findLessonsByProgram(db: Db, programId: string): Promise { return db.select().from(lessons).where(eq(lessons.programId, programId)); } -export async function findLessonsByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findLessonsByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(lessons) - .where(inArray(lessons.programId, programIds)); + return db.select().from(lessons).where(inArray(lessons.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Lesson.routes.ts b/examples/advanced-modeling/src/generated/Lesson.routes.ts index 3faa54390e..c5da461295 100644 --- a/examples/advanced-modeling/src/generated/Lesson.routes.ts +++ b/examples/advanced-modeling/src/generated/Lesson.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function lessonRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Lesson.$path, - db, - table: lessons, - insertSchema: LessonInsertSchema, - updateSchema: LessonUpdateSchema, - filterAllowlist: LessonFilterAllowlist, - sortAllowlist: LessonSortAllowlist, - dialect: "postgres", - knownFields: ["id", "programId", "title", "position"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Lesson.$path, + db, + table: lessons, + insertSchema: LessonInsertSchema, + updateSchema: LessonUpdateSchema, + filterAllowlist: LessonFilterAllowlist, + sortAllowlist: LessonSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "title", "position"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Lesson.ts b/examples/advanced-modeling/src/generated/Lesson.ts index c337e0ca25..025a7ab641 100644 --- a/examples/advanced-modeling/src/generated/Lesson.ts +++ b/examples/advanced-modeling/src/generated/Lesson.ts @@ -2,21 +2,13 @@ // Source metadata: Lesson (Lesson) // Extend in your own module (e.g. Lesson.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - type AnyPgColumn, - integer, - pgTable, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, integer, pgTable, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; export const lessons = pgTable("lessons", { id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), title: varchar("title", { length: 200 }).notNull(), position: integer("position").notNull(), }); @@ -24,24 +16,19 @@ export type Lesson = InferSelectModel; export type LessonInsert = InferInsertModel; export type LessonUpdate = Partial; export const LessonInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), title: z.string().min(1).max(200), position: z.number().int(), }); export const LessonUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), title: z.string().min(1).max(200).optional(), position: z.number().int().optional(), }); @@ -93,10 +80,7 @@ export const Lesson = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, position: { name: "position", diff --git a/examples/advanced-modeling/src/generated/Program.queries.ts b/examples/advanced-modeling/src/generated/Program.queries.ts index 55c228b3fe..cad3c64d26 100644 --- a/examples/advanced-modeling/src/generated/Program.queries.ts +++ b/examples/advanced-modeling/src/generated/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: string, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: string): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: string, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: string, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } -export async function findProgramsByAuthor( - db: Db, - authorId: string, -): Promise { +export async function findProgramsByAuthor(db: Db, authorId: string): Promise { return db.select().from(programs).where(eq(programs.authorId, authorId)); } -export async function findProgramsByAuthorIn( - db: Db, - authorIds: string[], -): Promise { +export async function findProgramsByAuthorIn(db: Db, authorIds: string[]): Promise { if (authorIds.length === 0) { return []; } - return db - .select() - .from(programs) - .where(inArray(programs.authorId, authorIds)); + return db.select().from(programs).where(inArray(programs.authorId, authorIds)); } diff --git a/examples/advanced-modeling/src/generated/Program.routes.ts b/examples/advanced-modeling/src/generated/Program.routes.ts index 4f9df9c3cd..d7f53b2bd5 100644 --- a/examples/advanced-modeling/src/generated/Program.routes.ts +++ b/examples/advanced-modeling/src/generated/Program.routes.ts @@ -35,31 +35,28 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function programRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Program.$path, - db, - table: programs, - insertSchema: ProgramInsertSchema, - updateSchema: ProgramUpdateSchema, - filterAllowlist: ProgramFilterAllowlist, - sortAllowlist: ProgramSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "title", - "status", - "summary", - "priceCents", - "coverKey", - "authorId", - "syllabus", - "instructorProfile", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Program.$path, + db, + table: programs, + insertSchema: ProgramInsertSchema, + updateSchema: ProgramUpdateSchema, + filterAllowlist: ProgramFilterAllowlist, + sortAllowlist: ProgramSortAllowlist, + dialect: "postgres", + knownFields: [ + "id", + "title", + "status", + "summary", + "priceCents", + "coverKey", + "authorId", + "syllabus", + "instructorProfile", + ], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Program.ts b/examples/advanced-modeling/src/generated/Program.ts index 3479546516..601e7ff873 100644 --- a/examples/advanced-modeling/src/generated/Program.ts +++ b/examples/advanced-modeling/src/generated/Program.ts @@ -2,51 +2,23 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - jsonb, - pgTable, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { authors } from "./Author"; -import { - type InstructorProfile, - InstructorProfileInsertSchema, -} from "./InstructorProfile"; -import { - type SyllabusSection, - SyllabusSectionInsertSchema, -} from "./SyllabusSection"; +import { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile"; +import { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection"; -export const programs = pgTable( - "programs", - { - id: uuid("id").primaryKey().defaultRandom(), - title: varchar("title", { length: 200 }).notNull(), - status: text("status", { - enum: ["draft", "published", "archived"] as const, - }), - summary: varchar("summary", { length: 2000 }), - priceCents: bigint("price_cents", { mode: "number" }), - coverKey: varchar("cover_key", { length: 80 }), - authorId: uuid("author_id") - .notNull() - .references((): AnyPgColumn => authors.id), - syllabus: jsonb("syllabus").$type(), - instructorProfile: jsonb("instructor_profile").$type(), - }, - (table) => [ - check( - "programs_status_chk", - sql`status IN ('draft', 'published', 'archived')`, - ), - ], -); +export const programs = pgTable("programs", { + id: uuid("id").primaryKey().defaultRandom(), + title: varchar("title", { length: 200 }).notNull(), + status: text("status", { enum: ["draft", "published", "archived"] as const }), + summary: varchar("summary", { length: 2000 }), + priceCents: bigint("price_cents", { mode: "number" }), + coverKey: varchar("cover_key", { length: 80 }), + authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id), + syllabus: jsonb("syllabus").$type(), + instructorProfile: jsonb("instructor_profile").$type(), +}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; export type ProgramUpdate = Partial; @@ -58,12 +30,10 @@ export const ProgramInsertSchema = z.object({ summary: z.string().max(2000).optional(), priceCents: z.number().int().optional(), coverKey: z.string().max(80).optional(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), syllabus: z.array(SyllabusSectionInsertSchema).optional(), instructorProfile: InstructorProfileInsertSchema.optional(), }); @@ -74,13 +44,10 @@ export const ProgramUpdateSchema = z.object({ summary: z.string().max(2000).optional().nullable(), priceCents: z.number().int().optional().nullable(), coverKey: z.string().max(80).optional().nullable(), - authorId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + authorId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(), instructorProfile: InstructorProfileInsertSchema.optional().nullable(), }); @@ -125,39 +92,21 @@ export const Program = { label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["draft", "published", "archived"] as const, + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const }, summary: { name: "summary", label: "Summary", view: "textarea", - rules: { - maxLength: { value: 2000, message: "Must be 2000 characters or fewer" }, - }, - }, - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", + rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } }, }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, coverKey: { name: "coverKey", label: "Cover Key", view: "image", - rules: { - maxLength: { value: 80, message: "Must be 80 characters or fewer" }, - }, + rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } }, }, authorId: { name: "authorId", @@ -166,18 +115,8 @@ export const Program = { htmlType: "text", rules: { required: "Author Id is required" }, }, - syllabus: { - name: "syllabus", - label: "Syllabus", - view: "text", - htmlType: "text", - }, - instructorProfile: { - name: "instructorProfile", - label: "Instructor Profile", - view: "text", - htmlType: "text", - }, + syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" }, + instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts index 2d3fcf25a3..02040e061f 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.queries.ts @@ -7,15 +7,8 @@ import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; import { type ProgramSummary, programSummaryView } from "./ProgramSummary"; -export async function findProgramSummaryById( - db: Db, - id: string, -): Promise { - const [row] = await db - .select() - .from(programSummaryView) - .where(eq(programSummaryView.id, id)) - .limit(1); +export async function findProgramSummaryById(db: Db, id: string): Promise { + const [row] = await db.select().from(programSummaryView).where(eq(programSummaryView.id, id)).limit(1); return row ?? null; } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts index 1050e44196..e2e18e3d9a 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.routes.ts @@ -31,18 +31,15 @@ import { mountReadOnlyCrudRoutes } from "../../codegen/runtime/drizzle-fastify/i * mount. Hand-write those reads rather than exposing this one open. */ export async function programSummaryRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountReadOnlyCrudRoutes({ - fastify: instance, - path: ProgramSummary.$path, - db, - view: programSummaryView, - filterAllowlist: ProgramSummaryFilterAllowlist, - sortAllowlist: ProgramSummarySortAllowlist, - dialect: "postgres", - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountReadOnlyCrudRoutes({ + fastify: instance, + path: ProgramSummary.$path, + db, + view: programSummaryView, + filterAllowlist: ProgramSummaryFilterAllowlist, + sortAllowlist: ProgramSummarySortAllowlist, + dialect: "postgres", + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/ProgramSummary.ts b/examples/advanced-modeling/src/generated/ProgramSummary.ts index 5d2aa001af..1576fe2edd 100644 --- a/examples/advanced-modeling/src/generated/ProgramSummary.ts +++ b/examples/advanced-modeling/src/generated/ProgramSummary.ts @@ -1,13 +1,6 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: ProgramSummary (ProgramSummary) -import { - bigint, - boolean, - pgView, - text, - uuid, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; // View declaration — Drizzle uses this for typed SELECT queries. @@ -36,18 +29,8 @@ export const ProgramSummary = { $path: "/program_summaries", id: { name: "id", label: "Id", view: "text", dbCol: "id" }, title: { name: "title", label: "Title", view: "text", dbCol: "title" }, - authorName: { - name: "authorName", - label: "Author Name", - view: "text", - dbCol: "author_name", - }, - lessonCount: { - name: "lessonCount", - label: "Lesson Count", - view: "number", - dbCol: "lesson_count", - }, + authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" }, + lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" }, completedRevenueCents: { name: "completedRevenueCents", label: "Completed Revenue Cents", @@ -56,17 +39,11 @@ export const ProgramSummary = { currency: "USD", locale: "en-US", }, - hasCoverArt: { - name: "hasCoverArt", - label: "Has Cover Art", - view: "checkbox", - dbCol: "has_cover_art", - }, + hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; -export const ProgramSummaryFilterAllowlist = - {} as const satisfies FilterAllowlist; +export const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; export const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist; diff --git a/examples/advanced-modeling/src/generated/Purchase.queries.ts b/examples/advanced-modeling/src/generated/Purchase.queries.ts index 85fa7e2c92..8d125b9e21 100644 --- a/examples/advanced-modeling/src/generated/Purchase.queries.ts +++ b/examples/advanced-modeling/src/generated/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: string, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: string): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: string, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: string, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: string): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesByProgram( - db: Db, - programId: string, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: string): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: string[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: string[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/examples/advanced-modeling/src/generated/Purchase.routes.ts b/examples/advanced-modeling/src/generated/Purchase.routes.ts index 767fac818a..e76a7d187f 100644 --- a/examples/advanced-modeling/src/generated/Purchase.routes.ts +++ b/examples/advanced-modeling/src/generated/Purchase.routes.ts @@ -35,27 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function purchaseRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Purchase.$path, - db, - table: purchases, - insertSchema: PurchaseInsertSchema, - updateSchema: PurchaseUpdateSchema, - filterAllowlist: PurchaseFilterAllowlist, - sortAllowlist: PurchaseSortAllowlist, - dialect: "postgres", - knownFields: [ - "id", - "programId", - "amountCents", - "status", - "purchasedAt", - ], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Purchase.$path, + db, + table: purchases, + insertSchema: PurchaseInsertSchema, + updateSchema: PurchaseUpdateSchema, + filterAllowlist: PurchaseFilterAllowlist, + sortAllowlist: PurchaseSortAllowlist, + dialect: "postgres", + knownFields: ["id", "programId", "amountCents", "status", "purchasedAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/advanced-modeling/src/generated/Purchase.ts b/examples/advanced-modeling/src/generated/Purchase.ts index 5e1ecd53ac..3ac361e202 100644 --- a/examples/advanced-modeling/src/generated/Purchase.ts +++ b/examples/advanced-modeling/src/generated/Purchase.ts @@ -2,41 +2,17 @@ // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - check, - pgTable, - text, - timestamp, - uuid, -} from "drizzle-orm/pg-core"; +import { type AnyPgColumn, bigint, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; -export const purchases = pgTable( - "purchases", - { - id: uuid("id").primaryKey().defaultRandom(), - programId: uuid("program_id") - .notNull() - .references((): AnyPgColumn => programs.id), - amountCents: bigint("amount_cents", { mode: "number" }), - status: text("status", { - enum: ["pending", "completed", "refunded"] as const, - }), - purchasedAt: timestamp("purchased_at", { - mode: "string", - withTimezone: true, - }), - }, - (table) => [ - check( - "purchases_status_chk", - sql`status IN ('pending', 'completed', 'refunded')`, - ), - ], -); +export const purchases = pgTable("purchases", { + id: uuid("id").primaryKey().defaultRandom(), + programId: uuid("program_id").notNull().references((): AnyPgColumn => programs.id), + amountCents: bigint("amount_cents", { mode: "number" }), + status: text("status", { enum: ["pending", "completed", "refunded"] as const }), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }), +}, (table) => [check("purchases_status_chk", sql`status IN ('pending', 'completed', 'refunded')`)]); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -49,10 +25,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -61,49 +35,33 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ), amountCents: z.number().int().optional(), status: z.enum(["pending", "completed", "refunded"]).optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ - programId: z - .string() - .regex( - /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, - "Invalid uuid", - ) - .optional(), + programId: z.string().regex( + /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/, + "Invalid uuid", + ).optional(), amountCents: z.number().int().optional().nullable(), status: z.enum(["pending", "completed", "refunded"]).optional().nullable(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional() - .nullable(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional().nullable(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A @@ -148,25 +106,9 @@ export const Purchase = { htmlType: "text", rules: { required: "Program Id is required" }, }, - amountCents: { - name: "amountCents", - label: "Amount Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, - status: { - name: "status", - label: "Status", - view: "dropdown", - options: ["pending", "completed", "refunded"] as const, - }, - purchasedAt: { - name: "purchasedAt", - label: "Purchased At", - view: "date", - htmlType: "datetime-local", - }, + amountCents: { name: "amountCents", label: "Amount Cents", view: "currency", currency: "USD", locale: "en-US" }, + status: { name: "status", label: "Status", view: "dropdown", options: ["pending", "completed", "refunded"] as const }, + purchasedAt: { name: "purchasedAt", label: "Purchased At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/advanced-modeling/src/generated/SyllabusSection.ts b/examples/advanced-modeling/src/generated/SyllabusSection.ts index ae049c1ad0..74f353ccd0 100644 --- a/examples/advanced-modeling/src/generated/SyllabusSection.ts +++ b/examples/advanced-modeling/src/generated/SyllabusSection.ts @@ -24,19 +24,14 @@ export const SyllabusSection = { label: "Heading", view: "text", htmlType: "text", - rules: { - required: "Heading is required", - maxLength: { value: 120, message: "Must be 120 characters or fewer" }, - }, + rules: { required: "Heading is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } }, }, summary: { name: "summary", label: "Summary", view: "text", htmlType: "text", - rules: { - maxLength: { value: 500, message: "Must be 500 characters or fewer" }, - }, + rules: { maxLength: { value: 500, message: "Must be 500 characters or fewer" } }, }, orderIndex: { name: "orderIndex", diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index 1c71c30927..774179acca 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -10,17 +10,17 @@ "generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561", "generated/python/subscriber_router.py": "16502ff815bf9ae29c7dba4700d0465d06058a9fd7ea8db5f98334d52d284851", "generated/ts/Subscriber.queries.ts": { - "hash": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562", + "hash": "63adba7ac4415f5e9962c4da100ffd97816524580a513e8350d14bc7a9f3507c", "generatedBy": "queries-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.routes.ts": { - "hash": "f76f592c98bd0ac5c07c4fe9c26cd88659793141e6620310dc725c7edcf68099", + "hash": "c26d2e8e146c5e310fabefa16d1a413109716544a3f817f20f4536cf09e2585e", "generatedBy": "routes-file", "sourceNode": "acme::Subscriber" }, "generated/ts/Subscriber.ts": { - "hash": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96", + "hash": "760b3d76d100d05f289070ce483f63ee022a3c6fc8d6356e691e4d17f0593734", "generatedBy": "entity-file", "sourceNode": "acme::Subscriber" }, diff --git a/examples/showcase/codegen/generators/barrel.ts b/examples/showcase/codegen/generators/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/examples/showcase/codegen/generators/barrel.ts +++ b/examples/showcase/codegen/generators/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/examples/showcase/codegen/generators/entity.ts b/examples/showcase/codegen/generators/entity.ts index 926da1c687..4931111a28 100644 --- a/examples/showcase/codegen/generators/entity.ts +++ b/examples/showcase/codegen/generators/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/examples/showcase/codegen/generators/queries.ts b/examples/showcase/codegen/generators/queries.ts index 8d03e08142..44617b4c61 100644 --- a/examples/showcase/codegen/generators/queries.ts +++ b/examples/showcase/codegen/generators/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index 16837743da..3117986622 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index e687d1acdb..026d00f5be 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/examples/showcase/codegen/templates/routes-index.ts b/examples/showcase/codegen/templates/routes-index.ts index e9969b576f..2f0608864b 100644 --- a/examples/showcase/codegen/templates/routes-index.ts +++ b/examples/showcase/codegen/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/examples/showcase/codegen/templates/view-decl.ts b/examples/showcase/codegen/templates/view-decl.ts index 9770bc091d..3dd02b2329 100644 --- a/examples/showcase/codegen/templates/view-decl.ts +++ b/examples/showcase/codegen/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/examples/showcase/generated/ts/Subscriber.queries.ts b/examples/showcase/generated/ts/Subscriber.queries.ts index caa8047243..93325d905a 100644 --- a/examples/showcase/generated/ts/Subscriber.queries.ts +++ b/examples/showcase/generated/ts/Subscriber.queries.ts @@ -5,11 +5,7 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; import { type Subscriber, @@ -19,21 +15,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -43,15 +29,9 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } export async function insertPreservingSubscriber( @@ -59,39 +39,22 @@ export async function insertPreservingSubscriber( data: z.input, ): Promise { const validated = SubscriberInsertPreservingSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/examples/showcase/generated/ts/Subscriber.routes.ts b/examples/showcase/generated/ts/Subscriber.routes.ts index efd2cb12ee..c4b84b3775 100644 --- a/examples/showcase/generated/ts/Subscriber.routes.ts +++ b/examples/showcase/generated/ts/Subscriber.routes.ts @@ -35,21 +35,18 @@ import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index"; * routesFile({ expose: ["list", "get"] }) rather than mounting them open. */ export async function subscriberRoutes(fastify: FastifyInstance) { - await fastify.register( - async (instance) => { - mountCrudRoutes({ - fastify: instance, - path: Subscriber.$path, - db, - table: subscribers, - insertSchema: SubscriberInsertSchema, - updateSchema: SubscriberUpdateSchema, - filterAllowlist: SubscriberFilterAllowlist, - sortAllowlist: SubscriberSortAllowlist, - dialect: "sqlite", - knownFields: ["id", "email", "name", "status", "createdAt"], - }); - }, - { prefix: "/api" }, - ); + await fastify.register(async (instance) => { + mountCrudRoutes({ + fastify: instance, + path: Subscriber.$path, + db, + table: subscribers, + insertSchema: SubscriberInsertSchema, + updateSchema: SubscriberUpdateSchema, + filterAllowlist: SubscriberFilterAllowlist, + sortAllowlist: SubscriberSortAllowlist, + dialect: "sqlite", + knownFields: ["id", "email", "name", "status", "createdAt"], + }); + }, { prefix: "/api" }); } diff --git a/examples/showcase/generated/ts/Subscriber.ts b/examples/showcase/generated/ts/Subscriber.ts index 68907c6ce7..61079d18dc 100644 --- a/examples/showcase/generated/ts/Subscriber.ts +++ b/examples/showcase/generated/ts/Subscriber.ts @@ -5,24 +5,13 @@ import { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm"; import { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, - (table) => [ - check( - "subscribers_status_chk", - sql`status IN ('active', 'paused', 'cancelled')`, - ), - ], -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export type SubscriberUpdate = Partial; @@ -35,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -47,19 +34,14 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .optional() - .transform(() => new Date().toISOString()), + createdAt: z.string().optional().transform(() => new Date().toISOString()), }); export const SubscriberUpdateSchema = z.object({ @@ -84,20 +66,14 @@ export const SubscriberInsertPreservingSchema = z.object({ email: z.string().min(1).max(320), name: z.string().optional(), status: z.enum(["active", "paused", "cancelled"]), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */ -export type SubscriberCreatePreserving = z.input< - typeof SubscriberInsertPreservingSchema ->; +export type SubscriberCreatePreserving = z.input; /** * Metadata constants for Subscriber. * @@ -130,10 +106,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 320, message: "Must be 320 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } }, }, name: { name: "name", label: "Name", view: "text", htmlType: "text" }, status: { @@ -143,12 +116,7 @@ export const Subscriber = { rules: { required: "Status is required" }, options: ["active", "paused", "cancelled"] as const, }, - createdAt: { - name: "createdAt", - label: "Created At", - view: "date", - htmlType: "datetime-local", - }, + createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" }, } as const; import type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist"; diff --git a/examples/showcase/inline/deep-currency.txt b/examples/showcase/inline/deep-currency.txt index 43a89436d5..c05418fd13 100644 --- a/examples/showcase/inline/deep-currency.txt +++ b/examples/showcase/inline/deep-currency.txt @@ -1,7 +1 @@ - priceCents: { - name: "priceCents", - label: "Price Cents", - view: "currency", - currency: "USD", - locale: "en-US", - }, + priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" }, diff --git a/examples/showcase/inline/ts-entity.txt b/examples/showcase/inline/ts-entity.txt index 4747cfe1d0..e43fc0a083 100644 --- a/examples/showcase/inline/ts-entity.txt +++ b/examples/showcase/inline/ts-entity.txt @@ -1,16 +1,11 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. -export const subscribers = sqliteTable( - "subscribers", - { - id: integer("id").primaryKey({ autoIncrement: true }), - email: text("email").notNull(), - name: text("name"), - status: text("status", { - enum: ["active", "paused", "cancelled"] as const, - }).notNull(), - createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), - }, -); +export const subscribers = sqliteTable("subscribers", { + id: integer("id").primaryKey({ autoIncrement: true }), + email: text("email").notNull(), + name: text("name"), + status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(), + createdAt: text("created_at").$defaultFn(() => new Date().toISOString()), +}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; export const SubscriberInsertSchema = z.object({ diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index de8940334c..1ba85b43c7 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -20,9 +20,9 @@ }, "ts-entity": { "lang": "ts", - "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n…\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable(\n "subscribers",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", {\n enum: ["active", "paused", "cancelled"] as const,\n }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n },\n (table) => [\n check(\n "subscribers_status_chk",\n sql`status IN ('active', 'paused', 'cancelled')`,\n ),\n ],\n);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m =\n /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/.exec(\n v,\n );\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t)\n ? v\n : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .optional()\n .transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z\n .string()\n .regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n )\n .transform(utcIsoTimestamp)\n .optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<\n typeof SubscriberInsertPreservingSchema\n>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: {\n name: "createdAt",\n label: "Created At",\n view: "date",\n htmlType: "datetime-local",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", - "lineCount": 165 + "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\n…\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n…\n});\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Subscriber (Subscriber)\n// Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { check, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";\nimport { z } from "zod";\n\nexport const subscribers = sqliteTable("subscribers", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n email: text("email").notNull(),\n name: text("name"),\n status: text("status", { enum: ["active", "paused", "cancelled"] as const }).notNull(),\n createdAt: text("created_at").$defaultFn(() => new Date().toISOString()),\n}, (table) => [check("subscribers_status_chk", sql`status IN ('active', 'paused', 'cancelled')`)]);\nexport type Subscriber = InferSelectModel<typeof subscribers>;\nexport type SubscriberInsert = InferInsertModel<typeof subscribers>;\nexport type SubscriberUpdate = Partial<SubscriberInsert>;\nexport type SubscriberStatus = "active" | "paused" | "cancelled";\nexport const SubscriberStatusEnum = z.enum(["active", "paused", "cancelled"]);\n/** A field.timestamp instant in UTC (`YYYY-MM-DDTHH:MM:SS[.fff]Z`): a value already spelled so is kept\n * as sent, an offset is applied, a zoneless value is UTC and a date alone is midnight UTC.\n * SQLite/D1 compare timestamps as text, so instants are stored in UTC. Generated. */\nfunction utcIsoTimestamp(v: string): string {\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$/.test(v)) {\n return v;\n }\n const m = /^(\\d{4}-\\d{2}-\\d{2})(?:[Tt ](\\d{2}:\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?(?:([Zz])|([+-]\\d{2}):?(\\d{2})?)?)?$/\n .exec(v);\n if (m === null) {\n return v;\n }\n const t = Date.parse(\n `${m[1]}T${m[2] ?? "00:00"}:${m[3] ?? "00"}.${(m[4] ?? "").slice(0, 3).padEnd(3, "0")}${\n m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}`\n }`,\n );\n return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\\.?0+Z$/, "Z");\n}\n\nexport const SubscriberInsertSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().optional().transform(() => new Date().toISOString()),\n});\n\nexport const SubscriberUpdateSchema = z.object({\n email: z.string().min(1).max(320).optional(),\n name: z.string().optional().nullable(),\n status: z.enum(["active", "paused", "cancelled"]).optional(),\n});\n\n/** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createSubscriber` call site;\n * the schema still validates at runtime. */\nexport type SubscriberCreate = z.input<typeof SubscriberInsertSchema>;\n\n/** Typed patch shape for Subscriber: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateSubscriber` call site. */\nexport type SubscriberPatch = z.input<typeof SubscriberUpdateSchema>;\n\n/** Insert-shape for import / restore / replication of Subscriber: identical to\n * SubscriberInsertSchema, but the @autoSet timestamp columns are written VERBATIM\n * (no create-time now() stamp) so the caller's original values are preserved. */\nexport const SubscriberInsertPreservingSchema = z.object({\n email: z.string().min(1).max(320),\n name: z.string().optional(),\n status: z.enum(["active", "paused", "cancelled"]),\n createdAt: z.string().regex(\n /^(?:\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8]))|(?:\\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:[Zz]|[+-](?:[01]\\d|2[0-3])(?::?[0-5]\\d)?)?)?$/,\n "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])",\n ).transform(utcIsoTimestamp).optional(),\n});\n\n/** Typed input of `insertPreservingSubscriber` — SubscriberInsertPreservingSchema's pre-transform shape. */\nexport type SubscriberCreatePreserving = z.input<typeof SubscriberInsertPreservingSchema>;\n/**\n * Metadata constants for Subscriber.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Subscriber = {\n $entity: "Subscriber",\n $table: "subscribers",\n $path: "/subscribers",\n id: { name: "id", label: "Id", view: "number", htmlType: "number" },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: { required: "Email is required", maxLength: { value: 320, message: "Must be 320 characters or fewer" } },\n },\n name: { name: "name", label: "Name", view: "text", htmlType: "text" },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n rules: { required: "Status is required" },\n options: ["active", "paused", "cancelled"] as const,\n },\n createdAt: { name: "createdAt", label: "Created At", view: "date", htmlType: "datetime-local" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const SubscriberSortAllowlist = {} as const satisfies SortAllowlist;\nexport type SubscriberFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: SubscriberFilter[];\n and?: SubscriberFilter[];\n};\n", + "lineCount": 133 }, "python-model": { "lang": "python", @@ -87,20 +87,20 @@ "deep-validators": { "lang": "ts", "inline": "…\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z\n .string()\n .min(1)\n .max(320)\n .regex(new RegExp("^(?:[^@]+@[^@]+)$"))\n .optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Name is required",\n maxLength: { value: 120, message: "Must be 120 characters or fewer" },\n },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", - "lineCount": 113 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Author (Author)\n// Extend in your own module (e.g. Author.extra.ts) — nothing imports it for you.\nimport type { InferInsertModel, InferSelectModel } from "drizzle-orm";\nimport { pgTable, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\nexport const authors = pgTable("authors", {\n id: uuid("id").primaryKey().defaultRandom(),\n name: varchar("name", { length: 120 }).notNull(),\n email: varchar("email", { length: 320 }).notNull(),\n bio: varchar("bio", { length: 2000 }),\n});\nexport type Author = InferSelectModel<typeof authors>;\nexport type AuthorInsert = InferInsertModel<typeof authors>;\nexport type AuthorUpdate = Partial<AuthorInsert>;\nexport const AuthorInsertSchema = z.object({\n name: z.string().min(1).max(120),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")),\n bio: z.string().max(500).optional(),\n});\n\nexport const AuthorUpdateSchema = z.object({\n name: z.string().min(1).max(120).optional(),\n email: z.string().min(1).max(320).regex(new RegExp("^(?:[^@]+@[^@]+)$")).optional(),\n bio: z.string().max(500).optional().nullable(),\n});\n\n/** Typed create shape for Author: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createAuthor` call site;\n * the schema still validates at runtime. */\nexport type AuthorCreate = z.input<typeof AuthorInsertSchema>;\n\n/** Typed patch shape for Author: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateAuthor` call site. */\nexport type AuthorPatch = z.input<typeof AuthorUpdateSchema>;\n/**\n * Metadata constants for Author.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Author, AuthorInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Author = {\n $entity: "Author",\n $table: "authors",\n $path: "/authors",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n name: {\n name: "name",\n label: "Name",\n view: "text",\n htmlType: "text",\n rules: { required: "Name is required", maxLength: { value: 120, message: "Must be 120 characters or fewer" } },\n },\n email: {\n name: "email",\n label: "Email",\n view: "text",\n htmlType: "text",\n rules: {\n pattern: { value: /[^@]+@[^@]+/, message: "Invalid format" },\n required: "Email is required",\n maxLength: { value: 320, message: "Must be 320 characters or fewer" },\n },\n },\n bio: {\n name: "bio",\n label: "Bio",\n view: "text",\n htmlType: "text",\n rules: {\n minLength: { value: 0, message: "Must be at least 0 characters" },\n maxLength: { value: 500, message: "Must be 500 characters or fewer" },\n },\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const AuthorSortAllowlist = {} as const satisfies SortAllowlist;\nexport type AuthorFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: AuthorFilter[];\n and?: AuthorFilter[];\n};\n", + "lineCount": 105 }, "deep-currency": { "lang": "ts", - "inline": "…\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport {\n type AnyPgColumn,\n bigint,\n check,\n jsonb,\n pgTable,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport {\n type InstructorProfile,\n InstructorProfileInsertSchema,\n} from "./InstructorProfile";\nimport {\n type SyllabusSection,\n SyllabusSectionInsertSchema,\n} from "./SyllabusSection";\n\nexport const programs = pgTable(\n "programs",\n {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", {\n enum: ["draft", "published", "archived"] as const,\n }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id")\n .notNull()\n .references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n },\n (table) => [\n check(\n "programs_status_chk",\n sql`status IN ('draft', 'published', 'archived')`,\n ),\n ],\n);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z\n .string()\n .regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n )\n .optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: {\n required: "Title is required",\n maxLength: { value: 200, message: "Must be 200 characters or fewer" },\n },\n },\n status: {\n name: "status",\n label: "Status",\n view: "dropdown",\n options: ["draft", "published", "archived"] as const,\n },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: {\n maxLength: { value: 2000, message: "Must be 2000 characters or fewer" },\n },\n },\n priceCents: {\n name: "priceCents",\n label: "Price Cents",\n view: "currency",\n currency: "USD",\n locale: "en-US",\n },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: {\n maxLength: { value: 80, message: "Must be 80 characters or fewer" },\n },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: {\n name: "syllabus",\n label: "Syllabus",\n view: "text",\n htmlType: "text",\n },\n instructorProfile: {\n name: "instructorProfile",\n label: "Instructor Profile",\n view: "text",\n htmlType: "text",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", - "lineCount": 194 + "inline": "…\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n…", + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: Program (Program)\n// Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you.\nimport { type InferInsertModel, type InferSelectModel, sql } from "drizzle-orm";\nimport { type AnyPgColumn, bigint, check, jsonb, pgTable, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\nimport { authors } from "./Author";\nimport { type InstructorProfile, InstructorProfileInsertSchema } from "./InstructorProfile";\nimport { type SyllabusSection, SyllabusSectionInsertSchema } from "./SyllabusSection";\n\nexport const programs = pgTable("programs", {\n id: uuid("id").primaryKey().defaultRandom(),\n title: varchar("title", { length: 200 }).notNull(),\n status: text("status", { enum: ["draft", "published", "archived"] as const }),\n summary: varchar("summary", { length: 2000 }),\n priceCents: bigint("price_cents", { mode: "number" }),\n coverKey: varchar("cover_key", { length: 80 }),\n authorId: uuid("author_id").notNull().references((): AnyPgColumn => authors.id),\n syllabus: jsonb("syllabus").$type<SyllabusSection[]>(),\n instructorProfile: jsonb("instructor_profile").$type<InstructorProfile>(),\n}, (table) => [check("programs_status_chk", sql`status IN ('draft', 'published', 'archived')`)]);\nexport type Program = InferSelectModel<typeof programs>;\nexport type ProgramInsert = InferInsertModel<typeof programs>;\nexport type ProgramUpdate = Partial<ProgramInsert>;\nexport type ProgramStatus = "draft" | "published" | "archived";\nexport const ProgramStatusEnum = z.enum(["draft", "published", "archived"]);\nexport const ProgramInsertSchema = z.object({\n title: z.string().min(1).max(200),\n status: z.enum(["draft", "published", "archived"]).optional(),\n summary: z.string().max(2000).optional(),\n priceCents: z.number().int().optional(),\n coverKey: z.string().max(80).optional(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ),\n syllabus: z.array(SyllabusSectionInsertSchema).optional(),\n instructorProfile: InstructorProfileInsertSchema.optional(),\n});\n\nexport const ProgramUpdateSchema = z.object({\n title: z.string().min(1).max(200).optional(),\n status: z.enum(["draft", "published", "archived"]).optional().nullable(),\n summary: z.string().max(2000).optional().nullable(),\n priceCents: z.number().int().optional().nullable(),\n coverKey: z.string().max(80).optional().nullable(),\n authorId: z.string().regex(\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n "Invalid uuid",\n ).optional(),\n syllabus: z.array(SyllabusSectionInsertSchema).optional().nullable(),\n instructorProfile: InstructorProfileInsertSchema.optional().nullable(),\n});\n\n/** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A\n * renamed/dropped/misspelt field is a compile error at every `createProgram` call site;\n * the schema still validates at runtime. */\nexport type ProgramCreate = z.input<typeof ProgramInsertSchema>;\n\n/** Typed patch shape for Program: every settable field, optional (FR-035 PATCH). A\n * renamed/dropped field is a compile error at every `updateProgram` call site. */\nexport type ProgramPatch = z.input<typeof ProgramUpdateSchema>;\n/**\n * Metadata constants for Program.\n *\n * Use these instead of magic strings so TS catches typos and refactors stay\n * coherent. Each non-dollar-prefixed key is a per-field object carrying\n * name, label, view, an htmlType where the field's view maps to one, and the\n * RHF-shaped validation rules derived from the field's validator children.\n *\n * placeholder and helpText are NOT emitted — no provider registers an attribute\n * for them, so nothing here could derive one. (htmlType is emitted, but derived\n * from the view subtype; the @htmlType override was removed for the same reason.)\n * useEntityForm still honours placeholder if you add it: this file is generated,\n * hand edits inside it survive regeneration through the three-way merge, and the\n * consumers read this const rather than the metadata. That is the intended way\n * to set it.\n *\n * Typical usage with the metaobjects React form helper:\n *\n * import { useEntityForm } from '@metaobjectsdev/react';\n * const form = useEntityForm(Program, ProgramInsertSchema);\n * <input {...form.input.id} />\n */\nexport const Program = {\n $entity: "Program",\n $table: "programs",\n $path: "/programs",\n id: { name: "id", label: "Id", view: "text", htmlType: "text" },\n title: {\n name: "title",\n label: "Title",\n view: "text",\n htmlType: "text",\n rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } },\n },\n status: { name: "status", label: "Status", view: "dropdown", options: ["draft", "published", "archived"] as const },\n summary: {\n name: "summary",\n label: "Summary",\n view: "textarea",\n rules: { maxLength: { value: 2000, message: "Must be 2000 characters or fewer" } },\n },\n priceCents: { name: "priceCents", label: "Price Cents", view: "currency", currency: "USD", locale: "en-US" },\n coverKey: {\n name: "coverKey",\n label: "Cover Key",\n view: "image",\n rules: { maxLength: { value: 80, message: "Must be 80 characters or fewer" } },\n },\n authorId: {\n name: "authorId",\n label: "Author Id",\n view: "text",\n htmlType: "text",\n rules: { required: "Author Id is required" },\n },\n syllabus: { name: "syllabus", label: "Syllabus", view: "text", htmlType: "text" },\n instructorProfile: { name: "instructorProfile", label: "Instructor Profile", view: "text", htmlType: "text" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramFilter[];\n and?: ProgramFilter[];\n};\n", + "lineCount": 133 }, "deep-projection": { "lang": "ts", "inline": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n…\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\n…", - "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport {\n bigint,\n boolean,\n pgView,\n text,\n uuid,\n varchar,\n} from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: {\n name: "authorName",\n label: "Author Name",\n view: "text",\n dbCol: "author_name",\n },\n lessonCount: {\n name: "lessonCount",\n label: "Lesson Count",\n view: "number",\n dbCol: "lesson_count",\n },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: {\n name: "hasCoverArt",\n label: "Has Cover Art",\n view: "checkbox",\n dbCol: "has_cover_art",\n },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist =\n {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", - "lineCount": 79 + "full": "// @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts.\n// Source metadata: ProgramSummary (ProgramSummary)\nimport { bigint, boolean, pgView, text, uuid, varchar } from "drizzle-orm/pg-core";\nimport { z } from "zod";\n\n// View declaration — Drizzle uses this for typed SELECT queries.\n// The SQL view is created/managed by migrate-ts; .existing() tells Drizzle\n// not to attempt DDL for this declaration.\nexport const programSummaryView = pgView("v_program_summary", {\n id: uuid("id").notNull(),\n title: varchar("title", { length: 200 }).notNull(),\n authorName: text("author_name"),\n lessonCount: bigint("lesson_count", { mode: "number" }),\n completedRevenueCents: bigint("completed_revenue_cents", { mode: "number" }),\n hasCoverArt: boolean("has_cover_art"),\n}).existing();\nexport const ProgramSummarySchema = z.object({\n id: z.string(),\n title: z.string(),\n authorName: z.string().nullable(),\n lessonCount: z.number().int().nullable(),\n completedRevenueCents: z.number().int().nullable(),\n hasCoverArt: z.boolean().nullable(),\n});\nexport type ProgramSummary = z.infer<typeof ProgramSummarySchema>;\nexport const ProgramSummary = {\n $entity: "ProgramSummary",\n $view: "v_program_summary",\n $path: "/program_summaries",\n id: { name: "id", label: "Id", view: "text", dbCol: "id" },\n title: { name: "title", label: "Title", view: "text", dbCol: "title" },\n authorName: { name: "authorName", label: "Author Name", view: "text", dbCol: "author_name" },\n lessonCount: { name: "lessonCount", label: "Lesson Count", view: "number", dbCol: "lesson_count" },\n completedRevenueCents: {\n name: "completedRevenueCents",\n label: "Completed Revenue Cents",\n view: "currency",\n dbCol: "completed_revenue_cents",\n currency: "USD",\n locale: "en-US",\n },\n hasCoverArt: { name: "hasCoverArt", label: "Has Cover Art", view: "checkbox", dbCol: "has_cover_art" },\n} as const;\nimport type { FilterAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummaryFilterAllowlist = {} as const satisfies FilterAllowlist;\nimport type { SortAllowlist } from "../../codegen/runtime/drizzle-fastify/filter-allowlist";\n\nexport const ProgramSummarySortAllowlist = {} as const satisfies SortAllowlist;\nexport type ProgramSummaryFilter = {\n limit?: number;\n offset?: number;\n sort?: string;\n or?: ProgramSummaryFilter[];\n and?: ProgramSummaryFilter[];\n};\n", + "lineCount": 56 } } } diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md index 588e061158..92401736a4 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md @@ -48,7 +48,7 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`, and `formatTs` for TypeScript output. The config's `apiPrefix` is +`pluralize`, and `formatTs` (a no-op kept so an owned copy still loads). The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. @@ -59,6 +59,11 @@ npm install --save-dev @metaobjectsdev/cli @metaobjectsdev/codegen-ts npm install @metaobjectsdev/metadata @metaobjectsdev/runtime-ts ``` +`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`, so npm does not install +them with the CLI. Install them when a generator you take writes code that imports them. +`meta gen --list --format json` gives each generator's `install.dev` and `install.runtime`, and +`meta eject ...` prints the consolidated install set. + For the React + TanStack codegen packages, also: ```bash diff --git a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts index 78746992c5..1dee1424a1 100644 --- a/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts +++ b/fixtures/conformance/routes-file-hono-basic/expected/Author.routes.hono.ts @@ -30,11 +30,7 @@ import type { Hono } from "hono"; * mount. Hand-write those verbs and narrow this file with * routesFileHono({ expose: ["list", "get"] }) rather than mounting them open. */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables -export function registerAuthorRoutes( - app: Hono, - deps: { db: unknown }, -): void { +export function registerAuthorRoutes(app: Hono, deps: { db: unknown }): void { mountCrudRoutes({ app, path: Author.$path, diff --git a/fixtures/contract-conformance/README.md b/fixtures/contract-conformance/README.md index e86c11df10..969958122f 100644 --- a/fixtures/contract-conformance/README.md +++ b/fixtures/contract-conformance/README.md @@ -11,7 +11,7 @@ Each case is a directory. corpus model, because that is the surface every port's routes are held to. - `case.json` keys: `meta` (repository-relative), `wire` (the setting, as in `.metaobjects/config.json`; a case on an api-contract model pins what that corpus pins, because the - integration suite holds that corpus's answers to this document), `strictExclude` (objects the strict profile leaves out, because the + integration suite holds that corpus's answers to this document), `api` (the `api` block of the config: `pagination`, `unknownFields`), `strictExclude` (objects the strict profile leaves out, because the strict subset cannot state them) and `reportExport` (the project wires `report-export`). - `expected/`: the exact tree the emitters write: the canonical schemas, the strict schemas and `openapi.json`. Or `expected-error.txt`: the exact refusal. @@ -30,6 +30,8 @@ document for that corpus. | `all-fields` | Every wire type, every constraint, a value object, a map, a recursive value object, a credential, and the write-mode fields. | | `all-fields-wire-string-emit` | `all-fields` under `wire: { decimals: "string", nullMembers: "emit" }`. | | `all-fields-wire-string-omit` | `all-fields` under `wire: { decimals: "string", nullMembers: "omit" }`. | +| `api-settings` | The `blog` model under `api.pagination`: the list's `limit` has a default and a maximum. | +| `api-settings-drop` | The `blog` model under `api.unknownFields: drop`: a write body says undeclared keys are dropped. | | `blog` | The api-contract corpus's root model: CRUD, filter, sort and paging. | | `decimal` | The api-contract `decimal/` model. | | `error-name-collision` | Refused: a real object takes the name of another object's create shape. | diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json index abb6483b2d..98fbb6c457 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2269,6 +2275,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json index 0df2287e3d..d5e6d19590 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2261,6 +2267,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/all-fields/expected/openapi.json b/fixtures/contract-conformance/all-fields/expected/openapi.json index 5a0735ad62..6db67e917e 100644 --- a/fixtures/contract-conformance/all-fields/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields/expected/openapi.json @@ -1055,6 +1055,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1075,7 +1076,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1144,6 +1145,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1164,7 +1166,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1202,6 +1204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1222,7 +1225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1357,6 +1360,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1377,7 +1381,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1446,6 +1450,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1466,7 +1471,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1504,6 +1509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1524,7 +1530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2266,6 +2272,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/api-settings-drop/case.json b/fixtures/contract-conformance/api-settings-drop/case.json new file mode 100644 index 0000000000..8b712ad580 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/case.json @@ -0,0 +1 @@ +{ "meta": "fixtures/api-contract-conformance/meta.json", "wire": {"decimals": "string", "nullMembers": "omit", "durations": "iso"}, "api": { "unknownFields": "drop" } } diff --git a/fixtures/contract-conformance/api-settings-drop/expected/openapi.json b/fixtures/contract-conformance/api-settings-drop/expected/openapi.json new file mode 100644 index 0000000000..7c50b01f62 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/openapi.json @@ -0,0 +1,773 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "api-settings-drop", + "version": "1.0.0" + }, + "paths": { + "/api/authors": { + "get": { + "operationId": "listAuthor", + "tags": [ + "Author" + ], + "parameters": [ + { + "name": "filter[id]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][eq]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][ne]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[id][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[name]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[name][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[bio]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[bio][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[createdAt]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][eq]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][ne]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[createdAt][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "sort", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "id", + "id:asc", + "id:desc", + "name", + "name:asc", + "name:desc", + "createdAt", + "createdAt:asc", + "createdAt:desc" + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "withCount", + "in": "query", + "description": "Answer { rows, total } instead of the array.", + "schema": { + "type": "integer", + "enum": [ + 1 + ] + } + } + ], + "responses": { + "200": { + "description": "The rows.", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/AuthorList" + }, + { + "$ref": "#/components/schemas/AuthorPage" + } + ] + } + } + } + }, + "400": { + "description": "The request was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "post": { + "operationId": "createAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorCreate" + } + } + } + }, + "responses": { + "201": { + "description": "The new row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/authors/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "get": { + "operationId": "getAuthor", + "tags": [ + "Author" + ], + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "patch": { + "operationId": "updateAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "put": { + "operationId": "putAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is dropped, and the rest of the body is written.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body that fails validation answers error \"validation\" with an issue for every problem, not the first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAuthor", + "tags": [ + "Author" + ], + "responses": { + "204": { + "description": "Deleted." + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApiError": { + "title": "ApiError", + "description": "The error envelope. `error` is the stable code; `message` is free prose.", + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." + } + } + }, + "Author": { + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] + }, + "AuthorCreate": { + "title": "AuthorCreate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] + }, + "AuthorList": { + "title": "AuthorList", + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "AuthorPage": { + "title": "AuthorPage", + "type": "object", + "required": [ + "rows", + "total" + ], + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "total": { + "type": "integer" + } + } + }, + "AuthorUpdate": { + "title": "AuthorUpdate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } + } + } + } +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json new file mode 100644 index 0000000000..dd93120f2e --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.create.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.create.schema.json", + "title": "Author.create", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json new file mode 100644 index 0000000000..15e9f54982 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.schema.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.schema.json", + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json new file mode 100644 index 0000000000..58723ebbb6 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.strict.schema.json @@ -0,0 +1,35 @@ +{ + "title": "Author", + "type": "object", + "properties": { + "name": { + "description": "Minimum length: 1. Maximum length: 100.", + "type": "string" + }, + "bio": { + "description": "Maximum length: 1000.", + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "description": "An instant. A value with no offset is read as UTC. Pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$.", + "type": "string" + }, + "issuedCurrency": { + "description": "Maximum length: 3.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "bio", + "createdAt", + "issuedCurrency" + ], + "additionalProperties": false +} diff --git a/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json new file mode 100644 index 0000000000..3f3c050341 --- /dev/null +++ b/fixtures/contract-conformance/api-settings-drop/expected/schemas/acme/blog/Author.update.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.update.schema.json", + "title": "Author.update", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } +} diff --git a/fixtures/contract-conformance/api-settings/case.json b/fixtures/contract-conformance/api-settings/case.json new file mode 100644 index 0000000000..067383d2e1 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/case.json @@ -0,0 +1 @@ +{ "meta": "fixtures/api-contract-conformance/meta.json", "wire": {"decimals": "string", "nullMembers": "omit", "durations": "iso"}, "api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 } } } diff --git a/fixtures/contract-conformance/api-settings/expected/openapi.json b/fixtures/contract-conformance/api-settings/expected/openapi.json new file mode 100644 index 0000000000..6622ad8527 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/openapi.json @@ -0,0 +1,776 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "api-settings", + "version": "1.0.0" + }, + "paths": { + "/api/authors": { + "get": { + "operationId": "listAuthor", + "tags": [ + "Author" + ], + "parameters": [ + { + "name": "filter[id]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][eq]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][ne]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][gte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lt]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][lte]", + "in": "query", + "schema": { + "type": "integer", + "format": "int64" + } + }, + { + "name": "filter[id][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[id][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[name]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[name][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[name][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[bio]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][eq]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][ne]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[bio][like]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "filter[bio][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "filter[createdAt]", + "in": "query", + "description": "Sugar for the eq operator.", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][eq]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][ne]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + }, + { + "name": "filter[createdAt][in]", + "in": "query", + "schema": { + "type": "string", + "description": "Comma-separated values." + } + }, + { + "name": "filter[createdAt][isNull]", + "in": "query", + "schema": { + "type": "boolean" + } + }, + { + "name": "sort", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "id", + "id:asc", + "id:desc", + "name", + "name:asc", + "name:desc", + "createdAt", + "createdAt:asc", + "createdAt:desc" + ] + } + }, + { + "name": "limit", + "in": "query", + "description": "Rows per page. Absent, the server answers 50; above 1000 it answers 400 limit_too_large.", + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 1000, + "default": 50 + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "withCount", + "in": "query", + "description": "Answer { rows, total } instead of the array.", + "schema": { + "type": "integer", + "enum": [ + 1 + ] + } + } + ], + "responses": { + "200": { + "description": "The rows.", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/AuthorList" + }, + { + "$ref": "#/components/schemas/AuthorPage" + } + ] + } + } + } + }, + "400": { + "description": "The request was refused.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "post": { + "operationId": "createAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorCreate" + } + } + } + }, + "responses": { + "201": { + "description": "The new row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/authors/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "format": "int64" + } + } + ], + "get": { + "operationId": "getAuthor", + "tags": [ + "Author" + ], + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "patch": { + "operationId": "updateAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "put": { + "operationId": "putAuthor", + "tags": [ + "Author" + ], + "requestBody": { + "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthorUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "The row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Author" + } + } + } + }, + "400": { + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + }, + "delete": { + "operationId": "deleteAuthor", + "tags": [ + "Author" + ], + "responses": { + "204": { + "description": "Deleted." + }, + "404": { + "description": "No such row.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "409": { + "description": "A constraint refused the write.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApiError": { + "title": "ApiError", + "description": "The error envelope. `error` is the stable code; `message` is free prose.", + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "field": { + "type": "string", + "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." + } + } + }, + "Author": { + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] + }, + "AuthorCreate": { + "title": "AuthorCreate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] + }, + "AuthorList": { + "title": "AuthorList", + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "AuthorPage": { + "title": "AuthorPage", + "type": "object", + "required": [ + "rows", + "total" + ], + "properties": { + "rows": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Author" + } + }, + "total": { + "type": "integer" + } + } + }, + "AuthorUpdate": { + "title": "AuthorUpdate", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } + } + } + } +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json new file mode 100644 index 0000000000..dd93120f2e --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.create.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.create.schema.json", + "title": "Author.create", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": "string", + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + }, + "issuedCurrency": { + "type": "string", + "maxLength": 3 + } + }, + "required": [ + "name", + "createdAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json new file mode 100644 index 0000000000..15e9f54982 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.schema.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.schema.json", + "title": "Author", + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "issuedCurrency": { + "type": [ + "string", + "null" + ], + "maxLength": 3 + }, + "autoCreatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "autoUpdatedAt": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "bio", + "createdAt", + "issuedCurrency", + "autoCreatedAt", + "autoUpdatedAt" + ] +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json new file mode 100644 index 0000000000..58723ebbb6 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.strict.schema.json @@ -0,0 +1,35 @@ +{ + "title": "Author", + "type": "object", + "properties": { + "name": { + "description": "Minimum length: 1. Maximum length: 100.", + "type": "string" + }, + "bio": { + "description": "Maximum length: 1000.", + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "description": "An instant. A value with no offset is read as UTC. Pattern: ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$.", + "type": "string" + }, + "issuedCurrency": { + "description": "Maximum length: 3.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "bio", + "createdAt", + "issuedCurrency" + ], + "additionalProperties": false +} diff --git a/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json new file mode 100644 index 0000000000..3f3c050341 --- /dev/null +++ b/fixtures/contract-conformance/api-settings/expected/schemas/acme/blog/Author.update.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "schemas/acme/blog/Author.update.schema.json", + "title": "Author.update", + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 1000 + }, + "createdAt": { + "type": "string", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$", + "description": "An instant. A value with no offset is read as UTC." + } + } +} diff --git a/fixtures/contract-conformance/blog/expected/openapi.json b/fixtures/contract-conformance/blog/expected/openapi.json index b9840d0b52..2ecab7e4f0 100644 --- a/fixtures/contract-conformance/blog/expected/openapi.json +++ b/fixtures/contract-conformance/blog/expected/openapi.json @@ -334,6 +334,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -354,7 +355,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -423,6 +424,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -443,7 +445,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -481,6 +483,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -501,7 +504,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -584,6 +587,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/decimal/expected/openapi.json b/fixtures/contract-conformance/decimal/expected/openapi.json index a742bb695a..d3383a8c53 100644 --- a/fixtures/contract-conformance/decimal/expected/openapi.json +++ b/fixtures/contract-conformance/decimal/expected/openapi.json @@ -283,6 +283,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -303,7 +304,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -372,6 +373,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -392,7 +394,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -430,6 +432,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -450,7 +453,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -519,6 +522,7 @@ "tags": [ "EntryTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[bucket]", @@ -1316,6 +1320,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1336,7 +1341,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1405,6 +1410,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1425,7 +1431,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1463,6 +1469,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1483,7 +1490,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1566,6 +1573,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/jsonb/expected/openapi.json b/fixtures/contract-conformance/jsonb/expected/openapi.json index 11ff07dcaa..4a8e9bc478 100644 --- a/fixtures/contract-conformance/jsonb/expected/openapi.json +++ b/fixtures/contract-conformance/jsonb/expected/openapi.json @@ -208,6 +208,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -228,7 +229,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -297,6 +298,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -317,7 +319,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -355,6 +357,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -375,7 +378,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -458,6 +461,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/m2m/expected/openapi.json b/fixtures/contract-conformance/m2m/expected/openapi.json index 813d6036ee..b8e1cfe858 100644 --- a/fixtures/contract-conformance/m2m/expected/openapi.json +++ b/fixtures/contract-conformance/m2m/expected/openapi.json @@ -586,6 +586,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -606,7 +607,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -675,6 +676,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -695,7 +697,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -733,6 +735,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -753,7 +756,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1128,6 +1131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1148,7 +1152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1217,6 +1221,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1237,7 +1242,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1275,6 +1280,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1295,7 +1301,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1532,6 +1538,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1552,7 +1559,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1621,6 +1628,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1641,7 +1649,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1679,6 +1687,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1699,7 +1708,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1834,6 +1843,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1854,7 +1864,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1923,6 +1933,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1943,7 +1954,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1981,6 +1992,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2001,7 +2013,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2136,6 +2148,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2156,7 +2169,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2225,6 +2238,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2245,7 +2259,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2283,6 +2297,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2303,7 +2318,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2438,6 +2453,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2458,7 +2474,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2527,6 +2543,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2547,7 +2564,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2585,6 +2602,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2605,7 +2623,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2740,6 +2758,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2760,7 +2779,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2829,6 +2848,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2849,7 +2869,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -2887,6 +2907,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2907,7 +2928,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3110,6 +3131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3130,7 +3152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3199,6 +3221,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3219,7 +3242,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3257,6 +3280,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3277,7 +3301,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3480,6 +3504,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3500,7 +3525,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3569,6 +3594,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3589,7 +3615,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3627,6 +3653,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3647,7 +3674,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3782,6 +3809,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3802,7 +3830,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3871,6 +3899,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3891,7 +3920,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3929,6 +3958,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3949,7 +3979,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4084,6 +4114,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4104,7 +4135,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4173,6 +4204,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4193,7 +4225,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4231,6 +4263,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4251,7 +4284,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4386,6 +4419,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4406,7 +4440,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4475,6 +4509,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4495,7 +4530,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4533,6 +4568,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4553,7 +4589,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4688,6 +4724,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4708,7 +4745,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4777,6 +4814,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4797,7 +4835,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4835,6 +4873,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4855,7 +4894,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5049,6 +5088,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/nullable-members/expected/openapi.json b/fixtures/contract-conformance/nullable-members/expected/openapi.json index fb552752b5..ff90896b05 100644 --- a/fixtures/contract-conformance/nullable-members/expected/openapi.json +++ b/fixtures/contract-conformance/nullable-members/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "SensorSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "limit", @@ -390,6 +394,7 @@ "tags": [ "SensorSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -434,6 +439,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/projection/expected/openapi.json b/fixtures/contract-conformance/projection/expected/openapi.json index fa22cc89b5..43c2b093b5 100644 --- a/fixtures/contract-conformance/projection/expected/openapi.json +++ b/fixtures/contract-conformance/projection/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "InvoiceLedger" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[number]", @@ -671,6 +675,7 @@ "tags": [ "InvoiceLedger" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -701,6 +706,7 @@ "tags": [ "InvoiceRegister" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[regNo]", @@ -909,6 +915,7 @@ "tags": [ "InvoiceRegister" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -939,6 +946,7 @@ "tags": [ "InvoiceStub" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[id]", @@ -1136,6 +1144,7 @@ "tags": [ "InvoiceSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[id]", @@ -1463,6 +1472,7 @@ "tags": [ "InvoiceSummary" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "responses": { "200": { "description": "The row.", @@ -1507,6 +1517,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/report/expected/openapi.json b/fixtures/contract-conformance/report/expected/openapi.json index ebd15ce842..28e9960f1d 100644 --- a/fixtures/contract-conformance/report/expected/openapi.json +++ b/fixtures/contract-conformance/report/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -313,6 +316,7 @@ "tags": [ "ExportCells" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[label]", @@ -673,6 +677,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -693,7 +698,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -762,6 +767,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -782,7 +788,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -820,6 +826,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -840,7 +847,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -975,6 +982,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -995,7 +1003,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1064,6 +1072,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1084,7 +1093,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1122,6 +1131,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1142,7 +1152,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1211,6 +1221,7 @@ "tags": [ "InvoiceCalendar" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[issuedOnDay]", @@ -1608,6 +1619,7 @@ "tags": [ "InvoiceDisputes" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[disputed]", @@ -1880,6 +1892,7 @@ "tags": [ "InvoiceStatusTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[status]", @@ -2264,6 +2277,7 @@ "tags": [ "InvoiceTotals" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[invoices]", @@ -2586,6 +2600,7 @@ "tags": [ "InvoicesByMonth" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[issuedOnMonth]", @@ -2974,6 +2989,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -2994,7 +3010,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3063,6 +3079,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3083,7 +3100,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3121,6 +3138,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -3141,7 +3159,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -3210,6 +3228,7 @@ "tags": [ "ProductRefunds" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productId]", @@ -3554,6 +3573,7 @@ "tags": [ "ProductRevenue" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productId]", @@ -4064,6 +4084,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4084,7 +4105,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4153,6 +4174,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4173,7 +4195,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4211,6 +4233,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4231,7 +4254,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4300,6 +4323,7 @@ "tags": [ "ReadingLog" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[seq]", @@ -4613,6 +4637,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4633,7 +4658,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4702,6 +4727,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4722,7 +4748,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4760,6 +4786,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -4780,7 +4807,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -4849,6 +4876,7 @@ "tags": [ "SalesByCategory" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[categoryName]", @@ -5293,6 +5321,7 @@ "tags": [ "SalesBySku" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[productSku]", @@ -5649,6 +5678,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5669,7 +5699,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5738,6 +5768,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5758,7 +5789,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5796,6 +5827,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -5816,7 +5848,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -5885,6 +5917,7 @@ "tags": [ "TicketsByTags" ], + "description": "Read-only: a write to this resource answers 405 {\"error\": \"method_not_allowed\"}.", "parameters": [ { "name": "filter[tickets]", @@ -6071,6 +6104,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/secret-fields/expected/openapi.json b/fixtures/contract-conformance/secret-fields/expected/openapi.json index 5be082d05d..a62c8ad8e1 100644 --- a/fixtures/contract-conformance/secret-fields/expected/openapi.json +++ b/fixtures/contract-conformance/secret-fields/expected/openapi.json @@ -208,6 +208,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -228,7 +229,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -297,6 +298,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -317,7 +319,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -355,6 +357,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -375,7 +378,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -543,6 +546,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } } diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json index 0c7c63df7b..05051958bc 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json @@ -184,6 +184,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -204,7 +205,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -273,6 +274,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -293,7 +295,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -331,6 +333,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -351,7 +354,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -486,6 +489,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -506,7 +510,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -575,6 +579,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -595,7 +600,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -633,6 +638,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -653,7 +659,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -736,6 +742,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/tph/expected/openapi.json b/fixtures/contract-conformance/tph/expected/openapi.json index f3f7c876ce..d09a4fd042 100644 --- a/fixtures/contract-conformance/tph/expected/openapi.json +++ b/fixtures/contract-conformance/tph/expected/openapi.json @@ -583,6 +583,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -603,7 +604,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -672,6 +673,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -692,7 +694,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -730,6 +732,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -750,7 +753,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1091,6 +1094,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1111,7 +1115,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1180,6 +1184,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1200,7 +1205,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1238,6 +1243,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1258,7 +1264,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1571,6 +1577,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1591,7 +1598,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1660,6 +1667,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1680,7 +1688,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1718,6 +1726,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -1738,7 +1747,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -1821,6 +1830,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/fixtures/contract-conformance/write-through/expected/openapi.json b/fixtures/contract-conformance/write-through/expected/openapi.json index 567483d952..1b28602b87 100644 --- a/fixtures/contract-conformance/write-through/expected/openapi.json +++ b/fixtures/contract-conformance/write-through/expected/openapi.json @@ -77,6 +77,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -97,7 +98,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -166,6 +167,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -186,7 +188,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -224,6 +226,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -244,7 +247,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -379,6 +382,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -399,7 +403,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -468,6 +472,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -488,7 +493,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -526,6 +531,7 @@ ], "requestBody": { "required": true, + "description": "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped.", "content": { "application/json": { "schema": { @@ -546,7 +552,7 @@ } }, "400": { - "description": "The request was refused.", + "description": "The request was refused. A body key the model does not declare answers error \"unknown_fields\" with the keys in fields, and nothing is written. Any other problem answers error \"validation\" with an issue for every problem.", "content": { "application/json": { "schema": { @@ -629,6 +635,52 @@ "field": { "type": "string", "description": "The rejected filter or sort field, on the four codes that name one." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The undeclared body keys, sorted, on unknown_fields." + }, + "issues": { + "type": "array", + "description": "Every problem with the body, on validation.", + "items": { + "type": "object", + "required": [ + "code", + "path", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "A Zod issue name. A client that does not know one treats it as custom." + }, + "path": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "description": "The location of the field in the body." + }, + "message": { + "type": "string" + } + } + } + }, + "maxLimit": { + "type": "integer", + "description": "The largest page the server serves, on limit_too_large." } } }, diff --git a/scripts/check-install-size.mjs b/scripts/check-install-size.mjs new file mode 100644 index 0000000000..cb3e286da6 --- /dev/null +++ b/scripts/check-install-size.mjs @@ -0,0 +1,207 @@ +#!/usr/bin/env node +// The install-size budget: what `npm install @metaobjectsdev/cli` puts on an adopter's disk, +// measured by installing it, and held to a number that only moves down. +// +// WHY A REAL INSTALL. `scripts/check-peer-ranges.ts` reads manifests, which catches a package +// that REQUIRES something unused. It cannot see what a dependency of a dependency drags in +// (libSQL pulls its own HTTP client and a polyfill for web streams; a native binary comes once per +// libc), and it cannot see a package that doubled in size. This installs the packed CLI the way +// an adopter's package manager does and counts the bytes. +// +// node scripts/check-install-size.mjs # check against the budget (the full CI lane) +// node scripts/check-install-size.mjs --update # lower the budget to what was measured +// +// THE RULES +// 1. The install must not exceed `budgetBytes`. +// 2. It must not sit more than `slackBytes` UNDER it. A saving that is not written down is a +// saving the next change can spend, so a smaller install fails until the budget is lowered +// with --update. That is the ratchet: the budget has no way to rise. +// 3. `budgetBytes` may not be higher than it is on `main`. Raising it to make a change pass +// is the one edit this file exists to refuse; raise it only with a ruling that says why. +// 4. None of the packages in FORBIDDEN is in the tree (a fresh-install test: the install-time +// guard in check-peer-ranges.ts reads manifests, this reads the result). +// +// The budget is for the platform it names (`platform`): native binaries differ by platform and +// by libc, so on another platform the check reports the number and passes. It needs the registry +// for third-party packages, which is why it runs in the full CI lane and not in `--only gates`. +// The packages under test are this checkout's, packed with `bun pm pack` (which writes `workspace:` +// ranges as versions), so nothing here depends on a release having been published. +// +// Build first (`bun run --filter '*' build`): a package is packed from its built `dist/`. + +import { execFileSync } from "node:child_process"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { enumerateWorkspacePackages } from "./publish-set.mjs"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const BUDGET_FILE = "scripts/install-size-budget.json"; +const BUDGET_PATH = join(ROOT, BUDGET_FILE); +const ENTRY = "@metaobjectsdev/cli"; +const SCOPE = "@metaobjectsdev/"; +const MB = 1024 * 1024; + +/** Packages that must not be installed by installing the CLI, and why. */ +const FORBIDDEN = { + "drizzle-orm": "only generated code imports it; codegen-ts lists it as an optional peer", + "@biomejs/biome": "generation runs no formatter; the CLI compares owned copies through the WebAssembly build", + "dprint-node": "seven native binaries; codegen-ts runs dprint as WebAssembly", + "ts-poet": "requires dprint-node on load; codegen-ts vendors the printer", + "@libsql/kysely-libsql": "an optional peer: a SQLite project declares it (`meta init` does), because it carries a native binary per platform and libc", + "libsql": "the native SQLite binding behind @libsql/kysely-libsql, installed only with it", +}; + +const update = process.argv.includes("--update"); + +function platformKey() { + return `${process.platform}-${process.arch}`; +} + +/** The workspace packages the CLI installs: it, and every `@metaobjectsdev/*` it requires, transitively. */ +function closureOf(entry, byName) { + const seen = new Set(); + const queue = [entry]; + while (queue.length > 0) { + const name = queue.pop(); + if (seen.has(name)) continue; + seen.add(name); + const pkg = byName.get(name); + if (pkg === undefined) continue; + const required = [ + ...Object.keys(pkg.dependencies ?? {}), + ...Object.keys(pkg.optionalDependencies ?? {}), + ...Object.keys(pkg.peerDependencies ?? {}).filter((d) => pkg.peerDependenciesMeta?.[d]?.optional !== true), + ]; + for (const dep of required) if (dep.startsWith(SCOPE)) queue.push(dep); + } + return [...seen].sort(); +} + +/** Bytes of every regular file under `dir`, what `du -sb` counts. */ +function bytesUnder(dir) { + let total = 0; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) total += bytesUnder(path); + else if (entry.isFile()) total += lstatSync(path).size; + } + return total; +} + +/** The top-level package directories of `node_modules`, scopes opened, largest first. */ +function breakdown(modules) { + const rows = []; + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === ".bin") continue; + const path = join(modules, entry.name); + if (entry.name.startsWith("@")) { + for (const inner of readdirSync(path, { withFileTypes: true })) { + if (inner.isDirectory()) rows.push({ name: `${entry.name}/${inner.name}`, bytes: bytesUnder(join(path, inner.name)) }); + } + } else { + rows.push({ name: entry.name, bytes: bytesUnder(path) }); + } + } + return rows.sort((a, b) => b.bytes - a.bytes); +} + +function installedNames(modules) { + const names = []; + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === ".bin") continue; + if (entry.name.startsWith("@")) { + for (const inner of readdirSync(join(modules, entry.name), { withFileTypes: true })) names.push(`${entry.name}/${inner.name}`); + } else names.push(entry.name); + } + return names; +} + +function mainBudget() { + try { + const text = execFileSync("git", ["show", `main:${BUDGET_FILE}`], { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + return JSON.parse(text).budgetBytes; + } catch { + return undefined; // no `main` here, or the file is new on this branch + } +} + +function measure() { + const packages = enumerateWorkspacePackages(ROOT).map(({ dir, pkg }) => ({ dir, pkg })); + const byName = new Map(packages.map(({ pkg }) => [pkg.name, pkg])); + const wanted = closureOf(ENTRY, byName); + const dirs = new Map(packages.map(({ dir, pkg }) => [pkg.name, dir])); + // Throwaway data goes to RAM when the machine has set it aside for that. + const scratch = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "mo-install-size-")); + try { + const tarballs = join(scratch, "tarballs"); + const project = join(scratch, "project"); + mkdirSync(tarballs); + mkdirSync(project); + for (const name of wanted) { + const dir = dirs.get(name); + if (dir === undefined) throw new Error(`${name} is required by ${ENTRY} but is not a workspace package`); + if (!existsSync(join(ROOT, dir, "dist"))) { + throw new Error(`${name} has no dist/: run \`bun run --filter '*' build\` first`); + } + execFileSync("bun", ["pm", "pack", "--destination", tarballs, "--quiet"], { cwd: join(ROOT, dir), stdio: ["ignore", "ignore", "inherit"] }); + } + writeFileSync(join(project, "package.json"), JSON.stringify({ name: "install-size", version: "1.0.0", private: true, type: "module" })); + const files = readdirSync(tarballs).map((f) => join(tarballs, f)); + execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund", "--no-progress", ...files], { cwd: project, stdio: ["ignore", "ignore", "inherit"] }); + const modules = join(project, "node_modules"); + return { bytes: bytesUnder(modules), rows: breakdown(modules), names: installedNames(modules), packed: wanted.length }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +function fail(message) { + console.error(`\n✖ ${message}\n`); + process.exit(1); +} + +const budget = JSON.parse(readFileSync(BUDGET_PATH, "utf8")); +const { bytes, rows, names, packed } = measure(); +const mb = (n) => (n / MB).toFixed(1); + +console.log(`install size: ${mb(bytes)} MB installing ${ENTRY} (${packed} workspace packages, ${names.length} top-level packages)`); +for (const row of rows.slice(0, 8)) console.log(` ${mb(row.bytes).padStart(6)} MB ${row.name}`); + +const forbidden = Object.keys(FORBIDDEN).filter((name) => names.includes(name)); +if (forbidden.length > 0) { + fail(`installing ${ENTRY} put packages in the tree that it must not:\n${forbidden.map((n) => ` ${n}: ${FORBIDDEN[n]}`).join("\n")}`); +} + +if (budget.platform !== platformKey()) { + console.log(`install-size budget: ${mb(budget.budgetBytes)} MB is for ${budget.platform}; this is ${platformKey()}, so the number above is reported and not checked`); + process.exit(0); +} + +const onMain = mainBudget(); +if (onMain !== undefined && budget.budgetBytes > onMain) { + fail(`the budget rose: ${BUDGET_FILE} says ${mb(budget.budgetBytes)} MB and main says ${mb(onMain)} MB. The budget only moves down.`); +} + +if (bytes > budget.budgetBytes) { + fail(`the install is ${mb(bytes - budget.budgetBytes)} MB over the budget (${mb(bytes)} MB, budget ${mb(budget.budgetBytes)} MB). Find what grew in the list above; the budget is not the thing to change.`); +} + +if (bytes < budget.budgetBytes - budget.slackBytes) { + if (!update) { + fail(`the install is ${mb(budget.budgetBytes - bytes)} MB under the budget (${mb(bytes)} MB, budget ${mb(budget.budgetBytes)} MB). Lower it, so the saving cannot be spent again: node scripts/check-install-size.mjs --update`); + } +} + +if (update) { + if (bytes >= budget.budgetBytes) { + console.log(`install-size budget: ${mb(budget.budgetBytes)} MB stays (measured ${mb(bytes)} MB; --update only lowers it)`); + } else { + writeFileSync(BUDGET_PATH, `${JSON.stringify({ ...budget, budgetBytes: bytes }, null, 2)}\n`); + console.log(`install-size budget: lowered from ${mb(budget.budgetBytes)} MB to ${mb(bytes)} MB`); + } + process.exit(0); +} + +console.log(`install-size budget: OK (${mb(bytes)} MB of ${mb(budget.budgetBytes)} MB)`); diff --git a/scripts/check-peer-ranges.test.ts b/scripts/check-peer-ranges.test.ts index e370a44eea..ab135f9d3b 100644 --- a/scripts/check-peer-ranges.test.ts +++ b/scripts/check-peer-ranges.test.ts @@ -42,9 +42,28 @@ describe("install-time guard — optionalDependencies are installed by default", ]); }); + test("drizzle-orm and zod are refused as dependencies and as required peers", () => { + const report = peerRangeReport(workspaceWith({ + dependencies: { zod: "^4.0.0" }, + peerDependencies: { "drizzle-orm": ">=0.38.0 <1.0.0" }, + })); + expect(report.installOnlyDeps).toEqual([ + expect.objectContaining({ dep: "zod", field: "dependencies" }), + expect.objectContaining({ dep: "drizzle-orm", field: "peerDependencies (required)" }), + ]); + }); + + test("drizzle-orm and zod as optional peers pass, which is how codegen-ts declares them", () => { + const report = peerRangeReport(workspaceWith({ + peerDependencies: { "drizzle-orm": ">=0.38.0 <1.0.0", zod: ">=3.23.0 <5.0.0" }, + peerDependenciesMeta: { "drizzle-orm": { optional: true }, zod: { optional: true } }, + })); + expect(report.installOnlyDeps).toEqual([]); + }); + test("a clean package passes: real dep, bounded peer counted", () => { const report = peerRangeReport(workspaceWith({ - dependencies: { "drizzle-orm": "^0.36.0" }, + dependencies: { kysely: "^0.27.0" }, peerDependencies: { react: "^18.0.0" }, })); expect(report.installOnlyDeps).toEqual([]); diff --git a/scripts/check-peer-ranges.ts b/scripts/check-peer-ranges.ts index cbc6800ad8..b2fbc45a82 100755 --- a/scripts/check-peer-ranges.ts +++ b/scripts/check-peer-ranges.ts @@ -33,17 +33,20 @@ * declaration lands it in every `@metaobjectsdev/cli` install: * * - the native Biome formatter (`@biomejs/biome`, which pulls a ~94 MB per-platform - * `@biomejs/cli-*` binary). Codegen formats through the WebAssembly build - * (`@biomejs/wasm-nodejs` + `@biomejs/js-api`, see `codegen-ts/src/format.ts`). + * `@biomejs/cli-*` binary). Generation runs no formatter; the CLI's owned-copy + * comparison uses the WebAssembly build (`@biomejs/wasm-nodejs` + `@biomejs/js-api`). * - `dprint-node` (~25 MB: all seven platform binaries in one package) and `ts-poet`, * which `require`s it on load. codegen-ts vendors the printer (`codegen-ts/src/poet.ts`) * and runs dprint as WebAssembly (`@dprint/typescript`). + * - `drizzle-orm` and `zod`, which only the code `meta gen` writes imports. `codegen-ts` lists + * them as optional peers, and `meta eject` prints the install set for the generators taken. + * `@metaobjectsdev/sdk` validates its config with zod at run time and is the one exception. * - any `@types/*` package. Type definitions do nothing at run time; one belongs in * `dependencies` only when a published `.d.ts` imports it, so a consumer's compile * needs it — and then it goes in `ALLOWED_TYPES_DEPS` below, with that reason. * - * Development use belongs in `devDependencies`; a genuine run-time need for the first two - * must be an optional peer (`peerDependenciesMeta`). + * Development use belongs in `devDependencies`; a genuine run-time need for the + * first three must be an optional peer (`peerDependenciesMeta`). */ import { join } from "node:path"; import { enumerateWorkspacePackages } from "./publish-set.mjs"; @@ -54,11 +57,17 @@ const BEYOND_ANY_REAL_VERSION = "9999.0.0"; /** Packages no publishable package may require at install time, with why. */ function installOnly(name: string): string | undefined { if (name === "@biomejs/biome" || name.startsWith("@biomejs/cli-")) { - return "the native Biome formatter (~94 MB binary); codegen formats through @biomejs/wasm-nodejs"; + return "the native Biome formatter (~94 MB binary); the CLI's owned-copy comparison uses the @biomejs/wasm-nodejs WASM build"; } if (name === "dprint-node" || name === "ts-poet") { return "dprint-node's seven native binaries (~25 MB; ts-poet requires it on load); codegen-ts vendors the printer and runs dprint as WebAssembly"; } + if (name === "drizzle-orm") { + return "~17 MB of ORM that only the generated code imports; the adopter's project installs it when it takes a generator (meta eject prints the set)"; + } + if (name === "zod") { + return "~8 MB that only generated code imports; the adopter's project installs it when it takes a generator (meta eject prints the set)"; + } if (name.startsWith("@types/")) { return "type definitions, unused at run time; list it in ALLOWED_TYPES_DEPS only if a published .d.ts imports it"; } @@ -66,10 +75,14 @@ function installOnly(name: string): string | undefined { } /** - * `@types/*` run-time dependencies that are deliberate: `" "` → why a - * consumer's compile needs it (a published `.d.ts` that imports it). Empty today. + * Deliberate exceptions to the install-only rule: `" "` → why. A `@types/*` + * entry is there because a published `.d.ts` imports it; any other entry is a package that + * uses the dependency at run time. */ -const ALLOWED_TYPES_DEPS: Record = {}; +const ALLOWED_TYPES_DEPS: Record = { + // Not a types package: the one deliberate run-time use of zod in the install set. + "@metaobjectsdev/sdk zod": "the sdk validates .metaobjects/config.json and package manifests with zod schemas at run time", +}; interface Violation { pkg: string; peer: string; range: string } export interface InstallOnlyDep { pkg: string; dep: string; field: string; why: string } diff --git a/scripts/check-reference-templates-lint.ts b/scripts/check-reference-templates-lint.ts index 9602ca7da0..6bacf13943 100644 --- a/scripts/check-reference-templates-lint.ts +++ b/scripts/check-reference-templates-lint.ts @@ -19,8 +19,8 @@ * trivially fixable with no behaviour change. * * Nothing could see them. The templates are excluded from each package's BUILD - * tsconfig, this repo ships no `biome.json` of its own (biome is a dependency here for - * `formatTs`, the codegen format pass — not a repo linter), and the gates that DO read + * tsconfig, this repo ships no `biome.json` of its own (biome is a devDependency here so + * the template lint below can run, not a repo linter), and the gates that DO read * these files — `test/reference-byte-identical.test.ts` in each package — compare * EMITTED OUTPUT, which is byte-identical whether a template asserts non-null or * narrows. The only reader who ever saw them was an adopter. @@ -76,9 +76,8 @@ export async function discoverTemplates(repo: string = REPO): Promise return found.sort(); } -/** biome is a devDependency of the codegen packages (shipped code formats through the - * WASM build instead), so a binary is present after `bun install`. Any of them is the - * same pinned version. */ +/** biome is a devDependency of the codegen packages, so a binary is present after + * `bun install`. Any of them is the same pinned version. */ export function resolveBiomeBin(repo: string = REPO): string | undefined { for (const root of PACKAGE_ROOTS) { const rootDir = join(repo, root); diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 51edf0119b..22db44d6d2 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -424,6 +424,12 @@ gate_assess_prompt() { node scripts/build-assess-prompt.mjs --out /dev/null && n # dependencies, optionalDependencies or a required peer; see scripts/check-peer-ranges.ts. gate_peer_ranges() { bun scripts/check-peer-ranges.ts && bun test scripts/check-peer-ranges.test.ts; } +# What `npm install @metaobjectsdev/cli` puts on disk, held to a budget that only moves down +# (scripts/check-install-size.mjs). It packs this checkout's built packages and installs them, +# so it needs dist/, npm and the registry for third-party packages: the full run's ts-slow +# lane, never `--only gates`, which has to work offline. +gate_install_size() { node scripts/check-install-size.mjs; } + # ── this repo's OWNED copies of the reference templates must BE the templates ── # owned-copies-current.test.ts already asserts byte-identity; this runs the same check # from the gates lane so a stale copy is named with the command that fixes it. Changing @@ -1366,6 +1372,7 @@ lane_ts() { lane_mutation() { if want ts; then step_if bun "completeness-gate (mutation, full)" gate_completeness; fi; } # ts-slow's half: the two real-PG suites plus the TS integration suite. lane_ts_integ() { + step_if npm "install size budget" gate_install_size integ_ready || return 0 use_pg_sidecar step_if bun "migrate-ts real-PG suite" gate_migrate_ts_pg @@ -1621,6 +1628,7 @@ elif [ "$PARALLEL" -eq 0 ]; then # Ordered BEFORE the docker integration step so a container-readiness flake there # can never prevent the migrate verdict from being produced. if in_lane_any ts ts-slow && docker info >/dev/null 2>&1; then ensure_pg_sidecar; fi + in_lane_any ts ts-slow && step_if npm "install size budget" gate_install_size in_lane_any ts ts-slow && step_if bun "migrate-ts real-PG suite" gate_migrate_ts_pg in_lane_any ts ts-slow && step_if bun "runtime-ts real-PG dialect matrix" gate_runtime_ts_pg in_lane_any ts ts-slow && step_if bun "prisma real-PG round trip" gate_prisma_pg diff --git a/scripts/install-size-budget.json b/scripts/install-size-budget.json new file mode 100644 index 0000000000..540e5e2222 --- /dev/null +++ b/scripts/install-size-budget.json @@ -0,0 +1,5 @@ +{ + "platform": "linux-x64", + "budgetBytes": 53470878, + "slackBytes": 2097152 +} diff --git a/scripts/regen-showcase.ts b/scripts/regen-showcase.ts index 7871334355..ddd52d1880 100644 --- a/scripts/regen-showcase.ts +++ b/scripts/regen-showcase.ts @@ -382,11 +382,9 @@ function pristineProject(): string { join(tmp, ".metaobjects", "config.json"), { recursive: true }); // A project with no `node_modules` anywhere above it switches Bun into auto-install: the // config's `@metaobjectsdev/*` imports would then resolve to a copy fetched into the - // machine-wide cache, not this tree, and that copy's formatter dependency cannot find its - // sibling `@biomejs/wasm-nodejs` ("Biome formatter error"), so every ts file comes out - // unformatted and the gate reports the whole committed tree as stale. An empty - // `node_modules` turns auto-install off; the CLI's own package aliases then resolve the - // workspace packages, which is what this check is meant to exercise. + // machine-wide cache, not this tree, so the gate would check that copy's output instead of + // the committed tree. An empty `node_modules` turns auto-install off; the CLI's own package + // aliases then resolve the workspace packages, which is what this check is meant to exercise. mkdirSync(join(tmp, "node_modules")); return tmp; } diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index 0487342c55..30328e7c5f 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -12,7 +12,8 @@ The MetaObjects CLI — scaffolds `metaobjects/` + `.metaobjects/`, runs codegen bun add -D @metaobjectsdev/cli ``` -The SQLite/Turso driver (`@libsql/kysely-libsql`) ships as a direct dependency — `meta migrate` against a `sqlite`/`libsql` URL works out of the box. Postgres remains an optional peer (install only if you target Postgres): +The SQLite/Turso driver (`@libsql/kysely-libsql`) is an optional peer, because it carries a native binary per platform and libc: `meta init` adds it to a SQLite project's `package.json` (run your package manager's install afterwards), and a project that skipped `init` adds it itself. Without it, `meta migrate` against a `sqlite`/`libsql` URL stops with the install command for your package manager. Postgres is an optional peer too (install only if you target Postgres): +- SQLite on Node: `bun add -D @libsql/kysely-libsql` - Postgres: `bun add -D pg` If a required driver is ever missing, the CLI prints an install command matching your project's package manager (npm / pnpm / yarn / bun, detected from the lockfile). @@ -28,7 +29,7 @@ bun run build:binary # → dist/meta (compiled for the build host's OS/ar ./dist/meta --help ``` -The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — codegen formats through the Node WebAssembly backend (`@biomejs/wasm-nodejs`), and the native Biome binary is not installed with the CLI. +The build externalizes two optional Biome WASM backends (`@biomejs/wasm-bundler`, `@biomejs/wasm-web`) that the CLI never loads — the owned-copy comparison uses the Node WebAssembly backend (`@biomejs/wasm-nodejs`), generation runs no formatter, and the native Biome binary is not installed with the CLI. ### Cross-compiling for other platforms @@ -44,7 +45,7 @@ bun build ./bin/meta.ts --compile --target=bun-windows-x64 --outfile dist/meta-w ### SQLite driver inside the binary -The standalone binary uses Bun's built-in **`bun:sqlite`** for the `sqlite` dialect (it ships inside the embedded Bun runtime). The npm/Node distribution uses the bundled `@libsql/kysely-libsql` dependency. This is automatic — the same `--db file:./app.db --dialect sqlite` flags work in both. (Postgres in the standalone binary still requires the `pg` peer to be resolvable, because `pg` is a native module that `--compile` cannot embed; sqlite is the fully self-contained path.) +The standalone binary uses Bun's built-in **`bun:sqlite`** for the `sqlite` dialect (it ships inside the embedded Bun runtime). The npm/Node distribution uses the `@libsql/kysely-libsql` driver your project declares. This is automatic — the same `--db file:./app.db --dialect sqlite` flags work in both. (Postgres in the standalone binary still requires the `pg` peer to be resolvable, because `pg` is a native module that `--compile` cannot embed; sqlite is the fully self-contained path.) Run schema ops from the compiled binary: @@ -109,7 +110,7 @@ Running `meta` with no arguments prints a concise status line (whether a `metaob Scaffolds `metaobjects/` (visible entity declarations, with a placeholder `meta.common.json`), `.metaobjects/` (hidden tool state: `config.json`, the always-on `AGENTS.md`, `.gitignore`, `.gen-state/`), the `metaobjects-*` skills under `.claude/skills/` (or `--skills-dir`), a root `AGENTS.md` / `CLAUDE.md` import of the always-on file, an **empty** `codegen/generators/` plus its `tsconfig.codegen.json`, and `metaobjects.config.ts` at the repo root. The scaffolded config carries `outputLayout: "package"` — one directory per metadata package, so two objects with one name in two packages are two files. The engine default stays `flat`; delete the line (or set `"flat"`) for the old layout. -**It copies no generators and declares no dependencies.** Codegen is opt-in (ADR-0034 Amendment 2): the scaffolded config carries `generators: []` and a comment pointing at the catalog. `meta gen --list --probe` shows what each generator would emit for your model, with the import line that runs it as shipped; `meta gen --list --format json` adds what to install (`install.dev`, `install.runtime`) and the config keys each generator reads (`configKeys`), which the text listing does not print. Import a generator from its package to use it unchanged; `meta eject ...` copies the ones you want to change into `codegen/generators/` — **yours to edit** — and prints the import line to swap in, the entry to add, the install command and any config keys those generators read. `meta gen` runs whatever `generators: [...]` holds: the package's generator where you imported it, your copy where you ejected it. +**It copies no generators.** It declares one dependency, the SQLite driver, and only in a SQLite project (see [Install](#install)). Codegen is opt-in (ADR-0034 Amendment 2): the scaffolded config carries `generators: []` and a comment pointing at the catalog. `meta gen --list --probe` shows what each generator would emit for your model, with the import line that runs it as shipped; `meta gen --list --format json` adds what to install (`install.dev`, `install.runtime`) and the config keys each generator reads (`configKeys`), which the text listing does not print. Import a generator from its package to use it unchanged; `meta eject ...` copies the ones you want to change into `codegen/generators/` — **yours to edit** — and prints the import line to swap in, the entry to add, the install command and any config keys those generators read. `meta gen` runs whatever `generators: [...]` holds: the package's generator where you imported it, your copy where you ejected it. Flags: - `--force` — overwrite scaffold files (memory records preserved) diff --git a/server/typescript/packages/cli/package.json b/server/typescript/packages/cli/package.json index 4664ba7cd7..5686d4a0a0 100644 --- a/server/typescript/packages/cli/package.json +++ b/server/typescript/packages/cli/package.json @@ -50,7 +50,6 @@ "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", - "@libsql/kysely-libsql": "^0.4.0", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/codegen-ts-react": "workspace:*", "@metaobjectsdev/codegen-ts-tanstack": "workspace:*", @@ -64,16 +63,21 @@ "jiti": "^2.4.0" }, "peerDependencies": { + "@libsql/kysely-libsql": ">=0.4.0 <0.5.0", "kysely": ">=0.27.0 <0.30.0", "pg": ">=8.0.0 <9.0.0" }, "peerDependenciesMeta": { + "@libsql/kysely-libsql": { + "optional": true + }, "pg": { "optional": true } }, "devDependencies": { "@libsql/client": "^0.14.0", + "@libsql/kysely-libsql": "^0.4.1", "@metaobjectsdev/test-generators": "workspace:*", "@types/node": "^22.0.0", "@types/pg": "^8.0.0", diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index 8c6a638cce..29e51fe13a 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -16,6 +16,8 @@ import { currentContentHash } from "../lib/agent-context-staleness.js"; import { findWranglerConfig, parseWranglerConfig } from "@metaobjectsdev/migrate-ts"; import { DEFAULT_DOCS_DIR } from "@metaobjectsdev/codegen-ts"; import { describeError } from "../lib/error-text.js"; +import { ownPeerRange } from "../lib/install-set.js"; +import { declaredDependencyNames, type PackageManifest } from "../lib/package-manifest.js"; import { SUBTYPE_ROOT, TYPE_METADATA, TYPE_SUBTYPE_SEPARATOR } from "@metaobjectsdev/metadata/constants"; import { docsRefForVersion } from "@metaobjectsdev/metadata"; @@ -832,7 +834,7 @@ export async function init(opts: InitOptions): Promise { result.preserved.push(".gitignore"); } - await prepareManifestForScaffold(opts.cwd, result); + await prepareManifestForScaffold(opts.cwd, result, resolveInitDialect(opts)); return result; } @@ -859,7 +861,7 @@ export async function init(opts: InitOptions): Promise { * accreted a second, and the second silently inherited the first's early returns. The * declarations are unconditional on a readable manifest — see the comment at that point. */ -async function prepareManifestForScaffold(cwd: string, result: InitResult): Promise { +async function prepareManifestForScaffold(cwd: string, result: InitResult, dialect: InitDialect): Promise { const pkgPath = join(cwd, "package.json"); if (!(await fileExists(pkgPath))) { // No package.json at all: say what is needed rather than inventing a manifest @@ -929,22 +931,31 @@ async function prepareManifestForScaffold(cwd: string, result: InitResult): Prom } } - // NO DEPENDENCIES ARE ADDED. `meta init` used to declare five packages here — - // codegen-ts and metadata for the generators it copied, drizzle-orm / zod / fastify - // for the code those generators would write — and every one of them was a - // consequence of the scaffold WIRING a suite. It wires nothing now, so declaring - // anything would be declaring a dependency on code this project may never generate. + // THE DATABASE DRIVER IS THE ONE DEPENDENCY INIT DECLARES. It used to declare five packages, + // codegen-ts and metadata for the generators it copied and drizzle-orm / zod / fastify for the + // code those generators would write, and every one of them was a consequence of the scaffold + // WIRING a suite. It wires nothing now, so those stay out: the need moved to the moment a + // generator is chosen, where `meta eject ...` reports the exact install set for what you + // took (lib/install-set.ts) and `meta gen --list --format json` carries it per entry. // - // The need did not vanish, it MOVED to the moment a generator is chosen: - // `meta eject ...` reports the exact install set for what you took, with - // third-party ranges read from the runtime package's own peerDependencies (see - // lib/install-set.ts), and `meta gen --list --format json` carries the same set per - // entry before you commit to anything. - if (moduleSystemNote !== undefined) { + // A driver is different: it belongs to the DATABASE the project named, not to a generator, and + // `meta migrate` and `meta verify --db` need it before any generator exists. SQLite's driver + // (libSQL, with a native binary per platform and libc) is not installed with the CLI, so a + // sqlite project declares it here, at the range the CLI was tested against. Postgres, D1 and + // MySQL have no driver of this kind to add: `pg` is the project's own, and D1 goes through + // wrangler. + const driverAdded = dialect === "sqlite" ? declareSqliteDriver(pkg) : false; + if (driverAdded) { + result.warnings.push( + `package.json: added ${SQLITE_DRIVER} to dependencies, the driver \`meta migrate\` and \`meta verify --db\` use for SQLite. ` + + "Run your package manager's install to fetch it.", + ); + } + if (moduleSystemNote !== undefined || driverAdded) { // Preserve the file's existing indentation rather than reformatting someone's manifest. const indent = /\n(\s+)"/.exec(raw)?.[1] ?? " "; await writeFile(pkgPath, `${JSON.stringify(pkg, null, indent)}\n`, "utf8"); - result.warnings.push(moduleSystemNote); + if (moduleSystemNote !== undefined) result.warnings.push(moduleSystemNote); } } @@ -953,6 +964,21 @@ async function prepareManifestForScaffold(cwd: string, result: InitResult): Prom +/** The SQLite driver `meta migrate` loads on Node (under Bun the built-in `bun:sqlite` is used). */ +const SQLITE_DRIVER = "@libsql/kysely-libsql"; + +/** Declare the SQLite driver unless the manifest already does, in any dependency field. + * True when the manifest changed. */ +function declareSqliteDriver(pkg: Record): boolean { + if (declaredDependencyNames(pkg as PackageManifest).has(SQLITE_DRIVER)) return false; + const range = ownPeerRange(SQLITE_DRIVER); + const deps = (pkg.dependencies ?? {}) as Record; + // Without a readable range the driver is still declared, at any version, rather than not at all. + deps[SQLITE_DRIVER] = range ?? "*"; + pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b))); + return true; +} + /** True when the project has hand-written CommonJS at the root (excluding tooling dirs). */ async function hasCommonJsSources(cwd: string): Promise { const SKIP = new Set(["node_modules", ".git", "dist", "build", ".metaobjects", "codegen"]); diff --git a/server/typescript/packages/cli/src/lib/install-set.ts b/server/typescript/packages/cli/src/lib/install-set.ts index c6252f0cbc..5f7c810cfa 100644 --- a/server/typescript/packages/cli/src/lib/install-set.ts +++ b/server/typescript/packages/cli/src/lib/install-set.ts @@ -20,6 +20,7 @@ import { createRequire } from "node:module"; import { existsSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { HTTP_RUNTIME_PACKAGE, type GeneratorRegistryEntry } from "@metaobjectsdev/codegen-ts"; import { cliVersion } from "./version.js"; import { packageOf } from "./catalog.js"; @@ -50,6 +51,30 @@ export function dependencyRangesOf(packageName: string): Record return manifestRangesOf(packageName, "dependencies"); } +/** + * A peer range the CLI itself declares, or `undefined` if it cannot be read. `meta init` writes + * the SQLite driver into a new project with it, so the range an adopter installs is the one this + * CLI was tested against and never a second copy kept here. + */ +export function ownPeerRange(name: string): string | undefined { + try { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let hops = 0; hops < 8; hops++) { + const candidate = join(dir, "package.json"); + if (existsSync(candidate)) { + const manifest = JSON.parse(readFileSync(candidate, "utf8")) as PackageManifest & { name?: string }; + if (manifest.name === "@metaobjectsdev/cli") return manifest.peerDependencies?.[name]; + } + const up = dirname(dir); + if (up === dir) break; + dir = up; + } + } catch { + // unreadable: the caller writes the package without a range + } + return undefined; +} + function manifestRangesOf(packageName: string, field: "peerDependencies" | "dependencies"): Record { try { const req = createRequire(import.meta.url); diff --git a/server/typescript/packages/cli/src/lib/owned-copy.ts b/server/typescript/packages/cli/src/lib/owned-copy.ts index 575349920b..addbe31936 100644 --- a/server/typescript/packages/cli/src/lib/owned-copy.ts +++ b/server/typescript/packages/cli/src/lib/owned-copy.ts @@ -32,7 +32,7 @@ // theirs and may not even parse), canonicalization degrades to trimmed raw lines. The // verdict then reads `differs` where it might have read `reformatted` — the pre-existing // behaviour, never a false `reformatted`. -import { Biome, Distribution } from "@biomejs/js-api"; +import type { Biome } from "@biomejs/js-api"; export type OwnedVerdict = /** Byte-for-byte the reference. */ @@ -53,11 +53,15 @@ export interface OwnedComparison { // One instance, created lazily and shared. Cache the PROMISE so concurrent first calls // (--list compares every owned copy) share one in-flight create rather than racing. +// The WebAssembly build is also LOADED lazily: it is about 14 MB of module that every other +// `meta` command (gen, verify, migrate, init) has no use for, so the import waits for the first +// comparison instead of being paid at start-up. let _biome: Promise | undefined; function getBiome(): Promise { if (!_biome) { - _biome = Biome.create({ distribution: Distribution.NODE }) + _biome = import("@biomejs/js-api") + .then(({ Biome: Formatter, Distribution }) => Formatter.create({ distribution: Distribution.NODE })) .then((biome) => { biome.applyConfiguration({ formatter: { enabled: true, indentStyle: "space", indentWidth: 2, lineWidth: 1 }, @@ -65,7 +69,7 @@ function getBiome(): Promise { }); return biome; }) - // A comparison is a REPORT LINE. If the formatter cannot start, say less — never + // A comparison is a REPORT LINE. If the formatter cannot load or start, say less — never // fail the command the adopter actually ran. .catch(() => undefined); } diff --git a/server/typescript/packages/cli/test/init-esm-package-type.test.ts b/server/typescript/packages/cli/test/init-esm-package-type.test.ts index 60083a1e70..c4e6fb81a3 100644 --- a/server/typescript/packages/cli/test/init-esm-package-type.test.ts +++ b/server/typescript/packages/cli/test/init-esm-package-type.test.ts @@ -17,6 +17,7 @@ // every first-touch compile failure except the one it was written for. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from "node:fs"; +const rm = (path: string, opts: { recursive: boolean; force: boolean }): void => rmSync(path, opts); import { tmpdir } from "node:os"; import { join } from "node:path"; import { init } from "../src/commands/init.js"; @@ -109,7 +110,7 @@ describe("meta init — ESM package type", () => { }); }); -describe("meta init — the scaffold declares no dependencies", () => { +describe("meta init — the scaffold declares no generator dependencies", () => { // ADR-0034 puts real source in the adopter's repo, and init used to declare what that // source imported (@metaobjectsdev/codegen-ts + /metadata) plus what the code it would // GENERATE imported (drizzle-orm, zod, fastify). Both sets existed only because init @@ -120,12 +121,12 @@ describe("meta init — the scaffold declares no dependencies", () => { // generators you take — covered end-to-end in scaffold-output-imports-declared.test.ts, // which ejects a selection, applies its install set and then checks the generated // output against the manifest. - test("adds nothing to dependencies or devDependencies", async () => { + test("adds only the SQLite driver, and nothing to devDependencies", async () => { writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x", type: "commonjs" }, null, 2) + "\n"); await init({ cwd: dir, quiet: true }); const pkg = readPkg(); expect(pkg.devDependencies).toBeUndefined(); - expect(pkg.dependencies).toBeUndefined(); + expect(Object.keys(pkg.dependencies as Record)).toEqual(["@libsql/kysely-libsql"]); }); test("still leaves a pin the project already chose exactly as it was", async () => { @@ -138,8 +139,38 @@ describe("meta init — the scaffold declares no dependencies", () => { const pkg = readPkg(); expect((pkg.devDependencies as Record)["ts-poet"]).toBe("6.0.0"); expect((pkg.dependencies as Record)["@metaobjectsdev/codegen-ts"]).toBe("0.1.0"); - // ...and adds nothing beside them. + // ...and adds nothing beside them but the SQLite driver. expect(Object.keys(pkg.devDependencies as Record)).toEqual(["ts-poet"]); - expect(Object.keys(pkg.dependencies as Record)).toEqual(["@metaobjectsdev/codegen-ts"]); + expect(Object.keys(pkg.dependencies as Record)).toEqual(["@libsql/kysely-libsql", "@metaobjectsdev/codegen-ts"]); + }); +}); + +describe("meta init — the SQLite driver", () => { + // libSQL carries a native binary per platform and libc, so the CLI does not install it; the + // project that targets SQLite declares it, at the range the CLI declares as its peer. + const driverOf = (): string | undefined => + (readPkg().dependencies as Record | undefined)?.["@libsql/kysely-libsql"]; + + test("a sqlite project declares it at the range the CLI was tested against", async () => { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x" }, null, 2) + "\n"); + const result = await init({ cwd: dir, quiet: true }); + expect(driverOf()).toBe(">=0.4.0 <0.5.0"); + expect(result.warnings.join("\n")).toContain("added @libsql/kysely-libsql"); + }); + + test("a postgres, mysql or d1 project does not", async () => { + for (const dialect of ["postgres", "mysql", "d1"]) { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x" }, null, 2) + "\n"); + rm(join(dir, ".metaobjects"), { recursive: true, force: true }); + await init({ cwd: dir, quiet: true, dialect, force: true }); + expect(driverOf(), dialect).toBeUndefined(); + } + }); + + test("a project that already declares it keeps its pin and gets no second entry", async () => { + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "x", devDependencies: { "@libsql/kysely-libsql": "0.4.1" } }, null, 2) + "\n"); + await init({ cwd: dir, quiet: true }); + expect(driverOf()).toBeUndefined(); + expect((readPkg().devDependencies as Record)["@libsql/kysely-libsql"]).toBe("0.4.1"); }); }); diff --git a/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts b/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts new file mode 100644 index 0000000000..88ee5194e9 --- /dev/null +++ b/server/typescript/packages/cli/test/owned-copy-lazy-biome.test.ts @@ -0,0 +1,44 @@ +// Biome's WebAssembly build is ~14 MB of module that only the owned-copy comparison uses. +// Importing owned-copy must not load it; the first canonicalLines call must. +import { describe, expect, test } from "bun:test"; +import { join } from "node:path"; +import { canonicalLines } from "../src/lib/owned-copy.js"; + +// onResolve does not see a static import inside a module (only dynamic ones), so the probe +// counts Biome module loads in onLoad, which sees both kinds. +const probe = ` +import { plugin } from "bun"; +import { readFileSync } from "node:fs"; +const loaded = []; +plugin({ + name: "biome-probe", + setup(build) { + build.onLoad({ filter: /@biomejs\\/.*\\.m?js$/ }, (args) => { + loaded.push(args.path); + return { loader: "js", contents: readFileSync(args.path, "utf8") }; + }); + }, +}); +const { canonicalLines } = await import(${JSON.stringify(join(import.meta.dir, "..", "src", "lib", "owned-copy.ts"))}); +const afterImport = loaded.length; +await canonicalLines("const x = {a:1};\\n"); +console.log(JSON.stringify({ afterImport, afterCall: loaded.length })); +`; + +describe("owned-copy loads Biome on first use", () => { + test("importing the module does not load Biome; the first comparison does", () => { + const run = Bun.spawnSync([process.execPath, "-e", probe], { cwd: join(import.meta.dir, "..") }); + expect(run.exitCode).toBe(0); + const { afterImport, afterCall } = JSON.parse(run.stdout.toString().trim().split("\n").pop() ?? "{}"); + expect(afterImport).toBe(0); + expect(afterCall).toBeGreaterThan(0); + }); + + test("a comparison still formats, so the lazy load works", async () => { + // Biome runs at line width 1, so a one-line object and an exploded one reach the same lines. + const tight = await canonicalLines("const x = {a:1,b:2};\n"); + const loose = await canonicalLines("const x = {\n a: 1,\n b: 2,\n};\n"); + expect(tight).toEqual(loose); + expect(tight).toContain("a: 1"); + }); +}); diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts index 30b46d12eb..e863523bb2 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-form.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesWriteApi, isProjection, @@ -49,7 +48,7 @@ export const angularFormFile = function angularFormFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.form.component.ts`), - content: await formatTs(renderFormFile(entity, ctx.renderContext)), + content: renderFormFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts index 30c4f2d2fa..37ffecba46 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-grid.ts @@ -4,7 +4,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, effectivePackage, @@ -52,7 +51,7 @@ export const angularGridFile = function angularGridFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.grid.component.ts`), - content: await formatTs(renderGridFile(entity, ctx.renderContext)), + content: renderGridFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts b/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts index 908549ceba..85ea04ee3e 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/angular-service.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, effectivePackage, @@ -45,7 +44,7 @@ export const angularServiceFile = function angularServiceFile( } return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.service.ts`), - content: await formatTs(renderServiceFile(entity, ctx.renderContext)), + content: renderServiceFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts b/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts index 635ffb4bf5..6faefd6d6c 100644 --- a/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts +++ b/server/typescript/packages/codegen-ts-angular/src/generators/barrel.ts @@ -3,7 +3,6 @@ import { oncePerRun, type Generator, type GeneratorFactory, - formatTs, packageToPath, servesClientTier, servesWriteApi, @@ -65,7 +64,7 @@ export const barrel = function barrel(opts?: AngularBarrelOpts): Generator { const content = `// ${GENERATED_HEADER}-angular — ${GENERATED_EDIT_NOTE}\n${lines.join("\n")}\n`; return { path: "index.ts", - content: await formatTs(content), + content: content, }; }), }; diff --git a/server/typescript/packages/codegen-ts-react/src/form-file.ts b/server/typescript/packages/codegen-ts-react/src/form-file.ts index 77ef09f909..01da741339 100644 --- a/server/typescript/packages/codegen-ts-react/src/form-file.ts +++ b/server/typescript/packages/codegen-ts-react/src/form-file.ts @@ -11,7 +11,6 @@ export interface FormFileOpts { /** * Forms are opt-in: a user must add `formFile()` to config.generators. - * .tsx files are not piped through formatTs (Biome only handles .ts here). * * Decide per generator what you consume: wire only the generators whose output you * actually import, and narrow this one with its `filter` option. There is no `@emit*` diff --git a/server/typescript/packages/codegen-ts-react/src/reference/form.ts b/server/typescript/packages/codegen-ts-react/src/reference/form.ts index 4e3e1fe825..af3f0f28bf 100644 --- a/server/typescript/packages/codegen-ts-react/src/reference/form.ts +++ b/server/typescript/packages/codegen-ts-react/src/reference/form.ts @@ -37,7 +37,6 @@ export interface FormFileOpts { /** * Forms are opt-in: a user must add `formFile()` to config.generators. - * .tsx files are not piped through formatTs (Biome only handles .ts here). * * Decide per generator what you consume: wire only the generators whose output you * actually import, and narrow this one with its `filter` option. There is no `@emit*` diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts index 47351e8cfd..2867201e78 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid-hook.ts @@ -27,7 +27,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, withClientDirective, @@ -123,11 +122,11 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo return [{ path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }, { path: entityOutputPath( ctx.renderContext.outputLayout, @@ -135,7 +134,7 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo `${entity.name}.grid.ts`, ), content: withClientDirective( - await formatTs(renderGridHookFile(entity, ctx.renderContext)), + renderGridHookFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts index 136b98a0ae..1cb3916f61 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/grid.ts @@ -27,7 +27,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientTier, withClientDirective, @@ -95,7 +94,7 @@ export const tanstackGrid = function tanstackGrid(opts?: TanstackGridOpts): Gene return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.columns.tsx`), content: withClientDirective( - await formatTs(renderColumnsFile(entity, ctx.renderContext)), + renderColumnsFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts b/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts index 33988efe85..fad80fffb7 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/reference/hooks.ts @@ -25,7 +25,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, entityOutputPath, servesClientHooks, withClientDirective, @@ -95,18 +94,18 @@ export const tanstackQuery = function tanstackQuery(opts?: TanstackQueryOpts): G const metaFile = { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }; return [metaFile, { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, `${entity.name}.hooks.ts`), - // Outside formatTs deliberately: the directive must stay the module's first - // token, and a formatter is entitled to move a leading string expression. + // The directive must stay the module's first + // token; an adopter's formatter keeps a leading string expression where it is. content: withClientDirective( - await formatTs(renderHooksFile(entity, ctx.renderContext)), + renderHooksFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts index a83ce11e9f..887f504942 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid-hook.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientTier, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientTier, isTphSubtype, withClientDirective, namesRef, namesConstArg, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -86,11 +86,11 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo return [{ path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }, { path: entityOutputPath( ctx.renderContext.outputLayout, @@ -98,7 +98,7 @@ export const tanstackGridHook = function tanstackGridHook(opts?: TanstackGridHoo `${entity.name}.grid.ts`, ), content: withClientDirective( - await formatTs(renderGridHookFile(entity, ctx.renderContext)), + renderGridHookFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts index 95cd1ab141..7383286e8b 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-grid.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, servesClientTier, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, servesClientTier, isTphSubtype, withClientDirective, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -64,7 +64,7 @@ export const tanstackGrid = function tanstackGrid(opts?: TanstackGridOpts): Gene return { path: entityOutputPath(ctx.renderContext.outputLayout, effectivePackage(entity), `${entity.name}.columns.tsx`), content: withClientDirective( - await formatTs(renderColumnsFile(entity, ctx.renderContext)), + renderColumnsFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }; diff --git a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts index 982291e69a..1421a48e94 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/tanstack-query.ts @@ -1,5 +1,5 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; -import { perEntity, type Generator, type GeneratorFactory, formatTs, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientHooks, isTphSubtype, +import { perEntity, type Generator, type GeneratorFactory, entityOutputPath, entityMetaFileName, renderEntityMetaFile, servesClientHooks, isTphSubtype, withClientDirective, namesRef, namesConstArg, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -60,18 +60,18 @@ export const tanstackQuery = function tanstackQuery(opts?: TanstackQueryOpts): G const metaFile = { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, entityMetaFileName(entity.name)), - content: await formatTs(renderEntityMetaFile( + content: renderEntityMetaFile( entity, ctx.renderContext.apiPrefix, namesConstArg(metaNames), - )), + ), }; return [metaFile, { path: entityOutputPath(ctx.renderContext.outputLayout, pkg, `${entity.name}.hooks.ts`), - // Outside formatTs deliberately: the directive must stay the module's first - // token, and a formatter is entitled to move a leading string expression. + // The directive must stay the module's first + // token; an adopter's formatter keeps a leading string expression where it is. content: withClientDirective( - await formatTs(renderHooksFile(entity, ctx.renderContext)), + renderHooksFile(entity, ctx.renderContext), ctx.renderContext.clientDirective, ), }]; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts index d8b5615b04..c84bc29fed 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/grid-filter/Subscriber.grid.ts @@ -6,19 +6,12 @@ import { subscriberActiveFilter } from "./Subscriber.columns"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useSubscriberActiveGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -30,9 +23,7 @@ export function useSubscriberActiveGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -45,10 +36,7 @@ export function useSubscriberActiveGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "active", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts index ead5c11f9f..1abb35cf34 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/multi-grid/Program.grid.ts @@ -5,19 +5,12 @@ import { Program } from "./Program.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useProgramDefaultGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -29,9 +22,7 @@ export function useProgramDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -44,8 +35,7 @@ export function useProgramDefaultGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { @@ -63,10 +53,7 @@ export function useProgramDefaultGrid() { } export function useProgramCompactGrid() { const [sorting, setSorting] = useState([]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 50, - }); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 50 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -78,9 +65,7 @@ export function useProgramCompactGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -93,8 +78,7 @@ export function useProgramCompactGrid() { const query = useQuery<{ rows: ProgramRow[]; total: number }>({ queryKey: ["program", "grid", "compact", qs], - queryFn: () => - fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), + queryFn: () => fetcher<{ rows: ProgramRow[]; total: number }>(`${Program.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts index a8497c2fd2..2c3b31f50f 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/golden/__snapshots__/single-entity/Subscriber.grid.ts @@ -5,21 +5,12 @@ import { Subscriber } from "./Subscriber.meta"; import { buildFilterQs } from "@metaobjectsdev/runtime-web"; import { useEntityPathFetcher } from "@metaobjectsdev/tanstack"; import { useQuery } from "@tanstack/react-query"; -import type { - ColumnFiltersState, - PaginationState, - SortingState, -} from "@tanstack/react-table"; +import type { ColumnFiltersState, PaginationState, SortingState } from "@tanstack/react-table"; import { useMemo, useState } from "react"; export function useSubscriberDefaultGrid() { - const [sorting, setSorting] = useState([ - { id: "createdAt", desc: true }, - ]); - const [pagination, setPagination] = useState({ - pageIndex: 0, - pageSize: 25, - }); + const [sorting, setSorting] = useState([{ id: "createdAt", desc: true }]); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 }); const [columnFilters, setColumnFilters] = useState([]); const [search, setSearch] = useState(""); @@ -31,9 +22,7 @@ export function useSubscriberDefaultGrid() { filterObj[f.id] = f.value as unknown; } const sortEntry = sorting[0]; - const sort = sortEntry - ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` - : undefined; + const sort = sortEntry ? `${sortEntry.id}:${sortEntry.desc ? "desc" : "asc"}` : undefined; return buildFilterQs({ ...filterObj, ...(sort !== undefined ? { sort } : {}), @@ -46,10 +35,7 @@ export function useSubscriberDefaultGrid() { const query = useQuery<{ rows: SubscriberRow[]; total: number }>({ queryKey: ["subscriber", "grid", "default", qs], - queryFn: () => - fetcher<{ rows: SubscriberRow[]; total: number }>( - `${Subscriber.$path}?${qs}`, - ), + queryFn: () => fetcher<{ rows: SubscriberRow[]; total: number }>(`${Subscriber.$path}?${qs}`), }); return { diff --git a/server/typescript/packages/codegen-ts/package.json b/server/typescript/packages/codegen-ts/package.json index 723edd2e6e..0beda3bf1f 100644 --- a/server/typescript/packages/codegen-ts/package.json +++ b/server/typescript/packages/codegen-ts/package.json @@ -143,8 +143,6 @@ "@metaobjectsdev/docs-site": "workspace:*", "@metaobjectsdev/render": "workspace:*", "@metaobjectsdev/migrate-ts": "workspace:*", - "@biomejs/js-api": "^0.7.0", - "@biomejs/wasm-nodejs": "^1.9.4", "@toon-format/toon": "^2.3.0", "@dprint/formatter": "^0.6.0", "@dprint/typescript": "0.87.1" @@ -153,6 +151,14 @@ "drizzle-orm": ">=0.38.0 <1.0.0", "zod": ">=3.23.0 <5.0.0" }, + "peerDependenciesMeta": { + "drizzle-orm": { + "optional": true + }, + "zod": { + "optional": true + } + }, "devDependencies": { "@biomejs/biome": "^1.9.0", "@metaobjectsdev/codegen-ts-react": "workspace:*", diff --git a/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts b/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts index 3bdd0e4e96..a50e243433 100644 --- a/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts +++ b/server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts @@ -12,7 +12,7 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { loadUris, type MetaObject, type MetaRoot, type WireFormat, wireFormatOf } from "@metaobjectsdev/metadata"; +import { type ApiPagination, loadUris, type MetaObject, type MetaRoot, type UnknownFieldsMode, type WireFormat, wireFormatOf } from "@metaobjectsdev/metadata"; import { defineConfig, type Generator, runGen } from "../src/index.js"; import { jsonSchemaFile, openApiFile } from "../src/generators/index.js"; import { readTree } from "./gen-cube-model-canonical.js"; @@ -22,6 +22,12 @@ const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..", "..", ".."); export const CONTRACT_CORPUS_DIR = join(REPO_ROOT, "fixtures", "contract-conformance"); +/** The parts of the `api` block of `.metaobjects/config.json` the document states. */ +interface ApiSettings { + readonly pagination?: ApiPagination; + readonly unknownFields?: UnknownFieldsMode; +} + /** This script, as a failing test names it. */ export const CONTRACT_SCRIPT = "server/typescript/packages/codegen-ts/scripts/gen-contract-conformance.ts (bun run gen:contract-conformance)"; @@ -34,6 +40,8 @@ export interface ContractCase { /** The metadata file: the case's own `meta.json`, or a shared one `case.json` names. */ readonly meta: string; readonly wire?: Partial; + /** The project's `api` block, as in `.metaobjects/config.json`. */ + readonly api?: ApiSettings; /** Objects the strict profile leaves out, because the strict subset cannot state them. */ readonly strictExclude: readonly string[]; /** The project wires `report-export`, so a report's list route takes `format`. */ @@ -44,6 +52,7 @@ interface CaseJson { /** Repository-relative metadata file. Default: `meta.json` beside it. */ meta?: string; wire?: Partial; + api?: ApiSettings; strictExclude?: string[]; reportExport?: boolean; } @@ -57,6 +66,7 @@ function readCase(name: string): ContractCase { dir, meta: json.meta === undefined ? join(dir, "meta.json") : join(REPO_ROOT, json.meta), ...(json.wire !== undefined && { wire: json.wire }), + ...(json.api !== undefined && { api: json.api }), strictExclude: json.strictExclude ?? [], reportExport: json.reportExport ?? false, }; @@ -76,6 +86,8 @@ export async function loadCaseModel(c: ContractCase): Promise { throw new Error(`${c.meta}: metadata did not load cleanly: ${result.errors.map((e) => e.message).join("; ")}`); } if (c.wire !== undefined) result.root.wireFormat = { ...wireFormatOf(result.root), ...c.wire }; + if (c.api?.pagination !== undefined) result.root.apiPagination = c.api.pagination; + if (c.api?.unknownFields !== undefined) result.root.apiUnknownFields = c.api.unknownFields; return result.root; } diff --git a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts index f6f9e11ac7..126d40db34 100644 --- a/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts +++ b/server/typescript/packages/codegen-ts/src/contract/build-openapi.ts @@ -5,10 +5,24 @@ // // It states the cross-port contract only. The TS-only filter extensions (`?search`, `filter[or]`) // are left out, and so are the `405` refusals on a read-only surface, which are not operations a -// caller can use (the api docs omit them for the same reason). +// caller can use (the api docs omit them for the same reason): a read-only resource says so in the +// description of its operations instead. +// +// It also states what the 1.3 routes do beyond the happy path: the project's page size +// (`api.pagination`), the refusal of an undeclared body key (`api.unknownFields`) and the list of +// validation issues. import { flatSurfaceFields } from "../flattened.js"; -import { type MetaField, type MetaObject, type MetaRoot, opsForField } from "@metaobjectsdev/metadata"; +import { + type ApiPagination, + apiPaginationOf, + apiUnknownFieldsOf, + type MetaField, + type MetaObject, + type MetaRoot, + opsForField, + UNKNOWN_FIELDS_REJECT, +} from "@metaobjectsdev/metadata"; import { FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_TIMESTAMP, FILTER_OP_IN, FILTER_OP_IS_NULL, FILTER_OP_LIKE } from "@metaobjectsdev/metadata/constants"; import { hasItemRoute, itemRouteField, servedPath, servesReadApi } from "../api-surface.js"; import { isProjection } from "../projection/projection-detector.js"; @@ -103,7 +117,15 @@ function errorResponse(description: string): JsonSchema { return { description, content: jsonContent({ $ref: componentRef(ERROR_COMPONENT) }) }; } +const READ_ONLY_NOTE = 'Read-only: a write to this resource answers 405 {"error": "method_not_allowed"}.'; + const BAD_REQUEST = errorResponse("The request was refused."); +const VALIDATION_REFUSED = errorResponse( + 'The request was refused. A body that fails validation answers error "validation" with an issue for every problem, not the first.', +); +const UNKNOWN_FIELDS_REFUSED = errorResponse( + 'The request was refused. A body key the model does not declare answers error "unknown_fields" with the keys in fields, and nothing is written. Any other problem answers error "validation" with an issue for every problem.', +); const NOT_FOUND = errorResponse("No such row."); const CONFLICT = errorResponse("A constraint refused the write."); @@ -141,9 +163,26 @@ function sortParameter(obj: MetaObject, excludeField: string | undefined, root: return [{ name: "sort", in: "query", schema: { type: "string", enum: values } }]; } -function pageParameters(minLimit: number): JsonSchema[] { +/** + * The page parameters. A project that sets `api.pagination` serves `defaultLimit` rows when `limit` + * is absent and refuses a `limit` above `maxLimit`, so the document says both. A report keeps its + * own row cap (a generator option the model does not hold), so it states neither. + */ +function pageParameters(minLimit: number, page: ApiPagination | undefined): JsonSchema[] { + const limit: JsonSchema = { + type: "integer", + minimum: minLimit, + ...(page !== undefined && { maximum: page.maxLimit, default: page.defaultLimit }), + }; return [ - { name: "limit", in: "query", schema: { type: "integer", minimum: minLimit } }, + { + name: "limit", + in: "query", + ...(page !== undefined && { + description: `Rows per page. Absent, the server answers ${page.defaultLimit}; above ${page.maxLimit} it answers 400 limit_too_large.`, + }), + schema: limit, + }, { name: "offset", in: "query", schema: { type: "integer", minimum: 0 } }, { name: "withCount", in: "query", description: "Answer { rows, total } instead of the array.", schema: { type: "integer", enum: [1] } }, ]; @@ -187,6 +226,8 @@ function idParameter(obj: MetaObject): JsonSchema { /** The operations of one resource: its collection path and, when it has rows by key, its item path. */ interface ResourceOps { + /** Writes are not served here (a projection or a report), and the operations say so. */ + readonly readOnly?: boolean; /** The object whose rows the routes answer, and whose name the operations carry. */ readonly row: MetaObject; readonly path: string; @@ -206,7 +247,7 @@ function listOperation(r: ResourceOps): JsonSchema { const parameters = [ ...filterParameters(row, r.excludeField, r.root), ...sortParameter(row, r.excludeField, r.root), - ...pageParameters(r.report ? 1 : 0), + ...pageParameters(r.report ? 1 : 0, r.report ? undefined : apiPaginationOf(r.root)), ...(r.reportExport ? [{ name: "format", in: "query", schema: { type: "string", enum: ["csv", "json", "xml"] } }] : []), ]; r.refs.listed.add(row); @@ -216,13 +257,22 @@ function listOperation(r: ResourceOps): JsonSchema { return { operationId: `list${row.name}`, tags: [row.name], + ...(r.readOnly === true && { description: READ_ONLY_NOTE }), parameters, responses: { "200": { description: "The rows.", content: { ...content, ...exports } }, "400": BAD_REQUEST }, }; } function writeBody(r: ResourceOps, shape: ContractShape): JsonSchema { - return { required: true, content: jsonContent(pathRef(r.refs, r.row, shape)) }; + const rejects = apiUnknownFieldsOf(r.root) === UNKNOWN_FIELDS_REJECT; + const description = rejects + ? "A top-level key the model does not declare is refused with 400 unknown_fields. A declared key the client may not set, such as the generated key, is dropped." + : "A top-level key the model does not declare is dropped, and the rest of the body is written."; + return { required: true, description, content: jsonContent(pathRef(r.refs, r.row, shape)) }; +} + +function writeRefused(r: ResourceOps): JsonSchema { + return apiUnknownFieldsOf(r.root) === UNKNOWN_FIELDS_REJECT ? UNKNOWN_FIELDS_REFUSED : VALIDATION_REFUSED; } function updateOperation(r: ResourceOps, operationId: string): JsonSchema { @@ -232,7 +282,7 @@ function updateOperation(r: ResourceOps, operationId: string): JsonSchema { requestBody: writeBody(r, "update"), responses: { "200": { description: "The row.", content: jsonContent(pathRef(r.refs, r.row, "read")) }, - "400": BAD_REQUEST, + "400": writeRefused(r), "404": NOT_FOUND, "409": CONFLICT, }, @@ -247,6 +297,7 @@ function itemOperations(r: ResourceOps): JsonSchema { get: { operationId: `get${row.name}`, tags, + ...(r.readOnly === true && { description: READ_ONLY_NOTE }), responses: { "200": { description: "The row.", content: jsonContent(pathRef(r.refs, row, "read")) }, "404": NOT_FOUND }, }, }), @@ -276,7 +327,7 @@ function collectionOperations(r: ResourceOps): JsonSchema { requestBody: writeBody(r, "create"), responses: { "201": { description: "The new row.", content: jsonContent(pathRef(r.refs, row, "read")) }, - "400": BAD_REQUEST, + "400": writeRefused(r), "409": CONFLICT, }, }, @@ -323,7 +374,7 @@ function pathsOf(obj: MetaObject, input: OpenApiBuildInput, refs: PathRefs): Rec if (isProjection(obj)) { return resourcePaths({ row: obj, path, report, reportExport: report && input.reportExport, item: hasItemRoute(obj), refs, root: input.root, - verbs: new Set(["list", "get"]), + readOnly: true, verbs: new Set(["list", "get"]), }); } const plan = tphPlan(obj, root); @@ -401,6 +452,21 @@ function collectSchemas(input: OpenApiBuildInput, refs: PathRefs): Record compareNames(a, b))); diff --git a/server/typescript/packages/codegen-ts/src/format.ts b/server/typescript/packages/codegen-ts/src/format.ts index 8e68172770..9e46d28a3f 100644 --- a/server/typescript/packages/codegen-ts/src/format.ts +++ b/server/typescript/packages/codegen-ts/src/format.ts @@ -1,50 +1,17 @@ -// Biome formatter integration. Used by generate() to format rendered TS before write. -// Per design §11: format errors are warnings, not throws. - -import { Biome, Distribution } from "@biomejs/js-api"; - -// Cache the Promise (not the resolved instance) so concurrent first calls -// share the same in-flight Biome.create() rather than racing to spawn two. -let _biomePromise: Promise | undefined; - -function getBiome(): Promise { - if (!_biomePromise) { - _biomePromise = Biome.create({ distribution: Distribution.NODE }).then((biome) => { - biome.applyConfiguration({ - formatter: { enabled: true, indentStyle: "space", indentWidth: 2 }, - javascript: { formatter: { quoteStyle: "double", semicolons: "always" } }, - }); - return biome; - }); - } - return _biomePromise; -} +// `formatTs` is a no-op kept only so an owned 1.2 generator copy still loads. +// +// Until 1.3.0 every reference generator piped its rendered text through Biome before it +// was written. Generation no longer runs a formatter: each generator writes the layout it +// means (the templates and `TsWriter`), and the adopter's own formatter owns the rest. A +// generator copied out with `meta eject` in 1.2 imports this name from the package entry, +// so the export stays and returns its input unchanged. A copy that wants a formatter calls +// the one it already depends on. /** - * Summarize Biome diagnostics into a single human-readable line, without - * dumping the raw diagnostic objects (which produce "[Object ...]" / - * "source: null" noise when stringified by console). + * Returns `content` unchanged. + * + * @deprecated Generation runs no formatter. A generator that wants one calls its own. */ -function summarizeDiagnostics(diagnostics: ReadonlyArray): string { - const count = diagnostics.length; - const first = diagnostics[0] as { description?: string; message?: string } | undefined; - const firstMsg = first?.description ?? first?.message ?? "(no description)"; - return count === 1 - ? `1 diagnostic: ${firstMsg}` - : `${count} diagnostics; first: ${firstMsg}`; -} - export async function formatTs(content: string): Promise { - try { - const biome = await getBiome(); - const result = biome.formatContent(content, { filePath: "in-memory.ts" }); - if (result.diagnostics.length > 0) { - console.warn(`[codegen-ts] Biome formatter: ${summarizeDiagnostics(result.diagnostics)}`); - return content; - } - return result.content; - } catch (err) { - console.warn(`[codegen-ts] Biome formatter error: ${(err as Error).message}`); - return content; - } + return content; } diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 3c6debf9f2..b6a2d2ea7c 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -14,7 +14,7 @@ export interface EmittedFile { path: string; /** The file's final contents, in any format — TypeScript, JSON, YAML, SQL, Markdown. * The runner writes it as given: it neither formats it nor adds a header, so a - * generator that wants either does it itself (`formatTs`, `GENERATED_HEADER`). */ + * generator that wants a header does it itself (`GENERATED_HEADER`). */ content: string; /** Set by the runner from generator.name — generators should not set this. */ generatedBy?: string; diff --git a/server/typescript/packages/codegen-ts/src/generators/barrel.ts b/server/typescript/packages/codegen-ts/src/generators/barrel.ts index 1638d0572c..4f324627ac 100644 --- a/server/typescript/packages/codegen-ts/src/generators/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/generators/barrel.ts @@ -1,6 +1,5 @@ import { oncePerRun, type Generator, type GeneratorFactory } from "../generator.js"; import { renderBarrel } from "../templates/barrel.js"; -import { formatTs } from "../format.js"; import { effectivePackage } from "../docs-paths.js"; import { claimBarrelNames } from "../naming/name-claims.js"; @@ -16,14 +15,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), ctx.renderContext!.extStyle, ctx.renderContext!.selfTarget, ctx.renderContext!.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts index f4500bd408..f33d1799e8 100644 --- a/server/typescript/packages/codegen-ts/src/generators/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/callable-file.ts @@ -9,7 +9,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type Generator, type GeneratorFactory } from "../generator.js"; import { renderCallableFile, isCallableEntity } from "../templates/callable-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; @@ -34,7 +33,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts index d6eb4e4eb7..1d4c3f8534 100644 --- a/server/typescript/packages/codegen-ts/src/generators/entity-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/entity-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { perEntity, type EmittedFile, type GenContext, type Generator, type GeneratorFactory } from "../generator.js"; import { renderEntityFile } from "../templates/entity-file.js"; import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isAbstract } from "../instance-artifacts.js"; import { effectivePackage } from "../docs-paths.js"; @@ -45,7 +44,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntityFile(entity, ctx.renderContext, { allowlists })), + content: renderEntityFile(entity, ctx.renderContext, { allowlists }), }; }); @@ -67,7 +66,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator if (sharedEnums !== null) { files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, - content: await formatTs(sharedEnums), + content: sharedEnums, }); } return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts index 94debcf794..a9fc2e300c 100644 --- a/server/typescript/packages/codegen-ts/src/generators/queries-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/queries-file.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderQueriesFile } from "../templates/queries-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { claimModuleNames } from "../naming/name-claims.js"; @@ -52,7 +51,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueriesFile(entity, ctx.renderContext)), + content: renderQueriesFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts index 347504b4cd..1065766bce 100644 --- a/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/report-export-file.ts @@ -2,7 +2,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GenContext, EmittedFile } from "../generator.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; -import { formatTs } from "../format.js"; import { isReport } from "../source-detect.js"; import { DEFAULT_EXPORT_MAX_ROWS, DEFAULT_XML_NULLS, EXPORT_WRITERS_BASENAME, @@ -58,14 +57,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts index 2c5956e61c..eaf551807d 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file-hono.ts @@ -3,7 +3,6 @@ import { perEntity, type Generator, type GeneratorFactory } from "../generator.j import { renderRoutesFileHono } from "../templates/routes-file-hono.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { isTphSubtype } from "../tph.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; @@ -105,7 +104,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -120,7 +119,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFileHono(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts index f0a871f20a..cef0c6d9f5 100644 --- a/server/typescript/packages/codegen-ts/src/generators/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/routes-file.ts @@ -4,7 +4,6 @@ import { renderRoutesFile } from "../templates/routes-file.js"; import { isTphSubtype } from "../tph.js"; import { servesReadApi } from "../api-surface.js"; import { renderRoutesIndex, routesIndexFileName } from "../templates/routes-index.js"; -import { formatTs } from "../format.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { resolveExpose, type ExposeOption } from "../routes-expose.js"; import { effectivePackage } from "../docs-paths.js"; @@ -63,7 +62,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator claimRouteSegment(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesFile(entity, ctx.renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -83,7 +82,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index e15436e26b..4cb6741bb4 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -112,6 +112,7 @@ export { CodegenError } from "./errors.js"; export { GENERATED_HEADER, GENERATED_EDIT_NOTE, NAMES_FILE_SUFFIX, DEFAULT_OUT_DIR, RETIRED_CODEGEN_ATTRS, sidecarLine, type RetiredCodegenAttr } from "./constants.js"; export { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; +// Kept so a generator copied out in 1.2 still loads; generation runs no formatter (format.ts). export { formatTs } from "./format.js"; export { pluralize, columnNameFromField, tableNameFromEntity, viewNameFromProjection, routesHandlerName, hookListNameSegment } from "./naming.js"; diff --git a/server/typescript/packages/codegen-ts/src/reference/barrel.ts b/server/typescript/packages/codegen-ts/src/reference/barrel.ts index 2c82677ac3..001cf7953d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/barrel.ts +++ b/server/typescript/packages/codegen-ts/src/reference/barrel.ts @@ -24,7 +24,6 @@ import { type ExtStyle, type ResolvedTarget, barrelModuleSpecifier, - formatTs, GENERATED_HEADER, GENERATED_EDIT_NOTE, effectivePackage, @@ -66,14 +65,12 @@ export const barrel = function barrel(opts?: BarrelOpts): Generator { for (const e of entities) claimBarrelNames(ctx, e); return { path: "index.ts", - content: await formatTs( - renderBarrel( + content: renderBarrel( entities.map((e) => ({ name: e.name, package: effectivePackage(e) })), rc.extStyle, rc.selfTarget, rc.entityModuleTarget, ), - ), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/callable.ts b/server/typescript/packages/codegen-ts/src/reference/callable.ts index 2faeaf9c8a..4cc0b17a8d 100644 --- a/server/typescript/packages/codegen-ts/src/reference/callable.ts +++ b/server/typescript/packages/codegen-ts/src/reference/callable.ts @@ -31,7 +31,6 @@ import { perEntity, type Generator, type GeneratorFactory, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -61,7 +60,7 @@ export const callableFile = function callableFile(opts?: CallableFileOpts): Gene effectivePackage(entity), `${entity.name}.callable.ts`, ), - content: await formatTs(renderCallableFile(entity, ctx.renderContext)), + content: renderCallableFile(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/entity.ts b/server/typescript/packages/codegen-ts/src/reference/entity.ts index 926da1c687..4931111a28 100644 --- a/server/typescript/packages/codegen-ts/src/reference/entity.ts +++ b/server/typescript/packages/codegen-ts/src/reference/entity.ts @@ -54,7 +54,6 @@ import { isWriteThrough, isAbstract, hasWritableRdbSource, - formatTs, ownedRuntimeImport, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, @@ -188,7 +187,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, renderContext, { allowlists })), + content: renderEntity(entity, renderContext, { allowlists }), }; }); @@ -209,7 +208,7 @@ export const entityFile = function entityFile(opts?: EntityFileOpts): Generator ctx.select !== undefined ? { select: ctx.select } : undefined, ); if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); + files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); } return files; }, diff --git a/server/typescript/packages/codegen-ts/src/reference/queries.ts b/server/typescript/packages/codegen-ts/src/reference/queries.ts index 8d03e08142..44617b4c61 100644 --- a/server/typescript/packages/codegen-ts/src/reference/queries.ts +++ b/server/typescript/packages/codegen-ts/src/reference/queries.ts @@ -43,7 +43,6 @@ import { isProjection, isWriteThrough, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, GENERATED_HEADER, @@ -173,7 +172,7 @@ export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generat claimModuleNames(ctx, entity); return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), + content: renderQueries(entity, ctx.renderContext), }; }), }; diff --git a/server/typescript/packages/codegen-ts/src/reference/report-export.ts b/server/typescript/packages/codegen-ts/src/reference/report-export.ts index 77ec25579c..0b6a881dca 100644 --- a/server/typescript/packages/codegen-ts/src/reference/report-export.ts +++ b/server/typescript/packages/codegen-ts/src/reference/report-export.ts @@ -29,7 +29,6 @@ import { effectivePackage, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, - formatTs, isCredentialField, isReport, relativeModuleSpecifier, @@ -247,14 +246,14 @@ export function reportExport(opts?: ReportExportOpts): Generator { const reports = ctx.entities.filter(ctx.matches).filter(isReport); if (reports.length === 0) return []; const out: EmittedFile[] = [ - { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: await formatTs(renderExportWriters(emit)) }, + { path: `${EXPORT_WRITERS_BASENAME}.ts`, content: renderExportWriters(emit) }, ]; // One module per report `meta gen ` named; the writers above serve them all. for (const report of reports.filter((r) => ctx.selected?.(r) ?? true)) { const pkg = effectivePackage(report); out.push({ path: entityOutputPath(layout, pkg, `${report.name}.export.ts`), - content: await formatTs(renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit)), + content: renderReportExportModule(report, { selfTarget, pkg, extStyle }, emit), }); } return out; diff --git a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts index 10910a4297..e61313e354 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes-hono.ts @@ -63,7 +63,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -183,7 +182,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -238,7 +236,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, @@ -338,7 +335,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("hono"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "hono")), + content: renderRoutesIndex(matched, ctx.renderContext, "hono"), }]; }, }; @@ -358,7 +355,7 @@ export const routesFileHono = function routesFileHono(opts?: RoutesFileHonoOpts) effectivePackage(entity), `${entity.name}.routes.hono.ts`, ), - content: await formatTs(renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutesHono(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/reference/routes.ts b/server/typescript/packages/codegen-ts/src/reference/routes.ts index 16837743da..3117986622 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes.ts @@ -73,7 +73,6 @@ import { writeDeniedColumnsLine, knownFieldsLine, servesReadApi, - formatTs, DEFAULT_OUTPUT_LAYOUT, entityOutputPath, effectivePackage, @@ -770,7 +769,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator }; return { path: entityOutputPath(ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT, effectivePackage(entity), `${entity.name}.routes.ts`), - content: await formatTs(renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows)), + content: renderRoutes(entity, renderContext, resolveExpose(entity, opts?.expose), opts?.reportMaxRows), }; }); const generator: Generator = { @@ -796,7 +795,7 @@ export const routesFile = function routesFile(opts?: RoutesFileOpts): Generator if (matched.length === 0 || !ctx.renderContext) return files; return [...files, { path: routesIndexFileName("fastify"), - content: await formatTs(renderRoutesIndex(matched, ctx.renderContext, "fastify")), + content: renderRoutesIndex(matched, ctx.renderContext, "fastify"), }]; }, }; diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 42b830eebc..6a9052139c 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -48,7 +48,7 @@ interface CheckEntry { name: Code; expr: Code; key: string; text: string } * - relations() block at the end of the section * * Returns a Code object so ts-poet can deduplicate imports when this composes - * with the rest of the entity file. Biome formatting runs after composition. + * with the rest of the entity file. */ export function renderDrizzleSchema( obj: MetaObject, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts index 6c00f30691..8231b343b2 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-file-hono.ts @@ -135,7 +135,6 @@ import { * ${runtimeSpec}. ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: false })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountReadOnlyCrudRoutesSym}({ app, @@ -190,7 +189,6 @@ import { * (auth, side effects, etc.). ${authSeamJsDoc({ framework: "hono", handlerName, mountPathExpr: authPathExpr, narrowable: true })} */ -// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables export function ${handlerName}(app: ${HonoSym}, deps: { db: unknown }): void { ${mountCrudRoutesSym}({ app, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts index 40918d6c70..a36408aa23 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-index.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-index.ts @@ -55,7 +55,6 @@ export function renderRoutesIndex( " * on the mount paths before calling this. An entity that needs a row-ownership rule", " * should not be registered open: narrow its routes with `expose` or hand-write them.", " */", - "// biome-ignore lint/suspicious/noExplicitAny: consumer-defined Hono bindings/variables", "export function registerAllRoutes(app: Hono, deps: { db: unknown }): void {", ...sorted.map((e) => ` ${handler(e)}(app, deps);`), "}", diff --git a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts index 01f3ef64e9..e039ce477f 100644 --- a/server/typescript/packages/codegen-ts/src/templates/view-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/view-decl.ts @@ -111,7 +111,7 @@ function viewColumnLine( : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 - ? `, ${JSON.stringify(spec.fnOptions)}` + ? `, ${optionsLiteral(spec.fnOptions)}` : ""; // #204 — of the table modifiers, only `.array()` (postgres native array element // typing) and `.notNull()` (shapes the SELECT type) carry to an existing view; @@ -252,3 +252,12 @@ export function renderViewReadZodObject(fields: readonly MetaField[], opts: View ${joinCode(lines, { on: ",\n" })} })`; } + +/** A column's options as a JS object literal: `{ length: 200 }`, not JSON's `{ "length": 200 }`. */ +function optionsLiteral(options: Record): string { + const entries = Object.entries(options).map(([key, value]) => { + const name = /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key); + return `${name}: ${JSON.stringify(value)}`; + }); + return `{ ${entries.join(", ")} }`; +} diff --git a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts index 9738b0eff4..79be12d2ff 100644 --- a/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-ui-page-parity.test.ts @@ -268,7 +268,7 @@ function evaluatePath(expr: string, ownPaths: ReadonlyMap): stri } /** - * Every mount in one emitted routes file. A line-oriented walk over the biome-formatted + * Every mount in one emitted routes file. A line-oriented walk over the emitted * output: a mount opens on `mount…CrudRoutes({` and closes on `});`, and the three * properties read are each one line. The count of openers is asserted against the * mounts recovered, so a formatting change that moved a property onto the opener line diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index fe5742c441..cc1773e117 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -391,6 +391,41 @@ describe("what a project's run changes", () => { }); }); +describe("the document states what the routes do beyond the happy path", () => { + type Operation = { description?: string; parameters?: Array<{ name: string; description?: string; schema?: JsonDoc }>; requestBody?: { description?: string }; responses?: Record }; + const operation = (doc: JsonDoc, path: string, method: string): Operation => + (((doc["paths"] as JsonDoc)[path] as JsonDoc)[method]) as Operation; + const document = async (name: string): Promise => jsonAt(await emit(corpusCase(name), [openApiFile({ title: "t", version: "1" })]), "openapi.json"); + + test("a project's page size is the limit's default and maximum, and absent it states neither", async () => { + const limitOf = (doc: JsonDoc) => operation(doc, "/api/authors", "get").parameters?.find((p) => p.name === "limit")?.schema; + expect(limitOf(await document("api-settings"))).toEqual({ type: "integer", minimum: 0, maximum: 1000, default: 50 }); + expect(limitOf(await document("blog"))).toEqual({ type: "integer", minimum: 0 }); + }); + + test("a write says an undeclared key is refused by default, and dropped under api.unknownFields: drop", async () => { + const reject = operation(await document("blog"), "/api/authors", "post"); + expect(reject.requestBody?.description).toContain("unknown_fields"); + expect(reject.responses?.["400"]?.description).toContain("unknown_fields"); + const drop = operation(await document("api-settings-drop"), "/api/authors", "post"); + expect(drop.requestBody?.description).toContain("dropped"); + expect(drop.responses?.["400"]?.description).not.toContain("unknown_fields"); + expect(drop.responses?.["400"]?.description).toContain("validation"); + }); + + test("the error envelope carries the validation issues and the undeclared keys", async () => { + const error = ((await document("blog"))["components"] as { schemas: Record }> }).schemas["ApiError"]; + expect(Object.keys(error?.properties ?? {})).toEqual(["error", "message", "field", "fields", "issues", "maxLimit"]); + }); + + test("a read-only resource says a write answers 405, though 405 is no operation", async () => { + const doc = await document("projection"); + expect(operation(doc, "/api/invoice_ledgers", "get").description).toContain("405"); + expect(operation(doc, "/api/invoices", "get").description).toBeUndefined(); + expect(Object.keys((doc["paths"] as JsonDoc)["/api/invoice_ledgers"] as JsonDoc)).toEqual(["get"]); + }); +}); + describe("the reference copies", () => { for (const c of contractCases()) { if (c.name.startsWith("error-")) continue; diff --git a/server/typescript/packages/codegen-ts/test/format.test.ts b/server/typescript/packages/codegen-ts/test/format.test.ts index 62b643b6fd..5155e62e3c 100644 --- a/server/typescript/packages/codegen-ts/test/format.test.ts +++ b/server/typescript/packages/codegen-ts/test/format.test.ts @@ -1,19 +1,28 @@ import { describe, test, expect } from "bun:test"; import { formatTs } from "../src/format.js"; +import { formatTs as formatTsFromEntry } from "../src/index.js"; +// Generation runs no formatter. `formatTs` stays exported only so a generator copied out +// with `meta eject` in 1.2 (which imports it from the package entry) still loads. describe("formatTs", () => { - test("formats unformatted TS into idiomatic Biome style", async () => { + test("is exported from the package entry, for owned 1.2 generator copies", () => { + expect(formatTsFromEntry).toBe(formatTs); + }); + + test("returns its input unchanged", async () => { const ugly = "import {x} from'y';export const a={b:1,c:2}"; - const formatted = await formatTs(ugly); - expect(formatted).not.toBe(ugly); - expect(formatted).toContain("import"); - expect(formatted.length).toBeGreaterThan(ugly.length); + expect(await formatTs(ugly)).toBe(ugly); }); - test("returns input unchanged on Biome error (with warning logged)", async () => { - const broken = "import { from 'x';"; // syntax error - const formatted = await formatTs(broken); - // Per design §11: format error → log warning, return unformatted - expect(typeof formatted).toBe("string"); + test("returns invalid TypeScript unchanged, with nothing logged", async () => { + const warnings: unknown[] = []; + const warn = console.warn; + console.warn = (...args: unknown[]) => warnings.push(args); + try { + expect(await formatTs("import { from 'x';")).toBe("import { from 'x';"); + } finally { + console.warn = warn; + } + expect(warnings).toEqual([]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts index c28721fad7..0041f533ab 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.queries.ts @@ -5,27 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -35,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { @@ -67,17 +43,11 @@ export async function deleteTagById(db: Db, id: number): Promise { const deleted = await db.delete(tags).where(eq(tags.id, id)).returning(); return deleted.length > 0; } -export async function findTagsByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findTagsByCustomer(db: Db, customerId: number): Promise { return db.select().from(tags).where(eq(tags.customerId, customerId)); } -export async function findTagsByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findTagsByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts index c427da5bcc..9659dd6b2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "../db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts index e403eda9de..a1cdad130f 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/Tag.ts @@ -1,17 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { TagNames } from "./Tag.names"; import { customers } from "./shop/users/Customer"; @@ -19,23 +10,16 @@ import { customers } from "./shop/users/Customer"; export const tags = sqliteTable(TagNames.sources.primary.table, { id: integer(TagNames.fields.id.column).primaryKey({ autoIncrement: true }), label: text(TagNames.fields.label.column).notNull(), - customerId: integer(TagNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), + customerId: integer(TagNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), }); -export const tagsRelations = relations(tags, ({ one }) => ({ - customer: one(customers, { - fields: [tags.customerId], - references: [customers.id], - }), -})); +export const tagsRelations = relations( + tags, + ({ one }) => ({ customer: one(customers, { fields: [tags.customerId], references: [customers.id] }) }), +); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - label: z.string().min(1).max(100), - customerId: z.number().int(), -}); +export const TagInsertSchema = z.object({ label: z.string().min(1).max(100), customerId: z.number().int() }); export const TagUpdateSchema = z.object({ label: z.string().min(1).max(100).optional(), @@ -82,10 +66,7 @@ export const Tag = { label: "Label", view: "text", htmlType: "text", - rules: { - required: "Label is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Label is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, customerId: { name: "customerId", @@ -101,10 +82,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts index 559cb87f7c..bcfbfe2d2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.queries.ts @@ -5,31 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Order, - OrderInsertSchema, - type OrderPatch, - orders, - OrderUpdateSchema, -} from "./Order"; +import { type Order, OrderInsertSchema, type OrderPatch, orders, OrderUpdateSchema } from "./Order"; export async function findOrderById(db: Db, id: number): Promise { - const [order] = await db - .select() - .from(orders) - .where(eq(orders.id, id)) - .limit(1); + const [order] = await db.select().from(orders).where(eq(orders.id, id)).limit(1); return order ?? null; } -export async function listOrders( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listOrders(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(orders).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -39,30 +22,19 @@ export async function listOrders( } return q; } -export async function createOrder( - db: Db, - data: z.input, -): Promise { +export async function createOrder(db: Db, data: z.input): Promise { const validated = OrderInsertSchema.parse(data); const [order] = await db.insert(orders).values(validated).returning(); return order!; } -export async function updateOrder( - db: Db, - id: number, - patch: OrderPatch, -): Promise { +export async function updateOrder(db: Db, id: number, patch: OrderPatch): Promise { const validated = OrderUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findOrderById(db, id); } - const [order] = await db - .update(orders) - .set(validated) - .where(eq(orders.id, id)) - .returning(); + const [order] = await db.update(orders).set(validated).where(eq(orders.id, id)).returning(); return order ?? null; } export async function deleteOrderById(db: Db, id: number): Promise { @@ -71,36 +43,21 @@ export async function deleteOrderById(db: Db, id: number): Promise { const deleted = await db.delete(orders).where(eq(orders.id, id)).returning(); return deleted.length > 0; } -export async function findOrdersByCustomer( - db: Db, - customerId: number, -): Promise { +export async function findOrdersByCustomer(db: Db, customerId: number): Promise { return db.select().from(orders).where(eq(orders.customerId, customerId)); } -export async function findOrdersByCustomerIn( - db: Db, - customerIds: number[], -): Promise { +export async function findOrdersByCustomerIn(db: Db, customerIds: number[]): Promise { if (customerIds.length === 0) { return []; } - return db - .select() - .from(orders) - .where(inArray(orders.customerId, customerIds)); + return db.select().from(orders).where(inArray(orders.customerId, customerIds)); } -export async function findOrdersByProduct( - db: Db, - productId: number, -): Promise { +export async function findOrdersByProduct(db: Db, productId: number): Promise { return db.select().from(orders).where(eq(orders.productId, productId)); } -export async function findOrdersByProductIn( - db: Db, - productIds: number[], -): Promise { +export async function findOrdersByProductIn(db: Db, productIds: number[]): Promise { if (productIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts index 6fe09bbd7a..0e3a90eb9c 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. import { db } from "../../../db"; -import { - Order, - OrderFilterAllowlist, - OrderInsertSchema, - orders, - OrderSortAllowlist, - OrderUpdateSchema, -} from "./Order"; +import { Order, OrderFilterAllowlist, OrderInsertSchema, orders, OrderSortAllowlist, OrderUpdateSchema } from "./Order"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts index c3b8a0b08e..679dc1380b 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Order.ts @@ -1,16 +1,8 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Order (shop::commerce::Order) // Extend in your own module (e.g. Order.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { customers } from "../users/Customer"; import { OrderNames } from "./Order.names"; @@ -18,24 +10,17 @@ import { products } from "./Product"; export const orders = sqliteTable(OrderNames.sources.primary.table, { id: integer(OrderNames.fields.id.column).primaryKey({ autoIncrement: true }), - customerId: integer(OrderNames.fields.customerId.column) - .notNull() - .references((): AnySQLiteColumn => customers.id), - productId: integer(OrderNames.fields.productId.column) - .notNull() - .references((): AnySQLiteColumn => products.id), + customerId: integer(OrderNames.fields.customerId.column).notNull().references((): AnySQLiteColumn => customers.id), + productId: integer(OrderNames.fields.productId.column).notNull().references((): AnySQLiteColumn => products.id), quantity: integer(OrderNames.fields.quantity.column).notNull(), }); -export const ordersRelations = relations(orders, ({ one }) => ({ - customer: one(customers, { - fields: [orders.customerId], - references: [customers.id], +export const ordersRelations = relations( + orders, + ({ one }) => ({ + customer: one(customers, { fields: [orders.customerId], references: [customers.id] }), + product: one(products, { fields: [orders.productId], references: [products.id] }), }), - product: one(products, { - fields: [orders.productId], - references: [products.id], - }), -})); +); export type Order = InferSelectModel; export type OrderInsert = InferInsertModel; export type OrderUpdate = Partial; @@ -114,10 +99,4 @@ export const OrderFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const OrderSortAllowlist = {} as const satisfies SortAllowlist; -export type OrderFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: OrderFilter[]; - and?: OrderFilter[]; -}; +export type OrderFilter = { limit?: number; offset?: number; sort?: string; or?: OrderFilter[]; and?: OrderFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts index 5dac95be94..35f904c45e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.queries.ts @@ -5,34 +5,14 @@ import { eq, inArray } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Product, - ProductInsertSchema, - type ProductPatch, - products, - ProductUpdateSchema, -} from "./Product"; -export async function findProductById( - db: Db, - id: number, -): Promise { - const [product] = await db - .select() - .from(products) - .where(eq(products.id, id)) - .limit(1); +import { type Product, ProductInsertSchema, type ProductPatch, products, ProductUpdateSchema } from "./Product"; +export async function findProductById(db: Db, id: number): Promise { + const [product] = await db.select().from(products).where(eq(products.id, id)).limit(1); return product ?? null; } -export async function listProducts( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listProducts(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(products).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,52 +22,32 @@ export async function listProducts( } return q; } -export async function createProduct( - db: Db, - data: z.input, -): Promise { +export async function createProduct(db: Db, data: z.input): Promise { const validated = ProductInsertSchema.parse(data); const [product] = await db.insert(products).values(validated).returning(); return product!; } -export async function updateProduct( - db: Db, - id: number, - patch: ProductPatch, -): Promise { +export async function updateProduct(db: Db, id: number, patch: ProductPatch): Promise { const validated = ProductUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProductById(db, id); } - const [product] = await db - .update(products) - .set(validated) - .where(eq(products.id, id)) - .returning(); + const [product] = await db.update(products).set(validated).where(eq(products.id, id)).returning(); return product ?? null; } export async function deleteProductById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(products) - .where(eq(products.id, id)) - .returning(); + const deleted = await db.delete(products).where(eq(products.id, id)).returning(); return deleted.length > 0; } -export async function findProductsByTag( - db: Db, - tagId: number, -): Promise { +export async function findProductsByTag(db: Db, tagId: number): Promise { return db.select().from(products).where(eq(products.tagId, tagId)); } -export async function findProductsByTagIn( - db: Db, - tagIds: number[], -): Promise { +export async function findProductsByTagIn(db: Db, tagIds: number[]): Promise { if (tagIds.length === 0) { return []; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts index 9a0149a188..3ab0fea323 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/commerce/Product.ts @@ -1,40 +1,25 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Product (shop::commerce::Product) // Extend in your own module (e.g. Product.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnySQLiteColumn, - integer, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnySQLiteColumn, integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; import { z } from "zod"; import { tags } from "../../Tag"; import { ProductNames } from "./Product.names"; export const products = sqliteTable(ProductNames.sources.primary.table, { - id: integer(ProductNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(ProductNames.fields.id.column).primaryKey({ autoIncrement: true }), name: text(ProductNames.fields.name.column).notNull(), - tagId: integer(ProductNames.fields.tagId.column) - .notNull() - .references((): AnySQLiteColumn => tags.id), + tagId: integer(ProductNames.fields.tagId.column).notNull().references((): AnySQLiteColumn => tags.id), }); -export const productsRelations = relations(products, ({ one }) => ({ - tag: one(tags, { fields: [products.tagId], references: [tags.id] }), -})); +export const productsRelations = relations( + products, + ({ one }) => ({ tag: one(tags, { fields: [products.tagId], references: [tags.id] }) }), +); export type Product = InferSelectModel; export type ProductInsert = InferInsertModel; export type ProductUpdate = Partial; -export const ProductInsertSchema = z.object({ - name: z.string().min(1).max(200), - tagId: z.number().int(), -}); +export const ProductInsertSchema = z.object({ name: z.string().min(1).max(200), tagId: z.number().int() }); export const ProductUpdateSchema = z.object({ name: z.string().min(1).max(200).optional(), @@ -81,10 +66,7 @@ export const Product = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, tagId: { name: "tagId", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts index 89fe94c91f..788988abeb 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.queries.ts @@ -5,34 +5,14 @@ import { eq } from "drizzle-orm"; import type { z } from "zod"; import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core"; -type Db = BaseSQLiteDatabase< - "sync" | "async", - unknown, - Record ->; +type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>; -import { - type Customer, - CustomerInsertSchema, - type CustomerPatch, - customers, - CustomerUpdateSchema, -} from "./Customer"; -export async function findCustomerById( - db: Db, - id: number, -): Promise { - const [customer] = await db - .select() - .from(customers) - .where(eq(customers.id, id)) - .limit(1); +import { type Customer, CustomerInsertSchema, type CustomerPatch, customers, CustomerUpdateSchema } from "./Customer"; +export async function findCustomerById(db: Db, id: number): Promise { + const [customer] = await db.select().from(customers).where(eq(customers.id, id)).limit(1); return customer ?? null; } -export async function listCustomers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listCustomers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(customers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -42,38 +22,24 @@ export async function listCustomers( } return q; } -export async function createCustomer( - db: Db, - data: z.input, -): Promise { +export async function createCustomer(db: Db, data: z.input): Promise { const validated = CustomerInsertSchema.parse(data); const [customer] = await db.insert(customers).values(validated).returning(); return customer!; } -export async function updateCustomer( - db: Db, - id: number, - patch: CustomerPatch, -): Promise { +export async function updateCustomer(db: Db, id: number, patch: CustomerPatch): Promise { const validated = CustomerUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findCustomerById(db, id); } - const [customer] = await db - .update(customers) - .set(validated) - .where(eq(customers.id, id)) - .returning(); + const [customer] = await db.update(customers).set(validated).where(eq(customers.id, id)).returning(); return customer ?? null; } export async function deleteCustomerById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(customers) - .where(eq(customers.id, id)) - .returning(); + const deleted = await db.delete(customers).where(eq(customers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts index cae74ba52f..ba7db33bb8 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/package/shop/users/Customer.ts @@ -7,21 +7,15 @@ import { z } from "zod"; import { CustomerNames } from "./Customer.names"; export const customers = sqliteTable(CustomerNames.sources.primary.table, { - id: integer(CustomerNames.fields.id.column).primaryKey({ - autoIncrement: true, - }), + id: integer(CustomerNames.fields.id.column).primaryKey({ autoIncrement: true }), email: text(CustomerNames.fields.email.column).notNull(), }); export type Customer = InferSelectModel; export type CustomerInsert = InferInsertModel; export type CustomerUpdate = Partial; -export const CustomerInsertSchema = z.object({ - email: z.string().min(1).max(255), -}); +export const CustomerInsertSchema = z.object({ email: z.string().min(1).max(255) }); -export const CustomerUpdateSchema = z.object({ - email: z.string().min(1).max(255).optional(), -}); +export const CustomerUpdateSchema = z.object({ email: z.string().min(1).max(255).optional() }); /** Typed create shape for Customer: the insert schema's INPUT (pre-transform) type. A * renamed/dropped/misspelt field is a compile error at every `createCustomer` call site; @@ -63,10 +57,7 @@ export const Customer = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts index f3e8bda7c5..f4b4ee53ee 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Exercise, - ExerciseInsertSchema, - type ExercisePatch, - exercises, - ExerciseUpdateSchema, -} from "./Exercise"; -export async function findExerciseById( - db: Db, - id: number, -): Promise { - const [exercise] = await db - .select() - .from(exercises) - .where(eq(exercises.id, id)) - .limit(1); +import { type Exercise, ExerciseInsertSchema, type ExercisePatch, exercises, ExerciseUpdateSchema } from "./Exercise"; +export async function findExerciseById(db: Db, id: number): Promise { + const [exercise] = await db.select().from(exercises).where(eq(exercises.id, id)).limit(1); return exercise ?? null; } -export async function listExercises( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listExercises(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(exercises).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,57 +22,34 @@ export async function listExercises( } return q; } -export async function createExercise( - db: Db, - data: z.input, -): Promise { +export async function createExercise(db: Db, data: z.input): Promise { const validated = ExerciseInsertSchema.parse(data); const [exercise] = await db.insert(exercises).values(validated).returning(); return exercise!; } -export async function updateExercise( - db: Db, - id: number, - patch: ExercisePatch, -): Promise { +export async function updateExercise(db: Db, id: number, patch: ExercisePatch): Promise { const validated = ExerciseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findExerciseById(db, id); } - const [exercise] = await db - .update(exercises) - .set(validated) - .where(eq(exercises.id, id)) - .returning(); + const [exercise] = await db.update(exercises).set(validated).where(eq(exercises.id, id)).returning(); return exercise ?? null; } export async function deleteExerciseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(exercises) - .where(eq(exercises.id, id)) - .returning(); + const deleted = await db.delete(exercises).where(eq(exercises.id, id)).returning(); return deleted.length > 0; } -export async function findExercisesByWorkout( - db: Db, - workoutId: number, -): Promise { +export async function findExercisesByWorkout(db: Db, workoutId: number): Promise { return db.select().from(exercises).where(eq(exercises.workoutId, workoutId)); } -export async function findExercisesByWorkoutIn( - db: Db, - workoutIds: number[], -): Promise { +export async function findExercisesByWorkoutIn(db: Db, workoutIds: number[]): Promise { if (workoutIds.length === 0) { return []; } - return db - .select() - .from(exercises) - .where(inArray(exercises.workoutId, workoutIds)); + return db.select().from(exercises).where(inArray(exercises.workoutId, workoutIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts index e2770d23c9..b06b1cd536 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Exercise.ts @@ -1,40 +1,23 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Exercise (Exercise) // Extend in your own module (e.g. Exercise.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - text, - varchar, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, text, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; import { workouts } from "./Workout"; export const exercises = pgTable("exercises", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - workoutId: bigint("workout_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => workouts.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + workoutId: bigint("workout_id", { mode: "number" }).notNull().references((): AnyPgColumn => workouts.id), name: varchar("name", { length: 200 }).notNull(), sets: integer("sets"), reps: integer("reps"), notes: text("notes"), }); -export const exercisesRelations = relations(exercises, ({ one }) => ({ - workout: one(workouts, { - fields: [exercises.workoutId], - references: [workouts.id], - }), -})); +export const exercisesRelations = relations( + exercises, + ({ one }) => ({ workout: one(workouts, { fields: [exercises.workoutId], references: [workouts.id] }) }), +); export type Exercise = InferSelectModel; export type ExerciseInsert = InferInsertModel; export type ExerciseUpdate = Partial; @@ -101,10 +84,7 @@ export const Exercise = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, sets: { name: "sets", label: "Sets", view: "number", htmlType: "number" }, reps: { name: "reps", label: "Reps", view: "number", htmlType: "number" }, diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts index 41d300bf52..885445757e 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Program, - ProgramInsertSchema, - type ProgramPatch, - programs, - ProgramUpdateSchema, -} from "./Program"; -export async function findProgramById( - db: Db, - id: number, -): Promise { - const [program] = await db - .select() - .from(programs) - .where(eq(programs.id, id)) - .limit(1); +import { type Program, ProgramInsertSchema, type ProgramPatch, programs, ProgramUpdateSchema } from "./Program"; +export async function findProgramById(db: Db, id: number): Promise { + const [program] = await db.select().from(programs).where(eq(programs.id, id)).limit(1); return program ?? null; } -export async function listPrograms( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(programs).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,38 +22,24 @@ export async function listPrograms( } return q; } -export async function createProgram( - db: Db, - data: z.input, -): Promise { +export async function createProgram(db: Db, data: z.input): Promise { const validated = ProgramInsertSchema.parse(data); const [program] = await db.insert(programs).values(validated).returning(); return program!; } -export async function updateProgram( - db: Db, - id: number, - patch: ProgramPatch, -): Promise { +export async function updateProgram(db: Db, id: number, patch: ProgramPatch): Promise { const validated = ProgramUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findProgramById(db, id); } - const [program] = await db - .update(programs) - .set(validated) - .where(eq(programs.id, id)) - .returning(); + const [program] = await db.update(programs).set(validated).where(eq(programs.id, id)).returning(); return program ?? null; } export async function deleteProgramById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(programs) - .where(eq(programs.id, id)) - .returning(); + const deleted = await db.delete(programs).where(eq(programs.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts index d9389baea0..1acd334a76 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.routes.ts @@ -45,14 +45,6 @@ export async function programRoutes(fastify: FastifyInstance) { filterAllowlist: ProgramFilterAllowlist, sortAllowlist: ProgramSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "slug", - "title", - "description", - "priceCents", - "isPublished", - "createdAt", - ], + knownFields: ["id", "slug", "title", "description", "priceCents", "isPublished", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts index aeffbeb30b..9432ac4f35 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Program.ts @@ -2,29 +2,17 @@ // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - integer, - pgTable, - text, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, integer, pgTable, text, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const programs = pgTable("programs", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), slug: varchar("slug", { length: 100 }).notNull().unique(), title: varchar("title", { length: 200 }).notNull(), description: text("description"), priceCents: integer("price_cents").notNull(), isPublished: boolean("is_published").notNull().default(false), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Program = InferSelectModel; export type ProgramInsert = InferInsertModel; @@ -36,10 +24,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -48,9 +34,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const ProgramInsertSchema = z.object({ @@ -59,14 +43,10 @@ export const ProgramInsertSchema = z.object({ description: z.string().optional(), priceCents: z.number().int(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const ProgramUpdateSchema = z.object({ @@ -75,14 +55,10 @@ export const ProgramUpdateSchema = z.object({ description: z.string().optional().nullable(), priceCents: z.number().int().optional(), isPublished: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Program: the insert schema's INPUT (pre-transform) type. A @@ -125,27 +101,16 @@ export const Program = { label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, title: { name: "title", label: "Title", view: "text", htmlType: "text", - rules: { - required: "Title is required", - maxLength: { value: 200, message: "Must be 200 characters or fewer" }, - }, - }, - description: { - name: "description", - label: "Description", - view: "text", - htmlType: "text", + rules: { required: "Title is required", maxLength: { value: 200, message: "Must be 200 characters or fewer" } }, }, + description: { name: "description", label: "Description", view: "text", htmlType: "text" }, priceCents: { name: "priceCents", label: "Price Cents", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts index ec01f4c9d5..905dbdf2e3 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.queries.ts @@ -7,28 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Purchase, - PurchaseInsertSchema, - type PurchasePatch, - purchases, - PurchaseUpdateSchema, -} from "./Purchase"; -export async function findPurchaseById( - db: Db, - id: number, -): Promise { - const [purchase] = await db - .select() - .from(purchases) - .where(eq(purchases.id, id)) - .limit(1); +import { type Purchase, PurchaseInsertSchema, type PurchasePatch, purchases, PurchaseUpdateSchema } from "./Purchase"; +export async function findPurchaseById(db: Db, id: number): Promise { + const [purchase] = await db.select().from(purchases).where(eq(purchases.id, id)).limit(1); return purchase ?? null; } -export async function listPurchases( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(purchases).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,79 +22,44 @@ export async function listPurchases( } return q; } -export async function createPurchase( - db: Db, - data: z.input, -): Promise { +export async function createPurchase(db: Db, data: z.input): Promise { const validated = PurchaseInsertSchema.parse(data); const [purchase] = await db.insert(purchases).values(validated).returning(); return purchase!; } -export async function updatePurchase( - db: Db, - id: number, - patch: PurchasePatch, -): Promise { +export async function updatePurchase(db: Db, id: number, patch: PurchasePatch): Promise { const validated = PurchaseUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findPurchaseById(db, id); } - const [purchase] = await db - .update(purchases) - .set(validated) - .where(eq(purchases.id, id)) - .returning(); + const [purchase] = await db.update(purchases).set(validated).where(eq(purchases.id, id)).returning(); return purchase ?? null; } export async function deletePurchaseById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(purchases) - .where(eq(purchases.id, id)) - .returning(); + const deleted = await db.delete(purchases).where(eq(purchases.id, id)).returning(); return deleted.length > 0; } -export async function findPurchasesBySubscriber( - db: Db, - subscriberId: number, -): Promise { - return db - .select() - .from(purchases) - .where(eq(purchases.subscriberId, subscriberId)); +export async function findPurchasesBySubscriber(db: Db, subscriberId: number): Promise { + return db.select().from(purchases).where(eq(purchases.subscriberId, subscriberId)); } -export async function findPurchasesBySubscriberIn( - db: Db, - subscriberIds: number[], -): Promise { +export async function findPurchasesBySubscriberIn(db: Db, subscriberIds: number[]): Promise { if (subscriberIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.subscriberId, subscriberIds)); + return db.select().from(purchases).where(inArray(purchases.subscriberId, subscriberIds)); } -export async function findPurchasesByProgram( - db: Db, - programId: number, -): Promise { +export async function findPurchasesByProgram(db: Db, programId: number): Promise { return db.select().from(purchases).where(eq(purchases.programId, programId)); } -export async function findPurchasesByProgramIn( - db: Db, - programIds: number[], -): Promise { +export async function findPurchasesByProgramIn(db: Db, programIds: number[]): Promise { if (programIds.length === 0) { return []; } - return db - .select() - .from(purchases) - .where(inArray(purchases.programId, programIds)); + return db.select().from(purchases).where(inArray(purchases.programId, programIds)); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts index 02caa5ee14..379b7a60b1 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.routes.ts @@ -45,12 +45,6 @@ export async function purchaseRoutes(fastify: FastifyInstance) { filterAllowlist: PurchaseFilterAllowlist, sortAllowlist: PurchaseSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "subscriberId", - "programId", - "amountCents", - "purchasedAt", - ], + knownFields: ["id", "subscriberId", "programId", "amountCents", "purchasedAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts index f74457a592..4e68280019 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Purchase.ts @@ -1,47 +1,26 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Purchase (Purchase) // Extend in your own module (e.g. Purchase.extra.ts) — nothing imports it for you. -import { - type InferInsertModel, - type InferSelectModel, - relations, -} from "drizzle-orm"; -import { - type AnyPgColumn, - bigint, - integer, - pgTable, - timestamp, -} from "drizzle-orm/pg-core"; +import { type InferInsertModel, type InferSelectModel, relations } from "drizzle-orm"; +import { type AnyPgColumn, bigint, integer, pgTable, timestamp } from "drizzle-orm/pg-core"; import { z } from "zod"; import { programs } from "./Program"; import { subscribers } from "./Subscriber"; export const purchases = pgTable("purchases", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), - subscriberId: bigint("subscriber_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => subscribers.id), - programId: bigint("program_id", { mode: "number" }) - .notNull() - .references((): AnyPgColumn => programs.id), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), + subscriberId: bigint("subscriber_id", { mode: "number" }).notNull().references((): AnyPgColumn => subscribers.id), + programId: bigint("program_id", { mode: "number" }).notNull().references((): AnyPgColumn => programs.id), amountCents: integer("amount_cents").notNull(), - purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + purchasedAt: timestamp("purchased_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); -export const purchasesRelations = relations(purchases, ({ one }) => ({ - subscriber: one(subscribers, { - fields: [purchases.subscriberId], - references: [subscribers.id], +export const purchasesRelations = relations( + purchases, + ({ one }) => ({ + subscriber: one(subscribers, { fields: [purchases.subscriberId], references: [subscribers.id] }), + program: one(programs, { fields: [purchases.programId], references: [programs.id] }), }), - program: one(programs, { - fields: [purchases.programId], - references: [programs.id], - }), -})); +); export type Purchase = InferSelectModel; export type PurchaseInsert = InferInsertModel; export type PurchaseUpdate = Partial; @@ -52,10 +31,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -64,37 +41,27 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const PurchaseInsertSchema = z.object({ subscriberId: z.number().int(), programId: z.number().int(), amountCents: z.number().int(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const PurchaseUpdateSchema = z.object({ subscriberId: z.number().int().optional(), programId: z.number().int().optional(), amountCents: z.number().int().optional(), - purchasedAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + purchasedAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Purchase: the insert schema's INPUT (pre-transform) type. A diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts index aa17a0b323..b91662c023 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.queries.ts @@ -14,21 +14,11 @@ import { subscribers, SubscriberUpdateSchema, } from "./Subscriber"; -export async function findSubscriberById( - db: Db, - id: number, -): Promise { - const [subscriber] = await db - .select() - .from(subscribers) - .where(eq(subscribers.id, id)) - .limit(1); +export async function findSubscriberById(db: Db, id: number): Promise { + const [subscriber] = await db.select().from(subscribers).where(eq(subscribers.id, id)).limit(1); return subscriber ?? null; } -export async function listSubscribers( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listSubscribers(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(subscribers).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -38,44 +28,24 @@ export async function listSubscribers( } return q; } -export async function createSubscriber( - db: Db, - data: z.input, -): Promise { +export async function createSubscriber(db: Db, data: z.input): Promise { const validated = SubscriberInsertSchema.parse(data); - const [subscriber] = await db - .insert(subscribers) - .values(validated) - .returning(); + const [subscriber] = await db.insert(subscribers).values(validated).returning(); return subscriber!; } -export async function updateSubscriber( - db: Db, - id: number, - patch: SubscriberPatch, -): Promise { +export async function updateSubscriber(db: Db, id: number, patch: SubscriberPatch): Promise { const validated = SubscriberUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findSubscriberById(db, id); } - const [subscriber] = await db - .update(subscribers) - .set(validated) - .where(eq(subscribers.id, id)) - .returning(); + const [subscriber] = await db.update(subscribers).set(validated).where(eq(subscribers.id, id)).returning(); return subscriber ?? null; } -export async function deleteSubscriberById( - db: Db, - id: number, -): Promise { +export async function deleteSubscriberById(db: Db, id: number): Promise { // Use .returning() unconditionally — supported on SQLite ≥3.35 (covers D1, libsql/Turso) // and Postgres. Result is an array of deleted rows; presence implies success. - const deleted = await db - .delete(subscribers) - .where(eq(subscribers.id, id)) - .returning(); + const deleted = await db.delete(subscribers).where(eq(subscribers.id, id)).returning(); return deleted.length > 0; } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts index 5b0664743b..5f8729600d 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.routes.ts @@ -45,13 +45,6 @@ export async function subscriberRoutes(fastify: FastifyInstance) { filterAllowlist: SubscriberFilterAllowlist, sortAllowlist: SubscriberSortAllowlist, dialect: "postgres", - knownFields: [ - "id", - "email", - "firstName", - "lastName", - "subscribed", - "createdAt", - ], + knownFields: ["id", "email", "firstName", "lastName", "subscribed", "createdAt"], }); } diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts index dee5dcdb18..125d01af10 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Subscriber.ts @@ -2,26 +2,16 @@ // Source metadata: Subscriber (Subscriber) // Extend in your own module (e.g. Subscriber.extra.ts) — nothing imports it for you. import type { InferInsertModel, InferSelectModel } from "drizzle-orm"; -import { - bigint, - boolean, - pgTable, - timestamp, - varchar, -} from "drizzle-orm/pg-core"; +import { bigint, boolean, pgTable, timestamp, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const subscribers = pgTable("subscribers", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), email: varchar("email", { length: 255 }).notNull().unique(), firstName: varchar("first_name", { length: 100 }).notNull(), lastName: varchar("last_name", { length: 100 }), subscribed: boolean("subscribed").notNull().default(true), - createdAt: timestamp("created_at", { mode: "string", withTimezone: true }) - .notNull() - .defaultNow(), + createdAt: timestamp("created_at", { mode: "string", withTimezone: true }).notNull().defaultNow(), }); export type Subscriber = InferSelectModel; export type SubscriberInsert = InferInsertModel; @@ -33,10 +23,8 @@ function utcIsoTimestamp(v: string): string { if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(v)) { return v; } - const m = - /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/.exec( - v, - ); + const m = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:([Zz])|([+-]\d{2}):?(\d{2})?)?)?$/ + .exec(v); if (m === null) { return v; } @@ -45,9 +33,7 @@ function utcIsoTimestamp(v: string): string { m[6] === undefined ? "Z" : `${m[6]}:${m[7] ?? "00"}` }`, ); - return Number.isNaN(t) - ? v - : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); + return Number.isNaN(t) ? v : new Date(t).toISOString().replace(/\.?0+Z$/, "Z"); } export const SubscriberInsertSchema = z.object({ @@ -55,14 +41,10 @@ export const SubscriberInsertSchema = z.object({ firstName: z.string().min(1).max(100), lastName: z.string().max(100).optional(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); export const SubscriberUpdateSchema = z.object({ @@ -70,14 +52,10 @@ export const SubscriberUpdateSchema = z.object({ firstName: z.string().min(1).max(100).optional(), lastName: z.string().max(100).optional().nullable(), subscribed: z.boolean().optional(), - createdAt: z - .string() - .regex( - /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, - "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", - ) - .transform(utcIsoTimestamp) - .optional(), + createdAt: z.string().regex( + /^(?:\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|02-(?:0[1-9]|1\d|2[0-8]))|(?:\d{2}(?:0[48]|[2468][048]|[13579][26])|(?:[02468][048]|[13579][26])00)-02-29)(?:[Tt ](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:[Zz]|[+-](?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?$/, + "must be an ISO 8601 timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", + ).transform(utcIsoTimestamp).optional(), }); /** Typed create shape for Subscriber: the insert schema's INPUT (pre-transform) type. A @@ -120,10 +98,7 @@ export const Subscriber = { label: "Email", view: "text", htmlType: "text", - rules: { - required: "Email is required", - maxLength: { value: 255, message: "Must be 255 characters or fewer" }, - }, + rules: { required: "Email is required", maxLength: { value: 255, message: "Must be 255 characters or fewer" } }, }, firstName: { name: "firstName", @@ -140,9 +115,7 @@ export const Subscriber = { label: "Last Name", view: "text", htmlType: "text", - rules: { - maxLength: { value: 100, message: "Must be 100 characters or fewer" }, - }, + rules: { maxLength: { value: 100, message: "Must be 100 characters or fewer" } }, }, subscribed: { name: "subscribed", diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts index 3141474717..64c6e754a7 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.queries.ts @@ -7,21 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Tag, - TagInsertSchema, - type TagPatch, - tags, - TagUpdateSchema, -} from "./Tag"; +import { type Tag, TagInsertSchema, type TagPatch, tags, TagUpdateSchema } from "./Tag"; export async function findTagById(db: Db, id: number): Promise { const [tag] = await db.select().from(tags).where(eq(tags.id, id)).limit(1); return tag ?? null; } -export async function listTags( - db: Db, - opts?: { limit?: number; offset?: number }, -): Promise { +export async function listTags(db: Db, opts?: { limit?: number; offset?: number }): Promise { let q = db.select().from(tags).$dynamic(); if (opts?.limit !== undefined) { q = q.limit(opts.limit); @@ -31,30 +22,19 @@ export async function listTags( } return q; } -export async function createTag( - db: Db, - data: z.input, -): Promise { +export async function createTag(db: Db, data: z.input): Promise { const validated = TagInsertSchema.parse(data); const [tag] = await db.insert(tags).values(validated).returning(); return tag!; } -export async function updateTag( - db: Db, - id: number, - patch: TagPatch, -): Promise { +export async function updateTag(db: Db, id: number, patch: TagPatch): Promise { const validated = TagUpdateSchema.parse(patch); // PATCH-5: an empty patch is a no-op — return the current row rather than let // Drizzle throw on an empty SET clause. if (Object.keys(validated).length === 0) { return findTagById(db, id); } - const [tag] = await db - .update(tags) - .set(validated) - .where(eq(tags.id, id)) - .returning(); + const [tag] = await db.update(tags).set(validated).where(eq(tags.id, id)).returning(); return tag ?? null; } export async function deleteTagById(db: Db, id: number): Promise { diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts index 8dc41fe210..fd85d72620 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.routes.ts @@ -2,14 +2,7 @@ // Source metadata: Tag (Tag) // Extend in your own module (e.g. Tag.extra.ts) — nothing imports it for you. import { db } from "~/server/db"; -import { - Tag, - TagFilterAllowlist, - TagInsertSchema, - tags, - TagSortAllowlist, - TagUpdateSchema, -} from "./Tag"; +import { Tag, TagFilterAllowlist, TagInsertSchema, tags, TagSortAllowlist, TagUpdateSchema } from "./Tag"; import { mountCrudRoutes } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; import type { FastifyInstance } from "fastify"; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts index 45b9c2c043..b6da2f7b23 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Tag.ts @@ -6,19 +6,14 @@ import { bigint, pgTable, varchar } from "drizzle-orm/pg-core"; import { z } from "zod"; export const tags = pgTable("tags", { - id: bigint("id", { mode: "number" }) - .primaryKey() - .generatedByDefaultAsIdentity(), + id: bigint("id", { mode: "number" }).primaryKey().generatedByDefaultAsIdentity(), name: varchar("name", { length: 50 }).notNull().unique(), slug: varchar("slug", { length: 50 }).notNull().unique(), }); export type Tag = InferSelectModel; export type TagInsert = InferInsertModel; export type TagUpdate = Partial; -export const TagInsertSchema = z.object({ - name: z.string().min(1).max(50), - slug: z.string().min(1).max(50), -}); +export const TagInsertSchema = z.object({ name: z.string().min(1).max(50), slug: z.string().min(1).max(50) }); export const TagUpdateSchema = z.object({ name: z.string().min(1).max(50).optional(), @@ -65,20 +60,14 @@ export const Tag = { label: "Name", view: "text", htmlType: "text", - rules: { - required: "Name is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Name is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, slug: { name: "slug", label: "Slug", view: "text", htmlType: "text", - rules: { - required: "Slug is required", - maxLength: { value: 50, message: "Must be 50 characters or fewer" }, - }, + rules: { required: "Slug is required", maxLength: { value: 50, message: "Must be 50 characters or fewer" } }, }, } as const; import type { FilterAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; @@ -87,10 +76,4 @@ export const TagFilterAllowlist = {} as const satisfies FilterAllowlist; import type { SortAllowlist } from "@metaobjectsdev/runtime-ts/drizzle-fastify"; export const TagSortAllowlist = {} as const satisfies SortAllowlist; -export type TagFilter = { - limit?: number; - offset?: number; - sort?: string; - or?: TagFilter[]; - and?: TagFilter[]; -}; +export type TagFilter = { limit?: number; offset?: number; sort?: string; or?: TagFilter[]; and?: TagFilter[] }; diff --git a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts index 5f5fe10e72..d56c7f45b5 100644 --- a/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts +++ b/server/typescript/packages/codegen-ts/test/golden/__snapshots__/postgres/Video.queries.ts @@ -7,25 +7,12 @@ import type { z } from "zod"; import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; type Db = PgDatabase>; -import { - type Video, - VideoInsertSchema, - type VideoPatch, - videos, - VideoUpdateSchema, -} from "./Video"; +import { type Video, VideoInsertSchema, type VideoPatch, videos, VideoUpdateSchema } from "./Video"; export async function findVideoById(db: Db, id: number): Promise