hackmud-script-manager-ng 0.26.5 → 0.26.7

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.
Files changed (70) hide show
  1. package/bin/hsm.d.ts +2 -0
  2. package/bin/hsm.js +493 -0
  3. package/constants.d.ts +2 -0
  4. package/constants.js +3 -0
  5. package/env.d.ts +10 -0
  6. package/generateTypeDeclaration.d.ts +1 -0
  7. package/generateTypeDeclaration.js +70 -0
  8. package/index.d.ts +16 -0
  9. package/index.js +52 -0
  10. package/package.json +3 -22
  11. package/processScript/index.d.ts +34 -0
  12. package/processScript/index.js +362 -0
  13. package/processScript/minify.d.ts +20 -0
  14. package/processScript/minify.js +431 -0
  15. package/processScript/postprocess.d.ts +1 -0
  16. package/processScript/postprocess.js +21 -0
  17. package/processScript/preprocess.d.ts +11 -0
  18. package/processScript/preprocess.js +107 -0
  19. package/processScript/shared.d.ts +5 -0
  20. package/processScript/shared.js +32 -0
  21. package/processScript/transform.d.ts +24 -0
  22. package/processScript/transform.js +803 -0
  23. package/pull.d.ts +7 -0
  24. package/pull.js +11 -0
  25. package/push.d.ts +42 -0
  26. package/push.js +164 -0
  27. package/syncMacros.d.ts +4 -0
  28. package/syncMacros.js +42 -0
  29. package/watch.d.ts +19 -0
  30. package/watch.js +220 -0
  31. package/.envrc +0 -1
  32. package/.github/FUNDING.yml +0 -14
  33. package/.github/workflows/publish.yml +0 -27
  34. package/.github/workflows/test.yml +0 -18
  35. package/.vscode/settings.json +0 -55
  36. package/CONTRIBUTING.md +0 -68
  37. package/eslint.config.js +0 -81
  38. package/game-scripts-tests/array-rest-works.ts +0 -6
  39. package/game-scripts-tests/this_array_in_object.ts +0 -16
  40. package/game-scripts-tests/this_function_array.ts +0 -9
  41. package/game-scripts-tests/this_in_default_argument.ts +0 -35
  42. package/game-scripts-tests/this_in_lambda_in_object.ts +0 -26
  43. package/pnpm-workspace.yaml +0 -2
  44. package/rollup.config.js +0 -69
  45. package/scripts/dev.sh +0 -3
  46. package/scripts/emit-declarations.sh +0 -3
  47. package/scripts/emit-package-json.js +0 -9
  48. package/scripts/lint.sh +0 -5
  49. package/scripts/package.sh +0 -7
  50. package/scripts/update.sh +0 -4
  51. package/scripts/version-dev.js +0 -14
  52. package/src/bin/hsm.ts +0 -754
  53. package/src/constants.ts +0 -2
  54. package/src/env.d.ts +0 -13
  55. package/src/generateTypeDeclaration.ts +0 -119
  56. package/src/index.ts +0 -13
  57. package/src/processScript/__snapshots__/index.ts.snap +0 -8
  58. package/src/processScript/index.ts +0 -474
  59. package/src/processScript/minify.ts +0 -594
  60. package/src/processScript/postprocess.ts +0 -19
  61. package/src/processScript/preprocess.ts +0 -130
  62. package/src/processScript/shared.ts +0 -33
  63. package/src/processScript/transform.ts +0 -978
  64. package/src/pull.ts +0 -20
  65. package/src/push.ts +0 -200
  66. package/src/syncMacros.ts +0 -53
  67. package/src/tsconfig.json +0 -14
  68. package/src/watch.ts +0 -258
  69. package/tsconfig.json +0 -23
  70. package/vitest.config.ts +0 -19
