kintone-plugin-ide 0.3.0 → 0.3.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.
@@ -1,32 +1,32 @@
1
- // esbuild: http(s) の import を fetch で読む
2
- import { CONFIG } from '../config.js';
3
- import { idbGet, idbSet } from '../util/idb.js';
4
-
5
- // バージョンが確定した URL(/pkg@1.2.3/...)は中身が変わらないので、ブラウザに残しておく
6
- const immutable = (u) => /@\d+\.\d+\.\d+(-[\w.]+)?\//.test(u) && !/[\^~*]/.test(decodeURIComponent(u));
7
-
8
- export function httpPlugin(log, cache = new Map()) {
9
- return {
10
- name: 'http',
11
- setup(b) {
12
- b.onResolve({ filter: /^https?:\/\// }, (a) => ({ path: a.path, namespace: 'http' }));
13
- // esm.sh から読んだモジュールの中の "/pkg@1.0.0/..." や相対パス
14
- b.onResolve({ filter: /.*/, namespace: 'http' }, (a) => ({ path: new URL(a.path, a.importer).href, namespace: 'http' }));
15
- b.onLoad({ filter: /.*/, namespace: 'http' }, async (a) => {
16
- if (!cache.has(a.path)) {
17
- const keep = immutable(a.path);
18
- let text = keep ? await idbGet(`http:${a.path}`) : undefined;
19
- if (text === undefined) {
20
- log?.info(`取得: ${a.path.replace(CONFIG.CDN.npm, 'esm.sh')}`);
21
- const res = await fetch(a.path);
22
- if (!res.ok) throw new Error(`${res.status} ${a.path}`);
23
- text = await res.text();
24
- if (keep) await idbSet(`http:${a.path}`, text);
25
- }
26
- cache.set(a.path, text);
27
- }
28
- return { contents: cache.get(a.path), loader: /\.css(\?|$)/.test(a.path) ? 'css' : 'js' };
29
- });
30
- },
31
- };
32
- }
1
+ // esbuild: http(s) の import を fetch で読む
2
+ import { CONFIG } from '../config.js';
3
+ import { idbGet, idbSet } from '../util/idb.js';
4
+
5
+ // バージョンが確定した URL(/pkg@1.2.3/...)は中身が変わらないので、ブラウザに残しておく
6
+ const immutable = (u) => /@\d+\.\d+\.\d+(-[\w.]+)?\//.test(u) && !/[\^~*]/.test(decodeURIComponent(u));
7
+
8
+ export function httpPlugin(log, cache = new Map()) {
9
+ return {
10
+ name: 'http',
11
+ setup(b) {
12
+ b.onResolve({ filter: /^https?:\/\// }, (a) => ({ path: a.path, namespace: 'http' }));
13
+ // esm.sh から読んだモジュールの中の "/pkg@1.0.0/..." や相対パス
14
+ b.onResolve({ filter: /.*/, namespace: 'http' }, (a) => ({ path: new URL(a.path, a.importer).href, namespace: 'http' }));
15
+ b.onLoad({ filter: /.*/, namespace: 'http' }, async (a) => {
16
+ if (!cache.has(a.path)) {
17
+ const keep = immutable(a.path);
18
+ let text = keep ? await idbGet(`http:${a.path}`) : undefined;
19
+ if (text === undefined) {
20
+ log?.info(`取得: ${a.path.replace(CONFIG.CDN.npm, 'esm.sh')}`);
21
+ const res = await fetch(a.path);
22
+ if (!res.ok) throw new Error(`${res.status} ${a.path}`);
23
+ text = await res.text();
24
+ if (keep) await idbSet(`http:${a.path}`, text);
25
+ }
26
+ cache.set(a.path, text);
27
+ }
28
+ return { contents: cache.get(a.path), loader: /\.css(\?|$)/.test(a.path) ? 'css' : 'js' };
29
+ });
30
+ },
31
+ };
32
+ }
@@ -1,168 +1,168 @@
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
- import { dirname, normalize } from '../util/path.js';
9
- import { isBinary } from '../util/bytes.js';
10
-
11
- export const TRANSFORM_EXT = /\.(svelte|svelte\.[jt]s|vue|s[ac]ss|less|ya?ml)$/;
12
-
13
- const lineCol = (text, offset) => {
14
- const before = text.slice(0, offset).split('\n');
15
- return { line: before.length, column: before[before.length - 1].length };
16
- };
17
- const fail = (path, message, loc) => ({ errors: [{ text: message, location: loc ? { file: path, line: loc.line, column: loc.column ?? 0 } : { file: path } }] });
18
- const injectCss = (css, id) => css.trim()
19
- ? `\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`
20
- : '';
21
- 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); };
22
-
23
- /**
24
- * @param {object} o
25
- * @param {Map<string,string>} o.files
26
- * @param {(name:string, range?:string)=>Promise<any>} o.load コンパイラを読む(deps.js の loadCompiler)
27
- * @param {object} o.esbuild esbuild(TS を剥がすのに使う)
28
- * @param {Record<string,string>} o.deps package.json の dependencies
29
- */
30
- export function createTransformer({ files, log, prod, load, esbuild, deps }) {
31
- const need = (name) => {
32
- if (!deps[name]) throw new Error(`${name} が package.json にありません。npm install ${name} してください(ランタイムとコンパイラのバージョンをそろえるため)`);
33
- return deps[name];
34
- };
35
-
36
- // ---- Sass ----
37
- async function compileSass(path, text) {
38
- const sass = await load('sass');
39
- const toUrl = (p) => new URL(`file:///${p}`);
40
- const candidates = (p) => {
41
- const d = dirname(p), b = p.split('/').pop();
42
- 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`];
43
- return bases.map(normalize);
44
- };
45
- const importer = {
46
- canonicalize(url, ctx) {
47
- const base = ctx && ctx.containingUrl ? ctx.containingUrl.pathname.slice(1) : path;
48
- const raw = url.startsWith('file:///') ? url.slice(8) : normalize(`${dirname(base)}/${url}`);
49
- const hit = candidates(raw).find((c) => files.has(c));
50
- return hit ? toUrl(hit) : null;
51
- },
52
- load(u) {
53
- const p = decodeURIComponent(u.pathname.slice(1));
54
- return { contents: files.get(p), syntax: p.endsWith('.sass') ? 'indented' : p.endsWith('.css') ? 'css' : 'scss' };
55
- },
56
- };
57
- try {
58
- const r = sass.compileString(text, { url: toUrl(path), syntax: path.endsWith('.sass') ? 'indented' : 'scss', importers: [importer], style: prod ? 'compressed' : 'expanded', silenceDeprecations: ['import'] });
59
- return r.css;
60
- } catch (e) {
61
- const s = e.span;
62
- 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 });
63
- }
64
- }
65
-
66
- // ---- Less ----
67
- async function compileLess(path, text) {
68
- const mod = await load('less');
69
- const less = mod.default || mod;
70
- const vfs = {
71
- install(lessObj, pm) {
72
- class VfsFileManager extends lessObj.FileManager {
73
- supports() { return true; }
74
- supportsSync() { return false; }
75
- loadFile(filename, currentDirectory) {
76
- const base = normalize(`${currentDirectory || dirname(path)}/${filename}`);
77
- const hit = [base, `${base}.less`, `${base}.css`].find((c) => files.has(c));
78
- return hit ? Promise.resolve({ contents: files.get(hit), filename: hit }) : Promise.reject({ type: 'File', message: `ファイルが見つかりません: ${filename}` });
79
- }
80
- }
81
- pm.addFileManager(new VfsFileManager());
82
- },
83
- };
84
- try {
85
- return (await less.render(text, { filename: path, plugins: [vfs], compress: prod })).css;
86
- } catch (e) {
87
- throw Object.assign(new Error(e.message), { loc: e.line ? { line: e.line, column: e.column || 0 } : null, file: e.filename || path });
88
- }
89
- }
90
-
91
- // ---- Svelte ----
92
- async function compileSvelte(path, text) {
93
- const svelte = await load('svelte', need('svelte'));
94
- const warn = (w) => log.warn(`${path}${w.start ? `:${w.start.line}:${w.start.column + 1}` : ''} ${w.message}`);
95
- try {
96
- if (/\.svelte\.[jt]s$/.test(path)) {
97
- const js = path.endsWith('.ts') ? (await esbuild.transform(text, { loader: 'ts', sourcefile: path })).code : text;
98
- const r = svelte.compileModule(js, { filename: path, generate: 'client', dev: !prod });
99
- r.warnings.forEach(warn);
100
- return { contents: r.js.code, loader: 'js' };
101
- }
102
- const r = svelte.compile(text, { filename: path, generate: 'client', dev: !prod, css: 'injected' });
103
- r.warnings.forEach(warn);
104
- return { contents: r.js.code, loader: 'js' };
105
- } catch (e) {
106
- throw Object.assign(new Error(e.message), { loc: e.start ? { line: e.start.line, column: e.start.column } : null });
107
- }
108
- }
109
-
110
- // ---- Vue ----
111
- async function compileVue(path, text) {
112
- const sfc = await load('vue', need('vue'));
113
- const { descriptor, errors } = sfc.parse(text, { filename: path });
114
- if (errors.length) {
115
- const e = errors[0];
116
- throw Object.assign(new Error(e.message), { loc: e.loc ? { line: e.loc.start.line, column: e.loc.start.column - 1 } : null });
117
- }
118
- const id = hashId(path);
119
- const scoped = descriptor.styles.some((s) => s.scoped);
120
- let code = '', lang = 'js';
121
- if (descriptor.script || descriptor.scriptSetup) {
122
- const s = sfc.compileScript(descriptor, { id, inlineTemplate: true, isProd: prod, genDefaultAs: '__sfc__', templateOptions: { compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } } });
123
- code = s.content;
124
- lang = /tsx?/.test((descriptor.scriptSetup || descriptor.script).lang || '') ? 'ts' : 'js';
125
- } else code = 'const __sfc__ = {};';
126
- if (descriptor.template && !descriptor.scriptSetup) {
127
- const t = sfc.compileTemplate({ source: descriptor.template.content, filename: path, id, scoped, isProd: prod, compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } });
128
- if (t.errors.length) throw new Error(String(t.errors[0].message || t.errors[0]));
129
- code += `\n${t.code.replace(/\nexport (function|const) (render|ssrRender)/, '\n$1 $2')}\n__sfc__.render = render;`;
130
- }
131
- if (scoped) code += `\n__sfc__.__scopeId = "data-v-${id}";`;
132
- let css = '';
133
- for (const st of descriptor.styles) {
134
- let source = st.content;
135
- if (/^s[ac]ss$/.test(st.lang || '')) source = await compileSass(`${path}.${st.lang}`, source);
136
- else if (st.lang === 'less') source = await compileLess(`${path}.less`, source);
137
- const r = sfc.compileStyle({ source, filename: path, id: `data-v-${id}`, scoped: st.scoped, isProd: prod });
138
- if (r.errors.length) throw new Error(String(r.errors[0].message || r.errors[0]));
139
- css += r.code + '\n';
140
- }
141
- code += injectCss(css, `vue-${id}`);
142
- code += '\nexport default __sfc__;\n';
143
- return { contents: code, loader: lang };
144
- }
145
-
146
- // ---- YAML ----
147
- async function compileYaml(path, text) {
148
- const yaml = await load('yaml');
149
- try { return { contents: `export default ${JSON.stringify((yaml.load || yaml.default.load)(text))};`, loader: 'js' }; }
150
- catch (e) { throw Object.assign(new Error(e.reason || e.message), { loc: e.mark ? { line: e.mark.line + 1, column: e.mark.column } : null }); }
151
- }
152
-
153
- /** @returns {Promise<{contents:string, loader:string, resolveDir:string}|{errors:any[]}|null>} */
154
- return async function transform(path, text) {
155
- if (!TRANSFORM_EXT.test(path) || isBinary(text)) return null;
156
- try {
157
- let r;
158
- if (/\.svelte(\.[jt]s)?$/.test(path)) r = await compileSvelte(path, text);
159
- else if (path.endsWith('.vue')) r = await compileVue(path, text);
160
- else if (/\.s[ac]ss$/.test(path)) r = { contents: await compileSass(path, text), loader: 'css' };
161
- else if (path.endsWith('.less')) r = { contents: await compileLess(path, text), loader: 'css' };
162
- else r = await compileYaml(path, text);
163
- return { ...r, resolveDir: '/' + dirname(path) };
164
- } catch (e) {
165
- return fail(e.file || path, e.message.split('\n')[0], e.loc);
166
- }
167
- };
168
- }
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
+ import { dirname, normalize } from '../util/path.js';
9
+ import { isBinary } from '../util/bytes.js';
10
+
11
+ export const TRANSFORM_EXT = /\.(svelte|svelte\.[jt]s|vue|s[ac]ss|less|ya?ml)$/;
12
+
13
+ const lineCol = (text, offset) => {
14
+ const before = text.slice(0, offset).split('\n');
15
+ return { line: before.length, column: before[before.length - 1].length };
16
+ };
17
+ const fail = (path, message, loc) => ({ errors: [{ text: message, location: loc ? { file: path, line: loc.line, column: loc.column ?? 0 } : { file: path } }] });
18
+ const injectCss = (css, id) => css.trim()
19
+ ? `\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`
20
+ : '';
21
+ 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); };
22
+
23
+ /**
24
+ * @param {object} o
25
+ * @param {Map<string,string>} o.files
26
+ * @param {(name:string, range?:string)=>Promise<any>} o.load コンパイラを読む(deps.js の loadCompiler)
27
+ * @param {object} o.esbuild esbuild(TS を剥がすのに使う)
28
+ * @param {Record<string,string>} o.deps package.json の dependencies
29
+ */
30
+ export function createTransformer({ files, log, prod, load, esbuild, deps }) {
31
+ const need = (name) => {
32
+ if (!deps[name]) throw new Error(`${name} が package.json にありません。npm install ${name} してください(ランタイムとコンパイラのバージョンをそろえるため)`);
33
+ return deps[name];
34
+ };
35
+
36
+ // ---- Sass ----
37
+ async function compileSass(path, text) {
38
+ const sass = await load('sass');
39
+ const toUrl = (p) => new URL(`file:///${p}`);
40
+ const candidates = (p) => {
41
+ const d = dirname(p), b = p.split('/').pop();
42
+ 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`];
43
+ return bases.map(normalize);
44
+ };
45
+ const importer = {
46
+ canonicalize(url, ctx) {
47
+ const base = ctx && ctx.containingUrl ? ctx.containingUrl.pathname.slice(1) : path;
48
+ const raw = url.startsWith('file:///') ? url.slice(8) : normalize(`${dirname(base)}/${url}`);
49
+ const hit = candidates(raw).find((c) => files.has(c));
50
+ return hit ? toUrl(hit) : null;
51
+ },
52
+ load(u) {
53
+ const p = decodeURIComponent(u.pathname.slice(1));
54
+ return { contents: files.get(p), syntax: p.endsWith('.sass') ? 'indented' : p.endsWith('.css') ? 'css' : 'scss' };
55
+ },
56
+ };
57
+ try {
58
+ const r = sass.compileString(text, { url: toUrl(path), syntax: path.endsWith('.sass') ? 'indented' : 'scss', importers: [importer], style: prod ? 'compressed' : 'expanded', silenceDeprecations: ['import'] });
59
+ return r.css;
60
+ } catch (e) {
61
+ const s = e.span;
62
+ 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 });
63
+ }
64
+ }
65
+
66
+ // ---- Less ----
67
+ async function compileLess(path, text) {
68
+ const mod = await load('less');
69
+ const less = mod.default || mod;
70
+ const vfs = {
71
+ install(lessObj, pm) {
72
+ class VfsFileManager extends lessObj.FileManager {
73
+ supports() { return true; }
74
+ supportsSync() { return false; }
75
+ loadFile(filename, currentDirectory) {
76
+ const base = normalize(`${currentDirectory || dirname(path)}/${filename}`);
77
+ const hit = [base, `${base}.less`, `${base}.css`].find((c) => files.has(c));
78
+ return hit ? Promise.resolve({ contents: files.get(hit), filename: hit }) : Promise.reject({ type: 'File', message: `ファイルが見つかりません: ${filename}` });
79
+ }
80
+ }
81
+ pm.addFileManager(new VfsFileManager());
82
+ },
83
+ };
84
+ try {
85
+ return (await less.render(text, { filename: path, plugins: [vfs], compress: prod })).css;
86
+ } catch (e) {
87
+ throw Object.assign(new Error(e.message), { loc: e.line ? { line: e.line, column: e.column || 0 } : null, file: e.filename || path });
88
+ }
89
+ }
90
+
91
+ // ---- Svelte ----
92
+ async function compileSvelte(path, text) {
93
+ const svelte = await load('svelte', need('svelte'));
94
+ const warn = (w) => log.warn(`${path}${w.start ? `:${w.start.line}:${w.start.column + 1}` : ''} ${w.message}`);
95
+ try {
96
+ if (/\.svelte\.[jt]s$/.test(path)) {
97
+ const js = path.endsWith('.ts') ? (await esbuild.transform(text, { loader: 'ts', sourcefile: path })).code : text;
98
+ const r = svelte.compileModule(js, { filename: path, generate: 'client', dev: !prod });
99
+ r.warnings.forEach(warn);
100
+ return { contents: r.js.code, loader: 'js' };
101
+ }
102
+ const r = svelte.compile(text, { filename: path, generate: 'client', dev: !prod, css: 'injected' });
103
+ r.warnings.forEach(warn);
104
+ return { contents: r.js.code, loader: 'js' };
105
+ } catch (e) {
106
+ throw Object.assign(new Error(e.message), { loc: e.start ? { line: e.start.line, column: e.start.column } : null });
107
+ }
108
+ }
109
+
110
+ // ---- Vue ----
111
+ async function compileVue(path, text) {
112
+ const sfc = await load('vue', need('vue'));
113
+ const { descriptor, errors } = sfc.parse(text, { filename: path });
114
+ if (errors.length) {
115
+ const e = errors[0];
116
+ throw Object.assign(new Error(e.message), { loc: e.loc ? { line: e.loc.start.line, column: e.loc.start.column - 1 } : null });
117
+ }
118
+ const id = hashId(path);
119
+ const scoped = descriptor.styles.some((s) => s.scoped);
120
+ let code = '', lang = 'js';
121
+ if (descriptor.script || descriptor.scriptSetup) {
122
+ const s = sfc.compileScript(descriptor, { id, inlineTemplate: true, isProd: prod, genDefaultAs: '__sfc__', templateOptions: { compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } } });
123
+ code = s.content;
124
+ lang = /tsx?/.test((descriptor.scriptSetup || descriptor.script).lang || '') ? 'ts' : 'js';
125
+ } else code = 'const __sfc__ = {};';
126
+ if (descriptor.template && !descriptor.scriptSetup) {
127
+ const t = sfc.compileTemplate({ source: descriptor.template.content, filename: path, id, scoped, isProd: prod, compilerOptions: { scopeId: scoped ? `data-v-${id}` : undefined } });
128
+ if (t.errors.length) throw new Error(String(t.errors[0].message || t.errors[0]));
129
+ code += `\n${t.code.replace(/\nexport (function|const) (render|ssrRender)/, '\n$1 $2')}\n__sfc__.render = render;`;
130
+ }
131
+ if (scoped) code += `\n__sfc__.__scopeId = "data-v-${id}";`;
132
+ let css = '';
133
+ for (const st of descriptor.styles) {
134
+ let source = st.content;
135
+ if (/^s[ac]ss$/.test(st.lang || '')) source = await compileSass(`${path}.${st.lang}`, source);
136
+ else if (st.lang === 'less') source = await compileLess(`${path}.less`, source);
137
+ const r = sfc.compileStyle({ source, filename: path, id: `data-v-${id}`, scoped: st.scoped, isProd: prod });
138
+ if (r.errors.length) throw new Error(String(r.errors[0].message || r.errors[0]));
139
+ css += r.code + '\n';
140
+ }
141
+ code += injectCss(css, `vue-${id}`);
142
+ code += '\nexport default __sfc__;\n';
143
+ return { contents: code, loader: lang };
144
+ }
145
+
146
+ // ---- YAML ----
147
+ async function compileYaml(path, text) {
148
+ const yaml = await load('yaml');
149
+ try { return { contents: `export default ${JSON.stringify((yaml.load || yaml.default.load)(text))};`, loader: 'js' }; }
150
+ catch (e) { throw Object.assign(new Error(e.reason || e.message), { loc: e.mark ? { line: e.mark.line + 1, column: e.mark.column } : null }); }
151
+ }
152
+
153
+ /** @returns {Promise<{contents:string, loader:string, resolveDir:string}|{errors:any[]}|null>} */
154
+ return async function transform(path, text) {
155
+ if (!TRANSFORM_EXT.test(path) || isBinary(text)) return null;
156
+ try {
157
+ let r;
158
+ if (/\.svelte(\.[jt]s)?$/.test(path)) r = await compileSvelte(path, text);
159
+ else if (path.endsWith('.vue')) r = await compileVue(path, text);
160
+ else if (/\.s[ac]ss$/.test(path)) r = { contents: await compileSass(path, text), loader: 'css' };
161
+ else if (path.endsWith('.less')) r = { contents: await compileLess(path, text), loader: 'css' };
162
+ else r = await compileYaml(path, text);
163
+ return { ...r, resolveDir: '/' + dirname(path) };
164
+ } catch (e) {
165
+ return fail(e.file || path, e.message.split('\n')[0], e.loc);
166
+ }
167
+ };
168
+ }
@@ -1,60 +1,60 @@
1
- // esbuild: IDE の中のファイル(Map)を読む。npm のパッケージは node_modules/ から
2
- import { dirname, ext, normalize } from '../util/path.js';
3
- import { isBinary, toBytes } from '../util/bytes.js';
4
- import { parseSpecifier, readPackageJson, npmUrl } from '../npm/registry.js';
5
- import { pkgDir, subFile } from '../npm/vendor.js';
6
- import { httpPlugin } from './http-plugin.js';
7
- import { SHARED_RUNTIMES } from '../config.js';
8
-
9
- const LOADERS = { ts: 'ts', mts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', jsx: 'jsx', json: 'json', css: 'css', svg: 'text', html: 'text', txt: 'text', md: 'text' };
10
- const EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json', '.css', '.svelte.ts', '.svelte.js', '/index.ts', '/index.tsx', '/index.js'];
11
-
12
- /**
13
- * @param {Map<string,string>} files
14
- * @param {{ vendor?: (name: string, sub: string) => Promise<string|null>, transform?: Function }} opts
15
- * vendor: node_modules に無いものを取ってきて置き、そのパスを返す(IDE から渡す)
16
- * transform: .svelte / .vue などを変換する(transformers.js)
17
- */
18
- export function vfsPlugin(files, log, { vendor, transform } = {}) {
19
- const deps = readPackageJson(files).dependencies;
20
- const warned = new Set();
21
- const http = httpPlugin(log);
22
- return {
23
- name: 'kintone-vfs',
24
- setup(b) {
25
- http.setup(b);
26
- b.onResolve({ filter: /^(\.{0,2}\/|[^@\w])/ }, (a) => {
27
- if (a.namespace === 'http') return undefined;
28
- const base = normalize(a.path.startsWith('/') ? a.path : `${dirname(a.importer)}/${a.path}`);
29
- for (const e of EXTS) if (files.has(base + e)) return { path: base + e, namespace: 'vfs' };
30
- // ESM の書き方("./foo.js" と書いて foo.ts を指す)
31
- const ts = base.replace(/\.js$/, '.ts');
32
- if (ts !== base && files.has(ts)) return { path: ts, namespace: 'vfs' };
33
- return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
34
- });
35
- b.onResolve({ filter: /^[@\w]/ }, async (a) => {
36
- if (a.kind === 'entry-point') return { path: normalize(a.path), namespace: 'vfs' };
37
- if (a.namespace === 'http') return undefined;
38
- const { name, sub } = parseSpecifier(a.path);
39
- if (!deps[name]) {
40
- if (!warned.has(name)) { warned.add(name); log.warn(`${name} が package.json にありません(最新版を CDN から直接使います)。npm install ${name} で node_modules に入ります`); }
41
- return { path: npmUrl(name, '', sub), namespace: 'http' };
42
- }
43
- if (SHARED_RUNTIMES.test(name)) return { path: npmUrl(name, deps[name], sub, { shared: true }), namespace: 'http' };
44
- const target = sub ? subFile(name, sub) : `${pkgDir(name)}index.mjs`;
45
- if (files.has(target)) return { path: target, namespace: 'vfs' };
46
- const got = vendor && (await vendor(name, sub));
47
- if (got) return { path: got, namespace: 'vfs' };
48
- return { path: npmUrl(name, deps[name], sub), namespace: 'http' };
49
- });
50
- b.onLoad({ filter: /.*/, namespace: 'vfs' }, async (a) => {
51
- if (!files.has(a.path)) return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
52
- const text = files.get(a.path);
53
- const t = transform && (await transform(a.path, text));
54
- if (t) return t;
55
- if (isBinary(text)) return { contents: toBytes(text), loader: 'dataurl' };
56
- return { contents: text, loader: LOADERS[ext(a.path)] || 'text', resolveDir: '/' + dirname(a.path) };
57
- });
58
- },
59
- };
60
- }
1
+ // esbuild: IDE の中のファイル(Map)を読む。npm のパッケージは node_modules/ から
2
+ import { dirname, ext, normalize } from '../util/path.js';
3
+ import { isBinary, toBytes } from '../util/bytes.js';
4
+ import { parseSpecifier, readPackageJson, npmUrl } from '../npm/registry.js';
5
+ import { pkgDir, subFile } from '../npm/vendor.js';
6
+ import { httpPlugin } from './http-plugin.js';
7
+ import { SHARED_RUNTIMES } from '../config.js';
8
+
9
+ const LOADERS = { ts: 'ts', mts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', jsx: 'jsx', json: 'json', css: 'css', svg: 'text', html: 'text', txt: 'text', md: 'text' };
10
+ const EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.json', '.css', '.svelte.ts', '.svelte.js', '/index.ts', '/index.tsx', '/index.js'];
11
+
12
+ /**
13
+ * @param {Map<string,string>} files
14
+ * @param {{ vendor?: (name: string, sub: string) => Promise<string|null>, transform?: Function }} opts
15
+ * vendor: node_modules に無いものを取ってきて置き、そのパスを返す(IDE から渡す)
16
+ * transform: .svelte / .vue などを変換する(transformers.js)
17
+ */
18
+ export function vfsPlugin(files, log, { vendor, transform } = {}) {
19
+ const deps = readPackageJson(files).dependencies;
20
+ const warned = new Set();
21
+ const http = httpPlugin(log);
22
+ return {
23
+ name: 'kintone-vfs',
24
+ setup(b) {
25
+ http.setup(b);
26
+ b.onResolve({ filter: /^(\.{0,2}\/|[^@\w])/ }, (a) => {
27
+ if (a.namespace === 'http') return undefined;
28
+ const base = normalize(a.path.startsWith('/') ? a.path : `${dirname(a.importer)}/${a.path}`);
29
+ for (const e of EXTS) if (files.has(base + e)) return { path: base + e, namespace: 'vfs' };
30
+ // ESM の書き方("./foo.js" と書いて foo.ts を指す)
31
+ const ts = base.replace(/\.js$/, '.ts');
32
+ if (ts !== base && files.has(ts)) return { path: ts, namespace: 'vfs' };
33
+ return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
34
+ });
35
+ b.onResolve({ filter: /^[@\w]/ }, async (a) => {
36
+ if (a.kind === 'entry-point') return { path: normalize(a.path), namespace: 'vfs' };
37
+ if (a.namespace === 'http') return undefined;
38
+ const { name, sub } = parseSpecifier(a.path);
39
+ if (!deps[name]) {
40
+ if (!warned.has(name)) { warned.add(name); log.warn(`${name} が package.json にありません(最新版を CDN から直接使います)。npm install ${name} で node_modules に入ります`); }
41
+ return { path: npmUrl(name, '', sub), namespace: 'http' };
42
+ }
43
+ if (SHARED_RUNTIMES.test(name)) return { path: npmUrl(name, deps[name], sub, { shared: true }), namespace: 'http' };
44
+ const target = sub ? subFile(name, sub) : `${pkgDir(name)}index.mjs`;
45
+ if (files.has(target)) return { path: target, namespace: 'vfs' };
46
+ const got = vendor && (await vendor(name, sub));
47
+ if (got) return { path: got, namespace: 'vfs' };
48
+ return { path: npmUrl(name, deps[name], sub), namespace: 'http' };
49
+ });
50
+ b.onLoad({ filter: /.*/, namespace: 'vfs' }, async (a) => {
51
+ if (!files.has(a.path)) return { errors: [{ text: `ファイルが見つかりません: ${a.path}` }] };
52
+ const text = files.get(a.path);
53
+ const t = transform && (await transform(a.path, text));
54
+ if (t) return t;
55
+ if (isBinary(text)) return { contents: toBytes(text), loader: 'dataurl' };
56
+ return { contents: text, loader: LOADERS[ext(a.path)] || 'text', resolveDir: '/' + dirname(a.path) };
57
+ });
58
+ },
59
+ };
60
+ }