workers-start 0.2.1 → 0.4.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/CHANGELOG.md +13 -0
- package/README.md +18 -14
- package/dist/accept.d.ts.map +1 -1
- package/dist/accept.js +6 -2
- package/dist/accept.js.map +1 -1
- package/dist/check-bundle-cli.d.ts +1 -1
- package/dist/check-bundle-cli.js +23 -6
- package/dist/check-bundle-cli.js.map +1 -1
- package/dist/check-bundle.d.ts +7 -4
- package/dist/check-bundle.d.ts.map +1 -1
- package/dist/check-bundle.js +32 -11
- package/dist/check-bundle.js.map +1 -1
- package/dist/entry.d.ts +8 -2
- package/dist/entry.d.ts.map +1 -1
- package/dist/entry.js +33 -12
- package/dist/entry.js.map +1 -1
- package/dist/head.d.ts +57 -6
- package/dist/head.d.ts.map +1 -1
- package/dist/head.js +80 -10
- package/dist/head.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/scripts.d.ts.map +1 -1
- package/dist/scripts.js +6 -2
- package/dist/scripts.js.map +1 -1
- package/dist/workers.d.ts.map +1 -1
- package/dist/workers.js +2 -1
- package/dist/workers.js.map +1 -1
- package/package.json +1 -3
- package/src/accept.ts +10 -2
- package/src/check-bundle-cli.ts +38 -9
- package/src/check-bundle.ts +59 -16
- package/src/entry.ts +79 -27
- package/src/head.ts +162 -27
- package/src/index.ts +24 -4
- package/src/scripts.ts +6 -2
- package/src/workers.ts +18 -4
- package/biome.preset.json +0 -47
package/src/check-bundle.ts
CHANGED
|
@@ -27,7 +27,13 @@ const ENV_FILE = /^(\.env(\..+)?|\.dev\.vars(\..+)?)$/;
|
|
|
27
27
|
const NOT_SECRETS = /\.(example|sample|template|tpl)$/;
|
|
28
28
|
const KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/;
|
|
29
29
|
const INLINE_COMMENT = /\s+#.*$/;
|
|
30
|
-
const ESCAPES: Record<string, string> = {
|
|
30
|
+
const ESCAPES: Record<string, string> = {
|
|
31
|
+
n: "\n",
|
|
32
|
+
r: "\r",
|
|
33
|
+
t: "\t",
|
|
34
|
+
'"': '"',
|
|
35
|
+
"\\": "\\",
|
|
36
|
+
};
|
|
31
37
|
|
|
32
38
|
/**
|
|
33
39
|
* KEY=value pairs from a dotenv file, parsed the way dotenv does: `#`
|
|
@@ -54,7 +60,12 @@ export function parseEnvFile(source: string): [string, string][] {
|
|
|
54
60
|
}
|
|
55
61
|
const end = closingQuoteIndex(body, quote);
|
|
56
62
|
raw = end === -1 ? body : body.slice(0, end);
|
|
57
|
-
pairs.push([
|
|
63
|
+
pairs.push([
|
|
64
|
+
key,
|
|
65
|
+
quote === '"'
|
|
66
|
+
? raw.replace(/\\(.)/g, (m, c: string) => ESCAPES[c] ?? m)
|
|
67
|
+
: raw,
|
|
68
|
+
]);
|
|
58
69
|
} else {
|
|
59
70
|
pairs.push([key, raw.replace(INLINE_COMMENT, "").trim()]);
|
|
60
71
|
}
|
|
@@ -97,14 +108,21 @@ export interface LeakOptions {
|
|
|
97
108
|
}
|
|
98
109
|
|
|
99
110
|
/** The env keys whose values appear, in any encoding, in any of the given file contents. */
|
|
100
|
-
export function leakedKeys(
|
|
111
|
+
export function leakedKeys(
|
|
112
|
+
pairs: [string, string][],
|
|
113
|
+
contents: string[],
|
|
114
|
+
options: LeakOptions = {},
|
|
115
|
+
): string[] {
|
|
101
116
|
const publicPrefixes = options.publicPrefixes ?? DEFAULT_PUBLIC_PREFIXES;
|
|
102
117
|
const leaked = new Set<string>();
|
|
103
118
|
for (const [key, value] of pairs) {
|
|
104
119
|
if (value.length < MIN_SECRET_LENGTH || value.startsWith("op://")) {
|
|
105
120
|
continue;
|
|
106
121
|
}
|
|
107
|
-
if (
|
|
122
|
+
if (
|
|
123
|
+
options.allow?.includes(key) ||
|
|
124
|
+
publicPrefixes.some((prefix) => key.startsWith(prefix))
|
|
125
|
+
) {
|
|
108
126
|
continue;
|
|
109
127
|
}
|
|
110
128
|
const forms = encodings(value);
|
|
@@ -115,11 +133,15 @@ export function leakedKeys(pairs: [string, string][], contents: string[], option
|
|
|
115
133
|
return [...leaked].sort();
|
|
116
134
|
}
|
|
117
135
|
|
|
118
|
-
/** Every KEY=value pair in the local env files of
|
|
119
|
-
export function localEnvPairs(
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
136
|
+
/** Every KEY=value pair in the local env files of one or more directories. */
|
|
137
|
+
export function localEnvPairs(
|
|
138
|
+
dirs: string | readonly string[],
|
|
139
|
+
): [string, string][] {
|
|
140
|
+
return (typeof dirs === "string" ? [dirs] : dirs).flatMap((dir) =>
|
|
141
|
+
readdirSync(dir)
|
|
142
|
+
.filter((name) => ENV_FILE.test(name) && !NOT_SECRETS.test(name))
|
|
143
|
+
.flatMap((name) => parseEnvFile(readFileSync(join(dir, name), "utf8"))),
|
|
144
|
+
);
|
|
123
145
|
}
|
|
124
146
|
|
|
125
147
|
/**
|
|
@@ -127,7 +149,10 @@ export function localEnvPairs(dir: string): [string, string][] {
|
|
|
127
149
|
* walk never loops or leaves the directory. `skip` holds paths relative to
|
|
128
150
|
* `dir`, with forward slashes.
|
|
129
151
|
*/
|
|
130
|
-
export function listFiles(
|
|
152
|
+
export function listFiles(
|
|
153
|
+
dir: string,
|
|
154
|
+
skip: readonly string[] = DEFAULT_SKIP,
|
|
155
|
+
): string[] {
|
|
131
156
|
const files: string[] = [];
|
|
132
157
|
const walk = (current: string): void => {
|
|
133
158
|
for (const name of readdirSync(current)) {
|
|
@@ -138,7 +163,10 @@ export function listFiles(dir: string, skip: readonly string[] = DEFAULT_SKIP):
|
|
|
138
163
|
}
|
|
139
164
|
if (stat.isDirectory()) {
|
|
140
165
|
walk(path);
|
|
141
|
-
} else if (
|
|
166
|
+
} else if (
|
|
167
|
+
stat.isFile() &&
|
|
168
|
+
!skip.includes(relative(dir, path).split(sep).join("/"))
|
|
169
|
+
) {
|
|
142
170
|
files.push(path);
|
|
143
171
|
}
|
|
144
172
|
}
|
|
@@ -152,7 +180,8 @@ export function readBuilt(path: string): string {
|
|
|
152
180
|
const bytes = readFileSync(path);
|
|
153
181
|
try {
|
|
154
182
|
if (path.endsWith(".gz")) return gunzipSync(bytes).toString("latin1");
|
|
155
|
-
if (path.endsWith(".br"))
|
|
183
|
+
if (path.endsWith(".br"))
|
|
184
|
+
return brotliDecompressSync(bytes).toString("latin1");
|
|
156
185
|
} catch {
|
|
157
186
|
// Not really compressed; scan the bytes as they are.
|
|
158
187
|
}
|
|
@@ -169,16 +198,30 @@ export interface CheckOptions extends LeakOptions {
|
|
|
169
198
|
skip?: readonly string[];
|
|
170
199
|
}
|
|
171
200
|
|
|
172
|
-
/**
|
|
173
|
-
|
|
201
|
+
/**
|
|
202
|
+
* Scan one or more build directories against the local env files in one or
|
|
203
|
+
* more directories, such as a package and its monorepo root.
|
|
204
|
+
*/
|
|
205
|
+
export function checkBundle(
|
|
206
|
+
envDirs: string | readonly string[],
|
|
207
|
+
dists: string | readonly string[],
|
|
208
|
+
options: CheckOptions = {},
|
|
209
|
+
): CheckResult {
|
|
174
210
|
const dirs = typeof dists === "string" ? [dists] : dists;
|
|
175
211
|
for (const dir of dirs) {
|
|
176
212
|
if (!existsSync(dir)) {
|
|
177
213
|
throw new Error(`${dir} does not exist. Build first.`);
|
|
178
214
|
}
|
|
179
215
|
}
|
|
180
|
-
const
|
|
181
|
-
|
|
216
|
+
for (const dir of typeof envDirs === "string" ? [envDirs] : envDirs) {
|
|
217
|
+
if (!existsSync(dir)) {
|
|
218
|
+
throw new Error(`Env directory ${dir} does not exist.`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const pairs = localEnvPairs(envDirs);
|
|
222
|
+
const files = dirs.flatMap((dir) =>
|
|
223
|
+
listFiles(dir, options.skip ?? DEFAULT_SKIP),
|
|
224
|
+
);
|
|
182
225
|
const leaked = leakedKeys(pairs, files.map(readBuilt), options);
|
|
183
226
|
return { envValues: pairs.length, files: files.length, leaked };
|
|
184
227
|
}
|
package/src/entry.ts
CHANGED
|
@@ -17,7 +17,17 @@ import { parseAccept, quality } from "./accept.js";
|
|
|
17
17
|
type MaybePromise<T> = T | Promise<T>;
|
|
18
18
|
|
|
19
19
|
/** What a Markdown renderer returns: a body, a body with a status, or null to serve HTML. */
|
|
20
|
-
export type MarkdownResult =
|
|
20
|
+
export type MarkdownResult =
|
|
21
|
+
| string
|
|
22
|
+
| { body: string; status?: number }
|
|
23
|
+
| null
|
|
24
|
+
| undefined;
|
|
25
|
+
|
|
26
|
+
/** What the Markdown renderer can reach besides the path and request. */
|
|
27
|
+
export interface MarkdownPage {
|
|
28
|
+
/** The page rendered by the handler with `Accept: text/html`, the extra fetch arguments passed through. */
|
|
29
|
+
html(): Promise<Response>;
|
|
30
|
+
}
|
|
21
31
|
|
|
22
32
|
export interface FetchHandler {
|
|
23
33
|
// biome-ignore lint/suspicious/noExplicitAny: handlers pass framework-specific extra arguments through.
|
|
@@ -31,9 +41,14 @@ export interface EntryOptions {
|
|
|
31
41
|
* Markdown rendering of a page. Called for GET and HEAD page requests that
|
|
32
42
|
* prefer text/markdown, with the decoded path, no trailing slash. Return
|
|
33
43
|
* null to serve HTML instead. If it throws, the error is logged and HTML is
|
|
34
|
-
* served.
|
|
44
|
+
* served. `page.html()` renders the same request through the handler as
|
|
45
|
+
* HTML, for a renderer that converts the page instead of building it.
|
|
35
46
|
*/
|
|
36
|
-
markdown?: (
|
|
47
|
+
markdown?: (
|
|
48
|
+
path: string,
|
|
49
|
+
request: Request,
|
|
50
|
+
page: MarkdownPage,
|
|
51
|
+
) => MaybePromise<MarkdownResult>;
|
|
37
52
|
/**
|
|
38
53
|
* Path prefixes that only accept GET, HEAD and OPTIONS. Matched by segment,
|
|
39
54
|
* case-insensitively, after decoding: `/api` covers `/api`, `/api/x` and
|
|
@@ -47,16 +62,24 @@ export interface EntryOptions {
|
|
|
47
62
|
/** Last-segment extensions that mark a file rather than a page. */
|
|
48
63
|
const FILE_EXTENSION =
|
|
49
64
|
/\.(?:js|mjs|cjs|css|map|json|xml|txt|md|csv|ico|png|jpe?g|gif|svg|webp|avif|bmp|woff2?|ttf|otf|eot|pdf|mp[34]|webm|wav|ogg|zip|gz|br|wasm|webmanifest|html?|rss|atom)$/i;
|
|
50
|
-
const DEV_INTERNALS = [
|
|
65
|
+
const DEV_INTERNALS = [
|
|
66
|
+
"/@vite/",
|
|
67
|
+
"/@fs/",
|
|
68
|
+
"/@id/",
|
|
69
|
+
"/@react-refresh",
|
|
70
|
+
"/node_modules/",
|
|
71
|
+
];
|
|
51
72
|
const DUPLICATE_SLASHES = /\/{2,}/g;
|
|
52
73
|
const TRAILING_SLASHES = /\/+$/;
|
|
53
74
|
|
|
54
|
-
export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = Object.freeze(
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
75
|
+
export const MARKDOWN_HEADERS: Readonly<Record<string, string>> = Object.freeze(
|
|
76
|
+
{
|
|
77
|
+
"content-type": "text/markdown; charset=utf-8",
|
|
78
|
+
vary: "Accept",
|
|
79
|
+
// A Markdown body is a second representation of a page, not a page of its own.
|
|
80
|
+
"x-robots-tag": "noindex",
|
|
81
|
+
},
|
|
82
|
+
);
|
|
60
83
|
|
|
61
84
|
/**
|
|
62
85
|
* True when the client names text/markdown with q > 0 and rates it at least
|
|
@@ -101,11 +124,17 @@ export function underPrefix(path: string, prefix: string): boolean {
|
|
|
101
124
|
* `.js` or `.xml` on the last segment. A dotted slug like `/blog/node.js-tips`
|
|
102
125
|
* is still a page.
|
|
103
126
|
*/
|
|
104
|
-
export function defaultIsPage(
|
|
127
|
+
export function defaultIsPage(
|
|
128
|
+
path: string,
|
|
129
|
+
readOnlyPrefixes: readonly string[] = ["/api"],
|
|
130
|
+
): boolean {
|
|
105
131
|
if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
|
|
106
132
|
return false;
|
|
107
133
|
}
|
|
108
|
-
if (
|
|
134
|
+
if (
|
|
135
|
+
path.startsWith("/_") ||
|
|
136
|
+
DEV_INTERNALS.some((prefix) => path.startsWith(prefix))
|
|
137
|
+
) {
|
|
109
138
|
return false;
|
|
110
139
|
}
|
|
111
140
|
return !FILE_EXTENSION.test(path);
|
|
@@ -125,10 +154,23 @@ export function mergeVary(existing: string | null, token: string): string {
|
|
|
125
154
|
|
|
126
155
|
const NULL_BODY_STATUS = new Set([101, 204, 205, 304]);
|
|
127
156
|
|
|
128
|
-
function markdownResponse(
|
|
129
|
-
|
|
157
|
+
function markdownResponse(
|
|
158
|
+
result: Exclude<MarkdownResult, null | undefined>,
|
|
159
|
+
head: boolean,
|
|
160
|
+
): Response {
|
|
161
|
+
const { body, status = 200 } =
|
|
162
|
+
typeof result === "string" ? { body: result } : result;
|
|
130
163
|
const noBody = head || NULL_BODY_STATUS.has(status);
|
|
131
|
-
return new Response(noBody ? null : body, {
|
|
164
|
+
return new Response(noBody ? null : body, {
|
|
165
|
+
status,
|
|
166
|
+
headers: MARKDOWN_HEADERS,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function withAcceptHtml(request: Request): Request {
|
|
171
|
+
const headers = new Headers(request.headers);
|
|
172
|
+
headers.set("accept", "text/html");
|
|
173
|
+
return new Request(request, { headers });
|
|
132
174
|
}
|
|
133
175
|
|
|
134
176
|
function withVaryAccept(response: Response): Response {
|
|
@@ -138,14 +180,19 @@ function withVaryAccept(response: Response): Response {
|
|
|
138
180
|
}
|
|
139
181
|
const headers = new Headers(response.headers);
|
|
140
182
|
headers.set("vary", vary);
|
|
141
|
-
return new Response(response.body, {
|
|
183
|
+
return new Response(response.body, {
|
|
184
|
+
status: response.status,
|
|
185
|
+
statusText: response.statusText,
|
|
186
|
+
headers,
|
|
187
|
+
});
|
|
142
188
|
}
|
|
143
189
|
|
|
144
190
|
export function createEntry(options: EntryOptions): {
|
|
145
191
|
fetch(request: Request, ...rest: unknown[]): Promise<Response>;
|
|
146
192
|
} {
|
|
147
193
|
const readOnlyPrefixes = options.readOnlyPrefixes ?? ["/api"];
|
|
148
|
-
const isPage =
|
|
194
|
+
const isPage =
|
|
195
|
+
options.isPage ?? ((path: string) => defaultIsPage(path, readOnlyPrefixes));
|
|
149
196
|
|
|
150
197
|
return {
|
|
151
198
|
async fetch(request, ...rest) {
|
|
@@ -155,7 +202,10 @@ export function createEntry(options: EntryOptions): {
|
|
|
155
202
|
|
|
156
203
|
if (readOnlyPrefixes.some((prefix) => underPrefix(path, prefix))) {
|
|
157
204
|
if (method === "OPTIONS") {
|
|
158
|
-
return new Response(null, {
|
|
205
|
+
return new Response(null, {
|
|
206
|
+
status: 204,
|
|
207
|
+
headers: { allow: "GET, HEAD, OPTIONS" },
|
|
208
|
+
});
|
|
159
209
|
}
|
|
160
210
|
if (!isRead) {
|
|
161
211
|
return Response.json(
|
|
@@ -172,22 +222,24 @@ export function createEntry(options: EntryOptions): {
|
|
|
172
222
|
|
|
173
223
|
if (options.markdown && wantsMarkdown(request)) {
|
|
174
224
|
try {
|
|
175
|
-
const result = await options.markdown(path, request
|
|
225
|
+
const result = await options.markdown(path, request, {
|
|
226
|
+
html: async () =>
|
|
227
|
+
options.handler.fetch(withAcceptHtml(request), ...rest),
|
|
228
|
+
});
|
|
176
229
|
if (result !== null && result !== undefined) {
|
|
177
230
|
return markdownResponse(result, method === "HEAD");
|
|
178
231
|
}
|
|
179
232
|
} catch (error) {
|
|
180
|
-
console.error(
|
|
233
|
+
console.error(
|
|
234
|
+
"workers-start: markdown renderer failed, serving HTML",
|
|
235
|
+
error,
|
|
236
|
+
);
|
|
181
237
|
}
|
|
182
238
|
}
|
|
183
239
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
headers.set("accept", "text/html");
|
|
188
|
-
pageRequest = new Request(request, { headers });
|
|
189
|
-
}
|
|
190
|
-
|
|
240
|
+
const pageRequest = acceptsHtml(request)
|
|
241
|
+
? request
|
|
242
|
+
: withAcceptHtml(request);
|
|
191
243
|
const response = await options.handler.fetch(pageRequest, ...rest);
|
|
192
244
|
return options.markdown ? withVaryAccept(response) : response;
|
|
193
245
|
},
|
package/src/head.ts
CHANGED
|
@@ -13,8 +13,8 @@ export interface SiteHead {
|
|
|
13
13
|
url: string;
|
|
14
14
|
/** Used for `og:site_name` and the default title suffix. */
|
|
15
15
|
name: string;
|
|
16
|
-
/**
|
|
17
|
-
defaultImage?: string;
|
|
16
|
+
/** The default share image: a path or URL, or an object with size, alt and type. */
|
|
17
|
+
defaultImage?: string | PageImage;
|
|
18
18
|
/** Author's handle with the @, for `twitter:creator`. */
|
|
19
19
|
twitterCreator?: string;
|
|
20
20
|
/** Site's handle with the @, for `twitter:site`. */
|
|
@@ -23,6 +23,18 @@ export interface SiteHead {
|
|
|
23
23
|
locale?: string;
|
|
24
24
|
/** Default `(title) => \`${title} | ${name}\``. */
|
|
25
25
|
titleTemplate?: (title: string) => string;
|
|
26
|
+
/** Robots directive for pages that set neither `robots` nor `noindex`, such as `index, follow`. */
|
|
27
|
+
robots?: string;
|
|
28
|
+
/** Keywords for pages that set none. */
|
|
29
|
+
keywords?: string[];
|
|
30
|
+
/** Site authors: a `meta name="author"` each, and a `link rel="author"` for each with a URL. */
|
|
31
|
+
authors?: { name: string; url?: string }[];
|
|
32
|
+
/**
|
|
33
|
+
* Tags written on every page before the page's own `meta`, such as
|
|
34
|
+
* `application-name` or an App Store banner. A page tag with the same
|
|
35
|
+
* name or property replaces the site's.
|
|
36
|
+
*/
|
|
37
|
+
meta?: MetaTag[];
|
|
26
38
|
}
|
|
27
39
|
|
|
28
40
|
export interface PageImage {
|
|
@@ -61,6 +73,8 @@ export interface PageSeo {
|
|
|
61
73
|
authors?: string[];
|
|
62
74
|
/** For articles: one `article:tag` each. */
|
|
63
75
|
tags?: string[];
|
|
76
|
+
/** For articles: `article:section`. */
|
|
77
|
+
section?: string;
|
|
64
78
|
keywords?: string[];
|
|
65
79
|
/** Adds `robots: noindex`. Ignored when `robots` is set. */
|
|
66
80
|
noindex?: boolean;
|
|
@@ -70,13 +84,78 @@ export interface PageSeo {
|
|
|
70
84
|
canonical?: string | false;
|
|
71
85
|
/** Extra tags, appended last. */
|
|
72
86
|
meta?: MetaTag[];
|
|
87
|
+
/**
|
|
88
|
+
* `link rel="alternate"` entries after the canonical: language versions
|
|
89
|
+
* with `hreflang`, or feeds with `type`. `href` is a path or URL.
|
|
90
|
+
*/
|
|
91
|
+
alternates?: {
|
|
92
|
+
href: string;
|
|
93
|
+
hreflang?: string;
|
|
94
|
+
type?: string;
|
|
95
|
+
title?: string;
|
|
96
|
+
}[];
|
|
97
|
+
/** Extra links, appended last as given. */
|
|
98
|
+
links?: HeadLink[];
|
|
99
|
+
/**
|
|
100
|
+
* schema.org data, written as one `application/ld+json` script. An array
|
|
101
|
+
* becomes an `@graph`. `@context` is added when missing.
|
|
102
|
+
*/
|
|
103
|
+
jsonLd?: object | object[];
|
|
73
104
|
}
|
|
74
105
|
|
|
75
|
-
export type MetaTag =
|
|
106
|
+
export type MetaTag =
|
|
107
|
+
| { title: string }
|
|
108
|
+
| { name: string; content: string }
|
|
109
|
+
| { property: string; content: string };
|
|
110
|
+
|
|
111
|
+
export interface HeadLink {
|
|
112
|
+
rel: string;
|
|
113
|
+
href: string;
|
|
114
|
+
type?: string;
|
|
115
|
+
hreflang?: string;
|
|
116
|
+
title?: string;
|
|
117
|
+
sizes?: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface HeadScript {
|
|
121
|
+
type: string;
|
|
122
|
+
children: string;
|
|
123
|
+
}
|
|
76
124
|
|
|
77
125
|
export interface HeadTags {
|
|
78
126
|
meta: MetaTag[];
|
|
79
|
-
links:
|
|
127
|
+
links: HeadLink[];
|
|
128
|
+
/** Present only when the page passes `jsonLd`. */
|
|
129
|
+
scripts?: HeadScript[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const SCHEMA_CONTEXT = "https://schema.org";
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A JSON-LD script for a route's `head().scripts`. An array becomes an
|
|
136
|
+
* `@graph`; `@context` is added when missing. `<`, `>`, `&`, U+2028 and
|
|
137
|
+
* U+2029 are escaped, so no value can close the script tag.
|
|
138
|
+
*/
|
|
139
|
+
export function jsonLdScript(data: object | object[]): HeadScript {
|
|
140
|
+
const body = Array.isArray(data)
|
|
141
|
+
? { "@context": SCHEMA_CONTEXT, "@graph": data }
|
|
142
|
+
: "@context" in data
|
|
143
|
+
? data
|
|
144
|
+
: { "@context": SCHEMA_CONTEXT, ...data };
|
|
145
|
+
const children = JSON.stringify(body)
|
|
146
|
+
.replace(/</g, "\\u003c")
|
|
147
|
+
.replace(/>/g, "\\u003e")
|
|
148
|
+
.replace(/&/g, "\\u0026")
|
|
149
|
+
.replace(/\u2028/g, "\\u2028")
|
|
150
|
+
.replace(/\u2029/g, "\\u2029");
|
|
151
|
+
return { type: "application/ld+json", children };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The name or property a meta tag is keyed by, or undefined for the title. */
|
|
155
|
+
function metaKey(tag: MetaTag): string | undefined {
|
|
156
|
+
if ("name" in tag) return `name:${tag.name}`;
|
|
157
|
+
if ("property" in tag) return `property:${tag.property}`;
|
|
158
|
+
return undefined;
|
|
80
159
|
}
|
|
81
160
|
|
|
82
161
|
export function createPageHead(site: SiteHead): {
|
|
@@ -84,7 +163,8 @@ export function createPageHead(site: SiteHead): {
|
|
|
84
163
|
absoluteUrl: (path: string) => string;
|
|
85
164
|
} {
|
|
86
165
|
const origin = new URL(site.url).origin;
|
|
87
|
-
const template =
|
|
166
|
+
const template =
|
|
167
|
+
site.titleTemplate ?? ((title: string) => `${title} | ${site.name}`);
|
|
88
168
|
|
|
89
169
|
/** `/` maps to the bare origin; anything else resolves against it, so absolute URLs pass through. */
|
|
90
170
|
const absoluteUrl = (path: string): string => {
|
|
@@ -92,7 +172,9 @@ export function createPageHead(site: SiteHead): {
|
|
|
92
172
|
return origin;
|
|
93
173
|
}
|
|
94
174
|
const resolved = new URL(
|
|
95
|
-
path.startsWith("/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(path)
|
|
175
|
+
path.startsWith("/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(path)
|
|
176
|
+
? path
|
|
177
|
+
: `/${path}`,
|
|
96
178
|
`${origin}/`,
|
|
97
179
|
);
|
|
98
180
|
return resolved.href;
|
|
@@ -104,19 +186,25 @@ export function createPageHead(site: SiteHead): {
|
|
|
104
186
|
const socialDescription = seo.socialDescription ?? seo.description;
|
|
105
187
|
const imageInput = seo.image ?? site.defaultImage;
|
|
106
188
|
const image: PageImage | undefined =
|
|
107
|
-
typeof imageInput === "string"
|
|
189
|
+
typeof imageInput === "string"
|
|
190
|
+
? { url: imageInput, ...seo.imageSize }
|
|
191
|
+
: imageInput;
|
|
108
192
|
const imageUrl = image ? absoluteUrl(image.url) : undefined;
|
|
109
193
|
|
|
110
194
|
const meta: MetaTag[] = [
|
|
111
195
|
{ title: seo.rawTitle ? seo.title : template(seo.title) },
|
|
112
196
|
{ name: "description", content: seo.description },
|
|
113
197
|
];
|
|
114
|
-
const robots = seo.robots ?? (seo.noindex ? "noindex" :
|
|
198
|
+
const robots = seo.robots ?? (seo.noindex ? "noindex" : site.robots);
|
|
115
199
|
if (robots) {
|
|
116
200
|
meta.push({ name: "robots", content: robots });
|
|
117
201
|
}
|
|
118
|
-
|
|
119
|
-
|
|
202
|
+
const keywords = seo.keywords ?? site.keywords;
|
|
203
|
+
if (keywords?.length) {
|
|
204
|
+
meta.push({ name: "keywords", content: keywords.join(", ") });
|
|
205
|
+
}
|
|
206
|
+
for (const author of site.authors ?? []) {
|
|
207
|
+
meta.push({ name: "author", content: author.name });
|
|
120
208
|
}
|
|
121
209
|
meta.push(
|
|
122
210
|
{ property: "og:title", content: socialTitle },
|
|
@@ -127,33 +215,80 @@ export function createPageHead(site: SiteHead): {
|
|
|
127
215
|
);
|
|
128
216
|
if (image && imageUrl) {
|
|
129
217
|
meta.push({ property: "og:image", content: imageUrl });
|
|
130
|
-
if (image.type)
|
|
131
|
-
|
|
132
|
-
if (image.
|
|
133
|
-
|
|
218
|
+
if (image.type)
|
|
219
|
+
meta.push({ property: "og:image:type", content: image.type });
|
|
220
|
+
if (image.width)
|
|
221
|
+
meta.push({ property: "og:image:width", content: String(image.width) });
|
|
222
|
+
if (image.height)
|
|
223
|
+
meta.push({
|
|
224
|
+
property: "og:image:height",
|
|
225
|
+
content: String(image.height),
|
|
226
|
+
});
|
|
227
|
+
if (image.alt)
|
|
228
|
+
meta.push({ property: "og:image:alt", content: image.alt });
|
|
134
229
|
}
|
|
135
230
|
meta.push({ property: "og:type", content: seo.type ?? "website" });
|
|
136
|
-
if (seo.published)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
231
|
+
if (seo.published)
|
|
232
|
+
meta.push({ property: "article:published_time", content: seo.published });
|
|
233
|
+
if (seo.modified)
|
|
234
|
+
meta.push({ property: "article:modified_time", content: seo.modified });
|
|
235
|
+
for (const author of seo.authors ?? [])
|
|
236
|
+
meta.push({ property: "article:author", content: author });
|
|
237
|
+
for (const tag of seo.tags ?? [])
|
|
238
|
+
meta.push({ property: "article:tag", content: tag });
|
|
239
|
+
if (seo.section)
|
|
240
|
+
meta.push({ property: "article:section", content: seo.section });
|
|
241
|
+
|
|
242
|
+
meta.push({
|
|
243
|
+
name: "twitter:card",
|
|
244
|
+
content: imageUrl ? "summary_large_image" : "summary",
|
|
245
|
+
});
|
|
246
|
+
if (site.twitterSite)
|
|
247
|
+
meta.push({ name: "twitter:site", content: site.twitterSite });
|
|
248
|
+
if (site.twitterCreator)
|
|
249
|
+
meta.push({ name: "twitter:creator", content: site.twitterCreator });
|
|
144
250
|
meta.push(
|
|
145
251
|
{ name: "twitter:title", content: socialTitle },
|
|
146
|
-
{
|
|
252
|
+
{
|
|
253
|
+
name: "twitter:description",
|
|
254
|
+
content: seo.twitterDescription ?? socialDescription,
|
|
255
|
+
},
|
|
147
256
|
);
|
|
148
257
|
if (imageUrl) {
|
|
149
258
|
meta.push({ name: "twitter:image", content: imageUrl });
|
|
150
|
-
if (image?.alt)
|
|
259
|
+
if (image?.alt)
|
|
260
|
+
meta.push({ name: "twitter:image:alt", content: image.alt });
|
|
151
261
|
}
|
|
262
|
+
const pageKeys = new Set((seo.meta ?? []).map(metaKey));
|
|
263
|
+
meta.push(
|
|
264
|
+
...(site.meta ?? []).filter((tag) => !pageKeys.has(metaKey(tag))),
|
|
265
|
+
);
|
|
152
266
|
meta.push(...(seo.meta ?? []));
|
|
153
267
|
|
|
154
|
-
const links =
|
|
155
|
-
seo.canonical === false
|
|
156
|
-
|
|
268
|
+
const links: HeadLink[] =
|
|
269
|
+
seo.canonical === false
|
|
270
|
+
? []
|
|
271
|
+
: [
|
|
272
|
+
{
|
|
273
|
+
rel: "canonical",
|
|
274
|
+
href: seo.canonical ? absoluteUrl(seo.canonical) : url,
|
|
275
|
+
},
|
|
276
|
+
];
|
|
277
|
+
for (const alternate of seo.alternates ?? []) {
|
|
278
|
+
links.push({
|
|
279
|
+
rel: "alternate",
|
|
280
|
+
...alternate,
|
|
281
|
+
href: absoluteUrl(alternate.href),
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
for (const author of site.authors ?? []) {
|
|
285
|
+
if (author.url)
|
|
286
|
+
links.push({ rel: "author", href: absoluteUrl(author.url) });
|
|
287
|
+
}
|
|
288
|
+
links.push(...(seo.links ?? []));
|
|
289
|
+
return seo.jsonLd
|
|
290
|
+
? { meta, links, scripts: [jsonLdScript(seo.jsonLd)] }
|
|
291
|
+
: { meta, links };
|
|
157
292
|
};
|
|
158
293
|
|
|
159
294
|
return { pageHead, absoluteUrl };
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
export type { MediaRange } from "./accept.js";
|
|
2
2
|
export { parseAccept, quality } from "./accept.js";
|
|
3
|
-
export type {
|
|
3
|
+
export type {
|
|
4
|
+
EntryOptions,
|
|
5
|
+
FetchHandler,
|
|
6
|
+
MarkdownPage,
|
|
7
|
+
MarkdownResult,
|
|
8
|
+
} from "./entry.js";
|
|
4
9
|
export {
|
|
5
10
|
acceptsHtml,
|
|
6
11
|
createEntry,
|
|
@@ -11,9 +16,24 @@ export {
|
|
|
11
16
|
underPrefix,
|
|
12
17
|
wantsMarkdown,
|
|
13
18
|
} from "./entry.js";
|
|
14
|
-
export type {
|
|
15
|
-
|
|
19
|
+
export type {
|
|
20
|
+
HeadLink,
|
|
21
|
+
HeadScript,
|
|
22
|
+
HeadTags,
|
|
23
|
+
MetaTag,
|
|
24
|
+
PageImage,
|
|
25
|
+
PageSeo,
|
|
26
|
+
SiteHead,
|
|
27
|
+
} from "./head.js";
|
|
28
|
+
export { createPageHead, jsonLdScript } from "./head.js";
|
|
16
29
|
export type { AnalyticsScriptOptions, ThemeScriptOptions } from "./scripts.js";
|
|
17
30
|
export { analyticsScript, inlineJson, themeScript } from "./scripts.js";
|
|
18
31
|
export type { WorkersModule } from "./workers.js";
|
|
19
|
-
export {
|
|
32
|
+
export {
|
|
33
|
+
afterResponse,
|
|
34
|
+
getBinding,
|
|
35
|
+
getEnvString,
|
|
36
|
+
isKvNamespace,
|
|
37
|
+
loadWorkers,
|
|
38
|
+
setWorkersModule,
|
|
39
|
+
} from "./workers.js";
|
package/src/scripts.ts
CHANGED
|
@@ -76,7 +76,9 @@ export function analyticsScript(options: AnalyticsScriptOptions): string {
|
|
|
76
76
|
}
|
|
77
77
|
const id = inlineJson(options.measurementId);
|
|
78
78
|
const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
|
|
79
|
-
const checks = [
|
|
79
|
+
const checks = [
|
|
80
|
+
`if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`,
|
|
81
|
+
];
|
|
80
82
|
if (options.skipPaths?.length) {
|
|
81
83
|
checks.push(
|
|
82
84
|
`var p=location.pathname;if(${inlineJson(options.skipPaths)}.some(function(s){return p===s||p.indexOf(s.replace(/\\/$/,"")+"/")===0}))return;`,
|
|
@@ -84,7 +86,9 @@ export function analyticsScript(options: AnalyticsScriptOptions): string {
|
|
|
84
86
|
}
|
|
85
87
|
if (options.consentCookie) {
|
|
86
88
|
const pair =
|
|
87
|
-
options.consentCookie.value === undefined
|
|
89
|
+
options.consentCookie.value === undefined
|
|
90
|
+
? null
|
|
91
|
+
: `${options.consentCookie.name}=${options.consentCookie.value}`;
|
|
88
92
|
checks.push(
|
|
89
93
|
`var k=document.cookie.split(/;\\s*/);if(!k.some(function(c){return ${pair === null ? `c.split("=")[0]===${inlineJson(options.consentCookie.name)}` : `c===${inlineJson(pair)}`}}))return;`,
|
|
90
94
|
);
|