@lowdefy/server 5.5.1 → 6.0.0

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 (62) hide show
  1. package/{pages/_app.js → client/App.jsx} +26 -34
  2. package/client/Page.jsx +109 -0
  3. package/client/main.jsx +39 -0
  4. package/lib/build/app.js +8 -1
  5. package/lib/build/appMeta.js +8 -1
  6. package/lib/build/auth.js +8 -1
  7. package/lib/build/config.js +8 -1
  8. package/lib/build/i18n.js +8 -1
  9. package/lib/build/logger.js +8 -1
  10. package/lib/build/theme.js +8 -1
  11. package/lib/client/auth/{Auth.js → Auth.jsx} +10 -2
  12. package/lib/client/auth/{AuthConfigured.js → AuthConfigured.jsx} +22 -10
  13. package/lib/client/sentry/captureSentryError.js +1 -1
  14. package/lib/client/sentry/initSentryClient.js +1 -1
  15. package/lib/client/sentry/setSentryUser.js +1 -1
  16. package/lib/server/apiWrapper.js +2 -9
  17. package/lib/server/auth/{getAuthOptions.js → getAuthConfig.js} +5 -4
  18. package/lib/server/auth/{getServerSession.js → session.js} +9 -6
  19. package/lib/server/auth/strategies.js +47 -0
  20. package/lib/server/log/createHandleError.js +15 -2
  21. package/lib/server/log/createLogger.js +18 -1
  22. package/lib/server/log/logRequest.js +41 -45
  23. package/lib/server/sentry/captureSentryError.js +1 -1
  24. package/lib/server/sentry/initSentry.js +6 -4
  25. package/lib/server/sentry/setSentryUser.js +1 -1
  26. package/lowdefy/createCustomPluginTypesMap.mjs +1 -0
  27. package/package.json +52 -39
  28. package/package.original.json +54 -41
  29. package/src/app.js +140 -0
  30. package/src/html/getAssets.js +45 -0
  31. package/src/html/renderPage.js +80 -0
  32. package/src/html/template.js +95 -0
  33. package/src/index.js +85 -0
  34. package/src/lib/getPathSegments.js +25 -0
  35. package/src/lib/safeScriptJson.js +38 -0
  36. package/src/middleware/apiContext.js +135 -0
  37. package/src/middleware/errorHandler.js +54 -0
  38. package/src/middleware/sentry.js +33 -0
  39. package/{pages/api/agent/[...path].js → src/routes/agent.js} +20 -42
  40. package/src/routes/apiPage.js +37 -0
  41. package/src/routes/auth.js +38 -0
  42. package/{pages/api/client-error.js → src/routes/clientError.js} +14 -16
  43. package/src/routes/cron.js +44 -0
  44. package/src/routes/cronForward.js +47 -0
  45. package/src/routes/detached.js +47 -0
  46. package/src/routes/endpoints.js +71 -0
  47. package/src/routes/mcp.js +34 -0
  48. package/{pages/api/request/[...path].js → src/routes/request.js} +10 -10
  49. package/src/routes/usage.js +46 -0
  50. package/src/routes/websocket.js +46 -0
  51. package/vite.config.js +61 -0
  52. package/.eslintrc.yaml +0 -1
  53. package/lib/client/Page.js +0 -56
  54. package/lib/server/serverSidePropsWrapper.js +0 -66
  55. package/next.config.js +0 -34
  56. package/pages/404.js +0 -49
  57. package/pages/[[...pageId]].js +0 -85
  58. package/pages/_document.js +0 -106
  59. package/pages/api/auth/[...nextauth].js +0 -37
  60. package/pages/api/endpoints/[...endpointId].js +0 -32
  61. package/pages/api/usage.js +0 -67
  62. /package/{postcss.config.js → postcss.config.cjs} +0 -0
