@lowdefy/api 6.0.0 → 7.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 (208) hide show
  1. package/dist/context/applySystemTrust.js +45 -0
  2. package/dist/context/createApiContext.js +18 -3
  3. package/dist/context/createAuthorizeOutcome.js +91 -0
  4. package/dist/context/createBoundSystemContext.js +33 -0
  5. package/dist/context/createEvaluateOperators.js +10 -3
  6. package/dist/context/createRequestSignal.js +47 -0
  7. package/dist/context/createSystemContext.js +80 -0
  8. package/dist/context/getCanonicalUrl.js +27 -0
  9. package/dist/context/getCurrentEnvironment.js +27 -0
  10. package/dist/context/isSameOriginRequest.js +85 -0
  11. package/dist/context/isWebSocketOriginAllowed.js +63 -0
  12. package/dist/context/normalizeInjectedCaller.js +58 -0
  13. package/dist/context/parseRequestBody.js +32 -0
  14. package/dist/context/readMemberships.js +71 -0
  15. package/dist/context/resolveAuthentication.js +758 -0
  16. package/dist/context/resolveStrategyCaller.js +7 -3
  17. package/dist/csp/addNonceToElements.js +23 -0
  18. package/dist/csp/createContentSecurityPolicy.js +45 -0
  19. package/dist/csp/getWebSocketSources.js +36 -0
  20. package/dist/email/renderAuthEmail.js +99 -0
  21. package/dist/index.js +22 -5
  22. package/dist/response/buildEndpointResult.js +3 -1
  23. package/dist/response/createWireProjection.js +88 -0
  24. package/dist/response/formatErrorForAgent.js +35 -0
  25. package/dist/response/normalizeErrorSources.js +10 -13
  26. package/dist/response/redactErrorResponse.js +42 -8
  27. package/dist/response/redactResponse.js +17 -10
  28. package/dist/routes/agent/authorizeAgent.js +17 -5
  29. package/dist/routes/agent/callAgent.js +12 -2
  30. package/dist/routes/agent/collectChatFiles.js +39 -0
  31. package/dist/routes/agent/prepareAgent.js +29 -4
  32. package/dist/routes/auth/buildAdminPlugin.js +33 -0
  33. package/dist/routes/auth/buildCaptchaPlugin.js +61 -0
  34. package/dist/routes/auth/buildMcpTokenPlugin.js +77 -0
  35. package/dist/routes/auth/buildOauthPostLogin.js +73 -0
  36. package/dist/routes/auth/buildPhoneNumberPlugin.js +57 -0
  37. package/dist/routes/auth/buildProviders.js +61 -0
  38. package/dist/routes/auth/createAsMetadataHandler.js +27 -0
  39. package/dist/routes/auth/createAuthLogger.js +31 -0
  40. package/dist/routes/auth/createMcpAccessTokenClaims.js +52 -0
  41. package/dist/routes/auth/createOnAPIError.js +41 -0
  42. package/dist/routes/auth/createSendEmail.js +54 -0
  43. package/dist/routes/auth/ensureMcpTokenIndexes.js +48 -0
  44. package/dist/routes/auth/getAuthEnforcement.js +41 -0
  45. package/dist/routes/auth/getBetterAuth.js +107 -0
  46. package/dist/routes/auth/getBetterAuthConfig.js +767 -0
  47. package/dist/routes/auth/handleAuthRequest.js +43 -0
  48. package/dist/routes/auth/hooks/authHookPoints.js +204 -0
  49. package/dist/routes/auth/hooks/buildEngineHooks.js +68 -0
  50. package/dist/routes/auth/hooks/buildHooks.js +112 -0
  51. package/dist/routes/auth/{callbacks/addUserFieldsToSession.js → hooks/composeAfterSlot.js} +11 -13
  52. package/dist/routes/auth/hooks/composeBeforeSlot.js +41 -0
  53. package/dist/routes/auth/hooks/createHookDispatch.js +59 -0
  54. package/dist/routes/auth/hooks/createUserAfterHook.js +36 -0
  55. package/dist/routes/auth/hooks/createUserBeforeHook.js +50 -0
  56. package/dist/routes/auth/hooks/findHookUser.js +27 -0
  57. package/dist/routes/auth/modelNames.js +30 -0
  58. package/dist/routes/auth/organizations/OrganizationKeyError.js +28 -0
  59. package/dist/routes/auth/organizations/authorizeRole.js +27 -0
  60. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +178 -0
  61. package/dist/routes/auth/organizations/createAcceptActiveOrgGuardHook.js +57 -0
  62. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +120 -0
  63. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +403 -0
  64. package/dist/routes/auth/organizations/createAdmissionGateHook.js +50 -0
  65. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +90 -0
  66. package/dist/routes/auth/organizations/createAutoJoinHook.js +68 -0
  67. package/dist/routes/auth/organizations/createEmailSendGate.js +59 -0
  68. package/dist/routes/auth/organizations/createExpiredInvitationGate.js +76 -0
  69. package/dist/routes/auth/organizations/ensureAuthIndexes.js +122 -0
  70. package/dist/routes/auth/organizations/ensureOrganization.js +132 -0
  71. package/dist/routes/auth/organizations/findPendingInvitation.js +43 -0
  72. package/dist/routes/auth/organizations/getHookRequestHeaders.js +24 -0
  73. package/dist/routes/auth/organizations/getOrganizationBinding.js +65 -0
  74. package/dist/routes/auth/organizations/isEmailAdmitted.js +89 -0
  75. package/dist/routes/auth/organizations/organizationAccessControl.js +94 -0
  76. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +62 -0
  77. package/dist/routes/auth/requestHooks/beginTwoFactorChallenge.js +145 -0
  78. package/dist/routes/auth/requestHooks/buildRequestHooks.js +288 -0
  79. package/dist/routes/auth/requestHooks/createOauthPostLoginHook.js +43 -0
  80. package/dist/routes/auth/requestHooks/createTwoFactorChallengeHook.js +59 -0
  81. package/dist/routes/auth/requestHooks/dispatchRequestHooks.js +47 -0
  82. package/dist/routes/auth/requestHooks/redirectToChallenge.js +79 -0
  83. package/dist/routes/auth/requestHooks/resolveTwoFactorPageUrl.js +31 -0
  84. package/dist/routes/auth/resolveCookiePrefix.js +30 -0
  85. package/dist/routes/auth/sanitizeSessionResponse.js +27 -0
  86. package/dist/routes/auth/strategies/getAuthStrategies.js +1 -1
  87. package/dist/routes/connections/checkUnwalledReach.js +37 -0
  88. package/dist/routes/connections/getConnectionConfig.js +6 -1
  89. package/dist/routes/connections/resolveTenantPreflight.js +226 -0
  90. package/dist/routes/connections/resolveUnwalledReach.js +144 -0
  91. package/dist/routes/endpoints/acceptDetachedEndpoint.js +50 -0
  92. package/dist/routes/endpoints/authorizeApiEndpoint.js +13 -4
  93. package/dist/routes/endpoints/callEndpoint.js +23 -7
  94. package/dist/routes/endpoints/control/controlFor.js +4 -7
  95. package/dist/routes/endpoints/control/controlIf.js +4 -8
  96. package/dist/routes/endpoints/control/controlLog.js +6 -14
  97. package/dist/routes/endpoints/control/controlParallelFor.js +65 -29
  98. package/dist/routes/endpoints/control/controlReject.js +36 -16
  99. package/dist/routes/endpoints/control/controlReturn.js +32 -9
  100. package/dist/routes/endpoints/control/controlSetState.js +4 -8
  101. package/dist/routes/endpoints/control/controlSwitch.js +4 -8
  102. package/dist/routes/endpoints/control/controlThrow.js +20 -21
  103. package/dist/routes/endpoints/control/controlTry.js +30 -11
  104. package/dist/routes/endpoints/control/controlWhile.js +55 -0
  105. package/dist/routes/endpoints/control/handleControl.js +3 -1
  106. package/dist/routes/endpoints/createWebhookAnswer.js +78 -0
  107. package/dist/routes/endpoints/evaluateRoutineOperators.js +27 -0
  108. package/dist/routes/endpoints/forwardScheduledEndpoint.js +21 -15
  109. package/dist/routes/endpoints/getEndpointConfig.js +18 -8
  110. package/dist/routes/endpoints/getEnvironmentSchedules.js +5 -7
  111. package/dist/routes/endpoints/getSchemaValidator.js +39 -0
  112. package/dist/routes/endpoints/handleAgentCall.js +25 -9
  113. package/dist/routes/endpoints/handleAuthStep.js +214 -0
  114. package/dist/routes/endpoints/handleDescribeDynamicPolicy.js +64 -0
  115. package/dist/routes/endpoints/handleEndpointCall.js +46 -12
  116. package/dist/routes/endpoints/handleRenderNotification.js +29 -12
  117. package/dist/routes/endpoints/handleRequest.js +13 -6
  118. package/dist/routes/endpoints/handleValidateDynamic.js +106 -0
  119. package/dist/routes/endpoints/handleValidateSchema.js +22 -22
  120. package/dist/routes/endpoints/invokeEndpoint.js +27 -3
  121. package/dist/routes/endpoints/operatorScope.js +28 -0
  122. package/dist/routes/{auth/events/createEventPlugins.js → endpoints/parseWebhookBody.js} +10 -6
  123. package/dist/routes/endpoints/resolveCallBinding.js +91 -0
  124. package/dist/routes/endpoints/resolveCronEnvironment.js +7 -6
  125. package/dist/routes/endpoints/resolveStepOrganizationId.js +64 -0
  126. package/dist/routes/endpoints/runDetachedEndpoint.js +64 -18
  127. package/dist/routes/endpoints/runRoutine.js +64 -5
  128. package/dist/routes/endpoints/runScheduledEndpoint.js +19 -11
  129. package/dist/routes/endpoints/runWebhookEndpoint.js +70 -23
  130. package/dist/routes/endpoints/runWebhookVerify.js +129 -0
  131. package/dist/routes/endpoints/scheduleBackground.js +10 -0
  132. package/dist/routes/endpoints/test/runTest.js +48 -11
  133. package/dist/routes/endpoints/validatePayload.js +144 -0
  134. package/dist/routes/log/logClientError.js +7 -4
  135. package/dist/routes/mcp/createMcpServer.js +143 -64
  136. package/dist/routes/mcp/getMcpJwks.js +93 -0
  137. package/dist/routes/mcp/getMcpResourceBinding.js +41 -0
  138. package/dist/routes/mcp/getMcpUri.js +69 -0
  139. package/dist/routes/mcp/oauthResourceLifecycle.js +122 -0
  140. package/dist/routes/mcp/runAfterToolCall.js +50 -0
  141. package/dist/routes/notifications/resolveNotificationLinks.js +39 -11
  142. package/dist/routes/page/dynamic/checkDynamicContent.js +81 -0
  143. package/dist/routes/page/dynamic/checkLiteralContent.js +242 -0
  144. package/dist/routes/page/dynamic/createContentError.js +34 -0
  145. package/dist/routes/page/dynamic/flagIconsOutsidePage.js +39 -0
  146. package/dist/routes/page/dynamic/flagTypesOutsidePage.js +44 -0
  147. package/dist/routes/page/dynamic/getPropertiesSchemaErrors.js +35 -0
  148. package/dist/routes/page/dynamic/loadDynamicArtifacts.js +52 -0
  149. package/dist/routes/page/dynamic/policy/checkAction.js +204 -0
  150. package/dist/routes/page/dynamic/policy/checkEvents.js +163 -0
  151. package/dist/routes/page/dynamic/policy/checkPolicy.js +313 -0
  152. package/dist/routes/page/dynamic/policy/checkValue.js +214 -0
  153. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +117 -0
  154. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +54 -0
  155. package/dist/routes/page/dynamic/policy/findSerializerKeys.js +50 -0
  156. package/dist/routes/page/dynamic/policy/isAllowedUrl.js +53 -0
  157. package/dist/routes/{auth/createAdapter.js → page/dynamic/policy/isUnderState.js} +5 -9
  158. package/dist/routes/page/dynamic/policy/normalizeUrlText.js +25 -0
  159. package/dist/routes/page/dynamic/resolveDynamicContent.js +89 -37
  160. package/dist/routes/page/dynamic/unescapeOperators.js +21 -4
  161. package/dist/routes/page/dynamic/validateFragment.js +17 -58
  162. package/dist/routes/page/getPageConfig.js +76 -6
  163. package/dist/routes/request/authorizeRequest.js +21 -6
  164. package/dist/routes/request/callRequest.js +21 -3
  165. package/dist/routes/request/callRequestResolver.js +55 -6
  166. package/dist/routes/request/checkConnectionRead.js +1 -1
  167. package/dist/routes/request/checkConnectionWrite.js +1 -1
  168. package/dist/routes/request/createWalledResolver.js +75 -0
  169. package/dist/routes/request/evaluateOperators.js +8 -12
  170. package/dist/routes/request/getRequestConfig.js +19 -3
  171. package/dist/routes/request/maskCredentialProperties.js +34 -0
  172. package/dist/routes/request/resolveTenancy.js +223 -0
  173. package/dist/routes/request/validateSchemas.js +7 -6
  174. package/dist/routes/{auth/callbacks/createCallbackPlugins.js → rootConfig/getAppEvents.js} +7 -6
  175. package/dist/routes/rootConfig/getHomeAndMenus.js +23 -16
  176. package/dist/routes/{auth/events/createSessionEvent.js → rootConfig/getPagePaths.js} +16 -18
  177. package/dist/routes/rootConfig/getRootConfig.js +9 -3
  178. package/dist/routes/rootConfig/menus/filterMenuList.js +5 -2
  179. package/dist/routes/websocket/authorizeWebsocket.js +19 -4
  180. package/dist/routes/websocket/createChannelRegistry.js +39 -14
  181. package/dist/routes/websocket/createWebSocketConnection.js +162 -28
  182. package/dist/routes/websocket/getCallerFingerprint.js +31 -0
  183. package/dist/routes/websocket/prepareChannel.js +29 -1
  184. package/dist/routes/websocket/resolveWebsocketCaller.js +40 -0
  185. package/dist/test/testContext.js +16 -11
  186. package/package.json +28 -12
  187. package/dist/context/createAuthorize.js +0 -45
  188. package/dist/response/omitErrorProps.js +0 -51
  189. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +0 -30
  190. package/dist/routes/auth/callbacks/createCallbacks.js +0 -46
  191. package/dist/routes/auth/callbacks/createJWTCallback.js +0 -77
  192. package/dist/routes/auth/callbacks/createRedirectCallback.js +0 -41
  193. package/dist/routes/auth/callbacks/createSessionCallback.js +0 -81
  194. package/dist/routes/auth/callbacks/createSignInCallback.js +0 -40
  195. package/dist/routes/auth/callbacks/validateSessionRoles.js +0 -33
  196. package/dist/routes/auth/createLogger.js +0 -35
  197. package/dist/routes/auth/createPrefixedCookies.js +0 -52
  198. package/dist/routes/auth/createProviders.js +0 -25
  199. package/dist/routes/auth/events/createCreateUserEvent.js +0 -41
  200. package/dist/routes/auth/events/createEvents.js +0 -56
  201. package/dist/routes/auth/events/createLinkAccountEvent.js +0 -43
  202. package/dist/routes/auth/events/createSignInEvent.js +0 -46
  203. package/dist/routes/auth/events/createSignOutEvent.js +0 -43
  204. package/dist/routes/auth/events/createUpdateUserEvent.js +0 -41
  205. package/dist/routes/auth/getAuthConfig.js +0 -86
  206. package/dist/routes/auth/resolveCookies.js +0 -37
  207. package/dist/routes/log/formatValidationError.js +0 -31
  208. /package/dist/{routes/notifications → email}/resolveThemeLogo.js +0 -0
