@hidemikimura/vanji 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-12)
4
+
5
+ No change to the public API.
6
+
7
+ - Faster updates of list rows: a text hole that is an element's only content keeps its text node on the row from the first update on, and later strings are written to it directly. Updating every 10th row of 1,000 went from about 1.4× to 1.2× the time of hand-written JavaScript (each operation repeated 400 times).
8
+ - A binding made only of `selected() === row.id ? 'a' : 'b'` is no longer re-evaluated when the item is replaced; it is written only when the selection changes.
9
+ - Fast lists no longer keep a copy of the previous items array.
10
+ - Cost: one more field per text hole per row (JS heap at 10,000 rows 1,951 KB → 1,996 KB) and 28 bytes more runtime (3,827 bytes gzipped).
11
+
12
+ ## 0.1.0 (2026-12-02)
13
+
14
+ First release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hidemikimura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,257 @@
1
- # Temporary Holding Version
1
+ # vanji
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `html` テンプレート + シグナル + 事前コンパイルの、超軽量 UI フレームワーク。
4
+
5
+ - **AI が扱いやすい**: ルールは「シグナルを読む式(関数呼び出しを含む式)はリアクティブ」の 1 つだけ。公開 API は 12 個。誤りはコンパイル時に修正案つきで報告。全仕様は `llms.txt` 1 ファイル
6
+ - **ビルド必須**: `html` テンプレートはビルド時に「テンプレート複製 + ノード直接参照 + バインディング」へ変換される。実行時のテンプレート解析なし
7
+ - **リストはコンパイラが専用コードにする**: 行ごとのリアクティブなノードやクロージャを作らず、行ごとに前回値のメモだけを持つ(thane を参考にした方式)
8
+ - **軽量**: ランタイムは本番ビルドで gzip 約 3.8KB(リスト付きの典型的なアプリで約 3.6KB、カウンター程度なら約 2.0KB)。開発時だけの長いエラーメッセージと検査は、本番ビルドで自動的に取り除かれる(`npm run size` で計測)
9
+ - 対象外: Lit 互換、SSR / ハイドレーション、Custom Elements
10
+
11
+ > 名前は「vanilla JS」から(素の JS に近い速さと軽さを目指す)。旧名は hayate(仮称)。
12
+ >
13
+ > サイト(英語・日本語、ガイド・デモ・ベンチマーク): https://hidemikimura.github.io/vanji/
14
+
15
+ ## 使い方
16
+
17
+ ```sh
18
+ npm install @hidemikimura/vanji
19
+ npm install -D vite
20
+ ```
21
+
22
+ ```js
23
+ // vite.config.js
24
+ import vanji from '@hidemikimura/vanji/vite';
25
+ export default { plugins: [vanji()] };
26
+ ```
27
+
28
+ ```js
29
+ import { html, signal, computed, mount } from '@hidemikimura/vanji';
30
+
31
+ const Counter = () => {
32
+ const count = signal(0);
33
+ const double = computed(() => count() * 2);
34
+ return html`
35
+ <button @click=${() => count.update(n => n + 1)}>
36
+ ${count()} (x2 = ${double()})
37
+ </button>`;
38
+ };
39
+
40
+ mount(Counter, document.getElementById('app'));
41
+ ```
42
+
43
+ TypeScript は Vite が先に JS へ変換するので、そのまま `.ts` で書けます(`example/` 参照)。型定義は同梱しています。
44
+
45
+ AI に書かせるときは、パッケージに同梱の全仕様 `node_modules/@hidemikimura/vanji/llms.txt` を読ませてください。
46
+
47
+ Claude Code 向けの skill も同梱しています(導入手順、ルール、リスト・フォーム・データ読み込み・外部ライブラリの書き方、よくある誤り、確認の手順)。プロジェクトにコピーすると、vanji のコードを書くときに自動で使われます。
48
+
49
+ ```sh
50
+ mkdir -p .claude/skills && cp -R node_modules/@hidemikimura/vanji/skills/vanji .claude/skills/
51
+ ```
52
+
53
+ 本番ビルド(Vite の `vite build`、Rollup では `NODE_ENV=production`)では、プラグインがランタイムの開発時だけのコード(長いエラーメッセージ、`s.set` の切り離しの検査)を取り除きます。明示したいときは `vanji({ dev: true })` / `vanji({ dev: false })` と書きます。
54
+
55
+ ## たった 1 つのルール
56
+
57
+ **穴(`${}`)の式が関数を呼んでいればリアクティブ、呼んでいなければ 1 回だけ設定。** シグナルはふつうに呼んで読む。
58
+
59
+ ```js
60
+ html`<p>${count()}</p>` // 更新される
61
+ html`<p class=${count() > 2 ? 'big' : ''}>` // 更新される
62
+ html`<p>${total()}</p>` // 更新される(total() の中で読んだシグナルも追跡)
63
+ html`<p>${'固定'} ${variable}</p>` // 1 回だけ
64
+ ```
65
+
66
+ 依存関係は実行時に追跡するので、関数の中で読んだシグナルも確実に反映されます。テンプレートの直下に穴を置くと(`html\`${title()}<p>…</p>\``)、戻り値は DOM ノードではなく配列になります。穴・`each`・`when`・`mount` の中で使ってください。穴の中で大文字で始まる関数を呼ぶと(`${Card(x)}`)コンポーネントとみなし、本体は 1 回だけ実行します。
67
+
68
+ ## 記法
69
+
70
+ | 記法 | 意味 |
71
+ | --- | --- |
72
+ | `<p>${v}</p>` | テキスト / ノード / 配列 / `null`・`false` は何も出さない |
73
+ | `href=${v}` | 属性(`null` / `undefined` で削除) |
74
+ | `class="a ${v}"` | 固定文字列と混在した属性 |
75
+ | `?disabled=${v}` | 真偽値属性 |
76
+ | `.value=${v}` | DOM プロパティ(関数を呼ばずに渡すと、その関数自体が値になる) |
77
+ | `@click=${fn}` | イベント(素の `addEventListener`) |
78
+ | `ref=${el => …}` | 要素の参照(生成時に 1 回) |
79
+ | `${each(items(), row => html…, { key: 'id' })}` | キー付きリスト(穴の中に直接書く) |
80
+ | `${when(cond(), html…, html…)}` | 条件分岐。真偽が反転したときだけ作り直す(穴の中に直接書く) |
81
+
82
+ ### リスト
83
+
84
+ ```js
85
+ const todos = signal([{ id: 1, title: 'a', done: false }]);
86
+ const toggle = id => todos.update(l => l.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
87
+
88
+ html`<ul>${each(todos(), t => html`
89
+ <li class=${t.done ? 'done' : ''} @click=${() => toggle(t.id)}>${t.title}</li>`, { key: 'id' })}</ul>`
90
+ ```
91
+
92
+ - アイテムはただのオブジェクトで、**イミュータブルに更新**します。同じキーで別のオブジェクトに入れ替えると、その行の DOM は残したまま、変わった部分だけを書き換えます
93
+ - 行のテンプレートが 1 つの要素で、穴がアイテムのフィールドを読むだけなら、行ごとにエフェクトもクロージャも作りません。`selected() === row.id ? 'on' : ''` はリスト全体で 1 つの購読になり、選択が変わると前後 2 行だけを書き換えます
94
+ - 行の中のイベントは、種類ごとにリストの親要素の 1 つのキャプチャリスナーで受けます。ハンドラは target から外側へ順に呼ばれ、`this` と `e.currentTarget` はその要素で、行の最新のアイテムを見ます。親要素自身のリスナーより先に動くので、行の `stopPropagation()` で止められます。バブリングしないイベント(focus など)は、対象の要素のハンドラだけが動きます
95
+ - 関数を呼ぶ穴は行ごとのエフェクトになります。入れ子のテンプレートやコンポーネント、ブロック本体の行関数、複数の要素からなる行も使えます(行ごとのスコープを持つ汎用の経路)。こちらも同じキーなら行を残し、アイテムや index を使う部分だけを更新するので、行の中で作ったもの(`onMount` / `ref` で作ったエディタなど)は残ります。ブロック本体の先頭でコピーした値(`const t = r.title`)は作ったときの値のままです
96
+ - 例外: 行関数を名前で渡す(`each(items(), Row, …)`)か、アイテムを分割代入で受け取る(`({ id }) => …`)と、アイテムが入れ替わったときに行を作り直します
97
+ - 2 番目の引数 `index` はただの数値で、行が動いても正しい値になります
98
+
99
+ ## API
100
+
101
+ | 関数 | 説明 |
102
+ | --- | --- |
103
+ | `signal(v)` | `s()` 読み取り、`s.set(v)`、`s.update(fn)`、`s.peek()` |
104
+ | `computed(fn)` | 派生値。遅延評価・キャッシュ・結果が同じなら伝播しない |
105
+ | `effect(fn)` | 即実行し、依存が変わるたび同期的に再実行。停止関数を返す |
106
+ | `batch(fn)` / `untrack(fn)` | 更新の一括化 / 購読しない読み取り |
107
+ | `onCleanup(fn)` / `onMount(fn)` | 破棄時 / DOM 接続後 |
108
+ | `root(fn)` | 手動の所有スコープ |
109
+ | `html`, `each`, `when` | テンプレートと、その穴の中で使うリスト・条件分岐 |
110
+ | `mount(Component, el)` | 描画。アンマウント関数を返す |
111
+
112
+ 状態はイミュータブルに更新します(`list.update(l => [...l, x])`)。
113
+
114
+ ## コンパイル結果の例
115
+
116
+ ```js
117
+ html`<button @click=${inc}>Count: ${count()}!</button>`
118
+ ```
119
+ ```js
120
+ const _tmpl$0 = _$template("<button>Count: <!>!</button>");
121
+ (() => {
122
+ const _$$r = _tmpl$0(), _$$e0 = _$$r.firstChild.nextSibling;
123
+ _$$r.addEventListener("click", inc);
124
+ _$insert(_$$r, () => (count()), _$$e0);
125
+ return _$$r;
126
+ })()
127
+ ```
128
+
129
+ ## 制約(コンパイルエラーになる)
130
+
131
+ - 非 void 要素は必ず閉じる(`<div />` は可)
132
+ - 動的タグ名・属性スプレッド不可、`<textarea>` 等の中の `${}` 不可
133
+ - `<tr>` は `<tbody>` 等の中、`<p>` の中にブロック要素不可
134
+ - 穴の中で直接 `await` 不可
135
+ - イベントの修飾子はない(`@click.once` などはエラー)
136
+ - `each()` と `when()` は穴の中に直接書く。`each` の引数は `(items, row, { key })`
137
+
138
+ ## 開発
139
+
140
+ ```sh
141
+ npm install
142
+ npm test # シグナル / コンパイラ / jsdom 上の DOM 統合テスト
143
+ npm run size # ランタイムの min / gzip / brotli サイズ(本番ビルドと開発ビルド)
144
+ cd example && npm install && npm run dev
145
+ cd bench && npm install && npx playwright install chromium && npm run build # thane のビルド用に Bun も npm で入る
146
+ node check.mjs # 5 実装が同じ DOM 結果になるか
147
+ node bench.mjs 9 # 速度(サンプルごとに新しいページ、中央値)。IMPLS=vanji,solid で対象を絞れる
148
+ node memory.mjs # メモリ(強制 GC 後。V8 の JS ヒープ + Blink のヒープ)
149
+ ```
150
+
151
+ ## ベンチマーク(素の JS / lit-html / Solid / Svelte / thane と比較)
152
+
153
+ 対象: 素の JavaScript(手書きの DOM 操作、下限の目安)、vanji、lit-html 3.3.3(`repeat`)、solid-js 1.9.20(`<For>` + `createSelector`)、svelte 5.59.2(runes、`flushSync` で同期化)、thane 0.2.0(`repeat` + キー、作者の js-framework-benchmark 実装と同じ書き方。thane 自身の CLI を Bun で動かしてビルド)。
154
+ 環境: Apple M5(10 コア)、Chromium 159(Playwright のフル版をヘッドレスで起動)。ページ読み込み 1 回 = 1 サンプルで、9 サンプル(10,000 行作成は 5 サンプル)の中央値。`bench.mjs 9` を 3 回実行し、その 3 つの中央値の真ん中を載せている。
155
+ 軽い操作(更新・選択・入れ替え・1 行削除)は、ページ内で 10 回繰り返した中央値を 1 サンプルとする。タイマーの精度は 5µs(cross-origin isolation が有効なため)。
156
+
157
+ スクリプト時間(フレームワーク自身の処理、ms):
158
+
159
+ | 操作 | 素の JS | vanji | lit-html | Solid | Svelte | thane |
160
+ | --- | --- | --- | --- | --- | --- | --- |
161
+ | 1,000 行作成 | 1.59 | 1.64 | 4.26 | 2.66 | 3.26 | 1.63 |
162
+ | 1,000 行置換 | 2.94 | 3.13 | 6.36 | 4.04 | 4.67 | 3.01 |
163
+ | 10 行おきに更新 | 0.045 | 0.060 | 0.180 | 0.130 | 0.225 | 0.065 |
164
+ | 行の選択 | 0.010 | 0.020 | 0.140 | 0.045 | 0.355 | 0.015 |
165
+ | 2 行入れ替え | 0.020 | 0.050 | 0.175 | 0.165 | 0.255 | 0.045 |
166
+ | 1 行削除 | 0.020 | 0.055 | 0.165 | 0.085 | 0.195 | 0.045 |
167
+ | 1,000 行に 1,000 行追加 | 1.91 | 1.99 | 4.36 | 2.72 | 3.42 | 1.72 |
168
+ | 1,000 行クリア | 1.48 | 1.83 | 2.16 | 1.69 | 2.12 | 1.60 |
169
+ | 10,000 行作成 | 15.1 | 16.4 | 37.0 | 22.1 | 29.0 | 15.9 |
170
+
171
+ 合計時間(スクリプト + スタイル計算 + レイアウト、ms):
172
+
173
+ | 操作 | 素の JS | vanji | lit-html | Solid | Svelte | thane |
174
+ | --- | --- | --- | --- | --- | --- | --- |
175
+ | 1,000 行作成 | 15.9 | 15.7 | 18.6 | 16.6 | 17.2 | 15.6 |
176
+ | 1,000 行置換 | 13.1 | 13.6 | 16.9 | 14.3 | 14.8 | 13.1 |
177
+ | 10 行おきに更新 | 3.31 | 3.37 | 3.42 | 3.42 | 3.46 | 3.23 |
178
+ | 行の選択 | 0.050 | 0.055 | 0.255 | 0.090 | 0.400 | 0.060 |
179
+ | 2 行入れ替え | 1.12 | 1.17 | 1.37 | 1.25 | 1.33 | 1.14 |
180
+ | 1 行削除 | 1.07 | 1.10 | 1.29 | 1.11 | 1.19 | 1.09 |
181
+ | 1,000 行に 1,000 行追加 | 16.9 | 16.7 | 15.8 | 13.9 | 14.7 | 14.9 |
182
+ | 1,000 行クリア | 1.54 | 1.89 | 2.33 | 1.75 | 2.20 | 1.68 |
183
+ | 10,000 行作成 | 127.5 | 122.2 | 154.9 | 134.2 | 141.8 | 120.8 |
184
+
185
+ 軽い操作を繰り返した時間(µs、括弧内は素の JS との比)。上の表の 0.1ms 未満の値はタイマーの 5µs 刻みに対して数刻みしかないので、`micro.mjs` で 1 ページの中で 400 回繰り返し(20 回ごとに表を作り直し、レイアウトは測らない)、1 回あたりの時間を 7 ページで比べた中央値です。軽い操作の比はこちらで読んでください:
186
+
187
+ | 操作 | 素の JS | vanji | lit-html | Solid | Svelte | thane |
188
+ | --- | --- | --- | --- | --- | --- | --- |
189
+ | 10 行おきに更新 | 54.9 | 67.9 (1.24×) | 157.4 (2.87×) | 108.2 (1.97×) | 130.0 (2.37×) | 62.6 (1.14×) |
190
+ | 行の選択 | 1.1 | 1.9 (1.73×) | 78.6 (71×) | 8.1 (7.36×) | 145.9 (133×) | 2.6 (2.36×) |
191
+ | 2 行入れ替え | 19.2 | 25.0 (1.30×) | 101.6 (5.29×) | 106.0 (5.52×) | 87.0 (4.53×) | 24.6 (1.28×) |
192
+ | 1 行削除 | 18.8 | 31.3 (1.66×) | 122.2 (6.50×) | 58.4 (3.11×) | 72.3 (3.85×) | 29.1 (1.55×) |
193
+
194
+ メモリ(描画・レイアウト後に強制 GC してからの増分。環境は上と同じ。`memory.mjs` を 3 回実行した中央値)。
195
+ 「合計」は V8 の JS ヒープと Blink のヒープ(DOM ノード・イベントリスナーなど。CDP の `Runtime.getHeapUsage` の embedderHeapUsedSize)の和です。1,000 行の Blink ヒープと、10,000 行の vanji・thane・Solid は、3 回のうち 1 回が ±350〜600KB ずれることがあります(GC のタイミングと推測、未特定):
196
+
197
+ | 指標 | 素の JS | vanji | lit-html | Solid | Svelte | thane |
198
+ | --- | --- | --- | --- | --- | --- | --- |
199
+ | 10,000 行: 合計(JS + Blink) | 72,458KB | 72,757KB | 89,406KB | 81,625KB | 84,107KB | 72,559KB |
200
+ | 10,000 行: うち JS ヒープ | 1,703KB | 1,996KB | 7,089KB | 9,620KB | 13,201KB | 1,788KB |
201
+ | 10,000 行: うち Blink ヒープ | 70,755KB | 70,761KB | 82,317KB | 72,005KB | 70,906KB | 70,772KB |
202
+ | 1,000 行: 合計(JS + Blink) | 7,606KB | 7,681KB | 9,081KB | 8,540KB | 8,891KB | 7,642KB |
203
+ | 1,000 行: うち JS ヒープ | 221KB | 296KB | 744KB | 1,057KB | 1,516KB | 243KB |
204
+ | 参考: `measureUserAgentSpecificMemory`(10,000 行) | 10,913KB | 11,223KB | 23,511KB | 19,008KB | 22,586KB | 11,017KB |
205
+
206
+ 読み方の注意:
207
+
208
+ - **絶対値は 3 回の実行で 10〜28% ぶれます**(重い操作)。同じ回・同じ操作の中では実装がそろって動くので、実装どうしは素の JS との比で比べてください。ぶれの原因は未特定です(Headless Shell 版では 5% 以内でした)。
209
+ - 0.1ms 未満の値(更新・選択・入れ替え・1 行削除のスクリプト時間)は、タイマーの 5µs 刻みに対して数刻みしかなく、比は粗くなります(例: 1 行削除は表では 2.60〜3.33 倍ですが、繰り返して測ると 1.66 倍)。比べるときは「軽い操作を繰り返した時間」の表を使ってください。
210
+ - この回は 1,000 行追加の素の JS(1.91ms)と 1,000 行クリアの vanji(1.83ms)が前回(1.53ms・1.47ms)より遅く出ました。どちらの処理も変えていないので、ぶれと考えています(原因は未特定)。
211
+ - **vanji v2(2026-12、thane を参考にした作り直し)の前後**(スクリプト時間の素の JS 比、各 3 回):
212
+
213
+ | 操作 | v1 | v2 | thane |
214
+ | --- | --- | --- | --- |
215
+ | 1,000 行作成 | 1.26〜1.32 | 0.97〜1.21 | 0.94〜1.08 |
216
+ | 1,000 行置換 | 1.42〜1.44 | 0.98〜1.04 | 0.98〜1.07 |
217
+ | 10 行おきに更新 | 1.67〜1.88 | 1.89〜2.00 | 1.44〜1.62 |
218
+ | 行の選択 | 1.50〜1.50 | 1.67〜2.50 | 0.67〜1.50 |
219
+ | 2 行入れ替え | 2.75〜3.25 | 2.00〜2.20 | 1.60〜1.80 |
220
+ | 1 行削除 | 2.33〜2.67 | 2.75〜3.33 | 2.25〜3.00 |
221
+ | 1,000 行に 1,000 行追加 | 1.82〜1.83 | 1.00〜1.05 | 0.91〜1.03 |
222
+ | 1,000 行クリア | 1.08〜1.10 | 1.00〜1.04 | 1.01〜1.06 |
223
+ | 10,000 行作成 | 1.43〜1.50 | 1.05〜1.15 | 1.03〜1.14 |
224
+
225
+ 重い操作は素の JS・thane とほぼ同じになりました。10 行おきの更新は v1 より遅いままです(0.075 → 0.080ms、thane 0.065ms)。1 行削除は差分処理の先頭・末尾の比較を軽くして v1 と thane の間まで戻りました(v1 0.040ms、v2 0.055ms、thane 0.045ms)。どちらも v2 のベンチマーク実装がイミュータブル更新(配列を作り直し、キーで比べる)になったことが主な理由です。JS ヒープは 10,000 行で 6,840KB → 1,951KB です。
226
+ - **10 行おきの更新の改善**(2026-12、0.1.1): 要素の唯一の子であるテキストの穴は、最初の更新でテキストノードを行に持ち、次からはそこへ直接書くようにしました(要素パスをたどらない)。あわせて、選択だけのバインディング(`selected() === row.id ? 'danger' : ''`)はアイテムの入れ替えでは読み直さず、前回のアイテムの配列も持たないようにしました(この 2 つは単独ではぶれの範囲でした)。操作を 400 回繰り返して測ると、更新 1 回は素の JS 比 1.36〜1.41 倍 → 1.14〜1.22 倍(thane 1.14〜1.21 倍)、上の表では 1.89〜2.00 倍 → 1.33〜1.63 倍です。代わりに 10,000 行の JS ヒープが 1,951KB → 1,996KB(行ごとに 1 フィールド × 穴の数)、ランタイムが gzip で +28B(全体 3,827B)増えました。1 行削除は表では 2.75〜3.33 → 3.33〜3.67 倍ですが、400 回繰り返した計測では変更前と差がなく(26.8µs → 28.1µs、各ページの値は重なる)、素の JS の値が 5µs 刻みで 0.020 → 0.015ms になったことが主な理由です。
227
+ - レイアウト時間はフレームワークの差ではありません。トレースで確認すると、4 実装ともブラウザが再計算する対象は同数です(1 行削除: 9,996 個中 6 個、1,000 行作成: 10,006 個)。
228
+ - 以前の 1 コア環境(Chromium 153)では、合計時間の「1,000 行作成」で lit-html が最速に見え、lit-html の置換・クリアが 100ms を超えていました。複数コアのこの環境ではどちらも再現しません。
229
+ - 素の JS・Solid・Svelte・thane・vanji はクリックイベントを委譲します(素の JS・thane・vanji は `<tbody>` に 1 つ、Solid・Svelte は `document`)。lit-html だけ行ごとに `addEventListener` しています。
230
+ - vanji と thane は行をただのオブジェクトにしてイミュータブルに更新し、Solid は行ごとにラベルのシグナルを持たせています(それぞれのフレームワークの定石)。
231
+ - メモリの大半(約 9 割)は Blink のヒープで、DOM ノードの数でほぼ決まります。`measureUserAgentSpecificMemory` は Blink のヒープを含まないので参考値です。
232
+ - ブラウザは `bench/browser.mjs` で起動し、全スクリプトで Playwright のフル版 Chromium を使います。別のバイナリは `CHROME_PATH` で指定できます。
233
+ - 調査用スクリプト: `micro.mjs`(軽い操作を 1 ページで数百回繰り返した 1 回あたりの時間。`OP=update|remove`)、`profile-rep.mjs`(軽い操作を繰り返した CPU プロファイル。関数ごとの 1 回あたりの時間)、`profile.mjs`(操作単位の CPU プロファイル。どちらも `npx vite build --minify false --outDir dist-prof` が必要)、`trace.mjs`(レイアウト対象数)、`trace-gc.mjs`(経過時間と CPU 時間の比較)、`trace-threads.mjs`(他スレッドの稼働)、`layout-lab.mjs`(フレームワークなしの DOM 実験)。
234
+
235
+ ## 構成
236
+
237
+ ```
238
+ src/signals.js リアクティブコア
239
+ src/dom.js DOM ランタイム(template / insert / 汎用 each / when / mount)
240
+ src/list.js リストの高速な経路(コンパイラが行テンプレートから作る仕様で動く)
241
+ src/internal.js コンパイル済みコードが使うヘルパー(非公開 API)
242
+ src/dev.js 開発フラグ(本番ビルドではプラグインが false にする)
243
+ compiler/ コンパイラ(index / template / list / ast)と Vite / Rollup プラグイン
244
+ llms.txt AI 向け全仕様
245
+ docs/design-v2.md v2 の設計(thane を参考にした作り直し)
246
+ example/ Vite + TypeScript のサンプル
247
+ site/ GitHub Pages のサイト(vanji 製。`main` / `master` に push すると .github/workflows/pages.yml が公開)
248
+ bench/ 素の JS / lit-html / Solid / Svelte / thane との比較ベンチマーク
249
+ ```
250
+
251
+ ## 未実装
252
+
253
+ HMR の状態保持、SSR。
254
+
255
+ ## ライセンス
256
+
257
+ MIT
@@ -0,0 +1,48 @@
1
+ // AST helpers shared by the compiler modules.
2
+
3
+ export const isNode = v => v && typeof v === 'object' && typeof v.type === 'string';
4
+
5
+ /** Pre-order walk; return false from `fn` to skip a subtree. */
6
+ export function walk(node, fn) {
7
+ if (fn(node) === false) return;
8
+ for (const key in node) {
9
+ const v = node[key];
10
+ if (Array.isArray(v)) {
11
+ for (const c of v) if (isNode(c)) walk(c, fn);
12
+ } else if (isNode(v)) walk(v, fn);
13
+ }
14
+ }
15
+
16
+ export const isFn = n =>
17
+ n.type === 'ArrowFunctionExpression' || n.type === 'FunctionExpression' || n.type === 'FunctionDeclaration';
18
+
19
+ /**
20
+ * THE template rule: a hole whose expression calls a function is reactive. Calls inside nested
21
+ * functions or nested html`` templates do not count (they do not run when the hole is evaluated).
22
+ */
23
+ export const hasCall = (node, isHtmlTag, reads = NONE) => {
24
+ let found = false;
25
+ walk(node, n => {
26
+ if (found || isFn(n) || isHtmlTag(n)) return false;
27
+ // `reads`: identifiers the compiler turns into getter calls (the item / index of a live each() row)
28
+ if (n.type === 'CallExpression' || n.type === 'TaggedTemplateExpression' || reads.has(n)) found = true;
29
+ });
30
+ return found;
31
+ };
32
+ const NONE = new Set();
33
+
34
+ /** Does the expression contain a function or a nested html`` template (anywhere)? */
35
+ export const hasFnOrTemplate = (node, isHtmlTag) => {
36
+ let found = false;
37
+ walk(node, n => {
38
+ if (found) return false;
39
+ if (isFn(n) || isHtmlTag(n)) found = true;
40
+ });
41
+ return found;
42
+ };
43
+
44
+ /** `() => expr` literal (old style): treated like `expr`, which is reactive when it calls a function. */
45
+ export const arrowBody = e =>
46
+ e.type === 'ArrowFunctionExpression' && !e.async && !e.params.length && e.body.type !== 'BlockStatement' ? e.body : null;
47
+
48
+ export const IDENT = /^[A-Za-z_$][\w$]*$/;
@@ -0,0 +1,21 @@
1
+ /** A compile error with its location and, usually, a hint on how to fix it. */
2
+ export class CompileError extends Error {
3
+ id: string;
4
+ loc: { line: number; column: number };
5
+ hint?: string;
6
+ }
7
+
8
+ export interface CompileResult {
9
+ code: string;
10
+ map: object | null;
11
+ warnings: Array<{ message: string; line: number; column: number }>;
12
+ }
13
+
14
+ /**
15
+ * Compile the html`` templates of one JavaScript module (run after TypeScript is stripped).
16
+ * Returns null when the module has no templates. Most projects use the Vite plugin instead.
17
+ */
18
+ export function compile(
19
+ code: string,
20
+ options?: { id?: string; moduleName?: string; sourceMap?: boolean }
21
+ ): CompileResult | null;
@@ -0,0 +1,155 @@
1
+ // vanji compiler: rewrites html`...` tagged templates into direct DOM code.
2
+ //
3
+ // html`<button @click=${inc}>Count: ${count()}</button>`
4
+ // becomes
5
+ // const _tmpl$0 = template("<button>Count: <!></button>");
6
+ // (() => { const _r = _tmpl$0(), _e0 = _r.firstChild.nextSibling;
7
+ // _r.addEventListener("click", inc); insert(_r, () => (count()), _e0); return _r; })()
8
+ //
9
+ // THE rule: a hole whose expression calls a function is reactive; anything else is set once.
10
+ // Input must be plain JavaScript (run after TypeScript has been stripped).
11
+ import { parse } from 'acorn';
12
+ import MagicString from 'magic-string';
13
+ import { walk } from './ast.js';
14
+ import { createTemplateCompiler } from './template.js';
15
+
16
+ export class CompileError extends Error {
17
+ constructor(message, { id, line, column, hint }) {
18
+ super(`[vanji] ${id}:${line}:${column} ${message}${hint ? `\n hint: ${hint}` : ''}`);
19
+ this.name = 'VanjiCompileError';
20
+ this.id = id;
21
+ this.loc = { line, column };
22
+ this.hint = hint;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @param {string} code JavaScript module source
28
+ * @param {{ id?: string, moduleName?: string, sourceMap?: boolean }} [options]
29
+ * @returns {{ code: string, map: object | null, warnings: Array<{message: string, line: number, column: number}> } | null}
30
+ * null when the file has no html`` templates
31
+ */
32
+ export function compile(code, { id = 'unknown', moduleName = '@hidemikimura/vanji', sourceMap = true } = {}) {
33
+ if (!code.includes(moduleName)) return null;
34
+
35
+ let ast;
36
+ try {
37
+ ast = parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
38
+ } catch (e) {
39
+ throw new CompileError(`Cannot parse module: ${e.message}`, {
40
+ id,
41
+ line: e.loc ? e.loc.line : 0,
42
+ column: e.loc ? e.loc.column : 0,
43
+ hint: 'The vanji compiler expects plain JavaScript. Run it after TypeScript/JSX transforms.',
44
+ });
45
+ }
46
+
47
+ // --- local names of vanji's html / each / when / signal / computed ---
48
+ const names = { html: null, each: null, when: null }, signalFns = new Set();
49
+ let nsName = null;
50
+ for (const n of ast.body) {
51
+ if (n.type !== 'ImportDeclaration' || n.source.value !== moduleName) continue;
52
+ for (const s of n.specifiers) {
53
+ if (s.type === 'ImportNamespaceSpecifier') nsName = s.local.name;
54
+ else if (s.type === 'ImportSpecifier') {
55
+ if (s.imported.name in names) names[s.imported.name] = s.local.name;
56
+ if (s.imported.name === 'signal' || s.imported.name === 'computed') signalFns.add(s.local.name);
57
+ }
58
+ }
59
+ }
60
+ if (!names.html && !nsName) return null;
61
+
62
+ const refersTo = (n, name) =>
63
+ (n.type === 'Identifier' && n.name === names[name]) ||
64
+ (n.type === 'MemberExpression' && !n.computed && n.object.type === 'Identifier' && n.object.name === nsName && n.property.name === name);
65
+ const isHtmlTag = n => n.type === 'TaggedTemplateExpression' && refersTo(n.tag, 'html');
66
+ const isEach = n => n.type === 'CallExpression' && refersTo(n.callee, 'each');
67
+ const isWhen = n => n.type === 'CallExpression' && refersTo(n.callee, 'when');
68
+
69
+ const fail = (message, hint, { line, column }) => {
70
+ throw new CompileError(message, { id, line, column, hint });
71
+ };
72
+
73
+ const warnings = [];
74
+ lintDetachedMethods(ast, signalFns, warnings);
75
+
76
+ const templates = new Map(); // kind + html -> { name, html, kind }
77
+ const helpers = new Set();
78
+ const handled = new Set(); // each() / when() calls compiled in place
79
+ const reads = new Map(); // identifier node -> getter call replacing it (the item / index of a live each() row)
80
+ const use = name => (helpers.add(name), `_$${name}`);
81
+ const { genTemplate } = createTemplateCompiler({ code, use, isHtmlTag, isEach, isWhen, templates, handled, reads, fail });
82
+
83
+ const ms = new MagicString(code);
84
+ const outermost = [];
85
+ walk(ast, n => {
86
+ if (isHtmlTag(n)) {
87
+ outermost.push(n);
88
+ return false;
89
+ }
90
+ });
91
+ for (const t of outermost) ms.overwrite(t.start, t.end, genTemplate(t));
92
+
93
+ // each() / when() only work directly in a template hole
94
+ walk(ast, n => {
95
+ if ((isEach(n) || isWhen(n)) && !handled.has(n)) {
96
+ const name = isEach(n) ? 'each' : 'when';
97
+ fail(
98
+ `${name}() must be written directly in a template hole`,
99
+ name === 'each'
100
+ ? "Write html`<ul>${each(todos(), t => html`<li>${t.title}</li>`, { key: 'id' })}</ul>`."
101
+ : 'Write html`<div>${when(user(), html`<p>Hi</p>`, html`<p>Sign in</p>`)}</div>`.',
102
+ n.loc.start
103
+ );
104
+ }
105
+ });
106
+
107
+ if (!templates.size) return null;
108
+ use('template');
109
+ const imports = [...helpers].map(h => `${h} as _$${h}`).join(', ');
110
+ const decl = [...templates.values()]
111
+ .map(t => `const ${t.name} = /*#__PURE__*/ _$template(${JSON.stringify(t.html)}${t.kind ? `, ${t.kind}` : ''});`)
112
+ .join(' ');
113
+ ms.prepend(`import { ${imports} } from "${moduleName}/internal"; ${decl} `);
114
+
115
+ return {
116
+ code: ms.toString(),
117
+ map: sourceMap ? ms.generateMap({ source: id, hires: true, includeContent: true }) : null,
118
+ warnings,
119
+ };
120
+ }
121
+
122
+ // lint: `s.set` / `s.update` passed around without its signal loses `this`
123
+ function lintDetachedMethods(ast, signalFns, warnings) {
124
+ const signalVars = new Set();
125
+ walk(ast, n => {
126
+ if (
127
+ n.type === 'VariableDeclarator' &&
128
+ n.id.type === 'Identifier' &&
129
+ n.init &&
130
+ n.init.type === 'CallExpression' &&
131
+ n.init.callee.type === 'Identifier' &&
132
+ signalFns.has(n.init.callee.name)
133
+ )
134
+ signalVars.add(n.id.name);
135
+ });
136
+ const callees = new Set();
137
+ walk(ast, n => {
138
+ if (n.type === 'CallExpression') callees.add(n.callee);
139
+ else if (
140
+ n.type === 'MemberExpression' &&
141
+ !n.computed &&
142
+ !callees.has(n) &&
143
+ n.object.type === 'Identifier' &&
144
+ signalVars.has(n.object.name) &&
145
+ /^(set|update|peek)$/.test(n.property.name)
146
+ )
147
+ warnings.push({
148
+ message:
149
+ `\`${n.object.name}.${n.property.name}\` is passed without being called, which detaches it from its signal and throws at runtime. ` +
150
+ `Wrap it: v => ${n.object.name}.${n.property.name}(v).`,
151
+ line: n.loc.start.line,
152
+ column: n.loc.start.column,
153
+ });
154
+ });
155
+ }