@softr/sdk 1.16.0-se23079.1 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1 -3
- package/dist/auth/isomorphic.js +3 -1
- package/dist/auth/methods/authenticator.js +1 -8
- package/dist/auth/methods/code.js +1 -5
- package/dist/auth/methods/emailCode2fa.js +1 -4
- package/dist/auth/methods/magicLink.js +1 -4
- package/dist/auth/methods/password.js +1 -3
- package/dist/auth/methods/passwordLink.js +1 -5
- package/dist/auth/methods/signup.js +1 -7
- package/dist/auth/methods/social.js +5 -4
- package/dist/auth/methods/utils.d.ts +1 -4
- package/dist/auth/methods/utils.js +1 -30
- package/dist/auth/sso.js +1 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/offline.d.ts +35 -0
- package/dist/offline.js +106 -0
- package/dist/package.js +1 -1
- package/dist/push.js +6 -5
- package/dist/service-worker.js +120 -0
- package/package.json +16 -43
- package/skills/softr-sdk/SKILL.md +4 -0
- package/skills/softr-sdk/auth/SKILL.md +2 -3
- package/skills/softr-sdk/offline/SKILL.md +119 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,9 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
### Minor Changes
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
- `auth.sendSignInCode`, `auth.signInWithCode`, and `auth.signUp` and `auth.confirmSignUp` without a password fail as `notEnabled` when the plan of the app's workspace does not include one-time email codes, as after a downgrade. Before, these calls worked on every plan. Action: on the login and sign-up pages, give `notEnabled` its own `case`, say this way to sign in is not available, and offer the other ways in.
|
|
9
|
-
- New error code `secondFactorNotEnabled`: the visitor owes a second step that the plan of the app's workspace does not include, as after a downgrade. Every call that signs a visitor in answers it in an app that asks that visitor for an authenticator step, and so does `auth.startAuthenticatorSetup`. `auth.signIn`, `auth.verifyEmailCode` and `auth.resendEmailCode` answer it in an app that asks for an emailed code after the password. Before, these calls worked on every plan. Action: give `secondFactorNotEnabled` its own `case` on the pages that sign a visitor in and on the page that sets up an authenticator. Say sign-in is not available on the app's plan and the app owner can fix it. Do not offer another way to sign in, because no way works.
|
|
7
|
+
- Add `useOfflineMode()`: the published app opens without internet and shows the pages and data the visitor last loaded, read only. Call it once in `RootDocument`; `useOfflineMode({ enabled: false })` turns it off and deletes what browsers kept.
|
|
10
8
|
|
|
11
9
|
## 1.15.4
|
|
12
10
|
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -10,12 +10,13 @@ import { readLocaleSettings } from "../locale-settings.js";
|
|
|
10
10
|
import { settings } from "./methods/settings.js";
|
|
11
11
|
import { bootErrorMiddleware } from "../boot-error.js";
|
|
12
12
|
import { pwaMiddleware } from "../pwa.js";
|
|
13
|
+
import { OFFLINE_USER_HEADER } from "../service-worker.js";
|
|
13
14
|
import { pushMiddleware } from "../push.js";
|
|
14
15
|
import { faviconMiddleware } from "../favicon.js";
|
|
15
16
|
import { embeddingMiddleware } from "../embedding.js";
|
|
16
17
|
import { appIdentityMiddleware } from "../app-identity.js";
|
|
17
18
|
import { accessDeniedStatusMiddleware } from "../route/access-denied-status.js";
|
|
18
|
-
import { getRequestHeader } from "@tanstack/react-start/server";
|
|
19
|
+
import { getRequestHeader, setResponseHeader } from "@tanstack/react-start/server";
|
|
19
20
|
import { createContext, useContext } from "react";
|
|
20
21
|
import { createMiddleware, createServerFn } from "@tanstack/react-start";
|
|
21
22
|
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
@@ -65,6 +66,7 @@ function softrAuthMiddleware() {
|
|
|
65
66
|
return session;
|
|
66
67
|
}
|
|
67
68
|
const [{ user }, settings$1] = await Promise.all([getSession(), readLocaleSettings()]);
|
|
69
|
+
setResponseHeader(OFFLINE_USER_HEADER, user?.id ?? "");
|
|
68
70
|
return next({ context: {
|
|
69
71
|
user,
|
|
70
72
|
permissions: { datasources: {} },
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/authenticator.ts
|
|
9
9
|
/**
|
|
@@ -22,7 +22,6 @@ async function startAuthenticatorSetup() {
|
|
|
22
22
|
assertCanChange("auth.startAuthenticatorSetup");
|
|
23
23
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupInit(readPendingAuthToken() ?? readSessionToken());
|
|
24
24
|
if (!result.ok) {
|
|
25
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
26
25
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
27
26
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
28
27
|
if (result.status >= 500) panic(`Expected authenticator setup to start, but got ${result.status}: ` + result.message);
|
|
@@ -43,8 +42,6 @@ async function confirmAuthenticatorSetup(details) {
|
|
|
43
42
|
assertCanChange("auth.confirmAuthenticatorSetup");
|
|
44
43
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code);
|
|
45
44
|
if (!result.ok) {
|
|
46
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
47
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
48
45
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
49
46
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
50
47
|
if (result.status >= 500) panic(`Expected authenticator setup to finish, but got ${result.status}: ` + result.message);
|
|
@@ -71,8 +68,6 @@ async function skipAuthenticatorSetup() {
|
|
|
71
68
|
assertCanChange("auth.skipAuthenticatorSetup");
|
|
72
69
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken());
|
|
73
70
|
if (!result.ok) {
|
|
74
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
75
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
76
71
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
77
72
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
78
73
|
if (result.status >= 500) panic(`Expected to skip authenticator setup, but got ${result.status}: ` + result.message);
|
|
@@ -97,8 +92,6 @@ async function verifyAuthenticator(credentials) {
|
|
|
97
92
|
assertCanChange("auth.verifyAuthenticator");
|
|
98
93
|
const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode });
|
|
99
94
|
if (!result.ok) {
|
|
100
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
101
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
102
95
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
103
96
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
104
97
|
if (result.status >= 500) panic(`Expected to verify the authenticator, but got ${result.status}: ` + result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/code.ts
|
|
9
9
|
const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccount"], ["This account is deactivated. Please contact the application owner.", "accountDeactivated"]]);
|
|
@@ -18,7 +18,6 @@ async function sendSignInCode(details) {
|
|
|
18
18
|
assertCanChange("auth.sendSignInCode");
|
|
19
19
|
const result = await makePlatform(sessionConfig().applicationId).sendSignInCode(details.email);
|
|
20
20
|
if (!result.ok) {
|
|
21
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
22
21
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
23
22
|
if (result.status === 400) return authError(SEND_CODE_ERRORS.get(result.message) ?? "invalidDetails", result.message);
|
|
24
23
|
if (result.status >= 500) panic(`Expected the sign-in code to be emailed, but got ${result.status}: ` + result.message);
|
|
@@ -40,9 +39,6 @@ async function signInWithCode(credentials) {
|
|
|
40
39
|
assertCanChange("auth.signInWithCode");
|
|
41
40
|
const result = await makePlatform(sessionConfig().applicationId).signInWithCode(credentials);
|
|
42
41
|
if (!result.ok) {
|
|
43
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
44
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
45
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
46
42
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
47
43
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
48
44
|
if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/emailCode2fa.ts
|
|
9
9
|
/**
|
|
@@ -18,8 +18,6 @@ async function verifyEmailCode(details) {
|
|
|
18
18
|
assertCanChange("auth.verifyEmailCode");
|
|
19
19
|
const result = await makePlatform(sessionConfig().applicationId).emailCodeVerify(readPendingAuthToken(), details.code);
|
|
20
20
|
if (!result.ok) {
|
|
21
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
22
|
-
if (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
23
21
|
if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
|
|
24
22
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
25
23
|
if (result.status >= 500) panic(`Expected to verify the emailed code, but got ${result.status}: ` + result.message);
|
|
@@ -57,7 +55,6 @@ async function resendEmailCode() {
|
|
|
57
55
|
assertCanChange("auth.resendEmailCode");
|
|
58
56
|
const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken());
|
|
59
57
|
if (!result.ok) {
|
|
60
|
-
if (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
61
58
|
if (result.status === 401) return authError("notAuthenticated", result.message);
|
|
62
59
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
63
60
|
if (result.status >= 500) panic(`Expected the code to be emailed again, but got ${result.status}: ` + result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/magicLink.ts
|
|
9
9
|
/**
|
|
@@ -18,9 +18,6 @@ async function signInWithMagicLink(credentials) {
|
|
|
18
18
|
assertCanChange("auth.signInWithMagicLink");
|
|
19
19
|
const result = await makePlatform(sessionConfig().applicationId).signInWithMagicLink(credentials);
|
|
20
20
|
if (!result.ok) {
|
|
21
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
22
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
23
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
24
21
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
25
22
|
if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
|
|
26
23
|
if (result.status >= 500) panic(`Expected magic-link sign-in to succeed, but got ${result.status}: ` + result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/password.ts
|
|
9
9
|
/**
|
|
@@ -18,8 +18,6 @@ async function signIn(credentials) {
|
|
|
18
18
|
assertCanChange("auth.signIn");
|
|
19
19
|
const result = await makePlatform(sessionConfig().applicationId).tokens(credentials);
|
|
20
20
|
if (!result.ok) {
|
|
21
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
22
|
-
if (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
23
21
|
if (result.status === 401) return authError("invalidCredentials", result.message);
|
|
24
22
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
25
23
|
if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/passwordLink.ts
|
|
9
9
|
/**
|
|
@@ -31,7 +31,6 @@ async function requestPasswordReset(details) {
|
|
|
31
31
|
async function checkPasswordLink(details) {
|
|
32
32
|
const result = await makePlatform(sessionConfig().applicationId).checkPasswordToken(details);
|
|
33
33
|
if (!result.ok) {
|
|
34
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
35
34
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
36
35
|
if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
|
|
37
36
|
panic(`Expected the link to be checked, but got ${result.status}: ${result.message}.`);
|
|
@@ -52,9 +51,6 @@ async function setPasswordWithLink(details) {
|
|
|
52
51
|
assertCanChange("auth.setPasswordWithLink");
|
|
53
52
|
const result = await makePlatform(sessionConfig().applicationId).setPassword(details);
|
|
54
53
|
if (!result.ok) {
|
|
55
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
56
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
57
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
58
54
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
59
55
|
if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
|
|
60
56
|
if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
|
|
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/methods/signup.ts
|
|
9
9
|
/**
|
|
@@ -15,9 +15,6 @@ async function signUp(details) {
|
|
|
15
15
|
assertCanChange("auth.signUp");
|
|
16
16
|
const result = await makePlatform(sessionConfig().applicationId).sendSignUpCode(details);
|
|
17
17
|
if (!result.ok) {
|
|
18
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
19
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
20
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
21
18
|
if (result.status === 409) return authError("emailTaken", result.message);
|
|
22
19
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
23
20
|
if (result.status === 400) return authError("invalidDetails", result.message);
|
|
@@ -51,9 +48,6 @@ async function confirmSignUp(details) {
|
|
|
51
48
|
password
|
|
52
49
|
});
|
|
53
50
|
if (!result.ok) {
|
|
54
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
55
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
56
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
57
51
|
if (result.status === 409) return authError("emailTaken", result.message);
|
|
58
52
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
59
53
|
if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
|
|
@@ -3,9 +3,11 @@ import { writeCookies } from "../../cookies.js";
|
|
|
3
3
|
import { sessionConfig } from "../config.js";
|
|
4
4
|
import { makePlatform } from "../platform.js";
|
|
5
5
|
import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
|
|
6
|
-
import { authError
|
|
6
|
+
import { authError } from "./utils.js";
|
|
7
|
+
import { z } from "zod";
|
|
7
8
|
|
|
8
9
|
//#region src/auth/methods/social.ts
|
|
10
|
+
const errorBodySchema = z.object({ code: z.string() });
|
|
9
11
|
/**
|
|
10
12
|
* Signs a visitor in with a Google token the browser obtained, creating their
|
|
11
13
|
* account the first time.
|
|
@@ -25,10 +27,9 @@ async function signInWithGoogle(credentials) {
|
|
|
25
27
|
assertCanChange("auth.signInWithGoogle");
|
|
26
28
|
const result = await makePlatform(sessionConfig().applicationId).signInWithGoogle(credentials);
|
|
27
29
|
if (!result.ok) {
|
|
28
|
-
if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
|
|
29
|
-
if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
|
|
30
|
-
if (isNotInPlan(result)) return authError("notEnabled", result.message);
|
|
31
30
|
if (result.status === 429) return authError("tooManyAttempts", result.message);
|
|
31
|
+
const body = errorBodySchema.safeParse(result.body);
|
|
32
|
+
if (body.success && body.data.code === "GOOGLE_NOT_IN_PLAN") return authError("notEnabled", result.message);
|
|
32
33
|
if (result.status === 400 && result.message.startsWith("Emails with ") && result.message.endsWith(" domain is not allowed to signup.")) return authError("emailDomainNotAllowed", result.message);
|
|
33
34
|
if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
|
|
34
35
|
if (result.status >= 500) panic(`Expected Google sign-in to succeed, but got ${result.status}: ` + result.message);
|
|
@@ -10,9 +10,6 @@ type AuthError = {
|
|
|
10
10
|
code: AuthErrorCode;
|
|
11
11
|
message: string;
|
|
12
12
|
};
|
|
13
|
-
type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed"
|
|
14
|
-
/** The plan of the app's workspace no longer includes this way to sign in, as after a downgrade. Another way in can still work. */ | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported"
|
|
15
|
-
/** Any call that signs a visitor in or up: the plan of the app's workspace has no room for this user. */ | "userLimitReached"
|
|
16
|
-
/** The visitor owes a second step that the plan of the app's workspace no longer includes. No way in works until the app owner changes the plan. */ | "secondFactorNotEnabled";
|
|
13
|
+
type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed" | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported";
|
|
17
14
|
//#endregion
|
|
18
15
|
export { AuthError, Result };
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
|
|
3
1
|
//#region src/auth/methods/utils.ts
|
|
4
2
|
function authError(code, message) {
|
|
5
3
|
return {
|
|
@@ -10,33 +8,6 @@ function authError(code, message) {
|
|
|
10
8
|
}
|
|
11
9
|
};
|
|
12
10
|
}
|
|
13
|
-
const errorBodySchema = z.object({ code: z.string() });
|
|
14
|
-
/**
|
|
15
|
-
* True when Softr refused because the plan of the app's workspace has no room
|
|
16
|
-
* for this user. It arrives as a 400, like a wrong code, so the status cannot
|
|
17
|
-
* tell them apart.
|
|
18
|
-
*/
|
|
19
|
-
function isUserLimitReached(result) {
|
|
20
|
-
const body = errorBodySchema.safeParse(result.body);
|
|
21
|
-
return body.success && body.data.code === "USER_LIMIT_REACHED";
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* True when Softr refused because the plan of the app's workspace does not
|
|
25
|
-
* include this way to sign in: Google sign-in or the one-time email code, as
|
|
26
|
-
* after a downgrade.
|
|
27
|
-
*/
|
|
28
|
-
function isNotInPlan(result) {
|
|
29
|
-
const body = errorBodySchema.safeParse(result.body);
|
|
30
|
-
return body.success && (body.data.code === "GOOGLE_NOT_IN_PLAN" || body.data.code === "EMAIL_CODE_NOT_IN_PLAN");
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* True when Softr refused because the visitor owes an authenticator app step
|
|
34
|
-
* that the plan of the app's workspace does not include, as after a downgrade.
|
|
35
|
-
*/
|
|
36
|
-
function isAuthenticatorNotInPlan(result) {
|
|
37
|
-
const body = errorBodySchema.safeParse(result.body);
|
|
38
|
-
return body.success && body.data.code === "AUTHENTICATOR_NOT_IN_PLAN";
|
|
39
|
-
}
|
|
40
11
|
|
|
41
12
|
//#endregion
|
|
42
|
-
export { authError
|
|
13
|
+
export { authError };
|
package/dist/auth/sso.js
CHANGED
|
@@ -145,8 +145,7 @@ function failure(result) {
|
|
|
145
145
|
case "SSO_IDP_REJECTED": return { error: "idp" };
|
|
146
146
|
case "SSO_NOT_ENABLED":
|
|
147
147
|
case "SSO_NOT_IN_PLAN":
|
|
148
|
-
case "SSO_MISCONFIGURED":
|
|
149
|
-
case "AUTHENTICATOR_NOT_IN_PLAN": return { error: "not-enabled" };
|
|
148
|
+
case "SSO_MISCONFIGURED": return { error: "not-enabled" };
|
|
150
149
|
case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" };
|
|
151
150
|
case "USER_DEACTIVATED":
|
|
152
151
|
case "SIGN_IN_RESTRICTED": return { error: "restricted" };
|
package/dist/index.d.ts
CHANGED
|
@@ -21,8 +21,9 @@ import { useOverrides } from "./core/use-overrides.js";
|
|
|
21
21
|
import { useUserTimezone } from "./timezone.js";
|
|
22
22
|
import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
23
23
|
import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
|
|
24
|
+
import { OfflineMode, OfflineModeOptions, useOfflineMode } from "./offline.js";
|
|
24
25
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
25
26
|
import { Audience } from "./route/audience.js";
|
|
26
27
|
import { Logo, LogoFile } from "./softr-config.schema.js";
|
|
27
28
|
import { getLogo } from "./softr-config.js";
|
|
28
|
-
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
|
29
|
+
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type OfflineMode, type OfflineModeOptions, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOfflineMode, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -16,7 +16,8 @@ import { softrMcpMiddleware } from "./mcp.js";
|
|
|
16
16
|
import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
17
17
|
import { useOverrides } from "./core/use-overrides.js";
|
|
18
18
|
import { useUserTimezone } from "./timezone.js";
|
|
19
|
+
import { useOfflineMode } from "./offline.js";
|
|
19
20
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
20
21
|
import { Audience } from "./route/audience.js";
|
|
21
22
|
|
|
22
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
|
23
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOfflineMode, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/offline.d.ts
|
|
2
|
+
type OfflineMode = {
|
|
3
|
+
/**
|
|
4
|
+
* `false` while the browser has no connection, or while the app shows saved
|
|
5
|
+
* copies because it cannot reach the server. Always `true` during server rendering.
|
|
6
|
+
*/
|
|
7
|
+
online: boolean;
|
|
8
|
+
};
|
|
9
|
+
type OfflineModeOptions = {
|
|
10
|
+
/**
|
|
11
|
+
* `false` turns offline mode off and deletes what this browser kept. Keep the
|
|
12
|
+
* call with `false` rather than removing it: browsers that ran offline mode
|
|
13
|
+
* before keep the visitor's copies, and keep saving new ones, until this runs
|
|
14
|
+
* or the visitor signs out. Defaults to `true`.
|
|
15
|
+
*/
|
|
16
|
+
enabled?: boolean;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Lets the published app open without internet and show the pages and data
|
|
20
|
+
* the visitor loaded, read only. Saves made offline fail as usual.
|
|
21
|
+
*
|
|
22
|
+
* Call it once, in the root route's `RootDocument`. The saved copies are
|
|
23
|
+
* deleted when another visitor signs in on this browser, or when the visitor
|
|
24
|
+
* signs out. In the Studio preview it only reports `online`.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* function OfflineBanner() {
|
|
28
|
+
* const { online } = useOfflineMode()
|
|
29
|
+
* if (online) return null
|
|
30
|
+
* return <div role="status">You're offline. Showing the last saved data.</div>
|
|
31
|
+
* }
|
|
32
|
+
*/
|
|
33
|
+
declare function useOfflineMode(options?: OfflineModeOptions): OfflineMode;
|
|
34
|
+
//#endregion
|
|
35
|
+
export { OfflineMode, OfflineModeOptions, useOfflineMode };
|
package/dist/offline.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, WORKER_PATH } from "./service-worker.js";
|
|
2
|
+
import { useCurrentUser } from "./auth/isomorphic.js";
|
|
3
|
+
import { useEffect, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { useLocation } from "@tanstack/react-router";
|
|
5
|
+
|
|
6
|
+
//#region src/offline.ts
|
|
7
|
+
const PAGE_MAX_AGE_MS = 30 * 6e4;
|
|
8
|
+
/**
|
|
9
|
+
* Lets the published app open without internet and show the pages and data
|
|
10
|
+
* the visitor loaded, read only. Saves made offline fail as usual.
|
|
11
|
+
*
|
|
12
|
+
* Call it once, in the root route's `RootDocument`. The saved copies are
|
|
13
|
+
* deleted when another visitor signs in on this browser, or when the visitor
|
|
14
|
+
* signs out. In the Studio preview it only reports `online`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* function OfflineBanner() {
|
|
18
|
+
* const { online } = useOfflineMode()
|
|
19
|
+
* if (online) return null
|
|
20
|
+
* return <div role="status">You're offline. Showing the last saved data.</div>
|
|
21
|
+
* }
|
|
22
|
+
*/
|
|
23
|
+
function useOfflineMode(options = {}) {
|
|
24
|
+
const enabled = options.enabled ?? true;
|
|
25
|
+
const userId = useCurrentUser()?.id ?? null;
|
|
26
|
+
const pathname = useLocation({ select: (location$1) => location$1.pathname });
|
|
27
|
+
const connected = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
|
|
28
|
+
const [showingCopies, setShowingCopies] = useState(false);
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (!("serviceWorker" in navigator)) return;
|
|
31
|
+
const onMessage = (event) => {
|
|
32
|
+
const data = event.data;
|
|
33
|
+
if (typeof data !== "object" || data === null || !("type" in data) || data.type !== OFFLINE_MESSAGE) return;
|
|
34
|
+
setShowingCopies("showingCopies" in data && data.showingCopies === true);
|
|
35
|
+
};
|
|
36
|
+
const onOnline = () => {
|
|
37
|
+
setShowingCopies(false);
|
|
38
|
+
navigator.serviceWorker.controller?.postMessage({
|
|
39
|
+
type: OFFLINE_MESSAGE,
|
|
40
|
+
online: true
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
navigator.serviceWorker.addEventListener("message", onMessage);
|
|
44
|
+
window.addEventListener("online", onOnline);
|
|
45
|
+
navigator.serviceWorker.controller?.postMessage({ type: OFFLINE_MESSAGE });
|
|
46
|
+
return () => {
|
|
47
|
+
navigator.serviceWorker.removeEventListener("message", onMessage);
|
|
48
|
+
window.removeEventListener("online", onOnline);
|
|
49
|
+
};
|
|
50
|
+
}, []);
|
|
51
|
+
useEffect(() => {
|
|
52
|
+
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return;
|
|
53
|
+
if (!enabled) {
|
|
54
|
+
deleteCopies().catch(() => {});
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (!connected || showingCopies) return;
|
|
58
|
+
(async () => {
|
|
59
|
+
const owner = userId ?? "";
|
|
60
|
+
const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY);
|
|
61
|
+
if (stored === void 0 || await stored.text() !== owner) {
|
|
62
|
+
await deleteCopies();
|
|
63
|
+
await (await caches.open(OFFLINE_CACHE)).put(OFFLINE_OWNER_KEY, new Response(owner));
|
|
64
|
+
}
|
|
65
|
+
await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
|
|
66
|
+
const cache = await caches.open(OFFLINE_CACHE);
|
|
67
|
+
const save = (url) => cache.add(new Request(url, { headers: { [OFFLINE_SAVE_HEADER]: "1" } }));
|
|
68
|
+
const page = await cache.match(pathname);
|
|
69
|
+
const savedAt = Date.parse(page?.headers.get("date") ?? "");
|
|
70
|
+
if (!(Date.now() - savedAt < PAGE_MAX_AGE_MS)) await save(pathname).catch(() => {});
|
|
71
|
+
const files = [];
|
|
72
|
+
for (const entry of performance.getEntriesByType("resource")) {
|
|
73
|
+
if (!(entry instanceof PerformanceResourceTiming)) continue;
|
|
74
|
+
if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue;
|
|
75
|
+
const url = new URL(entry.name);
|
|
76
|
+
if (url.origin !== location.origin) continue;
|
|
77
|
+
if (OFFLINE_SKIPPED_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) continue;
|
|
78
|
+
files.push(url.href);
|
|
79
|
+
}
|
|
80
|
+
await Promise.all(files.map(async (url) => {
|
|
81
|
+
if (await cache.match(url) === void 0) await save(url).catch(() => {});
|
|
82
|
+
}));
|
|
83
|
+
})().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
|
|
84
|
+
}, [
|
|
85
|
+
enabled,
|
|
86
|
+
userId,
|
|
87
|
+
pathname,
|
|
88
|
+
connected,
|
|
89
|
+
showingCopies
|
|
90
|
+
]);
|
|
91
|
+
return { online: connected && !showingCopies };
|
|
92
|
+
}
|
|
93
|
+
async function deleteCopies() {
|
|
94
|
+
await Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]);
|
|
95
|
+
}
|
|
96
|
+
function subscribeToConnection(onChange) {
|
|
97
|
+
window.addEventListener("online", onChange);
|
|
98
|
+
window.addEventListener("offline", onChange);
|
|
99
|
+
return () => {
|
|
100
|
+
window.removeEventListener("online", onChange);
|
|
101
|
+
window.removeEventListener("offline", onChange);
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
//#endregion
|
|
106
|
+
export { useOfflineMode };
|
package/dist/package.js
CHANGED
package/dist/push.js
CHANGED
|
@@ -4,13 +4,13 @@ import { sessionConfig } from "./auth/config.js";
|
|
|
4
4
|
import { readSessionToken } from "./auth/session.js";
|
|
5
5
|
import { readCached } from "./cache.js";
|
|
6
6
|
import { detectPlatform, isStandalone } from "./pwa.js";
|
|
7
|
+
import { OFFLINE_WORKER, WORKER_PATH } from "./service-worker.js";
|
|
7
8
|
import { z } from "zod";
|
|
8
9
|
import { useCallback, useEffect, useState } from "react";
|
|
9
10
|
import { createMiddleware } from "@tanstack/react-start";
|
|
10
11
|
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
11
12
|
|
|
12
13
|
//#region src/push.ts
|
|
13
|
-
const WORKER_PATH = "/_softr/sw.js";
|
|
14
14
|
const SETTINGS_PATH = "/_softr/push.json";
|
|
15
15
|
const SUBSCRIPTION_PATH = "/_softr/push";
|
|
16
16
|
const TTL_MS = 6e4;
|
|
@@ -55,9 +55,10 @@ function readWorker() {
|
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
/**
|
|
58
|
-
* Serves push notifications from the app's own origin: the service worker,
|
|
59
|
-
* app's push settings, and saving or
|
|
60
|
-
* the signed-in visitor. Every other
|
|
58
|
+
* Serves push notifications from the app's own origin: the service worker,
|
|
59
|
+
* which also runs offline mode, the app's push settings, and saving or
|
|
60
|
+
* removing this browser's subscription for the signed-in visitor. Every other
|
|
61
|
+
* request passes through untouched.
|
|
61
62
|
*/
|
|
62
63
|
function pushMiddleware() {
|
|
63
64
|
return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
|
|
@@ -67,7 +68,7 @@ function pushMiddleware() {
|
|
|
67
68
|
status: 503,
|
|
68
69
|
headers: { "cache-control": "no-store" }
|
|
69
70
|
});
|
|
70
|
-
return new Response(worker, { headers: {
|
|
71
|
+
return new Response(worker + OFFLINE_WORKER, { headers: {
|
|
71
72
|
"content-type": "text/javascript; charset=utf-8",
|
|
72
73
|
"cache-control": "no-cache",
|
|
73
74
|
"service-worker-allowed": "/"
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
//#region src/service-worker.ts
|
|
2
|
+
const WORKER_PATH = "/_softr/sw.js";
|
|
3
|
+
/** Pages, scripts, styles and images. Its owner entry is what turns offline mode on. */
|
|
4
|
+
const OFFLINE_CACHE = "softr-offline-v1";
|
|
5
|
+
/** Answers to the app's data calls, kept apart so a long session of them never pushes out the pages. */
|
|
6
|
+
const OFFLINE_DATA_CACHE = "softr-offline-data-v1";
|
|
7
|
+
/** Whose copies the offline cache holds: the user id, or empty for a signed-out visitor. */
|
|
8
|
+
const OFFLINE_OWNER_KEY = "/_softr/offline-owner";
|
|
9
|
+
/** Between the worker and the page: whether the worker answers with saved copies. */
|
|
10
|
+
const OFFLINE_MESSAGE = "softr-offline";
|
|
11
|
+
/**
|
|
12
|
+
* Names the signed-in user on each answer from the app's server, or is empty
|
|
13
|
+
* for a signed-out visitor. The worker deletes copies kept for someone else.
|
|
14
|
+
*/
|
|
15
|
+
const OFFLINE_USER_HEADER = "x-softr-offline-user";
|
|
16
|
+
/** Marks a request `useOfflineMode()` saves itself, so the worker leaves it alone. */
|
|
17
|
+
const OFFLINE_SAVE_HEADER = "x-softr-offline-save";
|
|
18
|
+
/** Paths offline mode never keeps: the SDK's own routes and the canvas engine's. */
|
|
19
|
+
const OFFLINE_SKIPPED_PREFIXES = ["/_softr/", "/.softr/"];
|
|
20
|
+
const MAX_COPIES = 300;
|
|
21
|
+
/**
|
|
22
|
+
* Added after the platform's worker. Same-origin GET requests go to the
|
|
23
|
+
* network first, and the last good answer is kept on the device for when the
|
|
24
|
+
* network fails. Writes and live streams are never kept.
|
|
25
|
+
*
|
|
26
|
+
* It keeps nothing until `useOfflineMode()` writes the owner entry. An app that
|
|
27
|
+
* registers the worker only for push still has its requests pass through it.
|
|
28
|
+
*/
|
|
29
|
+
const OFFLINE_WORKER = `
|
|
30
|
+
// Offline mode, added by @softr/sdk.
|
|
31
|
+
const SOFTR_OFFLINE_CACHE = ${JSON.stringify(OFFLINE_CACHE)};
|
|
32
|
+
const SOFTR_OFFLINE_DATA_CACHE = ${JSON.stringify(OFFLINE_DATA_CACHE)};
|
|
33
|
+
const SOFTR_OFFLINE_OWNER_KEY = ${JSON.stringify(OFFLINE_OWNER_KEY)};
|
|
34
|
+
const SOFTR_OFFLINE_SAVE_HEADER = ${JSON.stringify(OFFLINE_SAVE_HEADER)};
|
|
35
|
+
const SOFTR_OFFLINE_SKIPPED = ${JSON.stringify(OFFLINE_SKIPPED_PREFIXES)};
|
|
36
|
+
const SOFTR_OFFLINE_MESSAGE = ${JSON.stringify(OFFLINE_MESSAGE)};
|
|
37
|
+
const SOFTR_OFFLINE_USER_HEADER = ${JSON.stringify(OFFLINE_USER_HEADER)};
|
|
38
|
+
// Unknown after the worker starts, so the first answer after a restart always reaches the page.
|
|
39
|
+
let softrShowingCopies;
|
|
40
|
+
|
|
41
|
+
function softrSetShowingCopies(showingCopies) {
|
|
42
|
+
if (softrShowingCopies === showingCopies) return;
|
|
43
|
+
softrShowingCopies = showingCopies;
|
|
44
|
+
self.clients.matchAll({ type: 'window' }).then((pages) => {
|
|
45
|
+
for (const page of pages) page.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies });
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Page loads start while the worker starts, so a stopped worker does not delay them.
|
|
50
|
+
self.addEventListener('activate', (event) => {
|
|
51
|
+
if (self.registration.navigationPreload) event.waitUntil(self.registration.navigationPreload.enable());
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
self.addEventListener('message', (event) => {
|
|
55
|
+
if (event.data && event.data.type === SOFTR_OFFLINE_MESSAGE && event.source) {
|
|
56
|
+
// The browser is back online. The next request that fails says so again.
|
|
57
|
+
if (event.data.online === true) softrShowingCopies = false;
|
|
58
|
+
event.source.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies: softrShowingCopies === true });
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
function softrOfflineOwner() {
|
|
63
|
+
return caches.match(SOFTR_OFFLINE_OWNER_KEY, { cacheName: SOFTR_OFFLINE_CACHE }).then((owner) => owner && owner.text());
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function softrKeepCopy(owner, cacheName, key, response) {
|
|
67
|
+
// The copies were deleted, or now belong to someone else, while the request ran.
|
|
68
|
+
if ((await softrOfflineOwner()) !== owner) return;
|
|
69
|
+
const cache = await caches.open(cacheName);
|
|
70
|
+
await cache.put(key, response);
|
|
71
|
+
const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname !== SOFTR_OFFLINE_OWNER_KEY);
|
|
72
|
+
await Promise.all(keys.slice(0, Math.max(0, keys.length - ${MAX_COPIES})).map((key) => cache.delete(key)));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
self.addEventListener('fetch', (event) => {
|
|
76
|
+
const request = event.request;
|
|
77
|
+
if (request.method !== 'GET') return;
|
|
78
|
+
const url = new URL(request.url);
|
|
79
|
+
if (url.origin !== self.location.origin) return;
|
|
80
|
+
if (SOFTR_OFFLINE_SKIPPED.some((prefix) => url.pathname.startsWith(prefix))) return;
|
|
81
|
+
if (request.headers.has(SOFTR_OFFLINE_SAVE_HEADER)) return;
|
|
82
|
+
event.respondWith((async () => {
|
|
83
|
+
const fromNetwork = () => (request.mode === 'navigate' && event.preloadResponse
|
|
84
|
+
? event.preloadResponse.then((preloaded) => preloaded || fetch(request))
|
|
85
|
+
: fetch(request));
|
|
86
|
+
const owner = await softrOfflineOwner();
|
|
87
|
+
if (owner === undefined) return fromNetwork();
|
|
88
|
+
// A data call from the app's code has no destination; a page or a file has one.
|
|
89
|
+
const cacheName = request.destination === '' ? SOFTR_OFFLINE_DATA_CACHE : SOFTR_OFFLINE_CACHE;
|
|
90
|
+
// One copy of a page per path, whatever the search, like the hook keeps. Offline,
|
|
91
|
+
// a page opened with another search gets that copy, and its data may be missing.
|
|
92
|
+
const key = request.mode === 'navigate' ? url.origin + url.pathname : request;
|
|
93
|
+
try {
|
|
94
|
+
const response = await fromNetwork();
|
|
95
|
+
softrSetShowingCopies(false);
|
|
96
|
+
const user = response.headers.get(SOFTR_OFFLINE_USER_HEADER);
|
|
97
|
+
if (user !== null && user !== owner) {
|
|
98
|
+
// Someone else is signed in. Delete the copies even when the page no longer runs the hook.
|
|
99
|
+
event.waitUntil(Promise.all([caches.delete(SOFTR_OFFLINE_CACHE), caches.delete(SOFTR_OFFLINE_DATA_CACHE)]));
|
|
100
|
+
return response;
|
|
101
|
+
}
|
|
102
|
+
const streamed = (response.headers.get('content-type') || '').startsWith('text/event-stream');
|
|
103
|
+
if (response.status === 200 && response.type === 'basic' && !streamed) {
|
|
104
|
+
event.waitUntil(softrKeepCopy(owner, cacheName, key, response.clone()).catch(() => {}));
|
|
105
|
+
}
|
|
106
|
+
return response;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
const copy = await caches.match(key, { cacheName });
|
|
109
|
+
if (copy) {
|
|
110
|
+
softrSetShowingCopies(true);
|
|
111
|
+
return copy;
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
})());
|
|
116
|
+
});
|
|
117
|
+
`;
|
|
118
|
+
|
|
119
|
+
//#endregion
|
|
120
|
+
export { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, OFFLINE_USER_HEADER, OFFLINE_WORKER, WORKER_PATH };
|
package/package.json
CHANGED
|
@@ -1,41 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softr/sdk",
|
|
3
|
-
"version": "1.16.0
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
|
-
".": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
},
|
|
10
|
-
"./
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"types": "./dist/vite.d.ts",
|
|
20
|
-
"import": "./dist/vite.js"
|
|
21
|
-
},
|
|
22
|
-
"./logo-icon": {
|
|
23
|
-
"types": "./dist/logo-icon.d.ts",
|
|
24
|
-
"import": "./dist/logo-icon.js"
|
|
25
|
-
}
|
|
26
|
-
},
|
|
27
|
-
"bin": {
|
|
28
|
-
"softr-sdk": "./dist/cli.js"
|
|
29
|
-
},
|
|
30
|
-
"files": [
|
|
31
|
-
"dist",
|
|
32
|
-
"schema",
|
|
33
|
-
"skills",
|
|
34
|
-
"!skills/_artifacts",
|
|
35
|
-
"CHANGELOG.md"
|
|
36
|
-
],
|
|
37
|
-
"publishConfig": {
|
|
38
|
-
"access": "public"
|
|
6
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
7
|
+
"./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" },
|
|
8
|
+
"./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
|
|
9
|
+
"./vite": { "types": "./dist/vite.d.ts", "import": "./dist/vite.js" },
|
|
10
|
+
"./logo-icon": { "types": "./dist/logo-icon.d.ts", "import": "./dist/logo-icon.js" }
|
|
11
|
+
},
|
|
12
|
+
"bin": { "softr-sdk": "./dist/cli.js" },
|
|
13
|
+
"files": ["dist", "schema", "skills", "!skills/_artifacts", "CHANGELOG.md"],
|
|
14
|
+
"publishConfig": { "access": "public" },
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsdown",
|
|
17
|
+
"test": "node --import ./src/test-utils/setup.ts --test",
|
|
18
|
+
"typecheck": "tsc --noEmit"
|
|
39
19
|
},
|
|
40
20
|
"dependencies": {
|
|
41
21
|
"zod": "^4.4.3"
|
|
@@ -63,17 +43,10 @@
|
|
|
63
43
|
"optional": true
|
|
64
44
|
}
|
|
65
45
|
},
|
|
66
|
-
"keywords": [
|
|
67
|
-
"tanstack-intent"
|
|
68
|
-
],
|
|
46
|
+
"keywords": ["tanstack-intent"],
|
|
69
47
|
"intent": {
|
|
70
48
|
"version": 1,
|
|
71
49
|
"repo": "@softr/sdk",
|
|
72
50
|
"docs": "https://www.npmjs.com/package/@softr/sdk"
|
|
73
|
-
},
|
|
74
|
-
"scripts": {
|
|
75
|
-
"build": "tsdown",
|
|
76
|
-
"test": "node --import ./src/test-utils/setup.ts --test",
|
|
77
|
-
"typecheck": "tsc --noEmit"
|
|
78
51
|
}
|
|
79
|
-
}
|
|
52
|
+
}
|
|
@@ -57,6 +57,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
57
57
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
58
58
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
59
59
|
| Let visitors turn on push notifications | [push-notifications/SKILL.md](./push-notifications/SKILL.md) |
|
|
60
|
+
| Let the app open without internet, or show that the visitor is offline | [offline/SKILL.md](./offline/SKILL.md) |
|
|
60
61
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
61
62
|
|
|
62
63
|
## Quick Decision Tree
|
|
@@ -104,6 +105,9 @@ Adding an install button, or making the app installable?
|
|
|
104
105
|
Letting visitors turn on push notifications, or "notify users when …"?
|
|
105
106
|
load softr-sdk/push-notifications
|
|
106
107
|
|
|
108
|
+
Letting the app work offline, or showing that the visitor is offline?
|
|
109
|
+
load softr-sdk/offline
|
|
110
|
+
|
|
107
111
|
Showing a date, a time or a number on a page?
|
|
108
112
|
load softr-sdk/formatting
|
|
109
113
|
|
|
@@ -134,11 +134,10 @@ type AuthErrorCode =
|
|
|
134
134
|
| 'notAuthenticated' // a call that needs a signed-in visitor, made by one who is not
|
|
135
135
|
| 'emailDomainNotAllowed' // signUp, signInWithGoogle: the app lets only some email domains sign up, and this is not one
|
|
136
136
|
| 'linkExpired' // checkPasswordLink, setPasswordWithLink: the link is used, expired or no longer valid
|
|
137
|
-
| 'notEnabled'
|
|
138
|
-
| 'userLimitReached' // any call that signs a visitor in or up: the plan of the app's workspace has no room for this user
|
|
137
|
+
| 'notEnabled' // signInWithGoogle: the app's plan no longer includes Google sign-in
|
|
139
138
|
```
|
|
140
139
|
|
|
141
|
-
Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed.
|
|
140
|
+
Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed.
|
|
142
141
|
|
|
143
142
|
`code` is typed as every code the SDK produces, not the ones a given call can answer, so a `switch` needs a `default` even when the cases above it are complete. Give it a message rather than leaving it out.
|
|
144
143
|
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: offline
|
|
3
|
+
description: >-
|
|
4
|
+
Let the published app open without internet and show the pages and data the
|
|
5
|
+
visitor last loaded, read only: useOfflineMode, the OfflineMode type, the
|
|
6
|
+
offline banner and saves made offline. The service worker is already served,
|
|
7
|
+
never write one.
|
|
8
|
+
metadata:
|
|
9
|
+
type: sub-skill
|
|
10
|
+
library: softr-sdk
|
|
11
|
+
library_version: 1.16.0
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
# Offline mode
|
|
15
|
+
|
|
16
|
+
With offline mode on, the published app opens without internet and shows the pages and data the visitor already loaded while online, as they were then, sometimes a little older. Pages the visitor never opened are not there: a link to one shows the app's error page. Offline mode keeps nothing to save later: a save made offline fails as it would on any network error, and the app tells the visitor, unless the app has its own offline saving.
|
|
17
|
+
|
|
18
|
+
> **CRITICAL**: Never write a service worker, a `public/sw.js`, or any `navigator.serviceWorker` or `caches` code for offline. The app already serves its service worker, shared with push notifications, and `useOfflineMode()` turns offline mode on. A worker of the app's own replaces it, and push notifications stop arriving.
|
|
19
|
+
>
|
|
20
|
+
> **CRITICAL**: `useOfflineMode()` keeps reads only. Saving offline is app code, built only when the builder asks for it: the changes wait in IndexedDB in the page and are sent when the connection is back. It never goes into a service worker.
|
|
21
|
+
|
|
22
|
+
## Setup
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { useOfflineMode } from '@softr/sdk'
|
|
26
|
+
import type { OfflineMode, OfflineModeOptions } from '@softr/sdk'
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
type OfflineModeOptions = {
|
|
31
|
+
enabled?: boolean // false turns offline mode off and deletes what browsers kept; defaults to true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type OfflineMode = {
|
|
35
|
+
online: boolean // false while the browser has no connection, or the app shows saved copies because it cannot reach the server; always true during server rendering
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Core Patterns
|
|
40
|
+
|
|
41
|
+
### Turning it on
|
|
42
|
+
|
|
43
|
+
Call `useOfflineMode()` once, in `RootDocument` in `src/routes/__root.tsx`, so every page is kept. Call it nowhere else: each call also turns offline mode on or off. Render the banner from the same place. Use the banner component the template ships when it has one.
|
|
44
|
+
|
|
45
|
+
```tsx
|
|
46
|
+
function OfflineBanner() {
|
|
47
|
+
const { online } = useOfflineMode()
|
|
48
|
+
if (online) return null
|
|
49
|
+
return <div role="status">You're offline. Showing the last saved data.</div>
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Offline mode works only on the published app. Inside the Studio preview `online` still follows the connection, but nothing is kept on the device. That is expected, not a bug to fix.
|
|
54
|
+
|
|
55
|
+
### Saves made offline
|
|
56
|
+
|
|
57
|
+
A save made offline rejects like any failed request. Catch it as usual, and when `navigator.onLine` is `false`, say that the visitor is offline rather than showing a generic error. Do not call `useOfflineMode()` in the form for this:
|
|
58
|
+
|
|
59
|
+
```tsx
|
|
60
|
+
import { toast } from 'sonner'
|
|
61
|
+
|
|
62
|
+
// `save` is the form's own server function.
|
|
63
|
+
save(values).catch(() =>
|
|
64
|
+
toast.error(navigator.onLine ? 'Could not save your changes.' : "You're offline. Connect to save your changes."),
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Signing out
|
|
69
|
+
|
|
70
|
+
Nothing to add. The copies kept on the device are deleted when the visitor signs out, or when someone else signs in on the same browser.
|
|
71
|
+
|
|
72
|
+
### Turning it off
|
|
73
|
+
|
|
74
|
+
Remove the banner, and keep one call in `RootDocument` as `useOfflineMode({ enabled: false })`. That deletes what visitors' browsers kept the next time they open the app. Removing the call instead leaves offline mode on in browsers that ran it: they keep the visitor's copies, and keep saving new ones, until the visitor signs out or someone else signs in.
|
|
75
|
+
|
|
76
|
+
## Common Mistakes
|
|
77
|
+
|
|
78
|
+
### CRITICAL Writing a service worker for offline
|
|
79
|
+
|
|
80
|
+
Wrong:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
navigator.serviceWorker.register('/sw.js')
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Correct:
|
|
87
|
+
|
|
88
|
+
```tsx
|
|
89
|
+
const { online } = useOfflineMode()
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The app serves one service worker for push and offline mode. A worker of the app's own replaces it, so push notifications stop and nothing is kept offline.
|
|
93
|
+
|
|
94
|
+
Source: packages/sdk/src/offline.ts
|
|
95
|
+
|
|
96
|
+
### HIGH Calling the hook only on some pages
|
|
97
|
+
|
|
98
|
+
Wrong:
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
// src/routes/_app/orders.tsx
|
|
102
|
+
const { online } = useOfflineMode()
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Correct:
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
// RootDocument in src/routes/__root.tsx
|
|
109
|
+
<OfflineBanner />
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
A page is kept for offline only while the hook runs. Called from one page, every other page is missing offline.
|
|
113
|
+
|
|
114
|
+
Source: packages/sdk/src/offline.ts
|
|
115
|
+
|
|
116
|
+
## References
|
|
117
|
+
|
|
118
|
+
- [SKILL.md](../SKILL.md): the entrypoints and which one each export lives on
|
|
119
|
+
- [push-notifications/SKILL.md](../push-notifications/SKILL.md): push notifications, which share the same service worker
|