dsh-design-studio 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/comp-io.js ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * 组件(#30)接到各条路径上的那层:从哪读文件(设计目录 / 某一版的快照)、预览时怎么带上依赖、正式导出遇错怎么停、体检怎么报。
3
+ * 展开本身在 components.js(纯函数,不碰文件);这里只管文件和拼装。
4
+ */
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { COMP_DIR, usesComponents, expandComponents, catalog, catalogLine } from './components.js'
8
+
9
+ const MAX_READ = 8 * 1024 * 1024 // 和预览注入脚本的上限一样(serve.js MAX_HTML):预览能展开的页,预检也读得到;组件文件自己另有 256 KB 上限
10
+
11
+ /** 设计目录里的相对路径 → 内容;不出目录(含顺着软链接出去)、不是文件、太大、读不了都给 null */
12
+ export function dirReader(root) {
13
+ let real
14
+ try { real = fs.realpathSync(root) } catch { real = path.resolve(root) }
15
+ const read = (rel) => {
16
+ const r = String(rel || '').replace(/\\/g, '/').replace(/^\/+/, '')
17
+ if (!r || r.split('/').some((x) => x === '..' || x === '')) return null
18
+ try {
19
+ const f = fs.realpathSync(path.join(real, r))
20
+ if (!f.startsWith(real + path.sep)) return null
21
+ const st = fs.statSync(f)
22
+ if (!st.isFile() || st.size > MAX_READ) return null
23
+ return fs.readFileSync(f)
24
+ } catch { return null }
25
+ }
26
+ read.hasCompDir = () => hasCompDir(real)
27
+ return read
28
+ }
29
+
30
+ /**
31
+ * 设计目录的 components/ 里有没有组件文件(.html):有才算用上了组件(见 adopts)。
32
+ * 只有个空文件夹、或者放的是老项目自己的 JS 组件(components/rating.js),都不算
33
+ */
34
+ export function hasCompDir(root) {
35
+ return componentFiles(root).length > 0
36
+ }
37
+
38
+ /** 页面里写到的组件名(去重) */
39
+ const compNames = (html) => new Set([...String(html).matchAll(/<c-([a-z][a-z0-9-]*)/gi)].map((m) => m[1].toLowerCase()))
40
+
41
+ const DEFINE_C = /customElements\s*\.\s*define\s*\(\s*(?:\/\*[\s\S]*?\*\/\s*)?['"`]c-/
42
+ /** 页面引的外部脚本:{ local: [设计目录里的相对路径], remote: 有没有外链脚本 } */
43
+ function scriptsOf(html) {
44
+ const local = []
45
+ let remote = false
46
+ for (const m of String(html).replace(/<!--[\s\S]*?-->/g, '').matchAll(/<script\b[^>]*?\bsrc\s*=\s*(["']?)([^"'\s>]+)\1/gi)) {
47
+ const src = m[2].split(/[?#]/)[0]
48
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) { remote = true; continue }
49
+ local.push(src.replace(/^\.?\/+/, ''))
50
+ }
51
+ return { local, remote }
52
+ }
53
+
54
+ /**
55
+ * 这页归不归我们展开(写了 <c-…>、不是页面自己内联注册的之外):
56
+ * - 本地外部脚本里自己 customElements.define('c-…'):老页面自己的自定义元素,不接管
57
+ * - 设计的 components/ 里有组件文件(.html)、或至少一个用到的组件文件在:接管(缺的照样报缺组件)
58
+ * - 都没有:页面引了外部脚本就当它自己注册的(原样不动);一个外部脚本都没有,只能是我们的组件(缺组件照样报,正式导出照样拦)
59
+ */
60
+ export function adopts(html, read) {
61
+ if (!usesComponents(html)) return false
62
+ if (!read) return true
63
+ const sc = scriptsOf(html)
64
+ for (const rel of sc.local.slice(0, 20)) {
65
+ try { const b = read(rel); if (b && DEFINE_C.test(b.toString('utf8'))) return false } catch { /* 读不了:当没注册 */ }
66
+ }
67
+ try { if (read.hasCompDir && read.hasCompDir()) return true } catch { /* 当没有 */ }
68
+ for (const n of compNames(html)) if (read(`${COMP_DIR}/${n}.html`)) return true
69
+ return !sc.local.length && !sc.remote
70
+ }
71
+
72
+ /** 某一版快照里的文件(旧版本的页面、组件、组件带的样式全从同一份快照读,缺了就是缺了,不拿现在的顶) */
73
+ export function versionReader(history, root, n) {
74
+ return (rel) => {
75
+ try {
76
+ const f = history && history.fileOf(root, n, String(rel || '').replace(/\\/g, '/').replace(/^\/+/, ''))
77
+ return f ? fs.readFileSync(f) : null
78
+ } catch { return null }
79
+ }
80
+ }
81
+
82
+ /** 设计目录 components/ 下的组件文件名(只一层) */
83
+ export function componentFiles(root) {
84
+ try {
85
+ return fs.readdirSync(path.join(root, COMP_DIR), { withFileTypes: true })
86
+ .filter((d) => d.isFile() && /\.html$/i.test(d.name) && !d.name.startsWith('.'))
87
+ .map((d) => d.name)
88
+ .sort()
89
+ } catch { return [] }
90
+ }
91
+
92
+ /** 放进 <head> 最前面(没 <head> 放 <html> / doctype 后面);注释里提到的 <head> 不算 */
93
+ function headPut(html, tag) {
94
+ const bare = html.replace(/<!--[\s\S]*?(?:-->|$)/g, (c) => ' '.repeat(c.length))
95
+ const m = /<head\b[^>]*>/i.exec(bare) || /<html\b[^>]*>/i.exec(bare) || /^\s*<!doctype\b[^>]*>/i.exec(bare)
96
+ return m ? html.slice(0, m.index + m[0].length) + tag + html.slice(m.index + m[0].length) : tag + html
97
+ }
98
+
99
+ const attrEsc = (s) => String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
100
+
101
+ /** 这页用到的组件文件:picker 收到「这些文件改了」时靠它知道要不要刷新自己 */
102
+ export const depsMeta = (deps) => `<meta name="dsh-comp-deps" content="${attrEsc(deps.join(','))}">`
103
+
104
+ const EMPTY = Object.freeze({ deps: [], used: [], errors: [], warnings: [] })
105
+
106
+ /**
107
+ * 预览(画布、远程看、旧版本):展开,出错的实例原地红框;带上依赖。没用组件的页面原样返回(逐字节不变)
108
+ * @returns { html, deps, used, errors, warnings, comp: 用没用组件 }
109
+ */
110
+ export function expandPreview(html, read, page = '') {
111
+ if (!adopts(html, read)) return { html, ...EMPTY, comp: false }
112
+ const r = expandComponents(html, { read, page, placeholders: true })
113
+ return { ...r, html: headPut(r.html, depsMeta(r.deps)), comp: true }
114
+ }
115
+
116
+ /** 正式导出 / 公网链接:出错就抛 compErr(message 列出哪几屏、什么错),不出半截的东西 */
117
+ export function expandFormal(html, read, page = '') {
118
+ if (!adopts(html, read)) return { html, ...EMPTY, comp: false }
119
+ const r = expandComponents(html, { read, page, placeholders: false })
120
+ if (r.errors.length) throw compError([{ page, errors: r.errors }])
121
+ return { ...r, comp: true }
122
+ }
123
+
124
+ /** 几屏的错攒成一个 compErr:e.code = 'compErr',e.pages = [{ page, errors }],message 是一句人话 */
125
+ export function compError(list) {
126
+ const bad = list.filter((x) => x.errors && x.errors.length)
127
+ const first = bad[0] && bad[0].errors[0]
128
+ const e = new Error(`${bad.length} 屏的组件有错:${bad.slice(0, 3).map((x) => x.page).join('、')}${bad.length > 3 ? ' 等' : ''}${first ? `(${first.message})` : ''}`)
129
+ e.code = 'compErr'
130
+ e.pages = bad.map((x) => ({ page: x.page, errors: x.errors.slice(0, 5).map((d) => ({ code: d.code, message: d.message, file: d.file, line: d.line, fix: d.fix })) }))
131
+ return e
132
+ }
133
+
134
+ /** 导出前统一预检:这些屏(某一版就从那一版的快照读)里组件有没有错。→ [{ page, errors }](只列有错的) */
135
+ export function precheckScreens(keys, read) {
136
+ const out = []
137
+ for (const key of keys) {
138
+ const buf = read(key)
139
+ if (!buf) continue // 屏没了:导出那边自己会报
140
+ const html = buf.toString('utf8')
141
+ if (!adopts(html, read)) continue
142
+ const r = expandComponents(html, { read, page: key, placeholders: false })
143
+ if (r.errors.length) out.push({ page: key, errors: r.errors })
144
+ }
145
+ return out
146
+ }
147
+
148
+ /** 这页用没用组件(改字、调样式写回前问:用了就交给模型);给了 read 就按 adopts 认(老页面自己注册的 c-* 不算) */
149
+ export function pageUsesComponents(html, read = null) {
150
+ try { return read ? adopts(String(html || ''), read) : usesComponents(String(html || '')) } catch { return false }
151
+ }
152
+
153
+ /**
154
+ * 体检 / preview_page 用:整套设计的组件情况。
155
+ * @returns { items: catalog, line: 一行短目录, pages: [{ page, errors, warnings }](只列有问题的), unused: [组件名], usedBy: Map 名 → [屏] }
156
+ */
157
+ export function designComponents(root, keys, read = dirReader(root), mock = null) {
158
+ const names = componentFiles(root)
159
+ const pages = []
160
+ const usedBy = new Map()
161
+ const rootCls = new Map() // 组件名 → 根元素的第一个 class
162
+ for (const key of keys) {
163
+ const buf = read(key)
164
+ if (!buf) continue
165
+ const html = buf.toString('utf8')
166
+ if (!usesComponents(html)) continue
167
+ if (!adopts(html, read)) {
168
+ // 写了 <c-…> 但设计里没有 components/:当页面自己的自定义元素,没展开(要用组件就建文件)
169
+ pages.push({ page: key, errors: [], warnings: [{ code: 'unadopted', page: key, file: key, line: 0,
170
+ message: `这屏写了 ${[...compNames(html)].slice(0, 3).map((n) => `<c-${n}>`).join('、')},但设计里没有 components/ 文件夹:当成页面自己的自定义元素,没展开`,
171
+ fix: '要用组件就建 components/<名>.html;是页面自己注册的自定义元素就不用管' }] })
172
+ continue
173
+ }
174
+ const r = expandComponents(html, { read, page: key, mock, placeholders: false })
175
+ for (const n of r.used) { if (!usedBy.has(n)) usedBy.set(n, []); usedBy.get(n).push(key) }
176
+ const warnings = [...r.warnings, ...pageCssWarnings(html, r.used, read, rootCls, key)]
177
+ if (r.errors.length || warnings.length) pages.push({ page: key, errors: r.errors, warnings })
178
+ }
179
+ const items = names.length ? catalog(read, names) : []
180
+ const unused = items.map((x) => x.name).filter((n) => !usedBy.has(n))
181
+ return { items, line: catalogLine(items), pages, unused, usedBy }
182
+ }
183
+
184
+ /** 组件文件根元素的第一个 class(去掉注释和 <style> 再找第一个标签) */
185
+ function rootClassOf(buf) {
186
+ const src = String(buf || '').replace(/<!--[\s\S]*?-->/g, '').replace(/<style\b[\s\S]*?<\/style\s*>/gi, '')
187
+ const m = /<[a-z][\w-]*\b([^>]*)>/i.exec(src)
188
+ const c = m && /\bclass\s*=\s*(["'])([^"']*)\1/i.exec(m[1])
189
+ const first = c ? c[2].trim().split(/\s+/)[0] : ''
190
+ return /^[A-Za-z_-][\w-]*$/.test(first) ? first : ''
191
+ }
192
+
193
+ /** 这屏自己的 <style> 里又写了组件根元素的 class(各屏写一份就会走样):提醒删掉、写进组件 */
194
+ function pageCssWarnings(html, used, read, cache, page) {
195
+ const css = [...String(html).matchAll(/<style\b(?![^>]*data-dsh-comp-css)[^>]*>([\s\S]*?)<\/style\s*>/gi)].map((m) => m[1]).join('\n').replace(/\/\*[\s\S]*?\*\//g, '')
196
+ if (!css) return []
197
+ const out = []
198
+ for (const name of used) {
199
+ if (!cache.has(name)) cache.set(name, rootClassOf(read(`components/${name}.html`)))
200
+ const cls = cache.get(name)
201
+ if (!cls) continue
202
+ const re = new RegExp(`(?:^|[}\\s,>+~(])\\.${cls.replace(/[-]/g, '\\-')}(?![\\w-])[^{}]*\\{`)
203
+ if (re.test(css)) {
204
+ out.push({ code: 'page-css', page, file: page, line: 0,
205
+ message: `这屏的 <style> 里又写了组件 ${name} 的 .${cls}`,
206
+ fix: `删掉这屏里的这段,样式写进 components/${name}.html 的 <style>;只改这一屏就给 <c-${name}> 加 class 或 data-variant` })
207
+ }
208
+ }
209
+ return out
210
+ }
211
+
212
+ /** 体检报告里的几行(没组件、没问题给 []) */
213
+ export function formatComponents(dc, max = 12) {
214
+ const at = (d, page) => (d.file && d.file !== page ? `(${d.file}${d.line ? ` 第 ${d.line} 行` : ''})` : d.line ? `(第 ${d.line} 行)` : '')
215
+ const who = (r) => r.pages.size > 1 ? `${r.page} 等 ${r.pages.size} 屏` : r.page
216
+ // 组件文件里的同一条(几屏都用到这个组件)只列一次;选择器没从根 class 开始的,每个组件文件并成一行
217
+ const rows = []
218
+ const seen = new Map()
219
+ for (const kind of ['errors', 'warnings']) {
220
+ for (const p of dc.pages) {
221
+ for (const d of p[kind]) {
222
+ const comp = d.file && d.file !== p.page
223
+ const key = !comp ? null : d.code === 'css-scope' ? `scope|${d.file}` : `${kind}|${d.file}|${d.line}|${d.message}`
224
+ const old = key && seen.get(key)
225
+ if (old) { old.pages.add(p.page); if (d.code === 'css-scope' && !old.ds.some((x) => x.line === d.line && x.message === d.message)) old.ds.push(d); continue }
226
+ const r = { kind, page: p.page, d, ds: [d], pages: new Set([p.page]) }
227
+ rows.push(r)
228
+ if (key) seen.set(key, r)
229
+ }
230
+ }
231
+ }
232
+ const lines = []
233
+ for (const r of rows.slice(0, max)) {
234
+ const { d } = r
235
+ const tag = r.kind === 'errors' ? '✗' : '提醒'
236
+ if (d.code === 'css-scope' && r.ds.length > 1) {
237
+ const sel = (x) => (/「([^」]*)」/.exec(x.message) || [])[1] || ''
238
+ const ln = r.ds.map((x) => x.line).filter(Boolean)
239
+ lines.push(`- ${tag} ${who(r)}:${d.file} 里 ${r.ds.length} 个选择器没有从根元素的 class 开始(如「${r.ds.slice(0, 3).map(sel).join('」「')}」${ln.length ? `,第 ${ln.slice(0, 4).join('、')}${ln.length > 4 ? ' 等' : ''} 行` : ''})${d.fix ? ` → ${d.fix}` : ''}`)
240
+ continue
241
+ }
242
+ lines.push(`- ${tag} ${who(r)}:${d.message}${at(d, r.page)}${d.fix ? ` → ${d.fix}` : ''}`)
243
+ }
244
+ if (rows.length > max) lines.push(`- 还有 ${rows.length - max} 条没列`)
245
+ for (const it of dc.items) if (it.error) lines.push(`- ✗ ${it.file || `components/${it.name}.html`}:${it.error}`)
246
+ if (dc.unused.length) lines.push(`- 提醒 没有哪屏用到的组件:${dc.unused.slice(0, 6).join('、')}${dc.unused.length > 6 ? ' 等' : ''}`)
247
+ return lines
248
+ }