@lowdefy/client-core 0.0.0-experimental-20261019052246
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/LICENSE +201 -0
- package/README.md +9 -0
- package/dist/auth/createAuthFetchOptions.js +56 -0
- package/dist/auth/createAuthMethods.js +1070 -0
- package/dist/auth/createPkceChallenge.js +57 -0
- package/dist/auth/endBearerSession.js +26 -0
- package/dist/auth/getAuthorizationHeaders.js +31 -0
- package/dist/auth/validateAuthTransport.js +41 -0
- package/dist/claimCallerReload.js +41 -0
- package/dist/createCallAPI.js +39 -0
- package/dist/createCallRequest.js +34 -0
- package/dist/createHandleError.js +90 -0
- package/dist/createLowdefyCore.js +124 -0
- package/dist/createPageLifecycleManager.js +173 -0
- package/dist/getActiveLocale.js +26 -0
- package/dist/getContextKey.js +29 -0
- package/dist/hasOtherRoles.js +30 -0
- package/dist/index.js +32 -0
- package/dist/isOtherCaller.js +29 -0
- package/dist/recordCallerStamp.js +31 -0
- package/dist/recorder/buildEngineRecord.js +34 -0
- package/dist/recorder/buildInteractionRecord.js +60 -0
- package/dist/recorder/buildTraceEvent.js +62 -0
- package/dist/recorder/chunkRecords.js +78 -0
- package/dist/recorder/collectEventActions.js +22 -0
- package/dist/recorder/collectEventEndpoints.js +39 -0
- package/dist/recorder/collectEventRequests.js +38 -0
- package/dist/recorder/createPairingBuffer.js +177 -0
- package/dist/recorder/createPasswordRedactor.js +64 -0
- package/dist/recorder/createRecordBatcher.js +50 -0
- package/dist/recorder/createRecordingSession.js +60 -0
- package/dist/recorder/diffStateWrites.js +86 -0
- package/dist/recorder/isEventCall.js +26 -0
- package/dist/recorder/jsonType.js +35 -0
- package/dist/recorder/sendRecords.js +39 -0
- package/dist/recorder/toJsonSafe.js +26 -0
- package/dist/request.js +127 -0
- package/dist/setLowdefyUser.js +32 -0
- package/dist/shouldReloadForAuthError.js +39 -0
- package/dist/shouldReloadForBuild.js +45 -0
- package/dist/shouldReloadForCaller.js +50 -0
- package/dist/storage/clearUserStorage.js +36 -0
- package/dist/storage/clearUserStorageOnOwnerChange.js +42 -0
- package/dist/storage/createStorage.js +51 -0
- package/dist/storage/listUserStorageKeys.js +36 -0
- package/dist/storage/userStorageKey.js +24 -0
- package/dist/storage/userStoragePrefix.js +25 -0
- package/dist/test/createMemoryStore.js +40 -0
- package/dist/updateLowdefyPage.js +44 -0
- package/dist/url.js +29 -0
- package/dist/websocket/createWebSocketClient.js +428 -0
- package/package.json +57 -0
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
const BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
17
|
+
// Unpadded base64url (RFC 4648 section 5), written out because neither btoa nor
|
|
18
|
+
// Buffer is on every platform the core runs on.
|
|
19
|
+
function encodeBase64Url(bytes) {
|
|
20
|
+
let encoded = '';
|
|
21
|
+
for(let index = 0; index < bytes.length; index += 3){
|
|
22
|
+
const chunk = bytes[index] << 16 | (bytes[index + 1] ?? 0) << 8 | (bytes[index + 2] ?? 0);
|
|
23
|
+
const characters = Math.min(bytes.length - index, 3) + 1;
|
|
24
|
+
for(let position = 0; position < characters; position += 1){
|
|
25
|
+
encoded += BASE64URL_ALPHABET[chunk >> 18 - position * 6 & 63];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return encoded;
|
|
29
|
+
}
|
|
30
|
+
function encodeAscii(text) {
|
|
31
|
+
return Uint8Array.from(text, (character)=>character.charCodeAt(0));
|
|
32
|
+
}
|
|
33
|
+
// A PKCE pair (RFC 7636, S256) for the sign-in sheet: the code verifier the
|
|
34
|
+
// shell keeps in memory and sends only to exchange the one-time token, and the
|
|
35
|
+
// code challenge that goes in the /auth/mobile URL. Pure: the shell passes the
|
|
36
|
+
// random bytes and its platform's SHA-256 (expo-crypto), so the core needs
|
|
37
|
+
// neither. 32 to 96 bytes make the 43 to 128 character verifier RFC 7636 asks
|
|
38
|
+
// for; a shell sends 64.
|
|
39
|
+
async function createPkceChallenge({ verifierBytes, sha256 }) {
|
|
40
|
+
if (!(verifierBytes instanceof Uint8Array)) {
|
|
41
|
+
throw new Error(`createPkceChallenge verifierBytes must be a Uint8Array. Received ${JSON.stringify(verifierBytes)}.`);
|
|
42
|
+
}
|
|
43
|
+
if (verifierBytes.length < 32 || verifierBytes.length > 96) {
|
|
44
|
+
throw new Error(`createPkceChallenge verifierBytes must be 32 to 96 bytes long. Received ${verifierBytes.length}.`);
|
|
45
|
+
}
|
|
46
|
+
if (!type.isFunction(sha256)) {
|
|
47
|
+
throw new Error('createPkceChallenge sha256 must be a function.');
|
|
48
|
+
}
|
|
49
|
+
const codeVerifier = encodeBase64Url(verifierBytes);
|
|
50
|
+
const digest = await sha256(encodeAscii(codeVerifier));
|
|
51
|
+
return {
|
|
52
|
+
codeVerifier,
|
|
53
|
+
codeChallenge: encodeBase64Url(new Uint8Array(digest)),
|
|
54
|
+
codeChallengeMethod: 'S256'
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export default createPkceChallenge;
|
|
@@ -0,0 +1,26 @@
|
|
|
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 { parseCallerStamp } from '@lowdefy/helpers';
|
|
16
|
+
// The server refused a bearer host's session token with a 401: the session is
|
|
17
|
+
// gone (signed out elsewhere, ended by an admin, expired). The token is
|
|
18
|
+
// forgotten before the host hears of it, so nothing the host does next sends it
|
|
19
|
+
// again. A session token is never refused for a wrong password or code: Better
|
|
20
|
+
// Auth answers those with a 400, and its 401 credential refusals come from
|
|
21
|
+
// sign-in routes, which a shell calls only while it holds no token.
|
|
22
|
+
async function endBearerSession({ host, serverCaller }) {
|
|
23
|
+
await host.tokenStore.clear();
|
|
24
|
+
host.onCallerChanged(parseCallerStamp(serverCaller));
|
|
25
|
+
}
|
|
26
|
+
export default endBearerSession;
|
|
@@ -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
|
+
*/ import { type } from '@lowdefy/helpers';
|
|
16
|
+
// The Authorization header a call carries: the session token for a bearer host
|
|
17
|
+
// that holds one, else none. A cookie host's browser sends the session cookie
|
|
18
|
+
// itself, so its calls carry no header here.
|
|
19
|
+
function getAuthorizationHeaders({ host }) {
|
|
20
|
+
if (host.authTransport !== 'bearer') {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
const token = host.tokenStore.get();
|
|
24
|
+
if (type.isNone(token)) {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
Authorization: `Bearer ${token}`
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export default getAuthorizationHeaders;
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
const TOKEN_STORE_METHODS = [
|
|
17
|
+
'get',
|
|
18
|
+
'set',
|
|
19
|
+
'clear'
|
|
20
|
+
];
|
|
21
|
+
// How the host signs its calls in. A browser host sends the session cookie
|
|
22
|
+
// itself ('cookie', also when the host names none). A native shell has no
|
|
23
|
+
// cookie jar, so it holds the Better Auth session token and sends it as
|
|
24
|
+
// `Authorization: Bearer` ('bearer'), keeping the token in tokenStore:
|
|
25
|
+
// { get() the token held in memory or null, set(token), clear() }. get is
|
|
26
|
+
// synchronous, since a websocket opens synchronously; set and clear may return
|
|
27
|
+
// promises, which the core awaits.
|
|
28
|
+
function validateAuthTransport({ host }) {
|
|
29
|
+
const { authTransport, tokenStore } = host;
|
|
30
|
+
if (type.isUndefined(authTransport) || authTransport === 'cookie') {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (authTransport !== 'bearer') {
|
|
34
|
+
throw new Error(`Lowdefy client host authTransport must be "cookie" or "bearer". Received ${JSON.stringify(authTransport)}.`);
|
|
35
|
+
}
|
|
36
|
+
const missing = TOKEN_STORE_METHODS.filter((method)=>!type.isFunction(tokenStore?.[method]));
|
|
37
|
+
if (missing.length > 0) {
|
|
38
|
+
throw new Error(`Lowdefy client host with authTransport "bearer" needs a tokenStore with ${missing.join(', ')}.`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export default validateAuthTransport;
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
*/ // Session storage key holding when this tab last reloaded to follow its caller.
|
|
16
|
+
const RELOADED_FOR_CALLER_KEY = 'lowdefy.reloadedForCaller';
|
|
17
|
+
const RELOAD_INTERVAL_MS = 10000;
|
|
18
|
+
// True when this tab may reload because its caller changed (another person or
|
|
19
|
+
// organization, or the session ended), and records the reload. A tab reloads
|
|
20
|
+
// at most once per 10 seconds for its caller: if the freshly loaded page still
|
|
21
|
+
// disagrees with the server, reloading again would loop. Callers fail the call
|
|
22
|
+
// instead, so no data shows for the wrong caller either way.
|
|
23
|
+
//
|
|
24
|
+
// sessionStorage is the host's session store (get, set), which lasts as long
|
|
25
|
+
// as the tab.
|
|
26
|
+
function claimCallerReload({ sessionStorage }) {
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
try {
|
|
29
|
+
const last = Number(sessionStorage.get(RELOADED_FOR_CALLER_KEY));
|
|
30
|
+
if (Math.abs(now - last) < RELOAD_INTERVAL_MS) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
sessionStorage.set(RELOADED_FOR_CALLER_KEY, String(now));
|
|
34
|
+
} catch (error) {
|
|
35
|
+
// Browsers with storage disabled throw on sessionStorage access. Without
|
|
36
|
+
// the record the loop guard cannot work, so do not reload.
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
export default claimCallerReload;
|
|
@@ -0,0 +1,39 @@
|
|
|
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 request from './request.js';
|
|
16
|
+
// Endpoint calls from a bearer host (a native shell) carry no build id, so a
|
|
17
|
+
// server build change never refuses them: endpoints are the stable contract a
|
|
18
|
+
// shell's cached pages and its later offline outbox call across builds. Page
|
|
19
|
+
// requests keep the build id on every host.
|
|
20
|
+
function createCallAPI(lowdefy) {
|
|
21
|
+
const { apiBase, buildId } = lowdefy;
|
|
22
|
+
const endpointBuildId = lowdefy._internal.host.authTransport === 'bearer' ? undefined : buildId;
|
|
23
|
+
function callAPI({ payload, endpointId, pageId, blockId }) {
|
|
24
|
+
return request({
|
|
25
|
+
buildId: endpointBuildId,
|
|
26
|
+
url: `${apiBase}/api/endpoints/${endpointId}`,
|
|
27
|
+
method: 'POST',
|
|
28
|
+
body: {
|
|
29
|
+
payload,
|
|
30
|
+
pageId,
|
|
31
|
+
blockId
|
|
32
|
+
},
|
|
33
|
+
reloadOnAuthorizationError: false,
|
|
34
|
+
lowdefy
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return callAPI;
|
|
38
|
+
}
|
|
39
|
+
export default createCallAPI;
|
|
@@ -0,0 +1,34 @@
|
|
|
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 request from './request.js';
|
|
16
|
+
function createCallRequest(lowdefy) {
|
|
17
|
+
const { apiBase, buildId } = lowdefy;
|
|
18
|
+
function callRequest({ actionId, blockId, pageId, payload, requestId }) {
|
|
19
|
+
return request({
|
|
20
|
+
buildId,
|
|
21
|
+
url: `${apiBase}/api/request/${pageId}/${requestId}`,
|
|
22
|
+
method: 'POST',
|
|
23
|
+
body: {
|
|
24
|
+
actionId,
|
|
25
|
+
blockId,
|
|
26
|
+
payload
|
|
27
|
+
},
|
|
28
|
+
reloadOnAuthorizationError: true,
|
|
29
|
+
lowdefy
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return callRequest;
|
|
33
|
+
}
|
|
34
|
+
export default createCallRequest;
|
|
@@ -0,0 +1,90 @@
|
|
|
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 { getDevError } from '@lowdefy/engine';
|
|
16
|
+
import { expectedErrorNames } from '@lowdefy/errors';
|
|
17
|
+
import { serializer } from '@lowdefy/helpers';
|
|
18
|
+
function createHandleError(lowdefy) {
|
|
19
|
+
const loggedErrors = new Set();
|
|
20
|
+
const logger = lowdefy._internal.logger;
|
|
21
|
+
function logError(error) {
|
|
22
|
+
lowdefy._runtimeErrorCallback?.(error);
|
|
23
|
+
logger.error(error);
|
|
24
|
+
}
|
|
25
|
+
return async function handleError(error) {
|
|
26
|
+
// The dev tools show the dev server's full error; every decision below stays on
|
|
27
|
+
// the error config sees. Keying on the shown message means two different dev
|
|
28
|
+
// failures of one action both display. Every server failure carries its own
|
|
29
|
+
// requestId, and prod gives them all one generic message, so the requestId in
|
|
30
|
+
// the key is what lets a later failure - and the ID support asks for - log at
|
|
31
|
+
// all; one failure reaching here twice still logs once.
|
|
32
|
+
const devError = getDevError(error);
|
|
33
|
+
const shown = devError ?? error;
|
|
34
|
+
const errorKey = `${shown.message}:${error.configKey ?? ''}:${error.requestId ?? ''}`;
|
|
35
|
+
if (loggedErrors.has(errorKey)) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
loggedErrors.add(errorKey);
|
|
39
|
+
// An expected outcome - a UserError, or an auth gate's refusal the server
|
|
40
|
+
// already logged as one warning line - logs to the browser console only,
|
|
41
|
+
// never sent to the server or the error bar. Matched by name, not
|
|
42
|
+
// instanceof: plugins bundle their own @lowdefy/errors copy.
|
|
43
|
+
if (expectedErrorNames.has(error?.name)) {
|
|
44
|
+
logger.error(shown);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// Send known error types to server for logging with location resolution
|
|
48
|
+
if (error.isLowdefyError) {
|
|
49
|
+
// The server already logged this one — just display locally. Keyed on
|
|
50
|
+
// `handled`, not on `source`: a LowdefyInternalError is logged server-side
|
|
51
|
+
// but never gets a source (location resolution is skipped for it), so
|
|
52
|
+
// keying on source POSTed it back and had it logged twice.
|
|
53
|
+
if (error.handled) {
|
|
54
|
+
logError(shown);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
// Client-originated errors — send to server for logging + location resolution
|
|
58
|
+
try {
|
|
59
|
+
const serialized = serializer.serialize(error);
|
|
60
|
+
const response = await lowdefy._internal.host.fetch(`${lowdefy.apiBase ?? ''}/api/client-error`, {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: {
|
|
63
|
+
'Content-Type': 'application/json'
|
|
64
|
+
},
|
|
65
|
+
body: JSON.stringify(serialized),
|
|
66
|
+
credentials: 'same-origin'
|
|
67
|
+
});
|
|
68
|
+
if (response.ok) {
|
|
69
|
+
const { source: resolvedSource, configError: serializedConfigError } = await response.json();
|
|
70
|
+
if (resolvedSource) {
|
|
71
|
+
error.source = resolvedSource;
|
|
72
|
+
}
|
|
73
|
+
// If server produced a consolidated ConfigError, log it and return early
|
|
74
|
+
// (cause chain includes original error)
|
|
75
|
+
if (serializedConfigError) {
|
|
76
|
+
logError(serializer.deserialize(serializedConfigError));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
} catch {
|
|
81
|
+
// Server logging failed - continue with local console
|
|
82
|
+
}
|
|
83
|
+
logError(shown);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
// Other errors - just log locally
|
|
87
|
+
logError(shown);
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
export default createHandleError;
|
|
@@ -0,0 +1,124 @@
|
|
|
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 { translate, type } from '@lowdefy/helpers';
|
|
16
|
+
import { createBrowserLogger } from '@lowdefy/logger/browser';
|
|
17
|
+
import createAuthMethods from './auth/createAuthMethods.js';
|
|
18
|
+
import validateAuthTransport from './auth/validateAuthTransport.js';
|
|
19
|
+
import createCallAPI from './createCallAPI.js';
|
|
20
|
+
import createCallRequest from './createCallRequest.js';
|
|
21
|
+
import createHandleError from './createHandleError.js';
|
|
22
|
+
import createStorage from './storage/createStorage.js';
|
|
23
|
+
import createWebSocketClient from './websocket/createWebSocketClient.js';
|
|
24
|
+
// What a renderer gives the core to reach its platform. A store is
|
|
25
|
+
// { get(key), set(key, value), remove(key), keys() }, holding strings; its
|
|
26
|
+
// methods may throw when the platform blocks storage, and the core catches that.
|
|
27
|
+
const HOST_KEYS = [
|
|
28
|
+
'fetch',
|
|
29
|
+
'globals',
|
|
30
|
+
'onBuildChanged',
|
|
31
|
+
'onCallerChanged',
|
|
32
|
+
'router',
|
|
33
|
+
'sessionStorage',
|
|
34
|
+
'storage',
|
|
35
|
+
'WebSocket',
|
|
36
|
+
'websocketUrl'
|
|
37
|
+
];
|
|
38
|
+
// A host may also give authTransport ('cookie', the default, or 'bearer') and,
|
|
39
|
+
// for bearer, tokenStore: see validateAuthTransport.
|
|
40
|
+
// Builds lowdefy._internal and the app-level state of the lowdefy object for a
|
|
41
|
+
// renderer: requests, endpoint calls, the websocket client, auth methods,
|
|
42
|
+
// storage keys, translation, logging and error handling. The renderer then adds
|
|
43
|
+
// what draws the page (block components, icons, links) to
|
|
44
|
+
// lowdefy._internal.components.
|
|
45
|
+
//
|
|
46
|
+
// apiBase prefixes every API call. It is basePath on the web, where the API is
|
|
47
|
+
// served under the app's own path; a native shell passes its server's origin.
|
|
48
|
+
// basePath keeps its routing meaning (history URLs and storage keys).
|
|
49
|
+
function createLowdefyCore({ apiBase, auth, basePath, host, lowdefy, rootConfig, types }) {
|
|
50
|
+
if (!type.isObject(host)) {
|
|
51
|
+
throw new Error(`Lowdefy client host is not an object. Received ${JSON.stringify(host)}.`);
|
|
52
|
+
}
|
|
53
|
+
const missing = HOST_KEYS.filter((key)=>!(key in host));
|
|
54
|
+
if (missing.length > 0) {
|
|
55
|
+
throw new Error(`Lowdefy client host is missing ${missing.join(', ')}.`);
|
|
56
|
+
}
|
|
57
|
+
validateAuthTransport({
|
|
58
|
+
host
|
|
59
|
+
});
|
|
60
|
+
// The path memory lasts the session. A dev config reload clears initialised
|
|
61
|
+
// to rebuild the page contexts, but the paths this tab followed still name
|
|
62
|
+
// the same pages, and the page response it fetches next rewrites its own.
|
|
63
|
+
if (type.isUndefined(lowdefy.pathMemory)) {
|
|
64
|
+
lowdefy.pathMemory = new Map();
|
|
65
|
+
}
|
|
66
|
+
lowdefy._internal = {
|
|
67
|
+
actions: types.actions,
|
|
68
|
+
blockComponents: types.blocks,
|
|
69
|
+
blockMetas: types.blockMetas ?? {},
|
|
70
|
+
// The last caller stamp a response carried (recordCallerStamp). It names
|
|
71
|
+
// the session, not the page context, so it outlives a dev config reload,
|
|
72
|
+
// and the dev server records the first page config's before this runs.
|
|
73
|
+
callerStamp: lowdefy._internal?.callerStamp ?? null,
|
|
74
|
+
components: {},
|
|
75
|
+
displayMessage: ({ content })=>{
|
|
76
|
+
console.log(content);
|
|
77
|
+
return ()=>undefined;
|
|
78
|
+
},
|
|
79
|
+
globals: host.globals,
|
|
80
|
+
host,
|
|
81
|
+
initialised: true,
|
|
82
|
+
link: ()=>undefined,
|
|
83
|
+
operators: types.operators,
|
|
84
|
+
progress: {
|
|
85
|
+
state: {
|
|
86
|
+
progress: 0
|
|
87
|
+
},
|
|
88
|
+
dispatch: ()=>undefined
|
|
89
|
+
},
|
|
90
|
+
router: host.router
|
|
91
|
+
};
|
|
92
|
+
lowdefy.apiBase = apiBase ?? basePath;
|
|
93
|
+
lowdefy.apiResponses = {};
|
|
94
|
+
// Rebuilt with the page contexts, so a dev config reload runs the app events again.
|
|
95
|
+
lowdefy.appContext = null;
|
|
96
|
+
lowdefy.basePath = basePath;
|
|
97
|
+
lowdefy.contexts = {};
|
|
98
|
+
lowdefy.inputs = {};
|
|
99
|
+
lowdefy.pageInstances = {};
|
|
100
|
+
lowdefy.lowdefyApp = rootConfig.lowdefyApp;
|
|
101
|
+
lowdefy.lowdefyGlobal = rootConfig.lowdefyGlobal;
|
|
102
|
+
lowdefy.theme = rootConfig.theme ?? {};
|
|
103
|
+
lowdefy._internal.storage = createStorage({
|
|
104
|
+
basePath,
|
|
105
|
+
getUserId: ()=>lowdefy.user?.id ?? null,
|
|
106
|
+
sessionStorage: host.sessionStorage,
|
|
107
|
+
slug: lowdefy.lowdefyApp?.slug,
|
|
108
|
+
storage: host.storage
|
|
109
|
+
});
|
|
110
|
+
lowdefy._internal.callAPI = createCallAPI(lowdefy);
|
|
111
|
+
lowdefy._internal.auth = createAuthMethods(lowdefy, auth);
|
|
112
|
+
lowdefy._internal.callRequest = createCallRequest(lowdefy);
|
|
113
|
+
lowdefy._internal.websocketClient = createWebSocketClient(lowdefy);
|
|
114
|
+
lowdefy._internal.translate = (key, values)=>translate({
|
|
115
|
+
key,
|
|
116
|
+
values,
|
|
117
|
+
i18n: lowdefy.i18n
|
|
118
|
+
});
|
|
119
|
+
lowdefy._internal.logger = createBrowserLogger();
|
|
120
|
+
lowdefy._internal.handleError = createHandleError(lowdefy);
|
|
121
|
+
return lowdefy;
|
|
122
|
+
}
|
|
123
|
+
export { HOST_KEYS };
|
|
124
|
+
export default createLowdefyCore;
|
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
*/ // Page lifecycle events. Browser signals a page can react to, so apps do not
|
|
16
|
+
// have to poll to notice that a tab went away and came back, that the network
|
|
17
|
+
// dropped, or that the window was resized.
|
|
18
|
+
//
|
|
19
|
+
// - onVisible document became visible again, or the window regained focus.
|
|
20
|
+
// - onHidden document became hidden, or the window lost focus.
|
|
21
|
+
// - onOnline the browser reports the network is back.
|
|
22
|
+
// - onOffline the browser reports the network is gone.
|
|
23
|
+
// - onResize the window was resized.
|
|
24
|
+
//
|
|
25
|
+
// None of these fire on the initial page load - the active state is seeded from
|
|
26
|
+
// the document when the page mounts, and only transitions away from that seed
|
|
27
|
+
// trigger an event.
|
|
28
|
+
//
|
|
29
|
+
// The same resize listener keeps _media current: once a resize settles, the
|
|
30
|
+
// engine re-evaluates the blocks that read a media value that changed.
|
|
31
|
+
const VISIBILITY_DEBOUNCE_MS = 300;
|
|
32
|
+
const RESIZE_DEBOUNCE_MS = 150;
|
|
33
|
+
function createPageLifecycleManager() {
|
|
34
|
+
let destroyed = false;
|
|
35
|
+
let removeListeners = [];
|
|
36
|
+
let timeouts = [];
|
|
37
|
+
function init(context) {
|
|
38
|
+
destroyed = false;
|
|
39
|
+
const globals = context?._internal?.lowdefy?._internal?.globals ?? {};
|
|
40
|
+
const win = globals.window;
|
|
41
|
+
const doc = globals.document;
|
|
42
|
+
// A host with no window and document (a native shell) has no browser
|
|
43
|
+
// listeners to attach to.
|
|
44
|
+
if (!win || !doc) return;
|
|
45
|
+
if (typeof win.addEventListener !== 'function' || typeof doc.addEventListener !== 'function') {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const events = context._internal.rootBlock?.events ?? {};
|
|
49
|
+
const configured = (name)=>!!events[name];
|
|
50
|
+
const trigger = (name, event)=>{
|
|
51
|
+
if (destroyed) return;
|
|
52
|
+
// Page lifecycle chains run like onMountAsync - non blocking, and a
|
|
53
|
+
// failure in the chain must not break the page.
|
|
54
|
+
try {
|
|
55
|
+
Promise.resolve(context._internal.triggerPageEvent({
|
|
56
|
+
name,
|
|
57
|
+
event
|
|
58
|
+
})).catch((error)=>{
|
|
59
|
+
context._internal.lowdefy._internal.handleError?.(error);
|
|
60
|
+
});
|
|
61
|
+
} catch (error) {
|
|
62
|
+
context._internal.lowdefy._internal.handleError?.(error);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const setTimer = (fn, ms)=>{
|
|
66
|
+
const timeout = setTimeout(()=>{
|
|
67
|
+
timeouts = timeouts.filter((t)=>t !== timeout);
|
|
68
|
+
fn();
|
|
69
|
+
}, ms);
|
|
70
|
+
timeouts.push(timeout);
|
|
71
|
+
return timeout;
|
|
72
|
+
};
|
|
73
|
+
const listen = (target, name, handler)=>{
|
|
74
|
+
target.addEventListener(name, handler);
|
|
75
|
+
removeListeners.push(()=>target.removeEventListener(name, handler));
|
|
76
|
+
};
|
|
77
|
+
// --- onVisible / onHidden ------------------------------------------------
|
|
78
|
+
if (configured('onVisible') || configured('onHidden')) {
|
|
79
|
+
// Seeded from the document so the initial load never fires an event.
|
|
80
|
+
let active = doc.visibilityState !== 'hidden';
|
|
81
|
+
let pending = null;
|
|
82
|
+
const flush = ()=>{
|
|
83
|
+
const next = pending;
|
|
84
|
+
pending = null;
|
|
85
|
+
if (destroyed || !next) return;
|
|
86
|
+
// A focus that only restores a state we are already in is not an event.
|
|
87
|
+
if (next.active === active) return;
|
|
88
|
+
active = next.active;
|
|
89
|
+
trigger(next.active ? 'onVisible' : 'onHidden', {
|
|
90
|
+
visible: next.active,
|
|
91
|
+
reason: next.reason
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
// A tab coming back to the front fires visibilitychange and focus. Both
|
|
95
|
+
// are collected into one window so the event chain only runs once.
|
|
96
|
+
const signal = (nextActive, reason)=>{
|
|
97
|
+
if (destroyed) return;
|
|
98
|
+
if (pending) {
|
|
99
|
+
pending.active = nextActive;
|
|
100
|
+
// A visibilitychange is the more precise reason, so it wins the pair.
|
|
101
|
+
if (reason === 'visibility') pending.reason = 'visibility';
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
pending = {
|
|
105
|
+
active: nextActive,
|
|
106
|
+
reason
|
|
107
|
+
};
|
|
108
|
+
setTimer(flush, VISIBILITY_DEBOUNCE_MS);
|
|
109
|
+
};
|
|
110
|
+
listen(doc, 'visibilitychange', ()=>{
|
|
111
|
+
signal(doc.visibilityState !== 'hidden', 'visibility');
|
|
112
|
+
});
|
|
113
|
+
listen(win, 'focus', ()=>signal(true, 'focus'));
|
|
114
|
+
listen(win, 'blur', ()=>signal(false, 'focus'));
|
|
115
|
+
}
|
|
116
|
+
// --- onOnline / onOffline ------------------------------------------------
|
|
117
|
+
if (configured('onOnline')) {
|
|
118
|
+
listen(win, 'online', ()=>trigger('onOnline', {
|
|
119
|
+
online: true
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
if (configured('onOffline')) {
|
|
123
|
+
listen(win, 'offline', ()=>trigger('onOffline', {
|
|
124
|
+
online: false
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
// --- onResize and _media -------------------------------------------------
|
|
128
|
+
// The operator registry holds the operators of every page loaded so far, so
|
|
129
|
+
// a page that can not reach _media attaches no listener for it.
|
|
130
|
+
const watchMedia = !!context._internal.lowdefy._internal.operators._media;
|
|
131
|
+
const onResize = configured('onResize');
|
|
132
|
+
if (watchMedia || onResize) {
|
|
133
|
+
let resizeTimeout = null;
|
|
134
|
+
// One trailing debounce for the whole page: a drag fires resize at frame
|
|
135
|
+
// rate, and this evaluates once when it settles. A requestAnimationFrame
|
|
136
|
+
// throttle would evaluate every frame of the drag instead.
|
|
137
|
+
const flush = ()=>{
|
|
138
|
+
resizeTimeout = null;
|
|
139
|
+
if (destroyed) return;
|
|
140
|
+
// Blocks first, so onResize actions see the page evaluated at the new size.
|
|
141
|
+
if (watchMedia) {
|
|
142
|
+
context._internal.updateMedia();
|
|
143
|
+
}
|
|
144
|
+
if (onResize) {
|
|
145
|
+
trigger('onResize', {
|
|
146
|
+
width: win.innerWidth,
|
|
147
|
+
height: win.innerHeight
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
listen(win, 'resize', ()=>{
|
|
152
|
+
if (resizeTimeout) {
|
|
153
|
+
clearTimeout(resizeTimeout);
|
|
154
|
+
timeouts = timeouts.filter((t)=>t !== resizeTimeout);
|
|
155
|
+
}
|
|
156
|
+
resizeTimeout = setTimer(flush, RESIZE_DEBOUNCE_MS);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function destroy() {
|
|
161
|
+
destroyed = true;
|
|
162
|
+
removeListeners.forEach((remove)=>remove());
|
|
163
|
+
removeListeners = [];
|
|
164
|
+
timeouts.forEach((timeout)=>clearTimeout(timeout));
|
|
165
|
+
timeouts = [];
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
init,
|
|
169
|
+
destroy
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
export { RESIZE_DEBOUNCE_MS, VISIBILITY_DEBOUNCE_MS };
|
|
173
|
+
export default createPageLifecycleManager;
|