@phis/ui 0.4.6 → 0.4.8

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 (69) hide show
  1. package/components/controls/phi-text-control.d.ts +6 -1
  2. package/components/controls/phi-text-control.js +2 -1
  3. package/components/regions/presets/phi-area-shell-preset-nodes.d.ts +5 -0
  4. package/components/regions/presets/phi-area-shell-preset-nodes.js +17 -2
  5. package/components/widgets/label-sets/search-results.d.ts +4 -0
  6. package/components/widgets/label-sets/search-results.js +35 -0
  7. package/components/widgets/label-types/search-results.d.ts +15 -0
  8. package/components/widgets/label-types/search-results.js +10 -0
  9. package/constants/cms-widget-types.d.ts +2 -0
  10. package/constants/cms-widget-types.js +4 -0
  11. package/gateway/site-area.d.ts +10 -7
  12. package/gateway/site-area.js +13 -11
  13. package/gateway/site-config.js +7 -1
  14. package/gateway/site-read-marker-listeners.d.ts +24 -0
  15. package/gateway/site-read-marker-listeners.js +22 -0
  16. package/gateway/site-search.d.ts +37 -0
  17. package/gateway/site-search.js +116 -0
  18. package/next/areas/app.js +5 -1
  19. package/next/areas/public.js +5 -1
  20. package/next/seo-routes.js +2 -2
  21. package/package.json +2 -2
  22. package/plugins/runtime-modules/app/presets.js +23 -0
  23. package/plugins/runtime-modules/app/trees/phi-default-app-area-preset-tree.d.ts +2 -1
  24. package/plugins/runtime-modules/app/trees/phi-default-app-area-preset-tree.js +3 -2
  25. package/plugins/runtime-modules/client-manifests/common.js +8 -0
  26. package/plugins/runtime-modules/core/authoring-widgets.js +4 -0
  27. package/plugins/runtime-modules/core/widgets/card/plugin.js +18 -0
  28. package/plugins/runtime-modules/core/widgets/description/plugin.js +10 -0
  29. package/plugins/runtime-modules/core/widgets/html/plugin.js +16 -1
  30. package/plugins/runtime-modules/core/widgets/html/server.d.ts +6 -0
  31. package/plugins/runtime-modules/core/widgets/html/server.js +12 -4
  32. package/plugins/runtime-modules/core/widgets/markdown/plugin.js +16 -0
  33. package/plugins/runtime-modules/core/widgets/search-box/authoring.d.ts +6 -0
  34. package/plugins/runtime-modules/core/widgets/search-box/authoring.js +10 -0
  35. package/plugins/runtime-modules/core/widgets/search-box/client.d.ts +21 -0
  36. package/plugins/runtime-modules/core/widgets/search-box/client.js +17 -0
  37. package/plugins/runtime-modules/core/widgets/search-box/config.d.ts +63 -0
  38. package/plugins/runtime-modules/core/widgets/search-box/config.js +48 -0
  39. package/plugins/runtime-modules/core/widgets/search-box/plugin.d.ts +3 -0
  40. package/plugins/runtime-modules/core/widgets/search-box/plugin.js +11 -0
  41. package/plugins/runtime-modules/core/widgets/search-box/server.d.ts +21 -0
  42. package/plugins/runtime-modules/core/widgets/search-box/server.js +48 -0
  43. package/plugins/runtime-modules/core/widgets/search-results/authoring.d.ts +6 -0
  44. package/plugins/runtime-modules/core/widgets/search-results/authoring.js +10 -0
  45. package/plugins/runtime-modules/core/widgets/search-results/client.d.ts +34 -0
  46. package/plugins/runtime-modules/core/widgets/search-results/client.js +32 -0
  47. package/plugins/runtime-modules/core/widgets/search-results/config.d.ts +41 -0
  48. package/plugins/runtime-modules/core/widgets/search-results/config.js +39 -0
  49. package/plugins/runtime-modules/core/widgets/search-results/plugin.d.ts +3 -0
  50. package/plugins/runtime-modules/core/widgets/search-results/plugin.js +10 -0
  51. package/plugins/runtime-modules/core/widgets/search-results/server.d.ts +20 -0
  52. package/plugins/runtime-modules/core/widgets/search-results/server.js +73 -0
  53. package/plugins/runtime-modules/core/widgets/simple-text/plugin.js +11 -0
  54. package/plugins/runtime-modules/core/widgets.js +17 -0
  55. package/plugins/runtime-modules/public/presets.d.ts +16 -0
  56. package/plugins/runtime-modules/public/presets.js +22 -0
  57. package/plugins/runtime-modules/public-base-page-references.d.ts +1 -0
  58. package/plugins/runtime-modules/public-base-page-references.js +1 -0
  59. package/plugins/runtime-modules/search-page-references.d.ts +20 -0
  60. package/plugins/runtime-modules/search-page-references.js +35 -0
  61. package/plugins/runtime-modules/search-page-tree.d.ts +14 -0
  62. package/plugins/runtime-modules/search-page-tree.js +63 -0
  63. package/server-helpers/search-index.d.ts +28 -0
  64. package/server-helpers/search-index.js +310 -0
  65. package/server-helpers/search-text.d.ts +40 -0
  66. package/server-helpers/search-text.js +152 -0
  67. package/server-helpers.d.ts +1 -0
  68. package/server-helpers.js +1 -0
  69. package/types/cms-plugins.d.ts +20 -2
