@lowdefy/api 7.1.0 → 7.3.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 (126) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +99 -31
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +172 -98
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/isUserBanned.js +28 -0
  21. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  22. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  23. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  24. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  25. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  26. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  27. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  28. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  29. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  30. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  31. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  33. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  34. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  35. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  36. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  37. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  38. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  39. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  40. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  41. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  42. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  43. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  44. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  45. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
  46. package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
  47. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
  48. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  49. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  50. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
  51. package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
  52. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  53. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  54. package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
  55. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  56. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  57. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  58. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  59. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  60. package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
  61. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  62. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  63. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  64. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  65. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  66. package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
  67. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  68. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  69. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  70. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  71. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  72. package/dist/routes/auth/runReportingFaults.js +32 -0
  73. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  74. package/dist/routes/endpoints/callEndpoint.js +6 -3
  75. package/dist/routes/endpoints/control/controlFor.js +9 -6
  76. package/dist/routes/endpoints/control/controlIf.js +8 -3
  77. package/dist/routes/endpoints/control/controlLog.js +3 -1
  78. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  79. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  80. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  81. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  82. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  83. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  84. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  85. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  86. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  87. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  88. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  89. package/dist/routes/endpoints/handleRequest.js +3 -2
  90. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  91. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  92. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  93. package/dist/routes/endpoints/runRoutine.js +5 -5
  94. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  95. package/dist/routes/endpoints/test/runTest.js +30 -11
  96. package/dist/routes/mcp/createMcpServer.js +2 -7
  97. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  98. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  99. package/dist/routes/mobile/createAssetLinks.js +38 -0
  100. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  101. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  102. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  103. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  104. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  105. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  106. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  107. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  108. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  109. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  110. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  111. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  112. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  113. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  114. package/dist/routes/page/getPageConfig.js +25 -1
  115. package/dist/routes/request/callRequestResolver.js +29 -36
  116. package/dist/routes/request/stampTypedError.js +37 -0
  117. package/dist/routes/request/summarisedError.js +62 -0
  118. package/dist/routes/request/wrapResolverError.js +61 -0
  119. package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
  120. package/dist/routes/websocket/createChannelRegistry.js +62 -17
  121. package/dist/routes/websocket/createWebSocketConnection.js +59 -21
  122. package/dist/routes/websocket/prepareChannel.js +11 -0
  123. package/dist/test/createMemoryAuth.js +125 -0
  124. package/package.json +20 -22
  125. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  126. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -12,16 +12,18 @@
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
- */ // Run work after the response is sent. Platforms that reap the invocation once
15
+ */ import { isExpectedError } from '@lowdefy/errors';
16
+ // Run work after the response is sent. Platforms that reap the invocation once
16
17
  // the response is flushed (Vercel fluid compute) inject context.waitUntil in
17
18
  // their server's apiContext middleware to keep the invocation alive until the
18
19
  // promise settles (bounded by the function's maxDuration); locally /
19
20
  // self-hosted there is no waitUntil and the promise simply runs detached on
20
21
  // the still-alive Node process.
21
22
  //
