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
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Express HTTP Adapter
5
+ * Default adapter implementation bridging Webspresso onto Express
6
+ * @module core/http/express-adapter
7
+ */
8
+
9
+ const { HttpAdapter } = require('./adapter');
10
+
11
+ class ExpressHttpAdapter extends HttpAdapter {
12
+ constructor(app, options = {}) {
13
+ super(app, options);
14
+ }
15
+
16
+ use(...args) {
17
+ if (!this.app || typeof this.app.use !== 'function') {
18
+ throw new Error('ExpressHttpAdapter: underlying Express app does not support .use()');
19
+ }
20
+ return this.app.use(...args);
21
+ }
22
+
23
+ route(method, path, ...handlers) {
24
+ const m = (method || '').toLowerCase();
25
+ if (!this.app || typeof this.app[m] !== 'function') {
26
+ throw new Error(`ExpressHttpAdapter: unsupported HTTP method "${method}" on Express app`);
27
+ }
28
+ return this.app[m](path, ...handlers);
29
+ }
30
+
31
+ listen(port, callback) {
32
+ if (!this.app || typeof this.app.listen !== 'function') {
33
+ throw new Error('ExpressHttpAdapter: underlying Express app does not support .listen()');
34
+ }
35
+ return this.app.listen(port, callback);
36
+ }
37
+ }
38
+
39
+ function createExpressHttpAdapter(app, options = {}) {
40
+ return new ExpressHttpAdapter(app, options);
41
+ }
42
+
43
+ module.exports = {
44
+ ExpressHttpAdapter,
45
+ createExpressHttpAdapter,
46
+ };
@@ -0,0 +1,531 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Hono HTTP Adapter
5
+ * Adapter bridging Webspresso pipelines and routes onto Hono
6
+ * @module core/http/hono-adapter
7
+ */
8
+
9
+ const { HttpAdapter } = require('./adapter');
10
+ const { executeApiPipeline, executePagePipeline } = require('./pipeline');
11
+
12
+ /**
13
+ * Parses cookies from cookie header
14
+ * @param {string} cookieHeader
15
+ * @returns {Record<string, string>}
16
+ */
17
+ function parseCookies(cookieHeader) {
18
+ const cookies = {};
19
+ if (!cookieHeader || typeof cookieHeader !== 'string') return cookies;
20
+ const parts = cookieHeader.split(';');
21
+ for (const part of parts) {
22
+ const idx = part.indexOf('=');
23
+ if (idx > 0) {
24
+ const key = part.slice(0, idx).trim();
25
+ const val = part.slice(idx + 1).trim();
26
+ try {
27
+ cookies[key] = decodeURIComponent(val);
28
+ } catch (_) {
29
+ cookies[key] = val;
30
+ }
31
+ }
32
+ }
33
+ return cookies;
34
+ }
35
+
36
+ /**
37
+ * Creates an Express-compatible Request abstraction from a Hono Context
38
+ * @param {import('hono').Context} c
39
+ * @returns {Object}
40
+ */
41
+ function createHonoCompatReq(c) {
42
+ if (c && c._webspressoReq) {
43
+ return c._webspressoReq;
44
+ }
45
+ const rawHeaders = c.req.raw ? Object.fromEntries(c.req.raw.headers.entries()) : (c.req.header() || {});
46
+ const cookieHeader = c.req.header('cookie') || '';
47
+ const cookies = parseCookies(cookieHeader);
48
+
49
+ let pathname = '/';
50
+ try {
51
+ const url = new URL(c.req.url);
52
+ pathname = url.pathname;
53
+ } catch (_) {
54
+ pathname = c.req.path || '/';
55
+ }
56
+
57
+ const req = {
58
+ method: c.req.method,
59
+ url: c.req.url,
60
+ path: pathname,
61
+ headers: rawHeaders,
62
+ get params() {
63
+ return this._params || c.req.param() || {};
64
+ },
65
+ set params(val) {
66
+ this._params = val;
67
+ },
68
+ get query() {
69
+ return this._query || c.req.query() || {};
70
+ },
71
+ set query(val) {
72
+ this._query = val;
73
+ },
74
+ body: {},
75
+ cookies,
76
+ headersSent: false,
77
+ user: null,
78
+ session: null,
79
+ auth: null,
80
+ db: null,
81
+ service: null,
82
+ ip: c.req.header('x-forwarded-for')?.split(',')[0]?.trim() || c.req.header('x-real-ip') || '127.0.0.1',
83
+ protocol: 'http',
84
+ get(name) {
85
+ return c.req.header(name) ?? null;
86
+ },
87
+ header(name) {
88
+ return c.req.header(name) ?? null;
89
+ },
90
+ };
91
+
92
+ if (c) {
93
+ c._webspressoReq = req;
94
+ }
95
+ return req;
96
+ }
97
+
98
+ /**
99
+ * Creates an Express-compatible Response abstraction that renders to a Web Response
100
+ * @param {import('hono').Context} c
101
+ * @returns {Object}
102
+ */
103
+ function createHonoCompatRes(c) {
104
+ if (c && c._webspressoRes) {
105
+ return c._webspressoRes;
106
+ }
107
+ let statusCode = 200;
108
+ const headers = new Headers();
109
+ let bodyContent = null;
110
+ let headersSent = false;
111
+
112
+ const res = {
113
+ get statusCode() {
114
+ return statusCode;
115
+ },
116
+ set statusCode(code) {
117
+ statusCode = code;
118
+ },
119
+ get headersSent() {
120
+ return headersSent;
121
+ },
122
+ status(code) {
123
+ statusCode = code;
124
+ return res;
125
+ },
126
+ type(mime) {
127
+ if (!mime) return res;
128
+ let contentType = mime;
129
+ if (mime === 'html') contentType = 'text/html; charset=utf-8';
130
+ else if (mime === 'json') contentType = 'application/json; charset=utf-8';
131
+ else if (mime === 'text' || mime === 'txt') contentType = 'text/plain; charset=utf-8';
132
+ else if (mime === 'css') contentType = 'text/css; charset=utf-8';
133
+ else if (mime === 'js' || mime === 'javascript') contentType = 'application/javascript; charset=utf-8';
134
+ else if (!mime.includes('/')) contentType = `text/${mime}`;
135
+ headers.set('content-type', contentType);
136
+ return res;
137
+ },
138
+ setHeader(name, value) {
139
+ headers.set(name.toLowerCase(), String(value));
140
+ return res;
141
+ },
142
+ getHeader(name) {
143
+ return headers.get(name.toLowerCase());
144
+ },
145
+ cookie(name, value, opts = {}) {
146
+ let cookieStr = `${name}=${encodeURIComponent(value)}`;
147
+ if (opts.maxAge) cookieStr += `; Max-Age=${opts.maxAge}`;
148
+ if (opts.httpOnly) cookieStr += '; HttpOnly';
149
+ if (opts.secure) cookieStr += '; Secure';
150
+ if (opts.path) cookieStr += `; Path=${opts.path}`;
151
+ else cookieStr += '; Path=/';
152
+ if (opts.sameSite) cookieStr += `; SameSite=${opts.sameSite}`;
153
+ headers.append('set-cookie', cookieStr);
154
+ return res;
155
+ },
156
+ redirect(urlOrStatus, maybeUrl) {
157
+ headersSent = true;
158
+ let url;
159
+ let status = 302;
160
+ if (typeof urlOrStatus === 'number') {
161
+ status = urlOrStatus;
162
+ url = maybeUrl;
163
+ } else {
164
+ url = urlOrStatus;
165
+ if (typeof maybeUrl === 'number') status = maybeUrl;
166
+ }
167
+ statusCode = status;
168
+ headers.set('location', url);
169
+ return res.end();
170
+ },
171
+ writeHead(code, reasonOrHeaders, maybeHeaders) {
172
+ statusCode = code;
173
+ const h = typeof reasonOrHeaders === 'object' ? reasonOrHeaders : maybeHeaders;
174
+ if (h) {
175
+ for (const [k, v] of Object.entries(h)) {
176
+ headers.set(k.toLowerCase(), String(v));
177
+ }
178
+ }
179
+ return res;
180
+ },
181
+ end(data) {
182
+ headersSent = true;
183
+ if (data !== undefined) {
184
+ bodyContent = data;
185
+ }
186
+ if (typeof res._onEnd === 'function') {
187
+ res._onEnd();
188
+ }
189
+ return res;
190
+ },
191
+ json(data) {
192
+ if (!headers.has('content-type')) {
193
+ headers.set('content-type', 'application/json; charset=utf-8');
194
+ }
195
+ return res.end(JSON.stringify(data));
196
+ },
197
+ send(data) {
198
+ if (typeof data === 'object' && data !== null && !Buffer.isBuffer(data)) {
199
+ return res.json(data);
200
+ }
201
+ return res.end(data);
202
+ },
203
+ streamText(sourceOrCallback, maybeOptions = {}) {
204
+ headersSent = true;
205
+ const contentType = maybeOptions.contentType || 'text/plain; charset=utf-8';
206
+ headers.set('content-type', contentType);
207
+ headers.set('cache-control', 'no-cache, no-transform');
208
+ headers.set('x-content-type-options', 'nosniff');
209
+
210
+ const { readable, writable } = new TransformStream();
211
+ const writer = writable.getWriter();
212
+ const encoder = new TextEncoder();
213
+
214
+ const controller = {
215
+ async write(chunk) {
216
+ const text = typeof chunk === 'object' && !Buffer.isBuffer(chunk) ? JSON.stringify(chunk) : String(chunk);
217
+ await writer.write(encoder.encode(text));
218
+ },
219
+ async close() {
220
+ await writer.close();
221
+ },
222
+ };
223
+
224
+ (async () => {
225
+ try {
226
+ if (typeof sourceOrCallback === 'function') {
227
+ const ret = sourceOrCallback(controller);
228
+ if (ret && typeof ret[Symbol.asyncIterator] === 'function') {
229
+ for await (const chunk of ret) {
230
+ await controller.write(chunk);
231
+ }
232
+ } else if (ret && typeof ret.then === 'function') {
233
+ await ret;
234
+ }
235
+ } else if (sourceOrCallback && typeof sourceOrCallback[Symbol.asyncIterator] === 'function') {
236
+ for await (const chunk of sourceOrCallback) {
237
+ await controller.write(chunk);
238
+ }
239
+ }
240
+ } finally {
241
+ try { await writer.close(); } catch (_) {}
242
+ }
243
+ })();
244
+
245
+ res._streamBody = readable;
246
+ return res;
247
+ },
248
+ streamJson(sourceOrCallback, maybeOptions = {}) {
249
+ return res.streamText(sourceOrCallback, {
250
+ ...maybeOptions,
251
+ contentType: maybeOptions.contentType || 'application/x-ndjson; charset=utf-8',
252
+ map: (item) => (typeof item === 'string' && item.endsWith('\n') ? item : `${JSON.stringify(item)}\n`),
253
+ });
254
+ },
255
+ toResponse() {
256
+ if (res._streamBody) {
257
+ return new Response(res._streamBody, {
258
+ status: statusCode,
259
+ headers,
260
+ });
261
+ }
262
+ return new Response(bodyContent, {
263
+ status: statusCode,
264
+ headers,
265
+ });
266
+ },
267
+ };
268
+
269
+ if (c) {
270
+ c._webspressoRes = res;
271
+ }
272
+ return res;
273
+ }
274
+
275
+ class HonoHttpAdapter extends HttpAdapter {
276
+ constructor(app = null, options = {}) {
277
+ let honoInstance = app;
278
+ if (!honoInstance) {
279
+ const { Hono } = require('hono');
280
+ honoInstance = new Hono();
281
+ }
282
+ super(honoInstance, options);
283
+ }
284
+
285
+ use(...args) {
286
+ if (!this.app || typeof this.app.use !== 'function') {
287
+ throw new Error('HonoHttpAdapter: underlying Hono app does not support .use()');
288
+ }
289
+
290
+ let path = '*';
291
+ let handlers = args;
292
+ if (typeof args[0] === 'string') {
293
+ path = args[0];
294
+ handlers = args.slice(1);
295
+ }
296
+
297
+ for (const h of handlers) {
298
+ if (typeof h !== 'function') continue;
299
+
300
+ if (h.length >= 3) {
301
+ // Express-style middleware (req, res, next)
302
+ this.app.use(path, async (c, next) => {
303
+ const req = createHonoCompatReq(c);
304
+ const res = createHonoCompatRes(c);
305
+ let calledNext = false;
306
+ await new Promise((resolve, reject) => {
307
+ let settled = false;
308
+ const done = (err) => {
309
+ if (settled) return;
310
+ settled = true;
311
+ if (err) reject(err);
312
+ else resolve();
313
+ };
314
+ res._onEnd = () => done();
315
+
316
+ try {
317
+ h(req, res, (err) => {
318
+ if (!err) calledNext = true;
319
+ done(err);
320
+ });
321
+ } catch (err) {
322
+ done(err);
323
+ }
324
+ });
325
+
326
+ if (res.headersSent) {
327
+ return res.toResponse();
328
+ }
329
+ if (calledNext) {
330
+ await next();
331
+ }
332
+ });
333
+ } else {
334
+ // Hono middleware (c, next)
335
+ this.app.use(path, h);
336
+ }
337
+ }
338
+ return this;
339
+ }
340
+
341
+ route(method, path, ...handlers) {
342
+ const m = (method || '').toLowerCase();
343
+ // Normalize Express bracket parameters: e.g. /api/notes/[id] -> /api/notes/:id
344
+ const honoPath = path.replace(/\[([^\]]+)\]/g, ':$1');
345
+
346
+ for (const handler of handlers) {
347
+ if (typeof handler !== 'function') continue;
348
+
349
+ const honoHandler = async (c) => {
350
+ const req = createHonoCompatReq(c);
351
+ const res = createHonoCompatRes(c);
352
+
353
+ // Parse body if present
354
+ const contentType = c.req.header('content-type') || '';
355
+ if (contentType.includes('application/json')) {
356
+ try {
357
+ req.body = await c.req.json();
358
+ } catch (_) {
359
+ req.body = {};
360
+ }
361
+ } else if (contentType.includes('application/x-www-form-urlencoded')) {
362
+ try {
363
+ req.body = await c.req.parseBody();
364
+ } catch (_) {
365
+ req.body = {};
366
+ }
367
+ }
368
+
369
+ try {
370
+ const result = await handler(req, res);
371
+ if (res.headersSent) {
372
+ return res.toResponse();
373
+ }
374
+ if (result !== undefined) {
375
+ if (typeof result === 'object' && result !== null) {
376
+ return c.json(result);
377
+ }
378
+ return c.text(String(result));
379
+ }
380
+ return res.toResponse();
381
+ } catch (err) {
382
+ if (res.headersSent) {
383
+ return res.toResponse();
384
+ }
385
+ const status = err.status || err.statusCode || 500;
386
+ return c.json({
387
+ error: err.name || 'Error',
388
+ message: err.message,
389
+ status,
390
+ ...(err.issues || err.details ? { issues: err.issues || err.details } : {}),
391
+ }, status);
392
+ }
393
+ };
394
+
395
+ if (m === 'all') {
396
+ this.app.all(honoPath, honoHandler);
397
+ } else if (typeof this.app[m] === 'function') {
398
+ this.app[m](honoPath, honoHandler);
399
+ } else {
400
+ this.app.on(m.toUpperCase(), honoPath, honoHandler);
401
+ }
402
+ }
403
+ return this;
404
+ }
405
+
406
+ /**
407
+ * Register a defineApi endpoint on Hono using Webspresso's executeApiPipeline
408
+ * @param {string} method - HTTP method
409
+ * @param {string} path - URL path
410
+ * @param {Object} apiDef - API definition from defineApi
411
+ * @param {Object} [context={}] - App / Core context
412
+ */
413
+ registerApi(method, path, apiDef, context = {}) {
414
+ const handler = typeof apiDef === 'function' ? apiDef : (apiDef.handler || apiDef);
415
+ const compiledSchema = apiDef.schema ? apiDef.schema : null;
416
+ const descriptor = { path, method: method.toUpperCase(), file: 'virtual' };
417
+
418
+ return this.route(method, path, async (req, res) => {
419
+ return executeApiPipeline({
420
+ descriptor,
421
+ context,
422
+ apiDef,
423
+ handlerFn: handler,
424
+ compiledSchema,
425
+ middlewares: apiDef.middleware || [],
426
+ req,
427
+ res,
428
+ });
429
+ });
430
+ }
431
+
432
+ /**
433
+ * Register a definePage SSR route on Hono using Webspresso's executePagePipeline
434
+ * @param {string} path - URL path
435
+ * @param {Object} pageDef - Page definition from definePage
436
+ * @param {Object} [context={}] - App / Core context
437
+ */
438
+ registerPage(path, pageDef, context = {}) {
439
+ const descriptor = { path, method: 'GET', file: 'virtual' };
440
+ return this.route('get', path, async (req, res) => {
441
+ return executePagePipeline({
442
+ descriptor,
443
+ context,
444
+ pageDef,
445
+ middlewares: pageDef.middleware || [],
446
+ req,
447
+ res,
448
+ nunjucks: context.nunjucks,
449
+ });
450
+ });
451
+ }
452
+
453
+ /**
454
+ * Direct fetch request execution via Hono's app.request()
455
+ * @param {string|Request} input
456
+ * @param {RequestInit} [init]
457
+ * @returns {Promise<Response>}
458
+ */
459
+ async request(input, init) {
460
+ return Promise.resolve(this.app.request(input, init));
461
+ }
462
+
463
+ /**
464
+ * Standard Web / Cloudflare Workers Fetch Handler
465
+ * Enables: export default honoAdapter; or export default { fetch: (req, env, ctx) => honoAdapter.fetch(req, env, ctx) }
466
+ * @param {Request} request
467
+ * @param {any} [env]
468
+ * @param {any} [ctx]
469
+ * @returns {Response|Promise<Response>}
470
+ */
471
+ fetch(request, env, ctx) {
472
+ return this.app.fetch(request, env, ctx);
473
+ }
474
+
475
+ /**
476
+ * Listen on port using native Node http.createServer with Web Fetch bridge
477
+ * @param {number|string} port
478
+ * @param {Function} [callback]
479
+ */
480
+ listen(port, callback) {
481
+ const http = require('http');
482
+ const server = http.createServer(async (nodeReq, nodeRes) => {
483
+ try {
484
+ const protocol = nodeReq.socket.encrypted ? 'https' : 'http';
485
+ const host = nodeReq.headers.host || `localhost:${port}`;
486
+ const url = `${protocol}://${host}${nodeReq.url}`;
487
+
488
+ const chunks = [];
489
+ for await (const chunk of nodeReq) {
490
+ chunks.push(chunk);
491
+ }
492
+ const body = chunks.length > 0 && nodeReq.method !== 'GET' && nodeReq.method !== 'HEAD'
493
+ ? Buffer.concat(chunks)
494
+ : undefined;
495
+
496
+ const webReq = new Request(url, {
497
+ method: nodeReq.method,
498
+ headers: nodeReq.headers,
499
+ body,
500
+ duplex: 'half',
501
+ });
502
+
503
+ const webRes = await Promise.resolve(this.app.fetch(webReq));
504
+
505
+ nodeRes.statusCode = webRes.status;
506
+ webRes.headers.forEach((val, key) => {
507
+ nodeRes.setHeader(key, val);
508
+ });
509
+
510
+ const resBuffer = await webRes.arrayBuffer();
511
+ nodeRes.end(Buffer.from(resBuffer));
512
+ } catch (err) {
513
+ nodeRes.statusCode = 500;
514
+ nodeRes.end('Internal Server Error');
515
+ }
516
+ });
517
+
518
+ return server.listen(port, callback);
519
+ }
520
+ }
521
+
522
+ function createHonoHttpAdapter(app = null, options = {}) {
523
+ return new HonoHttpAdapter(app, options);
524
+ }
525
+
526
+ module.exports = {
527
+ HonoHttpAdapter,
528
+ createHonoHttpAdapter,
529
+ createHonoCompatReq,
530
+ createHonoCompatRes,
531
+ };
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso HTTP Layer
5
+ * @module core/http
6
+ */
7
+
8
+ const { HttpAdapter } = require('./adapter');
9
+ const { ExpressHttpAdapter, createExpressHttpAdapter } = require('./express-adapter');
10
+ const { runMiddlewares, enrichRouteError, executeApiPipeline, executePagePipeline } = require('./pipeline');
11
+
12
+ let _honoModule = null;
13
+ function getHonoModule() {
14
+ if (!_honoModule) {
15
+ _honoModule = require('./hono-adapter');
16
+ }
17
+ return _honoModule;
18
+ }
19
+
20
+ module.exports = {
21
+ HttpAdapter,
22
+ ExpressHttpAdapter,
23
+ createExpressHttpAdapter,
24
+ runMiddlewares,
25
+ enrichRouteError,
26
+ executeApiPipeline,
27
+ executePagePipeline,
28
+ };
29
+
30
+ Object.defineProperties(module.exports, {
31
+ HonoHttpAdapter: {
32
+ get: () => getHonoModule().HonoHttpAdapter,
33
+ enumerable: true,
34
+ configurable: true,
35
+ },
36
+ createHonoHttpAdapter: {
37
+ get: () => getHonoModule().createHonoHttpAdapter,
38
+ enumerable: true,
39
+ configurable: true,
40
+ },
41
+ });