@@ -0,0 +1,80 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { getPageConfig, getRootConfig } from '@lowdefy/api';
18
+
19
+ import appJson from '../../lib/build/app.js';
20
+ import lowdefyConfig from '../../lib/build/config.js';
21
+ import themeConfig from '../../lib/build/theme.js';
22
+ import getAssets from './getAssets.js';
23
+ import template from './template.js';
24
+
25
+ const basePath = lowdefyConfig.basePath ?? '';
26
+
27
+ // Replaces pages/[[...pageId]].js getServerSideProps and pages/404.js
28
+ // getStaticProps. The home redirect logic lives here, not at the route level.
29
+ async function renderPage(c, { pageId, status = 200 }) {
30
+ const context = c.get('lowdefyContext');
31
+ const { logger, session } = context;
32
+
33
+ let resolvedPageId = pageId;
34
+ const rootConfig = await getRootConfig(context);
35
+
36
+ if (!resolvedPageId) {
37
+ const { home } = rootConfig;
38
+ if (home.configured === false) {
39
+ logger.info({ event: 'redirect_to_homepage', pageId: home.pageId });
40
+ return c.redirect(`${basePath}/${home.pageId}`, 302);
41
+ }
42
+ resolvedPageId = home.pageId;
43
+ }
44
+
45
+ const pageConfig = await getPageConfig(context, {
46
+ pageId: resolvedPageId,
47
+ urlQuery: c.req.query(),
48
+ });
49
+
50
+ if (!pageConfig) {
51
+ if (resolvedPageId === '404') {
52
+ // No 404 page in the build — return a plain 404 rather than redirecting in a loop.
53
+ return c.text('Page not found.', 404);
54
+ }
55
+ logger.info({ event: 'redirect_page_not_found', pageId: resolvedPageId });
56
+ return c.redirect(`${basePath}/404`, 302);
57
+ }
58
+
59
+ logger.info({ event: 'page_view', pageId: resolvedPageId });
60
+
61
+ const html = template({
62
+ appendBody: appJson.html?.appendBody ?? '',
63
+ appendHead: appJson.html?.appendHead ?? '',
64
+ assets: getAssets(),
65
+ basePath,
66
+ config: {
67
+ basePath,
68
+ pageConfig,
69
+ rootConfig,
70
+ sentryDsn: process.env.SENTRY_DSN ?? null,
71
+ session: session ?? null,
72
+ },
73
+ themeConfig,
74
+ title: pageConfig.properties?.title ?? resolvedPageId,
75
+ });
76
+
77
+ return c.html(html, status);
78
+ }
79
+
80
+ export default renderPage;
@@ -0,0 +1,95 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import safeScriptJson from '../lib/safeScriptJson.js';
18
+
19
+ const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' };
20
+
21
+ function escapeHtml(value) {
22
+ return String(value).replace(/[&<>"]/g, (c) => HTML_ESCAPES[c]);
23
+ }
24
+
25
+ // Synchronous script that creates the @layer order declaration and keeps it as
26
+ // the first child of <head> via MutationObserver. antd's CSS-in-JS uses
27
+ // prependQueue to inject <style> tags at the top of <head>, which would
28
+ // otherwise make @layer antd the first (lowest priority) layer.
29
+ // MutationObserver fires before paint, so the browser never sees the wrong
30
+ // cascade order.
31
+ const layerOrderScript = `(function(){var s=document.createElement("style");s.id="__lf-layer-order";s.textContent="@layer theme, base, antd, components, utilities;";document.head.prepend(s);new MutationObserver(function(){if(document.head.firstChild!==s)document.head.prepend(s)}).observe(document.head,{childList:true})})();`;
32
+
33
+ // Synchronous pre-hydration script setting the <html> background and
34
+ // color-scheme — prevents a mode-mismatch flash of the page and of browser
35
+ // chrome (scrollbars, form controls) on page load. Mirrors useDarkMode.js
36
+ // resolution order: configDarkMode → localStorage → prefers-color-scheme.
37
+ function darkModeScript({ configColorMode, darkBg, lightBg }) {
38
+ return `(function(){var c=${safeScriptJson(configColorMode)};var db=${safeScriptJson(
39
+ darkBg
40
+ )};var lb=${safeScriptJson(
41
+ lightBg
42
+ )};var d;if(c==="dark")d=true;else if(c==="light")d=false;else{try{var p=localStorage.getItem("lowdefy_darkMode");if(p==="dark")d=true;else if(p==="light")d=false;else d=window.matchMedia("(prefers-color-scheme:dark)").matches}catch(e){d=window.matchMedia("(prefers-color-scheme:dark)").matches}}var bg=d?db:lb;document.documentElement.style.colorScheme=d?"dark":"light";if(bg)document.documentElement.style.backgroundColor=bg})();`;
43
+ }
44
+
45
+ function template({
46
+ appendBody = '',
47
+ appendHead = '',
48
+ assets,
49
+ basePath = '',
50
+ config,
51
+ themeConfig = {},
52
+ title,
53
+ }) {
54
+ const VALID_COLOR_MODES = ['system', 'light', 'dark'];
55
+ const configColorMode = VALID_COLOR_MODES.includes(themeConfig.darkMode)
56
+ ? themeConfig.darkMode
57
+ : 'system';
58
+ const darkBg = themeConfig?.antd?.darkToken?.colorBgLayout ?? '#000';
59
+ const lightBg = themeConfig?.antd?.lightToken?.colorBgLayout ?? '';
60
+
61
+ const cssLinks = assets.css
62
+ .map((file) => `<link rel="stylesheet" href="${basePath}/${file}" />`)
63
+ .join('\n ');
64
+ const modulePreloads = assets.imports
65
+ .map((file) => `<link rel="modulepreload" href="${basePath}/${file}" />`)
66
+ .join('\n ');
67
+
68
+ // appendHead and appendBody are intentionally raw HTML from app config
69
+ // (analytics snippets, font links) — they must not be escaped. The config
70
+ // JSON and pre-hydration interpolations go through safeScriptJson.
71
+ return `<!DOCTYPE html>
72
+ <html class="lowdefy">
73
+ <head>
74
+ <meta charset="utf-8" />
75
+ <script>${layerOrderScript}</script>
76
+ <script>${darkModeScript({ configColorMode, darkBg, lightBg })}</script>
77
+ <link rel="manifest" href="${basePath}/manifest.webmanifest" />
78
+ <link rel="icon" type="image/svg+xml" href="${basePath}/icon.svg" />
79
+ <link rel="apple-touch-icon" href="${basePath}/apple-touch-icon.png" />
80
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
81
+ ${title ? `<title>${escapeHtml(title)}</title>` : ''}
82
+ ${cssLinks}
83
+ ${modulePreloads}
84
+ ${appendHead}
85
+ </head>
86
+ <body>
87
+ <div id="root"></div>
88
+ <script id="__LOWDEFY_CONFIG__" type="application/json">${safeScriptJson(config)}</script>
89
+ ${appendBody}
90
+ <script type="module" src="${basePath}/${assets.js}"></script>
91
+ </body>
92
+ </html>`;
93
+ }
94
+
95
+ export default template;
package/src/index.js ADDED
@@ -0,0 +1,85 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { serve } from '@hono/node-server';
18
+ import * as Sentry from '@sentry/node';
19
+ import { WebSocketServer } from 'ws';
20
+
21
+ import initSentryServer from '../lib/server/sentry/initSentry.js';
22
+
23
+ // Auth.js v5 reads AUTH_URL but not NEXTAUTH_URL — alias the v4 variable
24
+ // before any auth config loads so existing deployments keep working.
25
+ if (process.env.NEXTAUTH_URL && !process.env.AUTH_URL) {
26
+ process.env.AUTH_URL = process.env.NEXTAUTH_URL;
27
+ }
28
+
29
+ const sentryEnabled = initSentryServer();
30
+
31
+ // Import after Sentry init so instrumentation observes the module graph.
32
+ const { default: createApp } = await import('./app.js');
33
+ const { default: createLogger } = await import('../lib/server/log/createLogger.js');
34
+ const { default: appMeta } = await import('../lib/build/appMeta.js');
35
+
36
+ const app = createApp();
37
+ const logger = createLogger({ server: 'lowdefy' });
38
+ const port = Number(process.env.PORT ?? 3000);
39
+
40
+ if (sentryEnabled) {
41
+ logger.info('Sentry enabled: server');
42
+ }
43
+
44
+ // Handles /api/websocket upgrades via serve({ websocket }). 256 KiB max frame,
45
+ // aligned with Vercel's documented default for WebSocket functions.
46
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 });
47
+
48
+ const server = serve({ fetch: app.fetch, port, websocket: { server: wss } }, (info) => {
49
+ // lowdefy_version logs once here rather than on every line — it is implied
50
+ // by the build, unlike the per-line deploy identity fields on the logger.
51
+ logger.info(
52
+ { port: info.port, lowdefy_version: appMeta.lowdefyVersion },
53
+ `Lowdefy server listening on http://localhost:${info.port}`
54
+ );
55
+ });
56
+
57
+ // Container runtimes send SIGTERM and escalate to SIGKILL after a grace period
58
+ // (Docker defaults to 10s) — finish in-flight work and exit before that deadline.
59
+ let shuttingDown = false;
60
+ function shutdown() {
61
+ if (shuttingDown) {
62
+ return;
63
+ }
64
+ shuttingDown = true;
65
+ // 1001 "going away" — clients reconnect and resubscribe on their own.
66
+ for (const client of wss.clients) {
67
+ client.close(1001, 'Server shutting down');
68
+ }
69
+ // Drop idle keep-alive connections so close() only waits on in-flight requests.
70
+ server.closeIdleConnections?.();
71
+ server.close(() => {
72
+ // Flush queued Sentry events; resolves immediately when Sentry is not enabled.
73
+ Sentry.close(2000).finally(() => process.exit(0));
74
+ });
75
+ // In-flight requests that outlive the grace period would otherwise hold the
76
+ // process open until SIGKILL — exit first so shutdown stays clean.
77
+ setTimeout(() => process.exit(1), 8000).unref();
78
+ }
79
+
80
+ process.on('SIGINT', shutdown);
81
+ process.on('SIGTERM', shutdown);
82
+
83
+ // Vercel's Node.js builder consumes the exported server — the same pattern
84
+ // Vercel documents for WebSocket support with Hono on Fluid compute.
85
+ export default server;
@@ -0,0 +1,25 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ // Splits the rest of a catch-all route into decoded segments, independent of
18
+ // any configured basePath. Mirrors the Next.js [...param] query arrays —
19
+ // nested ids (slashes in pageId or endpointId) are real.
20
+ function getPathSegments(c, prefix) {
21
+ const rest = c.req.path.split(prefix)[1] ?? '';
22
+ return rest.split('/').filter(Boolean).map(decodeURIComponent);
23
+ }
24
+
25
+ export default getPathSegments;
@@ -0,0 +1,38 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ // Escape characters that could break out of the enclosing <script> tag or
18
+ // terminate a JS string literal. Used to defuse the js/bad-code-sanitization
19
+ // class of injection for values embedded into inline scripts and the
20
+ // application/json config script.
21
+ const SCRIPT_ESCAPES = {
22
+ '<': '\\u003C',
23
+ '>': '\\u003E',
24
+ '\b': '\\b',
25
+ '\f': '\\f',
26
+ '\n': '\\n',
27
+ '\r': '\\r',
28
+ '\t': '\\t',
29
+ '\0': '\\0',
30
+ '\u2028': '\\u2028',
31
+ '\u2029': '\\u2029',
32
+ };
33
+
34
+ function safeScriptJson(value) {
35
+ return JSON.stringify(value).replace(/[<>\b\f\n\r\t\0\u2028\u2029]/g, (c) => SCRIPT_ESCAPES[c]);
36
+ }
37
+
38
+ export default safeScriptJson;
@@ -0,0 +1,135 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import path from 'node:path';
18
+ import { createApiContext } from '@lowdefy/api';
19
+ import { getSecretsFromEnv } from '@lowdefy/node-utils';
20
+ import { v4 as uuid } from 'uuid';
21
+
22
+ import agents from '../../build/plugins/agents.js';
23
+ import appMeta from '../../lib/build/appMeta.js';
24
+ import config from '../../lib/build/config.js';
25
+ import connections from '../../build/plugins/connections.js';
26
+ import createHandleError from '../../lib/server/log/createHandleError.js';
27
+ import createLogger from '../../lib/server/log/createLogger.js';
28
+ import fileCache from '../../lib/server/fileCache.js';
29
+ import getSession from '../../lib/server/auth/session.js';
30
+ import getStrategyCaller from '../../lib/server/auth/strategies.js';
31
+ import i18nConfig from '../../lib/build/i18n.js';
32
+ import jsMap from '../../build/plugins/operators/serverJsMap.js';
33
+ import logRequest from '../../lib/server/log/logRequest.js';
34
+ import loggerConfig from '../../lib/build/logger.js';
35
+ import notifications, {
36
+ interpolateProperties,
37
+ renderEmail,
38
+ } from '../../build/plugins/notifications.js';
39
+ import operators from '../../build/plugins/operators/server.js';
40
+ import setSentryUser from '../../lib/server/sentry/setSentryUser.js';
41
+ import websockets from '../../build/plugins/websockets.js';
42
+
43
+ const secrets = getSecretsFromEnv();
44
+
45
+ // Charset/length guard so a hostile x-request-id can't inject into logs.
46
+ const REQUEST_ID_REGEX = /^[\w.:-]{1,128}$/;
47
+
48
+ // Honor the request id assigned by an upstream proxy or load balancer so one
49
+ // id correlates client, proxy, and server logs; generate one otherwise.
50
+ function getRequestId(c) {
51
+ const incoming = c.req.header('x-request-id');
52
+ if (incoming && REQUEST_ID_REGEX.test(incoming)) {
53
+ return incoming;
54
+ }
55
+ return uuid();
56
+ }
57
+
58
+ // Replaces lib/server/apiWrapper.js. Builds the request context consumed by
59
+ // @lowdefy/api functions. Errors thrown by handlers are routed by Hono to the
60
+ // app-level error handler (src/middleware/errorHandler.js), which reads this
61
+ // context back from the Hono context.
62
+ function apiContext() {
63
+ return async function apiContextMiddleware(c, next) {
64
+ // The page-route mount ('/*') also matches /api/* paths that already
65
+ // built a context — never build twice for one request.
66
+ if (c.get('lowdefyContext')) {
67
+ return next();
68
+ }
69
+ const rid = getRequestId(c);
70
+ const context = {
71
+ rid,
72
+ agents,
73
+ appMeta,
74
+ buildDirectory: path.join(process.cwd(), 'build'),
75
+ config,
76
+ connections,
77
+ fileCache,
78
+ headers: c.req.header(),
79
+ // The deployment's own origin — detached endpoint calls loop back
80
+ // through it so the target runs in its own function invocation.
81
+ origin: new URL(c.req.url).origin,
82
+ i18n: i18nConfig,
83
+ interpolateProperties,
84
+ jsMap,
85
+ logger: createLogger({ rid }),
86
+ notifications,
87
+ operators,
88
+ renderEmail,
89
+ req: {
90
+ url: c.req.path,
91
+ method: c.req.method,
92
+ hostname: c.req.header('host'),
93
+ },
94
+ secrets,
95
+ // On Vercel (fluid compute) the platform request context keeps the
96
+ // invocation alive until waitUntil promises settle; on long-lived hosts
97
+ // the lookup resolves to nothing and background promises just run.
98
+ waitUntil: (promise) =>
99
+ globalThis[Symbol.for('@vercel/request-context')]?.get?.()?.waitUntil?.(promise),
100
+ websockets,
101
+ };
102
+ context.handleError = createHandleError({ context });
103
+ if (!c.req.path.includes('/api/auth')) {
104
+ context.session = await getSession(c);
105
+ if (!context.session?.user) {
106
+ const caller = await getStrategyCaller(c, context.logger);
107
+ if (caller) {
108
+ context.session = { user: caller };
109
+ }
110
+ }
111
+ // Set Sentry user context for authenticated requests
112
+ setSentryUser({
113
+ user: context.session?.user,
114
+ sentryConfig: loggerConfig.sentry,
115
+ });
116
+ }
117
+ createApiContext(context);
118
+ c.set('lowdefyContext', context);
119
+ // Echo the request id so clients and proxies can quote it when reporting
120
+ // a failure, and it can be matched to the rid on the server log lines.
121
+ c.header('x-request-id', context.rid);
122
+ const startTime = performance.now();
123
+ // Handler errors never reject next() — Hono's compose routes them to the
124
+ // app-level error handler at the throwing dispatch level, so by the time
125
+ // next() resolves c.res holds the final response, error or not.
126
+ await next();
127
+ logRequest({
128
+ context,
129
+ status: c.res.status,
130
+ durationMs: Math.round(performance.now() - startTime),
131
+ });
132
+ };
133
+ }
134
+
135
+ export default apiContext;
@@ -0,0 +1,54 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import * as Sentry from '@sentry/node';
18
+ import { redactErrorResponse } from '@lowdefy/api';
19
+
20
+ // Hono routes every handler error to the app-level error handler — upstream
21
+ // middleware try/catch never sees them (compose catches per dispatch level).
22
+ // API routes get the serialized error JSON the old apiWrapper returned;
23
+ // page routes get a plain 500.
24
+ function createErrorHandler({ basePath = '', logger }) {
25
+ return async function errorHandler(error, c) {
26
+ const path = basePath ? c.req.path.replace(basePath, '') : c.req.path;
27
+ // Unauthenticated requests to protected endpoints are expected traffic -
28
+ // one warning line and a 401, skipping the structured error log and the
29
+ // Sentry capture so probing cannot flood either. Keys strictly on the
30
+ // error name; the 500 path below is untouched.
31
+ if (error.name === 'AuthenticationError') {
32
+ logger.warn(`Unauthenticated request: ${c.req.method} ${c.req.path}`);
33
+ if (path.startsWith('/api/')) {
34
+ return c.json({ name: error.name, message: error.message }, 401);
35
+ }
36
+ return c.text('Unauthorized', 401);
37
+ }
38
+ const context = c.get('lowdefyContext');
39
+ if (context) {
40
+ await context.handleError(error);
41
+ } else {
42
+ logger.error(error);
43
+ }
44
+ if (process.env.SENTRY_DSN) {
45
+ Sentry.captureException(error);
46
+ }
47
+ if (path.startsWith('/api/')) {
48
+ return c.json(redactErrorResponse(context, error), 500);
49
+ }
50
+ return c.text('Internal Server Error', 500);
51
+ };
52
+ }
53
+
54
+ export default createErrorHandler;
@@ -0,0 +1,33 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import * as Sentry from '@sentry/node';
18
+
19
+ // Replaces @sentry/nextjs route auto-instrumentation: every request becomes
20
+ // an http.server transaction. Handler errors never propagate through
21
+ // middleware in Hono — captureException happens in the app error handler.
22
+ function sentryMiddleware() {
23
+ return async function sentry(c, next) {
24
+ if (!process.env.SENTRY_DSN) {
25
+ return next();
26
+ }
27
+ return Sentry.startSpan({ name: `${c.req.method} ${c.req.path}`, op: 'http.server' }, () =>
28
+ next()
29
+ );
30
+ };
31
+ }
32
+
33
+ export default sentryMiddleware;
@@ -17,34 +17,31 @@
17
17
  import { callAgent } from '@lowdefy/api';
