mnfst 0.5.331 → 0.5.333

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/manifest.js CHANGED
@@ -353,8 +353,8 @@
353
353
  const DEFAULT_VERSION = 'latest';
354
354
 
355
355
  // Stamped at build
356
- const LOADER_VERSION = '0.5.331';
357
- const MODULES_INTEGRITY = 'sha384-4rxUiN8QXqxmELwJkms5jQMRC4IRJL3Q4U+VoZQf1ntoEEjt/9LV/EIHnmm2qeow';
356
+ const LOADER_VERSION = '0.5.333';
357
+ const MODULES_INTEGRITY = 'sha384-EoPUnvcTd0V6ugOg+8X6DWOIWmgwj36CxAAGVd+PwRq2h5Rmxh+vUp0wjh+xzml5';
358
358
  const INTEGRITY_FILE = 'manifest.modules.integrity.json';
359
359
  const VENDOR_FILE = 'manifest.vendor.integrity.json';
360
360
  // 'strict' | 'warn' while checks are requested; map promise while they apply
@@ -400,23 +400,13 @@
400
400
  'data',
401
401
  'icons',
402
402
  'localization',
403
- 'markdown',
404
- 'svg',
405
- 'code',
406
403
  'color',
407
404
  'toasts',
408
405
  'tooltips',
409
406
  'dropdowns',
410
- 'combobox',
411
407
  'computed',
412
408
  'tabs',
413
- 'slides',
414
- 'colorpicker',
415
- 'datepicker',
416
- 'charts',
417
409
  'url-parameters',
418
- 'virtual',
419
- 'export',
420
410
  'status'
421
411
  ];
422
412
 
@@ -436,8 +426,8 @@
436
426
  'appwrite-presences'
437
427
  ];
438
428
 
439
- // Loaded on use (x-rich-text / $rich, x-submit), with data-plugins, or as a dependency
440
- const USAGE_LOADED_PLUGINS = ['rich-text', 'submissions'];
429
+ // Loaded on use (see USAGE_PLUGINS), with data-modules, or as a dependency
430
+ const USAGE_LOADED_PLUGINS = ['rich-text', 'submissions', 'markdown', 'svg', 'code', 'combobox', 'slides', 'colorpicker', 'datepicker', 'charts', 'virtual', 'export'];
441
431
 
442
432
  // Plugin dependencies: plugins that require other plugins to be loaded first
443
433
  const PLUGIN_DEPENDENCIES = {
@@ -736,6 +726,7 @@
736
726
  // owns page-level state (utilities' style element and its order observer)
737
727
  // fights the first. A failed load is forgotten so a retry can still run.
738
728
  const pluginLoads = new Map();
729
+ const pluginsSettled = new Set();
739
730
 
740
731
  async function addScript(pluginName, version = RESOLVED_VERSION) {
741
732
  const prior = pluginLoads.get(pluginName);
@@ -747,7 +738,7 @@
747
738
  }
748
739
  const promise = fetchPluginScript(pluginName, version);
749
740
  pluginLoads.set(pluginName, { version, promise });
750
- promise.catch(() => pluginLoads.delete(pluginName));
741
+ promise.then(() => pluginsSettled.add(pluginName), () => pluginLoads.delete(pluginName));
751
742
  return promise;
752
743
  }
753
744
 
@@ -830,13 +821,48 @@
830
821
  // into template content, which the parser detaches) and inline scripts.
831
822
  // Rendered text is deliberately not scanned — code samples on a page
832
823
  // must not pull plugins in.
