ssqch 0.10.1 → 0.11.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/bundled/completions/bash +61 -15
- package/bundled/completions/elvish +27 -12
- package/bundled/completions/fish +35 -23
- package/bundled/completions/powershell +29 -12
- package/bundled/completions/zsh +39 -19
- package/bundled/docs/agents.md +11 -0
- package/bundled/docs/comparing-builds.md +37 -5
- package/bundled/docs/configuring.md +30 -5
- package/bundled/docs/field-guide.md +1 -1
- package/bundled/docs/github-pages.md +1 -1
- package/bundled/docs/index.md +1 -1
- package/bundled/docs/known-gaps.md +1 -1
- package/bundled/docs/markdown.md +63 -5
- package/bundled/docs/multilingual.md +20 -3
- package/bundled/docs/nav.yml +1 -0
- package/bundled/docs/netlify.md +2 -2
- package/bundled/docs/plugins.md +4 -4
- package/bundled/docs/seo.md +39 -1
- package/bundled/docs/template-languages.md +6 -4
- package/bundled/docs/templates.md +3 -3
- package/bundled/docs/trailheads/from-eleventy.md +25 -13
- package/bundled/docs/trailheads/from-hugo.md +103 -0
- package/bundled/docs/trailheads/from-jekyll.md +49 -15
- package/bundled/docs/trailheads/from-mkdocs.md +54 -9
- package/bundled/docs/trailheads/from-zola.md +2 -2
- package/bundled/docs/trailheads.md +22 -5
- package/bundled/docs/where-values-come-from.md +1 -1
- package/bundled/mkdocs/404.jinja +6 -0
- package/bundled/ssqch.d.ts +71 -16
- package/lib/assets.js +10 -9
- package/lib/{chunk-MUYWL4ZX.js → chunk-2L3HR67O.js} +71 -18
- package/lib/{chunk-ERNVEZOK.js → chunk-2QTJTEBV.js} +1 -1
- package/lib/{chunk-CXRHH5P5.js → chunk-3HZZY3Y7.js} +5 -5
- package/lib/{chunk-G67W2FTJ.js → chunk-3K237XAX.js} +9 -8
- package/lib/{chunk-6RSZV5O2.js → chunk-443ZQLVX.js} +3 -3
- package/lib/{chunk-ZZBHBLDB.js → chunk-5ELAUHRL.js} +18 -16
- package/lib/{chunk-MDG5A4NI.js → chunk-A75EVUJX.js} +5 -5
- package/lib/{chunk-JFPLNHEQ.js → chunk-AIMEXBTK.js} +28 -5
- package/lib/{chunk-6OUT5VFK.js → chunk-B5E27PLU.js} +10 -39
- package/lib/{chunk-R2YGC3VE.js → chunk-CMJ7X5WW.js} +3 -2
- package/lib/{chunk-MDB3D3LP.js → chunk-ERAIEV3O.js} +2 -2
- package/lib/{chunk-DTSTCVRX.js → chunk-FCM3NYFR.js} +11 -8
- package/lib/{chunk-X7C6GFUM.js → chunk-GJNIQAIH.js} +8 -8
- package/lib/{chunk-FYRC2HBU.js → chunk-GLJQ4C76.js} +39 -18
- package/lib/{chunk-BXARVN5Z.js → chunk-GS5B3CBW.js} +1 -1
- package/lib/chunk-H5K2ZE7B.js +219 -0
- package/lib/{chunk-DNWA7WNO.js → chunk-HFSWUTXX.js} +1 -1
- package/lib/{chunk-7JGYYAKI.js → chunk-HWW5NCVJ.js} +1 -1
- package/lib/{chunk-BT3NVQOD.js → chunk-I3HYKEEW.js} +1 -1
- package/lib/{chunk-RFNLZM7W.js → chunk-IOBC665M.js} +1 -1
- package/lib/chunk-JC54PHIT.js +7992 -0
- package/lib/{chunk-3BQJY6GF.js → chunk-KCF2Z6N7.js} +1 -1
- package/lib/{chunk-HMVYNV6M.js → chunk-KZZS4W2V.js} +14 -12
- package/lib/{chunk-XR7GFL4B.js → chunk-LJOURBYT.js} +14 -12
- package/lib/chunk-OQGXZYZS.js +45 -0
- package/lib/chunk-OSBEH67S.js +6296 -0
- package/lib/{chunk-FYU22VDK.js → chunk-QJ5ZFTML.js} +14 -12
- package/lib/{chunk-LU73FTIR.js → chunk-QLUTNR37.js} +11 -10
- package/lib/{chunk-DUGGZ4EE.js → chunk-RBNPBTDP.js} +1 -1
- package/lib/{chunk-F65YUXZ7.js → chunk-RIAOXEXC.js} +10 -4
- package/lib/chunk-RVXGUMFI.js +21 -0
- package/lib/{chunk-FZGJUJAL.js → chunk-RYIWYWRQ.js} +3 -3
- package/lib/{chunk-LYPKL524.js → chunk-RZYAIX2R.js} +12 -10
- package/lib/{chunk-3NDFUMV2.js → chunk-V2FSMOFX.js} +3 -3
- package/lib/{chunk-26SHWRC6.js → chunk-X2GAVYV2.js} +524 -72
- package/lib/chunk-XS4EJSEK.js +279 -0
- package/lib/chunk-YCOTX2VM.js +37 -0
- package/lib/{chunk-P2TRR6XK.js → chunk-Z44IAMNG.js} +85 -16
- package/lib/chunk-Z5OP43HU.js +2945 -0
- package/lib/{chunk-3LODFCCH.js → chunk-ZINLHOX4.js} +2 -2
- package/lib/{chunk-HNG372DW.js → chunk-ZR3JYLFB.js} +814 -12347
- package/lib/cli.js +78 -37
- package/lib/elements.js +10 -9
- package/lib/image.js +11 -10
- package/lib/links.js +10 -9
- package/lib/minify.js +71 -12
- package/lib/redirects.js +10 -9
- package/lib/rss.js +13 -10
- package/lib/sass.js +13 -243
- package/lib/sitemap.js +18 -15
- package/lib/ssqch.js +6 -4
- package/package.json +1 -1
- package/types/index.d.ts +52 -11
- package/types/minify.d.ts +15 -3
- package/types/sass.d.ts +2 -0
- package/types/sitemap.d.ts +2 -2
- package/wasm/markdown.wasm +0 -0
- package/wasm/minify.wasm +0 -0
- package/wasm/sass.wasm +0 -0
- package/lib/chunk-II7ZRIAC.js +0 -1285
- package/lib/chunk-IOXCGMSF.js +0 -1539
- /package/lib/{chunk-JFPLNHEQ.js.LEGAL.txt → chunk-AIMEXBTK.js.LEGAL.txt} +0 -0
- /package/lib/{chunk-HNG372DW.js.LEGAL.txt → chunk-ZR3JYLFB.js.LEGAL.txt} +0 -0
|
@@ -0,0 +1,2945 @@
|
|
|
1
|
+
import { createRequire as __ssqchCreateRequire } from "node:module";
|
|
2
|
+
const require = __ssqchCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
baselineTime
|
|
5
|
+
} from "./chunk-H5K2ZE7B.js";
|
|
6
|
+
import {
|
|
7
|
+
rustRegExp
|
|
8
|
+
} from "./chunk-3GYLOC6Y.js";
|
|
9
|
+
import {
|
|
10
|
+
jinjaFilters,
|
|
11
|
+
readMkdocsYaml,
|
|
12
|
+
require_liquid_node
|
|
13
|
+
} from "./chunk-OSBEH67S.js";
|
|
14
|
+
import "./chunk-HWW5NCVJ.js";
|
|
15
|
+
import {
|
|
16
|
+
BUILTIN_FILTERS
|
|
17
|
+
} from "./chunk-GLJQ4C76.js";
|
|
18
|
+
import "./chunk-X2GAVYV2.js";
|
|
19
|
+
import "./chunk-RYIWYWRQ.js";
|
|
20
|
+
import {
|
|
21
|
+
findConfig
|
|
22
|
+
} from "./chunk-Z44IAMNG.js";
|
|
23
|
+
import "./chunk-2QTJTEBV.js";
|
|
24
|
+
import "./chunk-ERAIEV3O.js";
|
|
25
|
+
import {
|
|
26
|
+
VERSION
|
|
27
|
+
} from "./chunk-AD3HAW3W.js";
|
|
28
|
+
import "./chunk-YCOTX2VM.js";
|
|
29
|
+
import "./chunk-GS5B3CBW.js";
|
|
30
|
+
import {
|
|
31
|
+
require_nunjucks
|
|
32
|
+
} from "./chunk-JC54PHIT.js";
|
|
33
|
+
import "./chunk-HFSWUTXX.js";
|
|
34
|
+
import "./chunk-FVZ5JBRI.js";
|
|
35
|
+
import "./chunk-UU43WIZG.js";
|
|
36
|
+
import {
|
|
37
|
+
importFile
|
|
38
|
+
} from "./chunk-IOBC665M.js";
|
|
39
|
+
import "./chunk-CMUWRPSQ.js";
|
|
40
|
+
import {
|
|
41
|
+
TABLE,
|
|
42
|
+
TomlError,
|
|
43
|
+
compareText,
|
|
44
|
+
isDir,
|
|
45
|
+
isFile,
|
|
46
|
+
isPlainObject,
|
|
47
|
+
parseYaml,
|
|
48
|
+
readToml,
|
|
49
|
+
red,
|
|
50
|
+
tomlReason
|
|
51
|
+
} from "./chunk-AIMEXBTK.js";
|
|
52
|
+
import {
|
|
53
|
+
__toESM
|
|
54
|
+
} from "./chunk-I3PS26CI.js";
|
|
55
|
+
|
|
56
|
+
// src/scout.ts
|
|
57
|
+
var import_nunjucks = __toESM(require_nunjucks(), 1);
|
|
58
|
+
import { spawnSync } from "node:child_process";
|
|
59
|
+
import fs from "node:fs";
|
|
60
|
+
import { builtinModules } from "node:module";
|
|
61
|
+
import path from "node:path";
|
|
62
|
+
|
|
63
|
+
// src/json-edit.ts
|
|
64
|
+
var SPACE = /* @__PURE__ */ new Set([" ", " ", "\n", "\r"]);
|
|
65
|
+
function read(text) {
|
|
66
|
+
let i = 0;
|
|
67
|
+
const space = () => {
|
|
68
|
+
while (i < text.length && SPACE.has(text[i])) i++;
|
|
69
|
+
};
|
|
70
|
+
const string = () => {
|
|
71
|
+
const start = i++;
|
|
72
|
+
while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
|
|
73
|
+
i++;
|
|
74
|
+
return text.slice(start, i);
|
|
75
|
+
};
|
|
76
|
+
const value = () => {
|
|
77
|
+
space();
|
|
78
|
+
const start = i;
|
|
79
|
+
if (text[i] === "{") {
|
|
80
|
+
i++;
|
|
81
|
+
const members = [];
|
|
82
|
+
space();
|
|
83
|
+
if (text[i] === "}") i++;
|
|
84
|
+
else {
|
|
85
|
+
for (; ; ) {
|
|
86
|
+
space();
|
|
87
|
+
const at = i;
|
|
88
|
+
const key = JSON.parse(string());
|
|
89
|
+
space();
|
|
90
|
+
i++;
|
|
91
|
+
members.push({ start: at, key, value: value() });
|
|
92
|
+
space();
|
|
93
|
+
if (text[i++] === "}") break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { start, end: i, members };
|
|
97
|
+
}
|
|
98
|
+
if (text[i] === "[") {
|
|
99
|
+
i++;
|
|
100
|
+
space();
|
|
101
|
+
if (text[i] === "]") i++;
|
|
102
|
+
else {
|
|
103
|
+
for (; ; ) {
|
|
104
|
+
value();
|
|
105
|
+
space();
|
|
106
|
+
if (text[i++] === "]") break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { start, end: i };
|
|
110
|
+
}
|
|
111
|
+
if (text[i] === '"') {
|
|
112
|
+
string();
|
|
113
|
+
return { start, end: i };
|
|
114
|
+
}
|
|
115
|
+
while (i < text.length && !SPACE.has(text[i]) && !",]}".includes(text[i])) i++;
|
|
116
|
+
return { start, end: i };
|
|
117
|
+
};
|
|
118
|
+
return value();
|
|
119
|
+
}
|
|
120
|
+
var JsonText = class {
|
|
121
|
+
text;
|
|
122
|
+
constructor(text) {
|
|
123
|
+
this.text = text;
|
|
124
|
+
}
|
|
125
|
+
/** The value at `path`, by keys from the top (the last of two members with one key, as `JSON.parse` keeps it). */
|
|
126
|
+
find(path2) {
|
|
127
|
+
let at = read(this.text);
|
|
128
|
+
for (const key of path2) at = at?.members?.findLast((m) => m.key === key)?.value;
|
|
129
|
+
return at;
|
|
130
|
+
}
|
|
131
|
+
/** Gives the value at `path` the JSON `json`. */
|
|
132
|
+
replace(path2, json) {
|
|
133
|
+
const value = this.find(path2);
|
|
134
|
+
if (value) this.splice(value.start, value.end, json);
|
|
135
|
+
}
|
|
136
|
+
/** Takes out every member called `key` from the object at `path`, with the comma and the line break it brings. */
|
|
137
|
+
remove(path2, key) {
|
|
138
|
+
for (; ; ) {
|
|
139
|
+
const object = this.find(path2);
|
|
140
|
+
const members = object?.members;
|
|
141
|
+
const i = members?.findLastIndex((m) => m.key === key) ?? -1;
|
|
142
|
+
if (!object || !members || i === -1) return;
|
|
143
|
+
if (members.length === 1) this.splice(object.start + 1, object.end - 1, "");
|
|
144
|
+
else if (i < members.length - 1) this.splice(members[i].start, members[i + 1].start, "");
|
|
145
|
+
else this.splice(members[i - 1].value.end, members[i].value.end, "");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Puts `"key": json` in the object at `path`, before its first member whose key `before` says
|
|
150
|
+
* comes after it, or at the end. It takes the space its neighbours have between them; in an
|
|
151
|
+
* empty object, the file's line breaks and indentation, or none in a file on one line.
|
|
152
|
+
*/
|
|
153
|
+
insert(path2, key, json, before = () => false) {
|
|
154
|
+
const object = this.find(path2);
|
|
155
|
+
const members = object?.members;
|
|
156
|
+
if (!object || !members) return;
|
|
157
|
+
const member = `${JSON.stringify(key)}: ${json}`;
|
|
158
|
+
const k = members.findIndex((m) => before(m.key));
|
|
159
|
+
const spaceBefore = (j) => {
|
|
160
|
+
if (members.length === 1) {
|
|
161
|
+
const after = this.text.slice(object.start + 1, members[0].start);
|
|
162
|
+
return after.includes("\n") ? after : " ";
|
|
163
|
+
}
|
|
164
|
+
const from = this.text.indexOf(",", members[Math.max(j, 1) - 1].value.end) + 1;
|
|
165
|
+
return this.text.slice(from, members[Math.max(j, 1)].start);
|
|
166
|
+
};
|
|
167
|
+
if (members.length === 0) {
|
|
168
|
+
const newline = this.newline();
|
|
169
|
+
if (!this.text.trim().includes("\n")) return this.splice(object.start + 1, object.end - 1, member);
|
|
170
|
+
const indent = this.lineIndent(object.start);
|
|
171
|
+
this.splice(object.start + 1, object.end - 1, `${newline}${indent}${this.unit()}${member}${newline}${indent}`);
|
|
172
|
+
} else if (k === -1) {
|
|
173
|
+
const last = members[members.length - 1];
|
|
174
|
+
this.splice(last.value.end, last.value.end, `,${spaceBefore(members.length - 1)}${member}`);
|
|
175
|
+
} else {
|
|
176
|
+
this.splice(members[k].start, members[k].start, `${member},${spaceBefore(k)}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** An object for a new member, laid out as the file is: `{ "a": "1" }` on one line in a file on one line, else a member a line. */
|
|
180
|
+
object(entries, depth) {
|
|
181
|
+
if (!this.text.trim().includes("\n")) return `{${entries.map(([k, v]) => `${JSON.stringify(k)}: ${v}`).join(", ")}}`;
|
|
182
|
+
const newline = this.newline();
|
|
183
|
+
const inner = this.unit().repeat(depth + 1);
|
|
184
|
+
return `{${entries.map(([k, v]) => `${newline}${inner}${JSON.stringify(k)}: ${v}`).join(",")}${newline}${this.unit().repeat(depth)}}`;
|
|
185
|
+
}
|
|
186
|
+
splice(from, to, insert) {
|
|
187
|
+
this.text = this.text.slice(0, from) + insert + this.text.slice(to);
|
|
188
|
+
}
|
|
189
|
+
newline() {
|
|
190
|
+
return this.text.includes("\r\n") ? "\r\n" : "\n";
|
|
191
|
+
}
|
|
192
|
+
/** One level of indentation: the second line's, as npm writes it, or two spaces. */
|
|
193
|
+
unit() {
|
|
194
|
+
const second = this.text.split("\n")[1];
|
|
195
|
+
const indent = second === void 0 ? "" : /^[ \t]*/.exec(second)[0];
|
|
196
|
+
return indent === "" ? " " : indent;
|
|
197
|
+
}
|
|
198
|
+
/** The indentation of the line that `at` is on. */
|
|
199
|
+
lineIndent(at) {
|
|
200
|
+
const start = this.text.lastIndexOf("\n", at - 1) + 1;
|
|
201
|
+
return /^[ \t]*/.exec(this.text.slice(start))[0];
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// src/scout.ts
|
|
206
|
+
var ScoutError = class extends Error {
|
|
207
|
+
};
|
|
208
|
+
var fail = (message) => {
|
|
209
|
+
throw new ScoutError(message);
|
|
210
|
+
};
|
|
211
|
+
var GENERATORS = {
|
|
212
|
+
eleventy: { name: "Eleventy", build: "npx @11ty/eleventy", output: "_site" },
|
|
213
|
+
jekyll: { name: "Jekyll", build: "bundle exec jekyll build", output: "_site" },
|
|
214
|
+
zola: { name: "Zola", build: "zola build", output: "public" },
|
|
215
|
+
hugo: { name: "Hugo", build: "hugo", output: "public" },
|
|
216
|
+
mkdocs: { name: "MkDocs", build: "mkdocs build", output: "site" },
|
|
217
|
+
docusaurus: { name: "Docusaurus", build: "npx docusaurus build", output: "build" },
|
|
218
|
+
astro: { name: "Astro", build: "npx astro build", output: "dist" },
|
|
219
|
+
vitepress: { name: "VitePress", build: "npx vitepress build", output: ".vitepress/dist" },
|
|
220
|
+
hexo: { name: "Hexo", build: "npx hexo generate", output: "public" }
|
|
221
|
+
};
|
|
222
|
+
var ALIASES = { "11ty": "eleventy" };
|
|
223
|
+
function compareBuilds(dir, given) {
|
|
224
|
+
const cache = path.join(dir, ".cache/ssqch/baseline");
|
|
225
|
+
const reference = given !== "" ? given : fs.existsSync(path.join(cache, "ref-common")) ? ".cache/ssqch/baseline/ref-common" : ".cache/ssqch/baseline/ref-1";
|
|
226
|
+
const none = { reference, output: null, built: false, errors: [], same: false, summary: null, groups: [], files: { changed: [], added: [], removed: [] }, problem: null };
|
|
227
|
+
if (!isDir(path.resolve(dir, reference))) return { ...none, problem: `there's no reference build in ${reference}: \`ssqch baseline "<the old build command>"\` makes one` };
|
|
228
|
+
const run = (args) => spawnSync(process.execPath, [...process.execArgv, process.argv[1], ...args], { cwd: dir, encoding: "utf8", env: { ...process.env, TZ: "UTC", SOURCE_DATE_EPOCH: process.env.SOURCE_DATE_EPOCH ?? String(baselineTime(dir)) }, maxBuffer: 1 << 30 });
|
|
229
|
+
const built = run(["build", "--format", "json"]);
|
|
230
|
+
let build;
|
|
231
|
+
try {
|
|
232
|
+
build = JSON.parse(built.stdout);
|
|
233
|
+
} catch {
|
|
234
|
+
return { ...none, problem: `\`ssqch build\` printed no report: ${(built.stderr || built.stdout).trim().split("\n")[0]}` };
|
|
235
|
+
}
|
|
236
|
+
const errors = Array.isArray(build.errors) ? build.errors.map((e) => String(e.message).split("\n")[0]) : [];
|
|
237
|
+
const output = typeof build.output === "string" ? build.output : null;
|
|
238
|
+
if (!build.ok || output === null) return { ...none, output, errors: errors.slice(0, 10), problem: `ssqch's build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}` };
|
|
239
|
+
const compared = run(["diff", path.resolve(dir, reference), path.resolve(dir, output), "--format", "json", "--lines", "0"]);
|
|
240
|
+
let diff;
|
|
241
|
+
try {
|
|
242
|
+
diff = JSON.parse(compared.stdout);
|
|
243
|
+
} catch {
|
|
244
|
+
return { ...none, output, built: true, problem: `\`ssqch diff\` printed no report: ${(compared.stderr || compared.stdout).trim().split("\n")[0]}` };
|
|
245
|
+
}
|
|
246
|
+
const groups = Array.isArray(diff.groups) ? diff.groups.slice(0, 10).map((g) => ({ files: Number(g.files), kind: String(g.kind), first: Array.isArray(g.urls) ? String(g.urls[0]) : "", removed: (g.hunk?.removed ?? []).slice(0, 3).map(String), added: (g.hunk?.added ?? []).slice(0, 3).map(String) })) : [];
|
|
247
|
+
const paths = (list) => Array.isArray(list) ? list.slice(0, 20).map((f) => isPlainObject(f) ? String(f.path ?? f.url) : String(f)) : [];
|
|
248
|
+
return { reference, output, built: true, errors, same: diff.same === true, summary: isPlainObject(diff.summary) ? diff.summary : null, groups, files: { changed: paths(diff.changed), added: paths(diff.added), removed: paths(diff.removed) }, problem: null };
|
|
249
|
+
}
|
|
250
|
+
function detect(dir) {
|
|
251
|
+
const has = (rel) => fs.existsSync(path.join(dir, rel));
|
|
252
|
+
const text = (rel) => readUtf8(path.join(dir, rel)) ?? "";
|
|
253
|
+
const deps = (() => {
|
|
254
|
+
try {
|
|
255
|
+
const pkg = JSON.parse(text("package.json") || "{}");
|
|
256
|
+
return new Set(Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }));
|
|
257
|
+
} catch {
|
|
258
|
+
return /* @__PURE__ */ new Set();
|
|
259
|
+
}
|
|
260
|
+
})();
|
|
261
|
+
const found = [];
|
|
262
|
+
const eleventyConfig = ELEVENTY_CONFIGS.find(has);
|
|
263
|
+
if (eleventyConfig) found.push(["eleventy", eleventyConfig]);
|
|
264
|
+
else if (deps.has("@11ty/eleventy")) found.push(["eleventy", "package.json (@11ty/eleventy)"]);
|
|
265
|
+
const mkdocs2 = ["mkdocs.yml", "mkdocs.yaml"].find(has);
|
|
266
|
+
if (mkdocs2) found.push(["mkdocs", mkdocs2]);
|
|
267
|
+
const docusaurus = ["docusaurus.config.js", "docusaurus.config.ts", "docusaurus.config.mjs"].find(has);
|
|
268
|
+
if (docusaurus) found.push(["docusaurus", docusaurus]);
|
|
269
|
+
const astro = ["astro.config.mjs", "astro.config.js", "astro.config.ts", "astro.config.mts"].find(has);
|
|
270
|
+
if (astro) found.push(["astro", astro]);
|
|
271
|
+
if (has(".vitepress") || has("docs/.vitepress")) found.push(["vitepress", has(".vitepress") ? ".vitepress" : "docs/.vitepress"]);
|
|
272
|
+
const jekyllConfig = ["_config.yml", "_config.yaml", "_config.toml"].find(has);
|
|
273
|
+
if (jekyllConfig && deps.has("hexo")) found.push(["hexo", `${jekyllConfig} and package.json (hexo)`]);
|
|
274
|
+
else if (jekyllConfig) found.push(["jekyll", jekyllConfig]);
|
|
275
|
+
else if (/\b(jekyll|github-pages)\b/.test(text("Gemfile"))) found.push(["jekyll", "Gemfile"]);
|
|
276
|
+
const hugoConfig = ["hugo.toml", "hugo.yaml", "hugo.yml", "hugo.json", "config/_default/hugo.toml", "config/_default/config.toml", "config/_default/hugo.yaml"].find(has);
|
|
277
|
+
if (hugoConfig) found.push(["hugo", hugoConfig]);
|
|
278
|
+
const configToml = text("config.toml");
|
|
279
|
+
if (!hugoConfig && /^\s*baseURL\s*=/m.test(configToml)) found.push(["hugo", "config.toml (baseURL)"]);
|
|
280
|
+
else if (/^\s*base_url\s*=/m.test(configToml)) found.push(["zola", "config.toml (base_url)"]);
|
|
281
|
+
else if (has("zola.toml")) found.push(["zola", "zola.toml"]);
|
|
282
|
+
return found;
|
|
283
|
+
}
|
|
284
|
+
async function runScout(dir, options) {
|
|
285
|
+
try {
|
|
286
|
+
if (!isDir(dir)) fail(`${dir} isn't a folder`);
|
|
287
|
+
let id;
|
|
288
|
+
let how;
|
|
289
|
+
if (options.from !== void 0) {
|
|
290
|
+
id = ALIASES[options.from] ?? options.from;
|
|
291
|
+
if (!GENERATORS[id]) fail(`${options.from}: not a generator scout knows (${Object.keys(GENERATORS).join(", ")})`);
|
|
292
|
+
how = "--from";
|
|
293
|
+
} else {
|
|
294
|
+
const found = detect(dir);
|
|
295
|
+
if (found.length === 0) {
|
|
296
|
+
const ssqch = findConfig(dir) !== void 0 ? ": it has an ssqch.config.js, and nothing of another generator's, so the move may be done" : "";
|
|
297
|
+
fail(`couldn't tell which generator builds the site in ${dir}${ssqch}. Name it with --from (${Object.keys(GENERATORS).join(", ")})`);
|
|
298
|
+
}
|
|
299
|
+
if (found.length > 1) fail(`more than one generator's files are in ${dir} (${found.map(([g, file]) => `${GENERATORS[g].name}: ${file}`).join("; ")}): choose with --from`);
|
|
300
|
+
[id, how] = found[0];
|
|
301
|
+
}
|
|
302
|
+
const plan = id === "eleventy" ? eleventy(dir) : id === "jekyll" ? jekyll(dir) : id === "zola" ? zola(dir) : id === "hugo" ? hugo(dir) : id === "mkdocs" ? mkdocs(dir) : other(dir, id);
|
|
303
|
+
const report = scoutReport(plan, dir, id, how, await siteConfig(dir));
|
|
304
|
+
if (options.compare !== void 0) report.compare = compareBuilds(dir, options.compare);
|
|
305
|
+
if (options.writeDraft) {
|
|
306
|
+
for (const file of report.draft) if (!file.there) writeNew(dir, file.path, plan.newFiles.find(([p]) => p === file.path)[2]);
|
|
307
|
+
}
|
|
308
|
+
if (options.patch !== void 0) attempt(() => fs.writeFileSync(options.patch, patchOf(plan, dir)), `writing ${options.patch}`);
|
|
309
|
+
if (options.format === "json") process.stdout.write(`${JSON.stringify(scoutJson(report, options), null, 2)}
|
|
310
|
+
`);
|
|
311
|
+
else process.stdout.write(scoutText(report, options));
|
|
312
|
+
return 0;
|
|
313
|
+
} catch (e) {
|
|
314
|
+
process.stderr.write(`${red("error:")} ${e instanceof Error ? e.message : String(e)}
|
|
315
|
+
`);
|
|
316
|
+
return 1;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
async function siteConfig(dir) {
|
|
320
|
+
const file = findConfig(dir);
|
|
321
|
+
if (!file) return {};
|
|
322
|
+
try {
|
|
323
|
+
const value = (await importFile(file)).default;
|
|
324
|
+
return isPlainObject(value) ? { config: value } : { error: `${path.basename(file)}'s default export isn't an object` };
|
|
325
|
+
} catch (e) {
|
|
326
|
+
return { error: `${path.basename(file)}: ${e instanceof Error ? e.message.split("\n")[0] : String(e)}` };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function setIn(config, option) {
|
|
330
|
+
let want;
|
|
331
|
+
try {
|
|
332
|
+
want = new Function(`"use strict"; return ({ ${option} });`)();
|
|
333
|
+
} catch {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
const covers = (have, wanted) => {
|
|
337
|
+
if (isPlainObject(wanted)) return isPlainObject(have) && Object.entries(wanted).every(([k, v]) => covers(have[k], v));
|
|
338
|
+
if (Array.isArray(wanted) || typeof wanted === "function") return false;
|
|
339
|
+
return Object.is(have, wanted);
|
|
340
|
+
};
|
|
341
|
+
return isPlainObject(want) && Object.keys(want).length > 0 && covers(config, want);
|
|
342
|
+
}
|
|
343
|
+
function scoutReport(plan, dir, id, how, site = {}) {
|
|
344
|
+
const g = GENERATORS[id];
|
|
345
|
+
const { command, output, needs } = referenceBuild(dir, id);
|
|
346
|
+
const baseline = `ssqch baseline ${JSON.stringify(command)}${output === "_site" ? "" : ` --from ${output}`}`;
|
|
347
|
+
const edits = [];
|
|
348
|
+
const renamed = new Map(plan.renames);
|
|
349
|
+
for (const [file, changes] of plan.edits) edits.push({ path: file, ...renamed.has(file) ? { to: renamed.get(file) } : {}, changes });
|
|
350
|
+
for (const [from, to] of plan.renames) if (!plan.edits.some(([file]) => file === from)) edits.push({ path: from, to, changes: ["renamed"] });
|
|
351
|
+
const all = plan.byHand.map(([at, what, meta], order) => ({
|
|
352
|
+
at,
|
|
353
|
+
what,
|
|
354
|
+
code: meta?.code ?? `${id}-other`,
|
|
355
|
+
status: meta?.status ?? statusOf(what),
|
|
356
|
+
count: meta?.count ?? null,
|
|
357
|
+
files: meta?.files ?? null,
|
|
358
|
+
option: meta?.option ?? null,
|
|
359
|
+
docs: meta?.docs ?? null,
|
|
360
|
+
order
|
|
361
|
+
})).sort((a, b) => (b.files ?? -1) - (a.files ?? -1) || a.order - b.order).map(({ order: _, ...t }) => t);
|
|
362
|
+
const done = [];
|
|
363
|
+
const todo = all.filter((t) => {
|
|
364
|
+
if (t.status !== "option" || !t.option || !site.config || !setIn(site.config, t.option)) return true;
|
|
365
|
+
done.push({ at: t.at, what: t.what, code: t.code, option: t.option });
|
|
366
|
+
return false;
|
|
367
|
+
});
|
|
368
|
+
return {
|
|
369
|
+
dir,
|
|
370
|
+
generator: id,
|
|
371
|
+
name: g.name,
|
|
372
|
+
detectedBy: how,
|
|
373
|
+
build: { command, output, baseline, needs },
|
|
374
|
+
todo,
|
|
375
|
+
summary: { pages: plan.pages ?? null, ssqch: todo.filter((t) => t.status === "ssqch").length, option: todo.filter((t) => t.status === "option").length, notYet: todo.filter((t) => t.status === "not-yet").length, site: todo.filter((t) => t.status === "site").length, done: done.length },
|
|
376
|
+
draft: plan.newFiles.map(([file, from]) => ({ path: file, from, there: fs.existsSync(path.join(dir, file)) || file === "ssqch.config.js" && findConfig(dir) !== void 0 })),
|
|
377
|
+
edits,
|
|
378
|
+
underWay: findConfig(dir) !== void 0,
|
|
379
|
+
done,
|
|
380
|
+
configError: site.error ?? null
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function statusOf(what) {
|
|
384
|
+
if (/not in ssqch yet|don't run in ssqch|doesn't run|aren't supported|isn't supported/.test(what)) return "not-yet";
|
|
385
|
+
if (/\(in the draft\)|, in the draft/.test(what)) return "option";
|
|
386
|
+
if (/\bport\b|by hand|rewrite it|the site's own/i.test(what)) return "site";
|
|
387
|
+
return "ssqch";
|
|
388
|
+
}
|
|
389
|
+
function referenceBuild(dir, id) {
|
|
390
|
+
const g = GENERATORS[id];
|
|
391
|
+
let command = g.build;
|
|
392
|
+
let output = g.output;
|
|
393
|
+
const needs = [];
|
|
394
|
+
const netlify = readUtf8(path.join(dir, "netlify.toml")) ?? "";
|
|
395
|
+
const netlifyCommand = /^\s*command\s*=\s*"([^"]+)"/m.exec(netlify)?.[1];
|
|
396
|
+
const netlifyPublish = /^\s*publish\s*=\s*"([^"]+)"/m.exec(netlify)?.[1];
|
|
397
|
+
let scripts = {};
|
|
398
|
+
try {
|
|
399
|
+
scripts = JSON.parse(readUtf8(path.join(dir, "package.json")) ?? "{}").scripts ?? {};
|
|
400
|
+
} catch {
|
|
401
|
+
}
|
|
402
|
+
const words = { eleventy: /\beleventy\b/, jekyll: /\bjekyll\b/, hugo: /\bhugo\b/, zola: /\bzola\b/, mkdocs: /\bmkdocs\b/, docusaurus: /\bdocusaurus\b/, astro: /\bastro\b/, vitepress: /\bvitepress\b/, hexo: /\bhexo\b/ };
|
|
403
|
+
if (netlifyCommand && words[id].test(netlifyCommand)) command = netlifyCommand;
|
|
404
|
+
else if (typeof scripts.build === "string" && words[id].test(scripts.build)) command = "npm run build";
|
|
405
|
+
if (netlifyPublish && command === netlifyCommand) output = netlifyPublish.replace(/^\.\//, "").replace(/\/$/, "");
|
|
406
|
+
if (id === "mkdocs") {
|
|
407
|
+
const requirements = ["requirements.txt", "requirements-docs.txt", "docs/requirements.txt", "requirements/docs.txt"].filter((f) => isFile(path.join(dir, f)));
|
|
408
|
+
const venv = [".venv", "venv"].find((v) => isFile(path.join(dir, v, "bin", "mkdocs")) || isFile(path.join(dir, v, "Scripts", "mkdocs.exe")));
|
|
409
|
+
if (venv && command === g.build) command = `${venv}/bin/mkdocs build`;
|
|
410
|
+
const pyproject = readUtf8(path.join(dir, "pyproject.toml"));
|
|
411
|
+
const imports = /\b(?:mkautodoc|mkdocstrings)\b/.test(readUtf8(path.join(dir, "mkdocs.yml")) ?? readUtf8(path.join(dir, "mkdocs.yaml")) ?? "");
|
|
412
|
+
needs.push(`Python with MkDocs and the site's packages, in a virtual environment: ${requirements.length ? `\`pip install -r ${requirements[0]}\`` : pyproject ? "the packages pyproject.toml lists" : "`pip install mkdocs` and the theme and plugins mkdocs.yml names"}${imports && pyproject ? ", and `pip install -e .`: the API pages import the package itself" : ""}${venv ? ` (${venv} is there, so the command runs its mkdocs)` : '; then give baseline that environment\'s mkdocs (`ssqch baseline ".venv/bin/mkdocs build" --from site`)'}`);
|
|
413
|
+
}
|
|
414
|
+
if (id === "jekyll") {
|
|
415
|
+
const gemfile = readUtf8(path.join(dir, "Gemfile")) ?? "";
|
|
416
|
+
if (/\bgithub-pages\b/.test(gemfile)) {
|
|
417
|
+
const remote = spawnSync("git", ["remote", "get-url", "origin"], { cwd: dir, encoding: "utf8" }).stdout?.trim() ?? "";
|
|
418
|
+
const nwo = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(remote)?.[1];
|
|
419
|
+
needs.push(`PAGES_REPO_NWO=${nwo ?? "<owner>/<repo>"} in the environment: the github-pages gem reads the repository's name from GitHub, and without it writes placeholder github.com/pages/ URLs on every page`);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (/\btailwindcss\b/.test(readUtf8(path.join(dir, "package.json")) ?? "") && !["eleventy", "astro", "docusaurus", "vitepress"].includes(id)) needs.push("Node and `npm install` first: the site builds its CSS with Tailwind");
|
|
423
|
+
return { command, output, needs };
|
|
424
|
+
}
|
|
425
|
+
function scoutText(report, options) {
|
|
426
|
+
let out = `Scouting the ${report.name} site in ${report.dir} (found ${report.detectedBy === "--from" ? "with --from" : report.detectedBy})${report.underWay ? ": a move under way, with an ssqch.config.js" : ""}
|
|
427
|
+
`;
|
|
428
|
+
const { summary } = report;
|
|
429
|
+
if (report.todo.length) out += `
|
|
430
|
+
${report.todo.length} to do${summary.pages !== null ? ` across ${summary.pages} ${summary.pages === 1 ? "page" : "pages"}` : ""}: ${[[summary.ssqch, "ssqch does"], [summary.option, "an option does (the draft turns it on)"], [summary.notYet, "not in ssqch yet"], [summary.site, "the site's own code to port"]].filter(([n]) => n).map(([n, what]) => `${n} ${what}`).join(", ")}.
|
|
431
|
+
`;
|
|
432
|
+
if (report.done.length) out += `${report.todo.length ? "" : "\n"}${report.done.length} done already: ssqch.config.js sets ${report.done.map((d) => `\`${d.option}\``).filter((o, i, all) => all.indexOf(o) === i).join(", ")}.
|
|
433
|
+
`;
|
|
434
|
+
if (report.configError) out += `
|
|
435
|
+
Couldn't read the site's config, so nothing counts as done yet: ${report.configError}
|
|
436
|
+
`;
|
|
437
|
+
out += `
|
|
438
|
+
Reference build
|
|
439
|
+
${report.build.baseline}
|
|
440
|
+
`;
|
|
441
|
+
for (const need of report.build.needs) out += ` needs ${need}
|
|
442
|
+
`;
|
|
443
|
+
if (report.todo.length) {
|
|
444
|
+
out += `
|
|
445
|
+
To do (${report.todo.length})
|
|
446
|
+
`;
|
|
447
|
+
const mark = { ssqch: "", option: "[option] ", "not-yet": "[not yet] ", site: "[port] " };
|
|
448
|
+
for (const { at, what, status } of report.todo) out += ` ${mark[status]}${at}: ${what}
|
|
449
|
+
`;
|
|
450
|
+
}
|
|
451
|
+
const left = report.draft.filter((f) => !f.there);
|
|
452
|
+
if (report.draft.length) {
|
|
453
|
+
out += `
|
|
454
|
+
Draft (${left.length} to write${left.length < report.draft.length ? `, ${report.draft.length - left.length} there already` : ""})${options.writeDraft ? "" : ": --write-draft writes them, and never overwrites a file"}
|
|
455
|
+
`;
|
|
456
|
+
for (const f of report.draft) out += ` ${f.path} (${f.from})${f.there ? " [there already]" : ""}
|
|
457
|
+
`;
|
|
458
|
+
}
|
|
459
|
+
if (report.edits.length) {
|
|
460
|
+
out += `
|
|
461
|
+
Edits (${report.edits.length})${options.patch !== void 0 ? "" : ": --patch <file> writes them as a patch to review, and changes nothing"}
|
|
462
|
+
`;
|
|
463
|
+
for (const e of report.edits) out += ` ${e.path}${e.to ? ` -> ${e.to}` : ""}${e.changes.length && e.changes[0] !== "renamed" ? `: ${e.changes.join(", ")}` : ""}
|
|
464
|
+
`;
|
|
465
|
+
}
|
|
466
|
+
if (!report.todo.length && !left.length && !report.edits.length) out += "\nNothing left to do that scout can see.\n";
|
|
467
|
+
const c = report.compare;
|
|
468
|
+
if (c) {
|
|
469
|
+
out += `
|
|
470
|
+
Compared with ${c.reference}
|
|
471
|
+
`;
|
|
472
|
+
if (c.problem) out += ` ${c.problem}
|
|
473
|
+
${c.errors.map((e) => ` error: ${e}
|
|
474
|
+
`).join("")}`;
|
|
475
|
+
else if (c.same) out += " No differences: ssqch's build is the same as the reference.\n";
|
|
476
|
+
else if (c.summary) {
|
|
477
|
+
out += ` ${c.summary.changed} changed, ${c.summary.added} only in ssqch's, ${c.summary.removed} only in the reference; ${c.summary.unchangedPages} pages and ${c.summary.unchangedFiles} other files the same
|
|
478
|
+
`;
|
|
479
|
+
for (const g of c.groups) out += ` ${g.files} ${g.files === 1 ? "file" : "files"}, ${g.kind} (first ${g.first}): ${[...g.removed.map((l) => `-${l.trim()}`), ...g.added.map((l) => `+${l.trim()}`)].join(" ").slice(0, 160)}
|
|
480
|
+
`;
|
|
481
|
+
if (c.groups.length) out += ` The whole list: \`ssqch diff ${c.reference} ${c.output}\`
|
|
482
|
+
`;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (options.writeDraft) out += `
|
|
486
|
+
Wrote ${left.length} draft ${left.length === 1 ? "file" : "files"}.
|
|
487
|
+
`;
|
|
488
|
+
if (options.patch !== void 0) out += `
|
|
489
|
+
Wrote ${report.edits.length} ${report.edits.length === 1 ? "edit" : "edits"} to ${options.patch}: read it, then \`git apply ${options.patch}\`${report.dir === "." ? "" : ` in ${report.dir}`}.
|
|
490
|
+
`;
|
|
491
|
+
if (c && !c.problem) out += c.same ? '\nNext: the move matches. Then ssqch\'s own features, one at a time, with a compare after each: `ssqch docs "moving a site with an agent"`.\n' : `
|
|
492
|
+
Next: fix the biggest group above (one cause is often hundreds of files), then \`ssqch scout --compare\` again.
|
|
493
|
+
`;
|
|
494
|
+
else out += `
|
|
495
|
+
Next: \`${report.build.baseline}\` builds the site with ${report.name} to compare with${report.edits.length ? " (before the patch, or with --commit)" : ""}; then \`ssqch build\` and \`ssqch diff .cache/ssqch/baseline/ref-1 <ssqch's output>\`, the biggest group first. \`ssqch docs --from ${report.generator}\` has ${report.name}'s words and trailhead, and \`ssqch docs "moving a site with an agent"\` the whole loop. Run scout again to see what's left.
|
|
496
|
+
`;
|
|
497
|
+
return out;
|
|
498
|
+
}
|
|
499
|
+
function scoutJson(report, options) {
|
|
500
|
+
return {
|
|
501
|
+
generator: report.generator,
|
|
502
|
+
name: report.name,
|
|
503
|
+
detectedBy: report.detectedBy,
|
|
504
|
+
underWay: report.underWay,
|
|
505
|
+
configError: report.configError,
|
|
506
|
+
build: report.build,
|
|
507
|
+
summary: report.summary,
|
|
508
|
+
todo: report.todo,
|
|
509
|
+
done: report.done,
|
|
510
|
+
draft: report.draft,
|
|
511
|
+
edits: report.edits,
|
|
512
|
+
wroteDraft: options.writeDraft ? report.draft.filter((f) => !f.there).map((f) => f.path) : [],
|
|
513
|
+
patch: options.patch ?? null,
|
|
514
|
+
trailhead: `ssqch docs --from ${report.generator}`,
|
|
515
|
+
...report.compare ? { compare: report.compare } : {}
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function writeNew(dir, file, contents) {
|
|
519
|
+
const to = path.join(dir, file);
|
|
520
|
+
if (fs.existsSync(to)) return;
|
|
521
|
+
attempt(() => {
|
|
522
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
523
|
+
fs.writeFileSync(to, contents, { flag: "wx" });
|
|
524
|
+
}, `writing ${file}`);
|
|
525
|
+
}
|
|
526
|
+
function patchOf(plan, dir) {
|
|
527
|
+
const prefix = spawnSync("git", ["rev-parse", "--show-prefix"], { cwd: dir, encoding: "utf8" }).stdout?.trim() ?? "";
|
|
528
|
+
const at = (rel) => `${prefix}${rel}`.replace(/\\/g, "/");
|
|
529
|
+
const renamed = new Map(plan.renames);
|
|
530
|
+
const files = /* @__PURE__ */ new Set([...plan.edits.map(([f]) => f), ...plan.renames.map(([f]) => f)]);
|
|
531
|
+
let out = "";
|
|
532
|
+
for (const file of [...files].sort(compareText)) {
|
|
533
|
+
const to = renamed.get(file) ?? file;
|
|
534
|
+
const before = readUtf8(path.join(dir, file)) ?? "";
|
|
535
|
+
const after = plan.edits.find(([f]) => f === file)?.[2] ?? before;
|
|
536
|
+
out += `diff --git a/${at(file)} b/${at(to)}
|
|
537
|
+
`;
|
|
538
|
+
if (to !== file) out += `rename from ${at(file)}
|
|
539
|
+
rename to ${at(to)}
|
|
540
|
+
`;
|
|
541
|
+
if (before !== after) out += `--- a/${at(file)}
|
|
542
|
+
+++ b/${at(to)}
|
|
543
|
+
${unifiedHunks(before, after)}`;
|
|
544
|
+
}
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
function unifiedHunks(before, after) {
|
|
548
|
+
const split = (t) => t === "" ? [] : t.split(/(?<=\n)/);
|
|
549
|
+
const a = split(before);
|
|
550
|
+
const b = split(after);
|
|
551
|
+
const ops = lineOps(a, b);
|
|
552
|
+
const CONTEXT = 3;
|
|
553
|
+
let out = "";
|
|
554
|
+
let i = 0;
|
|
555
|
+
while (i < ops.length) {
|
|
556
|
+
if (ops[i].kind === " ") {
|
|
557
|
+
i++;
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
let start = Math.max(0, i - CONTEXT);
|
|
561
|
+
let end = i;
|
|
562
|
+
for (; ; ) {
|
|
563
|
+
while (end < ops.length && ops[end].kind !== " ") end++;
|
|
564
|
+
let next = end;
|
|
565
|
+
while (next < ops.length && ops[next].kind === " ") next++;
|
|
566
|
+
if (next < ops.length && next - end <= CONTEXT * 2) {
|
|
567
|
+
end = next;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
end = Math.min(ops.length, end + CONTEXT);
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
const slice = ops.slice(start, end);
|
|
574
|
+
const aStart = ops[start].a;
|
|
575
|
+
const bStart = ops[start].b;
|
|
576
|
+
const aCount = slice.filter((o) => o.kind !== "+").length;
|
|
577
|
+
const bCount = slice.filter((o) => o.kind !== "-").length;
|
|
578
|
+
out += `@@ -${aCount ? aStart + 1 : aStart},${aCount} +${bCount ? bStart + 1 : bStart},${bCount} @@
|
|
579
|
+
`;
|
|
580
|
+
for (const o of slice) {
|
|
581
|
+
const line = o.kind === "+" ? b[o.b] : a[o.a];
|
|
582
|
+
out += `${o.kind}${line}${line.endsWith("\n") ? "" : "\n\\n"}`;
|
|
583
|
+
}
|
|
584
|
+
i = end;
|
|
585
|
+
start = end;
|
|
586
|
+
}
|
|
587
|
+
return out;
|
|
588
|
+
}
|
|
589
|
+
function lineOps(a, b) {
|
|
590
|
+
const n = a.length;
|
|
591
|
+
const m = b.length;
|
|
592
|
+
const max = n + m;
|
|
593
|
+
const v = /* @__PURE__ */ new Map([[1, 0]]);
|
|
594
|
+
const trace = [];
|
|
595
|
+
outer: for (let d = 0; d <= max; d++) {
|
|
596
|
+
trace.push(new Map(v));
|
|
597
|
+
for (let k = -d; k <= d; k += 2) {
|
|
598
|
+
let x2 = k === -d || k !== d && (v.get(k - 1) ?? -1) < (v.get(k + 1) ?? -1) ? v.get(k + 1) : v.get(k - 1) + 1;
|
|
599
|
+
let y2 = x2 - k;
|
|
600
|
+
while (x2 < n && y2 < m && a[x2] === b[y2]) {
|
|
601
|
+
x2++;
|
|
602
|
+
y2++;
|
|
603
|
+
}
|
|
604
|
+
v.set(k, x2);
|
|
605
|
+
if (x2 >= n && y2 >= m) break outer;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const ops = [];
|
|
609
|
+
let x = n;
|
|
610
|
+
let y = m;
|
|
611
|
+
for (let d = trace.length - 1; d >= 0; d--) {
|
|
612
|
+
const vd = trace[d];
|
|
613
|
+
const k = x - y;
|
|
614
|
+
const prevK = k === -d || k !== d && (vd.get(k - 1) ?? -1) < (vd.get(k + 1) ?? -1) ? k + 1 : k - 1;
|
|
615
|
+
const prevX = vd.get(prevK) ?? 0;
|
|
616
|
+
const prevY = prevX - prevK;
|
|
617
|
+
while (x > prevX && y > prevY) {
|
|
618
|
+
x--;
|
|
619
|
+
y--;
|
|
620
|
+
ops.push({ kind: " ", a: x, b: y });
|
|
621
|
+
}
|
|
622
|
+
if (d > 0) {
|
|
623
|
+
if (x === prevX) {
|
|
624
|
+
y--;
|
|
625
|
+
ops.push({ kind: "+", a: x, b: y });
|
|
626
|
+
} else {
|
|
627
|
+
x--;
|
|
628
|
+
ops.push({ kind: "-", a: x, b: y });
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return ops.reverse();
|
|
633
|
+
}
|
|
634
|
+
function reason(e) {
|
|
635
|
+
const err = e;
|
|
636
|
+
const words = { ENOENT: "No such file or directory", EACCES: "Permission denied", EPERM: "Operation not permitted", EISDIR: "Is a directory", ENOTDIR: "Not a directory", EEXIST: "File exists", ENOTEMPTY: "Directory not empty", EROFS: "Read-only file system", ENOSPC: "No space left on device" };
|
|
637
|
+
if (process.platform !== "win32" && typeof err?.code === "string" && typeof err.errno === "number" && words[err.code]) return `${words[err.code]} (os error ${Math.abs(err.errno)})`;
|
|
638
|
+
return e instanceof Error ? e.message : String(e);
|
|
639
|
+
}
|
|
640
|
+
function attempt(step, what) {
|
|
641
|
+
try {
|
|
642
|
+
step();
|
|
643
|
+
} catch (e) {
|
|
644
|
+
fail(`${what}: ${reason(e)}`);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
var utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
648
|
+
function readUtf8(file) {
|
|
649
|
+
try {
|
|
650
|
+
return utf8.decode(fs.readFileSync(file));
|
|
651
|
+
} catch {
|
|
652
|
+
return void 0;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function readStrict(file, what) {
|
|
656
|
+
let bytes;
|
|
657
|
+
try {
|
|
658
|
+
bytes = fs.readFileSync(file);
|
|
659
|
+
} catch (e) {
|
|
660
|
+
return fail(`${what ? `${what}: ` : ""}${reason(e)}`);
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
return utf8.decode(bytes);
|
|
664
|
+
} catch {
|
|
665
|
+
return fail(`${what ? `${what}: ` : ""}stream did not contain valid UTF-8`);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
function extensionOf(name) {
|
|
669
|
+
const dot = name.lastIndexOf(".");
|
|
670
|
+
return dot <= 0 ? "" : name.slice(dot + 1);
|
|
671
|
+
}
|
|
672
|
+
var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
673
|
+
function lines(text) {
|
|
674
|
+
const parts = text.split("\n");
|
|
675
|
+
const last = parts.pop();
|
|
676
|
+
const out = parts.map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
677
|
+
if (last !== "") out.push(last);
|
|
678
|
+
return out;
|
|
679
|
+
}
|
|
680
|
+
function trimMatches(s, chars) {
|
|
681
|
+
let start = 0, end = s.length;
|
|
682
|
+
while (start < end && chars.includes(s[start])) start++;
|
|
683
|
+
while (end > start && chars.includes(s[end - 1])) end--;
|
|
684
|
+
return s.slice(start, end);
|
|
685
|
+
}
|
|
686
|
+
var trim = (s) => s.replace(new RegExp("^\\p{White_Space}+|\\p{White_Space}+$", "gu"), "");
|
|
687
|
+
var trimStart = (s) => s.replace(new RegExp("^\\p{White_Space}+", "u"), "");
|
|
688
|
+
var splitWhitespace = (s) => s.split(new RegExp("\\p{White_Space}+", "u")).filter((w) => w !== "");
|
|
689
|
+
var indentOf = (line) => line.slice(0, line.length - trimStart(line).length);
|
|
690
|
+
var occurrences = (text, word) => text.split(word).length - 1;
|
|
691
|
+
var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\#&~-]/g, "\\$&");
|
|
692
|
+
var IDENTIFIER = /^[\p{Alphabetic}\p{N}_$]+$/u;
|
|
693
|
+
function walk(root, skip, strict) {
|
|
694
|
+
const out = [];
|
|
695
|
+
if (isFile(root)) return [{ rel: "", abs: root, name: path.basename(root), isFile: true }];
|
|
696
|
+
const visit = (abs, rel) => {
|
|
697
|
+
let dirents;
|
|
698
|
+
try {
|
|
699
|
+
dirents = fs.readdirSync(abs, { withFileTypes: true });
|
|
700
|
+
} catch (e) {
|
|
701
|
+
if (strict) fail(`IO error for operation on ${abs}: ${reason(e)}: ${reason(e)}`);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
dirents.sort((a, b) => compareText(a.name, b.name));
|
|
705
|
+
for (const d of dirents) {
|
|
706
|
+
const childRel = rel === "" ? d.name : `${rel}/${d.name}`;
|
|
707
|
+
if (skip(d.name, childRel)) continue;
|
|
708
|
+
const childAbs = abs.endsWith(path.sep) ? abs + d.name : abs + path.sep + d.name;
|
|
709
|
+
out.push({ rel: childRel, abs: childAbs, name: d.name, isFile: d.isFile() });
|
|
710
|
+
if (d.isDirectory()) visit(childAbs, childRel);
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
visit(root, "");
|
|
714
|
+
return out;
|
|
715
|
+
}
|
|
716
|
+
function components(p) {
|
|
717
|
+
const parts = p.split(process.platform === "win32" ? /[\\/]/ : "/");
|
|
718
|
+
const out = parts.filter((part, i) => part !== "" && !(part === "." && i > 0));
|
|
719
|
+
return p.startsWith("/") ? ["/", ...out] : out;
|
|
720
|
+
}
|
|
721
|
+
var samePath = (a, b) => components(a).join("\0") === components(b).join("\0");
|
|
722
|
+
var ELEVENTY_CONFIGS = [".eleventy.js", "eleventy.config.js", "eleventy.config.mjs", "eleventy.config.cjs"];
|
|
723
|
+
var TEMPLATE_EXTENSIONS = ["md", "markdown", "njk", "liquid", "html", "hbs", "handlebars", "mustache", "edge", "ejs"];
|
|
724
|
+
var NAVIGATION_FILTER = rustRegExp(String.raw`\|\s*eleventyNavigation(?:Breadcrumb|ToHtml|ToMarkdown)?\b|\beleventyNavigation(?:Breadcrumb|ToHtml|ToMarkdown)?\s*\(`);
|
|
725
|
+
var DATA_FILE = rustRegExp(String.raw`\.11tydata\.(js|cjs|mjs|json|ya?ml|toml)$`);
|
|
726
|
+
var IMAGE_ATTR = rustRegExp(String.raw`\beleventy:(widths|ignore)\b`, "g");
|
|
727
|
+
var TEMPLATE_GLOBAL = rustRegExp(String.raw`\beleventy\.(generator|version)\b`, "g");
|
|
728
|
+
var CALL = rustRegExp(String.raw`\.\s*(addFilter|addAsyncFilter|addNunjucksFilter|addLiquidFilter|addNunjucksAsyncFilter|addShortcode|addAsyncShortcode|addNunjucksShortcode|addNunjucksAsyncShortcode|addLiquidShortcode|addPairedShortcode|addPairedAsyncShortcode|addPairedNunjucksShortcode|addPairedNunjucksAsyncShortcode|addPairedLiquidShortcode|addNunjucksTag|addLiquidTag|addNunjucksGlobal|addMarkdownHighlighter|addCollection|addTransform|addGlobalData|addPlugin|addPassthroughCopy|addWatchTarget|setLibrary|addDataExtension|addTemplateFormats|setTemplateFormats|addLayoutAlias|on)\s*\(\s*(?:["'\x60]([^"'\x60]*)["'\x60]|([A-Za-z_$][\w$.]*))?`, "g");
|
|
729
|
+
var SETTING = rustRegExp(String.raw`\b(input|output|includes|layouts|data|markdownTemplateEngine|htmlTemplateEngine|pathPrefix)\s*:\s*["'\x60]([^"'\x60]*)["'\x60]`, "g");
|
|
730
|
+
var FORMATS = rustRegExp(String.raw`templateFormats\s*:\s*\[([^\]]*)\]`);
|
|
731
|
+
var REQUIRE = rustRegExp(String.raw`(?:require\(\s*|from\s+)["'](@11ty/[\w./-]+|markdown-it[\w-]*|eleventy-[\w-]+|@[\w-]+/eleventy-[\w-]+)["']`, "g");
|
|
732
|
+
var setting = (code, key) => [...code.matchAll(SETTING)].find((c) => c[1] === key)?.[2];
|
|
733
|
+
function blankComments(js) {
|
|
734
|
+
const out = js.split("");
|
|
735
|
+
const blank = (from, to) => {
|
|
736
|
+
for (let k = from; k < to; k++) if (out[k] !== "\n") out[k] = " ";
|
|
737
|
+
};
|
|
738
|
+
let i = 0;
|
|
739
|
+
while (i < js.length) {
|
|
740
|
+
const c = js[i];
|
|
741
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
742
|
+
i++;
|
|
743
|
+
while (i < js.length && js[i] !== c && (c === "`" || js[i] !== "\n")) i += js[i] === "\\" ? 2 : 1;
|
|
744
|
+
i++;
|
|
745
|
+
} else if (c === "/" && js[i + 1] === "/") {
|
|
746
|
+
const at = js.indexOf("\n", i);
|
|
747
|
+
const end = at === -1 ? js.length : at;
|
|
748
|
+
blank(i, end);
|
|
749
|
+
i = end;
|
|
750
|
+
} else if (c === "/" && js[i + 1] === "*") {
|
|
751
|
+
const at = js.indexOf("*/", i + 2);
|
|
752
|
+
const end = at === -1 ? js.length : at + 2;
|
|
753
|
+
blank(i, end);
|
|
754
|
+
i = end;
|
|
755
|
+
} else i++;
|
|
756
|
+
}
|
|
757
|
+
return out.join("");
|
|
758
|
+
}
|
|
759
|
+
function pluginPackage(code, name) {
|
|
760
|
+
const base = name.split(".")[0];
|
|
761
|
+
if (base === "" || !IDENTIFIER.test(base)) return void 0;
|
|
762
|
+
const id = escapeRegex(base);
|
|
763
|
+
const re = rustRegExp(String.raw`(?:\b(?:const|let|var)\s+(?:${id}|\{[^}]*\b${id}\b[^}]*\})\s*=\s*(?:await\s+)?(?:require|import)\(\s*|\bimport\s+(?:${id}(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*))?|(?:[A-Za-z_$][\w$]*\s*,\s*)?\{[^}]*\b${id}\b[^}]*\}|\*\s+as\s+${id})\s+from\s+)["'\x60]([^"'\x60]+)["'\x60]`);
|
|
764
|
+
return re.exec(code)?.[1];
|
|
765
|
+
}
|
|
766
|
+
function eleventy(dir) {
|
|
767
|
+
if (!isDir(dir)) fail(`${dir} isn't a folder`);
|
|
768
|
+
const config = ELEVENTY_CONFIGS.find((name) => isFile(path.join(dir, name)));
|
|
769
|
+
const configText = config === void 0 ? "" : readStrict(path.join(dir, config), `reading ${config}`);
|
|
770
|
+
const output = setting(blankComments(configText), "output") ?? "_site";
|
|
771
|
+
const plan = { from: "Eleventy", renames: [], edits: [], newFiles: [], byHand: [] };
|
|
772
|
+
const extensions = /* @__PURE__ */ new Set();
|
|
773
|
+
const entries = walk(dir, (name, rel) => name.startsWith(".git") || name === "node_modules" || name === ".cache" || samePath(rel, output), true);
|
|
774
|
+
const isTemplate = (name) => TEMPLATE_EXTENSIONS.includes(asciiLower(extensionOf(name)));
|
|
775
|
+
const readsNavigation = entries.some((e) => e.isFile && isTemplate(e.name) && NAVIGATION_FILTER.test(readUtf8(e.abs) ?? ""));
|
|
776
|
+
const keep = readsNavigation ? ["eleventyNavigation"] : [];
|
|
777
|
+
const major = eleventyMajor(dir);
|
|
778
|
+
const dataEngine = /\bdataTemplateEngine\s*:\s*["'\x60](?!false)[^"'\x60]+["'\x60]/.test(blankComments(configText));
|
|
779
|
+
const input = config === void 0 ? "." : (setting(blankComments(configText), "input") ?? ".").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
780
|
+
const inInput = (rel) => input === "" || input === "." || rel === input || rel.startsWith(`${input}/`);
|
|
781
|
+
if (major !== void 0 && major < 2) keep.push("eleventy.generator");
|
|
782
|
+
if (readsNavigation) {
|
|
783
|
+
plan.byHand.push([".", "`eleventyNavigation` front matter was left as it is, because templates call the `eleventyNavigation` filter, which reads it. To keep that filter, define it with the package's own function: `import navigation from \"@11ty/eleventy-navigation/eleventy-navigation.js\"`, then `filters: { eleventyNavigation: (pages, key) => navigation.findNavigationEntries(pages, key) }`. To move to ssqch's navigation instead (`pagesTree`), rename it to `nav` (`ssqch docs nav`)"]);
|
|
784
|
+
} else {
|
|
785
|
+
const navPages = entries.filter((e) => e.isFile && isTemplate(e.name) && /^eleventyNavigation\s*:/m.test(readUtf8(e.abs) ?? "")).map((e) => e.rel);
|
|
786
|
+
if (navPages.length) plan.byHand.push([navPages[0], `\`eleventyNavigation\` front matter (in ${navPages.length} ${navPages.length === 1 ? "page" : "pages"}; this is the first): ssqch's navigation reads \`nav\`, with the same \`key\`, \`parent\`, \`order\` and \`title\`, as a tree from \`pagesTree(collections.all)\` (\`ssqch docs pagesTree\`). Rename it when the templates move to that; until then nothing reads it`]);
|
|
787
|
+
}
|
|
788
|
+
for (const entry of entries) {
|
|
789
|
+
if (!entry.isFile) continue;
|
|
790
|
+
const { rel, name } = entry;
|
|
791
|
+
const ext = asciiLower(extensionOf(name));
|
|
792
|
+
if (DATA_FILE.test(name)) plan.renames.push([rel, rel.replace(DATA_FILE, ".data.$1")]);
|
|
793
|
+
if (name.endsWith(".11ty.js") || name.endsWith(".11ty.cjs")) {
|
|
794
|
+
plan.byHand.push([rel, "JavaScript templates don't run in ssqch: rewrite it as a template, or as an engine of your own (`engines` in the config)"]);
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
if (ext === "webc") {
|
|
798
|
+
plan.byHand.push([rel, "WebC isn't supported: rewrite it as a template, with custom elements from `ssqch/elements` for the interactive parts"]);
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
const template = TEMPLATE_EXTENSIONS.includes(ext);
|
|
802
|
+
const data = DATA_FILE.test(name) || ["json", "yaml", "yml"].includes(ext) && !name.startsWith("package");
|
|
803
|
+
if (!template && !data) continue;
|
|
804
|
+
const text = readUtf8(entry.abs);
|
|
805
|
+
if (text === void 0) continue;
|
|
806
|
+
if (template) extensions.add(ext === "markdown" ? "md" : ext);
|
|
807
|
+
let [next, changes] = template ? rewriteTemplate(text, ext === "md" || ext === "markdown", keep) : rewriteData(text, keep);
|
|
808
|
+
if (data && dataEngine && /\{\{|\{%/.test(next)) {
|
|
809
|
+
const [unwrapped, literals, left] = unwrapUrlLiterals(next);
|
|
810
|
+
if (literals) {
|
|
811
|
+
next = unwrapped;
|
|
812
|
+
changes = [...changes, `${literals} \`{{ "/x/" | url }}\` -> "/x/" (dataTemplateEngine rendered them)`];
|
|
813
|
+
}
|
|
814
|
+
if (left) plan.byHand.push([rel, `${left} ${left === 1 ? "value has" : "values have"} template code (\`{{ }}\` or \`{% %}\`), which Eleventy's \`dataTemplateEngine\` rendered and ssqch prints as written: write the value itself, or compute it in a \`.data.js\` file`]);
|
|
815
|
+
}
|
|
816
|
+
if (changes.length) plan.edits.push([rel, changes, next]);
|
|
817
|
+
if (template && (text.includes("eleventy.env") || text.includes("eleventy.directories"))) plan.byHand.push([rel, "`eleventy.env` and `eleventy.directories` aren't there: use `ssqch.env` and `ssqch.serving`"]);
|
|
818
|
+
if (template && inInput(rel) && keep.includes("eleventy.generator") && text.search(TEMPLATE_GLOBAL) !== -1) plan.byHand.push([rel, `\`eleventy.generator\` and \`eleventy.version\` left as they are: Eleventy ${major} printed nothing for them, so in ssqch they print nothing too and the output matches. \`ssqch.generator\` prints "SiteSquatch v${VERSION}" when the move is done`]);
|
|
819
|
+
}
|
|
820
|
+
packageFiles(dir, plan, entries);
|
|
821
|
+
const ignored = [];
|
|
822
|
+
for (const at of [".eleventyignore", input && input !== "." ? `${input}/.eleventyignore` : ""]) {
|
|
823
|
+
if (!at) continue;
|
|
824
|
+
const text = readUtf8(path.join(dir, ...at.split("/")));
|
|
825
|
+
if (text === void 0) continue;
|
|
826
|
+
const base = at.includes("/") ? `${at.slice(0, at.lastIndexOf("/"))}/` : "";
|
|
827
|
+
for (const line of lines(text)) {
|
|
828
|
+
const glob = trim(line);
|
|
829
|
+
if (glob === "" || glob.startsWith("#") || glob.startsWith("!")) continue;
|
|
830
|
+
const rel = `${base}${glob.replace(/^\.\//, "")}`.replace(/\/$/, "/**");
|
|
831
|
+
ignored.push(rel.startsWith(`${input}/`) && input !== "." ? rel.slice(input.length + 1) : rel);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
for (const m of blankComments(configText).matchAll(/\.ignores\.add\(\s*["'\x60]([^"'\x60]+)["'\x60]\s*\)/g)) {
|
|
835
|
+
const rel = m[1].replace(/^\.\//, "").replace(/\/$/, "/**");
|
|
836
|
+
ignored.push(rel.startsWith(`${input}/`) && input !== "." ? rel.slice(input.length + 1) : rel);
|
|
837
|
+
}
|
|
838
|
+
const followed = config === void 0 ? /* @__PURE__ */ new Map() : helperModules(dir, config, configText);
|
|
839
|
+
const helpers = [];
|
|
840
|
+
const helperLists = [];
|
|
841
|
+
let helperText = "";
|
|
842
|
+
for (const rel of new Set(followed.values())) {
|
|
843
|
+
const text = readUtf8(path.join(dir, ...rel.split("/")));
|
|
844
|
+
if (text === void 0) continue;
|
|
845
|
+
const [, list, ported] = draftConfig(rel, text, extensions);
|
|
846
|
+
helperLists.push(...list.filter(([at]) => at !== rel));
|
|
847
|
+
helpers.push([rel, ported]);
|
|
848
|
+
helperText += `
|
|
849
|
+
${blankComments(text)}`;
|
|
850
|
+
}
|
|
851
|
+
const ports = config === void 0 ? [] : undefinedFilters(entries, blankComments(configText) + helperText, readsNavigation, plan);
|
|
852
|
+
modulesUsingEleventy(entries, config, plan);
|
|
853
|
+
outputChanges(entries, configText, input, plan);
|
|
854
|
+
otherBuildTools(dir, plan);
|
|
855
|
+
if (config !== void 0) {
|
|
856
|
+
const [source, byHand] = draftConfig(config, configText, extensions, ports, major, helpers, new Set(followed.keys()), ignored);
|
|
857
|
+
plan.byHand.push(...byHand, ...helperLists);
|
|
858
|
+
plan.newFiles.push(["ssqch.config.js", `a first draft, from ${config}`, source]);
|
|
859
|
+
} else {
|
|
860
|
+
plan.byHand.push([".", `no Eleventy config here (${ELEVENTY_CONFIGS.join(", ")}): is this the site's folder?`]);
|
|
861
|
+
}
|
|
862
|
+
return plan;
|
|
863
|
+
}
|
|
864
|
+
var HTML_TAG = /<[A-Za-z][^<>]*>/g;
|
|
865
|
+
var TEMPLATE_TAG = /\{\{.*?\}\}|\{%.*?%\}/gs;
|
|
866
|
+
function rewriteTemplate(text, markdown, keep = []) {
|
|
867
|
+
const changes = [];
|
|
868
|
+
let front = "", body = text;
|
|
869
|
+
if (text.startsWith("---")) {
|
|
870
|
+
const end = text.indexOf("\n---", 3);
|
|
871
|
+
if (end !== -1) {
|
|
872
|
+
front = text.slice(0, end + 4);
|
|
873
|
+
body = text.slice(end + 4);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
let attrs = false, globals = false;
|
|
877
|
+
body = outsideCode(body, markdown, (part) => {
|
|
878
|
+
const tagged = part.replace(HTML_TAG, (tag) => {
|
|
879
|
+
if (tag.search(IMAGE_ATTR) !== -1) attrs = true;
|
|
880
|
+
return tag.replace(IMAGE_ATTR, "ssqch:$1");
|
|
881
|
+
});
|
|
882
|
+
if (keep.includes("eleventy.generator")) return tagged;
|
|
883
|
+
return tagged.replace(TEMPLATE_TAG, (tag) => {
|
|
884
|
+
if (tag.search(TEMPLATE_GLOBAL) !== -1) globals = true;
|
|
885
|
+
return tag.replace(TEMPLATE_GLOBAL, "ssqch.$1");
|
|
886
|
+
});
|
|
887
|
+
});
|
|
888
|
+
if (attrs) changes.push("eleventy:widths/ignore -> ssqch:widths/ignore");
|
|
889
|
+
if (globals) changes.push("eleventy.generator/version -> ssqch.generator/version");
|
|
890
|
+
return [front + body, changes];
|
|
891
|
+
}
|
|
892
|
+
function outsideCode(text, markdown, change) {
|
|
893
|
+
if (!markdown) return change(text);
|
|
894
|
+
let out = "";
|
|
895
|
+
let fence;
|
|
896
|
+
let prose = "";
|
|
897
|
+
for (let start = 0; start < text.length; ) {
|
|
898
|
+
const nl = text.indexOf("\n", start);
|
|
899
|
+
const end = nl === -1 ? text.length : nl + 1;
|
|
900
|
+
const line = text.slice(start, end);
|
|
901
|
+
start = end;
|
|
902
|
+
const trimmed = trimStart(line);
|
|
903
|
+
const marker = trimmed.startsWith("```") ? "```" : trimmed.startsWith("~~~") ? "~~~" : void 0;
|
|
904
|
+
if (fence === void 0 && marker !== void 0) {
|
|
905
|
+
out += changeProse(prose, change);
|
|
906
|
+
prose = "";
|
|
907
|
+
fence = marker;
|
|
908
|
+
out += line;
|
|
909
|
+
} else if (fence !== void 0 && marker === fence) {
|
|
910
|
+
fence = void 0;
|
|
911
|
+
out += line;
|
|
912
|
+
} else if (fence !== void 0) {
|
|
913
|
+
out += line;
|
|
914
|
+
} else {
|
|
915
|
+
prose += line;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return out + changeProse(prose, change);
|
|
919
|
+
}
|
|
920
|
+
function changeProse(prose, change) {
|
|
921
|
+
return prose.split("`").map((part, i) => i % 2 === 1 ? part : change(part)).join("`");
|
|
922
|
+
}
|
|
923
|
+
function unwrapUrlLiterals(text) {
|
|
924
|
+
let literals = 0;
|
|
925
|
+
const out = text.replace(/\{\{-?\s*(\\?["'])([^"'{}\\]*)\1\s*\|\s*url\s*-?\}\}/g, (_, _q, value) => {
|
|
926
|
+
literals++;
|
|
927
|
+
return value === "" ? "." : value.startsWith("/") && !value.startsWith("//") ? path.posix.normalize(value) : value;
|
|
928
|
+
});
|
|
929
|
+
const left = (out.match(/\{\{|\{%/g) ?? []).length;
|
|
930
|
+
return [out, literals, left];
|
|
931
|
+
}
|
|
932
|
+
function rewriteData(text, _keep = []) {
|
|
933
|
+
return [text, []];
|
|
934
|
+
}
|
|
935
|
+
var ELEVENTY_FILTERS = {
|
|
936
|
+
slug: { say: "Eleventy's built-in `slug` (the slugify package): ssqch's is `slugify`, which drops `.` and other punctuation that `slug` keeps. For the same ids, port it: `slug: (s) => slugify(String(s), { lower: true })` with `import slugify from \"slugify\"`" },
|
|
937
|
+
log: { say: "Eleventy's built-in `log`: ported into the draft (it prints the value and passes it on)", port: "(value) => {\n console.log(value);\n return value;\n }" },
|
|
938
|
+
getCollectionItemIndex: { say: "Eleventy's built-in, ported into the draft: pass the page, `collection | getCollectionItemIndex(page)`", port: "(collection, page) => collection.findIndex((item) => item.url === page.url)" },
|
|
939
|
+
getCollectionItem: { say: "Eleventy's built-in, ported into the draft: pass the page, `collection | getCollectionItem(page)`", port: "(collection, page) => collection.find((item) => item.url === page.url)" },
|
|
940
|
+
inputPathToUrl: { say: "Eleventy's built-in: link to the page's URL itself (`collections` items have `url`), or a filter of your own that looks it up" },
|
|
941
|
+
renderTemplate: { say: "Eleventy's render plugin: a container (`::: name`) or an include does the same in ssqch" },
|
|
942
|
+
renderFile: { say: "Eleventy's render plugin: an `{% include %}` of the file" },
|
|
943
|
+
rssLastUpdatedDate: { say: 'the RSS plugin\'s old name: `rssPlugin()` from "ssqch/rss" has it (and `getNewestCollectionItemDate(collection) | dateToRfc3339`, its new one)' },
|
|
944
|
+
rssDate: { say: 'the RSS plugin\'s old name: `rssPlugin()` from "ssqch/rss" has it (and `dateToRfc3339`, its new one)' },
|
|
945
|
+
getNewestCollectionItemDate: { say: 'the RSS plugin\'s: `rssPlugin()` from "ssqch/rss" has it' },
|
|
946
|
+
dateToRfc3339: { say: 'the RSS plugin\'s: `rssPlugin()` from "ssqch/rss" has it' },
|
|
947
|
+
dateToRfc822: { say: 'the RSS plugin\'s: `rssPlugin()` from "ssqch/rss" has it' },
|
|
948
|
+
absoluteUrl: { say: 'the RSS plugin\'s: `rssPlugin()` from "ssqch/rss" has it' },
|
|
949
|
+
htmlToAbsoluteUrls: { say: 'the RSS plugin\'s: `rssPlugin()` from "ssqch/rss" has it (or `feedHtml`)' },
|
|
950
|
+
eleventyNavigationBreadcrumb: { say: "eleventy-navigation's: `navBreadcrumbs(nav, page.url)` with `nav` front matter (`ssqch docs navBreadcrumbs`)" },
|
|
951
|
+
eleventyNavigationToHtml: { say: "eleventy-navigation's: `navTree(nav, page.url)` and a template that writes the list (`ssqch docs navTree`)" },
|
|
952
|
+
eleventyNavigationToMarkdown: { say: "eleventy-navigation's: `navTree(nav, page.url)` and a template that writes the list (`ssqch docs navTree`)" }
|
|
953
|
+
};
|
|
954
|
+
var BUILT_IN_TAGS = /* @__PURE__ */ new Set(["if", "elif", "elseif", "elsif", "else", "endif", "for", "endfor", "empty", "set", "endset", "macro", "endmacro", "call", "endcall", "import", "from", "include", "extends", "block", "endblock", "filter", "endfilter", "raw", "endraw", "verbatim", "endverbatim", "asyncEach", "endeach", "asyncAll", "endall", "ifAsync", "assign", "capture", "endcapture", "case", "when", "endcase", "comment", "endcomment", "cycle", "decrement", "increment", "echo", "break", "continue", "unless", "endunless", "render", "layout", "liquid", "tablerow", "endtablerow", "with", "endwith", "autoescape", "endautoescape", "setAsync"]);
|
|
955
|
+
var engineFilterNames;
|
|
956
|
+
function knownFilters() {
|
|
957
|
+
if (engineFilterNames) return engineFilterNames;
|
|
958
|
+
const names = /* @__PURE__ */ new Set([...BUILTIN_FILTERS.map(([name]) => name), ...TABLE.filter((r) => r.kind === "filter" && r.alias).map((r) => r.word)]);
|
|
959
|
+
for (const name of Object.keys(jinjaFilters((t) => t))) names.add(name);
|
|
960
|
+
for (const name of Object.keys(jinjaFilters((t) => t, "njk"))) names.add(name);
|
|
961
|
+
for (const name of Object.keys(new import_nunjucks.default.Environment().filters)) names.add(name);
|
|
962
|
+
try {
|
|
963
|
+
const { Liquid } = require_liquid_node();
|
|
964
|
+
for (const name of Object.keys(new Liquid().filters)) names.add(name);
|
|
965
|
+
} catch {
|
|
966
|
+
}
|
|
967
|
+
return engineFilterNames = names;
|
|
968
|
+
}
|
|
969
|
+
var TEMPLATE_CODE = /\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}/g;
|
|
970
|
+
var PIPE_FILTER = /\|\s*([A-Za-z_][\w]*)/g;
|
|
971
|
+
var TAG_NAME = /^\{%-?\s*([A-Za-z_][\w]*)/;
|
|
972
|
+
function undefinedFilters(entries, config, readsNavigation, plan) {
|
|
973
|
+
const input = (setting(config, "input") ?? ".").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
974
|
+
const inInput = (rel) => input === "" || input === "." || rel === input || rel.startsWith(`${input}/`);
|
|
975
|
+
const defined = /* @__PURE__ */ new Set();
|
|
976
|
+
for (const c of config.matchAll(CALL)) {
|
|
977
|
+
if (c[2] !== void 0 && /Filter|Shortcode|Tag|Global/.test(c[1])) defined.add(c[2]);
|
|
978
|
+
}
|
|
979
|
+
const known = knownFilters();
|
|
980
|
+
const uses2 = /* @__PURE__ */ new Map();
|
|
981
|
+
for (const entry of entries) {
|
|
982
|
+
if (!entry.isFile || !inInput(entry.rel) || !["njk", "liquid", "md", "markdown", "html"].includes(asciiLower(extensionOf(entry.name)))) continue;
|
|
983
|
+
const text = readUtf8(entry.abs);
|
|
984
|
+
if (text === void 0 || !text.includes("{{") && !text.includes("{%")) continue;
|
|
985
|
+
for (const tag of text.matchAll(TEMPLATE_CODE)) {
|
|
986
|
+
const found = [];
|
|
987
|
+
const code = tag[0].replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
|
|
988
|
+
for (const m of code.matchAll(PIPE_FILTER)) found.push(m[1]);
|
|
989
|
+
const name = TAG_NAME.exec(code)?.[1];
|
|
990
|
+
if (name !== void 0 && tag[0].startsWith("{%") && !BUILT_IN_TAGS.has(name)) found.push(name);
|
|
991
|
+
for (const name2 of found) {
|
|
992
|
+
if (defined.has(name2) || known.has(name2) && !Object.hasOwn(ELEVENTY_FILTERS, name2)) continue;
|
|
993
|
+
if (readsNavigation && name2 === "eleventyNavigation") continue;
|
|
994
|
+
const line = occurrences(text.slice(0, tag.index), "\n") + 1;
|
|
995
|
+
const use = uses2.get(name2) ?? { first: `${entry.rel}:${line}`, templates: /* @__PURE__ */ new Set() };
|
|
996
|
+
use.templates.add(entry.rel);
|
|
997
|
+
uses2.set(name2, use);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
for (const name of [...uses2.keys()]) {
|
|
1002
|
+
const opens = name.slice(3);
|
|
1003
|
+
if (name.startsWith("end") && opens !== "" && (uses2.has(opens) || defined.has(opens) || known.has(opens) || BUILT_IN_TAGS.has(opens))) uses2.delete(name);
|
|
1004
|
+
}
|
|
1005
|
+
const ports = [];
|
|
1006
|
+
for (const [name, use] of [...uses2].sort(([a], [b]) => compareText(a, b))) {
|
|
1007
|
+
const where = use.templates.size === 1 ? "" : ` (in ${use.templates.size} templates; this is the first)`;
|
|
1008
|
+
const eleventy2 = Object.hasOwn(ELEVENTY_FILTERS, name) ? ELEVENTY_FILTERS[name] : void 0;
|
|
1009
|
+
if (eleventy2?.port) ports.push([name, eleventy2.port]);
|
|
1010
|
+
plan.byHand.push([use.first, eleventy2 ? `\`${name}\`${where}: ${eleventy2.say}` : `\`${name}\`${where} is a filter or shortcode nothing defines: not the template language, not ssqch, not the Eleventy config. A plugin's, or one a helper module adds? Port it to \`filters\``]);
|
|
1011
|
+
}
|
|
1012
|
+
return ports;
|
|
1013
|
+
}
|
|
1014
|
+
var RELATIVE_IMPORT = /(?:\brequire\(\s*|\bimport\s*\(\s*|\bfrom\s+)["'](\.{1,2}\/[^"']+)["']/g;
|
|
1015
|
+
var HELPER_CALL = /\.\s*(?:addFilter|addAsyncFilter|addNunjucksFilter|addLiquidFilter|addNunjucksAsyncFilter|addShortcode|addAsyncShortcode|addPairedShortcode|addNunjucksShortcode|addLiquidShortcode|addCollection|addTransform|addGlobalData|addPlugin|addPassthroughCopy|setLibrary)\s*\(/;
|
|
1016
|
+
function helperModules(dir, config, configText) {
|
|
1017
|
+
const found = /* @__PURE__ */ new Map();
|
|
1018
|
+
const seen = /* @__PURE__ */ new Set([config]);
|
|
1019
|
+
const queue = [[config, configText]];
|
|
1020
|
+
while (queue.length) {
|
|
1021
|
+
const [rel, text] = queue.shift();
|
|
1022
|
+
for (const m of blankComments(text).matchAll(RELATIVE_IMPORT)) {
|
|
1023
|
+
const base = path.posix.join(path.posix.dirname(rel), m[1]);
|
|
1024
|
+
if (base.startsWith("..")) continue;
|
|
1025
|
+
const target = [base, `${base}.js`, `${base}.cjs`, `${base}.mjs`, `${base}/index.js`].find((p) => isFile(path.join(dir, ...p.split("/"))));
|
|
1026
|
+
if (target === void 0) continue;
|
|
1027
|
+
if (seen.has(target)) {
|
|
1028
|
+
if ([...found.values()].includes(target)) found.set(m[1], target);
|
|
1029
|
+
continue;
|
|
1030
|
+
}
|
|
1031
|
+
seen.add(target);
|
|
1032
|
+
const next = readUtf8(path.join(dir, ...target.split("/")));
|
|
1033
|
+
if (next === void 0) continue;
|
|
1034
|
+
if (HELPER_CALL.test(blankComments(next))) found.set(m[1], target);
|
|
1035
|
+
queue.push([target, next]);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return found;
|
|
1039
|
+
}
|
|
1040
|
+
function modulesUsingEleventy(entries, config, plan) {
|
|
1041
|
+
const inData = {
|
|
1042
|
+
"@11ty/eleventy-img": '`image(src, options)` from "ssqch/image" in a data file (the URLs and sizes, without markup), or `imageUrl(src)` in a template',
|
|
1043
|
+
"@11ty/eleventy-fetch": '`fetch(url, { cache: "1d" })`, from "ssqch" in a data file: it keeps a copy in `.cache/ssqch/fetch/` as eleventy-fetch kept one in `.cache`'
|
|
1044
|
+
};
|
|
1045
|
+
for (const entry of entries) {
|
|
1046
|
+
if (!entry.isFile || entry.rel === config || !/\.(?:[cm]?js|[cm]?ts)$/.test(entry.name)) continue;
|
|
1047
|
+
const text = readUtf8(entry.abs);
|
|
1048
|
+
if (text === void 0 || !text.includes("eleventy") && !text.includes("markdown-it")) continue;
|
|
1049
|
+
const code = blankComments(text);
|
|
1050
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1051
|
+
for (const m of code.matchAll(REQUIRE)) {
|
|
1052
|
+
const pkg = m[1];
|
|
1053
|
+
if (seen.has(pkg) || pkg === "@11ty/eleventy") continue;
|
|
1054
|
+
seen.add(pkg);
|
|
1055
|
+
const what = Object.hasOwn(inData, pkg) ? inData[pkg] : replacement(pkg);
|
|
1056
|
+
if (what !== void 0) plan.byHand.push([`${entry.rel}:${occurrences(code.slice(0, m.index), "\n") + 1}`, `${pkg} -> ${what}`]);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
function otherBuildTools(dir, plan) {
|
|
1061
|
+
const tools = [["gulpfile.js", "Gulp"], ["gulpfile.mjs", "Gulp"], ["gulpfile.cjs", "Gulp"], ["Gruntfile.js", "Grunt"], ["webpack.config.js", "webpack"], ["webpack.config.mjs", "webpack"], ["postcss.config.js", "PostCSS"], ["postcss.config.cjs", "PostCSS"], ["vite.config.js", "Vite"], ["vite.config.mjs", "Vite"], ["rollup.config.js", "Rollup"], ["rollup.config.mjs", "Rollup"]];
|
|
1062
|
+
const parts = [
|
|
1063
|
+
[/\b(?:gulp-)?(?:dart-)?sass\b/, 'Sass -> `sassPlugin()` from "ssqch/sass"'],
|
|
1064
|
+
[/\b(?:gulp-rev|rev-hash|cachebust|gulp-hash)\b/, 'cache-busting -> `assetsPlugin()` from "ssqch/assets" (fingerprints)'],
|
|
1065
|
+
[/\b(?:gulp-htmlmin|html-minifier(?:-terser)?)\b/, 'HTML minifying -> `minifyPlugin()` from "ssqch/minify" (it keeps markup as written; html-minifier repairs unclosed tags)'],
|
|
1066
|
+
[/\b(?:gulp-(?:clean-css|cssnano)|cssnano|clean-css)\b/, "CSS minifying -> `minifyPlugin({ css: true })`, or Sass's compressed style"],
|
|
1067
|
+
[/\b(?:gulp-imagemin|imagemin|sharp)\b/, 'images -> `imagePlugin()` from "ssqch/image"'],
|
|
1068
|
+
[/\b(?:autoprefixer)\b/, "autoprefixer: not in ssqch; keep it as a `beforeBuild` `run:` step (or after `sassPlugin()`)"],
|
|
1069
|
+
[/\b(?:purgecss|gulp-purgecss|@fullhuman\/postcss-purgecss)\b/, "PurgeCSS: not in ssqch; keep it as a step of its own"],
|
|
1070
|
+
[/\b(?:terser|uglify|gulp-uglify|esbuild)\b/, "JavaScript bundling or minifying: not in ssqch; keep the tool, before `ssqch build`"],
|
|
1071
|
+
[/\b(?:svgo|gulp-svgmin|svg-sprite|gulp-svgstore)\b/, "SVG optimizing and sprites: not in ssqch; keep the tool"],
|
|
1072
|
+
[/\b(?:kss|gulp-kss)\b/, 'a style guide (KSS): not a generator\'s job; keep it (`afterBuild: { run: "kss ..." }`)']
|
|
1073
|
+
];
|
|
1074
|
+
for (const [file, tool] of tools) {
|
|
1075
|
+
const text = readUtf8(path.join(dir, file));
|
|
1076
|
+
if (text === void 0) continue;
|
|
1077
|
+
const found = parts.filter(([pattern]) => pattern.test(text)).map(([, say]) => say);
|
|
1078
|
+
plan.byHand.push([file, `${tool} builds part of the site too: keep it for the first, identical build (\`ssqch build && <the tool>\`, and both in \`ssqch baseline\`'s command)${found.length ? `. What it does, and ssqch's way: ${found.join("; ")}` : ""}`]);
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
function outputChanges(entries, configText, input, plan) {
|
|
1082
|
+
const line = (text, at) => occurrences(text.slice(0, at), "\n") + 1;
|
|
1083
|
+
const inInput = (rel) => input === "." || rel.startsWith(`${input}/`);
|
|
1084
|
+
const bare = [];
|
|
1085
|
+
for (const entry of entries) {
|
|
1086
|
+
if (!entry.isFile) continue;
|
|
1087
|
+
const ext = asciiLower(extensionOf(entry.name));
|
|
1088
|
+
const template = TEMPLATE_EXTENSIONS.includes(ext);
|
|
1089
|
+
const code = /^(?:[cm]?js|[cm]?ts)$/.test(ext);
|
|
1090
|
+
if (!template && !code) continue;
|
|
1091
|
+
const text = readUtf8(entry.abs);
|
|
1092
|
+
if (text === void 0) continue;
|
|
1093
|
+
if (template && inInput(entry.rel)) {
|
|
1094
|
+
const d = /\{\{-?\s*((?:page\.|\w+\.data\.)?date)\s*-?\}\}/.exec(text);
|
|
1095
|
+
if (d) bare.push([`${entry.rel}:${line(text, d.index)}`, occurrences(text, d[0])]);
|
|
1096
|
+
const p = /^pagination:\s*\n(?:[ \t]+.*\n)*?[ \t]+data:\s*["']?collections["']?\s*$/m.exec(text);
|
|
1097
|
+
if (p) plan.byHand.push([`${entry.rel}:${line(text, p.index)}`, "`pagination: { data: collections }` pages over the collections' names, which come in another order in ssqch (the order they're defined, not Eleventy's): page over a list of names you make in data, in the order you want"]);
|
|
1098
|
+
}
|
|
1099
|
+
if (code) {
|
|
1100
|
+
const js = blankComments(text);
|
|
1101
|
+
for (const m of js.matchAll(/\.(toLocaleDateString|toLocaleString|toLocaleTimeString)\(([^()]*)\)|DateTime\.fromJSDate\(([^()]*)\)/g)) {
|
|
1102
|
+
const args = m[2] ?? m[3] ?? "";
|
|
1103
|
+
if (/timeZone|zone/.test(args)) continue;
|
|
1104
|
+
plan.byHand.push([`${entry.rel}:${line(js, m.index)}`, `\`${m[1] ?? "DateTime.fromJSDate"}\` without a time zone uses the build machine's, so the page changes with where it's built: give it one (\`{ timeZone: "UTC" }\`, luxon's \`{ zone: "utc" }\`), or set \`timeZone\` in the config`]);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (bare.length) {
|
|
1109
|
+
const total = bare.reduce((n, [, c]) => n + c, 0);
|
|
1110
|
+
plan.byHand.push([bare[0][0], `\`{{ date }}\` prints a Date as it is (in ${bare.length} ${bare.length === 1 ? "template" : "templates"}, ${total} ${total === 1 ? "time" : "times"}; this is the first): Eleventy wrote \`Date.toString()\` (\`Mon Mar 08 2021 00:00:00 GMT+0000 (Coordinated Universal Time)\`, in the machine's time zone), ssqch writes ISO 8601. Format it (\`| dateformat("iso")\`), so the page doesn't depend on the machine; \`ssqch diff\` groups the two forms as dates`]);
|
|
1111
|
+
}
|
|
1112
|
+
const passed = [...blankComments(configText).matchAll(/addPassthroughCopy\(\s*["'\x60]([^"'\x60*{]+)["'\x60]/g)].map((m) => m[1].replace(/^\.\//, "").replace(/\/+$/, ""));
|
|
1113
|
+
for (const folder of new Set(passed)) {
|
|
1114
|
+
const inside = entries.filter((e) => e.isFile && e.rel.startsWith(`${folder}/`) && TEMPLATE_EXTENSIONS.includes(asciiLower(extensionOf(e.name))));
|
|
1115
|
+
if (inside.length) plan.byHand.push([folder, `is passed through, and has ${inside.length} ${inside.length === 1 ? "template" : "templates"} (${inside.slice(0, 3).map((e) => e.rel).join(", ")}${inside.length > 3 ? ", ..." : ""}): Eleventy rendered ${inside.length === 1 ? "it" : "them"}, ssqch copies ${inside.length === 1 ? "it" : "them"} as ${inside.length === 1 ? "it is" : "they are"}. Move ${inside.length === 1 ? "it" : "them"} out of the folder, or pass through only the other files`]);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
function eleventyMajor(dir) {
|
|
1119
|
+
const major = (version) => typeof version === "string" ? Number(/(\d+)/.exec(version)?.[1]) : Number.NaN;
|
|
1120
|
+
for (const file of [path.join(dir, "node_modules", "@11ty", "eleventy", "package.json"), path.join(dir, "package.json")]) {
|
|
1121
|
+
let pkg;
|
|
1122
|
+
try {
|
|
1123
|
+
pkg = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1124
|
+
} catch {
|
|
1125
|
+
continue;
|
|
1126
|
+
}
|
|
1127
|
+
if (!isPlainObject(pkg)) continue;
|
|
1128
|
+
const found = file.endsWith(path.join("eleventy", "package.json")) ? major(pkg.version) : major([pkg.dependencies, pkg.devDependencies].map((d) => isPlainObject(d) ? d["@11ty/eleventy"] : void 0).find((v) => v !== void 0));
|
|
1129
|
+
if (Number.isFinite(found)) return found;
|
|
1130
|
+
}
|
|
1131
|
+
return void 0;
|
|
1132
|
+
}
|
|
1133
|
+
function replacement(pkg) {
|
|
1134
|
+
switch (pkg) {
|
|
1135
|
+
case "@11ty/eleventy-img":
|
|
1136
|
+
return '`imagePlugin()` from "ssqch/image" (every <img> becomes a <picture>), or `image()` in data files';
|
|
1137
|
+
case "@11ty/eleventy-plugin-rss":
|
|
1138
|
+
return '`rssPlugin()` from "ssqch/rss"';
|
|
1139
|
+
case "@11ty/eleventy-plugin-syntaxhighlight":
|
|
1140
|
+
return '`markdown: { highlight: { classes: "prism", css: false } }`: Prism\'s class names and `<pre class="language-x">`, so your Prism theme\'s CSS still colors the code';
|
|
1141
|
+
case "@11ty/eleventy-navigation":
|
|
1142
|
+
return "`nav` front matter and `pagesTree(collections.all)`, with `navTree`, `navPager` and `navBreadcrumbs`";
|
|
1143
|
+
case "@11ty/eleventy-fetch":
|
|
1144
|
+
return '`fetch(url, { cache: "1d" })`';
|
|
1145
|
+
case "@11ty/eleventy-plugin-bundle":
|
|
1146
|
+
case "@11ty/eleventy-plugin-webc":
|
|
1147
|
+
case "@11ty/is-land":
|
|
1148
|
+
return 'custom elements with `elementsPlugin()` from "ssqch/elements"';
|
|
1149
|
+
case "@11ty/eleventy-upgrade-help":
|
|
1150
|
+
case "@11ty/eleventy":
|
|
1151
|
+
case "@11ty/eleventy-dev-server":
|
|
1152
|
+
return void 0;
|
|
1153
|
+
case "markdown-it":
|
|
1154
|
+
return 'ssqch\'s own Markdown: see the `markdown` options (its `breaks`, `linkify` and `typographer` are `breaks`, `autolinks: "fuzzy"` and `smartPunctuation`), render hooks and containers; or keep it with `engines: { md }`';
|
|
1155
|
+
case "markdown-it-implicit-figures":
|
|
1156
|
+
return "`markdown: { figures: true }` (what it writes with `figcaption: true`)";
|
|
1157
|
+
case "markdown-it-anchor":
|
|
1158
|
+
return 'heading ids are built in (`headingIds: "markdown-it-anchor"` for its own, in the draft unless it had a `slugify`); add its anchor links and `tabindex="-1"` with `_includes/hooks/heading.*`';
|
|
1159
|
+
case "markdown-it-footnote":
|
|
1160
|
+
return "built in (`markdown: { footnotes: true }`, the default)";
|
|
1161
|
+
case "markdown-it-container":
|
|
1162
|
+
return "built in: `::: name` renders `_includes/containers/name.*`";
|
|
1163
|
+
case "markdown-it-attrs":
|
|
1164
|
+
return "`{#id .class}` on headings is built in";
|
|
1165
|
+
default:
|
|
1166
|
+
return "check whether it's needed: see `ssqch docs --from eleventy`";
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
var PADDED = rustRegExp(String.raw`[(\[][ \t]+[^\s)\]]`, "g");
|
|
1170
|
+
var TIGHT = rustRegExp(String.raw`[(\[][^\s)\]]`, "g");
|
|
1171
|
+
var DANGLING = rustRegExp(String.raw`,[ \t]*\r?\n[ \t]*[}\]]`, "g");
|
|
1172
|
+
var CLOSED = rustRegExp(String.raw`[^\s,;{\[(][ \t]*\r?\n[ \t]*[}\]]`, "g");
|
|
1173
|
+
var BARE_KEY = rustRegExp(String.raw`[{,]\s*[A-Za-z_$][\w$]*\s*:`);
|
|
1174
|
+
var QUOTED_KEY = rustRegExp(String.raw`[{,]\s*["'][^"'\n]*["']\s*:`);
|
|
1175
|
+
function styleOf(text) {
|
|
1176
|
+
const indents = lines(text).filter((l) => trim(l) !== "").map(indentOf).filter((i) => i !== "");
|
|
1177
|
+
let indent = " ";
|
|
1178
|
+
if (indents.length && indents[0].startsWith(" ")) indent = " ";
|
|
1179
|
+
else if (indents.length) {
|
|
1180
|
+
const sizes = indents.filter((i) => !i.includes(" ")).map((i) => Buffer.byteLength(i));
|
|
1181
|
+
const smallest = sizes.length ? sizes.reduce((a, b) => Math.min(a, b)) : 2;
|
|
1182
|
+
indent = " ".repeat(Math.min(8, Math.max(1, smallest)));
|
|
1183
|
+
}
|
|
1184
|
+
const count = (re) => text.match(re)?.length ?? 0;
|
|
1185
|
+
const padded = count(PADDED) > count(TIGHT);
|
|
1186
|
+
const dangle = count(DANGLING) >= count(CLOSED);
|
|
1187
|
+
const quoteKeys = !BARE_KEY.test(text) && QUOTED_KEY.test(text);
|
|
1188
|
+
return { indent, padded, dangle, quoteKeys };
|
|
1189
|
+
}
|
|
1190
|
+
function styleKey(style, key) {
|
|
1191
|
+
const identifier = key !== "" && !/^[0-9]/.test(key) && IDENTIFIER.test(key);
|
|
1192
|
+
return identifier && !style.quoteKeys ? key : `"${key}"`;
|
|
1193
|
+
}
|
|
1194
|
+
function styleItems(style, items) {
|
|
1195
|
+
return items.map((item, i) => `${item}${i + 1 < items.length || style.dangle ? "," : ""}
|
|
1196
|
+
`).join("");
|
|
1197
|
+
}
|
|
1198
|
+
var styleList = (style, items) => style.padded ? `[ ${items.join(", ")} ]` : `[${items.join(", ")}]`;
|
|
1199
|
+
function closingBracket(text, open) {
|
|
1200
|
+
let depth = 0;
|
|
1201
|
+
let i = open;
|
|
1202
|
+
while (i < text.length) {
|
|
1203
|
+
const c = text[i];
|
|
1204
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1205
|
+
i++;
|
|
1206
|
+
while (i < text.length && text[i] !== c) i += text[i] === "\\" ? 2 : 1;
|
|
1207
|
+
} else if (c === "/" && text[i + 1] === "/") {
|
|
1208
|
+
while (i < text.length && text[i] !== "\n") i++;
|
|
1209
|
+
} else if (c === "/" && text[i + 1] === "*") {
|
|
1210
|
+
const end = text.indexOf("*/", i + 2);
|
|
1211
|
+
i = end === -1 ? text.length : end + 1;
|
|
1212
|
+
} else if (c === "(" || c === "[" || c === "{") {
|
|
1213
|
+
depth++;
|
|
1214
|
+
} else if (c === ")" || c === "]" || c === "}") {
|
|
1215
|
+
depth--;
|
|
1216
|
+
if (depth === 0) return i;
|
|
1217
|
+
}
|
|
1218
|
+
i++;
|
|
1219
|
+
}
|
|
1220
|
+
return void 0;
|
|
1221
|
+
}
|
|
1222
|
+
function topLevelArgs(code) {
|
|
1223
|
+
const parts = [];
|
|
1224
|
+
let start = 0, i = 0;
|
|
1225
|
+
while (i < code.length) {
|
|
1226
|
+
const c = code[i];
|
|
1227
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1228
|
+
let j = i + 1;
|
|
1229
|
+
while (j < code.length && code[j] !== c) j += code[j] === "\\" ? 2 : 1;
|
|
1230
|
+
i = j;
|
|
1231
|
+
} else if (c === "(" || c === "[" || c === "{") {
|
|
1232
|
+
i = closingBracket(code, i) ?? code.length;
|
|
1233
|
+
} else if (c === ",") {
|
|
1234
|
+
parts.push(trim(code.slice(start, i)));
|
|
1235
|
+
start = i + 1;
|
|
1236
|
+
}
|
|
1237
|
+
i++;
|
|
1238
|
+
}
|
|
1239
|
+
parts.push(trim(code.slice(Math.min(start, code.length))));
|
|
1240
|
+
return parts.filter((p) => p !== "");
|
|
1241
|
+
}
|
|
1242
|
+
function stringLiteral(code) {
|
|
1243
|
+
const s = trim(code);
|
|
1244
|
+
const quote = s[0];
|
|
1245
|
+
if (quote !== '"' && quote !== "'" && quote !== "`" || s.length < 2 || !s.endsWith(quote)) return void 0;
|
|
1246
|
+
const inner = s.slice(1, -1);
|
|
1247
|
+
if (inner.includes("\\") || inner.includes(quote) || quote === "`" && inner.includes("${")) return void 0;
|
|
1248
|
+
return inner;
|
|
1249
|
+
}
|
|
1250
|
+
function passthroughObject(code) {
|
|
1251
|
+
const s = trim(code);
|
|
1252
|
+
if (!s.startsWith("{") || !s.endsWith("}") || s.length < 2) return void 0;
|
|
1253
|
+
const pairs = [];
|
|
1254
|
+
for (const pair of topLevelArgs(s.slice(1, -1))) {
|
|
1255
|
+
const colon = pair.indexOf(":");
|
|
1256
|
+
if (colon === -1) return void 0;
|
|
1257
|
+
const rawKey = trim(pair.slice(0, colon));
|
|
1258
|
+
const key = stringLiteral(rawKey) ?? (IDENTIFIER.test(rawKey) ? rawKey : void 0);
|
|
1259
|
+
const value = stringLiteral(pair.slice(colon + 1));
|
|
1260
|
+
if (key === void 0 || value === void 0) return void 0;
|
|
1261
|
+
pairs.push([key, value]);
|
|
1262
|
+
}
|
|
1263
|
+
return pairs.length ? pairs : void 0;
|
|
1264
|
+
}
|
|
1265
|
+
var FUNCTION_EXPR = rustRegExp(String.raw`^(?:async\s+)?(?:function\b|\([^()]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)`);
|
|
1266
|
+
var DECLARED = rustRegExp(String.raw`\b(?:const|let|var|function|class|import)\s+(?:\*\s+as\s+)?([A-Za-z_$][\w$]*)`, "g");
|
|
1267
|
+
var DESTRUCTURED = rustRegExp(String.raw`\b(?:const|let|var|import)\s*\{([^}]*)\}`, "g");
|
|
1268
|
+
function declaredNames(text) {
|
|
1269
|
+
const names = /* @__PURE__ */ new Set();
|
|
1270
|
+
for (const c of text.matchAll(DECLARED)) names.add(c[1]);
|
|
1271
|
+
for (const c of text.matchAll(DESTRUCTURED)) {
|
|
1272
|
+
for (const part of c[1].split(",")) {
|
|
1273
|
+
const name = trim(part.split(/[: ]/).reverse().find((w) => trim(w) !== "") ?? "");
|
|
1274
|
+
if (name !== "") names.add(name);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
names.add("eleventyConfig");
|
|
1278
|
+
return names;
|
|
1279
|
+
}
|
|
1280
|
+
function parameterNames(head) {
|
|
1281
|
+
const names = /* @__PURE__ */ new Set();
|
|
1282
|
+
const add = (text) => {
|
|
1283
|
+
for (const word of text.split(/[^\p{Alphabetic}\p{N}_$]/u)) if (word !== "") names.add(word);
|
|
1284
|
+
};
|
|
1285
|
+
const open = head.indexOf("("), close = head.lastIndexOf(")");
|
|
1286
|
+
if (open === -1 || close < open) {
|
|
1287
|
+
add(head);
|
|
1288
|
+
return names;
|
|
1289
|
+
}
|
|
1290
|
+
for (const param of topLevelArgs(head.slice(open + 1, close))) add(withoutDefaults(param));
|
|
1291
|
+
return names;
|
|
1292
|
+
}
|
|
1293
|
+
function withoutDefaults(param) {
|
|
1294
|
+
let out = "";
|
|
1295
|
+
let skipping = -1;
|
|
1296
|
+
let depth = 0;
|
|
1297
|
+
for (let i = 0; i < param.length; i++) {
|
|
1298
|
+
const c = param[i];
|
|
1299
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1300
|
+
let j = i + 1;
|
|
1301
|
+
while (j < param.length && param[j] !== c) j += param[j] === "\\" ? 2 : 1;
|
|
1302
|
+
if (skipping === -1) out += param.slice(i, j + 1);
|
|
1303
|
+
i = j;
|
|
1304
|
+
} else if (c === "{" || c === "[") {
|
|
1305
|
+
depth++;
|
|
1306
|
+
if (skipping === -1) out += c;
|
|
1307
|
+
} else if (c === "}" || c === "]") {
|
|
1308
|
+
if (skipping === depth) skipping = -1;
|
|
1309
|
+
depth--;
|
|
1310
|
+
if (skipping === -1) out += c;
|
|
1311
|
+
} else if (c === "," && skipping === depth) {
|
|
1312
|
+
skipping = -1;
|
|
1313
|
+
out += c;
|
|
1314
|
+
} else if (c === "=" && param[i + 1] !== ">" && skipping === -1) {
|
|
1315
|
+
skipping = depth;
|
|
1316
|
+
} else if (skipping === -1) {
|
|
1317
|
+
out += c;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
return out;
|
|
1321
|
+
}
|
|
1322
|
+
function portableFunction(source, config, declared) {
|
|
1323
|
+
if (!FUNCTION_EXPR.test(source) || source.includes("this")) return void 0;
|
|
1324
|
+
const own = declaredNames(source);
|
|
1325
|
+
const params = parameterNames(FUNCTION_EXPR.exec(source)?.[0] ?? "");
|
|
1326
|
+
const outside = declaredNames(config.replace(source, () => ""));
|
|
1327
|
+
const uses2 = (name) => rustRegExp(String.raw`(^|[^\w$.])${escapeRegex(name)}([^\w$]|$)`).test(source);
|
|
1328
|
+
const foreign = [...declared].some((n) => outside.has(n) && !own.has(n) && !params.has(n) && uses2(n));
|
|
1329
|
+
return foreign ? void 0 : source;
|
|
1330
|
+
}
|
|
1331
|
+
function reindent(source, fromIndent, toIndent) {
|
|
1332
|
+
const [first = "", ...rest] = lines(source);
|
|
1333
|
+
let out = first;
|
|
1334
|
+
for (const line of rest) {
|
|
1335
|
+
out += "\n";
|
|
1336
|
+
if (trim(line) !== "") out += toIndent + (line.startsWith(fromIndent) ? line.slice(fromIndent.length) : trimStart(line));
|
|
1337
|
+
}
|
|
1338
|
+
return out;
|
|
1339
|
+
}
|
|
1340
|
+
function draftConfig(name, text, extensions, ports = [], eleventyMajor2, helpers = [], followed = /* @__PURE__ */ new Set(), ignored = []) {
|
|
1341
|
+
const code = blankComments(text);
|
|
1342
|
+
const lineOf = (offset) => occurrences(text.slice(0, offset), "\n") + 1;
|
|
1343
|
+
const style = styleOf(text);
|
|
1344
|
+
const ind = style.indent;
|
|
1345
|
+
const declared = declaredNames(text);
|
|
1346
|
+
const byHand = [];
|
|
1347
|
+
const passthrough = [], watch = [], todo = [];
|
|
1348
|
+
const aliases = [];
|
|
1349
|
+
const ported = [];
|
|
1350
|
+
for (const c of code.matchAll(CALL)) {
|
|
1351
|
+
const [whole, method, given, bare] = c;
|
|
1352
|
+
const quoted = given !== void 0 && whole[whole.length - given.length - 2] === "`" && given.includes("${") ? void 0 : given;
|
|
1353
|
+
const at = `${name}:${lineOf(c.index)}`;
|
|
1354
|
+
const arg = quoted ?? bare ?? "...";
|
|
1355
|
+
const open2 = c.index + Math.max(0, whole.indexOf("("));
|
|
1356
|
+
const close2 = closingBracket(code, open2);
|
|
1357
|
+
const args = close2 === void 0 ? [] : topLevelArgs(text.slice(open2 + 1, close2));
|
|
1358
|
+
const before = text.slice(0, c.index);
|
|
1359
|
+
const lastLine = before.slice(before.lastIndexOf("\n") + 1);
|
|
1360
|
+
const callIndent = indentOf(lastLine);
|
|
1361
|
+
const port = () => {
|
|
1362
|
+
if (quoted === void 0 || args.length !== 2) return false;
|
|
1363
|
+
const source = portableFunction(args[1], text, declared);
|
|
1364
|
+
if (source === void 0) return false;
|
|
1365
|
+
ported.push([quoted, reindent(source, callIndent, ind.repeat(2))]);
|
|
1366
|
+
return true;
|
|
1367
|
+
};
|
|
1368
|
+
const registers = method.startsWith("add") && (method.includes("Filter") || method.includes("Shortcode") || method.includes("Tag") || method === "addNunjucksGlobal");
|
|
1369
|
+
if (registers && quoted === void 0) {
|
|
1370
|
+
byHand.push([at, `${method}(${arg}, ...) takes its name from a variable: find the names it's called with, and port each one to \`filters\``]);
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
switch (method) {
|
|
1374
|
+
case "addPassthroughCopy": {
|
|
1375
|
+
const pairs = args[0] === void 0 ? void 0 : passthroughObject(args[0]);
|
|
1376
|
+
if (quoted !== void 0) passthrough.push(`"${quoted}"`);
|
|
1377
|
+
else if (pairs) for (const [from, to] of pairs) passthrough.push(`{ ${styleKey(style, from)}: "${to}" }`);
|
|
1378
|
+
else byHand.push([at, "addPassthroughCopy with a variable or a computed value -> `passthrough: [{ from: to }]`"]);
|
|
1379
|
+
break;
|
|
1380
|
+
}
|
|
1381
|
+
case "addWatchTarget":
|
|
1382
|
+
if (quoted !== void 0) watch.push(`"${quoted}"`);
|
|
1383
|
+
else byHand.push([at, "addWatchTarget -> `watch`"]);
|
|
1384
|
+
break;
|
|
1385
|
+
case "addFilter":
|
|
1386
|
+
case "addAsyncFilter":
|
|
1387
|
+
case "addNunjucksFilter":
|
|
1388
|
+
case "addLiquidFilter":
|
|
1389
|
+
if (!port()) {
|
|
1390
|
+
todo.push(`filters: ${arg}`);
|
|
1391
|
+
byHand.push([at, `${method}("${arg}") -> \`filters: { ${arg}: ... }\` (async functions are awaited)`]);
|
|
1392
|
+
}
|
|
1393
|
+
break;
|
|
1394
|
+
case "addNunjucksAsyncFilter":
|
|
1395
|
+
todo.push(`filters: ${arg}`);
|
|
1396
|
+
byHand.push([at, `${method}("${arg}") -> \`filters: { ${arg}: async (value) => ... }\`: return the result instead of calling the callback`]);
|
|
1397
|
+
break;
|
|
1398
|
+
case "addShortcode":
|
|
1399
|
+
case "addAsyncShortcode":
|
|
1400
|
+
case "addNunjucksShortcode":
|
|
1401
|
+
case "addNunjucksAsyncShortcode":
|
|
1402
|
+
case "addLiquidShortcode":
|
|
1403
|
+
if (!port()) {
|
|
1404
|
+
todo.push(`filters: ${arg}`);
|
|
1405
|
+
byHand.push([at, `${method}("${arg}") -> a filter: \`filters: { ${arg}: ... }\`. Nunjucks keeps \`{% ${arg} ... %}\`; in Liquid it's \`{{ x | ${arg} }}\``]);
|
|
1406
|
+
}
|
|
1407
|
+
break;
|
|
1408
|
+
case "addPairedShortcode":
|
|
1409
|
+
case "addPairedAsyncShortcode":
|
|
1410
|
+
case "addPairedNunjucksShortcode":
|
|
1411
|
+
case "addPairedNunjucksAsyncShortcode":
|
|
1412
|
+
case "addPairedLiquidShortcode":
|
|
1413
|
+
if (!port()) {
|
|
1414
|
+
todo.push(`filters: ${arg}`);
|
|
1415
|
+
byHand.push([at, `${method}("${arg}") -> a filter that gets the content first. Nunjucks keeps \`{% ${arg} %}...{% end${arg} %}\`; in Markdown, a \`::: ${arg}\` container`]);
|
|
1416
|
+
}
|
|
1417
|
+
break;
|
|
1418
|
+
case "addCollection":
|
|
1419
|
+
todo.push(`collections: ${arg}`);
|
|
1420
|
+
byHand.push([at, `addCollection("${arg}") -> \`collections: { ${arg}: (pages) => ... }\`: getAll() is pages.all(), getFilteredByTag is pages.byTag, getFilteredByGlob is pages.byGlob`]);
|
|
1421
|
+
break;
|
|
1422
|
+
case "addTransform":
|
|
1423
|
+
byHand.push([at, `addTransform("${arg}") -> \`transforms: { ${arg}: (content, page) => content }\` (an HTML minifier is \`minifyPlugin()\`)`]);
|
|
1424
|
+
break;
|
|
1425
|
+
case "addGlobalData":
|
|
1426
|
+
byHand.push([at, `addGlobalData("${arg}") -> \`data: { ${arg}: value or function }\``]);
|
|
1427
|
+
break;
|
|
1428
|
+
case "addNunjucksTag":
|
|
1429
|
+
case "addLiquidTag":
|
|
1430
|
+
todo.push(`filters: ${arg}`);
|
|
1431
|
+
byHand.push([at, `${method}("${arg}") -> a custom tag is a filter in ssqch: \`filters: { ${arg}: ... }\`, and \`{% ${arg} ... %}\` keeps working in Nunjucks`]);
|
|
1432
|
+
break;
|
|
1433
|
+
case "addNunjucksGlobal":
|
|
1434
|
+
byHand.push([at, `addNunjucksGlobal("${arg}") -> \`data: { ${arg}: value }\`, or a filter for a function`]);
|
|
1435
|
+
break;
|
|
1436
|
+
case "addMarkdownHighlighter":
|
|
1437
|
+
byHand.push([at, "addMarkdownHighlighter -> `markdown: { highlight: true }`, or a fence hook for a highlighter of your own"]);
|
|
1438
|
+
break;
|
|
1439
|
+
case "addPlugin": {
|
|
1440
|
+
const pkg = pluginPackage(code, arg);
|
|
1441
|
+
const known = pkg !== void 0 && `require("${pkg}")`.search(REQUIRE) !== -1 && replacement(pkg) !== void 0;
|
|
1442
|
+
const from = pkg === void 0 ? "" : ` (from ${pkg})`;
|
|
1443
|
+
if (known) byHand.push([at, `addPlugin(${arg})${from} -> see its package below`]);
|
|
1444
|
+
else if (pkg !== void 0 && followed.has(pkg)) byHand.push([at, `addPlugin(${arg})${from}: the site's own plugin. What it adds is listed with its own file and line, and what could be copied as written is in the draft`]);
|
|
1445
|
+
else byHand.push([at, `addPlugin(${arg})${from}: a plugin ssqch doesn't know, so the filters, shortcodes and transforms it adds aren't listed here. Read its source and port them, or put it in \`plugins: [...]\` if it's written for ssqch`]);
|
|
1446
|
+
break;
|
|
1447
|
+
}
|
|
1448
|
+
case "setLibrary": {
|
|
1449
|
+
const library = quoted === "md" && args[1] !== void 0 ? trim(args[1]) : void 0;
|
|
1450
|
+
if (library !== void 0) byHand.push([at, `setLibrary("md", ${library.length > 60 || library.includes("\n") ? "..." : library}) -> keep your markdown-it as it is with \`engines: { ${library === "md" ? "md" : `md: ${/^[A-Za-z_$][\w$]*$/.test(library) ? library : "yourMarkdownIt"}`} }\` (bring its import and setup into the config; \`ssqch docs "moving with identical output first"\`), or ssqch's own Markdown: \`markdown: { ... }\` options, render hooks and containers`]);
|
|
1451
|
+
else if (quoted !== void 0 && quoted !== "md") byHand.push([at, `setLibrary("${quoted}") -> ssqch has its own; a library of your own is an engine: \`engines: { ${quoted}: { render: (source, data) => ... } }\``]);
|
|
1452
|
+
else byHand.push([at, "setLibrary -> ssqch renders Markdown itself: `markdown: { ... }` options, render hooks and containers"]);
|
|
1453
|
+
break;
|
|
1454
|
+
}
|
|
1455
|
+
case "addLayoutAlias": {
|
|
1456
|
+
const target = args[1] === void 0 ? void 0 : stringLiteral(args[1]);
|
|
1457
|
+
if (quoted !== void 0 && target !== void 0) aliases.push([quoted, target]);
|
|
1458
|
+
else byHand.push([at, 'addLayoutAlias with a variable -> `layoutAliases: { name: "layouts/name.njk" }`']);
|
|
1459
|
+
break;
|
|
1460
|
+
}
|
|
1461
|
+
case "addDataExtension":
|
|
1462
|
+
byHand.push([at, "addDataExtension -> YAML, TOML and JSON data files load as they are"]);
|
|
1463
|
+
break;
|
|
1464
|
+
case "on":
|
|
1465
|
+
if (quoted?.startsWith("eleventy.")) byHand.push([at, `on("${arg}") -> \`beforeBuild\` or \`afterBuild\``]);
|
|
1466
|
+
break;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
const required = new Set([...code.matchAll(REQUIRE)].map((c) => c[1]));
|
|
1470
|
+
const packages = [...required].filter((p) => replacement(p) !== void 0).sort(compareText);
|
|
1471
|
+
const markdown = [];
|
|
1472
|
+
const markdownDefaults = [];
|
|
1473
|
+
const ownLibrary = /\.\s*setLibrary\s*\(\s*["'\x60]md["'\x60]/.test(code);
|
|
1474
|
+
if (required.has("markdown-it")) {
|
|
1475
|
+
if (/\bbreaks\s*:\s*true\b/.test(code)) markdown.push("breaks: true");
|
|
1476
|
+
if (/\blinkify\s*:\s*true\b/.test(code)) markdown.push('autolinks: "fuzzy"');
|
|
1477
|
+
if (/\btypographer\s*:\s*true\b/.test(code)) markdown.push("smartPunctuation: true");
|
|
1478
|
+
if (required.has("markdown-it-implicit-figures")) markdown.push("figures: true");
|
|
1479
|
+
}
|
|
1480
|
+
if (extensions.has("md")) {
|
|
1481
|
+
if (!required.has("markdown-it-anchor")) markdownDefaults.push(["Eleventy's markdown-it gave headings no ids (no markdown-it-anchor); take this out for ssqch's.", "headingIds: false"]);
|
|
1482
|
+
else if (!/\bslugify\s*:/.test(code)) markdownDefaults.push(["markdown-it-anchor's ids (encodeURIComponent of the text); take this out for ssqch's.", 'headingIds: "markdown-it-anchor"']);
|
|
1483
|
+
if (eleventyMajor2 !== void 0 && (eleventyMajor2 >= 3 || eleventyMajor2 === 2 && !ownLibrary)) markdownDefaults.push([`Eleventy ${eleventyMajor2} turns off markdown-it's indented code blocks (\`md.disable("code")\`).`, "indentedCode: false"]);
|
|
1484
|
+
}
|
|
1485
|
+
for (const pkg of packages) byHand.push([name, `${pkg} -> ${replacement(pkg)}`]);
|
|
1486
|
+
const engine = (key) => {
|
|
1487
|
+
const value = setting(code, key);
|
|
1488
|
+
if (value === "njk") return '"njk"';
|
|
1489
|
+
if (value === "false" || value === "") return "false";
|
|
1490
|
+
if (value !== void 0) return `"${value}"`;
|
|
1491
|
+
return code.includes(`${key}: false`) ? "false" : void 0;
|
|
1492
|
+
};
|
|
1493
|
+
const markdownEngine = engine("markdownTemplateEngine"), htmlEngine = engine("htmlTemplateEngine");
|
|
1494
|
+
const enginesComment = markdownEngine === void 0 ? htmlEngine === void 0 ? "Eleventy's defaults: Markdown and HTML run through Liquid first." : "From the Eleventy config's htmlTemplateEngine; Markdown runs through Liquid first, Eleventy's default." : htmlEngine === void 0 ? "From the Eleventy config's markdownTemplateEngine; HTML runs through Liquid first, Eleventy's default." : "From the Eleventy config's markdownTemplateEngine and htmlTemplateEngine.";
|
|
1495
|
+
const listed = FORMATS.exec(code);
|
|
1496
|
+
const formats = listed ? listed[1].split(",").map((f) => trimMatches(trim(f), "\"'`")).filter((f) => f !== "" && f !== "11ty.js") : [...extensions].sort(compareText).filter((e) => e !== "edge");
|
|
1497
|
+
const quotedList = (items) => styleList(style, items.map((i) => `"${i}"`));
|
|
1498
|
+
const dirs = [];
|
|
1499
|
+
for (const key of ["input", "output", "includes", "layouts", "data"]) {
|
|
1500
|
+
const value = setting(code, key);
|
|
1501
|
+
if (value !== void 0) dirs.push(`${key}: "${value}"`);
|
|
1502
|
+
}
|
|
1503
|
+
const [open, close] = style.padded ? ["( {", "} )"] : ["({", "})"];
|
|
1504
|
+
let out = `// A first draft, written by \`ssqch scout\` from ${name}.
|
|
1505
|
+
// What it couldn't carry over is listed at the end; \`ssqch docs --from eleventy\` has the whole
|
|
1506
|
+
// mapping.
|
|
1507
|
+
import { defineConfig } from "ssqch";
|
|
1508
|
+
|
|
1509
|
+
export default defineConfig${open}
|
|
1510
|
+
`;
|
|
1511
|
+
const entries = [];
|
|
1512
|
+
if (dirs.length) entries.push(`${ind}dirs: { ${dirs.join(", ")} }`);
|
|
1513
|
+
if (formats.length) entries.push(`${ind}templateFormats: ${quotedList(formats)}`);
|
|
1514
|
+
entries.push(`${ind}// ${enginesComment}
|
|
1515
|
+
${ind}markdownEngine: ${markdownEngine ?? '"liquid"'}`);
|
|
1516
|
+
entries.push(`${ind}htmlEngine: ${htmlEngine ?? '"liquid"'}`);
|
|
1517
|
+
const prefix = setting(code, "pathPrefix");
|
|
1518
|
+
if (prefix !== void 0 && prefix !== "/") entries.push(`${ind}base: "${prefix}"`);
|
|
1519
|
+
if (markdownDefaults.length) {
|
|
1520
|
+
const items = markdownDefaults.map(([why, item]) => `${ind}${ind}// ${why}
|
|
1521
|
+
${ind}${ind}${item}`);
|
|
1522
|
+
if (markdown.length) items.push(`${ind}${ind}// From the Eleventy config's markdown-it options.
|
|
1523
|
+
${ind}${ind}${markdown.join(`,
|
|
1524
|
+
${ind}${ind}`)}`);
|
|
1525
|
+
entries.push(`${ind}markdown: {
|
|
1526
|
+
${styleItems(style, items)}${ind}}`);
|
|
1527
|
+
} else if (markdown.length) entries.push(`${ind}// From the Eleventy config's markdown-it options.
|
|
1528
|
+
${ind}markdown: { ${markdown.join(", ")} }`);
|
|
1529
|
+
if (aliases.length) entries.push(`${ind}// From addLayoutAlias: \`layout: ${aliases[0][0]}\` is that file (without it, it'd be \`_includes/${aliases[0][0]}.*\`).
|
|
1530
|
+
${ind}layoutAliases: { ${aliases.map(([name2, target]) => `${styleKey(style, name2)}: "${target}"`).join(", ")} }`);
|
|
1531
|
+
if (ignored.length) entries.push(`${ind}// From .eleventyignore.
|
|
1532
|
+
${ind}ignore: ${styleList(style, ignored.map((g) => `"${g}"`))}`);
|
|
1533
|
+
const dataEngine = /\bdataTemplateEngine\s*:\s*["'\x60]([^"'\x60]*)["'\x60]/.exec(code)?.[1];
|
|
1534
|
+
if (dataEngine) byHand.push([name, `dataTemplateEngine: "${dataEngine}" -> ssqch doesn't render data files' strings. The ones that were only a literal through \`url\` (\`{{ '/about/' | url }}\`) are the literal now; the files with other template code are listed`]);
|
|
1535
|
+
if (passthrough.length) entries.push(`${ind}passthrough: ${styleList(style, [...new Set(passthrough)])}`);
|
|
1536
|
+
if (watch.length) entries.push(`${ind}watch: ${styleList(style, watch)}`);
|
|
1537
|
+
let filters = `
|
|
1538
|
+
${ind}filters: {
|
|
1539
|
+
`;
|
|
1540
|
+
if (ported.length) {
|
|
1541
|
+
filters += `${ind}${ind}// From ${name}, as written.
|
|
1542
|
+
`;
|
|
1543
|
+
filters += styleItems(style, ported.map(([filter, source]) => `${ind}${ind}${styleKey(style, filter)}: ${source}`));
|
|
1544
|
+
}
|
|
1545
|
+
for (const [file, list] of helpers) {
|
|
1546
|
+
if (!list.length) continue;
|
|
1547
|
+
filters += `${ind}${ind}// From ${file}, as written.
|
|
1548
|
+
`;
|
|
1549
|
+
filters += styleItems(style, list.map(([filter, source]) => `${ind}${ind}${styleKey(style, filter)}: ${source}`));
|
|
1550
|
+
}
|
|
1551
|
+
if (ports.length) {
|
|
1552
|
+
filters += `${ind}${ind}// Eleventy's own filters the templates use, ported.
|
|
1553
|
+
`;
|
|
1554
|
+
filters += styleItems(style, ports.map(([filter, source]) => `${ind}${ind}${styleKey(style, filter)}: ${source.replaceAll(" ", ind)}`));
|
|
1555
|
+
}
|
|
1556
|
+
if (!ported.length && !ports.length && !helpers.some(([, list]) => list.length) || todo.some((t) => t.startsWith("filters:"))) filters += `${ind}${ind}// Port each filter and shortcode here: name: (value, ...args) => result
|
|
1557
|
+
`;
|
|
1558
|
+
filters += `${ind}}`;
|
|
1559
|
+
entries.push(filters);
|
|
1560
|
+
entries.push(`${ind}collections: {
|
|
1561
|
+
${ind}${ind}// name: (pages) => pages.byTag("post")
|
|
1562
|
+
${ind}}`);
|
|
1563
|
+
entries.push(`${ind}plugins: []`);
|
|
1564
|
+
out += styleItems(style, entries);
|
|
1565
|
+
out += `${close};
|
|
1566
|
+
`;
|
|
1567
|
+
if (todo.length) {
|
|
1568
|
+
out += `
|
|
1569
|
+
// To port from ${name}:
|
|
1570
|
+
`;
|
|
1571
|
+
for (const item of todo) out += `// ${item}
|
|
1572
|
+
`;
|
|
1573
|
+
}
|
|
1574
|
+
return [out, byHand, ported];
|
|
1575
|
+
}
|
|
1576
|
+
var LOCKFILES = [["pnpm", ["pnpm-lock.yaml"]], ["yarn", ["yarn.lock"]], ["bun", ["bun.lock", "bun.lockb"]], ["npm", ["package-lock.json", "npm-shrinkwrap.json"]]];
|
|
1577
|
+
var packageManagerField = (pkg) => isPlainObject(pkg) && typeof pkg.packageManager === "string" ? pkg.packageManager : void 0;
|
|
1578
|
+
function packageManager(dir, pkg) {
|
|
1579
|
+
const named = (packageManagerField(pkg) ?? "").split("@")[0];
|
|
1580
|
+
const byName = LOCKFILES.find(([pm]) => named === pm);
|
|
1581
|
+
if (byName) return byName[0];
|
|
1582
|
+
return LOCKFILES.find(([, lockfiles]) => lockfiles.some((l) => isFile(path.join(dir, l))))?.[0] ?? "npm";
|
|
1583
|
+
}
|
|
1584
|
+
var ELEVENTY_COMMAND = rustRegExp(String.raw`(?:\bnpx\s+(?:-y\s+)?)?(?:@11ty/)?\beleventy\b((?:\s+--?[\w-]+(?:[= ](?:\x22[^\x22]*\x22|'[^']*'|[^\s&|;\x22-][^\s&|;\x22]*))?)*)`, "g");
|
|
1585
|
+
function rewriteScript(script, names) {
|
|
1586
|
+
const unknown = [];
|
|
1587
|
+
const out = script.replace(ELEVENTY_COMMAND, (whole, given, start) => {
|
|
1588
|
+
if (!isEleventyCommand(script, start, start + whole.length - given.length, names)) return whole;
|
|
1589
|
+
let command = "build";
|
|
1590
|
+
const flags = [];
|
|
1591
|
+
const parts = splitWhitespace(given);
|
|
1592
|
+
for (let i = 0; i < parts.length; i++) {
|
|
1593
|
+
const part = parts[i];
|
|
1594
|
+
const eq = part.indexOf("=");
|
|
1595
|
+
const flag = eq === -1 ? part : part.slice(0, eq);
|
|
1596
|
+
let value = eq === -1 ? void 0 : part.slice(eq + 1);
|
|
1597
|
+
const valueOf = () => {
|
|
1598
|
+
if (value === void 0 && i + 1 < parts.length && !parts[i + 1].startsWith("-")) value = parts[++i];
|
|
1599
|
+
return value;
|
|
1600
|
+
};
|
|
1601
|
+
if (flag === "--serve" || flag === "--watch") command = "serve";
|
|
1602
|
+
else if (flag === "--quiet") flags.push("--quiet");
|
|
1603
|
+
else if (flag === "--port") {
|
|
1604
|
+
const port = valueOf();
|
|
1605
|
+
if (port !== void 0) flags.push(`--port ${port}`);
|
|
1606
|
+
} else if (flag === "--output") {
|
|
1607
|
+
const output = valueOf();
|
|
1608
|
+
if (output !== void 0) flags.push(`--output ${output}`);
|
|
1609
|
+
} else if (flag === "--pathprefix" || flag === "--pathPrefix") {
|
|
1610
|
+
const base = valueOf();
|
|
1611
|
+
if (base !== void 0) flags.push(`--base ${base}`);
|
|
1612
|
+
} else if (flag !== "--incremental") unknown.push(flag);
|
|
1613
|
+
}
|
|
1614
|
+
const kept = command === "build" ? flags.filter((f) => !f.startsWith("--port")) : flags;
|
|
1615
|
+
return [`ssqch ${command}`, ...kept].join(" ");
|
|
1616
|
+
});
|
|
1617
|
+
return [out, unknown];
|
|
1618
|
+
}
|
|
1619
|
+
var lastChar = (s) => s === "" ? void 0 : Array.from(s.slice(-2)).pop();
|
|
1620
|
+
var firstChar = (s) => s === "" ? void 0 : String.fromCodePoint(s.codePointAt(0));
|
|
1621
|
+
function isEleventyCommand(script, start, wordEnd, names) {
|
|
1622
|
+
const partOfName = (c) => c !== void 0 && (/^[\p{Alphabetic}\p{N}]$/u.test(c) || "_-:./@$".includes(c));
|
|
1623
|
+
if (partOfName(lastChar(script.slice(0, start))) || partOfName(firstChar(script.slice(wordEnd)))) return false;
|
|
1624
|
+
const command = script.slice(0, start).split(/[&|;]/).pop() ?? "";
|
|
1625
|
+
const all = splitWhitespace(command);
|
|
1626
|
+
let skip = 0;
|
|
1627
|
+
while (skip < all.length && all[skip].includes("=") && !all[skip].startsWith("-")) skip++;
|
|
1628
|
+
const words = all.slice(skip);
|
|
1629
|
+
if (words.length === 0) return true;
|
|
1630
|
+
if (["npm", "pnpm", "yarn", "bun"].includes(words[0]) && ["run", "run-script"].includes(words[1])) return false;
|
|
1631
|
+
if (["run-s", "run-p", "npm-run-all", "npm-run-all2"].includes(words[0])) return false;
|
|
1632
|
+
if (words.length === 1 && (words[0] === "pnpm" || words[0] === "yarn")) return !names.includes("eleventy");
|
|
1633
|
+
return true;
|
|
1634
|
+
}
|
|
1635
|
+
var CAME_WITH_ELEVENTY = ["@sindresorhus/slugify", "browser-sync", "chokidar", "debug", "fast-glob", "gray-matter", "js-yaml", "liquidjs", "luxon", "markdown-it", "minimist", "moo", "nunjucks", "posthtml", "slugify"];
|
|
1636
|
+
var BARE_IMPORT = new RegExp(String.raw`(?:\brequire\(\s*|\bimport\s*\(\s*|\bfrom\s+|^\s*import\s+)["']([^"'./][^"']*)["']`, "gm");
|
|
1637
|
+
function packageOf(specifier) {
|
|
1638
|
+
if (specifier.startsWith("node:") || specifier.includes(":")) return void 0;
|
|
1639
|
+
const parts = specifier.split("/");
|
|
1640
|
+
const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
1641
|
+
return builtinModules.includes(name) ? void 0 : name;
|
|
1642
|
+
}
|
|
1643
|
+
function cameWithEleventy(dir, root, entries) {
|
|
1644
|
+
const listed = /* @__PURE__ */ new Set();
|
|
1645
|
+
for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
|
|
1646
|
+
if (isPlainObject(root[section])) for (const name of Object.keys(root[section])) listed.add(name);
|
|
1647
|
+
}
|
|
1648
|
+
const installed = (name) => {
|
|
1649
|
+
try {
|
|
1650
|
+
const p = JSON.parse(fs.readFileSync(path.join(dir, "node_modules", ...name.split("/"), "package.json"), "utf8"));
|
|
1651
|
+
return isPlainObject(p) ? p : void 0;
|
|
1652
|
+
} catch {
|
|
1653
|
+
return void 0;
|
|
1654
|
+
}
|
|
1655
|
+
};
|
|
1656
|
+
const eleventyPkg = installed("@11ty/eleventy");
|
|
1657
|
+
const eleventyDeps = eleventyPkg && isPlainObject(eleventyPkg.dependencies) ? new Set(Object.keys(eleventyPkg.dependencies)) : void 0;
|
|
1658
|
+
const came = (name) => eleventyDeps ? eleventyDeps.has(name) : CAME_WITH_ELEVENTY.includes(name);
|
|
1659
|
+
const found = /* @__PURE__ */ new Map();
|
|
1660
|
+
for (const entry of entries) {
|
|
1661
|
+
if (!entry.isFile || !/\.(?:[cm]?js|[cm]?ts)$/.test(entry.name)) continue;
|
|
1662
|
+
const text = readUtf8(entry.abs);
|
|
1663
|
+
if (text === void 0) continue;
|
|
1664
|
+
for (const m of blankComments(text).matchAll(BARE_IMPORT)) {
|
|
1665
|
+
const name = packageOf(m[1]);
|
|
1666
|
+
if (name === void 0 || listed.has(name) || name === "@11ty/eleventy" || found.has(name) || !came(name)) continue;
|
|
1667
|
+
found.set(name, entry.rel);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
return [...found].sort(([a], [b]) => compareText(a, b)).map(([name, file]) => {
|
|
1671
|
+
const version = installed(name)?.version;
|
|
1672
|
+
return [name, typeof version === "string" ? version : void 0, file];
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
function packageFiles(dir, plan, entries = []) {
|
|
1676
|
+
const text = readUtf8(path.join(dir, "package.json"));
|
|
1677
|
+
if (text === void 0) return;
|
|
1678
|
+
let pkg;
|
|
1679
|
+
try {
|
|
1680
|
+
pkg = JSON.parse(text);
|
|
1681
|
+
} catch {
|
|
1682
|
+
plan.byHand.push(["package.json", "isn't valid JSON, so its Eleventy dependency and scripts weren't changed"]);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
const root = isPlainObject(pkg) ? pkg : {};
|
|
1686
|
+
const edits = new JsonText(text);
|
|
1687
|
+
const version = VERSION;
|
|
1688
|
+
const changes = [];
|
|
1689
|
+
const hasSsqch = ["dependencies", "devDependencies"].some((k) => isPlainObject(root[k]) && Object.hasOwn(root[k], "ssqch"));
|
|
1690
|
+
let removed = false;
|
|
1691
|
+
let eleventySection = "devDependencies";
|
|
1692
|
+
const missing = cameWithEleventy(dir, root, entries);
|
|
1693
|
+
for (const section of ["dependencies", "devDependencies"]) {
|
|
1694
|
+
const deps = root[section];
|
|
1695
|
+
if (!isPlainObject(deps)) continue;
|
|
1696
|
+
if (Object.hasOwn(deps, "@11ty/eleventy")) {
|
|
1697
|
+
eleventySection = section;
|
|
1698
|
+
for (const [name, version2] of missing) {
|
|
1699
|
+
if (version2 === void 0) continue;
|
|
1700
|
+
deps[name] = version2;
|
|
1701
|
+
edits.insert([section], name, JSON.stringify(version2), (other2) => compareText(other2, name) > 0);
|
|
1702
|
+
}
|
|
1703
|
+
delete deps["@11ty/eleventy"];
|
|
1704
|
+
edits.remove([section], "@11ty/eleventy");
|
|
1705
|
+
removed = true;
|
|
1706
|
+
}
|
|
1707
|
+
if (Object.keys(deps).length === 0 && section === "dependencies") {
|
|
1708
|
+
delete root[section];
|
|
1709
|
+
edits.remove([], section);
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
if (removed) {
|
|
1713
|
+
const pinned = missing.filter(([, version2]) => version2 !== void 0);
|
|
1714
|
+
if (pinned.length) changes.push(`${pinned.map(([name, version2]) => `${name} ${version2}`).join(", ")} added to ${eleventySection}: the site's own code imports ${pinned.length === 1 ? "it" : "them"}, and ${pinned.length === 1 ? "it" : "they"} came with @11ty/eleventy (pinned to the version installed, since the output can depend on it)`);
|
|
1715
|
+
for (const [name, version2, file] of missing) {
|
|
1716
|
+
if (version2 === void 0) plan.byHand.push([file, `imports ${name}, which came with @11ty/eleventy and isn't in package.json: add it (\`npm ls ${name}\` before removing Eleventy says which version it had)`]);
|
|
1717
|
+
}
|
|
1718
|
+
if (hasSsqch) {
|
|
1719
|
+
changes.push("@11ty/eleventy removed (ssqch is already there)");
|
|
1720
|
+
} else {
|
|
1721
|
+
const pinned2 = JSON.stringify(version);
|
|
1722
|
+
if (!Object.hasOwn(root, "devDependencies")) {
|
|
1723
|
+
root.devDependencies = { ssqch: version };
|
|
1724
|
+
edits.insert([], "devDependencies", edits.object([["ssqch", pinned2]], 1));
|
|
1725
|
+
} else if (isPlainObject(root.devDependencies)) {
|
|
1726
|
+
root.devDependencies.ssqch = version;
|
|
1727
|
+
edits.insert(["devDependencies"], "ssqch", pinned2, (other2) => compareText(other2, "ssqch") > 0);
|
|
1728
|
+
}
|
|
1729
|
+
changes.push(`@11ty/eleventy -> ssqch ${version} in devDependencies`);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
const unknownFlags = [];
|
|
1733
|
+
const flagsAre = (unknown) => `${unknown.join(", ")} ${unknown.length === 1 ? "flag is" : "flags are"} Eleventy's: check what ssqch has (\`ssqch build --help\`, \`ssqch serve --help\`)`;
|
|
1734
|
+
const scripts = isPlainObject(root.scripts) ? root.scripts : void 0;
|
|
1735
|
+
const names = scripts ? Object.keys(scripts) : [];
|
|
1736
|
+
if (scripts) {
|
|
1737
|
+
let changed = false;
|
|
1738
|
+
for (const [name, script] of Object.entries(scripts)) {
|
|
1739
|
+
if (typeof script !== "string") continue;
|
|
1740
|
+
const [rewritten, unknown] = rewriteScript(script, names);
|
|
1741
|
+
if (rewritten !== script) {
|
|
1742
|
+
scripts[name] = rewritten;
|
|
1743
|
+
edits.replace(["scripts", name], JSON.stringify(rewritten));
|
|
1744
|
+
changed = true;
|
|
1745
|
+
}
|
|
1746
|
+
if (unknown.length) unknownFlags.push(`the \`${name}\` script's ${flagsAre(unknown)}`);
|
|
1747
|
+
if (/ssqch build[^&|;]*[^&]&(?!&)|(?:^|[^&])&\s*(?:npx\s+)?ssqch build/.test(rewritten)) plan.byHand.push(["package.json", `the \`${name}\` script runs \`ssqch build\` and another command at the same time (\`&\`): npm returns when the last one does, so what runs next (a deploy) can start while ssqch is still writing. Use \`&&\` to run them one after the other`]);
|
|
1748
|
+
}
|
|
1749
|
+
if (changed) changes.push("scripts: eleventy -> ssqch build, eleventy --serve -> ssqch serve");
|
|
1750
|
+
}
|
|
1751
|
+
if (isPlainObject(root.wireit)) {
|
|
1752
|
+
let changed = false;
|
|
1753
|
+
for (const [name, task] of Object.entries(root.wireit)) {
|
|
1754
|
+
if (!isPlainObject(task) || typeof task.command !== "string") continue;
|
|
1755
|
+
const [rewritten, unknown] = rewriteScript(task.command, names);
|
|
1756
|
+
if (rewritten !== task.command) {
|
|
1757
|
+
task.command = rewritten;
|
|
1758
|
+
edits.replace(["wireit", name, "command"], JSON.stringify(rewritten));
|
|
1759
|
+
changed = true;
|
|
1760
|
+
}
|
|
1761
|
+
if (unknown.length) unknownFlags.push(`wireit's \`${name}\` command's ${flagsAre(unknown)}`);
|
|
1762
|
+
}
|
|
1763
|
+
if (changed) changes.push("wireit commands: eleventy -> ssqch build, eleventy --serve -> ssqch serve");
|
|
1764
|
+
}
|
|
1765
|
+
for (const what of unknownFlags) plan.byHand.push(["package.json", what]);
|
|
1766
|
+
const edited = changes.length > 0;
|
|
1767
|
+
if (edited) plan.edits.push(["package.json", changes, edits.text]);
|
|
1768
|
+
const pm = packageManager(dir, pkg);
|
|
1769
|
+
for (const [manager, lockfiles] of LOCKFILES) {
|
|
1770
|
+
for (const lockfile of lockfiles) {
|
|
1771
|
+
const file = path.join(dir, lockfile);
|
|
1772
|
+
if (!isFile(file)) continue;
|
|
1773
|
+
let mentions = false;
|
|
1774
|
+
try {
|
|
1775
|
+
mentions = fs.readFileSync(file).includes("@11ty/eleventy");
|
|
1776
|
+
} catch {
|
|
1777
|
+
}
|
|
1778
|
+
if (manager !== pm) plan.byHand.push([lockfile, `${manager}'s lockfile, but the site uses ${pm}: delete it (a host that installs from it gets ${mentions ? "Eleventy" : "old packages"} and no ssqch)`]);
|
|
1779
|
+
else if (mentions || edited) plan.byHand.push([lockfile, `run \`${pm} install\` to update it for ssqch`]);
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
if (pm === "pnpm" && edited && waitsForReleaseAge(dir, pkg)) {
|
|
1783
|
+
plan.byHand.push(["pnpm-workspace.yaml", `pnpm waits a day before installing a new release, so if ssqch ${version} came out today, the install fails: add \`ssqch\` under \`minimumReleaseAgeExclude\` (\`ssqch docs "release age"\`)`]);
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
function waitsForReleaseAge(dir, pkg) {
|
|
1787
|
+
const field = packageManagerField(pkg);
|
|
1788
|
+
const major = field?.startsWith("pnpm@") ? field.slice(5).split(".")[0] : void 0;
|
|
1789
|
+
if (major !== void 0 && /^\+?\d+$/.test(major) && Number(major) <= 4294967295 && Number(major) < 11) return false;
|
|
1790
|
+
const workspace = lines(readUtf8(path.join(dir, "pnpm-workspace.yaml")) ?? "");
|
|
1791
|
+
const excluded = workspace.some((l) => trimMatches(trim(trimStart(l).replace(/^-+/, "")), `'"`).split("@")[0] === "ssqch");
|
|
1792
|
+
const off = workspace.some((l) => trim(l).replaceAll(" ", "") === "minimumReleaseAge:0");
|
|
1793
|
+
return !excluded && !off;
|
|
1794
|
+
}
|
|
1795
|
+
var TERA_CALLS = rustRegExp(String.raw`\b(get_url|get_section|get_page|get_taxonomy|get_taxonomy_url|get_image_metadata|resize_image|load_data|trans|get_hash)\s*\(`, "g");
|
|
1796
|
+
var NAMED_ARGUMENT = rustRegExp(String.raw`\|\s*\w+\(\s*\w+\s*=`, "g");
|
|
1797
|
+
var SHORTCODE_CALL = rustRegExp(String.raw`\{[{%]\s*([a-z_][a-z0-9_]*)\s*\(`, "g");
|
|
1798
|
+
function rewriteZolaFrontMatter(text) {
|
|
1799
|
+
if (!text.startsWith("+++")) return [text, []];
|
|
1800
|
+
const rest = text.slice(3);
|
|
1801
|
+
const end = rest.indexOf("\n+++");
|
|
1802
|
+
if (end === -1) return [text, []];
|
|
1803
|
+
const front = rest.slice(0, end), after = rest.slice(end);
|
|
1804
|
+
const newline = front.includes("\r\n") ? "\r\n" : "\n";
|
|
1805
|
+
const all = lines(front);
|
|
1806
|
+
const changes = [];
|
|
1807
|
+
const top = [], tables = [], tags = [];
|
|
1808
|
+
let table = "";
|
|
1809
|
+
for (let i = 0; i < all.length; i++) {
|
|
1810
|
+
const line = all[i];
|
|
1811
|
+
const trimmed = trim(line);
|
|
1812
|
+
if (trimmed.startsWith("[") && !trimmed.startsWith("[[") && trimmed.endsWith("]")) {
|
|
1813
|
+
table = trim(trimMatches(trimmed, "[]"));
|
|
1814
|
+
tables.push(line);
|
|
1815
|
+
} else if (table === "taxonomies" && trimmed.startsWith("tags") && trimStart(trimmed.slice(4)).startsWith("=")) {
|
|
1816
|
+
let value = line;
|
|
1817
|
+
while (occurrences(value, "[") > occurrences(value, "]") && i + 1 < all.length) {
|
|
1818
|
+
i++;
|
|
1819
|
+
value += newline + all[i];
|
|
1820
|
+
}
|
|
1821
|
+
tags.push(trimStart(value));
|
|
1822
|
+
} else if (table === "" && trimmed.startsWith("path") && trimStart(trimmed.slice(4)).startsWith("=")) {
|
|
1823
|
+
const value = trim(trimStart(trimmed.slice(4)).replace(/^=+/, ""));
|
|
1824
|
+
const quote = value[0] === '"' || value[0] === "'" ? value[0] : void 0;
|
|
1825
|
+
const close = quote === void 0 ? -1 : value.indexOf(quote, 1);
|
|
1826
|
+
if (close !== -1) {
|
|
1827
|
+
top.push(`permalink = "/${trimMatches(value.slice(1, close), "/")}/"`);
|
|
1828
|
+
changes.push("path -> permalink");
|
|
1829
|
+
} else {
|
|
1830
|
+
top.push(line);
|
|
1831
|
+
}
|
|
1832
|
+
} else if (table === "") {
|
|
1833
|
+
top.push(line);
|
|
1834
|
+
} else {
|
|
1835
|
+
tables.push(line);
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
if (!tags.length && !changes.length) return [text, []];
|
|
1839
|
+
if (tags.length) {
|
|
1840
|
+
changes.push("[taxonomies] tags -> tags");
|
|
1841
|
+
let at = 0;
|
|
1842
|
+
for (let k = top.length - 1; k >= 0; k--) {
|
|
1843
|
+
if (trim(top[k]) !== "") {
|
|
1844
|
+
at = k + 1;
|
|
1845
|
+
break;
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
top.splice(at, 0, ...tags);
|
|
1849
|
+
const header = tables.findIndex((l) => trim(l) === "[taxonomies]");
|
|
1850
|
+
if (header !== -1) {
|
|
1851
|
+
let next = tables.findIndex((l, k) => k > header && trim(l).startsWith("["));
|
|
1852
|
+
if (next === -1) next = tables.length;
|
|
1853
|
+
if (tables.slice(header + 1, next).every((l) => trim(l) === "")) {
|
|
1854
|
+
tables.splice(header, next - header);
|
|
1855
|
+
while (top.length && trim(top[top.length - 1]) === "" && !tables.length) top.pop();
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const body = [...top, ...tables].join(newline);
|
|
1860
|
+
return [`+++${newline}${body.startsWith(newline) ? body.slice(newline.length) : body}${after}`, changes];
|
|
1861
|
+
}
|
|
1862
|
+
function sortedKeys(value) {
|
|
1863
|
+
if (Array.isArray(value)) return value.map(sortedKeys);
|
|
1864
|
+
if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compareText(a, b)).map(([k, v]) => [k, sortedKeys(v)]));
|
|
1865
|
+
return value;
|
|
1866
|
+
}
|
|
1867
|
+
function tomlError(e, text) {
|
|
1868
|
+
if (!(e instanceof TomlError)) return tomlReason(e);
|
|
1869
|
+
const what = e.message.split("\n")[0].replace(/^Invalid TOML document: /, "");
|
|
1870
|
+
const gutter = " ".repeat(String(e.line).length + 1);
|
|
1871
|
+
const content = text.split("\n")[e.line - 1] ?? "";
|
|
1872
|
+
return `TOML parse error at line ${e.line}, column ${e.column}
|
|
1873
|
+
${gutter}|
|
|
1874
|
+
${e.line} | ${content}
|
|
1875
|
+
${gutter}|${" ".repeat(e.column)}^
|
|
1876
|
+
${what}
|
|
1877
|
+
`;
|
|
1878
|
+
}
|
|
1879
|
+
var JEKYLL_EXCLUDES = [".sass-cache", ".jekyll-cache", "gemfiles", "Gemfile", "Gemfile.lock", "node_modules", "vendor/bundle", "vendor/cache", "vendor/gems", "vendor/ruby"];
|
|
1880
|
+
var JEKYLL_PAGE = {
|
|
1881
|
+
content: "`content`, in a layout (Jekyll's `page.content` there is the page's source, before Liquid and Markdown)",
|
|
1882
|
+
name: "`page.fileSlug` (without the extension)",
|
|
1883
|
+
dir: "the folder of `page.url`",
|
|
1884
|
+
id: "`page.url`",
|
|
1885
|
+
collection: "the tag the collection is made from",
|
|
1886
|
+
next: "`navPager(collections.posts, page.url).next`",
|
|
1887
|
+
previous: "`navPager(collections.posts, page.url).previous`"
|
|
1888
|
+
};
|
|
1889
|
+
var LIQUID_TAGS = /* @__PURE__ */ new Set(["assign", "capture", "endcapture", "case", "when", "endcase", "comment", "endcomment", "cycle", "decrement", "increment", "echo", "for", "endfor", "break", "continue", "if", "elsif", "else", "endif", "unless", "endunless", "include", "include_relative", "render", "layout", "liquid", "raw", "endraw", "tablerow", "endtablerow", "highlight", "endhighlight", "link", "post_url", "block", "endblock"]);
|
|
1890
|
+
var JEKYLL_PLUGINS = {
|
|
1891
|
+
"jekyll-sitemap": { use: ['import { sitemapPlugin } from "ssqch/sitemap";', "sitemapPlugin({ url: site.url })"], say: "`sitemapPlugin({ url: site.url })`, in the draft (an empty `url` writes paths, as jekyll-sitemap did, and warns). jekyll-sitemap also wrote `/robots.txt` when the site had none: `robots.liquid`, in the plan. Its own sitemap's format (the order, `xsi:schemaLocation`) is a template of your own if the bytes matter" },
|
|
1892
|
+
"jekyll-redirect-from": { use: ['import { redirectsPlugin } from "ssqch/redirects";', "redirectsPlugin()"], say: "`redirectsPlugin()`, in the draft: `redirect_from` works as it is (templates read it as `aliases`); `_includes/hooks/redirect.*` is its page's markup. jekyll-redirect-from also wrote `/redirects.json`: `redirects.liquid`, in the plan" },
|
|
1893
|
+
"jekyll-feed": { use: ['import { rssPlugin } from "ssqch/rss";', "rssPlugin()"], say: "`rssPlugin()` is in the draft; the feed itself is a template of the site's (`feed.xml.liquid` with `permalink: /feed.xml`): `ssqch docs rssPlugin`" },
|
|
1894
|
+
"jekyll-seo-tag": { say: '`{% seo %}` becomes an include: `ssqch docs "From jekyll-seo-tag"` has one that writes its tags' },
|
|
1895
|
+
"jekyll-github-metadata": { say: "`site.github` isn't there: put what the templates read (`site.github.repository_nwo`, `site.github.url`) in the config's `data`" },
|
|
1896
|
+
"jekyll-paginate": { say: '`paginate` and `paginator` become `pagination: { data: "collections.posts", size: N }` in the listing page\'s front matter, and `pagination.items`' },
|
|
1897
|
+
"jekyll-toc": { say: '`toc(page.headings, { class: "section-nav" })` writes jekyll-toc\'s markup (`ssqch docs toc`)' },
|
|
1898
|
+
"jekyll-relative-links": { say: "ssqch leaves `[x](other.md)` as it's written: link to the page's URL" },
|
|
1899
|
+
"jekyll-optional-front-matter": { say: "a Markdown file without front matter is a page in ssqch too" },
|
|
1900
|
+
"jekyll-titles-from-headings": { say: "a page's `title` comes from its front matter only: add `title` to the pages that had theirs from the first heading" },
|
|
1901
|
+
"jekyll-default-layout": { say: "set `layout` in directory data, or in the config's `data`, for pages that had the default one" },
|
|
1902
|
+
"jekyll-readme-index": { say: "a `README.md` is a page in ssqch too; give it `permalink: /` to make it the index, or ignore it" },
|
|
1903
|
+
"jekyll-gist": { say: '`{% gist %}` becomes a function in `filters` (`{% gist "id" %}` calls it) that writes the `<script>`' },
|
|
1904
|
+
"jekyll-mentions": { say: "`@name` stays text: a transform of your own, or links in the source" },
|
|
1905
|
+
"jekyll-avatar": { say: "`{% avatar %}` becomes a function in `filters` that writes the `<img>`" }
|
|
1906
|
+
};
|
|
1907
|
+
var SEO_INCLUDE = '{%- comment -%} _includes/seo.liquid {%- endcomment -%}\n{%- assign site_title = site.title | default: site.name | markdownify | strip_html | normalize_whitespace | escape_once -%}\n{%- assign page_title = title | markdownify | strip_html | normalize_whitespace | escape_once | default: site_title -%}\n{%- assign about = description | default: site.description | markdownify | strip_html | normalize_whitespace | escape_once -%}\n{%- if page_title != site_title -%}{%- assign full_title = page_title | append: " | " | append: site_title -%}{%- elsif site.description -%}{%- assign full_title = site_title | append: " | " | append: about -%}{%- else -%}{%- assign full_title = site_title -%}{%- endif -%}\n{%- assign canonical = site.url | append: page.url -%}\n{%- if image -%}{%- assign image_url = site.url | append: image -%}{%- endif -%}\n{%- if date or tags -%}{%- assign published = page.date | date_to_xmlschema -%}{%- endif -%}\n{%- if page.url == "/" or page.url == "/about/" -%}{%- assign ld_type = "WebSite" -%}{%- elsif published -%}{%- assign ld_type = "BlogPosting" -%}{%- else -%}{%- assign ld_type = "WebPage" -%}{%- endif -%}\n<!-- Begin Jekyll SEO tag v2.8.0 -->\n<title>{{ full_title }}</title>\n<meta name="generator" content="{{ ssqch.generator }}" />\n<meta property="og:title" content="{{ page_title }}" />\n<meta property="og:locale" content="{{ lang | default: site.lang | default: "en_US" | replace: "-", "_" }}" />\n{% if about %}<meta name="description" content="{{ about }}" />\n<meta property="og:description" content="{{ about }}" />\n{% endif %}{% if site.url %}<link rel="canonical" href="{{ canonical }}" />\n<meta property="og:url" content="{{ canonical }}" />\n{% endif %}<meta property="og:site_name" content="{{ site_title }}" />\n{% if image_url %}<meta property="og:image" content="{{ image_url }}" />\n{% endif %}{% if published %}<meta property="og:type" content="article" />\n<meta property="article:published_time" content="{{ published }}" />\n{% else %}<meta property="og:type" content="website" />\n{% endif %}<meta name="twitter:card" content="{% if image_url %}summary_large_image{% else %}summary{% endif %}" />\n{% if image_url %}<meta property="twitter:image" content="{{ image_url }}" />\n{% endif %}<meta property="twitter:title" content="{{ page_title }}" />\n{% if site.twitter.username %}<meta name="twitter:site" content="@{{ site.twitter.username | remove: "@" }}" />\n{% endif %}{% if site.facebook.publisher %}<meta property="article:publisher" content="{{ site.facebook.publisher }}" />\n{% endif %}<script type="application/ld+json">\n{"@context":"https://schema.org","@type":{{ ld_type | jsonify }}{% if published %},"dateModified":{{ published | jsonify }},"datePublished":{{ published | jsonify }}{% endif %}{% if about %},"description":{{ about | jsonify }}{% endif %},"headline":{{ page_title | jsonify }}{% if image_url %},"image":{{ image_url | jsonify }}{% endif %}{% if ld_type == "BlogPosting" %},"mainEntityOfPage":{"@type":"WebPage","@id":{{ canonical | jsonify }}}{% endif %}{% if ld_type == "WebSite" %},"name":{{ site_title | jsonify }}{% endif %}{% if site.logo %},"publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":{{ site.url | append: site.logo | jsonify }}}}{% endif %},"url":{{ canonical | jsonify }}}</script>\n<!-- End Jekyll SEO tag -->\n';
|
|
1908
|
+
var JEKYLL_REDIRECT_PAGE = `{%- comment -%} jekyll-redirect-from writes the new URL whole: site.url in front of a path. {%- endcomment -%}
|
|
1909
|
+
{%- assign to = redirect.to -%}{%- unless to contains "://" -%}{%- assign to = site.url | append: redirect.to -%}{%- endunless -%}
|
|
1910
|
+
<!DOCTYPE html>
|
|
1911
|
+
<html lang="en-US">
|
|
1912
|
+
<meta charset="utf-8">
|
|
1913
|
+
<title>Redirecting…</title>
|
|
1914
|
+
<link rel="canonical" href="{{ to }}">
|
|
1915
|
+
<script>location="{{ to }}"</script>
|
|
1916
|
+
<meta http-equiv="refresh" content="0; url={{ to }}">
|
|
1917
|
+
<meta name="robots" content="noindex">
|
|
1918
|
+
<h1>Redirecting…</h1>
|
|
1919
|
+
<a href="{{ to }}">Click here if you are not redirected.</a>
|
|
1920
|
+
</html>
|
|
1921
|
+
`;
|
|
1922
|
+
var JEKYLL_REDIRECTS_JSON = `---
|
|
1923
|
+
permalink: /redirects.json
|
|
1924
|
+
excludeFromCollections: true
|
|
1925
|
+
---
|
|
1926
|
+
{%- comment -%} jekyll-redirect-from's redirects.json: each old URL and the new one. {%- endcomment -%}
|
|
1927
|
+
{%- assign docs = collections.all | sort: "inputPath" -%}
|
|
1928
|
+
{%- assign first = true -%}
|
|
1929
|
+
{ {%- for doc in docs -%}{%- for from in doc.data.aliases -%}{%- unless first %},{% endunless -%}{{ from | jsonify }}:{{ site.url | append: doc.url | jsonify }}{%- assign first = false -%}{%- endfor -%}{%- endfor -%} }`;
|
|
1930
|
+
var JEKYLL_ROBOTS = `---
|
|
1931
|
+
permalink: /robots.txt
|
|
1932
|
+
excludeFromCollections: true
|
|
1933
|
+
---
|
|
1934
|
+
Sitemap: {{ site.url }}/sitemap.xml
|
|
1935
|
+
`;
|
|
1936
|
+
var ROUGE_FENCE = `<div class="language-{% if fence.lang != "" %}{{ fence.lang }}{% else %}plaintext{% endif %} highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{{ fence.code | escape }}</code></pre></div></div>`;
|
|
1937
|
+
var GITHUB_PAGES_PLUGINS = ["jekyll-github-metadata", "jekyll-relative-links", "jekyll-optional-front-matter", "jekyll-titles-from-headings", "jekyll-default-layout", "jekyll-readme-index"];
|
|
1938
|
+
function jekyllPermalink(pattern, folder) {
|
|
1939
|
+
const styles = {
|
|
1940
|
+
date: "/:categories/:year/:month/:day/:title:output_ext",
|
|
1941
|
+
pretty: "/:categories/:year/:month/:day/:title/",
|
|
1942
|
+
ordinal: "/:categories/:year/:y_day/:title:output_ext",
|
|
1943
|
+
none: "/:categories/:title:output_ext"
|
|
1944
|
+
};
|
|
1945
|
+
const p = styles[pattern] ?? pattern;
|
|
1946
|
+
const strip = folder === "" ? "" : ` | remove_first: '/${folder}'`;
|
|
1947
|
+
const parts = {
|
|
1948
|
+
":year": "{{ page.date | date: '%Y' }}",
|
|
1949
|
+
":month": "{{ page.date | date: '%m' }}",
|
|
1950
|
+
":day": "{{ page.date | date: '%d' }}",
|
|
1951
|
+
":i_month": "{{ page.date | date: '%-m' }}",
|
|
1952
|
+
":i_day": "{{ page.date | date: '%-d' }}",
|
|
1953
|
+
":short_year": "{{ page.date | date: '%y' }}",
|
|
1954
|
+
":y_day": "{{ page.date | date: '%j' }}",
|
|
1955
|
+
":title": "{{ page.fileSlug }}",
|
|
1956
|
+
":name": "{{ page.fileSlug }}",
|
|
1957
|
+
":slug": "{{ page.fileSlug }}",
|
|
1958
|
+
":path": `{{ page.filePathStem${strip} }}`,
|
|
1959
|
+
":collection": folder.replace(/^_/, ""),
|
|
1960
|
+
":output_ext": ".html",
|
|
1961
|
+
":categories": "{% if categories %}/{{ categories | join: '/' | downcase }}{% endif %}"
|
|
1962
|
+
};
|
|
1963
|
+
let unknown = false;
|
|
1964
|
+
const out = p.replace(/:[a-z_]+/g, (m) => {
|
|
1965
|
+
if (Object.hasOwn(parts, m)) return parts[m];
|
|
1966
|
+
unknown = true;
|
|
1967
|
+
return m;
|
|
1968
|
+
});
|
|
1969
|
+
if (unknown) return void 0;
|
|
1970
|
+
const stem = "{{ page.filePathStem";
|
|
1971
|
+
let joined = out;
|
|
1972
|
+
while (joined.includes(`/${stem}`)) joined = joined.replace(`/${stem}`, stem);
|
|
1973
|
+
return joined.replace(/^\/(\{% if categories %\})/, "$1").replace(/\/\.html$/, "/index.html");
|
|
1974
|
+
}
|
|
1975
|
+
function jekyllTemplateNotes(text, lists) {
|
|
1976
|
+
const notes = [];
|
|
1977
|
+
const tags = [...text.matchAll(/\{\{[^}]*?\}\}|\{%[^%]*?%\}/g)].map((m) => m[0]);
|
|
1978
|
+
const pageKeys = /* @__PURE__ */ new Map();
|
|
1979
|
+
for (const tag of tags) for (const m of tag.matchAll(/(?<![\w.])page\.([A-Za-z_][\w-]*)/g)) if (Object.hasOwn(JEKYLL_PAGE, m[1])) pageKeys.set(m[1], (pageKeys.get(m[1]) ?? 0) + 1);
|
|
1980
|
+
for (const [key, n] of pageKeys) notes.push(`\`page.${key}\` (${n}): ${JEKYLL_PAGE[key]}`);
|
|
1981
|
+
const list = new RegExp(`(?:site|collections)\\.(?:${lists.join("|")})\\b`);
|
|
1982
|
+
if (tags.some((t) => /\.excerpt\b/.test(t))) notes.push("`excerpt` isn't Jekyll's: Jekyll's is the source up to `excerpt_separator` (the first blank line), rendered; ssqch's is the page up to `<!-- more -->`, or else its first paragraph. They differ when a page starts with something else than a paragraph");
|
|
1983
|
+
for (const tag of tags) {
|
|
1984
|
+
const sorted = /\|\s*(sort(?:_natural)?)\s*:\s*(["'])([A-Za-z_][\w-]*)\2/.exec(tag);
|
|
1985
|
+
if (sorted && list.test(tag)) notes.push(`\`${sorted[1]}: ${sorted[2]}${sorted[3]}${sorted[2]}\` on a collection: Jekyll's \`sort\` puts the items without \`${sorted[3]}\` first, ssqch's (Liquid's) last; with some missing it, sort them in the config, or a filter of your own`);
|
|
1986
|
+
}
|
|
1987
|
+
return [...new Set(notes)];
|
|
1988
|
+
}
|
|
1989
|
+
function jekyll(dir) {
|
|
1990
|
+
const configFile = ["_config.yml", "_config.yaml", "_config.toml"].find((f) => isFile(path.join(dir, f)));
|
|
1991
|
+
if (configFile === void 0) fail(`there's no _config.yml in ${dir}: is this the Jekyll site's folder?`);
|
|
1992
|
+
const configText = readStrict(path.join(dir, configFile));
|
|
1993
|
+
let config = {};
|
|
1994
|
+
try {
|
|
1995
|
+
config = configFile.endsWith(".toml") ? readToml(configText) : parseYaml(configText);
|
|
1996
|
+
} catch (e) {
|
|
1997
|
+
fail(`${configFile}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1998
|
+
}
|
|
1999
|
+
const plan = { from: "Jekyll", renames: [], edits: [], newFiles: [], byHand: [] };
|
|
2000
|
+
const list = (key) => Array.isArray(config[key]) ? config[key].filter((v) => typeof v === "string") : [];
|
|
2001
|
+
const layoutsDir = typeof config.layouts_dir === "string" ? config.layouts_dir : "_layouts";
|
|
2002
|
+
const includesDir = typeof config.includes_dir === "string" ? config.includes_dir : "_includes";
|
|
2003
|
+
const dataDir = typeof config.data_dir === "string" ? config.data_dir : "_data";
|
|
2004
|
+
const output = typeof config.destination === "string" ? config.destination.replace(/^\.\//, "") : "_site";
|
|
2005
|
+
const collections = isPlainObject(config.collections) ? config.collections : Array.isArray(config.collections) ? Object.fromEntries(config.collections.map((c) => [String(c), {}])) : {};
|
|
2006
|
+
const collectionsDir = typeof config.collections_dir === "string" ? config.collections_dir.replace(/\/$/, "") : "";
|
|
2007
|
+
const excluded = [...JEKYLL_EXCLUDES, ...list("exclude")];
|
|
2008
|
+
const included = new Set(list("include"));
|
|
2009
|
+
const isExcluded = (rel) => excluded.some((e) => {
|
|
2010
|
+
const glob = e.replace(/^\.\//, "").replace(/\/$/, "");
|
|
2011
|
+
return rel === glob || rel.startsWith(`${glob}/`) || glob.includes("*") && new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(/\u0000/g, ".*")}$`).test(rel);
|
|
2012
|
+
});
|
|
2013
|
+
const special = /* @__PURE__ */ new Set([layoutsDir, includesDir, dataDir, "_posts", "_drafts", "_sass", ...Object.keys(collections).map((c) => collectionsDir ? `${collectionsDir}/_${c}` : `_${c}`)]);
|
|
2014
|
+
const entries = walk(dir, (name, rel) => rel === output || name === ".git" || name === "node_modules" || name === ".cache" || isExcluded(rel) || (name.startsWith(".") || name.startsWith("_")) && !included.has(name) && !special.has(rel) && name !== "_posts" && name !== "_drafts" && !(collectionsDir && rel === collectionsDir), true);
|
|
2015
|
+
const collectionList = Object.keys(collections);
|
|
2016
|
+
const tags = /* @__PURE__ */ new Map();
|
|
2017
|
+
let markdownAttr = 0, ial = 0, seo = 0;
|
|
2018
|
+
const hasFrontMatter = (text) => /^---\s*\r?\n/.test(text);
|
|
2019
|
+
const statics = [];
|
|
2020
|
+
const frontMatterOther = [];
|
|
2021
|
+
for (const entry of entries) {
|
|
2022
|
+
if (!entry.isFile) continue;
|
|
2023
|
+
const ext = asciiLower(extensionOf(entry.name));
|
|
2024
|
+
const text = readUtf8(entry.abs);
|
|
2025
|
+
const templateDir = entry.rel.startsWith(`${layoutsDir}/`) || entry.rel.startsWith(`${includesDir}/`);
|
|
2026
|
+
if (entry.rel.startsWith(`${dataDir}/`) || entry.rel.startsWith("_sass/")) continue;
|
|
2027
|
+
const front2 = text !== void 0 && hasFrontMatter(text);
|
|
2028
|
+
if (!templateDir && !front2) {
|
|
2029
|
+
if (!["md", "markdown"].includes(ext)) statics.push(entry.rel);
|
|
2030
|
+
continue;
|
|
2031
|
+
}
|
|
2032
|
+
if (text === void 0) continue;
|
|
2033
|
+
if (front2 && !["md", "markdown", "html", "liquid", "scss", "sass"].includes(ext)) frontMatterOther.push(entry.rel);
|
|
2034
|
+
if (!(templateDir || front2) || ["scss", "sass"].includes(ext)) continue;
|
|
2035
|
+
let next = text;
|
|
2036
|
+
let changes = [];
|
|
2037
|
+
const left2 = jekyllTemplateNotes(text, ["posts", ...collectionList]);
|
|
2038
|
+
if (/\{%-?\s*seo\b[^%]*%\}/.test(next)) {
|
|
2039
|
+
next = next.replace(/\{%(-?)\s*seo\b[^%]*?(-?)%\}/g, "{%$1 include seo.liquid $2%}");
|
|
2040
|
+
changes = [...changes, "{% seo %} -> {% include seo.liquid %}"];
|
|
2041
|
+
}
|
|
2042
|
+
if (changes.length) plan.edits.push([entry.rel, changes, next]);
|
|
2043
|
+
for (const what of left2) plan.byHand.push([entry.rel, what]);
|
|
2044
|
+
for (const m of text.matchAll(/\{%-?\s*([a-z_][\w-]*)/g)) {
|
|
2045
|
+
const name = m[1];
|
|
2046
|
+
if (LIQUID_TAGS.has(name) || name.startsWith("end")) continue;
|
|
2047
|
+
if (name === "seo") seo++;
|
|
2048
|
+
const had = tags.get(name);
|
|
2049
|
+
tags.set(name, had ? [had[0] + 1, had[1]] : [1, `${entry.rel}:${occurrences(text.slice(0, m.index), "\n") + 1}`]);
|
|
2050
|
+
}
|
|
2051
|
+
if (["md", "markdown"].includes(ext)) {
|
|
2052
|
+
markdownAttr += (text.match(/\smarkdown\s*=\s*["']?(?:1|block|span)/g) ?? []).length;
|
|
2053
|
+
ial += (text.match(/\{:\s*[.#][^}]*\}/g) ?? []).length;
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
if (seo) {
|
|
2057
|
+
if (isFile(path.join(dir, includesDir, "seo.liquid"))) plan.newFiles.push([`${includesDir}/seo.liquid`, "jekyll-seo-tag's tags, for `{% seo %}`", ""]);
|
|
2058
|
+
else {
|
|
2059
|
+
const lock = readUtf8(path.join(dir, "Gemfile.lock")) ?? "";
|
|
2060
|
+
const version = /^\s{4}jekyll \(([\d.]+)\)$/m.exec(lock)?.[1];
|
|
2061
|
+
const include = version ? SEO_INCLUDE.replace("{{ ssqch.generator }}", `Jekyll v${version}`) : SEO_INCLUDE;
|
|
2062
|
+
plan.newFiles.push([`${includesDir}/seo.liquid`, `jekyll-seo-tag's tags, for \`{% seo %}\`${version ? `, with Jekyll v${version} as the generator (\`{{ ssqch.generator }}\` once the move is done)` : ""}: add the ones your site's options turn on (\`ssqch docs "From jekyll-seo-tag"\`)`, include]);
|
|
2063
|
+
}
|
|
2064
|
+
tags.delete("seo");
|
|
2065
|
+
}
|
|
2066
|
+
for (const [name, [n, at]] of [...tags].sort(([a], [b]) => compareText(a, b))) {
|
|
2067
|
+
plan.byHand.push([at, name === "seo" ? `\`{% seo %}\` (in ${n} ${n === 1 ? "place" : "places"}; this is the first): jekyll-seo-tag's tag becomes an include, \`{% include seo.liquid %}\`: \`ssqch docs "From jekyll-seo-tag"\` has one that writes its tags` : `\`{% ${name} %}\` (in ${n} ${n === 1 ? "place" : "places"}; this is the first) is a plugin's tag: a function in \`filters\` is a Liquid tag too (\`{% ${name} x %}\` calls \`${name}(x)\`), or an include`]);
|
|
2068
|
+
}
|
|
2069
|
+
if (ial) plan.byHand.push([".", `${ial} kramdown attribute lists (\`{: .class}\`): ssqch's Markdown doesn't read them, so they print as text. A \`{.class}\` on a heading works (\`## Title {#id .class}\`); for the others, HTML, or a container (\`::: name\`)`]);
|
|
2070
|
+
if (markdownAttr) plan.byHand.push([".", `${markdownAttr} \`markdown="1"\` elements: \`htmlMarkdown: "kramdown"\` (in the draft) reads them as kramdown does`]);
|
|
2071
|
+
const otherFormats = [...new Set(frontMatterOther.map((rel) => asciiLower(extensionOf(rel.split("/").pop()))))].sort(compareText);
|
|
2072
|
+
for (const rel of frontMatterOther) {
|
|
2073
|
+
const ext = asciiLower(extensionOf(rel.split("/").pop()));
|
|
2074
|
+
const at = plan.edits.findIndex(([file]) => file === rel);
|
|
2075
|
+
const text = at >= 0 ? plan.edits[at][2] : readUtf8(path.join(dir, ...rel.split("/")));
|
|
2076
|
+
if (text === void 0) continue;
|
|
2077
|
+
const fence = /^---[ \t]*\r?\n/.exec(text);
|
|
2078
|
+
const body = text.slice(fence[0].length);
|
|
2079
|
+
const has2 = (key) => new RegExp(`^${key}\\s*:`, "m").test(body.slice(0, Math.max(0, body.search(/^---[ \t]*$/m))));
|
|
2080
|
+
if (has2("render")) continue;
|
|
2081
|
+
const keys = [`render: liquid,${ext}`, ...has2("permalink") ? [] : [`permalink: "{{ page.filePathStem }}.${ext}"`]];
|
|
2082
|
+
const next = `${fence[0]}${keys.join("\n")}
|
|
2083
|
+
${body}`;
|
|
2084
|
+
const change = `front matter: render: liquid,${ext}${has2("permalink") ? "" : ", and a permalink that keeps its name"} (Jekyll rendered it)`;
|
|
2085
|
+
if (at >= 0) plan.edits[at] = [rel, [...plan.edits[at][1], change], next];
|
|
2086
|
+
else plan.edits.push([rel, [change], next]);
|
|
2087
|
+
}
|
|
2088
|
+
const defaults = Array.isArray(config.defaults) ? config.defaults.filter(isPlainObject) : [];
|
|
2089
|
+
const defaultsFor = (folder, type) => {
|
|
2090
|
+
const values = {};
|
|
2091
|
+
for (const d of defaults) {
|
|
2092
|
+
const scope = isPlainObject(d.scope) ? d.scope : {};
|
|
2093
|
+
const scopePath = typeof scope.path === "string" ? scope.path.replace(/^\.\//, "").replace(/\/$/, "") : "";
|
|
2094
|
+
if ((scopePath === "" || scopePath === folder) && (scope.type === void 0 || scope.type === type) && isPlainObject(d.values)) Object.assign(values, d.values);
|
|
2095
|
+
}
|
|
2096
|
+
return values;
|
|
2097
|
+
};
|
|
2098
|
+
const everyPage = {};
|
|
2099
|
+
const collectionNames = [];
|
|
2100
|
+
const directoryData = (folder, data, from) => {
|
|
2101
|
+
const name = `${folder}/${folder.split("/").pop()}.json`;
|
|
2102
|
+
const there = readUtf8(path.join(dir, ...name.split("/")));
|
|
2103
|
+
if (there !== void 0) {
|
|
2104
|
+
let same = false;
|
|
2105
|
+
try {
|
|
2106
|
+
same = JSON.stringify(sortedKeys(JSON.parse(there))) === JSON.stringify(sortedKeys(data));
|
|
2107
|
+
} catch {
|
|
2108
|
+
}
|
|
2109
|
+
if (!same) return plan.byHand.push([name, `it's there already, so ${from} wasn't written into it: ${JSON.stringify(data)}`]);
|
|
2110
|
+
}
|
|
2111
|
+
plan.newFiles.push([name, from, `${JSON.stringify(data, null, 2)}
|
|
2112
|
+
`]);
|
|
2113
|
+
};
|
|
2114
|
+
const postFolders = entries.filter((e) => !e.isFile && e.name === "_posts").map((e) => e.rel);
|
|
2115
|
+
for (const folder of postFolders) {
|
|
2116
|
+
const above = folder.split("/").slice(0, -1);
|
|
2117
|
+
let permalink = jekyllPermalink(typeof config.permalink === "string" ? config.permalink : "date", "");
|
|
2118
|
+
if (permalink && above.length) permalink = permalink.replace("{% if categories %}", `/${above.map((f) => f.toLowerCase()).join("/")}{% if categories %}`);
|
|
2119
|
+
const data = { tags: "posts", ...defaultsFor(folder, "posts") };
|
|
2120
|
+
if (permalink) data.permalink = permalink;
|
|
2121
|
+
else plan.byHand.push([configFile, `permalink: ${String(config.permalink)}: a placeholder ssqch can't write; give ${folder}/_posts.json a \`permalink\` of your own`]);
|
|
2122
|
+
directoryData(folder, data, `Jekyll's posts: the \`posts\` tag${permalink ? `, and the permalink${above.length ? ` (with ${above.join("/")} as categories)` : ""}` : ""}`);
|
|
2123
|
+
}
|
|
2124
|
+
if (postFolders.length) collectionNames.push("posts");
|
|
2125
|
+
if (isDir(path.join(dir, "_drafts"))) plan.byHand.push(["_drafts", "drafts: move them to `_posts` with `draft: true`, which `ssqch serve` builds and production builds leave out"]);
|
|
2126
|
+
for (const [name, settings] of Object.entries(collections)) {
|
|
2127
|
+
if (name === "posts") continue;
|
|
2128
|
+
const folder = collectionsDir ? `${collectionsDir}/_${name}` : `_${name}`;
|
|
2129
|
+
if (!isDir(path.join(dir, ...folder.split("/")))) continue;
|
|
2130
|
+
const s = isPlainObject(settings) ? settings : {};
|
|
2131
|
+
const data = { tags: name, ...defaultsFor(folder, name) };
|
|
2132
|
+
if (s.output === true) {
|
|
2133
|
+
const permalink = jekyllPermalink(typeof s.permalink === "string" ? s.permalink : "/:collection/:path/", folder);
|
|
2134
|
+
if (permalink) data.permalink = permalink;
|
|
2135
|
+
else plan.byHand.push([folder, `permalink: ${String(s.permalink)}: a placeholder ssqch can't write; give the folder's directory data a \`permalink\` of your own`]);
|
|
2136
|
+
} else data.permalink = false;
|
|
2137
|
+
directoryData(folder, data, `the \`${name}\` collection: its tag${s.output === true ? " and permalink" : ", and no pages (`output` isn't true)"}`);
|
|
2138
|
+
collectionNames.push(name);
|
|
2139
|
+
}
|
|
2140
|
+
for (const d of defaults) {
|
|
2141
|
+
const scope = isPlainObject(d.scope) ? d.scope : {};
|
|
2142
|
+
const folder = typeof scope.path === "string" ? scope.path.replace(/^\.\//, "").replace(/\/$/, "") : "";
|
|
2143
|
+
if (!isPlainObject(d.values)) continue;
|
|
2144
|
+
if (folder === "" && scope.type === void 0) Object.assign(everyPage, d.values);
|
|
2145
|
+
else if (folder === "") {
|
|
2146
|
+
if (scope.type !== "posts" && !Object.hasOwn(collections, String(scope.type))) plan.byHand.push([configFile, `defaults for \`type: ${String(scope.type)}\`: directory data in the folders those pages are in`]);
|
|
2147
|
+
} else if (!folder.includes("*") && folder !== "_posts" && !collectionNames.some((c) => folder === `_${c}` || folder === `${collectionsDir}/_${c}`) && isDir(path.join(dir, ...folder.split("/")))) directoryData(folder, { ...d.values }, `\`defaults\` for ${folder}`);
|
|
2148
|
+
else if (folder.includes("*")) plan.byHand.push([configFile, `defaults for \`${folder}\`: directory data in each folder it matches`]);
|
|
2149
|
+
}
|
|
2150
|
+
const tracked = spawnSync("git", ["-C", dir, "ls-files", "-z", "--others", "--exclude-standard"], { encoding: "utf8" });
|
|
2151
|
+
const untracked = tracked.status === 0 ? new Set(tracked.stdout.split("\0").filter(Boolean)) : /* @__PURE__ */ new Set();
|
|
2152
|
+
const left = statics.filter((rel) => untracked.has(rel) && !/^ssqch\.config\.[cm]?[jt]s$/.test(rel));
|
|
2153
|
+
if (left.length) {
|
|
2154
|
+
for (const rel of left) statics.splice(statics.indexOf(rel), 1);
|
|
2155
|
+
const folders = [...new Set(left.map((rel) => rel.includes("/") ? `${rel.slice(0, rel.indexOf("/"))}/` : rel))].sort(compareText);
|
|
2156
|
+
plan.byHand.push([folders[0], `${left.length} ${left.length === 1 ? "file" : "files"} git doesn't track (${folders.slice(0, 4).join(", ")}${folders.length > 4 ? ", ..." : ""}) left out of \`passthrough\`: Jekyll copied ${left.length === 1 ? "it" : "them"} from this folder, a fresh checkout wouldn't have ${left.length === 1 ? "it" : "them"}. Add ${left.length === 1 ? "it" : "them"} to git if ${left.length === 1 ? "it's" : "they're"} the site's`]);
|
|
2157
|
+
}
|
|
2158
|
+
const passthrough = [];
|
|
2159
|
+
const front = new Set(entries.filter((e) => e.isFile && !statics.includes(e.rel) && !untracked.has(e.rel)).map((e) => e.rel));
|
|
2160
|
+
const topLevel = /* @__PURE__ */ new Map();
|
|
2161
|
+
for (const rel of statics) {
|
|
2162
|
+
const top = rel.includes("/") ? rel.slice(0, rel.indexOf("/")) : "";
|
|
2163
|
+
if (top.startsWith("_")) continue;
|
|
2164
|
+
topLevel.set(top, [...topLevel.get(top) ?? [], rel]);
|
|
2165
|
+
}
|
|
2166
|
+
const copied = [];
|
|
2167
|
+
for (const [name, settings] of Object.entries(collections)) {
|
|
2168
|
+
const st = isPlainObject(settings) ? settings : {};
|
|
2169
|
+
if (st.output !== true) continue;
|
|
2170
|
+
const folder = collectionsDir ? `${collectionsDir}/_${name}` : `_${name}`;
|
|
2171
|
+
const pattern = typeof st.permalink === "string" ? st.permalink : "/:collection/:path/";
|
|
2172
|
+
const prefix = /^\/:path\b/.test(pattern) ? "" : `${name}/`;
|
|
2173
|
+
for (const e of entries) {
|
|
2174
|
+
if (!e.isFile || !e.rel.startsWith(`${folder}/`) || untracked.has(e.rel)) continue;
|
|
2175
|
+
const text = readUtf8(e.abs);
|
|
2176
|
+
if (text !== void 0 && hasFrontMatter(text)) continue;
|
|
2177
|
+
copied.push([e.rel, `${prefix}${e.rel.slice(folder.length + 1)}`]);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
const hidden = (rel) => {
|
|
2181
|
+
try {
|
|
2182
|
+
return fs.readdirSync(path.join(dir, ...rel.split("/")), { withFileTypes: true }).some((d) => d.name.startsWith("_") || d.name.startsWith(".") || d.isDirectory() && hidden(`${rel}/${d.name}`));
|
|
2183
|
+
} catch {
|
|
2184
|
+
return false;
|
|
2185
|
+
}
|
|
2186
|
+
};
|
|
2187
|
+
for (const [top, files] of [...topLevel].sort(([a], [b]) => compareText(a, b))) {
|
|
2188
|
+
const whole = top !== "" && ![...front].some((f) => f.startsWith(`${top}/`)) && !hidden(top);
|
|
2189
|
+
if (whole) passthrough.push(top);
|
|
2190
|
+
else {
|
|
2191
|
+
const sub = /* @__PURE__ */ new Map();
|
|
2192
|
+
for (const f of files) {
|
|
2193
|
+
const rest = top === "" ? f : f.slice(top.length + 1);
|
|
2194
|
+
const key = rest.includes("/") ? `${top === "" ? "" : `${top}/`}${rest.slice(0, rest.indexOf("/"))}` : f;
|
|
2195
|
+
sub.set(key, [...sub.get(key) ?? [], f]);
|
|
2196
|
+
}
|
|
2197
|
+
for (const [key] of [...sub].sort(([a], [b]) => compareText(a, b))) {
|
|
2198
|
+
if (key.includes("/") && !isFile(path.join(dir, ...key.split("/"))) && ([...front].some((f) => f.startsWith(`${key}/`)) || hidden(key))) for (const f of sub.get(key)) passthrough.push(f);
|
|
2199
|
+
else passthrough.push(key);
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
const ignores = [.../* @__PURE__ */ new Set([...list("exclude").map((e) => {
|
|
2204
|
+
const rel = e.replace(/^\.\//, "").replace(/\/$/, "");
|
|
2205
|
+
return !rel.includes("*") && isDir(path.join(dir, ...rel.split("/"))) ? `${rel}/**` : rel;
|
|
2206
|
+
}), "Gemfile", "Gemfile.lock"])];
|
|
2207
|
+
const gemfile = readUtf8(path.join(dir, "Gemfile")) ?? "";
|
|
2208
|
+
const named = /* @__PURE__ */ new Set([...list("plugins"), ...list("gems"), ...[...gemfile.matchAll(/^\s*gem\s+["']([^"']+)["']/gm)].map((m) => m[1])]);
|
|
2209
|
+
if (named.has("github-pages")) for (const p of GITHUB_PAGES_PLUGINS) named.add(p);
|
|
2210
|
+
const imports = ['import { defineConfig, readData } from "ssqch";'];
|
|
2211
|
+
const plugins = [];
|
|
2212
|
+
for (const name of [...named].sort(compareText)) {
|
|
2213
|
+
const known = JEKYLL_PLUGINS[name];
|
|
2214
|
+
if (!known) {
|
|
2215
|
+
if (name.startsWith("jekyll-") || name.startsWith("jekyll_")) plan.byHand.push(["Gemfile", `${name}: a plugin ssqch has no word for; what it adds to the output is a filter, a transform or a template of the site's`]);
|
|
2216
|
+
continue;
|
|
2217
|
+
}
|
|
2218
|
+
if (known.use) {
|
|
2219
|
+
imports.push(known.use[0]);
|
|
2220
|
+
plugins.push(known.use[1]);
|
|
2221
|
+
}
|
|
2222
|
+
if (name !== "jekyll-seo-tag" || seo === 0 && !isFile(path.join(dir, includesDir, "seo.liquid"))) plan.byHand.push(["Gemfile", `${name} -> ${known.say}`]);
|
|
2223
|
+
}
|
|
2224
|
+
const rouge = named.has("github-pages") || isPlainObject(config.kramdown) && isPlainObject(config.kramdown.syntax_highlighter_opts) && config.kramdown.syntax_highlighter_opts.default_lang !== void 0;
|
|
2225
|
+
if (rouge && !entries.some((e) => e.rel.startsWith(`${includesDir}/hooks/code.`))) {
|
|
2226
|
+
plan.newFiles.push([`${includesDir}/hooks/code.liquid`, "Rouge's classes on inline code, as GitHub Pages' kramdown wrote them", '<code class="language-plaintext highlighter-rouge">{{ code.code | escape }}</code>']);
|
|
2227
|
+
}
|
|
2228
|
+
if (rouge && !entries.some((e) => e.rel.startsWith(`${includesDir}/hooks/fence.`))) {
|
|
2229
|
+
plan.newFiles.push([`${includesDir}/hooks/fence.liquid`, "Rouge's wrapper for code blocks, as GitHub Pages' kramdown wrote it (the code itself isn't highlighted Rouge's way)", ROUGE_FENCE]);
|
|
2230
|
+
}
|
|
2231
|
+
const has = (rel) => entries.some((e) => e.rel === rel);
|
|
2232
|
+
if (named.has("jekyll-redirect-from") && !has("redirects.liquid") && !has("redirects.json")) plan.newFiles.push(["redirects.liquid", "jekyll-redirect-from's /redirects.json", JEKYLL_REDIRECTS_JSON]);
|
|
2233
|
+
if (named.has("jekyll-sitemap") && !has("robots.txt") && !has("robots.liquid")) plan.newFiles.push(["robots.liquid", "jekyll-sitemap's /robots.txt (the site has none)", JEKYLL_ROBOTS]);
|
|
2234
|
+
if (named.has("jekyll-redirect-from") && !entries.some((e) => e.rel.startsWith(`${includesDir}/hooks/redirect.`))) {
|
|
2235
|
+
plan.newFiles.push([`${includesDir}/hooks/redirect.liquid`, "jekyll-redirect-from's page for each old URL", JEKYLL_REDIRECT_PAGE]);
|
|
2236
|
+
}
|
|
2237
|
+
for (const e of entries) {
|
|
2238
|
+
if (!e.isFile || !e.rel.startsWith(`${layoutsDir}/`)) continue;
|
|
2239
|
+
const ext = asciiLower(extensionOf(e.name));
|
|
2240
|
+
if (["html", "liquid", "md", "markdown"].includes(ext)) continue;
|
|
2241
|
+
const to = e.rel.replace(/\.[^./]+$/, ".liquid");
|
|
2242
|
+
if (entries.some((o) => o.rel === to)) plan.byHand.push([e.rel, `a layout in .${ext}, which wouldn't run Liquid in ssqch; ${to} is there already, so rename it by hand`]);
|
|
2243
|
+
else plan.renames.push([e.rel, to]);
|
|
2244
|
+
}
|
|
2245
|
+
const pluginsDir = typeof config.plugins_dir === "string" ? config.plugins_dir : "_plugins";
|
|
2246
|
+
let pluginFiles = [];
|
|
2247
|
+
try {
|
|
2248
|
+
pluginFiles = fs.readdirSync(path.join(dir, pluginsDir)).filter((f) => f.endsWith(".rb")).sort(compareText);
|
|
2249
|
+
} catch {
|
|
2250
|
+
}
|
|
2251
|
+
for (const file of pluginFiles) {
|
|
2252
|
+
const ruby = readUtf8(path.join(dir, pluginsDir, file)) ?? "";
|
|
2253
|
+
const parts = [];
|
|
2254
|
+
if (/register_filter/.test(ruby)) {
|
|
2255
|
+
const filters = [...ruby.matchAll(/^\s*def\s+([a-z_][\w]*[?!]?)/gm)].map((m) => m[1]).filter((n) => !n.startsWith("self.") && n !== "initialize");
|
|
2256
|
+
parts.push(`filters ${filters.map((f) => `\`${f}\``).join(", ")}: functions in the config's \`filters\` (a function sees only its arguments, so pass what it read from \`@context\`, like \`page.lang\`)`);
|
|
2257
|
+
}
|
|
2258
|
+
for (const m of ruby.matchAll(/register_tag\(\s*["':]?([\w]+)["']?/g)) parts.push(`the tag \`{% ${m[1]} %}\`: a function in \`filters\` is a Liquid tag too, and returns its HTML`);
|
|
2259
|
+
for (const m of ruby.matchAll(/register_block\(\s*["':]?([\w]+)["']?/g)) parts.push(`the block \`{% ${m[1]} %}...{% end${m[1]} %}\`: a function in \`filters\` gets what's between them first`);
|
|
2260
|
+
if (/<\s*(?:Jekyll::)?Generator\b/.test(ruby)) parts.push("a generator (pages made from data): a collection of what to make, and one template with `pagination` over it, or a `.data.js` file");
|
|
2261
|
+
if (/<\s*(?:Jekyll::)?Page\b/.test(ruby) && !/<\s*(?:Jekyll::)?Generator\b/.test(ruby)) parts.push("pages of its own: a template with `pagination` over data");
|
|
2262
|
+
for (const m of ruby.matchAll(/Hooks\.register\s+:(\w+),\s*:(\w+)/g)) parts.push(`a \`${m[1]}\` \`${m[2]}\` hook: ${m[2] === "post_write" ? '`afterBuild` (a function, or `{ run: "..." }`)' : m[2].startsWith("pre") || m[2] === "post_read" || m[2] === "after_init" ? "`beforeBuild`, `computed` or a `.data.js` file" : "a transform (`transforms`) or `afterBuild`"}`);
|
|
2263
|
+
if (/<\s*(?:Jekyll::)?Converter\b/.test(ruby)) parts.push("a converter: an engine for its extension (`engines`)");
|
|
2264
|
+
plan.byHand.push([`${pluginsDir}/${file}`, `a Ruby plugin, which ssqch doesn't run: ${parts.length ? parts.join("; ") : "read it for what it adds to the output, then do that with a filter, a transform, a collection or `afterBuild`"}. "Porting a site's own plugins" in \`ssqch docs --from jekyll\` has a table of each kind`]);
|
|
2265
|
+
}
|
|
2266
|
+
if (named.has("github-pages")) plan.byHand.push(["Gemfile", "github-pages' default theme (jekyll-theme-primer) writes `/assets/css/style.css`: nothing in ssqch, so check whether a page links to it"]);
|
|
2267
|
+
const sass = isDir(path.join(dir, "_sass")) || entries.some((e) => e.isFile && /\.s[ac]ss$/.test(e.name) && front.has(e.rel));
|
|
2268
|
+
if (sass) {
|
|
2269
|
+
imports.push('import { sassPlugin } from "ssqch/sass";');
|
|
2270
|
+
const sources = entries.filter((e) => e.isFile && /\.s[ac]ss$/.test(e.name) && front.has(e.rel) && !e.rel.startsWith("_"));
|
|
2271
|
+
const files = sources.map((e) => `"${e.rel}": "/${e.rel.replace(/\.s[ac]ss$/, ".css")}"`);
|
|
2272
|
+
const loadPaths = isPlainObject(config.sass) && Array.isArray(config.sass.load_paths) ? config.sass.load_paths.map(String) : isDir(path.join(dir, "_sass")) ? ["_sass"] : [];
|
|
2273
|
+
plugins.push(`sassPlugin({ files: { ${files.join(", ")} }${loadPaths.length ? `, loadPaths: ${JSON.stringify(loadPaths)}` : ""}, charset: false })`);
|
|
2274
|
+
}
|
|
2275
|
+
const markdown = ['htmlMarkdown: "kramdown"', 'headingIds: "kramdown"', "smartPunctuation: true", "autolinks: false", "encodeUrls: false"];
|
|
2276
|
+
const kramdown = isPlainObject(config.kramdown) ? config.kramdown : {};
|
|
2277
|
+
if (kramdown.auto_ids === false) markdown[1] = "headingIds: false";
|
|
2278
|
+
if (kramdown.smart_quotes !== void 0 || kramdown.input === "GFM" && kramdown.hard_wrap === true) plan.byHand.push([configFile, "kramdown's `smart_quotes` or `hard_wrap`: check the draft's `markdown` against them (`breaks: true` for `hard_wrap`)"]);
|
|
2279
|
+
if (typeof config.markdown === "string" && !/kramdown/i.test(config.markdown)) plan.byHand.push([configFile, `markdown: ${config.markdown}: the draft's options are kramdown's; ssqch's Markdown is CommonMark with extensions (\`ssqch docs markdown\`)`]);
|
|
2280
|
+
let out = `// A first draft, written by \`ssqch scout\` from ${configFile}.
|
|
2281
|
+
// \`ssqch docs --from jekyll\` has the whole mapping.
|
|
2282
|
+
${[...new Set(imports)].join("\n")}
|
|
2283
|
+
|
|
2284
|
+
`;
|
|
2285
|
+
const cname = (readUtf8(path.join(dir, "CNAME")) ?? "").trim().split(/\s+/)[0];
|
|
2286
|
+
const urlFromCname = (typeof config.url !== "string" || config.url === "") && cname !== "" && (named.has("github-pages") || named.has("jekyll-github-metadata"));
|
|
2287
|
+
out += urlFromCname ? `// \`site.title\` and every other key of ${configFile} in templates read this. GitHub Pages gave
|
|
2288
|
+
// \`site.url\` from the CNAME (jekyll-github-metadata).
|
|
2289
|
+
const site = { ...readData(${JSON.stringify(configFile)}), url: ${JSON.stringify(`https://${cname}`)} };
|
|
2290
|
+
|
|
2291
|
+
export default defineConfig({
|
|
2292
|
+
` : `// \`site.title\` and every other key of ${configFile} in templates read this.
|
|
2293
|
+
const site = readData(${JSON.stringify(configFile)});
|
|
2294
|
+
|
|
2295
|
+
export default defineConfig({
|
|
2296
|
+
`;
|
|
2297
|
+
const builtIn = /* @__PURE__ */ new Set(["txt"]);
|
|
2298
|
+
out += ` // Markdown and HTML pages run through Liquid first, as in Jekyll.
|
|
2299
|
+
templateFormats: ${JSON.stringify(["liquid", "md", "html", ...otherFormats]).replaceAll(",", ", ")},
|
|
2300
|
+
markdownEngine: "liquid",
|
|
2301
|
+
htmlEngine: "liquid",
|
|
2302
|
+
`;
|
|
2303
|
+
const own = otherFormats.filter((e) => !builtIn.has(e));
|
|
2304
|
+
if (own.length) out += ` // Files with front matter that Jekyll rendered (their front matter puts Liquid first): the text as it is.
|
|
2305
|
+
engines: { ${own.map((e) => `${/^[a-z_]\w*$/.test(e) ? e : JSON.stringify(e)}: (text) => text`).join(", ")} },
|
|
2306
|
+
`;
|
|
2307
|
+
const dirs = [`layouts: ${JSON.stringify(layoutsDir)}`];
|
|
2308
|
+
if (includesDir !== "_includes") dirs.push(`includes: ${JSON.stringify(includesDir)}`);
|
|
2309
|
+
if (dataDir !== "_data") dirs.push(`data: ${JSON.stringify(dataDir)}`);
|
|
2310
|
+
if (output !== "_site") dirs.push(`output: ${JSON.stringify(output)}`);
|
|
2311
|
+
out += ` dirs: { ${dirs.join(", ")} },
|
|
2312
|
+
`;
|
|
2313
|
+
out += " // Jekyll drops the blank lines after the closing `---`.\n trimAfterFrontMatter: true,\n";
|
|
2314
|
+
out += " // Templates see Jekyll's `page` (front matter too: `page.title`) and `site` (`site.posts`,\n // each collection, `site.data`, `site.categories`), so the layouts and includes run as written.\n jekyllTemplates: true,\n";
|
|
2315
|
+
out += ` // kramdown's habits: markdown="1", its heading ids, smart quotes, no bare-URL links, URLs as written.
|
|
2316
|
+
markdown: { ${markdown.join(", ")} },
|
|
2317
|
+
`;
|
|
2318
|
+
out += ` // ${configFile}'s \`exclude\`, and what Jekyll leaves out by itself.
|
|
2319
|
+
ignore: [${ignores.map((g) => JSON.stringify(g)).join(", ")}],
|
|
2320
|
+
`;
|
|
2321
|
+
const passed = [...passthrough.map((p) => JSON.stringify(p)), ...copied.map(([from, to]) => `{ ${JSON.stringify(from)}: ${JSON.stringify(to)} }`)];
|
|
2322
|
+
if (passed.length) out += ` // What Jekyll copied as it is: files without front matter.
|
|
2323
|
+
passthrough: [${passed.join(", ")}],
|
|
2324
|
+
`;
|
|
2325
|
+
const pageDefaults = Object.entries(everyPage).map(([k, v]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${JSON.stringify(v)}`);
|
|
2326
|
+
out += pageDefaults.length ? ` // ${configFile}'s \`defaults\` for every page.
|
|
2327
|
+
data: { site, ${pageDefaults.join(", ")} },
|
|
2328
|
+
` : " data: { site },\n";
|
|
2329
|
+
out += ` filters: {
|
|
2330
|
+
// Plugins' tags and filters go here: name: (...args) => result
|
|
2331
|
+
},
|
|
2332
|
+
plugins: [${plugins.join(", ")}],
|
|
2333
|
+
});
|
|
2334
|
+
`;
|
|
2335
|
+
plan.newFiles.unshift(["ssqch.config.js", `a first draft, from ${configFile}`, out]);
|
|
2336
|
+
if (!isFile(path.join(dir, "package.json"))) plan.byHand.push([".", "no package.json: `npm init -y && npm install -D ssqch` pins the version the site builds with"]);
|
|
2337
|
+
if (typeof config.url === "string" && config.url !== "" && !config.url.startsWith("http")) plan.byHand.push([configFile, `url: ${config.url}: the site's address starts with https://`]);
|
|
2338
|
+
return plan;
|
|
2339
|
+
}
|
|
2340
|
+
function zola(dir) {
|
|
2341
|
+
const configPath = path.join(dir, "config.toml");
|
|
2342
|
+
if (!isFile(configPath)) fail(`there's no config.toml in ${dir}: is this the Zola site's folder?`);
|
|
2343
|
+
const configText = readStrict(configPath);
|
|
2344
|
+
let config = {};
|
|
2345
|
+
try {
|
|
2346
|
+
config = readToml(configText);
|
|
2347
|
+
} catch (e) {
|
|
2348
|
+
fail(`config.toml: ${tomlError(e, configText)}`);
|
|
2349
|
+
}
|
|
2350
|
+
const plan = { from: "Zola", renames: [], edits: [], newFiles: [], byHand: [] };
|
|
2351
|
+
const sections = [];
|
|
2352
|
+
const shortcodes = /* @__PURE__ */ new Set();
|
|
2353
|
+
let aliases = false, bundles = false;
|
|
2354
|
+
for (const entry of walk(path.join(dir, "content"), () => false, false)) {
|
|
2355
|
+
if (!entry.isFile || extensionOf(entry.name) !== "md") continue;
|
|
2356
|
+
const rel = `content/${entry.rel}`;
|
|
2357
|
+
const text2 = readUtf8(entry.abs);
|
|
2358
|
+
if (text2 === void 0) continue;
|
|
2359
|
+
if (entry.name === "_index.md") {
|
|
2360
|
+
sections.push(rel);
|
|
2361
|
+
continue;
|
|
2362
|
+
}
|
|
2363
|
+
if (entry.name === "index.md") {
|
|
2364
|
+
let count = 0;
|
|
2365
|
+
try {
|
|
2366
|
+
count = fs.readdirSync(path.dirname(entry.abs)).length;
|
|
2367
|
+
} catch {
|
|
2368
|
+
}
|
|
2369
|
+
if (count > 1) bundles = true;
|
|
2370
|
+
}
|
|
2371
|
+
aliases ||= text2.includes("\naliases");
|
|
2372
|
+
for (const c of text2.matchAll(SHORTCODE_CALL)) shortcodes.add(c[1]);
|
|
2373
|
+
if (text2.startsWith("---") && text2.includes("taxonomies:")) plan.byHand.push([rel, "YAML front matter with `taxonomies`: move `tags` to the top level"]);
|
|
2374
|
+
const [next, changes] = rewriteZolaFrontMatter(text2);
|
|
2375
|
+
if (changes.length) plan.edits.push([rel, changes, next]);
|
|
2376
|
+
}
|
|
2377
|
+
for (const section of sections) {
|
|
2378
|
+
let folder = section;
|
|
2379
|
+
while (folder.endsWith("/_index.md")) folder = folder.slice(0, -"/_index.md".length);
|
|
2380
|
+
const name = folder.split("/").pop();
|
|
2381
|
+
plan.byHand.push([section, `a section: its settings (\`sort_by\`, \`paginate_by\`, \`page_template\`) become directory data (${folder}/${name}.json: \`layout\`, \`tags\`, \`permalink\`) and an index page that lists the folder's pages`]);
|
|
2382
|
+
}
|
|
2383
|
+
for (const name of [...shortcodes].sort(compareText)) {
|
|
2384
|
+
const shortcode = (ext) => isFile(path.join(dir, "templates", "shortcodes", `${name}.${ext}`));
|
|
2385
|
+
if (shortcode("html") || shortcode("md")) plan.byHand.push([`templates/shortcodes/${name}.html`, `a shortcode used in content: make it a config filter (\`filters: { ${name}: ... }\`) or a macro; a body shortcode (\`{% ${name}() %}...{% end %}\`) becomes a \`::: ${name}\` container`]);
|
|
2386
|
+
}
|
|
2387
|
+
const tera = /* @__PURE__ */ new Map();
|
|
2388
|
+
let templateCount = 0;
|
|
2389
|
+
for (const entry of walk(path.join(dir, "templates"), () => false, false)) {
|
|
2390
|
+
if (!entry.isFile) continue;
|
|
2391
|
+
const text2 = readUtf8(entry.abs);
|
|
2392
|
+
if (text2 === void 0) continue;
|
|
2393
|
+
templateCount++;
|
|
2394
|
+
const count = (what, n) => {
|
|
2395
|
+
if (n > 0) tera.set(what, (tera.get(what) ?? 0) + n);
|
|
2396
|
+
};
|
|
2397
|
+
count("Tera functions (get_url, get_section, load_data, resize_image...): filters or data in the config", text2.match(TERA_CALLS)?.length ?? 0);
|
|
2398
|
+
count('filters with named arguments (`| date(format="%Y")`): positional in ssqch (`| dateformat("%Y")`)', text2.match(NAMED_ARGUMENT)?.length ?? 0);
|
|
2399
|
+
count("`page.content`, `section.content`: `content` in a layout", occurrences(text2, "page.content") + occurrences(text2, "section.content"));
|
|
2400
|
+
count("`section.pages`, `paginator.pages`: a collection (`collections.<tag>`), and `pagination.items`", occurrences(text2, "section.pages") + occurrences(text2, "paginator."));
|
|
2401
|
+
count("`page.title`, `page.extra`, `page.taxonomies`: front matter is at the top level (`title`, `extra`, `tags`)", occurrences(text2, "page.title") + occurrences(text2, "page.extra") + occurrences(text2, "page.taxonomies"));
|
|
2402
|
+
count("`page.permalink`: `page.url`", occurrences(text2, "page.permalink") + Math.max(0, occurrences(text2, ".permalink") - occurrences(text2, "page.permalink")));
|
|
2403
|
+
}
|
|
2404
|
+
if (templateCount > 0) {
|
|
2405
|
+
plan.byHand.push(["templates/", `${templateCount} Tera templates: they run as Jinja (\`htmlEngine: "jinja"\` in the draft config), and these need changing:`]);
|
|
2406
|
+
for (const [what, n] of [...tera].sort(([a], [b]) => compareText(a, b))) plan.byHand.push(["templates/", `${n} x ${what}`]);
|
|
2407
|
+
}
|
|
2408
|
+
const text = (key) => typeof config[key] === "string" ? config[key] : void 0;
|
|
2409
|
+
const flag = (key) => config[key] === true || isPlainObject(config.markdown) && config.markdown[key] === true;
|
|
2410
|
+
const baseUrl = text("base_url") ?? "";
|
|
2411
|
+
const site = {};
|
|
2412
|
+
for (const key of ["base_url", "title", "description", "default_language"]) {
|
|
2413
|
+
const value = text(key);
|
|
2414
|
+
if (value !== void 0) site[key] = value;
|
|
2415
|
+
}
|
|
2416
|
+
if (config.extra !== void 0) site.extra = sortedKeys(config.extra);
|
|
2417
|
+
const imports = ['import { defineConfig } from "ssqch";', 'import { linksPlugin } from "ssqch/links";'];
|
|
2418
|
+
const plugins = [];
|
|
2419
|
+
if (baseUrl.startsWith("http")) {
|
|
2420
|
+
imports.push('import { sitemapPlugin } from "ssqch/sitemap";');
|
|
2421
|
+
plugins.push(`sitemapPlugin({ url: ${JSON.stringify(baseUrl)} })`);
|
|
2422
|
+
}
|
|
2423
|
+
if (aliases) {
|
|
2424
|
+
imports.push('import { redirectsPlugin } from "ssqch/redirects";');
|
|
2425
|
+
plugins.push("redirectsPlugin()");
|
|
2426
|
+
}
|
|
2427
|
+
if (flag("compile_sass") && isDir(path.join(dir, "sass"))) {
|
|
2428
|
+
imports.push('import { sassPlugin } from "ssqch/sass";');
|
|
2429
|
+
plugins.push('sassPlugin({ files: { sass: "/" } })');
|
|
2430
|
+
}
|
|
2431
|
+
plugins.push("linksPlugin()");
|
|
2432
|
+
const markdown = ['headingIds: "ascii"'];
|
|
2433
|
+
if (flag("highlight_code")) markdown.push("highlight: true");
|
|
2434
|
+
if (flag("smart_punctuation")) markdown.push("smartPunctuation: true");
|
|
2435
|
+
let out = `// A first draft, written by \`ssqch scout\` from config.toml.
|
|
2436
|
+
// \`ssqch docs --from zola\` has the whole mapping.
|
|
2437
|
+
${imports.join("\n")}
|
|
2438
|
+
|
|
2439
|
+
export default defineConfig({
|
|
2440
|
+
`;
|
|
2441
|
+
out += ` dirs: { input: "content", output: ${JSON.stringify(text("output_dir") ?? "public")}, includes: "../templates" },
|
|
2442
|
+
`;
|
|
2443
|
+
out += ' // Tera templates are close to Jinja: Markdown and the .html templates run through it.\n templateFormats: ["md"],\n markdownEngine: "jinja",\n htmlEngine: "jinja",\n';
|
|
2444
|
+
if (sections.length) out += ' // Section files: their settings go in directory data (see the list `ssqch scout` printed).\n ignore: ["**/_index.md"],\n';
|
|
2445
|
+
if (bundles) out += " // Pages that are a folder (`post/index.md`) keep the files next to them.\n bundles: true,\n";
|
|
2446
|
+
out += ` markdown: { ${markdown.join(", ")} },
|
|
2447
|
+
`;
|
|
2448
|
+
if (isDir(path.join(dir, "static"))) out += ' passthrough: [{ static: "." }],\n';
|
|
2449
|
+
out += ` // \`config.title\` and \`config.extra.*\` in templates read this.
|
|
2450
|
+
data: {
|
|
2451
|
+
config: ${JSON.stringify(site, null, 2).replaceAll("\n", "\n ")},
|
|
2452
|
+
},
|
|
2453
|
+
`;
|
|
2454
|
+
out += ` filters: {
|
|
2455
|
+
// Port shortcodes and Tera functions here: name: (...args) => result
|
|
2456
|
+
},
|
|
2457
|
+
plugins: [${plugins.join(", ")}],
|
|
2458
|
+
});
|
|
2459
|
+
`;
|
|
2460
|
+
if (config.taxonomies !== void 0) plan.byHand.push(["config.toml", "taxonomies: tags are built in (`collections.<tag>`); tag pages are a template paginated over the tags (the `blog-tags` example), and other taxonomies are custom `collections`"]);
|
|
2461
|
+
if (flag("build_search_index")) plan.byHand.push(["config.toml", 'build_search_index: Pagefind after the build (`afterBuild: { run: "npx -y pagefind --site public" }`)']);
|
|
2462
|
+
if (flag("generate_feeds") || flag("generate_feed")) plan.byHand.push(["config.toml", "generate_feeds: a feed template with `rssPlugin()`'s filters (the `blog-tags` example has one)"]);
|
|
2463
|
+
plan.newFiles.push(["ssqch.config.js", "a first draft, from config.toml", out]);
|
|
2464
|
+
return plan;
|
|
2465
|
+
}
|
|
2466
|
+
var lineAt = (entry, text, index) => `${entry.rel}:${occurrences(text.slice(0, index), "\n") + 1}`;
|
|
2467
|
+
var Tally = class {
|
|
2468
|
+
seen = /* @__PURE__ */ new Map();
|
|
2469
|
+
add(name, entry, text, index) {
|
|
2470
|
+
const known = this.seen.get(name);
|
|
2471
|
+
if (known) {
|
|
2472
|
+
known.count++;
|
|
2473
|
+
known.files.add(entry.rel);
|
|
2474
|
+
return;
|
|
2475
|
+
}
|
|
2476
|
+
this.seen.set(name, { count: 1, files: /* @__PURE__ */ new Set([entry.rel]), first: lineAt(entry, text, index) });
|
|
2477
|
+
}
|
|
2478
|
+
/** Most used first, then by name. */
|
|
2479
|
+
sorted() {
|
|
2480
|
+
return [...this.seen].sort((a, b) => b[1].count - a[1].count || compareText(a[0], b[0]));
|
|
2481
|
+
}
|
|
2482
|
+
};
|
|
2483
|
+
var uses = (count, files) => `${count} ${count === 1 ? "use" : "uses"} in ${files} ${files === 1 ? "file" : "files"}; this is the first`;
|
|
2484
|
+
var HUGO_SHORTCODE = /\{\{([<%])\s*(?!\/)([\w./-]+)/g;
|
|
2485
|
+
var HUGO_BUILT_IN_SHORTCODES = /* @__PURE__ */ new Set(["details", "figure", "gist", "highlight", "instagram", "param", "qr", "ref", "relref", "vimeo", "x", "twitter", "youtube"]);
|
|
2486
|
+
var HUGO_HOOKS = { heading: "heading", link: "link", image: "image", codeblock: "fence" };
|
|
2487
|
+
var HUGO_FUNCTIONS = [
|
|
2488
|
+
[/\.GetPage\b/, "`.GetPage`: not in ssqch yet as a function; a collection, or `collections.all` filtered by `url`, finds a page", "hugo-getpage", "not-yet"],
|
|
2489
|
+
[/\bjs\.Build\b/, "`js.Build` (esbuild): ssqch bundles scripts with `ssqch/assets`, or keep esbuild as a `beforeBuild` step", "hugo-js-build", "ssqch"],
|
|
2490
|
+
[/\bcss\.TailwindCSS\b/, "`css.TailwindCSS`: run Tailwind's CLI as a `beforeBuild` step (`ssqch docs beforeBuild`)", "hugo-tailwind", "ssqch"],
|
|
2491
|
+
[/\b(?:toCSS|css\.Sass)\b/, 'Sass (`toCSS`, `css.Sass`): ssqch compiles Sass with `sassPlugin()` from "ssqch/sass"', "hugo-sass", "ssqch"],
|
|
2492
|
+
[/\|\s*fingerprint\b|\bresources\.Fingerprint\b/, "`fingerprint`: ssqch's is `assetsPlugin({ fingerprint: true })` (`ssqch docs fingerprint`)", "hugo-fingerprint", "ssqch"],
|
|
2493
|
+
[/\.(?:Resize|Fill|Fit|Crop)\s+"/, 'image processing (`.Resize`, `.Fill`): ssqch\'s is `imagePlugin()` from "ssqch/image"', "hugo-images", "ssqch"],
|
|
2494
|
+
[/\.Related\b/, "related content (`.Related`): not in ssqch yet; a filter of your own over a collection", "hugo-related", "not-yet"],
|
|
2495
|
+
[/\btransform\.Highlight\b|\bhighlight\s+\(/, "`transform.Highlight`: ssqch's highlighter is `highlight(code, lang)`, with Pygments' classes in the draft", "hugo-highlight", "ssqch"],
|
|
2496
|
+
[/\bi18n\b|\bT\s+"/, "translations (`i18n`, `T`): ssqch's are a filter over `_data` (`ssqch docs multilingual`)", "hugo-i18n", "ssqch"],
|
|
2497
|
+
[/\.Paginate\b|\.Paginator\b/, "`.Paginate`: ssqch's pagination is `pagination` in front matter (`ssqch docs pagination`)", "hugo-paginate", "ssqch"]
|
|
2498
|
+
];
|
|
2499
|
+
function readHugoConfig(dir) {
|
|
2500
|
+
for (const file of ["hugo.toml", "hugo.yaml", "hugo.yml", "hugo.json", "config.toml", "config/_default/hugo.toml", "config/_default/config.toml", "config/_default/hugo.yaml"]) {
|
|
2501
|
+
const text = readUtf8(path.join(dir, file));
|
|
2502
|
+
if (text === void 0) continue;
|
|
2503
|
+
try {
|
|
2504
|
+
const data = file.endsWith(".toml") ? readToml(text) : file.endsWith(".json") ? JSON.parse(text) : parseYaml(text);
|
|
2505
|
+
return [file, isPlainObject(data) ? data : {}];
|
|
2506
|
+
} catch (e) {
|
|
2507
|
+
return fail(`${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
return [void 0, {}];
|
|
2511
|
+
}
|
|
2512
|
+
var hugoKey = (config, key) => Object.entries(config).find(([k]) => k.toLowerCase() === key.toLowerCase())?.[1];
|
|
2513
|
+
function hugo(dir) {
|
|
2514
|
+
const plan = { from: "Hugo", renames: [], edits: [], newFiles: [], byHand: [] };
|
|
2515
|
+
const [configFile, config] = readHugoConfig(dir);
|
|
2516
|
+
const contentDir = typeof hugoKey(config, "contentDir") === "string" ? hugoKey(config, "contentDir") : "content";
|
|
2517
|
+
const output = typeof hugoKey(config, "publishDir") === "string" ? hugoKey(config, "publishDir") : "public";
|
|
2518
|
+
const entries = walk(dir, (name, rel) => name.startsWith(".git") || name === "node_modules" || name === ".cache" || rel === output || name === "resources" || rel === "_vendor", false);
|
|
2519
|
+
const inContent = new RegExp(`^${contentDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`);
|
|
2520
|
+
const content = entries.filter((e) => e.isFile && inContent.test(e.rel) && /\.(md|markdown|html)$/.test(e.name));
|
|
2521
|
+
plan.pages = content.length;
|
|
2522
|
+
const layouts = entries.filter((e) => e.isFile && /^(?:layouts|themes\/[^/]+\/layouts)\//.test(e.rel) && /\.(html|xml|json|txt)$/.test(e.name));
|
|
2523
|
+
const blockCalls = new Tally();
|
|
2524
|
+
const inlineCalls = new Tally();
|
|
2525
|
+
let sections = 0;
|
|
2526
|
+
let cascades = 0;
|
|
2527
|
+
let templated;
|
|
2528
|
+
let templatedCount = 0;
|
|
2529
|
+
for (const entry of content) {
|
|
2530
|
+
const text = readUtf8(entry.abs) ?? "";
|
|
2531
|
+
if (entry.name === "_index.md") sections++;
|
|
2532
|
+
if (/^cascade\s*:/m.test(text.slice(0, 4e3))) cascades++;
|
|
2533
|
+
for (const m of text.matchAll(HUGO_SHORTCODE)) {
|
|
2534
|
+
const lineStart = text.lastIndexOf("\n", m.index) + 1;
|
|
2535
|
+
const lineEnd = text.indexOf("\n", m.index);
|
|
2536
|
+
const line = text.slice(lineStart, lineEnd === -1 ? void 0 : lineEnd);
|
|
2537
|
+
(/^[ \t]*\{\{[<%][^\n]*[>%]\}\}[ \t]*$/.test(line) && (line.match(/\{\{[<%]/g) ?? []).length === 1 ? blockCalls : inlineCalls).add(m[2], entry, text, m.index);
|
|
2538
|
+
}
|
|
2539
|
+
const plain = text.replace(/\{\{[<%][\s\S]*?[%>]\}\}/g, "");
|
|
2540
|
+
if (/\{\{|\{%/.test(plain)) {
|
|
2541
|
+
templatedCount++;
|
|
2542
|
+
templated ??= lineAt(entry, plain, plain.search(/\{\{|\{%/));
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
const shortcodeFiles = new Map(entries.filter((e) => e.isFile && /(?:^|\/)layouts\/_?shortcodes\//.test(e.rel)).map((e) => [e.rel.replace(/^.*\/_?shortcodes\//, "").replace(/\.[^./]+$/, "").replace(/\.[^./]+$/, ""), e.rel]));
|
|
2546
|
+
const calls = blockCalls.sorted();
|
|
2547
|
+
if (calls.length || inlineCalls.seen.size) {
|
|
2548
|
+
const pages = new Set([...calls, ...inlineCalls.sorted()].flatMap(([, { files }]) => [...files])).size;
|
|
2549
|
+
plan.byHand.push([contentDir, `${(/* @__PURE__ */ new Set([...blockCalls.seen.keys(), ...inlineCalls.seen.keys()])).size} shortcodes, called in ${pages} ${pages === 1 ? "page" : "pages"}: \`markdown: { shortcodes: "hugo" }\` (in the draft) reads each call on a line of its own as a container, rendered by \`_includes/containers/<name>.*\`; the draft has a template to port for each of the site's own`, { code: "hugo-shortcodes", status: "option", files: pages, option: 'markdown: { shortcodes: "hugo" }', docs: "shortcodes" }]);
|
|
2550
|
+
}
|
|
2551
|
+
for (const [name, { count, files, first }] of calls) {
|
|
2552
|
+
const own = shortcodeFiles.get(name);
|
|
2553
|
+
const whose = own ? `the site's own (${own})` : HUGO_BUILT_IN_SHORTCODES.has(name) ? "Hugo's" : "nobody's (no template for it)";
|
|
2554
|
+
const draft = own && /^[\w-]+$/.test(name) ? `_includes/containers/${name}.jinja` : void 0;
|
|
2555
|
+
plan.byHand.push([first, `\`{{< ${name} >}}\`, ${whose} (${uses(count, files.size)}): a container${draft ? `; port its template into ${draft} (in the draft)` : `; write \`_includes/containers/${name}.jinja\``}`, { code: "hugo-shortcode", status: own ? "site" : "ssqch", count, files: files.size, docs: "containers" }]);
|
|
2556
|
+
if (draft) plan.newFiles.push([draft, `a container for the ${name} shortcode, to port from ${own}`, `{#- The ${name} shortcode (${own}), as a container: port its Go template here.
|
|
2557
|
+
container.args is what the call wrote after the name, container.props its named
|
|
2558
|
+
parameters (key="value"), and container.content the inside, rendered. -#}
|
|
2559
|
+
<div class="${name}">{{ container.content | safe }}</div>
|
|
2560
|
+
`]);
|
|
2561
|
+
}
|
|
2562
|
+
for (const [name, { count, files, first }] of inlineCalls.sorted()) plan.byHand.push([first, `\`{{< ${name} >}}\` inside a line of text (${uses(count, files.size)}): not in ssqch yet as written (only a shortcode on a line of its own is a container); a filter or an include, with \`markdownEngine\` on for those pages`, { code: "hugo-inline-shortcode", status: "not-yet", count, files: files.size }]);
|
|
2563
|
+
if (templated) plan.byHand.push([templated, `\`{{ }}\` or \`{% %}\` as text in ${templatedCount} ${templatedCount === 1 ? "page" : "pages"} (this is the first): Hugo prints them as they are, and so does ssqch with \`markdownEngine: false\` (in the draft)`, { code: "hugo-template-text", status: "option", files: templatedCount, option: "markdownEngine: false" }]);
|
|
2564
|
+
if (sections) plan.byHand.push([contentDir, `${sections} ${sections === 1 ? "section" : "sections"} (\`_index.md\`): ssqch's sections are folders with directory data (\`<folder>/<folder>.json\` for layout and permalink) and a collection (\`tags\`), and the section page a page of its own`, { code: "hugo-sections", status: "ssqch", count: sections, files: sections, docs: "directory data" }]);
|
|
2565
|
+
if (cascades) plan.byHand.push([contentDir, `\`cascade\` in ${cascades} ${cascades === 1 ? "page's" : "pages'"} front matter: ssqch's is directory data, which every page below it gets`, { code: "hugo-cascade", status: "ssqch", files: cascades, docs: "directory data" }]);
|
|
2566
|
+
for (const entry of entries.filter((e) => e.isFile && /(?:^|\/)layouts\/(?:_default\/)?_markup\/render-/.test(e.rel))) {
|
|
2567
|
+
const kind = /render-([a-z]+)(?:-([\w-]+))?\./.exec(entry.name);
|
|
2568
|
+
const ours = kind && HUGO_HOOKS[kind[1]];
|
|
2569
|
+
plan.byHand.push([entry.rel, ours ? `a render hook: ssqch's is \`_includes/hooks/${ours}${kind[2] ? `-${kind[2]}` : ""}.<ext>\` (\`ssqch docs hooks\`), written in the site's template language` : `a ${kind?.[1] ?? "render"} hook: not in ssqch yet (its hooks are heading, link, image, code, fence and footnotes)`, { code: "hugo-render-hook", status: ours ? "site" : "not-yet", docs: "hooks" }]);
|
|
2570
|
+
}
|
|
2571
|
+
if (layouts.length) plan.byHand.push([layouts[0].rel.replace(/\/.*$/, ""), `${layouts.length} Go ${layouts.length === 1 ? "template" : "templates"} to port: ssqch doesn't run Go templates. Jinja is closest: \`define\` and \`block\` map onto \`extends\` and \`block\`, and \`{{- -}}\` trims the same way, so the minifier sees the same text`, { code: "hugo-templates", status: "site", files: layouts.length, docs: "--from hugo" }]);
|
|
2572
|
+
for (const [pattern, what, code, status] of HUGO_FUNCTIONS) {
|
|
2573
|
+
let first;
|
|
2574
|
+
const files = /* @__PURE__ */ new Set();
|
|
2575
|
+
for (const entry of layouts) {
|
|
2576
|
+
const text = readUtf8(entry.abs) ?? "";
|
|
2577
|
+
const m = pattern.exec(text);
|
|
2578
|
+
if (!m) continue;
|
|
2579
|
+
files.add(entry.rel);
|
|
2580
|
+
first ??= lineAt(entry, text, m.index);
|
|
2581
|
+
}
|
|
2582
|
+
if (first) plan.byHand.push([first, `${what} (in ${files.size} ${files.size === 1 ? "template" : "templates"})`, { code, status, files: files.size }]);
|
|
2583
|
+
}
|
|
2584
|
+
const highlight = hugoKey(config, "markup");
|
|
2585
|
+
const noClasses = isPlainObject(highlight) && isPlainObject(highlight.highlight) ? highlight.highlight.noClasses !== false : true;
|
|
2586
|
+
if (noClasses && entries.some((e) => e.isFile && /\.(md|markdown)$/.test(e.name) && /^```/m.test(readUtf8(e.abs) ?? ""))) plan.byHand.push([configFile ?? ".", "code is highlighted with inline styles (Hugo's `noClasses`, its default): not in ssqch yet; the draft uses classes with Pygments' (and Chroma's) names, for a stylesheet (`hugo gen chromastyles`)", { code: "hugo-inline-styles", status: "not-yet" }]);
|
|
2587
|
+
const hasDir = (rel) => entries.some((e) => e.rel === rel && !e.isFile);
|
|
2588
|
+
if (hasDir("assets")) plan.byHand.push(["assets", "Hugo Pipes' sources: ssqch copies files with `passthrough` and processes them with its plugins (`ssqch docs assets`)", { code: "hugo-assets", status: "ssqch", docs: "assets" }]);
|
|
2589
|
+
const baseURL = typeof hugoKey(config, "baseURL") === "string" ? hugoKey(config, "baseURL").replace(/\/$/, "") : void 0;
|
|
2590
|
+
const site = {};
|
|
2591
|
+
for (const key of ["title", "languageCode", "copyright"]) if (hugoKey(config, key) !== void 0) site[key] = hugoKey(config, key);
|
|
2592
|
+
if (baseURL) site.url = baseURL;
|
|
2593
|
+
if (isPlainObject(hugoKey(config, "params"))) site.params = hugoKey(config, "params");
|
|
2594
|
+
const dirs = [`input: ${JSON.stringify(contentDir)}`, `output: ${JSON.stringify(output)}`, 'includes: "../_includes"', ...hasDir("data") ? ['data: "../data"'] : []];
|
|
2595
|
+
const imports = ['import { defineConfig } from "ssqch";', 'import { linksPlugin } from "ssqch/links";', ...baseURL ? ['import { sitemapPlugin } from "ssqch/sitemap";'] : []];
|
|
2596
|
+
let out = `// A first draft, written by \`ssqch scout\` from ${configFile ?? "the Hugo site"}.
|
|
2597
|
+
// \`ssqch docs --from hugo\` has the whole mapping.
|
|
2598
|
+
${imports.join("\n")}
|
|
2599
|
+
|
|
2600
|
+
export default defineConfig({
|
|
2601
|
+
`;
|
|
2602
|
+
out += ` dirs: { ${dirs.join(", ")} },
|
|
2603
|
+
`;
|
|
2604
|
+
if (basePath(baseURL) !== void 0) out += ` // baseURL's path: the site is served under it.
|
|
2605
|
+
base: ${JSON.stringify(basePath(baseURL))},
|
|
2606
|
+
`;
|
|
2607
|
+
out += " // Hugo doesn't run template code in content, and its shortcodes on a line of their own are\n // containers (_includes/containers/<name>.jinja).\n markdownEngine: false,\n";
|
|
2608
|
+
out += ' markdown: { shortcodes: "hugo", highlight: { classes: "pygments" } },\n';
|
|
2609
|
+
if (hasDir("static")) out += ' passthrough: [{ static: "." }],\n';
|
|
2610
|
+
out += ` data: { site: ${JSON.stringify(sortedKeys(site))} },
|
|
2611
|
+
`;
|
|
2612
|
+
out += ` plugins: [${[
|
|
2613
|
+
...baseURL ? [`sitemapPlugin({ url: ${JSON.stringify(baseURL)} })`] : [],
|
|
2614
|
+
// Hugo doesn't check links, so one that was broken there warns rather than failing the move's build.
|
|
2615
|
+
"linksPlugin({ fail: false })"
|
|
2616
|
+
].join(", ")}],
|
|
2617
|
+
});
|
|
2618
|
+
`;
|
|
2619
|
+
plan.newFiles.unshift(["ssqch.config.js", `a first draft, from ${configFile ?? "the Hugo site"}`, out]);
|
|
2620
|
+
return plan;
|
|
2621
|
+
}
|
|
2622
|
+
function readMkdocsYaml2(text) {
|
|
2623
|
+
try {
|
|
2624
|
+
return readMkdocsYaml(text);
|
|
2625
|
+
} catch (e) {
|
|
2626
|
+
return fail(e instanceof Error ? e.message : String(e));
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
var MKDOCS_PLUGINS = {
|
|
2630
|
+
search: { say: "MkDocs writes `search/search_index.json`, which the theme's search box reads (MkDocs turns `search` on when `plugins` isn't set): not in ssqch yet in that format; a page that loops over `collections.all` can write it, and Pagefind indexes the built site for a search of ssqch's own (`ssqch docs search`)", status: "not-yet" },
|
|
2631
|
+
mkdocstrings: { say: "API pages from Python docstrings (`::: package.module`): Python writes them, so it's not in ssqch yet; its `:::` lines would read as ssqch's containers, so the draft sets `markdown: { containers: false }`", status: "not-yet" },
|
|
2632
|
+
blog: { say: "a blog is a collection in ssqch: posts in a folder with directory data, with pagination for the index and categories", status: "ssqch" },
|
|
2633
|
+
redirects: { say: '`redirectsPlugin({ redirects })` from "ssqch/redirects", with `redirect_maps` (in the draft)', status: "option" },
|
|
2634
|
+
minify: { say: '`minifyPlugin()` from "ssqch/minify"', status: "ssqch" },
|
|
2635
|
+
tags: { say: "tags are a collection in ssqch (`tags` in front matter, and a page per tag by pagination)", status: "ssqch" },
|
|
2636
|
+
social: { say: "not in ssqch yet: social cards are images drawn per page (the `<meta>` tags are a layout's)", status: "not-yet" },
|
|
2637
|
+
privacy: { say: "not in ssqch yet: fetching external assets at build time", status: "not-yet" },
|
|
2638
|
+
offline: { say: "not in ssqch yet", status: "not-yet" },
|
|
2639
|
+
"git-revision-date-localized": { say: "`page.lastModified` (`ssqch docs lastModified`), formatted with a date filter", status: "ssqch" },
|
|
2640
|
+
"awesome-pages": { say: "the sidebar's order is `_data/nav.yml`'s (`navTree`)", status: "ssqch" },
|
|
2641
|
+
macros: { say: "Markdown runs through a template engine in ssqch (`markdownEngine`): the macros become the engine's, with the site's variables as data", status: "site" },
|
|
2642
|
+
i18n: { say: "`ssqch docs multilingual`", status: "ssqch" }
|
|
2643
|
+
};
|
|
2644
|
+
var MKDOCS_EXTENSIONS = {
|
|
2645
|
+
admonition: { say: '`!!!` admonitions: `markdown: { admonitions: "mkdocs" }` (in the draft) writes them as Python-Markdown does', status: "option", option: 'markdown: { admonitions: "mkdocs" }' },
|
|
2646
|
+
"pymdownx.details": { say: '`???` collapsible admonitions: `markdown: { admonitions: "mkdocs" }` (in the draft)', status: "option", option: 'markdown: { admonitions: "mkdocs" }' },
|
|
2647
|
+
"pymdownx.tabbed": { say: '`===` tabs: `markdown: { tabs: "mkdocs" }` (in the draft) writes them in the alternate style', status: "option", option: 'markdown: { tabs: "mkdocs" }' },
|
|
2648
|
+
"pymdownx.superfences": { say: "fences, built in; custom fences (mermaid) are a fence hook (`_includes/hooks/fence-mermaid.<ext>`)", status: "ssqch" },
|
|
2649
|
+
"pymdownx.highlight": { say: "`markdown: { highlight: { classes: \"pygments\" } }` (in the draft): Pygments' class names, cut by ssqch's grammars (the tokens can differ from Pygments', and the wrapper is a fence hook's: `_includes/hooks/fence.*`)", status: "option", option: 'markdown: { highlight: { classes: "pygments" } }' },
|
|
2650
|
+
codehilite: { say: "`markdown: { highlight: { classes: \"pygments\" } }` (in the draft) gives tokens Pygments' class names, cut by ssqch's grammars; codehilite's markup isn't the same (`<div class=\"codehilite\"><pre><span></span><code>`), and its tokens are Pygments', so a byte-for-byte move needs Pygments itself, or a fence hook (`_includes/hooks/fence.*`) for the wrapper", status: "option", option: 'markdown: { highlight: { classes: "pygments" } }' },
|
|
2651
|
+
mkautodoc: { say: "API pages from Python docstrings (`::: package.module`): Python writes them, so it's not in ssqch yet; its `:::` lines would read as ssqch's containers, so the draft sets `markdown: { containers: false }`", status: "not-yet" },
|
|
2652
|
+
"pymdownx.inlinehilite": { say: "not in ssqch yet: inline code with a language", status: "not-yet" },
|
|
2653
|
+
"pymdownx.snippets": { say: "`--8<--` snippets: not in ssqch yet as written; an include in a template engine (`markdownEngine`)", status: "not-yet" },
|
|
2654
|
+
"pymdownx.emoji": { say: "`:icon:` shortcodes: not in ssqch yet", status: "not-yet" },
|
|
2655
|
+
"pymdownx.keys": { say: "`++ctrl+c++` keys: not in ssqch yet", status: "not-yet" },
|
|
2656
|
+
"pymdownx.critic": { say: "not in ssqch yet", status: "not-yet" },
|
|
2657
|
+
"pymdownx.arithmatex": { say: "math: not in ssqch yet as written; KaTeX as a filter or a fence hook", status: "not-yet" },
|
|
2658
|
+
"pymdownx.tasklist": { say: "task lists, built in", status: "ssqch" },
|
|
2659
|
+
"pymdownx.caret": { say: "`^^insert^^` and `^sup^`: not in ssqch yet", status: "not-yet" },
|
|
2660
|
+
"pymdownx.mark": { say: "`==mark==`: not in ssqch yet", status: "not-yet" },
|
|
2661
|
+
"pymdownx.tilde": { say: "`~~delete~~`, built in (`~sub~` isn't)", status: "ssqch" },
|
|
2662
|
+
"pymdownx.magiclink": { say: "bare URLs, built in (`autolinks`); its repository shorthands aren't", status: "ssqch" },
|
|
2663
|
+
"pymdownx.smartsymbols": { say: "not in ssqch yet (`smartPunctuation` does quotes and dashes)", status: "not-yet" },
|
|
2664
|
+
"pymdownx.betterem": { say: "emphasis, built in (CommonMark's rules)", status: "ssqch" },
|
|
2665
|
+
smarty: { say: "`markdown: { smartPunctuation: true }` (in the draft)", status: "option", option: "markdown: { smartPunctuation: true }" },
|
|
2666
|
+
attr_list: { say: "attributes (`{#id .class}`), built in; on headings, ssqch keeps ids and classes", status: "ssqch" },
|
|
2667
|
+
md_in_html: { say: 'Markdown inside HTML with the bare `markdown` attribute: not in ssqch yet as written; `markdown: { htmlMarkdown: "kramdown" }` reads `markdown="1"`', status: "not-yet" },
|
|
2668
|
+
footnotes: { say: "footnotes, built in (their markup is a `footnotes` hook's)", status: "ssqch" },
|
|
2669
|
+
toc: { say: "`markdown: { headingIds: \"python-markdown\" }` (in the draft): toc's default ids (a repeated heading's `_1` too; a `slugify` of the site's own needs a function). The table of contents is `page.headings` and the `toc` filter", status: "option", option: 'markdown: { headingIds: "python-markdown" }' },
|
|
2670
|
+
def_list: { say: "`markdown: { definitionLists: true }` (in the draft)", status: "option", option: "markdown: { definitionLists: true }" },
|
|
2671
|
+
abbr: { say: "abbreviations: not in ssqch yet", status: "not-yet" },
|
|
2672
|
+
tables: { say: "tables, built in", status: "ssqch" },
|
|
2673
|
+
meta: { say: "front matter, built in", status: "ssqch" }
|
|
2674
|
+
};
|
|
2675
|
+
function basePath(url) {
|
|
2676
|
+
if (url === void 0) return void 0;
|
|
2677
|
+
const m = /^[a-z]+:\/\/[^/]+(\/.*)$/i.exec(url.endsWith("/") ? url : `${url}/`);
|
|
2678
|
+
return m && m[1] !== "/" ? m[1] : void 0;
|
|
2679
|
+
}
|
|
2680
|
+
function mkdocsUrl(file, directoryUrls) {
|
|
2681
|
+
const stem = file.replace(/\.md$/, "");
|
|
2682
|
+
if (/(?:^|\/)(?:index|README)$/.test(stem)) return `/${stem.replace(/(?:^|\/)?(?:index|README)$/, "")}${stem.includes("/") ? "/" : ""}`.replace(/\/+/g, "/");
|
|
2683
|
+
return directoryUrls ? `/${stem}/` : `/${stem}.html`;
|
|
2684
|
+
}
|
|
2685
|
+
function mkdocs(dir) {
|
|
2686
|
+
const configFile = ["mkdocs.yml", "mkdocs.yaml"].find((f) => isFile(path.join(dir, f))) ?? fail(`there's no mkdocs.yml in ${dir}: is this the MkDocs site's folder?`);
|
|
2687
|
+
const config = readMkdocsYaml2(readStrict(path.join(dir, configFile)));
|
|
2688
|
+
const plan = { from: "MkDocs", renames: [], edits: [], newFiles: [], byHand: [] };
|
|
2689
|
+
const docsDir = typeof config.docs_dir === "string" ? config.docs_dir : "docs";
|
|
2690
|
+
const siteDir = typeof config.site_dir === "string" ? config.site_dir : "site";
|
|
2691
|
+
const directoryUrls = config.use_directory_urls !== false;
|
|
2692
|
+
const pages = walk(path.join(dir, docsDir), (name) => name.startsWith(".") || name === "node_modules", false).filter((e) => e.isFile && /\.md$/.test(e.name)).map((e) => ({ ...e, rel: `${docsDir}/${e.rel}`, page: e.rel }));
|
|
2693
|
+
plan.pages = pages.length;
|
|
2694
|
+
const named = (list) => Array.isArray(list) ? list.map((item) => isPlainObject(item) ? Object.keys(item)[0] : String(item)) : isPlainObject(list) ? Object.keys(list) : [];
|
|
2695
|
+
const extensions = named(config.markdown_extensions);
|
|
2696
|
+
const plugins = config.plugins === void 0 ? ["search"] : named(config.plugins);
|
|
2697
|
+
const theme = isPlainObject(config.theme) ? config.theme.name : config.theme;
|
|
2698
|
+
if (typeof theme === "string") plan.byHand.push([`${configFile}: theme`, `the ${theme === "material" ? "Material" : theme} theme's templates are Jinja, which ssqch runs as written with \`mkdocsTemplates: true\` (in the draft, to turn on once they're there): it gives them MkDocs' context (\`config\`, \`nav\`, \`page\`, \`base_url\`, the \`url\` filter). Copy the theme's templates from its Python package into an ssqch theme first (\`ssqch docs --from mkdocs\`, "The theme")`, { code: "mkdocs-theme", status: "option", option: "mkdocsTemplates: true", docs: "mkdocsTemplates" }]);
|
|
2699
|
+
for (const name of plugins) {
|
|
2700
|
+
const known = MKDOCS_PLUGINS[name.replace(/^material\//, "")];
|
|
2701
|
+
plan.byHand.push([`${configFile}: plugins`, `\`${name}\`: ${known?.say ?? "not in ssqch yet: port it as a plugin (`ssqch docs plugins`)"}`, { code: "mkdocs-plugin", status: known?.status ?? "site" }]);
|
|
2702
|
+
}
|
|
2703
|
+
for (const name of extensions) {
|
|
2704
|
+
const known = MKDOCS_EXTENSIONS[name];
|
|
2705
|
+
plan.byHand.push([`${configFile}: markdown_extensions`, `\`${name}\`: ${known?.say ?? "not in ssqch yet"}`, { code: "mkdocs-extension", status: known?.status ?? "not-yet", ...known?.option ? { option: known.option } : {} }]);
|
|
2706
|
+
}
|
|
2707
|
+
const customDir = isPlainObject(config.theme) && typeof config.theme.custom_dir === "string" ? config.theme.custom_dir : void 0;
|
|
2708
|
+
if (customDir) {
|
|
2709
|
+
const overrides = walk(path.join(dir, customDir), (name) => name.startsWith("."), false).filter((e) => e.isFile).length;
|
|
2710
|
+
plan.byHand.push([`${configFile}: theme.custom_dir`, `\`${customDir}\` (${overrides} ${overrides === 1 ? "file" : "files"}) overrides the theme's templates: in ssqch it's the includes folder (\`dirs.includes\`, in the draft), which is read before a theme's, so a template there replaces the theme's of the same name and \`{% extends %}\` reaches the theme's`, { code: "mkdocs-custom-dir", status: "option", files: overrides, option: `dirs: { includes: ${JSON.stringify(path.posix.relative(docsDir, customDir))} }` }]);
|
|
2711
|
+
}
|
|
2712
|
+
plan.byHand.push([`${configFile}: theme`, "MkDocs writes `404.html` from the theme's `404.html` template, with absolute URLs: a page of its own in ssqch (`404.md` or `404.jinja` with `permalink: /404.html`)", { code: "mkdocs-404", status: "ssqch", docs: "404" }]);
|
|
2713
|
+
plan.byHand.push([`${configFile}: site_url`, "MkDocs writes `sitemap.xml.gz` beside `sitemap.xml`: `sitemapPlugin()` writes the `.xml`; the gzipped copy isn't in ssqch yet (an `afterBuild` step with `node:zlib`)", { code: "mkdocs-sitemap-gz", status: "not-yet" }]);
|
|
2714
|
+
if (isFile(path.join(dir, "hooks.py")) || config.hooks) plan.byHand.push([`${configFile}: hooks`, "Python hooks don't run in ssqch: port each as a plugin or a filter (`ssqch docs plugins`)", { code: "mkdocs-hooks", status: "site", docs: "plugins" }]);
|
|
2715
|
+
const syntax = [
|
|
2716
|
+
["links to .md files", /\]\((?![a-z]+:)[^)\s#]*\.md(?:#[^)\s]*)?\)|^[ \t]*\[[^\]\n]+\]:[ \t]*(?![a-z]+:)[^\s#]*\.md(?:#\S*)?[ \t]*$/gm, '`markdown: { sourceLinks: "relative" }` (in the draft) links each to its page\'s URL, as MkDocs does', "mkdocs-md-links", "option"],
|
|
2717
|
+
["admonitions (`!!!`, `???`)", /^[ \t]*(?:!!!|\?\?\?\+?)[ \t]+\w/gm, '`markdown: { admonitions: "mkdocs" }` (in the draft)', "mkdocs-admonitions", "option"],
|
|
2718
|
+
["tabs (`===`)", /^[ \t]*===[+!]{0,2}[ \t]+"/gm, '`markdown: { tabs: "mkdocs" }` (in the draft)', "mkdocs-tabs", "option"],
|
|
2719
|
+
["snippets (`--8<--`)", /^[ \t]*-+8<-+/gm, "not in ssqch yet as written", "mkdocs-snippets", "not-yet"],
|
|
2720
|
+
["icons and emoji (`:name:`)", /:(?:material|fontawesome|octicons|simple)-[\w-]+:/g, "not in ssqch yet", "mkdocs-icons", "not-yet"],
|
|
2721
|
+
["bare `markdown` attributes", /<[a-z][^>]*\smarkdown(?=[\s>])/g, 'not in ssqch yet as written: `htmlMarkdown: "kramdown"` reads `markdown="1"`', "mkdocs-md-in-html", "not-yet"],
|
|
2722
|
+
["API docs (`::: package.name`)", /^:::[ \t]+[\w.]+\.[\w.]+/gm, "mkautodoc's or mkdocstrings' blocks, which Python writes, so they're not in ssqch yet; `:::` is how ssqch's containers start, so the draft sets `markdown: { containers: false }`", "mkdocs-autodoc", "not-yet"]
|
|
2723
|
+
];
|
|
2724
|
+
for (const [what, pattern, say, code, status] of syntax) {
|
|
2725
|
+
let count = 0;
|
|
2726
|
+
let first;
|
|
2727
|
+
const files = /* @__PURE__ */ new Set();
|
|
2728
|
+
for (const entry of pages) {
|
|
2729
|
+
const text = readUtf8(entry.abs) ?? "";
|
|
2730
|
+
for (const m of text.matchAll(pattern)) {
|
|
2731
|
+
count++;
|
|
2732
|
+
files.add(entry.rel);
|
|
2733
|
+
first ??= lineAt(entry, text, m.index);
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
const option = { "mkdocs-md-links": 'markdown: { sourceLinks: "relative" }', "mkdocs-admonitions": 'markdown: { admonitions: "mkdocs" }', "mkdocs-tabs": 'markdown: { tabs: "mkdocs" }' }[code];
|
|
2737
|
+
if (first) plan.byHand.push([first, `${what} (${uses(count, files.size)}): ${say}`, { code, status, count, files: files.size, ...option ? { option } : {} }]);
|
|
2738
|
+
}
|
|
2739
|
+
const blogDates = pages.filter((e) => /^date:\s*\n\s+created:/m.test((readUtf8(e.abs) ?? "").slice(0, 2e3)));
|
|
2740
|
+
if (blogDates.length) plan.byHand.push([blogDates[0].rel, `\`date: { created, updated }\` front matter (Material's blog) in ${blogDates.length} ${blogDates.length === 1 ? "page" : "pages"}: ssqch's \`date\` is one date; not in ssqch yet as written`, { code: "mkdocs-blog-dates", status: "not-yet", files: blogDates.length }]);
|
|
2741
|
+
const site = {};
|
|
2742
|
+
for (const [from, to] of [["site_name", "name"], ["site_url", "url"], ["site_description", "description"], ["site_author", "author"], ["repo_url", "repo_url"], ["edit_uri", "edit_uri"], ["copyright", "copyright"]]) if (typeof config[from] === "string") site[to] = config[from];
|
|
2743
|
+
if (isPlainObject(config.extra)) site.extra = config.extra;
|
|
2744
|
+
const markdown = ['admonitions: "mkdocs"', 'tabs: "mkdocs"', 'sourceLinks: "relative"', 'headingIds: "python-markdown"', 'dialect: "python-markdown"'];
|
|
2745
|
+
if (extensions.some((e) => e === "pymdownx.highlight" || e === "codehilite")) markdown.push('highlight: { classes: "pygments" }');
|
|
2746
|
+
if (extensions.includes("def_list")) markdown.push("definitionLists: true");
|
|
2747
|
+
if (extensions.includes("smarty")) markdown.push("smartPunctuation: true");
|
|
2748
|
+
if (!extensions.includes("footnotes")) markdown.push("footnotes: false");
|
|
2749
|
+
if (pages.some((e) => /^:::[ \t]+[\w.]+\.[\w.]+/m.test(readUtf8(e.abs) ?? ""))) markdown.push("containers: false");
|
|
2750
|
+
const redirects = (() => {
|
|
2751
|
+
const entry = Array.isArray(config.plugins) ? config.plugins.find((p) => isPlainObject(p) && "redirects" in p) : void 0;
|
|
2752
|
+
const maps = entry && isPlainObject(entry.redirects) && isPlainObject(entry.redirects.redirect_maps) ? entry.redirects.redirect_maps : void 0;
|
|
2753
|
+
if (!maps) return void 0;
|
|
2754
|
+
const out2 = {};
|
|
2755
|
+
for (const [from, to] of Object.entries(maps)) if (typeof to === "string") out2[mkdocsUrl(from, directoryUrls)] = /^[a-z]+:/.test(to) ? to : mkdocsUrl(to.replace(/#.*$/, ""), directoryUrls) + (to.includes("#") ? to.slice(to.indexOf("#")) : "");
|
|
2756
|
+
return out2;
|
|
2757
|
+
})();
|
|
2758
|
+
const url = typeof config.site_url === "string" ? config.site_url.replace(/\/$/, "") : void 0;
|
|
2759
|
+
const imports = ['import { defineConfig } from "ssqch";', 'import { linksPlugin } from "ssqch/links";', ...url ? ['import { sitemapPlugin } from "ssqch/sitemap";'] : [], ...redirects ? ['import { redirectsPlugin } from "ssqch/redirects";'] : []];
|
|
2760
|
+
let out = `// A first draft, written by \`ssqch scout\` from ${configFile}.
|
|
2761
|
+
// \`ssqch docs --from mkdocs\` has the whole mapping. The sidebar is _data/nav.yml (navTree).
|
|
2762
|
+
${imports.join("\n")}
|
|
2763
|
+
|
|
2764
|
+
export default defineConfig({
|
|
2765
|
+
`;
|
|
2766
|
+
if (customDir) out += ` // theme.custom_dir: the theme's overrides, read before the theme's own templates.
|
|
2767
|
+
`;
|
|
2768
|
+
out += ` dirs: { input: ${JSON.stringify(docsDir)}, output: ${JSON.stringify(siteDir)}, includes: ${JSON.stringify(customDir ? path.posix.relative(docsDir, customDir) : "../_includes")}, data: "../_data" },
|
|
2769
|
+
`;
|
|
2770
|
+
if (basePath(url) !== void 0) out += ` // site_url's path: the site is served under it.
|
|
2771
|
+
base: ${JSON.stringify(basePath(url))},
|
|
2772
|
+
`;
|
|
2773
|
+
out += " // MkDocs doesn't run template code in pages; its blocks and links read as it writes them.\n markdownEngine: false,\n";
|
|
2774
|
+
if (typeof theme === "string") out += ` // The ${theme} theme's templates as they are: copy them into theme/ (\`ssqch docs --from mkdocs\`,
|
|
2775
|
+
// "The theme"), then turn these on.
|
|
2776
|
+
// theme: "theme", mkdocsTemplates: true,
|
|
2777
|
+
`;
|
|
2778
|
+
out += ` markdown: { ${markdown.join(", ")} },
|
|
2779
|
+
`;
|
|
2780
|
+
const copied = walk(path.join(dir, docsDir), (name) => name.startsWith(".") || name === "node_modules", false).filter((e) => e.isFile && !/\.md$/i.test(e.name) && !(customDir && path.join(dir, docsDir, e.rel).startsWith(path.join(dir, customDir) + path.sep)));
|
|
2781
|
+
const others = [...new Set(copied.filter((e) => /\.[A-Za-z0-9]+$/.test(e.name)).map((e) => extensionOf(e.name).toLowerCase()))].sort(compareText);
|
|
2782
|
+
const bare = copied.filter((e) => !/\.[A-Za-z0-9]+$/.test(e.name)).map((e) => `${docsDir}/${e.rel}`).sort(compareText);
|
|
2783
|
+
const entries = [...others.map((ext) => `{ ${JSON.stringify(`${docsDir}/**/*.${ext}`)}: "." }`), ...bare.map((file) => `{ ${JSON.stringify(file)}: ${JSON.stringify(file.slice(docsDir.length + 1))} }`)];
|
|
2784
|
+
if (entries.length) out += ` passthrough: [${entries.join(", ")}],
|
|
2785
|
+
`;
|
|
2786
|
+
out += ` data: { site: ${JSON.stringify(sortedKeys(site))} },
|
|
2787
|
+
`;
|
|
2788
|
+
const pluginCalls = [...url ? [`sitemapPlugin({ url: ${JSON.stringify(url)} })`] : [], ...redirects ? [`redirectsPlugin({ redirects: ${JSON.stringify(redirects)} })`] : [], config.strict === true ? "linksPlugin()" : "linksPlugin({ fail: false })"];
|
|
2789
|
+
out += ` plugins: [${pluginCalls.join(", ")}],
|
|
2790
|
+
});
|
|
2791
|
+
`;
|
|
2792
|
+
plan.newFiles.push(["ssqch.config.js", `a first draft, from ${configFile}`, out]);
|
|
2793
|
+
const highlighter = extensions.includes("pymdownx.highlight") ? "pymdownx.highlight" : extensions.includes("codehilite") ? "codehilite" : void 0;
|
|
2794
|
+
if (highlighter) {
|
|
2795
|
+
const open = highlighter === "codehilite" ? '<div class="codehilite">' : '<div class="{% if fence.lang %}language-{{ fence.lang }} {% endif %}highlight">';
|
|
2796
|
+
plan.newFiles.push([path.posix.join(customDir ?? "_includes", "hooks/fence.jinja"), `${highlighter}'s wrapper around highlighted code`, `{# ${highlighter}'s markup around a code block, by ssqch scout: the theme's CSS reads it. #}
|
|
2797
|
+
${open}<pre><span></span><code>{% if fence.highlighted %}{{ fence.highlighted | safe }}{% else %}{{ fence.code | e }}{% endif %}</code></pre></div>
|
|
2798
|
+
`]);
|
|
2799
|
+
}
|
|
2800
|
+
if (Array.isArray(config.nav)) {
|
|
2801
|
+
const titleOf = (file) => /^#[ \t]+(.+?)[ \t#]*$/m.exec(readUtf8(path.join(dir, docsDir, file)) ?? "")?.[1] ?? file.replace(/\.md$/, "").split("/").pop();
|
|
2802
|
+
let entries2 = 0;
|
|
2803
|
+
const convert = (list) => list.flatMap((item) => {
|
|
2804
|
+
if (typeof item === "string") {
|
|
2805
|
+
entries2++;
|
|
2806
|
+
return [/^[a-z]+:/.test(item) ? { title: item, url: item } : { title: titleOf(item), url: mkdocsUrl(item, directoryUrls) }];
|
|
2807
|
+
}
|
|
2808
|
+
if (!isPlainObject(item)) return [];
|
|
2809
|
+
return Object.entries(item).map(([title, value]) => {
|
|
2810
|
+
if (Array.isArray(value)) return { title, children: convert(value) };
|
|
2811
|
+
entries2++;
|
|
2812
|
+
return { title, url: typeof value === "string" && !/^[a-z]+:/.test(value) ? mkdocsUrl(value, directoryUrls) : String(value) };
|
|
2813
|
+
});
|
|
2814
|
+
});
|
|
2815
|
+
const nav = convert(config.nav);
|
|
2816
|
+
plan.newFiles.push(["_data/nav.yml", `the nav from ${configFile} (${entries2} entries), for \`navTree\``, `# From ${configFile}'s nav, by ssqch scout: titles as the nav gives them, or each page's first heading.
|
|
2817
|
+
${dumpYaml(nav)}`]);
|
|
2818
|
+
} else plan.byHand.push([configFile, "no `nav`: MkDocs builds the sidebar from the folders; ssqch's is `_data/nav.yml` (`navTree`) or `pagesTree(collections.all)`", { code: "mkdocs-nav", status: "ssqch", docs: "navTree" }]);
|
|
2819
|
+
return plan;
|
|
2820
|
+
}
|
|
2821
|
+
function dumpYaml(nav, indent = "") {
|
|
2822
|
+
const scalar = (v) => /^[\w./ -]+$/.test(v) && !/^\s|\s$|^(?:true|false|null|yes|no|on|off|~|-?\d[\d.]*)$/i.test(v) && !v.startsWith("- ") ? v : JSON.stringify(v);
|
|
2823
|
+
let out = "";
|
|
2824
|
+
for (const entry of nav) {
|
|
2825
|
+
out += `${indent}- title: ${scalar(String(entry.title))}
|
|
2826
|
+
`;
|
|
2827
|
+
if (entry.url !== void 0) out += `${indent} url: ${scalar(String(entry.url))}
|
|
2828
|
+
`;
|
|
2829
|
+
if (Array.isArray(entry.children)) out += `${indent} children:
|
|
2830
|
+
${dumpYaml(entry.children, `${indent} `)}`;
|
|
2831
|
+
}
|
|
2832
|
+
return out;
|
|
2833
|
+
}
|
|
2834
|
+
var TRAILHEADS = { docusaurus: "from-docusaurus", hexo: "from-hexo", astro: "from-component-frameworks", vitepress: "from-component-frameworks" };
|
|
2835
|
+
function countIn(entries, pattern) {
|
|
2836
|
+
let count = 0;
|
|
2837
|
+
let first;
|
|
2838
|
+
const files = /* @__PURE__ */ new Set();
|
|
2839
|
+
for (const entry of entries) {
|
|
2840
|
+
const text = readUtf8(entry.abs) ?? "";
|
|
2841
|
+
for (const m of text.matchAll(pattern)) {
|
|
2842
|
+
count++;
|
|
2843
|
+
files.add(entry.rel);
|
|
2844
|
+
first ??= lineAt(entry, text, m.index);
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
return { count, files: files.size, first };
|
|
2848
|
+
}
|
|
2849
|
+
function listSyntax(plan, entries, rows) {
|
|
2850
|
+
for (const [what, pattern, say, code, status] of rows) {
|
|
2851
|
+
const { count, files, first } = countIn(entries, new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
|
|
2852
|
+
if (first) plan.byHand.push([first, `${what} (${uses(count, files)}): ${say}`, { code, status, count, files }]);
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
function packagesLike(dir, pattern) {
|
|
2856
|
+
try {
|
|
2857
|
+
const pkg = JSON.parse(readUtf8(path.join(dir, "package.json")) ?? "{}");
|
|
2858
|
+
return Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).filter((name) => pattern.test(name)).sort(compareText);
|
|
2859
|
+
} catch {
|
|
2860
|
+
return [];
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
var SKIP_BUILT = (name) => name.startsWith(".git") || name === "node_modules" || name === ".cache" || name === "build" || name === "dist" || name === ".docusaurus" || name === ".astro";
|
|
2864
|
+
function other(dir, id) {
|
|
2865
|
+
const name = GENERATORS[id].name;
|
|
2866
|
+
const plan = { from: name, renames: [], edits: [], newFiles: [], byHand: [] };
|
|
2867
|
+
const entries = walk(dir, (n, rel) => SKIP_BUILT(n) || id === "vitepress" && /(?:^|\/)\.vitepress\/(?:cache|dist)$/.test(rel) || id === "hexo" && rel === "public", false).filter((e) => e.isFile);
|
|
2868
|
+
const pages = entries.filter((e) => /\.(md|mdx|markdown)$/.test(e.name));
|
|
2869
|
+
plan.pages = pages.length;
|
|
2870
|
+
if (id === "docusaurus") {
|
|
2871
|
+
const mdx = pages.filter((e) => e.name.endsWith(".mdx"));
|
|
2872
|
+
if (mdx.length) plan.byHand.push([mdx[0].rel, `${mdx.length} MDX ${mdx.length === 1 ? "page" : "pages"}: ssqch's Markdown doesn't run JSX; their components become Edge components or containers (\`ssqch docs --from docusaurus\`)`, { code: "docusaurus-mdx", status: "site", files: mdx.length }]);
|
|
2873
|
+
listSyntax(plan, pages, [
|
|
2874
|
+
["`import` of components in pages", /^import\s+[\w{},\s*]+\s+from\s+['"][^'"]+['"];?\s*$/m, "not in ssqch yet as written: Edge components (`@component(...)`) or containers", "docusaurus-imports", "not-yet"],
|
|
2875
|
+
["`<Tabs>` and `<TabItem>`", /<Tabs\b/, "tabs from containers (the versioned-docs example has them)", "docusaurus-tabs", "ssqch"],
|
|
2876
|
+
["admonitions (`:::note`)", /^:::(?:note|tip|info|warning|danger|caution)\b/m, "containers, built in: `_includes/containers/note.*` gives each its markup", "docusaurus-admonitions", "ssqch"],
|
|
2877
|
+
["`<!-- truncate -->` and `{/* truncate */}`", /<!--\s*truncate\s*-->|\{\/\*\s*truncate\s*\*\/\}/, "an excerpt's end: ssqch's marker is `<!-- more -->`", "docusaurus-truncate", "not-yet"],
|
|
2878
|
+
["`@site/` and `@theme/` paths", /@(?:site|theme)\//, "not in ssqch yet: paths from the site's root", "docusaurus-aliases", "not-yet"]
|
|
2879
|
+
]);
|
|
2880
|
+
for (const file of ["sidebars.js", "sidebars.ts"]) if (isFile(path.join(dir, file))) plan.byHand.push([file, "the sidebar: ssqch's is `_data/nav.yml` and `navTree`, or `pagesTree(collections.all)` from front matter", { code: "docusaurus-sidebar", status: "ssqch", docs: "navTree" }]);
|
|
2881
|
+
if (isDir(path.join(dir, "versioned_docs"))) plan.byHand.push(["versioned_docs", "versions as folders, each with its own sidebar: directory data per version (the versioned-docs example)", { code: "docusaurus-versions", status: "ssqch" }]);
|
|
2882
|
+
if (isDir(path.join(dir, "i18n"))) plan.byHand.push(["i18n", "translations: `ssqch docs multilingual`", { code: "docusaurus-i18n", status: "ssqch", docs: "multilingual" }]);
|
|
2883
|
+
for (const pkg of packagesLike(dir, /^@docusaurus\/plugin-|docusaurus-plugin-/)) plan.byHand.push(["package.json", `${pkg}: ${/sitemap/.test(pkg) ? '`sitemapPlugin()` from "ssqch/sitemap"' : /content-blog/.test(pkg) ? "a blog is a collection with directory data" : /client-redirects/.test(pkg) ? '`redirectsPlugin()` from "ssqch/redirects"' : /ideal-image/.test(pkg) ? '`imagePlugin()` from "ssqch/image"' : "not in ssqch yet: port it as a plugin"}`, { code: "docusaurus-plugin", status: /sitemap|content-blog|client-redirects|ideal-image/.test(pkg) ? "ssqch" : "site" }]);
|
|
2884
|
+
} else if (id === "astro") {
|
|
2885
|
+
const astro = entries.filter((e) => e.name.endsWith(".astro"));
|
|
2886
|
+
if (astro.length) plan.byHand.push([astro[0].rel, `${astro.length} \`.astro\` ${astro.length === 1 ? "component" : "components"} to port: ssqch doesn't run them; layouts and components become templates (Edge's components are closest), and their scripts custom elements from \`ssqch/elements\``, { code: "astro-components", status: "site", files: astro.length, docs: "--from astro" }]);
|
|
2887
|
+
const islands = entries.filter((e) => /\.(jsx|tsx|vue|svelte)$/.test(e.name) && !e.rel.startsWith("node_modules"));
|
|
2888
|
+
if (islands.length) plan.byHand.push([islands[0].rel, `${islands.length} framework ${islands.length === 1 ? "component" : "components"} (React, Vue, Svelte): islands in ssqch are custom elements whose scripts load where they're used (the islands example)`, { code: "astro-islands", status: "site", files: islands.length }]);
|
|
2889
|
+
const collections = ["src/content/config.ts", "src/content.config.ts", "src/content/config.mjs"].find((f) => isFile(path.join(dir, f)));
|
|
2890
|
+
if (collections) plan.byHand.push([collections, "content collections with schemas: ssqch's are collections and `schemas` (`ssqch docs schemas`)", { code: "astro-content-collections", status: "ssqch", docs: "schemas" }]);
|
|
2891
|
+
listSyntax(plan, pages, [["`import` in MDX pages", /^import\s+.+\s+from\s+['"][^'"]+['"]/m, "not in ssqch yet as written: Edge components or containers", "astro-mdx-imports", "not-yet"]]);
|
|
2892
|
+
for (const pkg of packagesLike(dir, /^@astrojs\//)) plan.byHand.push(["package.json", `${pkg}: ${/sitemap/.test(pkg) ? '`sitemapPlugin()` from "ssqch/sitemap"' : /mdx/.test(pkg) ? "MDX pages: see the MDX line" : /rss/.test(pkg) ? '`rssPlugin()` from "ssqch/rss"' : /react|vue|svelte|preact|solid/.test(pkg) ? "framework islands: custom elements" : "not in ssqch yet: port it as a plugin"}`, { code: "astro-integration", status: /sitemap|rss/.test(pkg) ? "ssqch" : "site" }]);
|
|
2893
|
+
} else if (id === "vitepress") {
|
|
2894
|
+
listSyntax(plan, pages, [
|
|
2895
|
+
["containers (`::: tip`)", /^:::\s*(?:tip|info|warning|danger|details)\b/m, "containers, built in: `_includes/containers/tip.*` gives each its markup", "vitepress-containers", "ssqch"],
|
|
2896
|
+
["code groups (`::: code-group`)", /^:::\s*code-group\b/m, "a container with a template of its own", "vitepress-code-group", "ssqch"],
|
|
2897
|
+
["Vue components in pages", /^<[A-Z][\w-]*[\s/>]/m, "not in ssqch yet as written: custom elements, or Edge components", "vitepress-vue", "not-yet"],
|
|
2898
|
+
["Vue expressions (`{{ $frontmatter.x }}`)", /\{\{\s*\$\w+/, "template code: with `markdownEngine` on, ssqch's templates read front matter as `{{ x }}`", "vitepress-expressions", "site"],
|
|
2899
|
+
["`[[toc]]`", /^\[\[toc\]\]\s*$/m, "the `toc` filter in the layout, from `page.headings`", "vitepress-toc", "ssqch"],
|
|
2900
|
+
["`<<< @/` snippets", /^<<<\s*@\//m, "not in ssqch yet as written: an include in a template engine", "vitepress-snippets", "not-yet"]
|
|
2901
|
+
]);
|
|
2902
|
+
const config = [".vitepress/config.ts", ".vitepress/config.mts", ".vitepress/config.js", ".vitepress/config.mjs", "docs/.vitepress/config.ts", "docs/.vitepress/config.mts", "docs/.vitepress/config.js"].find((f) => isFile(path.join(dir, f)));
|
|
2903
|
+
if (config) plan.byHand.push([config, "the config's `sidebar` and `nav`: ssqch's are data (`_data/nav.yml`) and `navTree`", { code: "vitepress-sidebar", status: "ssqch", docs: "navTree" }]);
|
|
2904
|
+
const theme = entries.find((e) => /(?:^|\/)\.vitepress\/theme\/index\.[jt]s$/.test(e.rel));
|
|
2905
|
+
if (theme) plan.byHand.push([theme.rel, "a custom theme (Vue): ssqch's layouts are templates; the theme's components become templates and custom elements", { code: "vitepress-theme", status: "site" }]);
|
|
2906
|
+
} else if (id === "hexo") {
|
|
2907
|
+
listSyntax(plan, pages, [
|
|
2908
|
+
["tag plugins (`{% codeblock %}`, `{% asset_img %}`, `{% post_link %}`)", /\{%\s*(?:codeblock|asset_img|asset_link|asset_path|post_link|post_path|blockquote|youtube|iframe|img|link|include_code|raw)\b/, "not in ssqch yet as written: filters or shortcodes of the site's own (Liquid's and Nunjucks' `{% %}` read them as tags)", "hexo-tag-plugins", "not-yet"],
|
|
2909
|
+
["`<!-- more -->`", /<!--\s*more\s*-->/, "an excerpt's end, as in ssqch", "hexo-more", "ssqch"]
|
|
2910
|
+
]);
|
|
2911
|
+
if (isDir(path.join(dir, "themes"))) plan.byHand.push(["themes", "the theme's layouts (EJS, Nunjucks, Pug): ssqch runs EJS and Nunjucks; Pug isn't in ssqch", { code: "hexo-theme", status: "site" }]);
|
|
2912
|
+
if (isDir(path.join(dir, "scaffolds"))) plan.byHand.push(["scaffolds", "scaffolds are ssqch's blueprints: `_blueprints/` and `ssqch new posts/pine.md`", { code: "hexo-scaffolds", status: "ssqch", docs: "blueprints" }]);
|
|
2913
|
+
for (const pkg of packagesLike(dir, /^hexo-/)) plan.byHand.push(["package.json", `${pkg}: ${/generator-sitemap/.test(pkg) ? "`sitemapPlugin()`" : /generator-feed/.test(pkg) ? "`rssPlugin()`" : /renderer-(?:ejs|nunjucks|marked|markdown-it)/.test(pkg) ? "ssqch renders it itself" : /generator-(?:archive|category|tag|index)/.test(pkg) ? "a page per tag or category by pagination" : "not in ssqch yet: port it as a plugin"}`, { code: "hexo-plugin", status: /sitemap|feed|renderer-(?:ejs|nunjucks|marked|markdown-it)|generator-(?:archive|category|tag|index)/.test(pkg) ? "ssqch" : "site" }]);
|
|
2914
|
+
}
|
|
2915
|
+
plan.byHand.push([".", `scout reads ${name} sites lightly (no draft yet): \`ssqch docs --from ${id}\` has ${name}'s words${TRAILHEADS[id] ? " and its trailhead" : ""}`, { code: `${id}-trailhead`, status: "ssqch", docs: `--from ${id}` }]);
|
|
2916
|
+
return plan;
|
|
2917
|
+
}
|
|
2918
|
+
export {
|
|
2919
|
+
SEO_INCLUDE,
|
|
2920
|
+
blankComments,
|
|
2921
|
+
detect,
|
|
2922
|
+
draftConfig,
|
|
2923
|
+
eleventy,
|
|
2924
|
+
hugo,
|
|
2925
|
+
jekyll,
|
|
2926
|
+
jekyllPermalink,
|
|
2927
|
+
jekyllTemplateNotes,
|
|
2928
|
+
mkdocs,
|
|
2929
|
+
other,
|
|
2930
|
+
patchOf,
|
|
2931
|
+
rewriteData,
|
|
2932
|
+
rewriteScript,
|
|
2933
|
+
rewriteTemplate,
|
|
2934
|
+
rewriteZolaFrontMatter,
|
|
2935
|
+
runScout,
|
|
2936
|
+
scoutJson,
|
|
2937
|
+
scoutReport,
|
|
2938
|
+
scoutText,
|
|
2939
|
+
setIn,
|
|
2940
|
+
siteConfig,
|
|
2941
|
+
tomlError,
|
|
2942
|
+
unifiedHunks,
|
|
2943
|
+
unwrapUrlLiterals,
|
|
2944
|
+
zola
|
|
2945
|
+
};
|