@dbp-wp/core 0.2.1 → 0.2.3
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.d.ts +81 -1
- package/dist/index.js +140 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ interface WpPostResponse {
|
|
|
27
27
|
raw?: string;
|
|
28
28
|
};
|
|
29
29
|
menu_order: number;
|
|
30
|
+
/** Featured image (attachment) ID; `0` when the post has no featured image. */
|
|
31
|
+
featured_media?: number;
|
|
30
32
|
meta: Record<string, unknown>;
|
|
31
33
|
/**
|
|
32
34
|
* Arbitrary post meta exposed by the companion plugin's `dbp_wp_meta` field.
|
|
@@ -83,6 +85,12 @@ interface WpPost {
|
|
|
83
85
|
* {@link WpPost.parent}; `undefined` when the post has no parent.
|
|
84
86
|
*/
|
|
85
87
|
parentType?: string;
|
|
88
|
+
/**
|
|
89
|
+
* Featured image (attachment) ID from the core `featured_media` field. Present only when
|
|
90
|
+
* the post has a featured image (`featured_media > 0`); `undefined` otherwise. The image's
|
|
91
|
+
* URL is resolved separately ({@link WpMedia}) so the listing stays lean.
|
|
92
|
+
*/
|
|
93
|
+
featuredMedia?: number;
|
|
86
94
|
}
|
|
87
95
|
/**
|
|
88
96
|
* Editable standard post fields. These map to core WordPress REST fields and need no
|
|
@@ -95,6 +103,11 @@ interface UpdatePostFields {
|
|
|
95
103
|
menuOrder?: number;
|
|
96
104
|
/** Post status (e.g. `publish`, `draft`). */
|
|
97
105
|
status?: string;
|
|
106
|
+
/**
|
|
107
|
+
* Featured image (attachment) ID (sent as `featured_media`). A core REST field — no
|
|
108
|
+
* companion plugin needed. Pass `0` to remove the post's featured image.
|
|
109
|
+
*/
|
|
110
|
+
featuredMedia?: number;
|
|
98
111
|
}
|
|
99
112
|
/** A WordPress post type available for listing/editing over REST. */
|
|
100
113
|
interface WpPostType {
|
|
@@ -112,6 +125,31 @@ interface DeleteMetaResult {
|
|
|
112
125
|
/** Keys actually deleted (a key not present on the post is omitted). */
|
|
113
126
|
deleted: string[];
|
|
114
127
|
}
|
|
128
|
+
/**
|
|
129
|
+
* A normalized WordPress media (attachment) item, as used by the media picker and the
|
|
130
|
+
* spreadsheet's featured-image column. Built from a raw `/wp/v2/media` response.
|
|
131
|
+
*/
|
|
132
|
+
interface WpMedia {
|
|
133
|
+
/** Attachment ID. */
|
|
134
|
+
id: number;
|
|
135
|
+
/** Full-size source URL of the media file (`''` when unavailable). */
|
|
136
|
+
sourceUrl: string;
|
|
137
|
+
/** Thumbnail-size URL when WordPress generated one; falls back to {@link WpMedia.sourceUrl}. */
|
|
138
|
+
thumbnailUrl: string;
|
|
139
|
+
/** Media title (rendered), or `''` when absent. */
|
|
140
|
+
title: string;
|
|
141
|
+
/** MIME type (e.g. `image/png`), or `''` when unknown. */
|
|
142
|
+
mimeType: string;
|
|
143
|
+
}
|
|
144
|
+
/** Parameters for listing media (image attachments). */
|
|
145
|
+
interface ListMediaParams {
|
|
146
|
+
/** 1-based page number. Defaults to 1. */
|
|
147
|
+
page?: number;
|
|
148
|
+
/** Page size (WordPress caps this at 100). Defaults to 30. */
|
|
149
|
+
perPage?: number;
|
|
150
|
+
/** Free-text search across media (title/filename). */
|
|
151
|
+
search?: string;
|
|
152
|
+
}
|
|
115
153
|
/** Parameters for listing posts. */
|
|
116
154
|
interface ListPostsParams {
|
|
117
155
|
/** REST post type slug (e.g. `posts`, `pages`). Defaults to `posts`. */
|
|
@@ -269,6 +307,13 @@ declare class WpClient {
|
|
|
269
307
|
private readonly credentials;
|
|
270
308
|
private readonly restBase;
|
|
271
309
|
constructor(credentials: WpCredentials);
|
|
310
|
+
/**
|
|
311
|
+
* Send an authenticated request and return the raw {@link Response} (throwing on non-2xx),
|
|
312
|
+
* so callers that need response headers — e.g. media pagination via `X-WP-TotalPages` —
|
|
313
|
+
* can read them. A JSON `Content-Type` is declared only when a body is sent; a caller may
|
|
314
|
+
* override it via `init.headers` (the media upload sends the file's own type).
|
|
315
|
+
*/
|
|
316
|
+
private send;
|
|
272
317
|
private request;
|
|
273
318
|
/**
|
|
274
319
|
* List the REST-enabled post types on the site (edit context), so the app can offer
|
|
@@ -329,7 +374,42 @@ declare class WpClient {
|
|
|
329
374
|
* that wants a non-fatal probe should treat a thrown error as "not available".
|
|
330
375
|
*/
|
|
331
376
|
detectConnector(): Promise<boolean>;
|
|
377
|
+
/**
|
|
378
|
+
* Upload an image to the media library via core REST (`POST /wp/v2/media`), the same
|
|
379
|
+
* contract WordPress uses: raw bytes with a `Content-Disposition` filename and the file's
|
|
380
|
+
* MIME type (octet-stream when unknown). No companion plugin needed; the authenticated
|
|
381
|
+
* user must have `upload_files`. Returns the normalized media item.
|
|
382
|
+
*/
|
|
383
|
+
uploadMedia(bytes: Uint8Array, filename: string, mimeType?: string): Promise<WpMedia>;
|
|
384
|
+
/**
|
|
385
|
+
* List image attachments (`GET /wp/v2/media?media_type=image`), paginated. Reads the
|
|
386
|
+
* `X-WP-TotalPages` response header so the picker can page through the library. A core
|
|
387
|
+
* REST call — no companion plugin needed.
|
|
388
|
+
*/
|
|
389
|
+
listMedia(params?: ListMediaParams): Promise<{
|
|
390
|
+
items: WpMedia[];
|
|
391
|
+
totalPages: number;
|
|
392
|
+
}>;
|
|
393
|
+
/**
|
|
394
|
+
* Resolve specific media ids to their URLs in one request (`?include=`), used to fill in
|
|
395
|
+
* the featured-image thumbnails for the posts currently shown — without embedding media
|
|
396
|
+
* into the lean post listing. A core REST call — no companion plugin needed.
|
|
397
|
+
*/
|
|
398
|
+
resolveMedia(ids: number[]): Promise<WpMedia[]>;
|
|
332
399
|
}
|
|
400
|
+
/**
|
|
401
|
+
* Build a `Content-Disposition` value for a media upload. Emits an ASCII-only
|
|
402
|
+
* `filename="…"` fallback (non-ASCII and header-unsafe characters replaced with `_`) plus an
|
|
403
|
+
* RFC 5987 `filename*=UTF-8''…` parameter, so a non-ASCII filename survives and never
|
|
404
|
+
* produces an invalid (non-ByteString) header value that `fetch` would reject. The path is
|
|
405
|
+
* reduced to its basename and quotes/CR/LF are dropped so the value cannot break the header.
|
|
406
|
+
*/
|
|
407
|
+
declare function buildContentDisposition(filename: string): string;
|
|
408
|
+
/**
|
|
409
|
+
* Normalize a raw `/wp/v2/media` item into {@link WpMedia}. Accepts `unknown` and guards each
|
|
410
|
+
* field, so a malformed entry degrades to empty strings rather than throwing.
|
|
411
|
+
*/
|
|
412
|
+
declare function normalizeMedia(raw: unknown): WpMedia;
|
|
333
413
|
|
|
334
414
|
/**
|
|
335
415
|
* Formula engine: evaluates a spreadsheet expression against named numeric cells.
|
|
@@ -416,4 +496,4 @@ declare function normalizeStatus(value: string): string;
|
|
|
416
496
|
*/
|
|
417
497
|
declare function buildImportPlan(table: ParsedTable, mapping: ImportTarget[]): ImportCreate[];
|
|
418
498
|
|
|
419
|
-
export { type DeleteMetaResult, type FormulaEngine, type ImportCreate, type ImportTarget, type ListPostsParams, PARENT_META_KEY, PARENT_TYPE_META_KEY, type ParsedTable, type PrintRecord, RelationError, type RelationTarget, SafeFormulaEngine, TemplateParseError, type UpdatePostFields, WpClient, type WpCredentials, type WpPost, type WpPostResponse, type WpPostType, WpRequestError, assertValidRelation, buildAuthHeader, buildClearRelationMeta, buildImportPlan, buildPrintRecord, buildSetRelationMeta, deriveChildren, getRelation, normalizeSiteUrl, normalizeStatus, parseCsv, parseJsonRecords, renderTemplate };
|
|
499
|
+
export { type DeleteMetaResult, type FormulaEngine, type ImportCreate, type ImportTarget, type ListMediaParams, type ListPostsParams, PARENT_META_KEY, PARENT_TYPE_META_KEY, type ParsedTable, type PrintRecord, RelationError, type RelationTarget, SafeFormulaEngine, TemplateParseError, type UpdatePostFields, WpClient, type WpCredentials, type WpMedia, type WpPost, type WpPostResponse, type WpPostType, WpRequestError, assertValidRelation, buildAuthHeader, buildClearRelationMeta, buildContentDisposition, buildImportPlan, buildPrintRecord, buildSetRelationMeta, deriveChildren, getRelation, normalizeMedia, normalizeSiteUrl, normalizeStatus, parseCsv, parseJsonRecords, renderTemplate };
|
package/dist/index.js
CHANGED
|
@@ -260,7 +260,13 @@ var WpClient = class {
|
|
|
260
260
|
}
|
|
261
261
|
credentials;
|
|
262
262
|
restBase;
|
|
263
|
-
|
|
263
|
+
/**
|
|
264
|
+
* Send an authenticated request and return the raw {@link Response} (throwing on non-2xx),
|
|
265
|
+
* so callers that need response headers — e.g. media pagination via `X-WP-TotalPages` —
|
|
266
|
+
* can read them. A JSON `Content-Type` is declared only when a body is sent; a caller may
|
|
267
|
+
* override it via `init.headers` (the media upload sends the file's own type).
|
|
268
|
+
*/
|
|
269
|
+
async send(path, init = {}) {
|
|
264
270
|
const response = await fetch(`${this.restBase}/wp-json${path}`, {
|
|
265
271
|
...init,
|
|
266
272
|
headers: {
|
|
@@ -277,7 +283,10 @@ var WpClient = class {
|
|
|
277
283
|
`WordPress REST request failed: ${response.status} ${response.statusText}`
|
|
278
284
|
);
|
|
279
285
|
}
|
|
280
|
-
return
|
|
286
|
+
return response;
|
|
287
|
+
}
|
|
288
|
+
async request(path, init = {}) {
|
|
289
|
+
return (await this.send(path, init)).json();
|
|
281
290
|
}
|
|
282
291
|
/**
|
|
283
292
|
* List the REST-enabled post types on the site (edit context), so the app can offer
|
|
@@ -413,6 +422,71 @@ var WpClient = class {
|
|
|
413
422
|
const index = await this.request("/");
|
|
414
423
|
return hasConnectorNamespace(index.namespaces);
|
|
415
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* Upload an image to the media library via core REST (`POST /wp/v2/media`), the same
|
|
427
|
+
* contract WordPress uses: raw bytes with a `Content-Disposition` filename and the file's
|
|
428
|
+
* MIME type (octet-stream when unknown). No companion plugin needed; the authenticated
|
|
429
|
+
* user must have `upload_files`. Returns the normalized media item.
|
|
430
|
+
*/
|
|
431
|
+
async uploadMedia(bytes, filename, mimeType) {
|
|
432
|
+
const response = await this.send("/wp/v2/media", {
|
|
433
|
+
method: "POST",
|
|
434
|
+
body: bytes,
|
|
435
|
+
headers: {
|
|
436
|
+
"Content-Type": mimeType && mimeType.length > 0 ? mimeType : "application/octet-stream",
|
|
437
|
+
"Content-Disposition": buildContentDisposition(filename)
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
return normalizeMedia(await response.json());
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* List image attachments (`GET /wp/v2/media?media_type=image`), paginated. Reads the
|
|
444
|
+
* `X-WP-TotalPages` response header so the picker can page through the library. A core
|
|
445
|
+
* REST call — no companion plugin needed.
|
|
446
|
+
*/
|
|
447
|
+
async listMedia(params = {}) {
|
|
448
|
+
const perPage = clampInt(params.perPage ?? 30, 1, 100);
|
|
449
|
+
const page = clampInt(params.page ?? 1, 1, Number.MAX_SAFE_INTEGER);
|
|
450
|
+
const query = new URLSearchParams({
|
|
451
|
+
media_type: "image",
|
|
452
|
+
per_page: String(perPage),
|
|
453
|
+
page: String(page)
|
|
454
|
+
});
|
|
455
|
+
const search = params.search?.trim();
|
|
456
|
+
if (search) {
|
|
457
|
+
query.set("search", search);
|
|
458
|
+
}
|
|
459
|
+
const response = await this.send(`/wp/v2/media?${query.toString()}`);
|
|
460
|
+
const raw = await response.json();
|
|
461
|
+
return {
|
|
462
|
+
items: Array.isArray(raw) ? raw.map(normalizeMedia) : [],
|
|
463
|
+
totalPages: parseTotalPages(response.headers.get("X-WP-TotalPages"))
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Resolve specific media ids to their URLs in one request (`?include=`), used to fill in
|
|
468
|
+
* the featured-image thumbnails for the posts currently shown — without embedding media
|
|
469
|
+
* into the lean post listing. A core REST call — no companion plugin needed.
|
|
470
|
+
*/
|
|
471
|
+
async resolveMedia(ids) {
|
|
472
|
+
const clean = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
|
|
473
|
+
if (clean.length === 0) {
|
|
474
|
+
return [];
|
|
475
|
+
}
|
|
476
|
+
const out = [];
|
|
477
|
+
for (let i = 0; i < clean.length; i += 100) {
|
|
478
|
+
const chunk = clean.slice(i, i + 100);
|
|
479
|
+
const query = new URLSearchParams({
|
|
480
|
+
include: chunk.join(","),
|
|
481
|
+
per_page: String(chunk.length)
|
|
482
|
+
});
|
|
483
|
+
const raw = await this.request(`/wp/v2/media?${query.toString()}`);
|
|
484
|
+
if (Array.isArray(raw)) {
|
|
485
|
+
out.push(...raw.map(normalizeMedia));
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
416
490
|
};
|
|
417
491
|
function buildUpdateBody(fields) {
|
|
418
492
|
const body = {};
|
|
@@ -425,6 +499,9 @@ function buildUpdateBody(fields) {
|
|
|
425
499
|
if (fields.status !== void 0) {
|
|
426
500
|
body.status = fields.status;
|
|
427
501
|
}
|
|
502
|
+
if (fields.featuredMedia !== void 0) {
|
|
503
|
+
body.featured_media = fields.featuredMedia;
|
|
504
|
+
}
|
|
428
505
|
return body;
|
|
429
506
|
}
|
|
430
507
|
function assertRouteSegment(segment) {
|
|
@@ -466,6 +543,62 @@ function sanitizeMetaKeys(keys) {
|
|
|
466
543
|
function hasConnectorNamespace(namespaces) {
|
|
467
544
|
return Array.isArray(namespaces) && namespaces.includes(CONNECTOR_NAMESPACE);
|
|
468
545
|
}
|
|
546
|
+
function buildContentDisposition(filename) {
|
|
547
|
+
const base = filename.split(/[/\\]/).pop() ?? filename;
|
|
548
|
+
const trimmed = base.replace(/[\r\n"]/g, "").trim() || "upload";
|
|
549
|
+
const ascii = trimmed.replace(/[^\x20-\x7e]/g, "_");
|
|
550
|
+
const encoded = encodeURIComponent(trimmed).replace(
|
|
551
|
+
/['()*!]/g,
|
|
552
|
+
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
|
|
553
|
+
);
|
|
554
|
+
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`;
|
|
555
|
+
}
|
|
556
|
+
function parseTotalPages(header) {
|
|
557
|
+
if (header === null) {
|
|
558
|
+
return 1;
|
|
559
|
+
}
|
|
560
|
+
const n = Number.parseInt(header, 10);
|
|
561
|
+
return Number.isFinite(n) && n > 0 ? n : 1;
|
|
562
|
+
}
|
|
563
|
+
function extractRendered(value) {
|
|
564
|
+
if (value !== null && typeof value === "object") {
|
|
565
|
+
const rendered = value.rendered;
|
|
566
|
+
if (typeof rendered === "string") {
|
|
567
|
+
return rendered;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return "";
|
|
571
|
+
}
|
|
572
|
+
function extractThumbnailUrl(mediaDetails) {
|
|
573
|
+
if (mediaDetails === null || typeof mediaDetails !== "object") {
|
|
574
|
+
return "";
|
|
575
|
+
}
|
|
576
|
+
const sizes = mediaDetails.sizes;
|
|
577
|
+
if (sizes === null || typeof sizes !== "object") {
|
|
578
|
+
return "";
|
|
579
|
+
}
|
|
580
|
+
for (const sizeName of ["thumbnail", "medium"]) {
|
|
581
|
+
const size = sizes[sizeName];
|
|
582
|
+
if (size !== null && typeof size === "object") {
|
|
583
|
+
const url = size.source_url;
|
|
584
|
+
if (typeof url === "string") {
|
|
585
|
+
return url;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return "";
|
|
590
|
+
}
|
|
591
|
+
function normalizeMedia(raw) {
|
|
592
|
+
const obj = typeof raw === "object" && raw !== null ? raw : {};
|
|
593
|
+
const sourceUrl = typeof obj.source_url === "string" ? obj.source_url : "";
|
|
594
|
+
return {
|
|
595
|
+
id: typeof obj.id === "number" ? obj.id : 0,
|
|
596
|
+
sourceUrl,
|
|
597
|
+
thumbnailUrl: extractThumbnailUrl(obj.media_details) || sourceUrl,
|
|
598
|
+
title: extractRendered(obj.title),
|
|
599
|
+
mimeType: typeof obj.mime_type === "string" ? obj.mime_type : ""
|
|
600
|
+
};
|
|
601
|
+
}
|
|
469
602
|
function normalizePostTypes(raw) {
|
|
470
603
|
if (typeof raw !== "object" || raw === null) {
|
|
471
604
|
return [];
|
|
@@ -499,6 +632,9 @@ function normalizePost(raw) {
|
|
|
499
632
|
if (raw.dbp_wp_meta !== void 0) {
|
|
500
633
|
post.dbpWpMeta = raw.dbp_wp_meta;
|
|
501
634
|
}
|
|
635
|
+
if (typeof raw.featured_media === "number" && raw.featured_media > 0) {
|
|
636
|
+
post.featuredMedia = raw.featured_media;
|
|
637
|
+
}
|
|
502
638
|
const rawParent = raw.meta?.[PARENT_META_KEY];
|
|
503
639
|
const rawParentType = raw.meta?.[PARENT_TYPE_META_KEY];
|
|
504
640
|
if (typeof rawParent === "number" && Number.isInteger(rawParent) && rawParent > 0 && typeof rawParentType === "string" && rawParentType !== "") {
|
|
@@ -718,11 +854,13 @@ export {
|
|
|
718
854
|
assertValidRelation,
|
|
719
855
|
buildAuthHeader,
|
|
720
856
|
buildClearRelationMeta,
|
|
857
|
+
buildContentDisposition,
|
|
721
858
|
buildImportPlan,
|
|
722
859
|
buildPrintRecord,
|
|
723
860
|
buildSetRelationMeta,
|
|
724
861
|
deriveChildren,
|
|
725
862
|
getRelation,
|
|
863
|
+
normalizeMedia,
|
|
726
864
|
normalizeSiteUrl,
|
|
727
865
|
normalizeStatus,
|
|
728
866
|
parseCsv,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/print.ts","../src/relation.ts","../src/wp-client.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: PrintRecord;\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\nfunction renderNodes(nodes: TemplateNode[], scope: Scope): 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 = resolve(node.path, scope);\n out += node.raw ? stringifyScalar(value) : escapeHtml(stringifyScalar(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 });\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 });\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 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","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 ListPostsParams,\n UpdatePostFields,\n WpCredentials,\n WpPost,\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/** 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 private async request<T>(path: string, init: RequestInit = {}): Promise<T> {\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 (await response.json()) as 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 * 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/** 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 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 * 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 // 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","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,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AAM,GAAG,MAAM,QAAQ,QAAQ,OAAO,GAAG;AAChD,YAAM,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":["ROUTE_SEGMENT"]}
|
|
1
|
+
{"version":3,"sources":["../src/print.ts","../src/relation.ts","../src/wp-client.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: PrintRecord;\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\nfunction renderNodes(nodes: TemplateNode[], scope: Scope): 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 = resolve(node.path, scope);\n out += node.raw ? stringifyScalar(value) : escapeHtml(stringifyScalar(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 });\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 });\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 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","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 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/** 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 * 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 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","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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