@riebeckite/plugin-responsive-image 0.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @riebeckite/plugin-responsive-image
2
+
3
+ Upgrades existing `<img>` elements with lazy loading and responsive
4
+ `<picture>` / `srcset` markup, using only image variants that are already
5
+ present in the content manifest.
6
+
7
+ [日本語](./README_ja.md)
8
+
9
+ ## Overview
10
+
11
+ `responsiveImage()` runs as a build-time HTML layer:
12
+
13
+ 1. It always adds `loading="lazy"` and `decoding="async"` to `<img>` elements
14
+ unless those attributes are already set.
15
+ 2. It adds a `sizes` attribute when one is missing.
16
+ 3. It looks for sibling variants that already exist in the manifest
17
+ (`photo.webp`, `photo.avif`, `photo-640.webp`, `photo-640.png`, …). When
18
+ variants are found the `<img>` becomes a `<picture>` element with grouped
19
+ `<source>` elements. When no variants are found the `<img>` is left in place
20
+ with just the added attributes.
21
+
22
+ The plugin never fabricates URLs and never writes files. It only references
23
+ assets that the manifest already knows about.
24
+
25
+ ## Usage
26
+
27
+ ```ts
28
+ import { defineConfig } from "@riebeckite/core";
29
+ import { attachment } from "@riebeckite/plugin-attachment";
30
+ import { obsidianMarkdown } from "@riebeckite/plugin-obsidian-markdown";
31
+ import { responsiveImage } from "@riebeckite/plugin-responsive-image";
32
+
33
+ export default defineConfig({
34
+ // ...
35
+ plugins: [obsidianMarkdown(), attachment(), responsiveImage()],
36
+ });
37
+ ```
38
+
39
+ `responsiveImage()` uses `order: 100`, so it runs after the media and
40
+ attachment renderers.
41
+
42
+ ## Options
43
+
44
+ | Option | Type | Default | Description |
45
+ | ------ | ---- | ------- | ----------- |
46
+ | `lazy` | `boolean` | `true` | Adds `loading="lazy"` when absent |
47
+ | `decoding` | `boolean` | `true` | Adds `decoding="async"` when absent |
48
+ | `sizes` | `string` | `"100vw"` | Fallback `sizes` value added when absent |
49
+ | `widths` | `number[]` | `[640, 1280, 1920]` | Width variants to look up |
50
+ | `formats` | `string[]` | `["webp", "avif"]` | Format variants to look up |
51
+ | `className` | `string` | `"rb-responsive-image"` | Class applied to `<picture>` |
52
+ | `generate` | `boolean` | `false` | Reserved |
53
+ | `outputDir` | `string` | unset | Reserved |
54
+
55
+ ## Variant discovery
56
+
57
+ Variants are matched against the asset paths the manifest already contains:
58
+
59
+ - format variants: `photo.webp`, `photo.avif`
60
+ - width variants: `photo-640.webp`, `photo-1280.avif`, `photo-1920.png`
61
+ - width variants in the original format: `photo-640.png`
62
+
63
+ The plugin maps the original `<img src>` back to a manifest asset by trying the
64
+ site asset URL (`/attachments/photo.png`) and the attachment URL
65
+ (`/assets/attachments/photo.png`). If the source cannot be matched to a manifest
66
+ asset, the `<img>` is left untouched.
67
+
68
+ ## Limitation: no image encoding
69
+
70
+ This plugin is a deterministic discovery/HTML layer. It does **not** encode or
71
+ generate new image files by default. `PluginAsset` only supports `style` and
72
+ `script` module specifiers, so Core currently exposes no supported way for a
73
+ plugin to emit arbitrary binary files into the build output.
74
+
75
+ `generate` and `outputDir` are reserved for a future release and do nothing
76
+ today. Adding real encoding requires a Core file-emission API; until then,
77
+ pre-generate the variants yourself (for example with an external image tool) and
78
+ commit them next to the original image. Sites copy referenced vault assets into
79
+ `public/` through `apps/web/scripts/build_images.ts`.
80
+
81
+ ## Exports
82
+
83
+ - `responsiveImage(options?)` / `responsiveImagePlugin` — plugin factory
84
+ - `resolveResponsiveImageOptions(options?)` — resolve defaults
85
+ - `buildResponsiveSrcset(existingPaths, src, options?)` — pure srcset planner
86
+ - `applyResponsiveImages(html, existingPaths, options?)` — HTML transform
87
+ - `collectKnownAssetPaths(manifest)` — manifest asset set helper
88
+ - Types: `ResponsiveImageOptions`, `ResolvedResponsiveImageOptions`,
89
+ `ResponsiveImagePlan`, `ResponsiveImageSource`, `ResponsiveImageVariant`
package/README_ja.md ADDED
@@ -0,0 +1,69 @@
1
+ # @riebeckite/plugin-responsive-image
2
+
3
+ 既存の `<img>` に遅延読み込みと、レスポンシブな `<picture>` / `srcset` を付与するプラグインです。参照するのは、すでにコンテンツマニフェストに存在する画像バリアントだけです。
4
+
5
+ [English](./README.md)
6
+
7
+ ## できること
8
+
9
+ `responsiveImage()` はビルド時の HTML レイヤーとして動作します。
10
+
11
+ 1. `<img>` に `loading="lazy"` と `decoding="async"` を付与します。すでに属性がある場合は変更しません。
12
+ 2. `sizes` がなければ追加します。
13
+ 3. マニフェスト上に存在する兄弟バリアント(`photo.webp`、`photo.avif`、`photo-640.webp`、`photo-640.png` など)を探します。見つかれば `<img>` を `<picture>` に置き換え、形式ごとの `<source>` を並べます。見つからなければ `<img>` のまま、追加属性だけを残します。
14
+
15
+ URL を捏造することはありません。ファイルを書き出すこともありません。マニフェストが把握しているアセットだけを参照します。
16
+
17
+ ## 設定
18
+
19
+ ```ts
20
+ import { defineConfig } from "@riebeckite/core";
21
+ import { attachment } from "@riebeckite/plugin-attachment";
22
+ import { obsidianMarkdown } from "@riebeckite/plugin-obsidian-markdown";
23
+ import { responsiveImage } from "@riebeckite/plugin-responsive-image";
24
+
25
+ export default defineConfig({
26
+ // ...
27
+ plugins: [obsidianMarkdown(), attachment(), responsiveImage()],
28
+ });
29
+ ```
30
+
31
+ `responsiveImage()` は `order: 100` で動作するため、メディアと添付ファイルのレンダラーより後に実行されます。
32
+
33
+ ## オプション
34
+
35
+ | オプション | 型 | 既定値 | 内容 |
36
+ | --- | --- | --- | --- |
37
+ | `lazy` | `boolean` | `true` | 未指定時に `loading="lazy"` を付与 |
38
+ | `decoding` | `boolean` | `true` | 未指定時に `decoding="async"` を付与 |
39
+ | `sizes` | `string` | `"100vw"` | 未指定時に追加する `sizes` |
40
+ | `widths` | `number[]` | `[640, 1280, 1920]` | 探索する幅バリアント |
41
+ | `formats` | `string[]` | `["webp", "avif"]` | 探索する形式バリアント |
42
+ | `className` | `string` | `"rb-responsive-image"` | `<picture>` に付与するクラス |
43
+ | `generate` | `boolean` | `false` | 予約 |
44
+ | `outputDir` | `string` | 未設定 | 予約 |
45
+
46
+ ## バリアントの探索
47
+
48
+ バリアントは、マニフェストに登録済みのアセットパスと照合します。
49
+
50
+ - 形式バリアント: `photo.webp`、`photo.avif`
51
+ - 幅バリアント: `photo-640.webp`、`photo-1280.avif`、`photo-1920.png`
52
+ - 元の形式の幅バリアント: `photo-640.png`
53
+
54
+ 元の `<img src>` は、サイトのアセット URL(`/attachments/photo.png`)と添付ファイル URL(`/assets/attachments/photo.png`)の両方を試して、マニフェスト上のアセットに対応付けます。対応するアセットが見つからない `<img>` はそのまま残します。
55
+
56
+ ## 制約: 画像のエンコードはしない
57
+
58
+ このプラグインは、決定的な探索と HTML 変換だけを担当します。既定では新しい画像ファイルを生成しません。`PluginAsset` は `style` と `script` のモジュール指定子しか扱えず、プラグインが任意のバイナリファイルをビルド成果物へ出力する手段を Core は提供していません。
59
+
60
+ `generate` と `outputDir` は将来のリリース向けの予約で、現在は何もしません。実際のエンコードには Core のファイル出力 API が必要です。それまでは、外部の画像ツールなどでバリアントを事前生成し、元画像の隣にコミットしてください。サイト側では `apps/web/scripts/build_images.ts` が、参照されたボールト内アセットを `public/` へコピーします。
61
+
62
+ ## 公開 API
63
+
64
+ - `responsiveImage(options?)` / `responsiveImagePlugin` — プラグインファクトリ
65
+ - `resolveResponsiveImageOptions(options?)` — 既定値の解決
66
+ - `buildResponsiveSrcset(existingPaths, src, options?)` — 純粋な srcset 計画
67
+ - `applyResponsiveImages(html, existingPaths, options?)` — HTML 変換
68
+ - `collectKnownAssetPaths(manifest)` — マニフェストのアセット集合を取得
69
+ - 型: `ResponsiveImageOptions`、`ResolvedResponsiveImageOptions`、`ResponsiveImagePlan`、`ResponsiveImageSource`、`ResponsiveImageVariant`
@@ -0,0 +1,17 @@
1
+ import { type ResponsiveImageOptions } from "./src/options.js";
2
+ export type { ResolvedResponsiveImageOptions, ResponsiveImageOptions, } from "./src/options.js";
3
+ export { DEFAULT_RESPONSIVE_IMAGE_CLASS, DEFAULT_RESPONSIVE_IMAGE_FORMATS, DEFAULT_RESPONSIVE_IMAGE_SIZES, DEFAULT_RESPONSIVE_IMAGE_WIDTHS, resolveResponsiveImageOptions, } from "./src/options.js";
4
+ export type { ResponsiveImagePlan, ResponsiveImageSource, ResponsiveImageVariant, } from "./src/types.js";
5
+ export { buildResponsiveSrcset, collectKnownAssetPaths } from "./src/srcset.js";
6
+ export { rehypeResponsiveImage } from "./src/rehype.js";
7
+ export { applyResponsiveImages } from "./src/html.js";
8
+ /**
9
+ * Build-time responsive image layer.
10
+ *
11
+ * The plugin normalises `loading`, `decoding` and `sizes` on `<img>` elements
12
+ * during the HTML pipeline, then upgrades marked images into `<picture>` /
13
+ * `srcset` markup only when matching sibling variants already exist in the
14
+ * content manifest. It never fabricates URLs and never writes files.
15
+ */
16
+ export declare function responsiveImage(options?: ResponsiveImageOptions): import("@riebeckite/core").RiebeckitePlugin<ResponsiveImageOptions>;
17
+ export declare const responsiveImagePlugin: typeof responsiveImage;
package/dist/index.js ADDED
@@ -0,0 +1,429 @@
1
+ // index.ts
2
+ import {
3
+ createStyleAsset,
4
+ definePlugin
5
+ } from "@riebeckite/core";
6
+
7
+ // src/html.ts
8
+ import { escapeHtmlAttribute } from "@riebeckite/core";
9
+
10
+ // src/options.ts
11
+ var DEFAULT_RESPONSIVE_IMAGE_CLASS = "rb-responsive-image";
12
+ var DEFAULT_RESPONSIVE_IMAGE_SIZES = "100vw";
13
+ var DEFAULT_RESPONSIVE_IMAGE_WIDTHS = [640, 1280, 1920];
14
+ var DEFAULT_RESPONSIVE_IMAGE_FORMATS = ["webp", "avif"];
15
+ function resolveResponsiveImageOptions(options = {}) {
16
+ return {
17
+ lazy: options.lazy ?? true,
18
+ decoding: options.decoding ?? true,
19
+ sizes: normalizeSizes(options.sizes),
20
+ widths: normalizeWidths(options.widths),
21
+ formats: normalizeFormats(options.formats),
22
+ className: normalizeClassName(options.className),
23
+ generate: options.generate ?? false,
24
+ outputDir: options.outputDir ?? null
25
+ };
26
+ }
27
+ function validateResponsiveImageOptions(options) {
28
+ if (!options) return [];
29
+ const issues = [];
30
+ for (const key of ["lazy", "decoding", "generate"]) {
31
+ if (options[key] !== void 0 && typeof options[key] !== "boolean") {
32
+ issues.push({ path: key, message: "Expected a boolean." });
33
+ }
34
+ }
35
+ if (options.sizes !== void 0 && (typeof options.sizes !== "string" || options.sizes.trim() === "")) {
36
+ issues.push({ path: "sizes", message: "Expected a non-empty string." });
37
+ }
38
+ if (options.className !== void 0 && (typeof options.className !== "string" || options.className.trim() === "")) {
39
+ issues.push({ path: "className", message: "Expected a non-empty string." });
40
+ }
41
+ if (options.widths !== void 0 && !isWidthList(options.widths)) {
42
+ issues.push({
43
+ path: "widths",
44
+ message: "Expected an array of positive integers."
45
+ });
46
+ }
47
+ if (options.formats !== void 0 && !isFormatList(options.formats)) {
48
+ issues.push({
49
+ path: "formats",
50
+ message: "Expected an array of non-empty strings."
51
+ });
52
+ }
53
+ if (options.outputDir !== void 0 && (typeof options.outputDir !== "string" || options.outputDir.trim() === "")) {
54
+ issues.push({ path: "outputDir", message: "Expected a non-empty string." });
55
+ }
56
+ return issues;
57
+ }
58
+ function normalizeSizes(value) {
59
+ const sizes = value?.trim();
60
+ return sizes ? sizes : DEFAULT_RESPONSIVE_IMAGE_SIZES;
61
+ }
62
+ function normalizeClassName(value) {
63
+ const className = value?.trim();
64
+ return className ? className : DEFAULT_RESPONSIVE_IMAGE_CLASS;
65
+ }
66
+ function normalizeWidths(value) {
67
+ if (!value) return [...DEFAULT_RESPONSIVE_IMAGE_WIDTHS];
68
+ const widths = Array.from(
69
+ new Set(
70
+ value.filter(
71
+ (width) => Number.isInteger(width) && width > 0
72
+ )
73
+ )
74
+ ).toSorted((a, b) => a - b);
75
+ return widths.length > 0 ? widths : [...DEFAULT_RESPONSIVE_IMAGE_WIDTHS];
76
+ }
77
+ function normalizeFormats(value) {
78
+ if (!value) return [...DEFAULT_RESPONSIVE_IMAGE_FORMATS];
79
+ const formats = [];
80
+ for (const candidate of value) {
81
+ if (typeof candidate !== "string") continue;
82
+ const format = candidate.trim().toLowerCase().replace(/^\.+/, "");
83
+ if (!/^[a-z0-9]+$/.test(format)) continue;
84
+ if (!formats.includes(format)) formats.push(format);
85
+ }
86
+ return formats.length > 0 ? formats : [...DEFAULT_RESPONSIVE_IMAGE_FORMATS];
87
+ }
88
+ function isWidthList(value) {
89
+ return Array.isArray(value) && value.every((item) => Number.isInteger(item) && item > 0);
90
+ }
91
+ function isFormatList(value) {
92
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "");
93
+ }
94
+
95
+ // src/srcset.ts
96
+ import {
97
+ attachmentUrl
98
+ } from "@riebeckite/core";
99
+ var FORMAT_MIME_TYPES = {
100
+ avif: "image/avif",
101
+ bmp: "image/bmp",
102
+ gif: "image/gif",
103
+ heic: "image/heic",
104
+ jpeg: "image/jpeg",
105
+ jpg: "image/jpeg",
106
+ jxl: "image/jxl",
107
+ png: "image/png",
108
+ svg: "image/svg+xml",
109
+ tiff: "image/tiff",
110
+ webp: "image/webp"
111
+ };
112
+ function buildResponsiveSrcset(existingPaths, src, options = {}) {
113
+ const resolved = resolveResponsiveImageOptions(options);
114
+ const known = toPathSet(existingPaths);
115
+ const match = matchKnownAsset(known, src);
116
+ if (!match) {
117
+ return { hasVariants: false, assetPath: null, sources: [], imgSrcset: "" };
118
+ }
119
+ const split = splitAssetPath(match.path);
120
+ if (!split) {
121
+ return { hasVariants: false, assetPath: null, sources: [], imgSrcset: "" };
122
+ }
123
+ const variants = collectVariants(split, resolved, known);
124
+ const urlFor = (path) => match.kind === "attachment" ? attachmentUrl(path) : `/${encodeAssetPath(path)}`;
125
+ const sources = [];
126
+ for (const format of resolved.formats) {
127
+ if (format === split.extension) continue;
128
+ const widthVariants = variants.filter((variant) => variant.format === format && variant.width !== void 0).toSorted((a, b) => (a.width ?? 0) - (b.width ?? 0));
129
+ if (widthVariants.length > 0) {
130
+ sources.push({
131
+ type: mimeTypeFor(format),
132
+ srcset: widthVariants.map((variant) => `${urlFor(variant.path)} ${variant.width}w`).join(", ")
133
+ });
134
+ continue;
135
+ }
136
+ const plainVariant = variants.find(
137
+ (variant) => variant.format === format && variant.width === void 0
138
+ );
139
+ if (plainVariant) {
140
+ sources.push({
141
+ type: mimeTypeFor(format),
142
+ srcset: urlFor(plainVariant.path)
143
+ });
144
+ }
145
+ }
146
+ const baseWidthVariants = variants.filter(
147
+ (variant) => variant.format === split.extension && variant.width !== void 0
148
+ ).toSorted((a, b) => (a.width ?? 0) - (b.width ?? 0));
149
+ const imgSrcset = baseWidthVariants.map((variant) => `${urlFor(variant.path)} ${variant.width}w`).join(", ");
150
+ return {
151
+ hasVariants: sources.length > 0 || imgSrcset !== "",
152
+ assetPath: match.path,
153
+ sources,
154
+ imgSrcset
155
+ };
156
+ }
157
+ function collectKnownAssetPaths(manifest) {
158
+ const paths = /* @__PURE__ */ new Set();
159
+ for (const entry of manifest.entries) {
160
+ for (const asset of entry.assets) paths.add(asset.path);
161
+ }
162
+ for (const path of manifest.byAsset.keys()) paths.add(path);
163
+ return paths;
164
+ }
165
+ function collectVariants(split, options, known) {
166
+ const variants = /* @__PURE__ */ new Map();
167
+ const add = (path, format, width) => {
168
+ if (path === joinAssetPath(split)) return;
169
+ if (!known.has(path)) return;
170
+ if (variants.has(path)) return;
171
+ variants.set(path, { path, format, width });
172
+ };
173
+ for (const format of options.formats) {
174
+ for (const width of options.widths) {
175
+ add(`${split.directory}${split.stem}-${width}.${format}`, format, width);
176
+ }
177
+ add(`${split.directory}${split.stem}.${format}`, format);
178
+ }
179
+ for (const width of options.widths) {
180
+ add(
181
+ `${split.directory}${split.stem}-${width}.${split.extension}`,
182
+ split.extension,
183
+ width
184
+ );
185
+ }
186
+ return [...variants.values()];
187
+ }
188
+ function matchKnownAsset(known, src) {
189
+ const clean = stripQueryAndFragment(src);
190
+ if (!clean || hasUrlScheme(clean)) return null;
191
+ const normalized = clean.startsWith("/") ? clean : `/${clean}`;
192
+ for (const path of known) {
193
+ if (normalized === `/${encodeAssetPath(path)}`) {
194
+ return { path, kind: "asset" };
195
+ }
196
+ if (normalized === attachmentUrl(path)) {
197
+ return { path, kind: "attachment" };
198
+ }
199
+ }
200
+ return null;
201
+ }
202
+ function splitAssetPath(path) {
203
+ const lastSlash = path.lastIndexOf("/");
204
+ const directory = path.slice(0, lastSlash + 1);
205
+ const fileName = path.slice(lastSlash + 1);
206
+ const dotIndex = fileName.lastIndexOf(".");
207
+ if (dotIndex <= 0 || dotIndex === fileName.length - 1) return null;
208
+ return {
209
+ directory,
210
+ stem: fileName.slice(0, dotIndex),
211
+ extension: fileName.slice(dotIndex + 1).toLowerCase()
212
+ };
213
+ }
214
+ function joinAssetPath(split) {
215
+ return `${split.directory}${split.stem}.${split.extension}`;
216
+ }
217
+ function mimeTypeFor(format) {
218
+ return FORMAT_MIME_TYPES[format] ?? `image/${format}`;
219
+ }
220
+ function toPathSet(paths) {
221
+ return paths instanceof Set ? paths : new Set(paths);
222
+ }
223
+ function stripQueryAndFragment(value) {
224
+ return value.split(/[?#]/, 1)[0] ?? "";
225
+ }
226
+ function hasUrlScheme(value) {
227
+ return /^[a-z][a-z0-9+.-]*:/i.test(value);
228
+ }
229
+ function encodeAssetPath(path) {
230
+ return path.split("/").map(encodeURIComponent).join("/");
231
+ }
232
+
233
+ // src/hast.ts
234
+ function visitElements(node, visitor, parent, index) {
235
+ if (isElementNode(node)) {
236
+ visitor(node, parent, index);
237
+ }
238
+ for (const [childIndex, child] of [...getChildren(node)].entries()) {
239
+ visitElements(
240
+ child,
241
+ visitor,
242
+ isElementNode(node) ? node : parent,
243
+ childIndex
244
+ );
245
+ }
246
+ }
247
+ function isElementNode(node) {
248
+ return node.type === "element";
249
+ }
250
+ function getStringProperty(node, key) {
251
+ const value = node.properties?.[key];
252
+ if (typeof value === "string") return value;
253
+ if (Array.isArray(value)) return value.join(" ");
254
+ return null;
255
+ }
256
+ function hasProperty(node, key) {
257
+ return node.properties?.[key] !== void 0;
258
+ }
259
+ function ensureProperty(node, key, value) {
260
+ if (!node.properties) node.properties = {};
261
+ if (key in node.properties) return;
262
+ node.properties[key] = value;
263
+ }
264
+ function getChildren(node) {
265
+ const children = node.children;
266
+ return Array.isArray(children) ? children : [];
267
+ }
268
+
269
+ // src/rehype.ts
270
+ var RESPONSIVE_IMAGE_MARKER = "data-responsive-image";
271
+ var RESPONSIVE_IMAGE_SOURCE = "@riebeckite/plugin-responsive-image";
272
+ var MARKER_PROPERTY = "dataResponsiveImage";
273
+ function rehypeResponsiveImage(options = {}) {
274
+ const resolved = resolveResponsiveImageOptions(options);
275
+ return (tree, file) => {
276
+ visitElements(tree, (node) => {
277
+ if (node.tagName !== "img") return;
278
+ if (hasProperty(node, MARKER_PROPERTY)) return;
279
+ const src = getStringProperty(node, "src");
280
+ if (!src || src.trim() === "") {
281
+ warnMalformed(
282
+ file,
283
+ 'An <img> element is missing a usable "src".'
284
+ );
285
+ }
286
+ if (resolved.lazy) ensureProperty(node, "loading", "lazy");
287
+ if (resolved.decoding) ensureProperty(node, "decoding", "async");
288
+ ensureProperty(node, "sizes", resolved.sizes);
289
+ if (!node.properties) node.properties = {};
290
+ node.properties[MARKER_PROPERTY] = "";
291
+ });
292
+ };
293
+ }
294
+ function warnMalformed(file, message) {
295
+ if (typeof file?.message !== "function") return;
296
+ file.message(message, { source: RESPONSIVE_IMAGE_SOURCE });
297
+ }
298
+
299
+ // src/html.ts
300
+ var IMG_TAG_PATTERN = /<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
301
+ var ATTRIBUTE_PATTERN = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
302
+ function applyResponsiveImages(html, knownPaths, options = {}) {
303
+ if (!html.includes(RESPONSIVE_IMAGE_MARKER)) return html;
304
+ return html.replace(
305
+ IMG_TAG_PATTERN,
306
+ (tag) => transformImgTag(tag, knownPaths, options)
307
+ );
308
+ }
309
+ function transformImgTag(tag, knownPaths, options) {
310
+ const inner = tag.slice("<img".length, tag.length - 1);
311
+ const attributes = parseAttributes(inner);
312
+ if (!hasMarker(attributes)) return tag;
313
+ const src = findAttribute(attributes, "src")?.value ?? null;
314
+ if (!src || src.trim() === "") return tag;
315
+ const plan = buildResponsiveSrcset(knownPaths, src, options);
316
+ if (!plan.hasVariants) return tag;
317
+ const resolved = resolveResponsiveImageOptions(options);
318
+ const baseAttributes = attributes.filter(
319
+ (attribute) => attribute.name.toLowerCase() !== RESPONSIVE_IMAGE_MARKER
320
+ );
321
+ const imageAttributes = normalizeImageAttributes(baseAttributes, resolved);
322
+ if (plan.imgSrcset) {
323
+ setAttribute(imageAttributes, "srcset", plan.imgSrcset);
324
+ }
325
+ const sources = plan.sources.map(
326
+ (source) => `<source type="${escapeHtmlAttribute(source.type)}" srcset="${escapeHtmlAttribute(source.srcset)}" />`
327
+ ).join("");
328
+ const image = `<img ${serializeAttributes(imageAttributes)} />`;
329
+ return `<picture class="${escapeHtmlAttribute(resolved.className)}">${sources}${image}</picture>`;
330
+ }
331
+ function normalizeImageAttributes(attributes, resolved) {
332
+ const result = [...attributes];
333
+ if (resolved.lazy) ensureAttribute(result, "loading", "lazy");
334
+ if (resolved.decoding) ensureAttribute(result, "decoding", "async");
335
+ ensureAttribute(result, "sizes", resolved.sizes);
336
+ return result;
337
+ }
338
+ function ensureAttribute(attributes, name, value) {
339
+ if (findAttribute(attributes, name)) return;
340
+ attributes.push({ name, value, escaped: true });
341
+ }
342
+ function setAttribute(attributes, name, value) {
343
+ const existing = findAttribute(attributes, name);
344
+ if (existing) {
345
+ existing.value = value;
346
+ existing.escaped = true;
347
+ return;
348
+ }
349
+ attributes.push({ name, value, escaped: true });
350
+ }
351
+ function findAttribute(attributes, name) {
352
+ const target = name.toLowerCase();
353
+ return attributes.find(
354
+ (attribute) => attribute.name.toLowerCase() === target
355
+ );
356
+ }
357
+ function hasMarker(attributes) {
358
+ return findAttribute(attributes, RESPONSIVE_IMAGE_MARKER) !== void 0;
359
+ }
360
+ function parseAttributes(source) {
361
+ const attributes = [];
362
+ ATTRIBUTE_PATTERN.lastIndex = 0;
363
+ for (const match of source.matchAll(ATTRIBUTE_PATTERN)) {
364
+ attributes.push({
365
+ name: match[1],
366
+ value: match[2] ?? match[3] ?? match[4] ?? null,
367
+ escaped: false
368
+ });
369
+ }
370
+ return attributes;
371
+ }
372
+ function serializeAttributes(attributes) {
373
+ return attributes.map((attribute) => serializeAttribute(attribute)).join(" ");
374
+ }
375
+ function serializeAttribute(attribute) {
376
+ if (attribute.value === null) return attribute.name;
377
+ const value = attribute.escaped ? attribute.value : attribute.value.replace(/"/g, "&quot;");
378
+ return `${attribute.name}="${value}"`;
379
+ }
380
+
381
+ // index.ts
382
+ var PLUGIN_NAME = "responsive-image";
383
+ function responsiveImage(options = {}) {
384
+ const resolved = resolveResponsiveImageOptions(options);
385
+ const tracked = /* @__PURE__ */ new Map();
386
+ return definePlugin({
387
+ name: PLUGIN_NAME,
388
+ order: 100,
389
+ options,
390
+ validateOptions: validateResponsiveImageOptions,
391
+ extendHtmlPipeline: (pipeline) => {
392
+ pipeline.use(rehypeResponsiveImage, options);
393
+ },
394
+ onPostProcessed: (context) => {
395
+ tracked.set(context.slug, context.content);
396
+ },
397
+ onManifestCreated: (context) => {
398
+ const knownPaths = collectKnownAssetPaths(context.manifest);
399
+ for (const entry of context.manifest.entries) {
400
+ if (!entry.html.includes(RESPONSIVE_IMAGE_MARKER)) continue;
401
+ const html = applyResponsiveImages(entry.html, knownPaths, options);
402
+ if (html === entry.html) continue;
403
+ entry.html = html;
404
+ const content = tracked.get(entry.slug);
405
+ if (content) content.html = html;
406
+ }
407
+ if (resolved.generate) {
408
+ context.logger.warn(
409
+ "`generate` is reserved: image encoding is not implemented yet, so no images were generated."
410
+ );
411
+ }
412
+ },
413
+ assets: [createStyleAsset(PLUGIN_NAME)]
414
+ });
415
+ }
416
+ var responsiveImagePlugin = responsiveImage;
417
+ export {
418
+ DEFAULT_RESPONSIVE_IMAGE_CLASS,
419
+ DEFAULT_RESPONSIVE_IMAGE_FORMATS,
420
+ DEFAULT_RESPONSIVE_IMAGE_SIZES,
421
+ DEFAULT_RESPONSIVE_IMAGE_WIDTHS,
422
+ applyResponsiveImages,
423
+ buildResponsiveSrcset,
424
+ collectKnownAssetPaths,
425
+ rehypeResponsiveImage,
426
+ resolveResponsiveImageOptions,
427
+ responsiveImage,
428
+ responsiveImagePlugin
429
+ };
@@ -0,0 +1,6 @@
1
+ import type { ElementNode, HastNode } from "./types.js";
2
+ export declare function visitElements(node: HastNode, visitor: (node: ElementNode, parent?: ElementNode, index?: number) => void, parent?: ElementNode, index?: number): void;
3
+ export declare function isElementNode(node: HastNode): node is ElementNode;
4
+ export declare function getStringProperty(node: ElementNode, key: string): string | null;
5
+ export declare function hasProperty(node: ElementNode, key: string): boolean;
6
+ export declare function ensureProperty(node: ElementNode, key: string, value: string): void;
@@ -0,0 +1,9 @@
1
+ import type { ResponsiveImageOptions } from "./options.js";
2
+ /**
3
+ * Manifest pass: replace marked `<img>` elements with a `<picture>` element
4
+ * built from sibling variants that already exist in the content manifest.
5
+ *
6
+ * This is the "dual mutation" step used by the query plugin: the manifest
7
+ * entry HTML and the cached `PostContent.html` must stay in sync.
8
+ */
9
+ export declare function applyResponsiveImages(html: string, knownPaths: Iterable<string>, options?: ResponsiveImageOptions): string;
@@ -0,0 +1,58 @@
1
+ import type { ConfigValidationIssue } from "@riebeckite/core";
2
+ export declare const DEFAULT_RESPONSIVE_IMAGE_CLASS = "rb-responsive-image";
3
+ export declare const DEFAULT_RESPONSIVE_IMAGE_SIZES = "100vw";
4
+ export declare const DEFAULT_RESPONSIVE_IMAGE_WIDTHS: number[];
5
+ export declare const DEFAULT_RESPONSIVE_IMAGE_FORMATS: string[];
6
+ export type ResponsiveImageOptions = {
7
+ /**
8
+ * Add `loading="lazy"` to processed images when the attribute is absent.
9
+ * Defaults to `true`.
10
+ */
11
+ lazy?: boolean;
12
+ /**
13
+ * Add `decoding="async"` to processed images when the attribute is absent.
14
+ * Defaults to `true`.
15
+ */
16
+ decoding?: boolean;
17
+ /**
18
+ * Fallback `sizes` value added when the attribute is absent.
19
+ * Defaults to `"100vw"`.
20
+ */
21
+ sizes?: string;
22
+ /**
23
+ * Candidate widths used to look up pre-generated width variants.
24
+ * Defaults to `[640, 1280, 1920]`.
25
+ */
26
+ widths?: readonly number[];
27
+ /**
28
+ * Candidate formats used to look up pre-generated format variants.
29
+ * Defaults to `["webp", "avif"]`.
30
+ */
31
+ formats?: readonly string[];
32
+ /**
33
+ * Class name applied to the generated `<picture>` element.
34
+ * Defaults to `"rb-responsive-image"`.
35
+ */
36
+ className?: string;
37
+ /**
38
+ * Reserved. Binary encoding is not implemented because Core has no
39
+ * file-emission API for plugins. Prepared for a future release.
40
+ */
41
+ generate?: boolean;
42
+ /**
43
+ * Reserved. Only meaningful together with `generate`.
44
+ */
45
+ outputDir?: string;
46
+ };
47
+ export type ResolvedResponsiveImageOptions = {
48
+ lazy: boolean;
49
+ decoding: boolean;
50
+ sizes: string;
51
+ widths: readonly number[];
52
+ formats: readonly string[];
53
+ className: string;
54
+ generate: boolean;
55
+ outputDir: string | null;
56
+ };
57
+ export declare function resolveResponsiveImageOptions(options?: ResponsiveImageOptions): ResolvedResponsiveImageOptions;
58
+ export declare function validateResponsiveImageOptions(options: ResponsiveImageOptions | undefined): readonly ConfigValidationIssue[];
@@ -0,0 +1,9 @@
1
+ import type { ResponsiveImageOptions } from "./options.js";
2
+ import type { HastNode } from "./types.js";
3
+ export declare const RESPONSIVE_IMAGE_MARKER = "data-responsive-image";
4
+ export declare const RESPONSIVE_IMAGE_SOURCE = "@riebeckite/plugin-responsive-image";
5
+ /**
6
+ * HTML-pipeline pass: normalise the responsive attributes on every `<img>` and
7
+ * mark it so the manifest pass can wrap it once the asset set is known.
8
+ */
9
+ export declare function rehypeResponsiveImage(options?: ResponsiveImageOptions): (tree: HastNode, file: unknown) => void;
@@ -0,0 +1,12 @@
1
+ import { type ContentManifest } from "@riebeckite/core";
2
+ import { type ResponsiveImageOptions } from "./options.js";
3
+ import type { ResponsiveImagePlan } from "./types.js";
4
+ /**
5
+ * Build the deterministic `<picture>` plan for a single image.
6
+ *
7
+ * Variants are only used when they already exist in `existingPaths`; the helper
8
+ * never fabricates URLs for files that are not part of the content manifest.
9
+ */
10
+ export declare function buildResponsiveSrcset(existingPaths: Iterable<string>, src: string, options?: ResponsiveImageOptions): ResponsiveImagePlan;
11
+ /** Collect every asset path the content manifest knows about. */
12
+ export declare function collectKnownAssetPaths(manifest: ContentManifest): Set<string>;
@@ -0,0 +1,34 @@
1
+ export type ElementNode = {
2
+ type: string;
3
+ tagName?: string;
4
+ properties?: Record<string, unknown>;
5
+ children?: HastNode[];
6
+ };
7
+ export type HastNode = ElementNode | {
8
+ type: string;
9
+ [key: string]: unknown;
10
+ };
11
+ export type HastFile = {
12
+ message(reason: string, options?: {
13
+ source?: string;
14
+ }): unknown;
15
+ };
16
+ export type ParsedAttribute = {
17
+ name: string;
18
+ value: string | null;
19
+ };
20
+ export type ResponsiveImageVariant = {
21
+ path: string;
22
+ format: string;
23
+ width?: number;
24
+ };
25
+ export type ResponsiveImageSource = {
26
+ type: string;
27
+ srcset: string;
28
+ };
29
+ export type ResponsiveImagePlan = {
30
+ hasVariants: boolean;
31
+ assetPath: string | null;
32
+ sources: ResponsiveImageSource[];
33
+ imgSrcset: string;
34
+ };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@riebeckite/plugin-responsive-image",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./style.css": "./style.css"
16
+ },
17
+ "dependencies": {
18
+ "@riebeckite/core": "0.0.1"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "files": [
24
+ "LICENSE",
25
+ "README.md",
26
+ "README_ja.md",
27
+ "dist",
28
+ "style.css"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/Rerurate514/riebeckite.git",
33
+ "directory": "packages/plugins/responsive-image"
34
+ },
35
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
38
+ },
39
+ "description": "Responsive image markup and lazy loading for Riebeckite.",
40
+ "keywords": [
41
+ "riebeckite",
42
+ "plugin",
43
+ "images",
44
+ "responsive-images"
45
+ ],
46
+ "engines": {
47
+ "node": "^20.19.0 || >=22.12.0"
48
+ },
49
+ "sideEffects": [
50
+ "./style.css"
51
+ ],
52
+ "scripts": {
53
+ "build": "node ../../../scripts/build_package.mjs"
54
+ }
55
+ }
package/style.css ADDED
@@ -0,0 +1,11 @@
1
+ .rb-responsive-image {
2
+ display: block;
3
+ max-width: 100%;
4
+ }
5
+
6
+ .rb-responsive-image > img {
7
+ display: block;
8
+ width: 100%;
9
+ max-width: 100%;
10
+ height: auto;
11
+ }