@@ -0,0 +1,310 @@
1
+ import "server-only";
2
+ import { createHash } from "node:crypto";
3
+ import { PHI_SEARCH_MAX_DOCUMENTS } from "@phis/contracts/search";
4
+ import { resolvePhiCmsPageRedirect } from "../components/cms/phi-cms-page-redirect";
5
+ import { getSiteAreaWithPublishedPages } from "../gateway/site-area";
6
+ import { onPhiSiteReadMarker } from "../gateway/site-read-marker-listeners";
7
+ import { fetchPhiSiteSearchIndexStates, putPhiSiteSearchIndexSet } from "../gateway/site-search";
8
+ import { readPhiAreaLandingSelection, readPhiAreaPublicRoutePaths } from "../helpers/cms-area-config";
9
+ import { collectPhiSitemapCandidates } from "../helpers/phi-seo";
10
+ import { compilePhiCmsActiveRouteTable, resolvePhiCmsAreaShellPresetBinding, resolvePhiCmsDescriptorCatalog, } from "../plugins/runtime-modules/descriptor-compiler";
11
+ import { resolvePhiCmsAreaRuntimeModuleScope } from "../components/cms/phi-cms-runtime-registry";
12
+ import { canPhiViewerAccess } from "../types/access";
13
+ import { resolvePhiCmsLookup } from "./cms-lookup";
14
+ import { resolveActivePresetModuleKeys } from "./cms-request";
15
+ import { runWithPhiRequestRuntime } from "./request-runtime";
16
+ import { loadPhiSiteRequestContext } from "./runtime";
17
+ import { joinPhiSearchText } from "./search-text";
18
+ /**
19
+ * The Site's half of its search (SEARCH.md): the documents phis indexes, built from the published Pages.
20
+ *
21
+ * A Page's words are not in one place phis could read -- Widget configs, content bound to an instance in
22
+ * a tree, documents fetched while the Page is drawn -- so the Site reads each Page the way a visitor's
23
+ * request does and writes what it saw. The enumeration is the sitemap's: the Area's published Pages and
24
+ * the active Module routes are the candidates, and resolving each one as a lookup decides whether a
25
+ * visitor would get a document. The text is each Widget's own answer (`searchText` on its plugin),
26
+ * translated for the language being indexed; the title and description are the Page's own.
27
+ *
28
+ * Two Areas, read as the reader who may search them: Public anonymously, App as a signed-in member with
29
+ * no further roles. A Page with a narrower access policy than that is not written.
30
+ *
31
+ * It runs when the Site's read marker is first seen by this process and whenever it moves -- which a
32
+ * publish does -- and writes only the sets whose fingerprint phis does not hold yet, so several
33
+ * processes noticing one publish produce one write. One run at a time per process; a marker that moves
34
+ * during a run queues one more.
35
+ */
36
+ const PHI_SEARCH_INDEX_AREAS = ["public", "app"];
37
+ /** How many Pages are resolved at once; each is a page lookup against the server. */
38
+ const PHI_SEARCH_INDEX_RESOLVE_CONCURRENCY = 4;
39
+ /** How long after the marker moved the run starts, so a burst of publishes is one run. */
40
+ const PHI_SEARCH_INDEX_DEBOUNCE_MS = 2_000;
41
+ /**
42
+ * What the extraction is, named in the fingerprint: a change in how documents are built reindexes every
43
+ * Site on its next start, which the published revisions alone would not do.
44
+ */
45
+ const PHI_SEARCH_INDEX_FORMAT = 2;
46
+ const REGISTRY_KEY = Symbol.for("phis-ui.search-index");
47
+ function readRegistry() {
48
+ const holder = globalThis;
49
+ holder[REGISTRY_KEY] ??= { bridges: new Map(), listening: false, running: null, queued: false, timer: null };
50
+ return holder[REGISTRY_KEY];
51
+ }
52
+ /**
53
+ * Names the Bridge an Area's Pages are read through. The Area host registers itself when it is created
54
+ * (next/areas/*.ts); an Area this process never served is not indexed by it, and another process will.
55
+ */
56
+ export function registerPhiSearchIndexArea(area, bridge) {
57
+ const registry = readRegistry();
58
+ registry.bridges.set(area, bridge);
59
+ if (!registry.listening) {
60
+ registry.listening = true;
61
+ onPhiSiteReadMarker(() => schedulePhiSearchIndexRun());
62
+ }
63
+ /*
64
+ * And once now: the Site's marker may have been seen before this Area was registered -- the proxy reads
65
+ * the config before the first page is served -- and a set phis already holds costs one read of its states.
66
+ */
67
+ schedulePhiSearchIndexRun();
68
+ }
69
+ /** Runs the indexer soon, once, however often it is asked meanwhile. */
70
+ function schedulePhiSearchIndexRun() {
71
+ const registry = readRegistry();
72
+ if (registry.timer)
73
+ return;
74
+ registry.timer = setTimeout(() => {
75
+ registry.timer = null;
76
+ void runPhiSearchIndex();
77
+ }, PHI_SEARCH_INDEX_DEBOUNCE_MS);
78
+ // A timer must not keep a process alive that is otherwise done.
79
+ registry.timer.unref?.();
80
+ }
81
+ /**
82
+ * Indexes every registered Area now, or queues one more run when one is under way. The promise settles
83
+ * when this run is done; it never rejects -- a failed Area is logged and the others are still written.
84
+ */
85
+ function runPhiSearchIndex() {
86
+ const registry = readRegistry();
87
+ if (registry.running) {
88
+ registry.queued = true;
89
+ return registry.running;
90
+ }
91
+ registry.running = (async () => {
92
+ try {
93
+ await indexRegisteredAreas(registry);
94
+ }
95
+ catch (error) {
96
+ console.error("[phis-ui] The search index run failed.", error);
97
+ }
98
+ finally {
99
+ registry.running = null;
100
+ if (registry.queued) {
101
+ registry.queued = false;
102
+ schedulePhiSearchIndexRun();
103
+ }
104
+ }
105
+ })();
106
+ return registry.running;
107
+ }
108
+ async function indexRegisteredAreas(registry) {
109
+ const first = registry.bridges.values().next().value;
110
+ const bridgeRuntime = first?.runtime;
111
+ if (!first || !bridgeRuntime)
112
+ return;
113
+ const credentials = {
114
+ apiBaseUrl: bridgeRuntime.apiBaseUrl,
115
+ internalToken: bridgeRuntime.internalToken,
116
+ siteKey: bridgeRuntime.siteKey,
117
+ };
118
+ const held = await fetchPhiSiteSearchIndexStates(credentials);
119
+ const heldFingerprint = (areaMask, locale) => held.find((state) => state.areaMask === areaMask && state.locale === locale)?.fingerprint ?? null;
120
+ for (const area of PHI_SEARCH_INDEX_AREAS) {
121
+ const bridge = registry.bridges.get(area);
122
+ if (!bridge)
123
+ continue;
124
+ try {
125
+ await indexArea({ area, bridge, credentials, heldFingerprint });
126
+ }
127
+ catch (error) {
128
+ console.error(`[phis-ui] Indexing the ${area} Area for search failed.`, error);
129
+ }
130
+ }
131
+ }
132
+ /**
133
+ * The reader an Area is indexed as: the Public Area's anonymous visitor, the App's signed-in member who
134
+ * holds no role -- the least any member holds, so what they may read every member may read.
135
+ */
136
+ function asIndexingReader(context, area) {
137
+ if (area === "public")
138
+ return context;
139
+ return {
140
+ ...context,
141
+ viewer: {
142
+ ...context.viewer,
143
+ access: "authenticated",
144
+ roleClaims: [],
145
+ groupClaims: [],
146
+ addonRoleClaims: [],
147
+ },
148
+ };
149
+ }
150
+ async function indexArea({ area, bridge, credentials, heldFingerprint, }) {
151
+ const { apiBaseUrl, internalToken, siteKey } = credentials;
152
+ const catalog = resolvePhiCmsDescriptorCatalog(bridge.runtimeModuleCatalog);
153
+ const shellBinding = resolvePhiCmsAreaShellPresetBinding(catalog, area);
154
+ if (!shellBinding) {
155
+ console.warn(`[phis-ui] The ${area} Area has no shell preset; nothing to index.`);
156
+ return;
157
+ }
158
+ const sourcePreset = {
159
+ ownerModuleId: shellBinding.descriptor.ownerModuleId,
160
+ presetKey: shellBinding.descriptor.presetKey,
161
+ };
162
+ const areaMask = area === "public" ? 1 : 2;
163
+ // The Site's languages and its server, read once as the anonymous reader; the locale is per set.
164
+ const anonymous = await loadPhiSiteRequestContext(siteKey, "", "", apiBaseUrl, internalToken);
165
+ const locales = anonymous.site.availableLocales.map((option) => option.code);
166
+ const { area: areaPreset, publishedPages } = await getSiteAreaWithPublishedPages({
167
+ apiBaseUrl,
168
+ internalToken,
169
+ siteKey,
170
+ locale: anonymous.site.defaultLocale,
171
+ sourcePreset,
172
+ area,
173
+ });
174
+ const activeModuleIds = resolveActivePresetModuleKeys(bridge.runtimeModuleCatalog, area, areaPreset ? { preset: areaPreset.preset } : null, anonymous.serverCapabilities);
175
+ const routeTable = compilePhiCmsActiveRouteTable({
176
+ catalog,
177
+ area,
178
+ activeModuleIds,
179
+ publicRoutePaths: readPhiAreaPublicRoutePaths(areaPreset?.preset.preset.config),
180
+ landingSelection: readPhiAreaLandingSelection(areaPreset?.preset.preset.config),
181
+ });
182
+ const candidates = collectPhiSitemapCandidates({
183
+ moduleRoutes: [...routeTable.exactByPath].map(([path, descriptor]) => [path, descriptor]),
184
+ publishedPages,
185
+ });
186
+ const fingerprint = createHash("sha256").update(JSON.stringify({
187
+ format: PHI_SEARCH_INDEX_FORMAT,
188
+ area,
189
+ publishedPages,
190
+ areaPreset: areaPreset?.preset ?? null,
191
+ activeModuleIds: [...activeModuleIds].sort(),
192
+ locales,
193
+ })).digest("hex");
194
+ // The Area's Module scope as the live render resolves it: the preset's selection, the locked ones implied.
195
+ const { moduleSet } = await resolvePhiCmsAreaRuntimeModuleScope({
196
+ cmsBridge: bridge,
197
+ area,
198
+ areaPreset: areaPreset?.preset ?? null,
199
+ serverCapabilities: anonymous.serverCapabilities,
200
+ });
201
+ const plugins = new Map();
202
+ const loadPlugin = (type) => {
203
+ let pending = plugins.get(type);
204
+ if (!pending) {
205
+ pending = (moduleSet.widgetDefinitionsByType.get(type)?.loadRuntime() ?? Promise.resolve(null))
206
+ .catch((error) => {
207
+ console.error(`[phis-ui] The search index could not load the Widget "${type}".`, error);
208
+ return null;
209
+ });
210
+ plugins.set(type, pending);
211
+ }
212
+ return pending;
213
+ };
214
+ if (locales.length === 0) {
215
+ console.warn(`[phis-ui] The Site names no locales; the ${area} Area is not indexed.`);
216
+ return;
217
+ }
218
+ for (const locale of locales) {
219
+ if (heldFingerprint(areaMask, locale) === fingerprint)
220
+ continue;
221
+ const context = asIndexingReader(await loadPhiSiteRequestContext(siteKey, locale, "", apiBaseUrl, internalToken), area);
222
+ const documents = await readDocuments({ bridge, area, locale, context, candidates, loadPlugin });
223
+ const answer = await putPhiSiteSearchIndexSet({
224
+ ...credentials,
225
+ area,
226
+ locale,
227
+ fingerprint,
228
+ documents,
229
+ });
230
+ if (answer.dropped > 0) {
231
+ console.warn(`[phis-ui] The search index dropped ${answer.dropped} document(s) of the ${area} Area (${locale}).`);
232
+ }
233
+ // One line per set, so an operator's log says when a Site became searchable and how large it is.
234
+ console.info(`[phis-ui] Search index ${area}/${locale}: ${answer.accepted ? `${answer.state.documentCount} documents written` : "already held"}.`);
235
+ }
236
+ }
237
+ async function readDocuments({ bridge, area, locale, context, candidates, loadPlugin, }) {
238
+ const documents = new Array(candidates.length).fill(null);
239
+ let next = 0;
240
+ async function work() {
241
+ while (next < candidates.length) {
242
+ const index = next++;
243
+ const path = candidates[index].path;
244
+ try {
245
+ documents[index] = await readDocument({ bridge, area, locale, context, path, loadPlugin });
246
+ }
247
+ catch (error) {
248
+ console.error(`[phis-ui] The search index could not read ${area}:${path} (${locale}).`, error);
249
+ }
250
+ }
251
+ }
252
+ await Promise.all(Array.from({ length: PHI_SEARCH_INDEX_RESOLVE_CONCURRENCY }, work));
253
+ return documents
254
+ .filter((document) => document !== null)
255
+ .slice(0, PHI_SEARCH_MAX_DOCUMENTS);
256
+ }
257
+ /**
258
+ * One Page as a document, or `null` where a reader of this Area would not get one: nothing resolves
259
+ * there, it forwards, it asked to stay out of the index, or its access policy is narrower than the
260
+ * reader's. The words are the Page's title and description and every Widget's own answer, in tree order.
261
+ */
262
+ async function readDocument({ bridge, area, locale, context, path, loadPlugin, }) {
263
+ const resolved = await resolvePhiCmsLookup({
264
+ bridge,
265
+ area,
266
+ locale,
267
+ path,
268
+ cookieHeader: "",
269
+ requestContext: context,
270
+ });
271
+ if (!resolved)
272
+ return null;
273
+ const page = resolved.page.page;
274
+ if (resolvePhiCmsPageRedirect(page, locale) != null)
275
+ return null;
276
+ if (resolved.runtime.page?.noindex === true)
277
+ return null;
278
+ if (!canPhiViewerAccess(resolved.runtime.viewer, page.accessPolicy))
279
+ return null;
280
+ /*
281
+ * The Widgets answer inside a request scope of their own. `searchText` is given the runtime, but the
282
+ * shared server helpers a Widget reaches for -- the translation of its texts first of all -- read the
283
+ * request runtime from the scope, and the indexer runs where no request is: at start-up, or on a
284
+ * timer after a publish. Without this scope every Widget that translates fails and a Page is indexed
285
+ * by title and description alone, which is what the first production index was.
286
+ */
287
+ const lines = await runWithPhiRequestRuntime(resolved.runtime, async () => {
288
+ const collected = [];
289
+ for (const widget of resolved.page.contentWidgets) {
290
+ const plugin = await loadPlugin(widget.widgetType);
291
+ if (!plugin?.searchText)
292
+ continue;
293
+ try {
294
+ const config = plugin.parseConfig(widget.config);
295
+ collected.push(...await plugin.searchText({ widget, config, runtime: resolved.runtime }));
296
+ }
297
+ catch (error) {
298
+ // One Widget that cannot say its words costs the Page those words, not the Page.
299
+ console.error(`[phis-ui] The search index could not read the Widget "${widget.widgetType}" on ${area}:${path}.`, error);
300
+ }
301
+ }
302
+ return collected;
303
+ });
304
+ return {
305
+ path: page.path,
306
+ title: resolved.runtime.page?.title ?? "",
307
+ description: resolved.runtime.page?.description ?? "",
308
+ text: joinPhiSearchText(lines),
309
+ };
310
+ }
@@ -0,0 +1,40 @@
1
+ import "server-only";
2
+ import type { PhiMarkdownBlock } from "../components/widgets/shared/markdown-body-client";
3
+ import { type PhiTextSource } from "../helpers/text-source";
4
+ import type { PhiBlockRuntime } from "../types";
5
+ /**
6
+ * What a Widget's `searchText` is made of (SEARCH.md): the words as a reader sees them, one line per
7
+ * block of text, with nothing a reader does not see.
8
+ *
9
+ * Three answers every text Widget needs: its own words translated the way its render translates them,
10
+ * a rendered Markdown document read back as lines, and an HTML fragment read without its tags. They
11
+ * stand here rather than in each Widget so that the index reads every Widget the same way.
12
+ */
13
+ /**
14
+ * The Widget's own words in the reader's language, the way the Widget's render translates them: a
15
+ * Preset's sentence through the platform's store, an author's through the Site's. Empty entries stay
16
+ * in place so the caller can line answers up with what it asked.
17
+ */
18
+ export declare function translatePhiSearchTexts(locale: string, texts: readonly (string | undefined | null)[], options: {
19
+ translate: boolean;
20
+ textSource?: PhiTextSource;
21
+ }): Promise<string[]>;
22
+ /**
23
+ * A Widget's own sentences the way its render shows them: masked, translated, filled -- the order
24
+ * `helpers/text-placeholders.ts` sets out, so `{site.name}` reads as the Site's name in the index as it
25
+ * does on the Page, and never reaches the translator. Empty entries are dropped.
26
+ */
27
+ export declare function translatePhiSearchWidgetTexts(runtime: PhiBlockRuntime, texts: readonly (string | undefined | null)[], options: {
28
+ translate: boolean;
29
+ textSource?: PhiTextSource;
30
+ }): Promise<string[]>;
31
+ /** A rendered Markdown document as lines of text, headings and paragraphs alike, code included. */
32
+ export declare function readPhiMarkdownSearchText(blocks: readonly PhiMarkdownBlock[]): string[];
33
+ /**
34
+ * An HTML fragment as lines of text: block elements end a line, every other tag is dropped, entities
35
+ * are read. Scripts and styles are gone before this is called -- the fragment is the sanitised one the
36
+ * Widget draws -- so only words remain.
37
+ */
38
+ export declare function readPhiHtmlSearchText(html: string): string[];
39
+ /** The lines a Widget answered, as one text: trimmed, empties dropped, one per line. */
40
+ export declare function joinPhiSearchText(lines: readonly (string | undefined | null)[]): string;
@@ -0,0 +1,152 @@
1
+ import "server-only";
2
+ import { maskPhiTextPlaceholders, resolvePhiTextPlaceholders } from "../helpers/text-placeholders";
3
+ import { PHI_TEXT_SOURCE_PRESET } from "../helpers/text-source";
4
+ import { trBulkForLocale, trGlobalBulkForLocale } from "./translate";
5
+ /**
6
+ * What a Widget's `searchText` is made of (SEARCH.md): the words as a reader sees them, one line per
7
+ * block of text, with nothing a reader does not see.
8
+ *
9
+ * Three answers every text Widget needs: its own words translated the way its render translates them,
10
+ * a rendered Markdown document read back as lines, and an HTML fragment read without its tags. They
11
+ * stand here rather than in each Widget so that the index reads every Widget the same way.
12
+ */
13
+ /**
14
+ * The Widget's own words in the reader's language, the way the Widget's render translates them: a
15
+ * Preset's sentence through the platform's store, an author's through the Site's. Empty entries stay
16
+ * in place so the caller can line answers up with what it asked.
17
+ */
18
+ export async function translatePhiSearchTexts(locale, texts, options) {
19
+ const source = texts.map((text) => (typeof text === "string" ? text.trim() : ""));
20
+ if (!options.translate || !source.some(Boolean)) {
21
+ return source;
22
+ }
23
+ const translated = options.textSource === PHI_TEXT_SOURCE_PRESET
24
+ ? await trGlobalBulkForLocale(locale, source)
25
+ : await trBulkForLocale(locale, source);
26
+ return translated.map((text, index) => text || source[index] || "");
27
+ }
28
+ /**
29
+ * A Widget's own sentences the way its render shows them: masked, translated, filled -- the order
30
+ * `helpers/text-placeholders.ts` sets out, so `{site.name}` reads as the Site's name in the index as it
31
+ * does on the Page, and never reaches the translator. Empty entries are dropped.
32
+ */
33
+ export async function translatePhiSearchWidgetTexts(runtime, texts, options) {
34
+ const present = texts.filter((text) => typeof text === "string" && text.trim().length > 0);
35
+ if (present.length === 0)
36
+ return [];
37
+ const masked = present.map((text) => maskPhiTextPlaceholders(text, 0));
38
+ const translated = await translatePhiSearchTexts(runtime.locale.current, masked.map((entry) => entry.text), options);
39
+ return translated
40
+ .map((text, index) => resolvePhiTextPlaceholders(text, masked[index].names, runtime, []))
41
+ .filter(Boolean);
42
+ }
43
+ function readInlineText(inlines) {
44
+ let text = "";
45
+ for (const inline of inlines) {
46
+ switch (inline.kind) {
47
+ case "text":
48
+ case "inline_code":
49
+ text += inline.text;
50
+ break;
51
+ case "strong":
52
+ case "emphasis":
53
+ case "delete":
54
+ case "link":
55
+ text += readInlineText(inline.children);
56
+ break;
57
+ case "image":
58
+ text += inline.alt;
59
+ break;
60
+ case "break":
61
+ text += " ";
62
+ break;
63
+ // A protected address is not written into the index: that is the point of protecting it.
64
+ case "mail_text":
65
+ break;
66
+ }
67
+ }
68
+ return text;
69
+ }
70
+ /** A rendered Markdown document as lines of text, headings and paragraphs alike, code included. */
71
+ export function readPhiMarkdownSearchText(blocks) {
72
+ const lines = [];
73
+ const push = (text) => {
74
+ const collapsed = text.replace(/\s+/gu, " ").trim();
75
+ if (collapsed)
76
+ lines.push(collapsed);
77
+ };
78
+ const walk = (block) => {
79
+ switch (block.kind) {
80
+ case "heading":
81
+ case "paragraph":
82
+ push(readInlineText(block.inlines));
83
+ break;
84
+ case "blockquote":
85
+ block.children.forEach(walk);
86
+ break;
87
+ case "list":
88
+ for (const item of block.items)
89
+ item.forEach(walk);
90
+ break;
91
+ case "code":
92
+ push(block.tokens.map((token) => token.text).join(""));
93
+ break;
94
+ case "table":
95
+ push(block.header.map(readInlineText).join(" "));
96
+ for (const row of block.rows)
97
+ push(row.map(readInlineText).join(" "));
98
+ break;
99
+ case "image":
100
+ push(block.image.alt);
101
+ break;
102
+ case "divider":
103
+ break;
104
+ }
105
+ };
106
+ blocks.forEach(walk);
107
+ return lines;
108
+ }
109
+ const HTML_BLOCK_TAGS = /<\/?(?:p|div|br|li|ul|ol|h[1-6]|tr|td|th|blockquote|pre|section|article|header|footer|figcaption|dd|dt)\b[^>]*>/giu;
110
+ const HTML_ENTITIES = {
111
+ amp: "&",
112
+ lt: "<",
113
+ gt: ">",
114
+ quot: "\"",
115
+ apos: "'",
116
+ nbsp: " ",
117
+ };
118
+ function decodeHtmlEntities(text) {
119
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/giu, (whole, entity) => {
120
+ if (entity.startsWith("#x") || entity.startsWith("#X")) {
121
+ const code = Number.parseInt(entity.slice(2), 16);
122
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
123
+ }
124
+ if (entity.startsWith("#")) {
125
+ const code = Number.parseInt(entity.slice(1), 10);
126
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
127
+ }
128
+ return HTML_ENTITIES[entity.toLowerCase()] ?? whole;
129
+ });
130
+ }
131
+ /**
132
+ * An HTML fragment as lines of text: block elements end a line, every other tag is dropped, entities
133
+ * are read. Scripts and styles are gone before this is called -- the fragment is the sanitised one the
134
+ * Widget draws -- so only words remain.
135
+ */
136
+ export function readPhiHtmlSearchText(html) {
137
+ const withBreaks = html
138
+ .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/giu, " ")
139
+ .replace(HTML_BLOCK_TAGS, "\n")
140
+ .replace(/<[^>]+>/gu, " ");
141
+ return withBreaks
142
+ .split("\n")
143
+ .map((line) => decodeHtmlEntities(line).replace(/\s+/gu, " ").trim())
144
+ .filter(Boolean);
145
+ }
146
+ /** The lines a Widget answered, as one text: trimmed, empties dropped, one per line. */
147
+ export function joinPhiSearchText(lines) {
148
+ return lines
149
+ .map((line) => (typeof line === "string" ? line.replace(/\s+/gu, " ").trim() : ""))
150
+ .filter(Boolean)
151
+ .join("\n");
152
+ }
@@ -11,3 +11,4 @@ export { loadPhiCmsRootRequest } from "./server-helpers/cms-root";
11
11
  export { isPhiCmsGatewayAuthError } from "./gateway/errors";