824
+ // attr matches x-name, x-name.mod and x-name:arg (family: also x-name-*); late: held until
825
+ // its module registers when Alpine walks it first (Rich Text and Submissions handle that themselves)
833
826
  const USAGE_PLUGINS = [
834
827
  { magic: '$chat', plugin: 'chat' },
835
828
  { magic: '$presence', plugin: 'appwrite-presences' },
836
- { magic: '$rich', plugin: 'rich-text', attr: 'x-rich-text' },
837
- { plugin: 'submissions', attr: 'x-submit' },
838
- ...['$share', '$secure', '$links', '$push', '$app', '$haptics', '$biometric', '$camera'].map(magic => ({ magic, plugin: 'device' }))
839
- ].map(u => ({ ...u, re: u.magic ? new RegExp('\\' + u.magic + '\\b') : null }));
829
+ { magic: '$rich', plugin: 'rich-text', attr: 'x-rich-text', family: true },
830
+ { plugin: 'submissions', attr: 'x-submit', family: true },
831
+ ...['$share', '$secure', '$links', '$push', '$app', '$haptics', '$biometric', '$camera'].map(magic => ({ magic, plugin: 'device' })),
832
+ { plugin: 'charts', attr: 'x-chart', magic: '$chart', present: 'ensureChartsPluginInitialized' },
833
+ { plugin: 'colorpicker', attr: 'x-colorpicker', magic: '$colorpicker', present: 'ensureColorpickerPluginInitialized' },
834
+ { plugin: 'datepicker', attr: 'x-date', magic: '$date', present: 'ensureDatepickerPluginInitialized' },
835
+ { plugin: 'combobox', attr: 'x-combobox', present: 'ensureComboboxPluginInitialized' },
836
+ { plugin: 'code', attr: 'x-code', present: 'ensureCodePluginInitialized' },
837
+ { plugin: 'code', attr: 'x-code-group', present: 'ensureCodePluginInitialized' },
838
+ { plugin: 'markdown', attr: 'x-markdown', present: 'ensureMarkdownPluginInitialized' },
839
+ { plugin: 'export', attr: 'x-export', magic: '$export', present: 'ensureExportPluginInitialized', call: true },
840
+ { plugin: 'export', attr: 'x-import', magic: '$import', present: 'ensureImportPluginInitialized', call: true },
841
+ { plugin: 'virtual', attr: 'x-virtual', present: 'ensureVirtualPluginInitialized' },
842
+ { plugin: 'slides', attr: 'x-carousel', present: 'ensureSlidesPluginInitialized' },
843
+ { plugin: 'svg', attr: 'x-svg', present: 'ensureSvgPluginInitialized' }
844
+ ].map(u => ({ ...u, late: USAGE_LOADED_PLUGINS.includes(u.plugin) && !['rich-text', 'submissions'].includes(u.plugin), re: u.magic ? new RegExp('\\' + u.magic + '\\b') : null }));
845
+ const USAGE_NAMES = [...new Set(USAGE_PLUGINS.map(u => u.plugin))];
846
+ const USAGE_ATTRS = new Map(USAGE_PLUGINS.filter(u => u.attr).map(u => [u.attr, u]));
847
+ const USAGE_FAMILIES = USAGE_PLUGINS.filter(u => u.family).map(u => [u.attr + '-', u]);
848
+ const attrPlugin = (name) => { const u = attrEntry(name); return u && u.plugin; };
849
+ // Usage entry for a directive attribute name, or undefined
850
+ function attrEntry(name) {
851
+ if (name.charCodeAt(0) !== 120 || name.charCodeAt(1) !== 45) return;
852
+ let end = name.length;
853
+ for (let i = 2; i < end; i++) { const c = name.charCodeAt(i); if (c === 46 || c === 58) { end = i; break; } }
854
+ const base = end === name.length ? name : name.slice(0, end);
855
+ const u = USAGE_ATTRS.get(base);
856
+ if (u) return u;
857
+ for (const [pre, entry] of USAGE_FAMILIES) if (base.startsWith(pre)) return entry;
858
+ }
859
+ // Plain-HTML trigger: <pre><code class="language-x"> and <code copy> (Code)
860
+ function elementPlugin(el) {
861
+ if (el.tagName !== 'CODE') return;
862
+ if (el.hasAttribute('copy')) return 'code';
863
+ const c = el.getAttribute('class');
864
+ if (c && c.indexOf('language-') !== -1 && el.parentElement && el.parentElement.tagName === 'PRE') return 'code';
865
+ }
840
866
  // $rich before Rich Text arrives (it loads on use, and SPA routes or component HTML can
841
867
  // need it later): an idle stand-in, so expressions never throw. Rich Text bumps `v` when
842
868
  // it registers the real magic, so effects that read $rich run again; Alpine binds magics
@@ -898,6 +924,263 @@
898
924
  stubEditMagic();
899
925
  // Plugins loaded after Alpine started adopt what its first walk already passed
900
926
  if (typeof document !== 'undefined') document.addEventListener('alpine:initialized', () => { window.__manifestAlpineStarted = true; }, { once: true });
