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