12
12
  export { loadPhiSiteRequestContext } from "./server-helpers/runtime";
13
13
  export { loadPhiRootLayoutContext, type LoadPhiRootLayoutContextOptions, type PhiRootLayoutContext, } from "./server-helpers/root-layout";
14
+ export { translatePhiSearchWidgetTexts } from "./server-helpers/search-text";
package/server-helpers.js CHANGED
@@ -17,3 +17,4 @@ export { loadPhiCmsRootRequest } from "./server-helpers/cms-root";
17
17
  export { isPhiCmsGatewayAuthError } from "./gateway/errors";
18
18
  export { loadPhiSiteRequestContext } from "./server-helpers/runtime";
19
19
  export { loadPhiRootLayoutContext, } from "./server-helpers/root-layout";
20
+ export { translatePhiSearchWidgetTexts } from "./server-helpers/search-text";
@@ -500,6 +500,24 @@ export type PhiCmsWidgetPlugin<TConfig> = {
500
500
  parseConfig: (raw: Record<string, unknown>) => TConfig;
501
501
  render: PhiBivariantCallback<[PhiCmsWidgetPluginRenderArgs<TConfig>], ReactNode>;
502
502
  renderPreview: PhiBivariantCallback<[PhiCmsWidgetPluginRenderArgs<TConfig>], ReactNode>;
503
+ /**
504
+ * The words this Widget shows a reader, for the Site's search index (SEARCH.md).
505
+ *
506
+ * Called by the indexer, never by a render, for each Widget of a published Page in each language: it
507
+ * answers the text as the reader sees it -- translated for `runtime.locale`, with the Page's values
508
+ * filled in -- and nothing a reader does not see. A Widget without it contributes no text, which is
509
+ * right for a picture, a form or a navigation; a Widget that draws words a visitor would search for
510
+ * says them here, in reading order, one entry per line or paragraph.
511
+ */
512
+ searchText?: PhiBivariantCallback<[
513
+ PhiCmsWidgetSearchTextArgs<TConfig>
514
+ ], Promise<readonly string[]> | readonly string[]>;
515
+ };
516
+ /** What a Widget is handed to say its words: the node, its parsed config and the render's runtime. */
517
+ export type PhiCmsWidgetSearchTextArgs<TConfig> = {
518
+ widget: PhiCmsContentWidgetNode;
519
+ config: TConfig;
520
+ runtime: PhiBlockRuntime;
503
521
  };