927
+ // On-use modules not registered when Alpine walks their element: the element and its subtree
928
+ // are held uninitialised (Alpine.deferInit, inert like a deferred container, x-cloak stays) and
929
+ // started once, after the directive registers. Their magics answer through a forwarding
930
+ // stand-in until the module arrives, so expressions never throw.
931
+ const lateEntries = USAGE_PLUGINS.filter(u => u.late);
932
+ const LATE_ATTRS = lateEntries.filter(u => u.attr).map(u => u.attr);
933
+ // Ran before this loader: registered during alpine:init ahead of the wrappers below
934
+ const preloaded = typeof window === 'undefined' ? [] : lateEntries.filter(u => window[u.present]).map(u => u.plugin);
935
+ const registered = new Set();
936
+ const waiters = new Map();
937
+ const whenRegistered = (name) => {
938
+ if (registered.has(name)) return Promise.resolve();
939
+ if (!waiters.has(name)) { let resolve; const promise = new Promise(r => { resolve = r; }); waiters.set(name, { promise, resolve }); }
940
+ return waiters.get(name).promise;
941
+ };
942
+ // Attributes added to live elements before their directive existed (no hold possible): re-set once it registers
943
+ const reset = new Map();
944
+ const warnedLate = new Set();
945
+ const lateDirective = (attr) => { const u = attrEntry(attr); return u && u.late && !preloaded.includes(u.plugin) ? u : null; };
946
+ // Will this module arrive? Starts its load when the page may load it on use
947
+ const gaveUp = new Set();
948
+ function bringLate(plugin) {
949
+ if (usageFailed.has(plugin) || gaveUp.has(plugin)) return null;
950
+ if (!pluginLoads.has(plugin)) {
951
+ if (!usageSniff || _omitted.includes(plugin)) return null;
952
+ fetchUsed(resolveDependencies([plugin]).filter(p => !usageLoaded(p)));
953
+ }
954
+ const load = pluginLoads.get(plugin);
955
+ return load ? load.promise : null;
956
+ }
957
+ const heldEls = new WeakSet();
958
+ let heldCount = 0;
959
+ let heldRelease = null;
960
+ // Rendered from source: hidden while held so raw markdown/code never shows
961
+ const RENDERS = ['markdown', 'code', 'svg'];
962
+ // Form state typed while held, put back after start so x-model takes it (a real edit: input, then change)
963
+ function snapshot(root) {
964
+ const typed = [];
965
+ const controls = root.matches('input, textarea, select') ? [root] : [];
966
+ controls.push(...root.querySelectorAll('input, textarea, select'));
967
+ for (const c of controls) {
968
+ try {
969
+ // Files picked while held can't be set back, only announced
970
+ if (c.type === 'file') { if (c.files && c.files.length) typed.push([c, 'files', null]); continue; }
971
+ // A radio the pick unchecked follows from the one it checked
972
+ if (c.type === 'radio') { if (c.checked && !c.defaultChecked) typed.push([c, 'checked', true]); }
973
+ else if (c.type === 'checkbox') { if (c.checked !== c.defaultChecked) typed.push([c, 'checked', c.checked]); }
974
+ else if (c.tagName === 'SELECT') { const sel = [...c.options].map(o => o.selected); if (sel.some((s, i) => s !== c.options[i].defaultSelected)) typed.push([c, 'options', sel]); }
975
+ else if (c.value !== c.defaultValue) typed.push([c, 'value', c.value]);
976
+ } catch (_) { /* skipped */ }
977
+ }
978
+ const a = document.activeElement;
979
+ const focus = a && root.contains(a) ? [a, a.selectionStart, a.selectionEnd] : null;
980
+ return () => {
981
+ // Outside the held element these edits were already seen live: stop the replay at its root
982
+ const replay = new WeakSet();
983
+ const stop = (e) => { if (replay.has(e)) e.stopPropagation(); };
984
+ root.addEventListener('input', stop);
985
+ root.addEventListener('change', stop);
986
+ const fire = (c, type) => { const e = new Event(type, { bubbles: true }); replay.add(e); c.dispatchEvent(e); };
987
+ for (const [c, k, v] of typed) {
988
+ try {
989
+ // Taken over by its directive on start (e.g. a date field turned read-only): not typable there
990
+ if (!c.isConnected || c.readOnly || c.disabled) continue;
991
+ if (k === 'options') [...c.options].forEach((o, i) => { o.selected = !!v[i]; });
992
+ else if (k !== 'files') c[k] = v;
993
+ fire(c, 'input');
994
+ fire(c, 'change');
995
+ } catch (_) { /* skipped */ }
996
+ }
997
+ root.removeEventListener('input', stop);
998
+ root.removeEventListener('change', stop);
999
+ if (focus && focus[0].isConnected) {
1000
+ try { focus[0].focus({ preventScroll: true }); if (focus[1] != null) focus[0].setSelectionRange(focus[1], focus[2]); } catch (_) { }
1001
+ }
1002
+ };
1003
+ }
1004
+ function hold(A, el, u) {
1005
+ const load = bringLate(u.plugin);
1006
+ if (!load) return false;
1007
+ const name = u.attr.slice(2);
1008
+ heldEls.add(el);
1009
+ if (!heldCount++ && window.ManifestPending) heldRelease = window.ManifestPending.hold('held');
1010
+ // Once per hold, whatever throws on the way
1011
+ let released = false;
1012
+ const release = () => {
1013
+ if (released) return;
1014
+ released = true;
1015
+ heldEls.delete(el);
1016
+ if (!--heldCount && heldRelease) { const r = heldRelease; heldRelease = null; r(); }
1017
+ };
1018
+ const early = [];
1019
+ let hidden = null;
1020
+ try {
1021
+ // $refs read during the hold caches its proxy: give the outer root its refs object now
1022
+ const root = !el.hasAttribute('x-data') && el.parentElement && el.parentElement.closest('[x-data]');
1023
+ if (root) {
1024
+ if (!root._x_refs) root._x_refs = {};
1025
+ // Its refs inside the held subtree resolve during the hold too (x-ref sets the same entry on start)
1026
+ for (const r of [el, ...el.querySelectorAll('[x-ref]')]) {
1027
+ const ref = r.getAttribute('x-ref');
1028
+ // Last one wins, as when Alpine sets them; a live ref of the same name stays
1029
+ if (ref && r.closest('[x-data]') === root && (!root._x_refs[ref] || early.some(e => e[2] === root._x_refs[ref]))) { root._x_refs[ref] = r; early.push([root, ref, r]); }
1030
+ }
1031
+ }
1032
+ hidden = RENDERS.includes(u.plugin) ? el.style.opacity : null;
1033
+ if (hidden !== null) el.style.opacity = '0';
1034
+ } catch (_) { /* best effort */ }
1035
+ const ready = new Promise((resolve) => {
1036
+ let started = false;
1037
+ whenRegistered(name).then(() => { started = true; resolve(); });
1038
+ const giveUp = (why) => {
1039
+ if (started) return;
1040
+ gaveUp.add(u.plugin);
1041
+ if (!warnedLate.has(u.plugin)) { warnedLate.add(u.plugin); console.warn(`[Manifest Loader] ${u.plugin} ${why}: starting the elements that use it now${why === 'failed to load' ? ', without it' : '; it applies to them if it starts later'}.`); }
1042
+ resolve();
1043
+ };
1044
+ load.catch(() => giveUp('failed to load'));
1045
+ // Loaded but never registered (e.g. its own vendor file failed): don't hold forever
1046
+ load.then(() => setTimeout(() => giveUp('has not started 10 s after loading'), 10000), () => { });
1047
+ });
1048
+ const start = ready.then(() => {
1049
+ let restore = null;
1050
+ try {
1051
+ heldEls.delete(el);
1052
+ if (hidden !== null) el.style.opacity = hidden;
1053
+ // Refs set early for elements removed before start: gone, as if never started
1054
+ for (const [root, ref, r] of early) if (!r.isConnected && root._x_refs && root._x_refs[ref] === r) delete root._x_refs[ref];
1055
+ restore = snapshot(el);
1056
+ } catch (_) { /* start anyway */ }
1057
+ // After Alpine's start of the element (same turn), so typed values win over the model's initial one
1058
+ setTimeout(() => { try { if (restore) restore(); } finally { release(); } }, 0);
1059
+ });
1060
+ try { A.deferInit(el, start); } catch (e) { release(); throw e; }
1061
+ return true;
1062
+ }
1063
+ let lateArmed = false;
1064
+ function armLateModules() {
1065
+ const A = typeof window === 'undefined' ? null : window.Alpine;
1066
+ if (lateArmed || !A || !A.directive || !A.magic) return;
1067
+ lateArmed = true;
1068
+ const directive = A.directive, magic = A.magic;
1069
+ A.directive = function (name) {
1070
+ const out = directive.apply(this, arguments);
1071
+ if (!registered.has(name)) {
1072
+ registered.add(name);
1073
+ const w = waiters.get(name);
1074
+ if (w) { waiters.delete(name); w.resolve(); }
1075
+ const els = reset.get(name);
1076
+ if (els) {
1077
+ reset.delete(name);
1078
+ setTimeout(() => els.forEach(([ref, attr]) => { const el = deref(ref); try { if (el && el.isConnected && el.hasAttribute(attr)) el.setAttribute(attr, el.getAttribute(attr)); } catch (_) { } }), 0);
1079
+ }
1080
+ }
1081
+ return out;
1082
+ };
1083
+ if (typeof A.interceptInit === 'function') {
1084
+ const canHold = typeof A.deferInit === 'function';
1085
+ // Never breaks Alpine's walk: an element that cannot be held is started as usual
1086
+ const intercept = (el) => { try { check(el); } catch (_) { /* not held */ } };
1087
+ const check = (el) => {
1088
+ if (heldEls.has(el)) return;
1089
+ for (const attr of el.attributes) {
1090
+ const u = lateDirective(attr.name);
1091
+ if (!u || registered.has(u.attr.slice(2))) continue;
1092
+ // Given up on: start now, apply the directive if it registers later
1093
+ if (gaveUp.has(u.plugin)) { note(u, el, attr.name); continue; }
1094
+ if (canHold) { if (hold(A, el, u)) return; continue; }
1095
+ // Older Alpine without deferInit: run just that directive once it registers
1096
+ if (bringLate(u.plugin)) note(u, el, attr.name);
1097
+ }
1098
+ };
1099
+ A.interceptInit(typeof A.skipDuringClone === 'function' ? A.skipDuringClone(intercept) : intercept);
1100
+ }
1101
+ armStandIns(A, magic);
1102
+ }
1103
+ const deref = (r) => r && typeof r.deref === 'function' ? r.deref() : r;
1104
+ function note(u, el, attr) {
1105
+ const name = u.attr.slice(2);
1106
+ if (registered.has(name)) return;
1107
+ if (!reset.has(name)) reset.set(name, []);
1108
+ // Weakly held: elements removed for good (route swaps) are not kept alive until it registers
1109
+ const list = reset.get(name).filter(([ref]) => deref(ref));
1110
+ list.push([typeof WeakRef === 'function' ? new WeakRef(el) : el, attr]);
1111
+ reset.set(name, list);
1112
+ }
1113
+ // Forwarding stand-in for a magic whose module has not registered yet
1114
+ function armStandIns(A, magic) {
1115
+ const real = {};
1116
+ const state = A.reactive ? A.reactive({ v: 0 }) : { v: 0 };
1117
+ // Probing must not count as a read (a second loader's stand-ins would start loads)
1118
+ const has = (name) => { window.__manifestProbing = true; try { return A.evaluate(document.createElement('div'), `typeof $${name}`) !== 'undefined'; } catch (_) { return false; } finally { window.__manifestProbing = false; } };
1119
+ // Reads the real value once there; until then reads as empty text, is callable and never thenable
1120
+ const forward = (resolve, settle) => new Proxy(function () { }, {
1121
+ get(t, k) {
1122
+ const v = resolve();
1123
+ if (v != null) { const r = v[k]; return typeof r === 'function' && k !== 'constructor' ? r.bind(v) : r; }
1124
+ if (k === Symbol.toPrimitive) return () => '';
1125
+ if (typeof k === 'symbol' || k === 'then') return undefined;
1126
+ return forward(() => { const b = resolve(); return b == null ? undefined : b[k]; }, settle);
1127
+ },
1128
+ apply(t, self, args) {
1129
+ const f = resolve();
1130
+ if (typeof f === 'function') return f.apply(self, args);
1131
+ // Function-valued magics: the call waits for the module, then runs once
1132
+ if (settle) return settle().then(() => { const g = resolve(); return typeof g === 'function' ? g.apply(self, args) : undefined; });
1133
+ let done = false, out;
1134
+ return forward(() => { if (done) return out; const g = resolve(); if (typeof g !== 'function') return undefined; done = true; return (out = g.apply(self, args)); }, settle);
1135
+ }
1136
+ });
1137
+ for (const u of lateEntries) {
1138
+ if (!u.magic || preloaded.includes(u.plugin) || pluginsSettled.has(u.plugin)) continue;
1139
+ const name = u.magic.slice(1);
1140
+ // An app's own magic of the same name stays
1141
+ if (has(name)) continue;
1142
+ let asked = false;
1143
+ const arrived = () => new Promise((resolve) => {
1144
+ if (real[name]) return resolve();
1145
+ const load = bringLate(u.plugin);
1146
+ if (!load) return resolve();
1147
+ const check = () => real[name] ? resolve() : null;
1148
+ load.then(() => setTimeout(() => { check(); setTimeout(resolve, 0); }, 0), resolve);
1149
+ });
1150
+ magic.call(A, name, (el, utils) => {
1151
+ void state.v;
1152
+ if (real[name]) return real[name](el, utils);
1153
+ if (!asked && !window.__manifestProbing) {
1154
+ asked = true;
1155
+ // No markup trigger (e.g. a script file): load it now, or say why it never will
1156
+ if (!bringLate(u.plugin) && !warnedLate.has(name) && !warnedLate.has(u.plugin)) {
1157
+ warnedLate.add(name);
1158
+ const fix = _omitted.includes(u.plugin) ? `remove ${u.plugin} from data-omit` : `add data-modules="+${u.plugin}"`;
1159
+ console.warn(`[Manifest Loader] ${u.magic} is used but ${u.plugin} is not loaded on this page: ${fix}.`);
1160
+ }
1161
+ }
1162
+ // A file picker needs the click's user activation, which may expire while the module loads
1163
+ const fn = !u.call ? null : u.magic !== '$import' ? arrived : () => arrived().then(() => {
1164
+ const ua = navigator.userActivation;
1165
+ if (ua && !ua.isActive && !warnedLate.has('$import:activation')) {
1166
+ warnedLate.add('$import:activation');
1167
+ console.warn('[Manifest Loader] $import waited for its module and the click that called it expired, so the browser may not open the file picker. Add data-modules="+import" to load it with the page.');
1168
+ }
1169
+ });
1170
+ return forward(() => real[name] ? real[name](el, utils) : undefined, fn);
1171
+ });
1172
+ }
1173
+ A.magic = function (name, cb) {
1174
+ if (lateEntries.some(u => u.magic === '$' + name)) { real[name] = cb; setTimeout(() => { state.v++; }, 0); }
1175
+ return magic.apply(this, arguments);
1176
+ };
1177
+ }
1178
+ if (typeof document !== 'undefined') {
1179
+ document.addEventListener('alpine:init', armLateModules, { once: true });
1180
+ if (typeof window !== 'undefined' && window.Alpine && window.Alpine.magic) armLateModules();
1181
+ }
1182
+ // Inside a held subtree: modules that walk elements themselves leave these to the hold
1183
+ if (typeof window !== 'undefined') window.__manifestHeld = (el) => { if (!heldCount) return false; for (let n = el; n; n = n.parentElement) if (heldEls.has(n)) return true; return false; };
901
1184
  // Framework web components — <x-*> tags that are NOT project components.