@@ -12,21 +12,30 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { AuthenticationError, ConfigError } from '@lowdefy/errors';
15
+ */ import { AuthenticationError, AuthorizationError, TwoFactorEnrolmentRequiredError } from '@lowdefy/errors';
16
16
  import { type } from '@lowdefy/helpers';
17
- function authorizeApiEndpoint({ authorize, logger, user }, { endpointConfig }) {
18
- if (!authorize(endpointConfig)) {
17
+ function authorizeApiEndpoint({ authorizeOutcome: authorize, logger, user }, { endpointConfig }) {
18
+ const outcome = authorize(endpointConfig);
19
+ if (outcome !== 'allow') {
19
20
  logger.debug({
20
21
  event: 'debug_api_authorize',
21
22
  authorized: false,
23
+ outcome,
22
24
  auth_config: endpointConfig.auth
23
25
  });
26
+ if (outcome === 'enrol_required') {
27
+ // Reached only after the role check passed, so the caller is authorised and
28
+ // this reveals nothing about what exists (Decision 6). A distinct code, not
29
+ // a 401 - a 401 reads to the client as a dead session and bounces the user
30
+ // to sign-in, which is the loop by another route.
31
+ throw new TwoFactorEnrolmentRequiredError(`Two-factor enrolment required for API Endpoint "${endpointConfig.endpointId}".`);
32
+ }
24
33
  // Unauthenticated on a protected endpoint - 401 tells the caller to fix
25
34
  // its credentials. Wrong roles stay opaque below.
26
35
  if (type.isNone(user)) {
27
36
  throw new AuthenticationError(`Authentication required for API endpoint "${endpointConfig.endpointId}".`);
28
37
  }
29
- throw new ConfigError(`API Endpoint "${endpointConfig.endpointId}" does not exist.`);
38
+ throw new AuthorizationError(`API Endpoint "${endpointConfig.endpointId}" does not exist.`);
30
39
  }
31
40
  logger.debug({
32
41
  event: 'debug_api_authorize',
@@ -12,16 +12,16 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { serializer } from '@lowdefy/helpers';
15
+ */ import { serializer, type } from '@lowdefy/helpers';
16
16
  import { AuthenticationError, ConfigError } from '@lowdefy/errors';
17
17
  import authorizeApiEndpoint from './authorizeApiEndpoint.js';
18
18
  import buildEndpointResult from '../../response/buildEndpointResult.js';
19
19
  import createEvaluateOperators from '../../context/createEvaluateOperators.js';
20
20
  import getEndpointConfig from './getEndpointConfig.js';
21
- import isUnauthenticatedHuman from './isUnauthenticatedHuman.js';
22
21
  import runRoutine from './runRoutine.js';
23
22
  import scheduleBackground from './scheduleBackground.js';
24
- async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
23
+ import validatePayload from './validatePayload.js';
24
+ async function callEndpoint(context, { blockId, endpointId, outsideCaller = false, pageId, payload }) {
25
25
  const { logger } = context;
26
26
  context.blockId = blockId;
27
27
  context.endpointId = endpointId;
@@ -38,10 +38,11 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
38
38
  endpointId
39
39
  });
40
40
  // Block HTTP access to InternalApi endpoints - same error as a missing
41
- // endpoint, including the unauthenticated fork, so an internal endpoint is
42
- // indistinguishable from one that does not exist on both paths.
41
+ // endpoint, including the guarded unauthenticated fork, so an internal
42
+ // endpoint is indistinguishable from one that does not exist on both paths.
43
43
  if (endpointConfig.type === 'InternalApi') {
44
- const err = await isUnauthenticatedHuman(context) ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
44
+ const unauthenticatedHuman = type.isNone(context.user) && !type.isNone(context.authEnforcement) && context.system !== true;
45
+ const err = unauthenticatedHuman ? new AuthenticationError(`Authentication required for API endpoint "${endpointId}".`) : new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
45
46
  logger.debug({
46
47
  params: {
47
48
  endpointId
@@ -53,10 +54,23 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
53
54
  authorizeApiEndpoint(context, {
54
55
  endpointConfig
55
56
  });
57
+ // Validated before the async fork, so a refused payload is answered to the
58
+ // caller rather than failing in the background. A page CallAPI without a
59
+ // payload sends none; it is an empty object here as on every other caller.
60
+ // A page's CallAPI names its page, whose config built the payload. A call that
61
+ // names no page is an API client's own, as is an MCP tool call
62
+ // (outsideCaller), so a refusal is that caller's mistake (validatePayload).
63
+ const deserializedPayload = serializer.deserialize(payload ?? {});
64
+ validatePayload({
65
+ endpointConfig,
66
+ payload: deserializedPayload,
67
+ outsideCaller: outsideCaller || type.isNone(pageId)
68
+ });
56
69
  const routineContext = {
57
70
  steps: {},
58
- payload: serializer.deserialize(payload),
71
+ payload: deserializedPayload,
59
72
  arrayIndices: [],
73
+ error: null,
60
74
  items: {},
61
75
  state: {},
62
76
  endpointDepth: 0
@@ -65,6 +79,8 @@ async function callEndpoint(context, { blockId, endpointId, pageId, payload }) {
65
79
  // Auth was already checked above; the outcome lands in logs (scheduleBackground)
66
80
  // and in whatever the routine itself records.
67
81
  if (endpointConfig.async === true) {
82
+ // The run outlives this request, so the request closing must not cancel it.
83
+ context.signal = undefined;
68
84
  scheduleBackground(context, {
69
85
  event: 'background_endpoint',
70
86
  endpointId
@@ -14,20 +14,17 @@
14
14
  limitations under the License.
15
15
  */ import { ConfigError } from '@lowdefy/errors';
16
16
  import runRoutine from '../runRoutine.js';
17
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
18
  async function controlFor(context, routineContext, { control }) {
18
- const { endpointId, logger, evaluateOperators } = context;
19
+ const { endpointId, logger } = context;
19
20
  const { items } = routineContext;
20
21
  const itemName = control[':for'];
21
22
  if (!itemName) {
22
23
  throw new Error(`Invalid :for in endpoint "${endpointId}" - missing variable name in :for.`);
23
24
  }
24
- const array = evaluateOperators({
25
+ const array = evaluateRoutineOperators(context, routineContext, {
25
26
  input: control[':in'],
26
- items,
27
- location: control['~k'] ?? ':for',
28
- payload: routineContext.payload,
29
- state: routineContext.state,
30
- steps: routineContext.steps
27
+ location: control['~k'] ?? ':for'
31
28
  });
32
29
  logger.debug({
33
30
  event: 'debug_control_for',
@@ -13,16 +13,12 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import runRoutine from '../runRoutine.js';
16
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
17
  async function controlIf(context, routineContext, { control }) {
17
- const { endpointId, logger, evaluateOperators } = context;
18
- const { items } = routineContext;
19
- const evaluatedIf = evaluateOperators({
18
+ const { endpointId, logger } = context;
19
+ const evaluatedIf = evaluateRoutineOperators(context, routineContext, {
20
20
  input: control[':if'],
21
- items,
22
- location: control['~k'] ?? ':if',
23
- payload: routineContext.payload,
24
- state: routineContext.state,
25
- steps: routineContext.steps
21
+ location: control['~k'] ?? ':if'
26
22
  });
27
23
  logger.debug({
28
24
  event: 'debug_control_if',
@@ -14,28 +14,20 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import { ConfigError } from '@lowdefy/errors';
17
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
18
  async function controlLog(context, routineContext, { control }) {
18
- const { endpointId, logger, evaluateOperators } = context;
19
- const { items } = routineContext;
19
+ const { endpointId, logger } = context;
20
20
  const location = control['~k'] ?? ':log';
21
21
  logger.debug({
22
22
  event: 'debug_control_log'
23
23
  });
24
- const log = evaluateOperators({
24
+ const log = evaluateRoutineOperators(context, routineContext, {
25
25
  input: control[':log'],
26
- items,
27
- location,
28
- payload: routineContext.payload,
29
- state: routineContext.state,
30
- steps: routineContext.steps
26
+ location
31
27
  });
32
- const logLevel = evaluateOperators({
28
+ const logLevel = evaluateRoutineOperators(context, routineContext, {
33
29
  input: control[':level'],
34
- items,
35
- location,
36
- payload: routineContext.payload,
37
- state: routineContext.state,
38
- steps: routineContext.steps
30
+ location
39
31
  }) ?? 'info';
40
32
  if (!type.isString(logLevel)) {
41
33
  throw new ConfigError(`Invalid :log in endpoint "${endpointId}" - :level must be a string.`, {
@@ -12,22 +12,42 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { ConfigError } from '@lowdefy/errors';
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import { ConfigError } from '@lowdefy/errors';
16
17
  import runRoutine from '../runRoutine.js';
18
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
19
+ // Runs `run(index)` for every index, at most `limit` at a time (every index at once without a
20
+ // limit), and resolves with the results in index order.
21
+ async function runLimited({ count, limit, run }) {
22
+ if (type.isUndefined(limit) || limit >= count) {
23
+ return Promise.all(Array.from({
24
+ length: count
25
+ }, (_, index)=>run(index)));
26
+ }
27
+ const results = new Array(count);
28
+ let next = 0;
29
+ async function lane() {
30
+ while(next < count){
31
+ const index = next;
32
+ next += 1;
33
+ results[index] = await run(index);
34
+ }
35
+ }
36
+ await Promise.all(Array.from({
37
+ length: limit
38
+ }, ()=>lane()));
39
+ return results;
40
+ }
17
41
  async function controlParallelFor(context, routineContext, { control }) {
18
- const { endpointId, logger, evaluateOperators } = context;
42
+ const { endpointId, logger } = context;
19
43
  const { items } = routineContext;
20
44
  const itemName = control[':parallel_for'];
21
45
  if (!itemName) {
22
46
  throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing variable name in :parallel_for.`);
23
47
  }
24
- const array = evaluateOperators({
48
+ const array = evaluateRoutineOperators(context, routineContext, {
25
49
  input: control[':in'],
26
- items,
27
- location: control['~k'] ?? ':parallel_for',
28
- payload: routineContext.payload,
29
- state: routineContext.state,
30
- steps: routineContext.steps
50
+ location: control['~k'] ?? ':parallel_for'
31
51
  });
32
52
  logger.debug({
33
53
  event: 'debug_control_parallel',
@@ -43,29 +63,45 @@ async function controlParallelFor(context, routineContext, { control }) {
43
63
  if (!control[':do']) {
44
64
  throw new Error(`Invalid :parallel_for in endpoint "${endpointId}" - missing :do.`);
45
65
  }
46
- const promises = array.map((item, index)=>{
47
- const updatedItems = {
48
- ...items,
49
- [itemName]: item
50
- };
51
- logger.debug({
52
- event: 'debug_control_parallel_iteration',
53
- itemName: itemName,
54
- value: item,
55
- items: updatedItems
56
- });
57
- return runRoutine(context, {
58
- ...routineContext,
59
- arrayIndices: [
60
- ...routineContext.arrayIndices,
61
- index
62
- ],
63
- items: updatedItems
64
- }, {
65
- routine: control[':do']
66
+ const concurrency = evaluateRoutineOperators(context, routineContext, {
67
+ input: control[':concurrency'],
68
+ location: control['~k'] ?? ':parallel_for'
69
+ });
70
+ if (!type.isUndefined(concurrency) && (!type.isInt(concurrency) || concurrency < 1)) {
71
+ throw new ConfigError(`Invalid :parallel_for in endpoint "${endpointId}" - :concurrency must be a positive integer.`, {
72
+ received: concurrency,
73
+ configKey: control['~k']
66
74
  });
75
+ }
76
+ // Every item runs, whatever an earlier one returned: :concurrency only limits how many run at
77
+ // once, so the result is the same with or without it.
78
+ const results = await runLimited({
79
+ count: array.length,
80
+ limit: concurrency,
81
+ run: (index)=>{
82
+ const item = array[index];
83
+ const updatedItems = {
84
+ ...items,
85
+ [itemName]: item
86
+ };
87
+ logger.debug({
88
+ event: 'debug_control_parallel_iteration',
89
+ itemName: itemName,
90
+ value: item,
91
+ items: updatedItems
92
+ });
93
+ return runRoutine(context, {
94
+ ...routineContext,
95
+ arrayIndices: [
96
+ ...routineContext.arrayIndices,
97
+ index
98
+ ],
99
+ items: updatedItems
100
+ }, {
101
+ routine: control[':do']
102
+ });
103
+ }
67
104
  });
68
- const results = await Promise.all(promises);
69
105
  const resultsMap = {
70
106
  error: [],
71
107
  reject: [],
@@ -12,37 +12,57 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { UserError } from '@lowdefy/errors';
15
+ */ import { ConfigError, UserError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import createWireProjection from '../../../response/createWireProjection.js';
18
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
19
  async function controlReject(context, routineContext, { control }) {
17
- const { evaluateOperators } = context;
18
- const { items } = routineContext;
19
20
  const location = control['~k'] ?? ':reject';
20
- const message = evaluateOperators({
21
+ const message = evaluateRoutineOperators(context, routineContext, {
21
22
  input: control[':reject'],
22
- items,
23
- location,
24
- payload: routineContext.payload,
25
- state: routineContext.state,
26
- steps: routineContext.steps
23
+ location
27
24
  });
28
- const cause = evaluateOperators({
25
+ const cause = evaluateRoutineOperators(context, routineContext, {
29
26
  input: control[':cause'],
30
- items,
31
- location,
32
- payload: routineContext.payload,
33
- state: routineContext.state,
34
- steps: routineContext.steps
27
+ location
35
28
  });
36
- const error = new UserError(message, {
29
+ // A reject is the author telling the user something, so it stays a UserError, whose message the
30
+ // wire passes through as written. An Error given as the message is reduced to what the wire
31
+ // would show for it - the author's text for a UserError, the generic message for a plugin error
32
+ // - rather than stringified with its library text; `{ _error: message }` opts into the real text.
33
+ const text = type.isError(message) ? createWireProjection(context)(message).message : message;
34
+ const error = new UserError(text, {
37
35
  cause,
38
36
  isReject: true
39
37
  });
38
+ // :status and :body set the HTTP answer of the webhook whose routine this reject ends
39
+ // (createWebhookAnswer). The build allows them only where a webhook can answer with them.
40
+ if (':status' in control) {
41
+ const status = evaluateRoutineOperators(context, routineContext, {
42
+ input: control[':status'],
43
+ location
44
+ });
45
+ if (!type.isInt(status) || status < 400 || status > 499) {
46
+ throw new ConfigError(':status in :reject must be an integer from 400 to 499.', {
47
+ received: status,
48
+ configKey: control['~k']
49
+ });
50
+ }
51
+ error.webhookStatus = status;
52
+ }
53
+ if (':body' in control) {
54
+ error.webhookBody = evaluateRoutineOperators(context, routineContext, {
55
+ input: control[':body'],
56
+ location
57
+ });
58
+ }
40
59
  // Log under `err` — see controlThrow: only the `err` key runs the pino error
41
60
  // serializer, so `error` would drop the message from the log line.
42
61
  context.logger.warn({
43
62
  event: 'warn_control_reject',
44
63
  err: error
45
64
  });
65
+ error.handled = true;
46
66
  return {
47
67
  status: 'reject',
48
68
  error
@@ -12,21 +12,44 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ async function controlReturn(context, routineContext, { control }) {
16
- const { evaluateOperators } = context;
17
- const { items } = routineContext;
18
- const response = evaluateOperators({
15
+ */ import { ConfigError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import checkLiteralContent from '../../page/dynamic/checkLiteralContent.js';
18
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
19
+ async function controlReturn(context, routineContext, { control }) {
20
+ const literalData = routineContext.literalData ?? null;
21
+ const response = evaluateRoutineOperators(context, routineContext, {
19
22
  input: control[':return'],
20
- items,
21
- location: control['~k'] ?? ':return',
22
- payload: routineContext.payload,
23
- state: routineContext.state,
24
- steps: routineContext.steps
23
+ literalData,
24
+ location: control['~k'] ?? ':return'
25
25
  });
26
+ // The :return of the endpoint a Dynamic block calls becomes page config.
27
+ if (literalData !== null) {
28
+ checkLiteralContent({
29
+ blocks: response?.blocks,
30
+ configKey: control['~k'],
31
+ literalData
32
+ });
33
+ }
26
34
  context.logger.debug({
27
35
  event: 'debug_control_return',
28
36
  response
29
37
  });
38
+ // :content_type sends a webhook's answer as text (createWebhookAnswer). The build allows it only
39
+ // in a webhook endpoint, and only as text/plain.
40
+ if (':content_type' in control) {
41
+ if (!type.isString(response)) {
42
+ throw new ConfigError(':return with :content_type text/plain must evaluate to a string.', {
43
+ received: response,
44
+ configKey: control['~k']
45
+ });
46
+ }
47
+ return {
48
+ status: 'return',
49
+ response,
50
+ contentType: control[':content_type']
51
+ };
52
+ }
30
53
  return {
31
54
  status: 'return',
32
55
  response
@@ -14,16 +14,12 @@
14
14
  limitations under the License.
15
15
  */ import { ConfigError } from '@lowdefy/errors';
16
16
  import { ReservedKeyError, set } from '@lowdefy/helpers';
17
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
17
18
  function controlSetState(context, routineContext, { control }) {
18
- const { logger, evaluateOperators } = context;
19
- const { items } = routineContext;
20
- const evaluatedSetState = evaluateOperators({
19
+ const { logger } = context;
20
+ const evaluatedSetState = evaluateRoutineOperators(context, routineContext, {
21
21
  input: control[':set_state'],
22
- items,
23
- location: control['~k'] ?? ':set_state',
24
- payload: routineContext.payload,
25
- state: routineContext.state,
26
- steps: routineContext.steps
22
+ location: control['~k'] ?? ':set_state'
27
23
  });
28
24
  logger.debug({
29
25
  event: 'debug_control_set_state',
@@ -13,21 +13,17 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import runRoutine from '../runRoutine.js';
16
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
17
  async function controlSwitch(context, routineContext, { control }) {
17
- const { endpointId, logger, evaluateOperators } = context;
18
- const { items } = routineContext;
18
+ const { endpointId, logger } = context;
19
19
  const cases = control[':switch'];
20
20
  logger.debug({
21
21
  event: 'debug_control_switch'
22
22
  });
23
23
  for (const caseObj of cases){
24
- const evaluatedCase = evaluateOperators({
24
+ const evaluatedCase = evaluateRoutineOperators(context, routineContext, {
25
25
  input: caseObj[':case'],
26
- items,
27
- location: caseObj['~k'] ?? control['~k'] ?? ':switch',
28
- payload: routineContext.payload,
29
- state: routineContext.state,
30
- steps: routineContext.steps
26
+ location: caseObj['~k'] ?? control['~k'] ?? ':switch'
31
27
  });
32
28
  logger.debug({
33
29
  event: 'debug_control_switch_case',
@@ -13,36 +13,35 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { UserError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
17
+ import evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
18
  async function controlThrow(context, routineContext, { control }) {
17
- const { evaluateOperators } = context;
18
- const { items } = routineContext;
19
19
  const location = control['~k'] ?? ':throw';
20
- const message = evaluateOperators({
20
+ const message = evaluateRoutineOperators(context, routineContext, {
21
21
  input: control[':throw'],
22
- items,
23
- location,
24
- payload: routineContext.payload,
25
- state: routineContext.state,
26
- steps: routineContext.steps
27
- });
28
- const cause = evaluateOperators({
29
- input: control[':cause'],
30
- items,
31
- location,
32
- payload: routineContext.payload,
33
- state: routineContext.state,
34
- steps: routineContext.steps
35
- });
36
- const error = new UserError(message, {
37
- cause
22
+ location
38
23
  });
24
+ // An Error, such as a rethrown `_error`, goes on unchanged. Wrapped in a UserError it would be
25
+ // stringified into the message, which the wire sends as author text; under its own class the
26
+ // wire makes it generic unless it was a UserError. It carries its own cause, so :cause is unused.
27
+ let error = message;
28
+ if (!type.isError(message)) {
29
+ const cause = evaluateRoutineOperators(context, routineContext, {
30
+ input: control[':cause'],
31
+ location
32
+ });
33
+ error = new UserError(message, {
34
+ cause
35
+ });
36
+ }
39
37
  // Log under `err` — the pino error serializer (createNodeLogger) is registered
40
38
  // for the `err` key only; an Error passed as `error` is JSON-dumped without its
41
39
  // non-enumerable `message`/`stack`, producing a log line with no message.
42
- context.logger.error({
43
- event: 'error_control_throw',
40
+ context.logger.warn({
41
+ event: 'warn_control_throw',
44
42
  err: error
45
43
  });
44
+ error.handled = true;
46
45
  return {
47
46
  status: 'error',
48
47
  error
@@ -12,23 +12,42 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import runRoutine from '../runRoutine.js';
15
+ */ import { projectCaughtError } from '@lowdefy/helpers';
16
+ import runRoutine from '../runRoutine.js';
16
17
  async function controlTry(context, routineContext, { control }) {
17
18
  context.logger.debug({
18
19
  event: 'debug_control_try'
19
20
  });
20
- let res = await runRoutine(context, routineContext, {
21
+ // With a :catch, an error in :try is handled here: `caught` makes runRoutine log an expected
22
+ // error (RequestError, ServiceError, UserError) at debug instead of as an error (nested
23
+ // controls and endpoint calls inherit it). Config, operator and internal errors are still
24
+ // reported through handleError. :catch and :finally run outside it, so their own errors are
25
+ // logged as usual.
26
+ const tryContext = control[':catch'] ? {
27
+ ...routineContext,
28
+ caught: true
29
+ } : routineContext;
30
+ let res = await runRoutine(context, tryContext, {
21
31
  routine: control[':try']
22
32
  });
23
- if (res.status === 'error') {
24
- if (control[':catch']) {
25
- context.logger.debug({
26
- event: 'debug_control_catch'
27
- });
28
- res = await runRoutine(context, routineContext, {
29
- routine: control[':catch']
30
- });
31
- }
33
+ if (res.status === 'error' && control[':catch']) {
34
+ context.logger.debug({
35
+ event: 'debug_control_catch'
36
+ });
37
+ // A child context rather than a field set on routineContext: the same object is handed to
38
+ // :try, :finally and every :parallel branch, so writing to it would let an inner :try clobber
39
+ // the outer catch's error and parallel branches read each other's. steps and state are still
40
+ // shared because routines mutate them in place. The projection is built once here, never the
41
+ // raw error, so no operator in the catch can read its received value or source.
42
+ const error = projectCaughtError(res.error, {
43
+ scrub: context.scrubSecrets
44
+ });
45
+ res = await runRoutine(context, {
46
+ ...routineContext,
47
+ error
48
+ }, {
49
+ routine: control[':catch']
50
+ });
32
51
  }
33
52
  if (control[':finally']) {
34
53
  context.logger.debug({
@@ -0,0 +1,55 @@
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 evaluateRoutineOperators from '../evaluateRoutineOperators.js';
16
+ import runRoutine from '../runRoutine.js';
17
+ async function controlWhile(context, routineContext, { control }) {
18
+ const { endpointId, logger } = context;
19
+ if (!control[':do']) {
20
+ throw new Error(`Invalid :while in endpoint "${endpointId}" - missing :do.`);
21
+ }
22
+ // No array index is pushed onto routineContext.arrayIndices. A :while has no item to
23
+ // index, so each iteration overwrites the previous iteration's step results, and
24
+ // `_step: my_step` reads the latest iteration's value. There is no iteration cap.
25
+ let iteration = 0;
26
+ while(true){
27
+ // The condition is evaluated fresh every iteration, so it sees the state and step
28
+ // results the body wrote. Hoisting it out of the loop makes the loop infinite.
29
+ const evaluated = evaluateRoutineOperators(context, routineContext, {
30
+ input: control[':while'],
31
+ location: control['~k'] ?? ':while'
32
+ });
33
+ logger.debug({
34
+ event: 'debug_control_while',
35
+ condition: {
36
+ input: control[':while'],
37
+ evaluated
38
+ },
39
+ iteration
40
+ });
41
+ if (!evaluated) {
42
+ return {
43
+ status: 'continue'
44
+ };
45
+ }
46
+ const res = await runRoutine(context, routineContext, {
47
+ routine: control[':do']
48
+ });
49
+ if (res?.status != 'continue') {
50
+ return res;
51
+ }
52
+ iteration += 1;
53
+ }
54
+ }
55
+ export default controlWhile;