18
18
  import { translate, type } from '@lowdefy/helpers';
19
19
 
20
- import apiWrapper from '../../../lib/server/apiWrapper.js';
20
+ import getPathSegments from '../lib/getPathSegments.js';
21
21
 
22
- async function handler({ context, req, res }) {
22
+ async function agentHandler(c) {
23
+ const context = c.get('lowdefyContext');
23
24
  const t = (key, values) => translate({ key, values, i18n: context.i18n });
24
- if (req.method !== 'POST') {
25
+ if (c.req.method !== 'POST') {
25
26
  throw new Error(t('agent.runtime.methodNotAllowed'));
26
27
  }
27
- const segments = req.query.path;
28
- if (!Array.isArray(segments) || segments.length < 2) {
29
- res.status(400).json({ error: t('agent.runtime.invalidPath') });
30
- return;
28
+ const segments = getPathSegments(c, '/api/agent/');
29
+ if (segments.length < 2) {
30
+ return c.json({ error: t('agent.runtime.invalidPath') }, 400);
31
31
  }
32
32
  const agentId = segments[segments.length - 1];
33
33
  const pageId = segments.slice(0, -1).join('/');
34
34
  context.logger.info({ event: 'call_agent', agentId, pageId });
35
- const { conversationId } = req.query;
36
- const { messages, urlQuery, sharedState } = req.body;
35
+ const { conversationId } = c.req.query();
36
+ const { messages, urlQuery, sharedState } = await c.req.json();
37
37
  if (!Array.isArray(messages)) {
38
- res.status(400).json({ error: t('agent.runtime.messagesMustBeArray') });
39
- return;
38
+ return c.json({ error: t('agent.runtime.messagesMustBeArray') }, 400);
40
39
  }
41
40
  if (urlQuery != null && (typeof urlQuery !== 'object' || Array.isArray(urlQuery))) {
42
- res.status(400).json({ error: t('agent.runtime.urlQueryMustBeObject') });
43
- return;
41
+ return c.json({ error: t('agent.runtime.urlQueryMustBeObject') }, 400);
44
42
  }
45
43
  if (sharedState != null && !type.isObject(sharedState)) {
46
- res.status(400).json({ error: t('agent.runtime.sharedStateMustBeObject') });
47
- return;
44
+ return c.json({ error: t('agent.runtime.sharedStateMustBeObject') }, 400);
48
45
  }
49
46
  const { response: webResponse } = await callAgent(context, {
50
47
  agentId,
@@ -55,32 +52,13 @@ async function handler({ context, req, res }) {
55
52
  urlQuery: urlQuery ?? undefined,
56
53
  });
57
54
 
58
- // Stream the Web Response body to the Next.js response
59
- res.setHeader('Content-Type', 'text/event-stream');
60
- res.setHeader('Cache-Control', 'no-cache');
61
- res.setHeader('Connection', 'keep-alive');
62
- res.setHeader('Content-Encoding', 'none');
63
- res.setHeader('Transfer-Encoding', 'chunked');
64
-
65
- const reader = webResponse.body.getReader();
66
- const decoder = new TextDecoder();
67
- let done = false;
68
- while (!done) {
69
- const { value, done: readerDone } = await reader.read();
70
- done = readerDone;
71
- if (value) {
72
- res.write(decoder.decode(value, { stream: true }));
73
- }
74
- }
75
- res.end();
55
+ // callAgent returns a Web Response — stream its body straight through.
56
+ return c.body(webResponse.body, 200, {
57
+ 'Content-Type': 'text/event-stream',
58
+ 'Cache-Control': 'no-cache',
59
+ Connection: 'keep-alive',
60
+ 'Content-Encoding': 'none',
61
+ });
76
62
  }
77
63
 
78
- export const config = {
79
- api: {
80
- bodyParser: {
81
- sizeLimit: '10mb',
82
- },
83
- },
84
- };
85
-
86
- export default apiWrapper(handler);
64
+ export default agentHandler;
@@ -0,0 +1,37 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { getPageConfig } from '@lowdefy/api';
18
+
19
+ import getPathSegments from '../lib/getPathSegments.js';
20
+
21
+ // Page config as JSON for client-side SPA navigation. The first page load is
22
+ // served embedded in the HTML; subsequent navigations fetch from here.
23
+ async function apiPageHandler(c) {
24
+ const context = c.get('lowdefyContext');
25
+ const pageId = getPathSegments(c, '/api/page/').join('/');
26
+ // The client forwards its current query string on the fetch so Dynamic block
27
+ // resolution sees the same urlQuery as an initial HTML load.
28
+ const pageConfig = await getPageConfig(context, { pageId, urlQuery: c.req.query() });
29
+ if (!pageConfig) {
30
+ context.logger.info({ event: 'api_page_not_found', pageId });
31
+ return c.json({ pageConfig: null }, 404);
32
+ }
33
+ context.logger.info({ event: 'api_page_view', pageId });
34
+ return c.json({ pageConfig });
35
+ }
36
+
37
+ export default apiPageHandler;