22
- // The outcome only exists in logs — completion and failure are logged through
23
- // the request logger so they reach the platform log stream (and any log
24
- // drains); a background failure must never surface as an unhandled rejection.
23
+ // The outcome only exists in logs - completion is logged through the request logger so it
24
+ // reaches the platform log stream (and any log drains). A failure is logged like a failure in
25
+ // the request: an expected outcome as a warning, a fault through handleError, so it carries its
26
+ // config location and reaches error tracking. It must never surface as an unhandled rejection.
25
27
  function scheduleBackground(context, { event, endpointId }, fn) {
26
28
  const { logger } = context;
27
29
  const promise = (async ()=>{
@@ -33,9 +35,7 @@ function scheduleBackground(context, { event, endpointId }, fn) {
33
35
  status: result?.status
34
36
  });
35
37
  } catch (err) {
36
- // A UserError is the caller's mistake, not a fault: warn level, as on
37
- // every other call path.
38
- if (err.name === 'UserError') {
38
+ if (isExpectedError(err)) {
39
39
  logger.warn({
40
40
  event: `${event}_failed`,
41
41
  endpointId,
@@ -43,11 +43,13 @@ function scheduleBackground(context, { event, endpointId }, fn) {
43
43
  }, err.message);
44
44
  return;
45
45
  }
46
- logger.error({
46
+ logger.info({
47
47
  event: `${event}_failed`,
48
- endpointId,
49
- err
50
- }, err.message);
48
+ endpointId
49
+ });
50
+ if (err?.handled !== true) {
51
+ await context.handleError(err);
52
+ }
51
53
  }
52
54
  })();
53
55
  if (context.waitUntil) {
@@ -12,7 +12,7 @@
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 { jest } from '@jest/globals';
15
+ */ import { vi } from 'vitest';
16
16
  import { wait } from '@lowdefy/helpers';
17
17
  import { operatorsServer } from '@lowdefy/operators-js';
18
18
  import createEvaluateOperators from '../../../context/createEvaluateOperators.js';
@@ -39,30 +39,44 @@ const defaultReadConfigImp = ({ connectionConfig = {
39
39
  }
40
40
  return null;
41
41
  };
42
- const mockReadConfigFile = jest.fn().mockImplementation(defaultReadConfigImp());
43
- const mockTestRequest = jest.fn((request)=>{
42
+ const mockReadConfigFile = vi.fn().mockImplementation(defaultReadConfigImp());
43
+ const mockTestRequest = vi.fn((request)=>{
44
44
  return request.request.response;
45
45
  });
46
- const mockTestRequestError = jest.fn((request)=>{
46
+ const mockTestRequestError = vi.fn((request)=>{
47
47
  throw new Error(request.request.message);
48
48
  });
49
- const mockTestRequestWait = jest.fn((request)=>wait(request.request.ms));
49
+ const mockTestRequestWait = vi.fn((request)=>wait(request.request.ms));
50
50
  // Waits `ms` and records how many of these requests were in flight at once (inFlight.max).
51
51
  const inFlight = {
52
52
  current: 0,
53
53
  max: 0
54
54
  };
55
- const mockTestRequestInFlight = jest.fn(async (request)=>{
55
+ const mockTestRequestInFlight = vi.fn(async (request)=>{
56
56
  inFlight.current += 1;
57
57
  inFlight.max = Math.max(inFlight.max, inFlight.current);
58
58
  await wait(request.request.ms);
59
59
  inFlight.current -= 1;
60
60
  return request.request.response;
61
61
  });
62
+ // Fails as a MongoDB write fails schema validation: the driver's error carries the document it
63
+ // rejected.
64
+ const mockTestRequestRejectDocument = vi.fn((request)=>{
65
+ const error = new Error('Document failed validation');
66
+ error.name = 'MongoServerError';
67
+ error.code = 121;
68
+ error.errInfo = {
69
+ details: {
70
+ document: request.request.document
71
+ }
72
+ };
73
+ throw error;
74
+ });
62
75
  mockTestRequest.schema = {};
63
76
  mockTestRequestError.schema = {};
64
77
  mockTestRequestWait.schema = {};
65
78
  mockTestRequestInFlight.schema = {};
79
+ mockTestRequestRejectDocument.schema = {};
66
80
  mockTestRequest.meta = {
67
81
  checkRead: false,
68
82
  checkWrite: false
@@ -79,6 +93,10 @@ mockTestRequestInFlight.meta = {
79
93
  checkRead: false,
80
94
  checkWrite: false
81
95
  };
96
+ mockTestRequestRejectDocument.meta = {
97
+ checkRead: false,
98
+ checkWrite: false
99
+ };
82
100
  const connections = {
83
101
  TestConnection: {
84
102
  schema: {},
@@ -86,16 +104,17 @@ const connections = {
86
104
  TestRequest: mockTestRequest,
87
105
  TestRequestError: mockTestRequestError,
88
106
  TestRequestWait: mockTestRequestWait,
89
- TestRequestInFlight: mockTestRequestInFlight
107
+ TestRequestInFlight: mockTestRequestInFlight,
108
+ TestRequestRejectDocument: mockTestRequestRejectDocument
90
109
  }
91
110
  }
92
111
  };
93
112
  const logger = {
94
- debug: jest.fn(),
95
- info: jest.fn(),
96
- warn: jest.fn(),
113
+ debug: vi.fn(),
114
+ info: vi.fn(),
115
+ warn: vi.fn(),
97
116
  // error: console.error,
98
- error: jest.fn()
117
+ error: vi.fn()
99
118
  };
100
119
  function createTextContext({ user = {
101
120
  id: 'id',
@@ -15,6 +15,7 @@
15
15
  */ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
16
16
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
17
  import { cleanBuildArtifact, serializer, type } from '@lowdefy/helpers';
18
+ import { isExpectedError } from '@lowdefy/errors';
18
19
  import formatErrorForAgent from '../../response/formatErrorForAgent.js';
19
20
  import callEndpoint from '../endpoints/callEndpoint.js';
20
21
  import runAfterToolCall from './runAfterToolCall.js';
@@ -211,13 +212,7 @@ async function createMcpServer({ context }) {
211
212
  // model needs to retry, not a structured error log. Everything else
212
213
  // goes through the server's error sink, which resolves the config
213
214
  // source, logs it and collects it for the dev feedback channel.
214
- if ([
215
- 'AuthenticationError',
216
- 'AuthorizationError',
217
- 'TwoFactorEnrolmentRequiredError'
218
- ].includes(error.name)) {
219
- context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
220
- } else if (error.name === 'UserError') {
215
+ if (isExpectedError(error)) {
221
216
  context.logger.warn(`Refused MCP tool call: ${name} - ${error.message}`);
222
217
  } else {
223
218
  await context.handleError(error);
@@ -12,11 +12,14 @@
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 invokeEndpoint from '../endpoints/invokeEndpoint.js';
15
+ */ import { isExpectedError } from '@lowdefy/errors';
16
+ import invokeEndpoint from '../endpoints/invokeEndpoint.js';
16
17
  // Runs the app's mcp.afterToolCall endpoint as the tool's caller, after the
17
18
  // reply to the agent is built. The hook observes the call; it can never change
18
- // the reply, so every failure (a refused caller, a payload its schema rejects,
19
- // a routine that errors or rejects) ends as one warning and nothing else.
19
+ // the reply, so every failure ends as one warning naming the hook and the tool.
20
+ // A fault the routine did not reach (a missing endpoint, a payload its schema
21
+ // rejects) is also reported through handleError, like any other fault; the
22
+ // routine's own faults already were, by runRoutine.
20
23
  // Awaited by the caller rather than left running: a serverless platform may
21
24
  // reap the invocation once the response is sent.
22
25
  async function runAfterToolCall(context, { hookId, payload }) {
@@ -45,6 +48,9 @@ async function runAfterToolCall(context, { hookId, payload }) {
45
48
  tool: payload.tool,
46
49
  err: error
47
50
  }, `MCP afterToolCall hook "${hookId}" failed after tool "${payload.tool}": ${error.message}`);
51
+ if (!isExpectedError(error) && error?.handled !== true) {
52
+ await context.handleError(error);
53
+ }
48
54
  }
49
55
  }
50
56
  export default runAfterToolCall;
@@ -0,0 +1,51 @@
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
+ // The apple-app-site-association document that lets the app's iOS shells open
17
+ // its links (universal links), built from mobile.shells in mobile/config.json.
18
+ // A shell needs both a team id and a bundle id to be named here.
19
+ //
20
+ // Every page path under basePath opens in the shell, not only the mobile
21
+ // pages: listing those paths in a public file would tell a signed-out visitor
22
+ // which pages exist. A shell asked for a web page gets the surface gate's
23
+ // 404 { surface: 'web' } and opens it in the browser. API routes, auth
24
+ // callbacks among them, always reach the server.
25
+ //
26
+ // Returns null when no shell takes iOS links.
27
+ function createAppleAppSiteAssociation({ mobileConfig, basePath }) {
28
+ const appIDs = (mobileConfig.shells ?? []).filter((shell)=>type.isString(shell.ios?.teamId) && type.isString(shell.ios?.bundleId)).map((shell)=>`${shell.ios.teamId}.${shell.ios.bundleId}`);
29
+ if (appIDs.length === 0) {
30
+ return null;
31
+ }
32
+ return {
33
+ applinks: {
34
+ details: [
35
+ {
36
+ appIDs,
37
+ components: [
38
+ {
39
+ '/': `${basePath}/api/*`,
40
+ exclude: true
41
+ },
42
+ {
43
+ '/': `${basePath}/*`
44
+ }
45
+ ]
46
+ }
47
+ ]
48
+ }
49
+ };
50
+ }
51
+ export default createAppleAppSiteAssociation;
@@ -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
+ */ import { type } from '@lowdefy/helpers';
16
+ // The Digital Asset Links statement that lets the app's Android shells open
17
+ // its links (app links), built from mobile.shells in mobile/config.json. A
18
+ // shell needs a package name and at least one signing certificate fingerprint
19
+ // to be named here. Android filters link paths in the shell's manifest.
20
+ //
21
+ // Returns null when no shell takes Android links.
22
+ function createAssetLinks({ mobileConfig }) {
23
+ const statements = (mobileConfig.shells ?? []).filter((shell)=>type.isString(shell.android?.package) && shell.android.sha256?.length > 0).map((shell)=>({
24
+ relation: [
25
+ 'delegate_permission/common.handle_all_urls'
26
+ ],
27
+ target: {
28
+ namespace: 'android_app',
29
+ package_name: shell.android.package,
30
+ sha256_cert_fingerprints: shell.android.sha256
31
+ }
32
+ }));
33
+ if (statements.length === 0) {
34
+ return null;
35
+ }
36
+ return statements;
37
+ }
38
+ export default createAssetLinks;
@@ -0,0 +1,31 @@
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
+ */ // The mobile frame with the items this caller may open. A stack frame has no
16
+ // items. A mobile menu item carries no auth of its own: it shows when the
17
+ // caller may open its page.
18
+ function filterMobileMenus({ menus, openablePageIds }) {
19
+ if (menus.stack === true) {
20
+ return menus;
21
+ }
22
+ if (menus.tabs) {
23
+ return {
24
+ tabs: menus.tabs.filter((item)=>openablePageIds.has(item.pageId))
25
+ };
26
+ }
27
+ return {
28
+ drawer: menus.drawer.filter((item)=>openablePageIds.has(item.pageId))
29
+ };
30
+ }
31
+ export default filterMobileMenus;
@@ -0,0 +1,23 @@
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 } from '@lowdefy/helpers';
16
+ // mobile.events, the app events a shell runs in place of the web app's events.
17
+ // Serialized like the web's (getAppEvents): their ~k markers reach the shell so
18
+ // app event errors resolve to their config.
19
+ async function getMobileAppEvents({ readConfigFile }) {
20
+ const events = await readConfigFile('mobile/events.json');
21
+ return serializer.serialize(events);
22
+ }
23
+ export default getMobileAppEvents;
@@ -0,0 +1,109 @@
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 filterMobileMenus from './filterMobileMenus.js';
17
+ import getLowdefyGlobal from '../rootConfig/getLowdefyGlobal.js';
18
+ import getLowdefyI18n from '../rootConfig/getLowdefyI18n.js';
19
+ import getMobileAppEvents from './getMobileAppEvents.js';
20
+ import getOpenablePageIds from './getOpenablePageIds.js';
21
+ function getShellAuth({ auth, config }) {
22
+ if (type.isNone(auth)) {
23
+ return null;
24
+ }
25
+ const { emailCode, unlock, unlockAfter, sharedDevice } = config.auth;
26
+ return {
27
+ emailCode,
28
+ unlock,
29
+ unlockAfter,
30
+ sharedDevice
31
+ };
32
+ }
33
+ // What a shell syncs on start: the mobile frame, the index of the pages this
34
+ // caller may open with each page's hash and typesKey, the type set of each of
35
+ // those keys, minShellVersion, the theme ({ darkMode, light, dark }, antd's
36
+ // computed tokens per mode) and the Tailwind class map. Menu icons carry their
37
+ // node data.
38
+ //
39
+ // The app's identity (lowdefyApp, with the buildId a shell stamps its page
40
+ // requests with), its global and its i18n are what a shell's engine starts
41
+ // from, as the web root config gives them. Its app events are mobile.events,
42
+ // not the web app's events, which may use web-only actions. Their _js comes as
43
+ // _jsEntries, module text a shell evaluates, as a mobile page's does.
44
+ //
45
+ // The dev build writes the page index without hashes or typesKeys, and no type
46
+ // sets: the dev server builds pages on demand. Its class map holds the classes
47
+ // of the pages the skeleton build compiles; a page built on request carries
48
+ // its own classes' entries.
49
+ //
50
+ // auth is the mobile.auth a shell signs in and locks by (emailCode, unlock,
51
+ // unlockAfter, sharedDevice), or null for an app without auth, which a shell
52
+ // opens with no sign-in screen. sessionExpiresIn is the server's alone.
53
+ //
54
+ // notifications, share, widgets, shortcuts and background drive the shell's
55
+ // native features: push registration endpoints and notification categories,
56
+ // the share page, widget sources, icon quick actions and background fetch.
57
+ //
58
+ // Returns null for an app without a mobile key: no shell opens it.
59
+ async function getMobileRootConfig(context) {
60
+ const [config, pageIndex, typeSets, theme, classMap, appJs, openablePageIds, events, lowdefyGlobal, i18n] = await Promise.all([
61
+ context.readConfigFile('mobile/config.json'),
62
+ context.readConfigFile('mobile/pageIndex.json'),
63
+ context.readConfigFile('mobile/typeSets.json'),
64
+ context.readConfigFile('mobile/theme.json'),
65
+ context.readConfigFile('mobile/classMap.json'),
66
+ context.readConfigFile('mobile/appJs.json'),
67
+ getOpenablePageIds(context),
68
+ getMobileAppEvents(context),
69
+ getLowdefyGlobal(context),
70
+ getLowdefyI18n(context)
71
+ ]);
72
+ if (Object.keys(config).length === 0) {
73
+ return null;
74
+ }
75
+ const openablePageIndex = pageIndex.filter((entry)=>openablePageIds.has(entry.pageId));
76
+ const openableTypeSets = {};
77
+ openablePageIndex.forEach((entry)=>{
78
+ if (typeSets[entry.typesKey]) {
79
+ openableTypeSets[entry.typesKey] = typeSets[entry.typesKey];
80
+ }
81
+ });
82
+ return {
83
+ _jsEntries: appJs.jsEntries,
84
+ auth: getShellAuth({
85
+ auth: context.auth,
86
+ config
87
+ }),
88
+ events,
89
+ homePageId: config.homePageId,
90
+ i18n,
91
+ lowdefyApp: context.appMeta,
92
+ lowdefyGlobal,
93
+ minShellVersion: config.minShellVersion,
94
+ menus: filterMobileMenus({
95
+ menus: config.menus,
96
+ openablePageIds
97
+ }),
98
+ pageIndex: openablePageIndex,
99
+ typeSets: openableTypeSets,
100
+ theme,
101
+ classMap,
102
+ notifications: config.notifications,
103
+ share: config.share,
104
+ widgets: config.widgets,
105
+ shortcuts: config.shortcuts,
106
+ background: config.background
107
+ };
108
+ }
109
+ export default getMobileRootConfig;
@@ -0,0 +1,21 @@
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
+ */ // The ids of the pages this caller may open, filtered as getPagePaths and the
16
+ // web menus are: only a "deny" outcome hides a page.
17
+ async function getOpenablePageIds(context) {
18
+ const routes = await context.readConfigFile('routes.json');
19
+ return new Set(routes.filter((route)=>context.authorizeOutcome(route) !== 'deny').map((route)=>route.pageId));
20
+ }
21
+ export default getOpenablePageIds;
@@ -16,6 +16,7 @@
16
16
  import { getPossibleOperators } from '@lowdefy/operators';
17
17
  import checkValue from './checkValue.js';
18
18
  import isUnderState from './isUnderState.js';
19
+ import overlapsStatePath from './overlapsStatePath.js';
19
20
  function isLiteralObject({ value, walk }) {
20
21
  return type.isObject(value) && getPossibleOperators({
21
22
  value,
@@ -156,6 +157,59 @@ function checkSetState({ params, path, walk }) {
156
157
  }
157
158
  });
158
159
  }
160
+ // A CallAPI's params are sent to the server and an action's skip is read as a
161
+ // condition, so a _state read in them draws nothing.
162
+ function checkActionValue({ action, path, walk }) {
163
+ Object.keys(action).forEach((key)=>{
164
+ if (key.startsWith('~')) return;
165
+ const undrawn = key === 'skip' || key === 'params' && action.type === 'CallAPI';
166
+ checkValue({
167
+ value: action[key],
168
+ key,
169
+ path: `${path}.${key}`,
170
+ walk: undrawn ? {
171
+ ...walk,
172
+ undrawn: true
173
+ } : walk
174
+ });
175
+ });
176
+ }
177
+ // SetState values under the policy's state are data: the page around the
178
+ // Dynamic block owns that state and treats it as input, and no block property
179
+ // can read it back (properties are literal), so only the operator rules apply.
180
+ // A content _state read that would draw a data key is refused at the end of
181
+ // the walk (checkPolicy). Without a state path the content may write any page
182
+ // state, which the page may draw, so every value keeps every check. So does a
183
+ // value bound to a content input whose value is an object (walk.objectValueIds:
184
+ // a rich text editor, an upload, a table input), which draws it as markup,
185
+ // links or images. checkSetState has judged the keys.
186
+ function checkSetStateValues({ action, path, walk }) {
187
+ const { params, ...rest } = action;
188
+ checkActionValue({
189
+ action: rest,
190
+ path,
191
+ walk
192
+ });
193
+ Object.keys(params).forEach((key)=>{
194
+ if (key.startsWith('~')) return;
195
+ const isData = !type.isNone(walk.policy.state) && !walk.objectValueIds.some((id)=>overlapsStatePath({
196
+ key,
197
+ id
198
+ }));
199
+ if (isData) {
200
+ walk.dataStateKeys.push(key);
201
+ }
202
+ checkValue({
203
+ value: params[key],
204
+ key,
205
+ path: `${path}.params.${key}`,
206
+ walk: isData ? {
207
+ ...walk,
208
+ isData: true
209
+ } : walk
210
+ });
211
+ });
212
+ }
159
213
  const ACTION_RULES = {
160
214
  CallAPI: checkCallApi,
161
215
  Link: checkLink,
@@ -195,8 +249,19 @@ function checkAction({ action, path, walk }) {
195
249
  path: `${path}.params`,
196
250
  walk
197
251
  });
198
- checkValue({
199
- value: action,
252
+ if (action.type === 'SetState' && isLiteralObject({
253
+ value: action.params,
254
+ walk
255
+ })) {
256
+ checkSetStateValues({
257
+ action,
258
+ path,
259
+ walk
260
+ });
261
+ return;
262
+ }
263
+ checkActionValue({
264
+ action,
200
265
  path,
201
266
  walk
202
267
  });
@@ -43,7 +43,10 @@ function checkActionList({ actions, path, walk }) {
43
43
  checkValue({
44
44
  value: item[':if'],
45
45
  path: `${itemPath}.:if`,
46
- walk
46
+ walk: {
47
+ ...walk,
48
+ undrawn: true
49
+ }
47
50
  });
48
51
  count += checkActionList({
49
52
  actions: item[':then'] ?? [],
@@ -71,7 +74,10 @@ function checkActionList({ actions, path, walk }) {
71
74
  checkValue({
72
75
  value: caseObject?.[':case'],
73
76
  path: `${casePath}.:case`,
74
- walk
77
+ walk: {
78
+ ...walk,
79
+ undrawn: true
80
+ }
75
81
  });
76
82
  count += checkActionList({
77
83
  actions: caseObject?.[':then'] ?? [],