Repository navigation
feat(concerto)!: native ESM migration for per-export tree-shaking (v5.0.0) - #1306
Conversation
Signed-off-by: Rishabh Jain <rishabhj2005@email.com>
…package-level tree shaking Listing `./dist/esm/index.mjs` in sideEffects prevented bundlers from skipping concerto-core entirely when nothing from it is imported. Instead, emit `dist/esm/dayjs-setup.js` as a separate file and reference that in sideEffects — keeping the real side effect (dayjs.extend() calls) declared while allowing the main ESM bundle to be tree-shaken at the package boundary. Verified: importing only concerto-util produces a 59 KB bundle; adding concerto-core jumps to 1.46 MB, confirming the package is correctly excluded when unused. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
The ESM dayjs-setup output lived at dist/esm/dayjs-setup.js. Since the package is not "type": "module", Node parses a .js file as CommonJS, so an ESM file with that extension is ambiguous. Emit it as .mjs and point the sideEffects entry at the .mjs path so the dayjs.extend() side effect stays correctly declared. Also document in DEVELOPERS.md that the monorepo must be built in dependency order (npm run build), because each package's exports.import now resolves to dist/esm/index.mjs. Addresses review feedback on PR #1263. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
- e2e: import Page as a type-only import (it is used only as a type), avoiding a runtime named-import mismatch under some TS transpile modes. - build-esm: gate the createRequire shim banner to the Node-only build. Browser-targeted .mjs outputs no longer carry a Node-only `import ... from "module"`, which could break downstream browser bundlers. Verified the browser bundles emit zero runtime require() calls (externals resolve as ESM imports), so the shim was unused there; the node-only package still receives it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
The browser-targeted ESM build externalised Node builtins, leaving bare `import "fs"` (concerto-core, concerto-util) and `import "path"` (concerto-util) in dist/esm/index.mjs. These only resolve in downstream consumers that ship Node-polyfill/fallback infrastructure; a stricter browser bundler would fail to resolve them. Stub Node builtins to empty modules for browser builds via an esbuild plugin (requires the async build API), matching the parity the webpack UMD build already achieves via resolve.fallback (fs/path -> false). The node-only linter build still externalises builtins and keeps its createRequire banner. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
Decorated is the base class of all decorated model elements (Declaration, Property, etc.) and was previously accessible only via the types/lib/introspect/decorated deep import path. With the exports field added in this PR, that path is no longer reachable. Exporting it from the main entry point is the correct fix. Signed-off-by: Matt Roberts <code@rbrts.uk>
issues.jsonl is a local beads issue-tracker data file that was accidentally committed. Remove it and ignore it so it never re-appears in diffs. This fixes the license-check CI failure (the tool scanned the file and found no Apache 2.0 header). Signed-off-by: Matt Roberts <code@rbrts.uk>
…(locks recipe R1-R10) Pilot for #1304 (concerto-334). Migrates two exemplar files to native ESM: - securityexception.ts: leaf, external named import (R3) + dual export (R1) - modelfile.ts: requires->imports (R2), global-undefined block->import type (R7), export=->dual export (R1), field declarations for subclass type-debt (R10) Locks the transformation recipe. Confirms: tsc-green is incremental per-file (bucket-A field-decls self-checkable); migrated<->unmigrated seam errors (bucket-B: TS2709/2351/2554) self-resolve at completeness. Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Signed-off-by: Matt Roberts <code@rbrts.uk>
…tion Phase C integration fixes for #1304. After migrating concerto-util and concerto-core CJS-interop syntax to native ESM, workspace imports resolve to their real types instead of `any` (previously masked by `const X = require(...)`). This unmasked pre-existing latent type inconsistencies at the migrated<->unmigrated seams. All fixes are runtime-neutral (verified against the 455c779 baseline, which had 0 tsc errors); no existing test files are modified. - validationexception: `component?` (JSDoc already says optional; extends BaseException whose 2nd/3rd params are optional) — clears 20 TS2554 - jsonpopulator: `visit(thing: any)` — the Declaration|Field union does not share the duck-typed decl/field predicates called via `?.()`; `path?: TypedStack<string>` matches the value always assigned at runtime - resourcevalidator: `constructor(options?)` — body already does `options || {}`; called with 0 args from factory.ts - metamodel: drop dead trailing `true` 5th arg to ModelFile ctor (ctor has 4 params and never reads arguments[4]; baseline tolerated it only because `ModelFile` was `require(...)` = any) - modelfile.getImports: annotate `result: string[]` (was inferred never[]) - jsongenerator: `let id: any = null` (matches sibling `result: any`) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
…port)
The migration converted `const uuid = require('uuid')` to
`import uuid from 'uuid'`, but uuid v9+'s ESM build exposes only named
exports (v4, etc.) with no default. tsc's esModuleInterop synthesized a
default (so the CJS build and .d.ts emit succeeded), but the esbuild ESM
bundle (build:esm) failed to resolve `default`. Usage is `uuid.v4()`, so
`import * as uuid from 'uuid'` is the correct, runtime-neutral form and
resolves cleanly under both tsc (CJS interop) and esbuild (native ESM).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Captures the strategic fork (Options A hybrid / B v5 clean-break / C measure-first), Phase-C implementation state, gating measurements, and resume instructions. Branch is a resumable checkpoint pending a human release-strategy decision. Refs: concerto-3oj, concerto-334 Signed-off-by: Matt Roberts <code@rbrts.uk>
Option B (clean break, v5) resolves the constraint conflict recorded in
plan-issue-1304-esm-migration.md §4: with leaf modules on native ESM,
`export default X` compiles to `exports.default = X` under `module: commonjs`,
so the existing `const X = require('../src/x'); new X()` pattern in the mocha
suites throws "X is not a constructor".
Under a major release those source-coupled requires are updated rather than
reverted. Each deep require now destructures the module's named export
(`const { X } = require('../src/x')`), falling back to `.default` where the
local binding does not match a named export.
- concerto-util: 85 passing / 66 failing -> 151 passing / 0 failing
- concerto-core: 93 passing / 279 failing -> 1276 passing / 0 failing
No source or public API changes; test wiring only. Also appends the required
licence header to the plan document so `license-check-and-add` passes.
Refs #1304
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Completes the Option B clean break across the published surface. These were
the last two packages still on TypeScript's CJS-interop syntax; concerto-core
and concerto-util were migrated earlier on this branch, and concerto-analysis,
concertino and concerto-linter were already clean.
concerto-cto:
- `export = Class` -> `export { Class }; export default Class;`
- `export = { a, b }` -> individual named exports plus a default object of the
same shape, so `Parser`, `Printer` and `External` keep their runtime shape
while their members become individually tree-shakeable.
- `import X = require('./x')` -> `import X from './x'`, except the generated
peggy parser, which has no default export and uses `import * as Parser`.
- `parseexception.ts` drops a `// @ts-ignore`d `require` for a real import.
concerto-vocabulary:
- `export = Class` -> named + default exports.
- The vocabulary <-> vocabularymanager cycle is removed at the source: the
type-only direction becomes `import type`, which erases at compile time, so
the compiled module graph has no cycle at all.
Public API surface is unchanged in both packages: the barrels export the same
names with the same runtime shapes. Test counts match baseline exactly
(cto 163, vocabulary 89).
Refs #1304
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Native ESM source syntax is a prerequisite for tree-shaking, not a sufficient condition. The ESM build was flattening each package into a single dist/esm/index.mjs, and once every module is inlined into one file there is nothing left for `sideEffects` to act on: a consumer's bundler is reduced to statement-level DCE across one large file, which the packages' cross-references defeat immediately. Measured before this change, importing `SecurityException` from concerto-core - a two-line exception subclass - cost 544,356 B against a 559,367 B whole-package ceiling. 97% of the package survived elimination. Make every src/**/*.ts module an entry point and emit with outdir + splitting + `.mjs` output extension, so the ESM build mirrors what tsc already produces for CJS: one output module per source module, shared code hoisted into chunks. dist/esm/index.mjs keeps its path, so main/module/exports are untouched. Minified browser-bundle sizes, before -> after: concerto-core, SecurityException only 544,356 B -> 3,627 B (-99.3%) concerto-core, ModelManager only 552,634 B -> 418,282 B (-24.3%) concerto-core, whole package 559,367 B -> 547,863 B concerto-util, Writer only 17,215 B -> 739 B (-95.7%) concerto-util, whole package 22,253 B -> 22,322 B Whole-package imports are unchanged, as expected; the win is in what a consumer does not import. ModelManager legitimately reaches most of the package, so its 24% is the honest floor for that symbol. Verified: all seven packages emit index.mjs plus a per-module graph; a Node ESM smoke test exercises ModelManager/Factory/Serializer round-tripping, CTO parse and print, Writer, TypedStack and VocabularyManager against the emitted .mjs; and a minified, tree-shaken consumer bundle that never imports dayjs-setup explicitly still round-trips a DateTime with the utc plugin live, confirming the one genuine module-level side effect in the tree survives shaking. Refs #1304 Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
MIGRATION.md is the consumer-facing guide for the 5.0.0 clean break: what breaks (deep ./dist/* constructor imports, in both CJS and ESM form), what does not (every root-package import), how to fix each, and the measured tree-shaking numbers. It also documents the type-import position: the packages deliberately do not widen their `exports` map to re-expose the `types/` declaration tree. Consumers should use `import type` from the package root, which is erased at compile time, cannot anchor a module into a bundle, and resolves identically under every module-resolution mode. Any type not reachable from a root barrel should be added to that barrel rather than deep-imported. The plan document records the Option B decision, the execution log, and the tree-shaking measurement including the two hypotheses that were tested and rejected before the real root cause was found. Refs #1304 Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
@DianaLease my plan was to merge to main, then release a 5.0 release |
The ESM build marked only workspace packages as external, so every runtime
dependency was compiled into the output. tsc does the opposite for the CJS
build, emitting require("dayjs"), which meant the two published artifacts
disagreed about what a dependency is.
Bundling gave each package its own private copy: debug was compiled into
concerto-util, concerto-core and concerto-cto independently, and an application
depending on all three shipped three copies and deduplicated none. It also hid
those dependencies from npm audit and SBOM tooling, and made a patch to any of
them require republishing concerto rather than a lockfile bump.
Published dist/esm, .mjs bytes:
concerto-util 75,726 -> 40,887 -46%
concerto-core 958,029 -> 441,228 -54%
concerto-vocabulary 349,284 -> 87,639 -75%
concerto-cto 505,039 -> 491,738 -3%
total 1,888,078 -> 1,061,492 -44%
Consumer bundle sizes barely move (-0.3% to -0.8%): the remaining duplication
is @accordproject/concerto-metamodel, which has to stay bundled — see below —
and it dominates what the packages share. The win here is the published
artifact and dependency hygiene, not the consumer's bundle.
The browser build still bundles its dependencies and its output is unchanged
byte-for-byte. It is consumed as a self-contained graph, and its Node-builtin
stubbing only holds if the dependencies reaching for builtins are resolved
here rather than by the consumer.
Four dependencies stay bundled because they are CommonJS with no ESM build and
Node's cjs-module-lexer cannot see their named exports; externalising them
emits `import { MetaModelUtil } from '...'` and Node throws "Named export not
found" at load time. The exception list carries the command to re-test them.
Two source imports needed file extensions. dayjs and @stoplight/spectral-cli
publish no exports map, so Node ESM rejects an extensionless subpath: bundling
had been resolving `dayjs/plugin/utc` by extension inference, and once the
specifier survives into the output it has to be `dayjs/plugin/utc.js`. Both
forms work unchanged under CommonJS.
Verified: npm run test:esm 10/10 (it caught both failures above before they
could ship), full monorepo suite unchanged, UMD browser e2e 3/3, lint and
licchk clean, dist/esm-browser byte-identical.
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
Runtime dependencies are now external in the node ESM build (
|
| package | before | after | |
|---|---|---|---|
| concerto-util | 75,726 | 40,887 | −46% |
| concerto-core | 958,029 | 441,228 | −54% |
| concerto-vocabulary | 349,284 | 87,639 | −75% |
| concerto-cto | 505,039 | 491,738 | −3% |
| total | 1,888,078 | 1,061,492 | −44% |
What it does not buy
Consumer bundle sizes barely move — between −0.3% and −0.8% across single-symbol, whole-package and multi-package imports. I'd expected a dedup win there and it didn't materialise, because the dependency the packages actually share is @accordproject/concerto-metamodel, and that one has to stay bundled (below). An intermediate build with everything external showed −13% on a multi-package consumer, so the win is real but currently blocked upstream.
So this is a published-artifact and dependency-hygiene change: smaller tarballs, dependencies visible to npm audit and SBOM tooling, and security patches flowing through a consumer's lockfile instead of requiring a concerto republish.
Two things that had to stay bundled or change
Four packages stay bundled. @accordproject/concerto-metamodel and the three @stoplight/spectral-* packages are CommonJS with no ESM build, and Node's cjs-module-lexer can't see their named exports. Externalising them emits import { MetaModelUtil } from '@accordproject/concerto-metamodel' and Node throws "Named export 'MetaModelUtil' not found" at load. Bundling is what esbuild's interop was already doing for them. The exception list in build-esm.js carries the one-liner to re-test each entry — if concerto-metamodel ever ships an exports map or an ESM build, dropping it from that list should unlock the consumer-bundle win too.
Two source imports needed file extensions. dayjs and @stoplight/spectral-cli publish no exports map, so Node ESM rejects an extensionless subpath. Bundling had been resolving dayjs/plugin/utc by extension inference; once the specifier survives into the output it has to be dayjs/plugin/utc.js. Both forms work unchanged under CommonJS.
The browser graph is untouched — it still bundles its dependencies (its Node-builtin stubbing only holds if those dependencies are resolved at build time rather than by the consumer), and dist/esm-browser is byte-identical to before.
Verification
npm run test:esm 10/10 — and worth noting it earned its keep here: it caught both of the failures above before they could ship, neither of which any unit test would have seen. Full monorepo suite unchanged (1276 / 163 / 151 / 89 / 99 / 18 / 19), UMD browser e2e 3/3, lint and licchk clean.
Generated by Claude Code
The smoke test exercises the emitted ESM rather than src/, so it only ran as a separate CI step. That left the feedback loop backwards: both regressions it has caught came from editing scripts/build-esm.js, and the contributor editing that file got a clean `npm run build` locally and learned about the breakage from CI minutes later. Hooking it to postbuild puts the check where the failure is: a build that emits a package which cannot be imported has failed. It also gates publishing for free, since publish.yml runs `npm run build` before `npm publish`. It has to hang off the root build, not an individual package's. The script imports all four packages by name, so it needs the full ordered build to have finished; a postbuild on concerto-util would fire during build:level0, before core and cto exist. The dedicated CI step is now redundant and removed — it would otherwise run twice on each of the six matrix legs, plus again in the e2e job, which builds through pretest:e2e. Verified the guard actually bites: reintroducing the extensionless `dayjs/plugin/utc` import makes `npm run build` exit 1 rather than emitting a broken artifact. Costs 1.7s against a 51s ordered build. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
The webpack UMD builds are removed from concerto-core, concerto-util and concerto-cto, along with the legacy top-level `browser` field that pointed at them. The `exports` map introduced for tree-shaking had already demoted them: it is consulted before the legacy `browser` field, so webpack 5, Vite, Rollup and esbuild were resolving the root import to dist/esm-browser rather than the UMD bundle. That was measurable downstream — concerto-playground's production bundle dropped 14% on this branch precisely because Vite stopped using the UMD build. What remained was a ~1MB artifact serving `<script src>` users and tooling too old to read `exports`. Removing it takes roughly a third off the ordered build (concerto-core's webpack step alone was 13.8s of ~51s) and drops webpack, webpack-cli, babel-loader, @babel/preset-env, node-polyfill-webpack-plugin and process from devDependencies — 241 packages out of the lockfile. The four .babelrc files go with them: they existed only to feed babel-loader inside the deleted webpack configs, and left in place would have pointed at an uninstalled preset. concerto-vocabulary's was already dead. The `browser` *condition* inside each `exports` map is untouched. That is the supported browser entry point and is what bundlers already use. The browser e2e tests are rewritten against the ESM graph rather than deleted, which closes a real gap: dist/esm-browser is the artifact browser consumers now receive and nothing tested it in a browser. Doing so needed two things the UMD tests never did. A module graph cannot be injected with addScriptTag — it imports sibling chunks by relative path — so the suite serves each package's dist/esm-browser over HTTP and imports it. And concerto-core's graph imports @accordproject/concerto-cto and -util as bare specifiers, which a browser cannot resolve, so the page carries an import map. Navigating to about:blank first, as the UMD suite did, fails: Chromium's Private Network Access check blocks a null-origin page from fetching loopback, so the server also serves a same-origin document to land on. Also adds e2e/.eslintrc.yml. That directory had no working TypeScript ESLint setup — `npx eslint .` failed to parse even the pre-existing spec — and it now holds two TypeScript files worth linting. Scoped with `root: true`. BREAKING CHANGE: the UMD bundles dist/concerto-core.js, dist/concerto-util.js and dist/concerto-cto.js are no longer published, and the `window['concerto-core']` style globals they exposed are gone. Bundler users are unaffected. `<script src>` users need a bundler or a module-type script; MIGRATION.md documents both. Verified: build clean with the ESM smoke test passing, full suite unchanged (1276/163/151/89/99/18/19), browser e2e 3/3 against the ESM graph, lint clean across all four changed areas, licchk clean, and no dist/concerto-*.js emitted. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
Two inaccuracies, both introduced by describing the browser story before the UMD bundles were actually removed. The bundler-user note explained that nothing changes for them "because exports takes precedence over the legacy browser field". That framing describes a conflict that no longer exists: the legacy browser field is gone. Reworded to say what is now true — those tools read exports, so they had already stopped using the UMD bundle, and removing it takes away something they were not resolving to. More substantially, the document listed only bundler users and script-tag users as affected. It missed the group that actually gets the worst of this: tooling that does not read exports at all. webpack 4, browserify and Parcel 1 found the UMD bundle through the top-level browser field, and with both that field and the bundle removed they now fall back to main — the CommonJS build, which imports fs and will not run in a browser. That failure is real and surfaces as a confusing missing-module error, so it is now called out explicitly, along with the fact that there is no supported path for those tools in 5.0.0. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Matt Roberts <code@rbrts.uk>
* fix(metamodel): make all named exports visible to cjs-module-lexer
module.exports assigned MetaModelNamespace as a `key: <string literal>`
property inline in the exports object. cjs-module-lexer, the static
analyzer Node's ESM loader uses to detect named exports of a CommonJS
module, only recognises `key: identifier` shorthand/pairs; a string
literal value stops its scan, so it silently dropped every property
that came after it. As a result `import { MetaModelNamespace } from
'@accordproject/concerto-metamodel'` (and DcsCto/DcsNamespace, which
came later in the object) threw "Named export not found" under Node
ESM, even though require() returned all four correctly.
Hoist the string to a local const and assign each export individually
via `exports.X = ...` so the lexer can see every one of them.
Verified with the real lexer that this changes the detected exports
from ["MetaModelUtil"] to ["MetaModelUtil","MetaModelNamespace",
"DcsCto","DcsNamespace"]. require() output and the generated
types/index.d.ts type surface are unchanged (an inline `@type {string}`
assertion keeps MetaModelNamespace typed as `string` rather than the
narrower string-literal type tsc would otherwise infer).
This unblocks accordproject/concerto#1306, which currently has to
bundle this package into concerto-core/vocabulary's ESM output instead
of externalising it, because externalising it emits exactly this
failing import.
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
* docs(metamodel): describe the export shape that is actually there
The explanatory comment referred to a string literal "in the object below",
but the change it accompanies removes that object literal — the exports are
now assigned individually. As written it described the shape being avoided as
though it were the current one.
Reworded to state both deliberate details of the code as it stands (individual
`exports.X` assignments, and MetaModelNamespace as a local binding) and to keep
the reason for each. No behaviour change.
Reported by Copilot on #89.
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Matt Roberts <code@rbrts.uk>
---------
Signed-off-by: Matt Roberts <code@rbrts.uk>
Co-authored-by: Claude <noreply@anthropic.com>
concerto-metamodel was the one runtime dependency held back from the Node
ESM build's externalisation list. Its CommonJS entry point assigned exports
with a string-literal object value, which halts cjs-module-lexer's scan, so
Node could not see the named exports and `import { MetaModelUtil } from
'@accordproject/concerto-metamodel'` threw at load time. Bundling it was the
workaround.
3.17.0 carries the upstream fix, so the workaround can go:
parse(index.js).exports
-> [ 'MetaModelUtil', 'MetaModelNamespace', 'DcsCto', 'DcsNamespace' ]
Raise the dependency floor to ^3.17.0 in the five packages that depend on
it. The floor is load-bearing rather than cosmetic: under ^3.16.0 npm could
resolve a version without the fix and the Node ESM build would break at
runtime.
Published artefacts shrink by the copies they no longer carry:
concerto-core 441,228 -> 374,081 bytes (-15%)
concerto-vocabulary 87,639 -> 25,408 bytes (-71%)
Bundled consumers see much less than that (a four-package bundle goes
587,881 -> 585,417, -0.4%): esbuild was already tree-shaking the inlined
copies down to the parts actually reached, and a single external CommonJS
copy cannot be tree-shaken, which offsets most of the deduplication. The
win here is install and download size, unbundled Node consumers, and having
one metamodel version in the tree instead of four.
The three @stoplight/spectral-* packages remain bundled; their named
exports are still invisible to the lexer.
Signed-off-by: Matt Roberts <code@rbrts.uk>
The published table mixed measurement methods: the 4.x column bundled a package's `dist/index.js` directly while the 5.0.0 column resolved through the `exports` map, and the numbers had drifted from the build as later commits landed. Re-measure both columns identically — import by package name, so resolution happens the way it does in a consumer's project — and give the browser and Node targets their own rows, since they resolve to different artefacts on both sides. 4.2.0 ships no `exports` map, so a browser bundler takes its `browser` field, which is the UMD bundle; that is what browser consumers actually got, and it is why the browser column starts so much higher than the Node one. Signed-off-by: Matt Roberts <code@rbrts.uk>
Types (#1308, merged in)#1308 is now part of this branch, so here is what it covers. Worth folding into the description; I couldn't edit it directly without risking the sections below the fold. The ESM switch restored real base-class types — Declared once, in the owning class. Real types. Three latent bugs it surfaced. Runtime behaviour is unchanged apart from those three exception arguments. Two notes on the description itself:
Two follow-ups left deliberately undone, both worth a look for 5.0.0: Generated by Claude Code |
… fields (#1308) * refactor(types)!: tighten introspect and model types, drop redeclared fields The ESM migration replaced `require()` with `import`, which restored real base-class types across `concerto-core` and so switched property checking back on. The migration papered over the resulting errors by declaring every instance field as `: any`, including fields that the base class already declared. This replaces those with real types. Declared once, in the owning class ---------------------------------- - ClassDeclaration no longer redeclares `modelFile` (Declaration owns it). - MapDeclaration no longer redeclares `modelFile`, `name` or `fqn`, and drops its `getModelFile`/`getName`/`getFullyQualifiedName` overrides, which were byte-identical to Declaration's. Its `process()` no longer recomputes `name`/`fqn` that `super.process()` has already set. - Property dropped `modelFile`, which was declared but never assigned. - ModelFile dropped `modelFile` and `ast`, likewise never assigned and already owned by Decorated. Fields carry definite assignment assertions rather than initialisers throughout: these classes are populated by a `process()` method that a base constructor invokes, and with `useDefineForClassFields` off a subclass initialiser is emitted after that constructor has run, clobbering the value. Real types ---------- - `Decorated.ast` is now an exported `AstNode` interface, and `decorators` is `Decorator[]`. `getModelFile()` declares `ModelFile`, which removes the casts its callers needed. - Declaration, ClassDeclaration, ScalarDeclaration, MapDeclaration, MapKeyType, MapValueType, Property, Field, RelationshipDeclaration, Decorator, ModelFile, Introspector and the four Validators carry concrete field and return types; nullable fields are `T | null` rather than `any`. - `ModelFile.getDeclarations()` is generic, so `getAssetDeclarations()` and friends return their own declaration type. - `NullUtil.isNull` and `ModelUtil.isValidIdentifier` are type predicates, which narrows at their call sites instead of forcing casts. - BaseModelManager, Factory, Serializer, the serializer visitors, the model classes, DecoratorManager and DecoratorExtractor take concrete field types. New shared interfaces live in `types.ts`: `SerializerOptions`, `GenerateOptions`, `InstanceGeneratorParameters`, and the decorator command shapes mirroring the DCS model. - `concerto-util` exports `WritableModelFile`/`WriteModelsOptions`; `concerto-cto` types `parse()` as `IModel`, gives `resolveExternal` a named options type, and drops the `as any` casts in FileDownloader. Bugs the tightening surfaced ---------------------------- - Property and ModelFile passed an always-undefined `this.modelFile` to IllegalModelException; they now pass the real ModelFile. - ScalarDeclaration passed `this.ast.name.location` as the *modelFile* argument to IllegalModelException, which was always undefined; it now passes `this.modelFile` and `this.ast.location`. - ClassDeclaration.declarationKind() gained a `return ''` stub during the migration, silently answering with an empty string for any subclass that forgot to override it. It throws now, matching Decorated.getModelFile(). Downstream, concerto-analysis and concerto-vocabulary needed null guards and narrowing casts where core methods now admit null. Breaking: the emitted .d.ts files change shape. Runtime behaviour is unchanged apart from the three exception arguments noted above. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YAZpnt3uqfBeGWeKAcwHXS Signed-off-by: Matt Roberts <code@rbrts.uk> * refactor(types): address review, narrow validator ASTs to metamodel types - CollectionSizeValidator, NumberValidator and StringValidator take their real metamodel nodes (ICollectionSizeValidator, the three domain validators, IStringRegexValidator/IStringLengthValidator) instead of the generic AstNode. Validator.validator is a union of those, and each subclass narrows it with `declare`, which emits nothing. - Property.decorator is gone. It was only ever assigned null and never read in src or test. - Decorator.handleError takes `string | Error` rather than `unknown`: the in-validate callers pass a message they just built, the catch passes the exception. - Identifiable.$timestamp is `Dayjs`, not `any`, and the JSDoc on it and on the Identifiable/Resource/Relationship constructors says so. It was documented as a string but has always held a Dayjs, which is what JSONGenerator formats and JSONPopulator rebuilds. - DecoratorExtractor keeps the explicit `> 0` comparison, via `?? 0`, rather than relying on a falsy length. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YAZpnt3uqfBeGWeKAcwHXS Signed-off-by: Matt Roberts <code@rbrts.uk> --------- Signed-off-by: Matt Roberts <code@rbrts.uk> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Signed-off-by: Matt Roberts <7544022+mttrbrts@users.noreply.github.com>
7b7bd02 to
00c4046
Compare
|
Did an independent review of the diff. The downstream validation and the Node-ESM/process-shim/dual-package discussion already cover the big items, so this is just the type-safety things I didn't see raised elsewhere. 1. Two casts force incompatible types through the escape hatch: downloader.downloadExternalDependencies(
this.getModelFiles() as unknown as (ModelFileInstance[] & ModelFileSource[]), ...);
ModelWriter.writeModelsToFileSystem(
this.getModelFiles() as unknown as WritableModelFile[], ...);The first one is the worse offender — 2. this.compareClassDeclarations(comparers, a.getAllDeclarations() as ClassDeclaration[], ...);
3. Minor:
|
jamieshorten's review flagged several `as unknown as` / `as X[]` casts
that the native-ESM migration introduced once real types replaced the
old CJS-interop `any`s.
- concerto-vocabulary/vocabulary.ts: getAllDeclarations() returns
Declaration[], and the only member used here is getName(), so drop
the unnecessary ClassDeclaration cast in favour of the real type.
- concerto-analysis/compare.ts: getAllDeclarations() is cast to
ClassDeclaration[] so map/scalar declarations can flow through the
same comparer pipeline. Verified runtime-safe (compareClassDeclaration
guards with instanceof, and the public Comparer.compareClassDeclaration
callback already has to tolerate this), so this is documented with a
SAFETY comment rather than widened, since a type-level fix would mean
changing the public Comparer callback's parameter type.
- concerto-core/basemodelmanager.ts: the two ModelWriter/FileDownloader
casts are similarly runtime-safe (ModelFileLoader always supplies
fileName/definitions; both ModelFileInstance and ModelFileSource only
need to structurally satisfy `{ ast }`) but not provable by their
current public interfaces, so both get a SAFETY comment explaining why.
No behaviour change. Full build (tsc + ESM emit + smoke test), lint and
the affected packages' unit tests (concerto-core 1278, concerto-analysis
99, concerto-vocabulary 89) all pass unchanged.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ECqBEJBSn19CRhCHLFmEw9
Signed-off-by: Claude <noreply@anthropic.com>
Follow-up to the review on #1306. The three `as unknown as` / `as X[]` casts were documented with SAFETY comments in a6a5688 on the grounds that removing them meant changing public API. Since 5.0.0 is a breaking release, change the API instead: each cast existed because a signature did not describe what the code actually does. FileDownloader<TFile, TSeed = TFile> ------------------------------------ One type parameter served as both the input and the output of downloadExternalDependencies(), but the files seeding the walk are not the type the bound FileLoader produces: BaseModelManager seeds it with parsed ModelFile instances and gets back raw ModelFileSource objects. The old signature could only be satisfied by casting to `ModelFileInstance[] & ModelFileSource[]` — an intersection no element can actually be. TSeed names the seed type and defaults to TFile, so existing single-parameter uses are unaffected; getExternalImports takes `TFile | TSeed`, which is exactly what it is handed at runtime. Comparer.compareClassDeclaration takes a Declaration ---------------------------------------------------- Every declaration in a model file goes through this callback, map and scalar declarations included, so `getAllDeclarations() as ClassDeclaration[]` was asserting something false to satisfy a callback type that had always been narrower than reality. Widening it to Declaration makes the compiler enforce what the runtime already required: narrow before reaching for ClassDeclaration members. The built-in comparers needed no changes — they only call Declaration-level methods and getDeclarationType(), which already took a Declaration. compareClassDeclaration()'s two negative instanceof guards collapse into one positive `instanceof ClassDeclaration` check: ScalarDeclaration and MapDeclaration both extend Declaration directly, so the positive form covers them and any future declaration kind, rather than needing a new guard per kind. writeModelsToFileSystem narrows instead of casting -------------------------------------------------- WritableModelFile requires a fileName and definitions; ModelFile types both nullable because a model file built from an AST alone has neither. That is real information, not noise, so the call site now narrows and throws an error naming the namespace it cannot write, rather than casting and letting fs raise a TypeError several frames later. Managers loaded from CTO are unaffected. MIGRATION.md documents all three under breaking changes. Verified: full build (tsc, both ESM graphs, 10/10 ESM smoke checks), full suite unchanged (concerto-core 1278, concerto-cto 163, concerto-util 151, vocabulary 89, analysis 99, plus the jest suites), lint and licence checks clean. No runtime behaviour change apart from the writeModelsToFileSystem error message. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ECqBEJBSn19CRhCHLFmEw9 Signed-off-by: Claude <noreply@anthropic.com>
Closes #1304
Converts the
@accordproject/concerto-*packages to native ESM so bundlers can tree-shake per export, and reshapes the published artefacts to match. This has to ship as 5.0.0 — it is a deliberate breaking change.What changed
export =/import X = require()→ native ESM across the packagesprocessbound in the browser graphtscalready does for CJSnpm run build: anyannotations → 29; real base-class types restored;Decorated.astexported asAstNode; 3 latent bugs fixed194 files changed, +3,486 / −5,380 across 40 commits.
Headline result
Minified bundle for a single-symbol import, measured with
esbuild --bundle --minify --format=esm, importing by package name so resolution happens the way it does in a consumer's project:{ Writer }fromconcerto-util{ SecurityException }fromconcerto-core{ ModelManager }fromconcerto-core4.2.0 ships no
exportsmap, so a browser bundler takes itsbrowserfield — the UMD bundle — which is what browser consumers actually got. Bundling for Node (--platform=node, taking 4.2.0'smainand 5.0.0'simportcondition) starts from a smaller baseline and lands in the same place: 28,647 → 863 B, 559,234 → 3,831 B, 559,229 → 426,781 B.ModelManagergenuinely reaches most of the package, so it shrinks least — that is the floor, not a bug.Downstream,
concerto-playground's production bundle drops 14.1%.For consumers
Not breaking for the overwhelming majority. Root-package imports are unchanged in both module systems. The breaks are deep imports into a package's compiled internals, and the removal of the UMD
<script>bundles.MIGRATION.mdis the full guide.Types (#1308, merged in)
What #1308 covers
The ESM switch restored real base-class types —
require()had been typing every base class asany, which switched property checking off acrossconcerto-core. The ESM migration silenced the fallout by declaring each instance field: any, including fields the base class already declared. #1308 replaced them with real types while the.d.tssurface is breaking anyway.: anyin the files it touched: 182 → 29, and 17 of those 29 are pre-existing inconcerto-vocabulary.Declared once, in the owning class.
ClassDeclarationno longer redeclaresmodelFile;MapDeclarationdropsmodelFile/name/fqnplus three overrides that were byte-identical toDeclaration's;PropertyandModelFiledrop fields that were declared but never assigned. Fields carry definite assignment assertions rather than initialisers — withuseDefineForClassFieldsoff, a subclass initialiser is emitted after the base constructor has runprocess(), and would clobber the value.Real types.
Decorated.astis an exportedAstNode; the introspect and model classes,BaseModelManager,Factory,Serializerand the serializer visitors carry concrete field and return types; the validators take their metamodel nodes (ICollectionSizeValidator,IStringRegexValidator/IStringLengthValidator, the three domain validators);ModelFile.getDeclarations()is generic, sogetAssetDeclarations()and friends return their own type;NullUtil.isNullandModelUtil.isValidIdentifierare type predicates.concerto-utilnow exportsWritableModelFile/WriteModelsOptions, andconcerto-ctotypesparse()asIModel.Three latent bugs it surfaced.
PropertyandModelFilepassed an always-undefinedthis.modelFiletoIllegalModelException;ScalarDeclarationpassedthis.ast.name.locationas that exception's modelFile argument, which was alwaysundefinedsinceast.nameis a string; andClassDeclaration.declarationKind()answered''for any subclass missing an override, which_resolveSuperType()uses to decide whether an extends clause is legal. It throws now.Runtime behaviour is unchanged apart from those three exception arguments.
Property.decoratoris gone (write-only, alwaysnull), andIdentifiable.$timestampis typedDayjs— it always held one; only the JSDoc saidstring.Two follow-ups left deliberately undone:
Decorator.getArguments()could returnDecoratorLiteralUnion[]straight from the AST instead of the projected shape it builds today (breaking change to a public method), andMapDeclaration's constructor callsthis.process()afterDeclaration's constructor already did, so every map declaration builds a throwawayMapKeyType/MapValueTypepair.Verification
postbuild, sonpm run buildfails if the emitted.mjsis wrong. It caught two real regressions during this work: an extensionlessdayjs/plugin/utcimport that Node ESM rejects, and named imports that the CJS lexer could not see.concerto-playgroundandtemplate-enginebuilt against packed tarballs.