@verajs/autoloader 0.1.3 → 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 +1 @@
1
- {"version":3,"file":"vera-autoloader.js","sources":["../../../../../../../shared-utils/src/utils.ts","../../../../../../src/autoloader.ts"],"sourcesContent":["import { GetResult, GetValueType } from '@verajs/shared-types';\n\n/**\n * Utility function for emulating .get chaining on Map prototypes for readability in the\n * signal handler function. This function checks for the existance of a key before getting it\n * and creates it if it doesn't exist.\n *\n * @param item The item to get the key for\n *\n * @returns An object with new get function to chain (g) or the items final value (v)\n */\nexport const get = <T>(item: T) => ({\n get: <K>(key: K, defaultValue: GetValueType<T>): GetResult<GetValueType<T>> => {\n if (isInstanceOf(item, Array)) {\n /** Compared against `undefined`, not truthiness — an existing `0`/`''`/`false` entry must\n * not be clobbered with the default (the falsy-check defect class from map-support). */\n if ((item as Array<GetValueType<T>>)[key as number] === undefined) {\n (item as Array<GetValueType<T>>)[key as number] = defaultValue;\n }\n return get<GetValueType<T>>((item as Array<GetValueType<T>>)[key as number]);\n } else if (isInstanceOf(item, Map) || isInstanceOf(item, WeakMap)) {\n if (!(item as Map<K, GetValueType<T>>).has(key)) {\n (item as Map<K, GetValueType<T>>).set(key, defaultValue);\n }\n return get<GetValueType<T>>((item as Map<K, GetValueType<T>>).get(key)!);\n }\n return throwError() as GetResult<GetValueType<T>>;\n },\n value: item,\n});\n\n/**\n * Get an object's type.\n *\n * @param obj The object\n * @return The type\n */\nexport const getType = (obj: unknown) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();\n\n/**\n * Check if an item is an instance of a class type.\n *\n * @param item Item to check\n * @param classType Class type to check\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst isInstanceOf = <I, C extends Function>(item: I, classType: C) => item instanceof classType;\n\n/**\n * Whether an item is a set or map\n *\n * @param item Item to check\n */\nconst KEYED_COLLECTIONS = ['map', 'set'];\nexport const isSetOrMap = <T>(item: T) => KEYED_COLLECTIONS.includes(getType(item));\n\n/**\n * Throws a minified error with an id number\n *\n * @param minifiedError Throws a minified error\n */\nexport const throwError = (minifiedError?: number): never => {\n throw new Error(minifiedError ? `Minified error: ${minifiedError}` : '');\n};\n\n/**\n * Remove a trailing slash from an url if its not root url (`/`).\n *\n * @param str String to remove trailing slash from\n */\nexport const stripTrailingSlash = (str: string) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);\n\n/**\n * Finds the entry for `priority` in a dense, priority-sorted pair of arrays, creating one if it is\n * not there yet. `order` holds the priorities and `list` the values at matching indices.\n *\n * Priority is deliberately NOT used as an array index. Indexing by priority leaves holes — hooks at\n * 25/50/75 produce a 76-element array with 73 of them empty — and these arrays are walked on every\n * render and every write, so the holes dominated the cost.\n *\n * @param list Values, ordered by ascending priority\n * @param order Priorities, parallel to `list`\n * @param priority Priority to find or create\n * @param create Builds the value when the priority is not present yet\n * @return The existing or newly created value\n */\nexport const prioritySlot = <T>(list: T[], order: number[], priority: number, create: () => T): T => {\n let slot = 0;\n while (slot < order.length && order[slot] < priority) slot++;\n if (order[slot] === priority) return list[slot];\n\n order.splice(slot, 0, priority);\n const created = create();\n list.splice(slot, 0, created);\n return created;\n};\n","import { AutoloaderOptions } from './types.js';\nimport { Autoloader } from '@verajs/shared-types';\nimport { stripTrailingSlash } from '@verajs/shared-utils';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`\n * @return An autoloader function that should be run on desired elements each render (if lazy load elements are\n * conditionally rendered)\n */\nexport const initAutoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): Autoloader => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n const base = new URL('.', rootDir).href;\n\n /**\n * One attempt per URL per page load. Without this, a file that fails to load was retried on\n * every render — console spam and a network request each time — and the same tag reached\n * through two different dirs raced to define twice.\n */\n const attempted = new Set<string>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * @param element The element the autoloader is discovering\n * @param tag The element's name\n * @return The element's expected location to be appended to the root dir\n */\n const elementURL = (element: Element, tag: string) => {\n const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');\n return `${dir}/${tag}${extension}`;\n };\n\n /**\n * Loads an element and then recursively calls discover on that element.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n const src = new URL(elementURL(element, tag), rootDir).href;\n if (attempted.has(src)) return;\n attempted.add(src);\n\n if (!src.startsWith(base)) {\n console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);\n return;\n }\n\n try {\n await import(/* @vite-ignore */ src);\n await customElements.whenDefined(tag);\n discover(element);\n } catch (error) {\n console.error(`Failed to load custom element ${tag} from ${src}:`, error);\n }\n };\n\n /**\n * Finds all elements within a parent element that are not defined and attempts to load each of them\n *\n * @param element The element to look for undefined custom elements within\n */\n const discover = (element: Element) => {\n if (element.getAttribute('autoloader') == null) return;\n if (element.getAttribute('autoload-ignore') != null) return;\n const componentElement = element.shadowRoot ?? element;\n const elements = componentElement.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n const tag = el.localName;\n if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {\n load(el, tag);\n }\n }\n };\n\n return discover;\n};\n"],"names":[],"mappings":"AAEA;;;;;;;;AAQG;AAuDH;;;;AAIG;AACI,MAAM,kBAAkB,GAAG,CAAC,GAAW,MAAM,GAAG,KAAK,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC;;AClE9G;;;;;;;;;;;;AAYG;AACI,MAAM,cAAc,GAAG,CAC5B,OAAe,EACf,aAAsB,EACtB,OAA2B,KACb;;AAEd,IAAA,IAAI,CAAC,OAAO;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC;;AAG1F,IAAA,MAAM,SAAS,GAAG,CAAA,CAAA,EAAI,CAAC,OAAO,EAAE,SAAS,IAAI,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE;AAExE;;;;;;AAMG;IACH,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI;AAEvC;;;;AAIG;AACH,IAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU;AAEnC;;;;;;;;;;AAUG;AACH,IAAA,MAAM,UAAU,GAAG,CAAC,OAAgB,EAAE,GAAW,KAAI;AACnD,QAAA,MAAM,GAAG,GAAG,kBAAkB,CAAC,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,IAAI,aAAa,IAAI,GAAG,CAAC;AAC5F,QAAA,OAAO,GAAG,GAAG,CAAA,CAAA,EAAI,GAAG,CAAA,EAAG,SAAS,EAAE;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C,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,YAAA,MAAM,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC;AACtB,YAAA,MAAM,GAAG,GAAG,EAAE,CAAC,SAAS;YACxB,IAAI,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,YAAY,CAAC,iBAAiB,CAAC,IAAI,IAAI,EAAE;AAChG,gBAAA,IAAI,CAAC,EAAE,EAAE,GAAG,CAAC;YACf;QACF;AACF,IAAA,CAAC;AAED,IAAA,OAAO,QAAQ;AACjB;;;;"}
1
+ {"version":3,"file":"vera-autoloader.js","sources":["../../src/autoloader.ts","../../src/loader.ts"],"sourcesContent":["import type { AutoloaderInstance, AutoloaderOptions } from './types.js';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * Discovery is **observed, not polled**. Each `autoloader`-marked component is watched once with a\n * `MutationObserver`, so an undefined element is found whenever it enters the DOM — by a render, by\n * `innerHTML`, by a third-party widget, or by having been in the HTML file all along. The previous\n * model re-scanned a marked component's whole tree on every render, which saw only what a Vera\n * render put there and cost more the larger the component got (measured in Chromium: 0.46 µs for a\n * 10-node component, 32.5 µs for a 1 000-node one, on every render, forever). An observation costs\n * ~0.6 µs per mutation batch and does not care how big the component is.\n *\n * One observer object watches every marked root — `observe()` takes many targets — and a mutation\n * only notifies observers on its own ancestor chain, so watched subtrees that are not the ones\n * changing cost nothing. Measured: 1 000 registrations left unrelated DOM work at 0.900 µs against\n * 0.933 µs with none. Watching `document` instead would have been the expensive shape, taxing every\n * mutation in the app by ~47%.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"data-autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`. `resolve` replaces URL building entirely.\n * @return `autoload` — call it with nothing to scan the page, with an element to watch that\n * component, or with a shadow root to watch that root. Safe to call repeatedly; a root is attached\n * once. Carries `url(tag)` and `retry(element)`.\n */\nexport const autoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): AutoloaderInstance => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /**\n * An option this autoloader does not have does nothing, and did so in silence — `extensions` or\n * `resolver` reads exactly like the real thing at a glance, and the symptom is the *default*\n * behaviour, which looks like the option was never needed rather than never seen.\n *\n * `__DEV__`-only, so a production bundle carries neither the list nor the text.\n */\n if (__DEV__ && options)\n for (const key of Object.keys(options))\n if (key !== 'extension' && key !== 'resolve')\n console.warn(\n `[vera] autoloader: \\`${key}\\` is not an option, so it was ignored. ` +\n `The options are extension and resolve.`\n );\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * `dir/tag.ext` is one layout, and a component library is as likely to use `tag/tag.js`,\n * `tag/index.js`, or a flat manifest. `resolve` replaces the URL-building step entirely while\n * leaving the containment check below untouched — so a custom layout cannot be used to escape\n * the entry's directory. Principle #6 names this module's hard-coded `.js` as the example of the\n * shape to avoid; the path around it is the same problem one level out.\n */\n const resolve = options?.resolve;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `data-autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n /**\n * A **relative** `rootDir` throws either way; development says why.\n *\n * The platform's own message — `Failed to construct 'URL': Invalid base URL` — names neither the\n * argument nor the fix. The value has to be absolute because every component URL resolves against\n * it, which is why `import.meta.url` is the documented answer. Behind `__DEV__`, so the build\n * folds it away and a production bundle carries neither the check nor the text.\n */\n if (__DEV__) {\n try {\n new URL('.', rootDir);\n } catch {\n throw new Error(\n `autoloader: rootDir must be an absolute URL, and \"${rootDir}\" is not. ` +\n `Pass import.meta.url — a relative path has nothing to resolve against.`\n );\n }\n }\n const base = new URL('.', rootDir).href;\n\n /** One attempt per URL per page load, so a 404 costs one request and one console line. */\n const attempted = new Set<string>();\n\n /**\n * Tags already being loaded, which is a different question from URLs already fetched.\n *\n * `<x-y>` and `<x-y data-autoload-dir=\"alt\">` are two URLs for one tag. Both used to import, and the\n * second module's `customElements.define('x-y')` threw `NotSupportedError` — surfacing as a\n * \"Failed to load\" for a component that had in fact loaded. A tag can only be defined once, so\n * the second URL could never have helped. It is released again if the first attempt fails, so a\n * second location is still allowed to try.\n */\n const requested = new Set<string>();\n\n /** The URL last tried for a tag, so `retry` knows which memo to clear. Dropped once it loads. */\n const failed = new Map<string, string>();\n\n /**\n * Roots under observation, so attaching is idempotent and cheap to re-attempt.\n *\n * Nothing prunes it, and nothing needs to: an observed node is collectable as soon as the page\n * drops it — measured in Chromium, where a removed node observed by a live observer is collected.\n * (jsdom reports otherwise, and reports it even after `disconnect()`, which is its own\n * bookkeeping rather than the observer contract.)\n */\n const watched = new WeakSet<Element | ShadowRoot>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `data-autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * Exposed as `autoload.url(tag)`, which is the whole of what a `preload` helper used to wrap:\n * with the URL in hand a caller can warm it with `<link rel=\"modulepreload\">`, prefetch it at a\n * lower priority, prime a service worker, or simply print it to answer \"why is it fetching\n * *that*?\" — the question this module gets asked most.\n *\n * @param tag The element's name\n * @param element The element being discovered, when there is one — only it can carry `data-autoload-dir`\n * @return The absolute URL this autoloader would fetch\n */\n const url = (tag: string, element?: Element) => {\n /**\n * Trailing slashes come off, and an empty or root-only directory becomes `.` — the entry file's\n * own directory, which is the only place a bounded URL can be anyway.\n *\n * The default used to be `/`, which built `//tag.js`: a **protocol-relative** URL, so\n * `new URL` read `tag.js` as a *host*. `autoloader(import.meta.url)` — the documented call\n * for components sitting beside the entry, since `componentsDir` is optional — therefore\n * refused every component it was asked for. `data-autoload-dir=\"/\"` did the same.\n */\n const dir = (element?.getAttribute('data-autoload-dir') ?? componentsDir ?? '.').replace(/\\/+$/, '') || '.';\n const href = new URL(resolve ? resolve(tag, dir) : `${dir}/${tag}${extension}`, rootDir).href;\n /**\n * **`?` and `#` end the path, so a directory cannot contain either.**\n *\n * The default layout builds `${dir}/${tag}${extension}` as text, and URL syntax then reads the\n * result rather than the intent. `data-autoload-dir=\"components?v=2\"` — an ordinary cache-buster, and\n * the reason this is a mistake someone makes rather than an attack — resolves to\n * `site/components?v=2/my-widget.js`, so the request goes to `site/components` with the **tag\n * name inside the query string**. The component file is never asked for. `#` is worse: the\n * fragment never reaches the network, so `site/components` is fetched outright.\n *\n * That is a wrong module, not a missing one, which is why it is refused rather than left to\n * 404. Containment does not catch it — the URL is genuinely inside the entry's directory, and\n * `data-autoload-dir=\"?\"` resolves to the entry file itself, re-importing the whole application under\n * a URL distinct enough to evaluate a second time.\n *\n * Only the default path is checked. `resolve` replaces URL building entirely and is documented\n * that way, so a query it adds is the caller's own — `components/tag.js?v=2` is exactly the\n * cache-buster the attribute cannot express, and it keeps working.\n */\n if (!resolve && /[?#]/.test(dir)) {\n const url = new URL(href);\n const refusal = new Error(\n `[vera] autoloader: refused ${href} for <${tag}> — data-autoload-dir \"${dir}\" contains ? or #, ` +\n `which ends the path, so <${tag}> lands in the query or fragment and ` +\n `${url.origin}${url.pathname} would be fetched instead. Use \\`resolve\\` to add a query.`\n );\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n /**\n * **An encoded separator is refused the way a real one is caught.**\n *\n * The URL parser handles every literal form: `..`, `..\\\\` and `%2e%2e/` all normalize into\n * genuine traversals that resolve outside `base` and fail the prefix test below — measured,\n * all three. But `%2F` and `%5C` survive resolution as DATA inside one path segment, so\n * `data-autoload-dir=\"..%2F..%2Fuploads\"` is textually inside the prefix while naming the exact\n * traversal a decode-then-resolve server turns real — and on a page whose markup is partly\n * authored elsewhere, that is an attacker importing an uploaded file as a same-origin module.\n * The URL standard is on the server's side here; principle #8 is not interested — this module\n * bounds what markup can turn into a module URL, and a directory whose name needs an encoded\n * slash has no honest reading. Same family as the `?`/`#` refusal above, same scope: the\n * default path only, since `resolve` owns its own URL building and a `%2F` in a query it adds\n * is legitimately its business.\n */\n if (!resolve && /%2f|%5c/i.test(dir)) {\n const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — encoded path separator in \"${dir}\"`);\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n /**\n * **Containment belongs here, not only at the fetch.**\n *\n * `data-autoload-dir` is an ordinary HTML attribute, so on any page whose markup is partly authored\n * elsewhere — a CMS, a sanitizer that keeps attributes, a template someone else fills — it is\n * an input. `data-autoload-dir=\"//evil.test\"` resolves to a different **origin** entirely, and\n * `..` walks out of the app.\n *\n * `load` always checked. This function is public and documented for preloading — warming a URL\n * with `<link rel=\"modulepreload\">` is its whole reason to exist — so returning a URL the loader\n * would refuse handed the caller the fetch this module declines to make. One check, at the one\n * place URLs are built, also covers a custom `resolve` returning something unbounded.\n *\n * `base` is `new URL('.', rootDir)`, which always ends in `/`, so the prefix test cannot be\n * satisfied by a sibling directory whose name merely starts the same way.\n */\n if (!href.startsWith(base)) {\n /**\n * The refused URL rides on the error, so discovery can dedupe on it exactly as it dedupes a\n * fetch. Keying the refusal on the *tag* instead would be wrong: `data-autoload-dir` is watched\n * precisely so it can be pointed somewhere else after a first attempt failed, and a tag\n * marked spent never looks again.\n */\n const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — resolves outside ${base}`);\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n return href;\n };\n\n /**\n * Loads an element's module and, once it has upgraded, starts watching it in turn.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n if (requested.has(tag)) return;\n let src;\n try {\n src = url(tag, element);\n } catch (error) {\n /**\n * Deduped on the refused URL, so it is reported once rather than on every scan — and so\n * pointing `data-autoload-dir` at a valid directory afterwards is a different URL and tries.\n */\n const href = (error as Error & { href?: string }).href;\n if (href !== undefined) {\n if (attempted.has(href)) return;\n attempted.add(href);\n }\n console.error((error as Error).message);\n return;\n }\n if (attempted.has(src)) return;\n attempted.add(src);\n requested.add(tag);\n failed.set(tag, src);\n\n try {\n await import(/* @vite-ignore */ src);\n /**\n * **A module can import cleanly and still not define the tag**, and that used to be silent\n * forever: `whenDefined` never settles, so the `catch` below never runs, no event is\n * dispatched, no line is logged, and the element sits unupgraded for the life of the page.\n * The everyday cause is a typo — markup says `<my-widget>`, the file defines `my-wdiget` — and\n * the everyday symptom is a blank space with a clean console.\n *\n * A dynamic `import()` resolves only after the module has fully evaluated, top-level `await`\n * included, so by here every `customElements.define` the module was going to run has run.\n * Two microtask turns are drained first anyway, which covers a define deferred by a resolved\n * promise; anything later than that is a floating promise the module never awaited.\n *\n * The wait is *not* abandoned — `whenDefined` is still awaited afterwards, so a definition\n * that does arrive late still upgrades and still gets watched. The error is a report, not a\n * refusal.\n */\n await Promise.resolve();\n await Promise.resolve();\n if (!customElements.get(tag)) {\n throw new Error(\n `imported ${src} but nothing defined <${tag}>. Check the tag name in that file matches ` +\n `the one in the markup, and that its \\`customElements.define\\` actually runs.`\n );\n }\n await customElements.whenDefined(tag);\n failed.delete(tag);\n watch(element);\n } catch (error) {\n requested.delete(tag);\n /**\n * Reported as a DOM event as well as a console line, because a component that never arrives\n * is something an app may want to render around — a placeholder, a retry button, a report to\n * an error tracker. An event rather than core's `'error'` insert: this package deliberately\n * does not depend on core, and reaching for `insert` from `@verajs/inserts` instead would\n * write to a registry core never reads in a production build.\n */\n element.dispatchEvent(\n new CustomEvent('vera:autoload-error', {\n bubbles: true,\n composed: true,\n detail: { tag, src, error, element },\n })\n );\n console.error(`[vera] autoloader: failed to load <${tag}> from ${src}:`, error);\n }\n };\n\n /** Loads one candidate, unless it has opted out. */\n const consider = (element: Element) => {\n if (element.getAttribute('data-autoload-ignore') == null) load(element, element.localName);\n };\n\n /**\n * `:not(:defined)` already means \"a custom element awaiting its definition\" — a dashless unknown\n * tag like `<madeupelement>` is defined, and an element leaves the set the moment its definition\n * lands. `tests/browser/autoloader.test.js` pins those semantics in a real engine, which is what\n * lets this trust the selector rather than re-checking the tag by hand.\n */\n const scan = (root: Element | ShadowRoot) => {\n const elements = root.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) consider(elements[i]);\n };\n\n /**\n * One observer for every watched root. A node added anywhere inside one is examined itself and\n * then scanned, because a subtree may arrive whole — `innerHTML` on a container delivers one\n * added node holding any number of undefined elements.\n */\n /**\n * Created on first use, not at construction.\n *\n * `new MutationObserver(...)` in the constructor made `autoloader` throw in Node —\n * `MutationObserver is not defined` — so an app entry that wires the autoloader could not be\n * imported server-side at all. `@verajs/router` attaches its window listeners lazily for exactly\n * this reason and says so; the observed-discovery rewrite reintroduced the problem here.\n */\n let observer;\n const observing = () =>\n (observer ??= new MutationObserver((records) => {\n for (const record of records) {\n /**\n * The three attributes are as much a part of discovery as insertion is. `autoloader` can be\n * put on a component that only becomes a lazy host once some state flips; `data-autoload-dir` can\n * be pointed somewhere else after a first attempt failed; `data-autoload-ignore` can be lifted.\n * Without watching them, all three needed the element to be inserted again before anything\n * noticed, which is not a thing that happens.\n */\n if (record.type === 'attributes') {\n const target = record.target as Element;\n if (record.attributeName === 'data-autoload') watch(target);\n else consider(target);\n continue;\n }\n\n const added = record.addedNodes;\n for (let i = 0; i < added.length; i++) {\n const node = added[i];\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n if (!customElements.get(element.localName) && element.localName.includes('-')) consider(element);\n scan(element);\n }\n }\n }));\n\n /**\n * Starts watching a component, and takes stock of what is already inside it.\n *\n * This is what the `'render'` insert calls, so it runs on every render of every component and has\n * to be cheap when there is nothing to do: an attribute read, then a `WeakSet` check. The scan\n * happens once, when the observation starts — everything after that arrives as a mutation.\n *\n * @param element The element to watch for undefined custom elements within\n */\n const watch = (target: Element | ShadowRoot | Document = document) => {\n /**\n * `autoload()` with nothing to point at means \"every marked host on the page, right now\".\n *\n * This used to happen by itself as the autoloader was created, which was wrong twice over: it\n * fired once, so markup arriving later — fetched, stamped from a template — was never seen and\n * said nothing about it; and two autoloaders on a page each adopted every marked host and raced\n * to load the same tags from their own directories, which needed an option to switch off. As a\n * shape of a function that already exists it costs almost nothing, can be called again whenever\n * new markup lands, and leaves `autoloader` free of side effects.\n *\n * A document is recognised by `nodeType`, not by having a `body`. `document.body` is null until\n * the parser reaches it, so an `autoload()` from a classic or `async` module script in `<head>`\n * fell straight through this branch and the document was treated as a root to watch — observing\n * `document` itself, `subtree: true`. That is precisely the shape this module exists to avoid\n * (~47% on every mutation in the app, measured), it was permanent once `watched` held the\n * document, and nothing said it had happened. `nodeType` is 9 from the moment the document is.\n */\n if ((target as Document).nodeType === 9)\n return (target as Document).querySelectorAll('[data-autoload]').forEach((el) => watch(el));\n let root = target as Element | ShadowRoot;\n /**\n * An `Element` has to opt in; a `ShadowRoot` handed over directly does not, because handing it\n * over *is* the opt-in. That is the way into a third-party component whose shadow root holds\n * tags of yours — nothing else can reach it, since an observer cannot cross a shadow boundary.\n */\n if ((target as Element).getAttribute) {\n const element = target as Element;\n if (element.getAttribute('data-autoload') == null) return;\n if (element.getAttribute('data-autoload-ignore') != null) return;\n root = element.shadowRoot ?? element;\n }\n if (watched.has(root)) return;\n watched.add(root);\n observing().observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-autoload', 'data-autoload-dir', 'data-autoload-ignore'],\n });\n scan(root);\n };\n\n /**\n * Forgets that this element's tag failed, and tries it again.\n *\n * A failed load is otherwise permanent for the page — right for a component that does not exist,\n * wrong for one lost to a dropped connection. `vera:autoload-error` hands you the element, which\n * is what makes retrying one thing rather than re-scanning every watched root possible.\n */\n const retry = (element: Element) => {\n const tag = element.localName;\n requested.delete(tag);\n const src = failed.get(tag);\n if (src) attempted.delete(src);\n failed.delete(tag);\n load(element, tag);\n };\n\n /**\n * The instance is also its own `wire` descriptor, so configuring the autoloader and installing it\n * are one call:\n *\n * ```js\n * wire([renderer, router, autoloader(import.meta.url, 'components')]);\n * ```\n *\n * This replaced `setAutoloader`, a bespoke registrar that lived in `@verajs/inserts` — the\n * registry package knowing about one specific consumer, which is the coupling `wire` exists to\n * remove. Every other module hands `wire` a descriptor; this one now does too.\n *\n * Priority 75 runs it *after* the renderer at 50, because it scans what the render just produced.\n */\n /**\n * `name` goes through `defineProperty` because a function's own `name` is non-writable, so\n * `Object.assign` throws in strict mode — and the descriptor's `name` is what the duplicate-\n * priority warning quotes, so leaving it as `\"watch\"` would name the wrong thing.\n */\n Object.defineProperty(watch, 'name', { value: '@verajs/autoloader', configurable: true });\n return Object.assign(watch, {\n url,\n retry,\n on: 'render' as const,\n fn: ((_: unknown, container: Element | ShadowRoot | Document) => {\n watch(container);\n }) as never,\n priority: 75,\n });\n};\n","/**\n * `directiveLoader` — the autoloader's answer on core's `'loader'` insert: a DIRECTIVE NAME\n * nobody has wired resolves by convention to one module URL, `{base}/{dir}/{name}.js`, exactly\n * as component tags resolve. The engine asks (design §7: directives DISCOVERS, autoloader\n * LOADS); this claims and imports; **the module registers itself** by importing\n * `wireDirectives` from the same specifier the page used — module caching makes that the same\n * registry, the precise symmetry of an autoloaded component calling `customElements.define`.\n *\n * ```js\n * import { wire } from '@verajs/core';\n * import { directiveLoader } from '@verajs/autoloader';\n * wire([directiveLoader(import.meta.url, 'directives')]);\n * ```\n *\n * A lazy module looks like:\n *\n * ```js\n * // directives/sparkle.js\n * import { wireDirectives } from '@verajs/directives';\n * wireDirectives({ name: 'sparkle', value: 'none', setup(el) { … } });\n * ```\n *\n * **The name is markup input** — it is the tail of an attribute an author (or a CMS, or an\n * attacker who can write attributes) chose — so it is allowlisted to the directive-name grammar\n * (`[a-z][a-z0-9-]*`) BEFORE any URL exists. That single gate closes the traversal and\n * encoded-separator families the component path has to police character by character, because a\n * tag name passes through the HTML parser and this does not. Containment against the entry's\n * directory is still enforced on the final URL, so an `alias` or `resolve` mistake cannot\n * escape either.\n *\n * The `alias` map is FACTORY-ONLY JavaScript (never markup — same rule as every policy option\n * in this codebase): it redirects names for grouped layouts, so `alias: { paint: 'motion.js',\n * split: 'motion.js' }` serves one bundle for a family. One attempt per name per page load,\n * exactly the autoloader's posture with URLs; the ASKER memoizes refusals, this memoizes loads.\n */\nimport type { DirectiveLoaderInstance, DirectiveLoaderOptions } from './types.js';\n\n/** The name grammar. An attribute tail that is not a plausible directive name is declined —\n * which also means it never becomes a URL. */\nconst SAFE_NAME = /^[a-z][a-z0-9-]*$/;\n\nexport const directiveLoader = (\n rootDir: string,\n directivesDir?: string,\n options?: DirectiveLoaderOptions\n): DirectiveLoaderInstance => {\n if (!rootDir) throw new Error('directiveLoader: rootDir is required (usually import.meta.url)');\n if (__DEV__) {\n try {\n new URL('.', rootDir);\n } catch {\n throw new Error(\n `directiveLoader: rootDir must be an absolute URL, and \"${rootDir}\" is not. ` +\n `Pass import.meta.url — a relative path has nothing to resolve against.`\n );\n }\n if (options)\n for (const key of Object.keys(options))\n if (key !== 'extension' && key !== 'alias' && key !== 'resolve')\n console.warn(\n `[vera] directiveLoader: \\`${key}\\` is not an option, so it was ignored. ` +\n `The options are extension, alias and resolve.`\n );\n }\n const base = new URL('.', rootDir).href;\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n const alias = options?.alias;\n const resolve = options?.resolve;\n const dir = (directivesDir ?? '.').replace(/\\/+$/, '') || '.';\n\n /** One import per name per page load; the promise is the memo, so N elements share one fetch. */\n const claimed = new Map<string, Promise<unknown>>();\n\n /**\n * The URL this loader would fetch for a name — public for the same reason the autoloader's\n * `url` is: warming with `<link rel=\"modulepreload\">` is the whole preload story, and printing\n * it answers \"why is it fetching THAT\". Throws on a name outside the grammar or a resolution\n * outside the entry's directory, exactly as `load` refuses them.\n */\n const url = (name: string): string => {\n if (!SAFE_NAME.test(name)) {\n throw new Error(`directiveLoader: \"${name}\" is not a directive name this will resolve.`);\n }\n const target = alias?.[name] ?? (resolve ? resolve(name, dir) : `${dir}/${name}${extension}`);\n const href = new URL(target, rootDir).href;\n /**\n * Containment on the FINAL url, whichever path built it. The name grammar already forbids\n * every traversal spelling markup could carry; this is the backstop for a factory mistake —\n * an `alias` of `../../evil.js`, a `resolve` returning an absolute URL — refused rather\n * than fetched, because a loader is a thing that turns strings into same-origin module\n * execution and the entry's directory is the stated bound.\n */\n if (!href.startsWith(base)) {\n throw new Error(`directiveLoader: refused ${href} for \"${name}\" — resolves outside ${base}`);\n }\n return href;\n };\n\n const load = (name: string): boolean | Promise<unknown> => {\n if (!SAFE_NAME.test(name)) return false;\n const existing = claimed.get(name);\n if (existing) return existing;\n let src: string;\n try {\n src = url(name);\n } catch (error) {\n console.error(`[vera] ${(error as Error).message}`);\n return false;\n }\n /**\n * The import IS the claim. Success means \"the module ran\" — whether it registered the name\n * is the ASKER's check, because only the asker owns the registry; a module that loads and\n * registers nothing earns `loader-loaded-nothing` there, with this URL in the story via the\n * console line below.\n */\n const request = import(/* @vite-ignore */ src).catch((error) => {\n console.error(`[vera] directiveLoader: failed to load \"${name}\" from ${src}:`, error);\n throw error;\n });\n claimed.set(name, request);\n return request;\n };\n\n /** The instance is its own wire descriptor — configuring and installing are one call. */\n Object.defineProperty(load, 'name', { value: '@verajs/autoloader directiveLoader', configurable: true });\n return Object.assign(load as (name: string, element: Element) => boolean | Promise<unknown>, {\n url,\n on: 'loader' as const,\n fn: load as never,\n /** Convention answers LAST: an app's own loader (an alias shim, a manifest) registers lower. */\n priority: 75,\n });\n};\n"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BG;AACI,MAA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)=>{if(!e)throw new Error("autoloader: rootDir is required (usually import.meta.url)");const r=`.${(o?.extension??".js").replace(/^\./,"")}`,l=new URL(".",e).href,n=new Set,a=async(o,a)=>{const i=new URL(((e,o)=>{var l;return`${"/"!==(l=e.getAttribute("autoload-dir")??t??"/")&&l.endsWith("/")?l.slice(0,-1):l}/${o}${r}`})(o,a),e).href;if(!n.has(i))if(n.add(i),i.startsWith(l))try{await import(i),await customElements.whenDefined(a),s(o)}catch(e){console.error(`Failed to load custom element ${a} from ${i}:`,e)}else console.error(`autoloader: refused ${i} for <${a}> — resolves outside ${l}`)},s=e=>{if(null==e.getAttribute("autoloader"))return;if(null!=e.getAttribute("autoload-ignore"))return;const t=(e.shadowRoot??e).querySelectorAll(":not(:defined)");for(let e=0;e<t.length;e++){const o=t[e],r=o.localName;r?.includes("-")&&!customElements.get(r)&&null==o.getAttribute("autoload-ignore")&&a(o,r)}};return s};export{e as initAutoloader};
1
+ const e=(e,t,r)=>{if(!e)throw new Error("autoloader: rootDir is required (usually import.meta.url)");const o=`.${(r?.extension??".js").replace(/^\./,"")}`,a=r?.resolve,n=new URL(".",e).href,i=new Set,s=new Set,d=new Map,l=new WeakSet,u=(r,i)=>{const s=(i?.getAttribute("data-autoload-dir")??t??".").replace(/\/+$/,"")||".",d=new URL(a?a(r,s):`${s}/${r}${o}`,e).href;if(!a&&/[?#]/.test(s)){const e=new URL(d),t=new Error(`[vera] autoloader: refused ${d} for <${r}> — data-autoload-dir "${s}" contains ? or #, which ends the path, so <${r}> lands in the query or fragment and ${e.origin}${e.pathname} would be fetched instead. Use \`resolve\` to add a query.`);throw t.href=d,t}if(!a&&/%2f|%5c/i.test(s)){const e=new Error(`[vera] autoloader: refused ${d} for <${r}> — encoded path separator in "${s}"`);throw e.href=d,e}if(!d.startsWith(n)){const e=new Error(`[vera] autoloader: refused ${d} for <${r}> — resolves outside ${n}`);throw e.href=d,e}return d},c=async(e,t)=>{if(s.has(t))return;let r;try{r=u(t,e)}catch(e){const t=e.href;if(void 0!==t){if(i.has(t))return;i.add(t)}return void console.error(e.message)}if(!i.has(r)){i.add(r),s.add(t),d.set(t,r);try{if(await import(r),await Promise.resolve(),await Promise.resolve(),!customElements.get(t))throw new Error(`imported ${r} but nothing defined <${t}>. Check the tag name in that file matches the one in the markup, and that its \`customElements.define\` actually runs.`);await customElements.whenDefined(t),d.delete(t),w(e)}catch(o){s.delete(t),e.dispatchEvent(new CustomEvent("vera:autoload-error",{bubbles:!0,composed:!0,detail:{tag:t,src:r,error:o,element:e}})),console.error(`[vera] autoloader: failed to load <${t}> from ${r}:`,o)}}},f=e=>{null==e.getAttribute("data-autoload-ignore")&&c(e,e.localName)},h=e=>{const t=e.querySelectorAll(":not(:defined)");for(let e=0;e<t.length;e++)f(t[e])};let m;const w=(e=document)=>{if(9===e.nodeType)return e.querySelectorAll("[data-autoload]").forEach((e=>w(e)));let t=e;if(e.getAttribute){const r=e;if(null==r.getAttribute("data-autoload"))return;if(null!=r.getAttribute("data-autoload-ignore"))return;t=r.shadowRoot??r}l.has(t)||(l.add(t),(m??=new MutationObserver((e=>{for(const t of e){if("attributes"===t.type){const e=t.target;"data-autoload"===t.attributeName?w(e):f(e);continue}const e=t.addedNodes;for(let t=0;t<e.length;t++){const r=e[t];if(1!==r.nodeType)continue;const o=r;!customElements.get(o.localName)&&o.localName.includes("-")&&f(o),h(o)}}}))).observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-autoload","data-autoload-dir","data-autoload-ignore"]}),h(t))};return Object.defineProperty(w,"name",{value:"@verajs/autoloader",configurable:!0}),Object.assign(w,{url:u,retry:e=>{const t=e.localName;s.delete(t);const r=d.get(t);r&&i.delete(r),d.delete(t),c(e,t)},on:"render",fn:(e,t)=>{w(t)},priority:75})},t=/^[a-z][a-z0-9-]*$/,r=(e,r,o)=>{if(!e)throw new Error("directiveLoader: rootDir is required (usually import.meta.url)");const a=new URL(".",e).href,n=`.${(o?.extension??".js").replace(/^\./,"")}`,i=o?.alias,s=o?.resolve,d=(r??".").replace(/\/+$/,"")||".",l=new Map,u=r=>{if(!t.test(r))throw new Error(`directiveLoader: "${r}" is not a directive name this will resolve.`);const o=i?.[r]??(s?s(r,d):`${d}/${r}${n}`),l=new URL(o,e).href;if(!l.startsWith(a))throw new Error(`directiveLoader: refused ${l} for "${r}" — resolves outside ${a}`);return l},c=e=>{if(!t.test(e))return!1;const r=l.get(e);if(r)return r;let o;try{o=u(e)}catch(e){return console.error(`[vera] ${e.message}`),!1}const a=import(o).catch((t=>{throw console.error(`[vera] directiveLoader: failed to load "${e}" from ${o}:`,t),t}));return l.set(e,a),a};return Object.defineProperty(c,"name",{value:"@verajs/autoloader directiveLoader",configurable:!0}),Object.assign(c,{url:u,on:"loader",fn:c,priority:75})};export{e as autoloader,r as directiveLoader};
2
2
  //# sourceMappingURL=vera-autoloader.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"vera-autoloader.min.js","sources":["../../../../../shared-utils/src/utils.ts","../../../../src/autoloader.ts"],"sourcesContent":["import { GetResult, GetValueType } from '@verajs/shared-types';\n\n/**\n * Utility function for emulating .get chaining on Map prototypes for readability in the\n * signal handler function. This function checks for the existance of a key before getting it\n * and creates it if it doesn't exist.\n *\n * @param item The item to get the key for\n *\n * @returns An object with new get function to chain (g) or the items final value (v)\n */\nexport const get = <T>(item: T) => ({\n get: <K>(key: K, defaultValue: GetValueType<T>): GetResult<GetValueType<T>> => {\n if (isInstanceOf(item, Array)) {\n /** Compared against `undefined`, not truthiness — an existing `0`/`''`/`false` entry must\n * not be clobbered with the default (the falsy-check defect class from map-support). */\n if ((item as Array<GetValueType<T>>)[key as number] === undefined) {\n (item as Array<GetValueType<T>>)[key as number] = defaultValue;\n }\n return get<GetValueType<T>>((item as Array<GetValueType<T>>)[key as number]);\n } else if (isInstanceOf(item, Map) || isInstanceOf(item, WeakMap)) {\n if (!(item as Map<K, GetValueType<T>>).has(key)) {\n (item as Map<K, GetValueType<T>>).set(key, defaultValue);\n }\n return get<GetValueType<T>>((item as Map<K, GetValueType<T>>).get(key)!);\n }\n return throwError() as GetResult<GetValueType<T>>;\n },\n value: item,\n});\n\n/**\n * Get an object's type.\n *\n * @param obj The object\n * @return The type\n */\nexport const getType = (obj: unknown) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();\n\n/**\n * Check if an item is an instance of a class type.\n *\n * @param item Item to check\n * @param classType Class type to check\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst isInstanceOf = <I, C extends Function>(item: I, classType: C) => item instanceof classType;\n\n/**\n * Whether an item is a set or map\n *\n * @param item Item to check\n */\nconst KEYED_COLLECTIONS = ['map', 'set'];\nexport const isSetOrMap = <T>(item: T) => KEYED_COLLECTIONS.includes(getType(item));\n\n/**\n * Throws a minified error with an id number\n *\n * @param minifiedError Throws a minified error\n */\nexport const throwError = (minifiedError?: number): never => {\n throw new Error(minifiedError ? `Minified error: ${minifiedError}` : '');\n};\n\n/**\n * Remove a trailing slash from an url if its not root url (`/`).\n *\n * @param str String to remove trailing slash from\n */\nexport const stripTrailingSlash = (str: string) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);\n\n/**\n * Finds the entry for `priority` in a dense, priority-sorted pair of arrays, creating one if it is\n * not there yet. `order` holds the priorities and `list` the values at matching indices.\n *\n * Priority is deliberately NOT used as an array index. Indexing by priority leaves holes — hooks at\n * 25/50/75 produce a 76-element array with 73 of them empty — and these arrays are walked on every\n * render and every write, so the holes dominated the cost.\n *\n * @param list Values, ordered by ascending priority\n * @param order Priorities, parallel to `list`\n * @param priority Priority to find or create\n * @param create Builds the value when the priority is not present yet\n * @return The existing or newly created value\n */\nexport const prioritySlot = <T>(list: T[], order: number[], priority: number, create: () => T): T => {\n let slot = 0;\n while (slot < order.length && order[slot] < priority) slot++;\n if (order[slot] === priority) return list[slot];\n\n order.splice(slot, 0, priority);\n const created = create();\n list.splice(slot, 0, created);\n return created;\n};\n","import { AutoloaderOptions } from './types.js';\nimport { Autoloader } from '@verajs/shared-types';\nimport { stripTrailingSlash } from '@verajs/shared-utils';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`\n * @return An autoloader function that should be run on desired elements each render (if lazy load elements are\n * conditionally rendered)\n */\nexport const initAutoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): Autoloader => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n const base = new URL('.', rootDir).href;\n\n /**\n * One attempt per URL per page load. Without this, a file that fails to load was retried on\n * every render — console spam and a network request each time — and the same tag reached\n * through two different dirs raced to define twice.\n */\n const attempted = new Set<string>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * @param element The element the autoloader is discovering\n * @param tag The element's name\n * @return The element's expected location to be appended to the root dir\n */\n const elementURL = (element: Element, tag: string) => {\n const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');\n return `${dir}/${tag}${extension}`;\n };\n\n /**\n * Loads an element and then recursively calls discover on that element.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n const src = new URL(elementURL(element, tag), rootDir).href;\n if (attempted.has(src)) return;\n attempted.add(src);\n\n if (!src.startsWith(base)) {\n console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);\n return;\n }\n\n try {\n await import(/* @vite-ignore */ src);\n await customElements.whenDefined(tag);\n discover(element);\n } catch (error) {\n console.error(`Failed to load custom element ${tag} from ${src}:`, error);\n }\n };\n\n /**\n * Finds all elements within a parent element that are not defined and attempts to load each of them\n *\n * @param element The element to look for undefined custom elements within\n */\n const discover = (element: Element) => {\n if (element.getAttribute('autoloader') == null) return;\n if (element.getAttribute('autoload-ignore') != null) return;\n const componentElement = element.shadowRoot ?? element;\n const elements = componentElement.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n const tag = el.localName;\n if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {\n load(el, tag);\n }\n }\n };\n\n return discover;\n};\n"],"names":["initAutoloader","rootDir","componentsDir","options","Error","extension","replace","base","URL","href","attempted","Set","load","async","element","tag","src","str","getAttribute","endsWith","slice","elementURL","has","add","startsWith","import","customElements","whenDefined","discover","error","console","elements","shadowRoot","querySelectorAll","i","length","el","localName","includes","get"],"mappings":"AAsEO,MCrDMA,EAAiB,CAC5BC,EACAC,EACAC,KAGA,IAAKF,EAAS,MAAM,IAAIG,MAAM,6DAG9B,MAAMC,EAAY,KAAKF,GAASE,WAAa,OAAOC,QAAQ,MAAO,MAS7DC,EAAO,IAAIC,IAAI,IAAKP,GAASQ,KAO7BC,EAAY,IAAIC,IAwBhBC,EAAOC,MAAOC,EAAkBC,KACpC,MAAMC,EAAM,IAAIR,IAZC,EAACM,EAAkBC,KDeN,IAACE,ECb/B,MAAO,GDaiD,OAAzBA,ECdAH,EAAQI,aAAa,iBAAmBhB,GAAiB,MDczBe,EAAIE,SAAS,KAAOF,EAAIG,MAAM,GAAG,GAAMH,KCbrFF,IAAMV,GAAW,EAUdgB,CAAWP,EAASC,GAAMd,GAASQ,KACvD,IAAIC,EAAUY,IAAIN,GAGlB,GAFAN,EAAUa,IAAIP,GAETA,EAAIQ,WAAWjB,GAKpB,UACQkB,OAA0BT,SAC1BU,eAAeC,YAAYZ,GACjCa,EAASd,EACX,CAAE,MAAOe,GACPC,QAAQD,MAAM,iCAAiCd,UAAYC,KAAQa,EACrE,MAVEC,QAAQD,MAAM,uBAAuBb,UAAYD,yBAA2BR,IAU9E,EAQIqB,EAAYd,IAChB,GAA0C,MAAtCA,EAAQI,aAAa,cAAuB,OAChD,GAA+C,MAA3CJ,EAAQI,aAAa,mBAA4B,OACrD,MACMa,GADmBjB,EAAQkB,YAAclB,GACbmB,iBAAiB,kBACnD,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAASI,OAAQD,IAAK,CACxC,MAAME,EAAKL,EAASG,GACdnB,EAAMqB,EAAGC,UACXtB,GAAKuB,SAAS,OAASZ,eAAea,IAAIxB,IAA8C,MAAtCqB,EAAGlB,aAAa,oBACpEN,EAAKwB,EAAIrB,EAEb,GAGF,OAAOa,CAAQ"}
1
+ {"version":3,"file":"vera-autoloader.min.js","sources":["../src/autoloader.ts","../src/loader.ts"],"sourcesContent":["import type { AutoloaderInstance, AutoloaderOptions } from './types.js';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * Discovery is **observed, not polled**. Each `autoloader`-marked component is watched once with a\n * `MutationObserver`, so an undefined element is found whenever it enters the DOM — by a render, by\n * `innerHTML`, by a third-party widget, or by having been in the HTML file all along. The previous\n * model re-scanned a marked component's whole tree on every render, which saw only what a Vera\n * render put there and cost more the larger the component got (measured in Chromium: 0.46 µs for a\n * 10-node component, 32.5 µs for a 1 000-node one, on every render, forever). An observation costs\n * ~0.6 µs per mutation batch and does not care how big the component is.\n *\n * One observer object watches every marked root — `observe()` takes many targets — and a mutation\n * only notifies observers on its own ancestor chain, so watched subtrees that are not the ones\n * changing cost nothing. Measured: 1 000 registrations left unrelated DOM work at 0.900 µs against\n * 0.933 µs with none. Watching `document` instead would have been the expensive shape, taxing every\n * mutation in the app by ~47%.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"data-autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`. `resolve` replaces URL building entirely.\n * @return `autoload` — call it with nothing to scan the page, with an element to watch that\n * component, or with a shadow root to watch that root. Safe to call repeatedly; a root is attached\n * once. Carries `url(tag)` and `retry(element)`.\n */\nexport const autoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): AutoloaderInstance => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /**\n * An option this autoloader does not have does nothing, and did so in silence — `extensions` or\n * `resolver` reads exactly like the real thing at a glance, and the symptom is the *default*\n * behaviour, which looks like the option was never needed rather than never seen.\n *\n * `__DEV__`-only, so a production bundle carries neither the list nor the text.\n */\n if (__DEV__ && options)\n for (const key of Object.keys(options))\n if (key !== 'extension' && key !== 'resolve')\n console.warn(\n `[vera] autoloader: \\`${key}\\` is not an option, so it was ignored. ` +\n `The options are extension and resolve.`\n );\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * `dir/tag.ext` is one layout, and a component library is as likely to use `tag/tag.js`,\n * `tag/index.js`, or a flat manifest. `resolve` replaces the URL-building step entirely while\n * leaving the containment check below untouched — so a custom layout cannot be used to escape\n * the entry's directory. Principle #6 names this module's hard-coded `.js` as the example of the\n * shape to avoid; the path around it is the same problem one level out.\n */\n const resolve = options?.resolve;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `data-autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n /**\n * A **relative** `rootDir` throws either way; development says why.\n *\n * The platform's own message — `Failed to construct 'URL': Invalid base URL` — names neither the\n * argument nor the fix. The value has to be absolute because every component URL resolves against\n * it, which is why `import.meta.url` is the documented answer. Behind `__DEV__`, so the build\n * folds it away and a production bundle carries neither the check nor the text.\n */\n if (__DEV__) {\n try {\n new URL('.', rootDir);\n } catch {\n throw new Error(\n `autoloader: rootDir must be an absolute URL, and \"${rootDir}\" is not. ` +\n `Pass import.meta.url — a relative path has nothing to resolve against.`\n );\n }\n }\n const base = new URL('.', rootDir).href;\n\n /** One attempt per URL per page load, so a 404 costs one request and one console line. */\n const attempted = new Set<string>();\n\n /**\n * Tags already being loaded, which is a different question from URLs already fetched.\n *\n * `<x-y>` and `<x-y data-autoload-dir=\"alt\">` are two URLs for one tag. Both used to import, and the\n * second module's `customElements.define('x-y')` threw `NotSupportedError` — surfacing as a\n * \"Failed to load\" for a component that had in fact loaded. A tag can only be defined once, so\n * the second URL could never have helped. It is released again if the first attempt fails, so a\n * second location is still allowed to try.\n */\n const requested = new Set<string>();\n\n /** The URL last tried for a tag, so `retry` knows which memo to clear. Dropped once it loads. */\n const failed = new Map<string, string>();\n\n /**\n * Roots under observation, so attaching is idempotent and cheap to re-attempt.\n *\n * Nothing prunes it, and nothing needs to: an observed node is collectable as soon as the page\n * drops it — measured in Chromium, where a removed node observed by a live observer is collected.\n * (jsdom reports otherwise, and reports it even after `disconnect()`, which is its own\n * bookkeeping rather than the observer contract.)\n */\n const watched = new WeakSet<Element | ShadowRoot>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `data-autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * Exposed as `autoload.url(tag)`, which is the whole of what a `preload` helper used to wrap:\n * with the URL in hand a caller can warm it with `<link rel=\"modulepreload\">`, prefetch it at a\n * lower priority, prime a service worker, or simply print it to answer \"why is it fetching\n * *that*?\" — the question this module gets asked most.\n *\n * @param tag The element's name\n * @param element The element being discovered, when there is one — only it can carry `data-autoload-dir`\n * @return The absolute URL this autoloader would fetch\n */\n const url = (tag: string, element?: Element) => {\n /**\n * Trailing slashes come off, and an empty or root-only directory becomes `.` — the entry file's\n * own directory, which is the only place a bounded URL can be anyway.\n *\n * The default used to be `/`, which built `//tag.js`: a **protocol-relative** URL, so\n * `new URL` read `tag.js` as a *host*. `autoloader(import.meta.url)` — the documented call\n * for components sitting beside the entry, since `componentsDir` is optional — therefore\n * refused every component it was asked for. `data-autoload-dir=\"/\"` did the same.\n */\n const dir = (element?.getAttribute('data-autoload-dir') ?? componentsDir ?? '.').replace(/\\/+$/, '') || '.';\n const href = new URL(resolve ? resolve(tag, dir) : `${dir}/${tag}${extension}`, rootDir).href;\n /**\n * **`?` and `#` end the path, so a directory cannot contain either.**\n *\n * The default layout builds `${dir}/${tag}${extension}` as text, and URL syntax then reads the\n * result rather than the intent. `data-autoload-dir=\"components?v=2\"` — an ordinary cache-buster, and\n * the reason this is a mistake someone makes rather than an attack — resolves to\n * `site/components?v=2/my-widget.js`, so the request goes to `site/components` with the **tag\n * name inside the query string**. The component file is never asked for. `#` is worse: the\n * fragment never reaches the network, so `site/components` is fetched outright.\n *\n * That is a wrong module, not a missing one, which is why it is refused rather than left to\n * 404. Containment does not catch it — the URL is genuinely inside the entry's directory, and\n * `data-autoload-dir=\"?\"` resolves to the entry file itself, re-importing the whole application under\n * a URL distinct enough to evaluate a second time.\n *\n * Only the default path is checked. `resolve` replaces URL building entirely and is documented\n * that way, so a query it adds is the caller's own — `components/tag.js?v=2` is exactly the\n * cache-buster the attribute cannot express, and it keeps working.\n */\n if (!resolve && /[?#]/.test(dir)) {\n const url = new URL(href);\n const refusal = new Error(\n `[vera] autoloader: refused ${href} for <${tag}> — data-autoload-dir \"${dir}\" contains ? or #, ` +\n `which ends the path, so <${tag}> lands in the query or fragment and ` +\n `${url.origin}${url.pathname} would be fetched instead. Use \\`resolve\\` to add a query.`\n );\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n /**\n * **An encoded separator is refused the way a real one is caught.**\n *\n * The URL parser handles every literal form: `..`, `..\\\\` and `%2e%2e/` all normalize into\n * genuine traversals that resolve outside `base` and fail the prefix test below — measured,\n * all three. But `%2F` and `%5C` survive resolution as DATA inside one path segment, so\n * `data-autoload-dir=\"..%2F..%2Fuploads\"` is textually inside the prefix while naming the exact\n * traversal a decode-then-resolve server turns real — and on a page whose markup is partly\n * authored elsewhere, that is an attacker importing an uploaded file as a same-origin module.\n * The URL standard is on the server's side here; principle #8 is not interested — this module\n * bounds what markup can turn into a module URL, and a directory whose name needs an encoded\n * slash has no honest reading. Same family as the `?`/`#` refusal above, same scope: the\n * default path only, since `resolve` owns its own URL building and a `%2F` in a query it adds\n * is legitimately its business.\n */\n if (!resolve && /%2f|%5c/i.test(dir)) {\n const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — encoded path separator in \"${dir}\"`);\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n /**\n * **Containment belongs here, not only at the fetch.**\n *\n * `data-autoload-dir` is an ordinary HTML attribute, so on any page whose markup is partly authored\n * elsewhere — a CMS, a sanitizer that keeps attributes, a template someone else fills — it is\n * an input. `data-autoload-dir=\"//evil.test\"` resolves to a different **origin** entirely, and\n * `..` walks out of the app.\n *\n * `load` always checked. This function is public and documented for preloading — warming a URL\n * with `<link rel=\"modulepreload\">` is its whole reason to exist — so returning a URL the loader\n * would refuse handed the caller the fetch this module declines to make. One check, at the one\n * place URLs are built, also covers a custom `resolve` returning something unbounded.\n *\n * `base` is `new URL('.', rootDir)`, which always ends in `/`, so the prefix test cannot be\n * satisfied by a sibling directory whose name merely starts the same way.\n */\n if (!href.startsWith(base)) {\n /**\n * The refused URL rides on the error, so discovery can dedupe on it exactly as it dedupes a\n * fetch. Keying the refusal on the *tag* instead would be wrong: `data-autoload-dir` is watched\n * precisely so it can be pointed somewhere else after a first attempt failed, and a tag\n * marked spent never looks again.\n */\n const refusal = new Error(`[vera] autoloader: refused ${href} for <${tag}> — resolves outside ${base}`);\n (refusal as Error & { href: string }).href = href;\n throw refusal;\n }\n return href;\n };\n\n /**\n * Loads an element's module and, once it has upgraded, starts watching it in turn.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n if (requested.has(tag)) return;\n let src;\n try {\n src = url(tag, element);\n } catch (error) {\n /**\n * Deduped on the refused URL, so it is reported once rather than on every scan — and so\n * pointing `data-autoload-dir` at a valid directory afterwards is a different URL and tries.\n */\n const href = (error as Error & { href?: string }).href;\n if (href !== undefined) {\n if (attempted.has(href)) return;\n attempted.add(href);\n }\n console.error((error as Error).message);\n return;\n }\n if (attempted.has(src)) return;\n attempted.add(src);\n requested.add(tag);\n failed.set(tag, src);\n\n try {\n await import(/* @vite-ignore */ src);\n /**\n * **A module can import cleanly and still not define the tag**, and that used to be silent\n * forever: `whenDefined` never settles, so the `catch` below never runs, no event is\n * dispatched, no line is logged, and the element sits unupgraded for the life of the page.\n * The everyday cause is a typo — markup says `<my-widget>`, the file defines `my-wdiget` — and\n * the everyday symptom is a blank space with a clean console.\n *\n * A dynamic `import()` resolves only after the module has fully evaluated, top-level `await`\n * included, so by here every `customElements.define` the module was going to run has run.\n * Two microtask turns are drained first anyway, which covers a define deferred by a resolved\n * promise; anything later than that is a floating promise the module never awaited.\n *\n * The wait is *not* abandoned — `whenDefined` is still awaited afterwards, so a definition\n * that does arrive late still upgrades and still gets watched. The error is a report, not a\n * refusal.\n */\n await Promise.resolve();\n await Promise.resolve();\n if (!customElements.get(tag)) {\n throw new Error(\n `imported ${src} but nothing defined <${tag}>. Check the tag name in that file matches ` +\n `the one in the markup, and that its \\`customElements.define\\` actually runs.`\n );\n }\n await customElements.whenDefined(tag);\n failed.delete(tag);\n watch(element);\n } catch (error) {\n requested.delete(tag);\n /**\n * Reported as a DOM event as well as a console line, because a component that never arrives\n * is something an app may want to render around — a placeholder, a retry button, a report to\n * an error tracker. An event rather than core's `'error'` insert: this package deliberately\n * does not depend on core, and reaching for `insert` from `@verajs/inserts` instead would\n * write to a registry core never reads in a production build.\n */\n element.dispatchEvent(\n new CustomEvent('vera:autoload-error', {\n bubbles: true,\n composed: true,\n detail: { tag, src, error, element },\n })\n );\n console.error(`[vera] autoloader: failed to load <${tag}> from ${src}:`, error);\n }\n };\n\n /** Loads one candidate, unless it has opted out. */\n const consider = (element: Element) => {\n if (element.getAttribute('data-autoload-ignore') == null) load(element, element.localName);\n };\n\n /**\n * `:not(:defined)` already means \"a custom element awaiting its definition\" — a dashless unknown\n * tag like `<madeupelement>` is defined, and an element leaves the set the moment its definition\n * lands. `tests/browser/autoloader.test.js` pins those semantics in a real engine, which is what\n * lets this trust the selector rather than re-checking the tag by hand.\n */\n const scan = (root: Element | ShadowRoot) => {\n const elements = root.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) consider(elements[i]);\n };\n\n /**\n * One observer for every watched root. A node added anywhere inside one is examined itself and\n * then scanned, because a subtree may arrive whole — `innerHTML` on a container delivers one\n * added node holding any number of undefined elements.\n */\n /**\n * Created on first use, not at construction.\n *\n * `new MutationObserver(...)` in the constructor made `autoloader` throw in Node —\n * `MutationObserver is not defined` — so an app entry that wires the autoloader could not be\n * imported server-side at all. `@verajs/router` attaches its window listeners lazily for exactly\n * this reason and says so; the observed-discovery rewrite reintroduced the problem here.\n */\n let observer;\n const observing = () =>\n (observer ??= new MutationObserver((records) => {\n for (const record of records) {\n /**\n * The three attributes are as much a part of discovery as insertion is. `autoloader` can be\n * put on a component that only becomes a lazy host once some state flips; `data-autoload-dir` can\n * be pointed somewhere else after a first attempt failed; `data-autoload-ignore` can be lifted.\n * Without watching them, all three needed the element to be inserted again before anything\n * noticed, which is not a thing that happens.\n */\n if (record.type === 'attributes') {\n const target = record.target as Element;\n if (record.attributeName === 'data-autoload') watch(target);\n else consider(target);\n continue;\n }\n\n const added = record.addedNodes;\n for (let i = 0; i < added.length; i++) {\n const node = added[i];\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n if (!customElements.get(element.localName) && element.localName.includes('-')) consider(element);\n scan(element);\n }\n }\n }));\n\n /**\n * Starts watching a component, and takes stock of what is already inside it.\n *\n * This is what the `'render'` insert calls, so it runs on every render of every component and has\n * to be cheap when there is nothing to do: an attribute read, then a `WeakSet` check. The scan\n * happens once, when the observation starts — everything after that arrives as a mutation.\n *\n * @param element The element to watch for undefined custom elements within\n */\n const watch = (target: Element | ShadowRoot | Document = document) => {\n /**\n * `autoload()` with nothing to point at means \"every marked host on the page, right now\".\n *\n * This used to happen by itself as the autoloader was created, which was wrong twice over: it\n * fired once, so markup arriving later — fetched, stamped from a template — was never seen and\n * said nothing about it; and two autoloaders on a page each adopted every marked host and raced\n * to load the same tags from their own directories, which needed an option to switch off. As a\n * shape of a function that already exists it costs almost nothing, can be called again whenever\n * new markup lands, and leaves `autoloader` free of side effects.\n *\n * A document is recognised by `nodeType`, not by having a `body`. `document.body` is null until\n * the parser reaches it, so an `autoload()` from a classic or `async` module script in `<head>`\n * fell straight through this branch and the document was treated as a root to watch — observing\n * `document` itself, `subtree: true`. That is precisely the shape this module exists to avoid\n * (~47% on every mutation in the app, measured), it was permanent once `watched` held the\n * document, and nothing said it had happened. `nodeType` is 9 from the moment the document is.\n */\n if ((target as Document).nodeType === 9)\n return (target as Document).querySelectorAll('[data-autoload]').forEach((el) => watch(el));\n let root = target as Element | ShadowRoot;\n /**\n * An `Element` has to opt in; a `ShadowRoot` handed over directly does not, because handing it\n * over *is* the opt-in. That is the way into a third-party component whose shadow root holds\n * tags of yours — nothing else can reach it, since an observer cannot cross a shadow boundary.\n */\n if ((target as Element).getAttribute) {\n const element = target as Element;\n if (element.getAttribute('data-autoload') == null) return;\n if (element.getAttribute('data-autoload-ignore') != null) return;\n root = element.shadowRoot ?? element;\n }\n if (watched.has(root)) return;\n watched.add(root);\n observing().observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['data-autoload', 'data-autoload-dir', 'data-autoload-ignore'],\n });\n scan(root);\n };\n\n /**\n * Forgets that this element's tag failed, and tries it again.\n *\n * A failed load is otherwise permanent for the page — right for a component that does not exist,\n * wrong for one lost to a dropped connection. `vera:autoload-error` hands you the element, which\n * is what makes retrying one thing rather than re-scanning every watched root possible.\n */\n const retry = (element: Element) => {\n const tag = element.localName;\n requested.delete(tag);\n const src = failed.get(tag);\n if (src) attempted.delete(src);\n failed.delete(tag);\n load(element, tag);\n };\n\n /**\n * The instance is also its own `wire` descriptor, so configuring the autoloader and installing it\n * are one call:\n *\n * ```js\n * wire([renderer, router, autoloader(import.meta.url, 'components')]);\n * ```\n *\n * This replaced `setAutoloader`, a bespoke registrar that lived in `@verajs/inserts` — the\n * registry package knowing about one specific consumer, which is the coupling `wire` exists to\n * remove. Every other module hands `wire` a descriptor; this one now does too.\n *\n * Priority 75 runs it *after* the renderer at 50, because it scans what the render just produced.\n */\n /**\n * `name` goes through `defineProperty` because a function's own `name` is non-writable, so\n * `Object.assign` throws in strict mode — and the descriptor's `name` is what the duplicate-\n * priority warning quotes, so leaving it as `\"watch\"` would name the wrong thing.\n */\n Object.defineProperty(watch, 'name', { value: '@verajs/autoloader', configurable: true });\n return Object.assign(watch, {\n url,\n retry,\n on: 'render' as const,\n fn: ((_: unknown, container: Element | ShadowRoot | Document) => {\n watch(container);\n }) as never,\n priority: 75,\n });\n};\n","/**\n * `directiveLoader` — the autoloader's answer on core's `'loader'` insert: a DIRECTIVE NAME\n * nobody has wired resolves by convention to one module URL, `{base}/{dir}/{name}.js`, exactly\n * as component tags resolve. The engine asks (design §7: directives DISCOVERS, autoloader\n * LOADS); this claims and imports; **the module registers itself** by importing\n * `wireDirectives` from the same specifier the page used — module caching makes that the same\n * registry, the precise symmetry of an autoloaded component calling `customElements.define`.\n *\n * ```js\n * import { wire } from '@verajs/core';\n * import { directiveLoader } from '@verajs/autoloader';\n * wire([directiveLoader(import.meta.url, 'directives')]);\n * ```\n *\n * A lazy module looks like:\n *\n * ```js\n * // directives/sparkle.js\n * import { wireDirectives } from '@verajs/directives';\n * wireDirectives({ name: 'sparkle', value: 'none', setup(el) { … } });\n * ```\n *\n * **The name is markup input** — it is the tail of an attribute an author (or a CMS, or an\n * attacker who can write attributes) chose — so it is allowlisted to the directive-name grammar\n * (`[a-z][a-z0-9-]*`) BEFORE any URL exists. That single gate closes the traversal and\n * encoded-separator families the component path has to police character by character, because a\n * tag name passes through the HTML parser and this does not. Containment against the entry's\n * directory is still enforced on the final URL, so an `alias` or `resolve` mistake cannot\n * escape either.\n *\n * The `alias` map is FACTORY-ONLY JavaScript (never markup — same rule as every policy option\n * in this codebase): it redirects names for grouped layouts, so `alias: { paint: 'motion.js',\n * split: 'motion.js' }` serves one bundle for a family. One attempt per name per page load,\n * exactly the autoloader's posture with URLs; the ASKER memoizes refusals, this memoizes loads.\n */\nimport type { DirectiveLoaderInstance, DirectiveLoaderOptions } from './types.js';\n\n/** The name grammar. An attribute tail that is not a plausible directive name is declined —\n * which also means it never becomes a URL. */\nconst SAFE_NAME = /^[a-z][a-z0-9-]*$/;\n\nexport const directiveLoader = (\n rootDir: string,\n directivesDir?: string,\n options?: DirectiveLoaderOptions\n): DirectiveLoaderInstance => {\n if (!rootDir) throw new Error('directiveLoader: rootDir is required (usually import.meta.url)');\n if (__DEV__) {\n try {\n new URL('.', rootDir);\n } catch {\n throw new Error(\n `directiveLoader: rootDir must be an absolute URL, and \"${rootDir}\" is not. ` +\n `Pass import.meta.url — a relative path has nothing to resolve against.`\n );\n }\n if (options)\n for (const key of Object.keys(options))\n if (key !== 'extension' && key !== 'alias' && key !== 'resolve')\n console.warn(\n `[vera] directiveLoader: \\`${key}\\` is not an option, so it was ignored. ` +\n `The options are extension, alias and resolve.`\n );\n }\n const base = new URL('.', rootDir).href;\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n const alias = options?.alias;\n const resolve = options?.resolve;\n const dir = (directivesDir ?? '.').replace(/\\/+$/, '') || '.';\n\n /** One import per name per page load; the promise is the memo, so N elements share one fetch. */\n const claimed = new Map<string, Promise<unknown>>();\n\n /**\n * The URL this loader would fetch for a name — public for the same reason the autoloader's\n * `url` is: warming with `<link rel=\"modulepreload\">` is the whole preload story, and printing\n * it answers \"why is it fetching THAT\". Throws on a name outside the grammar or a resolution\n * outside the entry's directory, exactly as `load` refuses them.\n */\n const url = (name: string): string => {\n if (!SAFE_NAME.test(name)) {\n throw new Error(`directiveLoader: \"${name}\" is not a directive name this will resolve.`);\n }\n const target = alias?.[name] ?? (resolve ? resolve(name, dir) : `${dir}/${name}${extension}`);\n const href = new URL(target, rootDir).href;\n /**\n * Containment on the FINAL url, whichever path built it. The name grammar already forbids\n * every traversal spelling markup could carry; this is the backstop for a factory mistake —\n * an `alias` of `../../evil.js`, a `resolve` returning an absolute URL — refused rather\n * than fetched, because a loader is a thing that turns strings into same-origin module\n * execution and the entry's directory is the stated bound.\n */\n if (!href.startsWith(base)) {\n throw new Error(`directiveLoader: refused ${href} for \"${name}\" — resolves outside ${base}`);\n }\n return href;\n };\n\n const load = (name: string): boolean | Promise<unknown> => {\n if (!SAFE_NAME.test(name)) return false;\n const existing = claimed.get(name);\n if (existing) return existing;\n let src: string;\n try {\n src = url(name);\n } catch (error) {\n console.error(`[vera] ${(error as Error).message}`);\n return false;\n }\n /**\n * The import IS the claim. Success means \"the module ran\" — whether it registered the name\n * is the ASKER's check, because only the asker owns the registry; a module that loads and\n * registers nothing earns `loader-loaded-nothing` there, with this URL in the story via the\n * console line below.\n */\n const request = import(/* @vite-ignore */ src).catch((error) => {\n console.error(`[vera] directiveLoader: failed to load \"${name}\" from ${src}:`, error);\n throw error;\n });\n claimed.set(name, request);\n return request;\n };\n\n /** The instance is its own wire descriptor — configuring and installing are one call. */\n Object.defineProperty(load, 'name', { value: '@verajs/autoloader directiveLoader', configurable: true });\n return Object.assign(load as (name: string, element: Element) => boolean | Promise<unknown>, {\n url,\n on: 'loader' as const,\n fn: load as never,\n /** Convention answers LAST: an app's own loader (an alias shim, a manifest) registers lower. */\n priority: 75,\n });\n};\n"],"names":["autoloader","rootDir","componentsDir","options","Error","extension","replace","resolve","base","URL","href","attempted","Set","requested","failed","Map","watched","WeakSet","url","tag","element","dir","getAttribute","test","refusal","origin","pathname","startsWith","load","async","has","src","error","undefined","add","console","message","set","import","Promise","customElements","get","whenDefined","delete","watch","dispatchEvent","CustomEvent","bubbles","composed","detail","consider","localName","scan","root","elements","querySelectorAll","i","length","observer","target","document","nodeType","forEach","el","shadowRoot","MutationObserver","records","record","type","attributeName","added","addedNodes","node","includes","observe","childList","subtree","attributes","attributeFilter","Object","defineProperty","value","configurable","assign","retry","on","fn","_","container","priority","SAFE_NAME","directiveLoader","directivesDir","alias","claimed","name","existing","request","catch"],"mappings":"AA8BO,MAAMA,EAAa,CACxBC,EACAC,EACAC,KAGA,IAAKF,EAAS,MAAM,IAAIG,MAAM,6DAkB9B,MAAMC,EAAY,KAAKF,GAASE,WAAa,OAAOC,QAAQ,MAAO,MAS7DC,EAAUJ,GAASI,QA2BnBC,EAAO,IAAIC,IAAI,IAAKR,GAASS,KAG7BC,EAAY,IAAIC,IAWhBC,EAAY,IAAID,IAGhBE,EAAS,IAAIC,IAUbC,EAAU,IAAIC,QAkBdC,EAAM,CAACC,EAAaC,KAUxB,MAAMC,GAAOD,GAASE,aAAa,sBAAwBpB,GAAiB,KAAKI,QAAQ,OAAQ,KAAO,IAClGI,EAAO,IAAID,IAAIF,EAAUA,EAAQY,EAAKE,GAAO,GAAGA,KAAOF,IAAMd,IAAaJ,GAASS,KAoBzF,IAAKH,GAAW,OAAOgB,KAAKF,GAAM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,IACEA,EAAMb,EAAI6E,EACZ,CAAE,MAAO/D,GAEP,OADAG,QAAQH,MAAM,UAAWA,EAAgBI,YAClC,CACT,CAOA,MAAM6D,EAAU3D,OAA0BP,GAAKmE,OAAOlE,IAEpD,MADAG,QAAQH,MAAM,2CAA2C+D,WAAchE,KAAQC,GACzEA,CAAK,IAGb,OADA8D,EAAQzD,IAAI0D,EAAME,GACXA,CAAO,EAKhB,OADAlB,OAAOC,eAAepD,EAAM,OAAQ,CAAEqD,MAAO,qCAAsCC,cAAc,IAC1FH,OAAOI,OAAOvD,EAAwE,CAC3FV,MACAmE,GAAI,SACJC,GAAI1D,EAEJ6D,SAAU,IACV"}
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "@verajs/autoloader",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
7
  "description": "A super small but powerful autoloader for web components that works great with VeraJs but can be used without.",
8
8
  "license": "MIT",
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
9
12
  "repository": {
10
13
  "type": "git",
11
14
  "url": "git+https://github.com/vera-js/vera.git",