@ajsmonty/adobe-mcp 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ // Asset tools (what people use Adobe Bridge for): batch rename + XMP metadata.
2
+ // Ported from the Barrows line of adobe-mcp (contributions by Derrin Byrne).
3
+ // Renaming is done directly on disk. Metadata uses Adobe's XMP library inside whichever
4
+ // Adobe app is already open (Photoshop, Illustrator, InDesign or After Effects).
5
+ import { z } from "zod";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { runJSX } from "../core/bridge.mjs";
9
+ import { lit, esPath, walk, runningApps } from "../core/helpers.mjs";
10
+
11
+ const XMP_LIB = `
12
+ if (ExternalObject.AdobeXMPScript == undefined) ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
13
+ var NS = XMPConst.NS_DC;
14
+ function arr(x, prop) { var o = []; var n = x.countArrayItems(NS, prop); for (var i = 1; i <= n; i++) o.push(String(x.getArrayItem(NS, prop, i))); return o; }
15
+ function loc(x, prop) { try { var v = x.getLocalizedText(NS, prop, null, 'x-default'); return v ? String(v) : ''; } catch (e) { return ''; } }
16
+ function readMeta(p) {
17
+ var xf = new XMPFile(p, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_READ), x = xf.getXMP(); xf.closeFile();
18
+ if (!x) return { file: p, title: '', description: '', keywords: [], creator: [], copyright: '' };
19
+ return { file: p, title: loc(x, 'title'), description: loc(x, 'description'), keywords: arr(x, 'subject'), creator: arr(x, 'creator'), copyright: loc(x, 'rights') };
20
+ }
21
+ `;
22
+
23
+ async function pickHost(host) {
24
+ if (host) return host;
25
+ const open = await runningApps();
26
+ for (const k of ["ps", "ai", "id", "ae"]) if (open[k]) return k;
27
+ throw new Error("Metadata needs one of Photoshop, Illustrator, InDesign or After Effects to be open (it uses their XMP library). Open one and try again.");
28
+ }
29
+
30
+ function collect(files, folder, recursive, exts) {
31
+ let out = [...(files || [])];
32
+ if (folder) {
33
+ const re = exts?.length ? new RegExp(`\\.(${exts.map((e) => e.replace(/^\./, "")).join("|")})$`, "i") : null;
34
+ out = out.concat(walk(folder, { maxDepth: recursive ? 10 : 0, filter: (f) => !re || re.test(f) }));
35
+ }
36
+ return out;
37
+ }
38
+
39
+ export function register(server, { text, errText }) {
40
+ server.registerTool(
41
+ "assets_batch_rename",
42
+ {
43
+ title: "Batch rename files",
44
+ description:
45
+ "Rename many files using a pattern, like Adobe Bridge's Batch Rename. Tokens: {name} original name, " +
46
+ "{n} counter (pad with {n:3}), {ext} extension, {parent} folder name, {date} YYYY-MM-DD (file modified), " +
47
+ "plus find/replace (regex). dry_run (default true) shows the before/after list; set false to rename. " +
48
+ "Never overwrites an existing file.",
49
+ inputSchema: {
50
+ folder: z.string().optional(),
51
+ files: z.array(z.string()).optional(),
52
+ extensions: z.array(z.string()).optional().describe("Only these extensions, e.g. ['jpg','png']."),
53
+ recursive: z.boolean().optional(),
54
+ pattern: z.string().optional().describe("New name pattern, default '{name}'. Example: 'XMAS26_{parent}_{n:3}'."),
55
+ find: z.string().optional().describe("Regex to find in the name (applied before the pattern)."),
56
+ replace: z.string().optional(),
57
+ case: z.enum(["keep", "lower", "upper"]).optional(),
58
+ start_number: z.number().int().optional(),
59
+ dry_run: z.boolean().optional(),
60
+ },
61
+ },
62
+ async (a) => {
63
+ try {
64
+ const list = collect(a.files, a.folder, a.recursive, a.extensions).sort((x, y) => x.localeCompare(y, undefined, { numeric: true }));
65
+ if (!list.length) throw new Error("No files matched.");
66
+ let n = a.start_number ?? 1;
67
+ const re = a.find ? new RegExp(a.find, "g") : null;
68
+ const plan = list.map((f) => {
69
+ const ext = path.extname(f), dir = path.dirname(f);
70
+ let name = path.basename(f, ext);
71
+ if (re) name = name.replace(re, a.replace ?? "");
72
+ const st = fs.statSync(f);
73
+ let out = (a.pattern || "{name}")
74
+ .replace(/\{name\}/g, name)
75
+ .replace(/\{parent\}/g, path.basename(dir))
76
+ .replace(/\{date\}/g, st.mtime.toISOString().slice(0, 10))
77
+ .replace(/\{ext\}/g, ext.slice(1))
78
+ .replace(/\{n(?::(\d+))?\}/g, (_, w) => String(n).padStart(Number(w || 0), "0"));
79
+ n++;
80
+ if (a.case === "lower") out = out.toLowerCase();
81
+ if (a.case === "upper") out = out.toUpperCase();
82
+ out = out.replace(/[\\/:*?"<>|]/g, "_");
83
+ return { from: f, to: path.join(dir, out + ext.toLowerCase()) };
84
+ });
85
+ const targets = new Set(), problems = [];
86
+ for (const p of plan) {
87
+ const key = p.to.toLowerCase();
88
+ if (targets.has(key)) problems.push(`Two files would both become ${path.basename(p.to)}`);
89
+ targets.add(key);
90
+ if (p.to.toLowerCase() !== p.from.toLowerCase() && fs.existsSync(p.to) && !plan.some((q) => q.from.toLowerCase() === key))
91
+ problems.push(`${path.basename(p.to)} already exists`);
92
+ }
93
+ const changes = plan.filter((p) => p.from !== p.to);
94
+ if (a.dry_run !== false || problems.length)
95
+ return text({ dry_run: true, files: plan.length, would_rename: changes.length, problems,
96
+ preview: changes.slice(0, 100).map((p) => `${path.basename(p.from)} → ${path.basename(p.to)}`),
97
+ note: problems.length ? "Fix the problems before renaming." : "Run again with dry_run: false to rename." });
98
+ // two-phase rename so swaps/collisions inside the batch are safe
99
+ const temps = changes.map((p, i) => {
100
+ const t = path.join(path.dirname(p.from), `.__rename_${process.pid}_${i}`);
101
+ fs.renameSync(p.from, t);
102
+ return { ...p, t };
103
+ });
104
+ for (const p of temps) fs.renameSync(p.t, p.to);
105
+ return text({ renamed: temps.length });
106
+ } catch (e) {
107
+ return errText(e);
108
+ }
109
+ }
110
+ );
111
+
112
+ server.registerTool(
113
+ "assets_read_metadata",
114
+ {
115
+ title: "Read file metadata (XMP)",
116
+ description:
117
+ "Read title, description, keywords, creator and copyright from images, PDFs, videos and Adobe files. " +
118
+ "Uses Adobe's XMP library inside an open Adobe app (Photoshop, Illustrator, InDesign or After Effects).",
119
+ inputSchema: {
120
+ files: z.array(z.string()).optional(),
121
+ folder: z.string().optional(),
122
+ extensions: z.array(z.string()).optional(),
123
+ host: z.enum(["ps", "ai", "id", "ae"]).optional().describe("Which open app to use (default: first one open)."),
124
+ },
125
+ },
126
+ async (a) => {
127
+ try {
128
+ const list = collect(a.files, a.folder, false, a.extensions).slice(0, 500);
129
+ if (!list.length) throw new Error("No files.");
130
+ const host = await pickHost(a.host);
131
+ const jsx = `${XMP_LIB}
132
+ var fs = ${lit(list.map(esPath))}, out = [];
133
+ for (var i = 0; i < fs.length; i++) { try { out.push(readMeta(new File(fs[i]).fsName)); } catch (e) { out.push({ file: fs[i], error: String(e) }); } }
134
+ return out;`;
135
+ return text({ via: host, files: await runJSX(host, jsx, 300000) });
136
+ } catch (e) {
137
+ return errText(e);
138
+ }
139
+ }
140
+ );
141
+
142
+ server.registerTool(
143
+ "assets_write_metadata",
144
+ {
145
+ title: "Write file metadata (XMP)",
146
+ description:
147
+ "Set title, description, keywords (replace or add), creator and copyright on many files at once — " +
148
+ "e.g. tag a campaign's assets. Only fields you pass are changed. Uses an open Adobe app's XMP library. " +
149
+ "Files open in an Adobe app should be closed first.",
150
+ inputSchema: {
151
+ files: z.array(z.string()).optional(),
152
+ folder: z.string().optional(),
153
+ extensions: z.array(z.string()).optional(),
154
+ title: z.string().optional(),
155
+ description: z.string().optional(),
156
+ keywords: z.array(z.string()).optional(),
157
+ keyword_mode: z.enum(["add", "replace"]).optional().describe("Default add."),
158
+ creator: z.string().optional(),
159
+ copyright: z.string().optional(),
160
+ host: z.enum(["ps", "ai", "id", "ae"]).optional(),
161
+ },
162
+ },
163
+ async (a) => {
164
+ try {
165
+ const list = collect(a.files, a.folder, false, a.extensions).slice(0, 2000);
166
+ if (!list.length) throw new Error("No files.");
167
+ const host = await pickHost(a.host);
168
+ const set = { title: a.title ?? null, description: a.description ?? null, keywords: a.keywords ?? null,
169
+ mode: a.keyword_mode || "add", creator: a.creator ?? null, copyright: a.copyright ?? null };
170
+ const jsx = `${XMP_LIB}
171
+ var fs = ${lit(list.map(esPath))}, S = ${lit(set)}, ok = 0, failed = [];
172
+ for (var i = 0; i < fs.length; i++) {
173
+ try {
174
+ var xf = new XMPFile(new File(fs[i]).fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_UPDATE), x = xf.getXMP() || new XMPMeta();
175
+ if (S.title !== null) x.setLocalizedText(NS, 'title', null, 'x-default', S.title);
176
+ if (S.description !== null) x.setLocalizedText(NS, 'description', null, 'x-default', S.description);
177
+ if (S.copyright !== null) x.setLocalizedText(NS, 'rights', null, 'x-default', S.copyright);
178
+ if (S.creator !== null) { x.deleteProperty(NS, 'creator'); x.appendArrayItem(NS, 'creator', S.creator, 0, XMPConst.ARRAY_IS_ORDERED); }
179
+ if (S.keywords !== null) {
180
+ var have = {}; if (S.mode === 'replace') x.deleteProperty(NS, 'subject'); else { var cur = arr(x, 'subject'); for (var c = 0; c < cur.length; c++) have[cur[c]] = 1; }
181
+ for (var k = 0; k < S.keywords.length; k++) if (!have[S.keywords[k]]) { x.appendArrayItem(NS, 'subject', S.keywords[k], 0, XMPConst.ARRAY_IS_UNORDERED); have[S.keywords[k]] = 1; }
182
+ }
183
+ if (xf.canPutXMP(x)) { xf.putXMP(x); xf.closeFile(XMPConst.CLOSE_UPDATE_SAFELY); ok++; }
184
+ else { xf.closeFile(); failed.push(fs[i] + ': this file type cannot hold XMP'); }
185
+ } catch (e) { failed.push(fs[i] + ': ' + e); }
186
+ }
187
+ return { updated: ok, failed: failed };`;
188
+ return text({ via: host, ...(await runJSX(host, jsx, 600000)) });
189
+ } catch (e) {
190
+ return errText(e);
191
+ }
192
+ }
193
+ );
194
+ }
@@ -0,0 +1,250 @@
1
+ // InDesign adapter (ExtendScript via AppleScript `do script` on macOS, COM DoScript on Windows).
2
+ // Ported from the Barrows line of adobe-mcp (contributions by Derrin Byrne).
3
+ import { z } from "zod";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { runJSX, downscalePng } from "../core/bridge.mjs";
8
+ import { lit, esPath } from "../core/helpers.mjs";
9
+
10
+ const ID_LIB = `
11
+ var __uil = app.scriptPreferences.userInteractionLevel;
12
+ app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
13
+ function restoreUI() { app.scriptPreferences.userInteractionLevel = __uil; }
14
+ function docFor(p) {
15
+ if (p) {
16
+ var f = new File(p);
17
+ for (var i = 0; i < app.documents.length; i++) if (app.documents[i].saved && app.documents[i].fullName.fsName === f.fsName) return app.documents[i];
18
+ if (!f.exists) throw new Error('File not found: ' + p);
19
+ return app.open(f);
20
+ }
21
+ if (!app.documents.length) throw new Error('No InDesign document is open.');
22
+ return app.activeDocument;
23
+ }
24
+ `;
25
+
26
+ export function register(server, { text, errText, registerAsset }) {
27
+ server.registerTool(
28
+ "id_run_extendscript",
29
+ {
30
+ title: "Run ExtendScript in InDesign",
31
+ description:
32
+ "Execute ExtendScript (JSX) inside InDesign and return the result. Runs as a function body: end with " +
33
+ "`return <value>`. ES3 only. Key DOM: app.documents, activeDocument.pages, textFrames, allPageItems, " +
34
+ "paragraphStyles, links, exportFile(ExportFormat.PDF_TYPE, file, false, preset). Measurements use the " +
35
+ "document's units (viewPreferences). Set app.scriptPreferences.userInteractionLevel to NEVER_INTERACT to avoid dialogs.",
36
+ inputSchema: {
37
+ code: z.string().describe("ExtendScript function body."),
38
+ timeout_seconds: z.number().optional().describe("Max seconds (default 120)."),
39
+ },
40
+ },
41
+ async ({ code, timeout_seconds }) => {
42
+ try {
43
+ const r = await runJSX("id", code, (timeout_seconds ?? 120) * 1000);
44
+ return text({ ok: true, result: r === undefined ? null : r });
45
+ } catch (e) {
46
+ return errText(e);
47
+ }
48
+ }
49
+ );
50
+
51
+ server.registerTool(
52
+ "id_get_state",
53
+ {
54
+ title: "Inspect open InDesign documents",
55
+ description:
56
+ "Lists open documents; for the active one returns pages, size, layers, named text frames with a preview " +
57
+ "of their text, paragraph styles, links (flagging missing/modified), missing fonts and data-merge fields.",
58
+ inputSchema: {},
59
+ },
60
+ async () => {
61
+ try {
62
+ const jsx = `
63
+ var out = { documents: [], active: null };
64
+ for (var i = 0; i < app.documents.length; i++) out.documents.push(app.documents[i].name);
65
+ if (app.documents.length) {
66
+ var d = app.activeDocument, a = { name: d.name, pages: d.pages.length, width: d.documentPreferences.pageWidth,
67
+ height: d.documentPreferences.pageHeight, units: String(d.viewPreferences.horizontalMeasurementUnits), layers: [], text_frames: [],
68
+ paragraph_styles: [], links: [], missing_fonts: [], merge_fields: [] };
69
+ for (var l = 0; l < d.layers.length; l++) a.layers.push(d.layers[l].name);
70
+ var tfs = d.textFrames;
71
+ for (var t = 0; t < tfs.length && t < 200; t++) { var tf = tfs[t];
72
+ var pg = null; try { pg = tf.parentPage ? tf.parentPage.name : null; } catch (e) {}
73
+ a.text_frames.push({ name: tf.name || tf.label || '', page: pg, text: String(tf.contents).substr(0, 80) }); }
74
+ for (var s = 0; s < d.paragraphStyles.length; s++) a.paragraph_styles.push(d.paragraphStyles[s].name);
75
+ for (var k = 0; k < d.links.length && k < 300; k++) { var L = d.links[k];
76
+ a.links.push({ name: L.name, status: L.status == LinkStatus.LINK_MISSING ? 'missing' : (L.status == LinkStatus.LINK_OUT_OF_DATE ? 'modified' : 'ok') }); }
77
+ for (var f = 0; f < d.fonts.length; f++) if (d.fonts[f].status != FontStatus.INSTALLED) a.missing_fonts.push(d.fonts[f].name);
78
+ try { var flds = d.dataMergeProperties.dataMergeFields; for (var m = 0; m < flds.length; m++) a.merge_fields.push(flds[m].fieldName); } catch (e) {}
79
+ out.active = a;
80
+ }
81
+ return out;`;
82
+ return text(await runJSX("id", jsx, 120000));
83
+ } catch (e) {
84
+ return errText(e);
85
+ }
86
+ }
87
+ );
88
+
89
+ server.registerTool(
90
+ "id_fill_text",
91
+ {
92
+ title: "Fill named text frames in InDesign",
93
+ description:
94
+ "Set the text of frames by their name (Layers panel) or script label in the active document (or a given " +
95
+ "file). Keeps the frame's formatting. Unmatched names are reported with the available frame names.",
96
+ inputSchema: {
97
+ fields: z.record(z.string()).describe("{ frameName: newText }"),
98
+ document_path: z.string().optional().describe("Open this file instead of using the active document."),
99
+ save: z.boolean().optional().describe("Save the document afterwards (default false)."),
100
+ },
101
+ },
102
+ async ({ fields, document_path, save }) => {
103
+ try {
104
+ const jsx = `${ID_LIB}
105
+ try {
106
+ var d = docFor(${lit(document_path ? esPath(document_path) : null)}), fields = ${lit(fields)}, set = [], missing = [], names = [];
107
+ var items = d.allPageItems;
108
+ for (var key in fields) {
109
+ var hit = 0;
110
+ for (var i = 0; i < items.length; i++) { var it = items[i];
111
+ if (it.constructor.name === 'TextFrame' && (it.name === key || it.label === key)) { it.contents = fields[key]; hit++; } }
112
+ if (hit) set.push(key); else missing.push(key);
113
+ }
114
+ if (missing.length) for (var j = 0; j < items.length; j++) if (items[j].constructor.name === 'TextFrame' && (items[j].name || items[j].label)) names.push(items[j].name || items[j].label);
115
+ var over = 0; for (var o = 0; o < d.textFrames.length; o++) if (d.textFrames[o].overflows) over++;
116
+ if (${lit(!!save)}) d.save();
117
+ return { document: d.name, set: set, not_found: missing, available_frame_names: names, frames_with_overset_text: over };
118
+ } finally { restoreUI(); }`;
119
+ return text(await runJSX("id", jsx, 120000));
120
+ } catch (e) {
121
+ return errText(e);
122
+ }
123
+ }
124
+ );
125
+
126
+ server.registerTool(
127
+ "id_export",
128
+ {
129
+ title: "Export an InDesign document",
130
+ description:
131
+ "Export the active document (or a given file) to PDF (with a named PDF preset such as '[High Quality " +
132
+ "Print]' or '[Press Quality]'), PNG or JPG. Page ranges like '1-3,5'. PNG/JPG export one file per page.",
133
+ inputSchema: {
134
+ output_path: z.string().describe("Absolute path; extension chooses the format (.pdf/.png/.jpg)."),
135
+ document_path: z.string().optional(),
136
+ pdf_preset: z.string().optional().describe("Default '[High Quality Print]'."),
137
+ pages: z.string().optional().describe("Page range, default all."),
138
+ resolution: z.number().optional().describe("PNG/JPG ppi (default 150)."),
139
+ },
140
+ },
141
+ async (a) => {
142
+ try {
143
+ const ext = path.extname(a.output_path).toLowerCase();
144
+ const jsx = `${ID_LIB}
145
+ try {
146
+ var d = docFor(${lit(a.document_path ? esPath(a.document_path) : null)}), f = new File(${lit(esPath(a.output_path))}), ext = ${lit(ext)};
147
+ new Folder(f.parent.fsName).create();
148
+ var range = ${lit(a.pages || null)};
149
+ if (ext === '.pdf') {
150
+ var pname = ${lit(a.pdf_preset || "[High Quality Print]")}, preset = app.pdfExportPresets.itemByName(pname);
151
+ if (!preset.isValid) { var names = []; for (var i = 0; i < app.pdfExportPresets.length; i++) names.push(app.pdfExportPresets[i].name);
152
+ throw new Error('PDF preset "' + pname + '" not found. Presets: ' + names.join(', ')); }
153
+ app.pdfExportPreferences.pageRange = range ? range : PageRange.ALL_PAGES;
154
+ d.exportFile(ExportFormat.PDF_TYPE, f, false, preset);
155
+ } else if (ext === '.png') {
156
+ var pp = app.pngExportPreferences; pp.exportResolution = ${lit(a.resolution ?? 150)};
157
+ pp.pngExportRange = range ? PNGExportRangeEnum.EXPORT_RANGE : PNGExportRangeEnum.EXPORT_ALL; if (range) pp.pageString = range;
158
+ d.exportFile(ExportFormat.PNG_FORMAT, f, false);
159
+ } else if (ext === '.jpg' || ext === '.jpeg') {
160
+ var jp = app.jpegExportPreferences; jp.exportResolution = ${lit(a.resolution ?? 150)}; jp.jpegQuality = JPEGOptionsQuality.MAXIMUM;
161
+ jp.jpegExportRange = range ? ExportRangeOrAllPages.EXPORT_RANGE : ExportRangeOrAllPages.EXPORT_ALL; if (range) jp.pageString = range;
162
+ d.exportFile(ExportFormat.JPG, f, false);
163
+ } else throw new Error('Use .pdf, .png or .jpg');
164
+ return { document: d.name, output: f.fsName };
165
+ } finally { restoreUI(); }`;
166
+ const r = await runJSX("id", jsx, 600000);
167
+ registerAsset?.({ app: "id", kind: ext.slice(1), path: a.output_path, meta: { doc: r.document } });
168
+ return text(r);
169
+ } catch (e) {
170
+ return errText(e);
171
+ }
172
+ }
173
+ );
174
+
175
+ server.registerTool(
176
+ "id_save_preview",
177
+ {
178
+ title: "Preview an InDesign page",
179
+ description: "Render one page of the active document as an image and return it inline, so Claude can see the layout.",
180
+ inputSchema: {
181
+ page: z.string().optional().describe("Page name/number (default 1)."),
182
+ max_width: z.number().optional().describe("Max preview width in px (default 1024)."),
183
+ },
184
+ },
185
+ async ({ page, max_width }) => {
186
+ try {
187
+ const pngPath = path.join(os.tmpdir(), `adobe_mcp_id_preview_${Date.now()}.png`);
188
+ const jsx = `${ID_LIB}
189
+ try {
190
+ var d = docFor(null), pp = app.pngExportPreferences;
191
+ pp.exportResolution = 96; pp.pngExportRange = PNGExportRangeEnum.EXPORT_RANGE; pp.pageString = ${lit(page || "1")};
192
+ d.exportFile(ExportFormat.PNG_FORMAT, new File(${lit(esPath(pngPath))}), false);
193
+ return { document: d.name, page: ${lit(page || "1")}, pages: d.pages.length };
194
+ } finally { restoreUI(); }`;
195
+ const meta = await runJSX("id", jsx, 180000);
196
+ if (!fs.existsSync(pngPath)) throw new Error("Preview image was not written.");
197
+ await downscalePng(pngPath, max_width ?? 1024);
198
+ const data = fs.readFileSync(pngPath).toString("base64");
199
+ fs.rmSync(pngPath, { force: true });
200
+ return { content: [{ type: "text", text: JSON.stringify(meta) }, { type: "image", data, mimeType: "image/png" }] };
201
+ } catch (e) {
202
+ return errText(e);
203
+ }
204
+ }
205
+ );
206
+
207
+ server.registerTool(
208
+ "id_data_merge",
209
+ {
210
+ title: "Run an InDesign data merge",
211
+ description:
212
+ "Run InDesign's built-in Data Merge on a template that already has merge fields placed (see id_get_state " +
213
+ "→ merge_fields) using a CSV/TXT data file, then export the merged result as a PDF. The template is not changed.",
214
+ inputSchema: {
215
+ template: z.string().describe("Absolute path to the .indd template."),
216
+ data_path: z.string().describe("CSV (comma) or TXT (tab) data file; headers must match the template's fields."),
217
+ output_pdf: z.string(),
218
+ pdf_preset: z.string().optional(),
219
+ },
220
+ },
221
+ async (a) => {
222
+ try {
223
+ const jsx = `${ID_LIB}
224
+ try {
225
+ var tpl = app.open(new File(${lit(esPath(a.template))})), merged;
226
+ try {
227
+ tpl.dataMergeProperties.selectDataSource(new File(${lit(esPath(a.data_path))}));
228
+ tpl.dataMergeProperties.mergeRecords();
229
+ merged = app.activeDocument;
230
+ var preset = app.pdfExportPresets.itemByName(${lit(a.pdf_preset || "[High Quality Print]")});
231
+ if (!preset.isValid) preset = app.pdfExportPresets[0];
232
+ app.pdfExportPreferences.pageRange = PageRange.ALL_PAGES;
233
+ var out = new File(${lit(esPath(a.output_pdf))}); new Folder(out.parent.fsName).create();
234
+ merged.exportFile(ExportFormat.PDF_TYPE, out, false, preset);
235
+ var pages = merged.pages.length;
236
+ } finally {
237
+ if (merged && merged !== tpl) merged.close(SaveOptions.NO);
238
+ tpl.close(SaveOptions.NO);
239
+ }
240
+ return { output: out.fsName, pages: pages };
241
+ } finally { restoreUI(); }`;
242
+ const r = await runJSX("id", jsx, 1200000);
243
+ registerAsset?.({ app: "id", kind: "pdf", path: a.output_pdf, meta: { merge: a.data_path } });
244
+ return text(r);
245
+ } catch (e) {
246
+ return errText(e);
247
+ }
248
+ }
249
+ );
250
+ }