workers-start 0.1.1 → 0.2.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/src/head.ts CHANGED
@@ -2,26 +2,39 @@
2
2
  * Per-page head tags in the shape a TanStack Router `head()` returns.
3
3
  *
4
4
  * The router keeps one meta per `name` or `property`, deepest route winning,
5
- * so any tag a page leaves out falls back to a parent's. This helper writes
6
- * the full Open Graph and Twitter set for every page so nothing inherits the
7
- * homepage's share card by accident.
5
+ * and concatenates links. So call `pageHead` from leaf routes only: a tag a
6
+ * leaf leaves out falls back to a parent's, and a canonical from both a
7
+ * layout and a leaf is emitted twice. Put site-wide tags (charset, viewport,
8
+ * icons) in the root route without this helper.
8
9
  */
9
10
 
10
11
  export interface SiteHead {
11
- /** Absolute origin, no trailing slash: `https://example.com`. */
12
+ /** Absolute origin: `https://example.com`. A trailing slash is ignored. */
12
13
  url: string;
13
14
  /** Used for `og:site_name` and the default title suffix. */
14
15
  name: string;
15
- /** Path under the site of the default share image. */
16
+ /** Path under the site, or an absolute URL, of the default share image. */
16
17
  defaultImage?: string;
17
- /** Twitter handle with the @. */
18
+ /** Author's handle with the @, for `twitter:creator`. */
18
19
  twitterCreator?: string;
20
+ /** Site's handle with the @, for `twitter:site`. */
21
+ twitterSite?: string;
19
22
  /** Default `en_US`. */
20
23
  locale?: string;
21
24
  /** Default `(title) => \`${title} | ${name}\``. */
22
25
  titleTemplate?: (title: string) => string;
23
26
  }
24
27
 
