-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bin.js
executable file
·322 lines (276 loc) · 8.55 KB
/
bin.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env node
/* eslint-disable dot-notation */
import { parseArgs } from 'node:util'
import assert from 'node:assert'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
import readline from 'node:readline'
import { minimatch } from 'minimatch'
import { NeocitiesAPIClient } from './index.js'
import { stackWithCauses } from 'pony-cause'
import { format } from '@lukeed/ms'
import createApplicationConfig from 'application-config'
import { printHelpText } from 'argsclopts'
import { pkg } from './pkg.cjs'
// @ts-ignore
import passwordPrompt from 'password-prompt'
/**
* @typedef {import('argsclopts').ArgscloptsParseArgsOptionsConfig} ArgscloptsParseArgsOptionsConfig
*/
/** @type {ArgscloptsParseArgsOptionsConfig} */
const options = {
help: {
type: 'boolean',
short: 'h',
help: 'print help text'
},
src: {
type: 'string',
short: 's',
default: 'public',
help: 'The directory to deploy to neocities'
},
cleanup: {
type: 'boolean',
short: 'c',
default: false,
help: 'Destructively clean up orphaned files on neocities'
},
protect: {
type: 'string',
short: 'p',
help: 'String to minimatch files which will never be cleaned up'
},
status: {
type: 'boolean',
help: 'Print auth status of current working directory'
},
'print-key': {
type: 'boolean',
help: 'Print api-key status of current working directory'
},
'clear-key': {
type: 'boolean',
help: 'Remove the currently associated API key'
},
'force-auth': {
type: 'boolean',
help: 'Force re-authorization of current working directory'
}
}
const cfg = createApplicationConfig(pkg.name)
const args = parseArgs({ options })
const isCI = process.env['CI']
if (args.values['version']) {
console.log(pkg.version)
process.exit(0)
}
if (args.values['help']) {
await printHelpText({
options,
name: pkg.name,
version: pkg.version,
exampleFn: ({ name }) => ' ' + `Example: ${name} --src public\n`
})
process.exit(0)
}
if (args.values['status']) {
try {
const siteName = await getSiteName()
if (!siteName) {
console.log('No site configuration found')
process.exit(0)
}
console.log(`Site name: ${siteName}`)
const apiKey = await getAPIKey(siteName)
if (apiKey) {
console.log('Auth status: API key Found')
} else {
console.log('Auth status: No API key found')
}
process.exit(0)
} catch (err) {
console.error(new Error('Error reading the status of the current working directory'), {
cause: err
})
process.exit(1)
}
}
if (args.values['print-key']) {
try {
const siteName = await getSiteName()
if (!siteName) {
console.error('No site is configured for this directory')
process.exit(0)
}
const apiKey = await getAPIKey(siteName)
console.log('API Key:')
console.log(apiKey)
process.exit(0)
} catch (err) {
console.error(new Error('Error while printing the key'), {
cause: err
})
process.exit(1)
}
}
if (args.values['clear-key']) {
try {
const siteName = await getSiteName()
if (!siteName) {
console.error('No site is configured for this directory')
process.exit(0)
}
const apiKey = await getAPIKey(siteName)
if (!apiKey) {
console.log('No api key found to clear')
process.exit(0)
}
// Save the API key in the config store
const configData = /** @type {*} */ (await cfg.read())
delete configData[siteName]
await cfg.write(configData)
console.log(`API Key cleared for ${siteName}`)
process.exit(0)
} catch (err) {
console.error(new Error('Error while clearing the key'), {
cause: err
})
process.exit(1)
}
}
const src = args.values['src']
const cleanup = Boolean(args.values['cleanup'])
const protectedFiles = String(args.values['protect'])
const forceAuth = Boolean(args.values['force-auth'])
async function main () {
const cwd = process.cwd()
let siteName = await getSiteName(cwd)
let apiKey
// Check if siteName is in the config
if (siteName) {
console.log(`Found siteName in config: ${siteName}`)
} else {
// Config file not found or siteName is missing
console.log('deploy-to-neocities.json not found or siteName is missing.')
if (isCI) {
console.log('Running in CI, skipping prompts')
process.exit(1)
}
console.log('Please enter siteName:')
// Setup readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
// Ask user for siteName
siteName = await new Promise((resolve) => {
rl.question('Enter siteName: ', (input) => {
rl.close()
resolve(input)
})
})
if (!siteName) {
console.log('You must provide a valid neocities site name!')
process.exit(1)
}
// Save the siteName into deploy-to-neocities.json
await fs.writeFile(join(cwd, 'deploy-to-neocities.json'), JSON.stringify({ siteName }), 'utf8')
console.log(`siteName saved: ${siteName}`)
}
// Check if the API key is in the config store
apiKey = await getAPIKey(siteName)
if (apiKey && !forceAuth) {
console.log(`API Key found for ${siteName}`)
} else {
console.log(`API Key not found for ${siteName}. Please enter your Neocities password:`)
// Ask user for Neocities password
// Ask user for password
if (isCI) {
console.log('Running in CI, skipping prompts')
process.exit(1)
}
const password = await passwordPrompt('Enter Neocities password: ')
if (!password) {
console.log('You must provide a valid password')
process.exit(1)
}
/// Use the async-neocities package to get the API keys
const newApiKey = await NeocitiesAPIClient.getKey(siteName, password)
if (!newApiKey) {
console.log('The API did not return an API key for some reason.')
process.exit(1)
}
apiKey = newApiKey
// Save the API key in the config store
const configData = /** @type {*} */ (await cfg.read())
configData[siteName] = apiKey
await cfg.write(configData)
console.log(`API Key saved for ${siteName}`)
}
assert(apiKey, 'An API key is required to proceed')
assert(typeof src === 'string', 'a string src is required')
const distDir = join(cwd, src)
const stat = await fs.stat(distDir)
assert(stat.isDirectory(), 'dist_dir must be a directory that exists')
const client = new NeocitiesAPIClient(apiKey)
const deployOpts = {
cleanup,
statsCb: NeocitiesAPIClient.statsHandler(),
protectedFileFilter: minimatch.filter(protectedFiles)
}
const stats = await client.deploy(distDir, deployOpts)
console.log(`Deployed to Neocities in ${format(stats.time)}:`)
console.log(` Uploaded ${stats.filesToUpload.length} files`)
console.log(` ${cleanup ? 'Deleted' : 'Orphaned'} ${stats.filesToDelete.length} files`)
console.log(` Skipped ${stats.filesSkipped.length} files`)
console.log(` ${stats.protectedFiles.length} protected files:`)
if (stats.protectedFiles.length) {
console.log(stats.protectedFiles)
}
}
// Run the main function with top-level await
await main().catch(err => {
console.error(stackWithCauses(err))
if (err.stats) {
console.log('Files to upload: ')
console.dir(err.stats.filesToUpload, { colors: true, depth: 999 })
if (cleanup) {
console.log('Files to delete: ')
console.dir(err.stats.filesToDelete, { colors: true, depth: 999 })
}
}
process.exit(1)
})
/**
* Get the siteName from deploy-to-neocities.json in cwd, or from ASYNC_NEOCITIES_SITE_NAME env var
* @param {string} cwd
* @return {Promise<string|undefined>}
*/
async function getSiteName (cwd = process.cwd()) {
let siteName = process.env['ASYNC_NEOCITIES_SITE_NAME']
if (siteName) return siteName
try {
const configFile = await fs.readFile(join(cwd, 'deploy-to-neocities.json'), 'utf8')
const config = JSON.parse(configFile)
siteName = config?.siteName
} catch (err) {
// swallow errors
}
return siteName
}
/**
* Get an API key from the ENV or config given a provided siteName
* @param {string} siteName
* @return {Promise<string|undefined>}
*/
async function getAPIKey (siteName) {
const envKey = process.env['ASYNC_NEOCITIES_API_KEY'] || process.env['NEOCITIES_API_TOKEN']
if (envKey) return envKey
if (!siteName) throw new Error('A siteName is required to look up an API key if no ENV key is provided')
// Receive the data as unknown
const rawData = await cfg.read()
/** @type {{ [siteName: string]: string }} */
const configData = /** @type {*} */ (rawData)
return configData?.[siteName]
}