@songloft/plugin-builder 2.20.0 → 2.22.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 +201 -0
- package/dist/cli.js +21 -9
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +21 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +21 -9
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/build.ts","../src/manifest.ts","../src/hash.ts","../src/static-assets.ts","../src/lynx-index-html.ts"],"sourcesContent":["// @songloft/plugin-builder — public API\nexport { buildPlugin, validatePlugin } from './build.js';\nexport type { BuildOptions, BuildResult, ValidationResult } from './build.js';\nexport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nexport { readManifest, validateManifest } from './manifest.js';\nexport type { ManifestValidationError } from './manifest.js';\n","// @songloft/plugin-builder — 核心 build 逻辑\n\nimport * as esbuild from 'esbuild';\nimport JSZip from 'jszip';\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, cpSync, unlinkSync, rmSync, readdirSync as readdirSyncTop } from 'node:fs';\nimport { join, resolve, dirname } from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { readManifest, validateManifest } from './manifest.js';\nimport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nimport { hashStaticAssets } from './static-assets.js';\nimport { generateLynxIndexHtml } from './lynx-index-html.js';\nimport type { PluginManifest } from '@songloft/plugin-sdk';\n\n// Windows 下 npm 是 npm.cmd,execFileSync/spawn 不走 shell,直接 'npm' 会 ENOENT\nconst NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';\n\nexport interface BuildOptions {\n cwd: string;\n outDir?: string;\n mode?: 'development' | 'production';\n sourcemap?: boolean;\n}\n\nexport interface BuildResult {\n zipPath: string;\n manifest: PluginManifest;\n size: number;\n entryHash: string;\n zipHash: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: { field: string; message: string }[];\n}\n\n/**\n * 构建插件:TS/JS → QuickJS-compatible JS → .jsplugin.zip\n */\nexport async function buildPlugin(opts: BuildOptions): Promise<BuildResult> {\n const cwd = resolve(opts.cwd);\n const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join(cwd, 'dist');\n const buildDir = join(outDir, '_build');\n const mode = opts.mode ?? 'production';\n\n // [1] 读取并校验 plugin.json\n const manifest = readManifest(cwd);\n const errors = validateManifest(manifest);\n if (errors.length > 0) {\n throw new Error(`Invalid plugin.json:\\n${errors.map(e => ` - ${e.field}: ${e.message}`).join('\\n')}`);\n }\n\n // [2] esbuild 打包 src/main.ts → build/main.js\n //\n // _build 是**纯暂存目录**:最后整目录进 zip(addDirToZip(zip, buildDir, ''))且整目录\n // 参与 computeCanonicalZipHash。所以它必须每次从零开始 —— 否则 [3.1.1] 步注入内容 hash\n // 产出的 `style.<hash>.css` 会**逐次堆积**:同一份源码构建多次,zip 里会带上历史所有版本\n // 的资源(实测 downloader 连构 4 次后 zip 里有 4 份 style.*.css),而 index.html 只引用\n // 最新那份。后果不只是体积——`zipHash` 会随构建历史漂移,同样的源码算出不同的哈希,\n // 这条哈希的完整性用途就没了。cpSync 是合并语义、不会替我们清,只能显式删。\n rmSync(buildDir, { recursive: true, force: true });\n mkdirSync(buildDir, { recursive: true });\n const entryPoint = join(cwd, 'src', 'main.ts');\n const entryPointAlt = join(cwd, 'src', 'main.js');\n const actualEntry = existsSync(entryPoint) ? entryPoint : entryPointAlt;\n\n if (!existsSync(actualEntry)) {\n throw new Error(`Entry file not found: src/main.ts or src/main.js`);\n }\n\n await esbuild.build({\n entryPoints: [actualEntry],\n outfile: join(buildDir, 'main.js'),\n bundle: true,\n platform: 'neutral',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n sourcemap: opts.sourcemap ? 'inline' : false,\n // 禁止使用 Node 内置模块\n plugins: [{\n name: 'no-node-builtins',\n setup(build) {\n build.onResolve({ filter: /^(fs|net|http|https|child_process|os|path|crypto|stream|util|events|buffer|url|querystring|zlib)$/ }, (args) => {\n return { errors: [{ text: `Node builtin \"${args.path}\" is not available in QuickJS runtime` }] };\n });\n },\n }],\n });\n\n // [2.5] 前端 Vue/Vite 编译(如果存在 frontend/ 目录)\n const frontendDir = join(cwd, 'frontend');\n if (existsSync(join(frontendDir, 'package.json'))) {\n // 仅在依赖缺失时安装:dev 模式每次热重载都会走到这里,无脑 npm install 会拖慢重建\n if (!existsSync(join(frontendDir, 'node_modules'))) {\n console.log(` 📦 Installing frontend dependencies...`);\n execFileSync(NPM, ['install'], { cwd: frontendDir, stdio: 'inherit' });\n }\n console.log(` 🚀 Building frontend project...`);\n execFileSync(NPM, ['run', 'build'], { cwd: frontendDir, stdio: 'inherit' });\n // 根据模板配置,产物会被直接输出到 cwd/static。但为了兼容自定义 dist 输出,加一个 fallback 拷贝:\n if (existsSync(join(frontendDir, 'dist'))) {\n cpSync(join(frontendDir, 'dist'), join(buildDir, 'static'), { recursive: true });\n }\n }\n\n // [2.6] Lynx 插件后处理:rspeedy 产出 dist/lynx/ 和 dist/web/ 子目录,\n // 将 bundle 文件提升到 static/ 根并生成 Flutter WebView 用的 index.html。\n if (manifest.renderEngine === 'lynx') {\n const staticOut = join(buildDir, 'static');\n const lynxBundleDir = join(staticOut, 'lynx');\n const webBundleDir = join(staticOut, 'web');\n mkdirSync(staticOut, { recursive: true });\n\n const lynxBundle = join(lynxBundleDir, 'main.lynx.bundle');\n const webBundle = join(webBundleDir, 'main.web.bundle');\n\n if (existsSync(lynxBundle)) {\n cpSync(lynxBundle, join(staticOut, 'main.lynx.bundle'));\n }\n if (existsSync(webBundle)) {\n cpSync(webBundle, join(staticOut, 'main.web.bundle'));\n }\n\n // Remove the intermediate subdirectories\n rmSync(lynxBundleDir, { recursive: true, force: true });\n rmSync(webBundleDir, { recursive: true, force: true });\n\n // Generate index.html for Flutter WebView fallback (loads web-core + .web.bundle)\n writeFileSync(join(staticOut, 'index.html'), generateLynxIndexHtml(manifest.entryPath));\n\n console.log(` 🔗 Lynx bundles flattened + index.html generated`);\n }\n\n // [3] 拷贝 static/ 到 build/(如果存在)\n const staticDir = join(cwd, 'static');\n if (existsSync(staticDir)) {\n cpSync(staticDir, join(buildDir, 'static'), { recursive: true });\n }\n\n // [3.0] 拷贝 bin/ 到 build/(如果存在,用于打包可执行文件)\n const binDir = join(cwd, 'bin');\n if (existsSync(binDir)) {\n cpSync(binDir, join(buildDir, 'bin'), { recursive: true });\n }\n\n // [3.1] 合并打包前端 JS(如果 static/js/app.js 存在)\n const staticJsAppPath = join(buildDir, 'static', 'js', 'app.js');\n if (existsSync(staticJsAppPath)) {\n const bundleOutPath = join(buildDir, 'static', 'js', 'app.bundle.js');\n await esbuild.build({\n entryPoints: [staticJsAppPath],\n outfile: bundleOutPath,\n bundle: true,\n platform: 'browser',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n });\n\n // 删除 static/js/ 下除 app.bundle.js 外的所有 .js 文件\n const staticJsDir = join(buildDir, 'static', 'js');\n const jsFiles = readdirSyncTop(staticJsDir).filter(f => f.endsWith('.js') && f !== 'app.bundle.js');\n for (const f of jsFiles) {\n unlinkSync(join(staticJsDir, f));\n }\n\n // 更新 index.html 中的 script 引用:将 app.js 替换为打包后的 app.bundle.js\n // 匹配时兼容属性顺序不同、多空格、以及 src 中有无 static/ 前缀\n const indexHtmlPath = join(buildDir, 'static', 'index.html');\n if (existsSync(indexHtmlPath)) {\n let html = readFileSync(indexHtmlPath, 'utf-8');\n const before = html;\n html = html.replace(\n /<script\\b[^>]*\\bsrc=\"(?:static\\/)?js\\/app\\.js\"[^>]*><\\/script>/,\n '<script src=\"static/js/app.bundle.js\"></script>'\n );\n if (html === before) {\n throw new Error(\n 'Failed to update script tag in static/index.html: ' +\n 'expected <script ... src=\"static/js/app.js\" ...> or <script ... src=\"js/app.js\" ...> but pattern not found'\n );\n }\n writeFileSync(indexHtmlPath, html);\n }\n\n console.log(` 📦 static/js/ bundled → app.bundle.js (${jsFiles.length} files merged)`);\n }\n\n // [3.1.1] 为 static/ 下所有 JS/CSS/字体/图片注入内容 hash 到文件名,\n // 并改写 HTML/CSS 中的引用,防止插件更新后浏览器使用旧缓存。\n // 可在 plugin.json 中设置 \"staticHash\": false 关闭(用于前端已用\n // Vite/Webpack 等工具自管理 hash 的场景)。\n const staticBuildDir = join(buildDir, 'static');\n let staticRenameMap: Map<string, string> | undefined;\n if (existsSync(staticBuildDir) && manifest.staticHash !== false) {\n const { renamed, renameMap } = hashStaticAssets(staticBuildDir);\n if (renamed > 0) {\n staticRenameMap = renameMap;\n console.log(` 🏷️ static assets hashed (${renamed} files)`);\n }\n }\n\n // [3.2] 编译 main.js 为 main.jsc 字节码(如果 jsc 工具可用)\n let mainFileName = 'main.js';\n const mainJsPath = join(buildDir, 'main.js');\n const mainJscPath = join(buildDir, 'main.jsc');\n try {\n const jscCmd = findJscBinary();\n if (!jscCmd) {\n throw new Error('jsc binary not found');\n }\n execFileSync(jscCmd, [mainJsPath, mainJscPath], { stdio: 'pipe' });\n // 编译成功,删除 main.js\n unlinkSync(mainJsPath);\n mainFileName = 'main.jsc';\n console.log(` 🔒 main.js compiled → main.jsc (via ${jscCmd})`);\n } catch {\n // jsc 可能在失败前已经创建了不完整的输出。回退到 main.js 时必须删除它,\n // 否则宿主会优先加载 main.jsc,并与按 main.js 计算的 entryHash 失配。\n if (existsSync(mainJscPath)) {\n unlinkSync(mainJscPath);\n }\n console.log(` ⚠️ jsc not available, keeping main.js`);\n }\n\n // [4] 计算 entryHash\n const mainJsContent = readFileSync(join(buildDir, mainFileName));\n const entryHash = computeEntryHash(mainJsContent);\n\n // [5] 计算 zipHash(排除 plugin.json)\n const zipHash = computeCanonicalZipHash(buildDir);\n\n // [6] 写入最终 plugin.json(含 hash)\n const finalManifest: PluginManifest = {\n ...manifest,\n main: mainFileName,\n entryHash,\n zipHash,\n };\n // icon 字段回写:用 hash 后的实际文件名替换原始文件名\n if (finalManifest.icon && staticRenameMap) {\n const hashedIcon = staticRenameMap.get(finalManifest.icon);\n if (hashedIcon) {\n finalManifest.icon = hashedIcon;\n }\n }\n writeFileSync(join(buildDir, 'plugin.json'), JSON.stringify(finalManifest, null, 2));\n\n // [7] 打包为 .jsplugin.zip\n mkdirSync(outDir, { recursive: true });\n const zip = new JSZip();\n addDirToZip(zip, buildDir, '');\n const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });\n const zipPath = join(outDir, `${manifest.entryPath}.jsplugin.zip`);\n writeFileSync(zipPath, zipBuffer);\n\n // [8] 输出报告\n const mainJsGzip = Buffer.byteLength(mainJsContent);\n console.log(`\\n✅ Build successful!`);\n console.log(` 📦 ${zipPath} (${(zipBuffer.length / 1024).toFixed(1)} KB)`);\n console.log(` 📄 main.js: ${(mainJsGzip / 1024).toFixed(1)} KB`);\n console.log(` 🔑 entryHash: ${entryHash}`);\n console.log(` 🔑 zipHash: ${zipHash}\\n`);\n\n return { zipPath, manifest: finalManifest, size: zipBuffer.length, entryHash, zipHash };\n}\n\n/**\n * 校验已构建的插件\n */\nexport async function validatePlugin(cwd: string): Promise<ValidationResult> {\n const resolvedCwd = resolve(cwd);\n const errors: { field: string; message: string }[] = [];\n\n // 读取 manifest\n let manifest: PluginManifest;\n try {\n manifest = readManifest(resolvedCwd);\n } catch {\n return { valid: false, errors: [{ field: 'plugin.json', message: 'cannot read plugin.json' }] };\n }\n\n // 字段校验\n const fieldErrors = validateManifest(manifest);\n errors.push(...fieldErrors);\n\n // hash 校验\n if (!manifest.entryHash || !manifest.zipHash) {\n errors.push({ field: 'hash', message: 'entryHash and zipHash are required. Run `songloft-plugin build` first.' });\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// --- 工具 ---\n\nimport { getJscBinaryPath } from '@songloft/jsc';\nimport { readdirSync, statSync } from 'node:fs';\n\n/**\n * 查找 jsc 二进制文件\n * 优先级:\n * 1. @songloft/jsc workspace 包中对应当前平台的预编译二进制\n * 2. PATH 中的 jsc 命令\n * 3. 项目根目录的 jsc 兼容旧路径\n */\nfunction findJscBinary(): string | null {\n // 获取当前文件所在目录(兼容 ESM 和 CJS)\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n // 1. 通过 @songloft/jsc 包定位预编译二进制\n try {\n const jscPath = getJscBinaryPath();\n if (existsSync(jscPath)) return jscPath;\n } catch {\n // 包未安装,继续尝试下一个路径\n }\n\n // 2. 检查 PATH 中的 jsc\n try {\n execFileSync('jsc', ['--help'], { stdio: 'pipe' });\n return 'jsc';\n } catch {\n // 继续尝试下一个路径\n }\n\n // 3. 兼容旧路径:项目根目录的 jsc (songloft/jsc)\n // 从 src/ 或 dist/ → plugin-builder/ → packages/ → plugin-toolchain/ → songloft/\n const projectJsc = join(currentDir, '..', '..', '..', '..', 'jsc');\n if (existsSync(projectJsc)) return projectJsc;\n\n return null;\n}\n\nfunction addDirToZip(zip: JSZip, dirPath: string, prefix: string) {\n const items = readdirSync(dirPath);\n for (const item of items) {\n const fullPath = join(dirPath, item);\n const zipPath = prefix ? `${prefix}/${item}` : item;\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n addDirToZip(zip, fullPath, zipPath);\n } else {\n zip.file(zipPath, readFileSync(fullPath));\n }\n }\n}\n","// @songloft/plugin-builder — manifest 校验模块\n\nimport type { PluginManifest } from '@songloft/plugin-sdk';\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface ManifestValidationError {\n field: string;\n message: string;\n}\n\nconst ENTRY_PATH_REGEX = /^[a-z][a-z0-9-]*$/;\n// 渲染引擎白名单,需与后端 internal/jsplugin 的校验保持一致。\n// 可选字段:缺省或空串 = webview(宿主默认)。\nconst VALID_RENDER_ENGINES = ['webview', 'lynx'];\nconst SEMVER_REGEX = /^\\d+\\.\\d+\\.\\d+/;\n// 权限白名单,需与后端 internal/jsplugin/permissions.go 的 AllPermissions 保持一致。\n// songs.* / playlists.* / fs.* 为声明层的通配符糖(一把梭)。\nconst VALID_PERMISSIONS = [\n 'storage',\n 'songs.read',\n 'songs.write',\n 'playlists.read',\n 'playlists.write',\n 'inter-plugin',\n 'command',\n 'jsenv',\n 'fs',\n 'fs:music',\n 'fs:external',\n 'websocket',\n 'persistent-storage',\n 'net',\n 'net:insecure-tls',\n 'tags.read',\n 'tags.write',\n 'songs.*',\n 'playlists.*',\n 'tags.*',\n 'fs.*',\n];\n\n/**\n * 从 cwd 读取 plugin.json\n */\nexport function readManifest(cwd: string): PluginManifest {\n const raw = readFileSync(join(cwd, 'plugin.json'), 'utf-8');\n return JSON.parse(raw) as PluginManifest;\n}\n\n/**\n * 校验 plugin.json 字段\n */\nexport function validateManifest(m: PluginManifest): ManifestValidationError[] {\n const errors: ManifestValidationError[] = [];\n\n if (!m.name || m.name.length < 2 || m.name.length > 50) {\n errors.push({ field: 'name', message: 'name must be 2-50 characters' });\n }\n if (!m.version || !SEMVER_REGEX.test(m.version)) {\n errors.push({ field: 'version', message: 'version must be valid semver (x.y.z)' });\n }\n if (!m.entryPath || !ENTRY_PATH_REGEX.test(m.entryPath)) {\n errors.push({ field: 'entryPath', message: 'entryPath must be lowercase kebab-case starting with a letter' });\n }\n if (!m.main || (!m.main.endsWith('.js') && !m.main.endsWith('.jsc'))) {\n errors.push({ field: 'main', message: 'main must end with .js or .jsc' });\n }\n // renderEngine 可选:未声明或空串走宿主默认(webview),仅校验显式给出的非法值\n const renderEngine = m.renderEngine as string | undefined;\n if (renderEngine !== undefined && renderEngine !== '' && !VALID_RENDER_ENGINES.includes(renderEngine)) {\n errors.push({\n field: 'renderEngine',\n message: `renderEngine must be one of ${VALID_RENDER_ENGINES.join(' | ')} (got: ${renderEngine})`,\n });\n }\n if (!Array.isArray(m.permissions)) {\n errors.push({ field: 'permissions', message: 'permissions must be an array' });\n } else {\n for (const perm of m.permissions) {\n if (!VALID_PERMISSIONS.includes(perm)) {\n errors.push({ field: 'permissions', message: `unknown permission: ${perm}` });\n }\n }\n }\n\n return errors;\n}\n","// @songloft/plugin-builder — hash 计算模块\n// 与后端 Go 版本 ComputeCanonicalZipHash / ComputeEntryHash 算法完全一致。\n\nimport { createHash } from 'node:crypto';\nimport { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, posix } from 'node:path';\n\n/**\n * sha256 hex\n */\nexport function sha256Hex(data: Buffer | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * 计算 entryHash(main.js 的 sha256)\n */\nexport function computeEntryHash(mainJsContent: Buffer | string): string {\n return sha256Hex(mainJsContent);\n}\n\n/**\n * 计算 canonical zipHash。\n *\n * 算法(与后端保持一致):\n * 1. 枚举 buildDir 下所有文件(排除 plugin.json)\n * 2. 按路径 Unicode 升序排序(使用 posix 风格的路径分隔符)\n * 3. 对每个文件:hasher.write(path + \"\\n\" + sha256Hex(content) + \"\\n\")\n * 4. 对最终拼接串再 sha256\n */\nexport function computeCanonicalZipHash(buildDir: string): string {\n const entries: { path: string; hash: string }[] = [];\n\n function walk(dir: string) {\n const items = readdirSync(dir);\n for (const item of items) {\n const fullPath = join(dir, item);\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else {\n const relPath = posix.normalize(relative(buildDir, fullPath).replace(/\\\\/g, '/'));\n if (relPath === 'plugin.json') continue;\n const content = readFileSync(fullPath);\n entries.push({ path: relPath, hash: sha256Hex(content) });\n }\n }\n }\n\n walk(buildDir);\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n\n const hasher = createHash('sha256');\n for (const e of entries) {\n hasher.update(e.path + '\\n' + e.hash + '\\n');\n }\n return hasher.digest('hex');\n}\n","// @songloft/plugin-builder — 前端静态资源 hash 处理\n//\n// 为 static/ 目录下的 JS/CSS/字体/图片等资源注入内容 hash 到文件名,\n// 并改写 HTML 中的 <script src> / <link href> 与 CSS 中的 url() 引用,\n// 防止插件版本更新后浏览器仍命中旧缓存。\n//\n// 处理顺序(按依赖反向):\n// 1. 叶子资源(字体/图片/媒体)先 hash\n// 2. CSS 改写内部 url(...) 后再 hash\n// 3. JS 单独 hash(不扫描内部内容)\n// 4. HTML 改写 <script src> / <link href> 等引用\n\nimport { readFileSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs';\nimport { join, dirname, basename, posix, relative } from 'node:path';\nimport { sha256Hex } from './hash.js';\n\nconst ASSET_EXT = /\\.(woff2?|ttf|otf|eot|png|jpe?g|gif|svg|webp|ico|mp3|mp4|wav|ogg)$/i;\nconst CSS_EXT = /\\.css$/i;\nconst JS_EXT = /\\.m?js$/i;\nconst HTML_EXT = /\\.html?$/i;\n\nconst HASH_LEN = 8;\n\n/**\n * 文件名\"看起来已经 hash 过\"的检测。\n * 匹配 `name.<8+位 url-safe base64/hex>.ext` 或 `name-<同上>.ext`,\n * 用于跳过已由 Vite/Webpack/Rollup 等工具自管理 hash 的产物。\n *\n * 注意:要保留至少一段\"语义名\",避免把 `roboto-400.woff2`(400 仅 3 位)\n * 或纯 hash 文件名误判。\n */\nconst HASHED_NAME_RE = /^(.+)[.-]([A-Za-z0-9_-]{8,})\\.[^.]+$/;\nfunction looksAlreadyHashed(filename: string): boolean {\n const m = HASHED_NAME_RE.exec(filename);\n if (!m) return false;\n const seg = m[2];\n // 8+ 位且由 hex 字符组成即视为 hash(含纯数字情况如 67058905)\n return /^[A-Fa-f0-9]{8,}$/.test(seg) || (/[A-Za-z]/.test(seg) && /\\d/.test(seg));\n}\n\n/**\n * 入口:hash static 目录下的资源并改写引用。\n * staticBuildDir 必须存在;不存在时由调用方判断后再传入。\n */\nexport function hashStaticAssets(staticBuildDir: string): { renamed: number; renameMap: Map<string, string> } {\n const all = walk(staticBuildDir);\n const rel = (p: string) => toPosix(relative(staticBuildDir, p));\n\n const assets = all.filter(p => ASSET_EXT.test(p));\n const cssList = all.filter(p => CSS_EXT.test(p));\n const jsList = all.filter(p => JS_EXT.test(p));\n const htmlList = all.filter(p => HTML_EXT.test(p));\n\n // 先扫描所有 CSS/HTML/JS,把\"被绝对路径(含 /static/)引用\"的资源加入\n // pinned 集合——这些文件不能改名,否则会破坏运行时引用。\n const pinned = collectPinnedAssets([...htmlList, ...cssList, ...jsList], rel, staticBuildDir);\n const notPinned = (p: string) => !pinned.has(rel(p));\n\n // 原相对路径 → 新相对路径(含 hash),均为 posix 风格\n const renameMap = new Map<string, string>();\n\n // 1. 叶子资源\n for (const file of assets.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 2. CSS:先改写 url(),再 hash\n for (const file of cssList) {\n const relPath = rel(file);\n const content = readFileSync(file, 'utf-8');\n const rewritten = rewriteCssUrls(content, relPath, renameMap);\n if (rewritten !== content) writeFileSync(file, rewritten);\n if (pinned.has(relPath)) continue;\n const newRel = renameWithHash(staticBuildDir, relPath);\n renameMap.set(relPath, newRel);\n }\n\n // 3. JS\n for (const file of jsList.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 4. HTML:改写引用\n for (const file of htmlList) {\n const relPath = rel(file);\n const html = readFileSync(file, 'utf-8');\n const rewritten = rewriteHtmlRefs(html, relPath, renameMap);\n if (rewritten !== html) writeFileSync(file, rewritten);\n }\n\n return { renamed: renameMap.size, renameMap };\n}\n\n// --- 内部工具 ---\n\n/**\n * 扫描指定文件(CSS/HTML/JS),找出\"被含 /static/ 的绝对路径引用\"的资源,\n * 比如 CSS 里 url('/api/v1/plugin/lxmusic/static/fonts/roboto.woff2')。\n * 这些资源不能改名,否则运行时绝对路径会 404。\n *\n * 返回的 set 包含相对 staticDir 的 posix 路径。\n */\nfunction collectPinnedAssets(\n files: string[],\n rel: (p: string) => string,\n staticDir: string,\n): Set<string> {\n const pinned = new Set<string>();\n // 匹配引号内或 url(...) 内出现的、含 /static/<rest> 的串\n const re = /\\/(?:[^\\s\"')]*\\/)?static\\/([A-Za-z0-9_\\-./]+?)(?=[\"')?#\\s]|$)/g;\n for (const file of files) {\n let content: string;\n try {\n content = readFileSync(file, 'utf-8');\n } catch {\n continue;\n }\n for (const m of content.matchAll(re)) {\n const candidate = m[1].replace(/\\/+$/, '');\n if (!candidate) continue;\n // 仅当该路径在 static 下真实存在\n const abs = join(staticDir, candidate);\n try {\n if (statSync(abs).isFile()) pinned.add(candidate);\n } catch {\n // 不存在,忽略\n }\n }\n }\n return pinned;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const item of readdirSync(dir)) {\n const full = join(dir, item);\n const st = statSync(full);\n if (st.isDirectory()) out.push(...walk(full));\n else out.push(full);\n }\n return out;\n}\n\nfunction toPosix(p: string): string {\n return p.split(/[\\\\/]/).join('/');\n}\n\n/**\n * 重命名文件:name.ext → name.<hash>.ext。返回新相对路径(posix)。\n * 若文件名已经包含可识别的 hash(来自 Vite/Webpack 等),则原路径直接返回,不动文件。\n */\nfunction renameWithHash(rootDir: string, relPath: string): string {\n const base = basename(relPath);\n if (looksAlreadyHashed(base)) return relPath;\n const abs = join(rootDir, relPath);\n const hash = sha256Hex(readFileSync(abs)).slice(0, HASH_LEN);\n const dir = dirname(relPath);\n const dot = base.lastIndexOf('.');\n const newBase = dot <= 0\n ? `${base}.${hash}`\n : `${base.slice(0, dot)}.${hash}${base.slice(dot)}`;\n const newRel = dir === '.' || dir === '' ? newBase : posix.join(toPosix(dir), newBase);\n renameSync(abs, join(rootDir, newRel));\n return newRel;\n}\n\ninterface ResolvedRef {\n /** 相对 static 根的路径,用作 renameMap key */\n staticRel: string;\n /** ?query#hash 后缀 */\n suffix: string;\n /** 原 url 是否带 \"static/\" 前缀(HTML 中常见) */\n hadStaticPrefix: boolean;\n /** 原 url 是否以 ./ 或 ../ 开头 */\n isExplicitRelative: boolean;\n}\n\n/**\n * 把出现在 fromFile(相对 static 根的路径)中的 url 解析为\n * 相对 static 根的资源路径,便于在 renameMap 中查找。\n *\n * 支持:\n * - \"static/css/style.css\" —— HTML 中从插件根访问\n * - \"css/style.css\" —— 从当前文件同目录访问\n * - \"./x.png\" / \"../foo\"\n *\n * 不处理:绝对路径(/...)、协议(http://、data:、blob: 等)、\n * 锚点(#xxx)、空 url。\n */\nfunction resolveRef(url: string, fromFile: string): ResolvedRef | null {\n if (!url) return null;\n if (/^(?:[a-z]+:|\\/\\/|#|data:|blob:|mailto:)/i.test(url)) return null;\n if (url.startsWith('/')) return null;\n\n let bare = url;\n let suffix = '';\n const qIdx = bare.search(/[?#]/);\n if (qIdx >= 0) {\n suffix = bare.slice(qIdx);\n bare = bare.slice(0, qIdx);\n }\n\n const hadStaticPrefix = bare.startsWith('static/');\n const isExplicitRelative = bare.startsWith('./') || bare.startsWith('../');\n\n let staticRel: string;\n if (hadStaticPrefix) {\n staticRel = bare.slice('static/'.length);\n } else {\n const fromDir = toPosix(dirname(fromFile));\n staticRel = fromDir === '.' || fromDir === ''\n ? bare.replace(/^\\.\\//, '')\n : posix.normalize(posix.join(fromDir, bare));\n }\n if (staticRel.startsWith('..')) return null;\n return { staticRel, suffix, hadStaticPrefix, isExplicitRelative };\n}\n\n/**\n * 根据 renameMap 重新组装引用字符串。renameMap 未命中时返回 null。\n */\nfunction applyRename(\n ref: ResolvedRef,\n renameMap: Map<string, string>,\n fromFile: string,\n): string | null {\n const renamed = renameMap.get(ref.staticRel);\n if (!renamed) return null;\n\n let out: string;\n if (ref.hadStaticPrefix) {\n out = `static/${renamed}`;\n } else {\n const fromDir = toPosix(dirname(fromFile));\n if (fromDir === '.' || fromDir === '') {\n out = renamed;\n } else {\n out = toPosix(relative(fromDir, renamed));\n }\n if (ref.isExplicitRelative && !out.startsWith('.')) out = `./${out}`;\n }\n return out + ref.suffix;\n}\n\nfunction tryRewrite(url: string, fromFile: string, renameMap: Map<string, string>): string | null {\n const ref = resolveRef(url, fromFile);\n if (!ref) return null;\n return applyRename(ref, renameMap, fromFile);\n}\n\n/** 改写 HTML 中的 src=/href= 引用 */\nfunction rewriteHtmlRefs(html: string, fromFile: string, renameMap: Map<string, string>): string {\n return html.replace(/\\b(src|href)\\s*=\\s*([\"'])([^\"']+)\\2/gi, (full, attr, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `${attr}=${quote}${replaced}${quote}`;\n });\n}\n\n/** 改写 CSS 中的 url(...) 与 @import \"...\" */\nfunction rewriteCssUrls(css: string, fromFile: string, renameMap: Map<string, string>): string {\n css = css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `url(${quote}${replaced}${quote})`;\n });\n css = css.replace(/@import\\s+(['\"])([^'\"]+)\\1/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `@import ${quote}${replaced}${quote}`;\n });\n return css;\n}\n","/**\n * Auto-generated index.html for Lynx plugins — Flutter WebView fallback.\n *\n * When a plugin declares renderEngine: \"lynx\", the builder produces this HTML\n * alongside the .lynx.bundle and .web.bundle. Flutter's WebView loads this page,\n * which bootstraps @lynx-js/web-core + the .web.bundle, making one ReactLynx\n * codebase render everywhere.\n */\n\nexport function generateLynxIndexHtml(entryPath: string): string {\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no\">\n <title>${entryPath}</title>\n <link href=\"../../jsplugin-assets/web-core/static/css/client.css\" rel=\"stylesheet\">\n <style>\n html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }\n lynx-view { width: 100vw; height: 100vh; display: block; }\n </style>\n</head>\n<body>\n <lynx-view id=\"plugin-view\"></lynx-view>\n <script type=\"module\" src=\"../../jsplugin-assets/web-core/static/js/client.js\"></script>\n <script type=\"module\" src=\"../../jsplugin-assets/lynx-plugin-bridge-shim.js\"></script>\n</body>\n</html>\n`;\n}\n"],"mappings":";;;;;;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;AACjE,UAAI,4BAAW,UAAU,EAAG,QAAO;AAEnC,SAAO;AACT;AAEA,SAAS,YAAY,KAAY,SAAiB,QAAgB;AAChE,QAAM,YAAQ,6BAAY,OAAO;AACjC,aAAW,QAAQ,OAAO;AACxB,UAAM,eAAW,wBAAK,SAAS,IAAI;AACnC,UAAM,UAAU,SAAS,GAAG,MAAM,IAAI,IAAI,KAAK;AAC/C,UAAM,WAAO,0BAAS,QAAQ;AAC9B,QAAI,KAAK,YAAY,GAAG;AACtB,kBAAY,KAAK,UAAU,OAAO;AAAA,IACpC,OAAO;AACL,UAAI,KAAK,aAAS,8BAAa,QAAQ,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;","names":["import_node_fs","import_node_path","import_node_fs","import_node_path","walk","import_node_fs","import_node_path","import_node_fs","build","readdirSyncTop","JSZip"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/build.ts","../src/manifest.ts","../src/hash.ts","../src/static-assets.ts","../src/lynx-index-html.ts","../src/frontend-npm.ts"],"sourcesContent":["// @songloft/plugin-builder — public API\nexport { buildPlugin, validatePlugin } from './build.js';\nexport type { BuildOptions, BuildResult, ValidationResult } from './build.js';\nexport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nexport { readManifest, validateManifest } from './manifest.js';\nexport type { ManifestValidationError } from './manifest.js';\n","// @songloft/plugin-builder — 核心 build 逻辑\n\nimport * as esbuild from 'esbuild';\nimport JSZip from 'jszip';\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, cpSync, unlinkSync, rmSync, readdirSync as readdirSyncTop } from 'node:fs';\nimport { join, resolve, dirname } from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { readManifest, validateManifest } from './manifest.js';\nimport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nimport { hashStaticAssets } from './static-assets.js';\nimport { generateLynxIndexHtml } from './lynx-index-html.js';\nimport type { PluginManifest } from '@songloft/plugin-sdk';\n\nimport { runFrontendNpm } from './frontend-npm.js';\n\nexport interface BuildOptions {\n cwd: string;\n outDir?: string;\n mode?: 'development' | 'production';\n sourcemap?: boolean;\n}\n\nexport interface BuildResult {\n zipPath: string;\n manifest: PluginManifest;\n size: number;\n entryHash: string;\n zipHash: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: { field: string; message: string }[];\n}\n\n/**\n * 构建插件:TS/JS → QuickJS-compatible JS → .jsplugin.zip\n */\nexport async function buildPlugin(opts: BuildOptions): Promise<BuildResult> {\n const cwd = resolve(opts.cwd);\n const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join(cwd, 'dist');\n const buildDir = join(outDir, '_build');\n const mode = opts.mode ?? 'production';\n\n // [1] 读取并校验 plugin.json\n const manifest = readManifest(cwd);\n const errors = validateManifest(manifest);\n if (errors.length > 0) {\n throw new Error(`Invalid plugin.json:\\n${errors.map(e => ` - ${e.field}: ${e.message}`).join('\\n')}`);\n }\n\n // [2] esbuild 打包 src/main.ts → build/main.js\n //\n // _build 是**纯暂存目录**:最后整目录进 zip(addDirToZip(zip, buildDir, ''))且整目录\n // 参与 computeCanonicalZipHash。所以它必须每次从零开始 —— 否则 [3.1.1] 步注入内容 hash\n // 产出的 `style.<hash>.css` 会**逐次堆积**:同一份源码构建多次,zip 里会带上历史所有版本\n // 的资源(实测 downloader 连构 4 次后 zip 里有 4 份 style.*.css),而 index.html 只引用\n // 最新那份。后果不只是体积——`zipHash` 会随构建历史漂移,同样的源码算出不同的哈希,\n // 这条哈希的完整性用途就没了。cpSync 是合并语义、不会替我们清,只能显式删。\n rmSync(buildDir, { recursive: true, force: true });\n mkdirSync(buildDir, { recursive: true });\n const entryPoint = join(cwd, 'src', 'main.ts');\n const entryPointAlt = join(cwd, 'src', 'main.js');\n const actualEntry = existsSync(entryPoint) ? entryPoint : entryPointAlt;\n\n if (!existsSync(actualEntry)) {\n throw new Error(`Entry file not found: src/main.ts or src/main.js`);\n }\n\n await esbuild.build({\n entryPoints: [actualEntry],\n outfile: join(buildDir, 'main.js'),\n bundle: true,\n platform: 'neutral',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n sourcemap: opts.sourcemap ? 'inline' : false,\n // 禁止使用 Node 内置模块\n plugins: [{\n name: 'no-node-builtins',\n setup(build) {\n build.onResolve({ filter: /^(fs|net|http|https|child_process|os|path|crypto|stream|util|events|buffer|url|querystring|zlib)$/ }, (args) => {\n return { errors: [{ text: `Node builtin \"${args.path}\" is not available in QuickJS runtime` }] };\n });\n },\n }],\n });\n\n // [2.5] 前端 Vue/Vite 编译(如果存在 frontend/ 目录)\n const frontendDir = join(cwd, 'frontend');\n if (existsSync(join(frontendDir, 'package.json'))) {\n // 仅在依赖缺失时安装:dev 模式每次热重载都会走到这里,无脑 npm install 会拖慢重建\n if (!existsSync(join(frontendDir, 'node_modules'))) {\n console.log(` 📦 Installing frontend dependencies...`);\n runFrontendNpm(frontendDir, 'install');\n }\n console.log(` 🚀 Building frontend project...`);\n runFrontendNpm(frontendDir, 'build');\n // 根据模板配置,产物会被直接输出到 cwd/static。但为了兼容自定义 dist 输出,加一个 fallback 拷贝:\n if (existsSync(join(frontendDir, 'dist'))) {\n cpSync(join(frontendDir, 'dist'), join(buildDir, 'static'), { recursive: true });\n }\n }\n\n // [2.6] Lynx 插件后处理:rspeedy 产出 dist/lynx/ 和 dist/web/ 子目录,\n // 将 bundle 文件提升到 static/ 根并生成 Flutter WebView 用的 index.html。\n if (manifest.renderEngine === 'lynx') {\n const staticOut = join(buildDir, 'static');\n const lynxBundleDir = join(staticOut, 'lynx');\n const webBundleDir = join(staticOut, 'web');\n mkdirSync(staticOut, { recursive: true });\n\n const lynxBundle = join(lynxBundleDir, 'main.lynx.bundle');\n const webBundle = join(webBundleDir, 'main.web.bundle');\n\n let webBundleVersion: string | undefined;\n if (existsSync(lynxBundle)) {\n cpSync(lynxBundle, join(staticOut, 'main.lynx.bundle'));\n }\n if (existsSync(webBundle)) {\n cpSync(webBundle, join(staticOut, 'main.web.bundle'));\n // SHA-256 前 16 位,与 MIoT/Bili 插件侧声明的版本格式一致。\n webBundleVersion = sha256Hex(readFileSync(webBundle)).slice(0, 16);\n }\n\n // Remove the intermediate subdirectories\n rmSync(lynxBundleDir, { recursive: true, force: true });\n rmSync(webBundleDir, { recursive: true, force: true });\n\n // Generate index.html for Flutter WebView fallback (loads web-core + .web.bundle)\n writeFileSync(join(staticOut, 'index.html'), generateLynxIndexHtml(manifest.entryPath, webBundleVersion));\n\n console.log(` 🔗 Lynx bundles flattened + index.html generated`);\n }\n\n // [3] 拷贝 static/ 到 build/(如果存在)\n const staticDir = join(cwd, 'static');\n if (existsSync(staticDir)) {\n cpSync(staticDir, join(buildDir, 'static'), { recursive: true });\n }\n\n // [3.0] 拷贝 bin/ 到 build/(如果存在,用于打包可执行文件)\n const binDir = join(cwd, 'bin');\n if (existsSync(binDir)) {\n cpSync(binDir, join(buildDir, 'bin'), { recursive: true });\n }\n\n // [3.1] 合并打包前端 JS(如果 static/js/app.js 存在)\n const staticJsAppPath = join(buildDir, 'static', 'js', 'app.js');\n if (existsSync(staticJsAppPath)) {\n const bundleOutPath = join(buildDir, 'static', 'js', 'app.bundle.js');\n await esbuild.build({\n entryPoints: [staticJsAppPath],\n outfile: bundleOutPath,\n bundle: true,\n platform: 'browser',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n });\n\n // 删除 static/js/ 下除 app.bundle.js 外的所有 .js 文件\n const staticJsDir = join(buildDir, 'static', 'js');\n const jsFiles = readdirSyncTop(staticJsDir).filter(f => f.endsWith('.js') && f !== 'app.bundle.js');\n for (const f of jsFiles) {\n unlinkSync(join(staticJsDir, f));\n }\n\n // 更新 index.html 中的 script 引用:将 app.js 替换为打包后的 app.bundle.js\n // 匹配时兼容属性顺序不同、多空格、以及 src 中有无 static/ 前缀\n const indexHtmlPath = join(buildDir, 'static', 'index.html');\n if (existsSync(indexHtmlPath)) {\n let html = readFileSync(indexHtmlPath, 'utf-8');\n const before = html;\n html = html.replace(\n /<script\\b[^>]*\\bsrc=\"(?:static\\/)?js\\/app\\.js\"[^>]*><\\/script>/,\n '<script src=\"static/js/app.bundle.js\"></script>'\n );\n if (html === before) {\n throw new Error(\n 'Failed to update script tag in static/index.html: ' +\n 'expected <script ... src=\"static/js/app.js\" ...> or <script ... src=\"js/app.js\" ...> but pattern not found'\n );\n }\n writeFileSync(indexHtmlPath, html);\n }\n\n console.log(` 📦 static/js/ bundled → app.bundle.js (${jsFiles.length} files merged)`);\n }\n\n // [3.1.1] 为 static/ 下所有 JS/CSS/字体/图片注入内容 hash 到文件名,\n // 并改写 HTML/CSS 中的引用,防止插件更新后浏览器使用旧缓存。\n // 可在 plugin.json 中设置 \"staticHash\": false 关闭(用于前端已用\n // Vite/Webpack 等工具自管理 hash 的场景)。\n const staticBuildDir = join(buildDir, 'static');\n let staticRenameMap: Map<string, string> | undefined;\n if (existsSync(staticBuildDir) && manifest.staticHash !== false) {\n const { renamed, renameMap } = hashStaticAssets(staticBuildDir);\n if (renamed > 0) {\n staticRenameMap = renameMap;\n console.log(` 🏷️ static assets hashed (${renamed} files)`);\n }\n }\n\n // [3.2] 编译 main.js 为 main.jsc 字节码(如果 jsc 工具可用)\n let mainFileName = 'main.js';\n const mainJsPath = join(buildDir, 'main.js');\n const mainJscPath = join(buildDir, 'main.jsc');\n try {\n const jscCmd = findJscBinary();\n if (!jscCmd) {\n throw new Error('jsc binary not found');\n }\n execFileSync(jscCmd, [mainJsPath, mainJscPath], { stdio: 'pipe' });\n // 编译成功,删除 main.js\n unlinkSync(mainJsPath);\n mainFileName = 'main.jsc';\n console.log(` 🔒 main.js compiled → main.jsc (via ${jscCmd})`);\n } catch {\n // jsc 可能在失败前已经创建了不完整的输出。回退到 main.js 时必须删除它,\n // 否则宿主会优先加载 main.jsc,并与按 main.js 计算的 entryHash 失配。\n if (existsSync(mainJscPath)) {\n unlinkSync(mainJscPath);\n }\n console.log(` ⚠️ jsc not available, keeping main.js`);\n }\n\n // [4] 计算 entryHash\n const mainJsContent = readFileSync(join(buildDir, mainFileName));\n const entryHash = computeEntryHash(mainJsContent);\n\n // [5] 计算 zipHash(排除 plugin.json)\n const zipHash = computeCanonicalZipHash(buildDir);\n\n // [6] 写入最终 plugin.json(含 hash)\n const finalManifest: PluginManifest = {\n ...manifest,\n main: mainFileName,\n entryHash,\n zipHash,\n };\n // icon 字段回写:用 hash 后的实际文件名替换原始文件名\n if (finalManifest.icon && staticRenameMap) {\n const hashedIcon = staticRenameMap.get(finalManifest.icon);\n if (hashedIcon) {\n finalManifest.icon = hashedIcon;\n }\n }\n writeFileSync(join(buildDir, 'plugin.json'), JSON.stringify(finalManifest, null, 2));\n\n // [7] 打包为 .jsplugin.zip\n mkdirSync(outDir, { recursive: true });\n const zip = new JSZip();\n addDirToZip(zip, buildDir, '');\n const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });\n const zipPath = join(outDir, `${manifest.entryPath}.jsplugin.zip`);\n writeFileSync(zipPath, zipBuffer);\n\n // [8] 输出报告\n const mainJsGzip = Buffer.byteLength(mainJsContent);\n console.log(`\\n✅ Build successful!`);\n console.log(` 📦 ${zipPath} (${(zipBuffer.length / 1024).toFixed(1)} KB)`);\n console.log(` 📄 main.js: ${(mainJsGzip / 1024).toFixed(1)} KB`);\n console.log(` 🔑 entryHash: ${entryHash}`);\n console.log(` 🔑 zipHash: ${zipHash}\\n`);\n\n return { zipPath, manifest: finalManifest, size: zipBuffer.length, entryHash, zipHash };\n}\n\n/**\n * 校验已构建的插件\n */\nexport async function validatePlugin(cwd: string): Promise<ValidationResult> {\n const resolvedCwd = resolve(cwd);\n const errors: { field: string; message: string }[] = [];\n\n // 读取 manifest\n let manifest: PluginManifest;\n try {\n manifest = readManifest(resolvedCwd);\n } catch {\n return { valid: false, errors: [{ field: 'plugin.json', message: 'cannot read plugin.json' }] };\n }\n\n // 字段校验\n const fieldErrors = validateManifest(manifest);\n errors.push(...fieldErrors);\n\n // hash 校验\n if (!manifest.entryHash || !manifest.zipHash) {\n errors.push({ field: 'hash', message: 'entryHash and zipHash are required. Run `songloft-plugin build` first.' });\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// --- 工具 ---\n\nimport { getJscBinaryPath } from '@songloft/jsc';\nimport { readdirSync, statSync } from 'node:fs';\n\n/**\n * 查找 jsc 二进制文件\n * 优先级:\n * 1. @songloft/jsc workspace 包中对应当前平台的预编译二进制\n * 2. PATH 中的 jsc 命令\n * 3. 项目根目录的 jsc 兼容旧路径\n */\nfunction findJscBinary(): string | null {\n // 获取当前文件所在目录(兼容 ESM 和 CJS)\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n // 1. 通过 @songloft/jsc 包定位预编译二进制\n try {\n const jscPath = getJscBinaryPath();\n if (existsSync(jscPath)) return jscPath;\n } catch {\n // 包未安装,继续尝试下一个路径\n }\n\n // 2. 检查 PATH 中的 jsc\n try {\n execFileSync('jsc', ['--help'], { stdio: 'pipe' });\n return 'jsc';\n } catch {\n // 继续尝试下一个路径\n }\n\n // 3. 兼容旧路径:项目根目录的 jsc (songloft/jsc)\n // 从 src/ 或 dist/ → plugin-builder/ → packages/ → plugin-toolchain/ → songloft/\n const projectJsc = join(currentDir, '..', '..', '..', '..', 'jsc');\n if (existsSync(projectJsc)) return projectJsc;\n\n return null;\n}\n\nfunction addDirToZip(zip: JSZip, dirPath: string, prefix: string) {\n const items = readdirSync(dirPath);\n for (const item of items) {\n const fullPath = join(dirPath, item);\n const zipPath = prefix ? `${prefix}/${item}` : item;\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n addDirToZip(zip, fullPath, zipPath);\n } else {\n zip.file(zipPath, readFileSync(fullPath));\n }\n }\n}\n","// @songloft/plugin-builder — manifest 校验模块\n\nimport type { PluginManifest } from '@songloft/plugin-sdk';\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface ManifestValidationError {\n field: string;\n message: string;\n}\n\nconst ENTRY_PATH_REGEX = /^[a-z][a-z0-9-]*$/;\n// 渲染引擎白名单,需与后端 internal/jsplugin 的校验保持一致。\n// 可选字段:缺省或空串 = webview(宿主默认)。\nconst VALID_RENDER_ENGINES = ['webview', 'lynx'];\nconst SEMVER_REGEX = /^\\d+\\.\\d+\\.\\d+/;\n// 权限白名单,需与后端 internal/jsplugin/permissions.go 的 AllPermissions 保持一致。\n// songs.* / playlists.* / fs.* 为声明层的通配符糖(一把梭)。\nconst VALID_PERMISSIONS = [\n 'storage',\n 'songs.read',\n 'songs.write',\n 'playlists.read',\n 'playlists.write',\n 'inter-plugin',\n 'command',\n 'jsenv',\n 'fs',\n 'fs:music',\n 'fs:external',\n 'websocket',\n 'persistent-storage',\n 'net',\n 'net:insecure-tls',\n 'tags.read',\n 'tags.write',\n 'songs.*',\n 'playlists.*',\n 'tags.*',\n 'fs.*',\n];\n\n/**\n * 从 cwd 读取 plugin.json\n */\nexport function readManifest(cwd: string): PluginManifest {\n const raw = readFileSync(join(cwd, 'plugin.json'), 'utf-8');\n return JSON.parse(raw) as PluginManifest;\n}\n\n/**\n * 校验 plugin.json 字段\n */\nexport function validateManifest(m: PluginManifest): ManifestValidationError[] {\n const errors: ManifestValidationError[] = [];\n\n if (!m.name || m.name.length < 2 || m.name.length > 50) {\n errors.push({ field: 'name', message: 'name must be 2-50 characters' });\n }\n if (!m.version || !SEMVER_REGEX.test(m.version)) {\n errors.push({ field: 'version', message: 'version must be valid semver (x.y.z)' });\n }\n if (!m.entryPath || !ENTRY_PATH_REGEX.test(m.entryPath)) {\n errors.push({ field: 'entryPath', message: 'entryPath must be lowercase kebab-case starting with a letter' });\n }\n if (!m.main || (!m.main.endsWith('.js') && !m.main.endsWith('.jsc'))) {\n errors.push({ field: 'main', message: 'main must end with .js or .jsc' });\n }\n // renderEngine 可选:未声明或空串走宿主默认(webview),仅校验显式给出的非法值\n const renderEngine = m.renderEngine as string | undefined;\n if (renderEngine !== undefined && renderEngine !== '' && !VALID_RENDER_ENGINES.includes(renderEngine)) {\n errors.push({\n field: 'renderEngine',\n message: `renderEngine must be one of ${VALID_RENDER_ENGINES.join(' | ')} (got: ${renderEngine})`,\n });\n }\n if (!Array.isArray(m.permissions)) {\n errors.push({ field: 'permissions', message: 'permissions must be an array' });\n } else {\n for (const perm of m.permissions) {\n if (!VALID_PERMISSIONS.includes(perm)) {\n errors.push({ field: 'permissions', message: `unknown permission: ${perm}` });\n }\n }\n }\n\n return errors;\n}\n","// @songloft/plugin-builder — hash 计算模块\n// 与后端 Go 版本 ComputeCanonicalZipHash / ComputeEntryHash 算法完全一致。\n\nimport { createHash } from 'node:crypto';\nimport { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, posix } from 'node:path';\n\n/**\n * sha256 hex\n */\nexport function sha256Hex(data: Buffer | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * 计算 entryHash(main.js 的 sha256)\n */\nexport function computeEntryHash(mainJsContent: Buffer | string): string {\n return sha256Hex(mainJsContent);\n}\n\n/**\n * 计算 canonical zipHash。\n *\n * 算法(与后端保持一致):\n * 1. 枚举 buildDir 下所有文件(排除 plugin.json)\n * 2. 按路径 Unicode 升序排序(使用 posix 风格的路径分隔符)\n * 3. 对每个文件:hasher.write(path + \"\\n\" + sha256Hex(content) + \"\\n\")\n * 4. 对最终拼接串再 sha256\n */\nexport function computeCanonicalZipHash(buildDir: string): string {\n const entries: { path: string; hash: string }[] = [];\n\n function walk(dir: string) {\n const items = readdirSync(dir);\n for (const item of items) {\n const fullPath = join(dir, item);\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else {\n const relPath = posix.normalize(relative(buildDir, fullPath).replace(/\\\\/g, '/'));\n if (relPath === 'plugin.json') continue;\n const content = readFileSync(fullPath);\n entries.push({ path: relPath, hash: sha256Hex(content) });\n }\n }\n }\n\n walk(buildDir);\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n\n const hasher = createHash('sha256');\n for (const e of entries) {\n hasher.update(e.path + '\\n' + e.hash + '\\n');\n }\n return hasher.digest('hex');\n}\n","// @songloft/plugin-builder — 前端静态资源 hash 处理\n//\n// 为 static/ 目录下的 JS/CSS/字体/图片等资源注入内容 hash 到文件名,\n// 并改写 HTML 中的 <script src> / <link href> 与 CSS 中的 url() 引用,\n// 防止插件版本更新后浏览器仍命中旧缓存。\n//\n// 处理顺序(按依赖反向):\n// 1. 叶子资源(字体/图片/媒体)先 hash\n// 2. CSS 改写内部 url(...) 后再 hash\n// 3. JS 单独 hash(不扫描内部内容)\n// 4. HTML 改写 <script src> / <link href> 等引用\n\nimport { readFileSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs';\nimport { join, dirname, basename, posix, relative } from 'node:path';\nimport { sha256Hex } from './hash.js';\n\nconst ASSET_EXT = /\\.(woff2?|ttf|otf|eot|png|jpe?g|gif|svg|webp|ico|mp3|mp4|wav|ogg)$/i;\nconst CSS_EXT = /\\.css$/i;\nconst JS_EXT = /\\.m?js$/i;\nconst HTML_EXT = /\\.html?$/i;\n\nconst HASH_LEN = 8;\n\n/**\n * 文件名\"看起来已经 hash 过\"的检测。\n * 匹配 `name.<8+位 url-safe base64/hex>.ext` 或 `name-<同上>.ext`,\n * 用于跳过已由 Vite/Webpack/Rollup 等工具自管理 hash 的产物。\n *\n * 注意:要保留至少一段\"语义名\",避免把 `roboto-400.woff2`(400 仅 3 位)\n * 或纯 hash 文件名误判。\n */\nconst HASHED_NAME_RE = /^(.+)[.-]([A-Za-z0-9_-]{8,})\\.[^.]+$/;\nfunction looksAlreadyHashed(filename: string): boolean {\n const m = HASHED_NAME_RE.exec(filename);\n if (!m) return false;\n const seg = m[2];\n // 8+ 位且由 hex 字符组成即视为 hash(含纯数字情况如 67058905)\n return /^[A-Fa-f0-9]{8,}$/.test(seg) || (/[A-Za-z]/.test(seg) && /\\d/.test(seg));\n}\n\n/**\n * 入口:hash static 目录下的资源并改写引用。\n * staticBuildDir 必须存在;不存在时由调用方判断后再传入。\n */\nexport function hashStaticAssets(staticBuildDir: string): { renamed: number; renameMap: Map<string, string> } {\n const all = walk(staticBuildDir);\n const rel = (p: string) => toPosix(relative(staticBuildDir, p));\n\n const assets = all.filter(p => ASSET_EXT.test(p));\n const cssList = all.filter(p => CSS_EXT.test(p));\n const jsList = all.filter(p => JS_EXT.test(p));\n const htmlList = all.filter(p => HTML_EXT.test(p));\n\n // 先扫描所有 CSS/HTML/JS,把\"被绝对路径(含 /static/)引用\"的资源加入\n // pinned 集合——这些文件不能改名,否则会破坏运行时引用。\n const pinned = collectPinnedAssets([...htmlList, ...cssList, ...jsList], rel, staticBuildDir);\n const notPinned = (p: string) => !pinned.has(rel(p));\n\n // 原相对路径 → 新相对路径(含 hash),均为 posix 风格\n const renameMap = new Map<string, string>();\n\n // 1. 叶子资源\n for (const file of assets.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 2. CSS:先改写 url(),再 hash\n for (const file of cssList) {\n const relPath = rel(file);\n const content = readFileSync(file, 'utf-8');\n const rewritten = rewriteCssUrls(content, relPath, renameMap);\n if (rewritten !== content) writeFileSync(file, rewritten);\n if (pinned.has(relPath)) continue;\n const newRel = renameWithHash(staticBuildDir, relPath);\n renameMap.set(relPath, newRel);\n }\n\n // 3. JS\n for (const file of jsList.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 4. HTML:改写引用\n for (const file of htmlList) {\n const relPath = rel(file);\n const html = readFileSync(file, 'utf-8');\n const rewritten = rewriteHtmlRefs(html, relPath, renameMap);\n if (rewritten !== html) writeFileSync(file, rewritten);\n }\n\n return { renamed: renameMap.size, renameMap };\n}\n\n// --- 内部工具 ---\n\n/**\n * 扫描指定文件(CSS/HTML/JS),找出\"被含 /static/ 的绝对路径引用\"的资源,\n * 比如 CSS 里 url('/api/v1/plugin/lxmusic/static/fonts/roboto.woff2')。\n * 这些资源不能改名,否则运行时绝对路径会 404。\n *\n * 返回的 set 包含相对 staticDir 的 posix 路径。\n */\nfunction collectPinnedAssets(\n files: string[],\n rel: (p: string) => string,\n staticDir: string,\n): Set<string> {\n const pinned = new Set<string>();\n // 匹配引号内或 url(...) 内出现的、含 /static/<rest> 的串\n const re = /\\/(?:[^\\s\"')]*\\/)?static\\/([A-Za-z0-9_\\-./]+?)(?=[\"')?#\\s]|$)/g;\n for (const file of files) {\n let content: string;\n try {\n content = readFileSync(file, 'utf-8');\n } catch {\n continue;\n }\n for (const m of content.matchAll(re)) {\n const candidate = m[1].replace(/\\/+$/, '');\n if (!candidate) continue;\n // 仅当该路径在 static 下真实存在\n const abs = join(staticDir, candidate);\n try {\n if (statSync(abs).isFile()) pinned.add(candidate);\n } catch {\n // 不存在,忽略\n }\n }\n }\n return pinned;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const item of readdirSync(dir)) {\n const full = join(dir, item);\n const st = statSync(full);\n if (st.isDirectory()) out.push(...walk(full));\n else out.push(full);\n }\n return out;\n}\n\nfunction toPosix(p: string): string {\n return p.split(/[\\\\/]/).join('/');\n}\n\n/**\n * 重命名文件:name.ext → name.<hash>.ext。返回新相对路径(posix)。\n * 若文件名已经包含可识别的 hash(来自 Vite/Webpack 等),则原路径直接返回,不动文件。\n */\nfunction renameWithHash(rootDir: string, relPath: string): string {\n const base = basename(relPath);\n if (looksAlreadyHashed(base)) return relPath;\n const abs = join(rootDir, relPath);\n const hash = sha256Hex(readFileSync(abs)).slice(0, HASH_LEN);\n const dir = dirname(relPath);\n const dot = base.lastIndexOf('.');\n const newBase = dot <= 0\n ? `${base}.${hash}`\n : `${base.slice(0, dot)}.${hash}${base.slice(dot)}`;\n const newRel = dir === '.' || dir === '' ? newBase : posix.join(toPosix(dir), newBase);\n renameSync(abs, join(rootDir, newRel));\n return newRel;\n}\n\ninterface ResolvedRef {\n /** 相对 static 根的路径,用作 renameMap key */\n staticRel: string;\n /** ?query#hash 后缀 */\n suffix: string;\n /** 原 url 是否带 \"static/\" 前缀(HTML 中常见) */\n hadStaticPrefix: boolean;\n /** 原 url 是否以 ./ 或 ../ 开头 */\n isExplicitRelative: boolean;\n}\n\n/**\n * 把出现在 fromFile(相对 static 根的路径)中的 url 解析为\n * 相对 static 根的资源路径,便于在 renameMap 中查找。\n *\n * 支持:\n * - \"static/css/style.css\" —— HTML 中从插件根访问\n * - \"css/style.css\" —— 从当前文件同目录访问\n * - \"./x.png\" / \"../foo\"\n *\n * 不处理:绝对路径(/...)、协议(http://、data:、blob: 等)、\n * 锚点(#xxx)、空 url。\n */\nfunction resolveRef(url: string, fromFile: string): ResolvedRef | null {\n if (!url) return null;\n if (/^(?:[a-z]+:|\\/\\/|#|data:|blob:|mailto:)/i.test(url)) return null;\n if (url.startsWith('/')) return null;\n\n let bare = url;\n let suffix = '';\n const qIdx = bare.search(/[?#]/);\n if (qIdx >= 0) {\n suffix = bare.slice(qIdx);\n bare = bare.slice(0, qIdx);\n }\n\n const hadStaticPrefix = bare.startsWith('static/');\n const isExplicitRelative = bare.startsWith('./') || bare.startsWith('../');\n\n let staticRel: string;\n if (hadStaticPrefix) {\n staticRel = bare.slice('static/'.length);\n } else {\n const fromDir = toPosix(dirname(fromFile));\n staticRel = fromDir === '.' || fromDir === ''\n ? bare.replace(/^\\.\\//, '')\n : posix.normalize(posix.join(fromDir, bare));\n }\n if (staticRel.startsWith('..')) return null;\n return { staticRel, suffix, hadStaticPrefix, isExplicitRelative };\n}\n\n/**\n * 根据 renameMap 重新组装引用字符串。renameMap 未命中时返回 null。\n */\nfunction applyRename(\n ref: ResolvedRef,\n renameMap: Map<string, string>,\n fromFile: string,\n): string | null {\n const renamed = renameMap.get(ref.staticRel);\n if (!renamed) return null;\n\n let out: string;\n if (ref.hadStaticPrefix) {\n out = `static/${renamed}`;\n } else {\n const fromDir = toPosix(dirname(fromFile));\n if (fromDir === '.' || fromDir === '') {\n out = renamed;\n } else {\n out = toPosix(relative(fromDir, renamed));\n }\n if (ref.isExplicitRelative && !out.startsWith('.')) out = `./${out}`;\n }\n return out + ref.suffix;\n}\n\nfunction tryRewrite(url: string, fromFile: string, renameMap: Map<string, string>): string | null {\n const ref = resolveRef(url, fromFile);\n if (!ref) return null;\n return applyRename(ref, renameMap, fromFile);\n}\n\n/** 改写 HTML 中的 src=/href= 引用 */\nfunction rewriteHtmlRefs(html: string, fromFile: string, renameMap: Map<string, string>): string {\n return html.replace(/\\b(src|href)\\s*=\\s*([\"'])([^\"']+)\\2/gi, (full, attr, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `${attr}=${quote}${replaced}${quote}`;\n });\n}\n\n/** 改写 CSS 中的 url(...) 与 @import \"...\" */\nfunction rewriteCssUrls(css: string, fromFile: string, renameMap: Map<string, string>): string {\n css = css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `url(${quote}${replaced}${quote})`;\n });\n css = css.replace(/@import\\s+(['\"])([^'\"]+)\\1/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `@import ${quote}${replaced}${quote}`;\n });\n return css;\n}\n","/**\n * Auto-generated index.html for Lynx plugins — Flutter WebView fallback.\n *\n * When a plugin declares renderEngine: \"lynx\", the builder produces this HTML\n * alongside the .lynx.bundle and .web.bundle. Flutter's WebView loads this page,\n * which bootstraps @lynx-js/web-core + the .web.bundle, making one ReactLynx\n * codebase render everywhere.\n *\n * webBundleVersion 是 main.web.bundle 的内容哈希;带上后新版本服务端的\n * lynx-plugin-bridge-shim 会按声明加载带版本参数的 bundle 地址,插件更新后\n * 浏览器不会命中旧缓存。未提供时保持原有固定地址(旧宿主兼容路径)。\n */\n\nexport function generateLynxIndexHtml(entryPath: string, webBundleVersion?: string): string {\n const bundleAttr = webBundleVersion\n ? ` data-songloft-lynx-bundle=\"static/main.web.bundle?v=${webBundleVersion}\"`\n : '';\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no\">\n <title>${entryPath}</title>\n <link href=\"../../jsplugin-assets/web-core/static/css/client.css\" rel=\"stylesheet\">\n <style>\n html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }\n lynx-view { width: 100vw; height: 100vh; display: block; }\n </style>\n</head>\n<body>\n <lynx-view id=\"plugin-view\"></lynx-view>\n <script type=\"module\" src=\"../../jsplugin-assets/web-core/static/js/client.js\"></script>\n <script type=\"module\" src=\"../../jsplugin-assets/lynx-plugin-bridge-shim.js\"${bundleAttr}></script>\n</body>\n</html>\n`;\n}\n","import { execFileSync } from 'node:child_process';\n\n/** Only fixed npm arguments enter cmd.exe; project paths use cwd, never shell interpolation. */\nexport function runFrontendNpm(cwd: string, action: 'install' | 'build'): void {\n execFileSync(\n process.platform === 'win32' ? 'npm.cmd' : 'npm',\n action === 'install' ? ['install'] : ['run', 'build'],\n { cwd, stdio: 'inherit', shell: process.platform === 'win32' },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,cAAyB;AACzB,mBAAkB;AAClB,IAAAA,kBAA8H;AAC9H,IAAAC,oBAAuC;AACvC,IAAAC,6BAA6B;AAC7B,sBAA8B;;;ACJ9B,qBAA6B;AAC7B,uBAAqB;AAOrB,IAAM,mBAAmB;AAGzB,IAAM,uBAAuB,CAAC,WAAW,MAAM;AAC/C,IAAM,eAAe;AAGrB,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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,QAAQ;AAC9B,QAAI,KAAK,YAAY,GAAG;AACtB,kBAAY,KAAK,UAAU,OAAO;AAAA,IACpC,OAAO;AACL,UAAI,KAAK,aAAS,8BAAa,QAAQ,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;","names":["import_node_fs","import_node_path","import_node_child_process","import_node_fs","import_node_path","walk","import_node_fs","import_node_path","import_node_fs","build","readdirSyncTop","JSZip"]}
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as esbuild from "esbuild";
|
|
|
3
3
|
import JSZip from "jszip";
|
|
4
4
|
import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, mkdirSync, existsSync, cpSync, unlinkSync, rmSync, readdirSync as readdirSyncTop } from "fs";
|
|
5
5
|
import { join as join4, resolve, dirname as dirname2 } from "path";
|
|
6
|
-
import { execFileSync } from "child_process";
|
|
6
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
7
7
|
import { fileURLToPath } from "url";
|
|
8
8
|
|
|
9
9
|
// src/manifest.ts
|
|
@@ -269,7 +269,8 @@ function rewriteCssUrls(css, fromFile, renameMap) {
|
|
|
269
269
|
}
|
|
270
270
|
|
|
271
271
|
// src/lynx-index-html.ts
|
|
272
|
-
function generateLynxIndexHtml(entryPath) {
|
|
272
|
+
function generateLynxIndexHtml(entryPath, webBundleVersion) {
|
|
273
|
+
const bundleAttr = webBundleVersion ? ` data-songloft-lynx-bundle="static/main.web.bundle?v=${webBundleVersion}"` : "";
|
|
273
274
|
return `<!DOCTYPE html>
|
|
274
275
|
<html>
|
|
275
276
|
<head>
|
|
@@ -285,16 +286,25 @@ function generateLynxIndexHtml(entryPath) {
|
|
|
285
286
|
<body>
|
|
286
287
|
<lynx-view id="plugin-view"></lynx-view>
|
|
287
288
|
<script type="module" src="../../jsplugin-assets/web-core/static/js/client.js"></script>
|
|
288
|
-
<script type="module" src="../../jsplugin-assets/lynx-plugin-bridge-shim.js"></script>
|
|
289
|
+
<script type="module" src="../../jsplugin-assets/lynx-plugin-bridge-shim.js"${bundleAttr}></script>
|
|
289
290
|
</body>
|
|
290
291
|
</html>
|
|
291
292
|
`;
|
|
292
293
|
}
|
|
293
294
|
|
|
295
|
+
// src/frontend-npm.ts
|
|
296
|
+
import { execFileSync } from "child_process";
|
|
297
|
+
function runFrontendNpm(cwd, action) {
|
|
298
|
+
execFileSync(
|
|
299
|
+
process.platform === "win32" ? "npm.cmd" : "npm",
|
|
300
|
+
action === "install" ? ["install"] : ["run", "build"],
|
|
301
|
+
{ cwd, stdio: "inherit", shell: process.platform === "win32" }
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
294
305
|
// src/build.ts
|
|
295
306
|
import { getJscBinaryPath } from "@songloft/jsc";
|
|
296
307
|
import { readdirSync as readdirSync3, statSync as statSync3 } from "fs";
|
|
297
|
-
var NPM = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
298
308
|
async function buildPlugin(opts) {
|
|
299
309
|
const cwd = resolve(opts.cwd);
|
|
300
310
|
const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join4(cwd, "dist");
|
|
@@ -337,10 +347,10 @@ ${errors.map((e) => ` - ${e.field}: ${e.message}`).join("\n")}`);
|
|
|
337
347
|
if (existsSync(join4(frontendDir, "package.json"))) {
|
|
338
348
|
if (!existsSync(join4(frontendDir, "node_modules"))) {
|
|
339
349
|
console.log(` \u{1F4E6} Installing frontend dependencies...`);
|
|
340
|
-
|
|
350
|
+
runFrontendNpm(frontendDir, "install");
|
|
341
351
|
}
|
|
342
352
|
console.log(` \u{1F680} Building frontend project...`);
|
|
343
|
-
|
|
353
|
+
runFrontendNpm(frontendDir, "build");
|
|
344
354
|
if (existsSync(join4(frontendDir, "dist"))) {
|
|
345
355
|
cpSync(join4(frontendDir, "dist"), join4(buildDir, "static"), { recursive: true });
|
|
346
356
|
}
|
|
@@ -352,15 +362,17 @@ ${errors.map((e) => ` - ${e.field}: ${e.message}`).join("\n")}`);
|
|
|
352
362
|
mkdirSync(staticOut, { recursive: true });
|
|
353
363
|
const lynxBundle = join4(lynxBundleDir, "main.lynx.bundle");
|
|
354
364
|
const webBundle = join4(webBundleDir, "main.web.bundle");
|
|
365
|
+
let webBundleVersion;
|
|
355
366
|
if (existsSync(lynxBundle)) {
|
|
356
367
|
cpSync(lynxBundle, join4(staticOut, "main.lynx.bundle"));
|
|
357
368
|
}
|
|
358
369
|
if (existsSync(webBundle)) {
|
|
359
370
|
cpSync(webBundle, join4(staticOut, "main.web.bundle"));
|
|
371
|
+
webBundleVersion = sha256Hex(readFileSync4(webBundle)).slice(0, 16);
|
|
360
372
|
}
|
|
361
373
|
rmSync(lynxBundleDir, { recursive: true, force: true });
|
|
362
374
|
rmSync(webBundleDir, { recursive: true, force: true });
|
|
363
|
-
writeFileSync2(join4(staticOut, "index.html"), generateLynxIndexHtml(manifest.entryPath));
|
|
375
|
+
writeFileSync2(join4(staticOut, "index.html"), generateLynxIndexHtml(manifest.entryPath, webBundleVersion));
|
|
364
376
|
console.log(` \u{1F517} Lynx bundles flattened + index.html generated`);
|
|
365
377
|
}
|
|
366
378
|
const staticDir = join4(cwd, "static");
|
|
@@ -422,7 +434,7 @@ ${errors.map((e) => ` - ${e.field}: ${e.message}`).join("\n")}`);
|
|
|
422
434
|
if (!jscCmd) {
|
|
423
435
|
throw new Error("jsc binary not found");
|
|
424
436
|
}
|
|
425
|
-
|
|
437
|
+
execFileSync2(jscCmd, [mainJsPath, mainJscPath], { stdio: "pipe" });
|
|
426
438
|
unlinkSync(mainJsPath);
|
|
427
439
|
mainFileName = "main.jsc";
|
|
428
440
|
console.log(` \u{1F512} main.js compiled \u2192 main.jsc (via ${jscCmd})`);
|
|
@@ -488,7 +500,7 @@ function findJscBinary() {
|
|
|
488
500
|
} catch {
|
|
489
501
|
}
|
|
490
502
|
try {
|
|
491
|
-
|
|
503
|
+
execFileSync2("jsc", ["--help"], { stdio: "pipe" });
|
|
492
504
|
return "jsc";
|
|
493
505
|
} catch {
|
|
494
506
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/build.ts","../src/manifest.ts","../src/hash.ts","../src/static-assets.ts","../src/lynx-index-html.ts"],"sourcesContent":["// @songloft/plugin-builder — 核心 build 逻辑\n\nimport * as esbuild from 'esbuild';\nimport JSZip from 'jszip';\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, cpSync, unlinkSync, rmSync, readdirSync as readdirSyncTop } from 'node:fs';\nimport { join, resolve, dirname } from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { readManifest, validateManifest } from './manifest.js';\nimport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nimport { hashStaticAssets } from './static-assets.js';\nimport { generateLynxIndexHtml } from './lynx-index-html.js';\nimport type { PluginManifest } from '@songloft/plugin-sdk';\n\n// Windows 下 npm 是 npm.cmd,execFileSync/spawn 不走 shell,直接 'npm' 会 ENOENT\nconst NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';\n\nexport interface BuildOptions {\n cwd: string;\n outDir?: string;\n mode?: 'development' | 'production';\n sourcemap?: boolean;\n}\n\nexport interface BuildResult {\n zipPath: string;\n manifest: PluginManifest;\n size: number;\n entryHash: string;\n zipHash: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: { field: string; message: string }[];\n}\n\n/**\n * 构建插件:TS/JS → QuickJS-compatible JS → .jsplugin.zip\n */\nexport async function buildPlugin(opts: BuildOptions): Promise<BuildResult> {\n const cwd = resolve(opts.cwd);\n const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join(cwd, 'dist');\n const buildDir = join(outDir, '_build');\n const mode = opts.mode ?? 'production';\n\n // [1] 读取并校验 plugin.json\n const manifest = readManifest(cwd);\n const errors = validateManifest(manifest);\n if (errors.length > 0) {\n throw new Error(`Invalid plugin.json:\\n${errors.map(e => ` - ${e.field}: ${e.message}`).join('\\n')}`);\n }\n\n // [2] esbuild 打包 src/main.ts → build/main.js\n //\n // _build 是**纯暂存目录**:最后整目录进 zip(addDirToZip(zip, buildDir, ''))且整目录\n // 参与 computeCanonicalZipHash。所以它必须每次从零开始 —— 否则 [3.1.1] 步注入内容 hash\n // 产出的 `style.<hash>.css` 会**逐次堆积**:同一份源码构建多次,zip 里会带上历史所有版本\n // 的资源(实测 downloader 连构 4 次后 zip 里有 4 份 style.*.css),而 index.html 只引用\n // 最新那份。后果不只是体积——`zipHash` 会随构建历史漂移,同样的源码算出不同的哈希,\n // 这条哈希的完整性用途就没了。cpSync 是合并语义、不会替我们清,只能显式删。\n rmSync(buildDir, { recursive: true, force: true });\n mkdirSync(buildDir, { recursive: true });\n const entryPoint = join(cwd, 'src', 'main.ts');\n const entryPointAlt = join(cwd, 'src', 'main.js');\n const actualEntry = existsSync(entryPoint) ? entryPoint : entryPointAlt;\n\n if (!existsSync(actualEntry)) {\n throw new Error(`Entry file not found: src/main.ts or src/main.js`);\n }\n\n await esbuild.build({\n entryPoints: [actualEntry],\n outfile: join(buildDir, 'main.js'),\n bundle: true,\n platform: 'neutral',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n sourcemap: opts.sourcemap ? 'inline' : false,\n // 禁止使用 Node 内置模块\n plugins: [{\n name: 'no-node-builtins',\n setup(build) {\n build.onResolve({ filter: /^(fs|net|http|https|child_process|os|path|crypto|stream|util|events|buffer|url|querystring|zlib)$/ }, (args) => {\n return { errors: [{ text: `Node builtin \"${args.path}\" is not available in QuickJS runtime` }] };\n });\n },\n }],\n });\n\n // [2.5] 前端 Vue/Vite 编译(如果存在 frontend/ 目录)\n const frontendDir = join(cwd, 'frontend');\n if (existsSync(join(frontendDir, 'package.json'))) {\n // 仅在依赖缺失时安装:dev 模式每次热重载都会走到这里,无脑 npm install 会拖慢重建\n if (!existsSync(join(frontendDir, 'node_modules'))) {\n console.log(` 📦 Installing frontend dependencies...`);\n execFileSync(NPM, ['install'], { cwd: frontendDir, stdio: 'inherit' });\n }\n console.log(` 🚀 Building frontend project...`);\n execFileSync(NPM, ['run', 'build'], { cwd: frontendDir, stdio: 'inherit' });\n // 根据模板配置,产物会被直接输出到 cwd/static。但为了兼容自定义 dist 输出,加一个 fallback 拷贝:\n if (existsSync(join(frontendDir, 'dist'))) {\n cpSync(join(frontendDir, 'dist'), join(buildDir, 'static'), { recursive: true });\n }\n }\n\n // [2.6] Lynx 插件后处理:rspeedy 产出 dist/lynx/ 和 dist/web/ 子目录,\n // 将 bundle 文件提升到 static/ 根并生成 Flutter WebView 用的 index.html。\n if (manifest.renderEngine === 'lynx') {\n const staticOut = join(buildDir, 'static');\n const lynxBundleDir = join(staticOut, 'lynx');\n const webBundleDir = join(staticOut, 'web');\n mkdirSync(staticOut, { recursive: true });\n\n const lynxBundle = join(lynxBundleDir, 'main.lynx.bundle');\n const webBundle = join(webBundleDir, 'main.web.bundle');\n\n if (existsSync(lynxBundle)) {\n cpSync(lynxBundle, join(staticOut, 'main.lynx.bundle'));\n }\n if (existsSync(webBundle)) {\n cpSync(webBundle, join(staticOut, 'main.web.bundle'));\n }\n\n // Remove the intermediate subdirectories\n rmSync(lynxBundleDir, { recursive: true, force: true });\n rmSync(webBundleDir, { recursive: true, force: true });\n\n // Generate index.html for Flutter WebView fallback (loads web-core + .web.bundle)\n writeFileSync(join(staticOut, 'index.html'), generateLynxIndexHtml(manifest.entryPath));\n\n console.log(` 🔗 Lynx bundles flattened + index.html generated`);\n }\n\n // [3] 拷贝 static/ 到 build/(如果存在)\n const staticDir = join(cwd, 'static');\n if (existsSync(staticDir)) {\n cpSync(staticDir, join(buildDir, 'static'), { recursive: true });\n }\n\n // [3.0] 拷贝 bin/ 到 build/(如果存在,用于打包可执行文件)\n const binDir = join(cwd, 'bin');\n if (existsSync(binDir)) {\n cpSync(binDir, join(buildDir, 'bin'), { recursive: true });\n }\n\n // [3.1] 合并打包前端 JS(如果 static/js/app.js 存在)\n const staticJsAppPath = join(buildDir, 'static', 'js', 'app.js');\n if (existsSync(staticJsAppPath)) {\n const bundleOutPath = join(buildDir, 'static', 'js', 'app.bundle.js');\n await esbuild.build({\n entryPoints: [staticJsAppPath],\n outfile: bundleOutPath,\n bundle: true,\n platform: 'browser',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n });\n\n // 删除 static/js/ 下除 app.bundle.js 外的所有 .js 文件\n const staticJsDir = join(buildDir, 'static', 'js');\n const jsFiles = readdirSyncTop(staticJsDir).filter(f => f.endsWith('.js') && f !== 'app.bundle.js');\n for (const f of jsFiles) {\n unlinkSync(join(staticJsDir, f));\n }\n\n // 更新 index.html 中的 script 引用:将 app.js 替换为打包后的 app.bundle.js\n // 匹配时兼容属性顺序不同、多空格、以及 src 中有无 static/ 前缀\n const indexHtmlPath = join(buildDir, 'static', 'index.html');\n if (existsSync(indexHtmlPath)) {\n let html = readFileSync(indexHtmlPath, 'utf-8');\n const before = html;\n html = html.replace(\n /<script\\b[^>]*\\bsrc=\"(?:static\\/)?js\\/app\\.js\"[^>]*><\\/script>/,\n '<script src=\"static/js/app.bundle.js\"></script>'\n );\n if (html === before) {\n throw new Error(\n 'Failed to update script tag in static/index.html: ' +\n 'expected <script ... src=\"static/js/app.js\" ...> or <script ... src=\"js/app.js\" ...> but pattern not found'\n );\n }\n writeFileSync(indexHtmlPath, html);\n }\n\n console.log(` 📦 static/js/ bundled → app.bundle.js (${jsFiles.length} files merged)`);\n }\n\n // [3.1.1] 为 static/ 下所有 JS/CSS/字体/图片注入内容 hash 到文件名,\n // 并改写 HTML/CSS 中的引用,防止插件更新后浏览器使用旧缓存。\n // 可在 plugin.json 中设置 \"staticHash\": false 关闭(用于前端已用\n // Vite/Webpack 等工具自管理 hash 的场景)。\n const staticBuildDir = join(buildDir, 'static');\n let staticRenameMap: Map<string, string> | undefined;\n if (existsSync(staticBuildDir) && manifest.staticHash !== false) {\n const { renamed, renameMap } = hashStaticAssets(staticBuildDir);\n if (renamed > 0) {\n staticRenameMap = renameMap;\n console.log(` 🏷️ static assets hashed (${renamed} files)`);\n }\n }\n\n // [3.2] 编译 main.js 为 main.jsc 字节码(如果 jsc 工具可用)\n let mainFileName = 'main.js';\n const mainJsPath = join(buildDir, 'main.js');\n const mainJscPath = join(buildDir, 'main.jsc');\n try {\n const jscCmd = findJscBinary();\n if (!jscCmd) {\n throw new Error('jsc binary not found');\n }\n execFileSync(jscCmd, [mainJsPath, mainJscPath], { stdio: 'pipe' });\n // 编译成功,删除 main.js\n unlinkSync(mainJsPath);\n mainFileName = 'main.jsc';\n console.log(` 🔒 main.js compiled → main.jsc (via ${jscCmd})`);\n } catch {\n // jsc 可能在失败前已经创建了不完整的输出。回退到 main.js 时必须删除它,\n // 否则宿主会优先加载 main.jsc,并与按 main.js 计算的 entryHash 失配。\n if (existsSync(mainJscPath)) {\n unlinkSync(mainJscPath);\n }\n console.log(` ⚠️ jsc not available, keeping main.js`);\n }\n\n // [4] 计算 entryHash\n const mainJsContent = readFileSync(join(buildDir, mainFileName));\n const entryHash = computeEntryHash(mainJsContent);\n\n // [5] 计算 zipHash(排除 plugin.json)\n const zipHash = computeCanonicalZipHash(buildDir);\n\n // [6] 写入最终 plugin.json(含 hash)\n const finalManifest: PluginManifest = {\n ...manifest,\n main: mainFileName,\n entryHash,\n zipHash,\n };\n // icon 字段回写:用 hash 后的实际文件名替换原始文件名\n if (finalManifest.icon && staticRenameMap) {\n const hashedIcon = staticRenameMap.get(finalManifest.icon);\n if (hashedIcon) {\n finalManifest.icon = hashedIcon;\n }\n }\n writeFileSync(join(buildDir, 'plugin.json'), JSON.stringify(finalManifest, null, 2));\n\n // [7] 打包为 .jsplugin.zip\n mkdirSync(outDir, { recursive: true });\n const zip = new JSZip();\n addDirToZip(zip, buildDir, '');\n const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });\n const zipPath = join(outDir, `${manifest.entryPath}.jsplugin.zip`);\n writeFileSync(zipPath, zipBuffer);\n\n // [8] 输出报告\n const mainJsGzip = Buffer.byteLength(mainJsContent);\n console.log(`\\n✅ Build successful!`);\n console.log(` 📦 ${zipPath} (${(zipBuffer.length / 1024).toFixed(1)} KB)`);\n console.log(` 📄 main.js: ${(mainJsGzip / 1024).toFixed(1)} KB`);\n console.log(` 🔑 entryHash: ${entryHash}`);\n console.log(` 🔑 zipHash: ${zipHash}\\n`);\n\n return { zipPath, manifest: finalManifest, size: zipBuffer.length, entryHash, zipHash };\n}\n\n/**\n * 校验已构建的插件\n */\nexport async function validatePlugin(cwd: string): Promise<ValidationResult> {\n const resolvedCwd = resolve(cwd);\n const errors: { field: string; message: string }[] = [];\n\n // 读取 manifest\n let manifest: PluginManifest;\n try {\n manifest = readManifest(resolvedCwd);\n } catch {\n return { valid: false, errors: [{ field: 'plugin.json', message: 'cannot read plugin.json' }] };\n }\n\n // 字段校验\n const fieldErrors = validateManifest(manifest);\n errors.push(...fieldErrors);\n\n // hash 校验\n if (!manifest.entryHash || !manifest.zipHash) {\n errors.push({ field: 'hash', message: 'entryHash and zipHash are required. Run `songloft-plugin build` first.' });\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// --- 工具 ---\n\nimport { getJscBinaryPath } from '@songloft/jsc';\nimport { readdirSync, statSync } from 'node:fs';\n\n/**\n * 查找 jsc 二进制文件\n * 优先级:\n * 1. @songloft/jsc workspace 包中对应当前平台的预编译二进制\n * 2. PATH 中的 jsc 命令\n * 3. 项目根目录的 jsc 兼容旧路径\n */\nfunction findJscBinary(): string | null {\n // 获取当前文件所在目录(兼容 ESM 和 CJS)\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n // 1. 通过 @songloft/jsc 包定位预编译二进制\n try {\n const jscPath = getJscBinaryPath();\n if (existsSync(jscPath)) return jscPath;\n } catch {\n // 包未安装,继续尝试下一个路径\n }\n\n // 2. 检查 PATH 中的 jsc\n try {\n execFileSync('jsc', ['--help'], { stdio: 'pipe' });\n return 'jsc';\n } catch {\n // 继续尝试下一个路径\n }\n\n // 3. 兼容旧路径:项目根目录的 jsc (songloft/jsc)\n // 从 src/ 或 dist/ → plugin-builder/ → packages/ → plugin-toolchain/ → songloft/\n const projectJsc = join(currentDir, '..', '..', '..', '..', 'jsc');\n if (existsSync(projectJsc)) return projectJsc;\n\n return null;\n}\n\nfunction addDirToZip(zip: JSZip, dirPath: string, prefix: string) {\n const items = readdirSync(dirPath);\n for (const item of items) {\n const fullPath = join(dirPath, item);\n const zipPath = prefix ? `${prefix}/${item}` : item;\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n addDirToZip(zip, fullPath, zipPath);\n } else {\n zip.file(zipPath, readFileSync(fullPath));\n }\n }\n}\n","// @songloft/plugin-builder — manifest 校验模块\n\nimport type { PluginManifest } from '@songloft/plugin-sdk';\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface ManifestValidationError {\n field: string;\n message: string;\n}\n\nconst ENTRY_PATH_REGEX = /^[a-z][a-z0-9-]*$/;\n// 渲染引擎白名单,需与后端 internal/jsplugin 的校验保持一致。\n// 可选字段:缺省或空串 = webview(宿主默认)。\nconst VALID_RENDER_ENGINES = ['webview', 'lynx'];\nconst SEMVER_REGEX = /^\\d+\\.\\d+\\.\\d+/;\n// 权限白名单,需与后端 internal/jsplugin/permissions.go 的 AllPermissions 保持一致。\n// songs.* / playlists.* / fs.* 为声明层的通配符糖(一把梭)。\nconst VALID_PERMISSIONS = [\n 'storage',\n 'songs.read',\n 'songs.write',\n 'playlists.read',\n 'playlists.write',\n 'inter-plugin',\n 'command',\n 'jsenv',\n 'fs',\n 'fs:music',\n 'fs:external',\n 'websocket',\n 'persistent-storage',\n 'net',\n 'net:insecure-tls',\n 'tags.read',\n 'tags.write',\n 'songs.*',\n 'playlists.*',\n 'tags.*',\n 'fs.*',\n];\n\n/**\n * 从 cwd 读取 plugin.json\n */\nexport function readManifest(cwd: string): PluginManifest {\n const raw = readFileSync(join(cwd, 'plugin.json'), 'utf-8');\n return JSON.parse(raw) as PluginManifest;\n}\n\n/**\n * 校验 plugin.json 字段\n */\nexport function validateManifest(m: PluginManifest): ManifestValidationError[] {\n const errors: ManifestValidationError[] = [];\n\n if (!m.name || m.name.length < 2 || m.name.length > 50) {\n errors.push({ field: 'name', message: 'name must be 2-50 characters' });\n }\n if (!m.version || !SEMVER_REGEX.test(m.version)) {\n errors.push({ field: 'version', message: 'version must be valid semver (x.y.z)' });\n }\n if (!m.entryPath || !ENTRY_PATH_REGEX.test(m.entryPath)) {\n errors.push({ field: 'entryPath', message: 'entryPath must be lowercase kebab-case starting with a letter' });\n }\n if (!m.main || (!m.main.endsWith('.js') && !m.main.endsWith('.jsc'))) {\n errors.push({ field: 'main', message: 'main must end with .js or .jsc' });\n }\n // renderEngine 可选:未声明或空串走宿主默认(webview),仅校验显式给出的非法值\n const renderEngine = m.renderEngine as string | undefined;\n if (renderEngine !== undefined && renderEngine !== '' && !VALID_RENDER_ENGINES.includes(renderEngine)) {\n errors.push({\n field: 'renderEngine',\n message: `renderEngine must be one of ${VALID_RENDER_ENGINES.join(' | ')} (got: ${renderEngine})`,\n });\n }\n if (!Array.isArray(m.permissions)) {\n errors.push({ field: 'permissions', message: 'permissions must be an array' });\n } else {\n for (const perm of m.permissions) {\n if (!VALID_PERMISSIONS.includes(perm)) {\n errors.push({ field: 'permissions', message: `unknown permission: ${perm}` });\n }\n }\n }\n\n return errors;\n}\n","// @songloft/plugin-builder — hash 计算模块\n// 与后端 Go 版本 ComputeCanonicalZipHash / ComputeEntryHash 算法完全一致。\n\nimport { createHash } from 'node:crypto';\nimport { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, posix } from 'node:path';\n\n/**\n * sha256 hex\n */\nexport function sha256Hex(data: Buffer | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * 计算 entryHash(main.js 的 sha256)\n */\nexport function computeEntryHash(mainJsContent: Buffer | string): string {\n return sha256Hex(mainJsContent);\n}\n\n/**\n * 计算 canonical zipHash。\n *\n * 算法(与后端保持一致):\n * 1. 枚举 buildDir 下所有文件(排除 plugin.json)\n * 2. 按路径 Unicode 升序排序(使用 posix 风格的路径分隔符)\n * 3. 对每个文件:hasher.write(path + \"\\n\" + sha256Hex(content) + \"\\n\")\n * 4. 对最终拼接串再 sha256\n */\nexport function computeCanonicalZipHash(buildDir: string): string {\n const entries: { path: string; hash: string }[] = [];\n\n function walk(dir: string) {\n const items = readdirSync(dir);\n for (const item of items) {\n const fullPath = join(dir, item);\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else {\n const relPath = posix.normalize(relative(buildDir, fullPath).replace(/\\\\/g, '/'));\n if (relPath === 'plugin.json') continue;\n const content = readFileSync(fullPath);\n entries.push({ path: relPath, hash: sha256Hex(content) });\n }\n }\n }\n\n walk(buildDir);\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n\n const hasher = createHash('sha256');\n for (const e of entries) {\n hasher.update(e.path + '\\n' + e.hash + '\\n');\n }\n return hasher.digest('hex');\n}\n","// @songloft/plugin-builder — 前端静态资源 hash 处理\n//\n// 为 static/ 目录下的 JS/CSS/字体/图片等资源注入内容 hash 到文件名,\n// 并改写 HTML 中的 <script src> / <link href> 与 CSS 中的 url() 引用,\n// 防止插件版本更新后浏览器仍命中旧缓存。\n//\n// 处理顺序(按依赖反向):\n// 1. 叶子资源(字体/图片/媒体)先 hash\n// 2. CSS 改写内部 url(...) 后再 hash\n// 3. JS 单独 hash(不扫描内部内容)\n// 4. HTML 改写 <script src> / <link href> 等引用\n\nimport { readFileSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs';\nimport { join, dirname, basename, posix, relative } from 'node:path';\nimport { sha256Hex } from './hash.js';\n\nconst ASSET_EXT = /\\.(woff2?|ttf|otf|eot|png|jpe?g|gif|svg|webp|ico|mp3|mp4|wav|ogg)$/i;\nconst CSS_EXT = /\\.css$/i;\nconst JS_EXT = /\\.m?js$/i;\nconst HTML_EXT = /\\.html?$/i;\n\nconst HASH_LEN = 8;\n\n/**\n * 文件名\"看起来已经 hash 过\"的检测。\n * 匹配 `name.<8+位 url-safe base64/hex>.ext` 或 `name-<同上>.ext`,\n * 用于跳过已由 Vite/Webpack/Rollup 等工具自管理 hash 的产物。\n *\n * 注意:要保留至少一段\"语义名\",避免把 `roboto-400.woff2`(400 仅 3 位)\n * 或纯 hash 文件名误判。\n */\nconst HASHED_NAME_RE = /^(.+)[.-]([A-Za-z0-9_-]{8,})\\.[^.]+$/;\nfunction looksAlreadyHashed(filename: string): boolean {\n const m = HASHED_NAME_RE.exec(filename);\n if (!m) return false;\n const seg = m[2];\n // 8+ 位且由 hex 字符组成即视为 hash(含纯数字情况如 67058905)\n return /^[A-Fa-f0-9]{8,}$/.test(seg) || (/[A-Za-z]/.test(seg) && /\\d/.test(seg));\n}\n\n/**\n * 入口:hash static 目录下的资源并改写引用。\n * staticBuildDir 必须存在;不存在时由调用方判断后再传入。\n */\nexport function hashStaticAssets(staticBuildDir: string): { renamed: number; renameMap: Map<string, string> } {\n const all = walk(staticBuildDir);\n const rel = (p: string) => toPosix(relative(staticBuildDir, p));\n\n const assets = all.filter(p => ASSET_EXT.test(p));\n const cssList = all.filter(p => CSS_EXT.test(p));\n const jsList = all.filter(p => JS_EXT.test(p));\n const htmlList = all.filter(p => HTML_EXT.test(p));\n\n // 先扫描所有 CSS/HTML/JS,把\"被绝对路径(含 /static/)引用\"的资源加入\n // pinned 集合——这些文件不能改名,否则会破坏运行时引用。\n const pinned = collectPinnedAssets([...htmlList, ...cssList, ...jsList], rel, staticBuildDir);\n const notPinned = (p: string) => !pinned.has(rel(p));\n\n // 原相对路径 → 新相对路径(含 hash),均为 posix 风格\n const renameMap = new Map<string, string>();\n\n // 1. 叶子资源\n for (const file of assets.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 2. CSS:先改写 url(),再 hash\n for (const file of cssList) {\n const relPath = rel(file);\n const content = readFileSync(file, 'utf-8');\n const rewritten = rewriteCssUrls(content, relPath, renameMap);\n if (rewritten !== content) writeFileSync(file, rewritten);\n if (pinned.has(relPath)) continue;\n const newRel = renameWithHash(staticBuildDir, relPath);\n renameMap.set(relPath, newRel);\n }\n\n // 3. JS\n for (const file of jsList.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 4. HTML:改写引用\n for (const file of htmlList) {\n const relPath = rel(file);\n const html = readFileSync(file, 'utf-8');\n const rewritten = rewriteHtmlRefs(html, relPath, renameMap);\n if (rewritten !== html) writeFileSync(file, rewritten);\n }\n\n return { renamed: renameMap.size, renameMap };\n}\n\n// --- 内部工具 ---\n\n/**\n * 扫描指定文件(CSS/HTML/JS),找出\"被含 /static/ 的绝对路径引用\"的资源,\n * 比如 CSS 里 url('/api/v1/plugin/lxmusic/static/fonts/roboto.woff2')。\n * 这些资源不能改名,否则运行时绝对路径会 404。\n *\n * 返回的 set 包含相对 staticDir 的 posix 路径。\n */\nfunction collectPinnedAssets(\n files: string[],\n rel: (p: string) => string,\n staticDir: string,\n): Set<string> {\n const pinned = new Set<string>();\n // 匹配引号内或 url(...) 内出现的、含 /static/<rest> 的串\n const re = /\\/(?:[^\\s\"')]*\\/)?static\\/([A-Za-z0-9_\\-./]+?)(?=[\"')?#\\s]|$)/g;\n for (const file of files) {\n let content: string;\n try {\n content = readFileSync(file, 'utf-8');\n } catch {\n continue;\n }\n for (const m of content.matchAll(re)) {\n const candidate = m[1].replace(/\\/+$/, '');\n if (!candidate) continue;\n // 仅当该路径在 static 下真实存在\n const abs = join(staticDir, candidate);\n try {\n if (statSync(abs).isFile()) pinned.add(candidate);\n } catch {\n // 不存在,忽略\n }\n }\n }\n return pinned;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const item of readdirSync(dir)) {\n const full = join(dir, item);\n const st = statSync(full);\n if (st.isDirectory()) out.push(...walk(full));\n else out.push(full);\n }\n return out;\n}\n\nfunction toPosix(p: string): string {\n return p.split(/[\\\\/]/).join('/');\n}\n\n/**\n * 重命名文件:name.ext → name.<hash>.ext。返回新相对路径(posix)。\n * 若文件名已经包含可识别的 hash(来自 Vite/Webpack 等),则原路径直接返回,不动文件。\n */\nfunction renameWithHash(rootDir: string, relPath: string): string {\n const base = basename(relPath);\n if (looksAlreadyHashed(base)) return relPath;\n const abs = join(rootDir, relPath);\n const hash = sha256Hex(readFileSync(abs)).slice(0, HASH_LEN);\n const dir = dirname(relPath);\n const dot = base.lastIndexOf('.');\n const newBase = dot <= 0\n ? `${base}.${hash}`\n : `${base.slice(0, dot)}.${hash}${base.slice(dot)}`;\n const newRel = dir === '.' || dir === '' ? newBase : posix.join(toPosix(dir), newBase);\n renameSync(abs, join(rootDir, newRel));\n return newRel;\n}\n\ninterface ResolvedRef {\n /** 相对 static 根的路径,用作 renameMap key */\n staticRel: string;\n /** ?query#hash 后缀 */\n suffix: string;\n /** 原 url 是否带 \"static/\" 前缀(HTML 中常见) */\n hadStaticPrefix: boolean;\n /** 原 url 是否以 ./ 或 ../ 开头 */\n isExplicitRelative: boolean;\n}\n\n/**\n * 把出现在 fromFile(相对 static 根的路径)中的 url 解析为\n * 相对 static 根的资源路径,便于在 renameMap 中查找。\n *\n * 支持:\n * - \"static/css/style.css\" —— HTML 中从插件根访问\n * - \"css/style.css\" —— 从当前文件同目录访问\n * - \"./x.png\" / \"../foo\"\n *\n * 不处理:绝对路径(/...)、协议(http://、data:、blob: 等)、\n * 锚点(#xxx)、空 url。\n */\nfunction resolveRef(url: string, fromFile: string): ResolvedRef | null {\n if (!url) return null;\n if (/^(?:[a-z]+:|\\/\\/|#|data:|blob:|mailto:)/i.test(url)) return null;\n if (url.startsWith('/')) return null;\n\n let bare = url;\n let suffix = '';\n const qIdx = bare.search(/[?#]/);\n if (qIdx >= 0) {\n suffix = bare.slice(qIdx);\n bare = bare.slice(0, qIdx);\n }\n\n const hadStaticPrefix = bare.startsWith('static/');\n const isExplicitRelative = bare.startsWith('./') || bare.startsWith('../');\n\n let staticRel: string;\n if (hadStaticPrefix) {\n staticRel = bare.slice('static/'.length);\n } else {\n const fromDir = toPosix(dirname(fromFile));\n staticRel = fromDir === '.' || fromDir === ''\n ? bare.replace(/^\\.\\//, '')\n : posix.normalize(posix.join(fromDir, bare));\n }\n if (staticRel.startsWith('..')) return null;\n return { staticRel, suffix, hadStaticPrefix, isExplicitRelative };\n}\n\n/**\n * 根据 renameMap 重新组装引用字符串。renameMap 未命中时返回 null。\n */\nfunction applyRename(\n ref: ResolvedRef,\n renameMap: Map<string, string>,\n fromFile: string,\n): string | null {\n const renamed = renameMap.get(ref.staticRel);\n if (!renamed) return null;\n\n let out: string;\n if (ref.hadStaticPrefix) {\n out = `static/${renamed}`;\n } else {\n const fromDir = toPosix(dirname(fromFile));\n if (fromDir === '.' || fromDir === '') {\n out = renamed;\n } else {\n out = toPosix(relative(fromDir, renamed));\n }\n if (ref.isExplicitRelative && !out.startsWith('.')) out = `./${out}`;\n }\n return out + ref.suffix;\n}\n\nfunction tryRewrite(url: string, fromFile: string, renameMap: Map<string, string>): string | null {\n const ref = resolveRef(url, fromFile);\n if (!ref) return null;\n return applyRename(ref, renameMap, fromFile);\n}\n\n/** 改写 HTML 中的 src=/href= 引用 */\nfunction rewriteHtmlRefs(html: string, fromFile: string, renameMap: Map<string, string>): string {\n return html.replace(/\\b(src|href)\\s*=\\s*([\"'])([^\"']+)\\2/gi, (full, attr, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `${attr}=${quote}${replaced}${quote}`;\n });\n}\n\n/** 改写 CSS 中的 url(...) 与 @import \"...\" */\nfunction rewriteCssUrls(css: string, fromFile: string, renameMap: Map<string, string>): string {\n css = css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `url(${quote}${replaced}${quote})`;\n });\n css = css.replace(/@import\\s+(['\"])([^'\"]+)\\1/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `@import ${quote}${replaced}${quote}`;\n });\n return css;\n}\n","/**\n * Auto-generated index.html for Lynx plugins — Flutter WebView fallback.\n *\n * When a plugin declares renderEngine: \"lynx\", the builder produces this HTML\n * alongside the .lynx.bundle and .web.bundle. Flutter's WebView loads this page,\n * which bootstraps @lynx-js/web-core + the .web.bundle, making one ReactLynx\n * codebase render everywhere.\n */\n\nexport function generateLynxIndexHtml(entryPath: string): string {\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no\">\n <title>${entryPath}</title>\n <link href=\"../../jsplugin-assets/web-core/static/css/client.css\" rel=\"stylesheet\">\n <style>\n html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }\n lynx-view { width: 100vw; height: 100vh; display: block; }\n </style>\n</head>\n<body>\n <lynx-view id=\"plugin-view\"></lynx-view>\n <script type=\"module\" src=\"../../jsplugin-assets/web-core/static/js/client.js\"></script>\n <script type=\"module\" src=\"../../jsplugin-assets/lynx-plugin-bridge-shim.js\"></script>\n</body>\n</html>\n`;\n}\n"],"mappings":";AAEA,YAAY,aAAa;AACzB,OAAO,WAAW;AAClB,SAAS,gBAAAA,eAAc,iBAAAC,gBAAe,WAAW,YAAY,QAAQ,YAAY,QAAQ,eAAe,sBAAsB;AAC9H,SAAS,QAAAC,OAAM,SAAS,WAAAC,gBAAe;AACvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;;;ACJ9B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AAOrB,IAAM,mBAAmB;AAGzB,IAAM,uBAAuB,CAAC,WAAW,MAAM;AAC/C,IAAM,eAAe;AAGrB,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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,cAAa,QAAQ,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;","names":["readFileSync","writeFileSync","join","dirname","readFileSync","join","walk","readFileSync","readdirSync","statSync","join","posix","relative","relative","readFileSync","join","statSync","readdirSync","posix","readdirSync","statSync","join","build","writeFileSync","readFileSync","dirname"]}
|
|
1
|
+
{"version":3,"sources":["../src/build.ts","../src/manifest.ts","../src/hash.ts","../src/static-assets.ts","../src/lynx-index-html.ts","../src/frontend-npm.ts"],"sourcesContent":["// @songloft/plugin-builder — 核心 build 逻辑\n\nimport * as esbuild from 'esbuild';\nimport JSZip from 'jszip';\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, cpSync, unlinkSync, rmSync, readdirSync as readdirSyncTop } from 'node:fs';\nimport { join, resolve, dirname } from 'node:path';\nimport { execFileSync } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { readManifest, validateManifest } from './manifest.js';\nimport { computeEntryHash, computeCanonicalZipHash, sha256Hex } from './hash.js';\nimport { hashStaticAssets } from './static-assets.js';\nimport { generateLynxIndexHtml } from './lynx-index-html.js';\nimport type { PluginManifest } from '@songloft/plugin-sdk';\n\nimport { runFrontendNpm } from './frontend-npm.js';\n\nexport interface BuildOptions {\n cwd: string;\n outDir?: string;\n mode?: 'development' | 'production';\n sourcemap?: boolean;\n}\n\nexport interface BuildResult {\n zipPath: string;\n manifest: PluginManifest;\n size: number;\n entryHash: string;\n zipHash: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: { field: string; message: string }[];\n}\n\n/**\n * 构建插件:TS/JS → QuickJS-compatible JS → .jsplugin.zip\n */\nexport async function buildPlugin(opts: BuildOptions): Promise<BuildResult> {\n const cwd = resolve(opts.cwd);\n const outDir = opts.outDir ? resolve(cwd, opts.outDir) : join(cwd, 'dist');\n const buildDir = join(outDir, '_build');\n const mode = opts.mode ?? 'production';\n\n // [1] 读取并校验 plugin.json\n const manifest = readManifest(cwd);\n const errors = validateManifest(manifest);\n if (errors.length > 0) {\n throw new Error(`Invalid plugin.json:\\n${errors.map(e => ` - ${e.field}: ${e.message}`).join('\\n')}`);\n }\n\n // [2] esbuild 打包 src/main.ts → build/main.js\n //\n // _build 是**纯暂存目录**:最后整目录进 zip(addDirToZip(zip, buildDir, ''))且整目录\n // 参与 computeCanonicalZipHash。所以它必须每次从零开始 —— 否则 [3.1.1] 步注入内容 hash\n // 产出的 `style.<hash>.css` 会**逐次堆积**:同一份源码构建多次,zip 里会带上历史所有版本\n // 的资源(实测 downloader 连构 4 次后 zip 里有 4 份 style.*.css),而 index.html 只引用\n // 最新那份。后果不只是体积——`zipHash` 会随构建历史漂移,同样的源码算出不同的哈希,\n // 这条哈希的完整性用途就没了。cpSync 是合并语义、不会替我们清,只能显式删。\n rmSync(buildDir, { recursive: true, force: true });\n mkdirSync(buildDir, { recursive: true });\n const entryPoint = join(cwd, 'src', 'main.ts');\n const entryPointAlt = join(cwd, 'src', 'main.js');\n const actualEntry = existsSync(entryPoint) ? entryPoint : entryPointAlt;\n\n if (!existsSync(actualEntry)) {\n throw new Error(`Entry file not found: src/main.ts or src/main.js`);\n }\n\n await esbuild.build({\n entryPoints: [actualEntry],\n outfile: join(buildDir, 'main.js'),\n bundle: true,\n platform: 'neutral',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n sourcemap: opts.sourcemap ? 'inline' : false,\n // 禁止使用 Node 内置模块\n plugins: [{\n name: 'no-node-builtins',\n setup(build) {\n build.onResolve({ filter: /^(fs|net|http|https|child_process|os|path|crypto|stream|util|events|buffer|url|querystring|zlib)$/ }, (args) => {\n return { errors: [{ text: `Node builtin \"${args.path}\" is not available in QuickJS runtime` }] };\n });\n },\n }],\n });\n\n // [2.5] 前端 Vue/Vite 编译(如果存在 frontend/ 目录)\n const frontendDir = join(cwd, 'frontend');\n if (existsSync(join(frontendDir, 'package.json'))) {\n // 仅在依赖缺失时安装:dev 模式每次热重载都会走到这里,无脑 npm install 会拖慢重建\n if (!existsSync(join(frontendDir, 'node_modules'))) {\n console.log(` 📦 Installing frontend dependencies...`);\n runFrontendNpm(frontendDir, 'install');\n }\n console.log(` 🚀 Building frontend project...`);\n runFrontendNpm(frontendDir, 'build');\n // 根据模板配置,产物会被直接输出到 cwd/static。但为了兼容自定义 dist 输出,加一个 fallback 拷贝:\n if (existsSync(join(frontendDir, 'dist'))) {\n cpSync(join(frontendDir, 'dist'), join(buildDir, 'static'), { recursive: true });\n }\n }\n\n // [2.6] Lynx 插件后处理:rspeedy 产出 dist/lynx/ 和 dist/web/ 子目录,\n // 将 bundle 文件提升到 static/ 根并生成 Flutter WebView 用的 index.html。\n if (manifest.renderEngine === 'lynx') {\n const staticOut = join(buildDir, 'static');\n const lynxBundleDir = join(staticOut, 'lynx');\n const webBundleDir = join(staticOut, 'web');\n mkdirSync(staticOut, { recursive: true });\n\n const lynxBundle = join(lynxBundleDir, 'main.lynx.bundle');\n const webBundle = join(webBundleDir, 'main.web.bundle');\n\n let webBundleVersion: string | undefined;\n if (existsSync(lynxBundle)) {\n cpSync(lynxBundle, join(staticOut, 'main.lynx.bundle'));\n }\n if (existsSync(webBundle)) {\n cpSync(webBundle, join(staticOut, 'main.web.bundle'));\n // SHA-256 前 16 位,与 MIoT/Bili 插件侧声明的版本格式一致。\n webBundleVersion = sha256Hex(readFileSync(webBundle)).slice(0, 16);\n }\n\n // Remove the intermediate subdirectories\n rmSync(lynxBundleDir, { recursive: true, force: true });\n rmSync(webBundleDir, { recursive: true, force: true });\n\n // Generate index.html for Flutter WebView fallback (loads web-core + .web.bundle)\n writeFileSync(join(staticOut, 'index.html'), generateLynxIndexHtml(manifest.entryPath, webBundleVersion));\n\n console.log(` 🔗 Lynx bundles flattened + index.html generated`);\n }\n\n // [3] 拷贝 static/ 到 build/(如果存在)\n const staticDir = join(cwd, 'static');\n if (existsSync(staticDir)) {\n cpSync(staticDir, join(buildDir, 'static'), { recursive: true });\n }\n\n // [3.0] 拷贝 bin/ 到 build/(如果存在,用于打包可执行文件)\n const binDir = join(cwd, 'bin');\n if (existsSync(binDir)) {\n cpSync(binDir, join(buildDir, 'bin'), { recursive: true });\n }\n\n // [3.1] 合并打包前端 JS(如果 static/js/app.js 存在)\n const staticJsAppPath = join(buildDir, 'static', 'js', 'app.js');\n if (existsSync(staticJsAppPath)) {\n const bundleOutPath = join(buildDir, 'static', 'js', 'app.bundle.js');\n await esbuild.build({\n entryPoints: [staticJsAppPath],\n outfile: bundleOutPath,\n bundle: true,\n platform: 'browser',\n format: 'iife',\n target: 'es2020',\n minify: mode === 'production',\n });\n\n // 删除 static/js/ 下除 app.bundle.js 外的所有 .js 文件\n const staticJsDir = join(buildDir, 'static', 'js');\n const jsFiles = readdirSyncTop(staticJsDir).filter(f => f.endsWith('.js') && f !== 'app.bundle.js');\n for (const f of jsFiles) {\n unlinkSync(join(staticJsDir, f));\n }\n\n // 更新 index.html 中的 script 引用:将 app.js 替换为打包后的 app.bundle.js\n // 匹配时兼容属性顺序不同、多空格、以及 src 中有无 static/ 前缀\n const indexHtmlPath = join(buildDir, 'static', 'index.html');\n if (existsSync(indexHtmlPath)) {\n let html = readFileSync(indexHtmlPath, 'utf-8');\n const before = html;\n html = html.replace(\n /<script\\b[^>]*\\bsrc=\"(?:static\\/)?js\\/app\\.js\"[^>]*><\\/script>/,\n '<script src=\"static/js/app.bundle.js\"></script>'\n );\n if (html === before) {\n throw new Error(\n 'Failed to update script tag in static/index.html: ' +\n 'expected <script ... src=\"static/js/app.js\" ...> or <script ... src=\"js/app.js\" ...> but pattern not found'\n );\n }\n writeFileSync(indexHtmlPath, html);\n }\n\n console.log(` 📦 static/js/ bundled → app.bundle.js (${jsFiles.length} files merged)`);\n }\n\n // [3.1.1] 为 static/ 下所有 JS/CSS/字体/图片注入内容 hash 到文件名,\n // 并改写 HTML/CSS 中的引用,防止插件更新后浏览器使用旧缓存。\n // 可在 plugin.json 中设置 \"staticHash\": false 关闭(用于前端已用\n // Vite/Webpack 等工具自管理 hash 的场景)。\n const staticBuildDir = join(buildDir, 'static');\n let staticRenameMap: Map<string, string> | undefined;\n if (existsSync(staticBuildDir) && manifest.staticHash !== false) {\n const { renamed, renameMap } = hashStaticAssets(staticBuildDir);\n if (renamed > 0) {\n staticRenameMap = renameMap;\n console.log(` 🏷️ static assets hashed (${renamed} files)`);\n }\n }\n\n // [3.2] 编译 main.js 为 main.jsc 字节码(如果 jsc 工具可用)\n let mainFileName = 'main.js';\n const mainJsPath = join(buildDir, 'main.js');\n const mainJscPath = join(buildDir, 'main.jsc');\n try {\n const jscCmd = findJscBinary();\n if (!jscCmd) {\n throw new Error('jsc binary not found');\n }\n execFileSync(jscCmd, [mainJsPath, mainJscPath], { stdio: 'pipe' });\n // 编译成功,删除 main.js\n unlinkSync(mainJsPath);\n mainFileName = 'main.jsc';\n console.log(` 🔒 main.js compiled → main.jsc (via ${jscCmd})`);\n } catch {\n // jsc 可能在失败前已经创建了不完整的输出。回退到 main.js 时必须删除它,\n // 否则宿主会优先加载 main.jsc,并与按 main.js 计算的 entryHash 失配。\n if (existsSync(mainJscPath)) {\n unlinkSync(mainJscPath);\n }\n console.log(` ⚠️ jsc not available, keeping main.js`);\n }\n\n // [4] 计算 entryHash\n const mainJsContent = readFileSync(join(buildDir, mainFileName));\n const entryHash = computeEntryHash(mainJsContent);\n\n // [5] 计算 zipHash(排除 plugin.json)\n const zipHash = computeCanonicalZipHash(buildDir);\n\n // [6] 写入最终 plugin.json(含 hash)\n const finalManifest: PluginManifest = {\n ...manifest,\n main: mainFileName,\n entryHash,\n zipHash,\n };\n // icon 字段回写:用 hash 后的实际文件名替换原始文件名\n if (finalManifest.icon && staticRenameMap) {\n const hashedIcon = staticRenameMap.get(finalManifest.icon);\n if (hashedIcon) {\n finalManifest.icon = hashedIcon;\n }\n }\n writeFileSync(join(buildDir, 'plugin.json'), JSON.stringify(finalManifest, null, 2));\n\n // [7] 打包为 .jsplugin.zip\n mkdirSync(outDir, { recursive: true });\n const zip = new JSZip();\n addDirToZip(zip, buildDir, '');\n const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });\n const zipPath = join(outDir, `${manifest.entryPath}.jsplugin.zip`);\n writeFileSync(zipPath, zipBuffer);\n\n // [8] 输出报告\n const mainJsGzip = Buffer.byteLength(mainJsContent);\n console.log(`\\n✅ Build successful!`);\n console.log(` 📦 ${zipPath} (${(zipBuffer.length / 1024).toFixed(1)} KB)`);\n console.log(` 📄 main.js: ${(mainJsGzip / 1024).toFixed(1)} KB`);\n console.log(` 🔑 entryHash: ${entryHash}`);\n console.log(` 🔑 zipHash: ${zipHash}\\n`);\n\n return { zipPath, manifest: finalManifest, size: zipBuffer.length, entryHash, zipHash };\n}\n\n/**\n * 校验已构建的插件\n */\nexport async function validatePlugin(cwd: string): Promise<ValidationResult> {\n const resolvedCwd = resolve(cwd);\n const errors: { field: string; message: string }[] = [];\n\n // 读取 manifest\n let manifest: PluginManifest;\n try {\n manifest = readManifest(resolvedCwd);\n } catch {\n return { valid: false, errors: [{ field: 'plugin.json', message: 'cannot read plugin.json' }] };\n }\n\n // 字段校验\n const fieldErrors = validateManifest(manifest);\n errors.push(...fieldErrors);\n\n // hash 校验\n if (!manifest.entryHash || !manifest.zipHash) {\n errors.push({ field: 'hash', message: 'entryHash and zipHash are required. Run `songloft-plugin build` first.' });\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// --- 工具 ---\n\nimport { getJscBinaryPath } from '@songloft/jsc';\nimport { readdirSync, statSync } from 'node:fs';\n\n/**\n * 查找 jsc 二进制文件\n * 优先级:\n * 1. @songloft/jsc workspace 包中对应当前平台的预编译二进制\n * 2. PATH 中的 jsc 命令\n * 3. 项目根目录的 jsc 兼容旧路径\n */\nfunction findJscBinary(): string | null {\n // 获取当前文件所在目录(兼容 ESM 和 CJS)\n const currentDir = dirname(fileURLToPath(import.meta.url));\n\n // 1. 通过 @songloft/jsc 包定位预编译二进制\n try {\n const jscPath = getJscBinaryPath();\n if (existsSync(jscPath)) return jscPath;\n } catch {\n // 包未安装,继续尝试下一个路径\n }\n\n // 2. 检查 PATH 中的 jsc\n try {\n execFileSync('jsc', ['--help'], { stdio: 'pipe' });\n return 'jsc';\n } catch {\n // 继续尝试下一个路径\n }\n\n // 3. 兼容旧路径:项目根目录的 jsc (songloft/jsc)\n // 从 src/ 或 dist/ → plugin-builder/ → packages/ → plugin-toolchain/ → songloft/\n const projectJsc = join(currentDir, '..', '..', '..', '..', 'jsc');\n if (existsSync(projectJsc)) return projectJsc;\n\n return null;\n}\n\nfunction addDirToZip(zip: JSZip, dirPath: string, prefix: string) {\n const items = readdirSync(dirPath);\n for (const item of items) {\n const fullPath = join(dirPath, item);\n const zipPath = prefix ? `${prefix}/${item}` : item;\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n addDirToZip(zip, fullPath, zipPath);\n } else {\n zip.file(zipPath, readFileSync(fullPath));\n }\n }\n}\n","// @songloft/plugin-builder — manifest 校验模块\n\nimport type { PluginManifest } from '@songloft/plugin-sdk';\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface ManifestValidationError {\n field: string;\n message: string;\n}\n\nconst ENTRY_PATH_REGEX = /^[a-z][a-z0-9-]*$/;\n// 渲染引擎白名单,需与后端 internal/jsplugin 的校验保持一致。\n// 可选字段:缺省或空串 = webview(宿主默认)。\nconst VALID_RENDER_ENGINES = ['webview', 'lynx'];\nconst SEMVER_REGEX = /^\\d+\\.\\d+\\.\\d+/;\n// 权限白名单,需与后端 internal/jsplugin/permissions.go 的 AllPermissions 保持一致。\n// songs.* / playlists.* / fs.* 为声明层的通配符糖(一把梭)。\nconst VALID_PERMISSIONS = [\n 'storage',\n 'songs.read',\n 'songs.write',\n 'playlists.read',\n 'playlists.write',\n 'inter-plugin',\n 'command',\n 'jsenv',\n 'fs',\n 'fs:music',\n 'fs:external',\n 'websocket',\n 'persistent-storage',\n 'net',\n 'net:insecure-tls',\n 'tags.read',\n 'tags.write',\n 'songs.*',\n 'playlists.*',\n 'tags.*',\n 'fs.*',\n];\n\n/**\n * 从 cwd 读取 plugin.json\n */\nexport function readManifest(cwd: string): PluginManifest {\n const raw = readFileSync(join(cwd, 'plugin.json'), 'utf-8');\n return JSON.parse(raw) as PluginManifest;\n}\n\n/**\n * 校验 plugin.json 字段\n */\nexport function validateManifest(m: PluginManifest): ManifestValidationError[] {\n const errors: ManifestValidationError[] = [];\n\n if (!m.name || m.name.length < 2 || m.name.length > 50) {\n errors.push({ field: 'name', message: 'name must be 2-50 characters' });\n }\n if (!m.version || !SEMVER_REGEX.test(m.version)) {\n errors.push({ field: 'version', message: 'version must be valid semver (x.y.z)' });\n }\n if (!m.entryPath || !ENTRY_PATH_REGEX.test(m.entryPath)) {\n errors.push({ field: 'entryPath', message: 'entryPath must be lowercase kebab-case starting with a letter' });\n }\n if (!m.main || (!m.main.endsWith('.js') && !m.main.endsWith('.jsc'))) {\n errors.push({ field: 'main', message: 'main must end with .js or .jsc' });\n }\n // renderEngine 可选:未声明或空串走宿主默认(webview),仅校验显式给出的非法值\n const renderEngine = m.renderEngine as string | undefined;\n if (renderEngine !== undefined && renderEngine !== '' && !VALID_RENDER_ENGINES.includes(renderEngine)) {\n errors.push({\n field: 'renderEngine',\n message: `renderEngine must be one of ${VALID_RENDER_ENGINES.join(' | ')} (got: ${renderEngine})`,\n });\n }\n if (!Array.isArray(m.permissions)) {\n errors.push({ field: 'permissions', message: 'permissions must be an array' });\n } else {\n for (const perm of m.permissions) {\n if (!VALID_PERMISSIONS.includes(perm)) {\n errors.push({ field: 'permissions', message: `unknown permission: ${perm}` });\n }\n }\n }\n\n return errors;\n}\n","// @songloft/plugin-builder — hash 计算模块\n// 与后端 Go 版本 ComputeCanonicalZipHash / ComputeEntryHash 算法完全一致。\n\nimport { createHash } from 'node:crypto';\nimport { readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, posix } from 'node:path';\n\n/**\n * sha256 hex\n */\nexport function sha256Hex(data: Buffer | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * 计算 entryHash(main.js 的 sha256)\n */\nexport function computeEntryHash(mainJsContent: Buffer | string): string {\n return sha256Hex(mainJsContent);\n}\n\n/**\n * 计算 canonical zipHash。\n *\n * 算法(与后端保持一致):\n * 1. 枚举 buildDir 下所有文件(排除 plugin.json)\n * 2. 按路径 Unicode 升序排序(使用 posix 风格的路径分隔符)\n * 3. 对每个文件:hasher.write(path + \"\\n\" + sha256Hex(content) + \"\\n\")\n * 4. 对最终拼接串再 sha256\n */\nexport function computeCanonicalZipHash(buildDir: string): string {\n const entries: { path: string; hash: string }[] = [];\n\n function walk(dir: string) {\n const items = readdirSync(dir);\n for (const item of items) {\n const fullPath = join(dir, item);\n const stat = statSync(fullPath);\n if (stat.isDirectory()) {\n walk(fullPath);\n } else {\n const relPath = posix.normalize(relative(buildDir, fullPath).replace(/\\\\/g, '/'));\n if (relPath === 'plugin.json') continue;\n const content = readFileSync(fullPath);\n entries.push({ path: relPath, hash: sha256Hex(content) });\n }\n }\n }\n\n walk(buildDir);\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n\n const hasher = createHash('sha256');\n for (const e of entries) {\n hasher.update(e.path + '\\n' + e.hash + '\\n');\n }\n return hasher.digest('hex');\n}\n","// @songloft/plugin-builder — 前端静态资源 hash 处理\n//\n// 为 static/ 目录下的 JS/CSS/字体/图片等资源注入内容 hash 到文件名,\n// 并改写 HTML 中的 <script src> / <link href> 与 CSS 中的 url() 引用,\n// 防止插件版本更新后浏览器仍命中旧缓存。\n//\n// 处理顺序(按依赖反向):\n// 1. 叶子资源(字体/图片/媒体)先 hash\n// 2. CSS 改写内部 url(...) 后再 hash\n// 3. JS 单独 hash(不扫描内部内容)\n// 4. HTML 改写 <script src> / <link href> 等引用\n\nimport { readFileSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs';\nimport { join, dirname, basename, posix, relative } from 'node:path';\nimport { sha256Hex } from './hash.js';\n\nconst ASSET_EXT = /\\.(woff2?|ttf|otf|eot|png|jpe?g|gif|svg|webp|ico|mp3|mp4|wav|ogg)$/i;\nconst CSS_EXT = /\\.css$/i;\nconst JS_EXT = /\\.m?js$/i;\nconst HTML_EXT = /\\.html?$/i;\n\nconst HASH_LEN = 8;\n\n/**\n * 文件名\"看起来已经 hash 过\"的检测。\n * 匹配 `name.<8+位 url-safe base64/hex>.ext` 或 `name-<同上>.ext`,\n * 用于跳过已由 Vite/Webpack/Rollup 等工具自管理 hash 的产物。\n *\n * 注意:要保留至少一段\"语义名\",避免把 `roboto-400.woff2`(400 仅 3 位)\n * 或纯 hash 文件名误判。\n */\nconst HASHED_NAME_RE = /^(.+)[.-]([A-Za-z0-9_-]{8,})\\.[^.]+$/;\nfunction looksAlreadyHashed(filename: string): boolean {\n const m = HASHED_NAME_RE.exec(filename);\n if (!m) return false;\n const seg = m[2];\n // 8+ 位且由 hex 字符组成即视为 hash(含纯数字情况如 67058905)\n return /^[A-Fa-f0-9]{8,}$/.test(seg) || (/[A-Za-z]/.test(seg) && /\\d/.test(seg));\n}\n\n/**\n * 入口:hash static 目录下的资源并改写引用。\n * staticBuildDir 必须存在;不存在时由调用方判断后再传入。\n */\nexport function hashStaticAssets(staticBuildDir: string): { renamed: number; renameMap: Map<string, string> } {\n const all = walk(staticBuildDir);\n const rel = (p: string) => toPosix(relative(staticBuildDir, p));\n\n const assets = all.filter(p => ASSET_EXT.test(p));\n const cssList = all.filter(p => CSS_EXT.test(p));\n const jsList = all.filter(p => JS_EXT.test(p));\n const htmlList = all.filter(p => HTML_EXT.test(p));\n\n // 先扫描所有 CSS/HTML/JS,把\"被绝对路径(含 /static/)引用\"的资源加入\n // pinned 集合——这些文件不能改名,否则会破坏运行时引用。\n const pinned = collectPinnedAssets([...htmlList, ...cssList, ...jsList], rel, staticBuildDir);\n const notPinned = (p: string) => !pinned.has(rel(p));\n\n // 原相对路径 → 新相对路径(含 hash),均为 posix 风格\n const renameMap = new Map<string, string>();\n\n // 1. 叶子资源\n for (const file of assets.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 2. CSS:先改写 url(),再 hash\n for (const file of cssList) {\n const relPath = rel(file);\n const content = readFileSync(file, 'utf-8');\n const rewritten = rewriteCssUrls(content, relPath, renameMap);\n if (rewritten !== content) writeFileSync(file, rewritten);\n if (pinned.has(relPath)) continue;\n const newRel = renameWithHash(staticBuildDir, relPath);\n renameMap.set(relPath, newRel);\n }\n\n // 3. JS\n for (const file of jsList.filter(notPinned)) {\n const newRel = renameWithHash(staticBuildDir, rel(file));\n renameMap.set(rel(file), newRel);\n }\n\n // 4. HTML:改写引用\n for (const file of htmlList) {\n const relPath = rel(file);\n const html = readFileSync(file, 'utf-8');\n const rewritten = rewriteHtmlRefs(html, relPath, renameMap);\n if (rewritten !== html) writeFileSync(file, rewritten);\n }\n\n return { renamed: renameMap.size, renameMap };\n}\n\n// --- 内部工具 ---\n\n/**\n * 扫描指定文件(CSS/HTML/JS),找出\"被含 /static/ 的绝对路径引用\"的资源,\n * 比如 CSS 里 url('/api/v1/plugin/lxmusic/static/fonts/roboto.woff2')。\n * 这些资源不能改名,否则运行时绝对路径会 404。\n *\n * 返回的 set 包含相对 staticDir 的 posix 路径。\n */\nfunction collectPinnedAssets(\n files: string[],\n rel: (p: string) => string,\n staticDir: string,\n): Set<string> {\n const pinned = new Set<string>();\n // 匹配引号内或 url(...) 内出现的、含 /static/<rest> 的串\n const re = /\\/(?:[^\\s\"')]*\\/)?static\\/([A-Za-z0-9_\\-./]+?)(?=[\"')?#\\s]|$)/g;\n for (const file of files) {\n let content: string;\n try {\n content = readFileSync(file, 'utf-8');\n } catch {\n continue;\n }\n for (const m of content.matchAll(re)) {\n const candidate = m[1].replace(/\\/+$/, '');\n if (!candidate) continue;\n // 仅当该路径在 static 下真实存在\n const abs = join(staticDir, candidate);\n try {\n if (statSync(abs).isFile()) pinned.add(candidate);\n } catch {\n // 不存在,忽略\n }\n }\n }\n return pinned;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const item of readdirSync(dir)) {\n const full = join(dir, item);\n const st = statSync(full);\n if (st.isDirectory()) out.push(...walk(full));\n else out.push(full);\n }\n return out;\n}\n\nfunction toPosix(p: string): string {\n return p.split(/[\\\\/]/).join('/');\n}\n\n/**\n * 重命名文件:name.ext → name.<hash>.ext。返回新相对路径(posix)。\n * 若文件名已经包含可识别的 hash(来自 Vite/Webpack 等),则原路径直接返回,不动文件。\n */\nfunction renameWithHash(rootDir: string, relPath: string): string {\n const base = basename(relPath);\n if (looksAlreadyHashed(base)) return relPath;\n const abs = join(rootDir, relPath);\n const hash = sha256Hex(readFileSync(abs)).slice(0, HASH_LEN);\n const dir = dirname(relPath);\n const dot = base.lastIndexOf('.');\n const newBase = dot <= 0\n ? `${base}.${hash}`\n : `${base.slice(0, dot)}.${hash}${base.slice(dot)}`;\n const newRel = dir === '.' || dir === '' ? newBase : posix.join(toPosix(dir), newBase);\n renameSync(abs, join(rootDir, newRel));\n return newRel;\n}\n\ninterface ResolvedRef {\n /** 相对 static 根的路径,用作 renameMap key */\n staticRel: string;\n /** ?query#hash 后缀 */\n suffix: string;\n /** 原 url 是否带 \"static/\" 前缀(HTML 中常见) */\n hadStaticPrefix: boolean;\n /** 原 url 是否以 ./ 或 ../ 开头 */\n isExplicitRelative: boolean;\n}\n\n/**\n * 把出现在 fromFile(相对 static 根的路径)中的 url 解析为\n * 相对 static 根的资源路径,便于在 renameMap 中查找。\n *\n * 支持:\n * - \"static/css/style.css\" —— HTML 中从插件根访问\n * - \"css/style.css\" —— 从当前文件同目录访问\n * - \"./x.png\" / \"../foo\"\n *\n * 不处理:绝对路径(/...)、协议(http://、data:、blob: 等)、\n * 锚点(#xxx)、空 url。\n */\nfunction resolveRef(url: string, fromFile: string): ResolvedRef | null {\n if (!url) return null;\n if (/^(?:[a-z]+:|\\/\\/|#|data:|blob:|mailto:)/i.test(url)) return null;\n if (url.startsWith('/')) return null;\n\n let bare = url;\n let suffix = '';\n const qIdx = bare.search(/[?#]/);\n if (qIdx >= 0) {\n suffix = bare.slice(qIdx);\n bare = bare.slice(0, qIdx);\n }\n\n const hadStaticPrefix = bare.startsWith('static/');\n const isExplicitRelative = bare.startsWith('./') || bare.startsWith('../');\n\n let staticRel: string;\n if (hadStaticPrefix) {\n staticRel = bare.slice('static/'.length);\n } else {\n const fromDir = toPosix(dirname(fromFile));\n staticRel = fromDir === '.' || fromDir === ''\n ? bare.replace(/^\\.\\//, '')\n : posix.normalize(posix.join(fromDir, bare));\n }\n if (staticRel.startsWith('..')) return null;\n return { staticRel, suffix, hadStaticPrefix, isExplicitRelative };\n}\n\n/**\n * 根据 renameMap 重新组装引用字符串。renameMap 未命中时返回 null。\n */\nfunction applyRename(\n ref: ResolvedRef,\n renameMap: Map<string, string>,\n fromFile: string,\n): string | null {\n const renamed = renameMap.get(ref.staticRel);\n if (!renamed) return null;\n\n let out: string;\n if (ref.hadStaticPrefix) {\n out = `static/${renamed}`;\n } else {\n const fromDir = toPosix(dirname(fromFile));\n if (fromDir === '.' || fromDir === '') {\n out = renamed;\n } else {\n out = toPosix(relative(fromDir, renamed));\n }\n if (ref.isExplicitRelative && !out.startsWith('.')) out = `./${out}`;\n }\n return out + ref.suffix;\n}\n\nfunction tryRewrite(url: string, fromFile: string, renameMap: Map<string, string>): string | null {\n const ref = resolveRef(url, fromFile);\n if (!ref) return null;\n return applyRename(ref, renameMap, fromFile);\n}\n\n/** 改写 HTML 中的 src=/href= 引用 */\nfunction rewriteHtmlRefs(html: string, fromFile: string, renameMap: Map<string, string>): string {\n return html.replace(/\\b(src|href)\\s*=\\s*([\"'])([^\"']+)\\2/gi, (full, attr, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `${attr}=${quote}${replaced}${quote}`;\n });\n}\n\n/** 改写 CSS 中的 url(...) 与 @import \"...\" */\nfunction rewriteCssUrls(css: string, fromFile: string, renameMap: Map<string, string>): string {\n css = css.replace(/url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `url(${quote}${replaced}${quote})`;\n });\n css = css.replace(/@import\\s+(['\"])([^'\"]+)\\1/gi, (full, quote, url) => {\n const replaced = tryRewrite(url, fromFile, renameMap);\n return replaced == null ? full : `@import ${quote}${replaced}${quote}`;\n });\n return css;\n}\n","/**\n * Auto-generated index.html for Lynx plugins — Flutter WebView fallback.\n *\n * When a plugin declares renderEngine: \"lynx\", the builder produces this HTML\n * alongside the .lynx.bundle and .web.bundle. Flutter's WebView loads this page,\n * which bootstraps @lynx-js/web-core + the .web.bundle, making one ReactLynx\n * codebase render everywhere.\n *\n * webBundleVersion 是 main.web.bundle 的内容哈希;带上后新版本服务端的\n * lynx-plugin-bridge-shim 会按声明加载带版本参数的 bundle 地址,插件更新后\n * 浏览器不会命中旧缓存。未提供时保持原有固定地址(旧宿主兼容路径)。\n */\n\nexport function generateLynxIndexHtml(entryPath: string, webBundleVersion?: string): string {\n const bundleAttr = webBundleVersion\n ? ` data-songloft-lynx-bundle=\"static/main.web.bundle?v=${webBundleVersion}\"`\n : '';\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no\">\n <title>${entryPath}</title>\n <link href=\"../../jsplugin-assets/web-core/static/css/client.css\" rel=\"stylesheet\">\n <style>\n html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }\n lynx-view { width: 100vw; height: 100vh; display: block; }\n </style>\n</head>\n<body>\n <lynx-view id=\"plugin-view\"></lynx-view>\n <script type=\"module\" src=\"../../jsplugin-assets/web-core/static/js/client.js\"></script>\n <script type=\"module\" src=\"../../jsplugin-assets/lynx-plugin-bridge-shim.js\"${bundleAttr}></script>\n</body>\n</html>\n`;\n}\n","import { execFileSync } from 'node:child_process';\n\n/** Only fixed npm arguments enter cmd.exe; project paths use cwd, never shell interpolation. */\nexport function runFrontendNpm(cwd: string, action: 'install' | 'build'): void {\n execFileSync(\n process.platform === 'win32' ? 'npm.cmd' : 'npm',\n action === 'install' ? ['install'] : ['run', 'build'],\n { cwd, stdio: 'inherit', shell: process.platform === 'win32' },\n );\n}\n"],"mappings":";AAEA,YAAY,aAAa;AACzB,OAAO,WAAW;AAClB,SAAS,gBAAAA,eAAc,iBAAAC,gBAAe,WAAW,YAAY,QAAQ,YAAY,QAAQ,eAAe,sBAAsB;AAC9H,SAAS,QAAAC,OAAM,SAAS,WAAAC,gBAAe;AACvC,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,qBAAqB;;;ACJ9B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AAOrB,IAAM,mBAAmB;AAGzB,IAAM,uBAAuB,CAAC,WAAW,MAAM;AAC/C,IAAM,eAAe;AAGrB,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKO,SAAS,aAAa,KAA6B;AACxD,QAAM,MAAM,aAAa,KAAK,KAAK,aAAa,GAAG,OAAO;AAC1D,SAAO,KAAK,MAAM,GAAG;AACvB;AAKO,SAAS,iBAAiB,GAA8C;AAC7E,QAAM,SAAoC,CAAC;AAE3C,MAAI,CAAC,EAAE,QAAQ,EAAE,KAAK,SAAS,KAAK,EAAE,KAAK,SAAS,IAAI;AACtD,WAAO,KAAK,EAAE,OAAO,QAAQ,SAAS,+BAA+B,CAAC;AAAA,EACxE;AACA,MAAI,CAAC,EAAE,WAAW,CAAC,aAAa,KAAK,EAAE,OAAO,GAAG;AAC/C,WAAO,KAAK,EAAE,OAAO,WAAW,SAAS,uCAAuC,CAAC;AAAA,EAC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,GAAG,WAAW;AAG1B,MAAI,CAAC,SAAS,aAAa,CAAC,SAAS,SAAS;AAC5C,WAAO,KAAK,EAAE,OAAO,QAAQ,SAAS,yEAAyE,CAAC;AAAA,EAClH;AAEA,SAAO,EAAE,OAAO,OAAO,WAAW,GAAG,OAAO;AAC9C;AAcA,SAAS,gBAA+B;AAEtC,QAAM,aAAaE,SAAQ,cAAc,YAAY,GAAG,CAAC;AAGzD,MAAI;AACF,UAAM,UAAU,iBAAiB;AACjC,QAAI,WAAW,OAAO,EAAG,QAAO;AAAA,EAClC,QAAQ;AAAA,EAER;AAGA,MAAI;AACF,IAAAD,cAAa,OAAO,CAAC,QAAQ,GAAG,EAAE,OAAO,OAAO,CAAC;AACjD,WAAO;AAAA,EACT,QAAQ;AAAA,EAER;AAIA,QAAM,aAAaJ,MAAK,YAAY,MAAM,MAAM,MAAM,MAAM,KAAK;AACjE,MAAI,WAAW,UAAU,EAAG,QAAO;AAEnC,SAAO;AACT;AAEA,SAAS,YAAY,KAAY,SAAiB,QAAgB;AAChE,QAAM,QAAQF,aAAY,OAAO;AACjC,aAAW,QAAQ,OAAO;AACxB,UAAM,WAAWE,MAAK,SAAS,IAAI;AACnC,UAAM,UAAU,SAAS,GAAG,MAAM,IAAI,IAAI,KAAK;AAC/C,UAAM,OAAOD,UAAS,QAAQ;AAC9B,QAAI,KAAK,YAAY,GAAG;AACtB,kBAAY,KAAK,UAAU,OAAO;AAAA,IACpC,OAAO;AACL,UAAI,KAAK,SAASG,cAAa,QAAQ,CAAC;AAAA,IAC1C;AAAA,EACF;AACF;","names":["readFileSync","writeFileSync","join","dirname","execFileSync","readFileSync","join","walk","readFileSync","readdirSync","statSync","join","posix","relative","relative","readFileSync","join","statSync","readdirSync","posix","readdirSync","statSync","join","build","readFileSync","writeFileSync","execFileSync","dirname"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@songloft/plugin-builder",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.22.0",
|
|
4
4
|
"description": "Build tool for Songloft JS plugins (TS/JS → QuickJS-compatible ZIP)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -24,13 +24,13 @@
|
|
|
24
24
|
"esbuild": "^0.25.0",
|
|
25
25
|
"jszip": "^3.10.0",
|
|
26
26
|
"glob": "^11.0.0",
|
|
27
|
-
"@songloft/jsc": "2.
|
|
27
|
+
"@songloft/jsc": "2.22.0"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"tsup": "^8.0.0",
|
|
31
31
|
"typescript": "^5.7.0",
|
|
32
32
|
"@types/node": "^22.0.0",
|
|
33
|
-
"@songloft/plugin-sdk": "^2.
|
|
33
|
+
"@songloft/plugin-sdk": "^2.22.0"
|
|
34
34
|
},
|
|
35
35
|
"keywords": [
|
|
36
36
|
"songloft",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
},
|
|
54
54
|
"scripts": {
|
|
55
55
|
"build": "tsup",
|
|
56
|
-
"test": "
|
|
56
|
+
"test": "node --test tests/*.test.mjs",
|
|
57
57
|
"typecheck": "tsc --noEmit"
|
|
58
58
|
}
|
|
59
59
|
}
|