-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbin.js
More file actions
executable file
·259 lines (225 loc) · 8.47 KB
/
Copy pathbin.js
File metadata and controls
executable file
·259 lines (225 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env node
/**
* @import { BuildStepWarnings, DomStackOpts as DomStackOpts } from './lib/builder.js'
* @import { Logger as PinoLogger } from 'pino'
* @import { BsInstance } from '@domstack/sync'
*/
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { basename, resolve, join, relative } from 'node:path'
import readline from 'node:readline'
import process from 'process'
import tree from 'pretty-tree'
import { inspect } from 'util'
import { createServer } from '@domstack/sync'
import { packageDirectory } from 'package-directory'
import { copyFile } from './lib/helpers/copy-file.js'
import { addPackageDependencies } from './lib/helpers/add-package-dependencies.js'
import { DomStack } from './index.js'
import { DomStackAggregateError } from './lib/helpers/domstack-aggregate-error.js'
import { generateTreeData } from './lib/helpers/generate-tree-data.js'
import { askYesNo } from './lib/helpers/cli-prompt.js'
import { createDomStackLogger } from './lib/logger.js'
import { CliUsageError, parseCliArgs } from './lib/cli/args.js'
import { formatCliHelp } from './lib/cli/help.js'
const __dirname = import.meta.dirname
/** @param {string} [pkgPath] */
async function getPkg (pkgPath = resolve(__dirname, './package.json')) {
const source = await readFile(pkgPath, 'utf8')
const pkg = JSON.parse(source.replace(/^\uFEFF/, ''))
return pkg
}
async function run () {
const { command, values: argv, helpCommand } = parseCliArgs(process.argv.slice(2))
if (argv['version']) {
const pkg = await getPkg()
console.log(pkg.version)
process.exit(0)
}
if (argv['help']) {
const pkg = await getPkg()
console.log(await formatCliHelp(helpCommand, pkg.version))
process.exit(0)
}
const cwd = process.cwd()
const src = resolve(join(cwd, String(argv['src'])))
if (command === 'eject') {
const language = argv['language']
const localPkg = await packageDirectory({ cwd: src })
if (!localPkg) {
console.error('Can\'t locate package.json, exiting without making changes')
process.exit(1)
}
const localPkgJson = join(localPkg, 'package.json')
const localPkgJsonContents = await getPkg(localPkgJson)
const targetIsModule = localPkgJsonContents.type === 'module'
const relativeSrc = relative(process.cwd(), src)
const relativePkg = relative(process.cwd(), localPkgJson)
const extension = language === 'ts' ? (targetIsModule ? 'ts' : 'mts') : targetIsModule ? 'js' : 'mjs'
const targetLayoutPath = `layouts/root.layout.${extension}`
const targetGlobalStylePath = 'globals/global.css'
const targetGlobalClientPath = `globals/global.client.${language === 'ts' ? 'ts' : extension}`
const tbPkgContents = await getPkg()
const mineVersion = tbPkgContents?.['dependencies']?.['mine.css']
const fragtmlVersion = tbPkgContents?.['dependencies']?.['fragtml']
const highlightVersion = tbPkgContents?.['dependencies']?.['highlight.js']
if (!mineVersion || !fragtmlVersion || !highlightVersion) {
console.error('Unable to resolve ejected dependency versions. Exiting...')
process.exit(1)
}
console.log(`
domstack eject actions:
- Write ${join(relativeSrc, targetLayoutPath)}
- Write ${join(relativeSrc, targetGlobalStylePath)}
- Write ${join(relativeSrc, targetGlobalClientPath)}
- Add mine.css@${mineVersion} to ${relativePkg}
- Add fragtml@${fragtmlVersion} to ${relativePkg}
- Add highlight.js@${highlightVersion} to ${relativePkg}
`)
if (!argv['yes']) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
let answer
try {
answer = await askYesNo(rl, 'Continue?')
} finally {
rl.close()
}
if (!answer) {
console.log('No action taken. Exiting.')
process.exit(0)
}
}
const defaultLayoutPath = join(__dirname, `lib/defaults/default.root.layout.${language}`)
const defaultGlobalStylePath = join(__dirname, 'lib/defaults/default.style.css')
const defaultGlobalClientPath = join(__dirname, 'lib/defaults/default.client.js')
const layoutSource = await readFile(defaultLayoutPath, 'utf8')
const layout = language === 'ts'
? layoutSource.replace("from '#types'", "from '@domstack/static/types.js'")
: layoutSource
await mkdir(join(src, 'layouts'), { recursive: true })
await Promise.all([
writeFile(join(src, targetLayoutPath), layout),
copyFile(defaultGlobalStylePath, join(src, targetGlobalStylePath)),
copyFile(defaultGlobalClientPath, join(src, targetGlobalClientPath)),
])
await addPackageDependencies(
localPkgJson,
{
'mine.css': mineVersion,
fragtml: fragtmlVersion,
'highlight.js': highlightVersion,
})
console.log('Done ejecting files!')
process.exit(0)
}
const dest = resolve(join(cwd, String(argv['dest'])))
/** @type {DomStackOpts} */
const opts = {}
if (argv['ignore']) opts.ignore = String(argv['ignore']).split(',')
if (argv['noEsbuildMeta']) opts.metafile = false
if (argv['domstackManifest']) opts.domstackManifest = true
if (argv['drafts']) opts.buildDrafts = true
if (argv['copy']) {
const copyPaths = Array.isArray(argv['copy']) ? argv['copy'] : [argv['copy']]
// @ts-expect-error
opts.copy = copyPaths.map(p => resolve(cwd, p))
}
const logger = createDomStackLogger(argv['verbose'] ? 'debug' : 'info')
opts.logger = logger
const domStack = new DomStack(src, dest, opts)
/** @type {BsInstance | null} */
let buildServer = null
const servePort = argv['port'] ? Number(argv['port']) : undefined
process.once('SIGINT', quit)
process.once('SIGTERM', quit)
async function quit () {
if (domStack.watching) {
await domStack.stopWatching()
logger.info('Watching stopped')
}
if (buildServer) {
await buildServer.exit()
buildServer = null
logger.info('Server stopped')
}
logger.info('Quitting cleanly')
process.exit(0)
}
if (command !== 'watch') {
try {
const results = await domStack.build()
logger.info(tree(generateTreeData(cwd, src, dest, results)))
logWarnings(logger, results?.warnings)
logger.info(`Built ${relative(cwd, src) || '.'} → ${relative(cwd, dest) || '.'}`)
logger.info('Build Success!')
if (command === 'serve') {
buildServer = await createServer({
server: dest,
files: basename(dest),
logger: logger.child({ component: 'sync', logPrefix: '[domstack-sync]' }),
...(servePort ? { port: servePort } : {}),
snippet: false,
})
logger.info(`Serving ${relative(cwd, dest)} without watching. Press Ctrl-C to stop.`)
}
} catch (err) {
if (!(err instanceof Error || err instanceof AggregateError)) throw new Error('Non-error thrown', { cause: err })
if (err instanceof DomStackAggregateError) {
if (err?.results?.siteData?.pages) {
logger.error(tree(generateTreeData(cwd, src, dest, err.results)))
}
}
if ('results' in err) delete err.results
logger.error(formatDiagnostic(err, Boolean(process.stdout.isTTY)))
logger.error('Build Failed!')
process.exit(1)
}
} else {
await domStack.watch({
serve: !argv['no-serve'],
onInitialBuild: (initialResults) => {
logger.info(tree(generateTreeData(cwd, src, dest, initialResults)))
logWarnings(logger, initialResults?.warnings)
},
})
}
}
/**
* @param {PinoLogger} logger
* @param {BuildStepWarnings | undefined} warnings
*/
function logWarnings (logger, warnings) {
if ((warnings?.length ?? 0) === 0) return
logger.warn('There were build warnings:')
for (const warning of warnings ?? []) {
if ('message' in warning) {
logger.warn(` ${warning.message}`)
} else {
logger.warn(formatDiagnostic(warning, Boolean(process.stdout.isTTY)))
}
}
}
/**
* Keep nested causes, locations, and every diagnostic visible in CLI output.
* @param {unknown} value
* @param {boolean} colors
*/
function formatDiagnostic (value, colors) {
return inspect(value, {
depth: null,
maxArrayLength: null,
maxStringLength: null,
colors,
})
}
run().catch(err => {
if (err instanceof CliUsageError) {
console.error(`domstack: ${err.message}`)
console.error(`Run "domstack${err.command ? ` ${err.command}` : ''} --help" for usage.`)
process.exit(1)
}
console.error(formatDiagnostic(
new Error('Unhandled domstack error', { cause: err }),
Boolean(process.stderr.isTTY)
))
process.exit(1)
})