sitesweep 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 M Bilal Raza
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,87 @@
1
- # Temporary Holding Version
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.
1
+ # sitesweep
2
+
3
+ **Check Core Web Vitals (CWV), accessibility, SEO and errors on every page of your site at once - instead of one URL at a time.**
4
+
5
+ PageSpeed Insights and Lighthouse test one page per run. A site with 50 pages, checked on phone,
6
+ tablet and desktop, is 150 runs by hand - so most people test the homepage and hope the rest is fine.
7
+
8
+ sitesweep reads your sitemap (or a list of pages) and tests all of them in one command:
9
+
10
+ ```sh
11
+ npx sitesweep --all
12
+ ```
13
+
14
+ You get one dashboard that shows which pages have problems, what is wrong on each one, and which
15
+ problems repeat across many pages - so one fix can solve dozens of pages at once.
16
+
17
+ ![The Issues view: each problem listed once, with how many pages it affects](https://raw.githubusercontent.com/bilaldev61/sitesweep/main/docs/dashboard-issues.png)
18
+
19
+ ## What it checks on every page
20
+
21
+ - **Core Web Vitals (CWV)**: LCP, INP and CLS, plus FCP and TTFB, measured while it scrolls the page and
22
+ clicks a button you choose, as a visitor would - including *what* moved the layout and *what* slowed the click
23
+ - **Lighthouse** scores and failed checks for performance, accessibility, SEO and best practices,
24
+ under a simulated slow phone on a 4G connection
25
+ - **Browser errors** - console errors, images and scripts that failed to load, uncaught exceptions
26
+ - **Before / after** - pin a run, make your fixes, run again, and see exactly what improved or got
27
+ worse, with the normal run-to-run noise filtered out
28
+
29
+ ![The Overview: Core Web Vitals and Lighthouse scores across every page](https://raw.githubusercontent.com/bilaldev61/sitesweep/main/docs/dashboard-overview.png)
30
+
31
+ Runs on your own machine with the Chrome you already have. No browser download, no account, and
32
+ nothing is uploaded anywhere.
33
+
34
+ ## Requirements
35
+
36
+ - Node.js 22.18 or newer
37
+ - Google Chrome installed (or set `SITESWEEP_CHROME_PATH` to a Chrome or Chromium binary)
38
+
39
+ ## Quick start
40
+
41
+ ```sh
42
+ npm install --save-dev sitesweep
43
+ npx sitesweep init # four questions -> sitesweep.config.mjs
44
+ npx sitesweep --limit=3 # a first run on three pages
45
+ ```
46
+
47
+ Then open `sitesweep-results/dashboard.html`.
48
+
49
+ ## Usage
50
+
51
+ ```sh
52
+ sitesweep init # write a starter config by answering four questions
53
+ sitesweep # measure on the first device in the config (mobile by default)
54
+ sitesweep --all # every device
55
+ sitesweep --tablet --limit=3 # one device, first three pages - a quick check
56
+ sitesweep --dry-run # print the plan, measure nothing
57
+ sitesweep baseline # pin the current results as the "before" run
58
+ sitesweep dashboard # re-render the dashboard from the data on disk
59
+ sitesweep --config=other.mjs # use another config file
60
+ ```
61
+
62
+ sitesweep either measures a site that is already running (`site.origin`), or runs a command that
63
+ builds and serves it (`site.serve.preview`), measures that, and stops it afterwards.
64
+
65
+ ## Config
66
+
67
+ A config only needs what is particular to your site; everything else has a default. This one is
68
+ complete:
69
+
70
+ ```js
71
+ export default {
72
+ brand: { site: 'My Shop' },
73
+ site: { origin: 'http://localhost:8080' }, // or: { serve: { preview: 'npm run build && npm run preview' } }
74
+ pages: { source: 'sitemap', sitemap: 'http://localhost:8080/sitemap.xml' }, // or: { source: 'urls', urls: ['/', '/about'] }
75
+ journey: { click: { role: 'button', namePattern: 'menu', flags: 'i' } }, // optional; without it INP is not measured
76
+ }
77
+ ```
78
+
79
+ A sitemap can be a file or a URL, plain, gzipped, or a sitemap index (as WordPress and Shopify
80
+ publish). The other fields - devices, an API rate limit to stay under, the run-to-run noise floors the
81
+ comparison uses, and more - are commented in
82
+ [`examples/bstore.config.mjs`](examples/bstore.config.mjs) (a React storefront with a JSON API);
83
+ [`examples/brealstate.config.mjs`](examples/brealstate.config.mjs) is a Laravel site with no API.
84
+
85
+ ## Status
86
+
87
+ Early: used on two sites so far.
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import process from 'node:process'
5
+
6
+ const HELP = `sitesweep - every page, every device, Core Web Vitals and Lighthouse, one dashboard
7
+
8
+ Usage:
9
+ sitesweep init [--force]
10
+ sitesweep [run] [--mobile|--tablet|--desktop|--all] [--limit=N] [--dry-run] [--open]
11
+ sitesweep baseline [--force|--status|--backfill-live]
12
+ sitesweep dashboard
13
+
14
+ Commands:
15
+ init answer four questions, get a sitesweep.config.mjs
16
+ run measure the site (the default)
17
+ baseline pin the current results as the "before" half of the comparison
18
+ dashboard re-render dashboard.html from the data on disk
19
+
20
+ Options:
21
+ --config=<file> the config to use (default: sitesweep.config.mjs, then survey.config.mjs, in this folder)
22
+ -h, --help this text
23
+ `
24
+
25
+ const COMMANDS = new Set(['init', 'run', 'baseline', 'dashboard'])
26
+ const args = process.argv.slice(2)
27
+
28
+ if (args.includes('-h') || args.includes('--help')) {
29
+ console.log(HELP)
30
+ process.exit(0)
31
+ }
32
+
33
+ const configArg = args.find((arg) => arg.startsWith('--config='))
34
+ if (configArg) process.env.SITESWEEP_CONFIG = path.resolve(configArg.slice('--config='.length))
35
+
36
+ const command = COMMANDS.has(args[0]) ? args[0] : 'run'
37
+ if (args[0] && !args[0].startsWith('-') && !COMMANDS.has(args[0])) {
38
+ console.error(`sitesweep: unknown command "${args[0]}".\n\n${HELP}`)
39
+ process.exit(1)
40
+ }
41
+
42
+ // The command modules read their flags from process.argv, as they did when they were scripts.
43
+ const rest = args.filter((arg, index) => !(index === 0 && COMMANDS.has(arg)) && arg !== configArg)
44
+ process.argv = [process.argv[0], process.argv[1], ...rest]
45
+
46
+ // The repo runs its sources (Node strips the types); the published package ships only the compiled dist/.
47
+ const code = existsSync(new URL('../src/survey.mjs', import.meta.url)) ? '../src' : '../dist/src'
48
+
49
+ try {
50
+ if (command === 'init') await import(`${code}/init.mjs`)
51
+ else if (command === 'run') await import(`${code}/survey.mjs`)
52
+ else if (command === 'baseline') await import(`${code}/baseline.mjs`)
53
+ else {
54
+ const { rebuildDashboard } = await import(`${code}/dashboard.mjs`)
55
+ process.exitCode = rebuildDashboard()
56
+ }
57
+ } catch (error) {
58
+ console.error(error instanceof Error ? error.message : String(error))
59
+ process.exit(1)
60
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * `sitesweep baseline` - pin one survey run so the next one can be measured against it.
3
+ *
4
+ * Why this exists at all: `survey.mjs` deletes the run directory at the start of every run, so
5
+ * without a snapshot the "before" half of a before/after comparison is destroyed by
6
+ * the run that is supposed to produce the "after" half. The baseline therefore lives OUTSIDE
7
+ * `output.results`, in `output.baseline`, and nothing but this script writes it.
8
+ *
9
+ * It also does one thing a plain copy cannot. The failing accessibility / SEO / best-practice checks
10
+ * were not collected when the run being snapshotted happened - `helpers/audit.ts` only harvested the
11
+ * performance category, and this script exists partly because of that gap. The data is still there
12
+ * though: every Lighthouse report HTML embeds the whole LHR as `window.__LIGHTHOUSE_JSON__`, so the
13
+ * checks are extracted from `reports/*.html` into the snapshot's own `data/audit/*.json` under the
14
+ * `checks` field the collector now writes. The copy is edited, never the live run.
15
+ *
16
+ * A snapshot is pinned on purpose. `survey:all` compares against it and never replaces it, because a
17
+ * baseline that moves every run cannot show a regression - it just follows the numbers. Re-pin with
18
+ * `--force` once the site has actually changed and you want the new state as the reference.
19
+ *
20
+ * Flags:
21
+ * sitesweep baseline # snapshot the run -> the baseline folder
22
+ * sitesweep baseline --force # replace an existing baseline
23
+ * sitesweep baseline --status # what is in the baseline, nothing written
24
+ * sitesweep baseline --backfill-live # add the checks field to the run in place
25
+ */
26
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
27
+ import path from 'node:path';
28
+ import process from 'node:process';
29
+ import survey, { projectRoot } from './config.mjs';
30
+ const PROJECT = projectRoot;
31
+ const SOURCE = path.resolve(PROJECT, String(survey.output.results));
32
+ const TARGET = path.resolve(PROJECT, String(survey.output.baseline));
33
+ const argv = process.argv.slice(2);
34
+ const force = argv.includes('--force');
35
+ const status = argv.includes('--status');
36
+ const backfillLive = argv.includes('--backfill-live');
37
+ const fail = (message) => {
38
+ console.error(`survey-baseline: ${message}\n`);
39
+ process.exit(1);
40
+ };
41
+ /** Same rule `helpers/audit.ts` uses for performance findings, applied to the other three categories. */
42
+ const SKIPPED_MODES = survey.lab.unjudgedModes;
43
+ const CATEGORIES = survey.lab.checkCategories;
44
+ const FAIL_BELOW = Number(survey.lab.failBelow);
45
+ function describeElements(audit) {
46
+ const items = audit?.details?.items ?? [];
47
+ const nodes = items
48
+ .map((item) => item?.node?.selector ?? item?.selector ?? item?.source?.url ?? item.url)
49
+ .filter((value, index, all) => typeof value === 'string' && value.length > 0 && all.indexOf(value) === index)
50
+ .slice(0, 3)
51
+ .map((value) => (value.length > 90 ? `${value.slice(0, 87)}...` : value));
52
+ return nodes;
53
+ }
54
+ /** Pulls the embedded LHR out of a Lighthouse HTML report. Returns null when the file has none. */
55
+ function readEmbeddedReport(file) {
56
+ if (!existsSync(file))
57
+ return null;
58
+ const html = readFileSync(file, 'utf8');
59
+ const marker = 'window.__LIGHTHOUSE_JSON__ =';
60
+ const from = html.indexOf(marker);
61
+ if (from === -1)
62
+ return null;
63
+ // The assignment sits in its own script tag, so the tag's end is the value's end. Taking the last
64
+ // brace inside it rather than the last one in the file matters: the report template has several
65
+ // scripts after this one, and a brace from those makes JSON.parse throw.
66
+ const body = html.slice(from + marker.length, html.indexOf('</script>', from));
67
+ const start = body.indexOf('{');
68
+ const end = body.lastIndexOf('}');
69
+ if (start === -1 || end <= start)
70
+ return null;
71
+ try {
72
+ return JSON.parse(body.slice(start, end + 1));
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ function checksOf(lhr) {
79
+ const checks = [];
80
+ for (const category of CATEGORIES) {
81
+ for (const ref of lhr?.categories?.[category]?.auditRefs ?? []) {
82
+ const audit = lhr.audits?.[ref.id];
83
+ if (!audit || audit.score === null || audit.score >= FAIL_BELOW)
84
+ continue;
85
+ if (SKIPPED_MODES.includes(audit.scoreDisplayMode))
86
+ continue;
87
+ checks.push({
88
+ category,
89
+ id: String(audit.id ?? ref.id),
90
+ title: String(audit.title),
91
+ score: Number(audit.score),
92
+ displayValue: audit.displayValue ? String(audit.displayValue) : '',
93
+ elements: describeElements(audit),
94
+ });
95
+ }
96
+ }
97
+ return checks;
98
+ }
99
+ /**
100
+ * Writes `checks` into every audit row in `dir` that has none, reading the report HTML beside
101
+ * `reportRoot`. Returns what it could and could not do; a row with no report on disk is counted, never
102
+ * guessed at.
103
+ */
104
+ function backfillChecks(dir, reportRoot) {
105
+ if (!existsSync(dir))
106
+ return { filled: 0, present: 0, missing: 0, versions: new Set() };
107
+ let filled = 0;
108
+ let present = 0;
109
+ let missing = 0;
110
+ const versions = new Set();
111
+ for (const file of readdirSync(dir).filter((name) => name.endsWith('.json'))) {
112
+ const full = path.join(dir, file);
113
+ const row = JSON.parse(readFileSync(full, 'utf8'));
114
+ if (Array.isArray(row.checks)) {
115
+ present += 1;
116
+ continue;
117
+ }
118
+ // `reportPath` is the absolute path the run wrote, so it is the exact file to read while it still
119
+ // exists. The stem is the fallback for a row whose path was moved or renamed by hand.
120
+ const stem = String(file).replace(/\.json$/, '').replace(/__/, '-').replace(/[^a-z0-9-]+/gi, '-');
121
+ const html = row.reportPath && existsSync(row.reportPath) ? row.reportPath : path.join(reportRoot, 'reports', `${stem}.html`);
122
+ const lhr = readEmbeddedReport(html);
123
+ if (!lhr) {
124
+ missing += 1;
125
+ continue;
126
+ }
127
+ versions.add(String(lhr.lighthouseVersion ?? 'unknown'));
128
+ row.checks = checksOf(lhr);
129
+ row.checksBackfilled = 'reports/';
130
+ filled += 1;
131
+ writeFileSync(full, JSON.stringify(row, null, 2), 'utf8');
132
+ }
133
+ return { filled, present, missing, versions };
134
+ }
135
+ // --- --backfill-live: the same extraction, applied to the run on disk ----------------------------
136
+ // A run measured before the field existed still has every Lighthouse report, so the failed checks can
137
+ // be recovered without spending another forty minutes. This edits the run directory in place, which
138
+ // the snapshot deliberately never does.
139
+ if (backfillLive) {
140
+ const dir = path.join(SOURCE, 'data', 'audit');
141
+ if (!existsSync(dir))
142
+ fail(`no audit rows at ${path.relative(PROJECT, dir)} - run \`sitesweep\` first.`);
143
+ const done = backfillChecks(dir, SOURCE);
144
+ console.log(`backfill-live: ${path.relative(PROJECT, dir)}`);
145
+ console.log(` ${done.filled} rows gained a checks field, ${done.present} already had one${done.missing ? `, ${done.missing} had no report on disk` : ''}`);
146
+ if (done.filled) {
147
+ console.log(` same rule the collector now applies (score < ${FAIL_BELOW} over [${CATEGORIES.join(', ')}]), so the two are comparable`);
148
+ console.log(' next: sitesweep dashboard # re-render, no measurement');
149
+ }
150
+ process.exit(0);
151
+ }
152
+ // --- --status: read only, so it is safe to run before deciding anything -------------------------
153
+ if (status) {
154
+ const metaFile = path.join(TARGET, 'BASELINE.json');
155
+ if (!existsSync(metaFile))
156
+ fail(`no baseline yet at ${path.relative(PROJECT, TARGET)} - run \`sitesweep baseline\` to create one.`);
157
+ const meta = JSON.parse(readFileSync(metaFile, 'utf8'));
158
+ console.log(`baseline: ${path.relative(PROJECT, TARGET)}`);
159
+ console.log(` captured ${meta.capturedAt} from a run that started ${meta.source?.startedAt} (${meta.source?.durationMinutes} min)`);
160
+ console.log(` scope ${meta.rows} rows over ${meta.pages} pages on ${(meta.devices ?? []).join(' + ')}`);
161
+ console.log(` checks ${meta.checks?.rowsWithChecks ?? 0} rows carry failed a11y/bp/seo checks (${meta.checks?.source ?? 'unknown source'})`);
162
+ console.log(` size ${meta.sizeMb} MB`);
163
+ process.exit(0);
164
+ }
165
+ if (!existsSync(path.join(SOURCE, 'data', 'vitals'))) {
166
+ fail(`${path.relative(PROJECT, SOURCE)} has no survey data - run \`sitesweep\` first.`);
167
+ }
168
+ if (existsSync(TARGET) && !force) {
169
+ const meta = existsSync(path.join(TARGET, 'BASELINE.json')) ? JSON.parse(readFileSync(path.join(TARGET, 'BASELINE.json'), 'utf8')) : {};
170
+ fail(`a baseline already exists (captured ${meta.capturedAt ?? 'unknown'}, ${meta.rows ?? '?'} rows).\n` +
171
+ ' It is pinned on purpose so a comparison has something fixed to measure against.\n' +
172
+ ` Re-pin with \`sitesweep baseline -- --force\`, which replaces it with the run now in ${survey.output.results}/`);
173
+ }
174
+ // --- copy the parts a comparison needs, and only those ------------------------------------------
175
+ const run = existsSync(path.join(SOURCE, 'run.json')) ? JSON.parse(readFileSync(path.join(SOURCE, 'run.json'), 'utf8')) : {};
176
+ rmSync(TARGET, { recursive: true, force: true });
177
+ mkdirSync(TARGET, { recursive: true });
178
+ cpSync(path.join(SOURCE, 'data'), path.join(TARGET, 'data'), { recursive: true });
179
+ for (const file of ['survey-results.json', 'run.json']) {
180
+ if (existsSync(path.join(SOURCE, file)))
181
+ cpSync(path.join(SOURCE, file), path.join(TARGET, file));
182
+ }
183
+ // --- backfill the checks the collector of that run did not save ---------------------------------
184
+ const done = backfillChecks(path.join(TARGET, 'data', 'audit'), SOURCE);
185
+ const backfilled = done.filled;
186
+ const alreadyHad = done.present;
187
+ const missingReport = done.missing;
188
+ const lighthouseVersions = done.versions;
189
+ const rows = readdirSync(path.join(TARGET, 'data', 'vitals')).filter((name) => name.endsWith('.json'));
190
+ const pages = new Set(rows.map((name) => name.replace(/\.json$/, '').split('__').slice(1).join('__')));
191
+ const sizeMb = Number((readdirSync(TARGET, { recursive: true, withFileTypes: true })
192
+ .filter((entry) => entry.isFile())
193
+ .reduce((total, entry) => total + statSync(path.join(entry.parentPath ?? entry.path, entry.name)).size, 0) / 1048576).toFixed(2));
194
+ writeFileSync(path.join(TARGET, 'BASELINE.json'), JSON.stringify({
195
+ schema: survey.output.baselineSchema,
196
+ capturedAt: new Date().toISOString(),
197
+ source: { startedAt: run.startedAt ?? null, finishedAt: run.finishedAt ?? null, durationMs: run.durationMs ?? null, durationMinutes: run.durationMs ? Number((run.durationMs / 60000).toFixed(1)) : null, exitCode: run.exitCode ?? null },
198
+ devices: run.devices ?? [],
199
+ rows: rows.length,
200
+ pages: pages.size,
201
+ sizeMb,
202
+ lighthouseVersion: [...lighthouseVersions].join(', ') || 'unknown',
203
+ checks: {
204
+ rowsWithChecks: backfilled + alreadyHad,
205
+ backfilledFromReports: backfilled,
206
+ alreadyPresent: alreadyHad,
207
+ rowsWithoutAReport: missingReport,
208
+ source: backfilled ? 'extracted from reports/*.html (the embedded window.__LIGHTHOUSE_JSON__)' : 'stored by helpers/audit.ts at collection time',
209
+ rule: `score < ${FAIL_BELOW} and scoreDisplayMode not in [${SKIPPED_MODES.join(', ')}], over categories [${CATEGORIES.join(', ')}]`,
210
+ },
211
+ note: 'Pinned by `sitesweep baseline`. `sitesweep` reads it and never writes it; --force re-pins.',
212
+ }, null, 2), 'utf8');
213
+ console.log(`baseline: ${path.relative(PROJECT, TARGET)} (${sizeMb} MB, ${rows.length} rows over ${pages.size} pages)`);
214
+ console.log(` checks: ${backfilled} rows backfilled from reports/, ${alreadyHad} already carried them${missingReport ? `, ${missingReport} had no report on disk` : ''}`);
215
+ if (backfilled)
216
+ console.log(' note: the backfilled field is the same rule the collector now applies, so the two are comparable');
217
+ console.log(` next: sitesweep --all # ~45 min, and the dashboard gains a comparison against this baseline`);
@@ -0,0 +1,84 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import process from 'node:process';
12
+ import { pathToFileURL } from 'node:url';
13
+ import defaults from './defaults.mjs';
14
+ /**
15
+ * Finds and loads the site's config. Every other module imports the config from here, never by path.
16
+ *
17
+ * Looked for in this order:
18
+ * 1. `SITESWEEP_CONFIG` - a path, absolute or relative to the working directory. `--config=<file>` on
19
+ * the command line sets it, so the child processes a run spawns load the same file;
20
+ * 2. `sitesweep.config.mjs` in the working directory;
21
+ * 3. `survey.config.mjs` in the working directory - the name the tool had before it was a package.
22
+ *
23
+ * The folder the config sits in is the project root: the results, the baseline, the page list and the
24
+ * preview command are all relative to it, so a run started from anywhere writes to the same place.
25
+ */
26
+ const CANDIDATES = ['sitesweep.config.mjs', 'survey.config.mjs'];
27
+ function locate() {
28
+ const named = String(process.env.SITESWEEP_CONFIG ?? '').trim();
29
+ if (named !== '') {
30
+ const file = path.resolve(named);
31
+ if (!existsSync(file))
32
+ throw new Error(`sitesweep: the config ${file} (from --config / SITESWEEP_CONFIG) does not exist.`);
33
+ return file;
34
+ }
35
+ for (const name of CANDIDATES) {
36
+ const file = path.resolve(name);
37
+ if (existsSync(file))
38
+ return file;
39
+ }
40
+ throw new Error(`sitesweep: no config in ${process.cwd()}.\n` +
41
+ `Create sitesweep.config.mjs there (examples/ in the sitesweep repo has two), or pass --config=<file>.`);
42
+ }
43
+ /** Absolute path of the config file that was loaded. */
44
+ export const configFile = locate();
45
+ /** The folder every relative path in the config is resolved against. */
46
+ export const projectRoot = path.dirname(configFile);
47
+ // Pinned for the processes this one spawns, so a child started from another directory loads this file.
48
+ process.env.SITESWEEP_CONFIG = configFile;
49
+ const loaded = await import(__rewriteRelativeImportExtension(pathToFileURL(configFile).href));
50
+ if (!loaded.default || typeof loaded.default !== 'object') {
51
+ throw new Error(`sitesweep: ${configFile} has no default export - it should end with \`export default { ... }\`.`);
52
+ }
53
+ const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
54
+ /** Objects merge field by field; arrays and plain values replace the default. */
55
+ function merge(base, override) {
56
+ if (!isPlainObject(base) || !isPlainObject(override))
57
+ return override === undefined ? base : override;
58
+ const out = { ...base };
59
+ for (const [key, value] of Object.entries(override))
60
+ out[key] = merge(base[key], value);
61
+ return out;
62
+ }
63
+ /**
64
+ * The config: the site's file over src/defaults.mjs. Typed from the BStore example, which carries every
65
+ * field with its reasoning.
66
+ * @type {typeof import('../examples/bstore.config.mjs').default}
67
+ */
68
+ const config = merge(defaults, loaded.default);
69
+ export default config;
70
+ if (!config.site.origin && !config.site.serve?.preview) {
71
+ throw new Error(`sitesweep: ${configFile} does not say how to reach the site. Set one of:\n` +
72
+ ` site.origin a URL that is already running, e.g. 'http://localhost:8080'\n` +
73
+ ` site.serve.preview a command that builds and serves it, e.g. 'npm run build && npm run preview'`);
74
+ }
75
+ /**
76
+ * The file name to print in errors that tell someone what to edit. A config that switches between
77
+ * profiles itself (BStore's does) exports its own `configSource` naming the profile actually in use.
78
+ * @type {string}
79
+ */
80
+ export const configSource = typeof loaded.configSource === 'string' ? loaded.configSource : path.basename(configFile);
81
+ /** A path from the config, resolved against the project root. */
82
+ export function fromRoot(relative) {
83
+ return path.resolve(projectRoot, String(relative));
84
+ }