kintone-plugin-ide 0.3.1 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kintone-plugin-ide",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "kintone のレコードを、そのままプラグインの開発環境(エディタ・ターミナル・ビルド・署名・インストール)にする",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -29,16 +29,19 @@
29
29
  "prepublishOnly": "npm run build && npm test"
30
30
  },
31
31
  "dependencies": {
32
- "fflate": "^0.8.2"
32
+ "esbuild-plugin-browser": "^0.1.0",
33
+ "fflate": "^0.8.2",
34
+ "kintone-plugin-web-signer": "^0.1.0"
33
35
  },
34
36
  "devDependencies": {
35
37
  "esbuild": "^0.25.0"
36
38
  },
37
39
  "repository": {
38
40
  "type": "git",
39
- "url": "git+https://github.com/yusura0929/kintone-plugin-ide.git"
41
+ "url": "git+https://github.com/yusura0929/kintone-plugin-ide.git",
42
+ "directory": "packages/ide"
40
43
  },
41
- "homepage": "https://github.com/yusura0929/kintone-plugin-ide#readme",
44
+ "homepage": "https://github.com/yusura0929/kintone-plugin-ide/tree/main/packages/ide#readme",
42
45
  "bugs": {
43
46
  "url": "https://github.com/yusura0929/kintone-plugin-ide/issues"
44
47
  },
@@ -1,11 +1,14 @@
1
1
  // manifest.json を読んで、必要なファイルをビルドし、contents.zip を作る
2
2
  import { zipSync } from 'fflate';
3
3
  import { loadEsbuild, loadValidator, loadCompiler } from '../deps.js';
4
- import { createTransformer } from './transformers.js';
4
+ import { browserPlugin } from 'esbuild-plugin-browser';
5
5
  import { readPackageJson } from '../npm/registry.js';
6
6
  import { kb, toBytes } from '../util/bytes.js';
7
7
  import { normalize, isVendor } from '../util/path.js';
8
- import { vfsPlugin } from './vfs-plugin.js';
8
+ import { pkgDir, subFile } from '../npm/vendor.js';
9
+ import { idbGet, idbSet } from '../util/idb.js';
10
+ import { CONFIG } from '../config.js';
11
+ import { isBinary } from '../util/bytes.js';
9
12
 
