@verajs/autoloader 0.1.3 → 0.2.1

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.
@@ -1,113 +1,656 @@
1
1
  /**
2
- * Utility function for emulating .get chaining on Map prototypes for readability in the
3
- * signal handler function. This function checks for the existance of a key before getting it
4
- * and creates it if it doesn't exist.
2
+ * **Where every diagnostic code is explained.** The URL is permanent: a released bundle is immutable, so every version
3
+ * published points here for ever — the domain cannot lapse and `/e/` cannot be reorganized without breaking links in
4
+ * code nobody can edit; the docs site redirects instead. `scripts/sync-diagnostics.mjs` imports this constant, so the
5
+ * pages and the bundles can never disagree about where they are.
6
+ */
7
+ const DOCS = 'https://verajs.dev/e/';
8
+ /**
9
+ * **One shape for every diagnostic the framework prints** — the short line production keeps, the whole sentence
10
+ * development adds — so a package converting its messages writes a table and a call, never its own format.
11
+ *
12
+ * production `[vera] hydration: element: found <i> — https://verajs.dev/e/hydration-fallback`
13
+ * development `[vera] hydration: element: found <i> — fell back to a client render: … (hydration-fallback)`
5
14
  *
6
- * @param item The item to get the key for
15
+ * `subject` is the free information — what the code already has at hand, naming the problem area — the same in both
16
+ * builds. `prose` is development only: the package's table entry (`Prose`), called behind `true ` at the call site so
17
+ * the table goes unreferenced in production and rollup drops it whole. Production prints the code inside the link, so
18
+ * the reader is one click from the explanation, which `scripts/sync-diagnostics.mjs` publishes from the same tables.
7
19
  *
8
- * @returns An object with new get function to chain (g) or the items final value (v)
20
+ * **Every production message is coded** (Brian, 2026-11-11; this supersedes "convert where smaller", 2026-10-02):
21
+ * consistency over a few bytes, so no package keeps a hand-written production line beside its table.
22
+ */
23
+ /*
24
+ * The parameter names are deliberately unlike anything a caller holds: terser will not inline a function whose
25
+ * parameter shadows a name at the call site (measured 2026-10-02 — directives passes its own `code`, and a parameter
26
+ * called `code` left `((e,t,n)=>`…`)(0,t,n)` in its bundle, +8 B; renamed, the call folds to the bare template).
27
+ */
28
+ /**
29
+ * **A misused API, named by its function** — the thrown-error twin of `diagnostic()`: `untrack: expected a function …
30
+ * (untrack-not-function)`, function-first because a stack already names the source and the sweep reads that shape. The
31
+ * prose comes from a package's table, behind `true `, so a development-only guard costs production nothing.
9
32
  */
33
+ const misuse = (forName, withCode, andProse) => true && andProse
34
+ ? `${forName}: ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
35
+ : `${forName}: ${DOCS}${withCode}`;
36
+ const diagnostic = (inArea, bySubject, withCode, andProse) =>
37
+ /** `true ` HERE as well as at the call: production folds this to the one-line form, branch and all. */
38
+ true && andProse
39
+ ? `[vera] ${inArea}: ${bySubject} — ${andProse[0]}${andProse[1] ? ` ${andProse[1]}` : ''} (${withCode})`
40
+ : `[vera] ${inArea}: ${bySubject} — ${DOCS}${withCode}`;
41
+
42
+ /**
43
+ * core's `html`/`svg`/`mathml` and the renderer's `tag` — a tagged template called as a function. The FACT is shared;
44
+ * the EXAMPLE is each emitter's: `html` writes markup, `tag` an element name — so the emitter passes it.
45
+ */
46
+ /**
47
+ * An option a module or loader does not have — autoloader(), directiveLoader(), router(), and the directives packs
48
+ * remote(), sensors(), motion(). One fact and one fix; the module is the line's SUBJECT and the list is its own.
49
+ */
50
+ const unknownOption = (key, list) => [
51
+ `\`${key}\` is not an option, so it was ignored.`,
52
+ `The options are ${list}.`,
53
+ ];
54
+
10
55
  /**
11
- * Remove a trailing slash from an url if its not root url (`/`).
56
+ * **What a thrown value says, whatever was thrown — and it never throws itself.** A caught value comes from author
57
+ * code (a `resolve` option, a motion tick or vocabulary function), and JavaScript can throw anything: `null`, an object
58
+ * with no prototype (`String()` finds no `toString`), one whose `toString` or `message` getter throws, a Proxy whose
59
+ * traps throw. Formatting it naively replaced the real failure with an unrelated TypeError from inside the framework.
60
+ * Anything unreadable becomes a fixed phrase; `Object.prototype.toString` is no fallback, since it reads
61
+ * `Symbol.toStringTag` through a Proxy's trap too.
12
62
  *
13
- * @param str String to remove trailing slash from
63
+ * **A deliberate duplicate of `thrownMessage` in `packages/ssr/src/vera/escaping.ts` — fix both copies.** `@verajs/ssr`
64
+ * is compiled per file with no bundling, so it cannot import this private, unpublished package at run time;
65
+ * `tests/thrown-message-copies.test.mjs` runs one table of thrown values against both, so they cannot drift.
14
66
  */
