@interactive-inc/emdash-plugins 0.1.1 → 0.3.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 (51) hide show
  1. package/README.md +135 -5
  2. package/dist/builder/admin/get-editor-page-id.d.ts +6 -1
  3. package/dist/builder/admin/get-editor-page-id.d.ts.map +1 -1
  4. package/dist/builder/admin/get-editor-page-id.js +5 -4
  5. package/dist/builder/admin/get-editor-page-id.js.map +1 -1
  6. package/dist/builder/admin/get-page-preview.d.ts +26 -6
  7. package/dist/builder/admin/get-page-preview.d.ts.map +1 -1
  8. package/dist/builder/admin/get-page-preview.js +19 -5
  9. package/dist/builder/admin/get-page-preview.js.map +1 -1
  10. package/dist/builder/catalog.d.ts +3 -3
  11. package/dist/builder/catalog.d.ts.map +1 -1
  12. package/dist/builder/catalog.js +11 -4
  13. package/dist/builder/catalog.js.map +1 -1
  14. package/dist/builder/constants.d.ts +1 -1
  15. package/dist/builder/constants.js +1 -1
  16. package/dist/builder/middleware.d.ts.map +1 -1
  17. package/dist/builder/middleware.js +12 -4
  18. package/dist/builder/middleware.js.map +1 -1
  19. package/dist/builder/options.d.ts +10 -0
  20. package/dist/builder/options.d.ts.map +1 -1
  21. package/dist/builder/options.js +30 -2
  22. package/dist/builder/options.js.map +1 -1
  23. package/dist/builder/runtime.d.ts.map +1 -1
  24. package/dist/builder/runtime.js +52 -17
  25. package/dist/builder/runtime.js.map +1 -1
  26. package/dist/builder/server/load-page.d.ts +5 -1
  27. package/dist/builder/server/load-page.d.ts.map +1 -1
  28. package/dist/builder/server/load-page.js +14 -2
  29. package/dist/builder/server/load-page.js.map +1 -1
  30. package/dist/builder/server/page-response.d.ts +13 -0
  31. package/dist/builder/server/page-response.d.ts.map +1 -1
  32. package/dist/builder/server/page-response.js +17 -2
  33. package/dist/builder/server/page-response.js.map +1 -1
  34. package/dist/builder/site-path.d.ts +12 -0
  35. package/dist/builder/site-path.d.ts.map +1 -0
  36. package/dist/builder/site-path.js +29 -0
  37. package/dist/builder/site-path.js.map +1 -0
  38. package/package.json +1 -1
  39. package/src/builder/admin/get-editor-page-id.ts +8 -4
  40. package/src/builder/admin/get-page-preview.ts +22 -6
  41. package/src/builder/admin/page-preview-field.tsx +15 -6
  42. package/src/builder/catalog.ts +13 -5
  43. package/src/builder/constants.ts +1 -1
  44. package/src/builder/middleware.ts +11 -4
  45. package/src/builder/options.ts +32 -2
  46. package/src/builder/pages/[...slug].astro +4 -1
  47. package/src/builder/pages/preview/[id].astro +1 -1
  48. package/src/builder/runtime.ts +45 -17
  49. package/src/builder/server/load-page.ts +14 -2
  50. package/src/builder/server/page-response.ts +20 -2
  51. package/src/builder/site-path.ts +23 -0
@@ -1,8 +1,26 @@
1
1
  import { z } from 'zod';
2
+ import { isSitePath } from './site-path.ts';
2
3
 
3
4
  const prefix = z.string().regex(/^(?:\/[a-zA-Z0-9_-]+)*$/);
