@verajs/autoloader 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,293 @@
1
1
  # @verajs/autoloader
2
2
 
3
- Lazy component loading by tag name (~0.6 KB gzip): the first time an undefined custom element
4
- appears inside an `autoloader`-marked component, its module is fetched from a bounded URL and
5
- defined. `extension: '.ts'` supports TypeScript dev servers.
3
+ Lazy component loading by tag name — <!--size:autoloader.gzip-->1.64 KB<!--/size:autoloader.gzip-->
4
+ gzipped, no dependencies, no build step required.
5
+
6
+ When an undefined custom element appears inside a component marked `autoloader`, its module is
7
+ fetched and defined. No manifest, no import list, no bundler plugin: the tag name *is* the module
8
+ name.
9
+
10
+ Discovery is **observed, not polled**. A marked component is watched once, so an element is found
11
+ whenever it enters the DOM — put there by a render, by `innerHTML`, by a third-party widget, or by
12
+ having been in the HTML file all along.
13
+
14
+ ```sh
15
+ npm i @verajs/autoloader
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ <!-- recipe -->
21
+ ```js
22
+ import { wire } from '@verajs/core';
23
+ import { autoloader } from '@verajs/autoloader';
24
+
25
+ const autoload = autoloader(import.meta.url, 'components');
26
+ wire(autoload); // watch every component as it renders
27
+ autoload(); // and scan whatever is already on the page
28
+ ```
29
+
30
+ ```html
31
+ <my-page autoloader>
32
+ <user-card></user-card> <!-- fetches components/user-card.js the first time it appears -->
33
+ </my-page>
34
+ ```
35
+
36
+ `rootDir` is almost always `import.meta.url` — every component URL is resolved relative to it, and
37
+ omitting `componentsDir` puts components beside the entry file.
38
+
39
+ `autoloader` returns **one function with three shapes**, plus two helpers:
40
+
41
+ | | |
42
+ | --- | --- |
43
+ | `autoload()` | scan the page for `[autoloader]` hosts and watch them |
44
+ | `autoload(element)` | watch that component |
45
+ | `autoload(shadowRoot)` | watch that root — no attribute needed, handing it over is the opt-in |
46
+ | `autoload.url(tag)` | the absolute URL it would fetch — **throws** if it would resolve outside `rootDir` |
47
+ | `autoload.retry(element)` | forget that this element's tag failed, and try again |
48
+
49
+ The instance is **also its own `wire` descriptor** — it carries `on: 'render'` at priority 75, so
50
+ `wire([renderer, autoload])` configures and installs in one call, and the scan runs after the
51
+ render that produced the markup. It replaced `setAutoloader`, a bespoke registrar that lived in
52
+ `@verajs/inserts`; every module now hands `wire` a descriptor, and this one is no exception.
53
+
54
+ Watching is idempotent: calling it twice on the same root does nothing the second time, which is why
55
+ it can be handed every component on every render.
56
+
57
+ Creating an autoloader does nothing on its own — no scanning, no listeners. `autoload()` is how a
58
+ hand-written page works with no framework involved at all, and you can call it again whenever new
59
+ markup lands:
60
+
61
+ ```html
62
+ <script type="module">
63
+ import { autoloader } from '@verajs/autoloader';
64
+ autoloader(import.meta.url, 'components')();
65
+ </script>
66
+
67
+ <div autoloader>
68
+ <user-card></user-card> <!-- loads, though nothing here renders -->
69
+ </div>
70
+ ```
71
+
72
+ A module script is deferred, so it runs after the page has parsed and the markup above is already
73
+ there.
74
+
75
+ ## Attributes
76
+
77
+ | | |
78
+ | --- | --- |
79
+ | `autoloader` | on a component, scan its tree for undefined elements. **Opt-in, per component** |
80
+ | `autoload-dir` | on an element, load it from a different directory |
81
+ | `autoload-ignore` | on an element, leave it alone. Applies to that element only, not its subtree |
82
+
83
+ Scanning is per-component on purpose: the insert scans the element's own tree, not the shadow roots
84
+ of its descendants, so each component that hosts lazily-loaded children carries the attribute.
85
+
86
+ It is `autoload-dir`, never HTML's global `dir` — `dir="rtl"` on any internationalised page would
87
+ otherwise have silently redirected component loading.
88
+
89
+ **All three are watched, not just read once.** Marking a component `autoloader` after it already has
90
+ a shadow root reaches inside it; repointing `autoload-dir` after a failed attempt tries the new
91
+ location; removing `autoload-ignore` lets an element load. None of that needed a re-insertion, which
92
+ is not a thing that happens.
93
+
94
+ ## Options
95
+
96
+ ```js
97
+ autoloader(import.meta.url, 'components', { extension: '.ts' });
98
+ ```
99
+
100
+ **`extension`** defaults to `.js`, with or without the leading dot. Set `.ts` so a TypeScript dev
101
+ server can autoload sources directly — it will not serve `foo.js` when only `foo.ts` exists.
102
+
103
+ **`resolve(tag, dir)`** replaces URL building entirely, for a layout `dir/tag.ext` cannot express:
104
+
105
+ ```js
106
+ autoloader(import.meta.url, 'components', {
107
+ resolve: (tag, dir) => `${dir}/${tag}/${tag}.js`, // components/user-card/user-card.js
108
+ });
109
+ ```
110
+
111
+ `dir` is the element's `autoload-dir` if it has one, otherwise `componentsDir`. The result is still
112
+ resolved against the entry file and still bounded by it, so a custom layout cannot reach anywhere
113
+ the default one could not.
114
+
115
+ ## Bounding
116
+
117
+ **Every resolved URL must stay inside the entry file's own directory**, and one that does not is
118
+ refused with a console error rather than fetched. Tag names cannot carry a `/` — the HTML parser
119
+ will not produce one — but `autoload-dir` is free text on an element, and turning markup into a
120
+ module URL is exactly the thing that needs bounding.
121
+
122
+ ```html
123
+ <x-y autoload-dir="https://example.com/x"></x-y> <!-- refused: absolute -->
124
+ <x-y autoload-dir="//example.com/x"></x-y> <!-- refused: protocol-relative -->
125
+ <x-y autoload-dir="../../../"></x-y> <!-- refused: escapes upward -->
126
+ <x-y autoload-dir="components?v=2"></x-y> <!-- refused: ? ends the path -->
127
+ ```
128
+
129
+ **A directory cannot contain `?` or `#`.** Both end the path, so the tag name would land in the
130
+ query or the fragment: `autoload-dir="components?v=2"` requests `components` with `x-y.js` inside
131
+ the query string, and the component file is never asked for. That is a *wrong* module rather than a
132
+ missing one, so it is refused rather than left to 404 — and note that containment does not catch it,
133
+ because such a URL is genuinely inside the entry's directory.
134
+
135
+ To cache-bust, use `resolve`, which owns URL building and can put the query where it belongs:
136
+
137
+ ```js
138
+ autoloader(import.meta.url, 'components', { resolve: (tag, dir) => `${dir}/${tag}.js?v=2` });
139
+ ```
140
+
141
+ A custom `resolve` is checked the same way. `rootDir` is your own code and is trusted; everything
142
+ derived from the DOM is not.
143
+
144
+ The check lives in `url()`, which is the one place a URL is built — so it holds for the loader and
145
+ for **you**. `autoload.url(tag, element)` throws rather than returning something the loader would
146
+ refuse: it is documented for preloading, and a `<link rel="modulepreload">` pointed at another
147
+ origin is the exact fetch this module declines to make. Discovery catches the throw, reports it once
148
+ and moves on, so a hostile attribute costs a console line rather than a broken page.
149
+
150
+ ## One attempt per URL, one module per tag
151
+
152
+ A URL is tried once per page load: a component that 404s logs once and is not retried until reload.
153
+
154
+ A **tag** is loaded once too, which is a different question. `<x-y>` and `<x-y autoload-dir="alt">`
155
+ are two URLs for one tag; both used to import, and the second module's `customElements.define('x-y')`
156
+ threw. A tag can only be defined once, so the second location could never have helped — it is tried
157
+ only if the first attempt fails.
158
+
159
+ ## When a component never arrives
160
+
161
+ A failed load logs, and dispatches `vera:autoload-error` on the element — bubbling and composed,
162
+ with `{ tag, src, error, element }` on `detail`. That is the hook for rendering around a component that is
163
+ not coming:
164
+
165
+ ```js
166
+ document.addEventListener('vera:autoload-error', ({ detail }) => {
167
+ report(detail.error);
168
+ detail.element.replaceWith(fallback());
169
+ });
170
+ ```
171
+
172
+ An element that has not arrived *yet* needs no hook — it is simply un-upgraded, which is what
173
+ `:not(:defined)` in your CSS is for.
174
+
175
+ ## Warming and recovering
176
+
177
+ `autoload.url(tag)` gives you the URL and gets out of the way, so warming is whatever you want it to
178
+ be — `modulepreload` for a component you know is coming, a lower-priority prefetch, priming a service
179
+ worker cache:
180
+
181
+ ```js
182
+ const link = document.createElement('link');
183
+ link.rel = 'modulepreload';
184
+ link.href = autoload.url('user-card');
185
+ document.head.appendChild(link);
186
+ ```
187
+
188
+ It is also the fastest answer to *why is it fetching that?* — the question this module gets asked
189
+ most.
190
+
191
+ `autoload.retry(element)` forgets that an element's tag failed and tries it again. A failed load is
192
+ otherwise permanent for the page, which is right for a component that does not exist and wrong for
193
+ one lost to a dropped connection. `vera:autoload-error` hands you the element:
194
+
195
+ ```js
196
+ addEventListener('vera:autoload-error', ({ detail }) => {
197
+ if (navigator.onLine) return;
198
+ addEventListener('online', () => autoload.retry(detail.element), { once: true });
199
+ });
200
+ ```
201
+
202
+ ## Reaching a shadow root nothing marked
203
+
204
+ An observer cannot cross a shadow boundary, so a component that never marks itself is out of reach —
205
+ including a third-party one holding tags of yours. Hand the root over directly and it is watched;
206
+ passing it *is* the opt-in, so no attribute is required:
207
+
208
+ ```js
209
+ autoload(someWidget.shadowRoot);
210
+ ```
211
+
212
+ ## Server-rendered pages
213
+
214
+ Markup from `@verajs/ssr` arrives as declarative shadow DOM, parsed before any script runs, with
215
+ nothing rendering it. `autoload()` reaches through those shadow roots the same as any other, so a
216
+ server-rendered page loads its components with no framework involvement:
217
+
218
+ ```html
219
+ <ssr-shell autoloader>
220
+ <template shadowrootmode="open">
221
+ <ssr-child></ssr-child> <!-- found by autoload() -->
222
+ </template>
223
+ </ssr-shell>
224
+ ```
225
+
226
+ ## What it does not do
227
+
228
+ Watching does not cross into a child component's shadow root on its own — a `MutationObserver`
229
+ cannot, by design — so a child that hosts lazily-loaded elements of its own marks itself
230
+ `autoloader`, or has its root handed over as above. Vera components get this automatically, because
231
+ the `'render'` insert offers each one up as it renders.
232
+
233
+ ## What it costs
234
+
235
+ One `MutationObserver` object watches every marked root, and a mutation only notifies observers on
236
+ its own ancestor chain — so watched subtrees that are not the ones changing cost nothing. Measured
237
+ in Chromium: 1 000 registrations left unrelated DOM work at 0.900 µs against 0.933 µs with none, and
238
+ watching a root adds ~0.6 µs per mutation batch into it.
239
+
240
+ Observers are never disconnected, and do not need to be: a removed node observed by a live observer
241
+ is still collectable — measured in Chromium with `--expose-gc`, and pinned by
242
+ `tests/browser/memory.test.js`. (jsdom disagrees, and disagrees even after `disconnect()`, which is
243
+ its own bookkeeping rather than the observer contract.)
244
+
245
+ This replaced a rescan of each marked component's whole tree on every render, which cost 0.46 µs for
246
+ a 10-node component, 3.4 µs at 100 nodes and **32.5 µs at 1 000** — on every render, for the life of
247
+ the page, long after everything had loaded. Watching `document` instead of each marked root would
248
+ have been the expensive shape: it taxes every DOM mutation in the app by ~47%, because every
249
+ mutation is inside it.
250
+
251
+ ## For AI assistants — and anyone who wants the whole API on one page
252
+
253
+ The repository root's [`llms.txt`](../../llms.txt) is the complete, hand-maintained API
254
+ reference for every package, written to be pasted into a model's context window: full export
255
+ tables, the buildless CDN and JSX recipes, semantics that differ from other frameworks, and the
256
+ mistakes that come up most. Its recipes are executed by the test suite, so they stay honest.
257
+
258
+ ## License
259
+
260
+ MIT
261
+
262
+
263
+ ## `directiveLoader` — lazy directives by convention
264
+
265
+ The same idea as component autoloading, pointed at `@verajs/directives`: an unknown
266
+ `data-vd-<name>` resolves to one module URL — `{base}/{dir}/{name}.js` — and the module
267
+ registers itself, exactly as an autoloaded component calls `customElements.define`.
268
+
269
+ ```js
270
+ import { wire } from '@verajs/core';
271
+ import { directiveLoader } from '@verajs/autoloader';
272
+
273
+ wire([directiveLoader(import.meta.url, 'directives')]);
274
+ ```
275
+
276
+ A lazy module:
277
+
278
+ ```js
279
+ // directives/sparkle.js
280
+ import { wireDirectives } from '@verajs/directives';
281
+ wireDirectives({ name: 'sparkle', value: 'none', setup(el) { /* … */ } });
282
+ ```
283
+
284
+ Module caching is the contract: the bare `@verajs/directives` import resolves to the same URL
285
+ the page loaded (bundler or import map), so the module wires the page's own registry.
286
+
287
+ Options — all factory-only JavaScript, never markup: `extension` (default `.js`), `alias`
288
+ (name → module path, for grouped layouts: `{ paint: 'motion.js', split: 'motion.js' }`), and
289
+ `resolve` (replaces path building; containment against the entry's directory still applies).
290
+ The name itself is markup input and is allowlisted to `[a-z][a-z0-9-]*` before any URL exists —
291
+ a name outside the grammar is declined, never fetched. `directiveLoader(...).url(name)` returns
292
+ the URL it would fetch, for `<link rel="modulepreload">` warming and for answering "why is it
293
+ fetching that". One attempt per name per page load; the engine memoizes the refusals.
@@ -1,34 +1,133 @@
1
1
  type AutoloaderOptions = {
2
- /**
3
- * File extension appended to the tag name when building a component's URL.
4
- *
5
- * Defaults to `.js`. Set to `.ts` so TypeScript projects can autoload their sources during
6
- * development — a dev server will not serve `foo.js` when only `foo.ts` exists on disk.
7
- * Accepted with or without the leading dot.
8
- */
9
- extension?: string;
2
+ /**
3
+ * File extension appended to the tag name when building a component's URL.
4
+ *
5
+ * Defaults to `.js`. Set to `.ts` so TypeScript projects can autoload their sources during
6
+ * development — a dev server will not serve `foo.js` when only `foo.ts` exists on disk.
7
+ * Accepted with or without the leading dot.
8
+ */
9
+ extension?: string;
10
+ /**
11
+ * Builds a tag's module URL yourself, replacing the default `dir/tag.extension`.
12
+ *
13
+ * `dir` is the resolved directory — the element's `data-autoload-dir` if it has one, otherwise the
14
+ * `componentsDir` this autoloader was created with. The result is still resolved against the
15
+ * entry file and still has to land inside its directory, so a custom layout cannot reach outside
16
+ * what the default one could.
17
+ *
18
+ * ```js
19
+ * autoloader(import.meta.url, 'components', { resolve: (tag, dir) => `${dir}/${tag}/${tag}.js` });
20
+ * ```
21
+ */
22
+ resolve?: (tag: string, dir: string) => string;
10
23
  };
11
-
12
- /** Autoload function to be run by autoloader each time a component with the "autoloader" attribute
13
- * is rerendered
24
+ /**
25
+ * What {@link autoloader} returns: one function with three shapes — no argument scans the page,
26
+ * an element watches that component, a shadow root watches that root — carrying the two operations
27
+ * that only make sense against a particular autoloader's directories and memo.
14
28
  */
15
- type Autoloader = (element: HTMLElement) => void;
29
+ type AutoloaderInstance = ((target?: Element | ShadowRoot | Document) => void) & {
30
+ /**
31
+ * The instance is its own `wire` descriptor — `wire([renderer, autoloader(…)])` — so
32
+ * configuring it and installing it are one call. `wire` tests for `on` before it tests for a
33
+ * function, which is what lets a module be both.
34
+ */
35
+ name: string;
36
+ on: 'render';
37
+ fn: never;
38
+ priority: number;
39
+ /** The absolute URL this autoloader would fetch for a tag — warm it, prefetch it, or print it. */
40
+ url: (tag: string, element?: Element) => string;
41
+ /** Forget that this element's tag failed, and try it again. */
42
+ retry: (element: Element) => void;
43
+ };
44
+ /** Options for `directiveLoader` — see loader.ts. `alias` and `resolve` are FACTORY-ONLY
45
+ * JavaScript; markup contributes nothing here but the name, and the name is allowlisted. */
46
+ type DirectiveLoaderOptions = {
47
+ /** File extension appended to the name. Defaults to `.js`. */
48
+ extension?: string;
49
+ /** Name → module path (relative to rootDir), for grouped or self-hosted layouts. */
50
+ alias?: Readonly<Record<string, string>>;
51
+ /** Replaces path building entirely; containment against rootDir's directory still applies. */
52
+ resolve?: (name: string, dir: string) => string;
53
+ };
54
+ type DirectiveLoaderInstance = ((name: string, element: Element) => boolean | Promise<unknown>) & {
55
+ /** The URL this loader would fetch for a name — for modulepreload warming and for asking
56
+ * "why is it fetching that". Throws where `load` would decline. */
57
+ url: (name: string) => string;
58
+ on: 'loader';
59
+ fn: never;
60
+ priority: number;
61
+ };
16
62
 
17
63
  /**
18
64
  * Inits an autoloader with the provided root directory, component directory and autoloader options.
19
65
  *
66
+ * Discovery is **observed, not polled**. Each `autoloader`-marked component is watched once with a
67
+ * `MutationObserver`, so an undefined element is found whenever it enters the DOM — by a render, by
68
+ * `innerHTML`, by a third-party widget, or by having been in the HTML file all along. The previous
69
+ * model re-scanned a marked component's whole tree on every render, which saw only what a Vera
70
+ * render put there and cost more the larger the component got (measured in Chromium: 0.46 µs for a
71
+ * 10-node component, 32.5 µs for a 1 000-node one, on every render, forever). An observation costs
72
+ * ~0.6 µs per mutation batch and does not care how big the component is.
73
+ *
74
+ * One observer object watches every marked root — `observe()` takes many targets — and a mutation
75
+ * only notifies observers on its own ancestor chain, so watched subtrees that are not the ones
76
+ * changing cost nothing. Measured: 1 000 registrations left unrelated DOM work at 0.900 µs against
77
+ * 0.933 µs with none. Watching `document` instead would have been the expensive shape, taxing every
78
+ * mutation in the app by ~47%.
79
+ *
20
80
  * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using
21
81
  * absolute paths
22
- * @param componentsDir The relative directory from the root directory. If element has an "autoload-dir" attribute, the
82
+ * @param componentsDir The relative directory from the root directory. If element has an "data-autoload-dir" attribute, the
23
83
  * autoloader will read from that first
24
84
  * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets
25
85
  * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`
26
- * exists). Defaults to `.js`
27
- * @return An autoloader function that should be run on desired elements each render (if lazy load elements are
28
- * conditionally rendered)
86
+ * exists). Defaults to `.js`. `resolve` replaces URL building entirely.
87
+ * @return `autoload` — call it with nothing to scan the page, with an element to watch that
88
+ * component, or with a shadow root to watch that root. Safe to call repeatedly; a root is attached
89
+ * once. Carries `url(tag)` and `retry(element)`.
90
+ */
91
+ declare const autoloader: (rootDir: string, componentsDir?: string, options?: AutoloaderOptions) => AutoloaderInstance;
92
+
93
+ /**
94
+ * `directiveLoader` — the autoloader's answer on core's `'loader'` insert: a DIRECTIVE NAME
95
+ * nobody has wired resolves by convention to one module URL, `{base}/{dir}/{name}.js`, exactly
96
+ * as component tags resolve. The engine asks (design §7: directives DISCOVERS, autoloader
97
+ * LOADS); this claims and imports; **the module registers itself** by importing
98
+ * `wireDirectives` from the same specifier the page used — module caching makes that the same
99
+ * registry, the precise symmetry of an autoloaded component calling `customElements.define`.
100
+ *
101
+ * ```js
102
+ * import { wire } from '@verajs/core';
103
+ * import { directiveLoader } from '@verajs/autoloader';
104
+ * wire([directiveLoader(import.meta.url, 'directives')]);
105
+ * ```
106
+ *
107
+ * A lazy module looks like:
108
+ *
109
+ * ```js
110
+ * // directives/sparkle.js
111
+ * import { wireDirectives } from '@verajs/directives';
112
+ * wireDirectives({ name: 'sparkle', value: 'none', setup(el) { … } });
113
+ * ```
114
+ *
115
+ * **The name is markup input** — it is the tail of an attribute an author (or a CMS, or an
116
+ * attacker who can write attributes) chose — so it is allowlisted to the directive-name grammar
117
+ * (`[a-z][a-z0-9-]*`) BEFORE any URL exists. That single gate closes the traversal and
118
+ * encoded-separator families the component path has to police character by character, because a
119
+ * tag name passes through the HTML parser and this does not. Containment against the entry's
120
+ * directory is still enforced on the final URL, so an `alias` or `resolve` mistake cannot
121
+ * escape either.
122
+ *
123
+ * The `alias` map is FACTORY-ONLY JavaScript (never markup — same rule as every policy option
124
+ * in this codebase): it redirects names for grouped layouts, so `alias: { paint: 'motion.js',
125
+ * split: 'motion.js' }` serves one bundle for a family. One attempt per name per page load,
126
+ * exactly the autoloader's posture with URLs; the ASKER memoizes refusals, this memoizes loads.
29
127
  */
30
- declare const initAutoloader: (rootDir: string, componentsDir?: string, options?: AutoloaderOptions) => Autoloader;
31
128
 
32
- export { initAutoloader };
33
- export type { AutoloaderOptions };
129
+ declare const directiveLoader: (rootDir: string, directivesDir?: string, options?: DirectiveLoaderOptions) => DirectiveLoaderInstance;
130
+
131
+ export { autoloader, directiveLoader };
132
+ export type { AutoloaderInstance, AutoloaderOptions, DirectiveLoaderInstance, DirectiveLoaderOptions };
34
133
  //# sourceMappingURL=vera-autoloader.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"vera-autoloader.d.ts","sources":["../../src/types.d.ts","../../../shared-types/src/types.d.ts","../../../../../../src/autoloader.ts"],"mappings":"AAAA,KAAK,iBAAiB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA,KAAK,UAAU,aAAa,WAAW;;;;;;;;;;;;;ACapC;AACH;cAKE,cAAA,sDAAA,iBAA4F,KAAA,UAAA;;;;","names":[]}
1
+ {"version":3,"file":"vera-autoloader.d.ts","sources":["../../src/autoloader.ts","../../src/loader.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BG;AACH;cAKE,UAAA,sDAAA,iBAAA,KAA4F,kBAAA;;ACE9F;AAC+C;AAC/C;AAEA;AAKE;AAAc;;AAEZ;AACE;;AACA;AACA;AAEI;;AAGN;;;AAGM;AAEI;;;AAIZ;AACA;AACA;AACA;;AAGA;AAEA;;;;;AAKG;AACH;;;cAGG,eAAA,sDAAA,sBAAA,KAAA,uBAAA;;;;","names":[]}