c3b-assets 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/README.md +121 -2
  2. package/bunny.js +62 -0
  3. package/c3b-assets.js +273 -0
  4. package/package.json +26 -4
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # c3b-assets
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
+ Fingerprints a project's images and syncs them to a [Bunny](https://bunny.net) storage zone, so images never live in
4
+ git and never need uploading by hand. Writes `d8e-asset-manifest.json`, which [d8e](https://codeberg.org/colab47/d8e)
5
+ (1.2.0+) uses to point every reference at the CDN.
6
+
7
+ ## How it works
8
+
9
+ Run `c3b-assets` in a project root whenever you add, change or remove an image under `src/asset/`. It:
10
+
11
+ 1. Fingerprints each image from its content — `asset/hero-banner.webp` is stored as
12
+ `colab-asset-manager/hero-banner.3f2a9c1e.webp`. Change the image and it gets a new name automatically, so it can be
13
+ cached forever and a stale copy can never be served.
14
+ 2. Uploads the ones the storage zone doesn't have yet (checksum-verified).
15
+ 3. Writes `d8e-asset-manifest.json`: each image's path under `src/` and its CDN URL. **Commit this file** — it's a few KB.
16
+ 4. Deletes files nobody references any more, **7 days** after they stopped being referenced, so pages in browser
17
+ caches, sent emails and older staging builds keep working in the meantime.
18
+
19
+ Code keeps referencing images normally (`<img src="asset/hero-banner.webp">`, `url(../asset/hero-banner.webp)`), so
20
+ local dev still works by opening `src/`. At deploy, d8e rewrites those references to the CDN URLs and leaves the
21
+ images out of `dist/`.
22
+
23
+ It only ever lists, uploads to and deletes inside the zone's `colab-asset-manager/` folder (the tool's old name,
24
+ kept so existing zones need no re-upload) — files uploaded by hand anywhere else in the zone are never touched. Supported: `avif`, `gif`, `jpeg`, `jpg`, `png`, `svg`, `webp`.
25
+
26
+ It runs on your machine only, never at deploy: the storage key stays off Heroku and Vercel, and staging can't delete
27
+ production's images.
28
+
29
+ ## Setup
30
+
31
+ ### 1. Install
32
+
33
+ ```
34
+ npm install -g c3b-assets@latest
35
+ ```
36
+
37
+ ### 2. Add `c3b-assets.json` to the project root
38
+
39
+ ```json
40
+ {
41
+ "storageZone": "viking-gear",
42
+ "storageHost": "jh.storage.bunnycdn.com",
43
+ "cdnUrl": "https://viking-gear-pz.b-cdn.net"
44
+ }
45
+ ```
46
+
47
+ - `storageZone`: the storage zone's name.
48
+ - `storageHost`: optional, defaults to `storage.bunnycdn.com` (Frankfurt). Use the zone's primary region:
49
+ `uk.`, `ny.`, `la.`, `sg.`, `se.`, `br.`, `jh.` (Johannesburg) or `syd.storage.bunnycdn.com`.
50
+ - `cdnUrl`: the pull zone connected to that storage zone.
51
+
52
+ ### 3. Gitignore the images
53
+
54
+ ```
55
+ src/asset/**/*.avif
56
+ src/asset/**/*.gif
57
+ src/asset/**/*.jpeg
58
+ src/asset/**/*.jpg
59
+ src/asset/**/*.png
60
+ src/asset/**/*.svg
61
+ src/asset/**/*.webp
62
+ ```
63
+
64
+ If the images are already committed, also run `git rm -r --cached src/asset` once (it keeps your local copies). Their
65
+ old versions stay in git history.
66
+
67
+ ### 4. Set the storage key
68
+
69
+ `BUNNY_STORAGE_KEY` is the storage zone password: Bunny dashboard → Storage → your zone → FTP & API Access. Keep it in
70
+ your shell profile or a password manager — never in the repo.
71
+
72
+ ## Usage
73
+
74
+ ```
75
+ c3b-assets --help # lists every flag
76
+ c3b-assets --pull # downloads the images the manifest lists into src/asset/ (no key needed)
77
+ c3b-assets --dry-run # shows what would be uploaded and deleted; changes nothing
78
+ c3b-assets # syncs and writes d8e-asset-manifest.json
79
+ ```
80
+
81
+ The version is printed first, so you can tell which install is running.
82
+
83
+ ### Changing an image
84
+
85
+ 1. **Fresh clone?** Run `c3b-assets --pull` first — images aren't in git, so `src/asset/` starts empty.
86
+ 2. Replace, add or remove the file in `src/asset/` (kebab-case names). Keeping the same name for a replacement is
87
+ fine: the fingerprint changes anyway. Check it locally by opening `src/`.
88
+ 3. `c3b-assets --dry-run`, then `c3b-assets`.
89
+ 4. Commit `d8e-asset-manifest.json` (plus any code change that references a new image) and deploy as usual.
90
+
91
+ If two people sync on different branches, `d8e-asset-manifest.json` conflicts on merge: pull both sets of images
92
+ into `src/asset/` (`--pull`) and run `c3b-assets` again — it rebuilds the manifest from what's there.
93
+
94
+ ### Safety checks
95
+
96
+ - **Nothing is deleted just because it's missing locally.** If images the manifest lists aren't in `src/asset/` (a
97
+ fresh clone, a half-copied folder), syncing refuses and says to `--pull`. If you removed them on purpose, add
98
+ `--allow-removals`.
99
+ - `--pull` never overwrites a local file that differs from Bunny — that's usually a change that hasn't been uploaded
100
+ yet. It only fills in missing ones, and checks each download against its fingerprint.
101
+ - Deletions only happen inside the zone's `colab-asset-manager/` folder, 7 days after a file stopped being referenced.
102
+
103
+ ## Limitations
104
+
105
+ - Bunny storage zones have one full-access password (plus a read-only one, which isn't enough to upload). Anyone who
106
+ uploads needs the full one: share it through a password manager, and regenerate it in Bunny if someone leaves.
107
+ - Videos and other large files stay where they are (Mux / Bunny Stream).
108
+
109
+ ---
110
+
111
+ ## Tests
112
+
113
+ `npm test` — Node's built-in test runner, no extra dependency. `test/c3b-assets.test.js` runs the real CLI
114
+ against fixture projects and a fake Bunny (`test/fake-bunny.js`, installed as the global `fetch`), so nothing reaches
115
+ the network and no key is needed.
116
+
117
+ ## Deploying to npm
118
+
119
+ 1. **FIRST TIME ONLY**: run `npm login`
120
+ 2. Bump the version in `package.json`
121
+ 3. `npm test`
122
+ 4. Run `npm publish`
package/bunny.js ADDED
@@ -0,0 +1,62 @@
1
+ import { createHash } from 'crypto';
2
+
3
+ // Thin wrapper over Bunny's Edge Storage HTTP API (https://bunny.net/docs/storage/http) — only the
4
+ // three calls c3b-assets needs. Uses the global fetch, so there are no dependencies.
5
+ export function createStorage({ host, zone, accessKey }) {
6
+ const base = `https://${ host }/${ zone }/`;
7
+
8
+ function request(method, path, options = {}) {
9
+ return fetch(base + encodeURI(path), {
10
+ ...options,
11
+ method,
12
+ headers: { AccessKey: accessKey, ...options.headers }
13
+ });
14
+ }
15
+
16
+ // Every file under `folder`, as paths relative to the zone root (e.g. colab-asset-manager/asset/logo.1a2b3c4d.svg).
17
+ async function listFiles(folder) {
18
+ const response = await request('GET', folder + '/');
19
+ // a folder that doesn't exist yet just means nothing has been uploaded
20
+ if (response.status === 404) {
21
+ return [];
22
+ }
23
+ if (!response.ok) {
24
+ throw new Error(`Listing ${ folder }/ failed: ${ response.status } ${ await response.text() }`);
25
+ }
26
+
27
+ const files = [];
28
+ for (const entry of await response.json()) {
29
+ const path = folder + '/' + entry.ObjectName;
30
+ if (entry.IsDirectory) {
31
+ files.push(...await listFiles(path));
32
+ } else {
33
+ files.push(path);
34
+ }
35
+ }
36
+
37
+ return files;
38
+ }
39
+
40
+ async function upload(path, content) {
41
+ // Bunny rejects the upload if the stored bytes don't match this, so a truncated upload can't
42
+ // end up being served from a URL that's cached forever.
43
+ const checksum = createHash('sha256').update(content).digest('hex').toUpperCase();
44
+ const response = await request('PUT', path, {
45
+ body: content,
46
+ headers: { 'Content-Type': 'application/octet-stream', Checksum: checksum }
47
+ });
48
+ if (response.status !== 201) {
49
+ throw new Error(`Uploading ${ path } failed: ${ response.status } ${ await response.text() }`);
50
+ }
51
+ }
52
+
53
+ async function remove(path) {
54
+ const response = await request('DELETE', path);
55
+ // already gone is the outcome we wanted anyway
56
+ if (!response.ok && response.status !== 404) {
57
+ throw new Error(`Deleting ${ path } failed: ${ response.status } ${ await response.text() }`);
58
+ }
59
+ }
60
+
61
+ return { listFiles, upload, remove };
62
+ }
package/c3b-assets.js ADDED
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'crypto';
3
+ import { existsSync, globSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
4
+ import { basename, dirname, extname, join, relative, resolve, sep } from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { createStorage } from './bunny.js';
7
+
8
+ // Printed first so it's obvious which installed version is running (same as d8e does).
9
+ const packageJsonPath = join(dirname(fileURLToPath(import.meta.url)), 'package.json');
10
+ const { version } = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
11
+ console.log(`c3b-assets version: ${ version }`);
12
+
13
+ // Fingerprints every image under src/asset/, uploads the ones Bunny doesn't have yet, and writes
14
+ // d8e-asset-manifest.json (asset path under src/ -> CDN URL) for d8e to rewrite references with.
15
+ // Files in Bunny that nothing references any more are deleted once they've been unreferenced
16
+ // for GRACE_DAYS — pages already in browser caches, sent emails and older staging builds still
17
+ // point at them for a while.
18
+ //
19
+ // Runs on your machine only (not at deploy), so the storage key never has to live on Heroku or
20
+ // Vercel, and staging can't delete production's images.
21
+
22
+ const SRC = resolve('src');
23
+ const ASSET_DIR = resolve(SRC, 'asset');
24
+ const CONFIG = resolve('c3b-assets.json');
25
+ const MANIFEST = resolve('d8e-asset-manifest.json');
26
+ const IMAGE_EXTENSIONS = ['avif', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp'];
27
+
28
+ // Everything c3b-assets uploads lives under this folder in the storage zone, and it only ever
29
+ // lists or deletes inside it — files uploaded by hand elsewhere in the zone are never touched.
30
+ // The folder keeps the tool's old name: every existing zone has its images there, and renaming it
31
+ // would re-upload every image and orphan the old copies.
32
+ const FOLDER = 'colab-asset-manager';
33
+ const GRACE_DAYS = 7;
34
+ const DAY_MS = 24 * 60 * 60 * 1000;
35
+
36
+ // Every flag the tool accepts, with its one-line description. `--help` prints them; anything not
37
+ // listed here is rejected rather than silently ignored.
38
+ const FLAGS = {
39
+ '--dry-run': 'report what would be uploaded, deleted and written, change nothing',
40
+ '--pull': 'download images listed in the manifest that are missing locally',
41
+ '--allow-removals': 'allow manifest entries with no local file to be dropped',
42
+ '--help': 'print this help',
43
+ };
44
+
45
+ function usage() {
46
+ console.log(`Usage: c3b-assets [flags]\n\nFingerprints images under src/asset/, syncs them to Bunny, writes d8e-asset-manifest.json.\n\nFlags:`);
47
+ for (const [flag, description] of Object.entries(FLAGS)) {
48
+ console.log(` ${ flag.padEnd(18) }${ description }`);
49
+ }
50
+ }
51
+
52
+ const args = process.argv.slice(2);
53
+ if (args.includes('--help') || args.includes('-h')) {
54
+ usage();
55
+ process.exit(0);
56
+ }
57
+ for (const arg of args) {
58
+ if (!(arg in FLAGS)) {
59
+ console.error(`c3b-assets: unknown option ${ arg }\n`);
60
+ usage();
61
+ process.exit(1);
62
+ }
63
+ }
64
+
65
+ const dryRun = args.includes('--dry-run');
66
+ const pull = args.includes('--pull');
67
+ const allowRemovals = args.includes('--allow-removals');
68
+
69
+ function fail(message) {
70
+ console.error(`c3b-assets: ${ message }`);
71
+ process.exit(1);
72
+ }
73
+
74
+ function readJson(path) {
75
+ try {
76
+ return JSON.parse(readFileSync(path, 'utf8'));
77
+ } catch (error) {
78
+ fail(`could not read ${ path }: ${ error.message }`);
79
+ }
80
+ }
81
+
82
+ const toPosix = (p) => p.split(sep).join('/');
83
+
84
+ function readConfig() {
85
+ if (!existsSync(CONFIG)) {
86
+ fail(`${ CONFIG } not found — see the README for its shape`);
87
+ }
88
+
89
+ const config = readJson(CONFIG);
90
+ if (!config.storageZone || !config.cdnUrl) {
91
+ fail('c3b-assets.json needs "storageZone" and "cdnUrl"');
92
+ }
93
+
94
+ return {
95
+ storageZone: config.storageZone,
96
+ storageHost: config.storageHost ?? 'storage.bunnycdn.com',
97
+ cdnUrl: config.cdnUrl.replace(/\/+$/, '')
98
+ };
99
+ }
100
+
101
+ // Each image's manifest key (its path under src/) and the fingerprinted path it's stored at in
102
+ // Bunny. The fingerprint comes from the content, so changing an image always gives it a new name.
103
+ function scanImages() {
104
+ const images = [];
105
+ for (const file of globSync(`${ ASSET_DIR }/**/*.{${ IMAGE_EXTENSIONS.join(',') }}`)) {
106
+ const content = readFileSync(file);
107
+ const hash = fingerprint(content);
108
+ const ext = extname(file);
109
+ const key = toPosix(relative(SRC, file));
110
+ const hashedName = basename(file, ext) + '.' + hash + ext;
111
+ // relative to src/asset/, not src/ — everything is under asset/, so repeating it in Bunny is
112
+ // just an extra folder level (asset/arch/x.webp is stored as colab-asset-manager/arch/x.<hash>.webp)
113
+ const remoteDir = toPosix(relative(ASSET_DIR, dirname(file)));
114
+ const remotePath = remoteDir ? `${ FOLDER }/${ remoteDir }/${ hashedName }` : `${ FOLDER }/${ hashedName }`;
115
+
116
+ images.push({ key, content, remotePath });
117
+ }
118
+ images.sort((a, b) => a.key.localeCompare(b.key));
119
+
120
+ return images;
121
+ }
122
+
123
+ // Which unreferenced files to delete now, and the updated record of when each one stopped being
124
+ // referenced. That record is kept in the manifest, so the grace period survives between runs and
125
+ // machines.
126
+ function planDeletions(remoteFiles, referenced, previouslyRetired, now) {
127
+ const retired = {};
128
+ const toDelete = [];
129
+
130
+ for (const path of remoteFiles) {
131
+ if (referenced.has(path)) {
132
+ continue;
133
+ }
134
+
135
+ const since = previouslyRetired[path] ?? now.toISOString().slice(0, 10);
136
+ const ageDays = (now - new Date(since)) / DAY_MS;
137
+ if (ageDays >= GRACE_DAYS) {
138
+ toDelete.push(path);
139
+ } else {
140
+ retired[path] = since;
141
+ }
142
+ }
143
+
144
+ return { retired, toDelete };
145
+ }
146
+
147
+ function fingerprint(content) {
148
+ return createHash('md5').update(content).digest('hex').slice(0, 8);
149
+ }
150
+
151
+ function sortedObject(entries) {
152
+ return Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b)));
153
+ }
154
+
155
+ const config = readConfig();
156
+
157
+ async function sync() {
158
+ const accessKey = process.env.BUNNY_STORAGE_KEY;
159
+ if (!accessKey) {
160
+ fail('set BUNNY_STORAGE_KEY to the storage zone password (Bunny dashboard: Storage > FTP & API Access)');
161
+ }
162
+ if (!existsSync(ASSET_DIR)) {
163
+ fail(`${ ASSET_DIR } not found — on a fresh clone, run "c3b-assets --pull" first`);
164
+ }
165
+
166
+ const storage = createStorage({ host: config.storageHost, zone: config.storageZone, accessKey });
167
+ const images = scanImages();
168
+ const previous = existsSync(MANIFEST) ? readJson(MANIFEST) : {};
169
+
170
+ // Images aren't in git, so a fresh clone (or a half-copied folder) looks exactly like someone
171
+ // deleting them — and syncing would then delete them from Bunny too. Removals have to be asked for.
172
+ const localKeys = new Set(images.map((image) => image.key));
173
+ const missing = Object.keys(previous.assets ?? {}).filter((key) => !localKeys.has(key));
174
+ if (missing.length > 0 && !allowRemovals) {
175
+ fail(`${ missing.length } image(s) in the manifest aren't in src/asset/ (e.g. ${ missing[0] }). `
176
+ + 'Run "c3b-assets --pull" to download them, or add --allow-removals if you removed them on purpose.');
177
+ }
178
+
179
+ const remoteFiles = new Set(await storage.listFiles(FOLDER));
180
+
181
+ const toUpload = images.filter((image) => !remoteFiles.has(image.remotePath));
182
+ const referenced = new Set(images.map((image) => image.remotePath));
183
+ const { retired, toDelete } = planDeletions(remoteFiles, referenced, previous.retired ?? {}, new Date());
184
+
185
+ console.log(`${ images.length } images, ${ toUpload.length } to upload, ${ toDelete.length } to delete, `
186
+ + `${ Object.keys(retired).length } waiting out the ${ GRACE_DAYS }-day grace period`);
187
+
188
+ for (const image of toUpload) {
189
+ console.log(` upload ${ image.remotePath }`);
190
+ if (!dryRun) {
191
+ await storage.upload(image.remotePath, image.content);
192
+ }
193
+ }
194
+
195
+ // Uploads go first and the manifest is only written once they've all succeeded, so a failed run
196
+ // leaves the previous manifest pointing at files that are still there.
197
+ const manifest = {
198
+ // encodeURI so a name with a space (or similar) is still a valid URL in srcset and unquoted CSS url()
199
+ assets: sortedObject(images.map((image) => [image.key, `${ config.cdnUrl }/${ encodeURI(image.remotePath) }`])),
200
+ retired: sortedObject(Object.entries(retired))
201
+ };
202
+ if (!dryRun) {
203
+ writeFileSync(MANIFEST, JSON.stringify(manifest, null, 2) + '\n');
204
+ }
205
+
206
+ for (const path of toDelete) {
207
+ console.log(` delete ${ path }`);
208
+ if (!dryRun) {
209
+ await storage.remove(path);
210
+ }
211
+ }
212
+
213
+ console.log(dryRun ? 'Dry run — nothing uploaded, deleted or written.' : `Wrote ${ MANIFEST }`);
214
+ }
215
+
216
+ // Downloads every image in the manifest that src/asset/ is missing, straight from the CDN — so it
217
+ // needs no storage key, just the committed manifest. A local file that differs from the manifest is
218
+ // kept, not overwritten: it's most likely a change that hasn't been uploaded yet.
219
+ async function pullImages() {
220
+ if (!existsSync(MANIFEST)) {
221
+ fail(`${ MANIFEST } not found — nothing to pull`);
222
+ }
223
+
224
+ const assets = readJson(MANIFEST).assets ?? {};
225
+ let downloaded = 0;
226
+ let upToDate = 0;
227
+ let kept = 0;
228
+
229
+ for (const [key, url] of Object.entries(assets)) {
230
+ const target = resolve(SRC, key);
231
+ if (!target.startsWith(ASSET_DIR + sep)) {
232
+ fail(`refusing to write outside src/asset/: ${ key }`);
233
+ }
234
+
235
+ // the fingerprint in the stored name (hero.0100d254.webp) is the content hash we expect
236
+ const expected = decodeURI(url).match(/\.([0-9a-f]{8})\.[^./]+$/)?.[1];
237
+
238
+ if (existsSync(target)) {
239
+ if (fingerprint(readFileSync(target)) === expected) {
240
+ upToDate++;
241
+ } else {
242
+ console.log(` keep ${ key } (differs from Bunny — not uploaded yet?)`);
243
+ kept++;
244
+ }
245
+ continue;
246
+ }
247
+
248
+ console.log(` pull ${ key }`);
249
+ if (dryRun) {
250
+ downloaded++;
251
+ continue;
252
+ }
253
+
254
+ const response = await fetch(url);
255
+ if (!response.ok) {
256
+ throw new Error(`Downloading ${ url } failed: ${ response.status }`);
257
+ }
258
+ const content = Buffer.from(await response.arrayBuffer());
259
+ if (fingerprint(content) !== expected) {
260
+ throw new Error(`Downloaded ${ key } doesn't match its fingerprint — not saved`);
261
+ }
262
+
263
+ mkdirSync(dirname(target), { recursive: true });
264
+ writeFileSync(target, content);
265
+ downloaded++;
266
+ }
267
+
268
+ console.log(`${ downloaded } downloaded, ${ upToDate } already up to date, ${ kept } kept (local changes)`
269
+ + (dryRun ? ' — dry run, nothing written' : ''));
270
+ }
271
+
272
+ // Bunny API errors (wrong key, wrong zone or region) print as one line rather than a stack trace
273
+ (pull ? pullImages() : sync()).catch((error) => fail(error.message));
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "c3b-assets",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Fingerprints a project's images and syncs them to a Bunny storage zone, writing the d8e-asset-manifest.json d8e reads.",
5
+ "license": "GPL-3.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "c3b-assets": "c3b-assets.js"
9
+ },
10
+ "files": [
11
+ "c3b-assets.js",
12
+ "bunny.js"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://codeberg.org/colab47/c3b-assets.git"
20
+ },
21
+ "publishConfig": {
22
+ "registry": "https://registry.npmjs.org"
23
+ },
24
+ "scripts": {
25
+ "test": "node --test test/*.test.js",
26
+ "deploy": "npm run test && npm publish"
27
+ }
28
+ }