package/bin/hsm.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/bin/hsm.js ADDED
@@ -0,0 +1,493 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile, readFile } from "fs/promises"
3
+ import { homedir } from "os"
4
+ import { resolve, extname, basename, dirname, relative } from "path"
5
+ import { assert } from "@samual/lib/assert"
6
+ import { AutoMap } from "@samual/lib/AutoMap"
7
+ import { countHackmudCharacters } from "@samual/lib/countHackmudCharacters"
8
+ import { writeFilePersistent } from "@samual/lib/writeFilePersistent"
9
+ import { supportedExtensions } from "../constants.js"
10
+ import { generateTypeDeclaration } from "../generateTypeDeclaration.js"
11
+ import { pull } from "../pull.js"
12
+ import { syncMacros } from "../syncMacros.js"
13
+ import "@samual/lib/readDirectoryWithStats"
14
+ import "@samual/lib/copyFilePersistent"
15
+ const options = new Map(),
16
+ commands = []
17
+ let didParseOption = !1,
18
+ didParseOptionAfterCommand = !1
19
+ for (const argument of process.argv.slice(2))
20
+ if ("-" == argument[0]) {
21
+ const argumentEqualsIndex = argument.indexOf("=")
22
+ let key, value
23
+ if (-1 == argumentEqualsIndex) {
24
+ key = argument
25
+ value = !0
26
+ } else {
27
+ key = argument.slice(0, argumentEqualsIndex)
28
+ value = argument.slice(argumentEqualsIndex + 1)
29
+ "true" == value ? (value = !0) : "false" == value && (value = !1)
30
+ }
31
+ if ("-" == argument[1]) options.set(key.slice(2), value)
32
+ else for (const option of key.slice(1)) options.set(option, value)
33
+ didParseOption = !0
34
+ } else {
35
+ didParseOption && (didParseOptionAfterCommand = !0)
36
+ commands.push(argument)
37
+ }
38
+ const pushModule = import("../push.js"),
39
+ processScriptModule = import("../processScript/index.js"),
40
+ watchModule = import("../watch.js"),
41
+ chokidarModule = import("chokidar"),
42
+ { default: chalk } = await import("chalk"),
43
+ colourA = chalk.rgb(255, 255, 255),
44
+ colourB = chalk.rgb(202, 202, 202),
45
+ colourC = chalk.rgb(155, 155, 155),
46
+ colourD = chalk.rgb(255, 0, 0),
47
+ colourF = chalk.rgb(255, 128, 0),
48
+ colourJ = chalk.rgb(255, 244, 4),
49
+ colourK = chalk.rgb(243, 249, 152),
50
+ colourL = chalk.rgb(30, 255, 0),
51
+ colourM = chalk.rgb(179, 255, 155),
52
+ colourN = chalk.rgb(0, 255, 255),
53
+ colourS = chalk.rgb(122, 178, 244),
54
+ colourV = chalk.rgb(255, 0, 236),
55
+ colourW = chalk.rgb(255, 150, 224),
56
+ formatOption = name => colourN(`-${1 == name.length ? "" : "-"}${name}`),
57
+ userColours = new AutoMap(user => {
58
+ let hash = 0
59
+ for (const char of user) hash += (hash >> 1) + hash + "xi1_8ratvsw9hlbgm02y5zpdcn7uekof463qj".indexOf(char) + 1
60
+ return [colourJ, colourK, colourM, colourW, colourL, colourB][hash % 6](user)
61
+ }),
62
+ log = message => console.log(colourS(message))
63
+ if (didParseOptionAfterCommand) {
64
+ process.exitCode = 1
65
+ console.warn(
66
+ colourF(
67
+ chalk.bold("Warning:") +
68
+ " Options should come after commands when calling the script.\n This warning will become an error in the next minor version of HSM."
69
+ )
70
+ )
71
+ }
72
+ if (process.version.startsWith("v21.")) {
73
+ process.exitCode = 1
74
+ console.warn(
75
+ colourF(
76
+ `${chalk.bold("Warning:")} Support for Node.js 21 will be dropped in the next minor version of HSM\n Your current version of Node.js is ${chalk.bold(process.version)}\n You should update your version of Node.js\n https://nodejs.org/en/download/package-manager\n`
77
+ )
78
+ )
79
+ }
80
+ if ("v" == commands[0] || "version" == commands[0] || popOption("version", "v")?.value) {
81
+ console.log("0.26.7")
82
+ process.exit()
83
+ }
84
+ let warnedDeprecatedEmitDtsAlias = !1
85
+ if (popOption("help", "h")?.value) {
86
+ logHelp()
87
+ process.exit()
88
+ }
89
+ let autoExit = !0
90
+ switch (commands[0]) {
91
+ case "push":
92
+ case "dev":
93
+ case "watch":
94
+ case "golf":
95
+ case "minify": {
96
+ const noMinifyOption = popOption("no-minify", "skip-minify")
97
+ if (noMinifyOption && "no-minify" != noMinifyOption.name) {
98
+ process.exitCode = 1
99
+ console.warn(
100
+ colourF(
101
+ `${chalk.bold("Warning:")} ${formatOption(noMinifyOption.name)} is deprecated and will be removed in the next minor\n release of HSM\n You should switch to using its alias ${colourN("--no-minify")}\n`
102
+ )
103
+ )
104
+ }
105
+ const mangleNamesOption = popOption("mangle-names"),
106
+ forceQuineCheatsOption = popOption("force-quine-cheats"),
107
+ noQuineCheatsOptions = popOption("no-quine-cheats"),
108
+ noMinifyIncompatibleOption = mangleNamesOption || forceQuineCheatsOption || noQuineCheatsOptions
109
+ if (noMinifyOption && noMinifyIncompatibleOption) {
110
+ logError(
111
+ `Options ${formatOption(noMinifyOption.name)} and ${formatOption(noMinifyIncompatibleOption.name)} are incompatible\n`
112
+ )
113
+ logHelp()
114
+ process.exit(1)
115
+ }
116
+ if (forceQuineCheatsOption && noQuineCheatsOptions) {
117
+ logError(
118
+ `Options ${formatOption(forceQuineCheatsOption.name)} and ${formatOption(noQuineCheatsOptions.name)} are incompatible\n`
119
+ )
120
+ logHelp()
121
+ process.exit(1)
122
+ }
123
+ noMinifyOption && assertOptionIsBoolean(noMinifyOption)
124
+ mangleNamesOption && assertOptionIsBoolean(mangleNamesOption)
125
+ forceQuineCheatsOption && assertOptionIsBoolean(forceQuineCheatsOption)
126
+ noQuineCheatsOptions && assertOptionIsBoolean(noQuineCheatsOptions)
127
+ const rootFolderPathOption = popOption("root-folder-path"),
128
+ rootFolderPath = rootFolderPathOption && resolve(rootFolderPathOption.value + "")
129
+ if ("golf" == commands[0] || "minify" == commands[0]) {
130
+ const watchOption = popOption("watch"),
131
+ target = commands[1]
132
+ if (!target) {
133
+ logError("Must provide target\n")
134
+ logHelp()
135
+ process.exit(1)
136
+ }
137
+ const fileExtension = extname(target)
138
+ if (!supportedExtensions.includes(fileExtension)) {
139
+ logError(
140
+ `Unsupported file extension "${chalk.bold(fileExtension)}"\nSupported extensions are "${supportedExtensions.map(extension => chalk.bold(extension)).join('", "')}"`
141
+ )
142
+ process.exit(1)
143
+ }
144
+ complainAboutUnrecognisedOptions()
145
+ const { processScript } = await processScriptModule,
146
+ fileBaseName = basename(target, fileExtension),
147
+ fileBaseNameEndsWithDotSrc = fileBaseName.endsWith(".src"),
148
+ scriptName = fileBaseNameEndsWithDotSrc ? fileBaseName.slice(0, -4) : fileBaseName,
149
+ scriptUser =
150
+ "scripts" == basename(resolve(target, "..")) && "hackmud" == basename(resolve(target, "../../.."))
151
+ ? basename(resolve(target, "../.."))
152
+ : void 0
153
+ let outputPath =
154
+ commands[2] ||
155
+ resolve(
156
+ dirname(target),
157
+ fileBaseNameEndsWithDotSrc
158
+ ? scriptName + ".js"
159
+ : ".js" == fileExtension
160
+ ? fileBaseName + ".min.js"
161
+ : fileBaseName + ".js"
162
+ )
163
+ const golfFile = () =>
164
+ readFile(target, { encoding: "utf8" }).then(async source => {
165
+ const timeStart = performance.now(),
166
+ { script, warnings } = await processScript(source, {
167
+ minify: noMinifyOption && !noMinifyOption.value,
168
+ scriptUser,
169
+ scriptName,
170
+ filePath: target,
171
+ mangleNames: mangleNamesOption?.value,
172
+ forceQuineCheats: forceQuineCheatsOption?.value ?? !noQuineCheatsOptions?.value,
173
+ rootFolderPath
174
+ }),
175
+ timeTook = performance.now() - timeStart
176
+ warnings.length && (process.exitCode = 1)
177
+ for (const { message } of warnings) console.warn(colourF(`${chalk.bold("Warning:")} ${message}`))
178
+ await writeFilePersistent(outputPath, script)
179
+ .catch(error => {
180
+ if (!commands[2] || "EISDIR" != error.code) throw error
181
+ outputPath = resolve(outputPath, basename(target, fileExtension) + ".js")
182
+ return writeFilePersistent(outputPath, script)
183
+ })
184
+ .then(() =>
185
+ log(
186
+ `Wrote ${chalk.bold(countHackmudCharacters(script))} chars to ${chalk.bold(relative(".", outputPath))} | took ${Math.round(100 * timeTook) / 100}ms`
187
+ )
188
+ )
189
+ })
190
+ if (watchOption) {
191
+ const { watch: watchFile } = await chokidarModule
192
+ watchFile(target, { awaitWriteFinish: { stabilityThreshold: 100 } })
193
+ .on("ready", () => log("Watching " + target))
194
+ .on("change", golfFile)
195
+ autoExit = !1
196
+ } else await golfFile()
197
+ } else {
198
+ const hackmudPath = getHackmudPath(),
199
+ sourcePath = commands[1]
200
+ if (!sourcePath) {
201
+ logError(`Must provide the directory to ${"push" == commands[0] ? "push from" : "watch"}\n`)
202
+ logHelp()
203
+ process.exit(1)
204
+ }
205
+ const scripts = commands.slice(2)
206
+ if (scripts.length) {
207
+ const invalidScript = scripts.find(
208
+ script => !/^(?:[a-z_][a-z\d_]{0,24}|\*)\.(?:[a-z_][a-z\d_]{0,24}|\*)$/.test(script)
209
+ )
210
+ if (invalidScript) {
211
+ logError(`Invalid script name: ${JSON.stringify(invalidScript)}\n`)
212
+ logHelp()
213
+ process.exit(1)
214
+ }
215
+ } else scripts.push("*.*")
216
+ const watchOption = popOption("watch")
217
+ if ("push" != commands[0] || watchOption?.value) {
218
+ const dtsPathOption = popOption(
219
+ "dts-path",
220
+ "type-declaration-path",
221
+ "type-declaration",
222
+ "dts",
223
+ "gen-types"
224
+ )
225
+ if (
226
+ dtsPathOption &&
227
+ "dts-path" != dtsPathOption.name &&
228
+ "type-declaration-path" != dtsPathOption.name
229
+ ) {
230
+ process.exitCode = 1
231
+ console.warn(
232
+ colourF(
233
+ `${chalk.bold("Warning:")} ${formatOption(dtsPathOption.name)} is deprecated and will be removed in the\n next minor release of HSM\n You should switch to using its alias ${colourN("--dts-path")}\n`
234
+ )
235
+ )
236
+ }
237
+ complainAboutUnrecognisedOptions()
238
+ const { watch } = await watchModule
239
+ watch(sourcePath, hackmudPath, {
240
+ scripts,
241
+ onPush: info => logInfo(info, hackmudPath),
242
+ typeDeclarationPath: dtsPathOption?.value.toString(),
243
+ minify: noMinifyOption && !noMinifyOption.value,
244
+ mangleNames: mangleNamesOption?.value,
245
+ onReady: () => log("Watching"),
246
+ forceQuineCheats: forceQuineCheatsOption?.value ?? !noQuineCheatsOptions?.value,
247
+ rootFolderPath
248
+ })
249
+ autoExit = !1
250
+ } else {
251
+ const dtsPathOption = popOption("dts-path")
252
+ complainAboutUnrecognisedOptions()
253
+ let declarationPathPromise
254
+ if (dtsPathOption) {
255
+ if ("string" != typeof dtsPathOption.value) {
256
+ logError(
257
+ `Option ${formatOption(dtsPathOption.name)} must be a string, got ${colourV(dtsPathOption.value)}\n`
258
+ )
259
+ logHelp()
260
+ process.exit(1)
261
+ }
262
+ let typeDeclarationPath = resolve(dtsPathOption.value)
263
+ const typeDeclaration = await generateTypeDeclaration(sourcePath, hackmudPath)
264
+ declarationPathPromise = writeFile(typeDeclarationPath, typeDeclaration)
265
+ .catch(error => {
266
+ assert(error instanceof Error, "src/bin/hsm.ts:318:38")
267
+ if ("EISDIR" != error.code) throw error
268
+ typeDeclarationPath = resolve(typeDeclarationPath, "player.d.ts")
269
+ return writeFile(typeDeclarationPath, typeDeclaration)
270
+ })
271
+ .then(() => typeDeclarationPath)
272
+ }
273
+ const { push, MissingSourceFolderError, MissingHackmudFolderError, NoUsersError } = await pushModule,
274
+ infos = await push(sourcePath, hackmudPath, {
275
+ scripts,
276
+ onPush: info => logInfo(info, hackmudPath),
277
+ minify: noMinifyOption && !noMinifyOption.value,
278
+ mangleNames: mangleNamesOption?.value,
279
+ forceQuineCheats: forceQuineCheatsOption?.value ?? !noQuineCheatsOptions?.value,
280
+ rootFolderPath
281
+ })
282
+ if (infos instanceof Error) {
283
+ logError(infos.message)
284
+ if (infos instanceof MissingSourceFolderError || infos instanceof NoUsersError) {
285
+ console.log()
286
+ logHelp()
287
+ } else
288
+ infos instanceof MissingHackmudFolderError &&
289
+ log(
290
+ `If this is not where your hackmud folder is, you can specify it with the\n${colourN("--hackmud-path")}=${colourB("<path>")} option or ${colourN("HSM_HACKMUD_PATH")} environment variable`
291
+ )
292
+ } else infos.length || logError("Could not find any scripts to push")
293
+ declarationPathPromise && log("Wrote type declaration to " + chalk.bold(await declarationPathPromise))
294
+ }
295
+ }
296
+ break
297
+ }
298
+ case "pull": {
299
+ const hackmudPath = getHackmudPath(),
300
+ script = commands[1]
301
+ if (!script) {
302
+ logError("Must provide the script to pull\n")
303
+ logHelp()
304
+ process.exit(1)
305
+ }
306
+ complainAboutUnrecognisedOptions()
307
+ const sourcePath = commands[2] || "."
308
+ await pull(sourcePath, hackmudPath, script).catch(error => {
309
+ console.error(error)
310
+ logError(`Something went wrong, did you forget to ${colourC("#down")} the script?`)
311
+ })
312
+ break
313
+ }
314
+ case "sync-macros": {
315
+ const hackmudPath = getHackmudPath()
316
+ complainAboutUnrecognisedOptions()
317
+ const { macrosSynced, usersSynced } = await syncMacros(hackmudPath)
318
+ log(`Synced ${macrosSynced} macros to ${usersSynced} users`)
319
+ break
320
+ }
321
+ case "generate-type-declaration":
322
+ case "gen-type-declaration":
323
+ case "gen-dts":
324
+ case "gen-types":
325
+ case "emit-dts": {
326
+ if ("emit-dts" != commands[0] && "gen-dts" != commands[0]) {
327
+ warnedDeprecatedEmitDtsAlias = !0
328
+ process.exitCode = 1
329
+ console.warn(
330
+ colourF(
331
+ `${chalk.bold("Warning:")} ${colourC("hsm")} ${colourL(commands[0])} is deprecated and will be removed\n in the next minor release of HSM\n You should switch to using its alias ${colourC("hsm")} ${colourL("emit-dts")}\n`
332
+ )
333
+ )
334
+ }
335
+ const hackmudPath = getHackmudPath(),
336
+ target = commands[1]
337
+ if (!target) {
338
+ logError("Must provide target directory\n")
339
+ logHelp()
340
+ process.exit(1)
341
+ }
342
+ complainAboutUnrecognisedOptions()
343
+ const sourcePath = resolve(target),
344
+ outputPath = commands[2] || "./player.d.ts",
345
+ typeDeclaration = await generateTypeDeclaration(sourcePath, hackmudPath)
346
+ let typeDeclarationPath = resolve(outputPath)
347
+ await writeFile(typeDeclarationPath, typeDeclaration).catch(error => {
348
+ assert(error instanceof Error, "src/bin/hsm.ts:462:35")
349
+ if ("EISDIR" != error.code) throw error
350
+ typeDeclarationPath = resolve(typeDeclarationPath, "player.d.ts")
351
+ return writeFile(typeDeclarationPath, typeDeclaration)
352
+ })
353
+ log("Wrote type declaration to " + chalk.bold(typeDeclarationPath))
354
+ break
355
+ }
356
+ case "help":
357
+ logHelp()
358
+ break
359
+ default:
360
+ commands[0] && logError(`Unknown command: ${colourL(commands[0])}\n`)
361
+ logHelp()
362
+ }
363
+ autoExit && process.exit()
364
+ function logHelp() {
365
+ const pushCommandDescription = "Push scripts from a directory to hackmud user's scripts directories",
366
+ hackmudPathOption = `${colourN("--hackmud-path")}=${colourB("<path>")}\n Override hackmud path`
367
+ switch (commands[0]) {
368
+ case "dev":
369
+ case "watch":
370
+ case "push":
371
+ console.log(
372
+ colourS(
373
+ `${colourJ("push" == commands[0] ? pushCommandDescription : "Watch a directory and push a script when modified")}\n\n${colourA("Usage:")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourB('<directory> ["<script user>.<script name>"...]')}\n\n${colourA("Arguments:")}\n${colourB("<directory>")}\n The source directory containing your scripts\n${colourB("<script user>")}\n A user to push script(s) to. Can be set to wild card (${colourV("*")}) which will try\n and discover users to push to\n${colourB("<script name>")}\n Name of a script to push. Can be set to wild card (${colourV("*")}) to find all scripts\n\n${colourA("Options:")}\n${colourN("--no-minify")}\n Skip minification to produce a "readable" script\n${colourN("--mangle-names")}\n Reduce character count further but lose function names in error call stacks\n${colourN("--force-quine-cheats")}, ${colourN("--no-quine-cheats")}\n Force quine cheats on or off\n${hackmudPathOption}\n${colourN("--dts-path")}=${colourB("<path>")}\n Path to generate a type declaration (.d.ts) file for the scripts\n${colourN("--watch")}\n Watch for changes\n${colourN("--root-folder-path")}\n The folder that root will be aliased to in import statements\n\n${colourA("Examples:")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")}\n Pushes all scripts found in ${colourV("src")} folder to all users\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")} ${colourC("foo")}${colourV(".")}${colourL("bar")}\n Pushes a script named ${colourL("bar")} found in ${colourV("src")} folder to user ${userColours.get("foo")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")} ${colourC("foo")}${colourV(".")}${colourL("bar")} ${colourC("baz")}${colourV(".")}${colourL("qux")}\n Multiple can be specified\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")} ${colourC("foo")}${colourV(".")}${colourL("*")}\n Pushes all scripts found in ${colourV("src")} folder to user ${userColours.get("foo")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")} ${colourC("*")}${colourV(".")}${colourL("foo")}\n Pushes all scripts named ${colourL("foo")} found in ${colourV("src")} folder to all user\n${colourC("hsm")} ${colourL(commands[0])} ${colourV("src")} ${colourC("*")}${colourV(".")}${colourL("*")}\n Pushes all scripts found in ${colourV("src")} folder to all users`
374
+ )
375
+ )
376
+ break
377
+ case "pull":
378
+ console.log(
379
+ colourS(
380
+ `${colourJ("Pull a script a from a hackmud user's script directory")}\n\n${colourA("Usage:")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourB("<script user>")}${colourV(".")}${colourB("<script name>")}\n\n${colourA("Options:")}\n${hackmudPathOption}`
381
+ )
382
+ )
383
+ break
384
+ case "minify":
385
+ case "golf":
386
+ console.log(
387
+ colourS(
388
+ `${colourJ("Minify a script file on the spot")}\n\n${colourA("Usage:")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourB("<target> [output path]")}\n\n${colourA("Options:")}\n${colourN("--no-minify")}\n Skip minification to produce a "readable" script\n${colourN("--mangle-names")}\n Reduce character count further but lose function names in error call stacks\n${colourN("--force-quine-cheats")}, ${colourN("--no-quine-cheats")}\n Force quine cheats on or off\n${colourN("--watch")}\n Watch for changes\n${colourN("--root-folder-path")}\n The folder that root will be aliased to in import statements`
389
+ )
390
+ )
391
+ break
392
+ case "generate-type-declaration":
393
+ case "gen-type-declaration":
394
+ case "gen-dts":
395
+ case "gen-types":
396
+ case "emit-dts":
397
+ if (!warnedDeprecatedEmitDtsAlias && "emit-dts" != commands[0] && "gen-dts" != commands[0]) {
398
+ process.exitCode = 1
399
+ console.warn(
400
+ colourF(
401
+ `${chalk.bold("Warning:")} ${colourC("hsm")} ${colourL(commands[0])} is deprecated and will be removed\n in the next minor release of HSM\n You should switch to using its alias ${colourC("hsm")} ${colourL("emit-dts")}\n`
402
+ )
403
+ )
404
+ }
405
+ console.log(
406
+ colourS(
407
+ `${colourJ("Generate a type declaration file for a directory of scripts")}\n\n${colourA("Usage:")}\n${colourC("hsm")} ${colourL(commands[0])} ${colourB("<directory> [output path]")}\n\n${colourA("Options:")}\n${hackmudPathOption}`
408
+ )
409
+ )
410
+ break
411
+ case "sync-macros":
412
+ console.log(
413
+ colourS(
414
+ `${colourJ("Sync macros across all hackmud users")}\n\n${colourA("Options:")}\n${hackmudPathOption}`
415
+ )
416
+ )
417
+ break
418
+ default:
419
+ console.log(
420
+ colourS(
421
+ `${colourJ("Hackmud Script Manager")}\n${colourN("Version") + colourS(": ") + colourV("0.26.7")}\n\n${colourA("Commands:")}\n${colourL("push")}\n ${pushCommandDescription}\n${colourL("minify")}\n Minify a script file on the spot\n${colourL("emit-dts")}\n Generate a type declaration file for a directory of scripts\n${colourL("sync-macros")}\n Sync macros across all hackmud users\n${colourL("pull")}\n Pull a script a from a hackmud user's script directory\n\n${colourA("Options:")}\n${colourN("--help")}\n Can be used on any command e.g. ${colourC("hsm")} ${colourL("push")} ${colourN("--help")} to show helpful information`
422
+ )
423
+ )
424
+ }
425
+ }
426
+ function logInfo({ path, users, characterCount, error, warnings }, hackmudPath) {
427
+ path = relative(".", path)
428
+ if (error) logError(`Error "${chalk.bold(error.message)}" in ${chalk.bold(path)}`)
429
+ else {
430
+ warnings.length && (process.exitCode = 1)
431
+ for (const warning of warnings) console.warn(colourF(`${chalk.bold("Warning:")} ${warning.message}`))
432
+ log(
433
+ `Pushed ${chalk.bold(path)} to ${users.map(user => chalk.bold(userColours.get(user))).join(", ")} | ${chalk.bold(characterCount + "")} chars | ${chalk.bold(resolve(hackmudPath, users[0], "scripts", basename(path, extname(path))) + ".js")}`
434
+ )
435
+ }
436
+ }
437
+ function logError(message) {
438
+ console.error(colourD(message))
439
+ process.exitCode = 1
440
+ }
441
+ function getHackmudPath() {
442
+ const hackmudPathOption = popOption("hackmud-path")
443
+ if (hackmudPathOption) {
444
+ if ("string" != typeof hackmudPathOption.value) {
445
+ logError(`Option ${colourN("--hackmud-path")} must be a string, got ${colourV(hackmudPathOption.value)}\n`)
446
+ logHelp()
447
+ process.exit(1)
448
+ }
449
+ if (!hackmudPathOption.value) {
450
+ logError(`Option ${colourN("--hackmud-path")} was specified but empty\n`)
451
+ logHelp()
452
+ process.exit(1)
453
+ }
454
+ return hackmudPathOption.value
455
+ }
456
+ if (null != process.env.HSM_HACKMUD_PATH) {
457
+ if (!process.env.HSM_HACKMUD_PATH) {
458
+ logError(`Environment variable ${colourN("HSM_HACKMUD_PATH")} was specified but empty\n`)
459
+ logHelp()
460
+ process.exit(1)
461
+ }
462
+ return process.env.HSM_HACKMUD_PATH
463
+ }
464
+ return "win32" == process.platform ? resolve(process.env.APPDATA, "hackmud") : resolve(homedir(), ".config/hackmud")
465
+ }
466
+ function assertOptionIsBoolean(option) {
467
+ if ("boolean" != typeof option.value) {
468
+ logError(`The value for ${formatOption(option.name)} must be ${colourV("true")} or ${colourV("false")}\n`)
469
+ logHelp()
470
+ process.exit(1)
471
+ }
472
+ }
473
+ function popOption(...names) {
474
+ const presentOptionNames = names.filter(name => options.has(name))
475
+ if (!presentOptionNames.length) return
476
+ if (presentOptionNames.length > 1) {
477
+ logError(
478
+ `The options ${presentOptionNames.map(formatOption).join(", ")} are aliases for each other. Please only specify one`
479
+ )
480
+ process.exit(1)
481
+ }
482
+ const value = options.get(presentOptionNames[0])
483
+ options.delete(presentOptionNames[0])
484
+ return { name: presentOptionNames[0], value }
485
+ }
486
+ function complainAboutUnrecognisedOptions() {
487
+ if (options.size) {
488
+ logError(
489
+ `Unrecognised option${options.size > 1 ? "s" : ""}: ${[...options.keys()].map(formatOption).join(", ")}`
490
+ )
491
+ process.exit(1)
492
+ }
493
+ }
package/constants.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare const supportedExtensions: string[];
2
+ export declare const validDBMethods: string[];
package/constants.js ADDED
@@ -0,0 +1,3 @@
1
+ const supportedExtensions = [".js", ".ts"],
2
+ validDBMethods = ["i", "r", "f", "u", "u1", "us", "ObjectId"]
3
+ export { supportedExtensions, validDBMethods }
package/env.d.ts CHANGED
@@ -632,6 +632,16 @@ type Lowsec = Midsec & PlayerLowsec & {
632
632
 
633
633
  /** **LOWSEC** */ expose_upgrades: (args: { target: string }) => UpgradeBase[] | ScriptFailure
634
634
  /** **LOWSEC** */ xfer_upgrade_from: (args: { target: string, i: number | number[] }) => ScriptResponse<{}>
635
+
636
+ /** **LOWSEC** */ expose_transactions: (args: {target: string, start?: number}) => {
637
+ time: Date
638
+ amount: number
639
+ sender: string
640
+ recipient: string
641
+ script: string | null
642
+ memo?: string
643
+ }[] | ScriptFailure
644
+ /** **LOWSEC** */ expose_upgrade_log: (args: {target: string, start?: number}) => { t: Date, u: string, r: string, msg: string }[] | ScriptFailure
635
645
  }
