@softr/sdk 0.0.100 → 0.0.101-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/isomorphic.d.ts +1 -1
- package/dist/auth/isomorphic.js +2 -0
- package/dist/cache.js +25 -0
- package/dist/formatting.d.ts +3 -3
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/push.d.ts +52 -0
- package/dist/push.js +292 -0
- package/dist/pwa.d.ts +2 -2
- package/dist/pwa.js +8 -19
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +6 -2
- package/skills/softr-sdk/ai/SKILL.md +2 -2
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +1 -1
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/push-notifications/SKILL.md +140 -0
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
|
@@ -21,7 +21,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
|
21
21
|
* requestMiddleware: [softrAuthMiddleware()],
|
|
22
22
|
* }))
|
|
23
23
|
*/
|
|
24
|
-
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
24
|
+
declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
25
25
|
user: User | null;
|
|
26
26
|
permissions: {
|
|
27
27
|
datasources: {};
|
package/dist/auth/isomorphic.js
CHANGED
|
@@ -8,6 +8,7 @@ import { makePlatform } from "./platform.js";
|
|
|
8
8
|
import { settings } from "./methods/settings.js";
|
|
9
9
|
import { bootErrorMiddleware } from "../boot-error.js";
|
|
10
10
|
import { pwaMiddleware } from "../pwa.js";
|
|
11
|
+
import { pushMiddleware } from "../push.js";
|
|
11
12
|
import { faviconMiddleware } from "../favicon.js";
|
|
12
13
|
import { embeddingMiddleware } from "../embedding.js";
|
|
13
14
|
import { appIdentityMiddleware } from "../app-identity.js";
|
|
@@ -38,6 +39,7 @@ function softrAuthMiddleware() {
|
|
|
38
39
|
appIdentityMiddleware(),
|
|
39
40
|
bootErrorMiddleware(),
|
|
40
41
|
pwaMiddleware(),
|
|
42
|
+
pushMiddleware(),
|
|
41
43
|
faviconMiddleware()
|
|
42
44
|
]).server(async ({ next }) => {
|
|
43
45
|
async function getSession() {
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { logger } from "./logger.js";
|
|
2
|
+
|
|
3
|
+
//#region src/cache.ts
|
|
4
|
+
/**
|
|
5
|
+
* Reads through a short cache. Never rejects: a failure is logged, reads as
|
|
6
|
+
* `null` and is not remembered, so the next request tries again.
|
|
7
|
+
*/
|
|
8
|
+
function readCached(what, ttlMs, current, store, load) {
|
|
9
|
+
const now = Date.now();
|
|
10
|
+
const cached = current();
|
|
11
|
+
if (cached !== void 0 && cached.expires > now) return cached.value;
|
|
12
|
+
const entry = {
|
|
13
|
+
expires: now + ttlMs,
|
|
14
|
+
value: load().catch((error) => {
|
|
15
|
+
logger.warn(`Could not read ${what}:`, error);
|
|
16
|
+
if (current() === entry) store(void 0);
|
|
17
|
+
return null;
|
|
18
|
+
})
|
|
19
|
+
};
|
|
20
|
+
store(entry);
|
|
21
|
+
return entry.value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
export { readCached };
|
package/dist/formatting.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react2 from "react";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/formatting.d.ts
|
|
@@ -94,7 +94,7 @@ declare function FormattingScope({
|
|
|
94
94
|
/** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
|
|
95
95
|
locale?: string;
|
|
96
96
|
children?: ReactNode;
|
|
97
|
-
}):
|
|
97
|
+
}): react2.FunctionComponentElement<react2.ProviderProps<Scope>>;
|
|
98
98
|
/**
|
|
99
99
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
100
100
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
@@ -115,6 +115,6 @@ declare function FormattedDate({
|
|
|
115
115
|
time?: boolean;
|
|
116
116
|
/** What renders while the visitor's zone is unknown. */
|
|
117
117
|
fallback?: ReactNode;
|
|
118
|
-
}):
|
|
118
|
+
}): react2.FunctionComponentElement<react2.FragmentProps>;
|
|
119
119
|
//#endregion
|
|
120
120
|
export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
|
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ import { FieldShape, SoftrFieldRegistry, fieldShape, formatDuration, formatField
|
|
|
16
16
|
import { useOverrides } from "./core/use-overrides.js";
|
|
17
17
|
import { useUserTimezone } from "./timezone.js";
|
|
18
18
|
import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
19
|
+
import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
|
|
19
20
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
20
21
|
import { Audience } from "./route/audience.js";
|
|
21
|
-
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 FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
|
22
|
+
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 FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, 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 User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { definePage, pageHead } from "./route/page.js";
|
|
|
6
6
|
import { toReturnPath } from "./auth/returnPath.js";
|
|
7
7
|
import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
|
|
8
8
|
import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
9
|
+
import { usePushNotifications } from "./push.js";
|
|
9
10
|
import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
10
11
|
import { softrMcpMiddleware } from "./mcp.js";
|
|
11
12
|
import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
@@ -14,4 +15,4 @@ import { useUserTimezone } from "./timezone.js";
|
|
|
14
15
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
15
16
|
import { Audience } from "./route/audience.js";
|
|
16
17
|
|
|
17
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
|
18
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DatasourceAction } from "./action.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/mcp.d.ts
|
|
5
5
|
|
|
@@ -31,6 +31,6 @@ type SoftrMcpOptions = {
|
|
|
31
31
|
* ],
|
|
32
32
|
* }))
|
|
33
33
|
*/
|
|
34
|
-
declare function softrMcpMiddleware(options?: SoftrMcpOptions):
|
|
34
|
+
declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
|
|
35
35
|
//#endregion
|
|
36
36
|
export { softrMcpMiddleware };
|
package/dist/package.js
CHANGED
package/dist/push.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import "@tanstack/react-start";
|
|
2
|
+
|
|
3
|
+
//#region src/push.d.ts
|
|
4
|
+
|
|
5
|
+
/** What the builder wrote in Studio for the prompt. Any of it may be missing. */
|
|
6
|
+
type PushPrompt = {
|
|
7
|
+
title: string | null;
|
|
8
|
+
message: string | null;
|
|
9
|
+
enableButtonLabel: string | null;
|
|
10
|
+
};
|
|
11
|
+
type PushNotifications = /** Loading, signed out, push off for this app or device, or a browser without push. */
|
|
12
|
+
{
|
|
13
|
+
status: "unavailable";
|
|
14
|
+
}
|
|
15
|
+
/** iPhone and iPad offer push only inside the installed app. */ | {
|
|
16
|
+
status: "install-first";
|
|
17
|
+
prompt: PushPrompt;
|
|
18
|
+
} | {
|
|
19
|
+
status: "ask";
|
|
20
|
+
prompt: PushPrompt;
|
|
21
|
+
/** The visitor skipped the prompt recently, within the builder's skip days. Hide the prompt. */
|
|
22
|
+
dismissed: boolean;
|
|
23
|
+
/** Asks the browser for permission and subscribes. Call it from a click. */
|
|
24
|
+
subscribe: () => Promise<void>;
|
|
25
|
+
/** Hides the prompt for as long as the builder set in Studio. */
|
|
26
|
+
dismiss: () => void;
|
|
27
|
+
} | {
|
|
28
|
+
status: "subscribed";
|
|
29
|
+
unsubscribe: () => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/** The visitor blocked notifications in the browser. Only they can undo it, in the browser's settings. */ | {
|
|
32
|
+
status: "blocked";
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Push notifications for the signed-in visitor. Call it once, in the one
|
|
36
|
+
* component that shows the prompt, rendered once in the root route's
|
|
37
|
+
* `RootDocument`, so this browser stays registered. Each call keeps state of
|
|
38
|
+
* its own, so a second call does not see a subscribe made through the first.
|
|
39
|
+
* Show a prompt only while `status` is `ask`
|
|
40
|
+
* and the prompt is not `dismissed`.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* function EnableNotifications() {
|
|
44
|
+
* const push = usePushNotifications()
|
|
45
|
+
* if (push.status !== "ask" || push.dismissed) return null
|
|
46
|
+
* const turnOn = () => push.subscribe().catch(() => toast.error("Notifications could not be turned on."))
|
|
47
|
+
* return <button onClick={turnOn}>{push.prompt.enableButtonLabel ?? "Turn on"}</button>
|
|
48
|
+
* }
|
|
49
|
+
*/
|
|
50
|
+
declare function usePushNotifications(): PushNotifications;
|
|
51
|
+
//#endregion
|
|
52
|
+
export { PushNotifications, PushPrompt, usePushNotifications };
|
package/dist/push.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
|
+
import { fetch } from "./fetch.js";
|
|
3
|
+
import { sessionConfig } from "./auth/config.js";
|
|
4
|
+
import { readSessionToken } from "./auth/session.js";
|
|
5
|
+
import { readCached } from "./cache.js";
|
|
6
|
+
import { detectPlatform, isStandalone } from "./pwa.js";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { useCallback, useEffect, useState } from "react";
|
|
9
|
+
import { createMiddleware } from "@tanstack/react-start";
|
|
10
|
+
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
11
|
+
|
|
12
|
+
//#region src/push.ts
|
|
13
|
+
const WORKER_PATH = "/_softr/sw.js";
|
|
14
|
+
const SETTINGS_PATH = "/_softr/push.json";
|
|
15
|
+
const SUBSCRIPTION_PATH = "/_softr/push";
|
|
16
|
+
const TTL_MS = 6e4;
|
|
17
|
+
const promptSchema = z.object({
|
|
18
|
+
title: z.string().nullable(),
|
|
19
|
+
message: z.string().nullable(),
|
|
20
|
+
enableButtonLabel: z.string().nullable(),
|
|
21
|
+
skipDays: z.number().nullable()
|
|
22
|
+
});
|
|
23
|
+
const settingsSchema = z.object({
|
|
24
|
+
vapidPublicKey: z.string(),
|
|
25
|
+
desktopEnabled: z.boolean(),
|
|
26
|
+
mobileEnabled: z.boolean(),
|
|
27
|
+
permissionPrompt: promptSchema.nullable()
|
|
28
|
+
});
|
|
29
|
+
const browserSubscriptionSchema = z.object({
|
|
30
|
+
endpoint: z.string(),
|
|
31
|
+
keys: z.object({
|
|
32
|
+
p256dh: z.string(),
|
|
33
|
+
auth: z.string()
|
|
34
|
+
})
|
|
35
|
+
});
|
|
36
|
+
let cachedSettings;
|
|
37
|
+
let cachedWorker;
|
|
38
|
+
function platformPushUrl() {
|
|
39
|
+
const { applicationId } = sessionConfig();
|
|
40
|
+
return `${softrApiUrl("SOFTR_PLATFORM_API_URL")}/v1/vibe/applications/${applicationId}/push`;
|
|
41
|
+
}
|
|
42
|
+
function readSettings() {
|
|
43
|
+
return readCached("push notifications from Softr", TTL_MS, () => cachedSettings, (entry) => cachedSettings = entry, async () => {
|
|
44
|
+
const response = await fetch(platformPushUrl(), { headers: { accept: "application/json" } });
|
|
45
|
+
if (response.status === 404) return null;
|
|
46
|
+
if (!response.ok) throw new Error(`The platform answered ${response.status}`);
|
|
47
|
+
return settingsSchema.parse(await response.json());
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function readWorker() {
|
|
51
|
+
return readCached("the push service worker from Softr", TTL_MS, () => cachedWorker, (entry) => cachedWorker = entry, async () => {
|
|
52
|
+
const response = await fetch(`${softrApiUrl("SOFTR_PLATFORM_API_URL")}/pwa/sw.js`);
|
|
53
|
+
if (!response.ok) throw new Error(`The platform answered ${response.status}`);
|
|
54
|
+
return response.text();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Serves push notifications from the app's own origin: the service worker, the
|
|
59
|
+
* app's push settings, and saving or removing this browser's subscription for
|
|
60
|
+
* the signed-in visitor. Every other request passes through untouched.
|
|
61
|
+
*/
|
|
62
|
+
function pushMiddleware() {
|
|
63
|
+
return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
|
|
64
|
+
if (pathname === WORKER_PATH && request.method === "GET") {
|
|
65
|
+
const worker = await readWorker();
|
|
66
|
+
if (worker === null) return new Response(null, {
|
|
67
|
+
status: 503,
|
|
68
|
+
headers: { "cache-control": "no-store" }
|
|
69
|
+
});
|
|
70
|
+
return new Response(worker, { headers: {
|
|
71
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
72
|
+
"cache-control": "no-cache",
|
|
73
|
+
"service-worker-allowed": "/"
|
|
74
|
+
} });
|
|
75
|
+
}
|
|
76
|
+
if (pathname === SETTINGS_PATH && request.method === "GET") {
|
|
77
|
+
const settings = await readSettings();
|
|
78
|
+
if (settings === null) return new Response(null, { status: 404 });
|
|
79
|
+
return Response.json(settings, { headers: { "cache-control": "no-store" } });
|
|
80
|
+
}
|
|
81
|
+
if (pathname === SUBSCRIPTION_PATH && (request.method === "POST" || request.method === "DELETE")) {
|
|
82
|
+
if (!request.headers.get("content-type")?.startsWith("application/json")) return new Response(null, { status: 415 });
|
|
83
|
+
const token = readSessionToken();
|
|
84
|
+
if (token === null) return new Response(null, { status: 401 });
|
|
85
|
+
const body = z.object({ subscription: browserSubscriptionSchema }).safeParse(await request.json().catch(() => null));
|
|
86
|
+
if (!body.success) return new Response(null, { status: 400 });
|
|
87
|
+
const response = await (request.method === "POST" ? fetch(platformPushUrl(), {
|
|
88
|
+
method: "POST",
|
|
89
|
+
headers: {
|
|
90
|
+
"content-type": "application/json",
|
|
91
|
+
authorization: `Bearer ${token}`
|
|
92
|
+
},
|
|
93
|
+
body: JSON.stringify({
|
|
94
|
+
origin: new URL(request.url).origin,
|
|
95
|
+
userAgent: request.headers.get("user-agent"),
|
|
96
|
+
subscription: body.data.subscription
|
|
97
|
+
})
|
|
98
|
+
}) : fetch(`${platformPushUrl()}?${new URLSearchParams({ endpoint: body.data.subscription.endpoint })}`, {
|
|
99
|
+
method: "DELETE",
|
|
100
|
+
headers: { authorization: `Bearer ${token}` }
|
|
101
|
+
})).catch(() => null);
|
|
102
|
+
if (response === null) return new Response(null, { status: 502 });
|
|
103
|
+
return new Response(null, { status: response.ok ? 204 : response.status });
|
|
104
|
+
}
|
|
105
|
+
return next();
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const DISMISSED_AT_KEY = "softr-push-dismissed-at";
|
|
109
|
+
/**
|
|
110
|
+
* Push notifications for the signed-in visitor. Call it once, in the one
|
|
111
|
+
* component that shows the prompt, rendered once in the root route's
|
|
112
|
+
* `RootDocument`, so this browser stays registered. Each call keeps state of
|
|
113
|
+
* its own, so a second call does not see a subscribe made through the first.
|
|
114
|
+
* Show a prompt only while `status` is `ask`
|
|
115
|
+
* and the prompt is not `dismissed`.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* function EnableNotifications() {
|
|
119
|
+
* const push = usePushNotifications()
|
|
120
|
+
* if (push.status !== "ask" || push.dismissed) return null
|
|
121
|
+
* const turnOn = () => push.subscribe().catch(() => toast.error("Notifications could not be turned on."))
|
|
122
|
+
* return <button onClick={turnOn}>{push.prompt.enableButtonLabel ?? "Turn on"}</button>
|
|
123
|
+
* }
|
|
124
|
+
*/
|
|
125
|
+
function usePushNotifications() {
|
|
126
|
+
const signedIn = useRouteContext({
|
|
127
|
+
from: rootRouteId,
|
|
128
|
+
select: (context) => context.user !== null
|
|
129
|
+
});
|
|
130
|
+
const [settings, setSettings] = useState(null);
|
|
131
|
+
const [registration, setRegistration] = useState(null);
|
|
132
|
+
const [subscribed, setSubscribed] = useState(false);
|
|
133
|
+
const [permission, setPermission] = useState("default");
|
|
134
|
+
const [dismissedAt, setDismissedAt] = useState(null);
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
|
|
137
|
+
if (!signedIn) {
|
|
138
|
+
try {
|
|
139
|
+
localStorage.removeItem(DISMISSED_AT_KEY);
|
|
140
|
+
} catch {}
|
|
141
|
+
setDismissedAt(null);
|
|
142
|
+
setSettings(null);
|
|
143
|
+
setSubscribed(false);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
let cancelled = false;
|
|
147
|
+
(async () => {
|
|
148
|
+
const response = await globalThis.fetch(SETTINGS_PATH, { headers: { accept: "application/json" } });
|
|
149
|
+
if (!response.ok) return;
|
|
150
|
+
const parsed = settingsSchema.safeParse(await response.json());
|
|
151
|
+
if (!parsed.success || cancelled) return;
|
|
152
|
+
setDismissedAt(readDismissedAt());
|
|
153
|
+
setSettings(parsed.data);
|
|
154
|
+
if (!("PushManager" in window) || !("Notification" in window)) return;
|
|
155
|
+
setPermission(Notification.permission);
|
|
156
|
+
const registered = await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
|
|
157
|
+
if (cancelled) return;
|
|
158
|
+
setRegistration(registered);
|
|
159
|
+
if (Notification.permission !== "granted") return;
|
|
160
|
+
const subscription = await registered.pushManager.getSubscription() ?? await registered.pushManager.subscribe({
|
|
161
|
+
userVisibleOnly: true,
|
|
162
|
+
applicationServerKey: decodeBase64Url(parsed.data.vapidPublicKey)
|
|
163
|
+
});
|
|
164
|
+
if (cancelled) return;
|
|
165
|
+
setSubscribed(await sendSubscription("POST", subscription));
|
|
166
|
+
})().catch((error) => console.warn("[@softr/sdk] Could not set up push notifications:", error));
|
|
167
|
+
return () => {
|
|
168
|
+
cancelled = true;
|
|
169
|
+
};
|
|
170
|
+
}, [signedIn]);
|
|
171
|
+
useEffect(() => {
|
|
172
|
+
if (registration === null) return;
|
|
173
|
+
return listenToWorker();
|
|
174
|
+
}, [registration]);
|
|
175
|
+
const subscribe = useCallback(async () => {
|
|
176
|
+
if (registration === null || settings === null) return;
|
|
177
|
+
const granted = await Notification.requestPermission();
|
|
178
|
+
setPermission(granted);
|
|
179
|
+
if (granted !== "granted") return;
|
|
180
|
+
const subscription = await registration.pushManager.subscribe({
|
|
181
|
+
userVisibleOnly: true,
|
|
182
|
+
applicationServerKey: decodeBase64Url(settings.vapidPublicKey)
|
|
183
|
+
});
|
|
184
|
+
if (!await sendSubscription("POST", subscription)) {
|
|
185
|
+
await subscription.unsubscribe();
|
|
186
|
+
throw new Error("Could not turn on push notifications");
|
|
187
|
+
}
|
|
188
|
+
setSubscribed(true);
|
|
189
|
+
}, [registration, settings]);
|
|
190
|
+
const unsubscribe = useCallback(async () => {
|
|
191
|
+
const subscription = await registration?.pushManager.getSubscription();
|
|
192
|
+
if (!subscription) return;
|
|
193
|
+
await sendSubscription("DELETE", subscription);
|
|
194
|
+
await subscription.unsubscribe();
|
|
195
|
+
setSubscribed(false);
|
|
196
|
+
}, [registration]);
|
|
197
|
+
const dismiss = useCallback(() => {
|
|
198
|
+
const now = Date.now();
|
|
199
|
+
try {
|
|
200
|
+
localStorage.setItem(DISMISSED_AT_KEY, String(now));
|
|
201
|
+
} catch {}
|
|
202
|
+
setDismissedAt(now);
|
|
203
|
+
}, []);
|
|
204
|
+
if (settings === null) return { status: "unavailable" };
|
|
205
|
+
const platform = detectPlatform();
|
|
206
|
+
if (platform !== "desktop" ? !settings.mobileEnabled : !settings.desktopEnabled) return { status: "unavailable" };
|
|
207
|
+
const prompt = {
|
|
208
|
+
title: settings.permissionPrompt?.title ?? null,
|
|
209
|
+
message: settings.permissionPrompt?.message ?? null,
|
|
210
|
+
enableButtonLabel: settings.permissionPrompt?.enableButtonLabel ?? null
|
|
211
|
+
};
|
|
212
|
+
if (platform === "ios" && !isStandalone()) return {
|
|
213
|
+
status: "install-first",
|
|
214
|
+
prompt
|
|
215
|
+
};
|
|
216
|
+
if (registration === null) return { status: "unavailable" };
|
|
217
|
+
if (subscribed) return {
|
|
218
|
+
status: "subscribed",
|
|
219
|
+
unsubscribe
|
|
220
|
+
};
|
|
221
|
+
if (permission === "denied") return { status: "blocked" };
|
|
222
|
+
return {
|
|
223
|
+
status: "ask",
|
|
224
|
+
prompt,
|
|
225
|
+
dismissed: isDismissed(dismissedAt, settings.permissionPrompt?.skipDays ?? null),
|
|
226
|
+
subscribe,
|
|
227
|
+
dismiss
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
async function sendSubscription(method, subscription) {
|
|
231
|
+
return (await globalThis.fetch(SUBSCRIPTION_PATH, {
|
|
232
|
+
method,
|
|
233
|
+
headers: { "content-type": "application/json" },
|
|
234
|
+
body: JSON.stringify({ subscription: subscription.toJSON() })
|
|
235
|
+
})).ok;
|
|
236
|
+
}
|
|
237
|
+
/** A missing skip-days setting means a skipped prompt never comes back on its own. */
|
|
238
|
+
function isDismissed(dismissedAt, skipDays) {
|
|
239
|
+
if (dismissedAt === null) return false;
|
|
240
|
+
if (skipDays === null) return true;
|
|
241
|
+
return Date.now() - dismissedAt < Math.max(skipDays, 1) * 24 * 60 * 60 * 1e3;
|
|
242
|
+
}
|
|
243
|
+
function readDismissedAt() {
|
|
244
|
+
try {
|
|
245
|
+
const stored = Number(localStorage.getItem(DISMISSED_AT_KEY));
|
|
246
|
+
return Number.isFinite(stored) && stored > 0 ? stored : null;
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Answers the service worker, which routes a notification click to the
|
|
253
|
+
* installed app when it is open, and keeps the app icon's badge right.
|
|
254
|
+
*/
|
|
255
|
+
function listenToWorker() {
|
|
256
|
+
const worker = navigator.serviceWorker;
|
|
257
|
+
const standalone = isStandalone();
|
|
258
|
+
if (standalone) worker.controller?.postMessage({ type: "pwa-standalone-opened" });
|
|
259
|
+
const onMessage = (event) => {
|
|
260
|
+
if (event.data === "is-this-standalone") {
|
|
261
|
+
event.ports[0]?.postMessage(standalone ? "yes" : "no");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (event.data?.type === "softr-pwa-redirect" && typeof event.data.url === "string") {
|
|
265
|
+
const target = new URL(event.data.url, window.location.href);
|
|
266
|
+
if (target.origin === window.location.origin) window.location.assign(target.href);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
const onVisible = () => {
|
|
270
|
+
if (document.visibilityState === "visible") worker.controller?.postMessage("reset-badge-count");
|
|
271
|
+
};
|
|
272
|
+
const onInstallOffered = () => worker.controller?.postMessage({ type: "pwa-uninstalled" });
|
|
273
|
+
worker.addEventListener("message", onMessage);
|
|
274
|
+
document.addEventListener("visibilitychange", onVisible);
|
|
275
|
+
window.addEventListener("beforeinstallprompt", onInstallOffered);
|
|
276
|
+
onVisible();
|
|
277
|
+
return () => {
|
|
278
|
+
worker.removeEventListener("message", onMessage);
|
|
279
|
+
document.removeEventListener("visibilitychange", onVisible);
|
|
280
|
+
window.removeEventListener("beforeinstallprompt", onInstallOffered);
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
function decodeBase64Url(value) {
|
|
284
|
+
const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
285
|
+
const binary = atob(base64);
|
|
286
|
+
const bytes = new Uint8Array(binary.length);
|
|
287
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
288
|
+
return bytes;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
//#endregion
|
|
292
|
+
export { pushMiddleware, usePushNotifications };
|
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react0 from "react";
|
|
2
2
|
import "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/pwa.d.ts
|
|
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
|
|
|
23
23
|
* )
|
|
24
24
|
* }
|
|
25
25
|
*/
|
|
26
|
-
declare function SoftrPwaHead():
|
|
26
|
+
declare function SoftrPwaHead(): react0.FunctionComponentElement<react0.FragmentProps>;
|
|
27
27
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
28
28
|
type PwaInstall = {
|
|
29
29
|
available: false;
|
package/dist/pwa.js
CHANGED
|
@@ -2,6 +2,7 @@ import { logger } from "./logger.js";
|
|
|
2
2
|
import { softrApiUrl } from "./softr-api.js";
|
|
3
3
|
import { fetch } from "./fetch.js";
|
|
4
4
|
import { sessionConfig } from "./auth/config.js";
|
|
5
|
+
import { readCached } from "./cache.js";
|
|
5
6
|
import { z } from "zod";
|
|
6
7
|
import { Fragment, createElement, useEffect, useState } from "react";
|
|
7
8
|
import { createMiddleware } from "@tanstack/react-start";
|
|
@@ -20,24 +21,9 @@ const pwaSchema = z.object({
|
|
|
20
21
|
})
|
|
21
22
|
});
|
|
22
23
|
let cached;
|
|
23
|
-
/**
|
|
24
|
-
* The app's PWA, or `null` when it is not installable right now. Never
|
|
25
|
-
* rejects: a failure reads as not installable and is not remembered, so the
|
|
26
|
-
* next request tries again.
|
|
27
|
-
*/
|
|
24
|
+
/** The app's PWA, or `null` when it is not installable right now. */
|
|
28
25
|
function readPwa() {
|
|
29
|
-
|
|
30
|
-
if (cached !== void 0 && cached.expires > now) return cached.pwa;
|
|
31
|
-
const entry = {
|
|
32
|
-
expires: now + TTL_MS,
|
|
33
|
-
pwa: fetchPwa().catch((error) => {
|
|
34
|
-
logger.warn("Could not read the PWA settings:", error);
|
|
35
|
-
if (cached === entry) cached = void 0;
|
|
36
|
-
return null;
|
|
37
|
-
})
|
|
38
|
-
};
|
|
39
|
-
cached = entry;
|
|
40
|
-
return entry.pwa;
|
|
26
|
+
return readCached("the PWA settings", TTL_MS, () => cached, (entry) => cached = entry, fetchPwa);
|
|
41
27
|
}
|
|
42
28
|
async function fetchPwa() {
|
|
43
29
|
const { applicationId } = sessionConfig();
|
|
@@ -123,7 +109,7 @@ const installSchema = pwaSchema.shape.install;
|
|
|
123
109
|
function usePwaInstall() {
|
|
124
110
|
const [install, setInstall] = useState({ available: false });
|
|
125
111
|
useEffect(() => {
|
|
126
|
-
if (
|
|
112
|
+
if (isStandalone()) return;
|
|
127
113
|
let cancelled = false;
|
|
128
114
|
globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
|
|
129
115
|
if (!response.ok) return;
|
|
@@ -147,6 +133,9 @@ function detectPlatform() {
|
|
|
147
133
|
if (/Android/.test(userAgent)) return "android";
|
|
148
134
|
return "desktop";
|
|
149
135
|
}
|
|
136
|
+
function isStandalone() {
|
|
137
|
+
return window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true;
|
|
138
|
+
}
|
|
150
139
|
|
|
151
140
|
//#endregion
|
|
152
|
-
export { SoftrPwaHead, pwaMiddleware, usePwaInstall };
|
|
141
|
+
export { SoftrPwaHead, detectPlatform, isStandalone, pwaMiddleware, usePwaInstall };
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: core
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
# Softr SDK core
|
|
@@ -32,7 +32,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
32
32
|
|
|
33
33
|
| Import | Runs | Holds |
|
|
34
34
|
| --- | --- | --- |
|
|
35
|
-
| `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
|
|
35
|
+
| `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `usePushNotifications`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
|
|
36
36
|
| `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration`, `ai` |
|
|
37
37
|
| `@softr/sdk/client` | Browser only | `useFileUpload` |
|
|
38
38
|
| `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
|
|
@@ -53,6 +53,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
53
53
|
| Call a connected third-party API (Slack, Stripe, Gmail, …), or an AI model on the user's own provider account | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
54
54
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
55
55
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
56
|
+
| Let visitors turn on push notifications | [push-notifications/SKILL.md](./push-notifications/SKILL.md) |
|
|
56
57
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
57
58
|
|
|
58
59
|
## Quick Decision Tree
|
|
@@ -97,6 +98,9 @@ Opening the app to an AI assistant over MCP?
|
|
|
97
98
|
Adding an install button, or making the app installable?
|
|
98
99
|
load softr-sdk/pwa
|
|
99
100
|
|
|
101
|
+
Letting visitors turn on push notifications, or "notify users when …"?
|
|
102
|
+
load softr-sdk/push-notifications
|
|
103
|
+
|
|
100
104
|
Showing a date, a time or a number on a page?
|
|
101
105
|
load softr-sdk/formatting
|
|
102
106
|
|
|
@@ -13,7 +13,7 @@ description: >-
|
|
|
13
13
|
metadata:
|
|
14
14
|
type: sub-skill
|
|
15
15
|
library: softr-sdk
|
|
16
|
-
library_version: 0.0.
|
|
16
|
+
library_version: 0.0.101-alpha.0
|
|
17
17
|
---
|
|
18
18
|
|
|
19
19
|
**Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -26,7 +26,7 @@ An app asks a model through an AI action. Softr runs the call on its own provide
|
|
|
26
26
|
|
|
27
27
|
Never choose silently between Softr AI and the user's own account. Decide for each AI feature, before you write its code, in this order:
|
|
28
28
|
|
|
29
|
-
1. The user said who runs it: follow it. "My OpenAI key" or "our Anthropic account", with exactly one integration of that type in `integration_list`: use that one, without asking. A new
|
|
29
|
+
1. The user said who runs it: follow it. "My OpenAI key" or "our Anthropic account", with exactly one integration of that type in `integration_list`: use that one, without asking. A new key of a provider they named — they asked for a new one, or the workspace holds none of that type — is one `requestinput` of type `integration` for that type: its card connects one. A connected key runs the feature; a skipped request means Softr AI, and you say so. Several keys of that type, or "my own key" with no provider: ask (step 4). A provider or a model named without "my" or "our" ("use Claude", "summarise with GPT") is a model preference on Softr AI, not a reason to ask.
|
|
30
30
|
2. The app already has AI features: follow the choice they made, and say so in one line.
|
|
31
31
|
3. `integration_list` shows no `OPEN_AI`, `ANTHROPIC_AI` or `GEMINI_AI` integration: use Softr AI, and say so in one line. Call the tool; do not assume the answer.
|
|
32
32
|
4. Otherwise ask with one `requestinput` of type `aiProvider`. Its card lists every key the workspace holds and every provider to connect, unfiltered. The answer is Softr AI, or the integration with its id and type: follow it, even when it is another provider than the one the user named. A declined request means Softr AI: use it, and say so in one line.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.
|
|
10
|
+
library_version: 0.0.101-alpha.0
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
|
|
@@ -7,7 +7,7 @@ description: >-
|
|
|
7
7
|
metadata:
|
|
8
8
|
type: sub-skill
|
|
9
9
|
library: softr-sdk
|
|
10
|
-
library_version: 0.0.
|
|
10
|
+
library_version: 0.0.101-alpha.0
|
|
11
11
|
---
|
|
12
12
|
|
|
13
13
|
**Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP.
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: push-notifications
|
|
3
|
+
description: >-
|
|
4
|
+
Let signed-in visitors turn on push notifications: usePushNotifications for
|
|
5
|
+
the prompt, its states and the Studio texts, the PushNotifications and
|
|
6
|
+
PushPrompt types, and how to check that push is on for the app. Notifications
|
|
7
|
+
are sent by Softr Workflows, never by app code; the service worker is already
|
|
8
|
+
served, never write one.
|
|
9
|
+
metadata:
|
|
10
|
+
type: sub-skill
|
|
11
|
+
library: softr-sdk
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
# Push notifications
|
|
16
|
+
|
|
17
|
+
The builder turns push on in Studio, under Users → Notifications, for desktop, mobile or both, and writes the prompt's texts there. Notifications are sent by a Softr Workflow's "Send notification" action, which the builder sets up in Studio. What the app adds is one thing: a prompt that lets the signed-in visitor turn notifications on in this browser.
|
|
18
|
+
|
|
19
|
+
> **CRITICAL**: Never write a service worker, a `public/sw.js`, or any `navigator.serviceWorker`, `PushManager` or `Notification` code of your own. The app already serves its service worker, and `usePushNotifications()` registers it, subscribes and unsubscribes.
|
|
20
|
+
>
|
|
21
|
+
> **CRITICAL**: Never send a push from app code. Sending is a Softr Workflow's "Send notification" action. When the builder asks for "notify X when Y", point them to that workflow; when Y is something the app does, the app triggers the workflow (load the Softr SDK `workflows` guidance). The app itself adds only the prompt.
|
|
22
|
+
|
|
23
|
+
## Setup
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { usePushNotifications } from '@softr/sdk'
|
|
27
|
+
import type { PushNotifications, PushPrompt } from '@softr/sdk'
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
type PushPrompt = {
|
|
32
|
+
title: string | null // what the builder wrote in Studio; any of these may be missing
|
|
33
|
+
message: string | null
|
|
34
|
+
enableButtonLabel: string | null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type PushNotifications =
|
|
38
|
+
| { status: 'unavailable' } // loading, signed out, push off, this device type off, or no browser support
|
|
39
|
+
| { status: 'install-first'; prompt: PushPrompt } // iPhone and iPad: push works only in the installed app
|
|
40
|
+
| {
|
|
41
|
+
status: 'ask'
|
|
42
|
+
prompt: PushPrompt
|
|
43
|
+
dismissed: boolean // skipped recently, within the builder's skip days; hide the prompt
|
|
44
|
+
subscribe: () => Promise<void> // call from a click
|
|
45
|
+
dismiss: () => void
|
|
46
|
+
}
|
|
47
|
+
| { status: 'subscribed'; unsubscribe: () => Promise<void> }
|
|
48
|
+
| { status: 'blocked' } // blocked in the browser; only the visitor can undo it there
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Is push on for the app?
|
|
52
|
+
|
|
53
|
+
Ask the running app for `/_softr/push.json`: `200` means push is on, `404` means it is off in Studio or the plan does not include it. Do not build a prompt against a `404`: push has to be turned on first. A change in Studio can take up to two minutes to reach the app.
|
|
54
|
+
|
|
55
|
+
Push works only on the published app. Inside the Studio preview the hook always says `unavailable`, so the prompt never shows there. That is expected, not a bug to fix.
|
|
56
|
+
|
|
57
|
+
## Core Patterns
|
|
58
|
+
|
|
59
|
+
### The prompt
|
|
60
|
+
|
|
61
|
+
Render it once, in `RootDocument` in `src/routes/__root.tsx`, so it shows on every page and the browser stays registered for the visitor. Use the prompt component the template ships when it has one. It shows only on `ask`, and shows nothing on `install-first`: on iPhone and iPad, the app's install button does that job (load the Softr SDK `pwa` guidance).
|
|
62
|
+
|
|
63
|
+
Call `usePushNotifications()` in that one component only. Each call keeps state of its own: a second call, in a header or on a settings page, does not see a subscribe made through the first, so the prompt would stay on screen after the visitor said yes.
|
|
64
|
+
|
|
65
|
+
`subscribe()` rejects when the browser or Softr refuses. Catch it and tell the visitor, so the button never fails in silence.
|
|
66
|
+
|
|
67
|
+
```tsx
|
|
68
|
+
function EnableNotifications() {
|
|
69
|
+
const push = usePushNotifications()
|
|
70
|
+
if (push.status !== 'ask' || push.dismissed) return null
|
|
71
|
+
return (
|
|
72
|
+
<div role="dialog">
|
|
73
|
+
<p>{push.prompt.title ?? 'Turn on notifications'}</p>
|
|
74
|
+
<p>{push.prompt.message ?? 'Get notified about updates.'}</p>
|
|
75
|
+
<button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
|
|
76
|
+
{push.prompt.enableButtonLabel ?? 'Turn on'}
|
|
77
|
+
</button>
|
|
78
|
+
<button onClick={push.dismiss}>Not now</button>
|
|
79
|
+
</div>
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Fall back to your own wording only where the builder left a text empty. On `install-first`, point the visitor to installing the app (load the Softr SDK `pwa` guidance); do not ask for permission.
|
|
85
|
+
|
|
86
|
+
### Signing out
|
|
87
|
+
|
|
88
|
+
Nothing to add. The browser keeps its subscription when the visitor signs out, so signing back in does not ask again.
|
|
89
|
+
|
|
90
|
+
## Common Mistakes
|
|
91
|
+
|
|
92
|
+
### CRITICAL Asking for permission on page load
|
|
93
|
+
|
|
94
|
+
Wrong:
|
|
95
|
+
|
|
96
|
+
```tsx
|
|
97
|
+
useEffect(() => { push.status === 'ask' && push.subscribe() }, [push.status])
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Correct:
|
|
101
|
+
|
|
102
|
+
```tsx
|
|
103
|
+
<button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
|
|
104
|
+
{push.prompt.enableButtonLabel ?? 'Turn on'}
|
|
105
|
+
</button>
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Browsers ignore or block a permission request that no click started, and a visitor who blocks it can only undo that in the browser's settings.
|
|
109
|
+
|
|
110
|
+
Source: packages/sdk/src/push.ts
|
|
111
|
+
|
|
112
|
+
### HIGH Showing the prompt whatever the status
|
|
113
|
+
|
|
114
|
+
Wrong:
|
|
115
|
+
|
|
116
|
+
```tsx
|
|
117
|
+
const push = usePushNotifications()
|
|
118
|
+
return <button onClick={() => push.subscribe()}>Turn on notifications</button>
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Correct:
|
|
122
|
+
|
|
123
|
+
```tsx
|
|
124
|
+
const push = usePushNotifications()
|
|
125
|
+
if (push.status !== 'ask' || push.dismissed) return null
|
|
126
|
+
return (
|
|
127
|
+
<button onClick={() => push.subscribe().catch(() => toast.error('Notifications could not be turned on.'))}>
|
|
128
|
+
{push.prompt.enableButtonLabel ?? 'Turn on'}
|
|
129
|
+
</button>
|
|
130
|
+
)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The hook says `unavailable` when push is off in Studio, for this device type, or for a signed-out visitor. A prompt that skips the check shows in all of those, and on iPhone it asks for something the browser cannot give.
|
|
134
|
+
|
|
135
|
+
Source: packages/sdk/src/push.ts
|
|
136
|
+
|
|
137
|
+
## References
|
|
138
|
+
|
|
139
|
+
- [SKILL.md](../SKILL.md): the entrypoints and which one each export lives on
|
|
140
|
+
- [pwa/SKILL.md](../pwa/SKILL.md): installing the app, which iPhone and iPad need before push
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -10,7 +10,7 @@ description: >-
|
|
|
10
10
|
metadata:
|
|
11
11
|
type: sub-skill
|
|
12
12
|
library: softr-sdk
|
|
13
|
-
library_version: 0.0.
|
|
13
|
+
library_version: 0.0.101-alpha.0
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. The same holds for any helper that calls `ds`: declare it inside the handler. A function at module level that calls `ds` keeps the server-only import in the browser bundle, and every page stops loading until it moves. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: sub-skill
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.
|
|
12
|
+
library_version: 0.0.101-alpha.0
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
**Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.
|