@sparknest/ui-build-vue 0.0.0-stage → 1.1.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.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { resolve } from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { buildLibrary } from '../src/index.mjs'
6
+
7
+ const command = process.argv[2]
8
+ if (command !== 'compile') {
9
+ console.error('Usage: ui-build compile [config]')
10
+ process.exit(1)
11
+ }
12
+
13
+ const configPath = resolve(process.cwd(), process.argv[3] ?? 'ui-build.config.mjs')
14
+ const config = (await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`)).default
15
+ await buildLibrary(config)
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@sparknest/ui-build-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.1",
4
+ "description": "Shared Vue component-library build core for Cedar and Maple",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.mjs",
9
+ "./browser-targets": {
10
+ "types": "./src/browser-targets.d.mts",
11
+ "import": "./src/browser-targets.mjs"
12
+ }
13
+ },
14
+ "bin": {
15
+ "ui-build": "./bin/ui-build.mjs"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "@vitejs/plugin-vue": "^5.2.4",
23
+ "@vitejs/plugin-vue-jsx": "^3.1.0",
24
+ "less": "^4.2.0",
25
+ "vite": "^5.4.21"
26
+ },
27
+ "peerDependencies": {
28
+ "typescript": ">=5",
29
+ "vue": ">=3.2",
30
+ "vue-tsc": ">=2"
31
+ },
32
+ "engines": {
33
+ "node": ">=20"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org/"
38
+ }
6
39
  }
@@ -0,0 +1 @@
1
+ export declare const browserTargets: readonly string[]
@@ -0,0 +1,3 @@
1
+ // Compilation floor, not a claim that these browser versions passed acceptance.
2
+ // Firefox 121 is the oldest Firefox in this contract with native :has().
3
+ export const browserTargets = Object.freeze(['chrome111', 'edge111', 'firefox121', 'safari16.4'])
@@ -0,0 +1,7 @@
1
+ // Module consumers choose development/production diagnostics; a standalone UMD
2
+ // build has no bundler (or Node process global) and is always production.
3
+ export function libraryDefines(format) {
4
+ return {
5
+ 'process.env.NODE_ENV': format === 'umd' ? JSON.stringify('production') : 'process.env.NODE_ENV',
6
+ }
7
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,418 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createRequire } from 'node:module'
3
+ import { existsSync } from 'node:fs'
4
+ import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
5
+ import { basename, dirname, relative, resolve } from 'node:path'
6
+ import vue from '@vitejs/plugin-vue'
7
+ import vueJsx from '@vitejs/plugin-vue-jsx'
8
+ import less from 'less'
9
+ import { build } from 'vite'
10
+ import { collectModuleEntries } from './module-entries.mjs'
11
+ import { libraryDefines } from './environment.mjs'
12
+ import { browserTargets } from './browser-targets.mjs'
13
+ export { browserTargets } from './browser-targets.mjs'
14
+
15
+ export function defineConfig(config) {
16
+ return config
17
+ }
18
+
19
+ async function walk(root) {
20
+ const entries = await readdir(root, { withFileTypes: true })
21
+ return (await Promise.all(entries.map(async (entry) => {
22
+ const path = resolve(root, entry.name)
23
+ return entry.isDirectory() ? walk(path) : [path]
24
+ }))).flat()
25
+ }
26
+
27
+ function run(binary, args, cwd) {
28
+ return new Promise((resolvePromise, reject) => {
29
+ const child = spawn(binary, args, { cwd, stdio: 'inherit' })
30
+ child.on('error', reject)
31
+ child.on('exit', (code) => code === 0
32
+ ? resolvePromise()
33
+ : reject(new Error(`${binary} exited with code ${code}`)))
34
+ })
35
+ }
36
+
37
+ function ignoreVueStylePlugin() {
38
+ return {
39
+ name: 'loca-ignore-vue-style',
40
+ transform(_code, id) {
41
+ if (id.includes('type=style')) {
42
+ return 'export default {}'
43
+ }
44
+ },
45
+ }
46
+ }
47
+
48
+ function styleImportPlugin() {
49
+ return {
50
+ name: 'loca-style-import',
51
+ transform(code, id) {
52
+ if (!/\.(?:[cm]?[jt]sx?|vue)$/.test(id)) return
53
+ return code.replace(/((?:import|from)\s*['"][^'"]+)\.less(['"])/g, '$1.css$2')
54
+ },
55
+ }
56
+ }
57
+
58
+ function externalMatcher(externals) {
59
+ return (id) => {
60
+ if (/\.(?:css|less|scss|sass)$/.test(id)) return true
61
+ return externals.some((name) => id === name || id.startsWith(`${name}/`))
62
+ }
63
+ }
64
+
65
+ function isSkippedSource(path) {
66
+ return /(?:^|\/)(?:example|__tests__|docs)(?:\/|$)/.test(path.replaceAll('\\', '/'))
67
+ }
68
+
69
+ async function renderLessFile(path) {
70
+ const source = await readFile(path, 'utf8')
71
+ const { css } = await less.render(source, { filename: path, javascriptEnabled: true })
72
+ return css
73
+ }
74
+
75
+ function extractVueStyleBlocks(source) {
76
+ const blocks = []
77
+ const re = /<style\b([^>]*)>([\s\S]*?)<\/style>/g
78
+ for (const match of source.matchAll(re)) {
79
+ blocks.push({ attrs: match[1] ?? '', content: match[2] ?? '' })
80
+ }
81
+ return blocks
82
+ }
83
+
84
+ async function compileVueSfcStyles({ root, sourceDir, outputs, cssVariables }) {
85
+ const sourceRoot = resolve(root, sourceDir)
86
+ const sourceFiles = (await walk(sourceRoot)).filter((path) => path.endsWith('.vue') && !isSkippedSource(relative(sourceRoot, path)))
87
+
88
+ for (const sourcePath of sourceFiles) {
89
+ const source = await readFile(sourcePath, 'utf8')
90
+ const blocks = extractVueStyleBlocks(source)
91
+ const rel = relative(sourceRoot, sourcePath).replaceAll('\\', '/')
92
+ const name = basename(sourcePath, '.vue')
93
+ const dir = dirname(rel)
94
+
95
+ for (const [index, block] of blocks.entries()) {
96
+ const lang = /\blang\s*=\s*['"]([^'"]+)['"]/.exec(block.attrs)?.[1] ?? 'css'
97
+ const fileName = index === 0 ? `${name}.css` : `${name}-${index}.css`
98
+ const target = dir === '.' ? fileName : `${dir}/${fileName}`
99
+ let css = block.content
100
+ if (lang === 'less') {
101
+ const rendered = await less.render(block.content, {
102
+ filename: sourcePath,
103
+ javascriptEnabled: true,
104
+ })
105
+ css = rendered.css
106
+ }
107
+ await Promise.all(outputs.map(async (output) => {
108
+ await mkdir(dirname(resolve(root, output, target)), { recursive: true })
109
+ await writeFile(resolve(root, output, target), css)
110
+ }))
111
+ }
112
+ }
113
+ }
114
+
115
+ async function rewriteComponentStyleEntries({ root, cssVariables }) {
116
+ const skip = new Set(['styles', 'style'])
117
+ const esRoot = resolve(root, 'es')
118
+ if (!existsSync(esRoot)) {
119
+ return
120
+ }
121
+ const dirs = (await readdir(esRoot, { withFileTypes: true }))
122
+ .filter((entry) => entry.isDirectory() && !skip.has(entry.name))
123
+
124
+ await Promise.all(dirs.map(async (entry) => {
125
+ const dirRoot = resolve(esRoot, entry.name)
126
+ const cssFiles = (await walk(dirRoot)).filter((path) => {
127
+ const rel = relative(dirRoot, path).replaceAll('\\', '/')
128
+ return path.endsWith('.css') && !rel.startsWith('style/')
129
+ })
130
+ if (!cssFiles.length) {
131
+ return
132
+ }
133
+ const specs = cssFiles.map((path) => `../${relative(dirRoot, path).replaceAll('\\', '/')}`)
134
+ const lines = specs.map((spec) => `import '${spec}'`)
135
+ if (cssVariables) {
136
+ lines.unshift(`import '../../${cssVariables.replace(/\.less$/, '.css')}'`)
137
+ }
138
+ const esCode = `${lines.join('\n')}\n`
139
+ const cjsCode = esCode.replace(/^import '([^']+)'$/gm, "require('$1')")
140
+ await Promise.all([
141
+ mkdir(resolve(root, 'es', entry.name, 'style'), { recursive: true }),
142
+ mkdir(resolve(root, 'lib', entry.name, 'style'), { recursive: true }),
143
+ ])
144
+ await writeFile(resolve(root, 'es', entry.name, 'style', 'index.mjs'), esCode)
145
+ await writeFile(resolve(root, 'lib', entry.name, 'style', 'index.js'), cjsCode)
146
+ }))
147
+ }
148
+
149
+ /**
150
+ * Aggregate foundation + every component style/index.less into one CSS string (no physical index.less).
151
+ */
152
+ async function renderAggregatedLibraryCss(sourceRoot) {
153
+ const foundation = 'style/index.less'
154
+ const foundationPath = resolve(sourceRoot, foundation)
155
+ const sourceFiles = await walk(sourceRoot)
156
+ const styleLess = sourceFiles
157
+ .map((path) => relative(sourceRoot, path).replaceAll('\\', '/'))
158
+ .filter((rel) => /(?:^|\/)style\/index\.less$/.test(rel) && rel !== foundation)
159
+ .sort()
160
+
161
+ if (!existsSync(foundationPath) && !styleLess.length) {
162
+ return null
163
+ }
164
+
165
+ const lines = []
166
+ const seen = new Set()
167
+ const collect = async (path) => {
168
+ if (seen.has(path) || !existsSync(path)) return
169
+ seen.add(path)
170
+ if (path.endsWith('.css')) {
171
+ lines.push(`@import (inline) ${JSON.stringify(path)};`)
172
+ return
173
+ }
174
+ if (path.endsWith('.less')) {
175
+ lines.push(`@import "./${relative(sourceRoot, path).replaceAll('\\', '/')}";`)
176
+ return
177
+ }
178
+ const source = await readFile(path, 'utf8')
179
+ for (const match of source.matchAll(/import\s+['"]([^'"]+)['"]/g)) {
180
+ if (!match[1].startsWith('.') && !match[1].endsWith('.css')) continue
181
+ const target = match[1].startsWith('.')
182
+ ? resolve(dirname(path), match[1])
183
+ : createRequire(path).resolve(match[1])
184
+ await collect(/\.(?:less|css|ts)$/.test(target) ? target : resolve(target, 'index.ts'))
185
+ }
186
+ }
187
+ if (existsSync(foundationPath)) {
188
+ await collect(foundationPath)
189
+ }
190
+ // Match on-demand dependency order in the full-library entry as well.
191
+ for (const entry of sourceFiles.filter(path => /\/style\/index\.ts$/.test(path.replaceAll('\\', '/'))).sort()) {
192
+ await collect(entry)
193
+ }
194
+ for (const rel of styleLess) {
195
+ await collect(resolve(sourceRoot, rel))
196
+ }
197
+
198
+ const { css } = await less.render(lines.join('\n'), {
199
+ // Anchor relative @imports at sourceRoot without writing a real index.less.
200
+ filename: resolve(sourceRoot, 'index.less'),
201
+ javascriptEnabled: true,
202
+ })
203
+ return css
204
+ }
205
+
206
+ async function compileStyles(config) {
207
+ const { root, sourceDir, outputs, bundleName, vueSfcStyles, cssVariables } = config
208
+ const sourceRoot = resolve(root, sourceDir)
209
+ const sourceFiles = await walk(sourceRoot)
210
+ const files = new Set()
211
+ // Foundation only (normalize / tokens / utilities). Not the full library CSS.
212
+ const foundationStyle = resolve(sourceRoot, 'style/index.less')
213
+ // Optional hand-written full entry; when absent, styles are auto-aggregated.
214
+ const fullCssEntry = resolve(sourceRoot, config.fullCssEntry ?? 'index.less')
215
+ if (existsSync(foundationStyle)) {
216
+ files.add(foundationStyle)
217
+ }
218
+ if (cssVariables) {
219
+ const cssVariablesPath = resolve(sourceRoot, cssVariables)
220
+ if (existsSync(cssVariablesPath)) {
221
+ files.add(cssVariablesPath)
222
+ }
223
+ }
224
+ const styleEntries = sourceFiles.filter((path) => /\/style\/index\.ts$/.test(path.replaceAll('\\', '/')))
225
+
226
+ for (const sourcePath of sourceFiles.filter((path) => /\.(?:[cm]?[jt]sx?|vue)$/.test(path) && !isSkippedSource(relative(sourceRoot, path)))) {
227
+ const source = await readFile(sourcePath, 'utf8')
228
+ for (const match of source.matchAll(/(?:import|from)\s*['"]([^'"]+\.less)['"]/g)) {
229
+ files.add(resolve(dirname(sourcePath), match[1]))
230
+ }
231
+ }
232
+
233
+ await Promise.all([...files].map(async (path) => {
234
+ if (!existsSync(path)) {
235
+ return
236
+ }
237
+ const css = await renderLessFile(path)
238
+ const target = relative(sourceRoot, path).replace(/\.less$/, '.css')
239
+ await Promise.all(outputs.map(async (output) => {
240
+ await mkdir(dirname(resolve(root, output, target)), { recursive: true })
241
+ await writeFile(resolve(root, output, target), css)
242
+ }))
243
+ }))
244
+
245
+ await Promise.all(styleEntries.map(async (entry) => {
246
+ const styleDir = dirname(entry)
247
+ const targetDir = relative(sourceRoot, styleDir)
248
+ // Keep the source side-effect graph: shared CSS must remain separate modules.
249
+ const source = await readFile(entry, 'utf8')
250
+ const imports = [...new Set([...source.matchAll(/import\s+['"]([^'"]+)['"]/g)]
251
+ .map((match) => match[1].replace(/\.less$/, '.css')))]
252
+ const resolveImport = (specifier, extension) => {
253
+ if (specifier.startsWith('.') && existsSync(resolve(styleDir, specifier, 'index.ts'))) {
254
+ return `${specifier}/index.${extension}`
255
+ }
256
+ return specifier.replace(/\.ts$/, `.${extension}`)
257
+ }
258
+ const esCode = imports.length ? imports.map((s) => `import '${resolveImport(s, 'mjs')}'\n`).join('') : 'export {}\n'
259
+ const cjsCode = imports.length ? imports.map((s) => `require('${resolveImport(s, 'js')}')\n`).join('') : "'use strict'\n"
260
+ await Promise.all([
261
+ mkdir(resolve(root, 'es', targetDir), { recursive: true }),
262
+ mkdir(resolve(root, 'lib', targetDir), { recursive: true }),
263
+ ])
264
+ await Promise.all([
265
+ writeFile(resolve(root, 'es', targetDir, 'index.mjs'), esCode),
266
+ writeFile(resolve(root, 'lib', targetDir, 'index.js'), cjsCode),
267
+ ])
268
+ }))
269
+
270
+ if (vueSfcStyles) {
271
+ await compileVueSfcStyles(config)
272
+ await rewriteComponentStyleEntries(config)
273
+ }
274
+
275
+ let bundleCss = null
276
+ if (existsSync(fullCssEntry)) {
277
+ bundleCss = await renderLessFile(fullCssEntry)
278
+ } else {
279
+ bundleCss = await renderAggregatedLibraryCss(sourceRoot)
280
+ }
281
+ if (bundleCss == null) {
282
+ const cssFiles = (await walk(resolve(root, 'es'))).filter((path) => path.endsWith('.css') && !path.endsWith(`${bundleName}.css`))
283
+ bundleCss = (await Promise.all(cssFiles.map((path) => readFile(path, 'utf8')))).join('\n')
284
+ }
285
+
286
+ await Promise.all(outputs.map(async (output) => {
287
+ await mkdir(resolve(root, output), { recursive: true })
288
+ await writeFile(resolve(root, output, `${bundleName}.css`), bundleCss)
289
+ }))
290
+ }
291
+
292
+ function vitePlugins(config) {
293
+ return [vue(), vueJsx(), styleImportPlugin(), ...(config.vueSfcStyles ? [ignoreVueStylePlugin()] : [])]
294
+ }
295
+
296
+ async function buildModules(config, format, outDir, extension) {
297
+ const root = resolve(config.root)
298
+ await build({
299
+ root,
300
+ configFile: false,
301
+ define: libraryDefines(format),
302
+ logLevel: 'warn',
303
+ plugins: vitePlugins(config),
304
+ build: {
305
+ target: [...browserTargets],
306
+ cssTarget: [...browserTargets],
307
+ copyPublicDir: false,
308
+ emptyOutDir: false,
309
+ minify: false,
310
+ outDir,
311
+ rollupOptions: {
312
+ input: await collectModuleEntries(root, config.sourceDir, config.entry),
313
+ external: externalMatcher(config.external),
314
+ preserveEntrySignatures: 'strict',
315
+ output: {
316
+ format,
317
+ preserveModules: true,
318
+ preserveModulesRoot: resolve(root, config.sourceDir),
319
+ entryFileNames: `[name].${extension}`,
320
+ exports: 'named',
321
+ },
322
+ },
323
+ },
324
+ })
325
+ }
326
+
327
+ async function buildBundle(config, format, outDir, fileName) {
328
+ const root = resolve(config.root)
329
+ await build({
330
+ root,
331
+ configFile: false,
332
+ define: libraryDefines(format),
333
+ logLevel: 'warn',
334
+ plugins: vitePlugins(config),
335
+ build: {
336
+ target: [...browserTargets],
337
+ cssTarget: [...browserTargets],
338
+ copyPublicDir: false,
339
+ emptyOutDir: false,
340
+ minify: format === 'cjs' ? false : 'esbuild',
341
+ outDir,
342
+ lib: {
343
+ entry: resolve(root, config.entry),
344
+ name: config.globalName,
345
+ formats: [format],
346
+ fileName: () => fileName,
347
+ },
348
+ rollupOptions: {
349
+ external: externalMatcher(format === 'umd' ? config.umdExternal : config.external),
350
+ output: { exports: 'named', globals: config.globals },
351
+ },
352
+ },
353
+ })
354
+ }
355
+
356
+ async function assertOutputs(config) {
357
+ const root = resolve(config.root)
358
+ const required = [
359
+ 'es/index.mjs',
360
+ `es/${config.bundleName}.esm.js`,
361
+ `es/${config.bundleName}.css`,
362
+ `lib/${config.bundleName}.cjs.js`,
363
+ `umd/${config.bundleName}.js`,
364
+ ]
365
+ if (config.emitTypes !== false) {
366
+ required.push('types/index.d.ts')
367
+ }
368
+ const missing = []
369
+ for (const path of required) {
370
+ try { await readFile(resolve(root, path)) } catch { missing.push(path) }
371
+ }
372
+ if (missing.length) throw new Error(`Missing build outputs:\n${missing.join('\n')}`)
373
+ }
374
+
375
+ export async function buildLibrary(userConfig) {
376
+ // A custom NODE_ENV makes Vite compile development-only Vue branches into a
377
+ // release. Reject it before cleaning any existing output, rather than silently
378
+ // mutating the environment of another build in the same process.
379
+ if (process.env.NODE_ENV && process.env.NODE_ENV !== 'production') {
380
+ throw new Error('buildLibrary requires NODE_ENV=production (or unset); custom compile/test modes are not release builds')
381
+ }
382
+ const config = {
383
+ sourceDir: 'src',
384
+ entry: 'src/index.ts',
385
+ external: ['vue'],
386
+ globals: { vue: 'Vue' },
387
+ umdExternal: ['vue'],
388
+ tsconfig: 'tsconfig.build.json',
389
+ emitTypes: true,
390
+ vueSfcStyles: false,
391
+ // Optional. When missing, full `{bundleName}.css` is auto-aggregated from **/style/index.less.
392
+ fullCssEntry: 'index.less',
393
+ ...userConfig,
394
+ }
395
+ config.root = resolve(config.root ?? process.cwd())
396
+
397
+ const cleanDirs = config.emitTypes === false ? ['es', 'lib', 'umd'] : ['es', 'lib', 'umd', 'types']
398
+ for (const dir of cleanDirs) {
399
+ await rm(resolve(config.root, dir), {
400
+ recursive: true,
401
+ force: true,
402
+ maxRetries: 3,
403
+ retryDelay: 100,
404
+ })
405
+ }
406
+
407
+ await buildModules(config, 'es', 'es', 'mjs')
408
+ await buildModules(config, 'cjs', 'lib', 'js')
409
+ await buildBundle(config, 'es', 'es', `${config.bundleName}.esm.js`)
410
+ await buildBundle(config, 'cjs', 'lib', `${config.bundleName}.cjs.js`)
411
+ await buildBundle(config, 'umd', 'umd', `${config.bundleName}.js`)
412
+ await compileStyles({ ...config, outputs: ['es', 'lib', 'umd'] })
413
+ if (config.emitTypes !== false) {
414
+ await run('vue-tsc', ['-p', config.tsconfig], config.root)
415
+ }
416
+
417
+ await assertOutputs(config)
418
+ }
@@ -0,0 +1,22 @@
1
+ import { readdir } from 'node:fs/promises'
2
+ import { relative, resolve } from 'node:path'
3
+
4
+ // A preserved module is not automatically a public entry: Rollup may redirect
5
+ // its re-exports to another module and drop them from the package subpath.
6
+ export async function collectModuleEntries(root, sourceDir, entry) {
7
+ const sourceRoot = resolve(root, sourceDir)
8
+ const entries = { index: resolve(root, entry) }
9
+ const skipped = new Set(['style', 'docs', 'example', 'components', 'node_modules'])
10
+ async function visit(directory) {
11
+ for (const item of await readdir(directory, { withFileTypes: true })) {
12
+ if (item.name.startsWith('_') || item.name.startsWith('.') || skipped.has(item.name)) continue
13
+ const full = resolve(directory, item.name)
14
+ if (item.isDirectory()) await visit(full)
15
+ else if (/^index\.(?:ts|tsx|js|mjs)$/.test(item.name) && full !== entries.index) {
16
+ entries[relative(sourceRoot, full).replaceAll('\\', '/').replace(/\.[^.]+$/, '')] = full
17
+ }
18
+ }
19
+ }
20
+ await visit(sourceRoot)
21
+ return entries
22
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.