@softr/sdk 0.0.101-alpha.1 → 0.0.101-seo.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/auth/context.d.ts +5 -0
  2. package/dist/auth/isomorphic.d.ts +2 -1
  3. package/dist/auth/isomorphic.js +4 -4
  4. package/dist/auth/session.d.ts +14 -0
  5. package/dist/auth/session.js +11 -1
  6. package/dist/index.d.ts +2 -3
  7. package/dist/index.js +2 -3
  8. package/dist/mcp.d.ts +2 -2
  9. package/dist/origin.js +16 -0
  10. package/dist/package.js +1 -1
  11. package/dist/pwa.js +19 -8
  12. package/dist/route/page.d.ts +41 -3
  13. package/dist/route/page.js +102 -25
  14. package/dist/server.d.ts +3 -1
  15. package/dist/server.js +3 -1
  16. package/dist/sitemap.d.ts +35 -0
  17. package/dist/sitemap.js +56 -0
  18. package/package.json +33 -10
  19. package/skills/softr-sdk/SKILL.md +8 -7
  20. package/skills/softr-sdk/ai/SKILL.md +2 -2
  21. package/skills/softr-sdk/auth/SKILL.md +1 -1
  22. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  23. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  24. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  25. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  26. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  27. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  28. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  29. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  30. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  31. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  32. package/skills/softr-sdk/routes-and-visibility/SKILL.md +90 -4
  33. package/skills/softr-sdk/sitemap/SKILL.md +112 -0
  34. package/skills/softr-sdk/workflows/SKILL.md +1 -1
  35. package/dist/cache.js +0 -25
  36. package/dist/push.d.ts +0 -52
  37. package/dist/push.js +0 -295
  38. package/skills/softr-sdk/push-notifications/SKILL.md +0 -140
package/dist/push.js DELETED
@@ -1,295 +0,0 @@
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
- if (Notification.permission !== "granted") {
159
- setRegistration(registered);
160
- return;
161
- }
162
- const subscription = await registered.pushManager.getSubscription() ?? await registered.pushManager.subscribe({
163
- userVisibleOnly: true,
164
- applicationServerKey: decodeBase64Url(parsed.data.vapidPublicKey)
165
- });
166
- if (cancelled) return;
167
- setSubscribed(await sendSubscription("POST", subscription));
168
- setRegistration(registered);
169
- })().catch((error) => console.warn("[@softr/sdk] Could not set up push notifications:", error));
170
- return () => {
171
- cancelled = true;
172
- };
173
- }, [signedIn]);
174
- useEffect(() => {
175
- if (registration === null) return;
176
- return listenToWorker();
177
- }, [registration]);
178
- const subscribe = useCallback(async () => {
179
- if (registration === null || settings === null) return;
180
- const granted = await Notification.requestPermission();
181
- setPermission(granted);
182
- if (granted !== "granted") return;
183
- const subscription = await registration.pushManager.subscribe({
184
- userVisibleOnly: true,
185
- applicationServerKey: decodeBase64Url(settings.vapidPublicKey)
186
- });
187
- if (!await sendSubscription("POST", subscription)) {
188
- await subscription.unsubscribe();
189
- throw new Error("Could not turn on push notifications");
190
- }
191
- setSubscribed(true);
192
- }, [registration, settings]);
193
- const unsubscribe = useCallback(async () => {
194
- const subscription = await registration?.pushManager.getSubscription();
195
- if (!subscription) return;
196
- await sendSubscription("DELETE", subscription);
197
- await subscription.unsubscribe();
198
- setSubscribed(false);
199
- }, [registration]);
200
- const dismiss = useCallback(() => {
201
- const now = Date.now();
202
- try {
203
- localStorage.setItem(DISMISSED_AT_KEY, String(now));
204
- } catch {}
205
- setDismissedAt(now);
206
- }, []);
207
- if (settings === null) return { status: "unavailable" };
208
- const platform = detectPlatform();
209
- if (platform !== "desktop" ? !settings.mobileEnabled : !settings.desktopEnabled) return { status: "unavailable" };
210
- const prompt = {
211
- title: settings.permissionPrompt?.title ?? null,
212
- message: settings.permissionPrompt?.message ?? null,
213
- enableButtonLabel: settings.permissionPrompt?.enableButtonLabel ?? null
214
- };
215
- if (platform === "ios" && !isStandalone()) return {
216
- status: "install-first",
217
- prompt
218
- };
219
- if (registration === null) return { status: "unavailable" };
220
- if (subscribed) return {
221
- status: "subscribed",
222
- unsubscribe
223
- };
224
- if (permission === "denied") return { status: "blocked" };
225
- return {
226
- status: "ask",
227
- prompt,
228
- dismissed: isDismissed(dismissedAt, settings.permissionPrompt?.skipDays ?? null),
229
- subscribe,
230
- dismiss
231
- };
232
- }
233
- async function sendSubscription(method, subscription) {
234
- return (await globalThis.fetch(SUBSCRIPTION_PATH, {
235
- method,
236
- headers: { "content-type": "application/json" },
237
- body: JSON.stringify({ subscription: subscription.toJSON() })
238
- })).ok;
239
- }
240
- /** A missing skip-days setting means a skipped prompt never comes back on its own. */
241
- function isDismissed(dismissedAt, skipDays) {
242
- if (dismissedAt === null) return false;
243
- if (skipDays === null) return true;
244
- return Date.now() - dismissedAt < Math.max(skipDays, 1) * 24 * 60 * 60 * 1e3;
245
- }
246
- function readDismissedAt() {
247
- try {
248
- const stored = Number(localStorage.getItem(DISMISSED_AT_KEY));
249
- return Number.isFinite(stored) && stored > 0 ? stored : null;
250
- } catch {
251
- return null;
252
- }
253
- }
254
- /**
255
- * Answers the service worker, which routes a notification click to the
256
- * installed app when it is open, and keeps the app icon's badge right.
257
- */
258
- function listenToWorker() {
259
- const worker = navigator.serviceWorker;
260
- const standalone = isStandalone();
261
- if (standalone) worker.controller?.postMessage({ type: "pwa-standalone-opened" });
262
- const onMessage = (event) => {
263
- if (event.data === "is-this-standalone") {
264
- event.ports[0]?.postMessage(standalone ? "yes" : "no");
265
- return;
266
- }
267
- if (event.data?.type === "softr-pwa-redirect" && typeof event.data.url === "string") {
268
- const target = new URL(event.data.url, window.location.href);
269
- if (target.origin === window.location.origin) window.location.assign(target.href);
270
- }
271
- };
272
- const onVisible = () => {
273
- if (document.visibilityState === "visible") worker.controller?.postMessage("reset-badge-count");
274
- };
275
- const onInstallOffered = () => worker.controller?.postMessage({ type: "pwa-uninstalled" });
276
- worker.addEventListener("message", onMessage);
277
- document.addEventListener("visibilitychange", onVisible);
278
- window.addEventListener("beforeinstallprompt", onInstallOffered);
279
- onVisible();
280
- return () => {
281
- worker.removeEventListener("message", onMessage);
282
- document.removeEventListener("visibilitychange", onVisible);
283
- window.removeEventListener("beforeinstallprompt", onInstallOffered);
284
- };
285
- }
286
- function decodeBase64Url(value) {
287
- const base64 = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
288
- const binary = atob(base64);
289
- const bytes = new Uint8Array(binary.length);
290
- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
291
- return bytes;
292
- }
293
-
294
- //#endregion
295
- export { pushMiddleware, usePushNotifications };
@@ -1,140 +0,0 @@
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.1
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