@politelabs/cabin-cli 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Polite Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # Cabin CLI
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
+ Develop a [Cabin](https://cabincms.com) site theme in a folder on your own machine, with your editor, git and a build tool, and sync it with the site as Shopify's CLI syncs a theme with a store. Rendering never leaves the server: `cabin theme dev` keeps a draft of your folder on the site and the page you have open draws itself again on every change.
4
+
5
+ ```
6
+ npm install --global @politelabs/cabin-cli
7
+ ```
8
+
9
+ Node 22.12 or newer. Nothing else is installed with it.
10
+
11
+ ## Signing in
12
+
13
+ A token is made on the site, under Site settings › API tokens: a *management* token, which acts as you. A self-hosted install can make one with `php artisan cabin:tokens:make`.
14
+
15
+ ```
16
+ cabin login
17
+ ```
18
+
19
+ That signs in to https://app.cabincms.com. For a self-hosted install, set `CABIN_HOST=https://cabin.example.com`. Inside a theme's folder, the host in `cabin.json` is used.
20
+
21
+ The token is kept in `~/.config/cabin/credentials.json`, by host and site, never in the theme's folder.
22
+
23
+ ## A theme
24
+
25
+ ```
26
+ cabin theme init --from birch # asks which site and what to call the theme
27
+ cd riverside
28
+ pnpm install # Tailwind, unless --no-tailwind
29
+ cabin theme dev # watches the folder, prints the preview link
30
+ cabin theme push --note "Tighter header" # saves a version
31
+ cabin theme publish # draws the site with it
32
+ ```
33
+
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
+
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.
37
+
38
+ | Command | What it does |
39
+ | --- | --- |
40
+ | `cabin login [--token]` | Keep a token for a host and site. The host defaults to https://app.cabincms.com. `logout` forgets it; `whoami` says who it is. |
41
+ | `cabin theme init [dir] [--from blank\|birch] [--site] [--name] [--key] [--no-tailwind]` | Make a theme on a site and write it into a folder. Asks for the site and name when they aren't given. |
42
+ | `cabin theme list` | The site's themes, with a star on the one the site is drawn with. |
43
+ | `cabin theme pull [--theme key] [--version id] [--all]` | Take the current (or a named) version's files. `theme.css` is skipped when `src/theme.css` exists, unless `--all`. |
44
+ | `cabin theme check [--no-build]` | Run every check a save runs, writing nothing. |
45
+ | `cabin theme push [--note] [--force] [--check] [--no-build]` | Save a version. Refused when someone saved since you pulled; `--force` saves over it. |
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 publish` | Draw the site with the theme. |
48
+ | `cabin theme open [--site]` | Open the Theme files screen, or the site. |
49
+
50
+ Problems are printed as `templates/home.twig:12 The raw filter isn't needed…`, the way the admin's Theme files screen says them. The built stylesheet is held to the same rules: no `@import`, no address on another host, at most 256 KB.
51
+
52
+ ## Developing the CLI
53
+
54
+ ```
55
+ pnpm install
56
+ pnpm test # units, and every command against a stub of the API
57
+ pnpm build # dist/index.js
58
+ node dist/index.js --help
59
+ ```
60
+
61
+ `CABIN_TEST_HOST` and `CABIN_TEST_TOKEN` run a smoke test against a real Cabin. The CLI follows the content API's contract, `docs/api/openapi.yaml` in the Cabin repository.
@@ -0,0 +1,45 @@
1
+ import { join } from 'node:path';
2
+ import { readText, writeText } from '../io/fs.js';
3
+ import { ApiClient } from '../lib/api.js';
4
+ import { CONFIG_FILE, DEFAULT_HOST, normalizeHost, parseConfig, parseState, STATE_FILE, serializeState, } from '../lib/config.js';
5
+ import { credentialsDir, parseCredentials, pick } from '../lib/credentials.js';
6
+ export class Refused extends Error {
7
+ }
8
+ /** Read `cabin.json` from the working directory, or refuse. */
9
+ export async function project(io) {
10
+ const json = await readText(join(io.cwd, CONFIG_FILE));
11
+ if (json === null) {
12
+ throw new Refused(`There's no ${CONFIG_FILE} here. Run cabin theme init to start a theme, or cd into one.`);
13
+ }
14
+ const config = parseConfig(json);
15
+ if ('error' in config) {
16
+ throw new Refused(config.error);
17
+ }
18
+ const token = await tokenFor(io, config.host, config.site);
19
+ const state = parseState(await readText(join(io.cwd, STATE_FILE)));
20
+ return {
21
+ config,
22
+ state,
23
+ api: new ApiClient(config.host, token, io.fetch),
24
+ root: io.cwd,
25
+ saveState: (next) => writeText(join(io.cwd, STATE_FILE), serializeState(next)),
26
+ };
27
+ }
28
+ /** The token kept for a host and site, or refuse with what to do. */
29
+ export async function tokenFor(io, host, site) {
30
+ const envToken = io.env.CABIN_TOKEN;
31
+ if (envToken) {
32
+ return envToken;
33
+ }
34
+ const credentials = parseCredentials(await readText(join(credentialsDir(io.env, io.home), 'credentials.json')));
35
+ const kept = pick(credentials, host, site);
36
+ if (kept === null) {
37
+ throw new Refused(`No token is kept for ${site} on ${host}. Run cabin login${host === DEFAULT_HOST ? '' : ` with CABIN_HOST=${host}`}.`);
38
+ }
39
+ return kept.token;
40
+ }
41
+ /** The host named by CABIN_HOST, if any. */
42
+ export function hostFrom(io) {
43
+ const given = io.env.CABIN_HOST ?? null;
44
+ return given === null ? null : normalizeHost(given);
45
+ }
@@ -0,0 +1,77 @@
1
+ import { join } from 'node:path';
2
+ import { readText, writeText } from '../io/fs.js';
3
+ import { ApiClient, ApiFailed } from '../lib/api.js';
4
+ import { flag } from '../lib/args.js';
5
+ import { CONFIG_FILE, DEFAULT_HOST, parseConfig } from '../lib/config.js';
6
+ import { credentialsDir, drop, looksLikeToken, parseCredentials, put, serializeCredentials, } from '../lib/credentials.js';
7
+ import { hostFrom, Refused, tokenFor } from './context.js';
8
+ /** The host to sign in to: the flag or CABIN_HOST, then cabin.json, then Cabin's own. */
9
+ async function loginHost(io) {
10
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
11
+ return (hostFrom(io) ??
12
+ ('error' in fromProject ? null : fromProject.host) ??
13
+ DEFAULT_HOST);
14
+ }
15
+ /** Keep a token for a host and the site it names. */
16
+ export async function login(parsed, io) {
17
+ const host = await loginHost(io);
18
+ let token = flag(parsed, 'token') ?? io.env.CABIN_TOKEN ?? '';
19
+ if (token === '') {
20
+ token = (await io.prompt('Paste a management token from Site settings › API tokens: ', true)).trim();
21
+ }
22
+ if (!looksLikeToken(token)) {
23
+ throw new Refused("That doesn't look like one of Cabin's tokens: they start with cabin_ and are 46 characters long.");
24
+ }
25
+ let info;
26
+ try {
27
+ info = await new ApiClient(host, token, io.fetch).token_();
28
+ }
29
+ catch (error) {
30
+ if (error instanceof ApiFailed && error.status === 401) {
31
+ throw new Refused(`That token isn't accepted by ${host}.`);
32
+ }
33
+ throw error;
34
+ }
35
+ if (info.kind !== 'management') {
36
+ io.err(`This is a ${info.kind} token. The theme commands need a management token, which acts as you.`);
37
+ }
38
+ const file = join(credentialsDir(io.env, io.home), 'credentials.json');
39
+ const all = put(parseCredentials(await readText(file)), host, info.site.handle, {
40
+ token,
41
+ name: info.user?.name ?? info.name,
42
+ savedAt: new Date(io.now()).toISOString(),
43
+ });
44
+ await writeText(file, serializeCredentials(all), 0o600);
45
+ io.out(`Signed in to ${info.site.name} (${info.site.handle}) on ${host}${info.user ? ` as ${info.user.name}` : ''}.`);
46
+ return 0;
47
+ }
48
+ /** Forget a token. */
49
+ export async function logout(parsed, io) {
50
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
51
+ const host = hostFrom(io) ?? ('error' in fromProject ? null : fromProject.host);
52
+ const site = flag(parsed, 'site') ??
53
+ ('error' in fromProject ? null : fromProject.site);
54
+ if (host === null || site === null) {
55
+ throw new Refused("Say which to forget: cabin logout --site handle, or run it inside a theme's folder.");
56
+ }
57
+ const file = join(credentialsDir(io.env, io.home), 'credentials.json');
58
+ await writeText(file, serializeCredentials(drop(parseCredentials(await readText(file)), host, site)), 0o600);
59
+ io.out(`Forgot the token for ${site} on ${host}.`);
60
+ return 0;
61
+ }
62
+ /** Say who the kept token is. */
63
+ export async function whoami(parsed, io) {
64
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
65
+ const host = hostFrom(io) ?? ('error' in fromProject ? null : fromProject.host);
66
+ const site = flag(parsed, 'site') ??
67
+ ('error' in fromProject ? null : fromProject.site);
68
+ if (host === null || site === null) {
69
+ throw new Refused("Say which: cabin whoami --site handle, or run it inside a theme's folder.");
70
+ }
71
+ const info = await new ApiClient(host, await tokenFor(io, host, site), io.fetch).token_();
72
+ io.out(`${info.site.name} (${info.site.handle}) on ${host}${info.site.url ? `, at ${info.site.url}` : ''}`);
73
+ io.out(info.user
74
+ ? `${info.user.name} <${info.user.email}>, through the ${info.kind} token "${info.name}"`
75
+ : `The ${info.kind} token "${info.name}"`);
76
+ return 0;
77
+ }
@@ -0,0 +1,24 @@
1
+ import { ApiFailed } from '../../lib/api.js';
2
+ import { has } from '../../lib/args.js';
3
+ import { problemLines } from '../../lib/problems.js';
4
+ import { project } from '../context.js';
5
+ import { buildFirst, filesIn } from './sync.js';
6
+ /** Run every check a save runs, writing nothing. */
7
+ export async function check(parsed, io) {
8
+ const { api, config, root } = await project(io);
9
+ await buildFirst(root, io, has(parsed, 'no-build'));
10
+ try {
11
+ const answer = await api.check(config.theme, await filesIn(root));
12
+ io.out(`No problems in ${answer.files} ${answer.files === 1 ? 'file' : 'files'} of "${answer.name}".`);
13
+ return 0;
14
+ }
15
+ catch (error) {
16
+ if (error instanceof ApiFailed && error.status === 422) {
17
+ for (const line of problemLines(error.errors)) {
18
+ io.err(line);
19
+ }
20
+ return 1;
21
+ }
22
+ throw error;
23
+ }
24
+ }
@@ -0,0 +1,122 @@
1
+ import { watch } from 'node:fs';
2
+ import { ApiFailed } from '../../lib/api.js';
3
+ import { flag, has } from '../../lib/args.js';
4
+ import { paint, syncedLine, wantsColor } from '../../lib/output.js';
5
+ import { problemLines } from '../../lib/problems.js';
6
+ import { isSkipped, isThemePath, toThemePath } from '../../lib/theme-files.js';
7
+ import { backoff, Debounce } from '../../lib/watch.js';
8
+ import { project } from '../context.js';
9
+ import { filesIn, scriptIn } from './sync.js';
10
+ /**
11
+ * Keep a draft of the folder on the site as it changes: the theme's `dev`
12
+ * script runs beside the watcher, every burst of changes is sent as one
13
+ * sync under the same draft token, and the page open on the link draws
14
+ * itself again. Ctrl-C ends both.
15
+ */
16
+ export async function dev(parsed, io) {
17
+ const { api, config, state, root, saveState } = await project(io);
18
+ const path = flag(parsed, 'path') ?? '/';
19
+ const color = wantsColor(io.isTTY, io.env);
20
+ let token = state.draftToken;
21
+ let failures = 0;
22
+ let stopped = false;
23
+ const child = has(parsed, 'no-build') ? null : await startScript(root, io);
24
+ const send = async (first) => {
25
+ try {
26
+ const draft = await api.draft(config.theme, await filesIn(root), path, token);
27
+ const renewed = token !== null && token !== draft.token;
28
+ token = draft.token;
29
+ await saveState({ ...state, draftToken: token });
30
+ failures = 0;
31
+ if (first || renewed) {
32
+ io.out(`Preview: ${paint(draft.url, 'cyan', color)}`);
33
+ io.out('The page draws itself again on every change. Ctrl-C stops.');
34
+ }
35
+ else if (draft.made) {
36
+ io.out('The draft had ended while idle; the same link works again.');
37
+ }
38
+ io.out(syncedLine(new Date(io.now()), Object.keys(await filesIn(root)).length));
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof ApiFailed && error.status === 422) {
43
+ for (const line of problemLines(error.errors)) {
44
+ io.err(paint(line, 'yellow', color));
45
+ }
46
+ return true;
47
+ }
48
+ if (error instanceof ApiFailed &&
49
+ (error.status === 401 || error.status === 403)) {
50
+ io.err(error.status === 401
51
+ ? 'The token was refused. Run cabin login.'
52
+ : `This token can't manage themes on ${config.site}.`);
53
+ stopped = true;
54
+ return false;
55
+ }
56
+ if (error instanceof ApiFailed && error.status === 0) {
57
+ failures += 1;
58
+ const wait = backoff(failures);
59
+ io.err(`Can't reach ${config.host}; trying again in ${Math.round(wait / 1000)} s.`);
60
+ await io.sleep(wait);
61
+ return false;
62
+ }
63
+ throw error;
64
+ }
65
+ };
66
+ let ok = await send(true);
67
+ while (!ok && !stopped) {
68
+ ok = await send(true);
69
+ }
70
+ if (stopped) {
71
+ child?.kill('SIGTERM');
72
+ return 1;
73
+ }
74
+ const debounce = new Debounce();
75
+ let dirty = false;
76
+ const watcher = watch(root, { recursive: true }, (_event, filename) => {
77
+ const relative = toThemePath(String(filename ?? ''));
78
+ if (relative === '' || isSkipped(relative) || !isThemePath(relative)) {
79
+ return;
80
+ }
81
+ debounce.push(io.now());
82
+ dirty = true;
83
+ });
84
+ const loop = (async () => {
85
+ while (!stopped) {
86
+ const due = debounce.due(io.now());
87
+ if (dirty && due !== null && due <= 0 && debounce.fire(io.now())) {
88
+ dirty = false;
89
+ let sent = await send(false);
90
+ while (!sent && !stopped) {
91
+ sent = await send(false);
92
+ }
93
+ }
94
+ await io.sleep(due === null ? 100 : Math.max(20, Math.min(due, 100)));
95
+ }
96
+ })();
97
+ await io.stopped;
98
+ stopped = true;
99
+ watcher.close();
100
+ await loop;
101
+ if (child !== null) {
102
+ child.kill('SIGTERM');
103
+ await Promise.race([
104
+ new Promise((resolve) => child.once('exit', () => resolve())),
105
+ io.sleep(2000),
106
+ ]);
107
+ if (child.exitCode === null) {
108
+ child.kill('SIGKILL');
109
+ }
110
+ }
111
+ io.out('Stopped. The draft stays on the site until it goes quiet for an hour; the next cabin theme dev brings the same link back.');
112
+ return 0;
113
+ }
114
+ async function startScript(root, io) {
115
+ const script = await scriptIn(root, 'dev', io);
116
+ if (script === null) {
117
+ return null;
118
+ }
119
+ const [command, args] = script;
120
+ io.out(`Running ${command} ${args.join(' ')} beside the watcher…`);
121
+ return io.spawn(command, args, root);
122
+ }
@@ -0,0 +1,143 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { exists, readText, writeText } from '../../io/fs.js';
3
+ import { ApiClient, ApiFailed } from '../../lib/api.js';
4
+ import { flag, has } from '../../lib/args.js';
5
+ import { parseChoice } from '../../lib/choose.js';
6
+ import { CONFIG_FILE, DEFAULT_HOST, serializeState } from '../../lib/config.js';
7
+ import { credentialsDir, parseCredentials, sitesOn, } from '../../lib/credentials.js';
8
+ import { problemLines } from '../../lib/problems.js';
9
+ import { scaffold } from '../../lib/scaffold.js';
10
+ import { hostFrom, Refused, tokenFor } from '../context.js';
11
+ /** A key from a name: lowercase letters, digits and hyphens, starting with a letter. */
12
+ export function keyFrom(name) {
13
+ const key = name
14
+ .toLowerCase()
15
+ .normalize('NFKD')
16
+ .replace(/[^a-z0-9]+/g, '-')
17
+ .replace(/^-+|-+$/g, '')
18
+ .slice(0, 63);
19
+ return /^[a-z]/.test(key) ? key : `theme-${key}`.replace(/-+$/, '');
20
+ }
21
+ /**
22
+ * The site to make the theme on: the flag or CABIN_SITE, else one of the
23
+ * sites a token is kept for on the host, asked for when there are several.
24
+ * The API names a token's site but lists no others, so the list is the
25
+ * kept tokens, each asked for its site's name.
26
+ */
27
+ async function chooseSite(parsed, io, host) {
28
+ const given = flag(parsed, 'site') ?? io.env.CABIN_SITE ?? null;
29
+ if (given !== null) {
30
+ return given;
31
+ }
32
+ const credentials = parseCredentials(await readText(join(credentialsDir(io.env, io.home), 'credentials.json')));
33
+ const handles = sitesOn(credentials, host);
34
+ if (handles.length === 0) {
35
+ throw new Refused(`You aren't signed in to a site on ${host}. Run cabin login first.`);
36
+ }
37
+ const found = await Promise.all(handles.map(async (handle) => {
38
+ const token = credentials.hosts[host]?.[handle]?.token ?? '';
39
+ try {
40
+ const info = await new ApiClient(host, token, io.fetch).token_();
41
+ return { handle, name: info.site.name };
42
+ }
43
+ catch (error) {
44
+ if (error instanceof ApiFailed && error.status === 401) {
45
+ io.err(`The token for ${handle} isn't accepted any more. Run cabin login to replace it.`);
46
+ return null;
47
+ }
48
+ throw error;
49
+ }
50
+ }));
51
+ const sites = found.filter((site) => site !== null);
52
+ const [only] = sites;
53
+ if (only === undefined) {
54
+ throw new Refused(`No kept token is accepted by ${host}.`);
55
+ }
56
+ if (sites.length === 1) {
57
+ io.out(`Site: ${only.name} (${only.handle})`);
58
+ return only.handle;
59
+ }
60
+ io.out('Which site is the theme for?');
61
+ sites.forEach((site, index) => {
62
+ io.out(` ${index + 1}. ${site.name} (${site.handle})`);
63
+ });
64
+ const index = parseChoice(await io.prompt(`Site (1-${sites.length}): `), sites.length);
65
+ const chosen = index === null ? undefined : sites[index];
66
+ if (chosen === undefined) {
67
+ throw new Refused(`Pick a number from 1 to ${sites.length}.`);
68
+ }
69
+ return chosen.handle;
70
+ }
71
+ /** The theme's name: the flag, else asked for, offering the folder's name. */
72
+ async function chooseName(parsed, io, dir) {
73
+ const given = flag(parsed, 'name');
74
+ if (given !== null) {
75
+ return given;
76
+ }
77
+ const fromDir = dir?.split(/[\\/]/).filter(Boolean).at(-1);
78
+ const typed = (await io.prompt(`What should the theme be called?${fromDir ? ` (${fromDir})` : ''} `)).trim();
79
+ const name = typed === '' ? fromDir : typed;
80
+ if (name === undefined || name === '') {
81
+ throw new Refused('Give the theme a name.');
82
+ }
83
+ return name;
84
+ }
85
+ /** Make a theme on the site and write it into a folder. */
86
+ export async function init(parsed, io) {
87
+ const given = parsed.positionals[0];
88
+ if (given !== undefined &&
89
+ (await exists(join(resolve(io.cwd, given), CONFIG_FILE)))) {
90
+ throw new Refused(`${given} already holds a theme (${CONFIG_FILE}). Use cabin theme pull there instead.`);
91
+ }
92
+ const host = hostFrom(io) ?? DEFAULT_HOST;
93
+ const site = await chooseSite(parsed, io, host);
94
+ const api = new ApiClient(host, await tokenFor(io, host, site), io.fetch);
95
+ const name = await chooseName(parsed, io, given);
96
+ const key = flag(parsed, 'key') ?? keyFrom(name);
97
+ const dir = given ?? key;
98
+ const root = resolve(io.cwd, dir);
99
+ if (given === undefined && (await exists(join(root, CONFIG_FILE)))) {
100
+ throw new Refused(`${dir} already holds a theme (${CONFIG_FILE}). Use cabin theme pull there instead.`);
101
+ }
102
+ const from = flag(parsed, 'from') ?? 'blank';
103
+ const sources = await api.sources();
104
+ if (!sources.some((source) => source.key === from)) {
105
+ throw new Refused(`There's nothing to start from called "${from}". Try: ${sources.map((s) => s.key).join(', ')}.`);
106
+ }
107
+ let theme;
108
+ try {
109
+ theme = await api.create(key, name, from);
110
+ }
111
+ catch (error) {
112
+ if (error instanceof ApiFailed && error.status === 422) {
113
+ for (const line of problemLines(error.errors)) {
114
+ io.err(line);
115
+ }
116
+ if ('key' in error.errors) {
117
+ io.err('Pick another key with --key.');
118
+ }
119
+ return 1;
120
+ }
121
+ throw error;
122
+ }
123
+ const tailwind = !has(parsed, 'no-tailwind');
124
+ for (const file of scaffold({ host, site, theme: theme.key }, theme.files, {
125
+ tailwind,
126
+ })) {
127
+ await writeText(join(root, file.path), file.contents);
128
+ }
129
+ await writeText(join(root, '.cabin', 'state.json'), serializeState({
130
+ versionId: theme.version?.id ?? null,
131
+ draftToken: null,
132
+ }));
133
+ io.out(`Made the theme "${theme.name}" (${theme.key}) on ${site}, from ${from}, in ${dir}.`);
134
+ io.out('');
135
+ io.out('Next:');
136
+ io.out(` cd ${dir}`);
137
+ if (tailwind) {
138
+ io.out(' pnpm install # or npm install: Tailwind, for src/theme.css');
139
+ }
140
+ io.out(' cabin theme dev # keeps a draft on the site as you work, and prints its link');
141
+ io.out(' cabin theme push # saves a version');
142
+ return 0;
143
+ }
@@ -0,0 +1,27 @@
1
+ import { themeTable } from '../../lib/output.js';
2
+ import { project } from '../context.js';
3
+ /** The site's themes. */
4
+ export async function list(_parsed, io) {
5
+ const { api, config } = await project(io);
6
+ const answer = await api.themes();
7
+ for (const line of themeTable(answer.themes.map((theme) => ({
8
+ key: theme.key,
9
+ name: theme.name,
10
+ chosen: theme.chosen,
11
+ version: theme.version?.number ?? null,
12
+ by: theme.version?.by ?? null,
13
+ at: theme.version?.createdAt ?? null,
14
+ })))) {
15
+ io.out(line);
16
+ }
17
+ if (answer.chosen !== null && !answer.chosen.startsWith('site:')) {
18
+ io.out(`The site is drawn with the install's theme "${answer.chosen}".`);
19
+ }
20
+ else if (answer.chosen === null) {
21
+ io.out('The site is on its own frontend.');
22
+ }
23
+ if (!answer.themes.some((theme) => theme.key === config.theme)) {
24
+ io.err(`This folder's theme, "${config.theme}", isn't on the site any more.`);
25
+ }
26
+ return 0;
27
+ }
@@ -0,0 +1,19 @@
1
+ import { has } from '../../lib/args.js';
2
+ import { project, Refused } from '../context.js';
3
+ /** Open the Theme files screen, or the site, in the browser. */
4
+ export async function open(parsed, io) {
5
+ const { api, config } = await project(io);
6
+ if (has(parsed, 'site')) {
7
+ const theme = await api.theme(config.theme);
8
+ if (theme.siteUrl === null) {
9
+ throw new Refused('This site has no address yet. Add a domain in Site settings, under General.');
10
+ }
11
+ await io.open(theme.siteUrl);
12
+ io.out(theme.siteUrl);
13
+ return 0;
14
+ }
15
+ const url = `${config.host}/sites/${config.site}/themes/${config.theme}/edit`;
16
+ await io.open(url);
17
+ io.out(url);
18
+ return 0;
19
+ }
@@ -0,0 +1,13 @@
1
+ import { standing } from '../../lib/versions.js';
2
+ import { project } from '../context.js';
3
+ /** Draw the site with the theme. */
4
+ export async function publish(_parsed, io) {
5
+ const { api, config, state } = await project(io);
6
+ const theme = await api.theme(config.theme);
7
+ if (standing(state.versionId, theme.version?.id ?? null) === 'behind') {
8
+ io.err(`The site's version ${theme.version?.number ?? '?'} isn't the one you last pushed. Pull or push first if that matters.`);
9
+ }
10
+ const answer = await api.choose(config.theme);
11
+ io.out(`Visitors now see "${answer.name}"${answer.version === null ? '' : ` (version ${answer.version})`}.`);
12
+ return 0;
13
+ }
@@ -0,0 +1,48 @@
1
+ import { join } from 'node:path';
2
+ import { exists, remove, walk, writeText } from '../../io/fs.js';
3
+ import { flag, has } from '../../lib/args.js';
4
+ import { isGenerated, isThemePath } from '../../lib/theme-files.js';
5
+ import { project, Refused } from '../context.js';
6
+ import { hasSource } from './sync.js';
7
+ /** Take the theme's files from the site into the folder. */
8
+ export async function pull(parsed, io) {
9
+ const { api, config, state, root, saveState } = await project(io);
10
+ const key = flag(parsed, 'theme') ?? config.theme;
11
+ const versionId = flag(parsed, 'version');
12
+ const all = has(parsed, 'all');
13
+ if (versionId !== null && !/^\d+$/.test(versionId)) {
14
+ throw new Refused("--version takes a version's id, as cabin theme list and the Theme files screen show it.");
15
+ }
16
+ const taken = versionId === null
17
+ ? await api.theme(key)
18
+ : await api.version(key, Number(versionId));
19
+ const files = taken.files;
20
+ const version = 'version' in taken ? taken.version : taken;
21
+ const generated = await hasSource(root);
22
+ let written = 0;
23
+ let skipped = null;
24
+ for (const [path, contents] of Object.entries(files)) {
25
+ if (!all && isGenerated(path, () => generated)) {
26
+ skipped = path;
27
+ continue;
28
+ }
29
+ await writeText(join(root, path), contents);
30
+ written += 1;
31
+ }
32
+ // What the site no longer has goes too, among the theme's own files.
33
+ let removed = 0;
34
+ for (const [relative] of await walk(root)) {
35
+ if (isThemePath(relative) &&
36
+ !(relative in files) &&
37
+ (await exists(join(root, relative)))) {
38
+ await remove(join(root, relative));
39
+ removed += 1;
40
+ }
41
+ }
42
+ await saveState({ ...state, versionId: version?.id ?? state.versionId });
43
+ 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
+ if (skipped !== null) {
45
+ io.out(`${skipped} is built from src/${skipped} here, so it was skipped. Use --all to take the site's.`);
46
+ }
47
+ return 0;
48
+ }
@@ -0,0 +1,35 @@
1
+ import { ApiFailed } from '../../lib/api.js';
2
+ import { flag, has } from '../../lib/args.js';
3
+ import { problemLines } from '../../lib/problems.js';
4
+ import { conflictLine, currentOf } from '../../lib/versions.js';
5
+ import { project } from '../context.js';
6
+ import { check } from './check.js';
7
+ import { buildFirst, filesIn } from './sync.js';
8
+ /** Save the folder's files as a version. */
9
+ export async function push(parsed, io) {
10
+ if (has(parsed, 'check')) {
11
+ return check(parsed, io);
12
+ }
13
+ const { api, config, state, root, saveState } = await project(io);
14
+ await buildFirst(root, io, has(parsed, 'no-build'));
15
+ const base = has(parsed, 'force') ? null : state.versionId;
16
+ try {
17
+ const theme = await api.save(config.theme, await filesIn(root), flag(parsed, 'note'), base);
18
+ await saveState({ ...state, versionId: theme.version?.id ?? null });
19
+ io.out(`Pushed as version ${theme.version?.number ?? '?'} of "${theme.name}".${theme.chosen ? ' The site shows it now.' : ''}`);
20
+ return 0;
21
+ }
22
+ catch (error) {
23
+ if (error instanceof ApiFailed && error.status === 409) {
24
+ io.err(conflictLine(currentOf(error.body)));
25
+ return 1;
26
+ }
27
+ if (error instanceof ApiFailed && error.status === 422) {
28
+ for (const line of problemLines(error.errors)) {
29
+ io.err(line);
30
+ }
31
+ return 1;
32
+ }
33
+ throw error;
34
+ }
35
+ }