@riebeckite/plugin-rename 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,123 @@
1
+ # @riebeckite/plugin-rename
2
+
3
+ Reduces broken URLs after notes are renamed or moved by turning detected
4
+ renames into permanent redirects on the existing Riebeckite redirect
5
+ machinery.
6
+
7
+ [日本語](./README_ja.md)
8
+
9
+ ## Basic usage
10
+
11
+ ```ts
12
+ import { defineConfig } from "@riebeckite/core";
13
+ import { renamePlugin } from "@riebeckite/plugin-rename";
14
+
15
+ export default defineConfig({
16
+ plugins: [
17
+ renamePlugin({
18
+ status: 308,
19
+ onUnexpectedRemoval: "warning",
20
+ }),
21
+ ],
22
+ });
23
+ ```
24
+
25
+ When a note moves, the plugin compares the current routes with the route lock
26
+ saved during the previous build. If it can identify the same note, it records a
27
+ redirect from the old permalink to the new one in `manifest.redirects`, which
28
+ Core already consumes for redirect pages and deploy files.
29
+
30
+ ## How it works
31
+
32
+ ```text
33
+ current entries (published only)
34
+ │
35
+ ▼
36
+ buildRouteLock ──► current RouteLock
37
+ │ │
38
+ │ ▼
39
+ └──────────► diffRoutes(previous, current)
40
+ │
41
+ ┌──────────────┴───────────────┐
42
+ ▼ ▼
43
+ rename redirects diagnostics
44
+ (merged + chain-collapsed) (ambiguous / removed)
45
+ │
46
+ ▼
47
+ manifest.redirects ◄── never overwrites an existing key
48
+ │
49
+ ▼
50
+ context.cache "routes.lock"
51
+ ```
52
+
53
+ Detection precedence is strict and never fuzzy:
54
+
55
+ 1. **Explicit identity** — the entry's frontmatter `id` matches a lock route's
56
+ `id`.
57
+ 2. **Exact content hash** — `sha256(entry.html)` matches exactly one new route.
58
+ 3. Otherwise the route is treated as removed.
59
+
60
+ Multiple matching candidates (or none) produce no redirect. Ambiguous matches
61
+ emit a `rename-ambiguous` diagnostic; unmatched removals emit a diagnostic whose
62
+ severity follows `onUnexpectedRemoval`.
63
+
64
+ ## State
65
+
66
+ The plugin never writes files directly. The only cross-build state is the route
67
+ lock, stored through `context.cache` under the key `routes.lock`. The cache is
68
+ created under `<content.dir>/../.riebeckite/cache` and is gitignored, so the
69
+ lock is machine-local and is regenerated from scratch when missing or corrupt.
70
+
71
+ Because the lock is machine-local, the first build on a fresh machine has no
72
+ history and cannot detect a rename that happened before the lock existed.
73
+
74
+ ## Options
75
+
76
+ | Option | Type | Default | Description |
77
+ | --- | --- | --- | --- |
78
+ | `enabled` | `boolean` | `true` | Enables rename detection |
79
+ | `status` | `301 \| 302 \| 307 \| 308` | `308` | HTTP status for new rename redirects |
80
+ | `onUnexpectedRemoval` | `"info" \| "warning" \| "error"` | `"warning"` | Severity when a route disappears without rename evidence |
81
+
82
+ ## Rules and guarantees
83
+
84
+ - Only entries passing `isPublished` are considered. Private or unpublished
85
+ notes never enter the lock and never produce redirects.
86
+ - Existing `manifest.redirects` keys are never overwritten, so Permalink's
87
+ `redirect_from` always wins.
88
+ - Permanent redirect chains are collapsed transitively (`A → B`, `B → C`
89
+ becomes `A → C`).
90
+ - The lock is deterministic: route keys and redirects are sorted, with no
91
+ timestamps or randomness.
92
+ - Redirects are replayed on every build, so the CLI build and the SSG build
93
+ reproduce the same redirects.
94
+
95
+ ## Exports
96
+
97
+ Functions:
98
+
99
+ - `renamePlugin(options?)` / `rename(options?)`
100
+ - `diffRoutes(previous, current, options?)`
101
+ - `buildRouteLock(entries, isPublished)`
102
+ - `collapseRedirects(rules)`
103
+ - `applyRouteRedirects(manifest, rules)`
104
+ - `parseRouteLock(value)`, `emptyRouteLock()`, `hashContent(html)`
105
+
106
+ Types:
107
+
108
+ - `RenameOptions`
109
+ - `RouteLock`, `RouteLockRoute`, `RouteLockRedirect`, `RedirectRule`
110
+ - `DiffRoutesOptions`, `DiffRoutesResult`, `RenameDiagnostic`
111
+
112
+ ## Limitations
113
+
114
+ - Git-based rename detection is not implemented. It would require filesystem or
115
+ repository access, which plugin code intentionally avoids. Rename detection
116
+ relies on frontmatter `id` and on exact content hashes only.
117
+ - A rename in which both the `id` is absent and the HTML body changes cannot be
118
+ detected and is reported as an unexpected removal.
119
+
120
+ ## See also
121
+
122
+ - [Permalink plugin](../permalink/README_en.md) — stable URLs and `redirect_from`
123
+ - [Plugin guide](../../../docs/en/plugin-system.md)
package/README_ja.md ADDED
@@ -0,0 +1,103 @@
1
+ # @riebeckite/plugin-rename
2
+
3
+ ノートのリネームや移動で発生するリンク切れを減らすプラグインです。検出したリネームを、Riebeckite が既に持つリダイレクト機構(`manifest.redirects`)に恒久的なリダイレクトとして登録します。
4
+
5
+ [English](./README_en.md)
6
+
7
+ ## 基本的な使い方
8
+
9
+ ```ts
10
+ import { defineConfig } from "@riebeckite/core";
11
+ import { renamePlugin } from "@riebeckite/plugin-rename";
12
+
13
+ export default defineConfig({
14
+ plugins: [
15
+ renamePlugin({
16
+ status: 308,
17
+ onUnexpectedRemoval: "warning",
18
+ }),
19
+ ],
20
+ });
21
+ ```
22
+
23
+ ノートが移動すると、プラグインは現在のルートと、前回のビルドで保存したルートロックを比較します。同一のノートだと判定できた場合は、旧パーマリンクから新パーマリンクへのリダイレクトを `manifest.redirects` に記録します。Core はこのリダイレクトをリダイレクトページやデプロイ用ファイルとしてそのまま利用します。
24
+
25
+ ## 仕組み
26
+
27
+ ```text
28
+ 現在のエントリ(公開分のみ)
29
+ │
30
+ ▼
31
+ buildRouteLock ──► 現在の RouteLock
32
+ │ │
33
+ │ ▼
34
+ └──────────► diffRoutes(前回, 今回)
35
+ │
36
+ ┌──────────────┴───────────────┐
37
+ ▼ ▼
38
+ リネームのリダイレクト 診断メッセージ
39
+ (統合 + チェーン集約) (曖昧 / 消失)
40
+ │
41
+ ▼
42
+ manifest.redirects ◄── 既存キーは上書きしない
43
+ │
44
+ ▼
45
+ context.cache "routes.lock"
46
+ ```
47
+
48
+ 判定の優先順位は厳密で、あいまい一致は行いません。
49
+
50
+ 1. **明示的な同一性** — エントリの frontmatter `id` がロック内のルートの `id` と一致する。
51
+ 2. **内容ハッシュの完全一致** — `sha256(entry.html)` が新しいルートちょうど 1 件と一致する。
52
+ 3. どちらも該当しない場合、そのルートは消失とみなす。
53
+
54
+ 候補が複数ある場合、または 1 件もない場合はリダイレクトを作りません。曖昧一致では `rename-ambiguous` 診断を、対応の取れない消失では `onUnexpectedRemoval` に従った重要度の診断を出力します。
55
+
56
+ ## 状態の保存
57
+
58
+ プラグインが直接ファイルを書き込むことはありません。ビルドをまたぐ状態はルートロックのみで、`context.cache` の `routes.lock` キーに保存します。キャッシュは `<content.dir>/../.riebeckite/cache` に作られて gitignore の対象なので、ロックはマシンローカルです。存在しない場合や壊れている場合は空のロックから再生成します。
59
+
60
+ ロックがマシンローカルであるため、新しいマシンでの初回ビルドには履歴がなく、ロックが存在する前に起きたリネームは検出できません。
61
+
62
+ ## オプション
63
+
64
+ | オプション | 型 | 既定値 | 説明 |
65
+ | --- | --- | --- | --- |
66
+ | `enabled` | `boolean` | `true` | リネーム検出を有効にする |
67
+ | `status` | `301 \| 302 \| 307 \| 308` | `308` | 新規リネームリダイレクトの HTTP ステータス |
68
+ | `onUnexpectedRemoval` | `"info" \| "warning" \| "error"` | `"warning"` | リネームの根拠なくルートが消えたときの重要度 |
69
+
70
+ ## ルールと保証
71
+
72
+ - `isPublished` を満たすエントリだけを対象にします。非公開ノートはロックにもリダイレクトにも入りません。
73
+ - 既存の `manifest.redirects` のキーは上書きしません。Permalink の `redirect_from` が常に優先されます。
74
+ - 恒久的なリダイレクトのチェーンは推移的に集約します(`A → B` と `B → C` は `A → C` になる)。
75
+ - ロックは決定的です。ルートキーとリダイレクトをソートし、タイムスタンプや乱数を使いません。
76
+ - リダイレクトは毎ビルドで再適用されるため、CLI ビルドと SSG ビルドが同じリダイレクトを再現します。
77
+
78
+ ## エクスポート
79
+
80
+ 関数:
81
+
82
+ - `renamePlugin(options?)` / `rename(options?)`
83
+ - `diffRoutes(previous, current, options?)`
84
+ - `buildRouteLock(entries, isPublished)`
85
+ - `collapseRedirects(rules)`
86
+ - `applyRouteRedirects(manifest, rules)`
87
+ - `parseRouteLock(value)`、`emptyRouteLock()`、`hashContent(html)`
88
+
89
+ 型:
90
+
91
+ - `RenameOptions`
92
+ - `RouteLock`、`RouteLockRoute`、`RouteLockRedirect`、`RedirectRule`
93
+ - `DiffRoutesOptions`、`DiffRoutesResult`、`RenameDiagnostic`
94
+
95
+ ## 制限事項
96
+
97
+ - git によるリネーム検出は実装していません。ファイルシステムやリポジトリへのアクセスが必要であり、プラグインコードは意図的にそれを避けています。リネーム検出は frontmatter `id` と内容ハッシュの完全一致のみに依存します。
98
+ - `id` がなく、本文 HTML も変化したリネームは検出できず、予期しない消失として報告されます。
99
+
100
+ ## 関連
101
+
102
+ - [Permalink プラグイン](../permalink/README_ja.md) — 安定した URL と `redirect_from`
103
+ - [プラグインガイド](../../../docs/ja/plugin-system.md)
@@ -0,0 +1,19 @@
1
+ import { type RiebeckitePlugin } from "@riebeckite/core";
2
+ import { type RedirectStatus } from "./src/lock.js";
3
+ export type { DiffRoutesOptions, DiffRoutesResult, ManifestRedirect, RedirectRule, RedirectSink, RedirectStatus, RenameDiagnostic, RouteLock, RouteLockRedirect, RouteLockRoute, RouteLockSourceEntry, } from "./src/lock.js";
4
+ export { applyRouteRedirects, buildRouteLock, collapseRedirects, diffRoutes, emptyRouteLock, hashContent, isRedirectStatus, parseRouteLock, } from "./src/lock.js";
5
+ export type RenameOptions = {
6
+ /** Enables rename detection and redirect emission. Defaults to `true`. */
7
+ enabled?: boolean;
8
+ /** HTTP status for newly discovered rename redirects. Defaults to `308`. */
9
+ status?: RedirectStatus;
10
+ /** Severity for routes that disappear without rename evidence. Defaults to `"warning"`. */
11
+ onUnexpectedRemoval?: "info" | "warning" | "error";
12
+ };
13
+ /**
14
+ * Reduces broken URLs after note renames by reusing the existing redirect
15
+ * machinery (`manifest.redirects`). The only cross-build state is a JSON route
16
+ * lock persisted through `context.cache`; no files are written directly.
17
+ */
18
+ export declare function renamePlugin(options?: RenameOptions): RiebeckitePlugin<RenameOptions>;
19
+ export declare const rename: typeof renamePlugin;
package/dist/index.js ADDED
@@ -0,0 +1,305 @@
1
+ // index.ts
2
+ import {
3
+ definePlugin,
4
+ isPublished
5
+ } from "@riebeckite/core";
6
+
7
+ // src/lock.ts
8
+ import { createHash } from "node:crypto";
9
+ var LOCK_VERSION = 1;
10
+ function hashContent(html) {
11
+ return createHash("sha256").update(html, "utf8").digest("hex");
12
+ }
13
+ function emptyRouteLock() {
14
+ return { version: LOCK_VERSION, routes: {}, redirects: [] };
15
+ }
16
+ function isRedirectStatus(value) {
17
+ return value === 301 || value === 302 || value === 307 || value === 308;
18
+ }
19
+ function buildRouteLock(entries, isPublished2) {
20
+ const routes = {};
21
+ for (const entry of entries) {
22
+ if (!isPublished2(entry.frontmatter)) continue;
23
+ const id = readId(entry.frontmatter);
24
+ routes[entry.slug] = id ? { permalink: entry.permalink, contentHash: hashContent(entry.html), id } : { permalink: entry.permalink, contentHash: hashContent(entry.html) };
25
+ }
26
+ return { version: LOCK_VERSION, routes: sortRoutes(routes), redirects: [] };
27
+ }
28
+ function parseRouteLock(value) {
29
+ if (!isRecord(value) || value.version !== LOCK_VERSION) return void 0;
30
+ if (!isRecord(value.routes)) return void 0;
31
+ if (!Array.isArray(value.redirects)) return void 0;
32
+ const routes = {};
33
+ for (const [slug, raw] of Object.entries(value.routes)) {
34
+ if (slug.length === 0 || !isRecord(raw)) return void 0;
35
+ const { permalink, contentHash } = raw;
36
+ if (typeof permalink !== "string" || typeof contentHash !== "string")
37
+ return void 0;
38
+ let id;
39
+ if (raw.id !== void 0) {
40
+ if (typeof raw.id !== "string") return void 0;
41
+ id = raw.id;
42
+ }
43
+ routes[slug] = id === void 0 ? { permalink, contentHash } : { permalink, contentHash, id };
44
+ }
45
+ const redirects = [];
46
+ for (const raw of value.redirects) {
47
+ if (!isRecord(raw)) return void 0;
48
+ const { from, to, status, reason } = raw;
49
+ if (typeof from !== "string" || typeof to !== "string") return void 0;
50
+ if (!isRedirectStatus(status)) return void 0;
51
+ if (reason !== "rename" && reason !== "id") return void 0;
52
+ redirects.push({ from, to, status, reason });
53
+ }
54
+ return {
55
+ version: LOCK_VERSION,
56
+ routes: sortRoutes(routes),
57
+ redirects: collapseRedirects(redirects)
58
+ };
59
+ }
60
+ function diffRoutes(previous, current, options = {}) {
61
+ const status = options.status ?? 308;
62
+ const removalSeverity = options.onUnexpectedRemoval ?? "warning";
63
+ const prev = parseRouteLock(previous) ?? emptyRouteLock();
64
+ const curr = parseRouteLock(current) ?? emptyRouteLock();
65
+ const added = [];
66
+ const diagnostics = [];
67
+ const candidates = [];
68
+ for (const slug of sortedKeys(curr.routes)) {
69
+ const route = curr.routes[slug];
70
+ if (!route) continue;
71
+ const before = prev.routes[slug];
72
+ if (before && before.permalink === route.permalink) continue;
73
+ candidates.push({ slug, route });
74
+ }
75
+ const used = /* @__PURE__ */ new Set();
76
+ for (const slug of sortedKeys(prev.routes)) {
77
+ const before = prev.routes[slug];
78
+ if (!before) continue;
79
+ const after = curr.routes[slug];
80
+ if (after && after.permalink === before.permalink) continue;
81
+ const idMatches = before.id === void 0 ? [] : candidates.filter(
82
+ (candidate) => !used.has(candidate.slug) && candidate.route.id === before.id
83
+ );
84
+ let matchedBy;
85
+ let match;
86
+ let ambiguous = 0;
87
+ if (idMatches.length === 1) {
88
+ match = idMatches[0];
89
+ matchedBy = "id";
90
+ } else if (idMatches.length > 1) {
91
+ ambiguous = idMatches.length;
92
+ } else {
93
+ const hashMatches = candidates.filter(
94
+ (candidate) => !used.has(candidate.slug) && candidate.route.contentHash === before.contentHash
95
+ );
96
+ if (hashMatches.length === 1) {
97
+ match = hashMatches[0];
98
+ matchedBy = "rename";
99
+ } else if (hashMatches.length > 1) {
100
+ ambiguous = hashMatches.length;
101
+ }
102
+ }
103
+ if (match && matchedBy) {
104
+ used.add(match.slug);
105
+ if (match.route.permalink !== before.permalink) {
106
+ added.push({
107
+ from: before.permalink,
108
+ to: match.route.permalink,
109
+ status,
110
+ reason: matchedBy
111
+ });
112
+ }
113
+ continue;
114
+ }
115
+ if (ambiguous > 0) {
116
+ diagnostics.push({
117
+ code: "rename-ambiguous",
118
+ severity: "warning",
119
+ message: `Cannot resolve the previous route "${before.permalink}" (slug "${slug}"): ${ambiguous} candidates share the same ${before.id === void 0 ? "content hash" : "id"}.`,
120
+ slug,
121
+ suggestion: 'Add a stable frontmatter "id" so the note can be identified after a rename.'
122
+ });
123
+ continue;
124
+ }
125
+ diagnostics.push({
126
+ code: "rename-removed",
127
+ severity: removalSeverity,
128
+ message: `Route "${before.permalink}" (slug "${slug}") disappeared without rename evidence and was dropped from the route lock.`,
129
+ slug
130
+ });
131
+ }
132
+ const lock = {
133
+ version: LOCK_VERSION,
134
+ routes: sortRoutes({ ...curr.routes }),
135
+ redirects: collapseRedirects([
136
+ ...prev.redirects,
137
+ ...curr.redirects,
138
+ ...added
139
+ ])
140
+ };
141
+ return { lock, added, diagnostics };
142
+ }
143
+ function collapseRedirects(rules) {
144
+ const byFrom = /* @__PURE__ */ new Map();
145
+ for (const rule of rules) {
146
+ if (!rule) continue;
147
+ if (rule.from === rule.to) continue;
148
+ byFrom.set(rule.from, { ...rule });
149
+ }
150
+ const collapsed = [];
151
+ for (const from of [...byFrom.keys()].sort()) {
152
+ const first = byFrom.get(from);
153
+ if (!first) continue;
154
+ const visited = /* @__PURE__ */ new Set([from]);
155
+ let to = first.to;
156
+ while (!visited.has(to)) {
157
+ const next = byFrom.get(to);
158
+ if (!next) break;
159
+ visited.add(to);
160
+ to = next.to;
161
+ }
162
+ if (to === from) continue;
163
+ collapsed.push({
164
+ from,
165
+ to,
166
+ status: first.status,
167
+ reason: first.reason
168
+ });
169
+ }
170
+ return collapsed;
171
+ }
172
+ function applyRouteRedirects(manifest, rules) {
173
+ const applied = [];
174
+ for (const rule of rules) {
175
+ if (manifest.redirects.has(rule.from)) continue;
176
+ if (manifest.byPermalink.has(rule.from)) continue;
177
+ const target = manifest.byPermalink.get(rule.to);
178
+ if (!target) continue;
179
+ manifest.redirects.set(rule.from, {
180
+ path: rule.to,
181
+ status: rule.status,
182
+ slug: target.slug
183
+ });
184
+ applied.push(rule);
185
+ }
186
+ return applied;
187
+ }
188
+ function readId(frontmatter) {
189
+ const value = frontmatter.id;
190
+ if (typeof value !== "string") return void 0;
191
+ const id = value.trim();
192
+ return id.length > 0 ? id : void 0;
193
+ }
194
+ function sortRoutes(routes) {
195
+ const sorted = {};
196
+ for (const slug of sortedKeys(routes)) {
197
+ const route = routes[slug];
198
+ if (route) sorted[slug] = route;
199
+ }
200
+ return sorted;
201
+ }
202
+ function sortedKeys(routes) {
203
+ return Object.keys(routes).sort();
204
+ }
205
+ function isRecord(value) {
206
+ return typeof value === "object" && value !== null && !Array.isArray(value);
207
+ }
208
+
209
+ // index.ts
210
+ var PLUGIN_NAME = "rename";
211
+ var LOCK_KEY = "routes.lock";
212
+ var CACHE_VERSION = "1";
213
+ var LOCK_MESSAGE = "Rename plugin: route lock could not be used; starting from an empty lock.";
214
+ function renamePlugin(options = {}) {
215
+ const enabled = options.enabled ?? true;
216
+ const status = options.status ?? 308;
217
+ const onUnexpectedRemoval = options.onUnexpectedRemoval ?? "warning";
218
+ if (![301, 302, 307, 308].includes(status)) {
219
+ throw new Error(`Rename plugin: invalid redirect status ${status}.`);
220
+ }
221
+ if (!["info", "warning", "error"].includes(onUnexpectedRemoval)) {
222
+ throw new Error(
223
+ `Rename plugin: invalid onUnexpectedRemoval severity "${onUnexpectedRemoval}".`
224
+ );
225
+ }
226
+ return definePlugin({
227
+ name: PLUGIN_NAME,
228
+ options,
229
+ cacheVersion: CACHE_VERSION,
230
+ enabled,
231
+ onManifestCreated: async ({
232
+ manifest,
233
+ config,
234
+ cache,
235
+ diagnostics,
236
+ logger
237
+ }) => {
238
+ if (!enabled) return;
239
+ if (!config) {
240
+ logger.warn(
241
+ "Rename plugin: no resolved config is available; skipping rename detection."
242
+ );
243
+ return;
244
+ }
245
+ const previous = await readLock(cache, logger);
246
+ const current = buildRouteLock(
247
+ manifest.entries,
248
+ (frontmatter) => isPublished(config, frontmatter)
249
+ );
250
+ const result = diffRoutes(previous, current, {
251
+ status,
252
+ onUnexpectedRemoval
253
+ });
254
+ for (const diagnostic of result.diagnostics) {
255
+ diagnostics.push(renameDiagnostic(diagnostic));
256
+ }
257
+ applyRouteRedirects(manifest, result.lock.redirects);
258
+ await writeLock(cache, result.lock, logger);
259
+ }
260
+ });
261
+ }
262
+ var rename = renamePlugin;
263
+ async function readLock(cache, logger) {
264
+ try {
265
+ const raw = await cache.get(LOCK_KEY);
266
+ if (raw === void 0) return emptyRouteLock();
267
+ const parsed = parseRouteLock(raw);
268
+ if (!parsed) {
269
+ logger.warn(LOCK_MESSAGE, { key: LOCK_KEY });
270
+ return emptyRouteLock();
271
+ }
272
+ return parsed;
273
+ } catch (error) {
274
+ logger.warn(LOCK_MESSAGE, { key: LOCK_KEY, error: messageOf(error) });
275
+ return emptyRouteLock();
276
+ }
277
+ }
278
+ async function writeLock(cache, lock, logger) {
279
+ try {
280
+ await cache.set(LOCK_KEY, lock);
281
+ } catch (error) {
282
+ logger.warn("Rename plugin: route lock could not be persisted.", {
283
+ key: LOCK_KEY,
284
+ error: messageOf(error)
285
+ });
286
+ }
287
+ }
288
+ function renameDiagnostic(diagnostic) {
289
+ return { pluginName: PLUGIN_NAME, ...diagnostic };
290
+ }
291
+ function messageOf(error) {
292
+ return error instanceof Error ? error.message : String(error);
293
+ }
294
+ export {
295
+ applyRouteRedirects,
296
+ buildRouteLock,
297
+ collapseRedirects,
298
+ diffRoutes,
299
+ emptyRouteLock,
300
+ hashContent,
301
+ isRedirectStatus,
302
+ parseRouteLock,
303
+ rename,
304
+ renamePlugin
305
+ };
@@ -0,0 +1,93 @@
1
+ export type RedirectStatus = 301 | 302 | 307 | 308;
2
+ export type RouteLockRoute = {
3
+ permalink: string;
4
+ contentHash: string;
5
+ id?: string;
6
+ };
7
+ export type RouteLockRedirect = {
8
+ from: string;
9
+ to: string;
10
+ status: RedirectStatus;
11
+ reason: "rename" | "id";
12
+ };
13
+ export type RouteLock = {
14
+ version: 1;
15
+ routes: Record<string, RouteLockRoute>;
16
+ redirects: RouteLockRedirect[];
17
+ };
18
+ export type RedirectRule = RouteLock["redirects"][number];
19
+ export type RenameDiagnostic = {
20
+ code: string;
21
+ severity: "info" | "warning" | "error";
22
+ message: string;
23
+ slug?: string;
24
+ suggestion?: string;
25
+ };
26
+ export type DiffRoutesResult = {
27
+ lock: RouteLock;
28
+ added: RedirectRule[];
29
+ diagnostics: RenameDiagnostic[];
30
+ };
31
+ export type DiffRoutesOptions = {
32
+ status?: RedirectStatus;
33
+ onUnexpectedRemoval?: "info" | "warning" | "error";
34
+ };
35
+ /**
36
+ * Minimal shape `buildRouteLock` reads from a content manifest entry. Only
37
+ * published entries should reach this function; the caller supplies the
38
+ * publish predicate so this module stays free of any runtime Core import.
39
+ */
40
+ export type RouteLockSourceEntry = {
41
+ slug: string;
42
+ permalink: string;
43
+ frontmatter: Record<string, unknown>;
44
+ html: string;
45
+ };
46
+ export declare function hashContent(html: string): string;
47
+ export declare function emptyRouteLock(): RouteLock;
48
+ export declare function isRedirectStatus(value: unknown): value is RedirectStatus;
49
+ /**
50
+ * Builds the current route lock from manifest entries. Entries are keyed by
51
+ * slug and only published entries are considered. Output is deterministic:
52
+ * route keys are sorted and redirects (always empty here) stay sorted.
53
+ */
54
+ export declare function buildRouteLock(entries: readonly RouteLockSourceEntry[], isPublished: (frontmatter: Record<string, unknown>) => boolean): RouteLock;
55
+ /**
56
+ * Parses a persisted lock. Returns `undefined` when the value is corrupt or
57
+ * uses an unknown format, so callers can fall back to an empty lock.
58
+ */
59
+ export declare function parseRouteLock(value: unknown): RouteLock | undefined;
60
+ /**
61
+ * Compares the previous lock with the current routes and returns the next lock
62
+ * plus any rename redirects discovered in this build.
63
+ *
64
+ * Detection precedence is strict and never fuzzy:
65
+ * 1. explicit identity (frontmatter `id`)
66
+ * 2. exact content hash (`sha256(html)`)
67
+ * 3. otherwise the route is treated as removed
68
+ */
69
+ export declare function diffRoutes(previous: RouteLock, current: RouteLock, options?: DiffRoutesOptions): DiffRoutesResult;
70
+ /**
71
+ * Merges redirect rules and collapses permanent chains: if `A -> B` is known
72
+ * and `B -> C` is added, the result keeps `A -> C` and `B -> C`. Output is
73
+ * sorted by `from` so the lock serializes deterministically.
74
+ */
75
+ export declare function collapseRedirects(rules: readonly RedirectRule[]): RedirectRule[];
76
+ export type ManifestRedirect = {
77
+ path: string;
78
+ status: RedirectStatus;
79
+ slug: string;
80
+ };
81
+ export type RedirectSink = {
82
+ redirects: Map<string, ManifestRedirect>;
83
+ byPermalink: ReadonlyMap<string, {
84
+ slug: string;
85
+ }>;
86
+ };
87
+ /**
88
+ * Adds rename redirects to `manifest.redirects` without ever overwriting an
89
+ * existing key (for example one declared through Permalink's `redirect_from`).
90
+ * Redirects whose source is a live permalink, or whose target is unknown, are
91
+ * skipped. Returns the rules that were actually applied.
92
+ */
93
+ export declare function applyRouteRedirects(manifest: RedirectSink, rules: readonly RedirectRule[]): RedirectRule[];
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@riebeckite/plugin-rename",
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
+ },
16
+ "dependencies": {
17
+ "@riebeckite/core": "0.0.1"
18
+ },
19
+ "devDependencies": {
20
+ "tsx": "^4.22.4"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "files": [
26
+ "LICENSE",
27
+ "README.md",
28
+ "README_ja.md",
29
+ "dist"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Rerurate514/riebeckite.git",
34
+ "directory": "packages/plugins/rename"
35
+ },
36
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
37
+ "bugs": {
38
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
39
+ },
40
+ "description": "Rename and move redirects for published Riebeckite notes.",
41
+ "keywords": [
42
+ "riebeckite",
43
+ "plugin",
44
+ "redirects",
45
+ "rename"
46
+ ],
47
+ "engines": {
48
+ "node": "^20.19.0 || >=22.12.0"
49
+ },
50
+ "sideEffects": false,
51
+ "scripts": {
52
+ "build": "node ../../../scripts/build_package.mjs",
53
+ "test": "node --import tsx --test \"test/*.test.ts\""
54
+ }
55
+ }