902
1185
  const FRAMEWORK_TAG_RE = /^x-(code|code-group)$/;
903
1186
  // Attribute values seen to hold no usage magic at all; repeated rows hit this instead of the regexes
@@ -910,8 +1193,11 @@
910
1193
  const wantComponents = !alreadyLoaded.includes('components');
911
1194
  if ((wanted.length === 0 && !wantComponents) || !root) return [];
912
1195
  const found = new Set();
913
- const target = new Set(wanted.map(u => u.plugin)).size + (wantComponents ? 1 : 0);
1196
+ const open = new Set(wanted.map(u => u.plugin));
1197
+ const target = open.size + (wantComponents ? 1 : 0);
914
1198
  const done = () => found.size === target;
1199
+ const take = (p) => { if (p && open.has(p) && !found.has(p)) found.add(p); };
1200
+ const wantCode = open.has('code');
915
1201
 
916
1202
  for (const s of root.querySelectorAll('script:not([src])')) {
917
1203
  const t = s.textContent || '';
@@ -924,8 +1210,9 @@
924
1210
  const tag = el.tagName.toLowerCase();
925
1211
  if (tag.startsWith('x-') && !FRAMEWORK_TAG_RE.test(tag)) found.add('components');
926
1212
  }
1213
+ if (wantCode) take(elementPlugin(el));
927
1214
  for (const attr of el.attributes || []) {
928
- for (const u of wanted) if (u.attr && !found.has(u.plugin) && (attr.name === u.attr || attr.name.startsWith(u.attr + '-') || attr.name.startsWith(u.attr + '.'))) found.add(u.plugin);
1215
+ take(attrPlugin(attr.name));
929
1216
  const v = attr.value;
930
1217
  if (!v || v.indexOf('$') === -1 || usageClean.has(v)) continue;
931
1218
  if (!USAGE_ANY_RE.test(v)) {
@@ -954,30 +1241,60 @@
954
1241
  return [...found];
955
1242
  }
956
1243
 
1244
+ // Boot sniff, once per page: everything the parsed document uses (nothing counted as loaded);
1245
+ // nodes added before the loader applies it are scanned then, not the whole document again
1246
+ let bootUsage = null;
1247
+ function sniffBoot() {
1248
+ if (bootUsage) return bootUsage;
1249
+ const added = new Set();
1250
+ const mo = typeof MutationObserver === 'undefined' ? null : new MutationObserver((records) => {
1251
+ for (const r of records) for (const n of r.addedNodes) if (n.nodeType === 1) added.add(n);
1252
+ });
1253
+ if (mo) mo.observe(document.documentElement, { childList: true, subtree: true });
1254
+ const used = detectUsagePlugins([]);
1255
+ bootUsage = {
1256
+ used,
1257
+ take() {
1258
+ if (mo) mo.disconnect();
1259
+ const all = new Set(used);
1260
+ for (const n of added) if (n.isConnected) detectUsagePlugins([...all], n).forEach(p => all.add(p));
1261
+ added.clear();
1262
+ return [...all];
1263
+ }
1264
+ };
1265
+ return bootUsage;
1266
+ }
1267
+
957
1268
  // Post-boot usage: component HTML, x-html and markdown content load the
958
1269
  // on-use plugins they reference. Derive path only, like the boot sniff.
959
1270
  let usageSniff = false;
960
1271
  // A failed on-use load is not retried within this page load
961
1272
  const usageFailed = new Set();
962
- const usageLoaded = (p) => pluginLoads.has(p) || usageFailed.has(p);
1273
+ // Settled loads only: a second caller waits on a load still in flight
1274
+ const usageLoaded = (p) => pluginsSettled.has(p) || usageFailed.has(p);
963
1275
  function loadUsed(source, version = RESOLVED_VERSION) {
964
1276
  if (!usageSniff || !source || typeof document === 'undefined') return Promise.resolve([]);
965
1277
  let root = source;
966
1278
  if (typeof source === 'string') {
967
- if (source.indexOf('x-') === -1 && source.indexOf('$') === -1) return Promise.resolve([]);
1279
+ if (source.indexOf('x-') === -1 && source.indexOf('$') === -1 && source.indexOf('<code') === -1) return Promise.resolve([]);
968
1280
  root = document.createElement('template');
969
1281
  root.innerHTML = source;
970
1282
  root = root.content;
971
1283
  }
972
- const loaded = [...new Set(USAGE_PLUGINS.map(u => u.plugin))].filter(usageLoaded).concat('components', _omitted);
1284
+ const loaded = USAGE_NAMES.filter(usageLoaded).concat('components', _omitted);
973
1285
  const used = detectUsagePlugins(loaded, root);
974
1286
  if (!used.length) return Promise.resolve([]);
975
- const list = resolveDependencies(used).filter(p => !usageLoaded(p));
1287
+ return fetchUsed(resolveDependencies(used).filter(p => !usageLoaded(p)), version);
1288
+ }
1289
+ function fetchUsed(list, version = RESOLVED_VERSION) {
1290
+ if (!list.length) return Promise.resolve([]);
1291
+ // Prerender waits for the module and the adoption it schedules
1292
+ const release = window.ManifestPending ? window.ManifestPending.hold('module') : () => { };
976
1293
  return Promise.all(list.map(p => addScript(p, version).catch(error => {
977
1294
  if (usageFailed.has(p)) return;
978
1295
  usageFailed.add(p);
979
1296
  console.warn(`[Manifest Loader] Failed to load plugin ${p}:`, error);
980
- }))).then(() => list);
1297
+ }))).then(() => new Promise(r => setTimeout(r, 0))).then(() => { release(); return list; });
981
1298
  }