15
- const stripTrailingSlash = (str) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);
67
+ const thrownMessage = (error) => {
68
+ try {
69
+ if (error instanceof Error)
70
+ return String(error.message);
71
+ const message = error?.message;
72
+ return typeof message === 'string' ? message : String(error);
73
+ }
74
+ catch {
75
+ return '[unprintable value thrown]';
76
+ }
77
+ };
78
+
79
+ const PROSE = {
80
+ 'loader-root-required': () => ['rootDir is required — the directory every path resolves against.', 'Pass import.meta.url.'],
81
+ 'loader-root-not-absolute': (rootDir) => [
82
+ `rootDir must be an absolute URL, and "${rootDir}" is not.`,
83
+ 'Pass import.meta.url — a relative path has nothing to resolve against.',
84
+ ],
85
+ /** Three reasons, one fact — a URL this loader will not fetch (and no request is made). */
86
+ /** The refused URL is the line's SUBJECT, so production — which prints no prose — still says which. */
87
+ 'loader-url-refused': (why) => [`refused — ${why}.`, 'Nothing was requested. Point the directory, or `resolve`, at a path inside rootDir.'],
88
+ /** What it threw is the SUBJECT (printed in every build); this explains it. */
89
+ 'loader-resolve-threw': () => [
90
+ 'the `resolve` option threw.',
91
+ 'The element was left unloaded; `resolve(name, dir)` must return a path and never throw.',
92
+ ],
93
+ 'loader-import-failed': (what, src) => [`failed to load ${what} from ${src}.`, 'The error is printed beside this line; the import itself failed.'],
94
+ 'autoloader-not-defined': (tag) => [
95
+ `the module loaded but nothing defined <${tag}>.`,
96
+ 'Check the tag name in that file matches the one in the markup, and that its `customElements.define` actually runs.',
97
+ ],
98
+ 'directive-loader-name': (name) => [`"${name}" is not a directive name this will resolve.`, 'A directive name is lowercase letters, digits and dashes, starting with a letter.'],
99
+ };
16
100
 
17
101
  /**
18
102
  * Inits an autoloader with the provided root directory, component directory and autoloader options.
19
103
  *
104
+ * Discovery is **observed, not polled**. Each `autoloader`-marked component is watched once with a
105
+ * `MutationObserver`, so an undefined element is found whenever it enters the DOM — by a render, by
106
+ * `innerHTML`, by a third-party widget, or by having been in the HTML file all along. The previous
107
+ * model re-scanned a marked component's whole tree on every render, which saw only what a Vera
108
+ * render put there and cost more the larger the component got (measured in Chromium: 0.46 µs for a
109
+ * 10-node component, 32.5 µs for a 1 000-node one, on every render, forever). An observation costs
110
+ * ~0.6 µs per mutation batch and does not care how big the component is.
111
+ *
112
+ * One observer object watches every marked root — `observe()` takes many targets — and a mutation
113
+ * only notifies observers on its own ancestor chain, so watched subtrees that are not the ones
114
+ * changing cost nothing. Measured: 1 000 registrations left unrelated DOM work at 0.900 µs against
115
+ * 0.933 µs with none. Watching `document` instead would have been the expensive shape, taxing every
116
+ * mutation in the app by ~47%.
117
+ *
20
118
  * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using
21
119
  * absolute paths
22
- * @param componentsDir The relative directory from the root directory. If element has an "autoload-dir" attribute, the
120
+ * @param componentsDir The relative directory from the root directory. If element has an "data-autoload-dir" attribute, the
23
121
  * autoloader will read from that first
24
122
  * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets
25
123
  * 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)
124
+ * exists). Defaults to `.js`. `resolve` replaces URL building entirely.
125
+ * @return `autoload` — call it with nothing to scan the page, with an element to watch that
126
+ * component, or with a shadow root to watch that root. Safe to call repeatedly; a root is attached
127
+ * once. Carries `url(tag)` and `retry(element)`.
29
128
  */
