Repository navigation
feat(examples): add metadata-driven grid, form and route proof in TypeScript - #609
Merged
Merged
Conversation
…ypeScript examples/dynamic-grid serves and renders every entity of a model from the metadata loaded at runtime, with no code generated per entity: - <MetaGrid entity="..."/> and <MetaForm entity="..."/> take an entity name and read columns, types, labels, enum members, relationships, validation limits, filter operators and sort from GET /_meta. They reuse EntityGrid, CurrencyInput and the filter query builder from the web client packages. - One Fastify mount serves list, get, create, update and delete for every entity through ObjectManager, on SQLite, with the wire contract of the generated routes: filter and sort allowlists from the model, typed filter values, bound parameters only, unknown-field 400, api.pagination, and no credential field read or written. - The only generated code is the types and name constants; the hand-written business rules are typed against them. - Editing the metadata file reloads the model: the grid, the form and the API change with no regeneration. A change that would lose data is refused. docs/features/metadata-driven-runtime.md measures it against the reference generators on the same five-entity model (1,781 hand-written lines paid once, against 3,629 generated lines that grow by about 726 an entity), gives the per-row cost of the metadata lookups, and lists what the approach cannot do. It is a TypeScript example, not a package, and claims no equivalent in the other ports. Also fixes mountCrudRoutes and mountDeleteRoute in runtime-ts, which answered 500 for DELETE on a missing row; they answer 404 now. The example's suite runs in the ts-unit lane, and the lane map sends a change under examples/dynamic-grid to the TypeScript lanes only.
Review of the example found nine defects; each is fixed with a test. Example (examples/dynamic-grid): - A credential (view.password) can no longer be filtered or sorted on, even when the model marks it @filterable. A like filter on a hidden value would read it out a prefix at a time. - A whole-number key is addressed by its plain decimal form only; 0x1, 1e0 and 01 are 404, not row 1. - Every list is ordered by the caller's sort and then the primary key, so rows that tie on the sort do not move between pages. - Model reloads run one at a time, and a schema change is applied by the migration engine's transactional applier, so one that fails part-way changes nothing. A runtime that cannot load removes its scratch files. - A business rule sees the model's defaults on create and the stored row on update; the stock rule no longer re-judges a line whose part and quantity did not change. - The grid keeps a reference title that arrives after the page was fetched again, and a field the caller's `where` fixes is not offered in the filter bar and cannot be overridden by a filter. Runtime (@metaobjectsdev/runtime-ts): - findMany with an offset and no limit was a SQL syntax error on SQLite and MySQL in the Kysely and Drizzle drivers. An offset alone now carries a limit no result can reach. Then a simplification pass: one isRecord a side, typed route params, the credential field list looked up once a list instead of once a row, rows and count fetched together. The write-up's size and timing tables are re-measured.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What Changed
examples/dynamic-grid, a workspace member that serves every entity from the loaded model: oneMetaGridand oneMetaFormcomponent readGET /api/_meta, and one Fastify route mount servesGET/POST/PATCH/PUT/DELETEthroughObjectManageron SQLite. Only the types and name constants (entityFile,namesFile) are generated, for hand-written business rules. Model edits reload while the page is open, with nometa gen.docs/features/metadata-driven-runtime.md, CHANGELOG entries, a README link, and wires the example's test suite intoscripts/ci-local.shandscripts/ci-lane-map.txt.@metaobjectsdev/runtime-tsfixes:mountDeleteRoutenow answers404 {"error":"not_found"}for a missing row instead of500, by callingObjectManager.deletewithifMissing: "ignore". The Kysely and Drizzle drivers no longer emitOFFSETwithoutLIMIT(a syntax error on SQLite and MySQL), so an offset alone works. Tests added for both.Measurement
From
docs/features/metadata-driven-runtime.md, produced bybun run measurein the example. It runs the reference generators in memory on the example's own model (5 entities and a value object) and counts both sides with one rule: a line is code when it is not blank and not only a comment.<MetaGrid>,<MetaForm>and their controlsentity: types, Zod schemas and the Drizzle tablenames: name constantsqueries: typed query helpersroutes: Fastify CRUD routeshooks: TanStack Query hooksgrid: TanStack Table columnsgrid-hook: grid state hookform: React form componentbarrel: index.tsPer entity, the generated path adds about 726 lines in 9.4 files. The metadata-driven path adds about 78 (its types and name constants) and no hand-written code. The two are the same size at about 3 entities; at 50 entities it is about 36,000 generated lines against about 5,700.
ObjectManager.findMany, 1000 rows of 9 columnsSELECTthrough Kysely with no metadata/_meta(5.2 KB of JSON)String(value)The sizes are exact. The timings are medians from one developer machine and move with its load: four runs on one day put the server's per-row overhead between 5.2 and 7.7 µs, and a run on the busy validation machine measured 10.4 µs. The "browser" rows were timed in Bun, not in a browser.
Read the sizes with these in mind. Nobody types the generated lines, so the comparison is about how much code exists to review and keep in step with the model. The 1826 lines are hand-written in the example because no package ships them. The two paths are not feature-identical, and the write-up lists what the metadata-driven path cannot do (no compile-time check on the UI or route layer, no browser-side validation from the model, a fixed set of form controls, no projections, reports, single-table inheritance or many-to-many routes, no authorization). It was built and tested on the TypeScript port only; no claim is made that another port has an equivalent, and C# has no
ObjectManagerfor a mount like this to stand on.Found and not changed here
view.password) that a model marks@filterable. The example's mount does. The generators were out of scope for this change.ObjectManagerreads a numeric key from a path with a lenient number parse, so0x1,1e0and01all address row 1 through the packaged route mounts. The example's mount accepts only the plain decimal form. Tightening the shared runtime would change behaviour for existing adopters, so it is left for a separate decision.This PR took one no-mistakes gate run.
Validation
Risk Assessment
✅ Low: The change is a self-contained example app, a workspace member that publishes nothing. The shared runtime-ts edits are small: the OFFSET-without-LIMIT workaround in the Kysely and Drizzle drivers, and DELETE now answers 404 for a missing row. Both have tests. I found no defects. The three fix rounds hold up:
shortNamenow returns an unqualified ref whole, routes capture the model once per request, and the source-grep test became a behavioural test.Testing
Baseline
scripts/ci-local.sh --affected --strict-toolchainspassed at the target commit and was not re-run. I drove the realbun src/server/main.tsdev server (isolated port 4311, scratch SQLite under a throwaway $DEV_SCRATCH dir) and passed all three scenarios live. Scenario 1: headless Chrome rendered the entity-agnostic grid from/api/_meta(screenshot). Scenario 2: the single route mount served list filter, sort, paging and limit guards, plus create, patch and delete with validation refusals, all as HTTP transcript. Scenario 3: appending a newWarrantyentity to the model made/api/warrantiesserve and accept writes at revision 2 with no restart; a YAML syntax break and removing an entity that holds rows were both refused, and the server kept serving the prior revision. I restored the model file (git status clean) and stopped the server process group. The example's own focused suite (bun testin examples/dynamic-grid) passed 122/122 and covers the review fixes (packageless-model shortName, single model capture per request, source-grep test removed). Those fixes were not re-run red-before-fix and the packageless path is in-process, not live. Note: after the refused revert the server kept revision 4 (with Warranty) while the worktree file was clean, which is the documented refuse-and-keep behavior, not a defect.Evidence: Live API transcript: list, filter, sort, paging guards, write validation, PATCH, DELETE
Evidence: Dev server log: live reload accepted, YAML break refused, drop-table refused, revisions
Evidence: Focused example suite run (bun test, 122 pass)
Pipeline
Updates from git push no-mistakes
✅ **Intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 2 issues found → auto-fixed (2) ✅
examples/dynamic-grid/test/app.test.tsx:139- New testsrc/client mentions no entity, field or collection of the demo modelreads everysrc/client/*.ts(x)file with readFileSync, strips comments by regex, and regex-matches entity/field names in the source text. This is a source-content-only assertion: it proves nothing about rendered behavior, and it has false positives and negatives (a name built from string parts, a name in a template literal, a comment-like string). The repo test-quality rule forbids this pattern. The behavior it stands for (no component names an entity) is already shown by the other tests, which render a metadata edit (a new entity, a changed enum) with no code change (live-reload.test.ts, the add-an-entity test inapp.test.tsx). Remove it, or replace it with a behavioral test that loads a model whose entity and field names are all new and asserts the grid, form and routes serve it.examples/dynamic-grid/src/server/routes.ts:289- Member GET and DELETE read the model twice per request:memberAtcallsmodel()for the entity, then the handler callsmodel().omagain. A reload between the two calls pairs an entity from revision N with the ObjectManager of N+1. If the reload removed that entity,om.findByIdorom.deletethrows and the request answers a redacted 500 instead of 404. The window is tiny, but the list, create and update handlers already captureconst current = model()once. Do the same in the GET-by-id handler (line 289) and the DELETE handler (line 334), and havememberAttake the captured model.🔧 Fix applied.
1 warning still open:
examples/dynamic-grid/src/client/model.ts:167-shortNamereturns the wrong name for an unqualified reference. When the ref has no::,ref.lastIndexOf('::')is -1 and theincludesguard adds 0, so the code runsref.slice(-1)and returns the last character.shortName("Customer")is"r", andshortName("Customer.id")is"d". I confirmed thatmetaJsonon a packageless model emits@objectRef: "Addr"unqualified. The demo model declarespackage: demo::workshop, so its refs are qualified and the tests pass. For a model without a package, the client silently gets no value object (thefield.objectrenders as 'no control' and the grid cell falls back to JSON), noreferences(foreign keys become plain integer inputs and cells show raw ids), and norelatedlists. Nothing errors. The README tells readers to edit the model and copy the approach. Same defect at every call site: model.ts:199 (valueObjectName), model.ts:217 (references), model.ts:263 (relatedModelstarget match). Fix: compute the start index fromlastIndexOfonly when the separator is present (const at = ref.lastIndexOf(SEP); const bare = at < 0 ? ref : ref.slice(at + SEP.length)), and add a test that loads a packageless model.🔧 Fix applied.
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
scripts/ci-local.sh --affected --strict-toolchainsscripts/ci-local.sh --affected --strict-toolchains(baseline, already passed at target commit, not re-run)PORT=4311 bun src/server/main.tsin examples/dynamic-grid with DEV_SCRATCH isolated (live dev server)curl -glist/filter/sort/paging/CRUD/validation against /api/customers, /api/technicians, /api/work_orders, /api/warrantiesModel append of Warranty entity to metaobjects/meta.workshop.yaml with reload observed via /api/_served revision 2Broken YAML append to model: reload refused, revision kept (server.log)Removing Warranty entity with rows: refused by drop-table guard, revision kept (server.log); model restored via git checkoutgoogle-chrome --headless=new --screenshot of http://127.0.0.1:4311/bun testin examples/dynamic-grid (122 pass, 0 fail) with DEV_SCRATCH set to a throwaway scratch directoryServer stopped by process group (TERM to pgid); scratch dir removed✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.