webspresso 0.0.106 → 0.0.107

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.
Files changed (49) hide show
  1. package/bin/webspresso.js +17 -7
  2. package/core/app.js +38 -6
  3. package/core/auth/index.js +4 -1
  4. package/core/auth/jwt.js +85 -13
  5. package/core/auth/magic-link.js +23 -5
  6. package/core/auth/manager.js +7 -1
  7. package/core/auth/redis-session.js +62 -25
  8. package/core/auth/session-manager.js +28 -2
  9. package/core/auth/sessions.js +182 -52
  10. package/core/console/eval.js +4 -1
  11. package/core/content/service.js +1 -0
  12. package/core/errors/domain.js +20 -2
  13. package/core/errors/http.js +1 -0
  14. package/core/http/hono-adapter.js +1 -1
  15. package/core/http/pipeline.js +36 -2
  16. package/core/index.js +12 -1
  17. package/core/mail/mailer.js +1 -1
  18. package/core/orm/eager-loader.js +81 -1
  19. package/core/orm/index.js +27 -13
  20. package/core/orm/json-fields.js +44 -13
  21. package/core/orm/model.js +12 -0
  22. package/core/orm/query-builder.js +33 -15
  23. package/core/orm/repository.js +59 -12
  24. package/core/orm/scopes.js +54 -4
  25. package/core/services/index.js +9 -0
  26. package/core/shutdown/shutdown-manager.js +57 -38
  27. package/core/studio/inspector.js +9 -1
  28. package/core/studio/server.js +24 -8
  29. package/core/utils/string.js +77 -16
  30. package/core/validation/index.js +18 -0
  31. package/index.d.ts +172 -8
  32. package/index.js +4 -0
  33. package/package.json +18 -8
  34. package/plugins/admin-panel/client/parts/07-model-list.js +5 -2
  35. package/plugins/admin-panel/index.js +24 -11
  36. package/plugins/admin-panel/modules/user-management.js +3 -2
  37. package/plugins/csrf/index.js +2 -1
  38. package/plugins/dashboard/index.js +27 -7
  39. package/src/app-context.js +9 -1
  40. package/src/file-router.js +12 -3
  41. package/src/plugin-manager.js +273 -48
  42. package/src/server.js +26 -33
  43. package/src/services/discovery.js +9 -1
  44. package/src/services/executor.js +271 -58
  45. package/src/services/index.js +52 -3
  46. package/src/services/loader.js +120 -0
  47. package/src/services/memoize.js +223 -49
  48. package/src/services/registry.js +492 -94
  49. package/src/services/validator.js +164 -13
