webspresso 0.0.104 → 0.0.106

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 (233) hide show
  1. package/.agents/AGENTS.md +21 -2
  2. package/.agents/ARCHITECTURE.md +23 -0
  3. package/.agents/CACHE.md +147 -0
  4. package/.agents/CLI.md +220 -8
  5. package/.agents/EARLY_HINTS.md +120 -0
  6. package/.agents/FLAGS.md +118 -0
  7. package/.agents/HEALTH.md +118 -0
  8. package/.agents/LIMITS.md +109 -0
  9. package/.agents/LOGGING.md +93 -0
  10. package/.agents/METRICS.md +127 -0
  11. package/.agents/MIGRATION_JOBS.md +95 -0
  12. package/.agents/ORM.md +155 -1
  13. package/.agents/PLUGINS.md +38 -3
  14. package/.agents/QUEUE.md +42 -0
  15. package/.agents/RATE_LIMIT.md +147 -0
  16. package/.agents/RESILIENCE.md +235 -0
  17. package/.agents/SCALE_OUT.md +109 -0
  18. package/.agents/SECRETS.md +117 -0
  19. package/AGENTS.md +16 -0
  20. package/README.md +2 -2
  21. package/bin/commands/add-aws.js +396 -0
  22. package/bin/commands/add-ci.js +523 -0
  23. package/bin/commands/add-cloudflare.js +240 -0
  24. package/bin/commands/add-cloudrun.js +381 -0
  25. package/bin/commands/add-docker.js +6 -6
  26. package/bin/commands/add-migration-job.js +396 -0
  27. package/bin/commands/assets-sync.js +209 -0
  28. package/bin/commands/client-generate.js +52 -0
  29. package/bin/commands/console.js +53 -0
  30. package/bin/commands/db-migrate.js +47 -2
  31. package/bin/commands/db-studio.js +84 -0
  32. package/bin/commands/deploy-check.js +242 -13
  33. package/bin/commands/dev.js +1 -1
  34. package/bin/commands/export.js +87 -0
  35. package/bin/commands/new.js +5 -5
  36. package/bin/commands/openapi.js +1 -1
  37. package/bin/commands/secrets-pull.js +208 -0
  38. package/bin/commands/start.js +1 -1
  39. package/bin/utils/db.js +7 -1
  40. package/bin/utils/project.js +2 -2
  41. package/bin/webspresso.js +22 -0
  42. package/core/app.js +421 -0
  43. package/core/auth/authenticate.js +93 -0
  44. package/core/auth/hash.js +5 -4
  45. package/core/auth/index.js +34 -4
  46. package/core/auth/jwt.js +5 -54
  47. package/core/auth/magic-link.js +4 -5
  48. package/core/auth/manager.js +53 -10
  49. package/core/auth/middleware.js +16 -68
  50. package/core/auth/oauth.js +8 -17
  51. package/core/auth/redis-session.js +1008 -0
  52. package/core/auth/sessions.js +156 -0
  53. package/core/auth/totp.js +2 -1
  54. package/core/cache/byte-size.js +123 -0
  55. package/core/cache/cdn.js +296 -0
  56. package/core/cache/index.js +33 -0
  57. package/core/cache/lru.js +477 -0
  58. package/core/cache/tagged-lru.js +354 -0
  59. package/core/commands/registry.js +6 -20
  60. package/core/console/commands.js +148 -0
  61. package/core/console/context.js +260 -0
  62. package/core/console/eval.js +70 -0
  63. package/core/console/index.js +22 -0
  64. package/core/console/repl.js +102 -0
  65. package/core/early-hints/index.js +267 -0
  66. package/core/errors/domain.js +49 -0
  67. package/core/errors/http.js +31 -0
  68. package/core/errors/index.js +10 -0
  69. package/core/errors/normalize.js +88 -2
  70. package/core/events/discovery.js +6 -24
  71. package/core/events/dispatcher.js +9 -7
  72. package/core/events/signal.js +7 -0
  73. package/core/export/discovery.js +191 -0
  74. package/core/export/exporter.js +277 -0
  75. package/core/export/index.js +24 -0
  76. package/core/flags/evaluator.js +252 -0
  77. package/core/flags/hasher.js +37 -0
  78. package/core/flags/index.js +21 -0
  79. package/core/flags/manager.js +263 -0
  80. package/core/flags/store.js +126 -0
  81. package/core/health/index.js +41 -0
  82. package/core/health/middleware.js +213 -0
  83. package/core/health/normalize.js +140 -0
  84. package/core/health/probes.js +203 -0
  85. package/core/http/adapter.js +74 -0
  86. package/core/http/express-adapter.js +46 -0
  87. package/core/http/hono-adapter.js +531 -0
  88. package/core/http/index.js +41 -0
  89. package/core/http/pipeline.js +485 -0
  90. package/core/index.js +336 -0
  91. package/core/limits/index.js +34 -0
  92. package/core/limits/middleware.js +325 -0
  93. package/core/limits/normalize.js +222 -0
  94. package/core/logger/formatters.js +264 -0
  95. package/core/logger/index.js +260 -0
  96. package/core/logger/trace.js +137 -0
  97. package/core/metrics/collectors.js +125 -0
  98. package/core/metrics/index.js +45 -0
  99. package/core/metrics/middleware.js +230 -0
  100. package/core/metrics/registry.js +366 -0
  101. package/core/orm/batch.js +70 -0
  102. package/core/orm/cache/fingerprint.js +2 -2
  103. package/core/orm/cache/memory-provider.js +27 -110
  104. package/core/orm/d1.js +265 -0
  105. package/core/orm/index.js +176 -13
  106. package/core/orm/json-fields.js +22 -8
  107. package/core/orm/migrate-cloud.js +194 -0
  108. package/core/orm/model.js +10 -0
  109. package/core/orm/pool.js +97 -0
  110. package/core/orm/query-builder.js +72 -9
  111. package/core/orm/repository.js +318 -19
  112. package/core/orm/schema-helpers.js +8 -10
  113. package/core/orm/scopes.js +321 -1
  114. package/core/orm/transaction.js +10 -2
  115. package/core/orm/utils.js +4 -86
  116. package/core/queue/adapters/cloudflare.js +131 -0
  117. package/core/queue/adapters/database.js +4 -8
  118. package/core/queue/adapters/pubsub.js +400 -0
  119. package/core/queue/adapters/sqs.js +419 -0
  120. package/core/queue/adapters/wait-until.js +77 -0
  121. package/core/queue/index.js +8 -0
  122. package/core/queue/manager.js +66 -41
  123. package/core/rate-limit/index.js +22 -0
  124. package/core/rate-limit/limiter.js +219 -0
  125. package/core/rate-limit/stores/memory.js +129 -0
  126. package/core/rate-limit/stores/redis.js +151 -0
  127. package/core/rate-limit/utils.js +112 -0
  128. package/core/resilience/circuit-breaker.js +422 -0
  129. package/core/resilience/errors.js +63 -0
  130. package/core/resilience/index.js +53 -0
  131. package/core/resilience/registry.js +97 -0
  132. package/core/resilience/retry.js +203 -0
  133. package/core/schema-cache.js +9 -2
  134. package/core/secrets/index.js +113 -0
  135. package/core/secrets/manager.js +308 -0
  136. package/core/secrets/providers/aws.js +288 -0
  137. package/core/secrets/providers/env.js +44 -0
  138. package/core/secrets/providers/gcp.js +307 -0
  139. package/core/secrets/providers/memory.js +76 -0
  140. package/core/shutdown/http-adapter.js +4 -1
  141. package/core/shutdown/shutdown-manager.js +129 -19
  142. package/core/stream/index.js +19 -0
  143. package/core/stream/text-stream.js +326 -0
  144. package/core/studio/index.js +43 -0
  145. package/core/studio/inspector.js +258 -0
  146. package/core/studio/server.js +325 -0
  147. package/core/studio/ui.js +681 -0
  148. package/core/utils/array.js +12 -0
  149. package/core/utils/base64url.js +8 -0
  150. package/core/utils/crypto.js +118 -0
  151. package/core/utils/ensure-leading-slash.js +6 -0
  152. package/core/utils/escape-regexp.js +7 -0
  153. package/core/utils/fetch.js +6 -5
  154. package/core/utils/fs.js +144 -0
  155. package/core/utils/hmac.js +6 -0
  156. package/core/utils/json.js +98 -0
  157. package/core/utils/object.js +106 -0
  158. package/core/utils/random.js +9 -0
  159. package/core/utils/regex.js +77 -0
  160. package/core/utils/sha256.js +6 -0
  161. package/core/utils/string.js +87 -0
  162. package/core/utils/strip-trailing-slash.js +6 -0
  163. package/core/utils/time.js +96 -0
  164. package/core/utils/timeout.js +348 -0
  165. package/core/utils/url.js +106 -0
  166. package/core/utils/walk.js +7 -0
  167. package/index.d.ts +1549 -2
  168. package/index.js +272 -2
  169. package/package.json +3 -2
  170. package/plugins/admin-panel/core/api-extensions.js +2 -5
  171. package/plugins/admin-panel/index.js +13 -6
  172. package/plugins/admin-panel/modules/menu.js +1 -1
  173. package/plugins/api-key/crypto.js +3 -3
  174. package/plugins/api-key/index.js +3 -2
  175. package/plugins/api-key/scopes.js +5 -7
  176. package/plugins/audit-log/api-handlers.js +6 -15
  177. package/plugins/audit-log/index.js +3 -1
  178. package/plugins/audit-log/parse.js +3 -3
  179. package/plugins/basic-auth/index.js +3 -2
  180. package/plugins/cors.js +3 -2
  181. package/plugins/csrf/index.js +9 -12
  182. package/plugins/csv/index.js +8 -5
  183. package/plugins/dashboard/app.js +2 -2
  184. package/plugins/dashboard/index.js +5 -5
  185. package/plugins/data-exchange/record-selection.js +2 -5
  186. package/plugins/email/api-handlers.js +5 -18
  187. package/plugins/email/auth-bridge.js +3 -2
  188. package/plugins/email/index.js +11 -9
  189. package/plugins/health-check.js +2 -1
  190. package/plugins/index.js +5 -0
  191. package/plugins/lazy.js +5 -6
  192. package/plugins/mcp/discovery.js +18 -17
  193. package/plugins/polar/src/api.js +2 -1
  194. package/plugins/polar/src/webhooks.js +5 -6
  195. package/plugins/queue/index.js +18 -2
  196. package/plugins/rate-limit/index.js +3 -1
  197. package/plugins/redirect/index.js +16 -9
  198. package/plugins/rls/index.js +170 -0
  199. package/plugins/seo-checker/index.js +2 -2
  200. package/plugins/site-analytics/index.js +3 -1
  201. package/plugins/site-analytics/tracking.js +2 -2
  202. package/plugins/sitemap.js +3 -2
  203. package/plugins/swagger.js +12 -5
  204. package/plugins/upload/gcs-provider.js +148 -0
  205. package/plugins/upload/index.js +136 -77
  206. package/plugins/upload/orphan-pruner.js +4 -3
  207. package/plugins/upload/s3-provider.js +257 -0
  208. package/plugins/webhooks/crypto.js +6 -11
  209. package/plugins/webhooks/dispatcher.js +8 -8
  210. package/plugins/webhooks/index.js +33 -23
  211. package/plugins/webhooks/matcher.js +7 -11
  212. package/plugins/webhooks/sender.js +8 -11
  213. package/plugins/xlsx/index.js +7 -5
  214. package/src/api/api-loader.js +12 -95
  215. package/src/api/define-api.js +1 -0
  216. package/src/app-context.js +41 -5
  217. package/src/client-runtime/constants.js +10 -0
  218. package/src/client-runtime/mount.js +2 -3
  219. package/src/dev/banner.js +6 -2
  220. package/src/dev/client-gen.js +458 -0
  221. package/src/discovery/scan-routes.js +5 -2
  222. package/src/file-router.js +3 -3
  223. package/src/helpers.js +212 -24
  224. package/src/modules/module-discovery.js +1 -9
  225. package/src/pages/page-loader.js +13 -154
  226. package/src/plugin-manager.js +99 -18
  227. package/src/server.js +335 -133
  228. package/src/services/discovery.js +19 -40
  229. package/src/services/executor.js +95 -25
  230. package/src/services/memoize.js +3 -25
  231. package/src/services/registry.js +15 -1
  232. package/src/services/validator.js +38 -20
  233. package/src/template/precompile.js +8 -19
