@dbp-wp/core 0.2.6 → 0.2.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.
package/dist/index.js CHANGED
@@ -273,6 +273,9 @@ function normalizeSiteUrl(siteUrl) {
273
273
  if (url.protocol !== "https:" && !(url.protocol === "http:" && isLocal)) {
274
274
  throw new Error(`Site URL must use https (http is allowed only for local hosts): ${siteUrl}`);
275
275
  }
276
+ if (!isLocal && isPrivateAddress(url.hostname)) {
277
+ throw new Error(`Site URL must not point to a private or local network address: ${siteUrl}`);
278
+ }
276
279
  if (url.username !== "" || url.password !== "") {
277
280
  throw new Error("Site URL must not contain embedded credentials.");
278
281
  }
@@ -281,6 +284,98 @@ function normalizeSiteUrl(siteUrl) {
281
284
  }
282
285
  return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
283
286
  }
287
+ function isPrivateAddress(hostname) {
288
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
289
+ if (v4) {
290
+ const octets = [Number(v4[1]), Number(v4[2]), Number(v4[3]), Number(v4[4])];
291
+ if (octets.some((o) => o > 255)) {
292
+ return false;
293
+ }
294
+ return isPrivateV4(octets);
295
+ }
296
+ if (hostname.includes(":")) {
297
+ return isPrivateV6(hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, ""));
298
+ }
299
+ return false;
300
+ }
301
+ function isPrivateV4(octets) {
302
+ const [a, b] = octets;
303
+ return a === 0 || // "this" network
304
+ a === 10 || // private
305
+ a === 127 || // loopback
306
+ a === 169 && b === 254 || // link-local (incl. 169.254.169.254 metadata)
307
+ a === 172 && b !== void 0 && b >= 16 && b <= 31 || // private
308
+ a === 192 && b === 168;
309
+ }
310
+ function expandV6(input) {
311
+ let s = input;
312
+ const v4m = /^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
313
+ if (v4m) {
314
+ const o = [Number(v4m[2]), Number(v4m[3]), Number(v4m[4]), Number(v4m[5])];
315
+ if (o.some((x) => x > 255)) {
316
+ return null;
317
+ }
318
+ s = `${v4m[1]}${(o[0] << 8 | o[1]).toString(16)}:${(o[2] << 8 | o[3]).toString(16)}`;
319
+ }
320
+ const halves = s.split("::");
321
+ if (halves.length > 2) {
322
+ return null;
323
+ }
324
+ const toGroups = (side) => {
325
+ if (side === "") {
326
+ return [];
327
+ }
328
+ const out = [];
329
+ for (const part of side.split(":")) {
330
+ if (!/^[0-9a-f]{1,4}$/.test(part)) {
331
+ return null;
332
+ }
333
+ out.push(parseInt(part, 16));
334
+ }
335
+ return out;
336
+ };
337
+ const left = toGroups(halves[0] ?? "");
338
+ if (left === null) {
339
+ return null;
340
+ }
341
+ if (halves.length === 2) {
342
+ const right = toGroups(halves[1] ?? "");
343
+ if (right === null) {
344
+ return null;
345
+ }
346
+ const gap = 8 - left.length - right.length;
347
+ if (gap < 1) {
348
+ return null;
349
+ }
350
+ return [...left, ...new Array(gap).fill(0), ...right];
351
+ }
352
+ return left.length === 8 ? left : null;
353
+ }
354
+ function isPrivateV6(addr) {
355
+ const groups = expandV6((addr.split("%")[0] ?? "").trim());
356
+ if (groups === null) {
357
+ return false;
358
+ }
359
+ if (groups.every((g) => g === 0)) {
360
+ return true;
361
+ }
362
+ if (groups.slice(0, 7).every((g) => g === 0) && groups[7] === 1) {
363
+ return true;
364
+ }
365
+ const first = groups[0] ?? 0;
366
+ if ((first & 65024) === 64512) {
367
+ return true;
368
+ }
369
+ if ((first & 65472) === 65152) {
370
+ return true;
371
+ }
372
+ if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 65535) {
373
+ const g6 = groups[6] ?? 0;
374
+ const g7 = groups[7] ?? 0;
375
+ return isPrivateV4([g6 >> 8 & 255, g6 & 255, g7 >> 8 & 255, g7 & 255]);
376
+ }
377
+ return false;
378
+ }
284
379
  function buildAuthHeader(credentials) {
285
380
  if (credentials.username.includes(":")) {
286
381
  throw new Error('Username must not contain a colon (":") for HTTP Basic authentication.');
@@ -456,14 +551,11 @@ var WpClient = class {
456
551
  async deletePostMeta(id, keys) {
457
552
  assertPostId(id);
458
553
  const cleanKeys = sanitizeMetaKeys(keys);
459
- const raw = await this.request(
460
- `/${CONNECTOR_NAMESPACE}/posts/${String(id)}/meta`,
461
- { method: "DELETE", body: JSON.stringify({ keys: cleanKeys }) }
462
- );
463
- return {
464
- postId: typeof raw.post_id === "number" ? raw.post_id : id,
465
- deleted: Array.isArray(raw.deleted) ? raw.deleted : []
466
- };
554
+ const response = await this.send(`/${CONNECTOR_NAMESPACE}/posts/${String(id)}/meta`, {
555
+ method: "DELETE",
556
+ body: JSON.stringify({ keys: cleanKeys })
557
+ });
558
+ return parseDeleteMetaResponse(await response.text(), id, cleanKeys);
467
559
  }
468
560
  /**
469
561
  * Set a child post's parent relation. The relation keys ride the standard core `meta`
@@ -614,6 +706,23 @@ function buildPostBody(fields, meta) {
614
706
  }
615
707
  return body;
616
708
  }
709
+ function parseDeleteMetaResponse(body, id, requestedKeys) {
710
+ const text = body.trim();
711
+ if (text === "") {
712
+ return { postId: id, deleted: [...requestedKeys] };
713
+ }
714
+ let raw;
715
+ try {
716
+ raw = JSON.parse(text);
717
+ } catch {
718
+ return { postId: id, deleted: [...requestedKeys] };
719
+ }
720
+ return {
721
+ // Trust the request `id` over a malformed `post_id` (0, negative, or fractional included).
722
+ postId: typeof raw.post_id === "number" && Number.isSafeInteger(raw.post_id) && raw.post_id > 0 ? raw.post_id : id,
723
+ deleted: Array.isArray(raw.deleted) ? raw.deleted.filter((k) => typeof k === "string") : []
724
+ };
725
+ }
617
726
  function sanitizeMetaKeys(keys) {
618
727
  if (!Array.isArray(keys)) {
619
728
  throw new Error("Meta keys must be an array of strings.");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/print.ts","../src/relation.ts","../src/wp-client.ts","../src/markdown.ts","../src/calc/index.ts","../src/importer.ts"],"sourcesContent":["/**\n * Print Design template engine.\n *\n * Renders a user-authored HTML template against a {@link PrintRecord} using a small,\n * mustache-like `{{ }}` syntax. Pure and framework-agnostic: the browser UI renders the\n * result inside a sandboxed iframe and prints it (see planning doc 04-print-design).\n *\n * Syntax:\n * - `{{ path }}` resolve a dotted path, HTML-escape the value, and output it.\n * - `{{{ path }}}` same, but output the value raw (no escaping) for HTML fields such as\n * `content` / `excerpt`, which already hold WordPress-rendered HTML.\n * - `{{#each path}} ... {{/each}}` iterate an array; inside the block, `this` is the\n * current item (and `this.<key>` reaches into an object item).\n *\n * Unknown paths render as the empty string. Paths resolve against the record, except\n * `this` / `this.<key>`, which resolve against the current `{{#each}}` item.\n */\n\nimport type { WpPostResponse } from './types';\n\n/** The data a template is rendered against (one WordPress post, flattened for templating). */\nexport interface PrintRecord {\n id: number;\n title: string;\n /** WordPress-rendered HTML. Use `{{{ content }}}` so it is not escaped. */\n content: string;\n /** WordPress-rendered HTML. Use `{{{ excerpt }}}` so it is not escaped. */\n excerpt: string;\n status: string;\n menuOrder: number;\n /** Absolute URL of the featured image, or `''` when the post has none. */\n featuredImageUrl: string;\n /**\n * Flattened post meta, keyed by meta key (values stringified; arrays joined with `, `).\n * Reachable in templates as `{{ meta.<key> }}`. A meta key containing a literal dot\n * cannot be addressed, since template paths split on `.`.\n */\n meta: Record<string, string>;\n /** Taxonomy terms keyed by REST base (e.g. `tax.category`), each an array of term names. */\n tax: Record<string, string[]>;\n}\n\n/** Thrown when a template has an unbalanced `{{#each}}` / `{{/each}}`. */\nexport class TemplateParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TemplateParseError';\n }\n}\n\ntype TemplateNode = TextNode | VarNode | EachNode;\ninterface TextNode {\n kind: 'text';\n value: string;\n}\ninterface VarNode {\n kind: 'var';\n path: string;\n /** `true` for triple-brace `{{{ }}}` (unescaped) output. */\n raw: boolean;\n}\ninterface EachNode {\n kind: 'each';\n path: string;\n body: TemplateNode[];\n}\n\ninterface Scope {\n /** The record paths resolve against by default. */\n record: object;\n /** The current `{{#each}}` item, reachable as `this` / `this.<key>`. */\n current?: unknown;\n}\n\n// Order matters: triple-brace and the each tags must be tried before the generic `{{ }}`.\n// `[\\s\\S]` (not `.`) so a tag may span newlines.\nconst TAG =\n /(\\{\\{\\{\\s*([\\s\\S]+?)\\s*\\}\\}\\})|(\\{\\{\\s*#each\\s+([\\s\\S]+?)\\s*\\}\\})|(\\{\\{\\s*\\/each\\s*\\}\\})|(\\{\\{\\s*([\\s\\S]+?)\\s*\\}\\})/g;\n\n/** Parse a template string into a node tree, validating `{{#each}}` nesting. */\nfunction parseTemplate(template: string): TemplateNode[] {\n const root: TemplateNode[] = [];\n // `current` is the node list we append to; `parents` lets us pop back out of an each\n // block; `open` tracks open each blocks so we can detect unbalanced tags.\n let current: TemplateNode[] = root;\n const parents: TemplateNode[][] = [];\n const open: EachNode[] = [];\n const pushText = (text: string): void => {\n if (text) current.push({ kind: 'text', value: text });\n };\n\n let last = 0;\n TAG.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = TAG.exec(template)) !== null) {\n pushText(template.slice(last, m.index));\n last = TAG.lastIndex;\n if (m[2] !== undefined) {\n // {{{ raw }}}\n current.push({ kind: 'var', path: m[2].trim(), raw: true });\n } else if (m[4] !== undefined) {\n // {{#each path}}\n const node: EachNode = { kind: 'each', path: m[4].trim(), body: [] };\n current.push(node);\n parents.push(current);\n current = node.body;\n open.push(node);\n } else if (m[5] !== undefined) {\n // {{/each}}\n if (open.length === 0) {\n throw new TemplateParseError('Unexpected {{/each}} without a matching {{#each}}.');\n }\n open.pop();\n current = parents.pop() ?? root;\n } else if (m[7] !== undefined) {\n // {{ var }}\n current.push({ kind: 'var', path: m[7].trim(), raw: false });\n }\n }\n pushText(template.slice(last));\n\n if (open.length > 0) {\n const unclosed = open[open.length - 1];\n throw new TemplateParseError(`Unclosed {{#each ${unclosed ? unclosed.path : ''}}}.`);\n }\n return root;\n}\n\n/** Walk a dotted path (e.g. `meta.price`) into a value, returning `undefined` if any hop misses. */\nfunction getPath(obj: unknown, path: string): unknown {\n let cur: unknown = obj;\n for (const key of path.split('.')) {\n if (cur === null || cur === undefined || typeof cur !== 'object') {\n return undefined;\n }\n cur = (cur as Record<string, unknown>)[key];\n }\n return cur;\n}\n\n/** Resolve a template path against the scope. `this` / `this.<key>` target the each item. */\nfunction resolve(path: string, scope: Scope): unknown {\n if (path === 'this') {\n return scope.current;\n }\n if (path.startsWith('this.')) {\n return getPath(scope.current, path.slice('this.'.length));\n }\n return getPath(scope.record, path);\n}\n\n/** Stringify a scalar for output; non-scalars (objects/arrays) and nullish render as ''. */\nfunction stringifyScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // Objects/arrays have no sensible inline string form; render nothing.\n return '';\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\nfunction renderNodes(nodes: TemplateNode[], scope: Scope, escape: boolean): string {\n let out = '';\n for (const node of nodes) {\n if (node.kind === 'text') {\n out += node.value;\n } else if (node.kind === 'var') {\n const value = stringifyScalar(resolve(node.path, scope));\n // `{{{ }}}` is always raw; `{{ }}` is HTML-escaped only in escaping (HTML) mode.\n out += node.raw || !escape ? value : escapeHtml(value);\n } else {\n // each: iterate only when the path resolves to an array; otherwise render nothing.\n const list = resolve(node.path, scope);\n if (Array.isArray(list)) {\n for (const item of list) {\n out += renderNodes(node.body, { record: scope.record, current: item }, escape);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Render a Print Design template against one record. Values are HTML-escaped for `{{ }}`\n * and emitted raw for `{{{ }}}`. Throws {@link TemplateParseError} on unbalanced\n * `{{#each}}` / `{{/each}}`.\n */\nexport function renderTemplate(template: string, record: PrintRecord): string {\n return renderNodes(parseTemplate(template), { record }, true);\n}\n\n/**\n * Render a template against an arbitrary record object, reusing the same `{{ }}` /\n * `{{#each}}` engine as {@link renderTemplate}. By default `{{ }}` values are HTML-escaped\n * (HTML output). Pass `escape: false` for a plain-text context (e.g. a spreadsheet cell\n * rendered as text, where the host already escapes for the DOM and re-escaping here would\n * surface literal entities). Throws {@link TemplateParseError} on unbalanced `{{#each}}`.\n */\nexport function renderRecordTemplate(\n template: string,\n record: object,\n options: { escape?: boolean } = {},\n): string {\n return renderNodes(parseTemplate(template), { record }, options.escape ?? true);\n}\n\n/** Flatten one meta value to a string. Arrays join their non-empty scalar parts. */\nfunction flattenMetaValue(value: unknown): string {\n if (Array.isArray(value)) {\n return value\n .map(stringifyScalar)\n .filter((s) => s !== '')\n .join(', ');\n }\n return stringifyScalar(value);\n}\n\n/** Merge core meta and connector meta (connector wins) into flat string values. */\nfunction flattenMeta(raw: WpPostResponse): Record<string, string> {\n // Null-proto so untrusted meta keys (e.g. `__proto__`, `constructor`) become plain own\n // entries with no prototype pollution and no inherited-key collisions.\n const out: Record<string, string> = Object.create(null) as Record<string, string>;\n const add = (src: Record<string, unknown> | undefined): void => {\n if (!src) return;\n for (const [key, value] of Object.entries(src)) {\n out[key] = flattenMetaValue(value);\n }\n };\n add(raw.meta);\n add(raw.dbp_wp_meta); // connector meta overlays core meta for the same key\n return out;\n}\n\n/** Extract the featured image URL from an `_embed`ded response, or '' when absent. */\nfunction extractFeaturedImageUrl(embedded: WpPostResponse['_embedded']): string {\n const media = embedded?.['wp:featuredmedia'];\n if (Array.isArray(media) && media.length > 0) {\n const first = media[0];\n if (first !== null && typeof first === 'object') {\n const sourceUrl = (first as Record<string, unknown>).source_url;\n if (typeof sourceUrl === 'string') {\n return sourceUrl;\n }\n }\n }\n return '';\n}\n\n/** Group `_embed`ded terms into `{ <taxonomy slug>: [term name, ...] }`. */\nfunction extractTerms(embedded: WpPostResponse['_embedded']): Record<string, string[]> {\n // Null-proto so a taxonomy slug like `toString`/`__proto__` cannot resolve an inherited\n // value (which would make `(tax[slug] ??= [])` skip the array and throw on `.push`).\n const tax: Record<string, string[]> = Object.create(null) as Record<string, string[]>;\n const groups = embedded?.['wp:term'];\n if (!Array.isArray(groups)) {\n return tax;\n }\n for (const group of groups) {\n if (!Array.isArray(group)) continue;\n for (const term of group) {\n if (term === null || typeof term !== 'object') continue;\n const entry = term as Record<string, unknown>;\n if (typeof entry.taxonomy === 'string' && typeof entry.name === 'string') {\n (tax[entry.taxonomy] ??= []).push(entry.name);\n }\n }\n }\n return tax;\n}\n\n/**\n * Build a {@link PrintRecord} from a raw WordPress REST post. Expects the request to have\n * used `context=edit` and `_embed` so `content`/`excerpt` and embedded media/terms are\n * present; missing pieces degrade to empty values rather than throwing.\n *\n * `title` uses the raw (unescaped) value so `{{ title }}` escaping is not doubled.\n * `content`/`excerpt` use the rendered HTML (intended for `{{{ }}}`).\n */\nexport function buildPrintRecord(raw: WpPostResponse): PrintRecord {\n return {\n id: raw.id,\n title: raw.title?.raw ?? raw.title?.rendered ?? '',\n content: raw.content?.rendered ?? '',\n excerpt: raw.excerpt?.rendered ?? '',\n status: raw.status,\n menuOrder: raw.menu_order,\n featuredImageUrl: extractFeaturedImageUrl(raw._embedded),\n meta: flattenMeta(raw),\n tax: extractTerms(raw._embedded),\n };\n}\n","import { renderRecordTemplate } from './print';\nimport type { WpPost } from './types';\n\n/**\n * Parent/child relations (MVP: links only).\n *\n * The relation is stored single-source on the **child**: `_dbp_wp_parent` holds the\n * parent post ID and `_dbp_wp_parent_type` holds the parent post type's REST route base.\n * The parent keeps no child list — a parent's children are derived from already-loaded\n * posts ({@link deriveChildren}), so there is no denormalized list to keep in sync.\n *\n * These keys are `_`-prefixed (protected) and are exposed over REST only because the\n * companion plugin registers them with `register_post_meta()` + an `edit_post`\n * `auth_callback`. They therefore travel through the standard core `meta` field — not the\n * connector's `dbp_wp_meta` field — so relation writes use a dedicated path.\n */\n\n/** Meta key holding a child's parent post ID. */\nexport const PARENT_META_KEY = '_dbp_wp_parent';\n\n/** Meta key holding the parent post type's REST route base. */\nexport const PARENT_TYPE_META_KEY = '_dbp_wp_parent_type';\n\n/** Allowed characters for a REST route segment (post type slug); mirrors the WpClient check. */\nconst ROUTE_SEGMENT = /^[a-z0-9_-]+$/i;\n\n/** A parent assignment for a child post. */\nexport interface RelationTarget {\n /** Parent post ID (positive integer). */\n parentId: number;\n /** Parent post type's REST route base (e.g. `pages`). */\n parentType: string;\n}\n\n/** Error thrown when a relation assignment is invalid (bad id/type, or self-parent). */\nexport class RelationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'RelationError';\n }\n}\n\n/**\n * Validate a parent assignment for a child. Throws {@link RelationError} when the parent\n * id is not a positive safe integer, the parent type is not a valid route segment, or the\n * parent is the child itself (post IDs are unique across types, so this catches a\n * self-parent regardless of type).\n */\nexport function assertValidRelation(childId: number, relation: RelationTarget): void {\n if (!Number.isSafeInteger(relation.parentId) || relation.parentId <= 0) {\n throw new RelationError(`Invalid parent id: ${String(relation.parentId)}`);\n }\n if (typeof relation.parentType !== 'string' || !ROUTE_SEGMENT.test(relation.parentType)) {\n throw new RelationError(`Invalid parent type: ${String(relation.parentType)}`);\n }\n if (relation.parentId === childId) {\n throw new RelationError('A post cannot be its own parent.');\n }\n}\n\n/**\n * Build the standard-`meta` body that sets a child's parent. Validates the assignment\n * first ({@link assertValidRelation}). The keys ride the core `meta` field, so the caller\n * sends `{ meta: <this> }`.\n */\nexport function buildSetRelationMeta(\n childId: number,\n relation: RelationTarget,\n): Record<string, unknown> {\n assertValidRelation(childId, relation);\n return {\n [PARENT_META_KEY]: relation.parentId,\n [PARENT_TYPE_META_KEY]: relation.parentType,\n };\n}\n\n/**\n * Build the standard-`meta` body that clears a child's parent. Sending `null` for a\n * registered single meta key makes WordPress delete it, so no stale value is left behind.\n */\nexport function buildClearRelationMeta(): Record<string, unknown> {\n return {\n [PARENT_META_KEY]: null,\n [PARENT_TYPE_META_KEY]: null,\n };\n}\n\n/**\n * Read a post's parent relation from its normalized fields, or null when it has no parent.\n * Both a positive `parent` id and a non-empty `parentType` are required for a relation to\n * count (a half-written relation reads as none).\n */\nexport function getRelation(post: WpPost): RelationTarget | null {\n if (\n typeof post.parent === 'number' &&\n post.parent > 0 &&\n typeof post.parentType === 'string' &&\n post.parentType !== ''\n ) {\n return { parentId: post.parent, parentType: post.parentType };\n }\n return null;\n}\n\n/**\n * Derive a parent's children from already-loaded posts: every post whose `_dbp_wp_parent`\n * equals `parentId`. This covers the common case of same-type children visible in the\n * current grid; cross-type or off-grid children would need a server-side query (deferred).\n */\nexport function deriveChildren(posts: WpPost[], parentId: number): WpPost[] {\n if (!Number.isSafeInteger(parentId) || parentId <= 0) {\n return [];\n }\n return posts.filter((post) => post.parent === parentId);\n}\n\n// --- Child data (template aggregation of a parent's children) ---\n//\n// The legacy app stored a per-parent template (`_dbpcloudwp_child_formula`) and cached its\n// rendered output (`_dbpcloudwp_child_value`) as parent meta — a denormalized value that\n// went stale whenever a child changed. The new model persists nothing: a column-level\n// template is rendered live against each parent's derived children, reusing the Print\n// template engine ({@link renderRecordTemplate}). So `{{ }}`/`{{#each}}` work as in Print.\n\n/** A child post flattened for templating inside a parent's child-data column. */\nexport interface ChildRecord {\n id: number;\n title: string;\n status: string;\n menuOrder: number;\n /** Flattened meta (core overlaid by connector), values stringified; `this.meta.<key>`. */\n meta: Record<string, string>;\n}\n\n/**\n * A parent exposed to a child-data template: its own fields plus the derived `children`\n * (and `childCount`), so a template can aggregate them, e.g.\n * `{{#each children}}{{ this.title }}{{/each}}`.\n */\nexport interface ParentAggregateRecord {\n id: number;\n title: string;\n status: string;\n menuOrder: number;\n meta: Record<string, string>;\n childCount: number;\n children: ChildRecord[];\n}\n\n/** Stringify one meta value; an array joins its non-empty scalar parts with `, `. */\nfunction flattenMetaValue(value: unknown): string {\n if (Array.isArray(value)) {\n return value\n .map((v) => (v === null || v === undefined ? '' : String(v)))\n .filter((s) => s !== '')\n .join(', ');\n }\n return value === null || value === undefined ? '' : String(value);\n}\n\n/**\n * Flatten a post's meta (core `meta` overlaid by connector `dbpWpMeta`) to flat string\n * values. Uses a null-proto accumulator so untrusted meta keys (`__proto__`, `constructor`)\n * become plain own entries with no prototype pollution and no inherited-key collisions.\n */\nfunction flattenPostMeta(post: WpPost): Record<string, string> {\n const out: Record<string, string> = Object.create(null) as Record<string, string>;\n const add = (src: Record<string, unknown> | undefined): void => {\n if (!src) return;\n for (const [key, value] of Object.entries(src)) {\n out[key] = flattenMetaValue(value);\n }\n };\n add(post.meta);\n add(post.dbpWpMeta); // connector meta overlays core meta for the same key\n return out;\n}\n\n/** Build a {@link ChildRecord} from a loaded post (meta flattened for templating). */\nexport function buildChildRecord(post: WpPost): ChildRecord {\n return {\n id: post.id,\n title: post.title,\n status: post.status,\n menuOrder: post.menuOrder,\n meta: flattenPostMeta(post),\n };\n}\n\n/** Build the {@link ParentAggregateRecord} a child-data template renders against. */\nexport function buildParentAggregate(parent: WpPost, children: WpPost[]): ParentAggregateRecord {\n return {\n id: parent.id,\n title: parent.title,\n status: parent.status,\n menuOrder: parent.menuOrder,\n meta: flattenPostMeta(parent),\n childCount: children.length,\n children: children.map(buildChildRecord),\n };\n}\n\n/**\n * Render a \"child data\" template for one parent: derive its children from the already-loaded\n * posts ({@link deriveChildren}), build the aggregate record, and render the template with\n * the shared Print engine. Same-type, in-grid children only (cross-type/off-grid children\n * need a server query — deferred). Rendered in plain-text (non-escaping) mode, since the\n * result is shown as a spreadsheet cell's text. Throws {@link TemplateParseError} on an\n * unbalanced `{{#each}}`.\n */\nexport function renderChildData(template: string, parent: WpPost, posts: WpPost[]): string {\n const children = deriveChildren(posts, parent.id);\n return renderRecordTemplate(template, buildParentAggregate(parent, children), { escape: false });\n}\n","import { buildPrintRecord, type PrintRecord } from './print';\nimport {\n PARENT_META_KEY,\n PARENT_TYPE_META_KEY,\n buildClearRelationMeta,\n buildSetRelationMeta,\n type RelationTarget,\n} from './relation';\nimport type {\n DeleteMetaResult,\n ListMediaParams,\n ListPostsParams,\n UpdatePostFields,\n WpCredentials,\n WpMedia,\n WpPost,\n WpPostEdit,\n WpPostResponse,\n WpPostType,\n} from './types';\n\n/** Hosts for which plain http is tolerated (local development). */\nconst LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);\n\n/** Allowed characters for a REST route segment (post type slug). No dots: a `.`/`..`\n * segment would be resolved by the URL parser and traverse the REST path. */\nconst ROUTE_SEGMENT = /^[a-z0-9_-]+$/i;\n\n/** REST field added by the companion plugin to carry arbitrary post meta. */\nconst META_FIELD = 'dbp_wp_meta';\n\n/**\n * Meta key holding the lossless Markdown source for a post edited in Markdown mode. An\n * underscore-prefixed (protected) key, so the companion plugin must register it with\n * `register_post_meta` + an `edit_post` auth callback to expose it over REST — the generic\n * `dbp_wp_meta` field excludes protected keys. Like the relation keys, it therefore rides\n * the standard core `meta` field, not `dbp_wp_meta`.\n */\nexport const MARKDOWN_META_KEY = '_dbp_wp_markdown';\n\n/** REST namespace registered by the companion plugin. */\nconst CONNECTOR_NAMESPACE = 'dbp-wp/v1';\n\n/**\n * Validate and normalize a WordPress site URL into a REST base (origin + base path).\n *\n * Requires https, except plain http is allowed for local development hosts. Rejects\n * embedded credentials, query strings, and fragments, and strips trailing slashes — so\n * an Application Password is never sent over cleartext to an unexpected target.\n */\nexport function normalizeSiteUrl(siteUrl: string): string {\n let url: URL;\n try {\n url = new URL(siteUrl);\n } catch {\n throw new Error(`Invalid site URL: ${siteUrl}`);\n }\n\n const isLocal = LOCAL_HOSTS.has(url.hostname);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLocal)) {\n throw new Error(`Site URL must use https (http is allowed only for local hosts): ${siteUrl}`);\n }\n if (url.username !== '' || url.password !== '') {\n throw new Error('Site URL must not contain embedded credentials.');\n }\n if (url.search !== '' || url.hash !== '') {\n throw new Error('Site URL must not contain a query string or fragment.');\n }\n\n return `${url.origin}${url.pathname}`.replace(/\\/+$/, '');\n}\n\n/**\n * Build the HTTP Basic `Authorization` header value from Application Password\n * credentials. WordPress treats the Application Password as the Basic-auth password.\n */\nexport function buildAuthHeader(credentials: WpCredentials): string {\n if (credentials.username.includes(':')) {\n throw new Error('Username must not contain a colon (\":\") for HTTP Basic authentication.');\n }\n const token = `${credentials.username}:${credentials.applicationPassword}`;\n const base64 = Buffer.from(token, 'utf-8').toString('base64');\n return `Basic ${base64}`;\n}\n\n/** Error thrown when the WordPress REST API returns a non-2xx response. */\nexport class WpRequestError extends Error {\n constructor(\n readonly status: number,\n readonly path: string,\n message: string,\n ) {\n super(message);\n this.name = 'WpRequestError';\n }\n}\n\n/**\n * Minimal WordPress REST client.\n *\n * Runs in the Node process (CLI shell), never in the browser, so Application Password\n * credentials stay server-side. MVP scope: list posts, read/write post meta.\n */\nexport class WpClient {\n private readonly restBase: string;\n\n constructor(private readonly credentials: WpCredentials) {\n this.restBase = normalizeSiteUrl(credentials.siteUrl);\n }\n\n /**\n * Send an authenticated request and return the raw {@link Response} (throwing on non-2xx),\n * so callers that need response headers — e.g. media pagination via `X-WP-TotalPages` —\n * can read them. A JSON `Content-Type` is declared only when a body is sent; a caller may\n * override it via `init.headers` (the media upload sends the file's own type).\n */\n private async send(path: string, init: RequestInit = {}): Promise<Response> {\n const response = await fetch(`${this.restBase}/wp-json${path}`, {\n ...init,\n headers: {\n Authorization: buildAuthHeader(this.credentials),\n // Only declare a JSON body when one is actually sent (GETs carry none).\n ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...init.headers,\n },\n });\n\n if (!response.ok) {\n throw new WpRequestError(\n response.status,\n path,\n `WordPress REST request failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n }\n\n private async request<T>(path: string, init: RequestInit = {}): Promise<T> {\n return (await this.send(path, init)).json() as Promise<T>;\n }\n\n /**\n * List the REST-enabled post types on the site (edit context), so the app can offer\n * a type selector. Returns each type's REST route base and display name.\n */\n async listPostTypes(): Promise<WpPostType[]> {\n const raw = await this.request<unknown>('/wp/v2/types?context=edit');\n return normalizePostTypes(raw);\n }\n\n /** List posts of a given type in edit context (raw fields, for editing). */\n async listPosts(params: ListPostsParams = {}): Promise<WpPost[]> {\n const type = params.type ?? 'posts';\n assertRouteSegment(type);\n const perPage = clampInt(params.perPage ?? 100, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n context: 'edit',\n per_page: String(perPage),\n page: String(page),\n });\n const raw = await this.request<WpPostResponse[]>(`/wp/v2/${type}?${query.toString()}`);\n return raw.map(normalizePost);\n }\n\n /**\n * List posts as {@link PrintRecord}s for Print Design. Requests `_embed` (so featured\n * media and taxonomy terms come back inline) plus `content`/`excerpt`; the standard\n * table/spreadsheet listing ({@link WpClient.listPosts}) is unaffected.\n */\n async listPostsForPrint(params: ListPostsParams = {}): Promise<PrintRecord[]> {\n const type = params.type ?? 'posts';\n assertRouteSegment(type);\n const perPage = clampInt(params.perPage ?? 100, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n context: 'edit',\n per_page: String(perPage),\n page: String(page),\n _embed: '1',\n });\n const raw = await this.request<WpPostResponse[]>(`/wp/v2/${type}?${query.toString()}`);\n return raw.map(buildPrintRecord);\n }\n\n /**\n * Update post fields in a single request. Standard fields (title, menu_order,\n * status) are core REST fields and need no plugin. When `meta` is supplied it rides\n * the same request through the companion plugin's `dbp_wp_meta` field (ignored by\n * WordPress without the connector). Pass the REST route slug as `type` (e.g.\n * `posts`, `pages`) — not the object type returned on a post.\n */\n async updatePost(\n id: number,\n fields: UpdatePostFields,\n type = 'posts',\n meta?: Record<string, unknown>,\n ): Promise<WpPost> {\n assertPostId(id);\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(buildPostBody(fields, meta)),\n });\n return normalizePost(raw);\n }\n\n /**\n * Create a new post in a single request, symmetric to {@link WpClient.updatePost}.\n * Standard fields (title, menu_order, status) are core REST fields; when `meta` is\n * supplied it rides the same request through the companion plugin's `dbp_wp_meta`\n * field. Pass the REST route slug as `type` (e.g. `posts`, `pages`).\n */\n async createPost(\n fields: UpdatePostFields,\n type = 'posts',\n meta?: Record<string, unknown>,\n ): Promise<WpPost> {\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(buildPostBody(fields, meta)),\n });\n return normalizePost(raw);\n }\n\n /**\n * Update only arbitrary post meta through the companion plugin's `dbp_wp_meta`\n * field. A thin wrapper over {@link WpClient.updatePost} with no standard fields.\n * Requires the connector; the connector writes scalar values only.\n */\n async updatePostMeta(\n id: number,\n meta: Record<string, unknown>,\n type = 'posts',\n ): Promise<WpPost> {\n return this.updatePost(id, {}, type, meta);\n }\n\n /**\n * Fetch a single post for body editing (edit context), returning the raw body\n * (`content.raw`) and, when present, the lossless Markdown source from\n * `_dbp_wp_markdown`. The standard listing ({@link WpClient.listPosts}) omits the body, so\n * the editor uses this dedicated read. The Markdown source comes back via the standard\n * `meta` field only when the connector registered the key; in restricted mode the post is\n * HTML-only. Pass the REST route slug as `type`.\n */\n async getPostForEdit(id: number, type = 'posts'): Promise<WpPostEdit> {\n assertPostId(id);\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`);\n return normalizePostForEdit(raw);\n }\n\n /**\n * Save a single post's body. Writes `content` (core REST) and, when `markdown` is given,\n * the `_dbp_wp_markdown` source via the standard `meta` field (registered by the connector)\n * — both in one request. Pass `markdown` as the source string for Markdown mode, `null` to\n * clear it (HTML mode on a post previously saved as Markdown), or omit it for an HTML-only\n * post. Writing/clearing `markdown` requires the connector; a content-only save does not.\n * Returns the re-fetched edit model (edit context), so the caller sees the persisted mode.\n */\n async updatePostBody(\n id: number,\n type: string,\n body: { content: string; markdown?: string | null },\n ): Promise<WpPostEdit> {\n assertPostId(id);\n assertRouteSegment(type);\n const reqBody = buildUpdateBody({ content: body.content });\n if (body.markdown !== undefined) {\n // Standard `meta` field (like the relation keys), not the connector's `dbp_wp_meta`:\n // `_dbp_wp_markdown` is protected and is only writable through register_post_meta.\n // `null` makes WordPress delete the key (no stale source left to mis-detect the mode).\n reqBody.meta = { [MARKDOWN_META_KEY]: body.markdown };\n }\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(reqBody),\n });\n return normalizePostForEdit(raw);\n }\n\n /**\n * Delete named meta keys from a single post via the companion plugin's\n * `DELETE /dbp-wp/v1/posts/<id>/meta` route. This route is keyed by id only (the\n * post type is irrelevant). Requires the connector.\n */\n async deletePostMeta(id: number, keys: string[]): Promise<DeleteMetaResult> {\n assertPostId(id);\n const cleanKeys = sanitizeMetaKeys(keys);\n const raw = await this.request<{ post_id?: unknown; deleted?: string[] }>(\n `/${CONNECTOR_NAMESPACE}/posts/${String(id)}/meta`,\n { method: 'DELETE', body: JSON.stringify({ keys: cleanKeys }) },\n );\n // Trust our own request `id` over a malformed connector `post_id`.\n return {\n postId: typeof raw.post_id === 'number' ? raw.post_id : id,\n deleted: Array.isArray(raw.deleted) ? raw.deleted : [],\n };\n }\n\n /**\n * Set a child post's parent relation. The relation keys ride the standard core `meta`\n * field (the connector registers them with `register_post_meta`), so this is a distinct\n * path from {@link WpClient.updatePostMeta} (which uses the connector's `dbp_wp_meta`\n * field). Validates the assignment (positive id, valid type, no self-parent) before\n * writing. Requires the connector; without it WordPress silently ignores the keys.\n */\n async setRelation(\n childId: number,\n childType: string,\n relation: RelationTarget,\n ): Promise<WpPost> {\n assertPostId(childId);\n assertRouteSegment(childType);\n const raw = await this.request<WpPostResponse>(\n `/wp/v2/${childType}/${String(childId)}?context=edit`,\n { method: 'POST', body: JSON.stringify({ meta: buildSetRelationMeta(childId, relation) }) },\n );\n return normalizePost(raw);\n }\n\n /**\n * Clear a child post's parent relation. Sends `null` for both relation keys, which makes\n * WordPress delete them (no stale `0`/empty value left behind). Requires the connector.\n */\n async clearRelation(childId: number, childType: string): Promise<WpPost> {\n assertPostId(childId);\n assertRouteSegment(childType);\n const raw = await this.request<WpPostResponse>(\n `/wp/v2/${childType}/${String(childId)}?context=edit`,\n { method: 'POST', body: JSON.stringify({ meta: buildClearRelationMeta() }) },\n );\n return normalizePost(raw);\n }\n\n /**\n * Detect whether the companion plugin is active by checking the REST index\n * (`/wp-json/`) for the connector's namespace. Throws on a failed request; a caller\n * that wants a non-fatal probe should treat a thrown error as \"not available\".\n */\n async detectConnector(): Promise<boolean> {\n const index = await this.request<{ namespaces?: unknown }>('/');\n return hasConnectorNamespace(index.namespaces);\n }\n\n /**\n * Upload an image to the media library via core REST (`POST /wp/v2/media`), the same\n * contract WordPress uses: raw bytes with a `Content-Disposition` filename and the file's\n * MIME type (octet-stream when unknown). No companion plugin needed; the authenticated\n * user must have `upload_files`. Returns the normalized media item.\n */\n async uploadMedia(bytes: Uint8Array, filename: string, mimeType?: string): Promise<WpMedia> {\n const response = await this.send('/wp/v2/media', {\n method: 'POST',\n body: bytes,\n headers: {\n 'Content-Type': mimeType && mimeType.length > 0 ? mimeType : 'application/octet-stream',\n 'Content-Disposition': buildContentDisposition(filename),\n },\n });\n return normalizeMedia(await response.json());\n }\n\n /**\n * List image attachments (`GET /wp/v2/media?media_type=image`), paginated. Reads the\n * `X-WP-TotalPages` response header so the picker can page through the library. A core\n * REST call — no companion plugin needed.\n */\n async listMedia(params: ListMediaParams = {}): Promise<{ items: WpMedia[]; totalPages: number }> {\n const perPage = clampInt(params.perPage ?? 30, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n media_type: 'image',\n per_page: String(perPage),\n page: String(page),\n });\n const search = params.search?.trim();\n if (search) {\n query.set('search', search);\n }\n const response = await this.send(`/wp/v2/media?${query.toString()}`);\n const raw = (await response.json()) as unknown;\n return {\n items: Array.isArray(raw) ? raw.map(normalizeMedia) : [],\n totalPages: parseTotalPages(response.headers.get('X-WP-TotalPages')),\n };\n }\n\n /**\n * Resolve specific media ids to their URLs in one request (`?include=`), used to fill in\n * the featured-image thumbnails for the posts currently shown — without embedding media\n * into the lean post listing. A core REST call — no companion plugin needed.\n */\n async resolveMedia(ids: number[]): Promise<WpMedia[]> {\n const clean = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];\n if (clean.length === 0) {\n return [];\n }\n // WordPress caps per_page at 100, so resolve in chunks of 100 — otherwise a request for\n // more than 100 ids would be silently truncated, leaving the rest unresolved.\n const out: WpMedia[] = [];\n for (let i = 0; i < clean.length; i += 100) {\n const chunk = clean.slice(i, i + 100);\n const query = new URLSearchParams({\n include: chunk.join(','),\n per_page: String(chunk.length),\n });\n const raw = await this.request<unknown>(`/wp/v2/media?${query.toString()}`);\n if (Array.isArray(raw)) {\n out.push(...raw.map(normalizeMedia));\n }\n }\n return out;\n }\n}\n\n/** Map editable fields to the WordPress REST request body (camelCase → snake_case). */\nexport function buildUpdateBody(fields: UpdatePostFields): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (fields.title !== undefined) {\n body.title = fields.title;\n }\n if (fields.menuOrder !== undefined) {\n body.menu_order = fields.menuOrder;\n }\n if (fields.status !== undefined) {\n body.status = fields.status;\n }\n if (fields.featuredMedia !== undefined) {\n // `0` is meaningful here (removes the featured image), so check for undefined, not falsy.\n body.featured_media = fields.featuredMedia;\n }\n if (fields.content !== undefined) {\n // `''` is meaningful here (clears the body), so check for undefined, not falsy.\n body.content = fields.content;\n }\n return body;\n}\n\nfunction assertRouteSegment(segment: string): void {\n if (!ROUTE_SEGMENT.test(segment)) {\n throw new Error(`Invalid REST route segment: ${segment}`);\n }\n}\n\nfunction assertPostId(id: number): void {\n if (!Number.isSafeInteger(id) || id <= 0) {\n throw new Error(`Invalid post id: ${id}`);\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) {\n return min;\n }\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\n/** Wrap arbitrary meta in the companion plugin's REST field for a write request. */\nexport function buildMetaBody(meta: Record<string, unknown>): Record<string, unknown> {\n return { [META_FIELD]: meta };\n}\n\n/**\n * Build a post-update body, folding in connector meta under `dbp_wp_meta` when given.\n * A provided `meta` is included as-is, even when empty — callers that should skip empty\n * meta (e.g. the CLI batch parser) omit it before calling.\n */\nexport function buildPostBody(\n fields: UpdatePostFields,\n meta?: Record<string, unknown>,\n): Record<string, unknown> {\n const body = buildUpdateBody(fields);\n if (meta !== undefined) {\n Object.assign(body, buildMetaBody(meta));\n }\n return body;\n}\n\n/** Validate and clean a list of meta keys for deletion (non-empty strings only). */\nexport function sanitizeMetaKeys(keys: unknown): string[] {\n if (!Array.isArray(keys)) {\n throw new Error('Meta keys must be an array of strings.');\n }\n const clean = keys.filter((key): key is string => typeof key === 'string' && key.length > 0);\n if (clean.length === 0) {\n throw new Error('At least one non-empty meta key is required.');\n }\n return clean;\n}\n\n/** True when a REST index `namespaces` list includes the connector namespace. */\nexport function hasConnectorNamespace(namespaces: unknown): boolean {\n return Array.isArray(namespaces) && namespaces.includes(CONNECTOR_NAMESPACE);\n}\n\n/**\n * Build a `Content-Disposition` value for a media upload. Emits an ASCII-only\n * `filename=\"…\"` fallback (non-ASCII and header-unsafe characters replaced with `_`) plus an\n * RFC 5987 `filename*=UTF-8''…` parameter, so a non-ASCII filename survives and never\n * produces an invalid (non-ByteString) header value that `fetch` would reject. The path is\n * reduced to its basename and quotes/CR/LF are dropped so the value cannot break the header.\n */\nexport function buildContentDisposition(filename: string): string {\n const base = filename.split(/[/\\\\]/).pop() ?? filename;\n const trimmed = base.replace(/[\\r\\n\"]/g, '').trim() || 'upload';\n const ascii = trimmed.replace(/[^\\x20-\\x7e]/g, '_');\n // Percent-encode per RFC 5987, also encoding the chars encodeURIComponent leaves bare.\n const encoded = encodeURIComponent(trimmed).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=\"${ascii}\"; filename*=UTF-8''${encoded}`;\n}\n\n/** Parse the `X-WP-TotalPages` header into a positive page count, defaulting to 1. */\nfunction parseTotalPages(header: string | null): number {\n if (header === null) {\n return 1;\n }\n const n = Number.parseInt(header, 10);\n return Number.isFinite(n) && n > 0 ? n : 1;\n}\n\n/** Read `<obj>.rendered` as a string, or `''` when absent/malformed. */\nfunction extractRendered(value: unknown): string {\n if (value !== null && typeof value === 'object') {\n const rendered = (value as Record<string, unknown>).rendered;\n if (typeof rendered === 'string') {\n return rendered;\n }\n }\n return '';\n}\n\n/** Prefer a thumbnail-sized URL from `media_details.sizes`, else a medium one, else `''`. */\nfunction extractThumbnailUrl(mediaDetails: unknown): string {\n if (mediaDetails === null || typeof mediaDetails !== 'object') {\n return '';\n }\n const sizes = (mediaDetails as Record<string, unknown>).sizes;\n if (sizes === null || typeof sizes !== 'object') {\n return '';\n }\n for (const sizeName of ['thumbnail', 'medium']) {\n const size = (sizes as Record<string, unknown>)[sizeName];\n if (size !== null && typeof size === 'object') {\n const url = (size as Record<string, unknown>).source_url;\n if (typeof url === 'string') {\n return url;\n }\n }\n }\n return '';\n}\n\n/**\n * Normalize a raw `/wp/v2/media` item into {@link WpMedia}. Accepts `unknown` and guards each\n * field, so a malformed entry degrades to empty strings rather than throwing.\n */\nexport function normalizeMedia(raw: unknown): WpMedia {\n const obj = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>;\n const sourceUrl = typeof obj.source_url === 'string' ? obj.source_url : '';\n return {\n id: typeof obj.id === 'number' ? obj.id : 0,\n sourceUrl,\n thumbnailUrl: extractThumbnailUrl(obj.media_details) || sourceUrl,\n title: extractRendered(obj.title),\n mimeType: typeof obj.mime_type === 'string' ? obj.mime_type : '',\n };\n}\n\n/**\n * Normalize the `/wp/v2/types` response (an object keyed by type name) into a list.\n * Skips entries without a string `rest_base` (not addressable over REST).\n */\nexport function normalizePostTypes(raw: unknown): WpPostType[] {\n if (typeof raw !== 'object' || raw === null) {\n return [];\n }\n const result: WpPostType[] = [];\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof value !== 'object' || value === null) {\n continue;\n }\n const entry = value as Record<string, unknown>;\n // Validate rest_base at ingestion so a malformed slug can't become a broken option.\n if (typeof entry.rest_base !== 'string' || !ROUTE_SEGMENT.test(entry.rest_base)) {\n continue;\n }\n result.push({\n slug: typeof entry.slug === 'string' ? entry.slug : key,\n restBase: entry.rest_base,\n name: typeof entry.name === 'string' ? entry.name : key,\n });\n }\n return result;\n}\n\nexport function normalizePost(raw: WpPostResponse): WpPost {\n const post: WpPost = {\n id: raw.id,\n type: raw.type,\n status: raw.status,\n title: raw.title.raw ?? raw.title.rendered,\n menuOrder: raw.menu_order,\n meta: raw.meta,\n };\n if (raw.dbp_wp_meta !== undefined) {\n post.dbpWpMeta = raw.dbp_wp_meta;\n }\n // featured_media is always present on a core post; 0 means \"no featured image\".\n if (typeof raw.featured_media === 'number' && raw.featured_media > 0) {\n post.featuredMedia = raw.featured_media;\n }\n // Parent relation rides the standard `meta` field (registered by the connector). It needs\n // both a positive id and a non-empty type; a half-written pair — e.g. from a raw REST\n // write that set only one key, or a parent type sanitized to '' — reads as no relation.\n // parent and parentType are therefore set together or not at all, so normalizePost,\n // getRelation, and deriveChildren stay consistent on malformed data.\n const rawParent = raw.meta?.[PARENT_META_KEY];\n const rawParentType = raw.meta?.[PARENT_TYPE_META_KEY];\n if (\n typeof rawParent === 'number' &&\n Number.isInteger(rawParent) &&\n rawParent > 0 &&\n typeof rawParentType === 'string' &&\n rawParentType !== ''\n ) {\n post.parent = rawParent;\n post.parentType = rawParentType;\n }\n return post;\n}\n\n/**\n * Normalize a raw post (edit context) into the body-editing model {@link WpPostEdit}.\n *\n * Reads `content.raw` for the body. Mode is determined by the Markdown source: only a\n * *non-empty* `_dbp_wp_markdown` value marks Markdown mode. This mirrors the relation keys'\n * value-based sentinel (a positive id means \"set\") and sidesteps the REST default for a\n * registered string meta (an unset key can come back as `''`), so an HTML-mode post is never\n * mistaken for an empty-bodied Markdown post.\n */\nexport function normalizePostForEdit(raw: WpPostResponse): WpPostEdit {\n const edit: WpPostEdit = {\n id: raw.id,\n type: raw.type,\n status: raw.status,\n title: raw.title.raw ?? raw.title.rendered,\n content: raw.content?.raw ?? '',\n };\n const markdown = raw.meta?.[MARKDOWN_META_KEY];\n if (typeof markdown === 'string' && markdown !== '') {\n edit.markdown = markdown;\n }\n return edit;\n}\n","import { marked } from 'marked';\n\n/**\n * Convert Markdown source to HTML for the single-post body editor.\n *\n * One shared implementation, used by the UI (live preview and the HTML mirrored into\n * `post_content` on save) and available to the CLI/future MCP layer, so a post's stored\n * HTML always matches what the editor previewed. GitHub-flavored Markdown is enabled.\n *\n * This does NOT sanitize the output. Sanitization is delegated to WordPress `kses` at save\n * time (capability-dependent), and the live preview is isolated in a sandboxed iframe with\n * no script execution — matching the body-editing design (no extra sanitizer dependency in\n * DBP WP).\n */\nexport function renderMarkdown(markdown: string): string {\n // `async: false` selects marked's synchronous overload (string return). Guard the result\n // so an unexpected non-string (e.g. a future async extension) degrades to empty rather\n // than leaking a Promise into the rendered body.\n const html = marked.parse(markdown, { async: false, gfm: true });\n return typeof html === 'string' ? html : '';\n}\n","import { Parser, type Expression } from 'expr-eval-fork';\n\n/**\n * Formula engine: evaluates a spreadsheet expression against named numeric cells.\n *\n * Implementations MUST NOT use `eval`, `Function`, or any other dynamic code execution.\n */\nexport interface FormulaEngine {\n /**\n * Evaluate a single expression against a map of cell references to numbers.\n * Throws on invalid syntax, unknown variables, or a non-numeric result.\n */\n evaluate(expression: string, context: Record<string, number>): number;\n}\n\n/**\n * Formula engine backed by expr-eval-fork, which parses to an AST and evaluates without\n * `eval`/`Function`. Member access, assignment, and function definitions are disabled,\n * the nondeterministic `random()` function is removed, and results are constrained to\n * finite numbers, so expressions stay pure, deterministic, and side-effect free.\n */\nexport class SafeFormulaEngine implements FormulaEngine {\n private readonly parser: Parser;\n\n constructor() {\n this.parser = new Parser({\n allowMemberAccess: false,\n operators: { assignment: false, fndef: false },\n });\n // The `operators.random` flag does not remove the random() function; delete it so\n // evaluation stays deterministic.\n delete this.parser.functions.random;\n }\n\n evaluate(expression: string, context: Record<string, number>): number {\n let parsed: Expression;\n try {\n parsed = this.parser.parse(expression);\n } catch (e) {\n throw new Error(`Invalid formula: ${e instanceof Error ? e.message : 'parse error'}`);\n }\n\n let result: unknown;\n try {\n result = parsed.evaluate(context);\n } catch (e) {\n throw new Error(`Formula evaluation failed: ${e instanceof Error ? e.message : 'error'}`);\n }\n\n if (typeof result !== 'number' || !Number.isFinite(result)) {\n throw new Error('Formula must evaluate to a finite number.');\n }\n return result;\n }\n}\n","import type { UpdatePostFields } from './types';\n\n// WordPress stores menu_order in a signed 32-bit column; ignore cells outside that range\n// so one bad value does not get the whole server-side chunk rejected.\nconst MENU_ORDER_MIN = -2_147_483_648;\nconst MENU_ORDER_MAX = 2_147_483_647;\n\n/**\n * A tabular view of an import file: a header row plus data rows. Both CSV and JSON\n * sources are normalized to this shape so the column-mapping logic is source-agnostic.\n * Each data row is aligned to `headers` by index; a short row has missing trailing cells.\n */\nexport interface ParsedTable {\n /** Column headers (CSV first row, or the union of JSON object keys). */\n headers: string[];\n /** Data rows; `rows[r][c]` is the cell under `headers[c]`. */\n rows: string[][];\n}\n\n/**\n * Where a file column is imported to. `skip` drops the column; `title`/`status`/\n * `menuOrder` map to standard post fields; `meta` writes an arbitrary post-meta key\n * (companion plugin required).\n */\nexport type ImportTarget =\n | { kind: 'skip' }\n | { kind: 'title' }\n | { kind: 'status' }\n | { kind: 'menuOrder' }\n | { kind: 'meta'; key: string };\n\n/** A single new post to create, derived from one import row. */\nexport interface ImportCreate {\n /** Standard fields (title / menuOrder / status). */\n fields: UpdatePostFields;\n /** Arbitrary meta to write via the companion plugin (omitted when none). */\n meta?: Record<string, unknown>;\n}\n\n/**\n * Parse CSV text into a table, taking the first record as headers. Implements the\n * RFC 4180 essentials: double-quoted fields, embedded commas/newlines, `\"\"` escapes,\n * and CRLF or LF line endings. A trailing newline does not produce an empty record.\n */\nexport function parseCsv(text: string): ParsedTable {\n const records = parseCsvRecords(text);\n const headers = records[0] ?? [];\n return { headers, rows: records.slice(1) };\n}\n\nfunction parseCsvRecords(text: string): string[][] {\n const records: string[][] = [];\n let record: string[] = [];\n let field = '';\n let inQuotes = false;\n let i = 0;\n\n const endField = (): void => {\n record.push(field);\n field = '';\n };\n const endRecord = (): void => {\n endField();\n records.push(record);\n record = [];\n };\n\n while (i < text.length) {\n const ch = text[i];\n if (inQuotes) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i += 2;\n continue;\n }\n inQuotes = false;\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n continue;\n }\n if (ch === '\"') {\n inQuotes = true;\n i += 1;\n continue;\n }\n if (ch === ',') {\n endField();\n i += 1;\n continue;\n }\n if (ch === '\\r') {\n endRecord();\n i += text[i + 1] === '\\n' ? 2 : 1;\n continue;\n }\n if (ch === '\\n') {\n endRecord();\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n }\n // An unclosed quote means the file is malformed; surface it rather than silently\n // merging the rest of the file into one field and writing corrupted data.\n if (inQuotes) {\n throw new Error('Malformed CSV: unterminated quoted field.');\n }\n // Flush a final record only if there is pending content (no trailing-newline ghost row).\n if (field !== '' || record.length > 0) {\n endRecord();\n }\n return records;\n}\n\n/**\n * Parse JSON text (an array of objects) into a table. Headers are the union of all\n * object keys in first-seen order. Object/array cell values are JSON-stringified;\n * null and undefined become an empty string. Throws if the JSON is not an array.\n */\nexport function parseJsonRecords(text: string): ParsedTable {\n const data: unknown = JSON.parse(text);\n if (!Array.isArray(data)) {\n throw new Error('JSON import must be an array of objects.');\n }\n const headers: string[] = [];\n const seen = new Set<string>();\n for (const entry of data) {\n if (isPlainRecord(entry)) {\n for (const key of Object.keys(entry)) {\n if (!seen.has(key)) {\n seen.add(key);\n headers.push(key);\n }\n }\n }\n }\n const rows = data.map((entry) => {\n const record = isPlainRecord(entry) ? entry : {};\n return headers.map((header) => stringifyCell(record[header]));\n });\n return { headers, rows };\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction stringifyCell(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return String(value);\n}\n\n/**\n * Known post-status values and English/value labels, mapped to the WordPress status.\n * A null-prototype map so inherited keys (`constructor`, `toString`, `__proto__`, …) do\n * not accidentally resolve to a function/object instead of falling back to the raw value.\n */\nconst STATUS_LABELS: Record<string, string> = Object.assign(\n Object.create(null) as Record<string, string>,\n {\n publish: 'publish',\n published: 'publish',\n draft: 'draft',\n pending: 'pending',\n private: 'private',\n future: 'future',\n },\n);\n\n/**\n * Normalize a status cell to a WordPress status. Known labels/values (case-insensitive,\n * e.g. `Published` → `publish`) are mapped; anything else passes through trimmed so the\n * WordPress REST API can validate it and surface a per-row error if invalid.\n */\nexport function normalizeStatus(value: string): string {\n const trimmed = value.trim();\n return STATUS_LABELS[trimmed.toLowerCase()] ?? trimmed;\n}\n\n/**\n * Apply a column mapping to a parsed table, producing one {@link ImportCreate} per row.\n * Empty cells contribute nothing; a row that maps to no fields and no meta is skipped.\n * Non-integer `menuOrder` cells are ignored. Meta is stored on a null-prototype object\n * so a header named `__proto__` is kept as data, never touching any prototype.\n */\nexport function buildImportPlan(table: ParsedTable, mapping: ImportTarget[]): ImportCreate[] {\n const creates: ImportCreate[] = [];\n for (const row of table.rows) {\n const fields: UpdatePostFields = {};\n let meta: Record<string, unknown> | undefined;\n\n for (let col = 0; col < mapping.length; col += 1) {\n const target = mapping[col];\n if (!target || target.kind === 'skip') {\n continue;\n }\n const value = row[col] ?? '';\n if (value === '') {\n continue;\n }\n switch (target.kind) {\n case 'title':\n fields.title = value;\n break;\n case 'status':\n fields.status = normalizeStatus(value);\n break;\n case 'menuOrder': {\n const order = Number(value);\n if (Number.isInteger(order) && order >= MENU_ORDER_MIN && order <= MENU_ORDER_MAX) {\n fields.menuOrder = order;\n }\n break;\n }\n case 'meta':\n // An empty/whitespace meta key would be rejected by the server (empty key),\n // failing the whole chunk; skip it rather than emit `meta[\"\"]`.\n if (target.key.trim() === '') {\n break;\n }\n if (!meta) {\n meta = Object.create(null) as Record<string, unknown>;\n }\n meta[target.key] = value;\n break;\n }\n }\n\n if (meta !== undefined && Object.keys(meta).length > 0) {\n creates.push({ fields, meta });\n } else if (Object.keys(fields).length > 0) {\n creates.push({ fields });\n }\n }\n return creates;\n}\n"],"mappings":";AA2CO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,IAAM,MACJ;AAGF,SAAS,cAAc,UAAkC;AACvD,QAAM,OAAuB,CAAC;AAG9B,MAAI,UAA0B;AAC9B,QAAM,UAA4B,CAAC;AACnC,QAAM,OAAmB,CAAC;AAC1B,QAAM,WAAW,CAAC,SAAuB;AACvC,QAAI,KAAM,SAAQ,KAAK,EAAE,MAAM,QAAQ,OAAO,KAAK,CAAC;AAAA,EACtD;AAEA,MAAI,OAAO;AACX,MAAI,YAAY;AAChB,MAAI;AACJ,UAAQ,IAAI,IAAI,KAAK,QAAQ,OAAO,MAAM;AACxC,aAAS,SAAS,MAAM,MAAM,EAAE,KAAK,CAAC;AACtC,WAAO,IAAI;AACX,QAAI,EAAE,CAAC,MAAM,QAAW;AAEtB,cAAQ,KAAK,EAAE,MAAM,OAAO,MAAM,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK,KAAK,CAAC;AAAA,IAC5D,WAAW,EAAE,CAAC,MAAM,QAAW;AAE7B,YAAM,OAAiB,EAAE,MAAM,QAAQ,MAAM,EAAE,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,EAAE;AACnE,cAAQ,KAAK,IAAI;AACjB,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I,UAAU,IAAI;AAChB;AAAA,MACF;AACA,cAAQ,OAAO,MAAM;AAAA,QACnB,KAAK;AACH,iBAAO,QAAQ;AACf;AAAA,QACF,KAAK;AACH,iBAAO,SAAS,gBAAgB,KAAK;AACrC;AAAA,QACF,KAAK,aAAa;AAChB,gBAAM,QAAQ,OAAO,KAAK;AAC1B,cAAI,OAAO,UAAU,KAAK,KAAK,SAAS,kBAAkB,SAAS,gBAAgB;AACjF,mBAAO,YAAY;AAAA,UACrB;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAGH,cAAI,OAAO,IAAI,KAAK,MAAM,IAAI;AAC5B;AAAA,UACF;AACA,cAAI,CAAC,MAAM;AACT,mBAAO,uBAAO,OAAO,IAAI;AAAA,UAC3B;AACA,eAAK,OAAO,GAAG,IAAI;AACnB;AAAA,MACJ;AAAA,IACF;AAEA,QAAI,SAAS,UAAa,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AACtD,cAAQ,KAAK,EAAE,QAAQ,KAAK,CAAC;AAAA,IAC/B,WAAW,OAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AACzC,cAAQ,KAAK,EAAE,OAAO,CAAC;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;","names":["flattenMetaValue","ROUTE_SEGMENT"]}
1
+ {"version":3,"sources":["../src/print.ts","../src/relation.ts","../src/wp-client.ts","../src/markdown.ts","../src/calc/index.ts","../src/importer.ts"],"sourcesContent":["/**\n * Print Design template engine.\n *\n * Renders a user-authored HTML template against a {@link PrintRecord} using a small,\n * mustache-like `{{ }}` syntax. Pure and framework-agnostic: the browser UI renders the\n * result inside a sandboxed iframe and prints it (see planning doc 04-print-design).\n *\n * Syntax:\n * - `{{ path }}` resolve a dotted path, HTML-escape the value, and output it.\n * - `{{{ path }}}` same, but output the value raw (no escaping) for HTML fields such as\n * `content` / `excerpt`, which already hold WordPress-rendered HTML.\n * - `{{#each path}} ... {{/each}}` iterate an array; inside the block, `this` is the\n * current item (and `this.<key>` reaches into an object item).\n *\n * Unknown paths render as the empty string. Paths resolve against the record, except\n * `this` / `this.<key>`, which resolve against the current `{{#each}}` item.\n */\n\nimport type { WpPostResponse } from './types';\n\n/** The data a template is rendered against (one WordPress post, flattened for templating). */\nexport interface PrintRecord {\n id: number;\n title: string;\n /** WordPress-rendered HTML. Use `{{{ content }}}` so it is not escaped. */\n content: string;\n /** WordPress-rendered HTML. Use `{{{ excerpt }}}` so it is not escaped. */\n excerpt: string;\n status: string;\n menuOrder: number;\n /** Absolute URL of the featured image, or `''` when the post has none. */\n featuredImageUrl: string;\n /**\n * Flattened post meta, keyed by meta key (values stringified; arrays joined with `, `).\n * Reachable in templates as `{{ meta.<key> }}`. A meta key containing a literal dot\n * cannot be addressed, since template paths split on `.`.\n */\n meta: Record<string, string>;\n /** Taxonomy terms keyed by REST base (e.g. `tax.category`), each an array of term names. */\n tax: Record<string, string[]>;\n}\n\n/** Thrown when a template has an unbalanced `{{#each}}` / `{{/each}}`. */\nexport class TemplateParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TemplateParseError';\n }\n}\n\ntype TemplateNode = TextNode | VarNode | EachNode;\ninterface TextNode {\n kind: 'text';\n value: string;\n}\ninterface VarNode {\n kind: 'var';\n path: string;\n /** `true` for triple-brace `{{{ }}}` (unescaped) output. */\n raw: boolean;\n}\ninterface EachNode {\n kind: 'each';\n path: string;\n body: TemplateNode[];\n}\n\ninterface Scope {\n /** The record paths resolve against by default. */\n record: object;\n /** The current `{{#each}}` item, reachable as `this` / `this.<key>`. */\n current?: unknown;\n}\n\n// Order matters: triple-brace and the each tags must be tried before the generic `{{ }}`.\n// `[\\s\\S]` (not `.`) so a tag may span newlines.\nconst TAG =\n /(\\{\\{\\{\\s*([\\s\\S]+?)\\s*\\}\\}\\})|(\\{\\{\\s*#each\\s+([\\s\\S]+?)\\s*\\}\\})|(\\{\\{\\s*\\/each\\s*\\}\\})|(\\{\\{\\s*([\\s\\S]+?)\\s*\\}\\})/g;\n\n/** Parse a template string into a node tree, validating `{{#each}}` nesting. */\nfunction parseTemplate(template: string): TemplateNode[] {\n const root: TemplateNode[] = [];\n // `current` is the node list we append to; `parents` lets us pop back out of an each\n // block; `open` tracks open each blocks so we can detect unbalanced tags.\n let current: TemplateNode[] = root;\n const parents: TemplateNode[][] = [];\n const open: EachNode[] = [];\n const pushText = (text: string): void => {\n if (text) current.push({ kind: 'text', value: text });\n };\n\n let last = 0;\n TAG.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = TAG.exec(template)) !== null) {\n pushText(template.slice(last, m.index));\n last = TAG.lastIndex;\n if (m[2] !== undefined) {\n // {{{ raw }}}\n current.push({ kind: 'var', path: m[2].trim(), raw: true });\n } else if (m[4] !== undefined) {\n // {{#each path}}\n const node: EachNode = { kind: 'each', path: m[4].trim(), body: [] };\n current.push(node);\n parents.push(current);\n current = node.body;\n open.push(node);\n } else if (m[5] !== undefined) {\n // {{/each}}\n if (open.length === 0) {\n throw new TemplateParseError('Unexpected {{/each}} without a matching {{#each}}.');\n }\n open.pop();\n current = parents.pop() ?? root;\n } else if (m[7] !== undefined) {\n // {{ var }}\n current.push({ kind: 'var', path: m[7].trim(), raw: false });\n }\n }\n pushText(template.slice(last));\n\n if (open.length > 0) {\n const unclosed = open[open.length - 1];\n throw new TemplateParseError(`Unclosed {{#each ${unclosed ? unclosed.path : ''}}}.`);\n }\n return root;\n}\n\n/** Walk a dotted path (e.g. `meta.price`) into a value, returning `undefined` if any hop misses. */\nfunction getPath(obj: unknown, path: string): unknown {\n let cur: unknown = obj;\n for (const key of path.split('.')) {\n if (cur === null || cur === undefined || typeof cur !== 'object') {\n return undefined;\n }\n cur = (cur as Record<string, unknown>)[key];\n }\n return cur;\n}\n\n/** Resolve a template path against the scope. `this` / `this.<key>` target the each item. */\nfunction resolve(path: string, scope: Scope): unknown {\n if (path === 'this') {\n return scope.current;\n }\n if (path.startsWith('this.')) {\n return getPath(scope.current, path.slice('this.'.length));\n }\n return getPath(scope.record, path);\n}\n\n/** Stringify a scalar for output; non-scalars (objects/arrays) and nullish render as ''. */\nfunction stringifyScalar(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // Objects/arrays have no sensible inline string form; render nothing.\n return '';\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\nfunction renderNodes(nodes: TemplateNode[], scope: Scope, escape: boolean): string {\n let out = '';\n for (const node of nodes) {\n if (node.kind === 'text') {\n out += node.value;\n } else if (node.kind === 'var') {\n const value = stringifyScalar(resolve(node.path, scope));\n // `{{{ }}}` is always raw; `{{ }}` is HTML-escaped only in escaping (HTML) mode.\n out += node.raw || !escape ? value : escapeHtml(value);\n } else {\n // each: iterate only when the path resolves to an array; otherwise render nothing.\n const list = resolve(node.path, scope);\n if (Array.isArray(list)) {\n for (const item of list) {\n out += renderNodes(node.body, { record: scope.record, current: item }, escape);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Render a Print Design template against one record. Values are HTML-escaped for `{{ }}`\n * and emitted raw for `{{{ }}}`. Throws {@link TemplateParseError} on unbalanced\n * `{{#each}}` / `{{/each}}`.\n */\nexport function renderTemplate(template: string, record: PrintRecord): string {\n return renderNodes(parseTemplate(template), { record }, true);\n}\n\n/**\n * Render a template against an arbitrary record object, reusing the same `{{ }}` /\n * `{{#each}}` engine as {@link renderTemplate}. By default `{{ }}` values are HTML-escaped\n * (HTML output). Pass `escape: false` for a plain-text context (e.g. a spreadsheet cell\n * rendered as text, where the host already escapes for the DOM and re-escaping here would\n * surface literal entities). Throws {@link TemplateParseError} on unbalanced `{{#each}}`.\n */\nexport function renderRecordTemplate(\n template: string,\n record: object,\n options: { escape?: boolean } = {},\n): string {\n return renderNodes(parseTemplate(template), { record }, options.escape ?? true);\n}\n\n/** Flatten one meta value to a string. Arrays join their non-empty scalar parts. */\nfunction flattenMetaValue(value: unknown): string {\n if (Array.isArray(value)) {\n return value\n .map(stringifyScalar)\n .filter((s) => s !== '')\n .join(', ');\n }\n return stringifyScalar(value);\n}\n\n/** Merge core meta and connector meta (connector wins) into flat string values. */\nfunction flattenMeta(raw: WpPostResponse): Record<string, string> {\n // Null-proto so untrusted meta keys (e.g. `__proto__`, `constructor`) become plain own\n // entries with no prototype pollution and no inherited-key collisions.\n const out: Record<string, string> = Object.create(null) as Record<string, string>;\n const add = (src: Record<string, unknown> | undefined): void => {\n if (!src) return;\n for (const [key, value] of Object.entries(src)) {\n out[key] = flattenMetaValue(value);\n }\n };\n add(raw.meta);\n add(raw.dbp_wp_meta); // connector meta overlays core meta for the same key\n return out;\n}\n\n/** Extract the featured image URL from an `_embed`ded response, or '' when absent. */\nfunction extractFeaturedImageUrl(embedded: WpPostResponse['_embedded']): string {\n const media = embedded?.['wp:featuredmedia'];\n if (Array.isArray(media) && media.length > 0) {\n const first = media[0];\n if (first !== null && typeof first === 'object') {\n const sourceUrl = (first as Record<string, unknown>).source_url;\n if (typeof sourceUrl === 'string') {\n return sourceUrl;\n }\n }\n }\n return '';\n}\n\n/** Group `_embed`ded terms into `{ <taxonomy slug>: [term name, ...] }`. */\nfunction extractTerms(embedded: WpPostResponse['_embedded']): Record<string, string[]> {\n // Null-proto so a taxonomy slug like `toString`/`__proto__` cannot resolve an inherited\n // value (which would make `(tax[slug] ??= [])` skip the array and throw on `.push`).\n const tax: Record<string, string[]> = Object.create(null) as Record<string, string[]>;\n const groups = embedded?.['wp:term'];\n if (!Array.isArray(groups)) {\n return tax;\n }\n for (const group of groups) {\n if (!Array.isArray(group)) continue;\n for (const term of group) {\n if (term === null || typeof term !== 'object') continue;\n const entry = term as Record<string, unknown>;\n if (typeof entry.taxonomy === 'string' && typeof entry.name === 'string') {\n (tax[entry.taxonomy] ??= []).push(entry.name);\n }\n }\n }\n return tax;\n}\n\n/**\n * Build a {@link PrintRecord} from a raw WordPress REST post. Expects the request to have\n * used `context=edit` and `_embed` so `content`/`excerpt` and embedded media/terms are\n * present; missing pieces degrade to empty values rather than throwing.\n *\n * `title` uses the raw (unescaped) value so `{{ title }}` escaping is not doubled.\n * `content`/`excerpt` use the rendered HTML (intended for `{{{ }}}`).\n */\nexport function buildPrintRecord(raw: WpPostResponse): PrintRecord {\n return {\n id: raw.id,\n title: raw.title?.raw ?? raw.title?.rendered ?? '',\n content: raw.content?.rendered ?? '',\n excerpt: raw.excerpt?.rendered ?? '',\n status: raw.status,\n menuOrder: raw.menu_order,\n featuredImageUrl: extractFeaturedImageUrl(raw._embedded),\n meta: flattenMeta(raw),\n tax: extractTerms(raw._embedded),\n };\n}\n","import { renderRecordTemplate } from './print';\nimport type { WpPost } from './types';\n\n/**\n * Parent/child relations (MVP: links only).\n *\n * The relation is stored single-source on the **child**: `_dbp_wp_parent` holds the\n * parent post ID and `_dbp_wp_parent_type` holds the parent post type's REST route base.\n * The parent keeps no child list — a parent's children are derived from already-loaded\n * posts ({@link deriveChildren}), so there is no denormalized list to keep in sync.\n *\n * These keys are `_`-prefixed (protected) and are exposed over REST only because the\n * companion plugin registers them with `register_post_meta()` + an `edit_post`\n * `auth_callback`. They therefore travel through the standard core `meta` field — not the\n * connector's `dbp_wp_meta` field — so relation writes use a dedicated path.\n */\n\n/** Meta key holding a child's parent post ID. */\nexport const PARENT_META_KEY = '_dbp_wp_parent';\n\n/** Meta key holding the parent post type's REST route base. */\nexport const PARENT_TYPE_META_KEY = '_dbp_wp_parent_type';\n\n/** Allowed characters for a REST route segment (post type slug); mirrors the WpClient check. */\nconst ROUTE_SEGMENT = /^[a-z0-9_-]+$/i;\n\n/** A parent assignment for a child post. */\nexport interface RelationTarget {\n /** Parent post ID (positive integer). */\n parentId: number;\n /** Parent post type's REST route base (e.g. `pages`). */\n parentType: string;\n}\n\n/** Error thrown when a relation assignment is invalid (bad id/type, or self-parent). */\nexport class RelationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'RelationError';\n }\n}\n\n/**\n * Validate a parent assignment for a child. Throws {@link RelationError} when the parent\n * id is not a positive safe integer, the parent type is not a valid route segment, or the\n * parent is the child itself (post IDs are unique across types, so this catches a\n * self-parent regardless of type).\n */\nexport function assertValidRelation(childId: number, relation: RelationTarget): void {\n if (!Number.isSafeInteger(relation.parentId) || relation.parentId <= 0) {\n throw new RelationError(`Invalid parent id: ${String(relation.parentId)}`);\n }\n if (typeof relation.parentType !== 'string' || !ROUTE_SEGMENT.test(relation.parentType)) {\n throw new RelationError(`Invalid parent type: ${String(relation.parentType)}`);\n }\n if (relation.parentId === childId) {\n throw new RelationError('A post cannot be its own parent.');\n }\n}\n\n/**\n * Build the standard-`meta` body that sets a child's parent. Validates the assignment\n * first ({@link assertValidRelation}). The keys ride the core `meta` field, so the caller\n * sends `{ meta: <this> }`.\n */\nexport function buildSetRelationMeta(\n childId: number,\n relation: RelationTarget,\n): Record<string, unknown> {\n assertValidRelation(childId, relation);\n return {\n [PARENT_META_KEY]: relation.parentId,\n [PARENT_TYPE_META_KEY]: relation.parentType,\n };\n}\n\n/**\n * Build the standard-`meta` body that clears a child's parent. Sending `null` for a\n * registered single meta key makes WordPress delete it, so no stale value is left behind.\n */\nexport function buildClearRelationMeta(): Record<string, unknown> {\n return {\n [PARENT_META_KEY]: null,\n [PARENT_TYPE_META_KEY]: null,\n };\n}\n\n/**\n * Read a post's parent relation from its normalized fields, or null when it has no parent.\n * Both a positive `parent` id and a non-empty `parentType` are required for a relation to\n * count (a half-written relation reads as none).\n */\nexport function getRelation(post: WpPost): RelationTarget | null {\n if (\n typeof post.parent === 'number' &&\n post.parent > 0 &&\n typeof post.parentType === 'string' &&\n post.parentType !== ''\n ) {\n return { parentId: post.parent, parentType: post.parentType };\n }\n return null;\n}\n\n/**\n * Derive a parent's children from already-loaded posts: every post whose `_dbp_wp_parent`\n * equals `parentId`. This covers the common case of same-type children visible in the\n * current grid; cross-type or off-grid children would need a server-side query (deferred).\n */\nexport function deriveChildren(posts: WpPost[], parentId: number): WpPost[] {\n if (!Number.isSafeInteger(parentId) || parentId <= 0) {\n return [];\n }\n return posts.filter((post) => post.parent === parentId);\n}\n\n// --- Child data (template aggregation of a parent's children) ---\n//\n// The legacy app stored a per-parent template (`_dbpcloudwp_child_formula`) and cached its\n// rendered output (`_dbpcloudwp_child_value`) as parent meta — a denormalized value that\n// went stale whenever a child changed. The new model persists nothing: a column-level\n// template is rendered live against each parent's derived children, reusing the Print\n// template engine ({@link renderRecordTemplate}). So `{{ }}`/`{{#each}}` work as in Print.\n\n/** A child post flattened for templating inside a parent's child-data column. */\nexport interface ChildRecord {\n id: number;\n title: string;\n status: string;\n menuOrder: number;\n /** Flattened meta (core overlaid by connector), values stringified; `this.meta.<key>`. */\n meta: Record<string, string>;\n}\n\n/**\n * A parent exposed to a child-data template: its own fields plus the derived `children`\n * (and `childCount`), so a template can aggregate them, e.g.\n * `{{#each children}}{{ this.title }}{{/each}}`.\n */\nexport interface ParentAggregateRecord {\n id: number;\n title: string;\n status: string;\n menuOrder: number;\n meta: Record<string, string>;\n childCount: number;\n children: ChildRecord[];\n}\n\n/** Stringify one meta value; an array joins its non-empty scalar parts with `, `. */\nfunction flattenMetaValue(value: unknown): string {\n if (Array.isArray(value)) {\n return value\n .map((v) => (v === null || v === undefined ? '' : String(v)))\n .filter((s) => s !== '')\n .join(', ');\n }\n return value === null || value === undefined ? '' : String(value);\n}\n\n/**\n * Flatten a post's meta (core `meta` overlaid by connector `dbpWpMeta`) to flat string\n * values. Uses a null-proto accumulator so untrusted meta keys (`__proto__`, `constructor`)\n * become plain own entries with no prototype pollution and no inherited-key collisions.\n */\nfunction flattenPostMeta(post: WpPost): Record<string, string> {\n const out: Record<string, string> = Object.create(null) as Record<string, string>;\n const add = (src: Record<string, unknown> | undefined): void => {\n if (!src) return;\n for (const [key, value] of Object.entries(src)) {\n out[key] = flattenMetaValue(value);\n }\n };\n add(post.meta);\n add(post.dbpWpMeta); // connector meta overlays core meta for the same key\n return out;\n}\n\n/** Build a {@link ChildRecord} from a loaded post (meta flattened for templating). */\nexport function buildChildRecord(post: WpPost): ChildRecord {\n return {\n id: post.id,\n title: post.title,\n status: post.status,\n menuOrder: post.menuOrder,\n meta: flattenPostMeta(post),\n };\n}\n\n/** Build the {@link ParentAggregateRecord} a child-data template renders against. */\nexport function buildParentAggregate(parent: WpPost, children: WpPost[]): ParentAggregateRecord {\n return {\n id: parent.id,\n title: parent.title,\n status: parent.status,\n menuOrder: parent.menuOrder,\n meta: flattenPostMeta(parent),\n childCount: children.length,\n children: children.map(buildChildRecord),\n };\n}\n\n/**\n * Render a \"child data\" template for one parent: derive its children from the already-loaded\n * posts ({@link deriveChildren}), build the aggregate record, and render the template with\n * the shared Print engine. Same-type, in-grid children only (cross-type/off-grid children\n * need a server query — deferred). Rendered in plain-text (non-escaping) mode, since the\n * result is shown as a spreadsheet cell's text. Throws {@link TemplateParseError} on an\n * unbalanced `{{#each}}`.\n */\nexport function renderChildData(template: string, parent: WpPost, posts: WpPost[]): string {\n const children = deriveChildren(posts, parent.id);\n return renderRecordTemplate(template, buildParentAggregate(parent, children), { escape: false });\n}\n","import { buildPrintRecord, type PrintRecord } from './print';\nimport {\n PARENT_META_KEY,\n PARENT_TYPE_META_KEY,\n buildClearRelationMeta,\n buildSetRelationMeta,\n type RelationTarget,\n} from './relation';\nimport type {\n DeleteMetaResult,\n ListMediaParams,\n ListPostsParams,\n UpdatePostFields,\n WpCredentials,\n WpMedia,\n WpPost,\n WpPostEdit,\n WpPostResponse,\n WpPostType,\n} from './types';\n\n/** Hosts for which plain http is tolerated (local development). */\nconst LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);\n\n/** Allowed characters for a REST route segment (post type slug). No dots: a `.`/`..`\n * segment would be resolved by the URL parser and traverse the REST path. */\nconst ROUTE_SEGMENT = /^[a-z0-9_-]+$/i;\n\n/** REST field added by the companion plugin to carry arbitrary post meta. */\nconst META_FIELD = 'dbp_wp_meta';\n\n/**\n * Meta key holding the lossless Markdown source for a post edited in Markdown mode. An\n * underscore-prefixed (protected) key, so the companion plugin must register it with\n * `register_post_meta` + an `edit_post` auth callback to expose it over REST — the generic\n * `dbp_wp_meta` field excludes protected keys. Like the relation keys, it therefore rides\n * the standard core `meta` field, not `dbp_wp_meta`.\n */\nexport const MARKDOWN_META_KEY = '_dbp_wp_markdown';\n\n/** REST namespace registered by the companion plugin. */\nconst CONNECTOR_NAMESPACE = 'dbp-wp/v1';\n\n/**\n * Validate and normalize a WordPress site URL into a REST base (origin + base path).\n *\n * Requires https, except plain http is allowed for local development hosts. Rejects\n * embedded credentials, query strings, and fragments, and strips trailing slashes — so\n * an Application Password is never sent over cleartext to an unexpected target.\n */\nexport function normalizeSiteUrl(siteUrl: string): string {\n let url: URL;\n try {\n url = new URL(siteUrl);\n } catch {\n throw new Error(`Invalid site URL: ${siteUrl}`);\n }\n\n const isLocal = LOCAL_HOSTS.has(url.hostname);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLocal)) {\n throw new Error(`Site URL must use https (http is allowed only for local hosts): ${siteUrl}`);\n }\n // SSRF defense: the client sends the Application Password to whatever the site URL points to,\n // so block private, loopback, and link-local IP-literal targets (e.g. 10.x, 192.168.x,\n // 169.254.169.254 cloud metadata, IPv6 ULA/link-local). The explicit local-dev hosts stay\n // allowed. This covers IP literals only — a hostname that resolves to a private address (DNS\n // rebinding) is not caught here, as fetch does not expose the resolved address.\n if (!isLocal && isPrivateAddress(url.hostname)) {\n throw new Error(`Site URL must not point to a private or local network address: ${siteUrl}`);\n }\n if (url.username !== '' || url.password !== '') {\n throw new Error('Site URL must not contain embedded credentials.');\n }\n if (url.search !== '' || url.hash !== '') {\n throw new Error('Site URL must not contain a query string or fragment.');\n }\n\n return `${url.origin}${url.pathname}`.replace(/\\/+$/, '');\n}\n\n/**\n * True when a URL hostname is an IP literal in a private, loopback, link-local, or unspecified\n * range — the SSRF block list used by {@link normalizeSiteUrl}. Returns false for DNS hostnames\n * (not resolved here) and for public IPs. Exported for unit testing.\n */\nexport function isPrivateAddress(hostname: string): boolean {\n // IPv4 literal.\n const v4 = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(hostname);\n if (v4) {\n const octets = [Number(v4[1]), Number(v4[2]), Number(v4[3]), Number(v4[4])];\n if (octets.some((o) => o > 255)) {\n return false; // not a valid IPv4 literal\n }\n return isPrivateV4(octets);\n }\n // IPv6 literal. A URL's hostname keeps the brackets (e.g. `[fe80::1]`), so strip them.\n if (hostname.includes(':')) {\n return isPrivateV6(hostname.toLowerCase().replace(/^\\[/, '').replace(/\\]$/, ''));\n }\n return false; // DNS hostname or non-literal: not blocked here\n}\n\n/** True for private, loopback, link-local, or unspecified IPv4 octets. */\nfunction isPrivateV4(octets: readonly number[]): boolean {\n const [a, b] = octets;\n return (\n a === 0 || // \"this\" network\n a === 10 || // private\n a === 127 || // loopback\n (a === 169 && b === 254) || // link-local (incl. 169.254.169.254 metadata)\n (a === 172 && b !== undefined && b >= 16 && b <= 31) || // private\n (a === 192 && b === 168) // private\n );\n}\n\n/**\n * Expand an IPv6 literal to its 8 16-bit groups, or null if unparseable. Handles `::`\n * compression and an embedded dotted-quad tail (e.g. `::ffff:1.2.3.4`). The WHATWG URL parser\n * canonicalizes an IPv4-mapped address to hex (`[::ffff:7f00:1]`), so the range check must work\n * on the expanded groups rather than string-matching the dotted form.\n */\nfunction expandV6(input: string): number[] | null {\n let s = input;\n // Convert a trailing dotted-quad to two hex groups.\n const v4m = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (v4m) {\n const o = [Number(v4m[2]), Number(v4m[3]), Number(v4m[4]), Number(v4m[5])];\n if (o.some((x) => x > 255)) {\n return null;\n }\n s = `${v4m[1]}${(((o[0] as number) << 8) | (o[1] as number)).toString(16)}:${(((o[2] as number) << 8) | (o[3] as number)).toString(16)}`;\n }\n const halves = s.split('::');\n if (halves.length > 2) {\n return null;\n }\n const toGroups = (side: string): number[] | null => {\n if (side === '') {\n return [];\n }\n const out: number[] = [];\n for (const part of side.split(':')) {\n if (!/^[0-9a-f]{1,4}$/.test(part)) {\n return null;\n }\n out.push(parseInt(part, 16));\n }\n return out;\n };\n const left = toGroups(halves[0] ?? '');\n if (left === null) {\n return null;\n }\n if (halves.length === 2) {\n const right = toGroups(halves[1] ?? '');\n if (right === null) {\n return null;\n }\n const gap = 8 - left.length - right.length;\n if (gap < 1) {\n return null; // `::` must stand for at least one zero group\n }\n return [...left, ...new Array<number>(gap).fill(0), ...right];\n }\n return left.length === 8 ? left : null;\n}\n\n/** True for IPv6 loopback/unspecified, ULA (fc00::/7), link-local (fe80::/10), or a mapped private v4. */\nfunction isPrivateV6(addr: string): boolean {\n const groups = expandV6((addr.split('%')[0] ?? '').trim()); // drop any zone id\n if (groups === null) {\n return false;\n }\n if (groups.every((g) => g === 0)) {\n return true; // :: unspecified\n }\n if (groups.slice(0, 7).every((g) => g === 0) && groups[7] === 1) {\n return true; // ::1 loopback\n }\n const first = groups[0] ?? 0;\n if ((first & 0xfe00) === 0xfc00) {\n return true; // ULA fc00::/7\n }\n if ((first & 0xffc0) === 0xfe80) {\n return true; // link-local fe80::/10\n }\n // IPv4-mapped ::ffff:a.b.c.d\n if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff) {\n const g6 = groups[6] ?? 0;\n const g7 = groups[7] ?? 0;\n return isPrivateV4([(g6 >> 8) & 0xff, g6 & 0xff, (g7 >> 8) & 0xff, g7 & 0xff]);\n }\n return false;\n}\n\n/**\n * Build the HTTP Basic `Authorization` header value from Application Password\n * credentials. WordPress treats the Application Password as the Basic-auth password.\n */\nexport function buildAuthHeader(credentials: WpCredentials): string {\n if (credentials.username.includes(':')) {\n throw new Error('Username must not contain a colon (\":\") for HTTP Basic authentication.');\n }\n const token = `${credentials.username}:${credentials.applicationPassword}`;\n const base64 = Buffer.from(token, 'utf-8').toString('base64');\n return `Basic ${base64}`;\n}\n\n/** Error thrown when the WordPress REST API returns a non-2xx response. */\nexport class WpRequestError extends Error {\n constructor(\n readonly status: number,\n readonly path: string,\n message: string,\n ) {\n super(message);\n this.name = 'WpRequestError';\n }\n}\n\n/**\n * Minimal WordPress REST client.\n *\n * Runs in the Node process (CLI shell), never in the browser, so Application Password\n * credentials stay server-side. MVP scope: list posts, read/write post meta.\n */\nexport class WpClient {\n private readonly restBase: string;\n\n constructor(private readonly credentials: WpCredentials) {\n this.restBase = normalizeSiteUrl(credentials.siteUrl);\n }\n\n /**\n * Send an authenticated request and return the raw {@link Response} (throwing on non-2xx),\n * so callers that need response headers — e.g. media pagination via `X-WP-TotalPages` —\n * can read them. A JSON `Content-Type` is declared only when a body is sent; a caller may\n * override it via `init.headers` (the media upload sends the file's own type).\n */\n private async send(path: string, init: RequestInit = {}): Promise<Response> {\n const response = await fetch(`${this.restBase}/wp-json${path}`, {\n ...init,\n headers: {\n Authorization: buildAuthHeader(this.credentials),\n // Only declare a JSON body when one is actually sent (GETs carry none).\n ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...init.headers,\n },\n });\n\n if (!response.ok) {\n throw new WpRequestError(\n response.status,\n path,\n `WordPress REST request failed: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n }\n\n private async request<T>(path: string, init: RequestInit = {}): Promise<T> {\n return (await this.send(path, init)).json() as Promise<T>;\n }\n\n /**\n * List the REST-enabled post types on the site (edit context), so the app can offer\n * a type selector. Returns each type's REST route base and display name.\n */\n async listPostTypes(): Promise<WpPostType[]> {\n const raw = await this.request<unknown>('/wp/v2/types?context=edit');\n return normalizePostTypes(raw);\n }\n\n /** List posts of a given type in edit context (raw fields, for editing). */\n async listPosts(params: ListPostsParams = {}): Promise<WpPost[]> {\n const type = params.type ?? 'posts';\n assertRouteSegment(type);\n const perPage = clampInt(params.perPage ?? 100, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n context: 'edit',\n per_page: String(perPage),\n page: String(page),\n });\n const raw = await this.request<WpPostResponse[]>(`/wp/v2/${type}?${query.toString()}`);\n return raw.map(normalizePost);\n }\n\n /**\n * List posts as {@link PrintRecord}s for Print Design. Requests `_embed` (so featured\n * media and taxonomy terms come back inline) plus `content`/`excerpt`; the standard\n * table/spreadsheet listing ({@link WpClient.listPosts}) is unaffected.\n */\n async listPostsForPrint(params: ListPostsParams = {}): Promise<PrintRecord[]> {\n const type = params.type ?? 'posts';\n assertRouteSegment(type);\n const perPage = clampInt(params.perPage ?? 100, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n context: 'edit',\n per_page: String(perPage),\n page: String(page),\n _embed: '1',\n });\n const raw = await this.request<WpPostResponse[]>(`/wp/v2/${type}?${query.toString()}`);\n return raw.map(buildPrintRecord);\n }\n\n /**\n * Update post fields in a single request. Standard fields (title, menu_order,\n * status) are core REST fields and need no plugin. When `meta` is supplied it rides\n * the same request through the companion plugin's `dbp_wp_meta` field (ignored by\n * WordPress without the connector). Pass the REST route slug as `type` (e.g.\n * `posts`, `pages`) — not the object type returned on a post.\n */\n async updatePost(\n id: number,\n fields: UpdatePostFields,\n type = 'posts',\n meta?: Record<string, unknown>,\n ): Promise<WpPost> {\n assertPostId(id);\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(buildPostBody(fields, meta)),\n });\n return normalizePost(raw);\n }\n\n /**\n * Create a new post in a single request, symmetric to {@link WpClient.updatePost}.\n * Standard fields (title, menu_order, status) are core REST fields; when `meta` is\n * supplied it rides the same request through the companion plugin's `dbp_wp_meta`\n * field. Pass the REST route slug as `type` (e.g. `posts`, `pages`).\n */\n async createPost(\n fields: UpdatePostFields,\n type = 'posts',\n meta?: Record<string, unknown>,\n ): Promise<WpPost> {\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(buildPostBody(fields, meta)),\n });\n return normalizePost(raw);\n }\n\n /**\n * Update only arbitrary post meta through the companion plugin's `dbp_wp_meta`\n * field. A thin wrapper over {@link WpClient.updatePost} with no standard fields.\n * Requires the connector; the connector writes scalar values only.\n */\n async updatePostMeta(\n id: number,\n meta: Record<string, unknown>,\n type = 'posts',\n ): Promise<WpPost> {\n return this.updatePost(id, {}, type, meta);\n }\n\n /**\n * Fetch a single post for body editing (edit context), returning the raw body\n * (`content.raw`) and, when present, the lossless Markdown source from\n * `_dbp_wp_markdown`. The standard listing ({@link WpClient.listPosts}) omits the body, so\n * the editor uses this dedicated read. The Markdown source comes back via the standard\n * `meta` field only when the connector registered the key; in restricted mode the post is\n * HTML-only. Pass the REST route slug as `type`.\n */\n async getPostForEdit(id: number, type = 'posts'): Promise<WpPostEdit> {\n assertPostId(id);\n assertRouteSegment(type);\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`);\n return normalizePostForEdit(raw);\n }\n\n /**\n * Save a single post's body. Writes `content` (core REST) and, when `markdown` is given,\n * the `_dbp_wp_markdown` source via the standard `meta` field (registered by the connector)\n * — both in one request. Pass `markdown` as the source string for Markdown mode, `null` to\n * clear it (HTML mode on a post previously saved as Markdown), or omit it for an HTML-only\n * post. Writing/clearing `markdown` requires the connector; a content-only save does not.\n * Returns the re-fetched edit model (edit context), so the caller sees the persisted mode.\n */\n async updatePostBody(\n id: number,\n type: string,\n body: { content: string; markdown?: string | null },\n ): Promise<WpPostEdit> {\n assertPostId(id);\n assertRouteSegment(type);\n const reqBody = buildUpdateBody({ content: body.content });\n if (body.markdown !== undefined) {\n // Standard `meta` field (like the relation keys), not the connector's `dbp_wp_meta`:\n // `_dbp_wp_markdown` is protected and is only writable through register_post_meta.\n // `null` makes WordPress delete the key (no stale source left to mis-detect the mode).\n reqBody.meta = { [MARKDOWN_META_KEY]: body.markdown };\n }\n const raw = await this.request<WpPostResponse>(`/wp/v2/${type}/${String(id)}?context=edit`, {\n method: 'POST',\n body: JSON.stringify(reqBody),\n });\n return normalizePostForEdit(raw);\n }\n\n /**\n * Delete named meta keys from a single post via the companion plugin's\n * `DELETE /dbp-wp/v1/posts/<id>/meta` route. This route is keyed by id only (the\n * post type is irrelevant). Requires the connector.\n */\n async deletePostMeta(id: number, keys: string[]): Promise<DeleteMetaResult> {\n assertPostId(id);\n const cleanKeys = sanitizeMetaKeys(keys);\n // Use send() (not request()) so an empty/204 response from the connector does not throw in\n // JSON.parse; parseDeleteMetaResponse tolerates it.\n const response = await this.send(`/${CONNECTOR_NAMESPACE}/posts/${String(id)}/meta`, {\n method: 'DELETE',\n body: JSON.stringify({ keys: cleanKeys }),\n });\n return parseDeleteMetaResponse(await response.text(), id, cleanKeys);\n }\n\n /**\n * Set a child post's parent relation. The relation keys ride the standard core `meta`\n * field (the connector registers them with `register_post_meta`), so this is a distinct\n * path from {@link WpClient.updatePostMeta} (which uses the connector's `dbp_wp_meta`\n * field). Validates the assignment (positive id, valid type, no self-parent) before\n * writing. Requires the connector; without it WordPress silently ignores the keys.\n */\n async setRelation(\n childId: number,\n childType: string,\n relation: RelationTarget,\n ): Promise<WpPost> {\n assertPostId(childId);\n assertRouteSegment(childType);\n const raw = await this.request<WpPostResponse>(\n `/wp/v2/${childType}/${String(childId)}?context=edit`,\n { method: 'POST', body: JSON.stringify({ meta: buildSetRelationMeta(childId, relation) }) },\n );\n return normalizePost(raw);\n }\n\n /**\n * Clear a child post's parent relation. Sends `null` for both relation keys, which makes\n * WordPress delete them (no stale `0`/empty value left behind). Requires the connector.\n */\n async clearRelation(childId: number, childType: string): Promise<WpPost> {\n assertPostId(childId);\n assertRouteSegment(childType);\n const raw = await this.request<WpPostResponse>(\n `/wp/v2/${childType}/${String(childId)}?context=edit`,\n { method: 'POST', body: JSON.stringify({ meta: buildClearRelationMeta() }) },\n );\n return normalizePost(raw);\n }\n\n /**\n * Detect whether the companion plugin is active by checking the REST index\n * (`/wp-json/`) for the connector's namespace. Throws on a failed request; a caller\n * that wants a non-fatal probe should treat a thrown error as \"not available\".\n */\n async detectConnector(): Promise<boolean> {\n const index = await this.request<{ namespaces?: unknown }>('/');\n return hasConnectorNamespace(index.namespaces);\n }\n\n /**\n * Upload an image to the media library via core REST (`POST /wp/v2/media`), the same\n * contract WordPress uses: raw bytes with a `Content-Disposition` filename and the file's\n * MIME type (octet-stream when unknown). No companion plugin needed; the authenticated\n * user must have `upload_files`. Returns the normalized media item.\n */\n async uploadMedia(bytes: Uint8Array, filename: string, mimeType?: string): Promise<WpMedia> {\n const response = await this.send('/wp/v2/media', {\n method: 'POST',\n body: bytes,\n headers: {\n 'Content-Type': mimeType && mimeType.length > 0 ? mimeType : 'application/octet-stream',\n 'Content-Disposition': buildContentDisposition(filename),\n },\n });\n return normalizeMedia(await response.json());\n }\n\n /**\n * List image attachments (`GET /wp/v2/media?media_type=image`), paginated. Reads the\n * `X-WP-TotalPages` response header so the picker can page through the library. A core\n * REST call — no companion plugin needed.\n */\n async listMedia(params: ListMediaParams = {}): Promise<{ items: WpMedia[]; totalPages: number }> {\n const perPage = clampInt(params.perPage ?? 30, 1, 100);\n const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);\n const query = new URLSearchParams({\n media_type: 'image',\n per_page: String(perPage),\n page: String(page),\n });\n const search = params.search?.trim();\n if (search) {\n query.set('search', search);\n }\n const response = await this.send(`/wp/v2/media?${query.toString()}`);\n const raw = (await response.json()) as unknown;\n return {\n items: Array.isArray(raw) ? raw.map(normalizeMedia) : [],\n totalPages: parseTotalPages(response.headers.get('X-WP-TotalPages')),\n };\n }\n\n /**\n * Resolve specific media ids to their URLs in one request (`?include=`), used to fill in\n * the featured-image thumbnails for the posts currently shown — without embedding media\n * into the lean post listing. A core REST call — no companion plugin needed.\n */\n async resolveMedia(ids: number[]): Promise<WpMedia[]> {\n const clean = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];\n if (clean.length === 0) {\n return [];\n }\n // WordPress caps per_page at 100, so resolve in chunks of 100 — otherwise a request for\n // more than 100 ids would be silently truncated, leaving the rest unresolved.\n const out: WpMedia[] = [];\n for (let i = 0; i < clean.length; i += 100) {\n const chunk = clean.slice(i, i + 100);\n const query = new URLSearchParams({\n include: chunk.join(','),\n per_page: String(chunk.length),\n });\n const raw = await this.request<unknown>(`/wp/v2/media?${query.toString()}`);\n if (Array.isArray(raw)) {\n out.push(...raw.map(normalizeMedia));\n }\n }\n return out;\n }\n}\n\n/** Map editable fields to the WordPress REST request body (camelCase → snake_case). */\nexport function buildUpdateBody(fields: UpdatePostFields): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (fields.title !== undefined) {\n body.title = fields.title;\n }\n if (fields.menuOrder !== undefined) {\n body.menu_order = fields.menuOrder;\n }\n if (fields.status !== undefined) {\n body.status = fields.status;\n }\n if (fields.featuredMedia !== undefined) {\n // `0` is meaningful here (removes the featured image), so check for undefined, not falsy.\n body.featured_media = fields.featuredMedia;\n }\n if (fields.content !== undefined) {\n // `''` is meaningful here (clears the body), so check for undefined, not falsy.\n body.content = fields.content;\n }\n return body;\n}\n\nfunction assertRouteSegment(segment: string): void {\n if (!ROUTE_SEGMENT.test(segment)) {\n throw new Error(`Invalid REST route segment: ${segment}`);\n }\n}\n\nfunction assertPostId(id: number): void {\n if (!Number.isSafeInteger(id) || id <= 0) {\n throw new Error(`Invalid post id: ${id}`);\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) {\n return min;\n }\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\n/** Wrap arbitrary meta in the companion plugin's REST field for a write request. */\nexport function buildMetaBody(meta: Record<string, unknown>): Record<string, unknown> {\n return { [META_FIELD]: meta };\n}\n\n/**\n * Build a post-update body, folding in connector meta under `dbp_wp_meta` when given.\n * A provided `meta` is included as-is, even when empty — callers that should skip empty\n * meta (e.g. the CLI batch parser) omit it before calling.\n */\nexport function buildPostBody(\n fields: UpdatePostFields,\n meta?: Record<string, unknown>,\n): Record<string, unknown> {\n const body = buildUpdateBody(fields);\n if (meta !== undefined) {\n Object.assign(body, buildMetaBody(meta));\n }\n return body;\n}\n\n/**\n * Parse a per-post meta-delete response. `send()` already threw on a non-2xx status, so an empty\n * body (e.g. a 204 from a backend that returns no content) or a non-JSON body means the delete\n * succeeded — the requested keys are reported as deleted. A JSON body's `deleted` list (the keys\n * actually present) takes precedence, and the request `id` is trusted over a malformed `post_id`.\n */\nexport function parseDeleteMetaResponse(\n body: string,\n id: number,\n requestedKeys: string[],\n): DeleteMetaResult {\n const text = body.trim();\n if (text === '') {\n return { postId: id, deleted: [...requestedKeys] };\n }\n let raw: { post_id?: unknown; deleted?: unknown };\n try {\n raw = JSON.parse(text) as { post_id?: unknown; deleted?: unknown };\n } catch {\n return { postId: id, deleted: [...requestedKeys] };\n }\n return {\n // Trust the request `id` over a malformed `post_id` (0, negative, or fractional included).\n postId:\n typeof raw.post_id === 'number' && Number.isSafeInteger(raw.post_id) && raw.post_id > 0\n ? raw.post_id\n : id,\n deleted: Array.isArray(raw.deleted)\n ? raw.deleted.filter((k): k is string => typeof k === 'string')\n : [],\n };\n}\n\n/** Validate and clean a list of meta keys for deletion (non-empty strings only). */\nexport function sanitizeMetaKeys(keys: unknown): string[] {\n if (!Array.isArray(keys)) {\n throw new Error('Meta keys must be an array of strings.');\n }\n const clean = keys.filter((key): key is string => typeof key === 'string' && key.length > 0);\n if (clean.length === 0) {\n throw new Error('At least one non-empty meta key is required.');\n }\n return clean;\n}\n\n/** True when a REST index `namespaces` list includes the connector namespace. */\nexport function hasConnectorNamespace(namespaces: unknown): boolean {\n return Array.isArray(namespaces) && namespaces.includes(CONNECTOR_NAMESPACE);\n}\n\n/**\n * Build a `Content-Disposition` value for a media upload. Emits an ASCII-only\n * `filename=\"…\"` fallback (non-ASCII and header-unsafe characters replaced with `_`) plus an\n * RFC 5987 `filename*=UTF-8''…` parameter, so a non-ASCII filename survives and never\n * produces an invalid (non-ByteString) header value that `fetch` would reject. The path is\n * reduced to its basename and quotes/CR/LF are dropped so the value cannot break the header.\n */\nexport function buildContentDisposition(filename: string): string {\n const base = filename.split(/[/\\\\]/).pop() ?? filename;\n const trimmed = base.replace(/[\\r\\n\"]/g, '').trim() || 'upload';\n const ascii = trimmed.replace(/[^\\x20-\\x7e]/g, '_');\n // Percent-encode per RFC 5987, also encoding the chars encodeURIComponent leaves bare.\n const encoded = encodeURIComponent(trimmed).replace(\n /['()*!]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n return `attachment; filename=\"${ascii}\"; filename*=UTF-8''${encoded}`;\n}\n\n/** Parse the `X-WP-TotalPages` header into a positive page count, defaulting to 1. */\nfunction parseTotalPages(header: string | null): number {\n if (header === null) {\n return 1;\n }\n const n = Number.parseInt(header, 10);\n return Number.isFinite(n) && n > 0 ? n : 1;\n}\n\n/** Read `<obj>.rendered` as a string, or `''` when absent/malformed. */\nfunction extractRendered(value: unknown): string {\n if (value !== null && typeof value === 'object') {\n const rendered = (value as Record<string, unknown>).rendered;\n if (typeof rendered === 'string') {\n return rendered;\n }\n }\n return '';\n}\n\n/** Prefer a thumbnail-sized URL from `media_details.sizes`, else a medium one, else `''`. */\nfunction extractThumbnailUrl(mediaDetails: unknown): string {\n if (mediaDetails === null || typeof mediaDetails !== 'object') {\n return '';\n }\n const sizes = (mediaDetails as Record<string, unknown>).sizes;\n if (sizes === null || typeof sizes !== 'object') {\n return '';\n }\n for (const sizeName of ['thumbnail', 'medium']) {\n const size = (sizes as Record<string, unknown>)[sizeName];\n if (size !== null && typeof size === 'object') {\n const url = (size as Record<string, unknown>).source_url;\n if (typeof url === 'string') {\n return url;\n }\n }\n }\n return '';\n}\n\n/**\n * Normalize a raw `/wp/v2/media` item into {@link WpMedia}. Accepts `unknown` and guards each\n * field, so a malformed entry degrades to empty strings rather than throwing.\n */\nexport function normalizeMedia(raw: unknown): WpMedia {\n const obj = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>;\n const sourceUrl = typeof obj.source_url === 'string' ? obj.source_url : '';\n return {\n id: typeof obj.id === 'number' ? obj.id : 0,\n sourceUrl,\n thumbnailUrl: extractThumbnailUrl(obj.media_details) || sourceUrl,\n title: extractRendered(obj.title),\n mimeType: typeof obj.mime_type === 'string' ? obj.mime_type : '',\n };\n}\n\n/**\n * Normalize the `/wp/v2/types` response (an object keyed by type name) into a list.\n * Skips entries without a string `rest_base` (not addressable over REST).\n */\nexport function normalizePostTypes(raw: unknown): WpPostType[] {\n if (typeof raw !== 'object' || raw === null) {\n return [];\n }\n const result: WpPostType[] = [];\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof value !== 'object' || value === null) {\n continue;\n }\n const entry = value as Record<string, unknown>;\n // Validate rest_base at ingestion so a malformed slug can't become a broken option.\n if (typeof entry.rest_base !== 'string' || !ROUTE_SEGMENT.test(entry.rest_base)) {\n continue;\n }\n result.push({\n slug: typeof entry.slug === 'string' ? entry.slug : key,\n restBase: entry.rest_base,\n name: typeof entry.name === 'string' ? entry.name : key,\n });\n }\n return result;\n}\n\nexport function normalizePost(raw: WpPostResponse): WpPost {\n const post: WpPost = {\n id: raw.id,\n type: raw.type,\n status: raw.status,\n title: raw.title.raw ?? raw.title.rendered,\n menuOrder: raw.menu_order,\n meta: raw.meta,\n };\n if (raw.dbp_wp_meta !== undefined) {\n post.dbpWpMeta = raw.dbp_wp_meta;\n }\n // featured_media is always present on a core post; 0 means \"no featured image\".\n if (typeof raw.featured_media === 'number' && raw.featured_media > 0) {\n post.featuredMedia = raw.featured_media;\n }\n // Parent relation rides the standard `meta` field (registered by the connector). It needs\n // both a positive id and a non-empty type; a half-written pair — e.g. from a raw REST\n // write that set only one key, or a parent type sanitized to '' — reads as no relation.\n // parent and parentType are therefore set together or not at all, so normalizePost,\n // getRelation, and deriveChildren stay consistent on malformed data.\n const rawParent = raw.meta?.[PARENT_META_KEY];\n const rawParentType = raw.meta?.[PARENT_TYPE_META_KEY];\n if (\n typeof rawParent === 'number' &&\n Number.isInteger(rawParent) &&\n rawParent > 0 &&\n typeof rawParentType === 'string' &&\n rawParentType !== ''\n ) {\n post.parent = rawParent;\n post.parentType = rawParentType;\n }\n return post;\n}\n\n/**\n * Normalize a raw post (edit context) into the body-editing model {@link WpPostEdit}.\n *\n * Reads `content.raw` for the body. Mode is determined by the Markdown source: only a\n * *non-empty* `_dbp_wp_markdown` value marks Markdown mode. This mirrors the relation keys'\n * value-based sentinel (a positive id means \"set\") and sidesteps the REST default for a\n * registered string meta (an unset key can come back as `''`), so an HTML-mode post is never\n * mistaken for an empty-bodied Markdown post.\n */\nexport function normalizePostForEdit(raw: WpPostResponse): WpPostEdit {\n const edit: WpPostEdit = {\n id: raw.id,\n type: raw.type,\n status: raw.status,\n title: raw.title.raw ?? raw.title.rendered,\n content: raw.content?.raw ?? '',\n };\n const markdown = raw.meta?.[MARKDOWN_META_KEY];\n if (typeof markdown === 'string' && markdown !== '') {\n edit.markdown = markdown;\n }\n return edit;\n}\n","import { marked } from 'marked';\n\n/**\n * Convert Markdown source to HTML for the single-post body editor.\n *\n * One shared implementation, used by the UI (live preview and the HTML mirrored into\n * `post_content` on save) and available to the CLI/future MCP layer, so a post's stored\n * HTML always matches what the editor previewed. GitHub-flavored Markdown is enabled.\n *\n * This does NOT sanitize the output. Sanitization is delegated to WordPress `kses` at save\n * time (capability-dependent), and the live preview is isolated in a sandboxed iframe with\n * no script execution — matching the body-editing design (no extra sanitizer dependency in\n * DBP WP).\n */\nexport function renderMarkdown(markdown: string): string {\n // `async: false` selects marked's synchronous overload (string return). Guard the result\n // so an unexpected non-string (e.g. a future async extension) degrades to empty rather\n // than leaking a Promise into the rendered body.\n const html = marked.parse(markdown, { async: false, gfm: true });\n return typeof html === 'string' ? html : '';\n}\n","import { Parser, type Expression } from 'expr-eval-fork';\n\n/**\n * Formula engine: evaluates a spreadsheet expression against named numeric cells.\n *\n * Implementations MUST NOT use `eval`, `Function`, or any other dynamic code execution.\n */\nexport interface FormulaEngine {\n /**\n * Evaluate a single expression against a map of cell references to numbers.\n * Throws on invalid syntax, unknown variables, or a non-numeric result.\n */\n evaluate(expression: string, context: Record<string, number>): number;\n}\n\n/**\n * Formula engine backed by expr-eval-fork, which parses to an AST and evaluates without\n * `eval`/`Function`. Member access, assignment, and function definitions are disabled,\n * the nondeterministic `random()` function is removed, and results are constrained to\n * finite numbers, so expressions stay pure, deterministic, and side-effect free.\n */\nexport class SafeFormulaEngine implements FormulaEngine {\n private readonly parser: Parser;\n\n constructor() {\n this.parser = new Parser({\n allowMemberAccess: false,\n operators: { assignment: false, fndef: false },\n });\n // The `operators.random` flag does not remove the random() function; delete it so\n // evaluation stays deterministic.\n delete this.parser.functions.random;\n }\n\n evaluate(expression: string, context: Record<string, number>): number {\n let parsed: Expression;\n try {\n parsed = this.parser.parse(expression);\n } catch (e) {\n throw new Error(`Invalid formula: ${e instanceof Error ? e.message : 'parse error'}`);\n }\n\n let result: unknown;\n try {\n result = parsed.evaluate(context);\n } catch (e) {\n throw new Error(`Formula evaluation failed: ${e instanceof Error ? e.message : 'error'}`);\n }\n\n if (typeof result !== 'number' || !Number.isFinite(result)) {\n throw new Error('Formula must evaluate to a finite number.');\n }\n return result;\n }\n}\n","import type { UpdatePostFields } from './types';\n\n// WordPress stores menu_order in a signed 32-bit column; ignore cells outside that range\n// so one bad value does not get the whole server-side chunk rejected.\nconst MENU_ORDER_MIN = -2_147_483_648;\nconst MENU_ORDER_MAX = 2_147_483_647;\n\n/**\n * A tabular view of an import file: a header row plus data rows. Both CSV and JSON\n * sources are normalized to this shape so the column-mapping logic is source-agnostic.\n * Each data row is aligned to `headers` by index; a short row has missing trailing cells.\n */\nexport interface ParsedTable {\n /** Column headers (CSV first row, or the union of JSON object keys). */\n headers: string[];\n /** Data rows; `rows[r][c]` is the cell under `headers[c]`. */\n rows: string[][];\n}\n\n/**\n * Where a file column is imported to. `skip` drops the column; `title`/`status`/\n * `menuOrder` map to standard post fields; `meta` writes an arbitrary post-meta key\n * (companion plugin required).\n */\nexport type ImportTarget =\n | { kind: 'skip' }\n | { kind: 'title' }\n | { kind: 'status' }\n | { kind: 'menuOrder' }\n | { kind: 'meta'; key: string };\n\n/** A single new post to create, derived from one import row. */\nexport interface ImportCreate {\n /** Standard fields (title / menuOrder / status). */\n fields: UpdatePostFields;\n /** Arbitrary meta to write via the companion plugin (omitted when none). */\n meta?: Record<string, unknown>;\n}\n\n/**\n * Parse CSV text into a table, taking the first record as headers. Implements the\n * RFC 4180 essentials: double-quoted fields, embedded commas/newlines, `\"\"` escapes,\n * and CRLF or LF line endings. A trailing newline does not produce an empty record.\n */\nexport function parseCsv(text: string): ParsedTable {\n const records = parseCsvRecords(text);\n const headers = records[0] ?? [];\n return { headers, rows: records.slice(1) };\n}\n\nfunction parseCsvRecords(text: string): string[][] {\n const records: string[][] = [];\n let record: string[] = [];\n let field = '';\n let inQuotes = false;\n let i = 0;\n\n const endField = (): void => {\n record.push(field);\n field = '';\n };\n const endRecord = (): void => {\n endField();\n records.push(record);\n record = [];\n };\n\n while (i < text.length) {\n const ch = text[i];\n if (inQuotes) {\n if (ch === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i += 2;\n continue;\n }\n inQuotes = false;\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n continue;\n }\n if (ch === '\"') {\n inQuotes = true;\n i += 1;\n continue;\n }\n if (ch === ',') {\n endField();\n i += 1;\n continue;\n }\n if (ch === '\\r') {\n endRecord();\n i += text[i + 1] === '\\n' ? 2 : 1;\n continue;\n }\n if (ch === '\\n') {\n endRecord();\n i += 1;\n continue;\n }\n field += ch;\n i += 1;\n }\n // An unclosed quote means the file is malformed; surface it rather than silently\n // merging the rest of the file into one field and writing corrupted data.\n if (inQuotes) {\n throw new Error('Malformed CSV: unterminated quoted field.');\n }\n // Flush a final record only if there is pending content (no trailing-newline ghost row).\n if (field !== '' || record.length > 0) {\n endRecord();\n }\n return records;\n}\n\n/**\n * Parse JSON text (an array of objects) into a table. Headers are the union of all\n * object keys in first-seen order. Object/array cell values are JSON-stringified;\n * null and undefined become an empty string. Throws if the JSON is not an array.\n */\nexport function parseJsonRecords(text: string): ParsedTable {\n const data: unknown = JSON.parse(text);\n if (!Array.isArray(data)) {\n throw new Error('JSON import must be an array of objects.');\n }\n const headers: string[] = [];\n const seen = new Set<string>();\n for (const entry of data) {\n if (isPlainRecord(entry)) {\n for (const key of Object.keys(entry)) {\n if (!seen.has(key)) {\n seen.add(key);\n headers.push(key);\n }\n }\n }\n }\n const rows = data.map((entry) => {\n const record = isPlainRecord(entry) ? entry : {};\n return headers.map((header) => stringifyCell(record[header]));\n });\n return { headers, rows };\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction stringifyCell(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return String(value);\n}\n\n/**\n * Known post-status values and English/value labels, mapped to the WordPress status.\n * A null-prototype map so inherited keys (`constructor`, `toString`, `__proto__`, …) do\n * not accidentally resolve to a function/object instead of falling back to the raw value.\n */\nconst STATUS_LABELS: Record<string, string> = Object.assign(\n Object.create(null) as Record<string, string>,\n {\n publish: 'publish',\n published: 'publish',\n draft: 'draft',\n pending: 'pending',\n private: 'private',\n future: 'future',\n },\n);\n\n/**\n * Normalize a status cell to a WordPress status. Known labels/values (case-insensitive,\n * e.g. `Published` → `publish`) are mapped; anything else passes through trimmed so the\n * WordPress REST API can validate it and surface a per-row error if invalid.\n */\nexport function normalizeStatus(value: string): string {\n const trimmed = value.trim();\n return STATUS_LABELS[trimmed.toLowerCase()] ?? trimmed;\n}\n\n/**\n * Apply a column mapping to a parsed table, producing one {@link ImportCreate} per row.\n * Empty cells contribute nothing; a row that maps to no fields and no meta is skipped.\n * Non-integer `menuOrder` cells are ignored. Meta is stored on a null-prototype object\n * so a header named `__proto__` is kept as data, never touching any prototype.\n */\nexport function buildImportPlan(table: ParsedTable, mapping: ImportTarget[]): ImportCreate[] {\n const creates: ImportCreate[] = [];\n for (const row of table.rows) {\n const fields: UpdatePostFields = {};\n let meta: Record<string, unknown> | undefined;\n\n for (let col = 0; col < mapping.length; col += 1) {\n const target = mapping[col];\n if (!target || target.kind === 'skip') {\n continue;\n }\n const value = row[col] ?? '';\n if (value === '') {\n continue;\n }\n switch (target.kind) {\n case 'title':\n fields.title = value;\n break;\n case 'status':\n fields.status = normalizeStatus(value);\n break;\n case 'menuOrder': {\n const order = Number(value);\n if (Number.isInteger(order) && order >= MENU_ORDER_MIN && order <= MENU_ORDER_MAX) {\n fields.menuOrder = order;\n }\n break;\n }\n case 'meta':\n // An empty/whitespace meta key would be rejected by the server (empty key),\n // failing the whole chunk; skip it rather than emit `meta[\"\"]`.\n if (target.key.trim() === '') {\n break;\n }\n if (!meta) {\n meta = Object.create(null) as Record<string, unknown>;\n }\n meta[target.key] = value;\n break;\n }\n }\n\n if (meta !== undefined && Object.keys(meta).length > 0) {\n creates.push({ fields, meta });\n } else if (Object.keys(fields).length > 0) {\n creates.push({ fields });\n }\n }\n return creates;\n}\n"],"mappings":";AA2CO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4BA,IAAM,MACJ;AAGF,SAAS,cAAc,UAAkC;AACvD,QAAM,OAAuB,CAAC;AAG9B,MAAI,UAA0B;AAC9B,QAAM,UAA4B,CAAC;AACnC,QAAM,OAAmB,CAAC;AAC1B,QAAM,WAAW,CAAC,SAAuB;AACvC,QAAI,KAAM,SAAQ,KAAK,EAAE,MAAM,QAAQ,OAAO,KAAK,CAAC;AAAA,EACtD;AAEA,MAAI,OAAO;AACX,MAAI,YAAY;AAChB,MAAI;AACJ,UAAQ,I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AM,SAAS,QAAQ,GAAG;AAC1B,UAAI,CAAC,UAAU,OAAO,SAAS,QAAQ;AACrC;AAAA,MACF;AACA,YAAM,QAAQ,IAAI,GAAG,KAAK;AAC1B,UAAI,UAAU,IAAI;AAChB;AAAA,MACF;AACA,cAAQ,OAAO,MAAM;AAAA,QACnB,KAAK;AACH,iBAAO,QAAQ;AACf;AAAA,QACF,KAAK;AACH,iBAAO,SAAS,gBAAgB,KAAK;AACrC;AAAA,QACF,KAAK,aAAa;AAChB,gBAAM,QAAQ,OAAO,KAAK;AAC1B,cAAI,OAAO,UAAU,KAAK,KAAK,SAAS,kBAAkB,SAAS,gBAAgB;AACjF,mBAAO,YAAY;AAAA,UACrB;AACA;AAAA,QACF;AAAA,QACA,KAAK;AAGH,cAAI,OAAO,IAAI,KAAK,MAAM,IAAI;AAC5B;AAAA,UACF;AACA,cAAI,CAAC,MAAM;AACT,mBAAO,uBAAO,OAAO,IAAI;AAAA,UAC3B;AACA,eAAK,OAAO,GAAG,IAAI;AACnB;AAAA,MACJ;AAAA,IACF;AAEA,QAAI,SAAS,UAAa,OAAO,KAAK,IAAI,EAAE,SAAS,GAAG;AACtD,cAAQ,KAAK,EAAE,QAAQ,KAAK,CAAC;AAAA,IAC/B,WAAW,OAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AACzC,cAAQ,KAAK,EAAE,OAAO,CAAC;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;","names":["flattenMetaValue","ROUTE_SEGMENT"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dbp-wp/core",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Core library for DBP WP: WordPress REST client, formula engine, importer, and typesetting data generation.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Takashi Matsuyama",