@politelabs/cabin-cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ cabin theme publish # draws the site with it
33
33
 
34
34
  `cabin theme init` asks which of the sites you're signed in to the theme is for, and what to call it; the folder is named after the theme unless you give one. `--site` and `--name` skip the questions. It makes the theme on the site and writes `cabin.json` (the host, the site's handle and the theme's key), which is committed; `.cabin/` holds what the CLI remembers and isn't.
35
35
 
36
- A theme is `theme.json`, `theme.css`, templates under `templates/` and patterns under `patterns/`. With Tailwind, `src/theme.css` is the source and `theme.css` is built from it by the `dev` and `build` scripts in the folder's `package.json`; `cabin theme dev` runs `dev` beside the watcher, and `push` runs `build` first. A folder with no scripts is synced as it is.
36
+ A theme is `theme.json`, `theme.css`, templates under `templates/`, patterns under `patterns/`, and its own scripts and drawings (`.js`, `.svg`) under `assets/`: a template prints one's address with `{{ asset('assets/nav.js') }}`, `theme.css` names one by its path (`url(assets/wave.svg)`), and a script at `assets/blocks/<block key>.js` is loaded only on the pages that block is on. A theme's pictures (`.png`, `.jpg`, `.webp`, `.gif`, `.avif` under `assets/`, 2 MB each at most) are synced too: `push` and `dev` send only the ones the site doesn't hold yet, `pull` fetches only the ones the folder lacks, and `{{ asset('assets/hero.png') }}` or `url(assets/hero.png)` in `theme.css` reaches one. With Tailwind, `src/theme.css` is the source and `theme.css` is built from it by the `dev` and `build` scripts in the folder's `package.json`. A new theme's Tailwind classes carry the prefix `tw:` (`tw:flex`, `tw:md:grid`), because Tailwind scans the templates for class names and a class of your own called `container` or `hidden` would otherwise silently take Tailwind's rules; a theme made with an earlier CLI has no prefix, and gets one by adding `prefix(tw)` to both `@import` lines in `src/theme.css` and to its Tailwind classes. `cabin theme dev` runs `dev` beside the watcher, and `push` runs `build` first; a `push` made while `dev` is running is remembered by both. A folder with no scripts is synced as it is.
37
37
 
38
38
  | Command | What it does |
39
39
  | --- | --- |
@@ -44,6 +44,7 @@ A theme is `theme.json`, `theme.css`, templates under `templates/` and patterns
44
44
  | `cabin theme check [--no-build]` | Run every check a save runs, writing nothing. |
45
45
  | `cabin theme push [--note] [--force] [--check] [--no-build]` | Save a version. Refused when someone saved since you pulled; `--force` saves over it. |
46
46
  | `cabin theme dev [--path /] [--no-build]` | Keep a draft on the site as the folder changes, with a link that reloads itself. |
47
+ | `cabin theme context [/path] [--only entry.fields] [--full] [--draft]` | Print what the theme's templates are handed for a page: the page's template and its data, then each custom block's. Long texts are cut short unless `--full`; `--only` prints one part, by a dotted path; `--draft` looks at the draft `theme dev` keeps instead of the saved version. |
47
48
  | `cabin theme publish` | Draw the site with the theme. |
48
49
  | `cabin theme open [--site]` | Open the Theme files screen, or the site. |
49
50
 
@@ -23,6 +23,7 @@ export async function project(io) {
23
23
  api: new ApiClient(config.host, token, io.fetch),
24
24
  root: io.cwd,
25
25
  saveState: (next) => writeText(join(io.cwd, STATE_FILE), serializeState(next)),
26
+ updateState: async (change) => writeText(join(io.cwd, STATE_FILE), serializeState(change(parseState(await readText(join(io.cwd, STATE_FILE)))))),
26
27
  };
27
28
  }
28
29
  /** The token kept for a host and site, or refuse with what to do. */
@@ -2,13 +2,14 @@ import { ApiFailed } from '../../lib/api.js';
2
2
  import { has } from '../../lib/args.js';
