previewer-agency 0.0.0-stage → 0.1.1

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,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # previewer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Upload HTML5 banners, images and videos to [Previewer](https://previewer.agency) from any folder,
4
+ whatever tool built them, and check on approvals. Needs Node 20 or newer; nothing else to install.
5
+
6
+ ```bash
7
+ npx previewer-agency login
8
+ npx previewer-agency push ./dist --client "Acme" --campaign "Spring sale"
9
+ ```
10
+
11
+ ## Sign in
12
+
13
+ ```bash
14
+ npx previewer-agency login
15
+ ```
16
+
17
+ Opens your browser. Check that the code matches the one in your terminal and approve. Your computer
18
+ gets its own token: it can do what you can do in Previewer (owners and editors: upload, create
19
+ campaigns, remove banners; viewers: look), stops working if your access ends, and shows under
20
+ **API** in the admin, where an owner can revoke it. `previewer logout` revokes it yourself.
21
+
22
+ The token is saved in `~/.config/previewer/config.json`, readable only by you.
23
+
24
+ ## Push a folder
25
+
26
+ ```bash
27
+ npx previewer-agency push ./dist --client "Acme" --campaign "Spring sale"
28
+ ```
29
+
30
+ What it picks up:
31
+
32
+ | In the folder | Becomes |
33
+ | --- | --- |
34
+ | `300x250.zip` | an HTML5 banner |
35
+ | `300x250/` with an `index.html` | an HTML5 banner (zipped for you) |
36
+ | `300x250.jpg` next to `300x250.zip`, or anything in `backups/` | that banner's backup image |
37
+ | other images and videos | image and video creatives |
38
+
39
+ Leave out `--client` and `--campaign` and `push` lets you pick them from a menu: arrow keys to move,
40
+ type to filter, Enter to choose, or **+ New campaign** to make one.
41
+
42
+ A file with the same name as a banner already in the campaign replaces it as a new version. If the
43
+ campaign doesn't exist yet, `push` offers to create it (`--create` skips the question). Large files
44
+ and big batches are split up for you.
45
+
46
+ The first push saves the campaign in `.previewer.json` in the current folder (ids only, safe to
47
+ commit). After that:
48
+
49
+ ```bash
50
+ npx previewer-agency push ./dist
51
+ ```
52
+
53
+ When it's done it prints the preview link and copies it to your clipboard. `--open` opens it.
54
+ `--dry-run` shows what would go up without uploading.
55
+
56
+ ## Check on it
57
+
58
+ ```bash
59
+ npx previewer-agency status # approvals per banner, backups, when the client last looked
60
+ npx previewer-agency open # open the preview
61
+ npx previewer-agency campaigns # list campaigns (--client to narrow)
62
+ npx previewer-agency link # choose this folder's campaign without uploading
63
+ npx previewer-agency whoami
64
+ ```
65
+
66
+ `--json` gives machine-readable output for `status`, `campaigns` and `whoami`.
67
+
68
+ ## In CI
69
+
70
+ Create a token under **API** in the admin (Upload access, narrowed to a client or campaign if you
71
+ like), store it as a secret, and:
72
+
73
+ ```bash
74
+ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
75
+ ```
76
+
77
+ `PREVIEWER_URL` points it at another Previewer address.
78
+
79
+ ## As a library
80
+
81
+ ```js
82
+ import { PreviewerClient } from 'previewer-agency';
83
+ import { collectUploads } from 'previewer-agency/files';
84
+
85
+ const api = new PreviewerClient({ baseUrl: 'https://previewer.agency', token: process.env.PREVIEWER_TOKEN });
86
+ const { items } = await collectUploads('./dist');
87
+ const { campaign } = await api.upload(42, items);
88
+ console.log(campaign.previewUrl);
89
+ ```
90
+
91
+ The API itself is documented at [previewer.agency/docs/api](https://previewer.agency/docs/api#tokens).
@@ -0,0 +1,418 @@
1
+ #!/usr/bin/env node
2
+ // previewer — upload banners to Previewer from any folder, and check on them.
3
+ // Run `previewer help` for the commands. See cli/README.md.
4
+
5
+ import { spawn } from 'node:child_process';
6
+ import { readFileSync } from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { createInterface } from 'node:readline/promises';
10
+ import { parseArgs } from 'node:util';
11
+ import { PreviewerClient, PreviewerError, newCliToken } from '../lib/api.mjs';
12
+ import { collectUploads } from '../lib/files.mjs';
13
+ import { selectMenu } from '../lib/menu.mjs';
14
+ import { DEFAULT_SITE, PROJECT_FILE, findProject, forgetSiteLogin, normalizeSite, resolveAuth, saveProject, saveSiteLogin } from '../lib/config.mjs';
15
+
16
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
17
+ const interactive = process.stdin.isTTY && process.stdout.isTTY;
18
+ const color = (code) => (text) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : String(text));
19
+ const bold = color(1);
20
+ const dim = color(2);
21
+ const green = color(32);
22
+ const red = color(31);
23
+ const yellow = color(33);
24
+ const cyan = color(36);
25
+
26
+ const say = (...lines) => console.log(lines.join('\n'));
27
+ const fail = (message, hint) => {
28
+ console.error(`${red('✖')} ${message}`);
29
+ if (hint) console.error(` ${dim(hint)}`);
30
+ process.exit(1);
31
+ };
32
+
33
+ const HELP = `${bold('previewer')} ${dim(VERSION)} — upload banners to Previewer and check on them
34
+
35
+ ${bold('Usage')}
36
+ previewer login Sign in (opens the browser to approve)
37
+ previewer push [folder] Upload a folder: ZIPs, banner folders, images, videos, backups
38
+ previewer status Approvals and views of this folder's campaign
39
+ previewer open Open the campaign's preview link
40
+ previewer link Choose which campaign this folder publishes to
41
+ previewer campaigns List campaigns
42
+ previewer whoami Show who you're signed in as
43
+ previewer logout Sign out (revokes this computer's token)
44
+
45
+ ${bold('Options')}
46
+ --client <name|id> Client to publish to (push, link, campaigns)
47
+ --campaign <name|id> Campaign to publish to (push, link, status, open)
48
+ --create Create the campaign if it doesn't exist (push)
49
+ --dry-run Show what push would upload, upload nothing
50
+ --open Open the preview after push
51
+ --json Machine-readable output (status, campaigns, whoami)
52
+ --site <url> Previewer address (default ${DEFAULT_SITE})
53
+
54
+ ${bold('In CI')}
55
+ Set PREVIEWER_TOKEN (create one under API in the Previewer admin), then:
56
+ previewer push dist --campaign 42
57
+
58
+ ${bold('Folders')}
59
+ *.zip and folders with an index.html are HTML5 banners. An image with the same name as a banner
60
+ (300x250.zip + 300x250.jpg), or in a backups/ folder, is its backup image. Other images and videos
61
+ are creatives. The first push saves the campaign to ${PROJECT_FILE}; after that, just run push.`;
62
+
63
+ // --- small helpers -------------------------------------------------------------------------------
64
+
65
+ // PREVIEWER_NO_BROWSER=1 (or no terminal, e.g. over SSH or in CI) prints the link instead.
66
+ const openInBrowser = (url) => {
67
+ if (process.env.PREVIEWER_NO_BROWSER || !interactive) return false;
68
+ const [command, args] =
69
+ process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
70
+ try {
71
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => undefined).unref();
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ };
77
+
78
+ const copyToClipboard = (text) =>
79
+ new Promise((resolve) => {
80
+ const [command, args] =
81
+ process.platform === 'darwin' ? ['pbcopy', []] : process.platform === 'win32' ? ['clip', []] : ['xclip', ['-selection', 'clipboard']];
82
+ try {
83
+ const child = spawn(command, args, { stdio: ['pipe', 'ignore', 'ignore'] });
84
+ child.on('error', () => resolve(false));
85
+ child.on('close', (code) => resolve(code === 0));
86
+ child.stdin.end(text);
87
+ } catch {
88
+ resolve(false);
89
+ }
90
+ });
91
+
92
+ const ago = (iso) => {
93
+ if (!iso) return null;
94
+ const minutes = Math.round((Date.now() - Date.parse(iso)) / 60000);
95
+ if (minutes < 1) return 'just now';
96
+ if (minutes < 60) return `${minutes} min ago`;
97
+ const hours = Math.round(minutes / 60);
98
+ if (hours < 24) return `${hours} h ago`;
99
+ const days = Math.round(hours / 24);
100
+ return days === 1 ? 'yesterday' : `${days} days ago`;
101
+ };
102
+
103
+ const kb = (bytes) => (bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`);
104
+
105
+ const ask = async (question) => {
106
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
107
+ try {
108
+ return (await rl.question(question)).trim();
109
+ } finally {
110
+ rl.close();
111
+ }
112
+ };
113
+
114
+ // An arrow-key menu (type to filter) in a terminal that supports it, otherwise a numbered list.
115
+ const CANCELLED = Symbol('cancelled');
116
+ const choose = async (title, options) => {
117
+ if (typeof process.stdin.setRawMode === 'function') {
118
+ const picked = await selectMenu(title, options, { style: { bold, dim, accent: cyan }, cancelled: CANCELLED });
119
+ if (picked === CANCELLED) process.exit(130);
120
+ return picked;
121
+ }
122
+ say('', bold(title));
123
+ options.forEach((option, index) => say(` ${dim(`${index + 1}.`)} ${option.label}`));
124
+ for (;;) {
125
+ const answer = Number(await ask(`Choose 1-${options.length}: `));
126
+ if (Number.isInteger(answer) && answer >= 1 && answer <= options.length) return options[answer - 1].value;
127
+ }
128
+ };
129
+
130
+ const confirm = async (question) => /^y(es)?$/i.test(await ask(`${question} [y/N] `));
131
+
132
+ const matchName = (items, wanted, key = 'name') => {
133
+ const needle = String(wanted).trim().toLowerCase();
134
+ return items.filter((item) => String(item[key]).toLowerCase() === needle);
135
+ };
136
+
137
+ // --- auth ----------------------------------------------------------------------------------------
138
+
139
+ const clientFor = async (options, project) => {
140
+ const auth = await resolveAuth({ site: options.site, project });
141
+ if (!auth.token) fail(`Not signed in to ${auth.site}.`, 'Run: previewer login');
142
+ return { client: new PreviewerClient({ baseUrl: auth.site, token: auth.token, userAgent: `previewer-cli/${VERSION}` }), auth };
143
+ };
144
+
145
+ const explain = (error) => {
146
+ if (!(error instanceof PreviewerError)) throw error;
147
+ const hint =
148
+ error.code === 'auth'
149
+ ? process.env.PREVIEWER_TOKEN
150
+ ? 'Check PREVIEWER_TOKEN.'
151
+ : 'Run: previewer login'
152
+ : error.code === 'forbidden'
153
+ ? 'Your token can\'t do this. Ask an owner, or sign in again with previewer login.'
154
+ : error.code === 'not_found'
155
+ ? 'Check the id, or that your token can reach it.'
156
+ : undefined;
157
+ fail(error.message, hint);
158
+ };
159
+
160
+ async function login(options) {
161
+ const config = await resolveAuth({ site: options.site });
162
+ const site = normalizeSite(options.site || config.site);
163
+ const api = new PreviewerClient({ baseUrl: site, userAgent: `previewer-cli/${VERSION}` });
164
+ const { token, hash, hint } = newCliToken();
165
+ const name = `${os.userInfo().username}@${os.hostname().replace(/\.local$/, '')}`;
166
+ const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: name });
167
+ const url = `${site}${started.verifyPath}`;
168
+
169
+ say('', `Your code: ${bold(started.userCode)}`, '', `Approve it in the browser: ${url}`);
170
+ say(openInBrowser(url) ? dim('(Opened your browser. Check that it shows the same code.)') : dim('(Open that link in your browser.)'));
171
+ say(dim('Waiting for approval…'));
172
+
173
+ const deadline = Date.parse(started.expiresAt);
174
+ while (Date.now() < deadline) {
175
+ await new Promise((resolve) => setTimeout(resolve, 2000));
176
+ const status = await api.loginStatus(started.requestId, token);
177
+ if (status === 'approved') {
178
+ const me = await new PreviewerClient({ baseUrl: site, token }).me();
179
+ await saveSiteLogin(site, { token, account: me.account });
180
+ say(`${green('✔')} Signed in to ${bold(me.account?.name ?? site)} (${me.token.permission}).`);
181
+ return;
182
+ }
183
+ if (status === 'denied') fail('The login was denied.');
184
+ if (status === 'expired') break;
185
+ }
186
+ fail('The login expired before it was approved.', 'Run previewer login again.');
187
+ }
188
+
189
+ async function logout(options) {
190
+ const auth = await resolveAuth({ site: options.site });
191
+ if (!auth.token || auth.fromEnv) fail(auth.fromEnv ? 'Signed in through PREVIEWER_TOKEN; unset it instead.' : `Not signed in to ${auth.site}.`);
192
+ try {
193
+ await new PreviewerClient({ baseUrl: auth.site, token: auth.token }).revokeSelf();
194
+ } catch (error) {
195
+ if (!(error instanceof PreviewerError) || error.code !== 'auth') throw error;
196
+ }
197
+ await forgetSiteLogin(auth.site);
198
+ say(`${green('✔')} Signed out of ${auth.site}. This computer's token is revoked.`);
199
+ }
200
+
201
+ async function whoami(options) {
202
+ const { client, auth } = await clientFor(options);
203
+ const me = await client.me();
204
+ if (options.json) return say(JSON.stringify({ site: auth.site, ...me }, null, 2));
205
+ const scope = me.token.campaignId ? `campaign ${me.token.campaignId}` : me.token.clientId ? `client ${me.token.clientId}` : 'the whole account';
206
+ say(`${bold(me.account?.name ?? '?')} on ${auth.site}`, `${me.token.name} · ${me.token.permission} · ${scope}${auth.fromEnv ? ' · from PREVIEWER_TOKEN' : ''}`);
207
+ }
208
+
209
+ // --- campaigns -----------------------------------------------------------------------------------
210
+
211
+ const resolveClient = async (api, wanted) => {
212
+ const clients = await api.clients();
213
+ if (/^\d+$/.test(String(wanted))) {
214
+ const byId = clients.find((client) => client.id === Number(wanted));
215
+ if (byId) return byId;
216
+ }
217
+ const matches = matchName(clients, wanted);
218
+ if (matches.length === 1) return matches[0];
219
+ fail(
220
+ matches.length ? `Several clients are called "${wanted}".` : `No client "${wanted}".`,
221
+ clients.length ? `Clients: ${clients.map((client) => client.name).join(', ')}` : 'Create the client in the Previewer admin first.',
222
+ );
223
+ };
224
+
225
+ /** The campaign to work on, from flags, the folder's link, or (in a terminal) a picker. */
226
+ const resolveCampaign = async (api, options, project, { allowCreate = false } = {}) => {
227
+ if (options.campaign && /^\d+$/.test(options.campaign)) return { campaign: await api.campaign(Number(options.campaign)), fromFlags: true };
228
+ if (options.campaign) {
229
+ const clientId = options.client ? (await resolveClient(api, options.client)).id : project?.clientId;
230
+ const campaigns = await api.campaigns(clientId ? { clientId } : {});
231
+ const matches = matchName(campaigns, options.campaign);
232
+ if (matches.length === 1) return { campaign: await api.campaign(matches[0].id), fromFlags: true };
233
+ if (matches.length > 1) fail(`Several campaigns are called "${options.campaign}".`, 'Add --client, or use the campaign id.');
234
+ if (!allowCreate) fail(`No campaign "${options.campaign}".`, 'Add --create to make it.');
235
+ if (!clientId) fail(`No campaign "${options.campaign}" yet. Which client is it for?`, 'Add --client <name>.');
236
+ if (!options.create && !(interactive && (await confirm(`Create campaign "${options.campaign}"?`)))) fail('Nothing uploaded.');
237
+ const created = await api.createCampaign({ clientId, name: options.campaign });
238
+ say(`${green('✔')} Created campaign ${bold(created.name)}.`);
239
+ return { campaign: created, fromFlags: true, created: true };
240
+ }
241
+ if (project?.campaignId) return { campaign: await api.campaign(project.campaignId), fromFlags: false };
242
+ if (!interactive) fail('Which campaign? This folder has no ' + PROJECT_FILE + '.', 'Add --campaign <name|id> (and --client <name>).');
243
+ return pickCampaign(api, options, { allowCreate });
244
+ };
245
+
246
+ const pickCampaign = async (api, options, { allowCreate }) => {
247
+ const client = options.client
248
+ ? await resolveClient(api, options.client)
249
+ : await (async () => {
250
+ const clients = await api.clients();
251
+ if (clients.length === 0) fail('No clients you can reach.', 'Create one in the Previewer admin.');
252
+ return clients.length === 1 ? clients[0] : choose('Client', clients.map((item) => ({ label: item.name, value: item })));
253
+ })();
254
+ const campaigns = await api.campaigns({ clientId: client.id });
255
+ const NEW = Symbol('new');
256
+ const picked = await choose(`Campaign for ${client.name}`, [
257
+ ...campaigns.map((item) => ({ label: `${item.name} ${dim(`(${item.bannerCount} banners)`)}`, value: item })),
258
+ ...(allowCreate ? [{ label: green('+ New campaign'), value: NEW, sticky: true }] : []),
259
+ ]);
260
+ if (picked === NEW) {
261
+ const name = await ask('Campaign name: ');
262
+ if (!name) fail('Nothing created.');
263
+ const created = await api.createCampaign({ clientId: client.id, name });
264
+ say(`${green('✔')} Created campaign ${bold(created.name)}.`);
265
+ return { campaign: created, picked: true, created: true };
266
+ }
267
+ return { campaign: await api.campaign(picked.id), picked: true };
268
+ };
269
+
270
+ const rememberCampaign = async (site, campaign, project) => {
271
+ if (project?.campaignId === campaign.id && project?.site === site) return;
272
+ const file = await saveProject(process.cwd(), { site, campaignId: campaign.id, clientId: campaign.client.id, client: campaign.client.name, campaign: campaign.name });
273
+ say(dim(`Saved to ${path.relative(process.cwd(), file) || file}: next time just run previewer push.`));
274
+ };
275
+
276
+ async function link(options) {
277
+ const project = await findProject(process.cwd());
278
+ const { client: api, auth } = await clientFor(options, project);
279
+ const { campaign } = await resolveCampaign(api, { ...options, campaign: options.campaign }, null, { allowCreate: true });
280
+ await rememberCampaign(auth.site, campaign, null);
281
+ say(`${green('✔')} This folder publishes to ${bold(`${campaign.client.name} → ${campaign.name}`)}.`);
282
+ }
283
+
284
+ async function listCampaigns(options) {
285
+ const { client: api } = await clientFor(options);
286
+ const clientId = options.client ? (await resolveClient(api, options.client)).id : undefined;
287
+ const campaigns = await api.campaigns(clientId ? { clientId } : {});
288
+ if (options.json) return say(JSON.stringify(campaigns, null, 2));
289
+ if (campaigns.length === 0) return say('No campaigns.');
290
+ for (const campaign of campaigns) {
291
+ const approvals = campaign.approvedCount === null ? '' : ` · ${campaign.approvedCount}/${campaign.bannerCount} approved`;
292
+ say(`${dim(String(campaign.id).padStart(5))} ${bold(campaign.name)} ${dim(`— ${campaign.client.name}`)}`, ` ${campaign.bannerCount} banners${approvals} · ${campaign.previewUrl}`);
293
+ }
294
+ }
295
+
296
+ // --- push / status / open ------------------------------------------------------------------------
297
+
298
+ async function push(options, folder = '.') {
299
+ const dir = path.resolve(folder);
300
+ const { items, skipped } = await collectUploads(dir).catch((error) =>
301
+ fail(error.code === 'ENOENT' ? `No folder ${folder}.` : `Could not read ${folder}: ${error.message}`),
302
+ );
303
+ for (const item of skipped) say(`${yellow('!')} Skipped ${item.name}: ${item.reason}`);
304
+ if (items.length === 0) fail(`Nothing to upload in ${folder}.`, 'Expected ZIPs, banner folders with an index.html, images or videos.');
305
+
306
+ const counts = ['banner', 'media', 'backup'].map((type) => items.filter((item) => item.type === type).length);
307
+ const total = items.reduce((sum, item) => sum + item.size, 0);
308
+ const summary = [
309
+ counts[0] && `${counts[0]} HTML5 banner${counts[0] === 1 ? '' : 's'}`,
310
+ counts[1] && `${counts[1]} image/video creative${counts[1] === 1 ? '' : 's'}`,
311
+ counts[2] && `${counts[2]} backup image${counts[2] === 1 ? '' : 's'}`,
312
+ ]
313
+ .filter(Boolean)
314
+ .join(', ');
315
+
316
+ if (options['dry-run']) {
317
+ say(`${bold('Would upload')} ${summary} (${kb(total)}):`);
318
+ for (const item of items) say(` ${dim(item.type.padEnd(6))} ${item.source}${item.source !== item.name ? dim(` → ${item.name}`) : ''} ${dim(kb(item.size))}`);
319
+ return;
320
+ }
321
+
322
+ const project = await findProject(process.cwd());
323
+ const { client: api, auth } = await clientFor(options, project);
324
+ const { campaign, picked, created } = await resolveCampaign(api, options, project, { allowCreate: true });
325
+ say(`Uploading ${summary} (${kb(total)}) to ${bold(`${campaign.client.name} → ${campaign.name}`)}…`);
326
+
327
+ const result = await api.upload(campaign.id, items, {
328
+ onProgress: (done, parts) => {
329
+ if (parts > 1) process.stdout.write(dim(` part ${done}/${parts}\n`));
330
+ },
331
+ });
332
+ const replaced = result.uploaded.filter((id) => campaign.banners?.some((banner) => banner.id === id)).length;
333
+ say(
334
+ `${green('✔')} Uploaded ${result.uploaded.length} creative${result.uploaded.length === 1 ? '' : 's'}${replaced ? ` (${replaced} new version${replaced === 1 ? '' : 's'})` : ''}${counts[2] ? ` and ${counts[2]} backup${counts[2] === 1 ? '' : 's'}` : ''}.`,
335
+ ` The campaign now has ${result.campaign.bannerCount} banner${result.campaign.bannerCount === 1 ? '' : 's'}.`,
336
+ );
337
+ if (picked || created || !project) await rememberCampaign(auth.site, result.campaign, project);
338
+ if (result.campaign.previewUrl) {
339
+ const copied = interactive && (await copyToClipboard(result.campaign.previewUrl));
340
+ say('', `${bold(result.campaign.previewUrl)}${copied ? dim(' (copied)') : ''}`);
341
+ if (options.open) openInBrowser(result.campaign.previewUrl);
342
+ }
343
+ }
344
+
345
+ async function status(options) {
346
+ const project = await findProject(process.cwd());
347
+ const { client: api } = await clientFor(options, project);
348
+ const { campaign } = await resolveCampaign(api, options, project);
349
+ if (options.json) return say(JSON.stringify(campaign, null, 2));
350
+
351
+ const reviewable = campaign.banners.filter((banner) => banner.kind !== 'external');
352
+ const approved = reviewable.filter((banner) => banner.status === 'approved').length;
353
+ say(
354
+ `${bold(`${campaign.client.name} → ${campaign.name}`)}`,
355
+ campaign.previewUrl ?? '',
356
+ [
357
+ `${campaign.bannerCount} banner${campaign.bannerCount === 1 ? '' : 's'}`,
358
+ campaign.approvalsRequired ? `${approved}/${reviewable.length} approved` : 'approvals off',
359
+ campaign.lastViewedAt ? `opened by the client ${ago(campaign.lastViewedAt)}` : 'not opened by the client yet',
360
+ ].join(' · '),
361
+ '',
362
+ );
363
+ const width = Math.max(10, ...campaign.banners.map((banner) => banner.label.length));
364
+ for (const banner of campaign.banners) {
365
+ const approvedNow = banner.status === 'approved';
366
+ const state = !campaign.approvalsRequired ? ''.padEnd(9) : (approvedNow ? green : yellow)((approvedNow ? 'approved' : 'in review').padEnd(9));
367
+ const backup = banner.kind !== 'html' ? ''.padEnd(9) : banner.hasBackup ? dim('backup ✓'.padEnd(9)) : yellow('no backup');
368
+ say(` ${banner.label.padEnd(width)} ${dim(`${banner.width}×${banner.height}`.padEnd(9))} ${state} ${backup} ${dim(ago(banner.updatedAt) ?? '')}`);
369
+ }
370
+ }
371
+
372
+ async function open(options) {
373
+ const project = await findProject(process.cwd());
374
+ const { client: api } = await clientFor(options, project);
375
+ const { campaign } = await resolveCampaign(api, options, project);
376
+ if (!campaign.previewUrl) fail('This campaign has no preview link yet.');
377
+ say(campaign.previewUrl);
378
+ openInBrowser(campaign.previewUrl);
379
+ }
380
+
381
+ // --- main ----------------------------------------------------------------------------------------
382
+
383
+ const COMMANDS = { login, logout, whoami, push, status, open, link, campaigns: listCampaigns };
384
+
385
+ const main = async () => {
386
+ let parsed;
387
+ try {
388
+ parsed = parseArgs({
389
+ allowPositionals: true,
390
+ options: {
391
+ client: { type: 'string' },
392
+ campaign: { type: 'string' },
393
+ create: { type: 'boolean' },
394
+ 'dry-run': { type: 'boolean' },
395
+ open: { type: 'boolean' },
396
+ json: { type: 'boolean' },
397
+ site: { type: 'string' },
398
+ help: { type: 'boolean', short: 'h' },
399
+ version: { type: 'boolean', short: 'v' },
400
+ },
401
+ });
402
+ } catch (error) {
403
+ fail(error.message, 'Run previewer help.');
404
+ }
405
+ const { values, positionals } = parsed;
406
+ if (values.version) return say(VERSION);
407
+ const [command, ...rest] = positionals;
408
+ if (!command || values.help || command === 'help') return say(HELP);
409
+ const run = COMMANDS[command];
410
+ if (!run) fail(`Unknown command "${command}".`, 'Run previewer help.');
411
+ try {
412
+ await run(values, ...rest);
413
+ } catch (error) {
414
+ explain(error);
415
+ }
416
+ };
417
+
418
+ main();
package/lib/api.mjs ADDED
@@ -0,0 +1,235 @@
1
+ // Client for the Previewer API v1 (docs/api.md). No dependencies: Node's own fetch, FormData and
2
+ // Blob (Node >= 20). Used by the `previewer` command and meant to be reused by other tools (ddf).
3
+
4
+ import { createHash, randomBytes } from 'node:crypto';
5
+ import { readFile } from 'node:fs/promises';
6
+
7
+ export class PreviewerError extends Error {
8
+ constructor(message, { status, code } = {}) {
9
+ super(message);
10
+ this.name = 'PreviewerError';
11
+ this.status = status;
12
+ this.code = code;
13
+ }
14
+ }
15
+
16
+ // Vercel caps one request body at 4.5 MB. Small files go in batches under 4 MB; anything over
17
+ // 3.5 MB is uploaded straight to storage first (upload-urls) and then registered.
18
+ const MAX_BATCH_BYTES = 4 * 1024 * 1024;
19
+ const DIRECT_ABOVE_BYTES = 3.5 * 1024 * 1024;
20
+
21
+ const codeForStatus = (status) =>
22
+ status === 401 ? 'auth' : status === 403 ? 'forbidden' : status === 404 ? 'not_found' : status === 409 ? 'conflict' : status === 429 ? 'rate_limit' : 'http';
23
+
24
+ export const newCliToken = () => {
25
+ const token = `pvw_${randomBytes(32).toString('base64url')}`;
26
+ return { token, hash: createHash('sha256').update(token).digest('hex'), hint: token.slice(-4) };
27
+ };
28
+
29
+ /** Greedily pack `{ size }` items into batches under `limit` bytes (an oversize item goes alone). */
30
+ export const packBatches = (items, limit = MAX_BATCH_BYTES) => {
31
+ const batches = [];
32
+ let current = [];
33
+ let bytes = 0;
34
+ for (const item of items) {
35
+ if (current.length > 0 && bytes + item.size > limit) {
36
+ batches.push(current);
37
+ current = [];
38
+ bytes = 0;
39
+ }
40
+ current.push(item);
41
+ bytes += item.size;
42
+ }
43
+ if (current.length > 0) batches.push(current);
44
+ return batches;
45
+ };
46
+
47
+ export class PreviewerClient {
48
+ /** @param {{ baseUrl: string, token?: string, userAgent?: string }} options */
49
+ constructor({ baseUrl, token, userAgent = 'previewer-cli' }) {
50
+ this.baseUrl = String(baseUrl).replace(/\/+$/, '');
51
+ this.token = token;
52
+ this.userAgent = userAgent;
53
+ }
54
+
55
+ async request(method, path, { json, form, token = this.token, allowStatus = [] } = {}) {
56
+ const headers = { 'User-Agent': this.userAgent, Accept: 'application/json' };
57
+ if (token) headers.Authorization = `Bearer ${token}`;
58
+ let body;
59
+ if (json !== undefined) {
60
+ headers['Content-Type'] = 'application/json';
61
+ body = JSON.stringify(json);
62
+ } else if (form) {
63
+ body = form;
64
+ }
65
+ let response;
66
+ try {
67
+ response = await fetch(`${this.baseUrl}${path}`, { method, headers, body });
68
+ } catch (error) {
69
+ throw new PreviewerError(`Could not reach ${this.baseUrl}: ${error.cause?.message || error.message}`, { code: 'network' });
70
+ }
71
+ let data = null;
72
+ try {
73
+ data = await response.json();
74
+ } catch {
75
+ data = null;
76
+ }
77
+ if (response.ok || allowStatus.includes(response.status)) return { status: response.status, data };
78
+ const message =
79
+ data?.error ||
80
+ (response.status === 413 ? 'The request was too large for the server.' : `${method} ${path} failed (HTTP ${response.status}).`);
81
+ throw new PreviewerError(message, { status: response.status, code: codeForStatus(response.status) });
82
+ }
83
+
84
+ async me() {
85
+ return (await this.request('GET', '/api/v1/me')).data;
86
+ }
87
+
88
+ async revokeSelf() {
89
+ return (await this.request('DELETE', '/api/v1/me')).data;
90
+ }
91
+
92
+ async clients() {
93
+ return (await this.request('GET', '/api/v1/clients')).data.clients;
94
+ }
95
+
96
+ async campaigns({ clientId } = {}) {
97
+ const query = clientId ? `?client=${Number(clientId)}` : '';
98
+ return (await this.request('GET', `/api/v1/campaigns${query}`)).data.campaigns;
99
+ }
100
+
101
+ async campaign(id) {
102
+ return (await this.request('GET', `/api/v1/campaigns/${Number(id)}`)).data.campaign;
103
+ }
104
+
105
+ async createCampaign({ clientId, name }) {
106
+ return (await this.request('POST', '/api/v1/campaigns', { json: { clientId, name } })).data.campaign;
107
+ }
108
+
109
+ async removeBanner(campaignId, bannerId) {
110
+ return (await this.request('DELETE', `/api/v1/campaigns/${Number(campaignId)}/banners/${encodeURIComponent(bannerId)}`)).data;
111
+ }
112
+
113
+ // --- previewer login ---------------------------------------------------------------------
114
+
115
+ async startLogin({ tokenHash, tokenHint, clientName }) {
116
+ return (await this.request('POST', '/api/v1/cli-login', { json: { tokenHash, tokenHint, clientName }, token: null })).data;
117
+ }
118
+
119
+ async loginStatus(requestId, token) {
120
+ return (await this.request('GET', `/api/v1/cli-login?request=${Number(requestId)}`, { token })).data.status;
121
+ }
122
+
123
+ // --- uploads -------------------------------------------------------------------------------
124
+
125
+ /**
126
+ * Upload creatives and backups to a campaign. Each item: { name, size, path? | buffer?, type }
127
+ * where type is 'banner' (HTML5 ZIP), 'media' (image/video, with width/height) or 'backup'.
128
+ * Splits into requests under the 4.5 MB cap; big files go straight to storage first.
129
+ * Backups go last, so their banners already exist. Not atomic: a failure part-way leaves the
130
+ * earlier parts saved, and running it again is safe (same names replace in place).
131
+ * @returns {Promise<{ uploaded: string[], campaign: object }>}
132
+ */
133
+ async upload(campaignId, items, { onProgress } = {}) {
134
+ const read = async (item) => item.buffer ?? (await readFile(item.path));
135
+ const banners = items.filter((item) => item.type === 'banner');
136
+ const media = items.filter((item) => item.type === 'media');
137
+ const backups = items.filter((item) => item.type === 'backup');
138
+ const bigZips = banners.filter((item) => item.size > DIRECT_ABOVE_BYTES);
139
+ const bigMedia = media.filter((item) => item.size > DIRECT_ABOVE_BYTES);
140
+ const smallBatches = packBatches([
141
+ ...banners.filter((item) => item.size <= DIRECT_ABOVE_BYTES),
142
+ ...media.filter((item) => item.size <= DIRECT_ABOVE_BYTES),
143
+ ]);
144
+ const backupBatches = packBatches(backups);
145
+ const total = (bigZips.length ? 1 : 0) + (bigMedia.length ? 1 : 0) + smallBatches.length + backupBatches.length;
146
+
147
+ const uploaded = [];
148
+ let campaign = null;
149
+ let done = 0;
150
+ const send = async (fill) => {
151
+ const form = new FormData();
152
+ await fill(form);
153
+ const { data } = await this.request('POST', `/api/v1/campaigns/${Number(campaignId)}/banners`, { form });
154
+ uploaded.push(...(data.uploaded || []));
155
+ campaign = data.campaign;
156
+ done += 1;
157
+ onProgress?.(done, total);
158
+ };
159
+
160
+ if (bigZips.length) {
161
+ const targets = await this.signUploads(campaignId, 'zip', bigZips);
162
+ for (const [index, item] of bigZips.entries()) await putToStorage(targets, targets.uploads[index], await read(item), 'application/zip');
163
+ await send((form) => form.append('stagedZips', JSON.stringify(targets.uploads.map((target) => ({ name: target.name, key: target.key })))));
164
+ }
165
+ if (bigMedia.length) {
166
+ const targets = await this.signUploads(campaignId, 'media', bigMedia);
167
+ for (const [index, item] of bigMedia.entries()) await putToStorage(targets, targets.uploads[index], await read(item), item.mimeType);
168
+ await send((form) =>
169
+ form.append(
170
+ 'preUploadedMedia',
171
+ JSON.stringify(targets.uploads.map((target) => ({ name: target.name, key: target.key, width: target.width, height: target.height }))),
172
+ ),
173
+ );
174
+ }
175
+ for (const batch of smallBatches) {
176
+ await send(async (form) => {
177
+ const meta = [];
178
+ for (const item of batch) {
179
+ const blob = new Blob([await read(item)], { type: item.mimeType || 'application/octet-stream' });
180
+ if (item.type === 'banner') {
181
+ form.append('banners[]', blob, item.name);
182
+ } else {
183
+ form.append('media[]', blob, item.name);
184
+ if (item.width && item.height) meta.push({ name: item.name, width: item.width, height: item.height });
185
+ }
186
+ }
187
+ if (meta.length) form.append('mediaMeta', JSON.stringify(meta));
188
+ });
189
+ }
190
+ for (const batch of backupBatches) {
191
+ await send(async (form) => {
192
+ for (const item of batch) form.append('backups[]', new Blob([await read(item)], { type: item.mimeType }), item.name);
193
+ });
194
+ }
195
+ if (!campaign) throw new PreviewerError('Nothing to upload.', { code: 'empty' });
196
+ return { uploaded, campaign };
197
+ }
198
+
199
+ async signUploads(campaignId, kind, items) {
200
+ const files = items.map((item) => ({
201
+ name: item.name,
202
+ size: item.size,
203
+ contentType: item.mimeType,
204
+ ...(item.width && item.height ? { width: item.width, height: item.height } : {}),
205
+ }));
206
+ return (await this.request('POST', `/api/v1/campaigns/${Number(campaignId)}/upload-urls`, { json: { kind, files } })).data;
207
+ }
208
+ }
209
+
210
+ /** PUT bytes to a signed storage upload target (what supabase-js uploadToSignedUrl does). */
211
+ async function putToStorage(config, target, buffer, contentType) {
212
+ const url = new URL(`${config.supabaseUrl}/storage/v1/object/upload/sign/${config.bucket}/${String(target.key).replace(/^\/+/, '')}`);
213
+ url.searchParams.set('token', target.token);
214
+ let response;
215
+ try {
216
+ response = await fetch(url, {
217
+ method: 'PUT',
218
+ headers: {
219
+ apikey: config.supabaseAnonKey,
220
+ Authorization: `Bearer ${config.supabaseAnonKey}`,
221
+ 'x-upsert': 'true',
222
+ 'content-type': contentType || 'application/octet-stream',
223
+ },
224
+ body: buffer,
225
+ });
226
+ } catch (error) {
227
+ throw new PreviewerError(`Upload of ${target.name} to storage failed: ${error.message}`, { code: 'network' });
228
+ }
229
+ if (!response.ok) {
230
+ const data = await response.json().catch(() => null);
231
+ throw new PreviewerError(data?.message || data?.error || `Upload of ${target.name} to storage failed (HTTP ${response.status}).`, {
232
+ status: response.status,
233
+ });
234
+ }
235
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // Where the CLI keeps things:
2
+ // - Sign-in per site: ~/.config/previewer/config.json (%APPDATA%\previewer on Windows), readable
3
+ // only by you (600). PREVIEWER_TOKEN / PREVIEWER_URL override it, for CI.
4
+ // - Which campaign a folder publishes to: .previewer.json in that folder (safe to commit: ids only).
5
+
6
+ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+
10
+ export const DEFAULT_SITE = 'https://previewer.agency';
11
+ export const PROJECT_FILE = '.previewer.json';
12
+
13
+ export const normalizeSite = (value) => String(value || '').trim().replace(/\/+$/, '');
14
+
15
+ const configDir = () =>
16
+ process.platform === 'win32'
17
+ ? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'previewer')
18
+ : path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'previewer');
19
+ export const configPath = () => path.join(configDir(), 'config.json');
20
+
21
+ export const loadConfig = async () => {
22
+ try {
23
+ const data = JSON.parse(await readFile(configPath(), 'utf8'));
24
+ return data && typeof data === 'object' ? data : {};
25
+ } catch (error) {
26
+ if (error.code === 'ENOENT') return {};
27
+ throw new Error(`Could not read ${configPath()}: ${error.message}`);
28
+ }
29
+ };
30
+
31
+ export const saveConfig = async (config) => {
32
+ await mkdir(configDir(), { recursive: true, mode: 0o700 });
33
+ await writeFile(configPath(), `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
34
+ await chmod(configPath(), 0o600).catch(() => undefined);
35
+ };
36
+
37
+ /** The site and token to use: flags, then environment, then the folder's link, then the saved default. */
38
+ export const resolveAuth = async ({ site: siteFlag, project } = {}) => {
39
+ const config = await loadConfig();
40
+ const site = normalizeSite(siteFlag || process.env.PREVIEWER_URL || project?.site || config.defaultSite || DEFAULT_SITE);
41
+ const envToken = String(process.env.PREVIEWER_TOKEN || '').trim();
42
+ const saved = config.sites?.[site];
43
+ return { site, token: envToken || saved?.token || '', fromEnv: Boolean(envToken), account: saved?.account ?? null, config };
44
+ };
45
+
46
+ export const saveSiteLogin = async (site, { token, account }) => {
47
+ const config = await loadConfig();
48
+ config.sites = { ...(config.sites || {}), [site]: { token, account, savedAt: new Date().toISOString() } };
49
+ config.defaultSite = site;
50
+ await saveConfig(config);
51
+ };
52
+
53
+ export const forgetSiteLogin = async (site) => {
54
+ const config = await loadConfig();
55
+ if (config.sites?.[site]) delete config.sites[site];
56
+ await saveConfig(config);
57
+ };
58
+
59
+ /** The nearest .previewer.json from `dir` upwards, or null. */
60
+ export const findProject = async (dir) => {
61
+ let current = path.resolve(dir);
62
+ for (;;) {
63
+ const file = path.join(current, PROJECT_FILE);
64
+ try {
65
+ return { file, ...JSON.parse(await readFile(file, 'utf8')) };
66
+ } catch (error) {
67
+ if (error.code !== 'ENOENT') throw new Error(`Could not read ${file}: ${error.message}`);
68
+ }
69
+ const parent = path.dirname(current);
70
+ if (parent === current) return null;
71
+ current = parent;
72
+ }
73
+ };
74
+
75
+ export const saveProject = async (dir, link) => {
76
+ const file = path.join(path.resolve(dir), PROJECT_FILE);
77
+ await writeFile(file, `${JSON.stringify(link, null, 2)}\n`);
78
+ return file;
79
+ };
package/lib/files.mjs ADDED
@@ -0,0 +1,240 @@
1
+ // Turns a folder into upload items for PreviewerClient.upload:
2
+ // - *.zip → HTML5 banner
3
+ // - a sub-folder with index.html → HTML5 banner, zipped on the fly
4
+ // - an image named like a banner (300x250.zip + 300x250.jpg), or any image in a backups/ or
5
+ // fallbacks/ sub-folder → that banner's backup image
6
+ // - any other image or video → an image/video creative
7
+ // Sizes come from the file itself (images, MP4) or a 300x250-style token in the name.
8
+
9
+ import { readdir, readFile, stat } from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { deflateRawSync } from 'node:zlib';
12
+
13
+ const IMAGE_RE = /\.(jpe?g|png|gif|webp)$/i;
14
+ const VIDEO_RE = /\.(mp4|webm)$/i;
15
+ const BACKUP_DIRS = new Set(['backups', 'backup', 'fallbacks', 'fallback']);
16
+ const SKIP = /^(\.|__MACOSX$|node_modules$|Thumbs\.db$)/;
17
+ const MIME = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.mp4': 'video/mp4', '.webm': 'video/webm', '.zip': 'application/zip' };
18
+
19
+ const SIZE_RE = /(\d{2,4})\s*x\s*(\d{2,4})/i;
20
+ export const sizeFromName = (name) => {
21
+ const match = String(name).match(SIZE_RE);
22
+ return match ? { width: Number(match[1]), height: Number(match[2]) } : null;
23
+ };
24
+
25
+ // Mirrors lib/shared/bannerIds.ts (HTML case): how the server ids a ZIP, so a backup can be named
26
+ // after exactly its banner.
27
+ const slug = (fileName) =>
28
+ (String(fileName).split(/[\\/]/).pop().replace(/\.[^.]+$/i, '') || 'creative')
29
+ .toLowerCase()
30
+ .trim()
31
+ .replace(/[^a-z0-9]+/g, '-')
32
+ .replace(/^-+|-+$/g, '') || 'creative';
33
+ export const bannerIdForZip = (zipName, size = sizeFromName(zipName)) => (size ? `${size.width}x${size.height}-${slug(zipName)}` : null);
34
+
35
+ const baseName = (name) => name.replace(/\.[^.]+$/, '');
36
+
37
+ // --- dimensions ----------------------------------------------------------------------------------
38
+
39
+ export const imageSize = (buffer) => {
40
+ try {
41
+ if (buffer.length > 24 && buffer.readUInt32BE(0) === 0x89504e47) return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
42
+ if (buffer.length > 10 && buffer.toString('ascii', 0, 3) === 'GIF') return { width: buffer.readUInt16LE(6), height: buffer.readUInt16LE(8) };
43
+ if (buffer.length > 30 && buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP') {
44
+ const chunk = buffer.toString('ascii', 12, 16);
45
+ if (chunk === 'VP8X') return { width: 1 + buffer.readUIntLE(24, 3), height: 1 + buffer.readUIntLE(27, 3) };
46
+ if (chunk === 'VP8L') {
47
+ const bits = buffer.readUInt32LE(21);
48
+ return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff) };
49
+ }
50
+ if (chunk === 'VP8 ') return { width: buffer.readUInt16LE(26) & 0x3fff, height: buffer.readUInt16LE(28) & 0x3fff };
51
+ }
52
+ if (buffer[0] === 0xff && buffer[1] === 0xd8) {
53
+ let offset = 2;
54
+ while (offset + 9 < buffer.length) {
55
+ if (buffer[offset] !== 0xff) return null;
56
+ const marker = buffer[offset + 1];
57
+ const length = buffer.readUInt16BE(offset + 2);
58
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
59
+ return { width: buffer.readUInt16BE(offset + 7), height: buffer.readUInt16BE(offset + 5) };
60
+ }
61
+ offset += 2 + length;
62
+ }
63
+ }
64
+ } catch {
65
+ return null;
66
+ }
67
+ return null;
68
+ };
69
+
70
+ // MP4/MOV: the display size sits in the first video track's `tkhd` box as 16.16 fixed point.
71
+ export const mp4Size = (buffer) => {
72
+ let from = 0;
73
+ for (;;) {
74
+ const at = buffer.indexOf('tkhd', from, 'ascii');
75
+ if (at < 4) return null;
76
+ const boxEnd = at - 4 + buffer.readUInt32BE(at - 4);
77
+ if (boxEnd <= buffer.length && boxEnd - 8 > at) {
78
+ const width = Math.round(buffer.readUInt32BE(boxEnd - 8) / 65536);
79
+ const height = Math.round(buffer.readUInt32BE(boxEnd - 4) / 65536);
80
+ if (width > 0 && height > 0) return { width, height };
81
+ }
82
+ from = at + 4;
83
+ }
84
+ };
85
+
86
+ // --- zip a banner folder ------------------------------------------------------------------------
87
+
88
+ const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
89
+ let c = n;
90
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
91
+ return c >>> 0;
92
+ });
93
+ const crc32 = (buffer) => {
94
+ let crc = 0xffffffff;
95
+ for (const byte of buffer) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
96
+ return (crc ^ 0xffffffff) >>> 0;
97
+ };
98
+
99
+ const listFiles = async (dir, prefix = '') => {
100
+ const out = [];
101
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
102
+ if (SKIP.test(entry.name)) continue;
103
+ const full = path.join(dir, entry.name);
104
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
105
+ if (entry.isDirectory()) out.push(...(await listFiles(full, rel)));
106
+ else if (entry.isFile()) out.push({ full, rel });
107
+ }
108
+ return out;
109
+ };
110
+
111
+ /** A minimal ZIP (deflate) of a folder's contents, paths relative to the folder. */
112
+ export const zipFolder = async (dir) => {
113
+ const locals = [];
114
+ const centrals = [];
115
+ let offset = 0;
116
+ for (const { full, rel } of await listFiles(dir)) {
117
+ const data = await readFile(full);
118
+ const compressed = deflateRawSync(data);
119
+ const name = Buffer.from(rel, 'utf8');
120
+ const crc = crc32(data);
121
+ const local = Buffer.alloc(30);
122
+ local.writeUInt32LE(0x04034b50, 0);
123
+ local.writeUInt16LE(20, 4);
124
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
125
+ local.writeUInt16LE(8, 8); // deflate
126
+ local.writeUInt32LE(crc, 14);
127
+ local.writeUInt32LE(compressed.length, 18);
128
+ local.writeUInt32LE(data.length, 22);
129
+ local.writeUInt16LE(name.length, 26);
130
+ const central = Buffer.alloc(46);
131
+ central.writeUInt32LE(0x02014b50, 0);
132
+ central.writeUInt16LE(20, 4);
133
+ central.writeUInt16LE(20, 6);
134
+ central.writeUInt16LE(0x0800, 8);
135
+ central.writeUInt16LE(8, 10);
136
+ central.writeUInt32LE(crc, 16);
137
+ central.writeUInt32LE(compressed.length, 20);
138
+ central.writeUInt32LE(data.length, 24);
139
+ central.writeUInt16LE(name.length, 28);
140
+ central.writeUInt32LE(offset, 42);
141
+ locals.push(local, name, compressed);
142
+ centrals.push(central, name);
143
+ offset += local.length + name.length + compressed.length;
144
+ }
145
+ const centralSize = centrals.reduce((sum, part) => sum + part.length, 0);
146
+ const end = Buffer.alloc(22);
147
+ end.writeUInt32LE(0x06054b50, 0);
148
+ end.writeUInt16LE(centrals.length / 2, 8);
149
+ end.writeUInt16LE(centrals.length / 2, 10);
150
+ end.writeUInt32LE(centralSize, 12);
151
+ end.writeUInt32LE(offset, 16);
152
+ return Buffer.concat([...locals, ...centrals, end]);
153
+ };
154
+
155
+ const adSizeFromHtml = (html) => {
156
+ const match = html.match(/<meta[^>]+name=["']ad\.size["'][^>]*content=["'][^"']*width=(\d+)[^"']*height=(\d+)/i);
157
+ return match ? { width: Number(match[1]), height: Number(match[2]) } : null;
158
+ };
159
+
160
+ // --- collect ------------------------------------------------------------------------------------
161
+
162
+ /**
163
+ * Everything in `dir` that can go up, as upload items, plus what was skipped and why.
164
+ * @returns {Promise<{ items: object[], skipped: Array<{ name: string, reason: string }> }>}
165
+ */
166
+ export const collectUploads = async (dir) => {
167
+ const items = [];
168
+ const skipped = [];
169
+ const images = [];
170
+ const bannerSizes = new Map(); // basename → { id }
171
+
172
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
173
+ if (SKIP.test(entry.name)) continue;
174
+ const full = path.join(dir, entry.name);
175
+ if (entry.isDirectory()) {
176
+ if (BACKUP_DIRS.has(entry.name.toLowerCase())) {
177
+ for (const inner of await readdir(full, { withFileTypes: true })) {
178
+ if (inner.isFile() && IMAGE_RE.test(inner.name)) images.push({ full: path.join(full, inner.name), name: inner.name, forceBackup: true });
179
+ }
180
+ continue;
181
+ }
182
+ const indexPath = path.join(full, 'index.html');
183
+ const indexStat = await stat(indexPath).catch(() => null);
184
+ if (!indexStat) {
185
+ skipped.push({ name: `${entry.name}/`, reason: 'folder without index.html' });
186
+ continue;
187
+ }
188
+ const size = adSizeFromHtml(await readFile(indexPath, 'utf8')) || sizeFromName(entry.name);
189
+ // Name the ZIP so the server finds the size even without an ad.size meta tag.
190
+ const zipName = sizeFromName(entry.name) || !size ? `${entry.name}.zip` : `${entry.name}-${size.width}x${size.height}.zip`;
191
+ const buffer = await zipFolder(full);
192
+ items.push({ type: 'banner', name: zipName, size: buffer.length, buffer, mimeType: MIME['.zip'], source: `${entry.name}/` });
193
+ bannerSizes.set(baseName(entry.name).toLowerCase(), { id: bannerIdForZip(zipName, size) });
194
+ continue;
195
+ }
196
+ if (!entry.isFile()) continue;
197
+ const info = await stat(full);
198
+ if (/\.zip$/i.test(entry.name)) {
199
+ items.push({ type: 'banner', name: entry.name, size: info.size, path: full, mimeType: MIME['.zip'], source: entry.name });
200
+ bannerSizes.set(baseName(entry.name).toLowerCase(), { id: bannerIdForZip(entry.name) });
201
+ } else if (IMAGE_RE.test(entry.name)) {
202
+ images.push({ full, name: entry.name, forceBackup: false });
203
+ } else if (VIDEO_RE.test(entry.name)) {
204
+ const head = await readFile(full);
205
+ const size = (/\.mp4$/i.test(entry.name) ? mp4Size(head) : null) || sizeFromName(entry.name);
206
+ if (!size) {
207
+ skipped.push({ name: entry.name, reason: 'video size unknown: put it in the name, e.g. intro-1080x1920.webm' });
208
+ continue;
209
+ }
210
+ items.push({ type: 'media', name: entry.name, size: info.size, path: full, mimeType: MIME[path.extname(entry.name).toLowerCase()], ...size, source: entry.name });
211
+ } else {
212
+ skipped.push({ name: entry.name, reason: 'not a ZIP, image or video' });
213
+ }
214
+ }
215
+
216
+ for (const image of images) {
217
+ const info = await stat(image.full);
218
+ const ext = path.extname(image.name).toLowerCase();
219
+ const pair = bannerSizes.get(baseName(image.name).toLowerCase());
220
+ if (image.forceBackup || pair) {
221
+ if (ext === '.gif') {
222
+ skipped.push({ name: image.name, reason: 'backup images must be JPG, PNG or WebP' });
223
+ continue;
224
+ }
225
+ // Named after its banner's id when known, so it lands on exactly that banner.
226
+ const name = pair?.id ? `${pair.id}${ext}` : image.name;
227
+ items.push({ type: 'backup', name, size: info.size, path: image.full, mimeType: MIME[ext], source: path.relative(dir, image.full) });
228
+ continue;
229
+ }
230
+ const buffer = await readFile(image.full);
231
+ const size = imageSize(buffer) || sizeFromName(image.name);
232
+ if (!size) {
233
+ skipped.push({ name: image.name, reason: 'image size unknown' });
234
+ continue;
235
+ }
236
+ items.push({ type: 'media', name: image.name, size: info.size, buffer, mimeType: MIME[ext], ...size, source: image.name });
237
+ }
238
+
239
+ return { items, skipped };
240
+ };
package/lib/menu.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // An arrow-key menu for the terminal, without dependencies: ↑/↓ to move, type to filter, Enter to
2
+ // choose, Esc to clear the filter (or cancel), Ctrl+C to cancel. `menuKey` and `menuLines` are pure,
3
+ // so the behaviour is tested without a terminal; `selectMenu` wires them to stdin/stdout.
4
+
5
+ import { emitKeypressEvents } from 'node:readline';
6
+
7
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
8
+ export const plain = (text) => String(text).replace(ANSI, '');
9
+
10
+ // Options marked `sticky` (like "+ New campaign") stay visible whatever the filter.
11
+ export const filterOptions = (options, query) => {
12
+ const needle = query.trim().toLowerCase();
13
+ if (!needle) return options;
14
+ return options.filter((option) => option.sticky || plain(option.label).toLowerCase().includes(needle));
15
+ };
16
+
17
+ export const initialMenuState = { query: '', index: 0, done: null, choice: undefined };
18
+
19
+ /** The next state after a keypress (`str` and `key` as readline's 'keypress' event gives them). */
20
+ export const menuKey = (state, options, str, key = {}) => {
21
+ const visible = filterOptions(options, state.query);
22
+ const count = visible.length;
23
+ if (key.ctrl && (key.name === 'c' || key.name === 'd')) return { ...state, done: 'cancel' };
24
+ switch (key.name) {
25
+ case 'escape':
26
+ return state.query ? { ...state, query: '', index: 0 } : { ...state, done: 'cancel' };
27
+ case 'up':
28
+ return { ...state, index: count ? (state.index - 1 + count) % count : 0 };
29
+ case 'down':
30
+ case 'tab':
31
+ return { ...state, index: count ? (state.index + 1) % count : 0 };
32
+ case 'home':
33
+ return { ...state, index: 0 };
34
+ case 'end':
35
+ return { ...state, index: Math.max(count - 1, 0) };
36
+ case 'return':
37
+ case 'enter':
38
+ return count ? { ...state, done: 'choose', choice: visible[Math.min(state.index, count - 1)] } : state;
39
+ case 'backspace':
40
+ return { ...state, query: state.query.slice(0, -1), index: 0 };
41
+ default:
42
+ if (str && !key.ctrl && !key.meta && /^[^\x00-\x1f\x7f]$/u.test(str)) return { ...state, query: state.query + str, index: 0 };
43
+ return state;
44
+ }
45
+ };
46
+
47
+ const fit = (line, columns) => {
48
+ const text = plain(line);
49
+ return text.length < columns ? line : `${text.slice(0, Math.max(columns - 2, 1))}…`;
50
+ };
51
+
52
+ /** The lines to draw for a state: a hint or the filter, then a window of options around the cursor. */
53
+ export const menuLines = (options, state, { rows = 24, columns = 80, style = {} } = {}) => {
54
+ const { dim = String, accent = String } = style;
55
+ const visible = filterOptions(options, state.query);
56
+ const size = Math.max(3, Math.min(visible.length, rows - 5, 12));
57
+ const start = Math.min(Math.max(0, state.index - Math.floor(size / 2)), Math.max(0, visible.length - size));
58
+ const lines = [state.query ? `${dim('Filter:')} ${state.query}` : dim('↑↓ move · type to filter · enter to choose')];
59
+ if (!visible.length) lines.push(dim(' Nothing matches. Backspace or Esc to clear.'));
60
+ visible.slice(start, start + size).forEach((option, offset) => {
61
+ lines.push(start + offset === state.index ? `${accent('❯')} ${accent(plain(option.label))}` : ` ${option.label}`);
62
+ });
63
+ if (visible.length > size) lines.push(dim(` ${start + 1}–${Math.min(start + size, visible.length)} of ${visible.length}`));
64
+ return lines.map((line) => fit(line, columns));
65
+ };
66
+
67
+ /**
68
+ * Shows the menu and resolves with the chosen option's value, or `cancelled` when the person backs
69
+ * out. Needs a TTY on both ends; callers fall back to a numbered list otherwise.
70
+ */
71
+ export const selectMenu = (title, options, { input = process.stdin, output = process.stdout, style = {}, cancelled = null } = {}) =>
72
+ new Promise((resolve) => {
73
+ const { bold = String, dim = String } = style;
74
+ let state = initialMenuState;
75
+ let drawn = 0;
76
+ const showCursor = () => output.write('\x1b[?25h');
77
+ const clear = () => (drawn ? `\x1b[${drawn}A\r\x1b[0J` : '');
78
+ const draw = () => {
79
+ const lines = menuLines(options, state, { rows: output.rows || 24, columns: output.columns || 80, style });
80
+ output.write(`${clear()}${lines.join('\n')}\n`);
81
+ drawn = lines.length;
82
+ };
83
+
84
+ const finish = (value, summary) => {
85
+ input.off('keypress', onKey);
86
+ input.setRawMode(wasRaw);
87
+ input.pause();
88
+ output.write(`${clear()}${summary ? `${summary}\n` : ''}`);
89
+ showCursor();
90
+ process.off('exit', showCursor);
91
+ resolve(value);
92
+ };
93
+ const onKey = (str, key) => {
94
+ state = menuKey(state, options, str, key ?? {});
95
+ if (state.done === 'cancel') return finish(cancelled, dim(' Cancelled.'));
96
+ if (state.done === 'choose') return finish(state.choice.value, ` ${dim('›')} ${plain(state.choice.label)}`);
97
+ draw();
98
+ };
99
+
100
+ output.write(`\n${bold(title)}\n\x1b[?25l`);
101
+ process.once('exit', showCursor);
102
+ emitKeypressEvents(input);
103
+ const wasRaw = Boolean(input.isRaw);
104
+ input.setRawMode(true);
105
+ input.on('keypress', onKey);
106
+ input.resume();
107
+ draw();
108
+ });
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "previewer-agency",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Upload HTML5 banners, images and videos to Previewer from any folder or CI job, and check approvals.",
5
+ "type": "module",
6
+ "bin": {
7
+ "previewer": "bin/previewer.mjs"
8
+ },
9
+ "exports": {
10
+ ".": "./lib/api.mjs",
11
+ "./files": "./lib/files.mjs"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "lib",
16
+ "README.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=20.11"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.mjs"
23
+ },
24
+ "keywords": [
25
+ "banners",
26
+ "html5",
27
+ "preview",
28
+ "ads",
29
+ "previewer"
30
+ ],
31
+ "homepage": "https://previewer.agency/docs/api",
32
+ "license": "UNLICENSED"
33
+ }