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
@@ -104,37 +104,48 @@ function webhooksPlugin(options = {}) {
104
104
  dispatcher.knex = db.knex || db;
105
105
  }
106
106
 
107
+ // Sync timeouts from app context if not explicitly passed
108
+ const timeouts = ctx?.timeouts || (ctx?.app && typeof ctx.app.get === 'function' ? ctx.app.get('timeouts') : null);
109
+ if (timeouts && timeouts.webhook && dispatcher.timeoutMs === 10000 && options.timeoutMs === undefined && options.timeout === undefined) {
110
+ dispatcher.timeoutMs = timeouts.webhook;
111
+ }
112
+
107
113
  // Attach dispatcher to app and request objects
108
114
  if (ctx.app) {
109
115
  ctx.app.webhooks = dispatcher;
110
- ctx.app.use((req, res, next) => {
116
+ }
117
+ const target = ctx.http || ctx.app;
118
+ if (target && typeof target.use === 'function') {
119
+ target.use((req, res, next) => {
111
120
  req.webhooks = dispatcher;
112
121
  next();
113
122
  });
123
+ }
114
124
 
115
- // Register built-in services in app.serviceRegistry if available
116
- if (ctx.app.serviceRegistry && typeof ctx.app.serviceRegistry.register === 'function') {
117
- if (!ctx.app.serviceRegistry.has('webhook.dispatch')) {
118
- ctx.app.serviceRegistry.register('webhook.dispatch', {
119
- handler: async (input) => dispatcher.dispatch(input.event, input.payload, input),
120
- });
121
- }
122
- if (!ctx.app.serviceRegistry.has('webhook.ping')) {
123
- ctx.app.serviceRegistry.register('webhook.ping', {
124
- handler: async (input) => dispatcher.pingEndpoint(input.endpointId),
125
- });
126
- }
127
- if (!ctx.app.serviceRegistry.has('webhook.retry')) {
128
- ctx.app.serviceRegistry.register('webhook.retry', {
129
- handler: async (input) => dispatcher.retryDelivery(input.deliveryId),
130
- });
131
- }
125
+ // Register built-in services in app.serviceRegistry if available
126
+ const registry = ctx.serviceRegistry || ctx.services || ctx.app?.serviceRegistry;
127
+ if (registry && typeof registry.register === 'function') {
128
+ if (!registry.has('webhook.dispatch')) {
129
+ registry.register('webhook.dispatch', {
130
+ handler: async (input) => dispatcher.dispatch(input.event, input.payload, input),
131
+ });
132
+ }
133
+ if (!registry.has('webhook.ping')) {
134
+ registry.register('webhook.ping', {
135
+ handler: async (input) => dispatcher.pingEndpoint(input.endpointId),
136
+ });
132
137
  }
138
+ if (!registry.has('webhook.retry')) {
139
+ registry.register('webhook.retry', {
140
+ handler: async (input) => dispatcher.retryDelivery(input.deliveryId),
141
+ });
142
+ }
143
+ }
133
144
 
134
- // Integrate with core/queue if queue is present
135
- const queueManager = options.queue || ctx.app.queue;
136
- if (queueManager && typeof queueManager.define === 'function') {
137
- dispatcher.setQueue(queueManager);
145
+ // Integrate with core/queue if queue is present
146
+ const queueManager = options.queue || ctx.queue || ctx.app?.queue;
147
+ if (queueManager && typeof queueManager.define === 'function') {
148
+ dispatcher.setQueue(queueManager);
138
149
  if (!queueManager.handlers?.has?.('webhooks.deliver')) {
139
150
  queueManager.define('webhooks.deliver', async (job) => {
140
151
  const { endpointId, deliveryId, event, payload, attempt } = job.data;
@@ -161,7 +172,6 @@ function webhooksPlugin(options = {}) {
161
172
  });
162
173
  }
163
174
  }
164
- }
165
175
 
166
176
  return () => {
167
177
  dispatcher.dispose();
@@ -6,6 +6,9 @@
6
6
 
7
7
  'use strict';
8
8
 
9
+ const { globToRegExp } = require('../../core/utils/regex');
10
+ const { safeJsonParse } = require('../../core/utils/json');
11
+
9
12
  /**
10
13
  * Normalize an event filter into an array of strings
11
14
  *
@@ -29,13 +32,9 @@ function normalizeEvents(events) {
29
32
 
30
33
  // If JSON array string like '["user.*", "order.created"]'
31
34
  if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
32
- try {
33
- const parsed = JSON.parse(trimmed);
34
- if (Array.isArray(parsed)) {
35
- return parsed.map((e) => (typeof e === 'string' ? e.trim() : '')).filter(Boolean);
36
- }
37
- } catch (err) {
38
- // Fall back to comma-separated
35
+ const parsed = safeJsonParse(trimmed, null);
36
+ if (Array.isArray(parsed)) {
37
+ return parsed.map((e) => (typeof e === 'string' ? e.trim() : '')).filter(Boolean);
39
38
  }
40
39
  }
41
40
 
@@ -58,10 +57,7 @@ function getPatternRegex(pattern) {
58
57
  const first = regexCache.keys().next().value;
59
58
  if (first !== undefined) regexCache.delete(first);
60
59
  }
61
- const escaped = pattern
62
- .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // escape regex specials except *
63
- .replace(/\*/g, '.*');
64
- cached = new RegExp(`^${escaped}$`, 'i');
60
+ cached = globToRegExp(pattern, { separator: null, flags: 'i' });
65
61
  regexCache.set(pattern, cached);
66
62
  }
67
63
  return cached;
@@ -8,6 +8,8 @@
8
8
 
9
9
  const crypto = require('crypto');
10
10
  const { signPayload } = require('./crypto');
11
+ const { safeJsonParse } = require('../../core/utils/json');
12
+ const { parseDurationMs } = require('../../core/utils/time');
11
13
 
12
14
  /**
13
15
  * Send a webhook HTTP request to a target endpoint
@@ -41,11 +43,12 @@ async function sendWebhook(options = {}) {
41
43
  secret,
42
44
  deliveryId = crypto.randomUUID ? crypto.randomUUID() : `dlv_${Date.now()}_${crypto.randomBytes(6).toString('hex')}`,
43
45
  headers: customHeaders = {},
44
- timeoutMs = 10000,
45
46
  wrapPayload = true,
46
47
  maxResponseBodyLength = 2048,
47
48
  } = opts;
48
49
 
50
+ const timeoutMs = parseDurationMs(opts.timeout !== undefined ? opts.timeout : (opts.timeoutMs !== undefined ? opts.timeoutMs : 10000), 10000);
51
+
49
52
  if (!url || typeof url !== 'string') {
50
53
  return {
51
54
  success: false,
@@ -110,16 +113,10 @@ async function sendWebhook(options = {}) {
110
113
  }
111
114
 
112
115
  // Parse custom headers if stored as JSON string
113
- let parsedCustomHeaders = {};
114
- if (typeof customHeaders === 'string') {
115
- try {
116
- parsedCustomHeaders = JSON.parse(customHeaders);
117
- } catch (e) {
118
- parsedCustomHeaders = {};
119
- }
120
- } else if (typeof customHeaders === 'object' && customHeaders !== null) {
121
- parsedCustomHeaders = customHeaders;
122
- }
116
+ const parsedHeadersObj = safeJsonParse(customHeaders, {});
117
+ const parsedCustomHeaders = (parsedHeadersObj && typeof parsedHeadersObj === 'object' && !Array.isArray(parsedHeadersObj))
118
+ ? parsedHeadersObj
119
+ : {};
123
120
 
124
121
  const requestHeaders = {
125
122
  'content-type': 'application/json',
@@ -53,12 +53,13 @@ function xlsxPlugin(options = {}) {
53
53
  }
54
54
 
55
55
  // 2. Register built-in services (xlsx.generate, xlsx.parse, xlsx.exportModel)
56
- if (ctx.app && ctx.app.serviceRegistry) {
56
+ const registry = ctx.serviceRegistry || ctx.services || ctx.app?.serviceRegistry;
57
+ if (registry && typeof registry.register === 'function') {
57
58
  const db = dbOption ?? ctx.db ?? ctx.app?.get?.('db') ?? null;
58
59
  const services = createXlsxServices({ db, ...options });
59
60
  for (const [name, def] of Object.entries(services)) {
60
- if (!ctx.app.serviceRegistry.has(name)) {
61
- ctx.app.serviceRegistry.register(name, def);
61
+ if (!registry.has(name)) {
62
+ registry.register(name, def);
62
63
  }
63
64
  }
64
65
  }
@@ -74,8 +75,9 @@ function xlsxPlugin(options = {}) {
74
75
  ctx.middlewares.xlsx = middleware;
75
76
  }
76
77
 
77
- if (ctx.app && typeof ctx.app.use === 'function') {
78
- ctx.app.use(middleware);
78
+ const target = ctx.http || ctx.app;
79
+ if (target && typeof target.use === 'function') {
80
+ target.use(middleware);
79
81
  }
80
82
  },
81
83
  };
@@ -11,6 +11,7 @@ const { ZodError } = require('zod');
11
11
  const { z: zForApi } = require('../../core/validation');
12
12
  const { resolveMiddlewares } = require('../file-router');
13
13
  const { translateValidationIssues, getTranslatorForRequest } = require('./validation-i18n');
14
+ const { executeApiPipeline, enrichRouteError } = require('../../core/http');
14
15
 
15
16
  /**
16
17
  * Compiles a schema definition from an API module
@@ -136,110 +137,26 @@ function createApiHandler(descriptor, context) {
136
137
  }
137
138
  }
138
139
 
139
- // 2. Injections
140
- if (db) req.db = db;
141
- if (serviceRegistry) {
142
- req.service = (name, input, opts) =>
143
- serviceRegistry.call(name, input, { req, res, db }, opts);
144
- }
145
-
146
- // 3. Schema validation
147
- if (compiledSchema) {
148
- try {
149
- validateRequestInput(req, compiledSchema);
150
- } catch (err) {
151
- if (err instanceof ZodError || err.name === 'ZodError' || Array.isArray(err?.issues)) {
152
- const pagesDir = context.pagesDir || appOptions.pagesDir || 'pages';
153
- const routeDir = descriptor.file ? path.dirname(descriptor.file) : '';
154
- const translatedIssues = translateValidationIssues(err.issues, {
155
- req,
156
- pagesDir,
157
- routeDir,
158
- isDev,
159
- });
160
- return res.status(400).json({
161
- error: 'Validation Error',
162
- issues: translatedIssues,
163
- });
164
- }
165
- throw err;
166
- }
167
- } else {
168
- req.input = {
169
- body: req.body,
170
- params: req.params,
171
- query: req.query,
172
- };
173
- }
174
-
175
- // 4. Resolve and execute middlewares (module-local first, cached across requests)
140
+ // 2. Resolve middlewares (module-local first, cached across requests)
176
141
  if (!cachedMiddlewares) {
177
142
  const moduleMiddlewares = descriptor.moduleConfig?.middlewares || {};
178
143
  const combinedRegistry = Object.assign({}, middlewares, moduleMiddlewares);
179
144
  cachedMiddlewares = resolveMiddlewares(apiDef.middleware, combinedRegistry);
180
145
  }
181
146
 
182
- for (const mw of cachedMiddlewares) {
183
- if (typeof mw !== 'function') continue;
184
- await new Promise((resolve, reject) => {
185
- try {
186
- mw(req, res, (err) => {
187
- if (err) reject(err);
188
- else resolve();
189
- });
190
- } catch (syncErr) {
191
- reject(syncErr);
192
- }
193
- });
194
- if (res.headersSent) return;
195
- }
196
-
197
- // 5. Execute handler
198
- const pagesDir = context.pagesDir || appOptions.pagesDir || 'pages';
199
- const routeDir = descriptor.file ? path.dirname(descriptor.file) : '';
200
- const tr = getTranslatorForRequest(req, { pagesDir, routeDir, isDev });
201
-
202
- const apiCtx = {
147
+ // 3. Execute framework-agnostic API pipeline
148
+ await executeApiPipeline({
149
+ descriptor,
150
+ context,
151
+ apiDef,
152
+ handlerFn,
153
+ compiledSchema,
154
+ middlewares: cachedMiddlewares,
203
155
  req,
204
156
  res,
205
- params: req.params || {},
206
- query: req.query || {},
207
- body: req.body || {},
208
- input: req.input,
209
- locale: tr.locale,
210
- t: tr.t,
211
- service: (name, input, opts) =>
212
- serviceRegistry ? serviceRegistry.call(name, input, { req, res, db }, opts) : null,
213
- module: descriptor.module || null,
214
- config: appOptions,
215
- logger: console,
216
- db,
217
- sse: (sourceOrOptions, maybeOptions) => res.sse(sourceOrOptions, maybeOptions),
218
- };
219
-
220
- req.ctx = apiCtx;
221
- res.service = apiCtx.service;
222
- res.input = apiCtx.input;
223
- res.module = apiCtx.module;
224
-
225
- const result = await handlerFn(req, res, apiCtx);
226
-
227
- // 6. Auto-respond if handler returned a value and response not yet sent
228
- if (!res.headersSent) {
229
- if (result !== undefined) {
230
- return res.json(result);
231
- }
232
- }
157
+ });
233
158
  } catch (err) {
234
- if (err && typeof err === 'object') {
235
- if (!err.route) err.route = descriptor.path;
236
- if (!err.method) err.method = descriptor.method ? descriptor.method.toUpperCase() : (req.method || 'GET');
237
- if (!err.source) err.source = descriptor.source || descriptor.file;
238
- if (!err.file) err.file = descriptor.file;
239
- if (!err.module) err.module = descriptor.module || null;
240
- if (!err.phase) err.phase = 'handler';
241
- if (!err.requestId) err.requestId = req.id || (req.headers && req.headers['x-request-id']) || null;
242
- }
159
+ enrichRouteError(err, descriptor, req);
243
160
  return next(err);
244
161
  }
245
162
  };
@@ -11,6 +11,7 @@
11
11
  * @param {string} [config.description] - Endpoint description for OpenAPI
12
12
  * @param {Array<string>} [config.tags] - Endpoint tags for OpenAPI
13
13
  * @param {Array<string|Function>} [config.middleware] - Named or functional middlewares
14
+ * @param {string|{ key: string, statusCode?: number, message?: string }} [config.flag] - Feature flag required to access this endpoint
14
15
  * @param {Object|Function} [config.schema] - Request schemas (params, query, body, headers)
15
16
  * @param {Object} [config.response] - Expected response schemas by status code
16
17
  * @param {Function} config.handler - Request handler: async (req, ctx) => data
@@ -3,18 +3,22 @@
3
3
  * @module src/app-context
4
4
  */
5
5
 
6
- /** @type {{ db: object|null, shutdownManager: object|null, serviceRegistry: object|null, events: object|null, mailer: object|null }} */
6
+ const { circuitBreakerRegistry, retry } = require('../core/resilience');
7
+
8
+ /** @type {{ db: object|null, shutdownManager: object|null, serviceRegistry: object|null, events: object|null, mailer: object|null, cache: object|null, breakers: object|null }} */
7
9
  let context = {
8
10
  db: null,
9
11
  shutdownManager: null,
10
12
  serviceRegistry: null,
11
13
  events: null,
12
14
  mailer: null,
15
+ cache: null,
16
+ breakers: circuitBreakerRegistry,
13
17
  };
14
18
 
15
19
  /**
16
20
  * Merge into the current context (typically called once from createApp).
17
- * @param {{ db?: object|null, shutdownManager?: object|null, serviceRegistry?: object|null, events?: object|null, mailer?: object|null }} partial
21
+ * @param {{ db?: object|null, shutdownManager?: object|null, serviceRegistry?: object|null, events?: object|null, mailer?: object|null, cache?: object|null }} partial
18
22
  */
19
23
  function setAppContext(partial) {
20
24
  context = { ...context, ...partial };
@@ -99,7 +103,7 @@ function hasEvents() {
99
103
  * Clear context (e.g. between tests).
100
104
  */
101
105
  function resetAppContext() {
102
- context = { db: null, shutdownManager: null, serviceRegistry: null, events: null, mailer: null };
106
+ context = { db: null, shutdownManager: null, serviceRegistry: null, events: null, mailer: null, cache: null };
103
107
  }
104
108
 
105
109
  /**
@@ -117,7 +121,21 @@ function hasMailer() {
117
121
  }
118
122
 
119
123
  /**
120
- * Express middleware: sets `req.db`, `req.service`, `req.events`, and `req.mailer` from registered app context.
124
+ * @returns {object|null}
125
+ */
126
+ function getCache() {
127
+ return context.cache;
128
+ }
129
+
130
+ /**
131
+ * @returns {boolean}
132
+ */
133
+ function hasCache() {
134
+ return context.cache != null;
135
+ }
136
+
137
+ /**
138
+ * Express middleware: sets `req.db`, `req.service`, `req.events`, `req.mailer`, and `req.cache` from registered app context.
121
139
  * File-based `pages/api/*` routes attach this automatically; use in `setupRoutes`
122
140
  * for manually registered handlers that need `req.db` and `req.service`.
123
141
  * @type {import('express').RequestHandler}
@@ -132,9 +150,25 @@ function attachDbMiddleware(req, res, next) {
132
150
  if (context.mailer != null) {
133
151
  req.mailer = context.mailer;
134
152
  }
153
+ if (context.cache != null) {
154
+ req.cache = context.cache;
155
+ }
156
+ req.breakers = context.breakers || circuitBreakerRegistry;
157
+ req.breaker = (name, opts) => (context.breakers || circuitBreakerRegistry).getBreaker(name, opts);
158
+ req.retry = retry;
135
159
  if (context.serviceRegistry != null) {
136
160
  req.service = (name, input, opts) =>
137
- context.serviceRegistry.call(name, input, req.context || { req, res, db: context.db, events: context.events, mailer: context.mailer }, opts);
161
+ context.serviceRegistry.call(name, input, req.context || {
162
+ req,
163
+ res,
164
+ db: context.db,
165
+ events: context.events,
166
+ mailer: context.mailer,
167
+ cache: context.cache,
168
+ breakers: req.breakers,
169
+ breaker: req.breaker,
170
+ retry,
171
+ }, opts);
138
172
  }
139
173
  next();
140
174
  }
@@ -152,6 +186,8 @@ module.exports = {
152
186
  hasEvents,
153
187
  getMailer,
154
188
  hasMailer,
189
+ getCache,
190
+ hasCache,
155
191
  resetAppContext,
156
192
  attachDbMiddleware,
157
193
  };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Client runtime base path constant
5
+ */
6
+ const CLIENT_RUNTIME_BASE = '/__webspresso/client-runtime';
7
+
8
+ module.exports = {
9
+ CLIENT_RUNTIME_BASE,
10
+ };
@@ -4,9 +4,7 @@
4
4
  */
5
5
 
6
6
  const path = require('path');
7
- const express = require('express');
8
-
9
- const CLIENT_RUNTIME_BASE = '/__webspresso/client-runtime';
7
+ const { CLIENT_RUNTIME_BASE } = require('./constants');
10
8
 
11
9
  /** Resolve a file next to the package's resolved main entry (works with package "exports"). */
12
10
  function pkgFileFromMain(pkg, ...segments) {
@@ -21,6 +19,7 @@ function pkgFileFromMain(pkg, ...segments) {
21
19
  function mountClientRuntime(app, flags) {
22
20
  if (!flags || (!flags.alpine && !flags.swup)) return;
23
21
 
22
+ const express = require('express');
24
23
  const router = express.Router();
25
24
 
26
25
  function send(res, filePath) {
package/src/dev/banner.js CHANGED
@@ -94,7 +94,7 @@ function collectBannerSummary(context = {}) {
94
94
  db,
95
95
  serviceRegistry,
96
96
  pluginManager,
97
- port = 3000,
97
+ port = 7331,
98
98
  host = 'localhost',
99
99
  } = context;
100
100
 
@@ -141,9 +141,13 @@ function collectBannerSummary(context = {}) {
141
141
  // 5. Plugins
142
142
  let pluginsList = [];
143
143
  let hasAdmin = false;
144
- if (pluginManager && pluginManager.plugins instanceof Map) {
144
+ if (context.hasAdmin !== undefined) {
145
+ hasAdmin = Boolean(context.hasAdmin);
146
+ } else if (pluginManager && pluginManager.plugins instanceof Map) {
145
147
  pluginsList = Array.from(pluginManager.plugins.keys());
146
148
  hasAdmin = pluginManager.plugins.has('adminPanel') || pluginManager.plugins.has('admin');
149
+ } else {
150
+ hasAdmin = true;
147
151
  }
148
152
 
149
153
  // URLs