28
+ export interface PageImage {
29
+ /** Path under the site, or an absolute URL. */
30
+ url: string;
31
+ width?: number;
32
+ height?: number;
33
+ alt?: string;
34
+ /** MIME type, such as `image/png`. */
35
+ type?: string;
36
+ }
37
+
25
38
  export interface PageSeo {
26
39
  title: string;
27
40
  /** Use `title` as the whole document title, without the template. */
@@ -36,15 +49,27 @@ export interface PageSeo {
36
49
  socialDescription?: string;
37
50
  /** Defaults to `socialDescription`. */
38
51
  twitterDescription?: string;
39
- /** Path under the site, or an absolute URL. */
40
- image?: string;
41
- imageSize?: { width: number; height: number; alt: string };
52
+ /** A path or URL, or an object with size, alt and type. Defaults to the site's image. */
53
+ image?: string | PageImage;
54
+ /** @deprecated Use `image: { url, width, height, alt }`. */
55
+ imageSize?: { width: number; height: number; alt?: string };
42
56
  /** ISO date, for articles. */
43
57
  published?: string;
44
58
  /** ISO date, for articles. */
45
59
  modified?: string;
46
- /** Adds `robots: noindex`. */
60
+ /** For articles: author names or profile URLs, one `article:author` each. */
61
+ authors?: string[];
62
+ /** For articles: one `article:tag` each. */
63
+ tags?: string[];
64
+ keywords?: string[];
65
+ /** Adds `robots: noindex`. Ignored when `robots` is set. */
47
66
  noindex?: boolean;
67
+ /** Full robots directive, such as `noindex, follow` or `max-image-preview:large`. */
68
+ robots?: string;
69
+ /** Override the canonical URL, or `false` to emit none. Defaults to the page URL. */
70
+ canonical?: string | false;
71
+ /** Extra tags, appended last. */
72
+ meta?: MetaTag[];
48
73
  }
49
74
 
50
75
  export type MetaTag = { title: string } | { name: string; content: string } | { property: string; content: string };
@@ -58,29 +83,40 @@ export function createPageHead(site: SiteHead): {
58
83
  pageHead: (seo: PageSeo) => HeadTags;
59
84
  absoluteUrl: (path: string) => string;
60
85
  } {
61
- const origin = site.url.replace(/\/+$/, "");
86
+ const origin = new URL(site.url).origin;
62
87
  const template = site.titleTemplate ?? ((title: string) => `${title} | ${site.name}`);
63
88
 
89
+ /** `/` maps to the bare origin; anything else resolves against it, so absolute URLs pass through. */
64
90
  const absoluteUrl = (path: string): string => {
65
- if (/^https?:\/\//.test(path)) {
66
- return path;
91
+ if (path === "/" || path === "") {
92
+ return origin;
67
93
  }
68
- return path === "/" ? origin : `${origin}${path}`;
94
+ const resolved = new URL(
95
+ path.startsWith("/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(path) ? path : `/${path}`,
96
+ `${origin}/`,
97
+ );
98
+ return resolved.href;
69
99
  };
70
100
 
71
101
  const pageHead = (seo: PageSeo): HeadTags => {
72
102
  const url = absoluteUrl(seo.path);
73
103
  const socialTitle = seo.socialTitle ?? seo.title;
74
104
  const socialDescription = seo.socialDescription ?? seo.description;
75
- const imagePath = seo.image ?? site.defaultImage;
76
- const image = imagePath ? absoluteUrl(imagePath) : undefined;
105
+ const imageInput = seo.image ?? site.defaultImage;
106
+ const image: PageImage | undefined =
107
+ typeof imageInput === "string" ? { url: imageInput, ...seo.imageSize } : imageInput;
108
+ const imageUrl = image ? absoluteUrl(image.url) : undefined;
77
109
 
78
110
  const meta: MetaTag[] = [
79
111
  { title: seo.rawTitle ? seo.title : template(seo.title) },
80
112
  { name: "description", content: seo.description },
81
113
  ];
82
- if (seo.noindex) {
83
- meta.push({ name: "robots", content: "noindex" });
114
+ const robots = seo.robots ?? (seo.noindex ? "noindex" : undefined);
115
+ if (robots) {
116
+ meta.push({ name: "robots", content: robots });
117
+ }
118
+ if (seo.keywords?.length) {
119
+ meta.push({ name: "keywords", content: seo.keywords.join(", ") });
84
120
  }
85
121
  meta.push(
86
122
  { property: "og:title", content: socialTitle },
@@ -89,36 +125,35 @@ export function createPageHead(site: SiteHead): {
89
125
  { property: "og:site_name", content: site.name },
90
126
  { property: "og:locale", content: site.locale ?? "en_US" },
91
127
  );
92
- if (image) {
93
- meta.push({ property: "og:image", content: image });
94
- }
95
- if (image && seo.imageSize) {
96
- meta.push(
97
- { property: "og:image:width", content: String(seo.imageSize.width) },
98
- { property: "og:image:height", content: String(seo.imageSize.height) },
99
- { property: "og:image:alt", content: seo.imageSize.alt },
100
- );
128
+ if (image && imageUrl) {
129
+ meta.push({ property: "og:image", content: imageUrl });
130
+ if (image.type) meta.push({ property: "og:image:type", content: image.type });
131
+ if (image.width) meta.push({ property: "og:image:width", content: String(image.width) });
132
+ if (image.height) meta.push({ property: "og:image:height", content: String(image.height) });
133
+ if (image.alt) meta.push({ property: "og:image:alt", content: image.alt });
101
134
  }
102
135
  meta.push({ property: "og:type", content: seo.type ?? "website" });
103
- if (seo.published) {
104
- meta.push({ property: "article:published_time", content: seo.published });
105
- }
106
- if (seo.modified) {
107
- meta.push({ property: "article:modified_time", content: seo.modified });
108
- }
109
- meta.push({ name: "twitter:card", content: image ? "summary_large_image" : "summary" });
110
- if (site.twitterCreator) {
111
- meta.push({ name: "twitter:creator", content: site.twitterCreator });
112
- }
136
+ if (seo.published) meta.push({ property: "article:published_time", content: seo.published });
137
+ if (seo.modified) meta.push({ property: "article:modified_time", content: seo.modified });
138
+ for (const author of seo.authors ?? []) meta.push({ property: "article:author", content: author });
139
+ for (const tag of seo.tags ?? []) meta.push({ property: "article:tag", content: tag });
140
+
141
+ meta.push({ name: "twitter:card", content: imageUrl ? "summary_large_image" : "summary" });
142
+ if (site.twitterSite) meta.push({ name: "twitter:site", content: site.twitterSite });
143
+ if (site.twitterCreator) meta.push({ name: "twitter:creator", content: site.twitterCreator });
113
144
  meta.push(
114
145
  { name: "twitter:title", content: socialTitle },
115
146
  { name: "twitter:description", content: seo.twitterDescription ?? socialDescription },
116
147
  );
117
- if (image) {
118
- meta.push({ name: "twitter:image", content: image });
148
+ if (imageUrl) {
149
+ meta.push({ name: "twitter:image", content: imageUrl });
150
+ if (image?.alt) meta.push({ name: "twitter:image:alt", content: image.alt });
119
151
  }
152
+ meta.push(...(seo.meta ?? []));
120
153
 
121
- return { meta, links: [{ rel: "canonical", href: url }] };
154
+ const links =
155
+ seo.canonical === false ? [] : [{ rel: "canonical", href: seo.canonical ? absoluteUrl(seo.canonical) : url }];
156
+ return { meta, links };
122
157
  };
123
158
 
124
159
  return { pageHead, absoluteUrl };
package/src/index.ts CHANGED
@@ -1,8 +1,19 @@
1
+ export type { MediaRange } from "./accept.js";
2
+ export { parseAccept, quality } from "./accept.js";
1
3
  export type { EntryOptions, FetchHandler, MarkdownResult } from "./entry.js";
2
- export { createEntry, defaultIsPage, MARKDOWN_HEADERS, normalizePath, wantsMarkdown } from "./entry.js";
3
- export type { HeadTags, MetaTag, PageSeo, SiteHead } from "./head.js";
4
+ export {
5
+ acceptsHtml,
6
+ createEntry,
7
+ defaultIsPage,
8
+ MARKDOWN_HEADERS,
9
+ mergeVary,
10
+ normalizePath,
11
+ underPrefix,
12
+ wantsMarkdown,
13
+ } from "./entry.js";
14
+ export type { HeadTags, MetaTag, PageImage, PageSeo, SiteHead } from "./head.js";
4
15
  export { createPageHead } from "./head.js";
5
16
  export type { AnalyticsScriptOptions, ThemeScriptOptions } from "./scripts.js";
6
- export { analyticsScript, themeScript } from "./scripts.js";
17
+ export { analyticsScript, inlineJson, themeScript } from "./scripts.js";
7
18
  export type { WorkersModule } from "./workers.js";
8
19
  export { afterResponse, getBinding, getEnvString, isKvNamespace, loadWorkers, setWorkersModule } from "./workers.js";
package/src/scripts.ts CHANGED
@@ -4,42 +4,90 @@
4
4
  * React renders, so they cause no hydration mismatch.
5
5
  */
6
6
 
7
+ /**
8
+ * JSON for embedding in an inline script: `<`, U+2028 and U+2029 are escaped,
9
+ * so no value can close the script tag or break the line.
10
+ */
11
+ export function inlineJson(value: unknown): string {
12
+ return JSON.stringify(value)
13
+ .replace(/</g, "\\u003c")
14
+ .replace(/\u2028/g, "\\u2028")
15
+ .replace(/\u2029/g, "\\u2029");
16
+ }
17
+
7
18
  export interface ThemeScriptOptions {
8
19
  /** localStorage key. Default `theme`. */
9
20
  storageKey?: string;
10
- /** Attribute set on `<html>`. Default `data-theme`. */
11
- attribute?: string;
12
21
  /** Accepted stored values. Default `["light", "dark"]`. */
13
22
  values?: string[];
23
+ /**
24
+ * How the choice is applied to `<html>`: set as an attribute (default
25
+ * `data-theme`), or added as a class (`{ class: true }`, as Tailwind's
26
+ * class-based dark mode expects).
27
+ */
28
+ target?: { attribute: string } | { class: true };
29
+ /**
30
+ * With no stored choice, apply the OS preference anyway (needed when CSS
31
+ * keys dark mode off the class or attribute rather than the media query).
32
+ */
33
+ followSystem?: boolean;
14
34
  }
15
35
 
16
36
  /**
17
- * Applies a stored theme choice before first paint, so it never flashes the
18
- * other theme. With no stored choice it does nothing, and CSS
37
+ * Applies the stored theme before first paint, so it never flashes the other
38
+ * one. With nothing stored and `followSystem` off it does nothing, and CSS
19
39
  * `color-scheme: light dark` follows the operating system.
20
40
  */
21
41
  export function themeScript(options: ThemeScriptOptions = {}): string {
22
- const key = JSON.stringify(options.storageKey ?? "theme");
23
- const attribute = JSON.stringify(options.attribute ?? "data-theme");
24
- const values = JSON.stringify(options.values ?? ["light", "dark"]);
25
- return `try{var t=localStorage.getItem(${key});if(${values}.indexOf(t)!==-1){document.documentElement.setAttribute(${attribute},t)}}catch(e){}`;
42
+ const key = inlineJson(options.storageKey ?? "theme");
43
+ const values = inlineJson(options.values ?? ["light", "dark"]);
44
+ const target = options.target ?? { attribute: "data-theme" };
45
+ const apply =
46
+ "class" in target
47
+ ? `var c=document.documentElement.classList;${values}.forEach(function(v){c.remove(v)});c.add(t)`
48
+ : `document.documentElement.setAttribute(${inlineJson(target.attribute)},t)`;
49
+ const fallback = options.followSystem
50
+ ? `if(${values}.indexOf(t)===-1){t=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}`
51
+ : "";
52
+ return `try{var t=localStorage.getItem(${key});${fallback}if(${values}.indexOf(t)!==-1){${apply}}}catch(e){}`;
26
53
  }
27
54
 
28
55
  export interface AnalyticsScriptOptions {
29
56
  /** GA4 measurement id, `G-…`. Public; safe in the bundle. */
30
57
  measurementId: string;
31
- /** Hostnames that report. Every other host (localhost, previews) loads nothing. */
58
+ /** Hostnames that report, compared without case. Every other host (localhost, previews) loads nothing. */
32
59
  hosts: string[];
60
+ /** Path prefixes that never load analytics, such as `/admin`. */
61
+ skipPaths?: string[];
62
+ /**
63
+ * Load only after consent: the name of a cookie that must be present (and
64
+ * equal `value`, when given). Without it, analytics loads on every page view.
65
+ */
66
+ consentCookie?: { name: string; value?: string };
33
67
  }
34
68
 
35
69
  /**
36
70
  * Google Analytics 4 bootstrap gated on `location.hostname`, so local dev and
37
71
  * preview deploys never fetch gtag.js or land in the production property.
38
72
  */
39
- export function analyticsScript({ measurementId, hosts }: AnalyticsScriptOptions): string {
40
- if (!/^G-[A-Z0-9]+$/.test(measurementId)) {
41
- throw new Error(`Not a GA4 measurement id: ${measurementId}`);
73
+ export function analyticsScript(options: AnalyticsScriptOptions): string {
74
+ if (!/^G-[A-Z0-9]+$/.test(options.measurementId)) {
75
+ throw new Error(`Not a GA4 measurement id: ${options.measurementId}`);
76
+ }
77
+ const id = inlineJson(options.measurementId);
78
+ const hosts = inlineJson(options.hosts.map((h) => h.toLowerCase()));
79
+ const checks = [`if(${hosts}.indexOf(location.hostname.toLowerCase())===-1)return;`];
80
+ if (options.skipPaths?.length) {
81
+ checks.push(
82
+ `var p=location.pathname;if(${inlineJson(options.skipPaths)}.some(function(s){return p===s||p.indexOf(s.replace(/\\/$/,"")+"/")===0}))return;`,
83
+ );
84
+ }
85
+ if (options.consentCookie) {
86
+ const pair =
87
+ options.consentCookie.value === undefined ? null : `${options.consentCookie.name}=${options.consentCookie.value}`;
88
+ checks.push(
89
+ `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
+ );
42
91
  }
43
- const id = JSON.stringify(measurementId);
44
- return `(function(){if(${JSON.stringify(hosts)}.indexOf(location.hostname)===-1)return;var s=document.createElement("script");s.async=true;s.src="https://www.googletagmanager.com/gtag/js?id="+${id};document.head.appendChild(s);window.dataLayer=window.dataLayer||[];function gtag(){window.dataLayer.push(arguments);}window.gtag=gtag;gtag("js",new Date());gtag("config",${id});})();`;
92
+ return `(function(){${checks.join("")}var s=document.createElement("script");s.async=true;s.src="https://www.googletagmanager.com/gtag/js?id="+${id};document.head.appendChild(s);window.dataLayer=window.dataLayer||[];function gtag(){window.dataLayer.push(arguments);}window.gtag=gtag;gtag("js",new Date());gtag("config",${id});})();`;
45
93
  }
package/src/workers.ts CHANGED
@@ -3,9 +3,11 @@
3
3
  * that also runs in vitest, Node scripts and the client bundle.
4
4
  *
5
5
  * The module is imported through a variable specifier, so neither Vite nor
6
- * vitest tries to resolve it, and only on first use. Outside workerd the
7
- * import fails and every helper here degrades: bindings are null, env reads
8
- * fall back to `process.env`, and `afterResponse` awaits the work in place.
6
+ * vitest tries to resolve it, and only on first use. Outside workerd (Node,
7
+ * vitest in Node, the browser) the import fails and every helper here
8
+ * degrades: bindings are null, env reads fall back to `process.env`, and
9
+ * `afterResponse` awaits the work in place. Inside workerd, including
10
+ * `@cloudflare/vitest-pool-workers`, the real bindings are used.
9
11
  */
10
12
 
11
13
  export interface WorkersModule {
@@ -22,19 +24,11 @@ function processEnv(): Record<string, string | undefined> {
22
24
  return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};
23
25
  }
24
26
 
25
- function isTestRuntime(): boolean {
26
- const env = processEnv();
27
- return Boolean(env.VITEST) || env.NODE_ENV === "test";
28
- }
29
-
30
27
  /** The `cloudflare:workers` module, or null outside workerd. */
31
28
  export function loadWorkers(): Promise<WorkersModule | null> {
32
29
  if (override !== undefined) {
33
30
  return Promise.resolve(override);
34
31
  }
35
- if (isTestRuntime()) {
36
- return Promise.resolve(null);
37
- }
38
32
  if (!modulePromise) {
39
33
  modulePromise = import(/* @vite-ignore */ WORKERS_MODULE)
40
34
  .then((mod) => mod as unknown as WorkersModule)
@@ -85,10 +79,16 @@ export async function afterResponse(work: Promise<unknown>): Promise<void> {
85
79
  mod.waitUntil(work);
86
80
  return;
87
81
  }
88
- await work;
82
+ // Same contract as waitUntil: a background failure is logged, never thrown
83
+ // into the request that started it.
84
+ try {
85
+ await work;
86
+ } catch (error) {
87
+ console.error("workers-start: background work failed", error);
88
+ }
89
89
  }
90
90
 
91
- /** True for anything with KV's `get` and `put`. Use as a `getBinding` guard. */
91
+ /** True for a KV namespace (it has `getWithMetadata`, which R2 buckets do not). Use as a `getBinding` guard. */
92
92
  export function isKvNamespace(value: unknown): value is {
93
93
  get(key: string): Promise<string | null>;
94
94
  put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;
@@ -96,6 +96,10 @@ export function isKvNamespace(value: unknown): value is {
96
96
  if (typeof value !== "object" || value === null) {
97
97
  return false;
98
98
  }
99
- const candidate = value as { get?: unknown; put?: unknown };
100
- return typeof candidate.get === "function" && typeof candidate.put === "function";
99
+ const candidate = value as { get?: unknown; put?: unknown; getWithMetadata?: unknown };
100
+ return (
101
+ typeof candidate.get === "function" &&
102
+ typeof candidate.put === "function" &&
103
+ typeof candidate.getWithMetadata === "function"
104
+ );
101
105
  }