sso-plugin.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. /* eslint-disable no-undef */
  2. // 基座 SSO 静态资源注入插件
  3. //
  4. // 业务项目用法(vite.config.js):
  5. // import ssoPlugin from 'sapit-ui-plus/vite-plugins/sso-plugin.js'
  6. // plugins: [ssoPlugin()]
  7. //
  8. // dev:以中间件兜底提供 /sso.html 与 /js/sso.js|qs.js|jquery-3.6.0.min.js
  9. // (挂在 vite 内部中间件之后,业务项目 public/ 里的同名文件优先级更高)
  10. // build:构建结束把 sso.html 与 js/ 脚本写入产物根目录
  11. // (业务项目无需再在 public/ 里维护 sso 文件;lib 模式构建自动跳过)
  12. import fs from 'node:fs'
  13. import path from 'node:path'
  14. import crypto from 'node:crypto'
  15. import { fileURLToPath } from 'node:url'
  16. // 包内相对本插件的 sso 资源目录:<pkg>/sso/
  17. const defaultDir = path.resolve(
  18. path.dirname(fileURLToPath(import.meta.url)),
  19. '..',
  20. 'sso'
  21. )
  22. // 相对 ssoDir 的文件 → Content-Type
  23. const FILES = {
  24. 'sso.html': 'text/html; charset=utf-8',
  25. 'js/sso.js': 'application/javascript; charset=utf-8',
  26. 'js/qs.js': 'application/javascript; charset=utf-8',
  27. 'js/jquery-3.6.0.min.js': 'application/javascript; charset=utf-8'
  28. }
  29. // 大 data URI 抽取阈值:超过则抽出为真实文件(lib 模式 vite 强制内联所有资产,
  30. // 大图 data URI 超浏览器 URL 长度上限无法渲染)
  31. const EXTRACT_THRESHOLD = 100 * 1024
  32. // 把产物 js/css 中超过阈值的 base64 data URI 抽出为 <outDir>/img/ 下的真实文件,
  33. // 并把引用改为相对当前文件的运行时路径(js 用 new URL(...,import.meta.url),css 直接相对路径)
  34. function extractLargeInlineAssets (outDir) {
  35. const imgDir = path.join(outDir, 'img')
  36. const scanDir = (dir, exts) => {
  37. let files = []
  38. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  39. const full = path.join(dir, entry.name)
  40. if (entry.isDirectory()) files = files.concat(scanDir(full, exts))
  41. else if (exts.some((e) => entry.name.endsWith(e))) files.push(full)
  42. }
  43. return files
  44. }
  45. const files = scanDir(outDir, ['.js', '.css'])
  46. let extracted = 0
  47. for (const file of files) {
  48. const isCss = file.endsWith('.css')
  49. let code = fs.readFileSync(file, 'utf8')
  50. let changed = false
  51. // 形态一:new URL("data:...;base64,xxx", import.meta.url) —— 只替换内部字面量为相对路径
  52. code = code.replace(
  53. /new URL\((['"])(data:image\/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=]+))\1, ?import\.meta\.url\)/g,
  54. (m, q, uri, sub, payload) => {
  55. if (uri.length < EXTRACT_THRESHOLD) return m
  56. const info = writeAsset(imgDir, outDir, sub, payload, file)
  57. extracted++
  58. changed = true
  59. return `new URL(${q}${info}${q}, import.meta.url)`
  60. }
  61. )
  62. // 形态二:普通字符串常量(lib 模式 import 内联的产物)—— 整体替换为 new URL 表达式
  63. code = code.replace(
  64. /(['"])(data:image\/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=]+))\1/g,
  65. (m, q, uri, sub, payload) => {
  66. if (uri.length < EXTRACT_THRESHOLD) return m
  67. const info = writeAsset(imgDir, outDir, sub, payload, file)
  68. extracted++
  69. changed = true
  70. if (isCss) return `url(${info})`
  71. return `new URL(${q}${info}${q}, import.meta.url).href`
  72. }
  73. )
  74. if (changed) fs.writeFileSync(file, code)
  75. }
  76. if (extracted) console.log(`[sapit-sso-assets] 已抽取 ${extracted} 个大内联资产到 img/`)
  77. }
  78. function writeAsset (imgDir, outDir, sub, payload, refFile) {
  79. fs.mkdirSync(imgDir, { recursive: true })
  80. const buf = Buffer.from(payload, 'base64')
  81. const hash = crypto.createHash('md5').update(buf).digest('hex').slice(0, 10)
  82. const ext = sub === 'jpeg' ? 'jpg' : sub
  83. const name = `inline-${hash}.${ext}`
  84. fs.writeFileSync(path.join(imgDir, name), buf)
  85. return path.relative(path.dirname(refFile), path.join(imgDir, name)).split(path.sep).join('/')
  86. }
  87. export default function ssoPlugin (options = {}) {
  88. const ssoDir = options.dir || defaultDir
  89. let root = process.cwd()
  90. let outDir = 'dist'
  91. let base = '/'
  92. let isLibBuild = false
  93. return {
  94. name: 'sapit-sso-assets',
  95. // 业务项目 dev 不预打包基座库:预打包会把资产统一内联成 data URI,
  96. // 大图超浏览器 URL 上限必挂;排除后直读原始模块(资产为真实文件引用)
  97. config () {
  98. return { optimizeDeps: { exclude: ['sapit-ui-plus'] } }
  99. },
  100. configResolved (config) {
  101. root = config.root || process.cwd()
  102. base = config.base || '/'
  103. outDir = (config.build && config.build.outDir) || 'dist'
  104. // 基座 lib 模式构建(打包组件库)不注入静态页
  105. isLibBuild = !!(config.build && config.build.lib)
  106. },
  107. // dev 防护:lib 产物里剩余的 `new URL("data:...", import.meta.url)`(如 utils.getImg
  108. // 动态调用产生的)会被 vite 的 import.meta.url 资产插件当相对路径解析,URL 规范化
  109. // 会吞掉 data URI 内容里的 "//"(xmlns、base64 全被破坏)。把字符串字面量拆成
  110. // 拼接表达式,让该插件的正则匹配不到;运行时求值结果不变。
  111. enforce: 'pre',
  112. transform (code) {
  113. if (code.indexOf('new URL("data:') === -1 && code.indexOf("new URL('data:") === -1) {
  114. return null
  115. }
  116. const RE = /new URL\((['"])data:[\s\S]*?\1, ?import\.meta\.url\)/g
  117. if (!RE.test(code)) return null
  118. return {
  119. code: code.replace(RE, (m) => m.replace(/, ?import\.meta\.url\)$/, ' + "", import.meta.url)')),
  120. map: null
  121. }
  122. },
  123. configureServer (server) {
  124. // post hook:在 vite 内部中间件之后执行,public/ 同名文件优先生效
  125. server.middlewares.use((req, res, next) => {
  126. let url = (req.url || '').split('?')[0]
  127. try { url = decodeURIComponent(url) } catch (e) { /* 保持原值 */ }
  128. if (base && base !== '/' && url.indexOf(base) === 0) {
  129. url = '/' + url.slice(base.length)
  130. }
  131. const contentType = FILES[url.replace(/^\//, '')]
  132. if (!contentType) return next()
  133. const full = path.join(ssoDir, url)
  134. if (!fs.existsSync(full)) return next()
  135. res.setHeader('Content-Type', contentType)
  136. res.end(fs.readFileSync(full))
  137. })
  138. },
  139. closeBundle () {
  140. const target = path.isAbsolute(outDir) ? outDir : path.join(root, outDir)
  141. if (isLibBuild) {
  142. // lib 模式 vite 强制内联所有资产(shouldInline 首行 config.build.lib 直接 return true,
  143. // assetsInlineLimit/?url 均无效),大图 data URI 超浏览器 URL 上限无法渲染,
  144. // 构建后统一抽出为真实文件
  145. extractLargeInlineAssets(target)
  146. return
  147. }
  148. for (const rel of Object.keys(FILES)) {
  149. const src = path.join(ssoDir, rel)
  150. const dest = path.join(target, rel)
  151. if (!fs.existsSync(src)) continue
  152. fs.mkdirSync(path.dirname(dest), { recursive: true })
  153. fs.copyFileSync(src, dest)
  154. }
  155. console.log(`[sapit-sso-assets] sso.html 与 js 脚本已注入 ${target}`)
  156. }
  157. }
  158. }