10
13
  export function sourceList(manifest) {
11
14
  const list = [];
@@ -59,7 +62,21 @@ export async function buildPlugin(files, log, { prod = false, vendor } = {}) {
59
62
  const manifest = readManifest(files);
60
63
  const outputs = new Map();
61
64
  const es = await loadEsbuild();
62
- const transform = createTransformer({ files, log, prod, load: loadCompiler, esbuild: es, deps: readPackageJson(files).dependencies });
65
+ // IDE のファイルは文字列(バイナリは "base64:...")。プラグインには Uint8Array で見せる
66
+ const source = { has: (p) => files.has(p), get: (p) => { const t = files.get(p); return t !== undefined && isBinary(t) ? toBytes(t) : t; } };
67
+ // npm のパッケージは node_modules/ に置いたものを使う。無ければ取ってきて置く(vendor)
68
+ const resolvePackage = async (name, sub) => {
69
+ const target = sub ? subFile(name, sub) : `${pkgDir(name)}index.mjs`;
70
+ if (files.has(target)) return target;
71
+ return vendor ? vendor(name, sub) : null;
72
+ };
73
+ const plugin = () => browserPlugin({
74
+ files: source, esbuild: es, prod, cdn: CONFIG.CDN.npm, resolvePackage,
75
+ dependencies: readPackageJson(files).dependencies,
76
+ transform: { load: loadCompiler },
77
+ cache: { get: idbGet, set: idbSet },
78
+ log: { info: log.info, warn: (t) => log.warn(/package\.json にありません/.test(t) ? `${t}。npm install で node_modules に入ります` : t) },
79
+ });
63
80
  for (const out of sourceList(manifest)) {
64
81
  if (files.has(out) && !isVendor(out)) { outputs.set(out, toBytes(files.get(out))); continue; }
65
82
  const entry = (out.endsWith('.js') || out.endsWith('.css')) && entryCandidates(out).find((p) => files.has(p));
@@ -73,7 +90,7 @@ export async function buildPlugin(files, log, { prod = false, vendor } = {}) {
73
90
  'process.env.NODE_ENV': JSON.stringify(prod ? 'production' : 'development'),
74
91
  __VUE_OPTIONS_API__: 'true', __VUE_PROD_DEVTOOLS__: 'false', __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false',
75
92
  },
76
- plugins: [vfsPlugin(files, log, { vendor, transform })],
93
+ plugins: [plugin()],
77
94
  }).catch((e) => e);
78
95
  for (const w of r.warnings || []) log.warn(fmtMsg(w));
79
96
  if (r.errors && r.errors.length) { r.errors.forEach((er) => log.error(fmtMsg(er))); throw new Error(`${entry} のビルドに失敗しました`); }
package/src/config.js CHANGED
@@ -38,9 +38,7 @@ export const F = CONFIG.FIELDS;
38
38
  export const BINARY_PREFIX = 'base64:';
39
39
  export const SETTINGS_KEY = 'kintone-plugin-ide:settings';
40
40
  export const NODE_MODULES = 'node_modules/';
41
- // 状態をモジュールで共有するランタイム。サブパスごとに丸ごと抱え込むと二重に入って壊れるので、
42
- // esm.sh の分割されたモジュールをそのまま読んで esbuild にまとめさせる(node_modules には印だけ置く)
43
- export const SHARED_RUNTIMES = /^(svelte|vue|@vue\/.+|react|react-dom|preact|solid-js|lit|@lit\/.+)$/;
41
+ export { SHARED_RUNTIMES } from 'esbuild-plugin-browser';
44
42
 
45
43
  // setup() の引数を CONFIG に重ねる。オブジェクトは差し替えずに中身を書き換える
46
44
  // (ほかのモジュールが CONFIG.FIELDS などを直接つかんでいるため)
@@ -3,7 +3,7 @@ import { F } from '../../config.js';
3
3
  import { api, apiError, downloadFile, uploadFile } from '../../kintone/api.js';
4
4
  import { install, addToTestApp } from '../../kintone/plugin.js';
5
5
  import { buildPlugin } from '../../build/build.js';
6
- import { generateKey, pack } from '../../packer/packer.js';
6
+ import { generateKey, pack } from 'kintone-plugin-web-signer';
7
7
  import { dec, enc, kb } from '../../util/bytes.js';
8
8
  import { safeName } from '../../util/path.js';
9
9
 
@@ -1,6 +1,6 @@
1
1
  // zip の取り込み・書き出し・ドラッグ&ドロップ
2
2
  import { zipSync, unzipSync } from 'fflate';
3
- import { unpack } from '../../packer/packer.js';
3
+ import { unpack } from 'kintone-plugin-web-signer';
4
4
  import { fromBytes, toBytes } from '../../util/bytes.js';
5
5
  import { downloadBlob, pickFile } from '../../util/dom.js';
6
6
  import { dirname, normalize, safeName, isVendor } from '../../util/path.js';
package/src/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * 使い方(アプリの「JavaScript / CSSでカスタマイズ」に入れる数行):
6
6
  * (async () => {
7
- * const { setup } = await import('https://esm.sh/kintone-plugin-ide@0.3.1');
7
+ * const { setup } = await import('https://esm.sh/kintone-plugin-ide@0.4.0');
8
8
  * setup({ installHosts: ['example.cybozu.com'] });
9
9
  * })();
10
10
  */
@@ -15,7 +15,8 @@ import { el } from './util/dom.js';
15
15
  export { CONFIG, configure, openIDE };
16
16
  // 画面を使わない部品(自分のツールから使える)
17
17
  export { buildPlugin, sourceList, readManifest } from './build/build.js';
18
- export { generateKey, pack, unpack, idFromSpki } from './packer/packer.js';
18
+ export { generateKey, pack, packFiles, unpack, idFromSpki, publicKeyFromPpk } from 'kintone-plugin-web-signer';
19
+ export { browserPlugin } from 'esbuild-plugin-browser';
19
20
  export { install, addToTestApp, deployApp } from './kintone/plugin.js';
20
21
 
21
22
  const open = () => openIDE().catch((e) => { console.error(e); alert('IDEを開けませんでした\n' + e.message); });
package/src/npm/vendor.js CHANGED
@@ -3,9 +3,9 @@
3
3
  // node_modules/<name>/index.mjs 本体(依存も全部入り)
4
4
  // node_modules/<name>/<sub>.mjs "dayjs/plugin/utc" のようなサブパス(使った時に取ってくる)
5
5
  // 取ってきたものは IndexedDB に name@version 単位でキャッシュするので、2回目からは通信しない。
6
- import { NODE_MODULES, SHARED_RUNTIMES } from '../config.js';
6
+ import { NODE_MODULES } from '../config.js';
7
+ import { httpPlugin, SHARED_RUNTIMES } from 'esbuild-plugin-browser';
7
8
  import { loadEsbuild } from '../deps.js';
8
- import { httpPlugin } from '../build/http-plugin.js';
9
9
  import { idbGet, idbSet } from '../util/idb.js';
10
10
  import { npmUrl } from './registry.js';
11
11
 
@@ -25,7 +25,7 @@ async function bundle(url, log) {
25
25
  const es = await loadEsbuild();
26
26
  const r = await es.build({
27
27
  entryPoints: [url], bundle: true, write: false, format: 'esm', target: 'es2020',
28
- logLevel: 'silent', legalComments: 'inline', plugins: [httpPlugin(log)],
28
+ logLevel: 'silent', legalComments: 'inline', plugins: [httpPlugin({ log, cache: { get: idbGet, set: idbSet } })],
29
29
  });
30
30
  return r.outputFiles[0].text;
31
31
  }
@@ -1,32 +0,0 @@
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 +0,0 @@
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 +0,0 @@
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,50 +0,0 @@
1
- // パッケージング(Web Crypto + fflate)― 公式パッカーとバイト単位で一致することを確認済み
2
- import { zipSync, unzipSync } from 'fflate';
3
- import { b64, unb64 } from '../util/bytes.js';
4
-
5
- const ALG = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-1' };
6
- const RSA_ALG = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]);
7
- const derLen = (n) => (n < 128 ? [n] : n < 256 ? [0x81, n] : [0x82, n >> 8, n & 255]);
8
- const cat = (...a) => { const o = new Uint8Array(a.reduce((s, x) => s + x.length, 0)); let i = 0; for (const x of a) { o.set(x, i); i += x.length; } return o; };
9
- const pemBody = (pem) => unb64(pem.replace(/-----[^-]+-----|\s/g, ''));
10
- const toPem = (der, label) => `-----BEGIN ${label}-----\n${b64(der).match(/.{1,64}/g).join('\n')}\n-----END ${label}-----\n`;
11
- // .ppk は PKCS#1。Web Crypto は PKCS#8 しか読めないので包む / 剥がす
12
- const p1to8 = (p1) => {
13
- const body = cat(new Uint8Array([0x02, 0x01, 0x00]), RSA_ALG, cat(new Uint8Array([0x04, ...derLen(p1.length)]), p1));
14
- return cat(new Uint8Array([0x30, ...derLen(body.length)]), body);
15
- };
16
- const p8to1 = (p8) => {
17
- let i = 0;
18
- const len = () => { let l = p8[i++]; if (l & 0x80) { const n = l & 0x7f; l = 0; for (let k = 0; k < n; k++) l = (l << 8) | p8[i++]; } return l; };
19
- const skip = () => { i++; const l = len(); i += l; };
20
- i++; len(); skip(); skip(); i++; const l = len();
21
- return p8.slice(i, i + l);
22
- };
23
-
24
- export async function generateKey() {
25
- const kp = await crypto.subtle.generateKey({ ...ALG, modulusLength: 1024, publicExponent: new Uint8Array([1, 0, 1]) }, true, ['sign', 'verify']);
26
- return toPem(p8to1(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey))), 'RSA PRIVATE KEY');
27
- }
28
- export async function idFromSpki(spki) {
29
- const hex = [...new Uint8Array(await crypto.subtle.digest('SHA-256', spki))].map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 32);
30
- return hex.replace(/[0-9a-f]/g, (c) => 'abcdefghijklmnop'['0123456789abcdef'.indexOf(c)]);
31
- }
32
- export async function pack(contentsZip, ppk) {
33
- const key = await crypto.subtle.importKey('pkcs8', p1to8(pemBody(ppk)), ALG, true, ['sign']);
34
- const signature = new Uint8Array(await crypto.subtle.sign(ALG, key, contentsZip));
35
- const jwk = await crypto.subtle.exportKey('jwk', key);
36
- const pub = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, alg: 'RS1', ext: true }, ALG, true, ['verify']);
37
- const spki = new Uint8Array(await crypto.subtle.exportKey('spki', pub));
38
- return { id: await idFromSpki(spki), plugin: zipSync({ 'contents.zip': contentsZip, PUBKEY: spki, SIGNATURE: signature }) };
39
- }
40
- // プラグインzip の署名を検証して中身を取り出す(import 用)。プラグインでなければ null
41
- export async function unpack(pluginZip) {
42
- const outer = unzipSync(pluginZip);
43
- if (!outer['contents.zip']) return null;
44
- let verified = false;
45
- if (outer.PUBKEY && outer.SIGNATURE) {
46
- const pub = await crypto.subtle.importKey('spki', outer.PUBKEY, ALG, false, ['verify']);
47
- verified = await crypto.subtle.verify(ALG, pub, outer.SIGNATURE, outer['contents.zip']);
48
- }
49
- return { contents: unzipSync(outer['contents.zip']), verified, id: outer.PUBKEY ? await idFromSpki(outer.PUBKEY) : null };
50
- }