982
1299
 
983
1300
  function watchUsage(version) {
@@ -986,7 +1303,10 @@
986
1303
  let queued = false;
987
1304
  const allLoaded = () => USAGE_PLUGINS.every(u => usageLoaded(u.plugin) || _omitted.includes(u.plugin));
988
1305
  const observer = new MutationObserver((records) => {
989
- for (const r of records) for (const n of r.addedNodes) if (n.nodeType === 1) pending.add(n);
1306
+ for (const r of records) {
1307
+ if (r.type === 'attributes') { attrAdded(r.target, r.attributeName); continue; }
1308
+ for (const n of r.addedNodes) if (n.nodeType === 1) pending.add(n);
1309
+ }
990
1310
  if (queued || !pending.size) return;
991
1311
  queued = true;
992
1312
  setTimeout(() => {
@@ -997,7 +1317,13 @@
997
1317
  if (allLoaded()) observer.disconnect();
998
1318
  }, 0);
999
1319
  });
1000
- observer.observe(document.documentElement, { childList: true, subtree: true });
1320
+ // Attribute additions on live elements, on-use directive names only (exact: setAttribute('x-date', …))
1321
+ observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: LATE_ATTRS });
1322
+ }
1323
+ function attrAdded(el, name) {
1324
+ const u = lateDirective(name);
1325
+ if (!u || !el.hasAttribute(name) || registered.has(u.attr.slice(2)) || window.__manifestHeld(el)) return;
1326
+ if (bringLate(u.plugin)) note(u, el, name);
1001
1327
  }