3
3
  import { problemLines } from '../../lib/problems.js';
4
4
  import { project } from '../context.js';
5
- import { buildFirst, filesIn } from './sync.js';
5
+ import { buildFirst, filesIn, picturesIn } from './sync.js';
6
6
  /** Run every check a save runs, writing nothing. */
7
7
  export async function check(parsed, io) {
8
8
  const { api, config, root } = await project(io);
9
9
  await buildFirst(root, io, has(parsed, 'no-build'));
10
10
  try {
11
- const answer = await api.check(config.theme, await filesIn(root));
11
+ const pictures = Object.entries(await picturesIn(root)).map(([path, picture]) => [path, { hash: picture.hash }]);
12
+ const answer = await api.check(config.theme, await filesIn(root), pictures.length === 0 ? null : Object.fromEntries(pictures));
12
13
  io.out(`No problems in ${answer.files} ${answer.files === 1 ? 'file' : 'files'} of "${answer.name}".`);
13
14
  return 0;
14
15
  }
@@ -0,0 +1,38 @@
1
+ import { ApiFailed } from '../../lib/api.js';
2
+ import { flag, has } from '../../lib/args.js';
3
+ import { contextLines } from '../../lib/context.js';
4
+ import { project, Refused } from '../context.js';
5
+ /**
6
+ * Print what the theme's templates are handed for a page of the site: the
7
+ * page's template and its data, then each custom block's. `dump` isn't
8
+ * allowed in a site theme, so this is how to see what there is to print.
9
+ */
10
+ export async function context(parsed, io) {
11
+ const { api, config, state } = await project(io);
12
+ const path = parsed.positionals[0] ?? flag(parsed, 'path') ?? '/';
13
+ const draft = has(parsed, 'draft');
14
+ if (draft && state.draftToken === null) {
15
+ throw new Refused('There is no draft to look at. Run cabin theme dev first, or leave --draft off to use the saved version.');
16
+ }
17
+ let answer;
18
+ try {
19
+ answer = await api.context(config.theme, path, draft ? state.draftToken : null);
20
+ }
21
+ catch (error) {
22
+ if (error instanceof ApiFailed && error.status === 404) {
23
+ throw new Refused(`${config.host} doesn't answer what templates are handed yet, or has no theme "${config.theme}".`);
24
+ }
25
+ throw error;
26
+ }
27
+ for (const line of contextLines(answer, {
28
+ full: has(parsed, 'full'),
29
+ only: flag(parsed, 'only'),
30
+ })) {
31
+ io.out(line);
32
+ }
33
+ if (answer.problem !== null) {
34
+ io.err(`The theme couldn't draw ${path}: ${answer.problem}`);
35
+ return 1;
36
+ }
37
+ return 0;
38
+ }
@@ -3,10 +3,10 @@ import { ApiFailed } from '../../lib/api.js';
3
3
  import { flag, has } from '../../lib/args.js';
4
4
  import { paint, syncedLine, wantsColor } from '../../lib/output.js';
5
5
  import { problemLines } from '../../lib/problems.js';
6
- import { isSkipped, isThemePath, toThemePath } from '../../lib/theme-files.js';
6
+ import { binariesFor, blobKey, heldBlobs, isSkipped, isSynced, toThemePath, } from '../../lib/theme-files.js';
7
7
  import { backoff, Debounce } from '../../lib/watch.js';
8
8
  import { project } from '../context.js';
9
- import { filesIn, scriptIn } from './sync.js';
9
+ import { filesIn, picturesIn, scriptIn } from './sync.js';
10
10
  /**
11
11
  * Keep a draft of the folder on the site as it changes: the theme's `dev`
12
12
  * script runs beside the watcher, every burst of changes is sent as one
@@ -14,19 +14,32 @@ import { filesIn, scriptIn } from './sync.js';
14
14
  * itself again. Ctrl-C ends both.
15
15
  */
16
16
  export async function dev(parsed, io) {
17
- const { api, config, state, root, saveState } = await project(io);
17
+ const { api, config, state, root, updateState } = await project(io);
18
18
  const path = flag(parsed, 'path') ?? '/';
19
19
  const color = wantsColor(io.isTTY, io.env);
20
20
  let token = state.draftToken;
21
21
  let failures = 0;
22
22
  let stopped = false;
23
23
  const child = has(parsed, 'no-build') ? null : await startScript(root, io);
24
+ // The pictures the site holds: the theme's, and every one sent since.
25
+ let held;
24
26
  const send = async (first) => {
25
27
  try {
26
- const draft = await api.draft(config.theme, await filesIn(root), path, token);
28
+ if (held === undefined) {
29
+ const known = (await api.theme(config.theme)).binaries;
30
+ held = known === undefined ? null : heldBlobs(known);
31
+ }
32
+ const pictures = await picturesIn(root);
33
+ const draft = await api.draft(config.theme, await filesIn(root), path, token, held === null ? null : binariesFor(pictures, held));
34
+ for (const [at, picture] of Object.entries(pictures)) {
35
+ held?.add(blobKey(at, picture.hash));
36
+ }
27
37
  const renewed = token !== null && token !== draft.token;
28
38
  token = draft.token;
29
- await saveState({ ...state, draftToken: token });
39
+ await updateState((current) => ({
40
+ ...current,
41
+ draftToken: token,
42
+ }));
30
43
  failures = 0;
31
44
  if (first || renewed) {
32
45
  io.out(`Preview: ${paint(draft.url, 'cyan', color)}`);
@@ -75,7 +88,7 @@ export async function dev(parsed, io) {
75
88
  let dirty = false;
76
89
  const watcher = watch(root, { recursive: true }, (_event, filename) => {
77
90
  const relative = toThemePath(String(filename ?? ''));
78
- if (relative === '' || isSkipped(relative) || !isThemePath(relative)) {
91
+ if (relative === '' || isSkipped(relative) || !isSynced(relative)) {
79
92
  return;
80
93
  }
81
94
  debounce.push(io.now());
@@ -1,10 +1,10 @@
1
1
  import { join } from 'node:path';
2
- import { exists, remove, walk, writeText } from '../../io/fs.js';
2
+ import { exists, remove, walk, walkPictures, writeBytes, writeText, } from '../../io/fs.js';
3
3
  import { flag, has } from '../../lib/args.js';
4
4
  import { isGenerated, isThemePath } from '../../lib/theme-files.js';
5
5
  import { project, Refused } from '../context.js';
6
6
  import { hasSource } from './sync.js';
7
- /** Take the theme's files from the site into the folder. */
7
+ /** Take the theme's files, and its pictures, from the site into the folder. */
8
8
  export async function pull(parsed, io) {
9
9
  const { api, config, state, root, saveState } = await project(io);
10
10
  const key = flag(parsed, 'theme') ?? config.theme;
@@ -39,6 +39,28 @@ export async function pull(parsed, io) {
39
39
  removed += 1;
40
40
  }
41
41
  }
42
+ // The theme's pictures: only the ones the folder lacks or has differently
43
+ // are fetched, and the ones the site no longer has go.
44
+ if (taken.binaries !== undefined) {
45
+ const local = await walkPictures(root);
46
+ for (const [path, picture] of Object.entries(taken.binaries)) {
47
+ if (local[path]?.hash === picture.hash) {
48
+ continue;
49
+ }
50
+ const answer = await io.fetch(new URL(picture.url, config.host));
51
+ if (!answer.ok) {
52
+ throw new Refused(`Couldn't fetch ${path} from the site (${answer.status}).`);
53
+ }
54
+ await writeBytes(join(root, path), new Uint8Array(await answer.arrayBuffer()));
55
+ written += 1;
56
+ }
57
+ for (const path of Object.keys(local)) {
58
+ if (!(path in taken.binaries)) {
59
+ await remove(join(root, path));
60
+ removed += 1;
61
+ }
62
+ }
63
+ }
42
64
  await saveState({ ...state, versionId: version?.id ?? state.versionId });
43
65
  io.out(`Pulled ${written} ${written === 1 ? 'file' : 'files'} of "${key}"${version ? ` at version ${version.number}` : ''}${removed > 0 ? `, and removed ${removed} the site no longer has` : ''}.`);
44
66
  if (skipped !== null) {
@@ -4,8 +4,8 @@ import { problemLines } from '../../lib/problems.js';
4
4
  import { conflictLine, currentOf } from '../../lib/versions.js';
5
5
  import { project } from '../context.js';
6
6
  import { check } from './check.js';
7
- import { buildFirst, filesIn } from './sync.js';
8
- /** Save the folder's files as a version. */
7
+ import { binariesIn, buildFirst, filesIn } from './sync.js';
8
+ /** Save the folder's files, and its pictures, as a version. */
9
9
  export async function push(parsed, io) {
10
10
  if (has(parsed, 'check')) {
11
11
  return check(parsed, io);
@@ -14,7 +14,7 @@ export async function push(parsed, io) {
14
14
  await buildFirst(root, io, has(parsed, 'no-build'));
15
15
  const base = has(parsed, 'force') ? null : state.versionId;
16
16
  try {
17
- const theme = await api.save(config.theme, await filesIn(root), flag(parsed, 'note'), base);
17
+ const theme = await api.save(config.theme, await filesIn(root), flag(parsed, 'note'), base, await binariesIn(root, api, config.theme, io));
18
18
  await saveState({ ...state, versionId: theme.version?.id ?? null });
19
19
  io.out(`Pushed as version ${theme.version?.number ?? '?'} of "${theme.name}".${theme.chosen ? ' The site shows it now.' : ''}`);
20
20
  return 0;
@@ -1,13 +1,35 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { exists, readText, walk } from '../../io/fs.js';
3
+ import { exists, readText, walk, walkPictures } from '../../io/fs.js';
4
4
  import { detectPackageManager, hasScript, runScript, } from '../../lib/scripts.js';
5
- import { collect } from '../../lib/theme-files.js';
5
+ import { binariesFor, collect, heldBlobs } from '../../lib/theme-files.js';
6
6
  import { Refused } from '../context.js';
7
7
  /** The theme files a folder holds now. */
8
8
  export async function filesIn(root) {
9
9
  return collect(await walk(root));
10
10
  }
11
+ /** The pictures a folder holds now, by path. */
12
+ export async function picturesIn(root) {
13
+ return walkPictures(root);
14
+ }
15
+ /**
16
+ * What to send for the folder's pictures, given what the site holds for
17
+ * the theme now. Null for a folder with none on a Cabin that takes none,
18
+ * so nothing about pictures is sent to it at all.
19
+ *
20
+ * @returns The pictures to send, and whether the site can take them.
21
+ */
22
+ export async function binariesIn(root, api, theme, io) {
23
+ const local = await picturesIn(root);
24
+ const held = (await api.theme(theme)).binaries;
25
+ if (held === undefined) {
26
+ if (Object.keys(local).length > 0) {
27
+ io.err("This Cabin doesn't take a theme's pictures yet, so the ones under assets/ weren't sent.");
28
+ }
29
+ return null;
30
+ }
31
+ return binariesFor(local, heldBlobs(held));
32
+ }
11
33
  /** Whether a folder has a script by name, and how to run it. */
12
34
  export async function scriptIn(root, name, io) {
13
35
  if (!hasScript(await readText(join(root, 'package.json')), name)) {
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
4
4
  import { Refused } from './commands/context.js';
5
5
  import { login, logout, whoami } from './commands/login.js';
6
6
  import { check } from './commands/theme/check.js';
7
+ import { context } from './commands/theme/context.js';
7
8
  import { dev } from './commands/theme/dev.js';
8
9
  import { init } from './commands/theme/init.js';
9
10
  import { list } from './commands/theme/list.js';
@@ -14,7 +15,7 @@ import { push } from './commands/theme/push.js';
14
15
  import { ApiFailed } from './lib/api.js';
15
16
  import { has, parse, USAGE } from './lib/args.js';
16
17
  import { problemLines } from './lib/problems.js';
17
- const VERSION = '0.3.0';
18
+ const VERSION = '0.5.0';
18
19
  const COMMANDS = {
19
20
  login,
20
21
  logout,
@@ -25,6 +26,7 @@ const COMMANDS = {
25
26
  'theme check': check,
26
27
  'theme push': push,
27
28
  'theme dev': dev,
29
+ 'theme context': context,
28
30
  'theme publish': publish,
29
31
  'theme open': open,
30
32
  };
package/dist/io/fs.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { mkdir, readdir, readFile, rm, stat, writeFile, } from 'node:fs/promises';
2
3
  import { dirname, join, relative } from 'node:path';
3
- import { isSkipped, toThemePath } from '../lib/theme-files.js';
4
+ import { isPicturePath, isSkipped, isThemePath, toThemePath, } from '../lib/theme-files.js';
4
5
  /** Read a text file, or null when it isn't there. */
5
6
  export async function readText(path) {
6
7
  try {
@@ -26,9 +27,49 @@ export async function exists(path) {
26
27
  export async function remove(path) {
27
28
  await rm(path, { force: true });
28
29
  }
30
+ /** Write a file that isn't text. */
31
+ export async function writeBytes(path, bytes) {
32
+ await mkdir(dirname(path), { recursive: true });
33
+ await writeFile(path, bytes);
34
+ }
35
+ /** What a file's bytes hash to: SHA-256, in hex, as the site names a picture. */
36
+ export function hashOf(bytes) {
37
+ return createHash('sha256').update(bytes).digest('hex');
38
+ }
39
+ /**
40
+ * The pictures under a folder, by path, each with its hash and its bytes
41
+ * in base64, leaving the folders that are never synced.
42
+ */
43
+ export async function walkPictures(root) {
44
+ const found = {};
45
+ async function visit(folder) {
46
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
47
+ const path = join(folder, entry.name);
48
+ const rel = toThemePath(relative(root, path));
49
+ if (isSkipped(rel)) {
50
+ continue;
51
+ }
52
+ if (entry.isDirectory()) {
53
+ await visit(path);
54
+ }
55
+ else if (entry.isFile() && isPicturePath(rel)) {
56
+ const bytes = await readFile(path);
57
+ found[rel] = {
58
+ hash: hashOf(bytes),
59
+ base64: bytes.toString('base64'),
60
+ };
61
+ }
62
+ }
63
+ }
64
+ if (await exists(root)) {
65
+ await visit(root);
66
+ }
67
+ return found;
68
+ }
29
69
  /**
30
- * Every text file under a folder, as [relative path, contents], leaving
31
- * the folders that are never synced.
70
+ * Every one of a theme's text files under a folder, as [relative path,
71
+ * contents], leaving the folders that are never synced and anything a
72
+ * theme doesn't hold as text.
32
73
  */
33
74
  export async function walk(root) {
34
75
  const found = [];
@@ -43,7 +84,7 @@ export async function walk(root) {
43
84
  if (entry.isDirectory()) {
44
85
  await visit(path);
45
86
  }
46
- else if (entry.isFile()) {
87
+ else if (entry.isFile() && isThemePath(rel)) {
47
88
  found.push([rel, await readFile(path, 'utf8')]);
48
89
  }
49
90
  }
package/dist/lib/api.js CHANGED
@@ -56,19 +56,24 @@ export class ApiClient {
56
56
  create(key, name, from) {
57
57
  return this.call('POST', '/v1/themes', { key, name, from });
58
58
  }
59
- save(key, files, note, baseVersion) {
59
+ save(key, files, note, baseVersion, binaries = null) {
60
60
  return this.call('PUT', `/v1/themes/${key}`, {
61
61
  files,
62
+ ...(binaries === null ? {} : { binaries }),
62
63
  note,
63
64
  base_version: baseVersion,
64
65
  });
65
66
  }
66
- check(key, files) {
67
- return this.call('POST', `/v1/themes/${key}/check`, { files });
67
+ check(key, files, binaries = null) {
68
+ return this.call('POST', `/v1/themes/${key}/check`, {
69
+ files,
70
+ ...(binaries === null ? {} : { binaries }),
71
+ });
68
72
  }
69
- draft(key, files, path, token) {
73
+ draft(key, files, path, token, binaries = null) {
70
74
  return this.call('POST', `/v1/themes/${key}/drafts`, {
71
75
  files,
76
+ ...(binaries === null ? {} : { binaries }),
72
77
  path,
73
78
  token,
74
79
  });
@@ -79,6 +84,13 @@ export class ApiClient {
79
84
  version(key, id) {
80
85
  return this.call('GET', `/v1/themes/${key}/versions/${id}`);
81
86
  }
87
+ context(key, path, token) {
88
+ const query = new URLSearchParams({
89
+ path,
90
+ ...(token === null ? {} : { token }),
91
+ });
92
+ return this.call('GET', `/v1/themes/${key}/context?${query.toString()}`);
93
+ }
82
94
  async call(method, path, body) {
83
95
  let response;
84
96
  try {
package/dist/lib/args.js CHANGED
@@ -14,6 +14,9 @@ const OPTIONS = {
14
14
  force: { type: 'boolean' },
15
15
  check: { type: 'boolean' },
16
16
  all: { type: 'boolean' },
17
+ draft: { type: 'boolean' },
18
+ full: { type: 'boolean' },
19
+ only: { type: 'string' },
17
20
  help: { type: 'boolean', short: 'h' },
18
21
  };
19
22
  /** Read the command words and flags from argv. */
@@ -69,6 +72,7 @@ export const USAGE = `cabin — develop a Cabin site theme locally
69
72
  cabin theme check [--no-build]
70
73
  cabin theme push [--note NOTE] [--force] [--check] [--no-build]
71
74
  cabin theme dev [--path /] [--no-build]
75
+ cabin theme context [/path] [--only entry.fields] [--full] [--draft]
72
76
  cabin theme publish
73
77
  cabin theme open [--site]
74
78
 
@@ -0,0 +1,68 @@
1
+ /** How long a piece of text is printed before it is cut, unless all of it is asked for. */
2
+ export const SHORT = 160;
3
+ /**
4
+ * A value with its long texts cut short, so a page's markup doesn't bury
5
+ * the data around it. What was cut says how long it was.
6
+ */
7
+ export function shorten(value, max = SHORT) {
8
+ if (typeof value === 'string') {
9
+ return value.length > max
10
+ ? `${value.slice(0, max)}… (${value.length} characters)`
11
+ : value;
12
+ }
13
+ if (Array.isArray(value)) {
14
+ return value.map((item) => shorten(item, max));
15
+ }
16
+ if (typeof value === 'object' && value !== null) {
17
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [
18
+ key,
19
+ shorten(inner, max),
20
+ ]));
21
+ }
22
+ return value;
23
+ }
24
+ /**
25
+ * The part of the data a dotted path names, as a template would reach it:
26
+ * `entry.fields.photo`, `list.entries.0.title`. Undefined when nothing is
27
+ * there.
28
+ */
29
+ export function pick(data, path) {
30
+ let at = data;
31
+ for (const key of path.split('.').filter((part) => part !== '')) {
32
+ if (typeof at !== 'object' || at === null || !(key in at)) {
33
+ return undefined;
34
+ }
35
+ at = at[key];
36
+ }
37
+ return at;
38
+ }
39
+ /**
40
+ * What to print for a page: its template and what a visitor would be
41
+ * answered, the data it was handed (or the part asked for), then each
42
+ * custom block's template and data.
43
+ */
44
+ export function contextLines(context, options) {
45
+ const show = (value) => JSON.stringify(options.full ? value : shorten(value), null, 2);
46
+ if (context.location !== null) {
47
+ return [`${context.path} → ${context.location} (${context.status})`];
48
+ }
49
+ if (context.template === null || context.data === null) {
50
+ return [`${context.path} drew no template (${context.status}).`];
51
+ }
52
+ if (options.only !== null) {
53
+ const part = pick(context.data, options.only);
54
+ return part === undefined
55
+ ? [
56
+ `${context.template} isn't handed "${options.only}". It is handed: ${Object.keys(context.data).join(', ')}.`,
57
+ ]
58
+ : [show(part)];
59
+ }
60
+ const lines = [
61
+ `${context.template} (${context.status})`,
62
+ show(context.data),
63
+ ];
64
+ for (const block of context.blocks) {
65
+ lines.push('', block.template, show(block.data));
66
+ }
67
+ return lines;
68
+ }
@@ -17,7 +17,10 @@ export function packageJson(key) {
17
17
  /**
18
18
  * The stylesheet's source with Tailwind: its theme and utilities, not its
19
19
  * preflight, so the stylesheet as pulled keeps its look, inside the base
20
- * layer so utilities written in templates win.
20
+ * layer so utilities written in templates win. Tailwind's classes are
21
+ * prefixed (`tw:flex`): it scans the templates for class names, and one
22
+ * of the theme's own called `container` or `hidden` would otherwise pick
23
+ * up Tailwind's rules without anyone asking.
21
24
  */
22
25
  export function tailwindSource(pulledCss) {
23
26
  return [
@@ -26,11 +29,14 @@ export function tailwindSource(pulledCss) {
26
29
  " utilities are included; its preflight isn't, so the styles below stay as",
27
30
  " they were. Cabin sets the site's colours and fonts as CSS variables:",
28
31
  ' --cabin-accent, --cabin-background, --cabin-text, --cabin-font-body, ...',
32
+ " Tailwind's classes carry the prefix tw: (tw:flex, tw:md:grid), so a class",
33
+ " of your own named like one of Tailwind's (container, hidden, flex) is",
34
+ ' only ever yours. Take prefix(tw) off both imports to write them bare.',
29
35
  " The built file has to pass Cabin's stylesheet rules: no @import, no url()",
30
36
  ' to another host, no data: URLs, and at most 256 KB. */',
31
37
  '@layer theme, base, components, utilities;',
32
- '@import "tailwindcss/theme.css" layer(theme);',
33
- '@import "tailwindcss/utilities.css" layer(utilities);',
38
+ '@import "tailwindcss/theme.css" layer(theme) prefix(tw);',
39
+ '@import "tailwindcss/utilities.css" layer(utilities) prefix(tw);',
34
40
  '@source "../templates";',
35
41
  '',
36
42
  '@layer base {',
@@ -1,10 +1,51 @@
1
1
  /**
2
2
  * What a theme may hold, as Cabin's `ThemeFileRules` says it: the manifest,
3
- * the stylesheet, templates under `templates/` at any depth, and patterns
4
- * under `patterns/`, named in lower case. A copy of the server's rule: the
5
- * server is the judge, and this only says what is worth sending.
3
+ * the stylesheet, templates under `templates/` at any depth, patterns
4
+ * under `patterns/`, and scripts and drawings (`.js`, `.svg`) under
5
+ * `assets/` at any depth, named in lower case, all as text. A copy of the server's
6
+ * rule: the server is the judge, and this only says what is worth sending.
6
7
  */
7
- export const THEME_PATH = /^(theme\.json|theme\.css|templates\/[a-z0-9_-]+(\/[a-z0-9_-]+)*\.twig|patterns\/[a-z0-9-]+\.json)$/;
8
+ export const THEME_PATH = /^(theme\.json|theme\.css|templates\/[a-z0-9_-]+(\/[a-z0-9_-]+)*\.twig|patterns\/[a-z0-9-]+\.json|assets\/[a-z0-9_-]+(\/[a-z0-9_-]+)*\.(js|svg))$/;
9
+ /**
10
+ * A theme's pictures: PNG, JPEG, WebP, GIF and AVIF under `assets/`. They
11
+ * aren't text, so they travel beside the files, as `binaries`. A copy of
12
+ * the server's rule, as the path above is.
13
+ */
14
+ export const PICTURE_PATH = /^assets\/[a-z0-9_-]+(\/[a-z0-9_-]+)*\.(png|jpg|jpeg|webp|gif|avif)$/;
15
+ /** Whether a path, relative to the theme's folder, is a picture's. */
16
+ export function isPicturePath(path) {
17
+ return PICTURE_PATH.test(path);
18
+ }
19
+ /** Whether a path is one that is synced at all: a theme's file, or a picture. */
20
+ export function isSynced(path) {
21
+ return isThemePath(path) || isPicturePath(path);
22
+ }
23
+ /**
24
+ * What names a stored picture on the site: its hash and its kind, since
25
+ * the site keeps a file under both.
26
+ */
27
+ export function blobKey(path, hash) {
28
+ return `${hash}.${path.slice(path.lastIndexOf('.') + 1)}`;
29
+ }
30
+ /** The blobs the site holds, from the pictures it says a theme has. */
31
+ export function heldBlobs(held) {
32
+ return new Set(Object.entries(held ?? {}).map(([path, picture]) => blobKey(path, picture.hash)));
33
+ }
34
+ /**
35
+ * What to send for the folder's pictures: only the bytes of the ones the
36
+ * site doesn't hold yet, and the hash of every other, so a picture that
37
+ * hasn't changed never travels twice.
38
+ */
39
+ export function binariesFor(local, held) {
40
+ const binaries = {};
41
+ for (const path of Object.keys(local).sort()) {
42
+ const picture = local[path];
43
+ binaries[path] = held.has(blobKey(path, picture.hash))
44
+ ? { hash: picture.hash }
45
+ : picture.base64;
46
+ }
47
+ return binaries;
48
+ }
8
49
  /** The files every theme has to hold. */
9
50
  export const REQUIRED = [
10
51
  'theme.json',
package/package.json CHANGED
@@ -1,37 +1,39 @@
1
1
  {
2
- "name": "@politelabs/cabin-cli",
3
- "version": "0.3.0",
4
- "description": "Develop a Cabin site theme locally: init, dev, push, pull, check, publish.",
5
- "license": "MIT",
6
- "repository": {
7
- "type": "git",
8
- "url": "https://github.com/PoliteLabs/cabin-cli.git"
9
- },
10
- "type": "module",
11
- "bin": {
12
- "cabin": "dist/index.js"
13
- },
14
- "files": [
15
- "dist",
16
- "README.md"
17
- ],
18
- "engines": {
19
- "node": ">=22.12"
20
- },
21
- "publishConfig": {
22
- "access": "public"
23
- },
24
- "devDependencies": {
25
- "@biomejs/biome": "2.2.4",
26
- "@types/node": "^22.13.5",
27
- "typescript": "^5.9.3",
28
- "vitest": "^3.2.4"
29
- },
30
- "scripts": {
31
- "build": "tsc -p tsconfig.build.json",
32
- "check": "biome check .",
33
- "check:fix": "biome check --write .",
34
- "types:check": "tsc --noEmit",
35
- "test": "vitest run"
36
- }
37
- }
2
+ "name": "@politelabs/cabin-cli",
3
+ "version": "0.5.0",
4
+ "description": "Develop a Cabin site theme locally: init, dev, push, pull, check, publish.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/PoliteLabs/cabin-cli.git"
9
+ },
10
+ "type": "module",
11
+ "bin": {
12
+ "cabin": "dist/index.js"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22.12"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.build.json",
26
+ "check": "biome check .",
27
+ "check:fix": "biome check --write .",
28
+ "types:check": "tsc --noEmit",
29
+ "test": "vitest run",
30
+ "prepublishOnly": "pnpm build"
31
+ },
32
+ "devDependencies": {
33
+ "@biomejs/biome": "2.2.4",
34
+ "@types/node": "^22.13.5",
35
+ "typescript": "^5.9.3",
36
+ "vitest": "^3.2.4"
37
+ },
38
+ "packageManager": "pnpm@12.15.0"
39
+ }