@@ -58,12 +58,17 @@ function collectModels() {
58
58
 
59
59
  /**
60
60
  * Safely collects all registered business services
61
+ * @param {Object} [explicitRegistry]
61
62
  * @returns {Array<Object>}
62
63
  */
63
- function collectServices() {
64
+ function collectServices(explicitRegistry) {
64
65
  try {
65
- if (!hasServiceRegistry()) return [];
66
- const registry = getServiceRegistry();
66
+ let registry = explicitRegistry;
67
+ if (!registry || !registry.services) {
68
+ if (hasServiceRegistry()) {
69
+ registry = getServiceRegistry();
70
+ }
71
+ }
67
72
  const result = [];
68
73
  if (registry && registry.services) {
69
74
  for (const [name, def] of registry.services.entries()) {
@@ -156,9 +161,11 @@ function dashboardPlugin(options = {}) {
156
161
  }
157
162
  }
158
163
 
164
+ const appRegistry = ctx.serviceRegistry || app?.serviceRegistry || appOptions.serviceRegistry;
165
+
159
166
  // Collect models and services
160
167
  const models = collectModels();
161
- const services = collectServices();
168
+ const services = collectServices(appRegistry);
162
169
 
163
170
  // Build config data
164
171
  const config = {
@@ -192,7 +199,20 @@ function dashboardPlugin(options = {}) {
192
199
 
193
200
  // 1. Dashboard HTML endpoint
194
201
  ctx.addRoute('get', dashboardPath, (req, res) => {
195
- const data = { routes, plugins, config, models, services, overview };
202
+ const currentServices = collectServices(req.app?.serviceRegistry || appRegistry);
203
+ const currentModels = collectModels();
204
+ const data = {
205
+ routes,
206
+ plugins,
207
+ config,
208
+ models: currentModels,
209
+ services: currentServices,
210
+ overview: {
211
+ ...overview,
212
+ modelsCount: currentModels.length,
213
+ servicesCount: currentServices.length,
214
+ },
215
+ };
196
216
  res.type('text/html');
197
217
  res.send(generateDashboardHtml(data));
198
218
  });
@@ -215,14 +235,14 @@ function dashboardPlugin(options = {}) {
215
235
  });
216
236
 
217
237
  ctx.addRoute('get', `${dashboardPath}/api/services`, (req, res) => {
218
- res.json(collectServices());
238
+ res.json(collectServices(req.app?.serviceRegistry || appRegistry));
219
239
  });
220
240
 
221
241
  ctx.addRoute('get', `${dashboardPath}/api/overview`, (req, res) => {
222
242
  res.json({
223
243
  routesCount: (ctx.routes || []).length,
224
244
  modelsCount: collectModels().length,
225
- servicesCount: collectServices().length,
245
+ servicesCount: collectServices(req.app?.serviceRegistry || appRegistry).length,
226
246
  pluginsCount: plugins.length,
227
247
  nodeVersion: process.version,
228
248
  platform: process.platform,
@@ -103,7 +103,15 @@ function hasEvents() {
103
103
  * Clear context (e.g. between tests).
104
104
  */
105
105
  function resetAppContext() {
106
- context = { db: null, shutdownManager: null, serviceRegistry: null, events: null, mailer: null, cache: null };
106
+ context = {
107
+ db: null,
108
+ shutdownManager: null,
109
+ serviceRegistry: null,
110
+ events: null,
111
+ mailer: null,
112
+ cache: null,
113
+ breakers: circuitBreakerRegistry,
114
+ };
107
115
  }
108
116
 
109
117
  /**
@@ -1576,12 +1576,19 @@ function mountPages(app, options) {
1576
1576
 
1577
1577
  // Create context with plugin helpers merged
1578
1578
  const baseHelpers = createHelpers({ req, res, locale, t });
1579
- const pluginHelpers = pluginManager ? pluginManager.getHelpers() : EMPTY_OBJECT;
1579
+ const pluginStaticHelpers = pluginManager ? pluginManager.getHelpers() : EMPTY_OBJECT;
1580
+ let pluginDynamicHelpers = null;
1580
1581
  if (pluginManager) {
1581
1582
  const contentApi = pluginManager.getPluginAPI('content');
1582
1583
  if (contentApi?.createRequestHelpers) {
1583
1584
  const buildHelpers = contentApi.createRequestHelpers();
1584
- pluginHelpers.content = buildHelpers(req);
1585
+ pluginDynamicHelpers = { content: buildHelpers(req) };
1586
+ }
1587
+ if (typeof pluginManager.getRequestHelpers === 'function') {
1588
+ const reqHelpers = pluginManager.getRequestHelpers(req);
1589
+ if (reqHelpers) {
1590
+ pluginDynamicHelpers = Object.assign(pluginDynamicHelpers || {}, reqHelpers);
1591
+ }
1585
1592
  }
1586
1593
  }
1587
1594
 
@@ -1612,7 +1619,9 @@ function mountPages(app, options) {
1612
1619
  canonical: null,
1613
1620
  ...njkTpl.metaPatch,
1614
1621
  },
1615
- fsy: { ...baseHelpers, ...pluginHelpers },
1622
+ fsy: pluginDynamicHelpers
1623
+ ? { ...baseHelpers, ...pluginStaticHelpers, ...pluginDynamicHelpers }
1624
+ : { ...baseHelpers, ...pluginStaticHelpers },
1616
1625
  clientRuntime,
1617
1626
  };
1618
1627
 
@@ -9,6 +9,14 @@
9
9
  */
10
10
  const { globToRegExp } = require('../core/utils/regex');
11
11
 
12
+ let scriptInjectorGetter = null;
13
+ function getCachedScriptInjector() {
14
+ if (!scriptInjectorGetter) {
15
+ scriptInjectorGetter = require('./helpers').getScriptInjector;
16
+ }
17
+ return scriptInjectorGetter();
18
+ }
19
+
12
20
  const semverCache = new Map();
13
21
 
14
22
  const semver = {
@@ -131,15 +139,50 @@ class PluginManager {
131
139
  this.pluginAPIs = new Map(); // name -> exposed API
132
140
  this.registeredHelpers = new Map(); // name -> helper function
133
141
  this.registeredFilters = new Map(); // name -> filter function
142
+ this.requestHelpers = []; // Array<Function (req) => Record<string, any>>
134
143
  this.routes = []; // Collected route metadata
135
144
  this.customRoutes = []; // Routes added by plugins
136
145
  this.cspDirectives = new Map(); // directive -> Set of sources (from plugins)
137
146
  this.disposers = []; // Array<{ name: string, fn: Function }>
147
+ this._cachedHelpers = null; // Cached helpers object
148
+ this.pendingAsyncOperations = []; // Track background promises
138
149
  this.app = null;
139
150
  this.nunjucksEnv = null;
140
151
  this.shutdownManager = null;
141
152
  }
142
153
 
154
+ /**
155
+ * Bind API methods to instance and extract prototype properties (classes)
156
+ * @private
157
+ */
158
+ _extractAndBindAPI(api, pluginName) {
159
+ if (!api || typeof api !== 'object') return api;
160
+ const bound = {};
161
+ const proto = Object.getPrototypeOf(api);
162
+ const keys = new Set([
163
+ ...Object.keys(api),
164
+ ...Object.getOwnPropertyNames(api),
165
+ ...(proto && proto !== Object.prototype ? Object.getOwnPropertyNames(proto) : [])
166
+ ]);
167
+
168
+ for (const key of keys) {
169
+ if (key === 'constructor') continue;
170
+ const desc = Object.getOwnPropertyDescriptor(api, key) || (proto ? Object.getOwnPropertyDescriptor(proto, key) : null);
171
+ if (desc && (desc.get || desc.set)) {
172
+ Object.defineProperty(bound, key, {
173
+ get: desc.get ? desc.get.bind(api) : undefined,
174
+ set: desc.set ? desc.set.bind(api) : undefined,
175
+ enumerable: true,
176
+ configurable: true,
177
+ });
178
+ } else {
179
+ const val = api[key];
180
+ bound[key] = typeof val === 'function' ? val.bind(api) : val;
181
+ }
182
+ }
183
+ return bound;
184
+ }
185
+
143
186
  /**
144
187
  * Register a plugin disposer
145
188
  * @param {string} name
@@ -291,17 +334,13 @@ class PluginManager {
291
334
  // Create plugin context
292
335
  const ctx = this._createPluginContext(plugin, context);
293
336
 
337
+ // Store plugin
294
338
  // Store plugin
295
339
  this.plugins.set(plugin.name, plugin);
296
340
 
297
341
  // Store API if provided
298
342
  if (plugin.api) {
299
- // Bind API methods to plugin instance
300
- const boundAPI = {};
301
- for (const [key, value] of Object.entries(plugin.api)) {
302
- boundAPI[key] = typeof value === 'function' ? value.bind(plugin) : value;
303
- }
304
- this.pluginAPIs.set(plugin.name, boundAPI);
343
+ this.pluginAPIs.set(plugin.name, this._extractAndBindAPI(plugin.api, plugin.name));
305
344
  }
306
345
 
307
346
  // Collect CSP requirements from plugin
@@ -452,12 +491,7 @@ class PluginManager {
452
491
 
453
492
  // Store API if provided
454
493
  if (plugin.api) {
455
- // Bind API methods to plugin instance
456
- const boundAPI = {};
457
- for (const [key, value] of Object.entries(plugin.api)) {
458
- boundAPI[key] = typeof value === 'function' ? value.bind(plugin) : value;
459
- }
460
- this.pluginAPIs.set(plugin.name, boundAPI);
494
+ this.pluginAPIs.set(plugin.name, this._extractAndBindAPI(plugin.api, plugin.name));
461
495
  }
462
496
 
463
497
  // Collect CSP requirements from plugin
@@ -474,6 +508,11 @@ class PluginManager {
474
508
  if (typeof result === 'function') {
475
509
  this.registerDisposer(plugin.name, result);
476
510
  hasDisposer = true;
511
+ } else if (result && typeof result.then === 'function') {
512
+ this.pendingAsyncOperations.push(result);
513
+ result.catch(err => {
514
+ console.warn(`[plugin-manager] Plugin "${plugin.name}" async setup() failed:`, err?.message || err);
515
+ });
477
516
  }
478
517
  } catch (err) {
479
518
  console.warn(`[plugin-manager] Plugin "${plugin.name}" setup() failed:`, err.message);
@@ -482,13 +521,18 @@ class PluginManager {
482
521
  }
483
522
  }
484
523
 
485
- // Call register hook (sync - if plugin has async register, it won't wait)
524
+ // Call register hook (sync - if plugin has async register, it won't block, but promises are safely caught)
486
525
  if (typeof plugin.register === 'function') {
487
526
  try {
488
527
  const result = plugin.register(ctx);
489
528
  if (typeof result === 'function') {
490
529
  this.registerDisposer(plugin.name, result);
491
530
  hasDisposer = true;
531
+ } else if (result && typeof result.then === 'function') {
532
+ this.pendingAsyncOperations.push(result);
533
+ result.catch(err => {
534
+ console.warn(`[plugin-manager] Plugin "${plugin.name}" async register() failed:`, err?.message || err);
535
+ });
492
536
  }
493
537
  } catch (err) {
494
538
  console.warn(`[plugin-manager] Plugin "${plugin.name}" register() failed:`, err.message);
@@ -545,22 +589,22 @@ class PluginManager {
545
589
  */
546
590
  _createPluginContext(plugin, context) {
547
591
  const self = this;
548
- // Import script injector
549
- const { getScriptInjector } = require('./helpers');
592
+ const pluginName = plugin?.name || 'unknown';
550
593
 
551
594
  return {
552
- app: context.app,
595
+ app: context.app || self.app,
553
596
  core: context.core || null,
554
597
  http: context.http || null,
555
- shutdown: context.shutdown || context.shutdownManager || null,
556
- shutdownManager: context.shutdownManager || context.shutdown || null,
598
+ shutdown: context.shutdown || context.shutdownManager || self.shutdownManager || null,
599
+ shutdownManager: context.shutdownManager || context.shutdown || self.shutdownManager || null,
557
600
  services: context.services || context.serviceRegistry || null,
558
601
  serviceRegistry: context.serviceRegistry || context.services || null,
559
602
  events: context.events || null,
560
603
  cache: context.cache || null,
561
- options: plugin._options || {},
562
- nunjucksEnv: context.nunjucksEnv,
604
+ options: plugin?._options || {},
605
+ nunjucksEnv: context.nunjucksEnv || self.nunjucksEnv,
563
606
  db: context.options?.db ?? context.db ?? null,
607
+ pagesDir: context.pagesDir || null,
564
608
  /** @type {Record<string, unknown>} Named middleware registry (same reference as createApp → mountPages) */
565
609
  middlewares: context.middlewares ?? {},
566
610
 
@@ -568,28 +612,43 @@ class PluginManager {
568
612
  * Get another plugin's API
569
613
  */
570
614
  usePlugin(name) {
571
- return self.pluginAPIs.get(name) || null;
615
+ return self.getPluginAPI(name) || null;
572
616
  },
573
617
 
574
618
  /**
575
619
  * Add a template helper (available as fsy.helperName())
576
620
  */
577
621
  addHelper(name, fn) {
578
- self.registeredHelpers.set(name, fn);
622
+ self.addHelper(name, fn, pluginName);
579
623
  },
580
624
 
581
625
  /**
582
626
  * Add a Nunjucks filter
583
627
  */
584
628
  addFilter(name, fn) {
585
- self.registeredFilters.set(name, fn);
629
+ self.addFilter(name, fn, pluginName);
630
+ },
631
+
632
+ /**
633
+ * Add a request-scoped helper provider (called on each SSR request)
634
+ */
635
+ addRequestHelper(fn) {
636
+ self.addRequestHelper(fn);
586
637
  },
587
638
 
588
639
  /**
589
640
  * Add a custom route
590
641
  */
591
642
  addRoute(method, path, ...handlers) {
592
- self.customRoutes.push({ method: method.toLowerCase(), path, handlers });
643
+ const httpMethod = method.toLowerCase();
644
+ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
645
+ console.log(` ${method.toUpperCase().padEnd(6)} ${path}`);
646
+ }
647
+ if (self.app && typeof self.app[httpMethod] === 'function') {
648
+ self.app[httpMethod](path, ...handlers);
649
+ } else {
650
+ self.customRoutes.push({ method: httpMethod, path, handlers });
651
+ }
593
652
  },
594
653
 
595
654
  /**
@@ -611,6 +670,14 @@ class PluginManager {
611
670
  self.registerDisposer(plugin.name, fn);
612
671
  },
613
672
 
673
+ /**
674
+ * Alias for onDispose
675
+ * @param {Function} fn
676
+ */
677
+ addDisposer(fn) {
678
+ self.registerDisposer(plugin.name, fn);
679
+ },
680
+
614
681
  /**
615
682
  * Alias for onDispose
616
683
  * @param {Function} fn
@@ -625,7 +692,7 @@ class PluginManager {
625
692
  * @param {Object} options - { priority: number, id: string }
626
693
  */
627
694
  injectHead(content, options = {}) {
628
- getScriptInjector().addHead(content, options);
695
+ getCachedScriptInjector().addHead(content, options);
629
696
  },
630
697
 
631
698
  /**
@@ -634,7 +701,7 @@ class PluginManager {
634
701
  * @param {Object} options - { priority: number, id: string }
635
702
  */
636
703
  injectBody(content, options = {}) {
637
- getScriptInjector().addBody(content, options);
704
+ getCachedScriptInjector().addBody(content, options);
638
705
  },
639
706
 
640
707
  /**
@@ -643,7 +710,7 @@ class PluginManager {
643
710
  * @param {Object} options - { id: string }
644
711
  */
645
712
  injectStyle(css, options = {}) {
646
- getScriptInjector().addStyle(css, options);
713
+ getCachedScriptInjector().addStyle(css, options);
647
714
  },
648
715
 
649
716
  /**
@@ -651,14 +718,14 @@ class PluginManager {
651
718
  * @param {Object} link - { name, path, icon, description }
652
719
  */
653
720
  registerDevLink(link) {
654
- getScriptInjector().registerPlugin(link);
721
+ getCachedScriptInjector().registerPlugin(link);
655
722
  },
656
723
 
657
724
  /**
658
725
  * Get the script injector instance for advanced usage
659
726
  */
660
727
  getScriptInjector() {
661
- return getScriptInjector();
728
+ return getCachedScriptInjector();
662
729
  }
663
730
  };
664
731
  }
@@ -704,15 +771,82 @@ class PluginManager {
704
771
  return directives;
705
772
  }
706
773
 
774
+ /**
775
+ * Get all registered helpers (to be merged with fsy)
776
+ */
777
+ /**
778
+ * Register a template helper (available as fsy.helperName())
779
+ * @param {string} name
780
+ * @param {Function} fn
781
+ * @param {string} [pluginName]
782
+ */
783
+ addHelper(name, fn, pluginName = 'unknown') {
784
+ if (this.registeredHelpers.has(name)) {
785
+ console.warn(`[plugin-manager] Helper "${name}" is already registered (registered by "${pluginName}" overwrites existing helper).`);
786
+ }
787
+ this.registeredHelpers.set(name, fn);
788
+ this._cachedHelpers = null;
789
+ }
790
+
791
+ /**
792
+ * Register a Nunjucks filter
793
+ * @param {string} name
794
+ * @param {Function} fn
795
+ * @param {string} [pluginName]
796
+ */
797
+ addFilter(name, fn, pluginName = 'unknown') {
798
+ if (this.registeredFilters.has(name)) {
799
+ console.warn(`[plugin-manager] Filter "${name}" is already registered (registered by "${pluginName}" overwrites existing filter).`);
800
+ }
801
+ this.registeredFilters.set(name, fn);
802
+ if (this.nunjucksEnv && typeof this.nunjucksEnv.addFilter === 'function') {
803
+ this.nunjucksEnv.addFilter(name, fn);
804
+ }
805
+ }
806
+
807
+ /**
808
+ * Register a request-scoped helper provider (called on each SSR request)
809
+ * @param {Function} fn - (req) => Record<string, any>
810
+ */
811
+ addRequestHelper(fn) {
812
+ if (typeof fn === 'function') {
813
+ this.requestHelpers.push(fn);
814
+ }
815
+ }
816
+
817
+ /**
818
+ * Get all request-scoped helpers for a request
819
+ * @param {Object} req
820
+ * @returns {Object|null}
821
+ */
822
+ getRequestHelpers(req) {
823
+ if (!this.requestHelpers || this.requestHelpers.length === 0) return null;
824
+ const result = {};
825
+ for (const fn of this.requestHelpers) {
826
+ try {
827
+ const helpers = fn(req);
828
+ if (helpers && typeof helpers === 'object') {
829
+ Object.assign(result, helpers);
830
+ }
831
+ } catch (err) {
832
+ console.warn('[plugin-manager] Error executing request helper:', err.message);
833
+ }
834
+ }
835
+ return result;
836
+ }
837
+
707
838
  /**
708
839
  * Get all registered helpers (to be merged with fsy)
709
840
  */
710
841
  getHelpers() {
711
- const helpers = {};
712
- for (const [name, fn] of this.registeredHelpers) {
713
- helpers[name] = fn;
842
+ if (!this._cachedHelpers) {
843
+ const helpers = {};
844
+ for (const [name, fn] of this.registeredHelpers) {
845
+ helpers[name] = fn;
846
+ }
847
+ this._cachedHelpers = helpers;
714
848
  }
715
- return helpers;
849
+ return this._cachedHelpers;
716
850
  }
717
851
 
718
852
  /**
@@ -724,23 +858,68 @@ class PluginManager {
724
858
 
725
859
  /**
726
860
  * Mount custom routes added by plugins
861
+ * @param {Object} [app] - Optional target app (defaults to this.app)
727
862
  */
728
- mountCustomRoutes() {
729
- for (const { method, path, handlers } of this.customRoutes) {
730
- if (this.app && this.app[method]) {
731
- this.app[method](path, ...handlers);
863
+ mountCustomRoutes(app = null) {
864
+ const targetApp = app || this.app;
865
+ if (!targetApp || this.customRoutes.length === 0) return;
866
+ const unmounted = this.customRoutes.splice(0, this.customRoutes.length);
867
+ for (const { method, path, handlers } of unmounted) {
868
+ if (typeof targetApp[method] === 'function') {
869
+ targetApp[method](path, ...handlers);
732
870
  }
733
871
  }
734
872
  }
735
873
 
736
874
  /**
737
- * Call onRoutesReady hook on all plugins
875
+ * Call onRoutesReady hook on all plugins (async)
738
876
  */
739
877
  async onRoutesReady(context) {
878
+ if (context) {
879
+ if (context.app) this.app = context.app;
880
+ if (context.nunjucksEnv) this.nunjucksEnv = context.nunjucksEnv;
881
+ if (context.shutdownManager) this.shutdownManager = context.shutdownManager;
882
+ }
883
+
884
+ for (const [name, plugin] of this.plugins) {
885
+ if (typeof plugin.onRoutesReady === 'function') {
886
+ const ctx = this._createPluginContext(plugin, context);
887
+ try {
888
+ await plugin.onRoutesReady(ctx);
889
+ } catch (err) {
890
+ console.warn(`[plugin-manager] Plugin "${name}" onRoutesReady() failed:`, err.message);
891
+ }
892
+ }
893
+ }
894
+
895
+ // Mount any routes added during onRoutesReady
896
+ this.mountCustomRoutes();
897
+ }
898
+
899
+ /**
900
+ * Call onRoutesReady hook on all plugins synchronously (tracking async promises)
901
+ */
902
+ onRoutesReadySync(context) {
903
+ if (context) {
904
+ if (context.app) this.app = context.app;
905
+ if (context.nunjucksEnv) this.nunjucksEnv = context.nunjucksEnv;
906
+ if (context.shutdownManager) this.shutdownManager = context.shutdownManager;
907
+ }
908
+
740
909
  for (const [name, plugin] of this.plugins) {
741
910
  if (typeof plugin.onRoutesReady === 'function') {
742
911
  const ctx = this._createPluginContext(plugin, context);
743
- await plugin.onRoutesReady(ctx);
912
+ try {
913
+ const res = plugin.onRoutesReady(ctx);
914
+ if (res && typeof res.then === 'function') {
915
+ this.pendingAsyncOperations.push(res);
916
+ res.catch(err => {
917
+ console.warn(`[plugin-manager] Plugin "${name}" async onRoutesReady() failed:`, err?.message || err);
918
+ });
919
+ }
920
+ } catch (err) {
921
+ console.warn(`[plugin-manager] Plugin "${name}" onRoutesReady() failed:`, err.message);
922
+ }
744
923
  }
745
924
  }
746
925
 
@@ -755,11 +934,48 @@ class PluginManager {
755
934
  for (const [name, plugin] of this.plugins) {
756
935
  if (typeof plugin.onReady === 'function') {
757
936
  const ctx = this._createPluginContext(plugin, context);
758
- await plugin.onReady(ctx);
937
+ try {
938
+ await plugin.onReady(ctx);
939
+ } catch (err) {
940
+ console.warn(`[plugin-manager] Plugin "${name}" onReady() failed:`, err.message);
941
+ }
759
942
  }
760
943
  }
761
944
  }
762
945
 
946
+ /**
947
+ * Call onReady hook on all plugins synchronously (tracking async promises)
948
+ */
949
+ onReadySync(context) {
950
+ for (const [name, plugin] of this.plugins) {
951
+ if (typeof plugin.onReady === 'function') {
952
+ const ctx = this._createPluginContext(plugin, context);
953
+ try {
954
+ const res = plugin.onReady(ctx);
955
+ if (res && typeof res.then === 'function') {
956
+ this.pendingAsyncOperations.push(res);
957
+ res.catch(err => {
958
+ console.warn(`[plugin-manager] Plugin "${name}" async onReady() failed:`, err?.message || err);
959
+ });
960
+ }
961
+ } catch (err) {
962
+ console.warn(`[plugin-manager] Plugin "${name}" onReady() failed:`, err.message);
963
+ }
964
+ }
965
+ }
966
+ }
967
+
968
+ /**
969
+ * Wait for all pending asynchronous plugin operations to settle
970
+ * @returns {Promise<void>}
971
+ */
972
+ async whenReady() {
973
+ if (this.pendingAsyncOperations.length > 0) {
974
+ const ops = this.pendingAsyncOperations.slice();
975
+ await Promise.allSettled(ops);
976
+ }
977
+ }
978
+
763
979
  /**
764
980
  * Get a plugin by name
765
981
  */
@@ -775,11 +991,7 @@ class PluginManager {
775
991
  if (plugin && plugin.isLazy && typeof plugin.hydrate === 'function' && !plugin.isHydrated) {
776
992
  const real = plugin.hydrate();
777
993
  if (real && real.api) {
778
- const boundAPI = {};
779
- for (const [key, value] of Object.entries(real.api)) {
780
- boundAPI[key] = typeof value === 'function' ? value.bind(real) : value;
781
- }
782
- this.pluginAPIs.set(name, boundAPI);
994
+ this.pluginAPIs.set(name, this._extractAndBindAPI(real.api, name));
783
995
  }
784
996
  return this.pluginAPIs.get(name) || (real && real.api) || plugin.api;
785
997
  }
@@ -802,19 +1014,32 @@ class PluginManager {
802
1014
  }
803
1015
 
804
1016
  /**
805
- * Execute all registered plugin disposers in reverse registration order
1017
+ * Execute all registered plugin disposers in reverse registration order with timeout protection
1018
+ * @param {number} [timeoutMs=5000]
806
1019
  * @returns {Promise<void>}
807
1020
  */
808
- async dispose() {
1021
+ async dispose(timeoutMs = 5000) {
809
1022
  const reverseDisposers = this.disposers.slice().reverse();
810
1023
  for (const { name, fn } of reverseDisposers) {
811
1024
  try {
812
- await fn();
1025
+ let timer = null;
1026
+ const disposerPromise = Promise.resolve().then(() => fn());
1027
+ const timeoutPromise = new Promise((_, reject) => {
1028
+ timer = setTimeout(() => {
1029
+ reject(new Error(`Disposer for "${name}" timed out after ${timeoutMs}ms`));
1030
+ }, timeoutMs);
1031
+ });
1032
+
1033
+ await Promise.race([disposerPromise, timeoutPromise]).finally(() => {
1034
+ if (timer) clearTimeout(timer);
1035
+ });
813
1036
  } catch (err) {
814
1037
  console.warn(`[plugin-manager] Plugin "${name}" disposer failed:`, err.message);
815
1038
  }
816
1039
  }
817
1040
  this.disposers = [];
1041
+ this.requestHelpers = [];
1042
+ this._cachedHelpers = null;
818
1043
  }
819
1044
 
820
1045
  /**