30
- const initAutoloader = (rootDir, componentsDir, options) => {
129
+ const autoloader = (rootDir, componentsDir, options) => {
31
130
  /** A configuration error fails at the misconfiguration, not once per element per render. */
32
131
  if (!rootDir)
33
- throw new Error('autoloader: rootDir is required (usually import.meta.url)');
132
+ throw new Error(misuse('autoloader', 'loader-root-required', true && PROSE['loader-root-required']()));
133
+ /**
134
+ * An option this autoloader does not have does nothing, and did so in silence — `extensions` or
135
+ * `resolver` reads exactly like the real thing at a glance, and the symptom is the *default*
136
+ * behavior, which looks like the option was never needed rather than never seen.
137
+ *
138
+ * `true `-only, so a production bundle carries neither the list nor the text.
139
+ */
140
+ if (true && options)
141
+ for (const key of Object.keys(options))
142
+ if (key !== 'extension' && key !== 'resolve')
143
+ console.warn(diagnostic('autoloader', 'options', 'unknown-option', true && unknownOption(key, 'extension, resolve')));
34
144
  /** Normalized so callers may pass either `ts` or `.ts` */
35
145
  const extension = `.${(options?.extension ?? '.js').replace(/^\./, '')}`;
146
+ /**
147
+ * `dir/tag.ext` is one layout, and a component library is as likely to use `tag/tag.js`,
148
+ * `tag/index.js`, or a flat manifest. `resolve` replaces the URL-building step entirely while
149
+ * leaving the containment check below untouched — so a custom layout cannot be used to escape
150
+ * the entry's directory. Principle #6 names this module's hard-coded `.js` as the example of the
151
+ * shape to avoid; the path around it is the same problem one level out.
152
+ */
153
+ const resolve = options?.resolve;
36
154
  /**
37
155
  * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`
38
- * (the HTML parser won't produce one), but the `autoload-dir` override is free text — and
156
+ * (the HTML parser won't produce one), but the `data-autoload-dir` override is free text — and
39
157
  * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An
40
158
  * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is
41
159
  * refused.
42
160
  */
43
- const base = new URL('.', rootDir).href;
44
161
  /**
45
- * One attempt per URL per page load. Without this, a file that fails to load was retried on
46
- * every render — console spam and a network request each time — and the same tag reached
47
- * through two different dirs raced to define twice.
162
+ * A **relative** `rootDir` throws either way; development says why.
163
+ *
164
+ * The platform's own message — `Failed to construct 'URL': Invalid base URL` — names neither the
165
+ * argument nor the fix. The value has to be absolute because every component URL resolves against
166
+ * it, which is why `import.meta.url` is the documented answer. Behind `true `, so the build
167
+ * folds it away and a production bundle carries neither the check nor the text.
48
168
  */
169
+ if (true ) {
170
+ try {
171
+ new URL('.', rootDir);
172
+ }
173
+ catch {
174
+ throw new Error(misuse('autoloader', 'loader-root-not-absolute', true && PROSE['loader-root-not-absolute'](rootDir)));
175
+ }
176
+ }
177
+ const base = new URL('.', rootDir).href;
178
+ /** One attempt per URL per page load, so a 404 costs one request and one console line. */
49
179
  const attempted = new Set();
180
+ /**
181
+ * Tags already being loaded, which is a different question from URLs already fetched.
182
+ *
183
+ * `<x-y>` and `<x-y data-autoload-dir="alt">` are two URLs for one tag. Both used to import, and the
184
+ * second module's `customElements.define('x-y')` threw `NotSupportedError` — surfacing as a
185
+ * "Failed to load" for a component that had in fact loaded. A tag can only be defined once, so
186
+ * the second URL could never have helped. It is released again if the first attempt fails, so a
187
+ * second location is still allowed to try.
188
+ */
189
+ const requested = new Set();
190
+ /** The URL last tried for a tag, so `retry` knows which memo to clear. Dropped once it loads. */
191
+ const failed = new Map();
192
+ /**
193
+ * Roots under observation, so attaching is idempotent and cheap to re-attempt.
194
+ *
195
+ * Nothing prunes it, and nothing needs to: an observed node is collectable as soon as the page
196
+ * drops it — measured in Chromium, where a removed node observed by a live observer is collected.
197
+ * (jsdom reports otherwise, and reports it even after `disconnect()`, which is its own
198
+ * bookkeeping rather than the observer contract.)
199
+ */
200
+ const watched = new WeakSet();
50
201
  /**
51
202
  * Creates the expected element url location to be appended to the root dir.
52
203
  *
53
- * The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global
204
+ * The per-element override attribute is `data-autoload-dir` — NOT `dir`, which is HTML's global
54
205
  * text-direction attribute (`dir="rtl"` on any i18n page would have silently redirected
55
206
  * component loading).
56
207
  *
57
- * @param element The element the autoloader is discovering
208
+ * Exposed as `autoload.url(tag)`, which is the whole of what a `preload` helper used to wrap:
209
+ * with the URL in hand a caller can warm it with `<link rel="modulepreload">`, prefetch it at a
210
+ * lower priority, prime a service worker, or simply print it to answer "why is it fetching
211
+ * *that*?" — the question this module gets asked most.
212
+ *
58
213
  * @param tag The element's name
59
- * @return The element's expected location to be appended to the root dir
214
+ * @param element The element being discovered, when there is one — only it can carry `data-autoload-dir`
215
+ * @return The absolute URL this autoloader would fetch
216
+ */
217
+ /**
218
+ * The URLs this loader refused, by the refusal it threw — read back in `load` to report each once. The refusal still
219
+ * carries `href` for a caller of `url()`; `load` reads this map instead, because whatever reaches its `catch` may be
220
+ * the caller's own throw, and reading a property off `null` (or a Proxy that throws) crashed the error path, where
221
+ * `WeakMap#get` answers `undefined` for anything.
60
222
  */
61
- const elementURL = (element, tag) => {
62
- const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');
63
- return `${dir}/${tag}${extension}`;
223
+ const refused = new WeakMap();
224
+ const url = (tag, element) => {
225
+ /**
226
+ * Trailing slashes come off, and an empty or root-only directory becomes `.` — the entry file's
227
+ * own directory, which is the only place a bounded URL can be anyway.
228
+ *
229
+ * The default used to be `/`, which built `//tag.js`: a **protocol-relative** URL, so
230
+ * `new URL` read `tag.js` as a *host*. `autoloader(import.meta.url)` — the documented call
231
+ * for components sitting beside the entry, since `componentsDir` is optional — therefore
232
+ * refused every component it was asked for. `data-autoload-dir="/"` did the same.
233
+ */
234
+ const dir = (element?.getAttribute('data-autoload-dir') ?? componentsDir ?? '.').replace(/\/+$/, '') || '.';
235
+ const href = new URL(resolve ? resolve(tag, dir) : `${dir}/${tag}${extension}`, rootDir).href;
236
+ /**
237
+ * **`?` and `#` end the path, so a directory cannot contain either.**
238
+ *
239
+ * The default layout builds `${dir}/${tag}${extension}` as text, and URL syntax then reads the
240
+ * result rather than the intent. `data-autoload-dir="components?v=2"` — an ordinary cache-buster, and
241
+ * the reason this is a mistake someone makes rather than an attack — resolves to
242
+ * `site/components?v=2/my-widget.js`, so the request goes to `site/components` with the **tag
243
+ * name inside the query string**. The component file is never asked for. `#` is worse: the
244
+ * fragment never reaches the network, so `site/components` is fetched outright.
245
+ *
246
+ * That is a wrong module, not a missing one, which is why it is refused rather than left to
247
+ * 404. Containment does not catch it — the URL is genuinely inside the entry's directory, and
248
+ * `data-autoload-dir="?"` resolves to the entry file itself, re-importing the whole application under
249
+ * a URL distinct enough to evaluate a second time.
250
+ *
251
+ * Only the default path is checked. `resolve` replaces URL building entirely and is documented
252
+ * that way, so a query it adds is the caller's own — `components/tag.js?v=2` is exactly the
253
+ * cache-buster the attribute cannot express, and it keeps working.
254
+ */
255
+ if (!resolve && /[?#]/.test(dir)) {
256
+ const url = new URL(href);
257
+ const refusal = new Error(diagnostic('autoloader', `<${tag}> ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](`data-autoload-dir "${dir}" contains ? or #, which ends the path, so <${tag}> lands in the query or fragment and ${url.origin}${url.pathname} would be fetched instead; use \`resolve\` to add a query`)));
258
+ refusal.href = href;
259
+ refused.set(refusal, href);
260
+ throw refusal;
261
+ }
262
+ /**
263
+ * **An encoded separator is refused the way a real one is caught.**
264
+ *
265
+ * The URL parser handles every literal form: `..`, `..\\` and `%2e%2e/` all normalize into
266
+ * genuine traversals that resolve outside `base` and fail the prefix test below — measured,
267
+ * all three. But `%2F` and `%5C` survive resolution as DATA inside one path segment, so
268
+ * `data-autoload-dir="..%2F..%2Fuploads"` is textually inside the prefix while naming the exact
269
+ * traversal a decode-then-resolve server turns real — and on a page whose markup is partly
270
+ * authored elsewhere, that is an attacker importing an uploaded file as a same-origin module.
271
+ * The URL standard is on the server's side here; principle #8 is not interested — this module
272
+ * bounds what markup can turn into a module URL, and a directory whose name needs an encoded
273
+ * slash has no honest reading. Same family as the `?`/`#` refusal above, same scope: the
274
+ * default path only, since `resolve` owns its own URL building and a `%2F` in a query it adds
275
+ * is legitimately its business.
276
+ */
277
+ if (!resolve && /%2f|%5c/i.test(dir)) {
278
+ const refusal = new Error(diagnostic('autoloader', `<${tag}> ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](`an encoded path separator in "${dir}"`)));
279
+ refusal.href = href;
280
+ refused.set(refusal, href);
281
+ throw refusal;
282
+ }
283
+ /**
284
+ * **Containment belongs here, not only at the fetch.**
285
+ *
286
+ * `data-autoload-dir` is an ordinary HTML attribute, so on any page whose markup is partly authored
287
+ * elsewhere — a CMS, a sanitizer that keeps attributes, a template someone else fills — it is
288
+ * an input. `data-autoload-dir="//evil.test"` resolves to a different **origin** entirely, and
289
+ * `..` walks out of the app.
290
+ *
291
+ * `load` always checked. This function is public and documented for preloading — warming a URL
292
+ * with `<link rel="modulepreload">` is its whole reason to exist — so returning a URL the loader
293
+ * would refuse handed the caller the fetch this module declines to make. One check, at the one
294
+ * place URLs are built, also covers a custom `resolve` returning something unbounded.
295
+ *
296
+ * `base` is `new URL('.', rootDir)`, which always ends in `/`, so the prefix test cannot be
297
+ * satisfied by a sibling directory whose name merely starts the same way.
298
+ */
299
+ if (!href.startsWith(base)) {
300
+ /**
301
+ * The refused URL rides on the error, so discovery can dedupe on it exactly as it dedupes a
302
+ * fetch. Keying the refusal on the *tag* instead would be wrong: `data-autoload-dir` is watched
303
+ * precisely so it can be pointed somewhere else after a first attempt failed, and a tag
304
+ * marked spent never looks again.
305
+ */
306
+ const refusal = new Error(diagnostic('autoloader', `<${tag}> ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](`it resolves outside ${base}`)));
307
+ refusal.href = href;
308
+ refused.set(refusal, href);
309
+ throw refusal;
310
+ }
311
+ return href;
64
312
  };
65
313
  /**
66
- * Loads an element and then recursively calls discover on that element.
314
+ * Loads an element's module and, once it has upgraded, starts watching it in turn.
67
315
  *
68
316
  * @param element The element to load
69
317
  * @param tag The tag to build the expected url from
70
318
  */
71
319
  const load = async (element, tag) => {
72
- const src = new URL(elementURL(element, tag), rootDir).href;
73
- if (attempted.has(src))
320
+ if (requested.has(tag))
74
321
  return;
75
- attempted.add(src);
76
- if (!src.startsWith(base)) {
77
- console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);
322
+ let src;
323
+ try {
324
+ src = url(tag, element);
325
+ }
326
+ catch (error) {
327
+ /**
328
+ * Deduped on the refused URL, so it is reported once rather than on every scan — and so
329
+ * pointing `data-autoload-dir` at a valid directory afterwards is a different URL and tries.
330
+ */
331
+ const href = refused.get(error);
332
+ if (href === undefined) {
333
+ /** Not a refusal of ours: the caller's `resolve` threw, and it can throw any value at all. */
334
+ console.error(diagnostic('autoloader', `<${tag}>: ${thrownMessage(error)}`, 'loader-resolve-threw', true && PROSE['loader-resolve-threw']()));
335
+ return;
336
+ }
337
+ if (attempted.has(href))
338
+ return;
339
+ attempted.add(href);
340
+ /** Routing: a refusal of ours, already carrying its code (`loader-url-refused`). */
341
+ console.error(error.message);
78
342
  return;
79
343
  }
344
+ if (attempted.has(src))
345
+ return;
346
+ attempted.add(src);
347
+ requested.add(tag);
348
+ failed.set(tag, src);
80
349
  try {
81
350
  await import(/* @vite-ignore */ src);
351
+ /**
352
+ * **A module can import cleanly and still not define the tag**, and that used to be silent
353
+ * forever: `whenDefined` never settles, so the `catch` below never runs, no event is
354
+ * dispatched, no line is logged, and the element sits unupgraded for the life of the page.
355
+ * The everyday cause is a typo — markup says `<my-widget>`, the file defines `my-wdiget` — and
356
+ * the everyday symptom is a blank space with a clean console.
357
+ *
358
+ * A dynamic `import()` resolves only after the module has fully evaluated, top-level `await`
359
+ * included, so by here every `customElements.define` the module was going to run has run.
360
+ * Two microtask turns are drained first anyway, which covers a define deferred by a resolved
361
+ * promise; anything later than that is a floating promise the module never awaited.
362
+ *
363
+ * The wait is *not* abandoned — `whenDefined` is still awaited afterwards, so a definition
364
+ * that does arrive late still upgrades and still gets watched. The error is a report, not a
365
+ * refusal.
366
+ */
367
+ await Promise.resolve();
368
+ await Promise.resolve();
369
+ if (!customElements.get(tag)) {
370
+ throw new Error(diagnostic('autoloader', `<${tag}> from ${src}`, 'autoloader-not-defined', true && PROSE['autoloader-not-defined'](tag)));
371
+ }
82
372
  await customElements.whenDefined(tag);
83
- discover(element);
373
+ failed.delete(tag);
374
+ watch(element);
84
375
  }
85
376
  catch (error) {
86
- console.error(`Failed to load custom element ${tag} from ${src}:`, error);
377
+ requested.delete(tag);
378
+ /**
379
+ * Reported as a DOM event as well as a console line, because a component that never arrives
380
+ * is something an app may want to render around — a placeholder, a retry button, a report to
381
+ * an error tracker. An event rather than core's `'error'` insert: this package deliberately
382
+ * does not depend on core, and reaching for `insert` from `@verajs/inserts` instead would
383
+ * write to a registry core never reads in a production build.
384
+ */
385
+ element.dispatchEvent(new CustomEvent('vera:autoload-error', {
386
+ bubbles: true,
387
+ composed: true,
388
+ detail: { tag, src, error, element },
389
+ }));
390
+ console.error('%s', diagnostic('autoloader', `<${tag}>`, 'loader-import-failed', true && PROSE['loader-import-failed'](`<${tag}>`, src)), error);
87
391
  }
88
392
  };
393
+ /** Loads one candidate, unless it has opted out. */
394
+ const consider = (element) => {
395
+ if (element.getAttribute('data-autoload-ignore') == null)
396
+ load(element, element.localName);
397
+ };
398
+ /**
399
+ * `:not(:defined)` already means "a custom element awaiting its definition" — a dashless unknown
400
+ * tag like `<madeupelement>` is defined, and an element leaves the set the moment its definition
401
+ * lands. `tests/browser/autoloader.test.js` pins those semantics in a real engine, which is what
402
+ * lets this trust the selector rather than re-checking the tag by hand.
403
+ */
404
+ const scan = (root) => {
405
+ const elements = root.querySelectorAll(':not(:defined)');
406
+ for (let i = 0; i < elements.length; i++)
407
+ consider(elements[i]);
408
+ };
89
409
  /**
90
- * Finds all elements within a parent element that are not defined and attempts to load each of them
410
+ * One observer for every watched root. A node added anywhere inside one is examined itself and
411
+ * then scanned, because a subtree may arrive whole — `innerHTML` on a container delivers one
412
+ * added node holding any number of undefined elements.
413
+ */
414
+ /**
415
+ * Created on first use, not at construction.
91
416
  *
92
- * @param element The element to look for undefined custom elements within
417
+ * `new MutationObserver(...)` in the constructor made `autoloader` throw in Node —
418
+ * `MutationObserver is not defined` — so an app entry that wires the autoloader could not be
419
+ * imported server-side at all. `@verajs/router` attaches its window listeners lazily for exactly
420
+ * this reason and says so; the observed-discovery rewrite reintroduced the problem here.
93
421
  */
94
- const discover = (element) => {
95
- if (element.getAttribute('autoloader') == null)
96
- return;
97
- if (element.getAttribute('autoload-ignore') != null)
98
- return;
99
- const componentElement = element.shadowRoot ?? element;
100
- const elements = componentElement.querySelectorAll(':not(:defined)');
101
- for (let i = 0; i < elements.length; i++) {
102
- const el = elements[i];
103
- const tag = el.localName;
104
- if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {
105
- load(el, tag);
422
+ let observer;
423
+ const observing = () => (observer ??= new MutationObserver((records) => {
424
+ for (const record of records) {
425
+ /**
426
+ * The three attributes are as much a part of discovery as insertion is. `autoloader` can be
427
+ * put on a component that only becomes a lazy host once some state flips; `data-autoload-dir` can
428
+ * be pointed somewhere else after a first attempt failed; `data-autoload-ignore` can be lifted.
429
+ * Without watching them, all three needed the element to be inserted again before anything
430
+ * noticed, which is not a thing that happens.
431
+ */
432
+ if (record.type === 'attributes') {
433
+ const target = record.target;
434
+ if (record.attributeName === 'data-autoload')
435
+ watch(target);
436
+ else
437
+ consider(target);
438
+ continue;
439
+ }
440
+ const added = record.addedNodes;
441
+ for (let i = 0; i < added.length; i++) {
442
+ const node = added[i];
443
+ if (node.nodeType !== 1)
444
+ continue;
445
+ const element = node;
446
+ if (!customElements.get(element.localName) && element.localName.includes('-'))
447
+ consider(element);
448
+ scan(element);
106
449
  }
107
450
  }
451
+ }));
452
+ /**
453
+ * Starts watching a component, and takes stock of what is already inside it.
454
+ *
455
+ * This is what the `'render'` insert calls, so it runs on every render of every component and has
456
+ * to be cheap when there is nothing to do: an attribute read, then a `WeakSet` check. The scan
457
+ * happens once, when the observation starts — everything after that arrives as a mutation.
458
+ *
459
+ * @param element The element to watch for undefined custom elements within
460
+ */
461
+ const watch = (target = document) => {
462
+ /**
463
+ * `autoload()` with nothing to point at means "every marked host on the page, right now".
464
+ *
465
+ * This used to happen by itself as the autoloader was created, which was wrong twice over: it
466
+ * fired once, so markup arriving later — fetched, stamped from a template — was never seen and
467
+ * said nothing about it; and two autoloaders on a page each adopted every marked host and raced
468
+ * to load the same tags from their own directories, which needed an option to switch off. As a
469
+ * shape of a function that already exists it costs almost nothing, can be called again whenever
470
+ * new markup lands, and leaves `autoloader` free of side effects.
471
+ *
472
+ * A document is recognized by `nodeType`, not by having a `body`. `document.body` is null until
473
+ * the parser reaches it, so an `autoload()` from a classic or `async` module script in `<head>`
474
+ * fell straight through this branch and the document was treated as a root to watch — observing
475
+ * `document` itself, `subtree: true`. That is precisely the shape this module exists to avoid
476
+ * (~47% on every mutation in the app, measured), it was permanent once `watched` held the
477
+ * document, and nothing said it had happened. `nodeType` is 9 from the moment the document is.
478
+ */
479
+ if (target.nodeType === 9)
480
+ return target.querySelectorAll('[data-autoload]').forEach((el) => watch(el));
481
+ let root = target;
482
+ /**
483
+ * An `Element` has to opt in; a `ShadowRoot` handed over directly does not, because handing it
484
+ * over *is* the opt-in. That is the way into a third-party component whose shadow root holds
485
+ * tags of yours — nothing else can reach it, since an observer cannot cross a shadow boundary.
486
+ */
487
+ if (target.getAttribute) {
488
+ const element = target;
489
+ if (element.getAttribute('data-autoload') == null)
490
+ return;
491
+ if (element.getAttribute('data-autoload-ignore') != null)
492
+ return;
493
+ root = element.shadowRoot ?? element;
494
+ }
495
+ if (watched.has(root))
496
+ return;
497
+ watched.add(root);
498
+ observing().observe(root, {
499
+ childList: true,
500
+ subtree: true,
501
+ attributes: true,
502
+ attributeFilter: ['data-autoload', 'data-autoload-dir', 'data-autoload-ignore'],
503
+ });
504
+ scan(root);
505
+ };
506
+ /**
507
+ * Forgets that this element's tag failed, and tries it again.
508
+ *
509
+ * A failed load is otherwise permanent for the page — right for a component that does not exist,
510
+ * wrong for one lost to a dropped connection. `vera:autoload-error` hands you the element, which
511
+ * is what makes retrying one thing rather than re-scanning every watched root possible.
512
+ */
513
+ const retry = (element) => {
514
+ const tag = element.localName;
515
+ requested.delete(tag);
516
+ const src = failed.get(tag);
517
+ if (src)
518
+ attempted.delete(src);
519
+ failed.delete(tag);
520
+ load(element, tag);
521
+ };
522
+ /**
523
+ * The instance is also its own `wire` descriptor, so configuring the autoloader and installing it
524
+ * are one call:
525
+ *
526
+ * ```js
527
+ * wire([renderer, router, autoloader(import.meta.url, 'components')]);
528
+ * ```
529
+ *
530
+ * This replaced `setAutoloader`, a bespoke registrar that lived in `@verajs/inserts` — the
531
+ * registry package knowing about one specific consumer, which is the coupling `wire` exists to
532
+ * remove. Every other module hands `wire` a descriptor; this one now does too.
533
+ *
534
+ * Priority 75 runs it *after* the renderer at 50, because it scans what the render just produced.
535
+ */
536
+ /**
537
+ * `name` goes through `defineProperty` because a function's own `name` is non-writable, so
538
+ * `Object.assign` throws in strict mode — and the descriptor's `name` is what the duplicate-
539
+ * priority warning quotes, so leaving it as `"watch"` would name the wrong thing.
540
+ */
541
+ Object.defineProperty(watch, 'name', { value: '@verajs/autoloader', configurable: true });
542
+ return Object.assign(watch, {
543
+ url,
544
+ retry,
545
+ on: 'render',
546
+ fn: ((_, container) => {
547
+ watch(container);
548
+ }),
549
+ priority: 75,
550
+ });
551
+ };
552
+
553
+ /** The refusals this loader throws itself — already coded, so `load` forwards them as they are (routing). */
554
+ const ours = new WeakSet();
555
+ const refuse = (message) => {
556
+ const error = new Error(message);
557
+ ours.add(error);
558
+ return error;
559
+ };
560
+ /** The name grammar. An attribute tail that is not a plausible directive name is declined —
561
+ * which also means it never becomes a URL. */
562
+ const SAFE_NAME = /^[a-z][a-z0-9-]*$/;
563
+ const directiveLoader = (rootDir, directivesDir, options) => {
564
+ if (!rootDir)
565
+ throw new Error(misuse('directiveLoader', 'loader-root-required', true && PROSE['loader-root-required']()));
566
+ if (true ) {
567
+ try {
568
+ new URL('.', rootDir);
569
+ }
570
+ catch {
571
+ throw new Error(misuse('directiveLoader', 'loader-root-not-absolute', true && PROSE['loader-root-not-absolute'](rootDir)));
572
+ }
573
+ if (options)
574
+ for (const key of Object.keys(options))
575
+ if (key !== 'extension' && key !== 'alias' && key !== 'resolve')
576
+ console.warn(diagnostic('directiveLoader', 'options', 'unknown-option', true && unknownOption(key, 'extension, alias, resolve')));
577
+ }
578
+ const base = new URL('.', rootDir).href;
579
+ const extension = `.${(options?.extension ?? '.js').replace(/^\./, '')}`;
580
+ const alias = options?.alias;
581
+ const resolve = options?.resolve;
582
+ const dir = (directivesDir ?? '.').replace(/\/+$/, '') || '.';
583
+ /** One import per name per page load; the promise is the memo, so N elements share one fetch. */
584
+ const claimed = new Map();
585
+ /**
586
+ * The URL this loader would fetch for a name — public for the same reason the autoloader's
587
+ * `url` is: warming with `<link rel="modulepreload">` is the whole preload story, and printing
588
+ * it answers "why is it fetching THAT". Throws on a name outside the grammar or a resolution
589
+ * outside the entry's directory, exactly as `load` refuses them.
590
+ */
591
+ const url = (name) => {
592
+ if (!SAFE_NAME.test(name)) {
593
+ throw refuse(misuse('directiveLoader', 'directive-loader-name', true && PROSE['directive-loader-name'](name)));
594
+ }
595
+ const target = alias?.[name] ?? (resolve ? resolve(name, dir) : `${dir}/${name}${extension}`);
596
+ const href = new URL(target, rootDir).href;
597
+ /**
598
+ * Containment on the FINAL url, whichever path built it. The name grammar already forbids
599
+ * every traversal spelling markup could carry; this is the backstop for a factory mistake —
600
+ * an `alias` of `../../evil.js`, a `resolve` returning an absolute URL — refused rather
601
+ * than fetched, because a loader is a thing that turns strings into same-origin module
602
+ * execution and the entry's directory is the stated bound.
603
+ */
604
+ if (!href.startsWith(base)) {
605
+ throw refuse(diagnostic('directiveLoader', `"${name}" ${href}`, 'loader-url-refused', true && PROSE['loader-url-refused'](`it resolves outside ${base}`)));
606
+ }
607
+ return href;
608
+ };
609
+ const load = (name) => {
610
+ if (!SAFE_NAME.test(name))
611
+ return false;
612
+ const existing = claimed.get(name);
613
+ if (existing)
614
+ return existing;
615
+ let src;
616
+ try {
617
+ src = url(name);
618
+ }
619
+ catch (error) {
620
+ /** `url` runs the caller's `resolve`, which can throw any value at all: formatted by what never throws. */
621
+ /** Ours (already coded) is forwarded as it is — routing; anything else is the caller's `resolve` throwing. */
622
+ if (ours.has(error))
623
+ console.error(error.message);
624
+ else
625
+ console.error(diagnostic('directiveLoader', `"${name}": ${thrownMessage(error)}`, 'loader-resolve-threw', true && PROSE['loader-resolve-threw']()));
626
+ return false;
627
+ }
628
+ /**
629
+ * The import IS the claim. Success means "the module ran" — whether it registered the name
630
+ * is the ASKER's check, because only the asker owns the registry; a module that loads and
631
+ * registers nothing earns `loader-loaded-nothing` there.
632
+ *
633
+ * A failure is the ASKER's to report too, and this prints nothing (2026-10-09): one failed import used to say two
634
+ * lines — this one with the URL and the error, the engine's with the directive and its elements. The engine now
635
+ * says one, asking `url` for the address and forwarding the import's error; a direct caller reads the address in
636
+ * the rejection's message and the import's own error as its `cause` — the standard shape.
637
+ */
638
+ const request = import(/* @vite-ignore */ src).catch((error) => {
639
+ throw new Error(src, { cause: error });
640
+ });
641
+ claimed.set(name, request);
642
+ return request;
108
643
  };
109
- return discover;
644
+ /** The instance is its own wire descriptor — configuring and installing are one call. */
645
+ Object.defineProperty(load, 'name', { value: '@verajs/autoloader directiveLoader', configurable: true });
646
+ return Object.assign(load, {
647
+ url,
648
+ on: 'loader',
649
+ fn: load,
650
+ /** Convention answers LAST: an app's own loader (an alias shim, a manifest) registers lower. */
651
+ priority: 75,
652
+ });
110
653
  };
111
654
 
112
- export { initAutoloader };
655
+ export { autoloader, directiveLoader };
113
656
  //# sourceMappingURL=vera-autoloader.js.map