504
522
  /**
505
523
  * Everything a Widget declares about itself, and nothing it renders.
@@ -518,8 +536,8 @@ export type PhiCmsBuilderWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TC
518
536
  renderEditor: PhiBivariantCallback<[PhiCmsBuilderWidgetRenderArgs<TConfig>], ReactNode>;
519
537
  renderEditorTools?: PhiBivariantCallback<[PhiCmsBuilderWidgetRenderArgs<TConfig>], ReactNode>;
520
538
  };
521
- export type PhiCmsServerWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TConfig> & Pick<PhiCmsWidgetPlugin<TConfig>, "render" | "renderPreview">;
522
- export type PhiCmsRuntimeWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TConfig> & Pick<PhiCmsWidgetPlugin<TConfig>, "render">;
539
+ export type PhiCmsServerWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TConfig> & Pick<PhiCmsWidgetPlugin<TConfig>, "render" | "renderPreview" | "searchText">;
540
+ export type PhiCmsRuntimeWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TConfig> & Pick<PhiCmsWidgetPlugin<TConfig>, "render" | "searchText">;
523
541
  export type PhiCmsPreviewWidgetPlugin<TConfig> = PhiCmsWidgetPluginDefinition<TConfig> & Pick<PhiCmsWidgetPlugin<TConfig>, "renderPreview">;
524
542
  export type PhiCmsRuntimeRenderRegistry = {
525
543
  runtimeModuleCatalog: PhiRuntimeModuleCatalog;