5
+ const name = z.string().regex(/^[a-z][a-z0-9_]*$/).max(60);
6
+ // A site path the host draws the document alone at; every {id} and {slug} is filled per entry.
7
+ const entryPreviewPath = z.string().max(200).refine(
8
+ value => /\{(?:id|slug)\}/.test(value) && isSitePath(value.replaceAll('{id}', 'id').replaceAll('{slug}', 'slug')),
9
+ 'documentPreviewPath must be a site path outside /_emdash that contains {id} or {slug} and no other tokens, dot segments, backslashes, query or fragment',
10
+ );
11
+ const documentCollection = z.strictObject({
12
+ name,
13
+ // "data" is where EmDash keeps an entry's fields, so a field of that name could not be told apart from them.
14
+ field: name.refine(value => value !== 'data', 'The document field cannot be named data').default('document'),
15
+ // Omitted: the preview is the entry's site URL from its EmDash URL pattern.
16
+ documentPreviewPath: entryPreviewPath.optional(),
17
+ });
18
+ type DocumentCollection = z.output<typeof documentCollection>;
4
19
  const optionsSchema = z.strictObject({
5
- collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).default('pages'),
20
+ // Served by the public and preview routes, and the default for the preview tool.
21
+ collection: name.default('pages'),
22
+ // More collections whose document field is validated and previewed; their pages are the host's own routes.
23
+ collections: z.array(z.union([name.transform((value): DocumentCollection => ({ name: value, field: 'document' })), documentCollection])).default([]),
6
24
  basePath: prefix.default(''),
7
25
  previewPath: prefix.refine(value => value.length > 0 && !value.startsWith('/_emdash'), 'Preview path must be outside EmDash').default('/preview'),
8
26
  homeSlug: z.string().regex(/^[a-zA-Z0-9_-]+$/).max(200).default('home'),
@@ -12,9 +30,21 @@ const optionsSchema = z.strictObject({
12
30
  });
13
31
  export type BuilderOptions = z.input<typeof optionsSchema>;
14
32
  export type ResolvedOptions = z.output<typeof optionsSchema>;
33
+ /** The result always lists the default collection first, so resolving it again changes nothing. */
15
34
  export function resolveOptions(options: BuilderOptions = {}): ResolvedOptions {
16
35
  const result = optionsSchema.parse(options);
17
36
  if (result.basePath.startsWith('/_emdash')) throw new Error('Page routes must be outside EmDash');
18
37
  if (result.basePath === result.previewPath || result.basePath.startsWith(`${result.previewPath}/`)) throw new Error('Page and preview routes overlap');
19
- return result;
38
+ const names = result.collections.map(item => item.name);
39
+ if (new Set(names).size !== names.length) throw new Error('Each collection may be listed only once');
40
+ // Compared as the router sees them: decoded.
41
+ const routed = (path: string) => decodeURIComponent(path);
42
+ const builderPreview = `${routed(result.previewPath)}/`;
43
+ for (const item of result.collections) {
44
+ // The builder's own preview route draws only the default collection, so it cannot serve another one.
45
+ const path = item.documentPreviewPath && routed(item.documentPreviewPath);
46
+ if (path?.startsWith(builderPreview) && !path.slice(builderPreview.length).includes('/')) throw new Error(`documentPreviewPath of collection ${item.name} overlaps the builder preview route ${result.previewPath}/{id}`);
47
+ }
48
+ const primary = result.collections.find(item => item.name === result.collection) ?? { name: result.collection, field: 'document' } satisfies DocumentCollection;
49
+ return { ...result, collections: [primary, ...result.collections.filter(item => item !== primary)] };
20
50
  }
@@ -4,7 +4,10 @@ import components from 'virtual:emdash-plugins/builder/extensions';
4
4
  import PageShell from 'virtual:emdash-plugins/builder/page-shell';
5
5
  import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
6
  const slug = Astro.params.slug || options.homeSlug;
7
- const { page, status } = await pageResponse(slug, options, components);
7
+ const result = await pageResponse(slug, options, components);
8
+ // These routes only draw documents; a stored entry without one cannot be shown.
9
+ const { page } = result;
10
+ const status = !page && result.status === 200 ? 503 : result.status;
8
11
  Astro.response.status = status;
9
12
  Astro.response.headers.set('Cache-Control', 'private, no-store');
10
13
  ---
@@ -6,7 +6,7 @@ import { pageResponse } from '@interactive-inc/emdash-plugins/builder/server';
6
6
  const result = await pageResponse(Astro.params.id ?? '', options, components);
7
7
  // A preview URL must actually authorize this entry; a guessed ID cannot act as a draft URL.
8
8
  const page = result.page?.isPreview ? result.page : null;
9
- const status = page ? 200 : result.status === 503 ? 503 : 404;
9
+ const status = page ? 200 : result.status === 503 || (result.status === 200 && !result.page) ? 503 : 404;
10
10
  Astro.response.status = status;
11
11
  Astro.response.headers.set('Cache-Control', 'private, no-store');
12
12
  Astro.response.headers.set('X-Robots-Tag', 'noindex, nofollow');
@@ -6,17 +6,21 @@ import { pluginId, pluginVersion } from './constants.ts';
6
6
  import { resolveOptions, type BuilderOptions } from './options.ts';
7
7
  import { componentContract, type ComponentExtensions } from './extensions.ts';
8
8
  import { maxMotionElements, motionTokens } from './motion-tokens.ts';
9
+ import { fillSitePath } from './site-path.ts';
9
10
 
10
11
  // EmDash's Contributor role is the lowest role that may read drafts.
11
12
  const contributorRole = 20;
12
13
  const documentInput = z.object({ document: z.unknown() });
13
- const pageInput = z.object({ id: z.string().min(1).max(200) });
14
+ const pageInput = z.object({ collection: z.string().regex(/^[a-z][a-z0-9_]*$/).max(60).optional(), id: z.string().min(1).max(200) });
14
15
 
15
16
  export function createPlugin(input: BuilderOptions = {}, components: ComponentExtensions = {}) {
16
17
  const options = resolveOptions(input);
17
18
  const contract = componentContract(components);
18
19
  const validate = (document: unknown) => validateDocument(document, components);
19
20
  const guide = createPageGuide(options);
21
+ const configured = new Map(options.collections.map(item => [item.name, item]));
22
+ // The default collection is always previewed by the builder's own route.
23
+ if (options.collections[0]!.documentPreviewPath) throw new Error(`Collection ${options.collection} is previewed at ${options.previewPath}/{id}; documentPreviewPath applies only to added collections`);
20
24
  const schemas = Object.fromEntries(Object.entries(contract.props).map(([name, props]) => [name, { props: z.toJSONSchema(props), ...(components[name] ? { description: components[name].description, container: !!components[name].container, motion: !!components[name].motion } : {}) }]));
21
25
  const motion = {
22
26
  enabled: options.motion,
@@ -25,7 +29,7 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
25
29
  };
26
30
  return definePlugin({
27
31
  id: pluginId, version: pluginVersion,
28
- capabilities: ['content:read', 'content:write', 'hooks.content-policy:register'],
32
+ capabilities: ['content:read', 'content:write', 'schema:read', 'hooks.content-policy:register'],
29
33
  admin: {
30
34
  entry: '@interactive-inc/emdash-plugins/builder/admin',
31
35
  fieldWidgets: [
@@ -37,29 +41,37 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
37
41
  'content:beforeSave': {
38
42
  errorPolicy: 'abort',
39
43
  handler: async event => {
40
- if (event.collection !== options.collection) return;
41
- if (!event.isNew && !Object.hasOwn(event.content, 'document')) return;
42
- const result = validate(event.content.document);
44
+ const field = configured.get(event.collection)?.field;
45
+ if (field === undefined) return;
46
+ if (!event.isNew && !Object.hasOwn(event.content, field)) return;
47
+ // An added collection's entry may have no page body yet; the default collection is nothing without one.
48
+ if (event.content[field] == null && event.collection !== options.collection) return;
49
+ const result = validate(event.content[field]);
43
50
  if (!result.success) throw new ContentSaveRejectedError(`Page JSON is invalid: ${result.errors.join('; ')}`);
44
- return { ...event.content, document: result.document };
51
+ return { ...event.content, [field]: result.document };
45
52
  },
46
53
  },
47
54
  'content:beforePublish': {
48
55
  errorPolicy: 'abort',
49
56
  handler: async event => {
50
- if (event.collection !== options.collection) return;
51
- const data = event.content.data;
52
- const document = data && typeof data === 'object' && 'document' in data ? data.document : event.content.document;
57
+ const field = configured.get(event.collection)?.field;
58
+ if (field === undefined) return;
59
+ const { content } = event;
60
+ const data = content.data && typeof content.data === 'object' && !Array.isArray(content.data) ? content.data as Record<string, unknown> : null;
61
+ // EmDash passes the stored entry: its fields sit in data, empty ones left out, next to id, type and status.
62
+ const isEntry = data !== null && typeof content.id === 'string';
63
+ const document = data && Object.hasOwn(data, field) ? data[field] : isEntry ? undefined : content[field];
64
+ if (document == null && event.collection !== options.collection) return;
53
65
  const result = validate(document);
54
66
  if (!result.success) return { cancel: true, reason: `Invalid page JSON: ${result.errors.join('; ')}` };
55
67
  },
56
68
  },
57
69
  },
58
70
  routes: {
59
- configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath }) },
71
+ configuration: { permission: 'content:read', handler: async () => ({ collection: options.collection, previewPath: options.previewPath, collections: options.collections }) },
60
72
  catalog: {
61
73
  permission: 'content:read',
62
- handler: async () => ({ version: 1, components: { ...componentSchemas, ...Object.fromEntries(Object.entries(components).map(([name]) => [name, schemas[name].props])) }, descriptions: schemas, motion, guide, configuration: { collection: options.collection, basePath: options.basePath, previewPath: options.previewPath, homeSlug: options.homeSlug } }),
74
+ handler: async () => ({ version: 1, components: { ...componentSchemas, ...Object.fromEntries(Object.entries(components).map(([name]) => [name, schemas[name].props])) }, descriptions: schemas, motion, guide, configuration: { collection: options.collection, collections: options.collections, basePath: options.basePath, previewPath: options.previewPath, homeSlug: options.homeSlug } }),
63
75
  },
64
76
  validate: {
65
77
  permission: 'content:read',
@@ -72,21 +84,37 @@ export function createPlugin(input: BuilderOptions = {}, components: ComponentEx
72
84
  handler: async ctx => {
73
85
  // Defense in depth: plugin capabilities must not widen a caller's draft access.
74
86
  if (!ctx.user || ctx.user.role < contributorRole) throw new Error('Draft access is required');
75
- const page = await ctx.content?.get(options.collection, pageInput.parse(ctx.input).id);
87
+ const input = pageInput.parse(ctx.input);
88
+ const collection = input.collection ?? options.collection;
89
+ // Only configured collections: this route must not sign draft links for the rest of the site.
90
+ const item = configured.get(collection);
91
+ if (!item) throw new Error(`Collection ${collection} is not configured for builder documents`);
92
+ const page = await ctx.content?.get(collection, input.id);
76
93
  if (!page) throw new Error('Page not found');
77
94
  const previewSecret = process.env.EMDASH_PREVIEW_SECRET;
78
95
  if (!previewSecret) throw new Error('Configure EMDASH_PREVIEW_SECRET before creating preview links');
79
- return {
80
- url: await getPreviewUrl({ collection: options.collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern: `${options.previewPath}/{id}` }),
81
- expiresIn: 900,
82
- };
96
+ let pathPattern = `${options.previewPath}/{id}`;
97
+ // Other collections are drawn by the host's own route: its documentPreviewPath, else the entry's site URL.
98
+ const source = item.documentPreviewPath ? 'documentPreviewPath' : 'URL pattern';
99
+ const invalid = `The ${source} of collection ${collection} must be a site path made of {slug} or {id}`;
100
+ if (collection !== options.collection) {
101
+ const pattern = item.documentPreviewPath ?? (await ctx.schema?.getCollection(collection))?.urlPattern;
102
+ if (!pattern) throw new Error(`Set a URL pattern on collection ${collection} before creating preview links`);
103
+ const path = fillSitePath(pattern, page);
104
+ if (!path) throw new Error(invalid);
105
+ pathPattern = path;
106
+ }
107
+ const url = await getPreviewUrl({ collection, id: page.id, secret: previewSecret, expiresIn: '15m', pathPattern });
108
+ // The signer parses the path as a URL; the link must still be the path that was checked.
109
+ if (collection !== options.collection && !url.startsWith(`${pathPattern}?_preview=`)) throw new Error(invalid);
110
+ return { url, expiresIn: 900 };
83
111
  },
84
112
  },
85
113
  },
86
114
  mcp: { tools: {
87
115
  catalog: { description: 'Read the supported site components, JSON property schemas, data bindings, theme tokens, and the page creation workflow.', route: 'catalog', input: z.object({}) },
88
116
  validate: { description: 'Validate a complete page document before saving it with EmDash content_create or content_update. Does not save or publish.', route: 'validate', input: documentInput },
89
- preview: { description: 'Create a 15-minute signed preview URL for one saved page. Use after saving a draft, before content_publish.', route: 'preview', input: pageInput },
117
+ preview: { description: `Create a 15-minute signed preview URL for one saved entry. Use after saving a draft, before content_publish. collection is one of ${options.collections.map(item => item.name).join(', ')}; omit it for ${options.collection}.`, route: 'preview', input: pageInput },
90
118
  } },
91
119
  });
92
120
  }