1002
1328
 
1003
1329
  const RENAMED_PLUGINS = { 'text-edit': 'rich-text' };
@@ -1424,6 +1750,11 @@
1424
1750
  if (!window.Alpine && !document.querySelector('script[src*="alpinejs"]')) {
1425
1751
  hint('preload', alpineUrlCandidates(config.alpine)[0], 'script');
1426
1752
  }
1753
+ // On-use modules this page uses, while manifest.json may still be in flight
1754
+ if (config.deriveFromManifest) {
1755
+ const used = sniffBoot().used.filter(p => p !== 'components' && !_omitted.includes(p));
1756
+ for (const p of resolveDependencies(used)) if (!config.plugins.includes(p)) hint('preload', getPluginUrl(p, config.version), 'script');
1757
+ }
1427
1758
  } catch (_) { /* optional */ }
1428
1759
  });
1429
1760
  } catch (_) { /* hints are optional */ }
@@ -1472,6 +1803,29 @@
1472
1803
  if (config.tailwind && !staticUtilitiesFullyCovered()) {
1473
1804
  pluginPromises.push(loadTailwind(config.version).catch(() => { }));
1474
1805
  }
1806
+ // Usage sniff once the document is parsed: on-use modules download alongside the
1807
+ // rest and run before Alpine. Derive path only — an explicit data-modules list is an
1808
+ // intentional constraint, not a default.
1809
+ const sniffed = !config.deriveFromManifest ? null : new Promise((resolve) => whenDomReady(() => {
1810
+ let late = [];
1811
+ try {
1812
+ const all = sniffBoot().take();
1813
+ // An omitted module the page uses fails far from the cause: say so once
1814
+ const blocked = all.filter(p => _omitted.includes(p) && !pluginsToLoad.includes(p));
1815
+ blocked.forEach(p => warnedLate.add(p));
1816
+ if (blocked.length) console.warn(`[Manifest Loader] data-omit lists ${blocked.join(', ')}, but this page uses ${blocked.length > 1 ? 'them' : 'it'}. Not loaded: remove ${blocked.length > 1 ? 'them' : 'it'} from data-omit to load.`);
1817
+ const used = all.filter(p => !pluginsToLoad.includes(p) && !_omitted.includes(p));
1818
+ if (used.length > 0) {
1819
+ late = resolveDependencies(used).filter(p => !pluginsToLoad.includes(p)).map(p => addScript(p, config.version).catch(error => {
1820
+ usageFailed.add(p);
1821
+ console.warn(`[Manifest Loader] Failed to load plugin ${p}:`, error);
1822
+ }));
1823
+ }
1824
+ } catch (_) { /* sniffing must never block Alpine */ }
1825
+ usageSniff = true;
1826
+ watchUsage(config.version);
1827
+ resolve(Promise.all(late));
1828
+ }));
1475
1829
  await Promise.all(pluginPromises);
