previewer-agency 0.3.2 → 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 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, and check on approvals.
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, create
45
- campaigns, remove banners; viewers: look), stops working if your access ends, and shows under
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.
@@ -81,6 +83,11 @@ npx previewer-agency push ./dist
81
83
  When it's done it prints the preview link and copies it to your clipboard. `--open` opens it.
82
84
  `--dry-run` shows what would go up, and to which client and campaign, without uploading.
83
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
+
84
91
  A `--client` you name has to own the campaign. In a folder linked to one client's campaign,
85
92
  `push --client "Another client"` stops before anything is uploaded; add `--campaign` to say which
86
93
  campaign of that client you mean.
@@ -88,14 +95,33 @@ campaign of that client you mean.
88
95
  ## Check on it
89
96
 
90
97
  ```bash
91
- 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
92
99
  npx previewer-agency open # open the preview
93
100
  npx previewer-agency campaigns # list campaigns (--client to narrow)
94
101
  npx previewer-agency link # choose this folder's campaign without uploading
95
102
  npx previewer-agency whoami
96
103
  ```
97
104
 
98
- `--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`.
99
125
 
100
126
  ## In CI
101
127
 
@@ -103,7 +129,7 @@ Create a token under **API** in the admin (Upload access, narrowed to a client o
103
129
  like), store it as a secret, and:
104
130
 
105
131
  ```bash
106
- PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
132
+ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42 --backups
107
133
  ```
108
134
 
109
135
  `PREVIEWER_URL` points it at another Previewer address.
@@ -111,7 +137,8 @@ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
111
137
  ## With an AI agent
112
138
 
113
139
  `previewer mcp` runs Previewer as an MCP server, so an agent like Claude Code or Cursor can upload,
114
- check approvals and set up a project for you. It uses the same sign-in as the command line; if this
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
115
142
  computer isn't signed in yet, the agent starts the sign-in, and you type its code in your browser and approve.
116
143
 
117
144
  Claude Code:
@@ -126,10 +153,28 @@ Cursor, Windsurf, Claude Desktop and others, in their MCP settings:
126
153
  { "mcpServers": { "previewer": { "command": "npx", "args": ["-y", "previewer-agency", "mcp"] } } }
127
154
  ```
128
155
 
129
- Then ask things like "upload dist to the Acme spring campaign and give me the link" or "which banners
130
- are still waiting for approval?". The tools: `whoami`, `sign_in`, `list_clients`, `list_campaigns`,
131
- `get_campaign`, `create_campaign`, `link_folder`, `upload_folder` and `remove_banner`. Approving is
132
- left to your client, in the preview.
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.
133
178
 
134
179
  To have an agent set up a project from scratch, point it at
135
180
  [previewer.agency/llms.txt](https://previewer.agency/llms.txt).
@@ -144,6 +189,15 @@ const api = new PreviewerClient({ baseUrl: 'https://previewer.agency', token: pr
144
189
  const { items } = await collectUploads('./dist');
145
190
  const { campaign } = await api.upload(42, items);
146
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');
147
198
  ```
148
199
 
200
+ Also on the client: `createClient`, `createCampaign`, `setNote`, `updateBanner`, `setPreviewPassword`,
201
+ `removeBanner` and `download`.
202
+
149
203
  The API itself is documented at [previewer.agency/docs/api](https://previewer.agency/docs/api#tokens).
package/bin/previewer.mjs CHANGED
@@ -13,6 +13,7 @@ import { clientMismatch } from '../lib/destination.mjs';
13
13
  import { collectUploads } from '../lib/files.mjs';
14
14
  import { createMcpServer, runStdio } from '../lib/mcp.mjs';
15
15
  import { selectMenu } from '../lib/menu.mjs';
16
+ import { backupTargets, campaignProblems, generateBackups, saveDownload, waitForApproval } from '../lib/tasks.mjs';
16
17
  import { DEFAULT_SITE, PROJECT_FILE, findProject, forgetSiteLogin, normalizeSite, resolveAuth, saveProject, saveSiteLogin } from '../lib/config.mjs';
17
18
 
18
19
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
@@ -40,7 +41,10 @@ const CMD = RAN_VIA_NPX ? 'npx previewer-agency' : 'previewer';
40
41
  const COMMAND_HELP = [
41
42
  ['login', 'Sign in (opens the browser to approve)'],
42
43
  ['push [folder]', 'Upload a folder: ZIPs, banner folders, images, videos, backups'],
43
- ['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)'],
44
48
  ['open', "Open the campaign's preview link"],
45
49
  ['link', 'Choose which campaign this folder publishes to'],
46
50
  ['campaigns', 'List campaigns'],
@@ -61,7 +65,11 @@ ${bold('Options')}
61
65
  --create Create the campaign if it doesn't exist (push)
62
66
  --dry-run Show what push would upload, upload nothing
63
67
  --open Open the preview after push
64
- --json Machine-readable output (status, campaigns, whoami)
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)
65
73
  --site <url> Previewer address (default ${DEFAULT_SITE})
66
74
 
67
75
  ${bold('In CI')}
@@ -422,6 +430,8 @@ async function push(options, folder = '.') {
422
430
  ` The campaign now has ${result.campaign.bannerCount} banner${result.campaign.bannerCount === 1 ? '' : 's'}.`,
423
431
  );
424
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));
425
435
  if (result.campaign.previewUrl) {
426
436
  const copied = interactive && (await copyToClipboard(result.campaign.previewUrl));
427
437
  say('', `${bold(result.campaign.previewUrl)}${copied ? dim(' (copied)') : ''}`);
@@ -429,6 +439,67 @@ async function push(options, folder = '.') {
429
439
  }
430
440
  }