@@ -17,13 +17,25 @@ export type LoadedPage = {
17
17
  isPreview: boolean;
18
18
  };
19
19
 
20
- /** All reads go through EmDash's published-entry and scoped preview checks. */
20
+ /** The entry is visible but its document field is empty, as an added collection allows. */
21
+ export const emptyDocument = Symbol('emptyDocument');
22
+
23
+ /** A page always has a document; an entry without one is an error here. */
21
24
  export async function loadPage(identifier: string, input: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<LoadedPage | null> {
25
+ const page = await readPage(identifier, input, components);
26
+ if (page === emptyDocument) throw new Error('Stored page JSON is invalid');
27
+ return page;
28
+ }
29
+
30
+ /** All reads go through EmDash's published-entry and scoped preview checks. */
31
+ export async function readPage(identifier: string, input: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<LoadedPage | typeof emptyDocument | null> {
22
32
  const options = resolveOptions(input);
23
33
  const { entry, error, isPreview } = await getEmDashEntry(options.collection, identifier);
24
34
  if (error) throw new Error('Could not load page');
25
35
  if (!entry) return null;
26
- const validated = validateDocument(entry.data.document, components);
36
+ const stored = entry.data[options.collections[0]!.field];
37
+ if (stored == null) return emptyDocument;
38
+ const validated = validateDocument(stored, components);
27
39
  if (!validated.success) throw new Error('Stored page JSON is invalid');
28
40
  const document = validated.document;
29
41
  const title = typeof entry.data.title === 'string' ? entry.data.title : '';
@@ -1,15 +1,33 @@
1
- import { loadPage, type LoadedPage } from './load-page.ts';
1
+ import { emptyDocument, readPage, type LoadedPage } from './load-page.ts';
2
2
 
3
3
  import type { BuilderOptions } from '../options.ts';
4
4
  import type { ComponentExtensions } from '../extensions.ts';
5
5
 
6
+ /** Status 200 without a page: the entry is visible and has no document to draw. */
6
7
  type Result = { page: LoadedPage | null; status: number };
7
8
  export async function pageResponse(identifier: string, options: BuilderOptions = {}, components: ComponentExtensions = {}): Promise<Result> {
8
9
  try {
9
- const page = await loadPage(identifier, options, components);
10
+ const page = await readPage(identifier, options, components);
11
+ if (page === emptyDocument) return { page: null, status: 200 };
10
12
  return { page, status: page ? 200 : 404 };
11
13
  } catch (error) {
12
14
  console.error('[emdash-plugins/builder] Page resolution failed', error);
13
15
  return { page: null, status: 503 };
14
16
  }
15
17
  }
18
+
19
+ /** The response of the host route, as Astro.response gives it. */
20
+ type RouteResponse = { status: number; headers: Headers };
21
+ /**
22
+ * For the host route at a collection's documentPreviewPath: returns the document only when the
23
+ * request's signed URL authorizes this entry, and sets the route's status and its private, unindexed headers.
24
+ */
25
+ export async function documentPreview(response: RouteResponse, identifier: string | undefined, options: BuilderOptions & { collection: string }, components: ComponentExtensions = {}): Promise<LoadedPage | null> {
26
+ const result = await pageResponse(identifier ?? '', options, components);
27
+ // A guessed ID, another entry's token or a published entry all read what is public, and none of that is a preview.
28
+ const page = result.page?.isPreview ? result.page : null;
29
+ response.status = page ? 200 : result.status === 503 ? 503 : 404;
30
+ response.headers.set('Cache-Control', 'private, no-store');
31
+ response.headers.set('X-Robots-Tag', 'noindex, nofollow');
32
+ return page;
33
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A path of this site that a signed preview may point to. Every segment must mean the same thing to
3
+ * a URL parser and to the router, which decodes more than once: after one decoding nothing is left
4
+ * to decode, and no segment is a separator, a dot segment or EmDash's own prefix (wherever the site is mounted).
5
+ */
6
+ export function isSitePath(path: string): boolean {
7
+ // EmDash's request context skips every path that starts with /_emdash, so a preview there never activates.
8
+ if (!/^(?:\/[A-Za-z0-9._~!*'()%-]+)+$/.test(path) || path.startsWith('/_emdash')) return false;
9
+ return path.slice(1).split('/').every(segment => {
10
+ let decoded: string;
11
+ try { decoded = decodeURIComponent(segment); } catch { return false; }
12
+ // eslint-disable-next-line no-control-regex -- control characters are exactly what must not pass
13
+ return !/[%/\\\u0000-\u001f\u007f-\u009f]/.test(decoded) && decoded !== '.' && decoded !== '..' && decoded.toLowerCase() !== '_emdash';
14
+ });
15
+ }
16
+
17
+ /** An entry's site path from a pattern of {slug} and {id}; null when the result is not a site path. */
18
+ export function fillSitePath(pattern: string, entry: { id: string; slug: string | null }): string | null {
19
+ const filled = pattern.replaceAll('{slug}', encodeURIComponent(entry.slug || entry.id)).replaceAll('{id}', encodeURIComponent(entry.id)).replace(/\/{2,}/g, '/');
20
+ const path = filled.length > 1 && filled.endsWith('/') ? filled.slice(0, -1) : filled;
21
+ // Date tokens have no value before publication, and EmDash's own routes never show a page.
22
+ return isSitePath(path) ? path : null;
23
+ }