@riebeckite/plugin-query 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,122 @@
1
+ # @riebeckite/plugin-query
2
+
3
+ Turn `query` code blocks into lists or tables of content. Filtering, sorting,
4
+ and pagination run against frontmatter and tags at build time, so no client-side
5
+ JavaScript is required.
6
+
7
+ [日本語](./README_ja.md)
8
+
9
+ ## Overview
10
+
11
+ `queryPlugin()` recognises fenced blocks
12
+
13
+ ````md
14
+ ```query
15
+ filter:
16
+ tags:
17
+ any: [diary]
18
+ sort:
19
+ field: date
20
+ order: desc
21
+ limit: 5
22
+ ```
23
+ ````
24
+
25
+ and renders them using the content manifest (every note's frontmatter, tags, and
26
+ permalink).
27
+
28
+ ## Usage
29
+
30
+ ```ts
31
+ import { defineConfig } from "@riebeckite/core";
32
+ import { queryPlugin } from "@riebeckite/plugin-query";
33
+
34
+ export default defineConfig({
35
+ // ...
36
+ plugins: [queryPlugin()],
37
+ });
38
+ ```
39
+
40
+ ## Block syntax
41
+
42
+ The block body is a YAML mapping. Every field is optional.
43
+
44
+ | Field | Type | Description |
45
+ | ----- | ---- | ----------- |
46
+ | `filter` | object | Filtering conditions (below) |
47
+ | `sort` | object \| object[] | `field` (a frontmatter key, `title`, `slug`, or `permalink`) and `order` (`asc` / `desc`, default `asc`). The default field is `date` |
48
+ | `limit` | number | Maximum number of entries |
49
+ | `offset` | number | Entries to skip from the top |
50
+ | `format` | `"table"` \| `"list"` | Output format. Defaults to `table` |
51
+ | `columns` | string[] | Table columns: presets (`title`, `date`, `updated`, `created`, `published`, `tags`, `description`, `permalink`) or frontmatter keys |
52
+ | `excludeSelf` | boolean | Exclude the note hosting the block from its own results |
53
+ | `empty` | string | Message shown when nothing matches |
54
+
55
+ ### `filter`
56
+
57
+ | Field | Type | Description |
58
+ | ----- | ---- | ----------- |
59
+ | `tags.any` | string[] | Has at least one of these tags |
60
+ | `tags.all` | string[] | Has every one of these tags |
61
+ | `tags.none` | string[] | Has none of these tags |
62
+ | `folder` | string \| string[] | Slug prefix match |
63
+ | `frontmatter` | object | Frontmatter equality. An array matches any member; string comparisons are case-insensitive |
64
+ | `date` | object | `field` (default `date`) plus inclusive `from` / `to` bounds |
65
+
66
+ ```yaml
67
+ filter:
68
+ tags:
69
+ any: [diary, note]
70
+ none: [draft]
71
+ folder: articles
72
+ frontmatter:
73
+ draft: false
74
+ date:
75
+ field: published
76
+ from: 2024-01-01
77
+ to: 2024-12-31
78
+ sort:
79
+ - field: date
80
+ order: desc
81
+ - field: title
82
+ limit: 10
83
+ format: list
84
+ ```
85
+
86
+ ## Options
87
+
88
+ | Option | Type | Default | Description |
89
+ | ------ | ---- | ------- | ----------- |
90
+ | `className` | `string` | `"rr-query"` | Root CSS class |
91
+ | `language` | `string` | `"query"` | Fence language to target |
92
+ | `defaultFormat` | `"table"` \| `"list"` | `"table"` | Format when a block omits `format` |
93
+ | `defaultColumns` | `string[]` | `["title", "date"]` | Columns when a block omits `columns` |
94
+ | `defaultSort` | object | none | Sort when a block omits `sort` |
95
+ | `defaultLimit` | `number` | none | Row cap when a block omits `limit` |
96
+ | `emptyMessage` | `string` | `"No matching content."` | Empty-state message |
97
+ | `excludeSelf` | `boolean` | `false` | Exclude the host page by default |
98
+
99
+ ## Diagnostics
100
+
101
+ A block that is not valid YAML (or not a mapping) renders an inline error and
102
+ emits a `content-query-invalid` error diagnostic. Unknown fields emit a
103
+ `content-query-unknown-field` warning.
104
+
105
+ ## Limitations
106
+
107
+ - Links produced by a query are not added to the content graph (backlinks).
108
+ Only links written in the source Markdown participate.
109
+ - Results are fixed at build time. Rebuilding a host note when a queried note
110
+ changes is future work; a full build always recomputes correctly.
111
+
112
+ ## Exports
113
+
114
+ - `queryPlugin(options?)` — plugin factory
115
+ - `remarkQuery(options?)` — remark transform usable on its own (`options.language` selects the fence language)
116
+ - `queryContentEntries(entries, spec)` — the Core matching engine (also
117
+ available from `@riebeckite/core`)
118
+ - Types: `QueryOptions`, `QuerySpec`, `QueryOutputFormat`
119
+
120
+ ## See also
121
+
122
+ - [Plugin guide](../../../docs/en/plugin-system.md)
package/README_ja.md ADDED
@@ -0,0 +1,114 @@
1
+ # @riebeckite/plugin-query
2
+
3
+ `query` コードブロックを、コンテンツの一覧(表またはリスト)に変換するプラグインです。絞り込み・並べ替え・件数制限をフロントマターとタグに対して行い、ビルド時に HTML を生成します。クライアント側の JavaScript は不要です。
4
+
5
+ [English](./README.md)
6
+
7
+ ## できること
8
+
9
+ `queryPlugin()` は Markdown 中のフェンスコードブロック
10
+
11
+ ````md
12
+ ```query
13
+ filter:
14
+ tags:
15
+ any: [diary]
16
+ sort:
17
+ field: date
18
+ order: desc
19
+ limit: 5
20
+ ```
21
+ ````
22
+
23
+ を検出し、マニフェスト(全ノートのフロントマター・タグ・パーマリンク)を使って結果を描画します。
24
+
25
+ ## 設定
26
+
27
+ ```ts
28
+ import { defineConfig } from "@riebeckite/core";
29
+ import { queryPlugin } from "@riebeckite/plugin-query";
30
+
31
+ export default defineConfig({
32
+ // ...
33
+ plugins: [queryPlugin()],
34
+ });
35
+ ```
36
+
37
+ ## ブロックの書き方
38
+
39
+ ブロック本文は YAML のマッピングです。すべて省略できます。
40
+
41
+ | フィールド | 型 | 内容 |
42
+ | --- | --- | --- |
43
+ | `filter` | object | 絞り込み条件(下記) |
44
+ | `sort` | object \| object[] | 並べ替え。`field`(フロントマターキー、`title`、`slug`、`permalink`)と `order`(`asc` / `desc`、既定 `asc`)。既定のフィールドは `date` |
45
+ | `limit` | number | 最大件数 |
46
+ | `offset` | number | 先頭から読み飛ばす件数 |
47
+ | `format` | `"table"` \| `"list"` | 表示形式。既定は `table` |
48
+ | `columns` | string[] | 表の列。プリセット(`title`、`date`、`updated`、`created`、`published`、`tags`、`description`、`permalink`)またはフロントマターキー |
49
+ | `excludeSelf` | boolean | このブロックを含むノート自身を結果から除く |
50
+ | `empty` | string | 一致が無いときのメッセージ |
51
+
52
+ ### `filter`
53
+
54
+ | フィールド | 型 | 内容 |
55
+ | --- | --- | --- |
56
+ | `tags.any` | string[] | いずれかのタグを持つ |
57
+ | `tags.all` | string[] | すべてのタグを持つ |
58
+ | `tags.none` | string[] | どのタグも持たない |
59
+ | `folder` | string \| string[] | スラッグの前方一致 |
60
+ | `frontmatter` | object | フロントマターの一致。値が配列ならそのいずれかに一致。文字列比較は大文字小文字を区別しない |
61
+ | `date` | object | `field`(既定 `date`)と `from` / `to`(両端を含む) |
62
+
63
+ ```yaml
64
+ filter:
65
+ tags:
66
+ any: [diary, note]
67
+ none: [draft]
68
+ folder: articles
69
+ frontmatter:
70
+ draft: false
71
+ date:
72
+ field: published
73
+ from: 2024-01-01
74
+ to: 2024-12-31
75
+ sort:
76
+ - field: date
77
+ order: desc
78
+ - field: title
79
+ limit: 10
80
+ format: list
81
+ ```
82
+
83
+ ## オプション
84
+
85
+ | オプション | 型 | 既定値 | 内容 |
86
+ | --- | --- | --- | --- |
87
+ | `className` | `string` | `"rr-query"` | ルート要素の CSS クラス |
88
+ | `language` | `string` | `"query"` | 対象のフェンス言語 |
89
+ | `defaultFormat` | `"table"` \| `"list"` | `"table"` | ブロックが `format` を省略したときの形式 |
90
+ | `defaultColumns` | `string[]` | `["title", "date"]` | ブロックが `columns` を省略したときの列 |
91
+ | `defaultSort` | object | なし | ブロックが `sort` を省略したときの並べ替え |
92
+ | `defaultLimit` | `number` | なし | ブロックが `limit` を省略したときの上限 |
93
+ | `emptyMessage` | `string` | `"No matching content."` | 空結果のメッセージ |
94
+ | `excludeSelf` | `boolean` | `false` | 既定で自身を除外する |
95
+
96
+ ## 診断
97
+
98
+ 不正な YAML やマッピングでないブロックは、その場にエラー表示を出しつつ、`content-query-invalid` のエラー診断を生成します。未知のフィールドは `content-query-unknown-field` の警告になります。
99
+
100
+ ## 制限事項
101
+
102
+ - クエリ結果として生成したリンクは、コンテンツグラフ(バックリンク)には含まれません。元の Markdown に書かれたリンクだけが対象です。
103
+ - 結果はビルド時に確定します。クエリ対象ノートの変更でホストノートを再生成する増分最適化は今後の課題です(フルビルドでは正しく再計算されます)。
104
+
105
+ ## エクスポート
106
+
107
+ - `queryPlugin(options?)` — プラグインファクトリ
108
+ - `remarkQuery(options?)` — Remark 変換だけを利用する場合の API(`options.language` でフェンス言語を指定)
109
+ - `queryContentEntries(entries, spec)` — Core の照合エンジン(`@riebeckite/core` からも利用可能)
110
+ - 型: `QueryOptions`、`QuerySpec`、`QueryOutputFormat`
111
+
112
+ ## 関連資料
113
+
114
+ - [プラグインシステム](../../../docs/ja/plugin-system.md)
@@ -0,0 +1,5 @@
1
+ import type { QueryOptions } from "./src/types.js";
2
+ export { remarkQuery } from "./src/remark.js";
3
+ export { queryContentEntries } from "@riebeckite/core";
4
+ export type { QueryOptions, QueryOutputFormat, QuerySpec, } from "./src/types.js";
5
+ export declare function queryPlugin(options?: QueryOptions): import("@riebeckite/core").RiebeckitePlugin<QueryOptions>;
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ // index.ts
2
+ import {
3
+ createStyleAsset,
4
+ definePlugin
5
+ } from "@riebeckite/core";
6
+
7
+ // src/remark.ts
8
+ import { visit } from "unist-util-visit";
9
+
10
+ // src/placeholder.ts
11
+ var QUERY_ATTRIBUTE = "data-rr-query";
12
+ function encodeQuerySpec(source) {
13
+ return encodeURIComponent(source);
14
+ }
15
+ function decodeQuerySpec(encoded) {
16
+ return decodeURIComponent(encoded);
17
+ }
18
+ function createQueryPlaceholder(source) {
19
+ return `<div ${QUERY_ATTRIBUTE}="${encodeQuerySpec(source)}"></div>`;
20
+ }
21
+ function createQueryPlaceholderPattern() {
22
+ return new RegExp(
23
+ `<div\\b[^>]*\\b${QUERY_ATTRIBUTE}="([^"]*)"[^>]*>\\s*</div>`,
24
+ "g"
25
+ );
26
+ }
27
+
28
+ // src/remark.ts
29
+ function remarkQuery(options = {}) {
30
+ const language = options.language ?? "query";
31
+ return (tree) => {
32
+ visit(tree, "code", (node, index, parent) => {
33
+ if (node.lang !== language) return;
34
+ if (!parent || index === void 0) return;
35
+ const html = {
36
+ type: "html",
37
+ value: createQueryPlaceholder(node.value)
38
+ };
39
+ parent.children.splice(index, 1, html);
40
+ });
41
+ };
42
+ }
43
+
44
+ // src/runtime.ts
45
+ import { queryContentEntries } from "@riebeckite/core";
46
+ import { matter } from "vfile-matter";
47
+
48
+ // src/render.ts
49
+ import {
50
+ escapeHtml,
51
+ escapeHtmlAttribute
52
+ } from "@riebeckite/core";
53
+ var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
54
+ var COLUMN_LABELS = {
55
+ title: "Title",
56
+ date: "Date",
57
+ updated: "Updated",
58
+ created: "Created",
59
+ published: "Published",
60
+ tags: "Tags",
61
+ description: "Description",
62
+ permalink: "Permalink"
63
+ };
64
+ function resolveQuery(spec, options) {
65
+ return {
66
+ format: spec.format ?? options.defaultFormat ?? "table",
67
+ columns: spec.columns ?? options.defaultColumns ?? ["title", "date"],
68
+ empty: spec.empty ?? options.emptyMessage ?? "No matching content.",
69
+ className: options.className ?? "rr-query"
70
+ };
71
+ }
72
+ function renderQueryResult(entries, query) {
73
+ if (entries.length === 0) {
74
+ return `<p class="${escapeHtmlAttribute(query.className)} ${escapeHtmlAttribute(query.className)}--empty">${escapeHtml(query.empty)}</p>`;
75
+ }
76
+ return query.format === "list" ? renderList(entries, query) : renderTable(entries, query);
77
+ }
78
+ function renderQueryError(message, options) {
79
+ const className = options.className ?? "rr-query";
80
+ return `<div class="${escapeHtmlAttribute(className)} ${escapeHtmlAttribute(className)}--error" role="status">${escapeHtml(message)}</div>`;
81
+ }
82
+ function renderTable(entries, query) {
83
+ const { className, columns } = query;
84
+ const head = columns.map(
85
+ (field) => `<th class="${escapeHtmlAttribute(className)}__heading" scope="col">${escapeHtml(columnLabel(field))}</th>`
86
+ ).join("");
87
+ const rows = entries.map((entry) => {
88
+ const cells = columns.map((field) => {
89
+ const modifier = escapeHtmlAttribute(`rr-query__cell--${slugify(field)}`);
90
+ return `<td class="${escapeHtmlAttribute(className)}__cell ${modifier}">${renderCell(entry, field, className)}</td>`;
91
+ }).join("");
92
+ return `<tr class="${escapeHtmlAttribute(className)}__row">${cells}</tr>`;
93
+ }).join("");
94
+ return [
95
+ `<div class="${escapeHtmlAttribute(className)}" data-rr-query-result>`,
96
+ `<table class="${escapeHtmlAttribute(className)}__table">`,
97
+ `<thead><tr>${head}</tr></thead>`,
98
+ `<tbody>${rows}</tbody>`,
99
+ "</table>",
100
+ "</div>"
101
+ ].join("");
102
+ }
103
+ function renderList(entries, query) {
104
+ const { className, columns } = query;
105
+ const metaColumns = columns.filter((field) => field !== "title");
106
+ const items = entries.map((entry) => {
107
+ const meta = metaColumns.map((field) => {
108
+ const value = renderCell(entry, field, className);
109
+ if (!value) return "";
110
+ return `<span class="${escapeHtmlAttribute(className)}__meta ${escapeHtmlAttribute(`rr-query__meta--${slugify(field)}`)}">${value}</span>`;
111
+ }).join(" ");
112
+ return `<li class="${escapeHtmlAttribute(className)}__item">${renderTitleLink(entry, className)}${meta ? ` ${meta}` : ""}</li>`;
113
+ }).join("");
114
+ return [
115
+ `<div class="${escapeHtmlAttribute(className)}" data-rr-query-result>`,
116
+ `<ul class="${escapeHtmlAttribute(className)}__list">${items}</ul>`,
117
+ "</div>"
118
+ ].join("");
119
+ }
120
+ function renderCell(entry, field, className) {
121
+ switch (field) {
122
+ case "title":
123
+ return renderTitleLink(entry, className);
124
+ case "tags":
125
+ return renderTags(entry.tags, className);
126
+ case "permalink":
127
+ case "url":
128
+ return `<a class="${escapeHtmlAttribute(className)}__link" href="${escapeHtmlAttribute(entry.permalink)}">${escapeHtml(entry.permalink)}</a>`;
129
+ default:
130
+ return escapeHtml(formatValue(readFrontmatterField(entry, field)));
131
+ }
132
+ }
133
+ function renderTitleLink(entry, className) {
134
+ return `<a class="${escapeHtmlAttribute(className)}__link" href="${escapeHtmlAttribute(entry.permalink)}">${escapeHtml(entry.title)}</a>`;
135
+ }
136
+ function renderTags(tags, className) {
137
+ return tags.map(
138
+ (tag) => `<span class="${escapeHtmlAttribute(className)}__tag">#${escapeHtml(tag)}</span>`
139
+ ).join(" ");
140
+ }
141
+ function readFrontmatterField(entry, field) {
142
+ if (field === "date") {
143
+ return entry.frontmatter.date ?? entry.frontmatter.created ?? entry.frontmatter.published ?? entry.frontmatter.updated;
144
+ }
145
+ return entry.frontmatter[field];
146
+ }
147
+ function columnLabel(field) {
148
+ return COLUMN_LABELS[field] ?? field;
149
+ }
150
+ function formatValue(value) {
151
+ if (value === void 0 || value === null) return "";
152
+ if (value instanceof Date) return formatDate(value);
153
+ if (Array.isArray(value)) return value.map((item) => formatValue(item)).join(", ");
154
+ if (typeof value === "string") {
155
+ return DATE_ONLY.test(value.trim()) ? value.trim() : value;
156
+ }
157
+ return String(value);
158
+ }
159
+ function formatDate(value) {
160
+ const time = value.getTime();
161
+ if (!Number.isFinite(time)) return "";
162
+ return value.toISOString().slice(0, 10);
163
+ }
164
+ function slugify(value) {
165
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
166
+ }
167
+
168
+ // src/runtime.ts
169
+ var KNOWN_KEYS = /* @__PURE__ */ new Set([
170
+ "filter",
171
+ "sort",
172
+ "limit",
173
+ "offset",
174
+ "format",
175
+ "columns",
176
+ "excludeSelf",
177
+ "empty"
178
+ ]);
179
+ function createQueryRuntime(options) {
180
+ const tracked = /* @__PURE__ */ new Map();
181
+ return {
182
+ track(slug, content) {
183
+ tracked.set(slug, content);
184
+ },
185
+ resolve(manifest, diagnostics) {
186
+ const entries = manifest.entries;
187
+ for (const entry of entries) {
188
+ if (!entry.html.includes(QUERY_ATTRIBUTE)) continue;
189
+ const html = replacePlaceholders(entry, entries, options, diagnostics);
190
+ if (html === entry.html) continue;
191
+ entry.html = html;
192
+ const content = tracked.get(entry.slug);
193
+ if (content) content.html = html;
194
+ }
195
+ }
196
+ };
197
+ }
198
+ function replacePlaceholders(entry, entries, options, diagnostics) {
199
+ const pattern = createQueryPlaceholderPattern();
200
+ return entry.html.replace(pattern, (_match, encoded) => {
201
+ const parsed = parseBlock(entry, encoded, options, diagnostics);
202
+ if (typeof parsed === "string") return parsed;
203
+ const query = resolveQuery(parsed, options);
204
+ const excludeSelf = parsed.excludeSelf ?? options.excludeSelf ?? false;
205
+ const pool = excludeSelf ? entries.filter((candidate) => candidate.slug !== entry.slug) : entries;
206
+ const selected = queryContentEntries(pool, parsed);
207
+ return renderQueryResult(selected, query);
208
+ });
209
+ }
210
+ function parseBlock(entry, encoded, options, diagnostics) {
211
+ let source;
212
+ try {
213
+ source = decodeQuerySpec(encoded);
214
+ } catch (error) {
215
+ return reportInvalid(
216
+ entry,
217
+ diagnostics,
218
+ `could not be decoded (${formatError(error)})`,
219
+ options
220
+ );
221
+ }
222
+ let parsed;
223
+ try {
224
+ parsed = parseYamlMapping(source);
225
+ } catch (error) {
226
+ return reportInvalid(
227
+ entry,
228
+ diagnostics,
229
+ `is not valid YAML (${formatError(error)})`,
230
+ options
231
+ );
232
+ }
233
+ if (parsed === null || parsed === void 0) return {};
234
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
235
+ return reportInvalid(entry, diagnostics, "must be a YAML mapping", options);
236
+ }
237
+ const spec = parsed;
238
+ for (const key of Object.keys(spec)) {
239
+ if (KNOWN_KEYS.has(key)) continue;
240
+ diagnostics.push({
241
+ code: "content-query-unknown-field",
242
+ severity: "warning",
243
+ pluginName: "query",
244
+ slug: entry.slug,
245
+ message: `Unknown query field \`${key}\` was ignored.`
246
+ });
247
+ }
248
+ return spec;
249
+ }
250
+ function reportInvalid(entry, diagnostics, reason, options) {
251
+ const message = `Query block in \`${entry.slug}\` ${reason}.`;
252
+ diagnostics.push({
253
+ code: "content-query-invalid",
254
+ severity: "error",
255
+ pluginName: "query",
256
+ slug: entry.slug,
257
+ message
258
+ });
259
+ return renderQueryError(message, options);
260
+ }
261
+ function parseYamlMapping(source) {
262
+ const document = `---
263
+ ${source}
264
+ ---
265
+ `;
266
+ const file = {
267
+ value: document,
268
+ data: {},
269
+ toString: () => document
270
+ };
271
+ matter(file);
272
+ return file.data.matter;
273
+ }
274
+ function formatError(error) {
275
+ return error instanceof Error ? error.message : String(error);
276
+ }
277
+
278
+ // index.ts
279
+ import { queryContentEntries as queryContentEntries2 } from "@riebeckite/core";
280
+ function queryPlugin(options = {}) {
281
+ const language = options.language ?? "query";
282
+ const runtime = createQueryRuntime(options);
283
+ return definePlugin({
284
+ name: "query",
285
+ options,
286
+ provides: ["content.query"],
287
+ validateOptions: validateQueryOptions,
288
+ extendMarkdownPipeline: (pipeline) => {
289
+ pipeline.use(remarkQuery, { language });
290
+ },
291
+ onPostProcessed: (context) => {
292
+ runtime.track(context.slug, context.content);
293
+ },
294
+ onManifestCreated: (context) => {
295
+ runtime.resolve(context.manifest, context.diagnostics);
296
+ },
297
+ assets: [createStyleAsset("query")]
298
+ });
299
+ }
300
+ function validateQueryOptions(options) {
301
+ if (!options) return [];
302
+ const issues = [];
303
+ if (options.className !== void 0 && (typeof options.className !== "string" || options.className.trim() === "")) {
304
+ issues.push({ path: "className", message: "Expected a non-empty string." });
305
+ }
306
+ if (options.language !== void 0 && (typeof options.language !== "string" || options.language.trim() === "")) {
307
+ issues.push({ path: "language", message: "Expected a non-empty string." });
308
+ }
309
+ if (!isFormat(options.defaultFormat)) {
310
+ issues.push({
311
+ path: "defaultFormat",
312
+ message: 'Expected "table" or "list".'
313
+ });
314
+ }
315
+ if (!isColumnList(options.defaultColumns)) {
316
+ issues.push({
317
+ path: "defaultColumns",
318
+ message: "Expected an array of column strings."
319
+ });
320
+ }
321
+ if (options.defaultLimit !== void 0 && (!Number.isFinite(options.defaultLimit) || options.defaultLimit < 0)) {
322
+ issues.push({
323
+ path: "defaultLimit",
324
+ message: "Expected a non-negative finite number."
325
+ });
326
+ }
327
+ if (options.emptyMessage !== void 0 && typeof options.emptyMessage !== "string") {
328
+ issues.push({ path: "emptyMessage", message: "Expected a string." });
329
+ }
330
+ if (options.excludeSelf !== void 0 && typeof options.excludeSelf !== "boolean") {
331
+ issues.push({ path: "excludeSelf", message: "Expected a boolean." });
332
+ }
333
+ return issues;
334
+ }
335
+ function isFormat(value) {
336
+ return value === void 0 || value === "table" || value === "list";
337
+ }
338
+ function isColumnList(value) {
339
+ return value === void 0 || Array.isArray(value) && value.every((item) => typeof item === "string");
340
+ }
341
+ export {
342
+ queryContentEntries2 as queryContentEntries,
343
+ queryPlugin,
344
+ remarkQuery
345
+ };
@@ -0,0 +1,5 @@
1
+ export declare const QUERY_ATTRIBUTE = "data-rr-query";
2
+ export declare function encodeQuerySpec(source: string): string;
3
+ export declare function decodeQuerySpec(encoded: string): string;
4
+ export declare function createQueryPlaceholder(source: string): string;
5
+ export declare function createQueryPlaceholderPattern(): RegExp;
@@ -0,0 +1,5 @@
1
+ import type { Root } from "mdast";
2
+ export type RemarkQueryOptions = {
3
+ language?: string;
4
+ };
5
+ export declare function remarkQuery(options?: RemarkQueryOptions): (tree: Root) => void;
@@ -0,0 +1,11 @@
1
+ import { type ContentManifestEntry } from "@riebeckite/core";
2
+ import type { QueryOptions, QuerySpec } from "./types.js";
3
+ export type ResolvedQuery = {
4
+ format: "table" | "list";
5
+ columns: readonly string[];
6
+ empty: string;
7
+ className: string;
8
+ };
9
+ export declare function resolveQuery(spec: QuerySpec, options: QueryOptions): ResolvedQuery;
10
+ export declare function renderQueryResult(entries: readonly ContentManifestEntry[], query: ResolvedQuery): string;
11
+ export declare function renderQueryError(message: string, options: QueryOptions): string;
@@ -0,0 +1,7 @@
1
+ import type { ContentManifest, Diagnostic, PostContent } from "@riebeckite/core";
2
+ import type { QueryOptions } from "./types.js";
3
+ export type QueryRuntime = {
4
+ track(slug: string, content: PostContent): void;
5
+ resolve(manifest: ContentManifest, diagnostics: Diagnostic[]): void;
6
+ };
7
+ export declare function createQueryRuntime(options: QueryOptions): QueryRuntime;
@@ -0,0 +1,18 @@
1
+ import type { ContentQuerySort, ContentQuerySpec } from "@riebeckite/core";
2
+ export type QueryOutputFormat = "table" | "list";
3
+ export type QuerySpec = ContentQuerySpec & {
4
+ format?: QueryOutputFormat;
5
+ columns?: readonly string[];
6
+ excludeSelf?: boolean;
7
+ empty?: string;
8
+ };
9
+ export type QueryOptions = {
10
+ className?: string;
11
+ language?: string;
12
+ defaultFormat?: QueryOutputFormat;
13
+ defaultColumns?: readonly string[];
14
+ defaultSort?: ContentQuerySort;
15
+ defaultLimit?: number;
16
+ emptyMessage?: string;
17
+ excludeSelf?: boolean;
18
+ };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@riebeckite/plugin-query",
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
+ "@types/mdast": "^4.0.4",
19
+ "unist-util-visit": "^5.1.0",
20
+ "vfile-matter": "^5.0.1",
21
+ "@riebeckite/core": "0.0.1"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "LICENSE",
28
+ "README.md",
29
+ "README_ja.md",
30
+ "dist",
31
+ "style.css"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/Rerurate514/riebeckite.git",
36
+ "directory": "packages/plugins/query"
37
+ },
38
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
39
+ "bugs": {
40
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
41
+ },
42
+ "description": "Build-time content queries for Riebeckite code blocks.",
43
+ "keywords": [
44
+ "riebeckite",
45
+ "plugin",
46
+ "query",
47
+ "markdown"
48
+ ],
49
+ "engines": {
50
+ "node": "^20.19.0 || >=22.12.0"
51
+ },
52
+ "sideEffects": [
53
+ "./style.css"
54
+ ],
55
+ "scripts": {
56
+ "build": "node ../../../scripts/build_package.mjs"
57
+ }
58
+ }
package/style.css ADDED
@@ -0,0 +1,111 @@
1
+ .rr-query {
2
+ --rr-query-ink: var(--rb-color-ink, #000000);
3
+ --rr-query-paper: var(--rb-color-paper, #ffffff);
4
+ --rr-query-muted: var(--rb-color-muted, #69645c);
5
+ --rr-query-accent: var(--rb-color-accent, #686868);
6
+ --rr-query-rule: var(
7
+ --rb-color-border,
8
+ color-mix(in srgb, var(--rr-query-ink) 18%, transparent)
9
+ );
10
+ --rr-query-surface: color-mix(
11
+ in srgb,
12
+ var(--rr-query-paper) 94%,
13
+ var(--rr-query-ink)
14
+ );
15
+
16
+ margin: 1.5rem 0;
17
+ color: var(--rr-query-ink);
18
+ }
19
+
20
+ .rr-query__table {
21
+ width: 100%;
22
+ border-collapse: collapse;
23
+ font-size: 0.9375rem;
24
+ }
25
+
26
+ .rr-query__heading {
27
+ padding: 0.5rem 0.75rem;
28
+ border-bottom: 1px solid var(--rr-query-ink);
29
+ text-align: left;
30
+ font-weight: 700;
31
+ }
32
+
33
+ .rr-query__cell {
34
+ padding: 0.5rem 0.75rem;
35
+ vertical-align: top;
36
+ }
37
+
38
+ .rr-query__row:not(:last-child) .rr-query__cell {
39
+ border-bottom: 1px solid var(--rr-query-rule);
40
+ }
41
+
42
+ .rr-query__cell--date,
43
+ .rr-query__meta--date,
44
+ .rr-query__meta--created,
45
+ .rr-query__meta--updated,
46
+ .rr-query__meta--published {
47
+ color: var(--rr-query-muted);
48
+ white-space: nowrap;
49
+ }
50
+
51
+ .rr-query__link {
52
+ color: inherit;
53
+ text-decoration: underline;
54
+ text-decoration-color: var(--rr-query-rule);
55
+ text-underline-offset: 0.2em;
56
+ }
57
+
58
+ .rr-query__link:hover,
59
+ .rr-query__link:focus-visible {
60
+ text-decoration-color: var(--rr-query-accent);
61
+ }
62
+
63
+ .rr-query__tag {
64
+ color: var(--rr-query-muted);
65
+ font-size: 0.8125em;
66
+ white-space: nowrap;
67
+ }
68
+
69
+ .rr-query__list {
70
+ margin: 0;
71
+ padding: 0;
72
+ list-style: none;
73
+ }
74
+
75
+ .rr-query__item {
76
+ display: flex;
77
+ flex-wrap: wrap;
78
+ gap: 0.5rem;
79
+ align-items: baseline;
80
+ padding: 0.5rem 0;
81
+ border-bottom: 1px solid var(--rr-query-rule);
82
+ }
83
+
84
+ .rr-query__item:last-child {
85
+ border-bottom: 0;
86
+ }
87
+
88
+ .rr-query__meta {
89
+ color: var(--rr-query-muted);
90
+ font-size: 0.8125em;
91
+ }
92
+
93
+ .rr-query--empty {
94
+ margin: 1.5rem 0;
95
+ color: var(--rr-query-muted);
96
+ font-style: italic;
97
+ }
98
+
99
+ .rr-query--error {
100
+ margin: 1.5rem 0;
101
+ padding: 0.75rem 1rem;
102
+ border: 1px solid var(--rr-query-ink);
103
+ background: var(--rr-query-surface);
104
+ font-size: 0.875rem;
105
+ }
106
+
107
+ html[data-theme="dark"] .rr-query,
108
+ html.dark .rr-query {
109
+ --rr-query-ink: var(--rb-color-paper, #ffffff);
110
+ --rr-query-paper: var(--rb-color-ink, #000000);
111
+ }