previewer-agency 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -12
- package/bin/previewer.mjs +123 -12
- package/lib/api.mjs +48 -0
- package/lib/destination.mjs +14 -0
- package/lib/mcp.mjs +200 -8
- package/lib/tasks.mjs +121 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# previewer
|
|
2
2
|
|
|
3
3
|
Upload HTML5 banners, images and videos to [Previewer](https://previewer.agency) from any folder,
|
|
4
|
-
whatever tool built them
|
|
4
|
+
whatever tool built them. See what the upload check found, generate the backup images, wait for your
|
|
5
|
+
client's approval and download the approved set, without opening the browser.
|
|
5
6
|
|
|
6
7
|
```bash
|
|
7
8
|
npx previewer-agency login
|
|
@@ -41,8 +42,9 @@ npx previewer-agency login
|
|
|
41
42
|
|
|
42
43
|
Opens your browser. Type the code your terminal shows and approve (it is never in the link, so nobody
|
|
43
44
|
can send you a link that signs them in). You get an email about it. Your computer
|
|
44
|
-
gets its own token: it can do what you can do in Previewer (owners and editors: upload,
|
|
45
|
-
campaigns, remove
|
|
45
|
+
gets its own token: it can do what you can do in Previewer (owners and editors: upload, generate
|
|
46
|
+
backups, create clients and campaigns, remove or hide banners, set a note or a preview password;
|
|
47
|
+
viewers: look and download), stops working if your access ends, and shows under
|
|
46
48
|
**API** in the admin, where an owner can revoke it. `previewer logout` revokes it yourself.
|
|
47
49
|
|
|
48
50
|
The token is saved in `~/.config/previewer/config.json`, readable only by you.
|
|
@@ -79,19 +81,47 @@ npx previewer-agency push ./dist
|
|
|
79
81
|
```
|
|
80
82
|
|
|
81
83
|
When it's done it prints the preview link and copies it to your clipboard. `--open` opens it.
|
|
82
|
-
`--dry-run` shows what would go up without uploading.
|
|
84
|
+
`--dry-run` shows what would go up, and to which client and campaign, without uploading.
|
|
85
|
+
|
|
86
|
+
After the upload, `push` lists what the [upload check](https://previewer.agency/docs/quality-checks)
|
|
87
|
+
found: a hard-coded link instead of a clickTag, a banner over the weight budget, a missing `ad.size`
|
|
88
|
+
tag. Fix it and push again; the same file name replaces the banner. `--backups` also generates the
|
|
89
|
+
backup image of every HTML5 banner that has none.
|
|
90
|
+
|
|
91
|
+
A `--client` you name has to own the campaign. In a folder linked to one client's campaign,
|
|
92
|
+
`push --client "Another client"` stops before anything is uploaded; add `--campaign` to say which
|
|
93
|
+
campaign of that client you mean.
|
|
83
94
|
|
|
84
95
|
## Check on it
|
|
85
96
|
|
|
86
97
|
```bash
|
|
87
|
-
npx previewer-agency status # approvals per banner, backups, when the client last looked
|
|
98
|
+
npx previewer-agency status # approvals per banner, backups, checks, when the client last looked
|
|
88
99
|
npx previewer-agency open # open the preview
|
|
89
100
|
npx previewer-agency campaigns # list campaigns (--client to narrow)
|
|
90
101
|
npx previewer-agency link # choose this folder's campaign without uploading
|
|
91
102
|
npx previewer-agency whoami
|
|
92
103
|
```
|
|
93
104
|
|
|
94
|
-
`--json` gives machine-readable output for `status`, `campaigns` and `whoami`.
|
|
105
|
+
`--json` gives machine-readable output for `status`, `wait`, `campaigns` and `whoami`.
|
|
106
|
+
|
|
107
|
+
## Backups, approval and hand-off
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
npx previewer-agency backups # generate the backup images that are missing
|
|
111
|
+
npx previewer-agency backups --all # make every one again
|
|
112
|
+
npx previewer-agency wait --timeout 240 # wait until your client approved everything
|
|
113
|
+
npx previewer-agency download ./handoff --approved
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- **`backups`** has Previewer play each HTML5 banner to its end frame and save it as a JPG within the
|
|
117
|
+
size limit, like **Generate backups** in the admin. One banner takes about as long as it plays.
|
|
118
|
+
- **`wait`** checks every 15 seconds and exits `0` once everything is approved, `2` when the time
|
|
119
|
+
is up (default 60 minutes), or `3` when there is nothing to wait for (the campaign doesn't ask for
|
|
120
|
+
approvals, or has nothing your client can approve). In a script: `previewer wait && previewer download ./handoff --approved`.
|
|
121
|
+
- **`download`** saves one ZIP with every creative and its backup image, laid out like **Download all**
|
|
122
|
+
in the admin. `--approved` leaves out what your client hasn't approved yet, and
|
|
123
|
+
anything you hid from the preview. If a ZIP with that name is already in the folder, the new one gets
|
|
124
|
+
a number: `… (2).zip`.
|
|
95
125
|
|
|
96
126
|
## In CI
|
|
97
127
|
|
|
@@ -99,7 +129,7 @@ Create a token under **API** in the admin (Upload access, narrowed to a client o
|
|
|
99
129
|
like), store it as a secret, and:
|
|
100
130
|
|
|
101
131
|
```bash
|
|
102
|
-
PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
|
|
132
|
+
PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42 --backups
|
|
103
133
|
```
|
|
104
134
|
|
|
105
135
|
`PREVIEWER_URL` points it at another Previewer address.
|
|
@@ -107,7 +137,8 @@ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
|
|
|
107
137
|
## With an AI agent
|
|
108
138
|
|
|
109
139
|
`previewer mcp` runs Previewer as an MCP server, so an agent like Claude Code or Cursor can upload,
|
|
110
|
-
|
|
140
|
+
read what the upload check found and fix it, generate backups, wait for approval, download the
|
|
141
|
+
approved set and set up a project for you. It uses the same sign-in as the command line; if this
|
|
111
142
|
computer isn't signed in yet, the agent starts the sign-in, and you type its code in your browser and approve.
|
|
112
143
|
|
|
113
144
|
Claude Code:
|
|
@@ -122,10 +153,28 @@ Cursor, Windsurf, Claude Desktop and others, in their MCP settings:
|
|
|
122
153
|
{ "mcpServers": { "previewer": { "command": "npx", "args": ["-y", "previewer-agency", "mcp"] } } }
|
|
123
154
|
```
|
|
124
155
|
|
|
125
|
-
Then ask things like "upload dist to the Acme spring campaign
|
|
126
|
-
are still waiting for approval?"
|
|
127
|
-
|
|
128
|
-
|
|
156
|
+
Then ask things like "upload dist to the Acme spring campaign, fix whatever the check complains about,
|
|
157
|
+
make the backups and give me the link", "which banners are still waiting for approval?" or "download
|
|
158
|
+
what's approved into ./handoff".
|
|
159
|
+
|
|
160
|
+
| Tool | What it does |
|
|
161
|
+
| --- | --- |
|
|
162
|
+
| `whoami`, `sign_in` | Which account this computer is signed in to; start a sign-in |
|
|
163
|
+
| `list_clients`, `list_campaigns` | What the token can reach |
|
|
164
|
+
| `get_campaign` | Preview link, approvals (with the name your client gave), backups, and what the upload check found per banner |
|
|
165
|
+
| `upload_folder` | Upload a folder; returns the preview link and what the check found in the uploaded banners |
|
|
166
|
+
| `generate_backups` | Generate the backup images that are missing (or all of them) |
|
|
167
|
+
| `wait_for_approval` | Wait for your client, up to about 45 seconds per call, and report where approvals stand |
|
|
168
|
+
| `download_campaign` | Save the creatives and backups as one ZIP, optionally only the approved ones |
|
|
169
|
+
| `create_client`, `create_campaign`, `link_folder` | Set up a client, a campaign, and the folder's link to it |
|
|
170
|
+
| `set_note` | The note at the top of the preview, for example what changed this round |
|
|
171
|
+
| `update_banner` | Hide a banner from the preview or show it again; put it in a group |
|
|
172
|
+
| `set_preview_password` | Put a password on a preview, or remove it |
|
|
173
|
+
| `remove_banner` | Remove one banner |
|
|
174
|
+
|
|
175
|
+
Approving is left to your client, in the preview: no tool can approve. Creating, changing and
|
|
176
|
+
removing need **Manage** access; uploading and generating backups need **Upload**; the rest works
|
|
177
|
+
with a read-only token.
|
|
129
178
|
|
|
130
179
|
To have an agent set up a project from scratch, point it at
|
|
131
180
|
[previewer.agency/llms.txt](https://previewer.agency/llms.txt).
|
|
@@ -140,6 +189,15 @@ const api = new PreviewerClient({ baseUrl: 'https://previewer.agency', token: pr
|
|
|
140
189
|
const { items } = await collectUploads('./dist');
|
|
141
190
|
const { campaign } = await api.upload(42, items);
|
|
142
191
|
console.log(campaign.previewUrl);
|
|
192
|
+
|
|
193
|
+
// What the upload check found, per banner:
|
|
194
|
+
for (const banner of campaign.banners) {
|
|
195
|
+
if (banner.checks?.status === 'fail') console.log(banner.label, banner.checks.items.filter((item) => item.status === 'fail'));
|
|
196
|
+
}
|
|
197
|
+
await api.generateBackup(42, '300x250');
|
|
143
198
|
```
|
|
144
199
|
|
|
200
|
+
Also on the client: `createClient`, `createCampaign`, `setNote`, `updateBanner`, `setPreviewPassword`,
|
|
201
|
+
`removeBanner` and `download`.
|
|
202
|
+
|
|
145
203
|
The API itself is documented at [previewer.agency/docs/api](https://previewer.agency/docs/api#tokens).
|
package/bin/previewer.mjs
CHANGED
|
@@ -9,9 +9,11 @@ import path from 'node:path';
|
|
|
9
9
|
import { createInterface } from 'node:readline/promises';
|
|
10
10
|
import { parseArgs } from 'node:util';
|
|
11
11
|
import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from '../lib/api.mjs';
|
|
12
|
+
import { clientMismatch } from '../lib/destination.mjs';
|
|
12
13
|
import { collectUploads } from '../lib/files.mjs';
|
|
13
14
|
import { createMcpServer, runStdio } from '../lib/mcp.mjs';
|
|
14
15
|
import { selectMenu } from '../lib/menu.mjs';
|
|
16
|
+
import { backupTargets, campaignProblems, generateBackups, saveDownload, waitForApproval } from '../lib/tasks.mjs';
|
|
15
17
|
import { DEFAULT_SITE, PROJECT_FILE, findProject, forgetSiteLogin, normalizeSite, resolveAuth, saveProject, saveSiteLogin } from '../lib/config.mjs';
|
|
16
18
|
|
|
17
19
|
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
@@ -39,7 +41,10 @@ const CMD = RAN_VIA_NPX ? 'npx previewer-agency' : 'previewer';
|
|
|
39
41
|
const COMMAND_HELP = [
|
|
40
42
|
['login', 'Sign in (opens the browser to approve)'],
|
|
41
43
|
['push [folder]', 'Upload a folder: ZIPs, banner folders, images, videos, backups'],
|
|
42
|
-
['status', "Approvals and views of this folder's campaign"],
|
|
44
|
+
['status', "Approvals, checks and views of this folder's campaign"],
|
|
45
|
+
['backups', 'Generate the backup images that are missing (--all: every one)'],
|
|
46
|
+
['wait', 'Wait until the client has approved everything (for scripts and CI)'],
|
|
47
|
+
['download [folder]', 'Save the creatives and backups as one ZIP (--approved: approved only)'],
|
|
43
48
|
['open', "Open the campaign's preview link"],
|
|
44
49
|
['link', 'Choose which campaign this folder publishes to'],
|
|
45
50
|
['campaigns', 'List campaigns'],
|
|
@@ -60,7 +65,11 @@ ${bold('Options')}
|
|
|
60
65
|
--create Create the campaign if it doesn't exist (push)
|
|
61
66
|
--dry-run Show what push would upload, upload nothing
|
|
62
67
|
--open Open the preview after push
|
|
63
|
-
--
|
|
68
|
+
--backups Generate missing backup images after push
|
|
69
|
+
--all Make every backup again, not only the missing ones (backups)
|
|
70
|
+
--approved Only what the client approved (download)
|
|
71
|
+
--timeout <minutes> How long wait keeps waiting (default 60; exits 2 when time is up)
|
|
72
|
+
--json Machine-readable output (status, wait, campaigns, whoami)
|
|
64
73
|
--site <url> Previewer address (default ${DEFAULT_SITE})
|
|
65
74
|
|
|
66
75
|
${bold('In CI')}
|
|
@@ -265,8 +274,23 @@ const resolveClient = async (api, wanted) => {
|
|
|
265
274
|
);
|
|
266
275
|
};
|
|
267
276
|
|
|
268
|
-
|
|
269
|
-
|
|
277
|
+
const MISMATCH_HINT = `Leave out --client, or name the campaign with --campaign (this folder's ${PROJECT_FILE} or the id points at another client's).`;
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* The campaign to work on, from flags, the folder's link, or (in a terminal) a picker. A client named
|
|
281
|
+
* with --client has to own it, however the campaign was found (the folder's link and a campaign id
|
|
282
|
+
* say nothing about the client).
|
|
283
|
+
*/
|
|
284
|
+
const resolveCampaign = async (api, options, project, settings = {}) => {
|
|
285
|
+
const found = await findCampaign(api, options, project, settings);
|
|
286
|
+
if (options.client) {
|
|
287
|
+
const mismatch = clientMismatch(found.campaign, await resolveClient(api, options.client));
|
|
288
|
+
if (mismatch) fail(mismatch, MISMATCH_HINT);
|
|
289
|
+
}
|
|
290
|
+
return found;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const findCampaign = async (api, options, project, { allowCreate = false } = {}) => {
|
|
270
294
|
if (options.campaign && /^\d+$/.test(options.campaign)) return { campaign: await api.campaign(Number(options.campaign)), fromFlags: true };
|
|
271
295
|
if (options.campaign) {
|
|
272
296
|
const clientId = options.client ? (await resolveClient(api, options.client)).id : project?.clientId;
|
|
@@ -361,14 +385,32 @@ async function push(options, folder = '.') {
|
|
|
361
385
|
if (options['dry-run']) {
|
|
362
386
|
say(`${bold('Would upload')} ${summary} (${kb(total)}):`);
|
|
363
387
|
for (const item of items) say(` ${dim(item.type.padEnd(6))} ${item.source}${item.source !== item.name ? dim(` → ${item.name}`) : ''} ${dim(kb(item.size))}`);
|
|
364
|
-
// Uploads nothing, but does say
|
|
388
|
+
// Uploads nothing, but does say where the real push would go and what it would stop on: a client
|
|
389
|
+
// that isn't there, or a campaign that isn't the named client's.
|
|
390
|
+
const linked = await findProject(process.cwd());
|
|
391
|
+
const auth = await resolveAuth({ site: options.site, project: linked });
|
|
392
|
+
if (!auth.token) return say('', dim(`Not signed in to ${auth.site}, so the client and campaign weren't checked.`));
|
|
393
|
+
const dry = new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` });
|
|
394
|
+
let client = null;
|
|
365
395
|
if (options.client) {
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (!known) say('', `${yellow('!')} No client "${options.client}" yet. Create it in the Previewer admin first; the campaign is created for you.`);
|
|
396
|
+
const clients = await dry.clients();
|
|
397
|
+
const known = /^\d+$/.test(String(options.client)) ? clients.some((item) => item.id === Number(options.client)) : matchName(clients, options.client).length > 0;
|
|
398
|
+
if (!known) return say('', `${yellow('!')} No client "${options.client}" yet. Create it in the Previewer admin first; the campaign is created for you.`);
|
|
399
|
+
client = await resolveClient(dry, options.client);
|
|
371
400
|
}
|
|
401
|
+
let campaign = null;
|
|
402
|
+
if (options.campaign && /^\d+$/.test(options.campaign)) campaign = await dry.campaign(Number(options.campaign));
|
|
403
|
+
else if (options.campaign) {
|
|
404
|
+
const clientId = client?.id ?? linked?.clientId;
|
|
405
|
+
const matches = matchName(await dry.campaigns(clientId ? { clientId } : {}), options.campaign);
|
|
406
|
+
if (matches.length > 1) return say('', `${yellow('!')} Several campaigns are called "${options.campaign}". Add --client, or use the campaign id.`);
|
|
407
|
+
if (matches.length === 0) return say('', `Campaign "${options.campaign}" doesn't exist yet${client ? ` for ${client.name}` : ''}: the push would ${options.create ? 'create it' : 'ask to create it (or add --create)'}.`);
|
|
408
|
+
campaign = matches[0];
|
|
409
|
+
} else if (linked?.campaignId) campaign = await dry.campaign(linked.campaignId);
|
|
410
|
+
else return say('', dim(`No campaign chosen yet: add --campaign <name|id>${client ? '' : ' (and --client <name>)'}.`));
|
|
411
|
+
const mismatch = clientMismatch(campaign, client);
|
|
412
|
+
if (mismatch) fail(mismatch, MISMATCH_HINT);
|
|
413
|
+
say('', `Would go to ${bold(`${campaign.client.name} → ${campaign.name}`)}.`);
|
|
372
414
|
return;
|
|
373
415
|
}
|
|
374
416
|
|
|
@@ -388,6 +430,8 @@ async function push(options, folder = '.') {
|
|
|
388
430
|
` The campaign now has ${result.campaign.bannerCount} banner${result.campaign.bannerCount === 1 ? '' : 's'}.`,
|
|
389
431
|
);
|
|
390
432
|
if (picked || created || !project) await rememberCampaign(auth.site, result.campaign, project);
|
|
433
|
+
printProblems(campaignProblems(result.campaign, result.uploaded));
|
|
434
|
+
if (options.backups) await makeBackups(api, result.campaign, backupTargets(result.campaign));
|
|
391
435
|
if (result.campaign.previewUrl) {
|
|
392
436
|
const copied = interactive && (await copyToClipboard(result.campaign.previewUrl));
|
|
393
437
|
say('', `${bold(result.campaign.previewUrl)}${copied ? dim(' (copied)') : ''}`);
|
|
@@ -395,6 +439,67 @@ async function push(options, folder = '.') {
|
|
|
395
439
|
}
|
|
396
440
|
}
|
|
397
441
|
|
|
442
|
+
// What the upload check found that needs a look, per banner. Says nothing when all is well.
|
|
443
|
+
const printProblems = (entries) => {
|
|
444
|
+
if (entries.length === 0) return;
|
|
445
|
+
say('', `${yellow('!')} The upload check found something in ${entries.length} banner${entries.length === 1 ? '' : 's'}:`);
|
|
446
|
+
for (const entry of entries) {
|
|
447
|
+
say(` ${bold(entry.label)}${entry.platform ? dim(` ${entry.platform}`) : ''}`);
|
|
448
|
+
for (const problem of entry.problems) say(` ${(problem.status === 'fail' ? red : yellow)(problem.status === 'fail' ? '✖' : '!')} ${problem.check}${problem.detail ? dim(`: ${problem.detail}`) : ''}`);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
const makeBackups = async (api, campaign, ids) => {
|
|
453
|
+
if (ids.length === 0) return say(dim('Every HTML5 banner already has a backup image.'));
|
|
454
|
+
say('', `Generating ${ids.length} backup image${ids.length === 1 ? '' : 's'} (each takes about as long as its banner plays)…`);
|
|
455
|
+
const result = await generateBackups(api, campaign.id, ids, {
|
|
456
|
+
onResult: (id, done, error) =>
|
|
457
|
+
say(error ? ` ${red('✖')} ${id}: ${error.message}` : done.generated ? ` ${green('✔')} ${id}${done.backupSizeBytes ? dim(` ${kb(done.backupSizeBytes)}`) : ''}` : ` ${dim('–')} ${id}${dim(' kept the backup uploaded meanwhile')}`),
|
|
458
|
+
});
|
|
459
|
+
if (result.failed.length) process.exitCode = 1;
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
async function backups(options) {
|
|
463
|
+
const project = await findProject(process.cwd());
|
|
464
|
+
const { client: api } = await clientFor(options, project);
|
|
465
|
+
const { campaign } = await resolveCampaign(api, options, project);
|
|
466
|
+
await makeBackups(api, campaign, backupTargets(campaign, { all: Boolean(options.all) }));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// For scripts: exits 0 once everything is approved, 2 when the time is up, 3 when the campaign has
|
|
470
|
+
// nothing to wait for (approvals off, or nothing the client can approve).
|
|
471
|
+
async function wait(options) {
|
|
472
|
+
const minutes = options.timeout === undefined ? 60 : Number(options.timeout);
|
|
473
|
+
if (!Number.isFinite(minutes) || minutes <= 0) fail('--timeout takes a number of minutes.');
|
|
474
|
+
const project = await findProject(process.cwd());
|
|
475
|
+
const { client: api } = await clientFor(options, project);
|
|
476
|
+
const { campaign } = await resolveCampaign(api, options, project);
|
|
477
|
+
if (!options.json) say(`Waiting for approval of ${bold(`${campaign.client.name} → ${campaign.name}`)} (up to ${minutes} min)…`);
|
|
478
|
+
let last = -1;
|
|
479
|
+
const result = await waitForApproval(api, campaign.id, {
|
|
480
|
+
timeoutMs: minutes * 60_000,
|
|
481
|
+
intervalMs: 15_000,
|
|
482
|
+
onTick: (state) => {
|
|
483
|
+
if (!options.json && state.approved !== last && last !== -1) say(dim(` ${state.approved}/${state.total} approved`));
|
|
484
|
+
last = state.approved;
|
|
485
|
+
},
|
|
486
|
+
});
|
|
487
|
+
if (options.json) say(JSON.stringify(result, null, 2));
|
|
488
|
+
else if (result.reason === 'all_approved') say(`${green('✔')} All ${result.total} approved.`);
|
|
489
|
+
else if (result.reason === 'timeout') say(`${yellow('!')} Still waiting: ${result.approved}/${result.total} approved.`);
|
|
490
|
+
else say(dim(result.reason === 'approvals_off' ? "This campaign doesn't ask for approvals." : 'Nothing in this campaign can be approved.'));
|
|
491
|
+
if (result.reason === 'timeout') process.exitCode = 2;
|
|
492
|
+
else if (result.reason !== 'all_approved') process.exitCode = 3;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function download(options, folder = '.') {
|
|
496
|
+
const project = await findProject(process.cwd());
|
|
497
|
+
const { client: api } = await clientFor(options, project);
|
|
498
|
+
const { campaign } = await resolveCampaign(api, options, project);
|
|
499
|
+
const saved = await saveDownload(api, campaign.id, path.resolve(folder), { approvedOnly: Boolean(options.approved) });
|
|
500
|
+
say(`${green('✔')} Saved ${bold(path.relative(process.cwd(), saved.file) || saved.file)} ${dim(kb(saved.bytes))}`);
|
|
501
|
+
}
|
|
502
|
+
|
|
398
503
|
async function status(options) {
|
|
399
504
|
const project = await findProject(process.cwd());
|
|
400
505
|
const { client: api } = await clientFor(options, project);
|
|
@@ -423,8 +528,10 @@ async function status(options) {
|
|
|
423
528
|
? ''.padEnd(9)
|
|
424
529
|
: (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
|
|
425
530
|
const backup = banner.kind !== 'html' ? ''.padEnd(9) : banner.hasBackup ? dim('backup ✓'.padEnd(9)) : yellow('no backup');
|
|
426
|
-
|
|
531
|
+
const check = !banner.checks ? ''.padEnd(8) : banner.checks.status === 'pass' ? dim('checks ✓') : (banner.checks.status === 'fail' ? red : yellow)(banner.checks.status === 'fail' ? 'checks ✖' : 'checks !');
|
|
532
|
+
say(` ${banner.label.padEnd(width)} ${dim(`${banner.width}×${banner.height}`.padEnd(9))} ${state} ${backup} ${check} ${dim(ago(banner.updatedAt) ?? '')}`);
|
|
427
533
|
}
|
|
534
|
+
printProblems(campaignProblems(campaign));
|
|
428
535
|
}
|
|
429
536
|
|
|
430
537
|
async function open(options) {
|
|
@@ -444,7 +551,7 @@ async function mcp() {
|
|
|
444
551
|
process.exit(0);
|
|
445
552
|
}
|
|
446
553
|
|
|
447
|
-
const COMMANDS = { login, logout, whoami, push, status, open, link, campaigns: listCampaigns, mcp };
|
|
554
|
+
const COMMANDS = { login, logout, whoami, push, status, backups, wait, download, open, link, campaigns: listCampaigns, mcp };
|
|
448
555
|
|
|
449
556
|
const main = async () => {
|
|
450
557
|
let parsed;
|
|
@@ -457,6 +564,10 @@ const main = async () => {
|
|
|
457
564
|
create: { type: 'boolean' },
|
|
458
565
|
'dry-run': { type: 'boolean' },
|
|
459
566
|
open: { type: 'boolean' },
|
|
567
|
+
backups: { type: 'boolean' },
|
|
568
|
+
all: { type: 'boolean' },
|
|
569
|
+
approved: { type: 'boolean' },
|
|
570
|
+
timeout: { type: 'string' },
|
|
460
571
|
json: { type: 'boolean' },
|
|
461
572
|
site: { type: 'string' },
|
|
462
573
|
help: { type: 'boolean', short: 'h' },
|
package/lib/api.mjs
CHANGED
|
@@ -122,6 +122,54 @@ export class PreviewerClient {
|
|
|
122
122
|
return (await this.request('DELETE', `/api/v1/campaigns/${Number(campaignId)}/banners/${encodeURIComponent(bannerId)}`)).data;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
async createClient({ name }) {
|
|
126
|
+
return (await this.request('POST', '/api/v1/clients', { json: { name } })).data.client;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The note shown at the top of the preview; '' clears it. */
|
|
130
|
+
async setNote(campaignId, note) {
|
|
131
|
+
return (await this.request('PATCH', `/api/v1/campaigns/${Number(campaignId)}`, { json: { note } })).data.campaign;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Put a password on the preview, or remove it with '' / null. */
|
|
135
|
+
async setPreviewPassword(campaignId, password) {
|
|
136
|
+
const path = `/api/v1/campaigns/${Number(campaignId)}/password`;
|
|
137
|
+
return (password ? await this.request('PUT', path, { json: { password } }) : await this.request('DELETE', path)).data;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Hide or show a banner on the preview and/or move it to a group: { hidden?, group? }. */
|
|
141
|
+
async updateBanner(campaignId, bannerId, changes) {
|
|
142
|
+
return (await this.request('PATCH', `/api/v1/campaigns/${Number(campaignId)}/banners/${encodeURIComponent(bannerId)}`, { json: changes })).data.campaign;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Render one HTML5 banner's backup image on the server. Takes the banner's length plus a few seconds. */
|
|
146
|
+
async generateBackup(campaignId, bannerId) {
|
|
147
|
+
return (await this.request('POST', `/api/v1/campaigns/${Number(campaignId)}/banners/${encodeURIComponent(bannerId)}/backup`)).data;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The campaign's creatives and backup images as one ZIP: `{ fileName, body }` where body is the
|
|
152
|
+
* response stream. `approvedOnly` leaves out what the client hasn't approved; `banners` picks ids.
|
|
153
|
+
*/
|
|
154
|
+
async download(campaignId, { approvedOnly = false, banners = [] } = {}) {
|
|
155
|
+
const query = new URLSearchParams();
|
|
156
|
+
if (approvedOnly) query.set('only', 'approved');
|
|
157
|
+
if (banners.length) query.set('banners', banners.join(','));
|
|
158
|
+
const path = `/api/v1/campaigns/${Number(campaignId)}/download${query.size ? `?${query}` : ''}`;
|
|
159
|
+
let response;
|
|
160
|
+
try {
|
|
161
|
+
response = await fetch(`${this.baseUrl}${path}`, { headers: { 'User-Agent': this.userAgent, Authorization: `Bearer ${this.token}` } });
|
|
162
|
+
} catch (error) {
|
|
163
|
+
throw new PreviewerError(`Could not reach ${this.baseUrl}: ${error.cause?.message || error.message}`, { code: 'network' });
|
|
164
|
+
}
|
|
165
|
+
if (!response.ok || !response.body) {
|
|
166
|
+
const data = await response.json().catch(() => null);
|
|
167
|
+
throw new PreviewerError(data?.error || `GET ${path} failed (HTTP ${response.status}).`, { status: response.status, code: codeForStatus(response.status) });
|
|
168
|
+
}
|
|
169
|
+
const named = /filename="([^"]+)"/.exec(response.headers.get('content-disposition') || '');
|
|
170
|
+
return { fileName: named ? named[1] : 'banners.zip', body: response.body };
|
|
171
|
+
}
|
|
172
|
+
|
|
125
173
|
// --- previewer login ---------------------------------------------------------------------
|
|
126
174
|
|
|
127
175
|
async startLogin({ tokenHash, tokenHint, clientName }) {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Where an upload is about to go, checked against what the caller said.
|
|
2
|
+
//
|
|
3
|
+
// A folder can be linked to a campaign (.previewer.json), and a campaign can be named by its id. When
|
|
4
|
+
// the caller also names a client, the campaign has to be that client's: otherwise "push for client B"
|
|
5
|
+
// in a folder linked to client A's campaign would put B's banners on A's preview link. Shared by the
|
|
6
|
+
// command line and the MCP server, so the two can't drift apart.
|
|
7
|
+
|
|
8
|
+
/** The reason this campaign is not the named client's, or null when it is (or no client was named). */
|
|
9
|
+
export const clientMismatch = (campaign, client) => {
|
|
10
|
+
if (!client || !campaign) return null;
|
|
11
|
+
if (campaign.client?.id === client.id) return null;
|
|
12
|
+
const owner = campaign.client?.name ? `${campaign.client.name}'s` : "another client's";
|
|
13
|
+
return `Campaign "${campaign.name}" (${campaign.id}) is ${owner}, not ${client.name}'s.`;
|
|
14
|
+
};
|
package/lib/mcp.mjs
CHANGED
|
@@ -7,16 +7,19 @@
|
|
|
7
7
|
import os from 'node:os';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { createInterface } from 'node:readline';
|
|
10
|
+
import { clientMismatch } from './destination.mjs';
|
|
10
11
|
import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from './api.mjs';
|
|
11
12
|
import { collectUploads } from './files.mjs';
|
|
12
13
|
import { PROJECT_FILE, findProject, resolveAuth, saveProject, saveSiteLogin } from './config.mjs';
|
|
14
|
+
import { backupTargets, campaignProblems, checkProblems, generateBackups, saveDownload, waitForApproval } from './tasks.mjs';
|
|
13
15
|
|
|
14
16
|
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
15
17
|
|
|
16
18
|
const INSTRUCTIONS = `Previewer (previewer.agency) hosts live previews of HTML5 banners, images and videos for an agency's clients: one link per campaign, where the client looks and approves.
|
|
17
|
-
Typical flow: whoami (call sign_in if not signed in; a person must approve in the browser) → list_campaigns or get_campaign → upload_folder → give the user the previewUrl.
|
|
18
|
-
A banner uploaded with the same file name replaces the existing one as a new version.
|
|
19
|
-
|
|
19
|
+
Typical flow: whoami (call sign_in if not signed in; a person must approve in the browser) → list_campaigns or get_campaign → upload_folder → fix what its checks report and upload again → generate_backups → give the user the previewUrl → wait_for_approval → download_campaign (approved_only) for the hand-off.
|
|
20
|
+
A banner uploaded with the same file name replaces the existing one as a new version. Every HTML5 banner is checked on upload (click-through, ad.size, weight, insecure assets): upload_folder and get_campaign return what needs fixing. The checks read the code, they don't run it on the ad platform, so treat them as a checklist.
|
|
21
|
+
Approvals are made by the client in the preview; you can read them (get_campaign, wait_for_approval) but not set them.
|
|
22
|
+
Only remove or hide banners, and only set or remove a preview password, when the user asked for exactly that. Never invent a password: use the one the user gave.`;
|
|
20
23
|
|
|
21
24
|
export class ToolError extends Error {}
|
|
22
25
|
|
|
@@ -50,6 +53,17 @@ const matchOne = (items, wanted, what) => {
|
|
|
50
53
|
return matches[0] ?? null;
|
|
51
54
|
};
|
|
52
55
|
|
|
56
|
+
// A banner as an agent needs it: the check result cut down to what needs attention (the passes are
|
|
57
|
+
// noise in a 40-banner campaign).
|
|
58
|
+
const bannerForAgent = (banner) => ({
|
|
59
|
+
...banner,
|
|
60
|
+
checks: banner.checks ? { status: banner.checks.status, platform: banner.checks.platform, zipKb: banner.checks.zipKb, problems: checkProblems(banner) } : null,
|
|
61
|
+
});
|
|
62
|
+
const campaignForAgent = (campaign) => ({ ...campaign, banners: (campaign.banners ?? []).map(bannerForAgent) });
|
|
63
|
+
|
|
64
|
+
// One MCP call should answer well inside a client's tool timeout (often 60 s).
|
|
65
|
+
const CALL_BUDGET_MS = 45_000;
|
|
66
|
+
|
|
53
67
|
const campaignSummary = (campaign) => ({
|
|
54
68
|
id: campaign.id,
|
|
55
69
|
name: campaign.name,
|
|
@@ -66,6 +80,8 @@ const campaignSummary = (campaign) => ({
|
|
|
66
80
|
*/
|
|
67
81
|
export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps = {} } = {}) => {
|
|
68
82
|
const d = {
|
|
83
|
+
now: () => Date.now(),
|
|
84
|
+
saveDownload,
|
|
69
85
|
resolveAuth,
|
|
70
86
|
findProject,
|
|
71
87
|
saveProject,
|
|
@@ -111,7 +127,19 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
111
127
|
return client;
|
|
112
128
|
};
|
|
113
129
|
|
|
114
|
-
|
|
130
|
+
// A client passed along has to own the campaign, however it was found: the folder's link and a
|
|
131
|
+
// campaign id say nothing about the client, and an upload to the wrong one lands on another
|
|
132
|
+
// client's preview link.
|
|
133
|
+
const resolveCampaign = async (api, project, args, settings = {}) => {
|
|
134
|
+
const found = await findCampaign(api, project, args, settings);
|
|
135
|
+
if (args.client !== undefined && args.client !== null && String(args.client).trim()) {
|
|
136
|
+
const mismatch = clientMismatch(found.campaign, await resolveClient(api, args.client));
|
|
137
|
+
if (mismatch) throw Object.assign(new ToolError(`${mismatch} Leave out client, or pass the campaign that is that client's.`), { mismatch: true });
|
|
138
|
+
}
|
|
139
|
+
return found;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const findCampaign = async (api, project, args, { create = false } = {}) => {
|
|
115
143
|
const wanted = args.campaign === undefined || args.campaign === null ? '' : String(args.campaign).trim();
|
|
116
144
|
if (!wanted) {
|
|
117
145
|
if (project?.campaignId) return { campaign: await api.campaign(project.campaignId) };
|
|
@@ -249,12 +277,12 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
249
277
|
name: 'get_campaign',
|
|
250
278
|
title: 'Campaign status',
|
|
251
279
|
description:
|
|
252
|
-
'One campaign: preview link, when the client last opened it, and per banner its size, kind, status (review or approved, with when), whether it has a backup image, and
|
|
280
|
+
'One campaign: preview link, note, whether it has a password, when the client last opened it, and per banner its size, kind, group, status (review or approved, with when and the name the client gave), whether it has a backup image, whether it is hidden from the preview, and what the upload check found (checks.problems: what to fix). Without campaign, uses the campaign the folder is linked to.',
|
|
253
281
|
inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, folder: FOLDER }),
|
|
254
282
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
255
283
|
run: async (args) => {
|
|
256
284
|
const { api, project } = await connect(args.folder);
|
|
257
|
-
return { campaign: (await resolveCampaign(api, project, args)).campaign };
|
|
285
|
+
return { campaign: campaignForAgent((await resolveCampaign(api, project, args)).campaign) };
|
|
258
286
|
},
|
|
259
287
|
},
|
|
260
288
|
{
|
|
@@ -287,7 +315,7 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
287
315
|
name: 'upload_folder',
|
|
288
316
|
title: 'Upload banners',
|
|
289
317
|
description:
|
|
290
|
-
'Upload a folder to a campaign: HTML5 banner ZIPs, banner folders with an index.html (zipped for you), images and videos, and backup images (300x250.jpg next to 300x250.zip, or anything in backups/). A file named like a banner already in the campaign replaces it as a new version. Returns the preview link to give the user. Use dry_run to see what would go up.',
|
|
318
|
+
'Upload a folder to a campaign: HTML5 banner ZIPs, banner folders with an index.html (zipped for you), images and videos, and backup images (300x250.jpg next to 300x250.zip, or anything in backups/). A file named like a banner already in the campaign replaces it as a new version. Returns the preview link to give the user, and `checks`: per uploaded banner what the upload check found that needs fixing (empty when all is well). Fix those in the source and upload again. Use dry_run to see what would go up and where. A client you pass has to own the campaign.',
|
|
291
319
|
inputSchema: object(
|
|
292
320
|
{
|
|
293
321
|
folder: { ...FOLDER, description: `The folder to upload, e.g. "dist". ${FOLDER.description}` },
|
|
@@ -305,7 +333,21 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
305
333
|
throw new ToolError(error.code === 'ENOENT' ? `No folder ${dir}.` : `Could not read ${dir}: ${error.message}`);
|
|
306
334
|
});
|
|
307
335
|
const files = items.map((item) => ({ type: item.type, file: item.source ?? item.name, as: item.name, bytes: item.size }));
|
|
308
|
-
if (args.dry_run)
|
|
336
|
+
if (args.dry_run) {
|
|
337
|
+
// Nothing is sent, but the destination is the real one: where this upload would go, or why
|
|
338
|
+
// that isn't known yet. A campaign that isn't the named client's stops here too.
|
|
339
|
+
let destination = null;
|
|
340
|
+
let destinationNote = null;
|
|
341
|
+
try {
|
|
342
|
+
const { api, project } = await connect(args.folder);
|
|
343
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
344
|
+
destination = campaignSummary(campaign);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (!(error instanceof ToolError) || error.mismatch) throw error;
|
|
347
|
+
destinationNote = error.message;
|
|
348
|
+
}
|
|
349
|
+
return { dryRun: true, folder: dir, files, skipped, destination, destinationNote };
|
|
350
|
+
}
|
|
309
351
|
if (items.length === 0) throw new ToolError(`Nothing to upload in ${dir}: expected ZIPs, banner folders with an index.html, images or videos.`);
|
|
310
352
|
|
|
311
353
|
const { api, auth, project } = await connect(args.folder);
|
|
@@ -320,6 +362,8 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
320
362
|
newVersions: result.uploaded.filter((id) => before.has(id)).length,
|
|
321
363
|
backups: items.filter((item) => item.type === 'backup').length,
|
|
322
364
|
skipped,
|
|
365
|
+
checks: campaignProblems(result.campaign, result.uploaded),
|
|
366
|
+
withoutBackup: backupTargets(result.campaign, { only: result.uploaded }).filter((id) => !result.campaign.banners?.find((banner) => banner.id === id)?.hasBackup),
|
|
323
367
|
...(linked ? { linked } : {}),
|
|
324
368
|
};
|
|
325
369
|
},
|
|
@@ -337,6 +381,154 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
|
|
|
337
381
|
return { removed: result.removed, campaign: campaignSummary(result.campaign) };
|
|
338
382
|
},
|
|
339
383
|
},
|
|
384
|
+
{
|
|
385
|
+
name: 'generate_backups',
|
|
386
|
+
title: 'Generate backup images',
|
|
387
|
+
description:
|
|
388
|
+
'Have Previewer make the backup (fallback) JPG of HTML5 banners: it plays each banner to its end frame and saves it within the size limit. By default every HTML5 banner that has no backup yet; pass banners for specific ones, or all: true to redo them all. Each takes about the banner\'s length, so one call does as many as fit in about 45 seconds and returns `remaining`: call again with banners: remaining until it is empty. Needs upload access.',
|
|
389
|
+
inputSchema: object({
|
|
390
|
+
campaign: CAMPAIGN,
|
|
391
|
+
client: CLIENT,
|
|
392
|
+
folder: FOLDER,
|
|
393
|
+
banners: { type: 'array', items: { type: 'string' }, description: 'Banner ids, as get_campaign lists them. Leave out for every banner without a backup.' },
|
|
394
|
+
all: { type: 'boolean', description: 'Also redo banners that already have a backup.' },
|
|
395
|
+
}),
|
|
396
|
+
annotations: { idempotentHint: true, openWorldHint: false },
|
|
397
|
+
run: async (args) => {
|
|
398
|
+
const { api, project } = await connect(args.folder);
|
|
399
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
400
|
+
const wanted = Array.isArray(args.banners) ? args.banners.map(String) : [];
|
|
401
|
+
const unknown = wanted.filter((id) => !campaign.banners.some((banner) => banner.id === id && banner.kind === 'html'));
|
|
402
|
+
if (unknown.length) throw new ToolError(`Not an HTML5 banner in this campaign: ${unknown.join(', ')}. get_campaign lists the ids.`);
|
|
403
|
+
const ids = backupTargets(campaign, { all: Boolean(args.all), only: wanted });
|
|
404
|
+
if (ids.length === 0) return { generated: [], remaining: [], note: 'Every HTML5 banner already has a backup image. Pass all: true to make them again.' };
|
|
405
|
+
const result = await generateBackups(api, campaign.id, ids, { deadline: d.now() + CALL_BUDGET_MS, now: d.now });
|
|
406
|
+
return {
|
|
407
|
+
...result,
|
|
408
|
+
...(result.kept.length ? { keptNote: 'A backup was uploaded for these while rendering; that one was kept.' } : {}),
|
|
409
|
+
...(result.remaining.length ? { next: 'Call generate_backups again with banners set to `remaining`.' } : {}),
|
|
410
|
+
};
|
|
411
|
+
},
|
|
412
|
+
},
|
|
413
|
+
{
|
|
414
|
+
name: 'wait_for_approval',
|
|
415
|
+
title: 'Wait for the client',
|
|
416
|
+
description:
|
|
417
|
+
'Wait until the client has approved, checking every few seconds for up to about 45 seconds. Returns as soon as everything is approved or (by default) any approval changed, with where things stand: approved / total, the banners still open, the newly approved ones and when the client last opened the preview. reason is all_approved, changed, timeout, approvals_off or nothing_to_approve. On timeout, call again; clients usually take hours, so between calls do other work or stop and tell the user.',
|
|
418
|
+
inputSchema: object({
|
|
419
|
+
campaign: CAMPAIGN,
|
|
420
|
+
client: CLIENT,
|
|
421
|
+
folder: FOLDER,
|
|
422
|
+
until_all_approved: { type: 'boolean', description: 'Keep waiting through single approvals; return only when everything is approved or the time is up.' },
|
|
423
|
+
}),
|
|
424
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
425
|
+
run: async (args) => {
|
|
426
|
+
const { api, project } = await connect(args.folder);
|
|
427
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
428
|
+
const result = await waitForApproval(api, campaign.id, { timeoutMs: CALL_BUDGET_MS, untilChange: !args.until_all_approved, sleep: d.sleep });
|
|
429
|
+
return { campaign: { id: campaign.id, name: campaign.name, previewUrl: campaign.previewUrl }, ...result };
|
|
430
|
+
},
|
|
431
|
+
},
|
|
432
|
+
{
|
|
433
|
+
name: 'download_campaign',
|
|
434
|
+
title: 'Download creatives',
|
|
435
|
+
description:
|
|
436
|
+
'Save a campaign as one ZIP in the project: every creative with its backup image, laid out for the hand-off to the media agency. approved_only leaves out what the client has not approved yet (and anything hidden from the preview). Returns the file path. A campaign with a lot of video can take longer than a tool call allows: then tell the user to run `npx previewer-agency download` themselves.',
|
|
437
|
+
inputSchema: object({
|
|
438
|
+
campaign: CAMPAIGN,
|
|
439
|
+
client: CLIENT,
|
|
440
|
+
folder: FOLDER,
|
|
441
|
+
to: { type: 'string', description: 'Folder to save the ZIP in, absolute or relative to the project. Default: the project folder.' },
|
|
442
|
+
approved_only: { type: 'boolean', description: 'Only the banners the client approved.' },
|
|
443
|
+
banners: { type: 'array', items: { type: 'string' }, description: 'Only these banner ids.' },
|
|
444
|
+
}),
|
|
445
|
+
annotations: { openWorldHint: false },
|
|
446
|
+
run: async (args) => {
|
|
447
|
+
const { api, project } = await connect(args.folder);
|
|
448
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
449
|
+
const saved = await d.saveDownload(api, campaign.id, folderPath(args.to), {
|
|
450
|
+
approvedOnly: Boolean(args.approved_only),
|
|
451
|
+
banners: Array.isArray(args.banners) ? args.banners.map(String) : [],
|
|
452
|
+
});
|
|
453
|
+
return { file: saved.file, bytes: saved.bytes, campaign: campaignSummary(campaign) };
|
|
454
|
+
},
|
|
455
|
+
},
|
|
456
|
+
{
|
|
457
|
+
name: 'create_client',
|
|
458
|
+
title: 'Create client',
|
|
459
|
+
description: 'Add a client by name (needs Manage access, and a token that is not limited to one client). Its logo, colours and approval default are set in the Previewer admin. Refused when a client with that name exists: use that one.',
|
|
460
|
+
inputSchema: object({ name: { type: 'string', description: 'Client name, as the agency writes it.' } }, ['name']),
|
|
461
|
+
annotations: { openWorldHint: false },
|
|
462
|
+
run: async (args) => {
|
|
463
|
+
const name = String(args.name ?? '').trim();
|
|
464
|
+
if (!name) throw new ToolError('Give the client a name.');
|
|
465
|
+
return { client: await (await connect()).api.createClient({ name }) };
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
name: 'set_note',
|
|
470
|
+
title: 'Set the campaign note',
|
|
471
|
+
description: 'Set the note shown at the top of the preview, for example what changed in this round (needs Manage access). An empty note removes it. The client sees it at once.',
|
|
472
|
+
inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, folder: FOLDER, note: { type: 'string', description: 'The note, plain text. "" removes it.' } }, ['note']),
|
|
473
|
+
annotations: { idempotentHint: true, openWorldHint: false },
|
|
474
|
+
run: async (args) => {
|
|
475
|
+
const { api, project } = await connect(args.folder);
|
|
476
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
477
|
+
const saved = await api.setNote(campaign.id, String(args.note ?? ''));
|
|
478
|
+
return { note: saved.note, campaign: campaignSummary(saved) };
|
|
479
|
+
},
|
|
480
|
+
},
|
|
481
|
+
{
|
|
482
|
+
name: 'update_banner',
|
|
483
|
+
title: 'Hide, show or group a banner',
|
|
484
|
+
description:
|
|
485
|
+
'Change how one banner appears on the preview (needs Manage access): hidden: true takes it off the client\'s page (it stays in the campaign, and can\'t be approved while hidden), hidden: false puts it back; group puts it under a group by name (made if it doesn\'t exist), group: "" takes it out of its group. It cannot change an approval.',
|
|
486
|
+
inputSchema: object(
|
|
487
|
+
{
|
|
488
|
+
campaign: CAMPAIGN,
|
|
489
|
+
client: CLIENT,
|
|
490
|
+
folder: FOLDER,
|
|
491
|
+
banner: { type: 'string', description: 'The banner id, as get_campaign lists it (e.g. "300x250").' },
|
|
492
|
+
hidden: { type: 'boolean', description: 'true hides it from the client\'s preview, false shows it.' },
|
|
493
|
+
group: { type: 'string', description: 'Group name, e.g. "Dutch". "" removes it from its group.' },
|
|
494
|
+
},
|
|
495
|
+
['banner'],
|
|
496
|
+
),
|
|
497
|
+
annotations: { idempotentHint: true, openWorldHint: false },
|
|
498
|
+
run: async (args) => {
|
|
499
|
+
const changes = {};
|
|
500
|
+
if (typeof args.hidden === 'boolean') changes.hidden = args.hidden;
|
|
501
|
+
if (typeof args.group === 'string') changes.group = args.group.trim() || null;
|
|
502
|
+
if (Object.keys(changes).length === 0) throw new ToolError('Pass hidden and/or group.');
|
|
503
|
+
const { api, project } = await connect(args.folder);
|
|
504
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
505
|
+
const saved = await api.updateBanner(campaign.id, String(args.banner), changes);
|
|
506
|
+
const banner = saved.banners.find((item) => item.id === String(args.banner));
|
|
507
|
+
return { banner: banner ? { id: banner.id, hidden: banner.hidden, group: banner.group } : null, campaign: campaignSummary(saved) };
|
|
508
|
+
},
|
|
509
|
+
},
|
|
510
|
+
{
|
|
511
|
+
name: 'set_preview_password',
|
|
512
|
+
title: 'Preview password',
|
|
513
|
+
description:
|
|
514
|
+
'Put a password on a campaign\'s preview, or remove it with remove: true (needs Manage access). Setting one, even the same one, locks out everyone who had unlocked the preview. Only when the user asked, with the password the user gave: never make one up, and tell the user they have to pass it on to their client themselves.',
|
|
515
|
+
inputSchema: object({
|
|
516
|
+
campaign: CAMPAIGN,
|
|
517
|
+
client: CLIENT,
|
|
518
|
+
folder: FOLDER,
|
|
519
|
+
password: { type: 'string', description: 'The password the user gave.' },
|
|
520
|
+
remove: { type: 'boolean', description: 'Remove the password instead.' },
|
|
521
|
+
}),
|
|
522
|
+
annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
523
|
+
run: async (args) => {
|
|
524
|
+
const password = typeof args.password === 'string' ? args.password : '';
|
|
525
|
+
if (Boolean(args.remove) === Boolean(password)) throw new ToolError('Pass either password, or remove: true.');
|
|
526
|
+
const { api, project } = await connect(args.folder);
|
|
527
|
+
const { campaign } = await resolveCampaign(api, project, args);
|
|
528
|
+
const result = await api.setPreviewPassword(campaign.id, args.remove ? null : password);
|
|
529
|
+
return { passwordProtected: result.passwordProtected, campaign: campaignSummary(campaign) };
|
|
530
|
+
},
|
|
531
|
+
},
|
|
340
532
|
];
|
|
341
533
|
|
|
342
534
|
const reply = (id, result) => ({ jsonrpc: '2.0', id, result });
|
package/lib/tasks.mjs
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// What the command line and the MCP server both do with a campaign beyond uploading: read the upload
|
|
2
|
+
// check, generate backup images, wait for the client, save the download. One place, so `previewer
|
|
3
|
+
// backups` and the generate_backups tool can't drift apart.
|
|
4
|
+
|
|
5
|
+
import { createWriteStream } from 'node:fs';
|
|
6
|
+
import { access, mkdir } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { Readable } from 'node:stream';
|
|
9
|
+
import { pipeline } from 'node:stream/promises';
|
|
10
|
+
|
|
11
|
+
/** A banner's check findings that need attention: fails and warnings, never passes or notes. */
|
|
12
|
+
export const checkProblems = (banner) =>
|
|
13
|
+
(banner.checks?.items ?? []).filter((item) => item.status === 'fail' || item.status === 'warn').map((item) => ({
|
|
14
|
+
check: item.label,
|
|
15
|
+
status: item.status,
|
|
16
|
+
detail: item.detail,
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
/** Per banner with something to fix: `[{ banner, label, status, platform, problems }]`. */
|
|
20
|
+
export const campaignProblems = (campaign, onlyIds) =>
|
|
21
|
+
(campaign.banners ?? [])
|
|
22
|
+
.filter((banner) => !onlyIds || onlyIds.includes(banner.id))
|
|
23
|
+
.map((banner) => ({ banner: banner.id, label: banner.label, status: banner.checks?.status ?? null, platform: banner.checks?.platform ?? null, problems: checkProblems(banner) }))
|
|
24
|
+
.filter((entry) => entry.problems.length > 0);
|
|
25
|
+
|
|
26
|
+
/** Where approvals stand: only what the client can approve (no links, nothing hidden). */
|
|
27
|
+
export const approvalState = (campaign) => {
|
|
28
|
+
const reviewable = (campaign.banners ?? []).filter((banner) => banner.kind !== 'external' && !banner.hidden);
|
|
29
|
+
const open = reviewable.filter((banner) => banner.status !== 'approved');
|
|
30
|
+
return {
|
|
31
|
+
approvalsRequired: campaign.approvalsRequired !== false,
|
|
32
|
+
approved: reviewable.length - open.length,
|
|
33
|
+
total: reviewable.length,
|
|
34
|
+
allApproved: campaign.approvalsRequired !== false && reviewable.length > 0 && open.length === 0,
|
|
35
|
+
open: open.map((banner) => banner.id),
|
|
36
|
+
lastApprovedAt: campaign.lastApprovedAt ?? null,
|
|
37
|
+
lastViewedAt: campaign.lastViewedAt ?? null,
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** The HTML5 banners that would get a backup: those without one, or all of them. */
|
|
42
|
+
export const backupTargets = (campaign, { all = false, only } = {}) =>
|
|
43
|
+
(campaign.banners ?? [])
|
|
44
|
+
.filter((banner) => banner.kind === 'html')
|
|
45
|
+
.filter((banner) => (only?.length ? only.includes(banner.id) : all || !banner.hasBackup))
|
|
46
|
+
.map((banner) => banner.id);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Generate backups one after another (the server renders one banner per request). Stops after
|
|
50
|
+
* `limit` banners or when the next one wouldn't be done by `deadline` (ms timestamp), going by the
|
|
51
|
+
* slowest render so far, and says what is left. The first one always runs.
|
|
52
|
+
*/
|
|
53
|
+
export const generateBackups = async (api, campaignId, ids, { limit = Infinity, deadline = Infinity, now = Date.now, onResult } = {}) => {
|
|
54
|
+
const generated = [];
|
|
55
|
+
const kept = [];
|
|
56
|
+
const failed = [];
|
|
57
|
+
let index = 0;
|
|
58
|
+
let slowest = 0;
|
|
59
|
+
for (; index < ids.length && index < limit && (index === 0 || now() + slowest < deadline); index += 1) {
|
|
60
|
+
const id = ids[index];
|
|
61
|
+
const started = now();
|
|
62
|
+
try {
|
|
63
|
+
const result = await api.generateBackup(campaignId, id);
|
|
64
|
+
(result.generated ? generated : kept).push(id);
|
|
65
|
+
onResult?.(id, result, null);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
failed.push({ banner: id, error: error.message });
|
|
68
|
+
onResult?.(id, null, error);
|
|
69
|
+
}
|
|
70
|
+
slowest = Math.max(slowest, now() - started);
|
|
71
|
+
}
|
|
72
|
+
return { generated, kept, failed, remaining: ids.slice(index) };
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Poll the campaign until the client has approved everything, anything about the approvals changed
|
|
77
|
+
* (`untilChange`), or the time is up. Returns the state and why it stopped.
|
|
78
|
+
*/
|
|
79
|
+
export const waitForApproval = async (api, campaignId, { timeoutMs, intervalMs = 5000, untilChange = false, sleep, onTick } = {}) => {
|
|
80
|
+
const pause = sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
81
|
+
const started = Date.now();
|
|
82
|
+
const first = approvalState(await api.campaign(campaignId));
|
|
83
|
+
let state = first;
|
|
84
|
+
const done = () => !state.approvalsRequired || state.allApproved || state.total === 0;
|
|
85
|
+
const changed = () => state.approved !== first.approved || state.lastApprovedAt !== first.lastApprovedAt || state.total !== first.total;
|
|
86
|
+
while (!done() && !(untilChange && changed()) && Date.now() - started + intervalMs <= timeoutMs) {
|
|
87
|
+
await pause(intervalMs);
|
|
88
|
+
state = approvalState(await api.campaign(campaignId));
|
|
89
|
+
onTick?.(state);
|
|
90
|
+
}
|
|
91
|
+
const reason = !state.approvalsRequired
|
|
92
|
+
? 'approvals_off'
|
|
93
|
+
: state.total === 0
|
|
94
|
+
? 'nothing_to_approve'
|
|
95
|
+
: state.allApproved
|
|
96
|
+
? 'all_approved'
|
|
97
|
+
: untilChange && changed()
|
|
98
|
+
? 'changed'
|
|
99
|
+
: 'timeout';
|
|
100
|
+
return { reason, ...state, newlyApproved: first.open.filter((id) => !state.open.includes(id)) };
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** Save the campaign ZIP into `dir` (created if needed), next to any earlier one. Returns `{ file, bytes }`. */
|
|
104
|
+
export const saveDownload = async (api, campaignId, dir, options = {}) => {
|
|
105
|
+
const { fileName, body } = await api.download(campaignId, options);
|
|
106
|
+
await mkdir(dir, { recursive: true });
|
|
107
|
+
// The name comes from the server: keep only its last segment, so it can't leave the folder.
|
|
108
|
+
const name = path.basename(fileName).replace(/[^\w.\- ()]+/g, '_') || 'banners.zip';
|
|
109
|
+
// Never over an earlier download: "name (2).zip", "name (3).zip", …
|
|
110
|
+
const exists = (candidate) => access(candidate).then(() => true, () => false);
|
|
111
|
+
const { name: stem, ext } = path.parse(name);
|
|
112
|
+
let file = path.join(dir, name);
|
|
113
|
+
for (let copy = 2; await exists(file); copy += 1) file = path.join(dir, `${stem} (${copy})${ext}`);
|
|
114
|
+
let bytes = 0;
|
|
115
|
+
const source = Readable.fromWeb(body);
|
|
116
|
+
source.on('data', (chunk) => {
|
|
117
|
+
bytes += chunk.length;
|
|
118
|
+
});
|
|
119
|
+
await pipeline(source, createWriteStream(file));
|
|
120
|
+
return { file, bytes };
|
|
121
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "previewer-agency",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP), and
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP): check results, backup images, approvals and the approved download.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"previewer": "bin/previewer.mjs"
|