esbuild-plugin-browser 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 oshio0929
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 oshio0929
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,48 +1,49 @@
1
- # esbuild-plugin-browser
2
-
3
- [esbuild-wasm](https://esbuild.github.io/api/#browser) をブラウザで動かすためのプラグイン。
4
- ファイルシステムが無い環境で、手元のファイルと npm のパッケージをまとめてビルドする。
5
-
6
- - 手元のファイルは `Map`(パス → 中身)など、`has` / `get` を持つものを渡すだけ。memfs でも OPFS でも、自分のデータベースでもつなげる
7
- - npm のパッケージは esm.sh から読む。バージョンは `package.json` の `dependencies` に合わせる
8
- - svelte / vue / react / preact などの「状態をモジュールで共有するランタイム」は、esm.sh が分けて配るモジュールのまま読む。サブパスごとに依存を抱え込んだ版を混ぜて、ランタイムが二重に入って壊れる問題を避ける
9
- - `.svelte`(Svelte 5)/ `.svelte.ts` / `.vue`(SFC・script setup・TS・scoped・`<style lang="scss">`)/ `.scss` / `.sass` / `.less` / `.yaml` を変換する。コンパイラは使うときに CDN から読み、svelte と vue は `package.json` のランタイムと同じバージョンにそろえる
10
-
11
- ```js
12
- import * as esbuild from 'https://cdn.jsdelivr.net/npm/esbuild-wasm@0.28.2/esm/browser.min.js';
13
- import { browserPlugin } from 'https://esm.sh/esbuild-plugin-browser@0.1.0';
14
-
15
- await esbuild.initialize({ wasmURL: 'https://cdn.jsdelivr.net/npm/esbuild-wasm@0.28.2/esbuild.wasm' });
16
-
17
- const files = new Map([
18
- ['package.json', JSON.stringify({ dependencies: { svelte: '^5.0.0' } })],
19
- ['src/main.ts', "import { mount } from 'svelte';\nimport App from './App.svelte';\nmount(App, { target: document.body });"],
20
- ['src/App.svelte', '<script>let n = $state(0);</script><button onclick={() => n++}>{n}</button>'],
21
- ]);
22
-
23
- const result = await esbuild.build({
24
- entryPoints: ['src/main.ts'],
25
- bundle: true,
26
- write: false,
27
- format: 'esm',
28
- plugins: [browserPlugin({ files, esbuild })],
29
- });
30
- ```
31
-
32
- ## オプション
33
-
34
- | 名前 | 中身 |
35
- |---|---|
36
- | `files` | 必須。`has(path)` / `get(path)`。パスは先頭の `/` なし。`Uint8Array` はバイナリとして data URL で読む |
37
- | `esbuild` | esbuild 本体。変換(`.svelte.ts` の TS を剥がす)に使う |
38
- | `dependencies` | 省くと `files` の `package.json` から読む |
39
- | `cdn` | 既定 `https://esm.sh` |
40
- | `transform` | 既定 `true`。`{ load }` でコンパイラの読み方を差し替えられる(`compilerLoader({ svelte: '...:range...' })`) |
41
- | `resolvePackage(name, sub, range)` | npm のパッケージを手元のファイルで解決したいとき。`files` のパスを返す。`null` なら CDN |
42
- | `cache` | `get` / `set`(非同期でいい)。バージョンが確定した URL だけを入れる |
43
- | `prod` | 本番向け(Sass / Less の圧縮、Svelte / Vue の本番モード) |
44
- | `log` | `{ info, warn }` |
45
-
46
- 相対 import は拡張子を省ける(`.ts` / `.tsx` / `.js` / `.svelte.ts` / `index.*` を探す)。`./foo.js` と書いて `foo.ts` を指す書き方も通る。
47
-
48
- MIT License
1
+ # esbuild-plugin-browser
2
+
3
+ [esbuild-wasm](https://esbuild.github.io/api/#browser) をブラウザで動かすためのプラグイン。
4
+ ファイルシステムが無い環境で、手元のファイルと npm のパッケージをまとめてビルドする。
5
+
6
+ - 手元のファイルは `Map`(パス → 中身)など、`has` / `get` を持つものを渡すだけ。memfs でも OPFS でも、自分のデータベースでもつなげる
7
+ - npm のパッケージは esm.sh から読む。バージョンは `package.json` の `dependencies` に合わせる
8
+ - svelte / vue / react / preact などの「状態をモジュールで共有するランタイム」は、esm.sh が分けて配るモジュールのまま読む。サブパスごとに依存を抱え込んだ版を混ぜて、ランタイムが二重に入って壊れる問題を避ける
9
+ - `.svelte`(Svelte 5)/ `.svelte.ts` / `.vue`(SFC・script setup・TS・scoped・`<style lang="scss">`)/ `.scss` / `.sass` / `.less` / `.yaml` を変換する。コンパイラは使うときに CDN から読み、svelte と vue は `package.json` のランタイムと同じバージョンにそろえる
10
+
11
+ ```js
12
+ import * as esbuild from 'https://cdn.jsdelivr.net/npm/esbuild-wasm@0.28.2/esm/browser.min.js';
13
+ import { browserPlugin } from 'https://esm.sh/esbuild-plugin-browser@0.1.0';
14
+
15
+ await esbuild.initialize({ wasmURL: 'https://cdn.jsdelivr.net/npm/esbuild-wasm@0.28.2/esbuild.wasm' });
16
+
17
+ const files = new Map([
18
+ ['package.json', JSON.stringify({ dependencies: { svelte: '^5.0.0' } })],
19
+ ['src/main.ts', "import { mount } from 'svelte';\nimport App from './App.svelte';\nmount(App, { target: document.body });"],
20
+ ['src/App.svelte', '<script>let n = $state(0);</script><button onclick={() => n++}>{n}</button>'],
21
+ ]);
22
+
23
+ const result = await esbuild.build({
24
+ entryPoints: ['src/main.ts'],
25
+ bundle: true,
26
+ write: false,
27
+ format: 'esm',
28
+ plugins: [browserPlugin({ files, esbuild })],
29
+ });
30
+ ```
31
+
32
+ ## オプション
33
+
34
+ | 名前 | 中身 |
35
+ |---|---|
36
+ | `files` | 必須。`has(path)` / `get(path)`。パスは先頭の `/` なし。`Uint8Array` はバイナリとして data URL で読む |
37
+ | `esbuild` | esbuild 本体。変換(`.svelte.ts` の TS を剥がす)に使う |
38
+ | `dependencies` | 省くと `files` の `package.json` から読む |
39
+ | `cdn` | 既定 `https://esm.sh` |
40
+ | `transform` | 既定 `true`。`{ load }` でコンパイラの読み方を差し替えられる(`compilerLoader({ svelte: '...:range...' })`) |
41
+ | `resolvePackage(name, sub, range)` | npm のパッケージを手元のファイルで解決したいとき。`files` のパスを返す。`null` なら CDN |
42
+ | `cache` | `get` / `set`(非同期でいい)。バージョンが確定した URL だけを入れる |
43
+ | `prod` | 本番向け(Sass / Less の圧縮、Svelte / Vue の本番モード) |
44
+ | `log` | `{ info, warn }` |
45
+ | `fetch` | CDN から取るときの `fetch`。中身のハッシュを確かめるものに差し替えるなど |
46
+
47
+ 相対 import は拡張子を省ける(`.ts` / `.tsx` / `.js` / `.svelte.ts` / `index.*` を探す)。`./foo.js` と書いて `foo.ts` を指す書き方も通る。
48
+
49
+ MIT License
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "esbuild-plugin-browser",
3
- "version": "0.1.0",
4
- "description": "esbuild-wasm をブラウザで動かすためのプラグイン。手元のファイル + esm.sh の npm + .svelte / .vue / .scss / .less / .yaml の変換",
5
- "type": "module",
6
- "main": "./src/index.js",
7
- "types": "./src/index.d.ts",
8
- "exports": {
9
- ".": { "types": "./src/index.d.ts", "import": "./src/index.js" },
10
- "./package.json": "./package.json"
11
- },
12
- "files": ["src", "README.md", "LICENSE"],
13
- "sideEffects": false,
14
- "scripts": { "test": "node test/smoke.mjs" },
15
- "peerDependencies": { "esbuild-wasm": ">=0.20" },
16
- "peerDependenciesMeta": { "esbuild-wasm": { "optional": true } },
17
- "repository": { "type": "git", "url": "git+https://github.com/yusura0929/kintone-plugin-ide.git", "directory": "packages/esbuild-plugin-browser" },
18
- "homepage": "https://github.com/yusura0929/kintone-plugin-ide/tree/main/packages/esbuild-plugin-browser#readme",
19
- "bugs": { "url": "https://github.com/yusura0929/kintone-plugin-ide/issues" },
20
- "keywords": ["esbuild", "esbuild-plugin", "esbuild-wasm", "browser", "svelte", "vue", "sass", "less", "esm.sh", "virtual-file-system"],
21
- "license": "MIT",
22
- "publishConfig": { "access": "public" }
23
- }
1
+ {
2
+ "name": "esbuild-plugin-browser",
3
+ "version": "0.2.0",
4
+ "description": "esbuild-wasm をブラウザで動かすためのプラグイン。手元のファイル + esm.sh の npm + .svelte / .vue / .scss / .less / .yaml の変換",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": { "types": "./src/index.d.ts", "import": "./src/index.js" },
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": ["src", "README.md", "LICENSE"],
13
+ "sideEffects": false,
14
+ "scripts": { "test": "node test/smoke.mjs" },
15
+ "peerDependencies": { "esbuild-wasm": ">=0.20" },
16
+ "peerDependenciesMeta": { "esbuild-wasm": { "optional": true } },
17
+ "repository": { "type": "git", "url": "git+https://github.com/yusura0929/kintone-plugin-ide.git", "directory": "packages/esbuild-plugin-browser" },
18
+ "homepage": "https://github.com/yusura0929/kintone-plugin-ide/tree/main/packages/esbuild-plugin-browser#readme",
19
+ "bugs": { "url": "https://github.com/yusura0929/kintone-plugin-ide/issues" },
20
+ "keywords": ["esbuild", "esbuild-plugin", "esbuild-wasm", "browser", "svelte", "vue", "sass", "less", "esm.sh", "virtual-file-system"],
21
+ "license": "MIT",
22
+ "publishConfig": { "access": "public" }
23
+ }
package/src/http.js CHANGED
@@ -1,36 +1,36 @@
1
- // http(s) の import を fetch で読む esbuild プラグイン
2
- // バージョンが確定した URL(/pkg@1.2.3/...)は中身が変わらないので、cache があればそこに残す
3
- const immutable = (u) => /@\d+\.\d+\.\d+(-[\w.]+)?\//.test(u) && !/[\^~*]/.test(decodeURIComponent(u));
4
-
5
- /**
6
- * @param {object} [o]
7
- * @param {{ get(key: string): any, set(key: string, value: string): any }} [o.cache] 永続キャッシュ(IndexedDB など)。非同期でもいい
8
- * @param {{ info?(t: string): void }} [o.log]
9
- * @param {typeof fetch} [o.fetch]
10
- */
11
- export function httpPlugin({ cache, log, fetch: f = globalThis.fetch.bind(globalThis) } = {}) {
12
- const memo = new Map();
13
- return {
14
- name: 'http',
15
- setup(b) {
16
- b.onResolve({ filter: /^https?:\/\// }, (a) => ({ path: a.path, namespace: 'http' }));
17
- // 取ってきたモジュールの中の "/pkg@1.0.0/..." や相対パス
18
- b.onResolve({ filter: /.*/, namespace: 'http' }, (a) => ({ path: new URL(a.path, a.importer).href, namespace: 'http' }));
19
- b.onLoad({ filter: /.*/, namespace: 'http' }, async (a) => {
20
- if (!memo.has(a.path)) {
21
- const keep = cache && immutable(a.path);
22
- let text = keep ? await cache.get(`http:${a.path}`) : undefined;
23
- if (text === undefined || text === null) {
24
- log?.info?.(`取得: ${a.path}`);
25
- const res = await f(a.path);
26
- if (!res.ok) throw new Error(`${res.status} ${a.path}`);
27
- text = await res.text();
28
- if (keep) await cache.set(`http:${a.path}`, text);
29
- }
30
- memo.set(a.path, text);
31
- }
32
- return { contents: memo.get(a.path), loader: /\.css(\?|$)/.test(a.path) ? 'css' : 'js' };
33
- });
34
- },
35
- };
36
- }
1
+ // http(s) の import を fetch で読む esbuild プラグイン
2
+ // バージョンが確定した URL(/pkg@1.2.3/...)は中身が変わらないので、cache があればそこに残す
3
+ const immutable = (u) => /@\d+\.\d+\.\d+(-[\w.]+)?\//.test(u) && !/[\^~*]/.test(decodeURIComponent(u));
4
+
5
+ /**
6
+ * @param {object} [o]
7
+ * @param {{ get(key: string): any, set(key: string, value: string): any }} [o.cache] 永続キャッシュ(IndexedDB など)。非同期でもいい
8
+ * @param {{ info?(t: string): void }} [o.log]
9
+ * @param {typeof fetch} [o.fetch]
10
+ */
11
+ export function httpPlugin({ cache, log, fetch: f = globalThis.fetch.bind(globalThis) } = {}) {
12
+ const memo = new Map();
13
+ return {
14
+ name: 'http',
15
+ setup(b) {
16
+ b.onResolve({ filter: /^https?:\/\// }, (a) => ({ path: a.path, namespace: 'http' }));
17
+ // 取ってきたモジュールの中の "/pkg@1.0.0/..." や相対パス
18
+ b.onResolve({ filter: /.*/, namespace: 'http' }, (a) => ({ path: new URL(a.path, a.importer).href, namespace: 'http' }));
19
+ b.onLoad({ filter: /.*/, namespace: 'http' }, async (a) => {
20
+ if (!memo.has(a.path)) {
21
+ const keep = cache && immutable(a.path);
22
+ let text = keep ? await cache.get(`http:${a.path}`) : undefined;
23
+ if (text === undefined || text === null) {
24
+ log?.info?.(`取得: ${a.path}`);
25
+ const res = await f(a.path);
26
+ if (!res.ok) throw new Error(`${res.status} ${a.path}`);
27
+ text = await res.text();
28
+ if (keep) await cache.set(`http:${a.path}`, text);
29
+ }
30
+ memo.set(a.path, text);
31
+ }
32
+ return { contents: memo.get(a.path), loader: /\.css(\?|$)/.test(a.path) ? 'css' : 'js' };
33
+ });
34
+ },
35
+ };
36
+ }
package/src/index.d.ts CHANGED
@@ -1,49 +1,51 @@
1
- import type { Plugin } from 'esbuild';
2
-
3
- export interface FileSource {
4
- has(path: string): boolean;
5
- get(path: string): string | Uint8Array | undefined;
6
- }
7
- export interface PersistentCache {
8
- get(key: string): unknown | Promise<unknown>;
9
- set(key: string, value: string): unknown | Promise<unknown>;
10
- }
11
- export interface Logger {
12
- info?(text: string): void;
13
- warn?(text: string): void;
14
- }
15
- export type CompilerLoader = (name: 'svelte' | 'vue' | 'sass' | 'less' | 'yaml', range?: string) => Promise<any>;
16
-
17
- export interface BrowserPluginOptions {
18
- /** ファイル(パスは先頭の / なし)。Map をそのまま渡せる。Uint8Array はバイナリ扱い */
19
- files: FileSource;
20
- /** esbuild 本体。.svelte などの変換を使うときに要る */
21
- esbuild?: unknown;
22
- /** 省くと files の package.json の dependencies を使う */
23
- dependencies?: Record<string, string>;
24
- /** npm の配信元(既定: https://esm.sh) */
25
- cdn?: string;
26
- /** ランタイムを共有するパッケージ(二重に入れない) */
27
- sharedRuntimes?: RegExp;
28
- /** .svelte / .vue / .scss / .less / .yaml の変換(既定: 有効) */
29
- transform?: boolean | { load?: CompilerLoader };
30
- prod?: boolean;
31
- /** npm のパッケージを手元のファイルで解決する。files のパスを返す。null なら CDN から */
32
- resolvePackage?: (name: string, sub: string, range: string) => string | null | Promise<string | null>;
33
- /** CDN から取ったものの永続キャッシュ(バージョンが確定した URL だけ入れる) */
34
- cache?: PersistentCache;
35
- log?: Logger;
36
- }
37
-
38
- export function browserPlugin(options: BrowserPluginOptions): Plugin;
39
- export default browserPlugin;
40
- export function httpPlugin(options?: { cache?: PersistentCache; log?: Logger; fetch?: typeof fetch }): Plugin;
41
- export function createTransformer(options: {
42
- files: FileSource; esbuild: unknown; deps?: Record<string, string>; load?: CompilerLoader; prod?: boolean; log?: Logger;
43
- }): (path: string, content: string | Uint8Array) => Promise<{ contents: string; loader: string; resolveDir: string } | { errors: unknown[] } | null>;
44
- export function compilerLoader(templates?: Partial<Record<'svelte' | 'vue' | 'sass' | 'less' | 'yaml', string>>): CompilerLoader;
45
- export const DEFAULT_COMPILERS: Record<'svelte' | 'vue' | 'sass' | 'less' | 'yaml', string>;
46
- export const TRANSFORM_EXT: RegExp;
47
- export const SHARED_RUNTIMES: RegExp;
48
- export function parseSpecifier(spec: string): { name: string; sub: string };
49
- export function esmShUrl(cdn: string, name: string, range: string, sub?: string, options?: { shared?: boolean; target?: string }): string;
1
+ import type { Plugin } from 'esbuild';
2
+
3
+ export interface FileSource {
4
+ has(path: string): boolean;
5
+ get(path: string): string | Uint8Array | undefined;
6
+ }
7
+ export interface PersistentCache {
8
+ get(key: string): unknown | Promise<unknown>;
9
+ set(key: string, value: string): unknown | Promise<unknown>;
10
+ }
11
+ export interface Logger {
12
+ info?(text: string): void;
13
+ warn?(text: string): void;
14
+ }
15
+ export type CompilerLoader = (name: 'svelte' | 'vue' | 'sass' | 'less' | 'yaml', range?: string) => Promise<any>;
16
+
17
+ export interface BrowserPluginOptions {
18
+ /** ファイル(パスは先頭の / なし)。Map をそのまま渡せる。Uint8Array はバイナリ扱い */
19
+ files: FileSource;
20
+ /** esbuild 本体。.svelte などの変換を使うときに要る */
21
+ esbuild?: unknown;
22
+ /** 省くと files の package.json の dependencies を使う */
23
+ dependencies?: Record<string, string>;
24
+ /** npm の配信元(既定: https://esm.sh) */
25
+ cdn?: string;
26
+ /** ランタイムを共有するパッケージ(二重に入れない) */
27
+ sharedRuntimes?: RegExp;
28
+ /** .svelte / .vue / .scss / .less / .yaml の変換(既定: 有効) */
29
+ transform?: boolean | { load?: CompilerLoader };
30
+ prod?: boolean;
31
+ /** npm のパッケージを手元のファイルで解決する。files のパスを返す。null なら CDN から */
32
+ resolvePackage?: (name: string, sub: string, range: string) => string | null | Promise<string | null>;
33
+ /** CDN から取ったものの永続キャッシュ(バージョンが確定した URL だけ入れる) */
34
+ cache?: PersistentCache;
35
+ log?: Logger;
36
+ /** CDN から取るときの fetch(中身を確かめる fetch に差し替えるなど) */
37
+ fetch?: typeof fetch;
38
+ }
39
+
40
+ export function browserPlugin(options: BrowserPluginOptions): Plugin;
41
+ export default browserPlugin;
42
+ export function httpPlugin(options?: { cache?: PersistentCache; log?: Logger; fetch?: typeof fetch }): Plugin;
43
+ export function createTransformer(options: {
44
+ files: FileSource; esbuild: unknown; deps?: Record<string, string>; load?: CompilerLoader; prod?: boolean; log?: Logger;
45
+ }): (path: string, content: string | Uint8Array) => Promise<{ contents: string; loader: string; resolveDir: string } | { errors: unknown[] } | null>;
46
+ export function compilerLoader(templates?: Partial<Record<'svelte' | 'vue' | 'sass' | 'less' | 'yaml', string>>): CompilerLoader;
47
+ export const DEFAULT_COMPILERS: Record<'svelte' | 'vue' | 'sass' | 'less' | 'yaml', string>;
48
+ export const TRANSFORM_EXT: RegExp;
49
+ export const SHARED_RUNTIMES: RegExp;
50
+ export function parseSpecifier(spec: string): { name: string; sub: string };
51
+ export function esmShUrl(cdn: string, name: string, range: string, sub?: string, options?: { shared?: boolean; target?: string }): string;
package/src/index.js CHANGED
@@ -1,96 +1,97 @@
1
- // esbuild-plugin-browser
2
- // esbuild-wasm をブラウザで動かすためのプラグイン。ファイルシステムが無い環境で、
3
- // - 手元のファイル(Map など)を読む
4
- // - npm のパッケージを esm.sh から読む(package.json のバージョンに合わせる)
5
- // - svelte / vue / react などの「ランタイムを共有するパッケージ」を二重に入れない
6
- // - .svelte / .svelte.ts / .vue / .scss / .sass / .less / .yaml を変換する(コンパイラは使う時に CDN から)
7
- import { dirname, ext, normalize } from './path.js';
8
- import { parseSpecifier, esmShUrl, SHARED_RUNTIMES } from './npm.js';
9
- import { httpPlugin } from './http.js';
10
- import { createTransformer, compilerLoader, DEFAULT_COMPILERS, TRANSFORM_EXT } from './transformers.js';
11
-
12
- export { httpPlugin, createTransformer, compilerLoader, DEFAULT_COMPILERS, TRANSFORM_EXT, parseSpecifier, esmShUrl, SHARED_RUNTIMES };
13
-
14
- const LOADERS = { ts: 'ts', mts: 'ts', cts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', cjs: 'js', jsx: 'jsx', json: 'json', css: 'css', svg: 'text', html: 'text', txt: 'text', md: 'text' };
15
- const EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json', '.css', '.svelte.ts', '.svelte.js', '/index.ts', '/index.tsx', '/index.js'];
16
-
17
- function readDeps(files) {
18
- if (!files.has('package.json')) return {};
19
- try {
20
- const v = files.get('package.json');
21
- return JSON.parse(typeof v === 'string' ? v : new TextDecoder().decode(v)).dependencies || {};
22
- } catch { return {}; }
23
- }
24
-
25
- /**
26
- * @param {object} o
27
- * @param {{ has(path: string): boolean, get(path: string): string|Uint8Array|undefined }} o.files
28
- * ファイル(パスは "src/main.ts" のように先頭の / なし)。Map をそのまま渡せる。Uint8Array はバイナリとして data URL で読む
29
- * @param {object} [o.esbuild] esbuild 本体。transform を使うときに要る(.svelte.ts の TS を剥がす)
30
- * @param {Record<string,string>} [o.dependencies] 省くと files の package.json から読む
31
- * @param {string} [o.cdn] npm の配信元(既定: https://esm.sh)
32
- * @param {RegExp} [o.sharedRuntimes]
33
- * @param {boolean|object} [o.transform] .svelte などの変換(既定: 有効)。{ load } でコンパイラの読み方を変えられる
34
- * @param {boolean} [o.prod]
35
- * @param {(name: string, sub: string, range: string) => Promise<string|null>|string|null} [o.resolvePackage]
36
- * npm のパッケージを手元のファイルで解決したいとき(node_modules に置いたものなど)。files のパスを返す。null なら CDN から
37
- * @param {{ get(key: string): any, set(key: string, value: string): any }} [o.cache] CDN から取ったものの永続キャッシュ
38
- * @param {{ info?(t: string): void, warn?(t: string): void }} [o.log]
39
- */
40
- export function browserPlugin(o) {
41
- const {
42
- files, esbuild, cdn = 'https://esm.sh', sharedRuntimes = SHARED_RUNTIMES,
43
- transform = true, prod = false, resolvePackage, cache, log = {},
44
- } = o;
45
- if (!files || typeof files.has !== 'function' || typeof files.get !== 'function') throw new Error('files には has / get を持つもの(Map など)を渡してください');
46
- const deps = o.dependencies || readDeps(files);
47
- const transformer = transform && esbuild
48
- ? createTransformer({ files, esbuild, deps, prod, log, ...(typeof transform === 'object' ? transform : {}) })
49
- : null;
50
- const http = httpPlugin({ cache, log });
51
- const warned = new Set();
52
-
53
- return {
54
- name: 'browser',
55
- setup(b) {
56
- http.setup(b);
57
- // 相対パス・絶対パス
58
- b.onResolve({ filter: /^(\.{0,2}\/|[^@\w])/ }, (a) => {
59
- if (a.namespace === 'http') return undefined;
60
- const base = normalize(a.path.startsWith('/') ? a.path : `${dirname(a.importer)}/${a.path}`);
61
- for (const e of EXTS) if (files.has(base + e)) return { path: base + e, namespace: 'vfs' };
62
- // ESM の書き方("./foo.js" と書いて foo.ts を指す)
63
- const ts = base.replace(/\.js$/, '.ts');
64
- if (ts !== base && files.has(ts)) return { path: ts, namespace: 'vfs' };
65
- return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
66
- });
67
- // npm のパッケージ
68
- b.onResolve({ filter: /^[@\w]/ }, async (a) => {
69
- if (a.kind === 'entry-point') return { path: normalize(a.path), namespace: 'vfs' };
70
- if (a.namespace === 'http') return undefined;
71
- const { name, sub } = parseSpecifier(a.path);
72
- const range = deps[name];
73
- if (!range) {
74
- if (!warned.has(name)) { warned.add(name); log.warn?.(`${name} が package.json にありません(最新版を CDN から読みます)`); }
75
- return { path: esmShUrl(cdn, name, '', sub, { shared: sharedRuntimes.test(name) }), namespace: 'http' };
76
- }
77
- if (sharedRuntimes.test(name)) return { path: esmShUrl(cdn, name, range, sub, { shared: true }), namespace: 'http' };
78
- const local = resolvePackage && (await resolvePackage(name, sub, range));
79
- if (local) return { path: normalize(local), namespace: 'vfs' };
80
- return { path: esmShUrl(cdn, name, range, sub), namespace: 'http' };
81
- });
82
- b.onLoad({ filter: /.*/, namespace: 'vfs' }, async (a) => {
83
- if (!files.has(a.path)) return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
84
- const content = files.get(a.path);
85
- if (transformer) {
86
- const t = await transformer(a.path, content);
87
- if (t) return t;
88
- }
89
- if (content instanceof Uint8Array) return { contents: content, loader: 'dataurl' };
90
- return { contents: content, loader: LOADERS[ext(a.path)] || 'text', resolveDir: '/' + dirname(a.path) };
91
- });
92
- },
93
- };
94
- }
95
-
96
- export default browserPlugin;
1
+ // esbuild-plugin-browser
2
+ // esbuild-wasm をブラウザで動かすためのプラグイン。ファイルシステムが無い環境で、
3
+ // - 手元のファイル(Map など)を読む
4
+ // - npm のパッケージを esm.sh から読む(package.json のバージョンに合わせる)
5
+ // - svelte / vue / react などの「ランタイムを共有するパッケージ」を二重に入れない
6
+ // - .svelte / .svelte.ts / .vue / .scss / .sass / .less / .yaml を変換する(コンパイラは使う時に CDN から)
7
+ import { dirname, ext, normalize } from './path.js';
8
+ import { parseSpecifier, esmShUrl, SHARED_RUNTIMES } from './npm.js';
9
+ import { httpPlugin } from './http.js';
10
+ import { createTransformer, compilerLoader, DEFAULT_COMPILERS, TRANSFORM_EXT } from './transformers.js';
11
+
12
+ export { httpPlugin, createTransformer, compilerLoader, DEFAULT_COMPILERS, TRANSFORM_EXT, parseSpecifier, esmShUrl, SHARED_RUNTIMES };
13
+
14
+ const LOADERS = { ts: 'ts', mts: 'ts', cts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', cjs: 'js', jsx: 'jsx', json: 'json', css: 'css', svg: 'text', html: 'text', txt: 'text', md: 'text' };
15
+ const EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json', '.css', '.svelte.ts', '.svelte.js', '/index.ts', '/index.tsx', '/index.js'];
16
+
17
+ function readDeps(files) {
18
+ if (!files.has('package.json')) return {};
19
+ try {
20
+ const v = files.get('package.json');
21
+ return JSON.parse(typeof v === 'string' ? v : new TextDecoder().decode(v)).dependencies || {};
22
+ } catch { return {}; }
23
+ }
24
+
25
+ /**
26
+ * @param {object} o
27
+ * @param {{ has(path: string): boolean, get(path: string): string|Uint8Array|undefined }} o.files
28
+ * ファイル(パスは "src/main.ts" のように先頭の / なし)。Map をそのまま渡せる。Uint8Array はバイナリとして data URL で読む
29
+ * @param {object} [o.esbuild] esbuild 本体。transform を使うときに要る(.svelte.ts の TS を剥がす)
30
+ * @param {Record<string,string>} [o.dependencies] 省くと files の package.json から読む
31
+ * @param {string} [o.cdn] npm の配信元(既定: https://esm.sh)
32
+ * @param {RegExp} [o.sharedRuntimes]
33
+ * @param {boolean|object} [o.transform] .svelte などの変換(既定: 有効)。{ load } でコンパイラの読み方を変えられる
34
+ * @param {boolean} [o.prod]
35
+ * @param {(name: string, sub: string, range: string) => Promise<string|null>|string|null} [o.resolvePackage]
36
+ * npm のパッケージを手元のファイルで解決したいとき(node_modules に置いたものなど)。files のパスを返す。null なら CDN から
37
+ * @param {{ get(key: string): any, set(key: string, value: string): any }} [o.cache] CDN から取ったものの永続キャッシュ
38
+ * @param {{ info?(t: string): void, warn?(t: string): void }} [o.log]
39
+ * @param {typeof fetch} [o.fetch] CDN から取るときの fetch(中身を確かめる fetch に差し替えるなど)
40
+ */
41
+ export function browserPlugin(o) {
42
+ const {
43
+ files, esbuild, cdn = 'https://esm.sh', sharedRuntimes = SHARED_RUNTIMES,
44
+ transform = true, prod = false, resolvePackage, cache, log = {},
45
+ } = o;
46
+ if (!files || typeof files.has !== 'function' || typeof files.get !== 'function') throw new Error('files には has / get を持つもの(Map など)を渡してください');
47
+ const deps = o.dependencies || readDeps(files);
48
+ const transformer = transform && esbuild
49
+ ? createTransformer({ files, esbuild, deps, prod, log, ...(typeof transform === 'object' ? transform : {}) })
50
+ : null;
51
+ const http = httpPlugin({ cache, log, fetch: o.fetch });
52
+ const warned = new Set();
53
+
54
+ return {
55
+ name: 'browser',
56
+ setup(b) {
57
+ http.setup(b);
58
+ // 相対パス・絶対パス
59
+ b.onResolve({ filter: /^(\.{0,2}\/|[^@\w])/ }, (a) => {
60
+ if (a.namespace === 'http') return undefined;
61
+ const base = normalize(a.path.startsWith('/') ? a.path : `${dirname(a.importer)}/${a.path}`);
62
+ for (const e of EXTS) if (files.has(base + e)) return { path: base + e, namespace: 'vfs' };
63
+ // ESM の書き方("./foo.js" と書いて foo.ts を指す)
64
+ const ts = base.replace(/\.js$/, '.ts');
65
+ if (ts !== base && files.has(ts)) return { path: ts, namespace: 'vfs' };
66
+ return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
67
+ });
68
+ // npm のパッケージ
69
+ b.onResolve({ filter: /^[@\w]/ }, async (a) => {
70
+ if (a.kind === 'entry-point') return { path: normalize(a.path), namespace: 'vfs' };
71
+ if (a.namespace === 'http') return undefined;
72
+ const { name, sub } = parseSpecifier(a.path);
73
+ const range = deps[name];
74
+ if (!range) {
75
+ if (!warned.has(name)) { warned.add(name); log.warn?.(`${name} が package.json にありません(最新版を CDN から読みます)`); }
76
+ return { path: esmShUrl(cdn, name, '', sub, { shared: sharedRuntimes.test(name) }), namespace: 'http' };
77
+ }
78
+ if (sharedRuntimes.test(name)) return { path: esmShUrl(cdn, name, range, sub, { shared: true }), namespace: 'http' };
79
+ const local = resolvePackage && (await resolvePackage(name, sub, range));
80
+ if (local) return { path: normalize(local), namespace: 'vfs' };
81
+ return { path: esmShUrl(cdn, name, range, sub), namespace: 'http' };
82
+ });
83
+ b.onLoad({ filter: /.*/, namespace: 'vfs' }, async (a) => {
84
+ if (!files.has(a.path)) return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
85
+ const content = files.get(a.path);
86
+ if (transformer) {
87
+ const t = await transformer(a.path, content);
88
+ if (t) return t;
89
+ }
90
+ if (content instanceof Uint8Array) return { contents: content, loader: 'dataurl' };
91
+ return { contents: content, loader: LOADERS[ext(a.path)] || 'text', resolveDir: '/' + dirname(a.path) };
92
+ });
93
+ },
94
+ };
95
+ }
96
+
97
+ export default browserPlugin;
package/src/npm.js CHANGED
@@ -1,22 +1,22 @@
1
- // "@scope/name/sub/path" → { name: "@scope/name", sub: "/sub/path" }
2
- export function parseSpecifier(spec) {
3
- const parts = spec.split('/');
4
- const n = spec.startsWith('@') ? 2 : 1;
5
- return { name: parts.slice(0, n).join('/'), sub: parts.length > n ? '/' + parts.slice(n).join('/') : '' };
6
- }
7
-
8
- /**
9
- * 状態をモジュールで共有するランタイム。サブパスごとに依存を抱え込んだ(?bundle)版を読むと、
10
- * 同じランタイムが二重に入って壊れる。これらは esm.sh が分けて配るモジュールのまま読む。
11
- */
12
- export const SHARED_RUNTIMES = /^(svelte|vue|@vue\/.+|react|react-dom|preact|solid-js|lit|@lit\/.+)$/;
13
-
14
- /**
15
- * esm.sh の URL を作る
16
- * @param {{ shared?: boolean, target?: string }} [o] shared: 依存を抱え込まない版
17
- */
18
- export function esmShUrl(cdn, name, range, sub = '', { shared = false, target = 'es2020' } = {}) {
19
- const base = `${cdn}/${name}${range ? '@' + range : ''}${sub}`;
20
- if (/\.css$/.test(sub)) return base;
21
- return `${base}?target=${target}${shared ? '' : '&bundle'}`;
22
- }
1
+ // "@scope/name/sub/path" → { name: "@scope/name", sub: "/sub/path" }
2
+ export function parseSpecifier(spec) {
3
+ const parts = spec.split('/');
4
+ const n = spec.startsWith('@') ? 2 : 1;
5
+ return { name: parts.slice(0, n).join('/'), sub: parts.length > n ? '/' + parts.slice(n).join('/') : '' };
6
+ }
7
+
8
+ /**
9
+ * 状態をモジュールで共有するランタイム。サブパスごとに依存を抱え込んだ(?bundle)版を読むと、
10
+ * 同じランタイムが二重に入って壊れる。これらは esm.sh が分けて配るモジュールのまま読む。
11
+ */
12
+ export const SHARED_RUNTIMES = /^(svelte|vue|@vue\/.+|react|react-dom|preact|solid-js|lit|@lit\/.+)$/;
13
+
14
+ /**
15
+ * esm.sh の URL を作る
16
+ * @param {{ shared?: boolean, target?: string }} [o] shared: 依存を抱え込まない版
17
+ */
18
+ export function esmShUrl(cdn, name, range, sub = '', { shared = false, target = 'es2020' } = {}) {
19
+ const base = `${cdn}/${name}${range ? '@' + range : ''}${sub}`;
20
+ if (/\.css$/.test(sub)) return base;
21
+ return `${base}?target=${target}${shared ? '' : '&bundle'}`;
22
+ }
package/src/path.js CHANGED
@@ -1,7 +1,7 @@
1
- export const dirname = (p) => p.split('/').slice(0, -1).join('/');
2
- export const normalize = (p) => {
3
- const out = [];
4
- for (const s of String(p).split('/')) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
5
- return out.join('/');
6
- };
7
- export const ext = (p) => p.split('.').pop().toLowerCase();
1
+ export const dirname = (p) => p.split('/').slice(0, -1).join('/');
2
+ export const normalize = (p) => {
3
+ const out = [];
4
+ for (const s of String(p).split('/')) { if (!s || s === '.') continue; if (s === '..') out.pop(); else out.push(s); }
5
+ return out.join('/');
6
+ };
7
+ export const ext = (p) => p.split('.').pop().toLowerCase();
@@ -1,189 +1,189 @@
1
- // esbuild に渡す前に変換するファイル(コンパイラは使う時に CDN から読む)
2
- // .svelte Svelte 5 のコンポーネント(CSS は JS に入れて実行時に差し込む)
3
- // .svelte.ts/.svelte.js Svelte 5 のルーン入りモジュール
4
- // .vue Vue 3 の SFC(<script setup> / TS / scoped CSS / <style lang="scss">)
5
- // .scss / .sass / .less CSS に
6
- // .yaml / .yml export default のオブジェクトに
7
- // svelte と vue のコンパイラは、package.json に書いたランタイムと同じバージョンを使う。
8
-
9
- // 既定のコンパイラの読み込み先(:range は package.json のバージョン範囲)
10
- export const DEFAULT_COMPILERS = {
11
- svelte: 'https://esm.sh/svelte@:range/compiler?target=es2020&bundle',
12
- vue: 'https://esm.sh/@vue/compiler-sfc@:range?target=es2020&bundle',
13
- sass: 'https://esm.sh/sass@1?target=es2020&bundle',
14
- less: 'https://esm.sh/less@4?target=es2020&bundle',
15
- yaml: 'https://esm.sh/js-yaml@4?target=es2020&bundle',
16
- };
17
- const loaded = new Map();
18
- /** URL のひな形からコンパイラを読む関数を作る(同じ URL は1回だけ読む) */
19
- export function compilerLoader(templates = DEFAULT_COMPILERS) {
20
- return (name, range = '') => {
21
- const url = (templates[name] || DEFAULT_COMPILERS[name]).replace(':range', range);
22
- if (!loaded.has(url)) loaded.set(url, import(/* @vite-ignore */ url).catch((e) => { loaded.delete(url); throw new Error(`${name} のコンパイラを読めませんでした: ${e.message}`); }));
23
- return loaded.get(url);
24
- };
25
- }
26
- import { dirname, normalize } from './path.js';
27
-
28
- export const TRANSFORM_EXT = /\.(svelte|svelte\.[jt]s|vue|s[ac]ss|less|ya?ml)$/;
29
-
30
- const lineCol = (text, offset) => {
31
- const before = text.slice(0, offset).split('\n');
32
- return { line: before.length, column: before[before.length - 1].length };
33
- };
34
- const fail = (path, message, loc) => ({ errors: [{ text: message, location: loc ? { file: path, line: loc.line, column: loc.column ?? 0 } : { file: path } }] });
35
- const injectCss = (css, id) => css.trim()
36
- ? `\n;(()=>{if(typeof document==='undefined'||document.getElementById(${JSON.stringify(id)}))return;const s=document.createElement('style');s.id=${JSON.stringify(id)};s.textContent=${JSON.stringify(css)};document.head.appendChild(s)})();\n`
37
- : '';
38
- const hashId = (s) => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; return h.toString(36); };
39
-
40
- /**
41
- * @param {object} o
42
- * @param {{ has(path: string): boolean, get(path: string): string|Uint8Array|undefined }} o.files
43
- * ファイルを読む口(Map でいい)。@use / @import の解決に使う
44
- * @param {object} o.esbuild esbuild(.svelte.ts の TS を剥がすのに使う)
45
- * @param {Record<string,string>} [o.deps] package.json の dependencies(svelte / vue のバージョン合わせ)
46
- * @param {(name:string, range?:string)=>Promise<any>} [o.load] コンパイラを読む(既定: esm.sh から)
47
- * @param {boolean} [o.prod]
48
- * @param {{ warn?(t: string): void }} [o.log]
49
- */
50
- export function createTransformer({ files, log = {}, prod = false, load = compilerLoader(), esbuild, deps = {} }) {
51
- const textOf = (p) => { const v = files.get(p); return typeof v === 'string' ? v : new TextDecoder().decode(v); };
52
- const need = (name) => {
53
- if (!deps[name]) throw new Error(`${name} が package.json にありません。npm install ${name} してください(ランタイムとコンパイラのバージョンをそろえるため)`);
54
- return deps[name];
55
- };
56
-
57
- // ---- Sass ----
58
- async function compileSass(path, text) {
59
- const sass = await load('sass');
60
- const toUrl = (p) => new URL(`file:///${p}`);
61
- const candidates = (p) => {
62
- const d = dirname(p), b = p.split('/').pop();
63
- const bases = /\.(s[ac]ss|css)$/.test(b) ? [p] : [`${p}.scss`, `${p}.sass`, `${p}.css`, `${d ? d + '/' : ''}_${b}.scss`, `${d ? d + '/' : ''}_${b}.sass`, `${p}/index.scss`, `${p}/_index.scss`];
64
- return bases.map(normalize);
65
- };
66
- const importer = {
67
- canonicalize(url, ctx) {
68
- const base = ctx && ctx.containingUrl ? ctx.containingUrl.pathname.slice(1) : path;
69
- const raw = url.startsWith('file:///') ? url.slice(8) : normalize(`${dirname(base)}/${url}`);
70
- const hit = candidates(raw).find((c) => files.has(c));
71
- return hit ? toUrl(hit) : null;
72
- },
73
- load(u) {
74
- const p = decodeURIComponent(u.pathname.slice(1));
75
- return { contents: textOf(p), syntax: p.endsWith('.sass') ? 'indented' : p.endsWith('.css') ? 'css' : 'scss' };
76
- },
77
- };
78
- try {
79
- const r = sass.compileString(text, { url: toUrl(path), syntax: path.endsWith('.sass') ? 'indented' : 'scss', importers: [importer], style: prod ? 'compressed' : 'expanded', silenceDeprecations: ['import'] });
80
- return r.css;
81
- } catch (e) {
82
- const s = e.span;
83
- throw Object.assign(new Error(e.sassMessage || e.message), { loc: s ? { line: s.start.line + 1, column: s.start.column } : null, file: s && s.url ? s.url.pathname.slice(1) : path });
84
- }
85
- }
86
-
87
- // ---- Less ----
88
- async function compileLess(path, text) {
89
- const mod = await load('less');
90
- const less = mod.default || mod;
91
- const vfs = {
92
- install(lessObj, pm) {
93
- class VfsFileManager extends lessObj.FileManager {
94
- supports() { return true; }
95
- supportsSync() { return false; }
96
- loadFile(filename, currentDirectory) {
97
- const base = normalize(`${currentDirectory || dirname(path)}/${filename}`);
98
- const hit = [base, `${base}.less`, `${base}.css`].find((c) => files.has(c));
99
- return hit ? Promise.resolve({ contents: textOf(hit), filename: hit }) : Promise.reject({ type: 'File', message: `ファイルが見つかりません: ${filename}` });
100
- }
101
- }
102
- pm.addFileManager(new VfsFileManager());
103
- },
104
- };
105
- try {
106
- return (await less.render(text, { filename: path, plugins: [vfs], compress: prod })).css;
107
- } catch (e) {
108
- throw Object.assign(new Error(e.message), { loc: e.line ? { line: e.line, column: e.column || 0 } : null, file: e.filename || path });
109
- }
110
- }
111
-
112
- // ---- Svelte ----
113
- async function compileSvelte(path, text) {
114
- const svelte = await load('svelte', need('svelte'));
115
- const warn = (w) => log.warn?.(`${path}${w.start ? `:${w.start.line}:${w.start.column + 1}` : ''} ${w.message}`);
116
- try {
117
- if (/\.svelte\.[jt]s$/.test(path)) {
118
- const js = path.endsWith('.ts') ? (await esbuild.transform(text, { loader: 'ts', sourcefile: path })).code : text;
119
- const r = svelte.compileModule(js, { filename: path, generate: 'client', dev: !prod });
120
- r.warnings.forEach(warn);
121
- return { contents: r.js.code, loader: 'js' };
122
- }
123
- const r = svelte.compile(text, { filename: path, generate: 'client', dev: !prod, css: 'injected' });
124
- r.warnings.forEach(warn);
125
- return { contents: r.js.code, loader: 'js' };
126
- } catch (e) {
127
- throw Object.assign(new Error(e.message), { loc: e.start ? { line: e.start.line, column: e.start.column } : null });
128
- }
129
- }
130
-
131
- // ---- Vue ----
132
- async function compileVue(path, text) {
133
- const sfc = await load('vue', need('vue'));
134
- const { descriptor, errors } = sfc.parse(text, { filename: path });
135
- if (errors.length) {
136
- const e = errors[0];
137
- throw Object.assign(new Error(e.message), { loc: e.loc ? { line: e.loc.start.line, column: e.loc.start.column - 1 } : null });
138
- }
139
- const id = hashId(path);
140
- const scoped = descriptor.styles.some((s) => s.scoped);
141
- let code = '', lang = 'js';
142
- if (descriptor.script || descriptor.scriptSetup) {
143
- const s = sfc.compileScript(descriptor, { id, inlineTemplate: true, isProd: prod, genDefaultAs: '__sfc__', templateOptions: { compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } } });
144
- code = s.content;
145
- lang = /tsx?/.test((descriptor.scriptSetup || descriptor.script).lang || '') ? 'ts' : 'js';
146
- } else code = 'const __sfc__ = {};';
147
- if (descriptor.template && !descriptor.scriptSetup) {
148
- const t = sfc.compileTemplate({ source: descriptor.template.content, filename: path, id, scoped, isProd: prod, compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } });
149
- if (t.errors.length) throw new Error(String(t.errors[0].message || t.errors[0]));
150
- code += `\n${t.code.replace(/\nexport (function|const) (render|ssrRender)/, '\n$1 $2')}\n__sfc__.render = render;`;
151
- }
152
- if (scoped) code += `\n__sfc__.__scopeId = "data-v-${id}";`;
153
- let css = '';
154
- for (const st of descriptor.styles) {
155
- let source = st.content;
156
- if (/^s[ac]ss$/.test(st.lang || '')) source = await compileSass(`${path}.${st.lang}`, source);
157
- else if (st.lang === 'less') source = await compileLess(`${path}.less`, source);
158
- const r = sfc.compileStyle({ source, filename: path, id: `data-v-${id}`, scoped: st.scoped, isProd: prod });
159
- if (r.errors.length) throw new Error(String(r.errors[0].message || r.errors[0]));
160
- css += r.code + '\n';
161
- }
162
- code += injectCss(css, `vue-${id}`);
163
- code += '\nexport default __sfc__;\n';
164
- return { contents: code, loader: lang };
165
- }
166
-
167
- // ---- YAML ----
168
- async function compileYaml(path, text) {
169
- const yaml = await load('yaml');
170
- try { return { contents: `export default ${JSON.stringify((yaml.load || yaml.default.load)(text))};`, loader: 'js' }; }
171
- catch (e) { throw Object.assign(new Error(e.reason || e.message), { loc: e.mark ? { line: e.mark.line + 1, column: e.mark.column } : null }); }
172
- }
173
-
174
- /** @returns {Promise<{contents:string, loader:string, resolveDir:string}|{errors:any[]}|null>} */
175
- return async function transform(path, text) {
176
- if (!TRANSFORM_EXT.test(path) || typeof text !== 'string') return null;
177
- try {
178
- let r;
179
- if (/\.svelte(\.[jt]s)?$/.test(path)) r = await compileSvelte(path, text);
180
- else if (path.endsWith('.vue')) r = await compileVue(path, text);
181
- else if (/\.s[ac]ss$/.test(path)) r = { contents: await compileSass(path, text), loader: 'css' };
182
- else if (path.endsWith('.less')) r = { contents: await compileLess(path, text), loader: 'css' };
183
- else r = await compileYaml(path, text);
184
- return { ...r, resolveDir: '/' + dirname(path) };
185
- } catch (e) {
186
- return fail(e.file || path, e.message.split('\n')[0], e.loc);
187
- }
188
- };
189
- }
1
+ // esbuild に渡す前に変換するファイル(コンパイラは使う時に CDN から読む)
2
+ // .svelte Svelte 5 のコンポーネント(CSS は JS に入れて実行時に差し込む)
3
+ // .svelte.ts/.svelte.js Svelte 5 のルーン入りモジュール
4
+ // .vue Vue 3 の SFC(<script setup> / TS / scoped CSS / <style lang="scss">)
5
+ // .scss / .sass / .less CSS に
6
+ // .yaml / .yml export default のオブジェクトに
7
+ // svelte と vue のコンパイラは、package.json に書いたランタイムと同じバージョンを使う。
8
+
9
+ // 既定のコンパイラの読み込み先(:range は package.json のバージョン範囲)
10
+ export const DEFAULT_COMPILERS = {
11
+ svelte: 'https://esm.sh/svelte@:range/compiler?target=es2020&bundle',
12
+ vue: 'https://esm.sh/@vue/compiler-sfc@:range?target=es2020&bundle',
13
+ sass: 'https://esm.sh/sass@1?target=es2020&bundle',
14
+ less: 'https://esm.sh/less@4?target=es2020&bundle',
15
+ yaml: 'https://esm.sh/js-yaml@4?target=es2020&bundle',
16
+ };
17
+ const loaded = new Map();
18
+ /** URL のひな形からコンパイラを読む関数を作る(同じ URL は1回だけ読む) */
19
+ export function compilerLoader(templates = DEFAULT_COMPILERS) {
20
+ return (name, range = '') => {
21
+ const url = (templates[name] || DEFAULT_COMPILERS[name]).replace(':range', range);
22
+ if (!loaded.has(url)) loaded.set(url, import(/* @vite-ignore */ url).catch((e) => { loaded.delete(url); throw new Error(`${name} のコンパイラを読めませんでした: ${e.message}`); }));
23
+ return loaded.get(url);
24
+ };
25
+ }
26
+ import { dirname, normalize } from './path.js';
27
+
28
+ export const TRANSFORM_EXT = /\.(svelte|svelte\.[jt]s|vue|s[ac]ss|less|ya?ml)$/;
29
+
30
+ const lineCol = (text, offset) => {
31
+ const before = text.slice(0, offset).split('\n');
32
+ return { line: before.length, column: before[before.length - 1].length };
33
+ };
34
+ const fail = (path, message, loc) => ({ errors: [{ text: message, location: loc ? { file: path, line: loc.line, column: loc.column ?? 0 } : { file: path } }] });
35
+ const injectCss = (css, id) => css.trim()
36
+ ? `\n;(()=>{if(typeof document==='undefined'||document.getElementById(${JSON.stringify(id)}))return;const s=document.createElement('style');s.id=${JSON.stringify(id)};s.textContent=${JSON.stringify(css)};document.head.appendChild(s)})();\n`
37
+ : '';
38
+ const hashId = (s) => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0; return h.toString(36); };
39
+
40
+ /**
41
+ * @param {object} o
42
+ * @param {{ has(path: string): boolean, get(path: string): string|Uint8Array|undefined }} o.files
43
+ * ファイルを読む口(Map でいい)。@use / @import の解決に使う
44
+ * @param {object} o.esbuild esbuild(.svelte.ts の TS を剥がすのに使う)
45
+ * @param {Record<string,string>} [o.deps] package.json の dependencies(svelte / vue のバージョン合わせ)
46
+ * @param {(name:string, range?:string)=>Promise<any>} [o.load] コンパイラを読む(既定: esm.sh から)
47
+ * @param {boolean} [o.prod]
48
+ * @param {{ warn?(t: string): void }} [o.log]
49
+ */
50
+ export function createTransformer({ files, log = {}, prod = false, load = compilerLoader(), esbuild, deps = {} }) {
51
+ const textOf = (p) => { const v = files.get(p); return typeof v === 'string' ? v : new TextDecoder().decode(v); };
52
+ const need = (name) => {
53
+ if (!deps[name]) throw new Error(`${name} が package.json にありません。npm install ${name} してください(ランタイムとコンパイラのバージョンをそろえるため)`);
54
+ return deps[name];
55
+ };
56
+
57
+ // ---- Sass ----
58
+ async function compileSass(path, text) {
59
+ const sass = await load('sass');
60
+ const toUrl = (p) => new URL(`file:///${p}`);
61
+ const candidates = (p) => {
62
+ const d = dirname(p), b = p.split('/').pop();
63
+ const bases = /\.(s[ac]ss|css)$/.test(b) ? [p] : [`${p}.scss`, `${p}.sass`, `${p}.css`, `${d ? d + '/' : ''}_${b}.scss`, `${d ? d + '/' : ''}_${b}.sass`, `${p}/index.scss`, `${p}/_index.scss`];
64
+ return bases.map(normalize);
65
+ };
66
+ const importer = {
67
+ canonicalize(url, ctx) {
68
+ const base = ctx && ctx.containingUrl ? ctx.containingUrl.pathname.slice(1) : path;
69
+ const raw = url.startsWith('file:///') ? url.slice(8) : normalize(`${dirname(base)}/${url}`);
70
+ const hit = candidates(raw).find((c) => files.has(c));
71
+ return hit ? toUrl(hit) : null;
72
+ },
73
+ load(u) {
74
+ const p = decodeURIComponent(u.pathname.slice(1));
75
+ return { contents: textOf(p), syntax: p.endsWith('.sass') ? 'indented' : p.endsWith('.css') ? 'css' : 'scss' };
76
+ },
77
+ };
78
+ try {
79
+ const r = sass.compileString(text, { url: toUrl(path), syntax: path.endsWith('.sass') ? 'indented' : 'scss', importers: [importer], style: prod ? 'compressed' : 'expanded', silenceDeprecations: ['import'] });
80
+ return r.css;
81
+ } catch (e) {
82
+ const s = e.span;
83
+ throw Object.assign(new Error(e.sassMessage || e.message), { loc: s ? { line: s.start.line + 1, column: s.start.column } : null, file: s && s.url ? s.url.pathname.slice(1) : path });
84
+ }
85
+ }
86
+
87
+ // ---- Less ----
88
+ async function compileLess(path, text) {
89
+ const mod = await load('less');
90
+ const less = mod.default || mod;
91
+ const vfs = {
92
+ install(lessObj, pm) {
93
+ class VfsFileManager extends lessObj.FileManager {
94
+ supports() { return true; }
95
+ supportsSync() { return false; }
96
+ loadFile(filename, currentDirectory) {
97
+ const base = normalize(`${currentDirectory || dirname(path)}/${filename}`);
98
+ const hit = [base, `${base}.less`, `${base}.css`].find((c) => files.has(c));
99
+ return hit ? Promise.resolve({ contents: textOf(hit), filename: hit }) : Promise.reject({ type: 'File', message: `ファイルが見つかりません: ${filename}` });
100
+ }
101
+ }
102
+ pm.addFileManager(new VfsFileManager());
103
+ },
104
+ };
105
+ try {
106
+ return (await less.render(text, { filename: path, plugins: [vfs], compress: prod })).css;
107
+ } catch (e) {
108
+ throw Object.assign(new Error(e.message), { loc: e.line ? { line: e.line, column: e.column || 0 } : null, file: e.filename || path });
109
+ }
110
+ }
111
+
112
+ // ---- Svelte ----
113
+ async function compileSvelte(path, text) {
114
+ const svelte = await load('svelte', need('svelte'));
115
+ const warn = (w) => log.warn?.(`${path}${w.start ? `:${w.start.line}:${w.start.column + 1}` : ''} ${w.message}`);
116
+ try {
117
+ if (/\.svelte\.[jt]s$/.test(path)) {
118
+ const js = path.endsWith('.ts') ? (await esbuild.transform(text, { loader: 'ts', sourcefile: path })).code : text;
119
+ const r = svelte.compileModule(js, { filename: path, generate: 'client', dev: !prod });
120
+ r.warnings.forEach(warn);
121
+ return { contents: r.js.code, loader: 'js' };
122
+ }
123
+ const r = svelte.compile(text, { filename: path, generate: 'client', dev: !prod, css: 'injected' });
124
+ r.warnings.forEach(warn);
125
+ return { contents: r.js.code, loader: 'js' };
126
+ } catch (e) {
127
+ throw Object.assign(new Error(e.message), { loc: e.start ? { line: e.start.line, column: e.start.column } : null });
128
+ }
129
+ }
130
+
131
+ // ---- Vue ----
132
+ async function compileVue(path, text) {
133
+ const sfc = await load('vue', need('vue'));
134
+ const { descriptor, errors } = sfc.parse(text, { filename: path });
135
+ if (errors.length) {
136
+ const e = errors[0];
137
+ throw Object.assign(new Error(e.message), { loc: e.loc ? { line: e.loc.start.line, column: e.loc.start.column - 1 } : null });
138
+ }
139
+ const id = hashId(path);
140
+ const scoped = descriptor.styles.some((s) => s.scoped);
141
+ let code = '', lang = 'js';
142
+ if (descriptor.script || descriptor.scriptSetup) {
143
+ const s = sfc.compileScript(descriptor, { id, inlineTemplate: true, isProd: prod, genDefaultAs: '__sfc__', templateOptions: { compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } } });
144
+ code = s.content;
145
+ lang = /tsx?/.test((descriptor.scriptSetup || descriptor.script).lang || '') ? 'ts' : 'js';
146
+ } else code = 'const __sfc__ = {};';
147
+ if (descriptor.template && !descriptor.scriptSetup) {
148
+ const t = sfc.compileTemplate({ source: descriptor.template.content, filename: path, id, scoped, isProd: prod, compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } });
149
+ if (t.errors.length) throw new Error(String(t.errors[0].message || t.errors[0]));
150
+ code += `\n${t.code.replace(/\nexport (function|const) (render|ssrRender)/, '\n$1 $2')}\n__sfc__.render = render;`;
151
+ }
152
+ if (scoped) code += `\n__sfc__.__scopeId = "data-v-${id}";`;
153
+ let css = '';
154
+ for (const st of descriptor.styles) {
155
+ let source = st.content;
156
+ if (/^s[ac]ss$/.test(st.lang || '')) source = await compileSass(`${path}.${st.lang}`, source);
157
+ else if (st.lang === 'less') source = await compileLess(`${path}.less`, source);
158
+ const r = sfc.compileStyle({ source, filename: path, id: `data-v-${id}`, scoped: st.scoped, isProd: prod });
159
+ if (r.errors.length) throw new Error(String(r.errors[0].message || r.errors[0]));
160
+ css += r.code + '\n';
161
+ }
162
+ code += injectCss(css, `vue-${id}`);
163
+ code += '\nexport default __sfc__;\n';
164
+ return { contents: code, loader: lang };
165
+ }
166
+
167
+ // ---- YAML ----
168
+ async function compileYaml(path, text) {
169
+ const yaml = await load('yaml');
170
+ try { return { contents: `export default ${JSON.stringify((yaml.load || yaml.default.load)(text))};`, loader: 'js' }; }
171
+ catch (e) { throw Object.assign(new Error(e.reason || e.message), { loc: e.mark ? { line: e.mark.line + 1, column: e.mark.column } : null }); }
172
+ }
173
+
174
+ /** @returns {Promise<{contents:string, loader:string, resolveDir:string}|{errors:any[]}|null>} */
175
+ return async function transform(path, text) {
176
+ if (!TRANSFORM_EXT.test(path) || typeof text !== 'string') return null;
177
+ try {
178
+ let r;
179
+ if (/\.svelte(\.[jt]s)?$/.test(path)) r = await compileSvelte(path, text);
180
+ else if (path.endsWith('.vue')) r = await compileVue(path, text);
181
+ else if (/\.s[ac]ss$/.test(path)) r = { contents: await compileSass(path, text), loader: 'css' };
182
+ else if (path.endsWith('.less')) r = { contents: await compileLess(path, text), loader: 'css' };
183
+ else r = await compileYaml(path, text);
184
+ return { ...r, resolveDir: '/' + dirname(path) };
185
+ } catch (e) {
186
+ return fail(e.file || path, e.message.split('\n')[0], e.loc);
187
+ }
188
+ };
189
+ }