You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support standard decorators in controller, register, target, targets and attr - #370
@controller, @register, @target, @targets and @attr now work with standard (TC39 2023-11) decorators as well as TypeScript's legacy experimentalDecorators. One import works in both modes, so a consumer can move off experimentalDecorators without a wrapper. Legacy calls take the existing code path, apart from the initializeAttrs order change described below. This follows github/memoize#52 and github/mini-throttle#45, and moves the logic of the @github-ui/catalyst wrapper from github/github-ui#43919 into Catalyst itself.
Why
TypeScript 5.0+, Babel and SWC (decoratorVersion: "2023-11") all support standard decorators. Today these decorators only accept the legacy (prototype, name) arguments. Under standard decorators TypeScript rejects them (TS1238, TS1240, TS1241), and at runtime they would get the wrong arguments.
How
Each decorator checks its second argument. An object with kind and addInitializer is a standard call. A string is a legacy call, which runs the existing code.
Decorator
Standard mode
@controller, @controller('name')
Registers the element from a class initializer, which runs after static fields such as observedAttributes and attrPrefix are assigned. That is when legacy class decorators run. A standard class decorator itself runs before them.
@attr
Decorates a field, accessor, getter or setter. Records the name in decorator metadata. @controller, defineObservedAttributes and initializeAttrs register it. Registration walks undecorated base classes, reads each class's own metadata, and registers base class attrs first.
@register
Defines the element from a class initializer, like @controller. Before this change it received the context object as the element name and threw.
@target, @targets
Decorate a public instance accessor (@target accessor output!: HTMLElement). Each returns a getter for findTarget(s) and a setter that throws TypeError, matching the getter-only legacy property. Standard decorators can't decorate declare fields, and a plain field would shadow the getter.
Attr initialization order:initializeAttrs reads each attr's current value as it goes, so a getter attr whose default reads another attr depends on that attr being initialized first. Standard decorators apply getters before fields, and overrides, subclasses and mixed legacy/standard classes break any rule based on registration order alone. initializeAttrs now initializes:
Field and accessor attrs, in registration order, as legacy decorators always have. An @attr accessor stores its value like a field and replaces a legacy @attr declare field, so it initializes with fields. Otherwise, when setting a missing attr's attribute runs connectedCallback early, that callback would see different attrs set than with the legacy field. Registration order puts base classes first and, within a class, standard attrs before legacy attr() calls, which can only follow the class definition. Fields read nothing. They're detected as own instance properties, or names with no accessor on the classes above HTMLElement. That covers fields declared without a value, including ones named like built-in accessors such as title.
Getter and setter attrs with a matching HTML attribute, checked after fields initialize because field callbacks may add attributes.
The remaining getter and setter attrs. Each returns its default both before and after it's initialized.
Standard decorators apply accessor decorators before field decorators, so a class mixing @attr accessors and fields registers, and initializes, its accessors first. The docs recommend @attr fields, which keep declaration order, as legacy decorators do. A test pins this order.
How initializeAttrs tells getter and setter attrs from stored ones: standard decorators record each attr's kind in the class's decorator metadata, so another decorator wrapping an @attr accessor doesn't change it. A subclass that redefines an inherited standard attr without decorating it, such as with a legacy getter, is classified by its own definition. Without metadata (legacy decorators, direct attr() calls or explicit initializeAttrs names), only a getter without a setter on the prototype chain counts as a getter attr, looking no further than the first native prototype. Anything with a setter, such as an auto-accessor or a getter and setter pair, keeps registration order as in v1.8.1. Because the search stops at the first native prototype, an attr named like a built-in accessor, such as value on an HTMLInputElement subclass, also stays a field. Whether a prototype is built in is cached per prototype, so this costs one source read per class, not per element. @controller, @register and @defineObservedAttributes throw a TypeError when they decorate anything but a class.
One case stays order-dependent: two getter attrs that both have HTML attributes, where the first declared reads the second. Legacy decorators on main behave the same way.
Reflection and attributeChangedCallback order for field attrs is unchanged. For legacy classes, the visible change is that getter attrs without a setter now initialize after field attrs, so such a getter's default can read a field's HTML value whatever the declaration order. A legacy getter and setter pair keeps registration order, as in v1.8.1, because without decorator metadata Catalyst can't tell it from an auto-accessor. With standard decorators, the pair initializes after fields. Dasherized attribute names are cached across elements, which keeps this at main's speed (see Runtime cost).
defineObservedAttributes also works as a standard class decorator. It waits for a class initializer, because TypeScript attaches Symbol.metadata only after class decorators run. Its one-argument legacy overload stays last, so Parameters and callback uses such as classes.map(defineObservedAttributes) keep their types.
Other members (static, private, symbol-named, or the wrong kind) throw a TypeError naming the supported kinds. TypeScript also rejects them at compile time, because it passes literal static/private types.
Symbol.metadata: the key is looked up for each class, with a Symbol.for('Symbol.metadata') fallback like the SWC and Babel helpers. It isn't cached at module load, because another library may define Symbol.metadata later. TypeScript only emits decorator metadata when Symbol.metadata exists at class definition, and no browser defines it natively yet. So when it's missing, Catalyst defines it as Symbol.for('Symbol.metadata') on import, as Lit does. This is the one exception to the "no polyfills" note in the guide, and the docs say so. The assignment is wrapped in try, so importing still works when Symbol is frozen (SES lockdown()).
Types: the standard overloads use small structural context types in src/decorator-context.ts rather than ClassDecoratorContext and friends. That way the published .d.ts still loads on TypeScript before 5.0. Legacy overloads come last and keep their signatures. One public type changes: controller(name) returns ControllerDecorator, an overloaded call signature that adds the standard shape. It's still assignable to (classObject: CustomElementClass) => void.
Compatibility
I don't believe this is a breaking change, based on the checks below. I packed the published 1.8.1 and this branch with npm pack and type-checked a consumer against each with skipLibCheck: false. The consumer used:
@controller with and without a name
@target/@targets on declare and ! fields (accessors in standard mode)
@attr on string, number and boolean fields, and on a getter/setter pair
direct controller(...), attr(...) and target(...) calls
assignment of controller(name) to the legacy decorator type
lib/abilities.js
a @ts-expect-error for an attr of type Date
The standard consumer also checks that plain-field and static @target uses are rejected.
TypeScript
Mode
1.8.1
This branch
4.5.5
experimentalDecorators
pass
pass
4.9.5
experimentalDecorators
pass
pass
5.0.4
experimentalDecorators
pass
pass
5.2.2
experimentalDecorators
pass
pass
5.9.3
experimentalDecorators
pass
pass
5.0.4
standard
fails (TS1238, TS1240, TS1241)
pass
5.2.2
standard
fails (TS1238, TS1240, TS1241)
pass
5.9.3
standard
fails (TS1240, TS1241)
pass
@attr in standard mode needs decorator metadata, which TypeScript emits from 5.2. On 5.0 and 5.1 it type-checks but throws @attr requires decorator metadata when the class is defined. @controller and @target/@targets work from 5.0.
Legacy runtime: all existing tests pass unchanged. The legacy path now also calls registerStandardAttrs, which finds no metadata on legacy classes and leaves their attrs alone. The only legacy behaviour change is the initializeAttrs order above, which has shared tests.
Tests and tooling
npm test runs web-test-runner twice, so the same behaviour tests cover both modes:
Legacy run (web-test-runner.config.js): all of test/*.ts, compiled by esbuild with legacy decorators, as before. 147 tests.
Standard run (web-test-runner-standard.config.js): the shared decorator tests test/attr.ts, test/bind.ts, test/controller.ts and test/register.ts, compiled with standard decorators, plus test/standard/*.ts. 98 tests. A plugin compiles tests and source with ts.transpileModule to native ES2022 class fields with useDefineForClassFields: true, the output of a modern TypeScript build. It replaces the esbuild plugin, which only lowers legacy decorators and renames classes when lowering them; Catalyst derives tag names from class names.
Targets: the target assertions live in test/helpers/target-tests.ts. test/target.ts (@target foo!) and test/standard/target.ts (@target accessor foo!) each define the fixture and call the helper.
Shared cases, now run in both modes:
statics assigned before define
controller(name)(Class) registering attrs
attr inheritance from undecorated bases (3 levels, base first), from parent controllers, and between sibling subclasses
manual defineObservedAttributes/initializeAttrs
assigning to a target throws
Standard only (test/standard):
@attr accessor
a late Symbol.metadata
missing metadata
the polyfill (metadata.ts loads Catalyst before Lit)
wrong-kind errors and named assignment errors
Legacy only: the abilities/v2 decorator tests (ability, controllable, mark, providable), which this PR doesn't change.
Type checks:test/types/decorators.ts and the shared test files type-check in both modes. npm run lint runs tsc and tsc -p test/standard.
Frozen Symbol:test/frozen-symbol.ts imports Catalyst with Symbol frozen.
Mutation checks: each regression test fails without its fix:
registering without addInitializer
caching the metadata key
no base-class walk
appending to inherited metadata
no polyfill
no try around it
no registration in defineObservedAttributes/initializeAttrs
Breaking only the standard @attr path fails the standard run, including shared test/controller.ts and test/attr.ts, while the legacy run still passes.
Tooling changes needed for the above:
typescript ^4.8.2 → ^5.9.3. Standard decorator metadata needs 5.2.
@typescript-eslint/* ^5.36.1 → ^5.62.0, for TS 5 syntax support. Prettier 2.6.2 → 2.8.8 in the lockfile only, within eslint-plugin-github's ^2.2.1 range, because 2.6 can't parse accessor.
tsconfig.json sets "types": ["mocha"]. TS 5.9 rejects the transitive @types/node@17 that was auto-included before.
src/bind.ts: removed a dead || 'handleEvent' after an object literal (always truthy), which TS 5.9 flags as TS2872. No behaviour change.
size-limit for {controller, attr, target, targets}: 2.5 kB → 3.4 kB. The bundle is 3.33 kB, up from 2.31 kB built the same way from main.
Verification beyond CI
Other compilers. The standard run's test files, compiled with esbuild 0.28, Babel 8 (@babel/plugin-proposal-decorators2023-11) and SWC 1.16 (decoratorVersion: "2023-11"), each to ES2022 with define semantics, pass everything except throws a clear error without decorator metadata. That test expects TypeScript's behaviour of emitting no metadata when Symbol.metadata is missing; those compilers always create it, so @attr works there. This run found that @defineObservedAttributes as a class decorator returned addInitializer's result, which esbuild rejects; it now returns nothing, with a test.
useDefineForClassFields. Standard decorators pass with it on and off. Legacy decorators pass with it off, and with it on everything except test/target.ts (see the docs on declare). That file hangs instead of failing because @web/dev-server-core calls structuredClone on results containing DOM elements (Sinon Chai calledWithMatch causes structuredClone to error in the test runner modernweb-dev/web#2772).
Existing tests.main's unmodified test/ directory and web-test-runner.config.js pass against this branch's src: 131 of 131.
Released tests.v1.8.1's unmodified test/ passes against this branch's src at bf5c10c: 129 of 129.
Legacy behavior changes. This branch's legacy tests, run against v1.8.1's src, fail 5 of 147. Three are the attr order fixes above, where v1.8.1 throws or reads the wrong value for a getter attr that reads a field. Two are from 940446f on main (bind subscription cleanup), which isn't part of this PR but ships with the next release. /view-components decorates only fields with @attr, so the getter order change doesn't affect it.
Legacy types. A strict experimentalDecorators consumer type-checks identically against v1.8.1's and this branch's declarations on TypeScript 4.5, 4.7, 4.9, 5.0, 5.2, 5.4 and 5.9, with skipLibCheck off: valid members pass, and an @attr of an object type fails on both.
Output.lib still targets ES2020, with no newer syntax.
@primer/view-components. At primer/view_components@b88fc19, tsc and its JS build pass against this branch's package, as they do against v1.8.1. primer_view_components.js grows from 185,953 to 188,431 bytes.
Other browsers. At 5a52b0b, with @web/test-runner-playwright (Playwright 1.65): WebKit passes both runs (147 legacy, 99 standard). Firefox passes every file except test/controller.ts, which runs no tests in Firefox at 92ed9d5 and at v1.8.1 either.
Consumer types. A legacy consumer type-checks identically against published 1.8.1 and this branch on TypeScript 4.5.5, 4.9.5, 5.0.4, 5.2.2 and 5.9.3, including exact Parameters/ReturnType identity checks for target, targets, register and defineObservedAttributes. Removing the repeated legacy overload makes that check fail, so it catches breaks. A standard consumer fails on 1.8.1 (TS1238/TS1240/TS1241) and passes on this branch on 5.0.4, 5.2.2 and 5.9.3.
Docs
The v1 guides (decorators, targets, attrs and "you will need") now cover:
standard decorators
the accessor requirement for @target/@targets
TypeScript 5.2+ for @attr metadata
the Symbol.metadata definition
attr initialization order
using declare for legacy @target/@targets when useDefineForClassFields is on. TypeScript turns that on by default for ES2022+ targets, and !, ? or | undefined fields shadow the getter.
Runtime cost
Measured in headless Chrome by setting innerHTML on a connected container to 10,000 elements, each with 2 @targets, a @targets list and 2 @attrs (one with a matching HTML attribute, one reflected). That timing covers parsing, upgrade, attr initialization and connect. Builds come from each commit's lib/, with test code compiled by TypeScript to ES2022. Values are medians of 7 interleaved rounds (each round's value is the median of 15 iterations after 5 warmups), with the range across rounds.
Render 10,000 elements
Target/attr reads
legacy, main
37.7 ms (37.4–39.1)
13.8 ms
legacy, this branch
37.1 ms (36.6–39.0)
14.0 ms
standard, this branch
37.8 ms (36.9–38.9)
14.2 ms
Final run at abdca2e, 11 interleaved rounds: legacy main 41.3 ms (39.0–44.5), legacy branch 39.2 ms (38.0–43.7), standard branch 38.6 ms (37.1–43.0). Reads 14.0–14.5 ms for all three. Load spiked during this run; across five runs since the field-first order, the branch's legacy median was at or below main's each time.
Legacy: no measurable change from main.
Standard: level with legacy. An earlier revision of this branch took 41.1 ms. Caching dasherized attribute names in initializeAttrs removed the gap, which also covers the attribute-first ordering.
Each run checks that every element connected with its attrs initialized and that targets resolve.
The machine was shared and under load during these runs; interleaving the variants keeps the comparison fair, but absolute numbers will differ elsewhere.
Build note: Catalyst derives tag names from class names. If TypeScript emits standard decorators as ES2022 and esbuild then lowers that to an older target, the class is renamed (_a). A bare @controller then throws when it defines the element. @controller('tag') still works; the only side effect is that register sets window._a, as legacy builds with minifiers already do. esbuild's own decorator lowering keeps names, and keepNames fixes the TS-then-esbuild case. The decorators guide now says this.
Not supported in standard mode
@target/@targets on plain fields, getters or setters. They need an accessor.
Static, private or symbol-named members for any member decorator. This matches what the legacy runtime effectively supports.
Standard @target doesn't record the name in meta(proto, 'target'). Nothing in 1.x reads that set.
npm run lint, npm run build, npm test (147 legacy + 98 standard, Chromium) and npm run size pass locally. Standard decorators also pass with useDefineForClassFields on and off. Legacy decorators pass with it off, and with it on everything except test/target.ts, whose @target foo! fields shadow the getters as described in the docs.
The same exports now accept TypeScript's legacy experimentalDecorators and
standard (TC39 2023-11) decorator calls. Legacy calls take the existing code
path.
- @controller registers from a class initializer, after static fields.
- @attr records names in decorator metadata; @controller registers them,
walking undecorated base classes. Symbol.metadata is defined if missing.
- @target/@targets decorate public instance accessors and throw on assignment.
- Context types are structural so the .d.ts loads on TypeScript < 5.0.
- Tests: test/standard runs in the browser compiled with standard decorators;
test/types fixtures type-check in both modes via npm run lint.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…in manual setup
Importing Catalyst no longer throws when Symbol is frozen (SES lockdown).
defineObservedAttributes and initializeAttrs now pick up standard @attr
members without @controller, as they do for legacy decorators.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
npm test now runs web-test-runner twice. The second run compiles
test/attr.ts, test/bind.ts and test/controller.ts with standard decorators,
plus test/standard for standard-only syntax. Target assertions live in
test/helpers/target-tests.ts, used by a legacy and a standard fixture.
Cross-mode cases moved from test/standard into the shared files.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@register threw under standard decorators because it received the context
object as the element name. It now defines the element from a class
initializer, like @controller. test/register.ts runs in both modes.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
mattcosta7
changed the title
Support standard decorators in controller, target, targets and attr
Support standard decorators in controller, register, target, targets and attr
Nov 13, 2026
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Attribute registration can skip inherited attributes or initialize them after child attributes in mixed decorator modes, causing missing reflection or reflected defaults instead of existing data values.
Adds standard decorator support to Catalyst’s v1 decorators while preserving legacy TypeScript usage, allowing consumers to migrate without changing imports.
Changes:
Add dual-mode decorator handling, deferred class registration, and metadata-backed attribute registration.
Expand runtime and type checks across both decorator modes.
Document standard decorator requirements and update supporting tooling.
File
Description
web-test-runner.config.js
Restrict legacy test discovery to TypeScript files.
web-test-runner-standard.config.js
Compile and run tests with standard decorators.
tsconfig.json
Exclude standard-only tests from legacy type checks.
test/types/decorators.ts
Check shared decorator types and legacy compatibility.
test/target.ts
Reuse shared target assertions for legacy decorators.
test/standard/tsconfig.json
Configure standard decorator type checks.
test/standard/target.ts
Test accessor targets and unsupported member errors.
test/standard/metadata.ts
Verify metadata setup without Lit loading first.
test/standard/attr.ts
Cover standard attr forms and metadata behavior.
test/helpers/target-tests.ts
Share target behavior tests between modes.
test/frozen-symbol.ts
Check imports when Symbol is frozen.
test/controller.ts
Cover direct registration and static-field timing.
test/attr.ts
Cover inheritance and manual attr initialization.
src/target.ts
Support standard accessor decorators for targets.
src/register.ts
Defer standard decorator registration until class initialization.
src/decorator-context.ts
Add structural context types and metadata helpers.
src/controller.ts
Support both decorator modes and named overloads.
src/bind.ts
Remove an unreachable fallback without changing behavior.
src/attr.ts
Record and register standard decorator metadata.
package.json
Update tooling, dual-mode checks, and bundle budget.
package-lock.json
Lock updated compiler and linting dependencies.
docs/_guide/you-will-need.md
Explain decorator compatibility and metadata setup.
docs/_guide/targets.md
Document the standard-mode accessor requirement.
docs/_guide/decorators.md
Explain standard syntax, compatibility, and build constraints.
When a base class uses standard @attr and a subclass records attrs with
legacy decorators or direct attr() calls, registerStandardAttrs appended
the base attrs after the subclass's, and skipped them entirely when the
base was registered after the subclass's meta snapshot was taken.
Rebuild the set base-first whenever standard attrs are involved, seeded
from the nearest registered ancestor. Pure legacy classes are unchanged.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- target/targets/register: list the legacy overloads first, so calls
with untyped arguments keep their legacy return types.
- decorator contexts: type metadata as `object | undefined`, so standard
decorators type-check with exactOptionalPropertyTypes.
- @attr: find a class's own metadata by Catalyst's attr lists instead of
the current Symbol.metadata key, so base classes defined before another
library redefined Symbol.metadata keep their attrs.
- @attr: initialize fields and accessors before getters and setters in
the same class. Standard decorators apply getter and setter decorators
first, so a getter could read a field before it was attribute-backed.
- @attr: reject setters whose type isn't a string, number or boolean in
standard mode, as legacy mode already does.
Type checks in test/types now also run with exactOptionalPropertyTypes
and without Lit's Symbol.metadata declaration.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
A standard subclass of an unregistered legacy base put its own attrs
before the inherited legacy ones. Walk the chain base to derived and add
each class's own legacy attrs, then its standard attrs.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Listing the legacy overload first fixed calls with untyped arguments, but
ReturnType and Parameters read the last overload, which was then the
standard one. List the legacy overload both first and last.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Premature class caching can leave standard @attr fields unobserved and unreflected, while registration-order defects cause dependent getters to miss initial attribute values.
- Defer @defineObservedAttributes as a standard class decorator until the
class's decorator metadata is attached, so @controller still registers attrs.
- Order standard stored attrs before legacy attrs on the same class.
- Move getter and setter attrs that override a base attr to the subclass's
position, with both standard and legacy decorators.
- Raise the lib/index.js size budget to 3.1kb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Attribute registration order breaks for subclass overrides and duplicate getter/setter decorations, causing dependent getters to miss existing HTML attribute values during initialization.
Preserve subclass legacy override order in mixed-mode merges
src/attr.ts:101
A standard-decorated base label getter stays ahead of a legacy subclass's input field even when the subclass redecorates label after input. If the overriding getter reads input, data-input="attribute" is ignored when the initial data-label is computed. Preserve the subclass's explicit legacy override positions without moving inherited snapshot entries, and add a mixed-mode override regression test.
- When standard and legacy attrs are merged, treat legacy attrs with a
getter on their class as computed, so they initialize after stored attrs,
including when they override a base attr.
- Restore the one-argument defineObservedAttributes overload as the last
signature, so callbacks and Parameters keep their legacy types.
- Drop the redundant registerStandardAttrs call in controller, since
defineObservedAttributes registers attrs before the element is defined.
- Accept any Symbol.metadata symbol in the metadata test.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
initializeAttrs now defines attrs that have a matching HTML attribute before
the others. A getter attr that reads another attr then sees its attribute value
whatever the registration order, and an attr without an attribute returns its
default before and after initialization. This replaces the stored/computed
split and the override-moving rules, which fixed some orderings by breaking
others (an overridden attr read by a base getter, a decorated getter and setter
pair).
The bundle shrinks back under the original 3 kB budget.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Attribute initialization ordering can evaluate getters before their dependencies are initialized and cause legacy callbacks to overwrite existing HTML attribute values.
The attribute-first sort dasherized each name several times per element and
made rendering 10,000 attr elements about 18% slower than main. Partition attrs
by whether they have an HTML attribute, dasherizing each once, and cache the
dasherized names across elements.
Rendering 10,000 elements with innerHTML (median of 7 interleaved runs):
legacy 37.1 ms (main 37.7 ms), standard 37.8 ms (41.1 ms before).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Field attrs read nothing, so initialize them first in registration order, as
legacy decorators always have. Getter, setter and accessor attrs follow, those
with an HTML attribute first. This keeps legacy attributeChangedCallback
ordering for fields, and lets a getter's default read fields that have HTML
attributes or no initial value. Fields are detected as own instance properties,
or names with no accessor on the prototype chain.
Raises the lib/index.js size budget to 3.1kb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Attribute initialization ordering can overwrite existing HTML attribute values in legacy mode and cause dependent getters to throw when callbacks add attributes.
…ields
- defineObservedAttributes returned addInitializer's result as a class
decorator. esbuild's addInitializer returns a number, and esbuild throws when
a class decorator returns anything but a function. Return nothing.
- The standard test run now compiles tests and source with TypeScript to
native ES2022 class fields with define semantics, the output of a modern
TypeScript build, instead of lowering to ES2020 and passing through esbuild.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…in accessors
- Fields named like built-in accessors, such as an uninitialized `title` in
legacy assignment mode, stay in the field group, so their reflection and
callbacks keep declaration order. Only accessors on classes extending
HTMLElement count.
- Check HTML attribute presence for getter, setter and accessor attrs after
fields initialize, because field callbacks may add attributes.
- Skip the accessor pass when a class has none.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Mixed standard and legacy attribute registration fails to preserve field order, allowing a data-ready callback to overwrite an HTML-provided data-status value.
Standard decorators record attrs when the class is defined, and legacy attr()
calls on that class can only follow, so merge them in that order. Otherwise a
standard field's attributeChangedCallback could run after a later legacy
field initialized, and overwrite its HTML value.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because decorator metadata timing and accessor initialization order can cause runtime failures or leave attributes unobserved and unreflected.
An `@attr accessor` stores its value like a field, and replaces a legacy
`@attr declare` field when code moves to standard decorators. Grouping it
with getters initialized attrs that have HTML attributes first, which
changed what connectedCallback sees when setting a missing attr's
attribute runs it early. Tag auto-accessor getters so they initialize
with fields, as the legacy fields they replace did.
Raises the lib/index.js size budget to 3.2kb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Standard decorators apply accessor decorators before field decorators,
so a class mixing `@attr` fields and accessors registers, and initializes,
its accessors first. Document the order, recommend fields to keep
declaration order as legacy decorators do, and test the order.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
initializeAttrs guessed whether an attr computes its value by finding an
accessor on the prototype chain. That misclassified two cases:
- An `@attr accessor` wrapped by another accessor decorator. Its getter
was replaced, so it initialized after getter attrs that read it.
- An attr named like an accessor of a built-in base element, such as
`value` on an HTMLInputElement subclass. The walk only stopped at
HTMLElement.prototype, so the attr moved after the others, changing
callback order from v1.8.1.
Standard decorators now record whether an attr is a getter or setter in
the class's decorator metadata, unless a subclass redefines it. Legacy
attrs keep the prototype walk, which now stops at the first native
prototype.
Raises the lib/index.js size budget to 3.3kb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
From a ship-check of 196af15:
- initializeAttrs with explicit names now registers standard attrs first,
so it knows an `@attr accessor` stores its value.
- A class's list of standard getter and setter attrs is read only from
its own metadata. Metadata inherits from the parent class's, so a
subclass overriding an `@attr` getter with an accessor was treated as
a getter.
- Whether a prototype belongs to a built-in class is cached per
prototype. Reading the class source for every element made legacy
getter attrs slower as the class grew.
- `@controller`, `@register` and `@defineObservedAttributes` throw a
TypeError when they decorate anything but a class, as `@attr` and
`@target` do for unsupported members.
Raises the lib/index.js size budget to 3.4kb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
TypeScript's standard decorator output declares the class twice under
one name, and esbuild renames one of them in any transform or bundle,
not only when lowering. Without a tag name, `@controller` then defines
`hello-world-element2` silently. `keepNames` only prevents this from
esbuild 0.18.2. Recommend passing a tag name with standard decorators.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Without standard decorator metadata, an auto-accessor and a getter and
setter pair look the same on the prototype. Treating both as getter
attrs reordered undecorated accessors registered by `attr()` calls or
explicit `initializeAttrs` names, unlike v1.8.1. Only a getter without
a setter now counts as a getter attr; anything with a setter keeps
registration order.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- `@attr` defines a class's own list of attrs in its decorator metadata
instead of assigning it. Metadata inherits from the parent class's,
and assigning fails when the parent's metadata is frozen.
- The built-in prototype check only reads `constructor` when it's a
function, so an attr named `constructor` initializes as in v1.8.1.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This branch has not been deployed
No deployments
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
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.
@controller,@register,@target,@targetsand@attrnow work with standard (TC39 2023-11) decorators as well as TypeScript's legacyexperimentalDecorators. One import works in both modes, so a consumer can move offexperimentalDecoratorswithout a wrapper. Legacy calls take the existing code path, apart from theinitializeAttrsorder change described below. This follows github/memoize#52 and github/mini-throttle#45, and moves the logic of the@github-ui/catalystwrapper from github/github-ui#43919 into Catalyst itself.Why
TypeScript 5.0+, Babel and SWC (
decoratorVersion: "2023-11") all support standard decorators. Today these decorators only accept the legacy(prototype, name)arguments. Under standard decorators TypeScript rejects them (TS1238, TS1240, TS1241), and at runtime they would get the wrong arguments.How
Each decorator checks its second argument. An object with
kindandaddInitializeris a standard call. A string is a legacy call, which runs the existing code.@controller,@controller('name')observedAttributesandattrPrefixare assigned. That is when legacy class decorators run. A standard class decorator itself runs before them.@attraccessor, getter or setter. Records the name in decorator metadata.@controller,defineObservedAttributesandinitializeAttrsregister it. Registration walks undecorated base classes, reads each class's own metadata, and registers base class attrs first.@register@controller. Before this change it received the context object as the element name and threw.@target,@targetsaccessor(@target accessor output!: HTMLElement). Each returns a getter forfindTarget(s)and a setter that throwsTypeError, matching the getter-only legacy property. Standard decorators can't decoratedeclarefields, and a plain field would shadow the getter.Attr initialization order:
initializeAttrsreads each attr's current value as it goes, so a getter attr whose default reads another attr depends on that attr being initialized first. Standard decorators apply getters before fields, and overrides, subclasses and mixed legacy/standard classes break any rule based on registration order alone.initializeAttrsnow initializes:accessorattrs, in registration order, as legacy decorators always have. An@attr accessorstores its value like a field and replaces a legacy@attr declarefield, so it initializes with fields. Otherwise, when setting a missing attr's attribute runsconnectedCallbackearly, that callback would see different attrs set than with the legacy field. Registration order puts base classes first and, within a class, standard attrs before legacyattr()calls, which can only follow the class definition. Fields read nothing. They're detected as own instance properties, or names with no accessor on the classes aboveHTMLElement. That covers fields declared without a value, including ones named like built-in accessors such astitle.Standard decorators apply accessor decorators before field decorators, so a class mixing
@attraccessors and fields registers, and initializes, its accessors first. The docs recommend@attrfields, which keep declaration order, as legacy decorators do. A test pins this order.How
initializeAttrstells getter and setter attrs from stored ones: standard decorators record each attr's kind in the class's decorator metadata, so another decorator wrapping an@attr accessordoesn't change it. A subclass that redefines an inherited standard attr without decorating it, such as with a legacy getter, is classified by its own definition. Without metadata (legacy decorators, directattr()calls or explicitinitializeAttrsnames), only a getter without a setter on the prototype chain counts as a getter attr, looking no further than the first native prototype. Anything with a setter, such as an auto-accessor or a getter and setter pair, keeps registration order as inv1.8.1. Because the search stops at the first native prototype, an attr named like a built-in accessor, such asvalueon anHTMLInputElementsubclass, also stays a field. Whether a prototype is built in is cached per prototype, so this costs one source read per class, not per element.@controller,@registerand@defineObservedAttributesthrow a TypeError when they decorate anything but a class.One case stays order-dependent: two getter attrs that both have HTML attributes, where the first declared reads the second. Legacy decorators on
mainbehave the same way.Reflection and
attributeChangedCallbackorder for field attrs is unchanged. For legacy classes, the visible change is that getter attrs without a setter now initialize after field attrs, so such a getter's default can read a field's HTML value whatever the declaration order. A legacy getter and setter pair keeps registration order, as inv1.8.1, because without decorator metadata Catalyst can't tell it from an auto-accessor. With standard decorators, the pair initializes after fields. Dasherized attribute names are cached across elements, which keeps this atmain's speed (see Runtime cost).defineObservedAttributesalso works as a standard class decorator. It waits for a class initializer, because TypeScript attachesSymbol.metadataonly after class decorators run. Its one-argument legacy overload stays last, soParametersand callback uses such asclasses.map(defineObservedAttributes)keep their types.Other members (static, private, symbol-named, or the wrong kind) throw a
TypeErrornaming the supported kinds. TypeScript also rejects them at compile time, because it passes literalstatic/privatetypes.Symbol.metadata: the key is looked up for each class, with aSymbol.for('Symbol.metadata')fallback like the SWC and Babel helpers. It isn't cached at module load, because another library may defineSymbol.metadatalater. TypeScript only emits decorator metadata whenSymbol.metadataexists at class definition, and no browser defines it natively yet. So when it's missing, Catalyst defines it asSymbol.for('Symbol.metadata')on import, as Lit does. This is the one exception to the "no polyfills" note in the guide, and the docs say so. The assignment is wrapped intry, so importing still works whenSymbolis frozen (SESlockdown()).Types: the standard overloads use small structural context types in
src/decorator-context.tsrather thanClassDecoratorContextand friends. That way the published.d.tsstill loads on TypeScript before 5.0. Legacy overloads come last and keep their signatures. One public type changes:controller(name)returnsControllerDecorator, an overloaded call signature that adds the standard shape. It's still assignable to(classObject: CustomElementClass) => void.Compatibility
I don't believe this is a breaking change, based on the checks below. I packed the published
1.8.1and this branch withnpm packand type-checked a consumer against each withskipLibCheck: false. The consumer used:@controllerwith and without a name@target/@targetsondeclareand!fields (accessors in standard mode)@attron string, number and boolean fields, and on a getter/setter paircontroller(...),attr(...)andtarget(...)callscontroller(name)to the legacy decorator typelib/abilities.js@ts-expect-errorfor an attr of typeDateThe standard consumer also checks that plain-field and static
@targetuses are rejected.1.8.1experimentalDecoratorsexperimentalDecoratorsexperimentalDecoratorsexperimentalDecoratorsexperimentalDecorators@attrin standard mode needs decorator metadata, which TypeScript emits from 5.2. On 5.0 and 5.1 it type-checks but throws@attr requires decorator metadatawhen the class is defined.@controllerand@target/@targetswork from 5.0.Legacy runtime: all existing tests pass unchanged. The legacy path now also calls
registerStandardAttrs, which finds no metadata on legacy classes and leaves their attrs alone. The only legacy behaviour change is theinitializeAttrsorder above, which has shared tests.Tests and tooling
npm testruns web-test-runner twice, so the same behaviour tests cover both modes:Legacy run (
web-test-runner.config.js): all oftest/*.ts, compiled by esbuild with legacy decorators, as before. 147 tests.Standard run (
web-test-runner-standard.config.js): the shared decorator teststest/attr.ts,test/bind.ts,test/controller.tsandtest/register.ts, compiled with standard decorators, plustest/standard/*.ts. 98 tests. A plugin compiles tests and source withts.transpileModuleto native ES2022 class fields withuseDefineForClassFields: true, the output of a modern TypeScript build. It replaces the esbuild plugin, which only lowers legacy decorators and renames classes when lowering them; Catalyst derives tag names from class names.Targets: the target assertions live in
test/helpers/target-tests.ts.test/target.ts(@target foo!) andtest/standard/target.ts(@target accessor foo!) each define the fixture and call the helper.Shared cases, now run in both modes:
controller(name)(Class)registering attrsdefineObservedAttributes/initializeAttrsStandard only (
test/standard):@attr accessorSymbol.metadatametadata.tsloads Catalyst before Lit)Legacy only: the abilities/v2 decorator tests (
ability,controllable,mark,providable), which this PR doesn't change.Type checks:
test/types/decorators.tsand the shared test files type-check in both modes.npm run lintrunstscandtsc -p test/standard.Frozen
Symbol:test/frozen-symbol.tsimports Catalyst withSymbolfrozen.Mutation checks: each regression test fails without its fix:
addInitializertryaround itdefineObservedAttributes/initializeAttrsBreaking only the standard
@attrpath fails the standard run, including sharedtest/controller.tsandtest/attr.ts, while the legacy run still passes.Tooling changes needed for the above:
typescript^4.8.2 → ^5.9.3. Standard decorator metadata needs 5.2.@typescript-eslint/*^5.36.1 → ^5.62.0, for TS 5 syntax support. Prettier 2.6.2 → 2.8.8 in the lockfile only, withineslint-plugin-github's^2.2.1range, because 2.6 can't parseaccessor.tsconfig.jsonsets"types": ["mocha"]. TS 5.9 rejects the transitive@types/node@17that was auto-included before.src/bind.ts: removed a dead|| 'handleEvent'after an object literal (always truthy), which TS 5.9 flags as TS2872. No behaviour change.{controller, attr, target, targets}: 2.5 kB → 3.4 kB. The bundle is 3.33 kB, up from 2.31 kB built the same way frommain.Verification beyond CI
@babel/plugin-proposal-decorators2023-11) and SWC 1.16 (decoratorVersion: "2023-11"), each to ES2022 with define semantics, pass everything exceptthrows a clear error without decorator metadata. That test expects TypeScript's behaviour of emitting no metadata whenSymbol.metadatais missing; those compilers always create it, so@attrworks there. This run found that@defineObservedAttributesas a class decorator returnedaddInitializer's result, which esbuild rejects; it now returns nothing, with a test.useDefineForClassFields. Standard decorators pass with it on and off. Legacy decorators pass with it off, and with it on everything excepttest/target.ts(see the docs ondeclare). That file hangs instead of failing because@web/dev-server-corecallsstructuredCloneon results containing DOM elements (Sinon Chai calledWithMatch causes structuredClone to error in the test runner modernweb-dev/web#2772).main's unmodifiedtest/directory andweb-test-runner.config.jspass against this branch'ssrc: 131 of 131.v1.8.1's unmodifiedtest/passes against this branch'ssrcat bf5c10c: 129 of 129.v1.8.1'ssrc, fail 5 of 147. Three are the attr order fixes above, wherev1.8.1throws or reads the wrong value for a getter attr that reads a field. Two are from940446fonmain(bind subscription cleanup), which isn't part of this PR but ships with the next release./view-componentsdecorates only fields with@attr, so the getter order change doesn't affect it.experimentalDecoratorsconsumer type-checks identically againstv1.8.1's and this branch's declarations on TypeScript 4.5, 4.7, 4.9, 5.0, 5.2, 5.4 and 5.9, withskipLibCheckoff: valid members pass, and an@attrof an object type fails on both.libstill targets ES2020, with no newer syntax.tscand its JS build pass against this branch's package, as they do againstv1.8.1.primer_view_components.jsgrows from 185,953 to 188,431 bytes.@web/test-runner-playwright(Playwright 1.65): WebKit passes both runs (147 legacy, 99 standard). Firefox passes every file excepttest/controller.ts, which runs no tests in Firefox at 92ed9d5 and atv1.8.1either.1.8.1and this branch on TypeScript 4.5.5, 4.9.5, 5.0.4, 5.2.2 and 5.9.3, including exactParameters/ReturnTypeidentity checks fortarget,targets,registeranddefineObservedAttributes. Removing the repeated legacy overload makes that check fail, so it catches breaks. A standard consumer fails on1.8.1(TS1238/TS1240/TS1241) and passes on this branch on 5.0.4, 5.2.2 and 5.9.3.Docs
The v1 guides (decorators, targets, attrs and "you will need") now cover:
accessorrequirement for@target/@targets@attrmetadataSymbol.metadatadefinitiondeclarefor legacy@target/@targetswhenuseDefineForClassFieldsis on. TypeScript turns that on by default for ES2022+ targets, and!,?or| undefinedfields shadow the getter.Runtime cost
Measured in headless Chrome by setting
innerHTMLon a connected container to 10,000 elements, each with 2@targets, a@targetslist and 2@attrs (one with a matching HTML attribute, one reflected). That timing covers parsing, upgrade, attr initialization and connect. Builds come from each commit'slib/, with test code compiled by TypeScript to ES2022. Values are medians of 7 interleaved rounds (each round's value is the median of 15 iterations after 5 warmups), with the range across rounds.mainFinal run at abdca2e, 11 interleaved rounds: legacy
main41.3 ms (39.0–44.5), legacy branch 39.2 ms (38.0–43.7), standard branch 38.6 ms (37.1–43.0). Reads 14.0–14.5 ms for all three. Load spiked during this run; across five runs since the field-first order, the branch's legacy median was at or belowmain's each time.main.initializeAttrsremoved the gap, which also covers the attribute-first ordering.The machine was shared and under load during these runs; interleaving the variants keeps the comparison fair, but absolute numbers will differ elsewhere.
Build note: Catalyst derives tag names from class names. If TypeScript emits standard decorators as ES2022 and esbuild then lowers that to an older target, the class is renamed (
_a). A bare@controllerthen throws when it defines the element.@controller('tag')still works; the only side effect is thatregistersetswindow._a, as legacy builds with minifiers already do. esbuild's own decorator lowering keeps names, andkeepNamesfixes the TS-then-esbuild case. The decorators guide now says this.Not supported in standard mode
@target/@targetson plain fields, getters or setters. They need anaccessor.@targetdoesn't record the name inmeta(proto, 'target'). Nothing in 1.x reads that set.npm run lint,npm run build,npm test(147 legacy + 98 standard, Chromium) andnpm run sizepass locally. Standard decorators also pass withuseDefineForClassFieldson and off. Legacy decorators pass with it off, and with it on everything excepttest/target.ts, whose@target foo!fields shadow the getters as described in the docs.