1476
1830
  if (manifestPromise) {
1477
1831
  manifest = await manifestPromise;
@@ -1483,28 +1837,8 @@
1483
1837
  window.ManifestComponentsRegistry.manifest = manifest;
1484
1838
  }
1485
1839
  }
1486
- // Usage sniff: Alpine is DCL-gated anyway, so the parsed document can
1487
- // be checked for magics with no declarative trigger and the missing
1488
- // plugins fetched before Alpine boots. Derive path only — an explicit
1489
- // data-plugins list is an intentional constraint, not a default.
1490
1840
  whenDomReady(async () => {
1491
- if (config.deriveFromManifest) {
1492
- try {
1493
- // An omitted module the page uses fails far from the cause: say so once
1494
- const blocked = _omitted.length ? detectUsagePlugins(pluginsToLoad).filter(p => _omitted.includes(p)) : [];
1495
- if (blocked.length) console.warn(`[Manifest Loader] data-omit lists ${blocked.join(', ')}, but this page uses ${blocked.length > 1 ? 'them' : 'it'}. Not loaded: remove ${blocked.length > 1 ? 'them' : 'it'} from data-omit to load.`);
1496
- const used = detectUsagePlugins([...pluginsToLoad, ..._omitted]);
1497
- if (used.length > 0) {
1498
- const late = resolveDependencies(used).filter(p => !pluginsToLoad.includes(p));
1499
- await Promise.all(late.map(p => addScript(p, config.version).catch(error => {
1500
- usageFailed.add(p);
1501
- console.warn(`[Manifest Loader] Failed to load plugin ${p}:`, error);
1502
- })));
1503
- }
1504
- } catch (_) { /* sniffing must never block Alpine */ }
1505
- usageSniff = true;
1506
- watchUsage(config.version);
1507
- }
1841
+ if (sniffed) await sniffed;
1508
1842
  startReadyCoordinator(pluginsToLoad, config.tailwind);
1509
1843
  loadAlpine(alpineUrlCandidates(config.alpine));
1510
1844
  });