payload-plugin-ploma 1.0.0 → 1.1.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/README.md CHANGED
@@ -34,7 +34,36 @@ export default buildConfig({
34
34
  });
35
35
  ```
36
36
 
37
- Posts are created every five minutes on a long-running server. Re-sending an article updates the post with the same slug.
37
+ `serverUrl` is optional and defaults to `https://content.datablue.dev`. Posts are created every minute on a long-running server, with a first check ten seconds after start. Re-sending an article updates the post with the same slug.
38
+
39
+ The plugin tells Ploma AI which site it is (`siteUrl`, default Payload's `serverURL`), so the site shows as connected. If a post fails, the reasons Payload gave (e.g. `category: Required`) are shown in Ploma AI.
40
+
41
+ ## Key takeaways
42
+
43
+ Each article carries up to three key takeaways. They go into the collection's field named `takeaways`, `keyTakeaways`, `highlights`, `keyPoints` or `tldr`, or into the one you name:
44
+
45
+ ```ts
46
+ fields: { /* … */ takeaways: "seo.keyTakeaways" },
47
+ ```
48
+
49
+ | Field type | What is written |
50
+ | --- | --- |
51
+ | `json` | the list |
52
+ | `text`, `textarea` | one `- item` line each |
53
+ | `array` | one row per item, in the row's first text field |
54
+ | `richText` | nothing, unless you pass `convertTakeaways: (items, article, payload) => …` |
55
+
56
+ ## Pictures inside the article
57
+
58
+ With `mediaCollection` set, the pictures in the body are saved into it and the body points at the saved copies, so the post doesn't depend on Ploma AI's server. A picture that can't be fetched keeps its original address. A file already in the collection under the same name is reused. Turn it off with `localizeImages: false`. It is skipped when `convertBody` is set, since your converter sees the original addresses.
59
+
60
+ ## Tables
61
+
62
+ HTML tables pass through as they are with an HTML or markdown body. For a rich text field, `convertBody` decides how tables convert.
63
+
64
+ ## Not sent by Ploma AI
65
+
66
+ FAQs and category aren't part of what Ploma AI sends. Use `defaults` for a fixed category.
38
67
 
39
68
  ## Rich text bodies
40
69
 
@@ -0,0 +1,30 @@
1
+ /** The part of a Payload field config these helpers read. */
2
+ export interface FieldConfig {
3
+ name?: string;
4
+ type: string;
5
+ fields?: FieldConfig[];
6
+ }
7
+ /** Follows a dotted path ("seo.takeaways") through groups to the field it names. */
8
+ export declare function resolveField(fields: FieldConfig[], path: string): FieldConfig | undefined;
9
+ /** The name of the collection's takeaways field, found by its name and type. Undefined when there isn't one. */
10
+ export declare function pickTakeawaysField(fields: FieldConfig[], taken?: string[]): string | undefined;
11
+ /**
12
+ * The takeaways in the shape the field holds: a JSON list, plain lines, or the first text field of each row of an
13
+ * array. Undefined when the field's shape isn't one of those (a rich text field needs `convertTakeaways`), so the post
14
+ * is made without it rather than failing.
15
+ */
16
+ export declare function takeawaysValue(field: FieldConfig | undefined, items: string[] | undefined): unknown;
17
+ /** Every picture inside the article (markdown or HTML), with its alt text. */
18
+ export declare function collectImages(article: {
19
+ html?: string;
20
+ markdown?: string;
21
+ }): Map<string, string>;
22
+ /** Replaces each picture address in the article's HTML and markdown with the one it was saved at. */
23
+ export declare function swapImages<T extends {
24
+ html: string;
25
+ markdown: string;
26
+ }>(article: T, saved: Map<string, string>): T;
27
+ /** A path from a media file made absolute with the site's address, unless there's no real address to use. */
28
+ export declare function absoluteUrl(url: string | undefined, site: string | undefined): string | undefined;
29
+ /** An error's message with the first few reasons Payload gave, e.g. "The following field is invalid: title". */
30
+ export declare function failureMessage(err: unknown): string;
@@ -0,0 +1,92 @@
1
+ // Pure helpers for the Payload plugin. They take plain data, so they can be tested without a running Payload.
2
+ // Names a site commonly gives its "key takeaways" field, in order of preference. Matched without case.
3
+ const TAKEAWAY_NAMES = [
4
+ "takeaways",
5
+ "keytakeaways",
6
+ "key_takeaways",
7
+ "key-takeaways",
8
+ "highlights",
9
+ "keypoints",
10
+ "key_points",
11
+ "tldr",
12
+ "summarypoints",
13
+ ];
14
+ // What a takeaways field can be and still be filled in.
15
+ const TAKEAWAY_TYPES = ["json", "textarea", "text", "array", "richText"];
16
+ /** Follows a dotted path ("seo.takeaways") through groups to the field it names. */
17
+ export function resolveField(fields, path) {
18
+ const [first, ...rest] = path.split(".");
19
+ const field = fields.find((f) => f.name === first);
20
+ if (!field || rest.length === 0)
21
+ return field;
22
+ return field.fields ? resolveField(field.fields, rest.join(".")) : undefined;
23
+ }
24
+ /** The name of the collection's takeaways field, found by its name and type. Undefined when there isn't one. */
25
+ export function pickTakeawaysField(fields, taken = []) {
26
+ const usable = fields.filter((f) => f.name && TAKEAWAY_TYPES.includes(f.type) && !taken.includes(f.name));
27
+ for (const want of TAKEAWAY_NAMES) {
28
+ const hit = usable.find((f) => f.name.toLowerCase() === want);
29
+ if (hit)
30
+ return hit.name;
31
+ }
32
+ return undefined;
33
+ }
34
+ /**
35
+ * The takeaways in the shape the field holds: a JSON list, plain lines, or the first text field of each row of an
36
+ * array. Undefined when the field's shape isn't one of those (a rich text field needs `convertTakeaways`), so the post
37
+ * is made without it rather than failing.
38
+ */
39
+ export function takeawaysValue(field, items) {
40
+ if (!field || !items?.length)
41
+ return undefined;
42
+ switch (field.type) {
43
+ case "json":
44
+ return items;
45
+ case "textarea":
46
+ case "text":
47
+ return items.map((item) => `- ${item}`).join("\n");
48
+ case "array": {
49
+ const text = (field.fields ?? []).find((f) => f.name && (f.type === "text" || f.type === "textarea"));
50
+ return text?.name ? items.map((item) => ({ [text.name]: item })) : undefined;
51
+ }
52
+ default:
53
+ return undefined;
54
+ }
55
+ }
56
+ const IMG_MD = /!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g;
57
+ const IMG_HTML = /<img\b[^>]*?\bsrc="(https?:\/\/[^"]+)"[^>]*>/g;
58
+ /** Every picture inside the article (markdown or HTML), with its alt text. */
59
+ export function collectImages(article) {
60
+ const images = new Map();
61
+ for (const match of (article.markdown ?? "").matchAll(IMG_MD))
62
+ images.set(match[2], match[1]);
63
+ for (const match of (article.html ?? "").matchAll(IMG_HTML)) {
64
+ if (!images.has(match[1]))
65
+ images.set(match[1], /\balt="([^"]*)"/.exec(match[0])?.[1] ?? "");
66
+ }
67
+ return images;
68
+ }
69
+ /** Replaces each picture address in the article's HTML and markdown with the one it was saved at. */
70
+ export function swapImages(article, saved) {
71
+ const swap = (text) => [...saved].reduce((out, [from, to]) => out.split(from).join(to), text ?? "");
72
+ return { ...article, html: swap(article.html), markdown: swap(article.markdown) };
73
+ }
74
+ /** A path from a media file made absolute with the site's address, unless there's no real address to use. */
75
+ export function absoluteUrl(url, site) {
76
+ if (!url)
77
+ return undefined;
78
+ if (/^https?:\/\//.test(url))
79
+ return url;
80
+ if (!site || !/^https?:\/\//.test(site) || /localhost|127\.0\.0\.1/.test(site))
81
+ return url;
82
+ return new URL(url, site).href;
83
+ }
84
+ /** An error's message with the first few reasons Payload gave, e.g. "The following field is invalid: title". */
85
+ export function failureMessage(err) {
86
+ const base = err instanceof Error ? err.message : "Unknown error";
87
+ const data = err?.data;
88
+ const reasons = (data?.errors ?? [])
89
+ .slice(0, 3)
90
+ .map((e) => `${e.path ?? e.label ?? "field"}: ${e.message ?? "invalid"}`);
91
+ return reasons.length > 0 ? `${base} (${reasons.join("; ")})` : base;
92
+ }
package/dist/index.d.ts CHANGED
@@ -13,13 +13,17 @@ export interface PlomaArticle {
13
13
  url: string;
14
14
  alt: string;
15
15
  } | null;
16
+ /** Up to three key takeaways, written once with the article. Empty when none were written. */
17
+ takeaways?: string[];
18
+ /** The live address Ploma AI already knows for the post, when the blog address is set in Ploma AI. */
19
+ url?: string;
16
20
  status: "draft" | "publish";
17
21
  /** ISO time the post should carry as its date. */
18
22
  publishAt: string;
19
23
  }
20
24
  export interface PlomaPluginOptions {
21
- /** The Ploma AI address, e.g. https://content.datablue.dev */
22
- serverUrl: string;
25
+ /** The Ploma AI address. Default https://content.datablue.dev. */
26
+ serverUrl?: string;
23
27
  /** The connection key from Ploma AI: Settings > Publish to > Payload CMS > Plugin. */
24
28
  connectionKey: string;
25
29
  /** The collection posts are created in, e.g. "posts". */
@@ -38,6 +42,12 @@ export interface PlomaPluginOptions {
38
42
  metaTitle?: string;
39
43
  metaDescription?: string;
40
44
  featuredImage?: string;
45
+ /**
46
+ * Where the key takeaways go. Left out, the plugin looks for a field named takeaways, keyTakeaways, highlights,
47
+ * keyPoints or tldr. A json, text, textarea or array field is filled in its own shape; a rich text field needs
48
+ * `convertTakeaways`.
49
+ */
50
+ takeaways?: string;
41
51
  };
42
52
  /** What the body field holds. Default "html". */
43
53
  bodyFormat?: "html" | "markdown";
@@ -46,10 +56,18 @@ export interface PlomaPluginOptions {
46
56
  * whose value isn't a string. Takes over from `bodyFormat`.
47
57
  */
48
58
  convertBody?: (article: PlomaArticle, payload: Payload) => unknown | Promise<unknown>;
49
- /** The upload collection the featured image is saved into. Required with `fields.featuredImage`. */
59
+ /** Builds the takeaways field's value yourself, e.g. for a rich text field. */
60
+ convertTakeaways?: (takeaways: string[], article: PlomaArticle, payload: Payload) => unknown | Promise<unknown>;
61
+ /** The upload collection the featured image and the pictures inside the article are saved into. */
50
62
  mediaCollection?: string;
51
63
  /** The media collection's alt text field. Default "alt". */
52
64
  mediaAltField?: string;
65
+ /**
66
+ * Save the pictures inside the article into `mediaCollection` and point the post at them, so it doesn't depend on
67
+ * Ploma AI's server. Default true when `mediaCollection` is set and you aren't using `convertBody` (which then
68
+ * sees the original addresses and can save them its own way). A picture that can't be fetched keeps its address.
69
+ */
70
+ localizeImages?: boolean;
53
71
  /**
54
72
  * How a draft is told apart from a live post. "versions" (default) uses
55
73
  * Payload's own drafts; give a field to set it to a value instead.
@@ -61,9 +79,14 @@ export interface PlomaPluginOptions {
61
79
  };
62
80
  /** Values added to every post, e.g. a required category or author. */
63
81
  defaults?: Record<string, unknown>;
64
- /** The live address of a created post, reported back to Ploma AI. */
82
+ /**
83
+ * The live address of a created post, reported back to Ploma AI. Left out, the address Ploma AI already holds for
84
+ * the post (from the blog address in its settings) is reported.
85
+ */
65
86
  urlFor?: (doc: Record<string, unknown>, article: PlomaArticle) => string | undefined;
66
- /** Minutes between checks on a long-running server. 0 turns it off. Default 5. */
87
+ /** The site's public address, shown in Ploma AI as the connected site. Default: Payload's `serverURL`. */
88
+ siteUrl?: string;
89
+ /** Minutes between checks on a long-running server. 0 turns it off. Default 1. */
67
90
  intervalMinutes?: number;
68
91
  /** Path of the endpoint that runs a check on demand, for a cron on serverless hosting. Default "/ploma/sync". */
69
92
  syncPath?: string;
@@ -75,4 +98,4 @@ export interface PlomaSyncResult {
75
98
  }
76
99
  /** Fetches whatever Ploma AI has queued and creates it as posts. */
77
100
  export declare function syncPloma(payload: Payload, options: PlomaPluginOptions): Promise<PlomaSyncResult>;
78
- export declare const plomaPlugin: (options: PlomaPluginOptions) => (config: Config) => Config;
101
+ export declare const plomaPlugin: (given: PlomaPluginOptions) => (config: Config) => Config;
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { absoluteUrl, collectImages, failureMessage, pickTakeawaysField, resolveField, swapImages, takeawaysValue, } from "./helpers.js";
2
+ const DEFAULT_SERVER_URL = "https://content.datablue.dev";
1
3
  function setPath(target, path, value) {
2
4
  const parts = path.split(".");
3
5
  let node = target;
@@ -10,10 +12,12 @@ function setPath(target, path, value) {
10
12
  node[parts[parts.length - 1]] = value;
11
13
  }
12
14
  async function callPloma(options, method, path, body) {
13
- const res = await fetch(`${options.serverUrl.replace(/\/+$/, "")}/api/wp${path}`, {
15
+ const res = await fetch(`${(options.serverUrl ?? DEFAULT_SERVER_URL).replace(/\/+$/, "")}/api/wp${path}`, {
14
16
  method,
15
17
  headers: {
16
18
  Authorization: `Bearer ${options.connectionKey}`,
19
+ // Which site this is, so Ploma AI can show it as connected.
20
+ ...(options.siteUrl ? { "X-Ploma-Site": options.siteUrl } : {}),
17
21
  Accept: "application/json",
18
22
  "Content-Type": "application/json",
19
23
  },
@@ -24,28 +28,65 @@ async function callPloma(options, method, path, body) {
24
28
  throw new Error(typeof data.error === "string" ? data.error : `Ploma AI answered ${res.status}.`);
25
29
  return data;
26
30
  }
31
+ /** Downloads a picture and saves it in the media collection; reuses a file saved before under the same name. */
27
32
  async function saveImage(payload, options, image) {
33
+ const name = new URL(image.url).pathname.split("/").pop() || "image";
34
+ const found = await payload
35
+ .find({ collection: options.mediaCollection, where: { filename: { equals: name } }, limit: 1, depth: 0 })
36
+ .catch(() => null);
37
+ const existing = found?.docs?.[0];
38
+ if (existing)
39
+ return { id: existing.id, url: existing.url };
28
40
  const res = await fetch(image.url);
29
41
  if (!res.ok)
30
42
  throw new Error(`Couldn't download the image (${res.status}).`);
31
43
  const data = Buffer.from(await res.arrayBuffer());
32
- const name = new URL(image.url).pathname.split("/").pop() || "image";
33
44
  const mimetype = res.headers.get("content-type")?.split(";")[0] || "image/jpeg";
34
45
  const doc = await payload.create({
35
46
  collection: options.mediaCollection,
36
47
  data: { [options.mediaAltField ?? "alt"]: image.alt },
37
48
  file: { data, mimetype, name, size: data.length },
38
49
  });
39
- return doc.id;
50
+ return { id: doc.id, url: doc.url };
51
+ }
52
+ /**
53
+ * The pictures inside the article live on Ploma AI's server. They are saved into the media collection and the article
54
+ * is rewritten to use them. A picture that can't be fetched keeps its original address; the post is still made.
55
+ */
56
+ async function localizeImages(payload, options, article) {
57
+ const wanted = options.localizeImages ?? !options.convertBody;
58
+ if (!wanted || !options.mediaCollection)
59
+ return article;
60
+ const saved = new Map();
61
+ for (const [url, alt] of collectImages(article)) {
62
+ try {
63
+ const file = await saveImage(payload, options, { url, alt });
64
+ const address = absoluteUrl(file.url, options.siteUrl);
65
+ if (address)
66
+ saved.set(url, address);
67
+ }
68
+ catch (err) {
69
+ payload.logger?.warn?.(`[ploma] Left a picture where it was (${url}): ${err instanceof Error ? err.message : err}`);
70
+ }
71
+ }
72
+ return saved.size > 0 ? swapImages(article, saved) : article;
40
73
  }
41
74
  async function bodyFor(article, options, payload) {
42
75
  if (options.convertBody)
43
76
  return options.convertBody(article, payload);
44
77
  return options.bodyFormat === "markdown" ? article.markdown : article.html;
45
78
  }
46
- async function upsert(payload, options, article) {
79
+ /** Where the takeaways go: the configured field, else the collection's own takeaways field if it has one. */
80
+ function takeawaysPath(options, fields) {
81
+ if (options.fields.takeaways)
82
+ return options.fields.takeaways;
83
+ const taken = Object.values(options.fields).filter((v) => typeof v === "string" && !v.includes("."));
84
+ return pickTakeawaysField(fields, taken);
85
+ }
86
+ async function upsert(payload, options, original) {
47
87
  const { fields } = options;
48
88
  const data = { ...options.defaults };
89
+ const article = await localizeImages(payload, options, original);
49
90
  if (fields.title)
50
91
  setPath(data, fields.title, article.title);
51
92
  setPath(data, fields.slug, article.slug);
@@ -61,7 +102,19 @@ async function upsert(payload, options, article) {
61
102
  if (fields.featuredImage && article.featuredImage) {
62
103
  if (!options.mediaCollection)
63
104
  throw new Error("Set mediaCollection to save the featured image.");
64
- setPath(data, fields.featuredImage, await saveImage(payload, options, article.featuredImage));
105
+ setPath(data, fields.featuredImage, (await saveImage(payload, options, article.featuredImage)).id);
106
+ }
107
+ if (article.takeaways?.length) {
108
+ const collectionFields = payload.collections?.[options.collection]?.config?.fields ?? [];
109
+ const path = takeawaysPath(options, collectionFields);
110
+ if (path) {
111
+ const value = options.convertTakeaways
112
+ ? await options.convertTakeaways(article.takeaways, article, payload)
113
+ : takeawaysValue(resolveField(collectionFields, path), article.takeaways);
114
+ // A field whose shape isn't known is left out, so the post is made without it rather than failing.
115
+ if (value !== undefined)
116
+ setPath(data, path, value);
117
+ }
65
118
  }
66
119
  const live = article.status === "publish";
67
120
  const statusOption = options.status ?? "versions";
@@ -96,14 +149,16 @@ export async function syncPloma(payload, options) {
96
149
  for (const article of articles ?? []) {
97
150
  try {
98
151
  const doc = (await upsert(payload, options, article));
152
+ const url = options.urlFor ? options.urlFor(doc, article) : article.url;
99
153
  await callPloma(options, "POST", `/articles/${encodeURIComponent(article.id)}/ack`, {
100
154
  status: article.status,
101
- ...(options.urlFor ? { url: options.urlFor(doc, article) } : {}),
155
+ ...(url ? { url } : {}),
102
156
  });
103
157
  result.created++;
104
158
  }
105
159
  catch (err) {
106
- const message = err instanceof Error ? err.message : "Unknown error";
160
+ // Payload says "The following field is invalid" and keeps the reasons in data: put the first few in the message.
161
+ const message = failureMessage(err);
107
162
  result.errors.push(`${article.slug}: ${message}`);
108
163
  await callPloma(options, "POST", `/articles/${encodeURIComponent(article.id)}/fail`, {
109
164
  error: message.slice(0, 500),
@@ -120,8 +175,9 @@ export async function syncPloma(payload, options) {
120
175
  result.ok = result.errors.length === 0;
121
176
  return result;
122
177
  }
123
- export const plomaPlugin = (options) => (config) => {
124
- const interval = options.intervalMinutes ?? 5;
178
+ export const plomaPlugin = (given) => (config) => {
179
+ const options = { ...given, siteUrl: given.siteUrl ?? config.serverURL };
180
+ const interval = options.intervalMinutes ?? 1;
125
181
  return {
126
182
  ...config,
127
183
  endpoints: [
@@ -141,6 +197,9 @@ export const plomaPlugin = (options) => (config) => {
141
197
  onInit: async (payload) => {
142
198
  await config.onInit?.(payload);
143
199
  if (interval > 0) {
200
+ // A first check soon after start, so a new connection shows as connected in Ploma AI at once.
201
+ const first = setTimeout(() => void syncPloma(payload, options), 10_000);
202
+ first.unref?.();
144
203
  const timer = setInterval(() => void syncPloma(payload, options), interval * 60_000);
145
204
  timer.unref?.();
146
205
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload-plugin-ploma",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Publishes articles written in Ploma AI into a Payload collection. The site fetches them, so no firewall rule is needed.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -10,14 +10,16 @@
10
10
  ],
11
11
  "scripts": {
12
12
  "build": "tsc",
13
- "typecheck": "tsc --noEmit"
13
+ "typecheck": "tsc --noEmit",
14
+ "test": "vitest run"
14
15
  },
15
16
  "peerDependencies": {
16
17
  "payload": "^3.0.0"
17
18
  },
18
19
  "devDependencies": {
19
20
  "payload": "^3.0.0",
20
- "typescript": "^5.6.0"
21
+ "typescript": "^5.6.0",
22
+ "vitest": "^2.1.9"
21
23
  },
22
24
  "license": "MIT",
23
25
  "repository": {