package/src/helpers.js CHANGED
@@ -11,6 +11,7 @@ const relativeTime = require('dayjs/plugin/relativeTime');
11
11
  const utc = require('dayjs/plugin/utc');
12
12
  const timezone = require('dayjs/plugin/timezone');
13
13
  const customParseFormat = require('dayjs/plugin/customParseFormat');
14
+ const { globToRegExp } = require('../core/utils/regex');
14
15
 
15
16
  // Extend dayjs with plugins
16
17
  dayjs.extend(relativeTime);
@@ -659,7 +660,15 @@ function getAssetManager() {
659
660
  * @returns {Object} fsy helper object
660
661
  */
661
662
  function createHelpers(ctx) {
662
- const { req, res, baseUrl = process.env.BASE_URL || 'http://localhost:3000', locale = 'en', t = null } = ctx || {};
663
+ const { req, res, baseUrl = process.env.BASE_URL || 'http://localhost:7331', locale = 'en', t = null } = ctx || {};
664
+ const resolveAssetManager = () => ctx?.assetManager || ctx?.app?.assetManager || req?.app?.assetManager || getAssetManager();
665
+ const assetManager = new Proxy({}, {
666
+ get(_, prop) {
667
+ const mgr = resolveAssetManager();
668
+ const val = mgr[prop];
669
+ return typeof val === 'function' ? val.bind(mgr) : val;
670
+ }
671
+ });
663
672
 
664
673
  return {
665
674
  /** Active request locale */
@@ -729,6 +738,38 @@ function createHelpers(ctx) {
729
738
  return req?.__flash?.errors || {};
730
739
  },
731
740
 
741
+ /**
742
+ * Check if a feature flag is enabled for current request/context
743
+ * @param {string} flagKey
744
+ * @param {Object} [customContext]
745
+ * @returns {boolean}
746
+ */
747
+ hasFeature(flagKey, customContext) {
748
+ if (req && typeof req.hasFeature === 'function') {
749
+ return req.hasFeature(flagKey, customContext);
750
+ }
751
+ if (ctx && typeof ctx.hasFeature === 'function') {
752
+ return ctx.hasFeature(flagKey, customContext);
753
+ }
754
+ return false;
755
+ },
756
+
757
+ /**
758
+ * Get active variant for a multivariate feature flag
759
+ * @param {string} flagKey
760
+ * @param {Object} [customContext]
761
+ * @returns {string|null}
762
+ */
763
+ flag(flagKey, customContext) {
764
+ if (req && typeof req.getVariant === 'function') {
765
+ return req.getVariant(flagKey, customContext);
766
+ }
767
+ if (ctx && typeof ctx.getVariant === 'function') {
768
+ return ctx.getVariant(flagKey, customContext);
769
+ }
770
+ return this.hasFeature(flagKey, customContext) ? 'enabled' : false;
771
+ },
772
+
732
773
  /**
733
774
  * Get flash message by key (e.g. 'success', 'error', 'info')
734
775
  * @param {string} [key]
@@ -988,16 +1029,6 @@ function createHelpers(ctx) {
988
1029
  return `<script type="application/ld+json">${json}</script>`;
989
1030
  },
990
1031
 
991
- /**
992
- * Get the path to a static asset
993
- * @param {string} path - Asset path
994
- * @returns {string}
995
- */
996
- asset(path) {
997
- const assetPath = path.startsWith('/') ? path : `/${path}`;
998
- return assetPath;
999
- },
1000
-
1001
1032
  /**
1002
1033
  * Get the current locale
1003
1034
  * @returns {string}
@@ -1025,7 +1056,7 @@ function createHelpers(ctx) {
1025
1056
  if (pattern.includes('*')) {
1026
1057
  let regex = isPathRegexCache.get(pattern);
1027
1058
  if (regex === undefined) {
1028
- regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
1059
+ regex = globToRegExp(pattern, { separator: null });
1029
1060
  if (isPathRegexCache.size < 500) {
1030
1061
  isPathRegexCache.set(pattern, regex);
1031
1062
  }
@@ -1042,7 +1073,7 @@ function createHelpers(ctx) {
1042
1073
  * @returns {string}
1043
1074
  */
1044
1075
  asset(assetPath) {
1045
- return getAssetManager().asset(assetPath);
1076
+ return assetManager.asset(assetPath);
1046
1077
  },
1047
1078
 
1048
1079
  /**
@@ -1052,7 +1083,7 @@ function createHelpers(ctx) {
1052
1083
  * @returns {string}
1053
1084
  */
1054
1085
  css(href, attrs = {}) {
1055
- return getAssetManager().css(href, attrs);
1086
+ return assetManager.css(href, attrs);
1056
1087
  },
1057
1088
 
1058
1089
  /**
@@ -1062,7 +1093,7 @@ function createHelpers(ctx) {
1062
1093
  * @returns {string}
1063
1094
  */
1064
1095
  js(src, attrs = {}) {
1065
- return getAssetManager().js(src, attrs);
1096
+ return assetManager.js(src, attrs);
1066
1097
  },
1067
1098
 
1068
1099
  /**
@@ -1073,7 +1104,7 @@ function createHelpers(ctx) {
1073
1104
  * @returns {string}
1074
1105
  */
1075
1106
  img(src, alt = '', attrs = {}) {
1076
- return getAssetManager().img(src, alt, attrs);
1107
+ return assetManager.img(src, alt, attrs);
1077
1108
  },
1078
1109
 
1079
1110
  /**
@@ -1093,7 +1124,7 @@ function createHelpers(ctx) {
1093
1124
  * @returns {string}
1094
1125
  */
1095
1126
  pageJs(name, attrs = {}) {
1096
- return getAssetManager().pageJs(name, attrs);
1127
+ return assetManager.pageJs(name, attrs);
1097
1128
  },
1098
1129
 
1099
1130
  /**
@@ -1102,7 +1133,7 @@ function createHelpers(ctx) {
1102
1133
  * @returns {string}
1103
1134
  */
1104
1135
  pageJsUrl(name) {
1105
- return getAssetManager().pageJsUrl(name);
1136
+ return assetManager.pageJsUrl(name);
1106
1137
  },
1107
1138
 
1108
1139
  /**
@@ -1112,7 +1143,7 @@ function createHelpers(ctx) {
1112
1143
  * @returns {string}
1113
1144
  */
1114
1145
  pageCss(name, attrs = {}) {
1115
- return getAssetManager().pageCss(name, attrs);
1146
+ return assetManager.pageCss(name, attrs);
1116
1147
  },
1117
1148
 
1118
1149
  /**
@@ -1121,7 +1152,7 @@ function createHelpers(ctx) {
1121
1152
  * @returns {string}
1122
1153
  */
1123
1154
  pageCssUrl(name) {
1124
- return getAssetManager().pageCssUrl(name);
1155
+ return assetManager.pageCssUrl(name);
1125
1156
  },
1126
1157
 
1127
1158
  /**
@@ -1130,7 +1161,7 @@ function createHelpers(ctx) {
1130
1161
  * @returns {boolean}
1131
1162
  */
1132
1163
  hasPageJs(name) {
1133
- return getAssetManager().hasPageJs(name);
1164
+ return assetManager.hasPageJs(name);
1134
1165
  },
1135
1166
 
1136
1167
  /**
@@ -1139,7 +1170,7 @@ function createHelpers(ctx) {
1139
1170
  * @returns {boolean}
1140
1171
  */
1141
1172
  hasPageCss(name) {
1142
- return getAssetManager().hasPageCss(name);
1173
+ return assetManager.hasPageCss(name);
1143
1174
  },
1144
1175
 
1145
1176
  /**
@@ -1150,12 +1181,12 @@ function createHelpers(ctx) {
1150
1181
  */
1151
1182
  pageAssets(nameOrAttrs, attrs) {
1152
1183
  if (typeof nameOrAttrs === 'string' && nameOrAttrs.trim()) {
1153
- return getAssetManager().pageAssets(nameOrAttrs, attrs);
1184
+ return assetManager.pageAssets(nameOrAttrs, attrs);
1154
1185
  }
1155
1186
  const opts = (typeof nameOrAttrs === 'object' && nameOrAttrs !== null) ? nameOrAttrs : (attrs || {});
1156
1187
  const routeFile = req?.context?.file;
1157
1188
  const routePath = req?.context?.path || req?.path;
1158
- return getAssetManager().pageAssetsForRoute(routeFile, routePath, opts);
1189
+ return assetManager.pageAssetsForRoute(routeFile, routePath, opts);
1159
1190
  },
1160
1191
 
1161
1192
  /**
@@ -1408,6 +1439,13 @@ class ScriptInjector {
1408
1439
  * @param {Object} options - { priority: number, id: string }
1409
1440
  */
1410
1441
  addHead(content, options = {}) {
1442
+ if (options.id) {
1443
+ const idx = this.headScripts.findIndex(s => s.id === options.id);
1444
+ if (idx !== -1) {
1445
+ this.headScripts[idx] = { content, priority: options.priority || 0, id: options.id };
1446
+ return;
1447
+ }
1448
+ }
1411
1449
  this.headScripts.push({
1412
1450
  content,
1413
1451
  priority: options.priority || 0,
@@ -1421,6 +1459,13 @@ class ScriptInjector {
1421
1459
  * @param {Object} options - { priority: number, id: string }
1422
1460
  */
1423
1461
  addBody(content, options = {}) {
1462
+ if (options.id) {
1463
+ const idx = this.bodyScripts.findIndex(s => s.id === options.id);
1464
+ if (idx !== -1) {
1465
+ this.bodyScripts[idx] = { content, priority: options.priority || 0, id: options.id };
1466
+ return;
1467
+ }
1468
+ }
1424
1469
  this.bodyScripts.push({
1425
1470
  content,
1426
1471
  priority: options.priority || 0,
@@ -1434,6 +1479,13 @@ class ScriptInjector {
1434
1479
  * @param {Object} options - { id: string }
1435
1480
  */
1436
1481
  addStyle(css, options = {}) {
1482
+ if (options.id) {
1483
+ const idx = this.styles.findIndex(s => s.id === options.id);
1484
+ if (idx !== -1) {
1485
+ this.styles[idx] = { content: css, id: options.id };
1486
+ return;
1487
+ }
1488
+ }
1437
1489
  this.styles.push({
1438
1490
  content: css,
1439
1491
  id: options.id || null
@@ -2206,6 +2258,30 @@ const utils = {
2206
2258
  return require('../core/utils/crypto').safeCompare(a, b);
2207
2259
  },
2208
2260
 
2261
+ sha256(data, encoding) {
2262
+ return require('../core/utils/crypto').sha256(data, encoding);
2263
+ },
2264
+
2265
+ hmacSha256(data, secret, encoding) {
2266
+ return require('../core/utils/crypto').hmacSha256(data, secret, encoding);
2267
+ },
2268
+
2269
+ randomToken(byteLength, encoding) {
2270
+ return require('../core/utils/crypto').randomToken(byteLength, encoding);
2271
+ },
2272
+
2273
+ randomId(prefix, byteLength, encoding) {
2274
+ return require('../core/utils/crypto').randomId(prefix, byteLength, encoding);
2275
+ },
2276
+
2277
+ base64UrlEncode(input) {
2278
+ return require('../core/utils/crypto').base64UrlEncode(input);
2279
+ },
2280
+
2281
+ base64UrlDecode(input) {
2282
+ return require('../core/utils/crypto').base64UrlDecode(input);
2283
+ },
2284
+
2209
2285
  escapeHtml(value) {
2210
2286
  return require('../core/utils/html').escapeHtml(value);
2211
2287
  },
@@ -2214,8 +2290,120 @@ const utils = {
2214
2290
  return require('../core/utils/html').unescapeHtml(value);
2215
2291
  },
2216
2292
 
2293
+ walkDirectory(dir, options) {
2294
+ return require('../core/utils/fs').walkDirectory(dir, options);
2295
+ },
2296
+
2297
+ walkDirectoryDetailed(dir, options) {
2298
+ return require('../core/utils/fs').walkDirectoryDetailed(dir, options);
2299
+ },
2300
+
2217
2301
  getClientIp(req, fallback) {
2218
2302
  return require('../core/utils/ip').getClientIp(req, fallback);
2303
+ },
2304
+
2305
+ stripTrailingSlash(input, options) {
2306
+ return require('../core/utils/url').stripTrailingSlash(input, options);
2307
+ },
2308
+
2309
+ ensureLeadingSlash(input) {
2310
+ return require('../core/utils/url').ensureLeadingSlash(input);
2311
+ },
2312
+
2313
+ ensureTrailingSlash(input) {
2314
+ return require('../core/utils/url').ensureTrailingSlash(input);
2315
+ },
2316
+
2317
+ stripLeadingSlash(input) {
2318
+ return require('../core/utils/url').stripLeadingSlash(input);
2319
+ },
2320
+
2321
+ joinUrl(base, ...paths) {
2322
+ return require('../core/utils/url').joinUrl(base, ...paths);
2323
+ },
2324
+
2325
+ escapeRegExp(str) {
2326
+ return require('../core/utils/regex').escapeRegExp(str);
2327
+ },
2328
+
2329
+ escapeRegex(str) {
2330
+ return require('../core/utils/regex').escapeRegExp(str);
2331
+ },
2332
+
2333
+ globToRegExp(pattern, options) {
2334
+ return require('../core/utils/regex').globToRegExp(pattern, options);
2335
+ },
2336
+
2337
+ parseDurationSec(duration, defaultSec) {
2338
+ return require('../core/utils/time').parseDurationSec(duration, defaultSec);
2339
+ },
2340
+
2341
+ parseDuration(duration, defaultSec) {
2342
+ return require('../core/utils/time').parseDurationSec(duration, defaultSec);
2343
+ },
2344
+
2345
+ parseDurationMs(ttl, defaultMs) {
2346
+ return require('../core/utils/time').parseDurationMs(ttl, defaultMs);
2347
+ },
2348
+
2349
+ parseTtlMs(ttl, defaultMs) {
2350
+ return require('../core/utils/time').parseDurationMs(ttl, defaultMs);
2351
+ },
2352
+
2353
+ sleep(ms) {
2354
+ return require('../core/utils/time').sleep(ms);
2355
+ },
2356
+
2357
+ safeJsonParse(input, fallback, reviver) {
2358
+ return require('../core/utils/json').safeJsonParse(input, fallback, reviver);
2359
+ },
2360
+
2361
+ safeJsonStringify(value, space, fallback) {
2362
+ return require('../core/utils/json').safeJsonStringify(value, space, fallback);
2363
+ },
2364
+
2365
+ isValidJson(str) {
2366
+ return require('../core/utils/json').isValidJson(str);
2367
+ },
2368
+
2369
+ toCamelCase(str) {
2370
+ return require('../core/utils/string').toCamelCase(str);
2371
+ },
2372
+
2373
+ snakeToCamel(str) {
2374
+ return require('../core/utils/string').snakeToCamel(str);
2375
+ },
2376
+
2377
+ toSnakeCase(str) {
2378
+ return require('../core/utils/string').toSnakeCase(str);
2379
+ },
2380
+
2381
+ camelToSnake(str) {
2382
+ return require('../core/utils/string').camelToSnake(str);
2383
+ },
2384
+
2385
+ toKebabCase(str) {
2386
+ return require('../core/utils/string').toKebabCase(str);
2387
+ },
2388
+
2389
+ toPascalCase(str) {
2390
+ return require('../core/utils/string').toPascalCase(str);
2391
+ },
2392
+
2393
+ ensureArray(value) {
2394
+ return require('../core/utils/object').ensureArray(value);
2395
+ },
2396
+
2397
+ pick(obj, keys) {
2398
+ return require('../core/utils/object').pick(obj, keys);
2399
+ },
2400
+
2401
+ omit(obj, keys) {
2402
+ return require('../core/utils/object').omit(obj, keys);
2403
+ },
2404
+
2405
+ deepClone(obj) {
2406
+ return require('../core/utils/object').deepClone(obj);
2219
2407
  }
2220
2408
  };
2221
2409
 
@@ -9,15 +9,7 @@
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
11
  const { scanDirSafely, isPrivateOrIgnored } = require('../discovery/file-route-parser');
12
-
13
- /**
14
- * Converts a file path to camelCase or dot-separated identifier
15
- * @param {string} str
16
- * @returns {string}
17
- */
18
- function toCamelCase(str) {
19
- return str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
20
- }
12
+ const { toCamelCase } = require('../../core/utils/string');
21
13
 
22
14
  /**
23
15
  * Discovers services, middlewares, and configuration for a module directory
@@ -18,6 +18,8 @@ const {
18
18
  resolvePageAssets,
19
19
  applyPageAssetsToTemplateData,
20
20
  } = require('../file-router');
21
+ const { sendEarlyHints } = require('../../core/early-hints');
22
+ const { executePagePipeline, enrichRouteError } = require('../../core/http');
21
23
 
22
24
  const EMPTY_ARRAY = Object.freeze([]);
23
25
 
@@ -96,163 +98,20 @@ function createPageHandler(descriptor, context) {
96
98
  cachedMiddlewares = resolveMiddlewares(pageDef.middleware, combinedRegistry);
97
99
  }
98
100
 
99
- // Run middlewares in sequence
100
- for (const mw of cachedMiddlewares) {
101
- if (typeof mw !== 'function') continue;
102
- await new Promise((resolve, reject) => {
103
- try {
104
- mw(req, res, (err) => {
105
- if (err) reject(err);
106
- else resolve();
107
- });
108
- } catch (syncErr) {
109
- reject(syncErr);
110
- }
111
- });
112
- if (res.headersSent) return;
113
- }
114
-
115
- // 3. Build Page Context
116
- const baseUrl = process.env.BASE_URL || `http://localhost:${process.env.PORT || 3000}`;
117
- const locale = detectLocale(req);
118
- const fsy = createHelpers({ req, res, baseUrl, locale });
119
-
120
- // i18n
121
- const defaultLocale = process.env.DEFAULT_LOCALE || 'en';
122
- let t;
123
- if (!isDev && translatorCache) {
124
- const transKey = `${pagesDir}::::${locale}::${defaultLocale}`;
125
- t = translatorCache.get(transKey);
126
- if (!t) {
127
- const translations = loadI18n(pagesDir, '', locale, false);
128
- const fallbackTranslations = locale !== defaultLocale ? loadI18n(pagesDir, '', defaultLocale, false) : undefined;
129
- t = createTranslator(translations, {
130
- locale,
131
- fallbackTranslations,
132
- fallbackLocale: defaultLocale,
133
- });
134
- translatorCache.set(transKey, t);
135
- }
136
- } else {
137
- const translations = loadI18n(pagesDir, '', locale, isDev);
138
- const fallbackTranslations = locale !== defaultLocale ? loadI18n(pagesDir, '', defaultLocale, isDev) : undefined;
139
- t = createTranslator(translations, {
140
- locale,
141
- fallbackTranslations,
142
- fallbackLocale: defaultLocale,
143
- });
144
- }
145
-
146
- const pageCtx = {
101
+ // 3. Execute framework-agnostic Page pipeline
102
+ await executePagePipeline({
103
+ descriptor,
104
+ context,
105
+ pageDef,
106
+ middlewares: cachedMiddlewares,
147
107
  req,
148
108
  res,
149
- params: req.params || {},
150
- query: req.query || {},
151
- service: (name, input, opts) =>
152
- serviceRegistry ? serviceRegistry.call(name, input, { req, res, db }, opts) : null,
153
- module: descriptor.module || null,
154
- config: appOptions,
155
- logger: console,
156
- redirect: (url, status = 302) => {
157
- res.redirect(status, url);
158
- return { __redirected: true };
159
- },
160
- error: (status = 500, message = 'Page Error') => {
161
- const err = new Error(message);
162
- err.status = status;
163
- throw err;
164
- },
165
- fsy,
166
- locale,
167
- t,
168
- db,
169
- };
170
-
171
- // 4. Run load() lifecycle
172
- let loadedData = {};
173
- if (typeof pageDef.load === 'function') {
174
- loadedData = (await pageDef.load(pageCtx)) || {};
175
- if (loadedData.__redirected || res.headersSent) {
176
- return;
177
- }
178
- }
179
-
180
- // 5. Run head() lifecycle
181
- let headData = {};
182
- if (typeof pageDef.head === 'function') {
183
- headData = (await pageDef.head(loadedData, pageCtx)) || {};
184
- }
185
-
186
- // 6. Check for companion Nunjucks template (cached in production)
187
- const templateExists = hasNjkTemplate !== null ? hasNjkTemplate : fs.existsSync(njkCandidate);
188
-
189
- if (templateExists && nunjucks) {
190
- let pageHead = headData;
191
- let pageAssetsActive = false;
192
- const pageAssetsOpt = context.pageAssets || (appOptions && appOptions.pageAssets);
193
- if (pageAssetsOpt) {
194
- const pageAssetsResolved = resolvePageAssets(pageAssetsOpt);
195
- if (pageAssetsResolved.enabled) {
196
- const pageAssetBundle = applyPageAssetsToTemplateData(
197
- pageAssetsResolved,
198
- loadedData,
199
- {
200
- file: descriptor.source || descriptor.file,
201
- routePath: descriptor.path,
202
- },
203
- fsy?.assetManager || getAssetManager()
204
- );
205
- loadedData = pageAssetBundle.data;
206
- pageHead = {
207
- ...headData,
208
- stylesheets: [...(headData.stylesheets || []), ...(pageAssetBundle.pageHead?.stylesheets || [])],
209
- scripts: [...(headData.scripts || []), ...(pageAssetBundle.pageHead?.scripts || [])],
210
- };
211
- pageAssetsActive = true;
212
- }
213
- }
214
-
215
- const templateData = {
216
- ...loadedData,
217
- head: pageHead,
218
- pageHead,
219
- pageAssets: pageAssetsActive || Boolean(loadedData.pageAssets),
220
- fsy,
221
- locale,
222
- t,
223
- params: req.params,
224
- query: req.query,
225
- };
226
- return nunjucks.render(njkCandidate, templateData, (err, html) => {
227
- if (err) return next(err);
228
- res.setHeader('Content-Type', 'text/html; charset=utf-8');
229
- return res.send(html);
230
- });
231
- }
232
-
233
- // 7. Render via definePage render() method
234
- if (typeof pageDef.render === 'function') {
235
- const html = await pageDef.render(loadedData, pageCtx);
236
- res.setHeader('Content-Type', 'text/html; charset=utf-8');
237
- return res.send(html);
238
- }
239
-
240
- // 8. Fallback: if json or data
241
- if (typeof loadedData === 'object' && loadedData !== null) {
242
- return res.json(loadedData);
243
- }
244
-
245
- return res.send(String(loadedData));
109
+ nunjucks,
110
+ njkCandidate,
111
+ hasNjkTemplate,
112
+ });
246
113
  } catch (err) {
247
- if (err && typeof err === 'object') {
248
- if (!err.route) err.route = descriptor.path;
249
- if (!err.method) err.method = descriptor.method ? descriptor.method.toUpperCase() : (req.method || 'GET');
250
- if (!err.source) err.source = descriptor.source || descriptor.file;
251
- if (!err.file) err.file = descriptor.file;
252
- if (!err.module) err.module = descriptor.module || null;
253
- if (!err.phase) err.phase = 'page';
254
- if (!err.requestId) err.requestId = req.id || (req.headers && req.headers['x-request-id']) || null;
255
- }
114
+ enrichRouteError(err, descriptor, req);
256
115
  return next(err);
257
116
  }
258
117
  };