cook-ssg 2.5.0 → 2.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cook-ssg",
3
- "version": "2.5.0",
3
+ "version": "2.7.0",
4
4
  "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
5
  "type": "module",
6
6
  "bin": {
package/scripts/build.js CHANGED
@@ -25,6 +25,8 @@ import generateSitemap from './plugins/generate-sitemap-xml.js';
25
25
  import htmlCollections from './plugins/html-collections.js';
26
26
  import minifySrc from './plugins/minify-src.js';
27
27
  import { optimizeImagesGenerate, optimizeImagesRewrite } from './plugins/optimize-images.js';
28
+ import { programsData, programHeaders, allPrograms, loadProgramAreas } from './plugins/programs.js';
29
+ import { themeInject, resetThemeCache } from './plugins/theme.js';
28
30
  import { packageComponentsCopy, packageComponentsInject } from './plugins/package-components.js';
29
31
  import processMarkdown from './plugins/process-markdown.js';
30
32
  import repeatCollection from './plugins/repeat-collection.js';
@@ -47,7 +49,8 @@ import { collectSitePages } from './utils/site-pages/site-pages.js';
47
49
 
48
50
  // CONFIG
49
51
  // Combined user overrides on top of internal defaults
50
- import config, { plugins } from './utils/config/config.js';
52
+ import config, { plugins, distPath, siteRoot } from './utils/config/config.js';
53
+ import { siteRootDir } from './utils/site-root/site-root.js';
51
54
 
52
55
  const cwd = process.cwd();
53
56
 
@@ -83,6 +86,9 @@ class Build {
83
86
  // Show init message
84
87
  console.log(`${ chalk.blue('\n[Build]') } ${ chalk.blue.bold('`npm run build`') }`);
85
88
 
89
+ // Program areas must be known before any pass runs (copySrc is first)
90
+ loadProgramAreas();
91
+
86
92
  // PLUGIN: Create `/dist` if not already made
87
93
  await createDist();
88
94
 
@@ -97,6 +103,9 @@ class Build {
97
103
  // see every page; merges with markdown collections.
98
104
  await htmlCollections({store, data});
99
105
 
106
+ // PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
107
+ await programsData({data});
108
+
100
109
  // PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
101
110
  await optimizeImagesGenerate({store});
102
111
 
@@ -185,6 +194,9 @@ class Build {
185
194
  // PLUGIN: Add a module script for npm component packages used on the page
186
195
  await packageComponentsInject({file, store, allowType: ['.html']});
187
196
 
197
+ // PLUGIN: Site theme: data-theme/data-mode on <html> (or the article) and theme stylesheet links, from `theme` config
198
+ await themeInject({file, allowType: ['.html']});
199
+
188
200
  // PLUGIN: Pre-render Declarative Shadow DOM for web components
189
201
  await declarativeShadowDom({file, store, allowType: ['.html']});
190
202
 
@@ -243,6 +255,15 @@ class Build {
243
255
  // built-in post-loop plugin so they all work with plain root paths.
244
256
  await applyBasePath();
245
257
 
258
+ // Sandboxed programs: `_headers` rules (Cloudflare Pages, Netlify) appended
259
+ // to the site's own `_headers`, which copySrc already placed in dist.
260
+ if (!Util.validatePageChange()) {
261
+ const headersFile = path.join(siteRootDir(distPath, siteRoot), '_headers');
262
+ const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf-8') : null;
263
+ const headers = programHeaders(allPrograms(), existing);
264
+ if (headers !== null) fs.writeFileSync(headersFile, headers);
265
+ }
266
+
246
267
  // CUSTOM PLUGINS: Run custom user plugins after file loop
247
268
  await customPlugins({store, data, plugins: plugins.after, log: 'After' });
248
269
 
@@ -278,6 +299,7 @@ export async function runBuild() {
278
299
  delete store.cachedLayouts;
279
300
  delete store.cachedInline;
280
301
  }
302
+ resetThemeCache();
281
303
  store.bundle = { css: {}, js: {} };
282
304
  // Collections are fully rebuilt by processMarkdown every run — stale
283
305
  // entries would otherwise accumulate (duplicate blog posts on the
package/scripts/dev.js CHANGED
@@ -8,6 +8,8 @@ import path from 'node:path';
8
8
  // In-process rebuilds: no cold Node process per save — module imports,
9
9
  // config, and (for single-page rebuilds) template caches stay warm
10
10
  import { runBuild } from './build.js';
11
+ import fs from 'fs-extra';
12
+ import { loadProgramAreas, isProgramFile } from './plugins/programs.js';
11
13
 
12
14
  const browserSync = browserSyncLib.create('Dev Server');
13
15
 
@@ -113,6 +115,21 @@ async function rebuild(file) {
113
115
  }
114
116
  building = true;
115
117
 
118
+ // A change inside a program folder is copied as is: no page build
119
+ loadProgramAreas();
120
+ if (isProgramFile(file, srcPath)) {
121
+ const fileDist = file.replace(`${srcPath}/`, `${distPath}/`);
122
+ try {
123
+ await fs.copy(file, fileDist);
124
+ browserSync.reload(fileDist);
125
+ } catch (err) {
126
+ console.error(chalk.red(`\n[dev] Could not copy ${file}: ${err && err.message ? err.message : err}`));
127
+ }
128
+ building = false;
129
+ if (queuedFile) { const next = queuedFile; queuedFile = null; rebuild(next); }
130
+ return;
131
+ }
132
+
116
133
  // DEV_CHANGED_PAGE tells the build whether to run the whole pipeline
117
134
  // or just this changed file (see validatePageChange)
118
135
  process.env.DEV_CHANGED_PAGE = file;
@@ -147,3 +164,12 @@ watchFiles.forEach(watchPath => {
147
164
  // Watch `/src` files for changes
148
165
  browserSync.watch(`${srcPath}${watchPath}`).on('change', file => { rebuild(file); });
149
166
  });
167
+
168
+ // config/theme.json lives outside /src; Vanilla Press rewrites it on Apply.
169
+ // A change forces a full rebuild so every page picks up the new theme.
170
+ const themeJson = `${process.cwd()}/config/theme.json`;
171
+ browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
172
+
173
+ // config/programs.json (Vanilla Press) feeds the programs data: rebuild on change.
174
+ const programsJson = `${process.cwd()}/config/programs.json`;
175
+ browserSync.watch(programsJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
@@ -35,6 +35,7 @@ import { siteRootDir } from '../utils/site-root/site-root.js';
35
35
 
36
36
  // Config
37
37
  import { basePath as basePathConfig, distPath, siteRoot } from '../utils/config/config.js';
38
+ import { isProgramFile } from './programs.js';
38
39
 
39
40
 
40
41
  // ============================================================================
@@ -174,7 +175,7 @@ class ApplyBasePath {
174
175
  Logger.persist.header(`\nApply basePath ${this.basePath}`);
175
176
 
176
177
  const rootDir = siteRootDir(this.distPath, this.siteRoot);
177
- const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html'));
178
+ const htmlFiles = (Util.getPaths(rootDir, rootDir, []) || []).filter(p => p.endsWith('.html') && !isProgramFile(p, rootDir));
178
179
 
179
180
  let files = 0;
180
181
  let total = 0;
@@ -10,6 +10,7 @@ import chalk from 'chalk';
10
10
  import fs from 'fs-extra';
11
11
  import Logger from '../utils/logger/logger.js';
12
12
  import Util from '../utils/util/util.js';
13
+ import { isProgramFile } from './programs.js';
13
14
 
14
15
  // Config
15
16
  import { buildOnlyPaths, distPath, srcPath } from '../utils/config/config.js';
@@ -63,6 +64,8 @@ class CopySrc {
63
64
  if (pattern.test(src)) return false;
64
65
  }
65
66
  }
67
+ // Program folders ship untouched: every file, markdown included
68
+ if (isProgramFile(src, srcPath)) return true;
66
69
  // Skip directories (allow them to be traversed, filtering happens on files/subdirs)
67
70
  if (fs.lstatSync(src).isDirectory()) return true;
68
71
  // ---
@@ -13,6 +13,7 @@ import Logger from '../utils/logger/logger.js';
13
13
  import Spinner from '../utils/spinner/spinner.js';
14
14
  import Timer from '../utils/timer/timer.js';
15
15
  import { convertPageToDirectory, distPath } from '../utils/config/config.js';
16
+ import { isProgramFile } from './programs.js';
16
17
  import { getSrcConfig } from '../utils/get-src/get-src.js';
17
18
 
18
19
  const cwd = process.cwd();
@@ -99,6 +100,9 @@ class CreateDirFromFile {
99
100
  const allowed = utils.isAllowedType({file, allowType, disallowType});
100
101
  if (!allowed) return;
101
102
 
103
+ // Early Exit: program folders ship untouched
104
+ if (isProgramFile(fileName, distPath)) return;
105
+
102
106
  // Early Exit: Do not create directory if current file is an index.html page
103
107
  if (file.name === 'index') return;
104
108
 
@@ -24,6 +24,7 @@ import Util from '../utils/util/util.js';
24
24
  // Config
25
25
  import { distPath, siteRoot, fingerprint as fingerprintConfig } from '../utils/config/config.js';
26
26
  import { siteRootDir } from '../utils/site-root/site-root.js';
27
+ import { isProgramFile } from './programs.js';
27
28
 
28
29
 
29
30
  // ============================================================================
@@ -173,7 +174,7 @@ class FingerprintAssets {
173
174
 
174
175
  // Phase 2: Rewrite HTML references
175
176
  const htmlFiles = (Util.getPaths(this.rootDir, this.rootDir, []) || [])
176
- .filter(p => p.endsWith('.html'));
177
+ .filter(p => p.endsWith('.html') && !isProgramFile(p, this.rootDir));
177
178
  let totalRewrites = 0;
178
179
  for (const htmlPath of htmlFiles) {
179
180
  const original = await fs.readFile(htmlPath, 'utf-8');
@@ -203,6 +204,7 @@ class FingerprintAssets {
203
204
  return all.filter(p => {
204
205
  // Skip source maps in the candidate list — handled alongside their source.
205
206
  if (p.endsWith('.map')) return false;
207
+ if (isProgramFile(p, this.rootDir)) return false;
206
208
  const ext = path.extname(p);
207
209
  if (!this.config.types.includes(ext)) return false;
208
210
  if (excludes.some(r => r.test(p))) return false;
@@ -10,6 +10,7 @@ import Util from '../utils/util/util.js';
10
10
  // CONFIG
11
11
  import { distPath, fragments, sitemap, siteRoot, srcPath } from '../utils/config/config.js';
12
12
  import { siteRootDir } from '../utils/site-root/site-root.js';
13
+ import { isProgramFile } from './programs.js';
13
14
 
14
15
 
15
16
  // DEFINE
@@ -145,6 +146,8 @@ class GenerateSitemap {
145
146
  files = files.filter(fileName => Util.isExtension(fileName, allowedExt));
146
147
  // Skip SPA fragment files (content duplicates of their parent page)
147
148
  files = files.filter(fileName => !fileName.endsWith(`/${this.fragmentsFilename}`));
149
+ // Program folders are not site pages
150
+ files = files.filter(fileName => !isProgramFile(fileName, this.rootDir));
148
151
  // Format for xml: Remove `/dist`
149
152
  files = files.map(fileName => fileName.slice(this.rootDir.length));
150
153
  // Format for xml: Remove `filename`
@@ -34,6 +34,7 @@ import Logger from '../utils/logger/logger.js';
34
34
  import Util from '../utils/util/util.js';
35
35
  import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
36
36
  import { normalizeSiteRoot } from '../utils/site-root/site-root.js';
37
+ import { isInProgram } from './programs.js';
37
38
 
38
39
  // Config
39
40
  import {
@@ -174,6 +175,7 @@ export default async function htmlCollections({
174
175
  let collected = 0;
175
176
  for (const file of files) {
176
177
  const relPath = path.relative(srcPath, file).split(path.sep).join('/');
178
+ if (isInProgram(relPath)) continue;
177
179
  if (buildOnlyPaths.some(dir => relPath === dir || relPath.startsWith(`${dir}/`))) continue;
178
180
 
179
181
  const distFile = `${distPath}/${relPath}`;
@@ -24,6 +24,7 @@ import Util from '../utils/util/util.js';
24
24
 
25
25
  // Config
26
26
  import { distPath, images as imagesConfig } from '../utils/config/config.js';
27
+ import { isProgramFile } from './programs.js';
27
28
 
28
29
 
29
30
  // ============================================================================
@@ -113,6 +114,7 @@ class OptimizeImagesGenerate {
113
114
  const allPaths = Util.getPaths(dir, dir, []);
114
115
  if (!allPaths) return [];
115
116
  return allPaths.filter(p => {
117
+ if (isProgramFile(p, dir)) return false;
116
118
  const ext = path.extname(p).toLowerCase();
117
119
  if (!rasterExts.includes(ext)) return false;
118
120
  // Skip our own generated derivatives (foo-320w.webp) — rescanning
@@ -17,6 +17,7 @@ import { renderTemplate } from '../utils/interpolate/interpolate.js';
17
17
 
18
18
  // Config
19
19
  import { addToCollection, sortCollections, toCollectionItem } from '../utils/collections/collections.js';
20
+ import { isProgramFile } from './programs.js';
20
21
  import { distPath, srcPath, markdown as markdownConfig } from '../utils/config/config.js';
21
22
 
22
23
 
@@ -111,7 +112,7 @@ class ProcessMarkdown {
111
112
  const entries = Util.getPaths(dir, dir, []);
112
113
 
113
114
  for (const entry of entries) {
114
- if (entry.endsWith('.md')) {
115
+ if (entry.endsWith('.md') && !isProgramFile(entry, srcPath)) {
115
116
  files.push(entry);
116
117
  }
117
118
  }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * @file programs.js
3
+ * @description Programs: folders of hand-written HTML/JS (`src/<area>/<slug>/`)
4
+ * that Cook leaves untouched. Reads config/programs.json, validates areas and
5
+ * cards, exposes `programs` / `programAreas` data, and answers "is this path
6
+ * inside a program folder" (isInProgram) for the other build passes.
7
+ */
8
+
9
+ import chalk from 'chalk';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { getPrograms, srcPath, buildOnlyPaths } from '../utils/config/config.js';
13
+
14
+ const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/;
15
+ const isSlug = (v) => typeof v === 'string' && SLUG.test(v);
16
+ const TAG = '[programs] ';
17
+ export const RESERVED_AREAS = ['media', 'assets', 'layouts', 'includes'];
18
+
19
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /**
22
+ * Validate raw config/programs.json.
23
+ * @param {unknown} raw
24
+ * @param {{ srcEntries: string[], buildOnlyPaths: string[], hasIndex: (area: string, slug: string) => boolean }} ctx
25
+ */
26
+ export function normalizePrograms(raw, { srcEntries = [], buildOnlyPaths: buildOnly = [], hasIndex = () => true } = {}) {
27
+ const warnings = [];
28
+ const areas = [];
29
+ const programs = [];
30
+ // A slug-shaped area that collides with a page folder (R10): no programs data, but its
31
+ // subfolders stay program folders (untouched) and its sandboxed cards keep their rule.
32
+ const protectedAreas = [];
33
+ const protectedPrograms = [];
34
+ if (!isObj(raw)) return { areas, programs, warnings, protectedAreas, protectedPrograms };
35
+
36
+ const taken = new Set(srcEntries);
37
+ const buildOnlySet = new Set(buildOnly.map(p => String(p).replace(/^\/+|\/+$/g, '')));
38
+ const byPath = Object.create(null);
39
+ const protectedByPath = Object.create(null);
40
+
41
+ for (const a of Array.isArray(raw.areas) ? raw.areas : []) {
42
+ const p = isObj(a) ? a.path : undefined;
43
+ let why = null;
44
+ if (!isSlug(p)) why = 'use one lowercase segment (a-z, 0-9, hyphens)';
45
+ else if (RESERVED_AREAS.includes(p)) why = 'that name is reserved';
46
+ else if (buildOnlySet.has(p)) why = 'it is a buildOnlyPaths entry';
47
+ else if (byPath[p] || protectedByPath[p]) why = 'duplicate area';
48
+ else if (taken.has(p)) {
49
+ const area = { path: p, sandbox: a.sandbox === true };
50
+ protectedByPath[p] = area;
51
+ protectedAreas.push(area);
52
+ warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: the site already has a page or folder with that name `
53
+ + '(no programs data for it; its subfolders still ship untouched as program folders)');
54
+ continue;
55
+ }
56
+ if (why) {
57
+ warnings.push(`${TAG}area ${JSON.stringify(p)} ignored: ${why}`);
58
+ continue;
59
+ }
60
+ const area = { path: p, title: typeof a.title === 'string' && a.title ? a.title : p, sandbox: a.sandbox === true };
61
+ byPath[p] = area;
62
+ areas.push(area);
63
+ }
64
+
65
+ const seen = new Set();
66
+ for (const c of Array.isArray(raw.programs) ? raw.programs : []) {
67
+ const label = isObj(c) ? `${c.area}/${c.slug}` : JSON.stringify(c);
68
+ if (isObj(c) && protectedByPath[c.area]) {
69
+ if (isSlug(c.slug) && !seen.has(label)) {
70
+ seen.add(label);
71
+ protectedPrograms.push({
72
+ area: c.area, slug: c.slug, sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : protectedByPath[c.area].sandbox,
73
+ });
74
+ }
75
+ continue;
76
+ }
77
+ if (!isObj(c) || !byPath[c.area]) {
78
+ warnings.push(`${TAG}program ${label} ignored: unknown area`);
79
+ continue;
80
+ }
81
+ if (!isSlug(c.slug)) {
82
+ warnings.push(`${TAG}program ${label} ignored: bad slug (use a-z, 0-9, hyphens)`);
83
+ continue;
84
+ }
85
+ if (seen.has(label)) {
86
+ warnings.push(`${TAG}program ${label} ignored: duplicate`);
87
+ continue;
88
+ }
89
+ seen.add(label);
90
+ const tags = Array.isArray(c.tags) ? c.tags.filter(t => typeof t === 'string') : [];
91
+ programs.push({
92
+ ...c,
93
+ title: typeof c.title === 'string' && c.title ? c.title : c.slug,
94
+ tags,
95
+ url: `/${c.area}/${c.slug}/`,
96
+ sandbox: typeof c.sandbox === 'boolean' ? c.sandbox : byPath[c.area].sandbox,
97
+ hasIndex: !!hasIndex(c.area, c.slug),
98
+ });
99
+ }
100
+ return { areas, programs, warnings, protectedAreas, protectedPrograms };
101
+ }
102
+
103
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : Infinity);
104
+
105
+ function sortPrograms(list) {
106
+ return list.slice().sort((a, b) => {
107
+ const da = String(a.date || ''), db = String(b.date || '');
108
+ if (da !== db) return da < db ? 1 : -1;
109
+ const o = num(a.order) - num(b.order);
110
+ if (o) return o < 0 ? -1 : 1;
111
+ return String(a.title).localeCompare(String(b.title));
112
+ });
113
+ }
114
+
115
+ // Names in src/ that an area path may not reuse. A page `demos.html|md` is the
116
+ // area's list page (with or without the `demos/` folder yet), so it does not
117
+ // count; a folder holding pages of its own (a blog) does, as does any other file.
118
+ function readSrcEntries(dir) {
119
+ let ents;
120
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
121
+ const holdsPages = (name) => {
122
+ try {
123
+ return fs.readdirSync(path.join(dir, name), { withFileTypes: true })
124
+ .some(e => e.isFile() && /\.(html|md)$/.test(e.name) && e.name !== 'index.html');
125
+ } catch { return false; }
126
+ };
127
+ const out = new Set();
128
+ for (const e of ents) {
129
+ if (e.isDirectory()) { if (holdsPages(e.name)) out.add(e.name); }
130
+ else if (!/\.(html|md)$/.test(e.name)) out.add(e.name);
131
+ }
132
+ return [...out];
133
+ }
134
+
135
+ function load() {
136
+ const hasIndex = (area, slug) => fs.existsSync(path.join(srcPath, area, slug, 'index.html'));
137
+ return normalizePrograms(getPrograms(), { srcEntries: readSrcEntries(srcPath), buildOnlyPaths, hasIndex });
138
+ }
139
+
140
+ let areaPaths = [];
141
+
142
+ /** Every area whose subfolders are program folders: the valid ones and the colliding ones (R10). */
143
+ const protectedPaths = ({ areas, protectedAreas }) => [...areas, ...protectedAreas].map(a => a.path);
144
+
145
+ /** Compute the area list for this build (programsData calls it). */
146
+ export function loadProgramAreas() {
147
+ areaPaths = protectedPaths(load());
148
+ return areaPaths;
149
+ }
150
+
151
+ /** Valid area paths from the current config. */
152
+ export function programAreaPaths() {
153
+ return load().areas.map(a => a.path);
154
+ }
155
+
156
+ /**
157
+ * Is relPath (relative to src or dist, `/` separators) inside <area>/<sub>/?
158
+ * @param {string} relPath
159
+ */
160
+ export function isInProgram(relPath) {
161
+ if (!areaPaths.length || typeof relPath !== 'string') return false;
162
+ const parts = relPath.replace(/\\/g, '/').replace(/^\.?\/+/, '').split('/');
163
+ return parts.length >= 3 && areaPaths.includes(parts[0]);
164
+ }
165
+
166
+ /**
167
+ * Is filePath (as the build passes see it, e.g. `dist/demos/x/y.html`) inside a
168
+ * program folder? baseDir is the directory the path is relative to (dist, src).
169
+ * @param {string} filePath
170
+ * @param {string} baseDir
171
+ */
172
+ export function isProgramFile(filePath, baseDir) {
173
+ if (!areaPaths.length || typeof filePath !== 'string') return false;
174
+ return isInProgram(path.relative(baseDir, filePath).split(path.sep).join('/'));
175
+ }
176
+
177
+ /** Set `programs` and `programAreas` on the data store. */
178
+ export async function programsData({ data }) {
179
+ const loaded = load();
180
+ const { areas, programs, warnings } = loaded;
181
+ areaPaths = protectedPaths(loaded);
182
+ for (const w of warnings) console.log(chalk.yellow(w));
183
+ const shown = sortPrograms(programs.filter(p => p.listed === true && p.hasIndex))
184
+ .map(({ hasIndex, ...card }) => card);
185
+ data.programs = shown;
186
+ const byArea = Object.create(null);
187
+ for (const a of areas) byArea[a.path] = shown.filter(p => p.area === a.path);
188
+ data.programAreas = byArea;
189
+ }
190
+
191
+ const SANDBOX_RULE = 'Content-Security-Policy: sandbox allow-scripts allow-forms allow-popups allow-pointer-lock allow-modals';
192
+
193
+ /**
194
+ * Cloudflare Pages / Netlify `_headers` text: the site's own rules, then a
195
+ * sandbox block for each sandboxed program (listed or not), in program order.
196
+ * @param {Array<{area: string, slug: string, sandbox?: boolean}>} programs
197
+ * @param {string|null} existing - The site's own `_headers` text, if any
198
+ * @returns {string|null} null when no program is sandboxed
199
+ */
200
+ export function programHeaders(programs, existing) {
201
+ const sandboxed = (programs || []).filter(p => p.sandbox === true);
202
+ if (!sandboxed.length) return null;
203
+ const blocks = sandboxed.map(p => `/${p.area}/${p.slug}/*\n ${SANDBOX_RULE}\n`).join('\n');
204
+ return existing ? `${existing}\n${blocks}` : blocks;
205
+ }
206
+
207
+ /**
208
+ * Programs (listed and unlisted) from the current config, for `_headers`: the valid ones,
209
+ * then those in a colliding area (R10), whose sandbox rule must still be written.
210
+ */
211
+ export function allPrograms() {
212
+ const { programs, protectedPrograms } = load();
213
+ return [...programs, ...protectedPrograms];
214
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * @file theme.js
3
+ * @description Site theme setting and the per-page theme plan (pure
4
+ * functions), plus themeInject, the per-page build step that writes
5
+ * data-theme / data-mode and the theme stylesheet links.
6
+ */
7
+
8
+ import chalk from 'chalk';
9
+ import Util from '../utils/util/util.js';
10
+ import { getTheme } from '../utils/config/config.js';
11
+
12
+ const SAFE_ID = /^[a-z0-9-]+$/;
13
+ const isSafeId = (v) => typeof v === 'string' && SAFE_ID.test(v);
14
+ const has = (obj, key) => !!obj && Object.hasOwn(obj, key);
15
+ const isUrl = (v) => typeof v === 'string'
16
+ && !/[\s"'`<>\\]/.test(v)
17
+ && ((v.startsWith('/') && !v.startsWith('//')) || /^https?:\/\/[^/]/.test(v));
18
+ const TAG = '[theme] ';
19
+
20
+ /**
21
+ * Validate a raw theme setting (config/theme.json or main.js `theme`).
22
+ * @param {unknown} raw
23
+ * @returns {{ setting: object|null, warnings: string[] }}
24
+ */
25
+ export function normalizeThemeSetting(raw) {
26
+ const warnings = [];
27
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { setting: null, warnings };
28
+ if (!isSafeId(raw.name)) {
29
+ warnings.push(`${TAG}theme setting ignored: unsafe or missing name ${JSON.stringify(raw.name)}`);
30
+ return { setting: null, warnings };
31
+ }
32
+ let adjust = null;
33
+ if (raw.adjust != null) {
34
+ if (isSafeId(raw.adjust)) adjust = raw.adjust;
35
+ else warnings.push(`${TAG}theme adjust ignored: unsafe id ${JSON.stringify(raw.adjust)}`);
36
+ }
37
+ const mode = ['auto', 'light', 'dark'].includes(raw.mode) ? raw.mode : 'auto';
38
+ const files = Object.create(null);
39
+ for (const [id, url] of Object.entries(raw.files || {})) {
40
+ if (isSafeId(id) && isUrl(url)) files[id] = url;
41
+ else warnings.push(`${TAG}theme file ignored: ${JSON.stringify(id)}`);
42
+ }
43
+ const modes = Object.create(null);
44
+ for (const [id, m] of Object.entries(raw.modes || {})) {
45
+ if (isSafeId(id) && (m === 'light' || m === 'dark')) modes[id] = m;
46
+ else warnings.push(`${TAG}theme mode ignored: ${JSON.stringify(id)}`);
47
+ }
48
+ return { setting: { name: raw.name, mode, adjust, files, modes }, warnings };
49
+ }
50
+
51
+ /**
52
+ * Work out what a page gets: data-theme ids, forced scheme, stylesheet links.
53
+ * Ids always start with the theme name, including "default".
54
+ * @param {object|null} setting - Normalized setting
55
+ * @param {object} [frontMatter]
56
+ * @param {string} [pagePath] - For warnings
57
+ */
58
+ export function pageThemePlan(setting, frontMatter = {}, pagePath = '') {
59
+ if (!setting) return null;
60
+ const warnings = [];
61
+ const where = pagePath || 'page';
62
+ const fm = frontMatter || {};
63
+
64
+ const problems = [];
65
+ let pageTheme = null;
66
+ if (fm.theme != null) {
67
+ if (isSafeId(fm.theme)) pageTheme = fm.theme;
68
+ else problems.push(`theme ${JSON.stringify(fm.theme)} (use a-z, 0-9 and hyphens)`);
69
+ }
70
+ let scope = 'page';
71
+ if (fm.themeScope != null) {
72
+ if (fm.themeScope === 'page' || fm.themeScope === 'article') scope = fm.themeScope;
73
+ else problems.push(`themeScope ${JSON.stringify(fm.themeScope)} (use page or article)`);
74
+ }
75
+ if (problems.length) warnings.push(`${TAG}${where}: front matter ignored: ${problems.join('; ')}`);
76
+
77
+ const siteIds = [setting.name, ...(setting.adjust ? [setting.adjust] : [])];
78
+ const siteForced = setting.mode === 'light' || setting.mode === 'dark' ? setting.mode : null;
79
+ const forced = (id) => (has(setting.modes, id) ? setting.modes[id] : null) || siteForced;
80
+
81
+ let html;
82
+ let scoped = null;
83
+ let linkIds;
84
+ if (pageTheme && scope === 'article') {
85
+ html = { ids: siteIds, mode: forced(setting.name) };
86
+ scoped = { ids: [pageTheme], mode: forced(pageTheme) };
87
+ linkIds = [...siteIds, pageTheme];
88
+ } else if (pageTheme) {
89
+ html = { ids: [pageTheme], mode: forced(pageTheme) };
90
+ linkIds = [pageTheme];
91
+ } else {
92
+ html = { ids: siteIds, mode: forced(setting.name) };
93
+ linkIds = siteIds;
94
+ }
95
+
96
+ const links = [];
97
+ for (const id of [...new Set(linkIds)]) {
98
+ if (has(setting.files, id) && typeof setting.files[id] === 'string') links.push({ id, href: setting.files[id] });
99
+ }
100
+ return { html, scoped, links, warnings };
101
+ }
102
+
103
+
104
+ // INJECT (PER PAGE)
105
+ // -----------------------------
106
+ const VB_CSS = /vanilla-breeze[^/]*\.css/;
107
+ let cachedSetting;
108
+ let settingReady = false;
109
+
110
+ /** Forget the cached setting; called at the start of every build. */
111
+ export function resetThemeCache() {
112
+ settingReady = false;
113
+ cachedSetting = undefined;
114
+ }
115
+
116
+ function getSetting() {
117
+ if (!settingReady) {
118
+ settingReady = true;
119
+ const { setting, warnings } = normalizeThemeSetting(getTheme());
120
+ for (const w of warnings) console.log(chalk.yellow(w));
121
+ cachedSetting = setting;
122
+ }
123
+ return cachedSetting;
124
+ }
125
+
126
+ function setTheme(el, { ids, mode }) {
127
+ if (ids.length) el.setAttribute('data-theme', ids.join(' '));
128
+ if (mode) el.setAttribute('data-mode', mode);
129
+ }
130
+
131
+ /**
132
+ * Per page: theme attributes on <html> (or the article) and stylesheet links.
133
+ * Does nothing when there is no theme setting.
134
+ */
135
+ export async function themeInject({ file, allowType }) {
136
+ const setting = getSetting();
137
+ if (!setting) return;
138
+ if (!Util.isAllowedType({ file, allowType })) return;
139
+
140
+ const dom = Util.fileDom(file);
141
+ const document = dom.window.document;
142
+ const html = document.documentElement;
143
+ // Partials (no <html>) are not pages: leave them untouched
144
+ if (!html || html.tagName !== 'HTML') return;
145
+
146
+ const plan = pageThemePlan(setting, file.frontMatter, file.path);
147
+ const warnings = [...plan.warnings];
148
+ let head = document.querySelector('head');
149
+ if (!head) {
150
+ head = document.createElement('head');
151
+ html.insertBefore(head, html.firstChild);
152
+ }
153
+
154
+ let htmlTheme = plan.html;
155
+ let links = plan.links;
156
+ if (plan.scoped) {
157
+ const target = document.querySelector('article') || document.querySelector('main');
158
+ if (target) {
159
+ setTheme(target, plan.scoped);
160
+ } else {
161
+ warnings.push(`[theme] ${file.path}: no <article> or <main> for themeScope article; applied to the whole page`);
162
+ htmlTheme = plan.scoped;
163
+ links = plan.links.filter(l => plan.scoped.ids.includes(l.id));
164
+ }
165
+ }
166
+ for (const w of warnings) console.log(chalk.yellow(w));
167
+
168
+ setTheme(html, htmlTheme);
169
+ html.setAttribute('data-theme-source', 'site');
170
+
171
+ {
172
+ const sheets = [...document.querySelectorAll('link[rel~="stylesheet"]')];
173
+ const present = new Set();
174
+ for (const l of document.querySelectorAll('link')) {
175
+ if (l.hasAttribute('data-vb-theme')) present.add(`id:${l.getAttribute('data-vb-theme')}`);
176
+ }
177
+ for (const l of sheets) present.add(`href:${l.getAttribute('href')}`);
178
+ let anchor = sheets.filter(l => VB_CSS.test(l.getAttribute('href') || '')).pop() || null;
179
+ for (const { id, href } of links) {
180
+ if (present.has(`id:${id}`) || present.has(`href:${href}`)) continue;
181
+ const link = document.createElement('link');
182
+ link.setAttribute('rel', 'stylesheet');
183
+ link.setAttribute('href', href);
184
+ link.setAttribute('data-vb-theme', id);
185
+ if (anchor) anchor.after(link);
186
+ else head.appendChild(link);
187
+ anchor = link;
188
+ }
189
+ }
190
+ Util.commitDom(file, dom);
191
+ }
@@ -2,6 +2,7 @@
2
2
  // ----------------------------------
3
3
  import fs from 'node:fs';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import chalk from 'chalk';
5
6
 
6
7
  const cwd = process.cwd();
7
8
 
@@ -16,6 +17,38 @@ if (userConfigPathExists) {
16
17
  userConfig = userConfigModule.default || userConfigModule;
17
18
  }
18
19
 
20
+ // config/theme.json (written by Vanilla Press); main.js `theme` wins when defined
21
+ const themeJsonPath = `${cwd}/config/theme.json`;
22
+
23
+ /**
24
+ * The site theme setting. Re-read on every call so a long-lived process
25
+ * (`cook dev`) sees config/theme.json rewrites; main.js `theme` stays as loaded.
26
+ */
27
+ function getTheme() {
28
+ if (userConfig.theme !== undefined) return userConfig.theme;
29
+ if (!fs.existsSync(themeJsonPath)) return undefined;
30
+ try {
31
+ return JSON.parse(fs.readFileSync(themeJsonPath, 'utf8'));
32
+ } catch (err) {
33
+ console.log(chalk.yellow(`[theme] config/theme.json: ${err.message}`));
34
+ return undefined;
35
+ }
36
+ }
37
+
38
+ // config/programs.json (written by Vanilla Press): areas of hand-written programs and their cards
39
+ const programsJsonPath = `${cwd}/config/programs.json`;
40
+
41
+ /** The programs config. Re-read on every call, like getTheme. */
42
+ function getPrograms() {
43
+ if (!fs.existsSync(programsJsonPath)) return undefined;
44
+ try {
45
+ return JSON.parse(fs.readFileSync(programsJsonPath, 'utf8'));
46
+ } catch (err) {
47
+ console.log(chalk.yellow(`[programs] config/programs.json: ${err.message}`));
48
+ return undefined;
49
+ }
50
+ }
51
+
19
52
 
20
53
  // DEFINE DEFAULT CONFIG
21
54
  // -----------------------------
@@ -316,6 +349,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
316
349
  export default config;
317
350
 
318
351
  // Named exports for destructuring imports
352
+ export { getTheme, getPrograms };
319
353
  export const {
320
354
  activeLink,
321
355
  autoComponents,
@@ -8,6 +8,7 @@
8
8
  import fs from 'node:fs/promises';
9
9
  import Logger from '../logger/logger.js';
10
10
  import Util from '../util/util.js';
11
+ import { isProgramFile } from '../../plugins/programs.js';
11
12
  import { SourceFile } from '../source-file/source-file.js';
12
13
 
13
14
  // CONFIG
@@ -116,7 +117,8 @@ async function getSrcFiles() {
116
117
  const isValidPageChange = Util.validatePageChange();
117
118
  if (isValidPageChange) {
118
119
  const getDistVersionOfChangedPage = process.env.DEV_CHANGED_PAGE.replace(srcPath, distPath);
119
- files = [getDistVersionOfChangedPage];
120
+ // A file inside a program folder is only copied (copySrc), never built
121
+ files = isProgramFile(getDistVersionOfChangedPage, distPath) ? [] : [getDistVersionOfChangedPage];
120
122
  }
121
123
  // FULL BUILD
122
124
  // Otherwise, find all allowed files, loop through them, and run the build plugins on them
@@ -134,6 +136,8 @@ async function getSrcFiles() {
134
136
  files = Util.getPaths(distPath, distPath, excludedPaths);
135
137
  // Get only the allowed files by extension (.css, .html)
136
138
  files = files.filter(fileName => manualAllow(fileName, userAllowedPaths) || Util.isExtension(fileName, allowedExt));
139
+ // Program folders ship untouched
140
+ files = files.filter(fileName => !isProgramFile(fileName, distPath));
137
141
  // Move known include files to the front of the array, so they are ideally built first
138
142
  // before being replaced in other page files.
139
143
  files = files.sort((a,b) => {
@@ -164,7 +168,7 @@ async function getSrcImages(cb) {
164
168
  // Get images in `/dist`
165
169
  let images = Util.getPaths(distPath, distPath, excludedPaths);
166
170
  // Get only the allowed images by extension (.css, .html)
167
- images = images.filter(fileName => Util.isExtension(fileName, allowedExt));
171
+ images = images.filter(fileName => Util.isExtension(fileName, allowedExt) && !isProgramFile(fileName, distPath));
168
172
  // Run tasks on matched images
169
173
  if (cb) cb(images);
170
174
  }
@@ -13,6 +13,7 @@ import { promises as fs } from 'node:fs';
13
13
  import Util from '../util/util.js';
14
14
  import { distPath as defaultDistPath, siteRoot as defaultSiteRoot } from '../config/config.js';
15
15
  import { siteRootDir, fileToUrlPath } from '../site-root/site-root.js';
16
+ import { isProgramFile } from '../../plugins/programs.js';
16
17
 
17
18
  /**
18
19
  * Collect all built index pages with their source and parsed document.
@@ -25,7 +26,7 @@ export async function collectSitePages(distPathArg = defaultDistPath, siteRootAr
25
26
  const rootDir = siteRootDir(distPathArg, siteRootArg);
26
27
  const htmlFiles = Util.getPaths(rootDir, rootDir, []) || [];
27
28
  const indexFiles = htmlFiles.filter(
28
- f => f.endsWith('/index.html') || f === `${rootDir}/index.html`
29
+ f => (f.endsWith('/index.html') || f === `${rootDir}/index.html`) && !isProgramFile(f, rootDir)
29
30
  );
30
31
 
31
32
  const pages = [];
@@ -745,7 +745,8 @@ function validatePageChange() {
745
745
  // single-page fast path would copy the file into dist and leave every
746
746
  // dependent page stale. Match whole directory segments only: a PAGE
747
747
  // named template-strings-demo.html is still a fast-path page change.
748
- const isBuildOnly = changedDevPage && /\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage);
748
+ const isBuildOnly = changedDevPage && (/\/(includes?|templates?|components?|layouts?)\//.test(changedDevPage)
749
+ || /\/config\/(theme|programs)\.json$/.test(changedDevPage));
749
750
  // Return true (valid) if it was a page change AND it wasn't a build-only file
750
751
  return changedDevPage && !isBuildOnly;
751
752
  }