@lowdefy/api 5.6.0 → 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.
- package/dist/context/createAuthorize.js +4 -1
- package/dist/context/resolveStrategyCaller.js +56 -0
- package/dist/index.js +12 -2
- package/dist/routes/agent/callAgent.js +7 -184
- package/dist/routes/agent/prepareAgent.js +173 -0
- package/dist/routes/auth/createLogger.js +2 -5
- package/dist/routes/auth/createPrefixedCookies.js +52 -0
- package/dist/routes/auth/{getNextAuthConfig.js → getAuthConfig.js} +27 -16
- package/dist/routes/auth/resolveCookies.js +37 -0
- package/dist/routes/auth/strategies/createAuthStrategies.js +77 -0
- package/dist/routes/auth/strategies/getAuthStrategies.js +31 -0
- package/dist/routes/endpoints/authorizeApiEndpoint.js +8 -2
- package/dist/routes/endpoints/callEndpoint.js +26 -3
- package/dist/routes/endpoints/control/controlReject.js +3 -1
- package/dist/routes/endpoints/control/controlThrow.js +4 -1
- package/dist/routes/endpoints/findSchedule.js +35 -0
- package/dist/routes/endpoints/forwardScheduledEndpoint.js +106 -0
- package/dist/routes/endpoints/getEndpointConfig.js +9 -3
- package/dist/routes/endpoints/getEnvironmentSchedules.js +29 -0
- package/dist/routes/endpoints/handleAgentCall.js +83 -0
- package/dist/routes/endpoints/handleEndpointCall.js +49 -1
- package/dist/routes/endpoints/handleRenderNotification.js +189 -0
- package/dist/routes/endpoints/handleValidateSchema.js +3 -1
- package/dist/routes/endpoints/isUnauthenticatedHuman.js +31 -0
- package/dist/routes/endpoints/resolveCronEnvironment.js +37 -0
- package/dist/routes/endpoints/runDetachedEndpoint.js +66 -0
- package/dist/routes/endpoints/runRoutine.js +12 -0
- package/dist/routes/endpoints/runScheduledEndpoint.js +104 -0
- package/dist/routes/endpoints/runWebhookEndpoint.js +83 -0
- package/dist/routes/endpoints/scheduleBackground.js +48 -0
- package/dist/routes/mcp/createMcpServer.js +160 -0
- package/dist/routes/notifications/derivePreview.js +30 -0
- package/dist/routes/notifications/getNotificationConfig.js +32 -0
- package/dist/routes/notifications/resolveNotificationLinks.js +72 -0
- package/dist/routes/notifications/resolveThemeLogo.js +35 -0
- package/dist/routes/page/dynamic/resolveDynamicContent.js +172 -0
- package/dist/routes/page/dynamic/unescapeOperators.js +36 -0
- package/dist/routes/page/dynamic/validateFragment.js +104 -0
- package/dist/routes/page/getPageConfig.js +16 -6
- package/dist/routes/websocket/authorizeWebsocket.js +27 -0
- package/dist/routes/websocket/createChannelRegistry.js +269 -0
- package/dist/routes/websocket/createWebSocketConnection.js +131 -0
- package/dist/routes/websocket/getWebsocketConfig.js +30 -0
- package/dist/routes/websocket/getWebsocketResolver.js +33 -0
- package/dist/routes/websocket/prepareChannel.js +72 -0
- package/dist/test/testContext.js +4 -2
- package/package.json +12 -10
|
@@ -0,0 +1,160 @@
|
|
|
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
|
+
*/ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
16
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
17
|
+
import { AuthenticationError } from '@lowdefy/errors';
|
|
18
|
+
import { serializer, type } from '@lowdefy/helpers';
|
|
19
|
+
import callEndpoint from '../endpoints/callEndpoint.js';
|
|
20
|
+
import isUnauthenticatedHuman from '../endpoints/isUnauthenticatedHuman.js';
|
|
21
|
+
// LLM-safe tool names use the same rule as buildAgents tool naming.
|
|
22
|
+
function toToolName(id) {
|
|
23
|
+
return id.replaceAll('/', '__');
|
|
24
|
+
}
|
|
25
|
+
// Twin of cleanBuildArtifact in packages/utils/ai-utils/src/buildAgentTools.js -
|
|
26
|
+
// duplicated here rather than shared, since pulling in @lowdefy/ai-utils would
|
|
27
|
+
// add the ai SDK and MCP client deps to api just for this. Strips build-artifact
|
|
28
|
+
// serializer markers (~k, ~r, ~l) and unwraps { '~arr': [...] } back to a plain
|
|
29
|
+
// array, so payloadSchema reaches MCP clients as plain JSON Schema.
|
|
30
|
+
function cleanBuildArtifact(obj) {
|
|
31
|
+
return JSON.parse(JSON.stringify(serializer.deserialize(obj)));
|
|
32
|
+
}
|
|
33
|
+
// A stateless per-request MCP server exposing the configured api endpoints
|
|
34
|
+
// as tools. Built with the SDK's low-level Server: tool input schemas are
|
|
35
|
+
// config-provided JSON Schema (payloadSchema), which the low-level handlers
|
|
36
|
+
// accept directly - no zod conversion. The server is constructed with the
|
|
37
|
+
// request's context, so the caller is known at construction time: tools/list
|
|
38
|
+
// filters by context.authorize, and tools/call re-authorizes inside
|
|
39
|
+
// callEndpoint (defense in depth). Returns null when no mcp block is
|
|
40
|
+
// configured.
|
|
41
|
+
async function createMcpServer({ context }) {
|
|
42
|
+
const mcpConfig = await context.readConfigFile('mcp.json');
|
|
43
|
+
if (type.isNone(mcpConfig) || mcpConfig.configured !== true) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
// serverInfo doubles as the connector card in clients such as claude.ai:
|
|
47
|
+
// title, websiteUrl and icons are optional branding the app may configure,
|
|
48
|
+
// and are omitted (not sent as undefined) when it does not. icons is config
|
|
49
|
+
// structure, so like payloadSchema it carries build-artifact markers that
|
|
50
|
+
// must not reach the client.
|
|
51
|
+
const serverInfo = {
|
|
52
|
+
name: mcpConfig.name,
|
|
53
|
+
version: mcpConfig.version
|
|
54
|
+
};
|
|
55
|
+
for (const key of [
|
|
56
|
+
'title',
|
|
57
|
+
'websiteUrl'
|
|
58
|
+
]){
|
|
59
|
+
if (!type.isNone(mcpConfig[key])) {
|
|
60
|
+
serverInfo[key] = mcpConfig[key];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!type.isNone(mcpConfig.icons)) {
|
|
64
|
+
serverInfo.icons = cleanBuildArtifact(mcpConfig.icons);
|
|
65
|
+
}
|
|
66
|
+
const server = new Server(serverInfo, {
|
|
67
|
+
capabilities: {
|
|
68
|
+
tools: {}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
server.setRequestHandler(ListToolsRequestSchema, async ()=>{
|
|
72
|
+
const tools = [];
|
|
73
|
+
for (const endpointId of mcpConfig.endpoints){
|
|
74
|
+
const endpointConfig = await context.readConfigFile(`api/${endpointId}.json`);
|
|
75
|
+
if (type.isNone(endpointConfig) || !context.authorize(endpointConfig)) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
tools.push({
|
|
79
|
+
name: toToolName(endpointId),
|
|
80
|
+
description: endpointConfig.description,
|
|
81
|
+
inputSchema: cleanBuildArtifact(endpointConfig.payloadSchema)
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
tools
|
|
86
|
+
};
|
|
87
|
+
});
|
|
88
|
+
server.setRequestHandler(CallToolRequestSchema, async (request)=>{
|
|
89
|
+
const { name, arguments: args } = request.params;
|
|
90
|
+
context.logger.info({
|
|
91
|
+
event: 'mcp_tool_call',
|
|
92
|
+
tool: name
|
|
93
|
+
});
|
|
94
|
+
const endpointId = mcpConfig.endpoints.find((id)=>toToolName(id) === name);
|
|
95
|
+
try {
|
|
96
|
+
if (!type.isNone(endpointId)) {
|
|
97
|
+
const { error, response, success } = await callEndpoint(context, {
|
|
98
|
+
blockId: '_mcp',
|
|
99
|
+
endpointId,
|
|
100
|
+
pageId: '_mcp',
|
|
101
|
+
payload: args ?? {}
|
|
102
|
+
});
|
|
103
|
+
if (!success) {
|
|
104
|
+
const deserialized = serializer.deserialize(error);
|
|
105
|
+
return {
|
|
106
|
+
content: [
|
|
107
|
+
{
|
|
108
|
+
type: 'text',
|
|
109
|
+
text: deserialized?.message ?? 'Endpoint failed.'
|
|
110
|
+
}
|
|
111
|
+
],
|
|
112
|
+
isError: true
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
content: [
|
|
117
|
+
{
|
|
118
|
+
type: 'text',
|
|
119
|
+
text: JSON.stringify(serializer.deserialize(response))
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// An unknown tool answers like a gated one for an anonymous caller on an
|
|
125
|
+
// auth'd app, so tools/call cannot be used to enumerate tool names that
|
|
126
|
+
// tools/list already hides from that caller.
|
|
127
|
+
if (await isUnauthenticatedHuman(context)) {
|
|
128
|
+
throw new AuthenticationError(`Authentication required for API endpoint "${name}".`);
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
content: [
|
|
132
|
+
{
|
|
133
|
+
type: 'text',
|
|
134
|
+
text: `Unknown tool "${name}".`
|
|
135
|
+
}
|
|
136
|
+
],
|
|
137
|
+
isError: true
|
|
138
|
+
};
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// Unauthenticated calls to gated tools are expected probing traffic -
|
|
141
|
+
// a warn line and the 401-shaped message, not a structured error log.
|
|
142
|
+
if (error.name === 'AuthenticationError') {
|
|
143
|
+
context.logger.warn(`Unauthenticated MCP tool call: ${name}`);
|
|
144
|
+
} else {
|
|
145
|
+
context.logger.error(error);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
content: [
|
|
149
|
+
{
|
|
150
|
+
type: 'text',
|
|
151
|
+
text: error.message
|
|
152
|
+
}
|
|
153
|
+
],
|
|
154
|
+
isError: true
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return server;
|
|
159
|
+
}
|
|
160
|
+
export default createMcpServer;
|
|
@@ -0,0 +1,30 @@
|
|
|
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
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
// Rough inversion of the interpolation pipeline for the preview text: strip
|
|
17
|
+
// author markdown syntax and unescape the backslash-escaped interpolated values.
|
|
18
|
+
function stripMarkdown(text) {
|
|
19
|
+
return text.replace(/```[\s\S]*?```/g, ' ').replace(/`([^`]*)`/g, '$1').replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^#{1,6}\s+/gm, '').replace(/^\s*>\s?/gm, '').replace(/^\s*[-*+]\s+/gm, '').replace(/(\*\*|__|\*|_|~~)/g, '').replace(/\\([!-/:-@[-`{-~])/g, '$1').replace(/\s+/g, ' ').trim();
|
|
20
|
+
}
|
|
21
|
+
function derivePreview({ properties }) {
|
|
22
|
+
if (type.isString(properties.preview) && properties.preview !== '') {
|
|
23
|
+
return properties.preview;
|
|
24
|
+
}
|
|
25
|
+
if (type.isString(properties.message) && properties.message !== '') {
|
|
26
|
+
return stripMarkdown(properties.message).slice(0, 140);
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
export default derivePreview;
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
*/ import { ConfigError } from '@lowdefy/errors';
|
|
16
|
+
async function getNotificationConfig({ logger, readConfigFile }, { notificationId, configKey }) {
|
|
17
|
+
const notification = await readConfigFile(`notifications/${notificationId}.json`);
|
|
18
|
+
if (!notification) {
|
|
19
|
+
const err = new ConfigError(`Notification "${notificationId}" does not exist.`, {
|
|
20
|
+
configKey
|
|
21
|
+
});
|
|
22
|
+
logger.debug({
|
|
23
|
+
params: {
|
|
24
|
+
notificationId
|
|
25
|
+
},
|
|
26
|
+
err
|
|
27
|
+
}, err.message);
|
|
28
|
+
throw err;
|
|
29
|
+
}
|
|
30
|
+
return notification;
|
|
31
|
+
}
|
|
32
|
+
export default getNotificationConfig;
|
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
*/ import { serializer, type, urlQuery } from '@lowdefy/helpers';
|
|
16
|
+
function resolveLinkValue({ link, option, serverUrl, basePath, landingPage, recordId }) {
|
|
17
|
+
// Absolute URLs pass through — links into other apps or external destinations.
|
|
18
|
+
// They skip any landing page, so they carry no mark-as-read.
|
|
19
|
+
if (type.isString(link)) {
|
|
20
|
+
return link;
|
|
21
|
+
}
|
|
22
|
+
if (type.isObject(link) && !type.isNone(link.pageId)) {
|
|
23
|
+
if (type.isNone(landingPage)) {
|
|
24
|
+
// No landing page configured — link straight to the target page.
|
|
25
|
+
const query = urlQuery.stringify(link.urlQuery ?? {});
|
|
26
|
+
return `${serverUrl}${basePath}/${link.pageId}${query ? `?${query}` : ''}`;
|
|
27
|
+
}
|
|
28
|
+
// The option query param is the dot-path of the link inside the record's
|
|
29
|
+
// data — the landing page reads the original target back with
|
|
30
|
+
// get(record.data, option) after marking the record read.
|
|
31
|
+
const query = urlQuery.stringify({
|
|
32
|
+
_id: recordId,
|
|
33
|
+
option
|
|
34
|
+
});
|
|
35
|
+
return `${serverUrl}${basePath}${landingPage}?${query}`;
|
|
36
|
+
}
|
|
37
|
+
return link;
|
|
38
|
+
}
|
|
39
|
+
// Resolves link values in a copy of the data item to URLs; the stored record
|
|
40
|
+
// keeps the original { pageId, urlQuery } objects for in-app navigation.
|
|
41
|
+
// data.links is the framework convention; link fields inside arrays are
|
|
42
|
+
// resolved for the data keys the template declares (Template.dataKeys), so
|
|
43
|
+
// custom templates get the same treatment as the built-in ones.
|
|
44
|
+
function resolveNotificationLinks({ item, dataKeys, serverUrl, basePath, landingPage, recordId }) {
|
|
45
|
+
const resolved = serializer.copy(item);
|
|
46
|
+
Object.keys(resolved.links ?? {}).forEach((key)=>{
|
|
47
|
+
resolved.links[key] = resolveLinkValue({
|
|
48
|
+
link: resolved.links[key],
|
|
49
|
+
option: `links.${key}`,
|
|
50
|
+
serverUrl,
|
|
51
|
+
basePath,
|
|
52
|
+
landingPage,
|
|
53
|
+
recordId
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
(dataKeys ?? []).forEach((arrayKey)=>{
|
|
57
|
+
if (!type.isArray(resolved[arrayKey])) return;
|
|
58
|
+
resolved[arrayKey].forEach((entry, index)=>{
|
|
59
|
+
if (!type.isObject(entry) || type.isNone(entry.link)) return;
|
|
60
|
+
entry.link = resolveLinkValue({
|
|
61
|
+
link: entry.link,
|
|
62
|
+
option: `${arrayKey}.${index}.link`,
|
|
63
|
+
serverUrl,
|
|
64
|
+
basePath,
|
|
65
|
+
landingPage,
|
|
66
|
+
recordId
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
return resolved;
|
|
71
|
+
}
|
|
72
|
+
export default resolveNotificationLinks;
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
// A theme logo written as an app-relative path ("/logo.png", a public/ asset)
|
|
17
|
+
// resolves against the deployment's serverUrl + basePath, so one config works
|
|
18
|
+
// across environments. Absolute ("https://...") and protocol-relative ("//...")
|
|
19
|
+
// URLs pass through. Without a serverUrl an email client can never fetch a
|
|
20
|
+
// relative path, so the logo is dropped — EmailLayout falls back to the
|
|
21
|
+
// companyName text header, which beats a broken image.
|
|
22
|
+
function resolveThemeLogo({ theme, serverUrl, basePath }) {
|
|
23
|
+
const { logo, ...rest } = theme;
|
|
24
|
+
if (!type.isString(logo) || !logo.startsWith('/') || logo.startsWith('//')) {
|
|
25
|
+
return theme;
|
|
26
|
+
}
|
|
27
|
+
if (type.isNone(serverUrl)) {
|
|
28
|
+
return rest;
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
...rest,
|
|
32
|
+
logo: `${serverUrl}${basePath}${logo}`
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export default resolveThemeLogo;
|
|
@@ -0,0 +1,172 @@
|
|
|
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
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
import { ConfigError } from '@lowdefy/errors';
|
|
17
|
+
import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
|
|
18
|
+
import invokeEndpoint from '../../endpoints/invokeEndpoint.js';
|
|
19
|
+
import unescapeOperators from './unescapeOperators.js';
|
|
20
|
+
import validateFragment from './validateFragment.js';
|
|
21
|
+
const MAX_DYNAMIC_DEPTH = 5;
|
|
22
|
+
function collectDynamicBlocks(block, found) {
|
|
23
|
+
if (block.type === 'Dynamic') {
|
|
24
|
+
// A Dynamic block's content comes from resolution; its fallback slot is
|
|
25
|
+
// resolved separately when a failure activates it.
|
|
26
|
+
found.push(block);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
Object.values(block.slots ?? {}).forEach((slot)=>{
|
|
30
|
+
(slot.blocks ?? []).forEach((child)=>collectDynamicBlocks(child, found));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function setResolvedContent(block, blocks) {
|
|
34
|
+
if (!block.slots) {
|
|
35
|
+
block.slots = {};
|
|
36
|
+
}
|
|
37
|
+
block.slots.content = {
|
|
38
|
+
...block.slots.content ?? {},
|
|
39
|
+
blocks
|
|
40
|
+
};
|
|
41
|
+
delete block.slots.fallback;
|
|
42
|
+
delete block.properties.endpointId;
|
|
43
|
+
delete block.properties.params;
|
|
44
|
+
delete block.properties.required;
|
|
45
|
+
delete block.properties.types;
|
|
46
|
+
}
|
|
47
|
+
async function resolveBlocks(context, { blocks, depth, shared }) {
|
|
48
|
+
const found = [];
|
|
49
|
+
blocks.forEach((block)=>collectDynamicBlocks(block, found));
|
|
50
|
+
await Promise.all(found.map((block)=>resolveDynamicBlock(context, {
|
|
51
|
+
block,
|
|
52
|
+
depth,
|
|
53
|
+
shared
|
|
54
|
+
})));
|
|
55
|
+
}
|
|
56
|
+
async function resolveDynamicBlock(context, { block, depth, shared }) {
|
|
57
|
+
const { logger } = context;
|
|
58
|
+
const { endpointId, params, required } = block.properties;
|
|
59
|
+
try {
|
|
60
|
+
if (depth >= MAX_DYNAMIC_DEPTH) {
|
|
61
|
+
throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" exceeded the maximum dynamic nesting depth of ${MAX_DYNAMIC_DEPTH}.`, {
|
|
62
|
+
configKey: block['~k']
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const { error, response, status } = await invokeEndpoint(context, {
|
|
66
|
+
endpointId,
|
|
67
|
+
payload: {
|
|
68
|
+
blockId: block.blockId,
|
|
69
|
+
pageId: shared.pageId,
|
|
70
|
+
params: params ?? {},
|
|
71
|
+
urlQuery: shared.urlQuery ?? {}
|
|
72
|
+
},
|
|
73
|
+
endpointDepth: 0
|
|
74
|
+
});
|
|
75
|
+
if ([
|
|
76
|
+
'error',
|
|
77
|
+
'reject'
|
|
78
|
+
].includes(status)) {
|
|
79
|
+
throw error ?? new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" endpoint "${endpointId}" failed with status "${status}".`, {
|
|
80
|
+
configKey: block['~k']
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
if (!type.isObject(response) || !type.isArray(response.blocks)) {
|
|
84
|
+
throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" endpoint "${endpointId}" must return an object with a "blocks" array.`, {
|
|
85
|
+
received: response,
|
|
86
|
+
configKey: block['~k']
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
// Unescape before building so operator counting validates the real
|
|
90
|
+
// (client-evaluated) operators against the bundle.
|
|
91
|
+
const { blocks, callApiActionRefs, requestActionRefs, warnings } = shared.buildDynamicBlocks({
|
|
92
|
+
blocks: unescapeOperators(response.blocks),
|
|
93
|
+
pageId: shared.pageId,
|
|
94
|
+
dynamicBlockId: block.blockId,
|
|
95
|
+
idPrefix: block.id,
|
|
96
|
+
types: shared.types,
|
|
97
|
+
blockMetas: shared.blockMetas
|
|
98
|
+
});
|
|
99
|
+
warnings.forEach((warning)=>{
|
|
100
|
+
logger.warn({
|
|
101
|
+
event: 'dynamic_block_warning',
|
|
102
|
+
blockId: block.blockId,
|
|
103
|
+
pageId: shared.pageId
|
|
104
|
+
}, warning.message);
|
|
105
|
+
});
|
|
106
|
+
await validateFragment(context, {
|
|
107
|
+
blocks,
|
|
108
|
+
blockSchemas: shared.blockSchemas,
|
|
109
|
+
callApiActionRefs,
|
|
110
|
+
dynamicBlockId: block.blockId,
|
|
111
|
+
pageId: shared.pageId,
|
|
112
|
+
pageRequests: shared.pageRequests,
|
|
113
|
+
requestActionRefs
|
|
114
|
+
});
|
|
115
|
+
await resolveBlocks(context, {
|
|
116
|
+
blocks,
|
|
117
|
+
depth: depth + 1,
|
|
118
|
+
shared
|
|
119
|
+
});
|
|
120
|
+
setResolvedContent(block, blocks);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (required === true) {
|
|
123
|
+
throw new ConfigError(`Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`, {
|
|
124
|
+
configKey: block['~k'],
|
|
125
|
+
cause: error
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
logger.error({
|
|
129
|
+
event: 'dynamic_block_error',
|
|
130
|
+
blockId: block.blockId,
|
|
131
|
+
endpointId,
|
|
132
|
+
pageId: shared.pageId,
|
|
133
|
+
err: error
|
|
134
|
+
}, `Dynamic block "${block.blockId}" on page "${shared.pageId}" failed to resolve: ${error.message}`);
|
|
135
|
+
const fallbackBlocks = block.slots?.fallback?.blocks ?? [];
|
|
136
|
+
setResolvedContent(block, fallbackBlocks);
|
|
137
|
+
await resolveBlocks(context, {
|
|
138
|
+
blocks: fallbackBlocks,
|
|
139
|
+
depth: depth + 1,
|
|
140
|
+
shared
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function resolveDynamicContent(context, { pageConfig, urlQuery }) {
|
|
145
|
+
// Loaded lazily so apps without dynamic pages never load the build package.
|
|
146
|
+
const { default: buildDynamicBlocks } = await import('@lowdefy/build/dynamic');
|
|
147
|
+
const [types, blockMetas, blockSchemas] = await Promise.all([
|
|
148
|
+
context.readConfigFile('types.json'),
|
|
149
|
+
context.readConfigFile('plugins/blockMetas.json'),
|
|
150
|
+
context.readConfigFile('plugins/blockSchemas.json')
|
|
151
|
+
]);
|
|
152
|
+
context.evaluateOperators = createEvaluateOperators(context);
|
|
153
|
+
const shared = {
|
|
154
|
+
blockMetas: blockMetas ?? {},
|
|
155
|
+
blockSchemas: blockSchemas ?? {},
|
|
156
|
+
buildDynamicBlocks,
|
|
157
|
+
pageId: pageConfig.pageId,
|
|
158
|
+
pageRequests: pageConfig.requests ?? [],
|
|
159
|
+
types: types ?? {},
|
|
160
|
+
urlQuery
|
|
161
|
+
};
|
|
162
|
+
// The page root block itself can be a Dynamic block.
|
|
163
|
+
await resolveBlocks(context, {
|
|
164
|
+
blocks: [
|
|
165
|
+
pageConfig
|
|
166
|
+
],
|
|
167
|
+
depth: 0,
|
|
168
|
+
shared
|
|
169
|
+
});
|
|
170
|
+
return pageConfig;
|
|
171
|
+
}
|
|
172
|
+
export default resolveDynamicContent;
|
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
// One extra leading underscore defers operator evaluation by one level — the
|
|
17
|
+
// same convention _function bodies use for __args. Shared operators like
|
|
18
|
+
// _state are registered on the server, so a plain `_state` in a routine's
|
|
19
|
+
// :return evaluates there (against empty routine state). Authors write
|
|
20
|
+
// `__state` instead: it survives the server evaluation untouched, and this
|
|
21
|
+
// unescape strips one underscore so the client evaluates the real operator.
|
|
22
|
+
function unescapeOperators(value) {
|
|
23
|
+
if (type.isArray(value)) {
|
|
24
|
+
return value.map(unescapeOperators);
|
|
25
|
+
}
|
|
26
|
+
if (!type.isObject(value)) {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
const result = {};
|
|
30
|
+
Object.keys(value).forEach((key)=>{
|
|
31
|
+
const unescapedKey = key.startsWith('__') ? key.slice(1) : key;
|
|
32
|
+
result[unescapedKey] = unescapeOperators(value[key]);
|
|
33
|
+
});
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
export default unescapeOperators;
|
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
*/ import { validate } from '@lowdefy/ajv';
|
|
16
|
+
import { getOperatorType, type } from '@lowdefy/helpers';
|
|
17
|
+
import { ConfigError } from '@lowdefy/errors';
|
|
18
|
+
function isOperatorObject(value) {
|
|
19
|
+
return getOperatorType(value) !== null;
|
|
20
|
+
}
|
|
21
|
+
function escapePointerSegment(segment) {
|
|
22
|
+
return segment.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
23
|
+
}
|
|
24
|
+
function collectOperatorPaths(value, path, paths) {
|
|
25
|
+
if (type.isArray(value)) {
|
|
26
|
+
value.forEach((item, index)=>collectOperatorPaths(item, `${path}/${index}`, paths));
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (!type.isObject(value)) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (isOperatorObject(value)) {
|
|
33
|
+
paths.push(path);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
Object.keys(value).forEach((key)=>{
|
|
37
|
+
if (key.startsWith('~')) return;
|
|
38
|
+
collectOperatorPaths(value[key], `${path}/${escapePointerSegment(key)}`, paths);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
// A schema violation at or under an operator node cannot be judged before the
|
|
42
|
+
// operator evaluates on the client — { _state: columns } may legitimately sit
|
|
43
|
+
// where the schema wants an array. Violations on operator-free paths stand.
|
|
44
|
+
function validateBlockProperties(block, { blockSchemas, dynamicBlockId, pageId }) {
|
|
45
|
+
const properties = block.properties;
|
|
46
|
+
if (!type.isObject(properties) || isOperatorObject(properties)) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
// Block schemas validate the whole pre-build block shape; the plugin's
|
|
50
|
+
// properties schema sits at schema.properties.properties.
|
|
51
|
+
const propertiesSchema = blockSchemas[block.type]?.properties?.properties;
|
|
52
|
+
if (type.isNone(propertiesSchema)) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const result = validate({
|
|
56
|
+
schema: propertiesSchema,
|
|
57
|
+
data: properties,
|
|
58
|
+
returnErrors: true
|
|
59
|
+
});
|
|
60
|
+
if (result.valid) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const operatorPaths = [];
|
|
64
|
+
collectOperatorPaths(properties, '', operatorPaths);
|
|
65
|
+
const errors = result.errors.filter((error)=>!operatorPaths.some((path)=>error.instancePath === path || error.instancePath.startsWith(`${path}/`)));
|
|
66
|
+
if (errors.length > 0) {
|
|
67
|
+
const messages = errors.map((error)=>`properties${error.instancePath || ''} ${error.message}`);
|
|
68
|
+
throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved block "${block.blockId}" (${block.type}) has invalid properties:\n${messages.map((message)=>` - ${message}`).join('\n')}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function walkBlocks(blocks, callback) {
|
|
72
|
+
blocks.forEach((block)=>{
|
|
73
|
+
callback(block);
|
|
74
|
+
Object.values(block.slots ?? {}).forEach((slot)=>{
|
|
75
|
+
walkBlocks(slot.blocks ?? [], callback);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async function validateFragment(context, { blocks, blockSchemas, callApiActionRefs, dynamicBlockId, pageId, pageRequests, requestActionRefs }) {
|
|
80
|
+
walkBlocks(blocks, (block)=>{
|
|
81
|
+
validateBlockProperties(block, {
|
|
82
|
+
blockSchemas,
|
|
83
|
+
dynamicBlockId,
|
|
84
|
+
pageId
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
// Request actions can only reference requests defined statically on the page —
|
|
88
|
+
// request artifacts are written at build time.
|
|
89
|
+
const pageRequestIds = new Set(pageRequests.map((request)=>request.requestId));
|
|
90
|
+
requestActionRefs.forEach(({ requestId, blockId, eventId })=>{
|
|
91
|
+
if (!pageRequestIds.has(requestId)) {
|
|
92
|
+
throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved content references request "${requestId}" on event "${eventId}" on block "${blockId}" which is not defined on the page.`);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
// CallAPI refs fail resolution instead of the user's click — same checks the
|
|
96
|
+
// HTTP endpoint route applies.
|
|
97
|
+
await Promise.all(callApiActionRefs.map(async ({ endpointId, blockId, eventId })=>{
|
|
98
|
+
const endpointConfig = await context.readConfigFile(`api/${endpointId}.json`);
|
|
99
|
+
if (!endpointConfig || endpointConfig.type === 'InternalApi') {
|
|
100
|
+
throw new ConfigError(`Dynamic block "${dynamicBlockId}" on page "${pageId}" resolved content has a CallAPI action on event "${eventId}" on block "${blockId}" targeting endpoint "${endpointId}" which does not exist or is not accessible from client pages.`);
|
|
101
|
+
}
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
export default validateFragment;
|
|
@@ -13,14 +13,24 @@
|
|
|
13
13
|
See the License for the specific language governing permissions and
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/ import { serializer } from '@lowdefy/helpers';
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
import resolveDynamicContent from './dynamic/resolveDynamicContent.js';
|
|
17
|
+
async function getPageConfig(context, { pageId, urlQuery }) {
|
|
18
|
+
const pageConfig = await context.readConfigFile(`pages/${pageId}.json`);
|
|
19
|
+
if (pageConfig && context.authorize(pageConfig)) {
|
|
19
20
|
// eslint-disable-next-line no-unused-vars
|
|
20
21
|
const { auth, ...rest } = pageConfig;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
if (rest.dynamic !== true) {
|
|
23
|
+
// Use serializer.serialize to ensure ~k keys (non-enumerable after deserialize)
|
|
24
|
+
// are made enumerable again for JSON transfer to client
|
|
25
|
+
return serializer.serialize(rest);
|
|
26
|
+
}
|
|
27
|
+
// readConfigFile caches parsed artifacts — deep copy before resolution so
|
|
28
|
+
// one request's resolved content never reaches another via the cache.
|
|
29
|
+
const resolved = await resolveDynamicContent(context, {
|
|
30
|
+
pageConfig: serializer.copy(rest),
|
|
31
|
+
urlQuery
|
|
32
|
+
});
|
|
33
|
+
return serializer.serialize(resolved);
|
|
24
34
|
}
|
|
25
35
|
return null;
|
|
26
36
|
}
|