@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
@@ -20,6 +20,11 @@ type Session = {
20
20
  type SoftrContext = Session & {
21
21
  /** Read it with `useFormatting()`. */
22
22
  formatting: Formatting;
23
+ /**
24
+ * The app's origin, such as `https://acme.com`, for building absolute URLs.
25
+ * Absent until the root route has resolved `getSoftrContext`.
26
+ */
27
+ origin?: string;
23
28
  };
24
29
  //#endregion
25
30
  export { SoftrContext };
@@ -21,12 +21,13 @@ 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>, _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>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
28
28
  };
29
29
  formatting: Formatting;
30
+ origin: string;
30
31
  }>;
31
32
  /**
32
33
  * Resolves the route context of the root route: the visitor and what they may
@@ -8,7 +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
+ import { appOrigin } from "../origin.js";
12
12
  import { faviconMiddleware } from "../favicon.js";
13
13
  import { embeddingMiddleware } from "../embedding.js";
14
14
  import { appIdentityMiddleware } from "../app-identity.js";
@@ -39,9 +39,8 @@ function softrAuthMiddleware() {
39
39
  appIdentityMiddleware(),
40
40
  bootErrorMiddleware(),
41
41
  pwaMiddleware(),
42
- pushMiddleware(),
43
42
  faviconMiddleware()
44
- ]).server(async ({ next }) => {
43
+ ]).server(async ({ next, request }) => {
45
44
  async function getSession() {
46
45
  const token = readSessionToken();
47
46
  if (token === null) return { user: null };
@@ -63,7 +62,8 @@ function softrAuthMiddleware() {
63
62
  return next({ context: {
64
63
  user,
65
64
  permissions: { datasources: {} },
66
- formatting: resolveFormatting(settings$1, getRequestHeader("accept-language") ?? null, readUserTimezone())
65
+ formatting: resolveFormatting(settings$1, getRequestHeader("accept-language") ?? null, readUserTimezone()),
66
+ origin: appOrigin(request)
67
67
  } });
68
68
  });
69
69
  }
@@ -0,0 +1,14 @@
1
+ import "./context.js";
2
+
3
+ //#region src/auth/session.d.ts
4
+
5
+ /**
6
+ * Runs `fn` as a signed-out visitor, whoever sent the request, so every `ds`
7
+ * read inside it returns only what a signed-out visitor may see.
8
+ *
9
+ * @example
10
+ * const page = await asSignedOutVisitor(() => ds.list(articlesQuery).limit(100))
11
+ */
12
+ declare function asSignedOutVisitor<T>(fn: () => T): Promise<Awaited<T>>;
13
+ //#endregion
14
+ export { asSignedOutVisitor };
@@ -45,6 +45,16 @@ function sessionCookie(base) {
45
45
  function withSessionToken(token, fn) {
46
46
  return standInToken.run(token, fn);
47
47
  }
48
+ /**
49
+ * Runs `fn` as a signed-out visitor, whoever sent the request, so every `ds`
50
+ * read inside it returns only what a signed-out visitor may see.
51
+ *
52
+ * @example
53
+ * const page = await asSignedOutVisitor(() => ds.list(articlesQuery).limit(100))
54
+ */
55
+ function asSignedOutVisitor(fn) {
56
+ return standInToken.run(null, async () => await fn());
57
+ }
48
58
  /** The platform token this request carries, or `null`. */
49
59
  function readSessionToken() {
50
60
  const standIn = standInToken.getStore();
@@ -215,4 +225,4 @@ function openEnvelope(raw, purpose) {
215
225
  }
216
226
 
217
227
  //#endregion
218
- export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
228
+ export { asSignedOutVisitor, clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ import { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, Form
7
7
  import { SoftrContext } from "./auth/context.js";
8
8
  import { AuthSettings } from "./auth/platform.js";
9
9
  import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.js";
10
- import { Page, PageSettings, definePage, pageHead } from "./route/page.js";
10
+ import { Page, PageSettings, definePage, excerpt, jsonLdScript, pageHead } from "./route/page.js";
11
11
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
12
12
  import { toReturnPath } from "./auth/returnPath.js";
13
13
  import { AuthOptions, AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
@@ -16,7 +16,6 @@ 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";
20
19
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
21
20
  import { Audience } from "./route/audience.js";
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 };
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, excerpt, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, jsonLdScript, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -2,11 +2,10 @@ import { defineAiAction, defineIntegration, defineMutation, defineQuery, defineW
2
2
  import { useFileUpload } from "./core/use-file-upload.js";
3
3
  import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.js";
4
4
  import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
5
- import { definePage, pageHead } from "./route/page.js";
5
+ import { definePage, excerpt, jsonLdScript, 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";
10
9
  import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
11
10
  import { softrMcpMiddleware } from "./mcp.js";
12
11
  import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
@@ -15,4 +14,4 @@ import { useUserTimezone } from "./timezone.js";
15
14
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
16
15
  import { Audience } from "./route/audience.js";
17
16
 
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 };
17
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, excerpt, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, jsonLdScript, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start8 from "@tanstack/react-start";
2
+ import * as _tanstack_react_start7 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): _tanstack_react_start8.RequestMiddlewareAfterServer<{}, undefined, undefined>;
34
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start7.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
35
  //#endregion
36
36
  export { softrMcpMiddleware };
package/dist/origin.js ADDED
@@ -0,0 +1,16 @@
1
+ import { requireDefined } from "./assertions.js";
2
+
3
+ //#region src/origin.ts
4
+ /** The app's primary origin when one is configured, else the origin `request` reached. */
5
+ function appOrigin(request) {
6
+ const primary = process.env.SOFTR_PRIMARY_ORIGIN;
7
+ if (primary) return requireDefined(URL.parse(primary), `SOFTR_PRIMARY_ORIGIN is not a URL: ${primary}`).origin;
8
+ const url = new URL(request.url);
9
+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
10
+ const protocol = proto === "https" || proto === "http" ? `${proto}:` : url.protocol;
11
+ const host = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || url.host;
12
+ return new URL(`${protocol}//${host}`).origin;
13
+ }
14
+
15
+ //#endregion
16
+ export { appOrigin };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.101-alpha.1";
2
+ var version = "0.0.101-seo.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.js CHANGED
@@ -2,7 +2,6 @@ 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";
6
5
  import { z } from "zod";
7
6
  import { Fragment, createElement, useEffect, useState } from "react";
8
7
  import { createMiddleware } from "@tanstack/react-start";
@@ -21,9 +20,24 @@ const pwaSchema = z.object({
21
20
  })
22
21
  });
23
22
  let cached;
24
- /** The app's PWA, or `null` when it is not installable right now. */
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
+ */
25
28
  function readPwa() {
26
- return readCached("the PWA settings", TTL_MS, () => cached, (entry) => cached = entry, fetchPwa);
29
+ const now = Date.now();
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;
27
41
  }
28
42
  async function fetchPwa() {
29
43
  const { applicationId } = sessionConfig();
@@ -109,7 +123,7 @@ const installSchema = pwaSchema.shape.install;
109
123
  function usePwaInstall() {
110
124
  const [install, setInstall] = useState({ available: false });
111
125
  useEffect(() => {
112
- if (isStandalone()) return;
126
+ if (window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true) return;
113
127
  let cancelled = false;
114
128
  globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
115
129
  if (!response.ok) return;
@@ -133,9 +147,6 @@ function detectPlatform() {
133
147
  if (/Android/.test(userAgent)) return "android";
134
148
  return "desktop";
135
149
  }
136
- function isStandalone() {
137
- return window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true;
138
- }
139
150
 
140
151
  //#endregion
141
- export { SoftrPwaHead, detectPlatform, isStandalone, pwaMiddleware, usePwaInstall };
152
+ export { SoftrPwaHead, pwaMiddleware, usePwaInstall };
@@ -6,6 +6,11 @@ import { AnyRouteMatch } from "@tanstack/react-router";
6
6
  type HeadContext = {
7
7
  match: {
8
8
  id: string;
9
+ pathname?: string;
10
+ search?: object;
11
+ context?: {
12
+ origin?: string;
13
+ };
9
14
  };
10
15
  matches: ReadonlyArray<{
11
16
  id: string;
@@ -60,15 +65,48 @@ type Links = NonNullable<AnyRouteMatch["links"]>;
60
65
  * A canonical URL names one page, so only the page the visitor is on renders
61
66
  * its own.
62
67
  *
63
- * Returned rather than called with the route's context: a `head` written as
64
- * `(ctx) => …` before `loader` stops TypeScript inferring the loader's types.
68
+ * Unless the page sets `canonicalUrl`, its canonical URL and `og:url` are its
69
+ * own address, keeping only the `page` query parameter. The social title and
70
+ * description fall back to the title and description.
71
+ *
72
+ * Write a `head` that reads the loader's data after `loader`, so TypeScript
73
+ * infers the loader's types.
65
74
  *
66
75
  * @example
67
76
  * head: pageHead(pageSettings)
77
+ *
78
+ * @example
79
+ * loader: ({ params }) => getArticle({ data: params.articleId }),
80
+ * head: (ctx) =>
81
+ * pageHead({
82
+ * ...pageSettings,
83
+ * title: ctx.loaderData?.fields.title ?? pageSettings.title,
84
+ * description: excerpt(ctx.loaderData?.fields.body) ?? pageSettings.description,
85
+ * })(ctx),
68
86
  */
69
87
  declare function pageHead(page: Page): (ctx: HeadContext) => {
70
88
  meta: Meta;
71
89
  links: Links;
72
90
  };
91
+ /**
92
+ * Plain text for a page description: markdown and HTML stripped, whitespace
93
+ * collapsed, and cut at a word boundary with an ellipsis when longer than
94
+ * `maxLength`. `undefined` when nothing is left.
95
+ *
96
+ * @example
97
+ * description: excerpt(ctx.loaderData?.fields.body) ?? pageSettings.description
98
+ */
99
+ declare function excerpt(text: string | null | undefined, maxLength?: number): string | undefined;
100
+ /**
101
+ * A `head` script entry carrying `data` as JSON-LD. Every `<` is escaped, so
102
+ * no value can close the script tag.
103
+ *
104
+ * @example
105
+ * scripts: [jsonLdScript({ "@context": "https://schema.org", "@type": "Article", headline: article.title })]
106
+ */
107
+ declare function jsonLdScript(data: object): {
108
+ type: "application/ld+json";
109
+ children: string;
110
+ };
73
111
  //#endregion
74
- export { Page, PageSettings, definePage, pageHead };
112
+ export { Page, PageSettings, definePage, excerpt, jsonLdScript, pageHead };
@@ -1,3 +1,5 @@
1
+ import { assert } from "../assertions.js";
2
+
1
3
  //#region src/route/page.ts
2
4
  /**
3
5
  * Declares a route's settings: its name in Studio, who may open it, its title and its SEO tags.
@@ -29,51 +31,126 @@ function definePage(settings) {
29
31
  * A canonical URL names one page, so only the page the visitor is on renders
30
32
  * its own.
31
33
  *
32
- * Returned rather than called with the route's context: a `head` written as
33
- * `(ctx) => …` before `loader` stops TypeScript inferring the loader's types.
34
+ * Unless the page sets `canonicalUrl`, its canonical URL and `og:url` are its
35
+ * own address, keeping only the `page` query parameter. The social title and
36
+ * description fall back to the title and description.
37
+ *
38
+ * Write a `head` that reads the loader's data after `loader`, so TypeScript
39
+ * infers the loader's types.
34
40
  *
35
41
  * @example
36
42
  * head: pageHead(pageSettings)
43
+ *
44
+ * @example
45
+ * loader: ({ params }) => getArticle({ data: params.articleId }),
46
+ * head: (ctx) =>
47
+ * pageHead({
48
+ * ...pageSettings,
49
+ * title: ctx.loaderData?.fields.title ?? pageSettings.title,
50
+ * description: excerpt(ctx.loaderData?.fields.body) ?? pageSettings.description,
51
+ * })(ctx),
37
52
  */
38
53
  function pageHead(page) {
39
54
  return (ctx) => {
40
- const resolve = (setting) => typeof setting === "function" ? setting(ctx) : setting;
41
- const tag = (setting, make) => {
42
- const value = resolve(setting);
43
- return typeof value === "string" && value !== "" ? [make(value)] : [];
55
+ const resolve = (setting) => {
56
+ const value = typeof setting === "function" ? setting(ctx) : setting;
57
+ return value === "" ? void 0 : value;
44
58
  };
59
+ const origin = ctx.match.context?.origin;
60
+ const title = resolve(page.title);
61
+ const description = resolve(page.description);
62
+ const socialTitle = resolve(page.socialTitle) ?? title;
63
+ const socialDescription = resolve(page.socialDescription) ?? description;
64
+ const socialImage = resolve(page.socialImage);
45
65
  const indexing = resolve(page.searchEngineIndexing);
66
+ const canonical = ctx.matches.at(-1)?.id === ctx.match.id ? canonicalUrl(resolve(page.canonicalUrl), ctx.match.pathname, ctx.match.search, origin) : void 0;
46
67
  return {
47
68
  meta: [
48
- ...tag(page.title, (title) => ({ title })),
49
- ...tag(page.description, (content) => ({
69
+ ...title === void 0 ? [] : [{ title }],
70
+ ...description === void 0 ? [] : [{
50
71
  name: "description",
51
- content
52
- })),
53
- ...tag(page.socialTitle, (content) => ({
72
+ content: description
73
+ }],
74
+ ...socialTitle === void 0 ? [] : [{
54
75
  property: "og:title",
55
- content
56
- })),
57
- ...tag(page.socialDescription, (content) => ({
76
+ content: socialTitle
77
+ }],
78
+ ...socialDescription === void 0 ? [] : [{
58
79
  property: "og:description",
59
- content
60
- })),
61
- ...tag(page.socialImage, (content) => ({
80
+ content: socialDescription
81
+ }],
82
+ ...socialImage === void 0 ? [] : [{
62
83
  property: "og:image",
63
- content
64
- })),
65
- ...typeof indexing === "boolean" ? [{
84
+ content: URL.parse(socialImage, origin)?.href ?? socialImage
85
+ }],
86
+ ...canonical === void 0 ? [] : [{
87
+ property: "og:url",
88
+ content: canonical
89
+ }],
90
+ ...indexing === void 0 ? [] : [{
66
91
  name: "robots",
67
92
  content: indexing ? "index" : "noindex"
68
- }] : []
93
+ }]
69
94
  ],
70
- links: ctx.matches.at(-1)?.id === ctx.match.id ? tag(page.canonicalUrl, (href) => ({
95
+ links: canonical === void 0 ? [] : [{
71
96
  rel: "canonical",
72
- href
73
- })) : []
97
+ href: canonical
98
+ }]
74
99
  };
75
100
  };
76
101
  }
102
+ function canonicalUrl(stated, pathname, search, origin) {
103
+ if (stated !== void 0) return URL.parse(stated, origin)?.href;
104
+ if (origin === void 0 || pathname === void 0) return void 0;
105
+ const url = new URL(pathname.length > 1 ? pathname.replace(/\/+$/, "") : pathname, origin);
106
+ const page = typeof search === "object" && search !== null && "page" in search ? search.page : void 0;
107
+ if (typeof page === "string" || typeof page === "number") url.searchParams.set("page", String(page));
108
+ return url.href;
109
+ }
110
+ /**
111
+ * Plain text for a page description: markdown and HTML stripped, whitespace
112
+ * collapsed, and cut at a word boundary with an ellipsis when longer than
113
+ * `maxLength`. `undefined` when nothing is left.
114
+ *
115
+ * @example
116
+ * description: excerpt(ctx.loaderData?.fields.body) ?? pageSettings.description
117
+ */
118
+ function excerpt(text, maxLength = 155) {
119
+ assert(maxLength > 1, "maxLength must be at least 2");
120
+ if (!text) return void 0;
121
+ const plain = text.replace(/<[^>]*>/g, " ").replace(/^\s*(`{3,}|~{3,}).*$/gm, "").replace(/^\s*([-*_]\s*){3,}$/gm, "").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s*(#{1,6}|>+|[-*+]|\d+[.)])\s+/gm, "").replace(/[*`]+|~~|(?<!\w)_+|_+(?!\w)/g, "").replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos|nbsp);/gi, (entity, name) => {
122
+ const lower = name.toLowerCase();
123
+ if (!lower.startsWith("#")) return NAMED_ENTITIES[lower] ?? entity;
124
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
125
+ return code <= 1114111 ? String.fromCodePoint(code) : entity;
126
+ }).replace(/\s+/g, " ").replace(/ ([.,;:!?])/g, "$1").trim();
127
+ if (plain === "") return void 0;
128
+ if (plain.length <= maxLength) return plain;
129
+ const cut = plain.slice(0, maxLength);
130
+ const lastSpace = cut.lastIndexOf(" ");
131
+ return `${(lastSpace > 0 ? cut.slice(0, lastSpace) : cut.slice(0, maxLength - 1)).replace(/[\s.,;:!?-]+$/, "")}…`;
132
+ }
133
+ const NAMED_ENTITIES = {
134
+ amp: "&",
135
+ lt: "<",
136
+ gt: ">",
137
+ quot: "\"",
138
+ apos: "'",
139
+ nbsp: " "
140
+ };
141
+ /**
142
+ * A `head` script entry carrying `data` as JSON-LD. Every `<` is escaped, so
143
+ * no value can close the script tag.
144
+ *
145
+ * @example
146
+ * scripts: [jsonLdScript({ "@context": "https://schema.org", "@type": "Article", headline: article.title })]
147
+ */
148
+ function jsonLdScript(data) {
149
+ return {
150
+ type: "application/ld+json",
151
+ children: JSON.stringify(data).replaceAll("<", "\\u003c")
152
+ };
153
+ }
77
154
 
78
155
  //#endregion
79
- export { definePage, pageHead };
156
+ export { definePage, excerpt, jsonLdScript, pageHead };
package/dist/server.d.ts CHANGED
@@ -5,5 +5,7 @@ import { FieldChoice, RecordOption, RecordOptions } from "./core/options.js";
5
5
  import { ds } from "./datasource/datasource.js";
6
6
  import { workflow } from "./core/workflow.js";
7
7
  import { integration } from "./core/integration.js";
8
+ import { asSignedOutVisitor } from "./auth/session.js";
9
+ import { SitemapEntry, sitemapXml } from "./sitemap.js";
8
10
  import "@tanstack/react-start/server-only";
9
- export { AiError, type FieldChoice, type RecordOption, type RecordOptions, ai, auth, ds, integration, upload, workflow };
11
+ export { AiError, type FieldChoice, type RecordOption, type RecordOptions, type SitemapEntry, ai, asSignedOutVisitor, auth, ds, integration, sitemapXml, upload, workflow };
package/dist/server.js CHANGED
@@ -1,9 +1,11 @@
1
+ import { asSignedOutVisitor } from "./auth/session.js";
1
2
  import { upload } from "./core/file-upload.js";
2
3
  import { ds } from "./datasource/datasource.js";
3
4
  import { auth } from "./auth/server.js";
4
5
  import { workflow } from "./core/workflow.js";
5
6
  import { integration } from "./core/integration.js";
6
7
  import { AiError, ai } from "./core/ai.js";
8
+ import { sitemapXml } from "./sitemap.js";
7
9
  import "@tanstack/react-start/server-only";
8
10
 
9
- export { AiError, ai, auth, ds, integration, upload, workflow };
11
+ export { AiError, ai, asSignedOutVisitor, auth, ds, integration, sitemapXml, upload, workflow };
@@ -0,0 +1,35 @@
1
+ //#region src/sitemap.d.ts
2
+ /** A page for {@link sitemapXml}: a path or full URL, or an object with the page's details. */
3
+ type SitemapEntry = string | {
4
+ loc: string;
5
+ lastmod?: string | Date;
6
+ changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
7
+ priority?: number;
8
+ alternateRefs?: Array<{
9
+ href: string;
10
+ hreflang: string;
11
+ }>;
12
+ images?: Array<{
13
+ loc: string;
14
+ caption?: string;
15
+ title?: string;
16
+ }>;
17
+ news?: {
18
+ publication: {
19
+ name: string;
20
+ language: string;
21
+ };
22
+ publicationDate: string | Date;
23
+ title: string;
24
+ };
25
+ };
26
+ /**
27
+ * The sitemap response listing `entries`. A path resolves against the app's
28
+ * origin, and a full URL is kept as written.
29
+ *
30
+ * @example
31
+ * GET: ({ request }) => sitemapXml(request, ["/", "/pricing", { loc: "/blog", changefreq: "daily" }])
32
+ */
33
+ declare function sitemapXml(request: Request, entries: Array<SitemapEntry>): Response;
34
+ //#endregion
35
+ export { SitemapEntry, sitemapXml };
@@ -0,0 +1,56 @@
1
+ import { assert } from "./assertions.js";
2
+ import { appOrigin } from "./origin.js";
3
+
4
+ //#region src/sitemap.ts
5
+ const MAX_URLS = 5e4;
6
+ /**
7
+ * The sitemap response listing `entries`. A path resolves against the app's
8
+ * origin, and a full URL is kept as written.
9
+ *
10
+ * @example
11
+ * GET: ({ request }) => sitemapXml(request, ["/", "/pricing", { loc: "/blog", changefreq: "daily" }])
12
+ */
13
+ function sitemapXml(request, entries) {
14
+ assert(entries.length <= MAX_URLS, `A sitemap lists at most ${MAX_URLS} URLs, got ${entries.length}.`);
15
+ const origin = appOrigin(request);
16
+ const url = (path) => escapeXml(new URL(path, origin).href);
17
+ const date = (value) => escapeXml(value instanceof Date ? value.toISOString() : value);
18
+ const pages = entries.map((entry) => typeof entry === "string" ? { loc: entry } : entry);
19
+ const namespaces = [
20
+ "xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"",
21
+ ...pages.some((page) => page.alternateRefs?.length) ? ["xmlns:xhtml=\"http://www.w3.org/1999/xhtml\""] : [],
22
+ ...pages.some((page) => page.images?.length) ? ["xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\""] : [],
23
+ ...pages.some((page) => page.news !== void 0) ? ["xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\""] : []
24
+ ];
25
+ const urls = pages.map((page) => [
26
+ " <url>",
27
+ ` <loc>${url(page.loc)}</loc>`,
28
+ ...page.lastmod === void 0 ? [] : [` <lastmod>${date(page.lastmod)}</lastmod>`],
29
+ ...page.changefreq === void 0 ? [] : [` <changefreq>${page.changefreq}</changefreq>`],
30
+ ...page.priority === void 0 ? [] : [` <priority>${page.priority}</priority>`],
31
+ ...(page.alternateRefs ?? []).map((ref) => ` <xhtml:link rel="alternate" hreflang="${escapeXml(ref.hreflang)}" href="${url(ref.href)}"/>`),
32
+ ...(page.images ?? []).map((image) => {
33
+ const caption = image.caption === void 0 ? "" : `<image:caption>${escapeXml(image.caption)}</image:caption>`;
34
+ const title = image.title === void 0 ? "" : `<image:title>${escapeXml(image.title)}</image:title>`;
35
+ return ` <image:image><image:loc>${url(image.loc)}</image:loc>${caption}${title}</image:image>`;
36
+ }),
37
+ ...(page.news === void 0 ? [] : [page.news]).map((news) => {
38
+ return ` <news:news><news:publication>${`<news:name>${escapeXml(news.publication.name)}</news:name>`}${`<news:language>${escapeXml(news.publication.language)}</news:language>`}</news:publication>${`<news:publication_date>${date(news.publicationDate)}</news:publication_date>`}<news:title>${escapeXml(news.title)}</news:title></news:news>`;
39
+ }),
40
+ " </url>"
41
+ ].join("\n"));
42
+ const xml = [
43
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
44
+ `<urlset ${namespaces.join(" ")}>`,
45
+ ...urls,
46
+ "</urlset>",
47
+ ""
48
+ ];
49
+ return new Response(xml.join("\n"), { headers: { "content-type": "application/xml; charset=utf-8" } });
50
+ }
51
+ function escapeXml(value) {
52
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
53
+ }
54
+
55
+ //#endregion
56
+ export { sitemapXml };
package/package.json CHANGED
@@ -1,16 +1,37 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.101-alpha.1",
3
+ "version": "0.0.101-seo.0",
4
4
  "type": "module",
5
5
  "exports": {
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
- },
11
- "bin": { "softr-sdk": "./dist/cli.js" },
12
- "files": ["dist", "schema", "skills", "!skills/_artifacts"],
13
- "publishConfig": { "access": "public" },
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.js"
9
+ },
10
+ "./client": {
11
+ "types": "./dist/client.d.ts",
12
+ "import": "./dist/client.js"
13
+ },
14
+ "./server": {
15
+ "types": "./dist/server.d.ts",
16
+ "import": "./dist/server.js"
17
+ },
18
+ "./vite": {
19
+ "types": "./dist/vite.d.ts",
20
+ "import": "./dist/vite.js"
21
+ }
22
+ },
23
+ "bin": {
24
+ "softr-sdk": "./dist/cli.js"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "schema",
29
+ "skills",
30
+ "!skills/_artifacts"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
14
35
  "scripts": {
15
36
  "build": "tsdown",
16
37
  "test": "node --import ./src/test-utils/setup.ts --test",
@@ -42,7 +63,9 @@
42
63
  "optional": true
43
64
  }
44
65
  },
45
- "keywords": ["tanstack-intent"],
66
+ "keywords": [
67
+ "tanstack-intent"
68
+ ],
46
69
  "intent": {
47
70
  "version": 1,
48
71
  "repo": "@softr/sdk",