431
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
+
432
503
  async function status(options) {
433
504
  const project = await findProject(process.cwd());
434
505
  const { client: api } = await clientFor(options, project);
@@ -457,8 +528,10 @@ async function status(options) {
457
528
  ? ''.padEnd(9)
458
529
  : (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
459
530
  const backup = banner.kind !== 'html' ? ''.padEnd(9) : banner.hasBackup ? dim('backup ✓'.padEnd(9)) : yellow('no backup');
460
- say(` ${banner.label.padEnd(width)} ${dim(`${banner.width}×${banner.height}`.padEnd(9))} ${state} ${backup} ${dim(ago(banner.updatedAt) ?? '')}`);
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) ?? '')}`);
461
533
  }
534
+ printProblems(campaignProblems(campaign));
462
535
  }
463
536
 
464
537
  async function open(options) {
@@ -478,7 +551,7 @@ async function mcp() {
478
551
  process.exit(0);
479
552
  }
480
553
 
481
- 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 };
482
555
 
483
556
  const main = async () => {
484
557
  let parsed;
@@ -491,6 +564,10 @@ const main = async () => {
491
564
  create: { type: 'boolean' },
492
565
  'dry-run': { type: 'boolean' },
493
566
  open: { type: 'boolean' },
567
+ backups: { type: 'boolean' },
568
+ all: { type: 'boolean' },
569
+ approved: { type: 'boolean' },
570
+ timeout: { type: 'string' },
494
571
  json: { type: 'boolean' },
495
572
  site: { type: 'string' },
496
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 }) {
package/lib/mcp.mjs CHANGED
@@ -11,13 +11,15 @@ import { clientMismatch } from './destination.mjs';
11
11
  import { PreviewerClient, PreviewerError, isApprovalPath, newCliToken } from './api.mjs';
12
12
  import { collectUploads } from './files.mjs';
13
13
  import { PROJECT_FILE, findProject, resolveAuth, saveProject, saveSiteLogin } from './config.mjs';
14
+ import { backupTargets, campaignProblems, checkProblems, generateBackups, saveDownload, waitForApproval } from './tasks.mjs';
14
15
 
15
16
  const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
16
17
 
17
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.
18
- 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.
19
- A banner uploaded with the same file name replaces the existing one as a new version. Approvals are made by the client in the preview; you can read them (get_campaign) but not set them.
20
- Only remove banners when the user asked for that specific banner.`;
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.`;
21
23
 
22
24
  export class ToolError extends Error {}
23
25
 
@@ -51,6 +53,17 @@ const matchOne = (items, wanted, what) => {
51
53
  return matches[0] ?? null;
52
54
  };
53
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
+
54
67
  const campaignSummary = (campaign) => ({
55
68
  id: campaign.id,
56
69
  name: campaign.name,
@@ -67,6 +80,8 @@ const campaignSummary = (campaign) => ({
67
80
  */
68
81
  export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps = {} } = {}) => {
69
82
  const d = {
83
+ now: () => Date.now(),
84
+ saveDownload,
70
85
  resolveAuth,
71
86
  findProject,
72
87
  saveProject,
@@ -262,12 +277,12 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
262
277
  name: 'get_campaign',
263
278
  title: 'Campaign status',
264
279
  description:
265
- '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 its file size. Without campaign, uses the campaign the folder is linked to.',
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.',
266
281
  inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, folder: FOLDER }),
267
282
  annotations: { readOnlyHint: true, openWorldHint: false },
268
283
  run: async (args) => {
269
284
  const { api, project } = await connect(args.folder);
270
- return { campaign: (await resolveCampaign(api, project, args)).campaign };
285
+ return { campaign: campaignForAgent((await resolveCampaign(api, project, args)).campaign) };
271
286
  },
272
287
  },
273
288
  {
@@ -300,7 +315,7 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
300
315
  name: 'upload_folder',
301
316
  title: 'Upload banners',
302
317
  description:
303
- '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 and where. A client you pass has to own the campaign.',
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.',
304
319
  inputSchema: object(
305
320
  {
306
321
  folder: { ...FOLDER, description: `The folder to upload, e.g. "dist". ${FOLDER.description}` },
@@ -347,6 +362,8 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
347
362
  newVersions: result.uploaded.filter((id) => before.has(id)).length,
348
363
  backups: items.filter((item) => item.type === 'backup').length,
349
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),
350
367
  ...(linked ? { linked } : {}),
351
368
  };
352
369
  },
@@ -364,6 +381,154 @@ export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps =
364
381
  return { removed: result.removed, campaign: campaignSummary(result.campaign) };
365
382
  },
366
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
+ },
367
532
  ];
368
533
 
369
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.3.2",
4
- "description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP), and check approvals.",
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"