636
646
  }
637
647
 
@@ -0,0 +1 @@
1
+ export declare function generateTypeDeclaration(sourceDirectory: string, hackmudPath?: string): Promise<string>;
@@ -0,0 +1,70 @@
1
+ import { basename, resolve } from "path"
2
+ import { readDirectoryWithStats } from "@samual/lib/readDirectoryWithStats"
3
+ async function generateTypeDeclaration(sourceDirectory, hackmudPath) {
4
+ const users = new Set()
5
+ if (hackmudPath)
6
+ for (const { stats, name } of await readDirectoryWithStats(hackmudPath))
7
+ stats.isFile() && name.endsWith(".key") && users.add(basename(name, ".key"))
8
+ const wildScripts = [],
9
+ wildAnyScripts = [],
10
+ allScripts = {},
11
+ allAnyScripts = {}
12
+ await Promise.all(
13
+ (await readDirectoryWithStats(sourceDirectory))
14
+ .filter(({ stats, name }) => !stats.isDirectory() || /^[a-z_][a-z\d_]{0,24}$/.test(name))
15
+ .map(async ({ stats, name }) => {
16
+ if (stats.isFile())
17
+ name.endsWith(".ts")
18
+ ? name.endsWith(".d.ts") || wildScripts.push(basename(name, ".ts"))
19
+ : name.endsWith(".js") && wildAnyScripts.push(basename(name, ".js"))
20
+ else if (stats.isDirectory()) {
21
+ const scripts = [],
22
+ anyScripts = []
23
+ allScripts[name] = scripts
24
+ allAnyScripts[name] = anyScripts
25
+ users.add(name)
26
+ for (const child of await readDirectoryWithStats(resolve(sourceDirectory, name)))
27
+ child.stats.isFile() &&
28
+ (child.name.endsWith(".ts")
29
+ ? name.endsWith(".d.ts") || scripts.push(basename(child.name, ".ts"))
30
+ : child.name.endsWith(".js") && anyScripts.push(basename(child.name, ".js")))
31
+ }
32
+ })
33
+ )
34
+ let o = ""
35
+ for (const script of wildScripts)
36
+ o += `type $${script}$ = typeof import(${JSON.stringify(resolve(sourceDirectory, script))}).default\n`
37
+ o += "\n"
38
+ for (const user in allScripts) {
39
+ const scripts = allScripts[user]
40
+ for (const script of scripts)
41
+ o += `type $${user}$${script}$ = typeof import(${JSON.stringify(resolve(sourceDirectory, user, script))}).default\n`
42
+ }
43
+ o +=
44
+ "\ntype ArrayRemoveFirst<A> = A extends [ infer FirstItem, ...infer Rest ] ? Rest : never\n\ntype Subscript<T extends (...args: any) => any> =\n\t(...args: ArrayRemoveFirst<Parameters<T>>) => ReturnType<T> | ScriptFailure\n\ntype WildFullsec = Record<string, () => ScriptFailure> & {\n"
45
+ for (const script of wildScripts) o += `\t${script}: Subscript<$${script}$>\n`
46
+ for (const script of wildAnyScripts) o += `\t${script}: (...args: any) => any\n`
47
+ o += "}\n\ninterface PlayerFullsec {"
48
+ let lastWasMultiLine = !0
49
+ for (const user of users) {
50
+ const scripts = allScripts[user],
51
+ anyScripts = allAnyScripts[user]
52
+ if ((scripts && scripts.length) || (anyScripts && anyScripts.length)) {
53
+ lastWasMultiLine = !0
54
+ o += `\n\t${user}: WildFullsec & {\n`
55
+ if (scripts) for (const script of scripts) o += `\t\t${script}: Subscript<$${user}$${script}$>\n`
56
+ if (anyScripts) for (const script of anyScripts) o += `\t\t${script}: (...args: any) => any\n`
57
+ o += "\t}"
58
+ } else {
59
+ if (lastWasMultiLine) {
60
+ o += "\n"
61
+ lastWasMultiLine = !1
62
+ }
63
+ o += `\t${user}: WildFullsec`
64
+ }
65
+ o += "\n"
66
+ }
67
+ o += "}\n"
68
+ return o
69
+ }
70
+ export { generateTypeDeclaration }
package/index.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export { supportedExtensions } from "./constants";
2
+ export { generateTypeDeclaration } from "./generateTypeDeclaration";
3
+ export { processScript } from "./processScript";
4
+ export { pull } from "./pull";
5
+ export { push } from "./push";
6
+ export { syncMacros } from "./syncMacros";
7
+ export { watch } from "./watch";
8
+ export type Info = {
9
+ path: string;
10
+ users: string[];
11
+ characterCount: number;
12
+ error: Error | undefined;
13
+ warnings: {
14
+ message: string;
15
+ }[];
16
+ };
package/index.js ADDED
@@ -0,0 +1,52 @@
1
+ export { supportedExtensions } from "./constants.js"
2
+ export { generateTypeDeclaration } from "./generateTypeDeclaration.js"
3
+ export { processScript } from "./processScript/index.js"
4
+ export { pull } from "./pull.js"
5
+ export { push } from "./push.js"
6
+ export { syncMacros } from "./syncMacros.js"
7
+ export { watch } from "./watch.js"
8
+ import "path"
9
+ import "@samual/lib/readDirectoryWithStats"
10
+ import "@babel/generator"
11
+ import "@babel/parser"
12
+ import "@babel/plugin-proposal-decorators"
13
+ import "@babel/plugin-proposal-destructuring-private"
14
+ import "@babel/plugin-transform-class-properties"
15
+ import "@babel/plugin-transform-class-static-block"
16
+ import "@babel/plugin-transform-explicit-resource-management"
17
+ import "@babel/plugin-transform-exponentiation-operator"
18
+ import "@babel/plugin-transform-json-strings"
19
+ import "@babel/plugin-transform-logical-assignment-operators"
20
+ import "@babel/plugin-transform-nullish-coalescing-operator"
21
+ import "@babel/plugin-transform-numeric-separator"
22
+ import "@babel/plugin-transform-object-rest-spread"
23
+ import "@babel/plugin-transform-optional-catch-binding"
24
+ import "@babel/plugin-transform-optional-chaining"
25
+ import "@babel/plugin-transform-private-property-in-object"
26
+ import "@babel/plugin-transform-unicode-sets-regex"
27
+ import "@babel/traverse"
28
+ import "@babel/types"
29
+ import "@rollup/plugin-alias"
30
+ import "@rollup/plugin-babel"
31
+ import "@rollup/plugin-commonjs"
32
+ import "@rollup/plugin-json"
33
+ import "@rollup/plugin-node-resolve"
34
+ import "@samual/lib/assert"
35
+ import "prettier"
36
+ import "rollup"
37
+ import "./processScript/minify.js"
38
+ import "@samual/lib/countHackmudCharacters"
39
+ import "@samual/lib/spliceString"
40
+ import "acorn"
41
+ import "terser"
42
+ import "./processScript/shared.js"
43
+ import "./processScript/postprocess.js"
44
+ import "./processScript/preprocess.js"
45
+ import "import-meta-resolve"
46
+ import "./processScript/transform.js"
47
+ import "@samual/lib/clearObject"
48
+ import "@samual/lib/copyFilePersistent"
49
+ import "fs/promises"
50
+ import "@samual/lib/AutoMap"
51
+ import "@samual/lib/writeFilePersistent"
52
+ import "chokidar"