inlaycms 0.6.0 → 0.7.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/assets/admin/admin.js +1 -1
- package/dist/adapters/admin/screens/media.d.ts +4 -1
- package/dist/adapters/admin/screens/media.js +22 -2
- package/dist/adapters/admin/screens/redirects.js +3 -1
- package/dist/adapters/cli/main.js +9 -1
- package/dist/adapters/mcp/tools/read.d.ts +1 -1
- package/dist/adapters/mcp/tools/read.js +44 -1
- package/dist/adapters/mcp/tools/write.js +76 -5
- package/dist/adapters/site/plugin.d.ts +2 -0
- package/dist/adapters/site/plugin.js +10 -1
- package/dist/adapters/site/public.d.ts +9 -1
- package/dist/adapters/site/public.js +48 -30
- package/dist/core/content/find-text.d.ts +31 -0
- package/dist/core/content/find-text.js +124 -0
- package/dist/core/content/search.js +1 -14
- package/dist/core/content/text-match.d.ts +14 -0
- package/dist/core/content/text-match.js +99 -0
- package/dist/core/content/text-replace.d.ts +14 -0
- package/dist/core/content/text-replace.js +100 -0
- package/dist/core/core.d.ts +7 -0
- package/dist/core/core.js +2 -0
- package/dist/core/messages/en.d.ts +33 -2
- package/dist/core/messages/en.js +33 -2
- package/dist/core/release/pack.js +4 -0
- package/dist/core/release/public-files.d.ts +14 -0
- package/dist/core/release/public-files.js +43 -0
- package/dist/core/release/window.d.ts +2 -0
- package/dist/core/release/window.js +6 -0
- package/dist/core/report.d.ts +1 -1
- package/dist/core/richtext/runs.d.ts +12 -0
- package/dist/core/richtext/runs.js +31 -0
- package/dist/core/version.d.ts +2 -0
- package/dist/core/version.js +2 -0
- package/dist/host/app.d.ts +6 -0
- package/dist/host/app.js +3 -0
- package/package.json +1 -1
|
@@ -2,6 +2,7 @@ import { z } from 'zod';
|
|
|
2
2
|
import { agentLinks, toAgent } from '../../../core/agent/format.js';
|
|
3
3
|
import { agentTypeSchema } from '../../../core/agent/schema.js';
|
|
4
4
|
import { docLabels } from '../../../core/content/schema.js';
|
|
5
|
+
import { fold } from '../../../core/content/text-match.js';
|
|
5
6
|
import { InlayError } from '../../../core/errors.js';
|
|
6
7
|
import { t } from '../../../core/messages/index.js';
|
|
7
8
|
import { designedInCode } from '../../../core/registry/designed.js';
|
|
@@ -29,6 +30,13 @@ const searchEntriesInput = z.object({
|
|
|
29
30
|
locale: z.string().describe(t('mcp.param.locale')).optional(),
|
|
30
31
|
limit: z.number().int().min(1).max(50).describe(t('mcp.param.limit')).optional(),
|
|
31
32
|
});
|
|
33
|
+
const findTextInput = z.object({
|
|
34
|
+
text: z.string().describe(t('mcp.param.findText')),
|
|
35
|
+
type: z.string().describe(t('mcp.param.findType')).optional(),
|
|
36
|
+
locale: z.string().describe(t('mcp.param.findLocale')).optional(),
|
|
37
|
+
limit: z.number().int().min(1).max(100).describe(t('mcp.param.findLimit')).optional(),
|
|
38
|
+
offset: z.number().int().min(0).describe(t('mcp.param.findOffset')).optional(),
|
|
39
|
+
});
|
|
32
40
|
/** `locale`, or the default locale when it's absent. An unknown locale is refused. */
|
|
33
41
|
function localeOf(registry, locale) {
|
|
34
42
|
if (locale === undefined)
|
|
@@ -258,7 +266,36 @@ async function searchEntries(deps, args) {
|
|
|
258
266
|
})),
|
|
259
267
|
};
|
|
260
268
|
}
|
|
261
|
-
|
|
269
|
+
async function findText(deps, args) {
|
|
270
|
+
if (fold(args.text).text.trim() === '')
|
|
271
|
+
throw new InlayError('invalid_operation', 'mcp.findText.blank');
|
|
272
|
+
if (args.type !== undefined)
|
|
273
|
+
await requireType(deps, args.type);
|
|
274
|
+
const locale = args.locale === undefined ? undefined : localeOf(deps.core.registry, args.locale);
|
|
275
|
+
const { total, documents, designedInCode } = await deps.core.findText(args.text, {
|
|
276
|
+
...(args.type !== undefined && { type: args.type }),
|
|
277
|
+
...(locale !== undefined && { locale }),
|
|
278
|
+
...(args.limit !== undefined && { limit: args.limit }),
|
|
279
|
+
...(args.offset !== undefined && { offset: args.offset }),
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
total,
|
|
283
|
+
documents: documents.map(({ document: d, matches }) => ({
|
|
284
|
+
id: d.id,
|
|
285
|
+
groupId: d.groupId,
|
|
286
|
+
type: d.type,
|
|
287
|
+
kind: d.kind,
|
|
288
|
+
title: d.title,
|
|
289
|
+
locale: d.locale,
|
|
290
|
+
revisionId: d.headRev,
|
|
291
|
+
published: d.publishedRev !== null,
|
|
292
|
+
hasUnpublishedChanges: d.publishedRev !== d.headRev,
|
|
293
|
+
matches: matches.map((m) => ({ ...m, path: m.path.join('.') })),
|
|
294
|
+
})),
|
|
295
|
+
...(designedInCode.length > 0 && { designedInCode, note: t('mcp.findText.designedInCode') }),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/** `describe_site`, `describe_type`, `get_document`, `search_entries`, `find_text` and `list_gaps`. */
|
|
262
299
|
export function register(server, deps, _ctx) {
|
|
263
300
|
const run = (fn) => tool(async (args) => ok(await fn(args)), deps.log);
|
|
264
301
|
server.registerTool('describe_site', {
|
|
@@ -285,6 +322,12 @@ export function register(server, deps, _ctx) {
|
|
|
285
322
|
inputSchema: searchEntriesInput,
|
|
286
323
|
annotations: READ_ONLY,
|
|
287
324
|
}, run((args) => searchEntries(deps, args)));
|
|
325
|
+
server.registerTool('find_text', {
|
|
326
|
+
title: t('mcp.tool.find_text.title'),
|
|
327
|
+
description: t('mcp.tool.find_text.description'),
|
|
328
|
+
inputSchema: findTextInput,
|
|
329
|
+
annotations: READ_ONLY,
|
|
330
|
+
}, run((args) => findText(deps, args)));
|
|
288
331
|
server.registerTool('list_gaps', {
|
|
289
332
|
title: t('mcp.tool.list_gaps.title'),
|
|
290
333
|
description: t('mcp.tool.list_gaps.description'),
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { contentFromAgent, fromAgent, parsePath } from '../../../core/agent/format.js';
|
|
3
3
|
import { formatDiff } from '../../../core/content/diff.js';
|
|
4
|
-
import { patchProblems, unknownContentKeys } from '../../../core/content/patch.js';
|
|
4
|
+
import { applyPatch, patchProblems, unknownContentKeys } from '../../../core/content/patch.js';
|
|
5
5
|
import { docLabels, documentRefsWithPaths, normalizeContent } from '../../../core/content/schema.js';
|
|
6
|
+
import { replaceText } from '../../../core/content/text-replace.js';
|
|
6
7
|
import { contentIssue, mergeIssues, validateContent } from '../../../core/content/validate.js';
|
|
7
8
|
import { InlayError } from '../../../core/errors.js';
|
|
9
|
+
import { fieldMeta } from '../../../core/fields/define.js';
|
|
8
10
|
import { defOf, unwrap } from '../../../core/fields/zod-internals.js';
|
|
9
11
|
import { t } from '../../../core/messages/index.js';
|
|
10
12
|
import { designedInCode } from '../../../core/registry/designed.js';
|
|
@@ -20,6 +22,9 @@ const updateDocumentInput = z.object({
|
|
|
20
22
|
path: z.string().describe(t('mcp.param.changePath')),
|
|
21
23
|
value: z.unknown().describe(t('mcp.param.changeValue')).optional(),
|
|
22
24
|
remove: z.literal(true).describe(t('mcp.param.changeRemove')).optional(),
|
|
25
|
+
find: z.string().describe(t('mcp.param.changeFind')).optional(),
|
|
26
|
+
replace: z.string().describe(t('mcp.param.changeReplace')).optional(),
|
|
27
|
+
occurrences: z.array(z.number()).describe(t('mcp.param.changeOccurrences')).optional(),
|
|
23
28
|
}))
|
|
24
29
|
.min(1)
|
|
25
30
|
.max(100)
|
|
@@ -135,11 +140,60 @@ async function groupIdIssues(deps, type, data) {
|
|
|
135
140
|
}
|
|
136
141
|
return issues;
|
|
137
142
|
}
|
|
138
|
-
|
|
139
|
-
|
|
143
|
+
const REPLACE_KINDS = new Set(['text', 'textarea', 'richText', 'inlineText']);
|
|
144
|
+
/** The field a replace works on: the text field at `path`, or the link whose label `path` names. */
|
|
145
|
+
function replaceTarget(registry, type, path) {
|
|
146
|
+
const field = fieldAt(registry, type, path);
|
|
147
|
+
const kind = field && fieldMeta(field)?.kind;
|
|
148
|
+
if (kind && REPLACE_KINDS.has(kind))
|
|
149
|
+
return { path, kind: kind };
|
|
150
|
+
if (path.at(-1) !== 'text')
|
|
151
|
+
return null;
|
|
152
|
+
const link = fieldAt(registry, type, path.slice(0, -1));
|
|
153
|
+
if (link && fieldMeta(link)?.kind === 'link')
|
|
154
|
+
return { path: path.slice(0, -1), kind: 'link' };
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
function valueAt(data, path) {
|
|
158
|
+
let current = data;
|
|
159
|
+
for (const segment of path) {
|
|
160
|
+
if (typeof current !== 'object' || current === null)
|
|
161
|
+
return undefined;
|
|
162
|
+
current = current[segment];
|
|
163
|
+
}
|
|
164
|
+
return current;
|
|
165
|
+
}
|
|
166
|
+
const REPLACE_FAILURES = {
|
|
167
|
+
notFound: 'mcp.change.notFound',
|
|
168
|
+
occurrence: 'mcp.change.occurrence',
|
|
169
|
+
noOccurrences: 'mcp.change.noOccurrences',
|
|
170
|
+
spansFormatting: 'mcp.change.spansFormatting',
|
|
171
|
+
};
|
|
172
|
+
/** A find-and-replace change as one patch op on the field, seeing what the ops before it did. */
|
|
173
|
+
function replaceOp(registry, type, data, opsSoFar, path, change) {
|
|
174
|
+
const labels = docLabels(registry, type, path) ?? path.map(String);
|
|
175
|
+
const target = replaceTarget(registry, type, path);
|
|
176
|
+
if (target === null)
|
|
177
|
+
return contentIssue(path, labels, 'invalid', 'mcp.change.notText');
|
|
178
|
+
const patched = applyPatch(registry, type, data, opsSoFar);
|
|
179
|
+
const current = valueAt(patched.ok ? patched.data : data, target.path);
|
|
180
|
+
const result = current === undefined
|
|
181
|
+
? { ok: false, reason: 'notFound', count: 0 }
|
|
182
|
+
: replaceText(target.kind, current, change.find, change.replace, change.occurrences);
|
|
183
|
+
if (!result.ok) {
|
|
184
|
+
return contentIssue(path, labels, 'invalid', REPLACE_FAILURES[result.reason], { find: change.find, count: result.count });
|
|
185
|
+
}
|
|
186
|
+
return { op: { path: target.path, value: result.value }, count: result.count };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The change list as patch operations, converted from the agent format, and the problems of the changes that can't be.
|
|
190
|
+
* A replace works on `data` with the earlier changes applied, and is counted in `replaced`.
|
|
191
|
+
*/
|
|
192
|
+
function toOps(deps, type, data, changes) {
|
|
140
193
|
const { registry } = deps.core;
|
|
141
194
|
const issues = [];
|
|
142
195
|
const ops = [];
|
|
196
|
+
const replaced = [];
|
|
143
197
|
for (const change of changes) {
|
|
144
198
|
const path = parsePath(change.path);
|
|
145
199
|
if (path === null) {
|
|
@@ -148,6 +202,22 @@ function toOps(deps, type, changes) {
|
|
|
148
202
|
}
|
|
149
203
|
const hasValue = change.value !== undefined;
|
|
150
204
|
const remove = change.remove === true;
|
|
205
|
+
if (change.find !== undefined || change.replace !== undefined || change.occurrences !== undefined) {
|
|
206
|
+
if (change.find === undefined || change.replace === undefined || hasValue || remove) {
|
|
207
|
+
const labels = docLabels(registry, type, path) ?? path.map(String);
|
|
208
|
+
issues.push(contentIssue(path, labels, 'invalid', 'mcp.change.replaceShape'));
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const result = replaceOp(registry, type, data, ops, path, { ...change, find: change.find, replace: change.replace });
|
|
212
|
+
if ('op' in result) {
|
|
213
|
+
ops.push(result.op);
|
|
214
|
+
replaced.push({ path: change.path, count: result.count });
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
issues.push(result);
|
|
218
|
+
}
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
151
221
|
if (hasValue === remove) {
|
|
152
222
|
const labels = docLabels(registry, type, path) ?? path.map(String);
|
|
153
223
|
issues.push(contentIssue(path, labels, 'invalid', hasValue ? 'mcp.change.both' : 'mcp.change.neither'));
|
|
@@ -171,7 +241,7 @@ function toOps(deps, type, changes) {
|
|
|
171
241
|
else
|
|
172
242
|
issues.push(...result.issues);
|
|
173
243
|
}
|
|
174
|
-
return { ops, issues };
|
|
244
|
+
return { ops, issues, replaced };
|
|
175
245
|
}
|
|
176
246
|
/**
|
|
177
247
|
* Saves the changes as a draft. Any problem is reported with every other one: the changes that can't be read,
|
|
@@ -182,7 +252,7 @@ async function updateDocument(deps, args, ctx) {
|
|
|
182
252
|
const def = deps.core.registry.getType(doc.type);
|
|
183
253
|
if (def.kind !== 'collection' && designedInCode(def.template))
|
|
184
254
|
throw new InlayError('invalid_operation', 'mcp.designedInCode');
|
|
185
|
-
const { ops, issues } = toOps(deps, doc.type, args.changes);
|
|
255
|
+
const { ops, issues, replaced } = toOps(deps, doc.type, doc.data, args.changes);
|
|
186
256
|
issues.push(...(await groupIdIssues(deps, doc.type, opsAsData(ops))));
|
|
187
257
|
if (issues.length > 0)
|
|
188
258
|
throw validation(mergeIssues(issues, patchProblems(deps.core.registry, doc.type, doc.data, ops)));
|
|
@@ -201,6 +271,7 @@ async function updateDocument(deps, args, ctx) {
|
|
|
201
271
|
revisionId: result.document.headRev,
|
|
202
272
|
changed: result.changed,
|
|
203
273
|
changes: formatDiff(result.diff),
|
|
274
|
+
...(args.changes.some((c) => c.find !== undefined) && { replaced }),
|
|
204
275
|
previewUrl: previewLink(deps, path ?? '/'),
|
|
205
276
|
};
|
|
206
277
|
}
|
|
@@ -76,6 +76,8 @@ export interface InlayOptions {
|
|
|
76
76
|
trustedKeys?: readonly string[];
|
|
77
77
|
/** What the admin's Releases screen can ask of `inlaycms serve` (preview, activate, push checks). */
|
|
78
78
|
adminHost?: AdminHostHooks;
|
|
79
|
+
/** Also serves the files in `publicDir` whose names have a dot at the site root, such as `/privacy-policy.pdf`. */
|
|
80
|
+
rootPublicFiles?: boolean;
|
|
79
81
|
}
|
|
80
82
|
/** What a site running under `inlaycms serve` can ask of the server. */
|
|
81
83
|
export interface HostApi {
|
|
@@ -30,7 +30,7 @@ import { startBackupSchedule } from './backup-schedule.js';
|
|
|
30
30
|
import { isLockedRequest, registerSiteLockGate, registerUnlockRoute } from './lock.js';
|
|
31
31
|
import { codeFilesFor, registerCodeFileRoutes } from './code-files.js';
|
|
32
32
|
import { registerMediaRoutes } from './media-routes.js';
|
|
33
|
-
import { registerPublicRoutes } from './public.js';
|
|
33
|
+
import { registerPublicRoutes, rootPublicPath, sendPublicFile } from './public.js';
|
|
34
34
|
import { previewLink, readPreview, registerPreviewRoutes } from './preview.js';
|
|
35
35
|
import { catalogPage, renderPageResult } from './render.js';
|
|
36
36
|
import { registerReleaseRoutes } from './routes.js';
|
|
@@ -184,6 +184,14 @@ function registerSiteRoutes(app, core, cache, integrations, opts) {
|
|
|
184
184
|
}
|
|
185
185
|
async function handle(request, reply) {
|
|
186
186
|
const { path, search } = splitUrl(request.url);
|
|
187
|
+
if (opts.rootPublic !== undefined) {
|
|
188
|
+
const rootPath = rootPublicPath(request.raw.url ?? '');
|
|
189
|
+
if (rootPath !== null) {
|
|
190
|
+
const sent = await sendPublicFile(request, reply, { ...opts.rootPublic, autoHead: true }, rootPath);
|
|
191
|
+
if (sent !== null)
|
|
192
|
+
return sent;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
187
195
|
const state = opts.preview === 'forced' ? 'preview' : stateOf(request);
|
|
188
196
|
const preview = state === 'preview';
|
|
189
197
|
if (preview)
|
|
@@ -486,6 +494,7 @@ const plugin = async (app, opts) => {
|
|
|
486
494
|
secret,
|
|
487
495
|
now,
|
|
488
496
|
assets: siteAssets,
|
|
497
|
+
...(opts.publicDir !== undefined && opts.rootPublicFiles && { rootPublic: { dir: opts.publicDir, maxAge: opts.publicMaxAge ?? 3600 } }),
|
|
489
498
|
...(opts.cdn && { cdn: opts.cdn }),
|
|
490
499
|
...(opts.noSite && { noSite: opts.noSite }),
|
|
491
500
|
...(opts.preview && { preview: opts.preview }),
|
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
import type { FastifyInstance } from 'fastify';
|
|
1
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
2
|
+
/** The request's path without its query or leading `/`, when its last segment has a `.`; null otherwise. */
|
|
3
|
+
export declare function rootPublicPath(rawUrl: string): string | null;
|
|
4
|
+
/** Sends the file `rawPath` names under `opts.dir`, or returns null, leaving `reply` alone, when nothing servable is there. */
|
|
5
|
+
export declare function sendPublicFile(request: FastifyRequest, reply: FastifyReply, opts: {
|
|
6
|
+
dir: string;
|
|
7
|
+
maxAge: number;
|
|
8
|
+
autoHead?: boolean;
|
|
9
|
+
}, rawPath: string): Promise<FastifyReply | null>;
|
|
2
10
|
/** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
|
|
3
11
|
export declare function registerPublicRoutes(app: FastifyInstance, opts: {
|
|
4
12
|
dir: string;
|
|
@@ -26,45 +26,63 @@ const TYPES = {
|
|
|
26
26
|
'.pdf': 'application/pdf',
|
|
27
27
|
'.map': 'application/json; charset=utf-8',
|
|
28
28
|
};
|
|
29
|
+
/** The request's path without its query or leading `/`, when its last segment has a `.`; null otherwise. */
|
|
30
|
+
export function rootPublicPath(rawUrl) {
|
|
31
|
+
const q = rawUrl.indexOf('?');
|
|
32
|
+
const path = q === -1 ? rawUrl : rawUrl.slice(0, q);
|
|
33
|
+
const last = path.slice(path.lastIndexOf('/') + 1);
|
|
34
|
+
if (!last.includes('.'))
|
|
35
|
+
return null;
|
|
36
|
+
return path.slice(1);
|
|
37
|
+
}
|
|
38
|
+
/** Sends the file `rawPath` names under `opts.dir`, or returns null, leaving `reply` alone, when nothing servable is there. */
|
|
39
|
+
export async function sendPublicFile(request, reply, opts, rawPath) {
|
|
40
|
+
const file = locate(opts.dir, rawPath);
|
|
41
|
+
if (file === null)
|
|
42
|
+
return null;
|
|
43
|
+
let bytes;
|
|
44
|
+
try {
|
|
45
|
+
// A symlink is never followed: not as the file, nor as a folder on the way to it.
|
|
46
|
+
if (!(await lstat(file)).isFile())
|
|
47
|
+
return null;
|
|
48
|
+
if (!(await realpath(file)).startsWith((await realpath(opts.dir)) + sep))
|
|
49
|
+
return null;
|
|
50
|
+
bytes = await readFile(file);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const rawUrl = request.raw.url ?? '';
|
|
56
|
+
const q = rawUrl.indexOf('?');
|
|
57
|
+
const hex = createHash('sha256').update(bytes).digest('hex');
|
|
58
|
+
const etag = `"${hex.slice(0, 32)}"`;
|
|
59
|
+
const version = new URLSearchParams(q === -1 ? '' : rawUrl.slice(q + 1)).get('v');
|
|
60
|
+
const cacheControl = version === hex.slice(0, ASSET_VERSION_LENGTH) ? 'public, max-age=31536000, immutable' : `public, max-age=${opts.maxAge}`;
|
|
61
|
+
reply.header('cache-control', cacheControl).header('etag', etag);
|
|
62
|
+
if (etagMatches(request.headers['if-none-match'], etag))
|
|
63
|
+
return reply.code(304).send();
|
|
64
|
+
const ext = extname(file).toLowerCase();
|
|
65
|
+
reply.type(TYPES[ext] ?? 'application/octet-stream').header('x-content-type-options', 'nosniff');
|
|
66
|
+
// An SVG opened on its own could run script on the site's origin.
|
|
67
|
+
if (ext === '.svg')
|
|
68
|
+
reply.header('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'");
|
|
69
|
+
// Under a GET-only route Fastify answers HEAD itself, from the payload's length.
|
|
70
|
+
return request.method === 'HEAD' && opts.autoHead !== true ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
|
|
71
|
+
}
|
|
29
72
|
/** Serves the files under `opts.dir` at `/public/*`, GET and HEAD, never anything outside it. */
|
|
30
73
|
export function registerPublicRoutes(app, opts) {
|
|
31
74
|
app.route({
|
|
32
75
|
method: ['GET', 'HEAD'],
|
|
33
76
|
url: '/public/*',
|
|
34
77
|
handler: async (request, reply) => {
|
|
35
|
-
const missing = () => reply.code(404).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(catalogPage('site.notFound.title', 'site.notFound'));
|
|
36
78
|
const wildcard = request.params['*'] ?? '';
|
|
37
|
-
const q = request.raw.url?.indexOf('?') ?? -1;
|
|
38
79
|
const rawUrl = request.raw.url ?? '';
|
|
80
|
+
const q = rawUrl.indexOf('?');
|
|
39
81
|
const rawPath = (q === -1 ? rawUrl : rawUrl.slice(0, q)).slice('/public/'.length);
|
|
40
|
-
const
|
|
41
|
-
if (
|
|
42
|
-
return
|
|
43
|
-
|
|
44
|
-
try {
|
|
45
|
-
// A symlink is never followed: not as the file, nor as a folder on the way to it.
|
|
46
|
-
if (!(await lstat(file)).isFile())
|
|
47
|
-
return missing();
|
|
48
|
-
if (!(await realpath(file)).startsWith((await realpath(opts.dir)) + sep))
|
|
49
|
-
return missing();
|
|
50
|
-
bytes = await readFile(file);
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return missing();
|
|
54
|
-
}
|
|
55
|
-
const hex = createHash('sha256').update(bytes).digest('hex');
|
|
56
|
-
const etag = `"${hex.slice(0, 32)}"`;
|
|
57
|
-
const version = new URLSearchParams(q === -1 ? '' : rawUrl.slice(q + 1)).get('v');
|
|
58
|
-
const cacheControl = version === hex.slice(0, ASSET_VERSION_LENGTH) ? 'public, max-age=31536000, immutable' : `public, max-age=${opts.maxAge}`;
|
|
59
|
-
reply.header('cache-control', cacheControl).header('etag', etag);
|
|
60
|
-
if (etagMatches(request.headers['if-none-match'], etag))
|
|
61
|
-
return reply.code(304).send();
|
|
62
|
-
const ext = extname(file).toLowerCase();
|
|
63
|
-
reply.type(TYPES[ext] ?? 'application/octet-stream').header('x-content-type-options', 'nosniff');
|
|
64
|
-
// An SVG opened on its own could run script on the site's origin.
|
|
65
|
-
if (ext === '.svg')
|
|
66
|
-
reply.header('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'");
|
|
67
|
-
return request.method === 'HEAD' ? reply.header('content-length', bytes.length).send() : reply.send(bytes);
|
|
82
|
+
const sent = await sendPublicFile(request, reply, opts, rawPath === '' ? wildcard : rawPath);
|
|
83
|
+
if (sent !== null)
|
|
84
|
+
return sent;
|
|
85
|
+
return reply.code(404).type('text/html; charset=utf-8').header('cache-control', 'no-store').send(catalogPage('site.notFound.title', 'site.notFound'));
|
|
68
86
|
},
|
|
69
87
|
});
|
|
70
88
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type PathSegment } from '../fields/walk.js';
|
|
2
|
+
import type { CoreDeps, DocumentSummary } from '../types.js';
|
|
3
|
+
export interface TextOccurrence {
|
|
4
|
+
n: number;
|
|
5
|
+
snippet: string;
|
|
6
|
+
spansFormatting?: true;
|
|
7
|
+
}
|
|
8
|
+
export interface FieldMatch {
|
|
9
|
+
path: PathSegment[];
|
|
10
|
+
text: string;
|
|
11
|
+
count: number;
|
|
12
|
+
occurrences: TextOccurrence[];
|
|
13
|
+
hidden?: true;
|
|
14
|
+
}
|
|
15
|
+
export interface FindTextResult {
|
|
16
|
+
total: number;
|
|
17
|
+
documents: Array<{
|
|
18
|
+
document: DocumentSummary;
|
|
19
|
+
matches: FieldMatch[];
|
|
20
|
+
}>;
|
|
21
|
+
designedInCode: Array<{
|
|
22
|
+
type: string;
|
|
23
|
+
title: string;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
export declare function findText(deps: CoreDeps, text: string, opts?: {
|
|
27
|
+
type?: string;
|
|
28
|
+
locale?: string;
|
|
29
|
+
limit?: number;
|
|
30
|
+
offset?: number;
|
|
31
|
+
}): Promise<FindTextResult>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { fieldValues } from '../fields/walk.js';
|
|
2
|
+
import { isRecord } from '../fields/zod-internals.js';
|
|
3
|
+
import { textRuns } from '../richtext/runs.js';
|
|
4
|
+
import { designedInCode } from '../registry/designed.js';
|
|
5
|
+
import { documentSchema } from './schema.js';
|
|
6
|
+
import { parseData, summaryQuery, toSummary } from './read.js';
|
|
7
|
+
import { findPhrase, snippetAround } from './text-match.js';
|
|
8
|
+
const KINDS = new Set(['text', 'textarea', 'richText', 'inlineText', 'link']);
|
|
9
|
+
const SNIPPET = 100;
|
|
10
|
+
const MAX_OCCURRENCES = 20;
|
|
11
|
+
function hiddenSlot(data, path) {
|
|
12
|
+
if (path[0] !== 'slots' || typeof path[1] !== 'string')
|
|
13
|
+
return false;
|
|
14
|
+
const slot = data.slots[path[1]];
|
|
15
|
+
return isRecord(slot) && slot.enabled === false;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The fields of a document's values in schema order, including those in switched-off slots,
|
|
19
|
+
* whose draft schema carries no field kinds: those are walked with their block's schema instead.
|
|
20
|
+
*/
|
|
21
|
+
function foundFields(deps, type, data) {
|
|
22
|
+
const { slots } = deps.registry.getType(type).template;
|
|
23
|
+
const keys = Object.keys(slots);
|
|
24
|
+
const off = new Map();
|
|
25
|
+
for (const [key, slot] of Object.entries(slots)) {
|
|
26
|
+
const value = data.slots[key];
|
|
27
|
+
if (!isRecord(value) || value.enabled !== false)
|
|
28
|
+
continue;
|
|
29
|
+
const found = fieldValues(slot.block.schema, value.data, KINDS);
|
|
30
|
+
off.set(key, found.map((v) => ({ ...v, path: ['slots', key, 'data', ...v.path] })));
|
|
31
|
+
}
|
|
32
|
+
const slotOf = (v) => (v.path[0] === 'slots' && typeof v.path[1] === 'string' ? v.path[1] : undefined);
|
|
33
|
+
const rank = (v) => {
|
|
34
|
+
const key = slotOf(v);
|
|
35
|
+
if (key === undefined)
|
|
36
|
+
return -1;
|
|
37
|
+
const i = keys.indexOf(key);
|
|
38
|
+
return i === -1 ? keys.length : i;
|
|
39
|
+
};
|
|
40
|
+
return fieldValues(documentSchema(deps.registry, type, 'strict'), data, KINDS)
|
|
41
|
+
.filter((v) => {
|
|
42
|
+
const key = slotOf(v);
|
|
43
|
+
return key === undefined || !off.has(key);
|
|
44
|
+
})
|
|
45
|
+
.concat(...off.values())
|
|
46
|
+
.sort((a, b) => rank(a) - rank(b));
|
|
47
|
+
}
|
|
48
|
+
function fieldMatches(fields, data, phrase) {
|
|
49
|
+
const matches = [];
|
|
50
|
+
for (const found of fields) {
|
|
51
|
+
let path = found.path;
|
|
52
|
+
const runs = [];
|
|
53
|
+
if (found.meta.kind === 'link') {
|
|
54
|
+
if (!isRecord(found.value) || typeof found.value.text !== 'string')
|
|
55
|
+
continue;
|
|
56
|
+
path = [...path, 'text'];
|
|
57
|
+
runs.push({ text: found.value.text, pieces: [] });
|
|
58
|
+
}
|
|
59
|
+
else if (found.meta.kind === 'richText' || found.meta.kind === 'inlineText') {
|
|
60
|
+
if (!isRecord(found.value) || !Array.isArray(found.value.content))
|
|
61
|
+
continue;
|
|
62
|
+
runs.push(...textRuns(found.value));
|
|
63
|
+
}
|
|
64
|
+
else if (typeof found.value === 'string') {
|
|
65
|
+
runs.push({ text: found.value, pieces: [] });
|
|
66
|
+
}
|
|
67
|
+
const groups = new Map();
|
|
68
|
+
for (const run of runs) {
|
|
69
|
+
for (const hit of findPhrase(run.text, phrase, 'loose')) {
|
|
70
|
+
let group = groups.get(hit.text);
|
|
71
|
+
if (!group) {
|
|
72
|
+
group = { path, text: hit.text, count: 0, occurrences: [] };
|
|
73
|
+
if (hiddenSlot(data, path))
|
|
74
|
+
group.hidden = true;
|
|
75
|
+
groups.set(hit.text, group);
|
|
76
|
+
}
|
|
77
|
+
group.count += 1;
|
|
78
|
+
if (group.occurrences.length < MAX_OCCURRENCES) {
|
|
79
|
+
const occurrence = { n: group.count, snippet: snippetAround(run.text, hit, SNIPPET) };
|
|
80
|
+
if (run.pieces.length > 0 && !run.pieces.some((p) => hit.start >= p.start && hit.end <= p.end)) {
|
|
81
|
+
occurrence.spansFormatting = true;
|
|
82
|
+
}
|
|
83
|
+
group.occurrences.push(occurrence);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
matches.push(...groups.values());
|
|
88
|
+
}
|
|
89
|
+
return matches;
|
|
90
|
+
}
|
|
91
|
+
export async function findText(deps, text, opts = {}) {
|
|
92
|
+
const { registry } = deps;
|
|
93
|
+
if (opts.type !== undefined)
|
|
94
|
+
registry.getType(opts.type);
|
|
95
|
+
const designed = () => [...registry.site.singletons, ...registry.site.globals]
|
|
96
|
+
.filter((def) => (opts.type === undefined || def.name === opts.type) && designedInCode(def.template))
|
|
97
|
+
.map((def) => ({ type: def.name, title: def.label }));
|
|
98
|
+
if (text.trim() === '')
|
|
99
|
+
return { total: 0, documents: [], designedInCode: [] };
|
|
100
|
+
const limit = Math.min(100, Math.max(1, Math.trunc(opts.limit ?? 20)));
|
|
101
|
+
const offset = Math.max(0, Math.trunc(opts.offset ?? 0));
|
|
102
|
+
let query = summaryQuery(deps).where('documents.deleted_at', 'is', null);
|
|
103
|
+
if (opts.type !== undefined)
|
|
104
|
+
query = query.where('documents.type', '=', opts.type);
|
|
105
|
+
if (opts.locale !== undefined)
|
|
106
|
+
query = query.where('documents.locale', '=', opts.locale);
|
|
107
|
+
const rows = await query.execute();
|
|
108
|
+
const typeOrder = [...registry.site.singletons, ...registry.site.globals, ...registry.site.collections].map((d) => d.name);
|
|
109
|
+
const rank = (type) => {
|
|
110
|
+
const i = typeOrder.indexOf(type);
|
|
111
|
+
return i === -1 ? typeOrder.length : i;
|
|
112
|
+
};
|
|
113
|
+
const found = [];
|
|
114
|
+
for (const row of rows) {
|
|
115
|
+
const data = parseData(deps, row.type, row.head_data);
|
|
116
|
+
const matches = fieldMatches(foundFields(deps, row.type, data), data, text);
|
|
117
|
+
if (matches.length > 0)
|
|
118
|
+
found.push({ document: toSummary(deps, row), matches });
|
|
119
|
+
}
|
|
120
|
+
found.sort((a, b) => rank(a.document.type) - rank(b.document.type) ||
|
|
121
|
+
registry.locales.indexOf(a.document.locale) - registry.locales.indexOf(b.document.locale) ||
|
|
122
|
+
b.document.headRev - a.document.headRev);
|
|
123
|
+
return { total: found.length, documents: found.slice(offset, offset + limit), designedInCode: designed() };
|
|
124
|
+
}
|
|
@@ -1,23 +1,10 @@
|
|
|
1
1
|
import { fieldValues } from '../fields/walk.js';
|
|
2
2
|
import { richTextText } from '../richtext/schema.js';
|
|
3
3
|
import { documentSchema } from './schema.js';
|
|
4
|
+
import { fold } from './text-match.js';
|
|
4
5
|
import { parseData, summaryQuery, toSummary } from './read.js';
|
|
5
6
|
const KINDS = new Set(['text', 'textarea', 'richText', 'inlineText']);
|
|
6
7
|
const SNIPPET = 160;
|
|
7
|
-
/** Lower-cased text without accents, with each normalized character's index in the original. */
|
|
8
|
-
function fold(text) {
|
|
9
|
-
let out = '';
|
|
10
|
-
const index = [];
|
|
11
|
-
let i = 0;
|
|
12
|
-
for (const ch of text) {
|
|
13
|
-
for (const c of ch.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase()) {
|
|
14
|
-
out += c;
|
|
15
|
-
index.push(i);
|
|
16
|
-
}
|
|
17
|
-
i += ch.length;
|
|
18
|
-
}
|
|
19
|
-
return { text: out, index };
|
|
20
|
-
}
|
|
21
8
|
const normalize = (text) => fold(text).text;
|
|
22
9
|
function snippetOf(body, words) {
|
|
23
10
|
if (words.length === 0)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Lower-cased text without accents, with each normalized character's index in the original. */
|
|
2
|
+
export declare function fold(text: string): {
|
|
3
|
+
text: string;
|
|
4
|
+
index: number[];
|
|
5
|
+
};
|
|
6
|
+
export interface PhraseHit {
|
|
7
|
+
start: number;
|
|
8
|
+
end: number;
|
|
9
|
+
text: string;
|
|
10
|
+
}
|
|
11
|
+
/** Non-overlapping whole-word hits of a phrase, left to right, as offsets into `text`. None for a phrase that is blank once loose matching drops accents. */
|
|
12
|
+
export declare function findPhrase(text: string, phrase: string, mode: 'loose' | 'exact'): PhraseHit[];
|
|
13
|
+
/** About `size` characters of `text` centered on a hit, trimmed. */
|
|
14
|
+
export declare function snippetAround(text: string, hit: PhraseHit, size: number): string;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/** Lower-cased text without accents, with each normalized character's index in the original. */
|
|
2
|
+
export function fold(text) {
|
|
3
|
+
let out = '';
|
|
4
|
+
const index = [];
|
|
5
|
+
let i = 0;
|
|
6
|
+
for (const ch of text) {
|
|
7
|
+
for (const c of ch.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase()) {
|
|
8
|
+
out += c;
|
|
9
|
+
index.push(i);
|
|
10
|
+
}
|
|
11
|
+
i += ch.length;
|
|
12
|
+
}
|
|
13
|
+
return { text: out, index };
|
|
14
|
+
}
|
|
15
|
+
const WORD = /^[\p{L}\p{N}\p{M}]$/u;
|
|
16
|
+
const firstChar = (s) => [...s][0] ?? '';
|
|
17
|
+
const lastChar = (s) => [...s].at(-1) ?? '';
|
|
18
|
+
function charBefore(text, at) {
|
|
19
|
+
if (at <= 0)
|
|
20
|
+
return '';
|
|
21
|
+
const code = text.charCodeAt(at - 1);
|
|
22
|
+
if (code >= 0xdc00 && code <= 0xdfff && at >= 2)
|
|
23
|
+
return text.slice(at - 2, at);
|
|
24
|
+
return text.slice(at - 1, at);
|
|
25
|
+
}
|
|
26
|
+
function charAt(text, at) {
|
|
27
|
+
return String.fromCodePoint(text.codePointAt(at) ?? 0x20);
|
|
28
|
+
}
|
|
29
|
+
function edgesOk(text, start, end, phrase) {
|
|
30
|
+
if (WORD.test(firstChar(phrase)) && start > 0 && WORD.test(charBefore(text, start)))
|
|
31
|
+
return false;
|
|
32
|
+
if (WORD.test(lastChar(phrase)) && end < text.length && WORD.test(charAt(text, end)))
|
|
33
|
+
return false;
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
37
|
+
/** Non-overlapping whole-word hits of a phrase, left to right, as offsets into `text`. None for a phrase that is blank once loose matching drops accents. */
|
|
38
|
+
export function findPhrase(text, phrase, mode) {
|
|
39
|
+
if (phrase.trim() === '')
|
|
40
|
+
return [];
|
|
41
|
+
const hits = [];
|
|
42
|
+
if (mode === 'exact') {
|
|
43
|
+
let from = 0;
|
|
44
|
+
for (;;) {
|
|
45
|
+
const at = text.indexOf(phrase, from);
|
|
46
|
+
if (at === -1)
|
|
47
|
+
break;
|
|
48
|
+
const end = at + phrase.length;
|
|
49
|
+
if (edgesOk(text, at, end, phrase)) {
|
|
50
|
+
hits.push({ start: at, end, text: text.slice(at, end) });
|
|
51
|
+
from = end;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
from = at + 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return hits;
|
|
58
|
+
}
|
|
59
|
+
const parts = fold(phrase).text.split(/\s+/).filter((p) => p !== '');
|
|
60
|
+
if (parts.length === 0)
|
|
61
|
+
return [];
|
|
62
|
+
const folded = fold(text);
|
|
63
|
+
const regex = new RegExp(parts.map(escapeRegExp).join('\\s+'), 'gu');
|
|
64
|
+
const edge = phrase.trim();
|
|
65
|
+
for (;;) {
|
|
66
|
+
const m = regex.exec(folded.text);
|
|
67
|
+
if (!m)
|
|
68
|
+
break;
|
|
69
|
+
const matchStart = m.index;
|
|
70
|
+
const matchEnd = matchStart + m[0].length;
|
|
71
|
+
if (matchEnd === matchStart) {
|
|
72
|
+
regex.lastIndex = matchStart + 1;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const start = folded.index[matchStart] ?? 0;
|
|
76
|
+
let end = text.length;
|
|
77
|
+
const lastOriginal = folded.index[matchEnd - 1];
|
|
78
|
+
for (let k = matchEnd; k < folded.index.length; k++) {
|
|
79
|
+
const original = folded.index[k];
|
|
80
|
+
if (original !== undefined && original !== lastOriginal) {
|
|
81
|
+
end = original;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (edgesOk(text, start, end, edge)) {
|
|
86
|
+
hits.push({ start, end, text: text.slice(start, end) });
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
regex.lastIndex = matchStart + 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return hits;
|
|
93
|
+
}
|
|
94
|
+
/** About `size` characters of `text` centered on a hit, trimmed. */
|
|
95
|
+
export function snippetAround(text, hit, size) {
|
|
96
|
+
const center = Math.floor((hit.start + hit.end) / 2);
|
|
97
|
+
const start = Math.max(0, center - Math.floor(size / 2));
|
|
98
|
+
return text.slice(start, start + size).trim();
|
|
99
|
+
}
|