clarusjs 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/check/generate.d.ts +6 -0
- package/dist/check/generate.js +12 -22
- package/dist/cli/check.js +58 -15
- package/dist/cli/explain.js +0 -1
- package/dist/cli/index.js +0 -1
- package/dist/compiler/emit-client.js +1 -11
- package/dist/compiler/emit-server.js +1 -2
- package/dist/compiler/errors.js +0 -1
- package/dist/compiler/html-expr.js +2 -7
- package/dist/compiler/index.js +10 -8
- package/dist/compiler/ir.d.ts +1 -0
- package/dist/compiler/ir.js +9 -14
- package/dist/compiler/parse.d.ts +1 -0
- package/dist/compiler/parse.js +18 -19
- package/dist/compiler/script.js +2 -31
- package/dist/compiler/shared.js +0 -5
- package/dist/runtime/dom.js +4 -1
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -30
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +4 -0
- package/dist/runtime/loader.js +41 -2
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +32 -42
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/dist/server/handler.d.ts +18 -0
- package/dist/server/handler.js +80 -53
- package/dist/server/head.d.ts +36 -0
- package/dist/server/head.js +129 -0
- package/dist/server/manifest.js +0 -3
- package/dist/server/modes.js +0 -5
- package/dist/server/views.js +0 -7
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +9 -0
- package/dist/vite/build.js +43 -17
- package/dist/vite/links.d.ts +2 -0
- package/dist/vite/links.js +11 -10
- package/dist/vite/manifest.js +2 -10
- package/dist/vite/netlify.js +1 -7
- package/dist/vite/plugin.d.ts +35 -0
- package/dist/vite/plugin.js +162 -88
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/dist/vite/sitemap.d.ts +11 -0
- package/dist/vite/sitemap.js +31 -0
- package/package.json +18 -2
package/dist/vite/plugin.js
CHANGED
|
@@ -6,26 +6,29 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
6
6
|
}
|
|
7
7
|
return path;
|
|
8
8
|
};
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { createRequire } from 'node:module';
|
|
12
11
|
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
13
12
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
13
|
import { isRunnableDevEnvironment, normalizePath } from 'vite';
|
|
15
14
|
import { compile, scopeId, ClarusError } from '../compiler/index.js';
|
|
16
15
|
import { parse } from '../compiler/parse.js';
|
|
17
|
-
import { findClarusFiles, prerender } from './build.js';
|
|
16
|
+
import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, routeToFile } from './build.js';
|
|
17
|
+
export { packageOf } from './build.js';
|
|
18
|
+
export { gitDates } from './sitemap.js';
|
|
18
19
|
import { writeManifest } from './manifest.js';
|
|
19
20
|
import { writeNetlifyFunction } from './netlify.js';
|
|
20
21
|
import { checkLinks } from './links.js';
|
|
22
|
+
import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
|
|
23
|
+
import { projectAliases, resolveAlias } from './aliases.js';
|
|
24
|
+
import { gitDates, sitemapXml } from './sitemap.js';
|
|
21
25
|
import { checkModes, modeFor } from '../server/modes.js';
|
|
22
|
-
import { routeFromFile } from '../server/handler.js';
|
|
26
|
+
import { rootLinks, routeFromFile } from '../server/handler.js';
|
|
27
|
+
import { basePath } from '../server/head.js';
|
|
23
28
|
import { sendResponse, toRequest } from './node.js';
|
|
24
|
-
// From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
|
|
25
29
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
26
30
|
const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
|
|
27
31
|
const ENTRY = 'virtual:clarusjs/server-entry';
|
|
28
|
-
/** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
|
|
29
32
|
export function clientUrlFor(root, file) {
|
|
30
33
|
const rel = relative(root, file);
|
|
31
34
|
return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
|
|
@@ -34,16 +37,17 @@ const LOADER_ENTRY = 'cl-loader';
|
|
|
34
37
|
const ROUTER_ENTRY = 'cl-router';
|
|
35
38
|
const NAV_ENTRY = 'cl-nav';
|
|
36
39
|
const STYLES_ENTRY = 'cl-styles';
|
|
37
|
-
// Every component's <style>, generated into one stylesheet (gitignored, like the rest of .clarusjs/).
|
|
38
40
|
const STYLES_FILE = '.clarusjs/styles.css';
|
|
39
|
-
/** Scope ids come from the path relative to the app root, so server, client and stylesheet always agree. */
|
|
40
41
|
const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
|
|
41
|
-
|
|
42
|
-
* Each page's stylesheets (absolute paths), from its own `@import './x.css'` and its components', transitively.
|
|
43
|
-
* Dependencies come first, so a layout's base CSS is linked before what the page adds.
|
|
44
|
-
*/
|
|
45
|
-
function pageStylesheets(root, files) {
|
|
42
|
+
function pageStylesheets(root, files, aliases = []) {
|
|
46
43
|
const deps = new Map();
|
|
44
|
+
const require = createRequire(resolve(root, 'package.json'));
|
|
45
|
+
const packageFile = (spec) => { try {
|
|
46
|
+
return realpathSync(require.resolve(spec.replace(/\?.*$/, '')));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
} };
|
|
47
51
|
const read = (file) => {
|
|
48
52
|
if (!deps.has(file)) {
|
|
49
53
|
let parsed;
|
|
@@ -52,15 +56,15 @@ function pageStylesheets(root, files) {
|
|
|
52
56
|
}
|
|
53
57
|
catch {
|
|
54
58
|
parsed = null;
|
|
55
|
-
}
|
|
56
|
-
// Relative to the file, or root-relative ('/src/layouts/docs.tscl', as Vite resolves it).
|
|
59
|
+
}
|
|
57
60
|
const near = (from) => {
|
|
58
61
|
const path = from.replace(/\?.*$/, '');
|
|
59
62
|
return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
|
|
60
63
|
};
|
|
64
|
+
const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from);
|
|
61
65
|
deps.set(file, {
|
|
62
|
-
css: parsed?.cssImports.map((c) => near(c.from)) ?? [],
|
|
63
|
-
components: parsed?.imports.
|
|
66
|
+
css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
|
|
67
|
+
components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
|
|
64
68
|
});
|
|
65
69
|
}
|
|
66
70
|
return deps.get(file);
|
|
@@ -85,29 +89,37 @@ function pageStylesheets(root, files) {
|
|
|
85
89
|
}
|
|
86
90
|
return pages;
|
|
87
91
|
}
|
|
88
|
-
/** Write .clarusjs/styles.css from every component under src/; false when no component has a <style>. */
|
|
89
92
|
function writeStyles(root, files) {
|
|
90
93
|
let css = '';
|
|
91
|
-
|
|
94
|
+
const head = new Set();
|
|
95
|
+
const outDir = resolve(root, '.clarusjs');
|
|
96
|
+
for (const file of files.components(root)) {
|
|
92
97
|
try {
|
|
93
|
-
|
|
98
|
+
let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
|
|
99
|
+
out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
|
|
100
|
+
for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
|
|
101
|
+
head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
|
|
102
|
+
const target = relative(outDir, resolve(file, '..', spec)).split(sep).join('/');
|
|
103
|
+
return q + (target.startsWith('.') ? target : `./${target}`) + q;
|
|
104
|
+
}) + ';');
|
|
105
|
+
}
|
|
106
|
+
return '';
|
|
107
|
+
});
|
|
94
108
|
if (out)
|
|
95
109
|
css += `/* ${relative(root, file).split(sep).join('/')} */\n${out}`;
|
|
96
110
|
}
|
|
97
|
-
catch { }
|
|
111
|
+
catch { }
|
|
98
112
|
}
|
|
99
|
-
|
|
113
|
+
css = [...head].map((x) => `${x}\n`).join('') + css;
|
|
114
|
+
mkdirSync(outDir, { recursive: true });
|
|
100
115
|
writeFileSync(resolve(root, STYLES_FILE), css);
|
|
101
116
|
return css !== '';
|
|
102
117
|
}
|
|
103
|
-
// Client entry name of a client-mode page's browser render module.
|
|
104
118
|
const renderEntry = (name) => `render/${name}`;
|
|
105
119
|
const CLIENT_OUT = 'dist/client';
|
|
106
|
-
// Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
|
|
107
120
|
const CHUNK_TOKEN = '__CLARUS_CHUNK__';
|
|
108
121
|
const SERVER_OUT = 'dist/server';
|
|
109
|
-
const entryName = (root, file) => relative(root, file).replace(/\.[^./\\]+$/, '');
|
|
110
|
-
/** Client-mode pages: route (as the file names it) → absolute file. */
|
|
122
|
+
const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
|
|
111
123
|
function clientPages(appRoot, modes, files) {
|
|
112
124
|
const pages = new Map();
|
|
113
125
|
for (const file of files.find(resolve(appRoot, 'src/pages'))) {
|
|
@@ -121,6 +133,8 @@ export default function clarusjs(options = {}) {
|
|
|
121
133
|
const modes = options.routes ?? {};
|
|
122
134
|
checkModes(modes);
|
|
123
135
|
const sources = options.sources ?? [];
|
|
136
|
+
if (options.site && !/^https?:\/\/[^/]/.test(options.site.url))
|
|
137
|
+
throw new Error(`clarusjs: site.url must be an absolute http(s) URL, got "${options.site.url}"`);
|
|
124
138
|
for (const src of sources) {
|
|
125
139
|
if (!/^\.[\w-]+$/.test(src.extension))
|
|
126
140
|
throw new Error(`clarusjs: a source extension must look like ".md", got "${src.extension}"`);
|
|
@@ -128,10 +142,10 @@ export default function clarusjs(options = {}) {
|
|
|
128
142
|
throw new Error('clarusjs: .tscl files are compiled directly; a source needs its own extension');
|
|
129
143
|
}
|
|
130
144
|
const extensions = ['.tscl', ...sources.map((src) => src.extension)];
|
|
131
|
-
|
|
132
|
-
// Page sources only apply under src/pages: elsewhere (src/parts, …) their files are plain files, not components.
|
|
145
|
+
let aliases = [];
|
|
133
146
|
const files = {
|
|
134
147
|
find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
|
|
148
|
+
components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions, aliases),
|
|
135
149
|
read: (file, appRoot) => {
|
|
136
150
|
const code = readFileSync(file, 'utf8');
|
|
137
151
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
@@ -149,9 +163,6 @@ export default function clarusjs(options = {}) {
|
|
|
149
163
|
let root = process.cwd();
|
|
150
164
|
let command = 'serve';
|
|
151
165
|
let base = '/';
|
|
152
|
-
// `vite build` only: client entry name (see entryName) → public URL of its hashed chunk.
|
|
153
|
-
// Read from the client manifest on disk, because Vite resolves config (and so creates a new plugin instance) per
|
|
154
|
-
// environment: the server build cannot see state set during the client build.
|
|
155
166
|
let built;
|
|
156
167
|
const builtUrls = () => {
|
|
157
168
|
if (command !== 'build')
|
|
@@ -164,7 +175,6 @@ export default function clarusjs(options = {}) {
|
|
|
164
175
|
}
|
|
165
176
|
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
166
177
|
built = new Map();
|
|
167
|
-
// By entry name, and by source key: names are sanitized ([id] → _id_), keys keep the real path.
|
|
168
178
|
for (const [key, chunk] of Object.entries(manifest)) {
|
|
169
179
|
if (!chunk.isEntry)
|
|
170
180
|
continue;
|
|
@@ -177,31 +187,44 @@ export default function clarusjs(options = {}) {
|
|
|
177
187
|
return {
|
|
178
188
|
name: 'clarusjs',
|
|
179
189
|
config(userConfig, env) {
|
|
190
|
+
const projectRoot = resolve(userConfig.root ?? process.cwd());
|
|
191
|
+
aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
|
|
192
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
193
|
+
const own = projectAliases(projectRoot).map((a) => ({ find: new RegExp(`^${escape(a.find)}${a.exact ? '$' : a.find.endsWith('/') ? '' : '(?=/|$)'}`), replacement: a.replacement }));
|
|
180
194
|
const config = {
|
|
181
195
|
appType: 'custom',
|
|
182
196
|
resolve: {
|
|
183
197
|
alias: [
|
|
184
198
|
{ find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
|
|
185
199
|
{ find: 'clarusjs/runtime', replacement: here('../runtime/index') },
|
|
200
|
+
...own,
|
|
186
201
|
],
|
|
187
202
|
},
|
|
188
203
|
};
|
|
189
204
|
if (env.isPreview)
|
|
190
|
-
config.build = { outDir: CLIENT_OUT };
|
|
205
|
+
config.build = { outDir: CLIENT_OUT };
|
|
206
|
+
const shipping = new Set();
|
|
207
|
+
if (!env.isPreview) {
|
|
208
|
+
for (const file of files.components(resolve(userConfig.root ?? process.cwd()))) {
|
|
209
|
+
const name = packageOfFile(file);
|
|
210
|
+
if (name)
|
|
211
|
+
shipping.add(name);
|
|
212
|
+
}
|
|
213
|
+
if (shipping.size)
|
|
214
|
+
config.ssr = { noExternal: [...shipping] };
|
|
215
|
+
}
|
|
191
216
|
if (env.command !== 'build')
|
|
192
217
|
return config;
|
|
193
218
|
if (userConfig.base !== undefined && !userConfig.base.startsWith('/') && !/^https?:\/\//.test(userConfig.base)) {
|
|
194
|
-
// Pages live at different depths and islands are imported from the loader, so URLs must not be relative.
|
|
195
219
|
throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
|
|
196
220
|
}
|
|
197
|
-
// Client entries: the island loader plus every stateful component. Stateless components never reach the client.
|
|
198
221
|
const appRoot = resolve(userConfig.root ?? process.cwd());
|
|
199
222
|
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
200
|
-
|
|
223
|
+
const components = files.components(appRoot);
|
|
224
|
+
for (const file of components) {
|
|
201
225
|
if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
|
|
202
226
|
input[entryName(appRoot, file)] = file;
|
|
203
227
|
}
|
|
204
|
-
// Client routes: the router, and each page's render function for the browser.
|
|
205
228
|
const client = clientPages(appRoot, modes, files);
|
|
206
229
|
if (client.size)
|
|
207
230
|
input[ROUTER_ENTRY] = here('../runtime/router');
|
|
@@ -209,36 +232,29 @@ export default function clarusjs(options = {}) {
|
|
|
209
232
|
input[NAV_ENTRY] = here('../runtime/fragments');
|
|
210
233
|
if (writeStyles(appRoot, files))
|
|
211
234
|
input[STYLES_ENTRY] = resolve(appRoot, STYLES_FILE);
|
|
212
|
-
|
|
213
|
-
for (const sheet of new Set([...pageStylesheets(appRoot, files).values()].flat())) {
|
|
235
|
+
for (const sheet of new Set([...pageStylesheets(appRoot, files, aliases).values()].flat())) {
|
|
214
236
|
if (!existsSync(sheet))
|
|
215
237
|
throw new Error(`clarusjs: imported stylesheet not found: ${relative(appRoot, sheet)}`);
|
|
216
|
-
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '')}`] = sheet;
|
|
238
|
+
input[`css/${relative(appRoot, sheet).split(sep).join('/').replace(/\.css$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3))}`] = sheet;
|
|
217
239
|
}
|
|
218
240
|
for (const file of client.values())
|
|
219
241
|
input[renderEntry(entryName(appRoot, file))] = `${file}?render`;
|
|
220
242
|
config.builder = {};
|
|
221
243
|
config.environments = {
|
|
222
|
-
// Island chunks are loaded with import() and must keep their `attach` export.
|
|
223
244
|
client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
|
|
224
|
-
// Always .mjs, so Node loads it as ESM whatever the app's package.json says.
|
|
225
245
|
ssr: { build: { outDir: SERVER_OUT, rolldownOptions: { input: { index: ENTRY }, output: { entryFileNames: '[name].mjs' } } } },
|
|
226
246
|
};
|
|
227
247
|
return config;
|
|
228
248
|
},
|
|
229
|
-
// Each build re-reads the client manifest: a builder can run buildApp() more than once.
|
|
230
249
|
buildStart() { built = undefined; },
|
|
231
|
-
// Client build: nested islands rendered in the browser get their chunk's real URL.
|
|
232
250
|
generateBundle(_options, bundle) {
|
|
233
251
|
if (this.environment.config.consumer !== 'client' || command !== 'build')
|
|
234
252
|
return;
|
|
235
253
|
const byName = new Map();
|
|
236
|
-
// By sanitized name and by the raw entry name from the source path ([id] stays [id]).
|
|
237
254
|
for (const out of Object.values(bundle)) {
|
|
238
255
|
if (out.type !== 'chunk' || !out.isEntry)
|
|
239
256
|
continue;
|
|
240
257
|
byName.set(out.name, base + out.fileName);
|
|
241
|
-
// Only island chunks: a client page's ?render chunk would otherwise take its island's place.
|
|
242
258
|
if (out.facadeModuleId && !/[?&]render\b/.test(out.facadeModuleId))
|
|
243
259
|
byName.set(entryName(root, out.facadeModuleId.replace(/\?.*$/, '')), base + out.fileName);
|
|
244
260
|
}
|
|
@@ -258,39 +274,56 @@ export default function clarusjs(options = {}) {
|
|
|
258
274
|
command = config.command;
|
|
259
275
|
base = config.base;
|
|
260
276
|
},
|
|
261
|
-
// Order matters: the server build needs the client's hashed URLs, and prerendering needs the server build.
|
|
262
277
|
async buildApp(builder) {
|
|
263
278
|
const { client, ssr } = builder.environments;
|
|
264
279
|
if (!client || !ssr)
|
|
265
280
|
return;
|
|
281
|
+
checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
|
|
266
282
|
await builder.build(client);
|
|
267
283
|
await builder.build(ssr);
|
|
268
284
|
const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
|
|
269
285
|
const out = resolve(builder.config.root, CLIENT_OUT);
|
|
270
286
|
const dist = dirname(out);
|
|
271
287
|
const manifestFile = resolve(dist, 'clarusjs-manifest.json');
|
|
272
|
-
rmSync(manifestFile, { force: true });
|
|
288
|
+
rmSync(manifestFile, { force: true });
|
|
273
289
|
const { routes, readers, loaded, server } = await prerender(entry, out, manifestFile);
|
|
274
290
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
275
|
-
// Pages that read the manifest saw none on the first pass: render them again now that it exists.
|
|
276
291
|
if (readers.length) {
|
|
277
292
|
await prerender(entry, out, manifestFile, readers);
|
|
278
293
|
writeManifest(dist, routes, builder.config.base, loaded, server);
|
|
279
294
|
}
|
|
280
|
-
// Links between pages and to anchors, checked against what was written.
|
|
281
295
|
const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
|
|
296
|
+
const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
|
|
297
|
+
if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
|
|
298
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
|
|
299
|
+
writeFileSync(resolve(out, routeToFile('/404')), html);
|
|
300
|
+
writeFileSync(resolve(out, '404.html'), html);
|
|
301
|
+
}
|
|
302
|
+
if (pageRoutes.includes('/500') && !clientRoutes.includes('/500')) {
|
|
303
|
+
const html = rootLinks(readFileSync(resolve(out, routeToFile('/500')), 'utf8'), basePath(builder.config.base));
|
|
304
|
+
writeFileSync(resolve(out, routeToFile('/500')), html);
|
|
305
|
+
writeFileSync(resolve(out, '500.html'), html);
|
|
306
|
+
}
|
|
307
|
+
if (options.redirects) {
|
|
308
|
+
writeRedirects(out, options.redirects, basePath(builder.config.base).replace(/\/$/, ''), routes);
|
|
309
|
+
const moved = Object.keys(options.redirects).map((from) => (from.length > 1 ? from.replace(/\/+$/, '') : from));
|
|
310
|
+
pageRoutes.push(...moved);
|
|
311
|
+
clientRoutes.push(...moved);
|
|
312
|
+
}
|
|
282
313
|
const issues = checkLinks({
|
|
283
314
|
outDir: out,
|
|
284
315
|
routes: pageRoutes,
|
|
285
316
|
serverRoutes: server.map((x) => x.route),
|
|
286
|
-
clientRoutes
|
|
317
|
+
clientRoutes,
|
|
287
318
|
base: builder.config.base,
|
|
319
|
+
site: options.site?.url,
|
|
288
320
|
});
|
|
289
321
|
const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
|
|
290
|
-
// Each problem names the page's source file, and the line where the link is written literally.
|
|
291
322
|
const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
|
|
323
|
+
const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
324
|
+
const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
|
|
292
325
|
const locate = (page, href) => {
|
|
293
|
-
const file =
|
|
326
|
+
const file = fileOf(page);
|
|
294
327
|
if (!file)
|
|
295
328
|
return page;
|
|
296
329
|
const rel = relative(builder.config.root, file).split(sep).join('/');
|
|
@@ -310,21 +343,45 @@ export default function clarusjs(options = {}) {
|
|
|
310
343
|
}
|
|
311
344
|
if (errors.length)
|
|
312
345
|
throw new Error(`clarusjs: broken links:\n ${errors.join('\n ')}`);
|
|
346
|
+
if (options.site && options.sitemap !== false) {
|
|
347
|
+
const dates = gitDates(builder.config.root, 'src/pages');
|
|
348
|
+
const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
|
|
349
|
+
const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
|
|
350
|
+
.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
|
|
351
|
+
const optedOut = (page) => {
|
|
352
|
+
const file = resolve(out, routeToFile(page));
|
|
353
|
+
const html = readFileSync(file, 'utf8');
|
|
354
|
+
const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
|
|
355
|
+
const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
|
|
356
|
+
const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
|
|
357
|
+
if (marker)
|
|
358
|
+
writeFileSync(file, html.replace(marker, ''));
|
|
359
|
+
return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
|
|
360
|
+
};
|
|
361
|
+
const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
|
|
362
|
+
.map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
|
|
363
|
+
writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
|
|
364
|
+
}
|
|
365
|
+
if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
|
|
366
|
+
const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
|
|
367
|
+
writeFileSync(resolve(out, 'robots.txt'), `User-agent: *\nAllow: /\n${sitemap}`);
|
|
368
|
+
}
|
|
313
369
|
if (options.adapter === 'netlify')
|
|
314
370
|
writeNetlifyFunction(builder.config.root, entry, server.map((s) => s.route), options.fragments === true);
|
|
315
371
|
},
|
|
316
|
-
resolveId(id) {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
372
|
+
resolveId: { order: 'pre', handler(id, importer) {
|
|
373
|
+
if (/^\.\/navigate\.[jt]s$/.test(id) && importer && /[\\/]runtime[\\/](router|fragments)\.[jt]s$/.test(importer)) {
|
|
374
|
+
return `${here('../runtime/navigate')}?cl-copy=${/router\.[jt]s$/.test(importer) ? 'router' : 'nav'}`;
|
|
375
|
+
}
|
|
376
|
+
if (id === '/cl-loader.js')
|
|
377
|
+
return here('../runtime/loader');
|
|
378
|
+
if (id === '/cl-router.js')
|
|
379
|
+
return here('../runtime/router');
|
|
380
|
+
if (id === '/cl-nav.js')
|
|
381
|
+
return here('../runtime/fragments');
|
|
382
|
+
if (id === ENTRY)
|
|
383
|
+
return '\0' + ENTRY;
|
|
384
|
+
} },
|
|
328
385
|
load: { order: 'pre', handler(id) {
|
|
329
386
|
if (id !== '\0' + ENTRY) {
|
|
330
387
|
if (/[?&](raw|url|inline)\b/.test(id) || id.startsWith('\0'))
|
|
@@ -338,9 +395,8 @@ export default function clarusjs(options = {}) {
|
|
|
338
395
|
const loaderUrl = urls?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
339
396
|
const routerUrl = urls?.get(ROUTER_ENTRY) ?? '/cl-router.js';
|
|
340
397
|
const navUrl = urls?.get(NAV_ENTRY) ?? '/cl-nav.js';
|
|
341
|
-
// Each page's imported stylesheets: built URLs (by source key), or the source served by Vite in dev.
|
|
342
398
|
const css = {};
|
|
343
|
-
for (const [route, sheets] of pageStylesheets(root, files)) {
|
|
399
|
+
for (const [route, sheets] of pageStylesheets(root, files, aliases)) {
|
|
344
400
|
if (!sheets.length)
|
|
345
401
|
continue;
|
|
346
402
|
css[route] = sheets.map((sheet) => {
|
|
@@ -351,9 +407,7 @@ export default function clarusjs(options = {}) {
|
|
|
351
407
|
return url;
|
|
352
408
|
});
|
|
353
409
|
}
|
|
354
|
-
// Built: the hashed stylesheet, if any component has styles. Dev: the generated file, served by Vite.
|
|
355
410
|
const stylesUrl = urls ? urls.get(STYLES_ENTRY) : writeStyles(root, files) ? `/${STYLES_FILE}` : undefined;
|
|
356
|
-
// Built: hashed chunk URLs. Dev: the source, served as JS by Vite.
|
|
357
411
|
const client = {};
|
|
358
412
|
for (const [route, file] of clientPages(root, modes, files)) {
|
|
359
413
|
const key = `${relative(root, file).split(sep).join('/')}?render`;
|
|
@@ -364,7 +418,6 @@ export default function clarusjs(options = {}) {
|
|
|
364
418
|
}
|
|
365
419
|
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
366
420
|
`import { registerViews, render } from ${JSON.stringify(here('../server/views'))}\n` +
|
|
367
|
-
// Every view under src/, for render(name, props) in server code. Also exported for apps that import the build.
|
|
368
421
|
`registerViews(import.meta.glob(${JSON.stringify(['/src/**/*.tscl', ...extensions.slice(1).map((e) => `/src/pages/**/*${e}`)])}))\n` +
|
|
369
422
|
`export { render }\n` +
|
|
370
423
|
`export default createHandler(import.meta.glob(${glob('/src/pages')}), {\n` +
|
|
@@ -375,17 +428,18 @@ export default function clarusjs(options = {}) {
|
|
|
375
428
|
` client: ${JSON.stringify(client)},\n` +
|
|
376
429
|
` base: ${JSON.stringify(base)},\n` +
|
|
377
430
|
` fragments: ${options.fragments === true},\n` +
|
|
431
|
+
` dev: ${command === 'serve'},\n` +
|
|
378
432
|
` navUrl: ${JSON.stringify(navUrl)},\n` +
|
|
379
433
|
` stylesUrl: ${JSON.stringify(stylesUrl)},\n` +
|
|
380
434
|
` css: ${JSON.stringify(css)},\n` +
|
|
435
|
+
` site: ${JSON.stringify(options.site)},\n` +
|
|
436
|
+
` head: { ...${JSON.stringify(options.head ?? {})}, transform: Object.values(import.meta.glob('/src/head.ts', { eager: true }))[0]?.transformHead },\n` +
|
|
381
437
|
`})\n`;
|
|
382
438
|
} },
|
|
383
439
|
transform: {
|
|
384
440
|
filter: { id: fileRe },
|
|
385
|
-
handler(raw, id) {
|
|
441
|
+
async handler(raw, id) {
|
|
386
442
|
const file = id.replace(/\?.*$/, '');
|
|
387
|
-
// A page source's file is compiled from the .tscl text it produces: only under src/pages, and never when it is
|
|
388
|
-
// imported as text or a URL (CHANGELOG.md?raw stays a string).
|
|
389
443
|
const src = sources.find((x) => file.endsWith(x.extension));
|
|
390
444
|
if (src && (/[?&](raw|url|inline)\b/.test(id) || !normalizePath(file).startsWith(normalizePath(resolve(root, 'src/pages')) + '/')))
|
|
391
445
|
return null;
|
|
@@ -393,25 +447,34 @@ export default function clarusjs(options = {}) {
|
|
|
393
447
|
const code = src
|
|
394
448
|
? src.toTscl(raw, file, { route: rel.startsWith('src/pages/') ? routeFromFile(`/${rel}`) : '', root, addDependency: (dep) => this.addWatchFile(dep) })
|
|
395
449
|
: raw;
|
|
396
|
-
// ?render: a component's server render function, used in the browser to render children of islands.
|
|
397
450
|
const renderQuery = /[?&]render\b/.test(id);
|
|
398
451
|
const target = this.environment.config.consumer === 'server' || renderQuery ? 'server' : 'client';
|
|
399
|
-
// ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
|
|
400
452
|
const consumer = this.environment.config.consumer;
|
|
401
|
-
// Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
|
|
402
|
-
// exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
|
|
403
453
|
const urls = consumer === 'server' ? builtUrls() : undefined;
|
|
404
|
-
// Built URLs by entry name, or by source key when the name was sanitized ([tag] → _tag_).
|
|
405
454
|
const clientUrl = urls
|
|
406
455
|
? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/'))
|
|
407
456
|
: command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
|
|
408
457
|
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
409
458
|
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
410
459
|
}
|
|
460
|
+
let parsed;
|
|
461
|
+
try {
|
|
462
|
+
parsed = parse(code, file);
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
parsed = null;
|
|
466
|
+
}
|
|
467
|
+
for (const imp of parsed ? [...parsed.imports, ...parsed.dataImports, ...parsed.cssImports] : []) {
|
|
468
|
+
if (/^[./]/.test(imp.from) || /^[a-z]+:/i.test(imp.from))
|
|
469
|
+
continue;
|
|
470
|
+
if (await this.resolve(imp.from.replace(/\?.*$/, ''), id))
|
|
471
|
+
continue;
|
|
472
|
+
const before = code.slice(0, imp.start);
|
|
473
|
+
const line = before.split('\n').length;
|
|
474
|
+
this.error(`${rel}:${line}:${imp.start - before.lastIndexOf('\n')} cannot resolve '${imp.from}': no file, package or path alias (~/, tsconfig paths, resolve.alias) matches it`);
|
|
475
|
+
}
|
|
411
476
|
try {
|
|
412
|
-
// A ?render module runs in the browser: its child components must be render modules too.
|
|
413
477
|
const renderImports = renderQuery && this.environment.config.consumer !== 'server';
|
|
414
|
-
// moduleType: a source extension may have its own built-in type in Rolldown (.txt is text); the output is JS.
|
|
415
478
|
return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
|
|
416
479
|
}
|
|
417
480
|
catch (err) {
|
|
@@ -421,28 +484,25 @@ export default function clarusjs(options = {}) {
|
|
|
421
484
|
}
|
|
422
485
|
},
|
|
423
486
|
},
|
|
424
|
-
// The built site is static files: /guide/x is guide/x/index.html. appType 'custom' turns off Vite's own lookup.
|
|
425
487
|
configurePreviewServer(server) {
|
|
426
488
|
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
427
|
-
const base = server.config.base;
|
|
489
|
+
const base = server.config.base;
|
|
428
490
|
server.middlewares.use((req, _res, next) => {
|
|
429
491
|
let url;
|
|
430
492
|
try {
|
|
431
493
|
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
432
494
|
}
|
|
433
495
|
catch {
|
|
434
|
-
return next();
|
|
496
|
+
return next();
|
|
435
497
|
}
|
|
436
498
|
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
437
499
|
if (inBase !== undefined) {
|
|
438
|
-
// A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
|
|
439
500
|
const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
|
|
440
501
|
if (file.startsWith(outDir) && existsSync(file))
|
|
441
502
|
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
442
503
|
}
|
|
443
504
|
next();
|
|
444
505
|
});
|
|
445
|
-
// Server routes go to the built handler, as they would in production; anything else that isn't a file is a 404.
|
|
446
506
|
return () => {
|
|
447
507
|
server.middlewares.use(async (req, res, next) => {
|
|
448
508
|
try {
|
|
@@ -461,10 +521,17 @@ export default function clarusjs(options = {}) {
|
|
|
461
521
|
next(err);
|
|
462
522
|
}
|
|
463
523
|
});
|
|
524
|
+
server.middlewares.use((req, res, next) => {
|
|
525
|
+
const page = resolve(outDir, '404.html');
|
|
526
|
+
if ((req.method !== 'GET' && req.method !== 'HEAD') || !existsSync(page))
|
|
527
|
+
return next();
|
|
528
|
+
res.statusCode = 404;
|
|
529
|
+
res.setHeader('content-type', 'text/html; charset=utf-8');
|
|
530
|
+
res.end(req.method === 'HEAD' ? undefined : readFileSync(page));
|
|
531
|
+
});
|
|
464
532
|
};
|
|
465
533
|
},
|
|
466
534
|
configureServer(server) {
|
|
467
|
-
// Component styles change with their .tscl files: regenerate the stylesheet (Vite then updates the page's CSS).
|
|
468
535
|
const restyle = (file) => { if (fileRe.test(file))
|
|
469
536
|
writeStyles(server.config.root, files); };
|
|
470
537
|
server.watcher.on('change', restyle);
|
|
@@ -476,9 +543,16 @@ export default function clarusjs(options = {}) {
|
|
|
476
543
|
const env = server.environments.ssr;
|
|
477
544
|
if (!isRunnableDevEnvironment(env))
|
|
478
545
|
return next();
|
|
546
|
+
if (options.redirects) {
|
|
547
|
+
const prefix = basePath(server.config.base).replace(/\/$/, '');
|
|
548
|
+
const pathname = new URL(req.url ?? '/', 'http://x').pathname;
|
|
549
|
+
const to = redirectFor(options.redirects, pathname.startsWith(prefix + '/') ? pathname.slice(prefix.length) : pathname, prefix);
|
|
550
|
+
if (to !== undefined)
|
|
551
|
+
return void res.writeHead(301, { location: to }).end();
|
|
552
|
+
}
|
|
479
553
|
const app = await env.runner.import(ENTRY);
|
|
480
554
|
const response = await app.default.fetch(toRequest(req));
|
|
481
|
-
if (response.status === 404)
|
|
555
|
+
if (response.status === 404 && !response.headers.get('content-type')?.startsWith('text/html'))
|
|
482
556
|
return next();
|
|
483
557
|
await sendResponse(res, response);
|
|
484
558
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Old paths start with /; none may be a page (`pages`: the site's routes, [param] segments matching any one). */
|
|
2
|
+
export declare function checkRedirects(redirects: Record<string, string>, pages?: string[]): void;
|
|
3
|
+
/** The redirect for a request path in dev (the base already removed), or undefined. */
|
|
4
|
+
export declare function redirectFor(redirects: Record<string, string>, pathname: string, prefix: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Writes each old path's page and the _redirects lines (after any the site's public/ already has). `built`: every
|
|
7
|
+
* route the build wrote (pages, data and fragment files); a redirect whose file would replace one of them, or land
|
|
8
|
+
* outside `out` (%2e%2e segments), fails before anything is written.
|
|
9
|
+
*/
|
|
10
|
+
export declare function writeRedirects(out: string, redirects: Record<string, string>, prefix: string, built?: string[]): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, resolve, sep } from 'node:path';
|
|
3
|
+
import { routeToFile } from './build.js';
|
|
4
|
+
const attr = (s) => s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
5
|
+
export function checkRedirects(redirects, pages = []) {
|
|
6
|
+
const route = (r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
|
|
7
|
+
for (const from of Object.keys(redirects)) {
|
|
8
|
+
if (!from.startsWith('/'))
|
|
9
|
+
throw new Error(`clarusjs: redirects['${from}']: paths start with /`);
|
|
10
|
+
if (pages.some((p) => route(p).test(trim(from))))
|
|
11
|
+
throw new Error(`clarusjs: redirects['${from}']: ${from} is a page; remove the page or the redirect`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
|
|
15
|
+
const target = (to, prefix) => (to.startsWith('/') ? prefix + to : to);
|
|
16
|
+
export function redirectFor(redirects, pathname, prefix) {
|
|
17
|
+
const to = Object.entries(redirects).find(([from]) => trim(from) === trim(pathname))?.[1];
|
|
18
|
+
return to === undefined ? undefined : target(to, prefix);
|
|
19
|
+
}
|
|
20
|
+
export function writeRedirects(out, redirects, prefix, built = []) {
|
|
21
|
+
const fileOf = (route) => resolve(out, routeToFile(route));
|
|
22
|
+
const taken = new Map(built.map((route) => [fileOf(route), route]));
|
|
23
|
+
for (const from of Object.keys(redirects)) {
|
|
24
|
+
const file = fileOf(from);
|
|
25
|
+
if (!file.startsWith(resolve(out) + sep))
|
|
26
|
+
throw new Error(`clarusjs: redirects['${from}'] is outside the site`);
|
|
27
|
+
if (taken.has(file))
|
|
28
|
+
throw new Error(`clarusjs: redirects['${from}'] would replace the page ${taken.get(file)}`);
|
|
29
|
+
}
|
|
30
|
+
const lines = [];
|
|
31
|
+
for (const [from, to] of Object.entries(redirects)) {
|
|
32
|
+
const url = attr(target(to, prefix));
|
|
33
|
+
const file = fileOf(from);
|
|
34
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
35
|
+
writeFileSync(file, `<!doctype html><html><head><meta charset="utf-8"><title>Moved</title><meta http-equiv="refresh" content="0; url=${url}"><link rel="canonical" href="${url}"><meta name="robots" content="noindex"></head><body><p>This page moved to <a href="${url}">${url}</a>.</p></body></html>\n`);
|
|
36
|
+
lines.push(`${prefix}${trim(from)} ${target(to, prefix)} 301\n`);
|
|
37
|
+
}
|
|
38
|
+
const file = resolve(out, '_redirects');
|
|
39
|
+
if (lines.length)
|
|
40
|
+
writeFileSync(file, (existsSync(file) ? readFileSync(file, 'utf8').replace(/\n?$/, '\n') : '') + lines.join(''));
|
|
41
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Newest commit time (unix seconds) of every file under `dir` that git knows, by absolute path. One `git log` lists
|
|
3
|
+
* commits newest first with the files each touched, so a file's first appearance is its last change. Not a git
|
|
4
|
+
* repository (or no git): an empty map.
|
|
5
|
+
*/
|
|
6
|
+
export declare function gitDates(root: string, dir: string): Map<string, number>;
|
|
7
|
+
/** The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known. */
|
|
8
|
+
export declare function sitemapXml(siteUrl: string, base: string, pages: {
|
|
9
|
+
path: string;
|
|
10
|
+
lastmod: number | undefined;
|
|
11
|
+
}[]): string;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
const xml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
4
|
+
export function gitDates(root, dir) {
|
|
5
|
+
const dates = new Map();
|
|
6
|
+
let log;
|
|
7
|
+
try {
|
|
8
|
+
log = execFileSync('git', ['log', '--format=%x01%ct', '-z', '--name-only', '--relative', '--', dir], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return dates;
|
|
12
|
+
}
|
|
13
|
+
for (const commit of log.split('\x01').slice(1)) {
|
|
14
|
+
const [time, ...files] = commit.split('\0');
|
|
15
|
+
for (const file of files.map((f) => f.replace(/^\n/, '')).filter(Boolean)) {
|
|
16
|
+
const path = resolve(root, file);
|
|
17
|
+
if (!dates.has(path))
|
|
18
|
+
dates.set(path, Number(time));
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return dates;
|
|
22
|
+
}
|
|
23
|
+
export function sitemapXml(siteUrl, base, pages) {
|
|
24
|
+
const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
|
|
25
|
+
const urls = pages.map(({ path, lastmod }) => {
|
|
26
|
+
const loc = new URL(`./${path.slice(1)}`, root).href;
|
|
27
|
+
const date = lastmod === undefined ? '' : `<lastmod>${new Date(lastmod * 1000).toISOString().slice(0, 10)}</lastmod>`;
|
|
28
|
+
return `<url><loc>${xml(loc)}</loc>${date}</url>\n`;
|
|
29
|
+
});
|
|
30
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('')}</urlset>\n`;
|
|
31
|
+
}
|