@stati/core 1.27.2 → 1.29.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.
Files changed (136) hide show
  1. package/README.md +6 -1
  2. package/dist/config/errors.d.ts +10 -0
  3. package/dist/config/errors.d.ts.map +1 -0
  4. package/dist/config/errors.js +10 -0
  5. package/dist/config/loader.d.ts.map +1 -1
  6. package/dist/config/loader.js +15 -2
  7. package/dist/constants.d.ts +26 -0
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/constants.js +23 -0
  10. package/dist/core/build.d.ts.map +1 -1
  11. package/dist/core/build.js +201 -41
  12. package/dist/core/collections.d.ts +139 -0
  13. package/dist/core/collections.d.ts.map +1 -0
  14. package/dist/core/collections.js +342 -0
  15. package/dist/core/content.d.ts.map +1 -1
  16. package/dist/core/content.js +2 -1
  17. package/dist/core/dev.d.ts.map +1 -1
  18. package/dist/core/dev.js +11 -62
  19. package/dist/core/expand.d.ts +86 -0
  20. package/dist/core/expand.d.ts.map +1 -0
  21. package/dist/core/expand.js +484 -0
  22. package/dist/core/isg/builder.d.ts +27 -2
  23. package/dist/core/isg/builder.d.ts.map +1 -1
  24. package/dist/core/isg/builder.js +83 -11
  25. package/dist/core/isg/deps.d.ts +9 -0
  26. package/dist/core/isg/deps.d.ts.map +1 -1
  27. package/dist/core/isg/deps.js +30 -1
  28. package/dist/core/isg/hash.d.ts +14 -2
  29. package/dist/core/isg/hash.d.ts.map +1 -1
  30. package/dist/core/isg/hash.js +30 -2
  31. package/dist/core/isg/index.d.ts +4 -2
  32. package/dist/core/isg/index.d.ts.map +1 -1
  33. package/dist/core/isg/index.js +4 -2
  34. package/dist/core/isg/manifest.js +14 -0
  35. package/dist/core/isg/prune.d.ts +32 -0
  36. package/dist/core/isg/prune.d.ts.map +1 -0
  37. package/dist/core/isg/prune.js +113 -0
  38. package/dist/core/markdown.d.ts +10 -1
  39. package/dist/core/markdown.d.ts.map +1 -1
  40. package/dist/core/markdown.js +13 -3
  41. package/dist/core/navigation.d.ts +4 -2
  42. package/dist/core/navigation.d.ts.map +1 -1
  43. package/dist/core/navigation.js +17 -2
  44. package/dist/core/templates.d.ts +15 -1
  45. package/dist/core/templates.d.ts.map +1 -1
  46. package/dist/core/templates.js +121 -126
  47. package/dist/core/utils/fs.utils.d.ts +29 -1
  48. package/dist/core/utils/fs.utils.d.ts.map +1 -1
  49. package/dist/core/utils/fs.utils.js +74 -1
  50. package/dist/core/utils/index.d.ts +3 -3
  51. package/dist/core/utils/index.d.ts.map +1 -1
  52. package/dist/core/utils/index.js +3 -3
  53. package/dist/core/utils/paths.utils.d.ts +15 -0
  54. package/dist/core/utils/paths.utils.d.ts.map +1 -1
  55. package/dist/core/utils/paths.utils.js +20 -0
  56. package/dist/core/utils/template-discovery.utils.d.ts +25 -1
  57. package/dist/core/utils/template-discovery.utils.d.ts.map +1 -1
  58. package/dist/core/utils/template-discovery.utils.js +61 -11
  59. package/dist/images/config.d.ts +52 -0
  60. package/dist/images/config.d.ts.map +1 -0
  61. package/dist/images/config.js +200 -0
  62. package/dist/images/index.d.ts +15 -0
  63. package/dist/images/index.d.ts.map +1 -0
  64. package/dist/images/index.js +11 -0
  65. package/dist/images/manifest.d.ts +36 -0
  66. package/dist/images/manifest.d.ts.map +1 -0
  67. package/dist/images/manifest.js +69 -0
  68. package/dist/images/markdown-rule.d.ts +26 -0
  69. package/dist/images/markdown-rule.d.ts.map +1 -0
  70. package/dist/images/markdown-rule.js +60 -0
  71. package/dist/images/markup.d.ts +39 -0
  72. package/dist/images/markup.d.ts.map +1 -0
  73. package/dist/images/markup.js +72 -0
  74. package/dist/images/og.d.ts +52 -0
  75. package/dist/images/og.d.ts.map +1 -0
  76. package/dist/images/og.js +165 -0
  77. package/dist/images/plan.d.ts +101 -0
  78. package/dist/images/plan.d.ts.map +1 -0
  79. package/dist/images/plan.js +128 -0
  80. package/dist/images/provider.d.ts +35 -0
  81. package/dist/images/provider.d.ts.map +1 -0
  82. package/dist/images/provider.js +70 -0
  83. package/dist/images/resolve.d.ts +45 -0
  84. package/dist/images/resolve.d.ts.map +1 -0
  85. package/dist/images/resolve.js +51 -0
  86. package/dist/images/runtime.d.ts +258 -0
  87. package/dist/images/runtime.d.ts.map +1 -0
  88. package/dist/images/runtime.js +659 -0
  89. package/dist/images/sources.d.ts +47 -0
  90. package/dist/images/sources.d.ts.map +1 -0
  91. package/dist/images/sources.js +97 -0
  92. package/dist/images/utils/image-probe.utils.d.ts +30 -0
  93. package/dist/images/utils/image-probe.utils.d.ts.map +1 -0
  94. package/dist/images/utils/image-probe.utils.js +307 -0
  95. package/dist/images/utils/index.d.ts +7 -0
  96. package/dist/images/utils/index.d.ts.map +1 -0
  97. package/dist/images/utils/index.js +5 -0
  98. package/dist/index.d.ts +2 -1
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/metrics/noop.d.ts.map +1 -1
  101. package/dist/metrics/noop.js +3 -0
  102. package/dist/metrics/recorder.d.ts.map +1 -1
  103. package/dist/metrics/recorder.js +3 -0
  104. package/dist/metrics/types.d.ts +8 -0
  105. package/dist/metrics/types.d.ts.map +1 -1
  106. package/dist/rss/generator.d.ts.map +1 -1
  107. package/dist/rss/generator.js +5 -2
  108. package/dist/search/generator.d.ts +9 -0
  109. package/dist/search/generator.d.ts.map +1 -1
  110. package/dist/search/generator.js +20 -0
  111. package/dist/search/index.d.ts +1 -1
  112. package/dist/search/index.d.ts.map +1 -1
  113. package/dist/search/index.js +1 -1
  114. package/dist/seo/auto-inject.d.ts +3 -0
  115. package/dist/seo/auto-inject.d.ts.map +1 -1
  116. package/dist/seo/auto-inject.js +1 -0
  117. package/dist/seo/generator.d.ts +24 -0
  118. package/dist/seo/generator.d.ts.map +1 -1
  119. package/dist/seo/generator.js +65 -1
  120. package/dist/seo/index.d.ts +1 -1
  121. package/dist/seo/index.d.ts.map +1 -1
  122. package/dist/seo/index.js +1 -1
  123. package/dist/types/config.d.ts +60 -0
  124. package/dist/types/config.d.ts.map +1 -1
  125. package/dist/types/content.d.ts +150 -3
  126. package/dist/types/content.d.ts.map +1 -1
  127. package/dist/types/images.d.ts +185 -0
  128. package/dist/types/images.d.ts.map +1 -0
  129. package/dist/types/images.js +8 -0
  130. package/dist/types/index.d.ts +3 -2
  131. package/dist/types/index.d.ts.map +1 -1
  132. package/dist/types/isg.d.ts +19 -0
  133. package/dist/types/isg.d.ts.map +1 -1
  134. package/dist/types/seo.d.ts +9 -0
  135. package/dist/types/seo.d.ts.map +1 -1
  136. package/package.json +1 -1
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The markdown-it `image` rule that adds dimensions, lazy loading and responsive variants.
3
+ * @module images/markdown-rule
4
+ */
5
+ /** Key of the page's image state in the markdown-it `env`. */
6
+ export const IMAGES_ENV_KEY = 'statiImages';
7
+ /** An image counts as near the top of a page when it sits in one of the first blocks. */
8
+ const EAGER_BLOCK_LIMIT = 3;
9
+ /**
10
+ * Installs the image rule. It holds no per-page state: each render passes its page's image
11
+ * state in `env`, and renders without it fall through to the previous rule. Installed before
12
+ * plugins and `markdown.configure`, so a custom image rule there replaces it.
13
+ *
14
+ * @param md - The markdown-it instance
15
+ */
16
+ export function installImageRule(md) {
17
+ const previous = md.renderer.rules.image ??
18
+ ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options));
19
+ md.renderer.rules.image = (tokens, idx, options, env, self) => {
20
+ const images = env?.[IMAGES_ENV_KEY];
21
+ const token = tokens[idx];
22
+ if (!images || !token) {
23
+ return previous(tokens, idx, options, env, self);
24
+ }
25
+ const alt = self.renderInlineAsText(token.children ?? [], options, env);
26
+ const result = images.renderMarkdownImage(token, alt);
27
+ if ('html' in result) {
28
+ return result.html;
29
+ }
30
+ // Left as authored, apart from a stripped `?raw` suffix
31
+ if (result.src !== token.attrGet('src')) {
32
+ token.attrSet('src', result.src);
33
+ }
34
+ return previous(tokens, idx, options, env, self);
35
+ };
36
+ }
37
+ /**
38
+ * Picks the image `eagerFirst` loads eagerly: the document's first image, when it sits in
39
+ * one of the first top-level blocks. A first image further down is not the page's largest
40
+ * contentful paint, so it stays lazy.
41
+ *
42
+ * @param tokens - Parsed block tokens
43
+ * @returns The image token, or undefined
44
+ */
45
+ export function selectEagerImage(tokens) {
46
+ let blocks = 0;
47
+ for (const token of tokens) {
48
+ if (token.level === 0 && token.nesting !== -1) {
49
+ blocks++;
50
+ if (blocks > EAGER_BLOCK_LIMIT)
51
+ return undefined;
52
+ }
53
+ if (token.type === 'inline') {
54
+ const image = token.children?.find((child) => child.type === 'image');
55
+ if (image)
56
+ return image;
57
+ }
58
+ }
59
+ return undefined;
60
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * HTML for processed images.
3
+ * @module images/markup
4
+ */
5
+ import type { VariantPlan } from './plan.js';
6
+ /**
7
+ * Attributes for an `<img>` element.
8
+ */
9
+ export interface ImgMarkupOptions {
10
+ alt: string;
11
+ title?: string | undefined;
12
+ /** Other authored attributes, such as `class` or `id`, in order */
13
+ attributes?: ReadonlyArray<readonly [string, string]> | undefined;
14
+ width?: number | string | undefined;
15
+ height?: number | string | undefined;
16
+ /** Load eagerly with high fetch priority instead of lazily */
17
+ eager?: boolean | undefined;
18
+ srcset?: string | undefined;
19
+ sizes?: string | undefined;
20
+ }
21
+ /**
22
+ * Renders an `<img>` with dimensions, loading hints and authored attributes.
23
+ *
24
+ * @param src - Image URL
25
+ * @param options - Attributes
26
+ * @returns The `<img>` element
27
+ */
28
+ export declare function renderImg(src: string, options: ImgMarkupOptions): string;
29
+ /**
30
+ * Renders a responsive image: a `<picture>` with one `<source>` per modern format, or a
31
+ * plain `<img srcset>` when there are none.
32
+ *
33
+ * @param plan - The planned variants
34
+ * @param options - Attributes for the `<img>` fallback
35
+ * @param sizes - The `sizes` attribute
36
+ * @returns The `<picture>` or `<img>` element
37
+ */
38
+ export declare function renderResponsiveImage(plan: VariantPlan, options: Omit<ImgMarkupOptions, 'srcset' | 'sizes'>, sizes: string): string;
39
+ //# sourceMappingURL=markup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markup.d.ts","sourceRoot":"","sources":["../../src/images/markup.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAgB7C;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,mEAAmE;IACnE,UAAU,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAAC;IAClE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACpC,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACrC,8DAA8D;IAC9D,KAAK,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B;AAMD;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,MAAM,CAexE;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,GAAG,OAAO,CAAC,EACnD,KAAK,EAAE,MAAM,GACZ,MAAM,CAgBR"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * HTML for processed images.
3
+ * @module images/markup
4
+ */
5
+ import { escapeHtml } from '../seo/utils/index.js';
6
+ /** Attributes Stati sets itself; authored values for these are ignored or handled separately. */
7
+ const MANAGED_ATTRIBUTES = new Set([
8
+ 'src',
9
+ 'srcset',
10
+ 'sizes',
11
+ 'alt',
12
+ 'title',
13
+ 'width',
14
+ 'height',
15
+ 'loading',
16
+ 'decoding',
17
+ 'fetchpriority',
18
+ ]);
19
+ function attribute(name, value) {
20
+ return ` ${name}="${escapeHtml(String(value))}"`;
21
+ }
22
+ /**
23
+ * Renders an `<img>` with dimensions, loading hints and authored attributes.
24
+ *
25
+ * @param src - Image URL
26
+ * @param options - Attributes
27
+ * @returns The `<img>` element
28
+ */
29
+ export function renderImg(src, options) {
30
+ let html = `<img${attribute('src', src)}`;
31
+ if (options.srcset)
32
+ html += attribute('srcset', options.srcset);
33
+ if (options.sizes)
34
+ html += attribute('sizes', options.sizes);
35
+ html += attribute('alt', options.alt);
36
+ if (options.title)
37
+ html += attribute('title', options.title);
38
+ for (const [name, value] of options.attributes ?? []) {
39
+ if (!MANAGED_ATTRIBUTES.has(name.toLowerCase())) {
40
+ html += attribute(name, value);
41
+ }
42
+ }
43
+ if (options.width !== undefined)
44
+ html += attribute('width', options.width);
45
+ if (options.height !== undefined)
46
+ html += attribute('height', options.height);
47
+ html += options.eager ? ' loading="eager" fetchpriority="high"' : ' loading="lazy"';
48
+ return `${html} decoding="async">`;
49
+ }
50
+ /**
51
+ * Renders a responsive image: a `<picture>` with one `<source>` per modern format, or a
52
+ * plain `<img srcset>` when there are none.
53
+ *
54
+ * @param plan - The planned variants
55
+ * @param options - Attributes for the `<img>` fallback
56
+ * @param sizes - The `sizes` attribute
57
+ * @returns The `<picture>` or `<img>` element
58
+ */
59
+ export function renderResponsiveImage(plan, options, sizes) {
60
+ const img = renderImg(plan.fallback.src, {
61
+ ...options,
62
+ srcset: plan.fallback.srcset,
63
+ sizes,
64
+ });
65
+ if (plan.sources.length === 0) {
66
+ return img;
67
+ }
68
+ const sources = plan.sources
69
+ .map((source) => `<source${attribute('type', source.type)}${attribute('srcset', source.srcset)}${attribute('sizes', sizes)}>`)
70
+ .join('');
71
+ return `<picture>${sources}${img}</picture>`;
72
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Helpers for Open Graph image generation: template lookup, exclusions and inlining.
3
+ * @module images/og
4
+ */
5
+ import type { PageModel } from '../types/index.js';
6
+ /**
7
+ * Clears the Open Graph template lookup cache.
8
+ */
9
+ export declare function clearOgTemplateCache(): void;
10
+ /**
11
+ * Finds the Open Graph template for a page: the nearest file named `templateName` in the
12
+ * page's directory or one of its parents, up to the source directory.
13
+ *
14
+ * @param pageSourcePath - Absolute path of the page's Markdown file
15
+ * @param srcDir - Absolute source directory
16
+ * @param templateName - Template file name, such as `og.eta`
17
+ * @returns Absolute path of the template, or null when there is none
18
+ */
19
+ export declare function findOgTemplatePath(pageSourcePath: string, srcDir: string, templateName: string): Promise<string | null>;
20
+ /**
21
+ * Whether a page gets no generated Open Graph image: it sets its own image in front matter
22
+ * (`seo.openGraph.image`, or `false` to have none) or matches an `exclude` pattern.
23
+ */
24
+ export declare function isOgImageExcluded(page: PageModel, exclude: readonly string[]): boolean;
25
+ /**
26
+ * File name stem for a page's Open Graph image, from its URL.
27
+ * The root page is `index`; `/blog/hello/` becomes `blog-hello`.
28
+ */
29
+ export declare function ogImageSlug(url: string): string;
30
+ /**
31
+ * Replaces local `<img src>` values in Open Graph HTML with data URIs, because the renderer
32
+ * does not fetch files. Root-relative paths resolve from the static directory, relative ones
33
+ * from `baseDir`. Remote URLs and data URIs are left alone.
34
+ *
35
+ * @param generatedSource - Finds the source of an image Stati generates (`/_img/...`), such as
36
+ * a responsive variant from `stati.image()`. Cards inline the source, because generated
37
+ * files may not exist yet.
38
+ * @returns The HTML and the absolute paths of the files that were inlined
39
+ */
40
+ export declare function inlineLocalImages(html: string, dirs: {
41
+ staticDir: string;
42
+ baseDir: string;
43
+ srcDir: string;
44
+ }, generatedSource?: (path: string) => string | undefined): Promise<{
45
+ html: string;
46
+ files: string[];
47
+ }>;
48
+ /**
49
+ * The template path to show in messages, relative to the project.
50
+ */
51
+ export declare function displayTemplatePath(templatePath: string): string;
52
+ //# sourceMappingURL=og.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"og.d.ts","sourceRoot":"","sources":["../../src/images/og.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAKnD;;GAEG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C;AAED;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACtC,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAyBxB;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAOtF;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAU/C;AAsCD;;;;;;;;;GASG;AACH,wBAAsB,iBAAiB,CACrC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAC5D,eAAe,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,GACrD,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAwC5C;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAEhE"}
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Helpers for Open Graph image generation: template lookup, exclusions and inlining.
3
+ * @module images/og
4
+ */
5
+ import { dirname, extname, join, relative, resolve } from 'node:path';
6
+ import { isPathWithinDirectory, pathExists, readFileBuffer } from '../core/utils/index.js';
7
+ import { matchesGlob } from '../core/utils/glob-patterns.utils.js';
8
+ /** Cache of template lookups per directory, cleared at the start of each build. */
9
+ const templateCache = new Map();
10
+ /**
11
+ * Clears the Open Graph template lookup cache.
12
+ */
13
+ export function clearOgTemplateCache() {
14
+ templateCache.clear();
15
+ }
16
+ /**
17
+ * Finds the Open Graph template for a page: the nearest file named `templateName` in the
18
+ * page's directory or one of its parents, up to the source directory.
19
+ *
20
+ * @param pageSourcePath - Absolute path of the page's Markdown file
21
+ * @param srcDir - Absolute source directory
22
+ * @param templateName - Template file name, such as `og.eta`
23
+ * @returns Absolute path of the template, or null when there is none
24
+ */
25
+ export async function findOgTemplatePath(pageSourcePath, srcDir, templateName) {
26
+ const root = resolve(srcDir);
27
+ let dir = dirname(resolve(pageSourcePath));
28
+ const visited = [];
29
+ while (isPathWithinDirectory(root, dir)) {
30
+ const cacheKey = `${dir}|${templateName}`;
31
+ if (templateCache.has(cacheKey)) {
32
+ const cached = templateCache.get(cacheKey);
33
+ for (const key of visited)
34
+ templateCache.set(key, cached);
35
+ return cached;
36
+ }
37
+ visited.push(cacheKey);
38
+ const candidate = join(dir, templateName);
39
+ if (await pathExists(candidate)) {
40
+ for (const key of visited)
41
+ templateCache.set(key, candidate);
42
+ return candidate;
43
+ }
44
+ if (dir === root)
45
+ break;
46
+ dir = dirname(dir);
47
+ }
48
+ for (const key of visited)
49
+ templateCache.set(key, null);
50
+ return null;
51
+ }
52
+ /**
53
+ * Whether a page gets no generated Open Graph image: it sets its own image in front matter
54
+ * (`seo.openGraph.image`, or `false` to have none) or matches an `exclude` pattern.
55
+ */
56
+ export function isOgImageExcluded(page, exclude) {
57
+ const seo = page.frontMatter.seo;
58
+ const image = seo?.openGraph?.image;
59
+ if (image !== undefined && image !== null && image !== '') {
60
+ return true;
61
+ }
62
+ return exclude.some((pattern) => matchesGlob(page.url, pattern));
63
+ }
64
+ /**
65
+ * File name stem for a page's Open Graph image, from its URL.
66
+ * The root page is `index`; `/blog/hello/` becomes `blog-hello`.
67
+ */
68
+ export function ogImageSlug(url) {
69
+ const slug = url
70
+ .split('/')
71
+ .filter(Boolean)
72
+ .join('-')
73
+ .replace(/[^a-zA-Z0-9-_]+/g, '-')
74
+ .replace(/-+/g, '-')
75
+ .replace(/^-|-$/g, '')
76
+ .toLowerCase();
77
+ return slug || 'index';
78
+ }
79
+ const MIME_BY_EXTENSION = {
80
+ '.png': 'image/png',
81
+ '.jpg': 'image/jpeg',
82
+ '.jpeg': 'image/jpeg',
83
+ '.gif': 'image/gif',
84
+ '.webp': 'image/webp',
85
+ '.avif': 'image/avif',
86
+ '.svg': 'image/svg+xml',
87
+ };
88
+ const NAMED_ENTITIES = {
89
+ amp: '&',
90
+ lt: '<',
91
+ gt: '>',
92
+ quot: '"',
93
+ apos: "'",
94
+ };
95
+ /**
96
+ * Decodes the character references in an attribute value: the ones Eta's escaping writes,
97
+ * and numeric ones.
98
+ */
99
+ function decodeHtmlEntities(text) {
100
+ return text.replace(/&(#[xX][0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, (match, entity) => {
101
+ if (!entity.startsWith('#'))
102
+ return NAMED_ENTITIES[entity];
103
+ const code = entity[1] === 'x' || entity[1] === 'X'
104
+ ? parseInt(entity.slice(2), 16)
105
+ : parseInt(entity.slice(1), 10);
106
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
107
+ });
108
+ }
109
+ /**
110
+ * Replaces local `<img src>` values in Open Graph HTML with data URIs, because the renderer
111
+ * does not fetch files. Root-relative paths resolve from the static directory, relative ones
112
+ * from `baseDir`. Remote URLs and data URIs are left alone.
113
+ *
114
+ * @param generatedSource - Finds the source of an image Stati generates (`/_img/...`), such as
115
+ * a responsive variant from `stati.image()`. Cards inline the source, because generated
116
+ * files may not exist yet.
117
+ * @returns The HTML and the absolute paths of the files that were inlined
118
+ */
119
+ export async function inlineLocalImages(html, dirs, generatedSource) {
120
+ const files = [];
121
+ // `[^<>]` keeps each match inside one tag, so unclosed tags can't make the search quadratic
122
+ const pattern = /(<img\b[^<>]*?\bsrc\s*=\s*)("([^"]*)"|'([^']*)')/gi;
123
+ const replacements = [];
124
+ for (const match of html.matchAll(pattern)) {
125
+ // The value is HTML-escaped: `a&amp;b.png` names the file `a&b.png`
126
+ const src = decodeHtmlEntities(match[3] ?? match[4] ?? '').trim();
127
+ if (!src || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(src))
128
+ continue;
129
+ let path;
130
+ try {
131
+ path = decodeURIComponent(src.replace(/[?#].*$/, ''));
132
+ }
133
+ catch {
134
+ continue;
135
+ }
136
+ let filePath = generatedSource?.(path);
137
+ if (!filePath) {
138
+ filePath = path.startsWith('/') ? join(dirs.staticDir, path) : resolve(dirs.baseDir, path);
139
+ const root = path.startsWith('/') ? dirs.staticDir : dirs.srcDir;
140
+ if (!isPathWithinDirectory(root, filePath))
141
+ continue;
142
+ }
143
+ const mime = MIME_BY_EXTENSION[extname(filePath).toLowerCase()];
144
+ if (!mime)
145
+ continue;
146
+ files.push(filePath.replace(/\\/g, '/'));
147
+ const bytes = await readFileBuffer(filePath);
148
+ if (!bytes)
149
+ continue;
150
+ const dataUri = `data:${mime};base64,${bytes.toString('base64')}`;
151
+ replacements.push({ match: match[0], replacement: `${match[1]}"${dataUri}"` });
152
+ }
153
+ let result = html;
154
+ for (const { match, replacement } of replacements) {
155
+ // A function, so `$&` and the like in the tag's other attributes stay literal
156
+ result = result.replace(match, () => replacement);
157
+ }
158
+ return { html: result, files };
159
+ }
160
+ /**
161
+ * The template path to show in messages, relative to the project.
162
+ */
163
+ export function displayTemplatePath(templatePath) {
164
+ return relative(process.cwd(), templatePath).replace(/\\/g, '/') || templatePath;
165
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Decides which files to generate for an image and what to call them.
3
+ * Names come from inputs, not from encoded bytes, so page HTML can be written before
4
+ * encoding finishes.
5
+ * @module images/plan
6
+ */
7
+ import type { ImageOutputFormat, ImageSourceFormat } from '../types/index.js';
8
+ import type { ResolvedResponsiveConfig } from './config.js';
9
+ /**
10
+ * Picks the widths to generate for an image.
11
+ * Configured widths up to the image's own width are kept, and the image's own width is
12
+ * added when it is below the largest configured width. Images are never enlarged.
13
+ *
14
+ * @param intrinsicWidth - The image's display width
15
+ * @param configured - Candidate widths, ascending
16
+ * @returns Widths to generate, ascending
17
+ */
18
+ export declare function planWidths(intrinsicWidth: number, configured: readonly number[]): number[];
19
+ /**
20
+ * The format of the `<img>` fallback for a source format: the source's own format, except
21
+ * GIF, which becomes PNG.
22
+ */
23
+ export declare function fallbackFormatFor(format: ImageSourceFormat): ImageOutputFormat;
24
+ /**
25
+ * File extension for a format.
26
+ */
27
+ export declare function extensionFor(format: ImageSourceFormat | ImageOutputFormat): string;
28
+ /**
29
+ * MIME type for a generated format.
30
+ */
31
+ export declare function mimeTypeFor(format: ImageOutputFormat): string;
32
+ /**
33
+ * A URL-safe base name for generated files, from the source file name.
34
+ */
35
+ export declare function imageBaseName(filePath: string): string;
36
+ /** One file to generate, with its path relative to the output directory and its URL. */
37
+ export interface PlannedOutput {
38
+ /** Path relative to the output directory, with forward slashes */
39
+ relPath: string;
40
+ /** Root-relative URL */
41
+ url: string;
42
+ width: number;
43
+ format: ImageOutputFormat;
44
+ quality?: number;
45
+ }
46
+ /**
47
+ * A copy of a co-located source image under its content-hashed name.
48
+ */
49
+ export interface CopyPlan {
50
+ key: string;
51
+ /** Path relative to the output directory, with forward slashes */
52
+ relPath: string;
53
+ /** Root-relative URL */
54
+ url: string;
55
+ }
56
+ /**
57
+ * Plans the copy of a co-located image: `/_img/{name}-{hash}.{ext}`.
58
+ *
59
+ * @param filePath - Absolute source path
60
+ * @param sourceHash - SHA-256 of the source bytes
61
+ * @param format - Source format
62
+ */
63
+ export declare function planCopy(filePath: string, sourceHash: string, format: ImageSourceFormat): CopyPlan;
64
+ /**
65
+ * Generated files for one responsive image, grouped for markup.
66
+ */
67
+ export interface VariantPlan {
68
+ /** Cache key covering the output name, source bytes, options and encoder */
69
+ key: string;
70
+ /** Every file to generate */
71
+ outputs: PlannedOutput[];
72
+ /** `<source>` elements, one per modern format, in order of preference */
73
+ sources: Array<{
74
+ type: string;
75
+ srcset: string;
76
+ }>;
77
+ /** The `<img>` fallback in the source's own format */
78
+ fallback: {
79
+ src: string;
80
+ srcset: string;
81
+ };
82
+ }
83
+ /**
84
+ * Inputs for {@link planVariants}.
85
+ */
86
+ export interface VariantPlanInput {
87
+ filePath: string;
88
+ sourceHash: string;
89
+ format: ImageSourceFormat;
90
+ /** Display width */
91
+ width: number;
92
+ responsive: ResolvedResponsiveConfig;
93
+ /** Encoder identity, so encoder upgrades produce new URLs */
94
+ providerVersion: string;
95
+ }
96
+ /**
97
+ * Plans the responsive variants of one image: `/_img/{name}-{hash}-{width}.{ext}` for every
98
+ * width in each modern format, plus the fallback format.
99
+ */
100
+ export declare function planVariants(input: VariantPlanInput): VariantPlan;
101
+ //# sourceMappingURL=plan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../src/images/plan.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAa5D;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,cAAc,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAU1F;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,CAE9E;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,GAAG,MAAM,CAElF;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAE7D;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,wFAAwF;AACxF,MAAM,WAAW,aAAa;IAC5B,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,wBAAwB;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,iBAAiB,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,wBAAwB;IACxB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACtB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,iBAAiB,GACxB,QAAQ,CAMV;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,4EAA4E;IAC5E,GAAG,EAAE,MAAM,CAAC;IACZ,6BAA6B;IAC7B,OAAO,EAAE,aAAa,EAAE,CAAC;IACzB,yEAAyE;IACzE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACjD,sDAAsD;IACtD,QAAQ,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3C;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,oBAAoB;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,wBAAwB,CAAC;IACrC,6DAA6D;IAC7D,eAAe,EAAE,MAAM,CAAC;CACzB;AAaD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG,WAAW,CAiDjE"}
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Decides which files to generate for an image and what to call them.
3
+ * Names come from inputs, not from encoded bytes, so page HTML can be written before
4
+ * encoding finishes.
5
+ * @module images/plan
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { basename, extname, posix } from 'node:path';
9
+ import { slugify } from '../core/utils/index.js';
10
+ import { IMAGES_OUTPUT_DIR } from '../constants.js';
11
+ /** Length of the hash in generated file names. */
12
+ const NAME_HASH_LENGTH = 8;
13
+ /** MIME types for `<source type>`. */
14
+ const MIME_TYPES = {
15
+ avif: 'image/avif',
16
+ webp: 'image/webp',
17
+ jpeg: 'image/jpeg',
18
+ png: 'image/png',
19
+ };
20
+ /**
21
+ * Picks the widths to generate for an image.
22
+ * Configured widths up to the image's own width are kept, and the image's own width is
23
+ * added when it is below the largest configured width. Images are never enlarged.
24
+ *
25
+ * @param intrinsicWidth - The image's display width
26
+ * @param configured - Candidate widths, ascending
27
+ * @returns Widths to generate, ascending
28
+ */
29
+ export function planWidths(intrinsicWidth, configured) {
30
+ const widths = configured.filter((width) => width <= intrinsicWidth);
31
+ const largest = configured.length > 0 ? Math.max(...configured) : intrinsicWidth;
32
+ if (intrinsicWidth < largest && !widths.includes(intrinsicWidth)) {
33
+ widths.push(intrinsicWidth);
34
+ }
35
+ if (widths.length === 0) {
36
+ widths.push(intrinsicWidth);
37
+ }
38
+ return [...new Set(widths)].sort((a, b) => a - b);
39
+ }
40
+ /**
41
+ * The format of the `<img>` fallback for a source format: the source's own format, except
42
+ * GIF, which becomes PNG.
43
+ */
44
+ export function fallbackFormatFor(format) {
45
+ return format === 'gif' ? 'png' : format;
46
+ }
47
+ /**
48
+ * File extension for a format.
49
+ */
50
+ export function extensionFor(format) {
51
+ return format === 'jpeg' ? 'jpg' : format;
52
+ }
53
+ /**
54
+ * MIME type for a generated format.
55
+ */
56
+ export function mimeTypeFor(format) {
57
+ return MIME_TYPES[format];
58
+ }
59
+ /**
60
+ * A URL-safe base name for generated files, from the source file name.
61
+ */
62
+ export function imageBaseName(filePath) {
63
+ return slugify(basename(filePath, extname(filePath))) || 'image';
64
+ }
65
+ /**
66
+ * Plans the copy of a co-located image: `/_img/{name}-{hash}.{ext}`.
67
+ *
68
+ * @param filePath - Absolute source path
69
+ * @param sourceHash - SHA-256 of the source bytes
70
+ * @param format - Source format
71
+ */
72
+ export function planCopy(filePath, sourceHash, format) {
73
+ const relPath = posix.join(IMAGES_OUTPUT_DIR, `${imageBaseName(filePath)}-${sourceHash.slice(0, NAME_HASH_LENGTH)}.${extensionFor(format)}`);
74
+ return { key: `copy:${relPath}`, relPath, url: `/${relPath}` };
75
+ }
76
+ function qualityFor(format, responsive) {
77
+ return responsive.quality[format];
78
+ }
79
+ function srcsetOf(outputs) {
80
+ return outputs.map((output) => `${output.url} ${output.width}w`).join(', ');
81
+ }
82
+ /**
83
+ * Plans the responsive variants of one image: `/_img/{name}-{hash}-{width}.{ext}` for every
84
+ * width in each modern format, plus the fallback format.
85
+ */
86
+ export function planVariants(input) {
87
+ const widths = planWidths(input.width, input.responsive.widths);
88
+ const fallbackFormat = fallbackFormatFor(input.format);
89
+ const formats = input.responsive.formats.filter((format) => format !== fallbackFormat);
90
+ const hash = createHash('sha256')
91
+ .update(JSON.stringify({
92
+ source: input.sourceHash,
93
+ widths,
94
+ formats,
95
+ fallbackFormat,
96
+ quality: [...formats, fallbackFormat].map((f) => qualityFor(f, input.responsive) ?? null),
97
+ provider: input.providerVersion,
98
+ }))
99
+ .digest('hex');
100
+ const baseName = imageBaseName(input.filePath);
101
+ const name = `${baseName}-${hash.slice(0, NAME_HASH_LENGTH)}`;
102
+ const outputsFor = (format) => widths.map((width) => {
103
+ const relPath = posix.join(IMAGES_OUTPUT_DIR, `${name}-${width}.${extensionFor(format)}`);
104
+ const quality = qualityFor(format, input.responsive);
105
+ return {
106
+ relPath,
107
+ url: `/${relPath}`,
108
+ width,
109
+ format,
110
+ ...(quality !== undefined && { quality }),
111
+ };
112
+ });
113
+ const sourceOutputs = formats.map((format) => ({ format, outputs: outputsFor(format) }));
114
+ const fallbackOutputs = outputsFor(fallbackFormat);
115
+ return {
116
+ // The name is part of the key: identical files under different names get their own outputs
117
+ key: `variants:${baseName}:${hash}`,
118
+ outputs: [...sourceOutputs.flatMap((group) => group.outputs), ...fallbackOutputs],
119
+ sources: sourceOutputs.map((group) => ({
120
+ type: mimeTypeFor(group.format),
121
+ srcset: srcsetOf(group.outputs),
122
+ })),
123
+ fallback: {
124
+ src: fallbackOutputs[fallbackOutputs.length - 1].url,
125
+ srcset: srcsetOf(fallbackOutputs),
126
+ },
127
+ };
128
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Finds and loads the optional `@stati/images` package.
3
+ * @module images/provider
4
+ */
5
+ import type { ImageProvider } from '../types/index.js';
6
+ /** Provider contract version this core supports. */
7
+ export declare const SUPPORTED_PROVIDER_API_VERSION = 1;
8
+ /** Image features that need the package. */
9
+ export type ImageFeature = 'responsive' | 'og';
10
+ /**
11
+ * Resolves the package from the project, as markdown-it plugins are, so it is found under
12
+ * strict layouts such as pnpm's where core cannot see the project's dependencies.
13
+ * Resolution walks up from the project, which also covers workspaces.
14
+ *
15
+ * @returns The resolved entry file, or null when the package is not installed
16
+ */
17
+ export declare function resolveImagesPackage(cwd?: string): string | null;
18
+ /**
19
+ * The error shown when a feature is on but the package is missing.
20
+ */
21
+ export declare function missingPackageMessage(features: ImageFeature[]): string;
22
+ /**
23
+ * Checks that the package is installed and, when `load` is set, creates its provider.
24
+ *
25
+ * @param options.features - The features that are on; they decide the error message
26
+ * @param options.load - Whether to import the package; false only checks it is installed
27
+ * @returns The provider, or null when `load` is false
28
+ * @throws {Error} When the package is missing, fails to load, or is incompatible
29
+ */
30
+ export declare function loadImageProvider(options: {
31
+ features: ImageFeature[];
32
+ load: boolean;
33
+ cwd?: string;
34
+ }): Promise<ImageProvider | null>;
35
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/images/provider.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAIvD,oDAAoD;AACpD,eAAO,MAAM,8BAA8B,IAAI,CAAC;AAEhD,4CAA4C;AAC5C,MAAM,MAAM,YAAY,GAAG,YAAY,GAAG,IAAI,CAAC;AAE/C;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,GAAE,MAAsB,GAAG,MAAM,GAAG,IAAI,CAO/E;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,MAAM,CAItE;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,OAAO,EAAE;IAC/C,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,IAAI,EAAE,OAAO,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAuChC"}