@adamhl8/bask 0.6.1 → 0.7.0

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 (45) hide show
  1. package/README.md +81 -5
  2. package/dist/bask-file/bask-file.js +2 -2
  3. package/dist/bask-file/bask-file.js.map +1 -1
  4. package/dist/bask-file/task-index.js +1 -2
  5. package/dist/bask-file/task-index.js.map +1 -1
  6. package/dist/cli/bask-parser.js +37 -0
  7. package/dist/cli/bask-parser.js.map +1 -0
  8. package/dist/cli/help.js +32 -0
  9. package/dist/cli/help.js.map +1 -0
  10. package/dist/cli/list.d.ts +5 -0
  11. package/dist/{bask-file → cli}/list.js +11 -3
  12. package/dist/cli/list.js.map +1 -0
  13. package/dist/cli/optique.js +25 -0
  14. package/dist/cli/optique.js.map +1 -0
  15. package/dist/cli/print-error.js +8 -0
  16. package/dist/cli/print-error.js.map +1 -0
  17. package/dist/cli/run-bask.js +60 -0
  18. package/dist/cli/run-bask.js.map +1 -0
  19. package/dist/cli/run-task.js +21 -0
  20. package/dist/cli/run-task.js.map +1 -0
  21. package/dist/cli/split-args.js +25 -0
  22. package/dist/cli/split-args.js.map +1 -0
  23. package/dist/cli/task-parser.js +49 -0
  24. package/dist/cli/task-parser.js.map +1 -0
  25. package/dist/cli.js +9 -7
  26. package/dist/cli.js.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +2 -2
  29. package/dist/index.js.map +1 -1
  30. package/dist/{bask-file/loaded.js → loaded-bask-file.js} +2 -2
  31. package/dist/loaded-bask-file.js.map +1 -0
  32. package/dist/task/args.d.ts +13 -0
  33. package/dist/task/args.js +12 -0
  34. package/dist/task/args.js.map +1 -0
  35. package/dist/task.d.ts +19 -8
  36. package/dist/task.js +27 -10
  37. package/dist/task.js.map +1 -1
  38. package/dist/utils.js +3 -5
  39. package/dist/utils.js.map +1 -1
  40. package/package.json +2 -1
  41. package/dist/bask-file/list.d.ts +0 -4
  42. package/dist/bask-file/list.js.map +0 -1
  43. package/dist/bask-file/loaded.js.map +0 -1
  44. package/dist/run-bask.js +0 -47
  45. package/dist/run-bask.js.map +0 -1
package/README.md CHANGED
@@ -13,6 +13,7 @@ A task runner where your tasks are TypeScript functions.
13
13
  - [Task options](#task-options)
14
14
  - [Task naming](#task-naming)
15
15
  - [The default task](#the-default-task)
16
+ - [Task arguments](#task-arguments)
16
17
  - [Task dependencies](#task-dependencies)
17
18
  - [Task hooks](#task-hooks)
18
19
  - [Running commands](#running-commands)
@@ -93,7 +94,7 @@ Available tasks:
93
94
 
94
95
  ### Defining tasks
95
96
 
96
- `task` takes a function, and optionally an [options](#task-options) object first. The function receives `sh`, a [shell](#running-commands) for running commands, and it can be async or sync:
97
+ `task` takes a function, and optionally an [options](#task-options) object first. The function receives `sh`, a [shell](#running-commands) for running commands, along with the task's [`args` and `positionals`](#task-arguments). It can be async or sync:
97
98
 
98
99
  ```ts
99
100
  export const build = task({ desc: "Build the project" }, async ({ sh }) => {
@@ -113,6 +114,8 @@ export const hello = task(() => {
113
114
  - `hidden`: Keeps the task runnable but leaves it out of the task list
114
115
  - `alias`: Other names the task runs under, as a string or an array
115
116
  - Write them in kebab-case or camelCase, and either spelling runs the task
117
+ - `args`: The args the task takes from the command line (see [Task arguments](#task-arguments))
118
+ - `positionals`: Lets the task take positionals, including everything after `--` (see [Task arguments](#task-arguments))
116
119
 
117
120
  ```ts
118
121
  export const releaseRun = task({ desc: "Run from CI", hidden: true }, async ({ sh }) => {
@@ -167,6 +170,66 @@ export default build
167
170
 
168
171
  ---
169
172
 
173
+ ### Task arguments
174
+
175
+ A task can take args from the command line. Declare them with the `args` option, and set `positionals: true` to accept positionals. The task gets them, typed, as `args` and `positionals`:
176
+
177
+ ```ts
178
+ export const test = task(
179
+ {
180
+ desc: "Run tests",
181
+ args: {
182
+ watch: { short: "w", desc: "Rerun when files change" },
183
+ timeout: { type: "string", desc: "Per-test timeout in ms" },
184
+ },
185
+ positionals: true,
186
+ },
187
+ async ({ sh, args, positionals }) => {
188
+ // args: { watch: boolean, timeout: string | undefined }, positionals: string[]
189
+ await sh`bun test ${args.watch ? "--watch" : []} --timeout ${args.timeout ?? "5000"} ${positionals}`
190
+ },
191
+ )
192
+ ```
193
+
194
+ ```sh
195
+ bask test -w --timeout 10000 src/foo.test.ts
196
+ bask test -- --bail # everything after `--` is a positional
197
+ ```
198
+
199
+ Each arg takes:
200
+
201
+ - `short`: A one-letter or one-digit short flag, like `w` for `-w`
202
+ - `type`: `"boolean"` (the default) or `"string"`
203
+ - `desc`: Shown on the task's help page
204
+
205
+ The long flag is the arg's name in kebab-case, so `dryRun` is `--dry-run`. An arg that isn't passed is `false` if it's a boolean, or `undefined` if it's a string.
206
+
207
+ - Flags before the task name are bask's, and args after it are the task's: `bask -l` lists the tasks, while `bask test -l` passes `-l` to `test`
208
+ - bask doesn't reserve any names, so a task can declare its own `-l` or `-h`
209
+ - You must name a default task to pass args to it: `bask build -w` or `bask default -w`
210
+ - An unknown flag, a missing value, or a positional to a task that doesn't accept them prints the task's usage and an error, and exits with code 2
211
+
212
+ Only the command line passes args, and only to the task you named. A task that runs as a [dependency](#task-dependencies) or as a [hook](#task-hooks) gets its own empty args, so for a variant, make a separate task. A hook function on the named task gets that task's `args` and `positionals` (see [Task hooks](#task-hooks)).
213
+
214
+ Run `bask -h <task>` to see a task's help page:
215
+
216
+ ```
217
+ Run tests
218
+ Usage: bask test [-w/--watch] [--timeout VALUE] [ARG...]
219
+
220
+ ARG
221
+ -w, --watch Rerun when files change
222
+ --timeout VALUE Per-test timeout in ms
223
+ ```
224
+
225
+ Args also show next to the task in the task list:
226
+
227
+ ```
228
+ test # Run tests [-w/--watch] [--timeout VALUE] [ARG...]
229
+ ```
230
+
231
+ ---
232
+
170
233
  ### Task dependencies
171
234
 
172
235
  To depend on another task, call it. Each task runs at most once per invocation, however many tasks call it. If two tasks call it at the same time, they both wait on the same run.
@@ -211,8 +274,19 @@ build.after(async ({ sh }) => {
211
274
  - Hooks run once per invocation, along with their task
212
275
  - This includes when another task calls the task
213
276
  - Each hook gets its own `sh`, separate from the task's
277
+ - A hook function gets its task's `args` and `positionals`, typed from the task's `args` option
278
+ - A task used as a hook runs with its own empty args, not the args of the task it's hooked to
214
279
  - Adding a hook to a task that has already started throws an error
215
280
 
281
+ A hook function can check its task's args, which helps when extending a shared task:
282
+
283
+ ```ts
284
+ // The shared `build` task declares a `watch` arg
285
+ build.after(async ({ sh, args }) => {
286
+ if (!args.watch) await sh`du -sh dist`
287
+ })
288
+ ```
289
+
216
290
  The built-in `list` task, which prints the task list, takes hooks too:
217
291
 
218
292
  ```ts
@@ -370,16 +444,18 @@ This way, each project extends the shared tasks without copying or replacing the
370
444
 
371
445
  ## CLI Reference
372
446
 
373
- `bask [options] [task]`
447
+ `bask [-l] [-h] [task] [task args]`
374
448
 
375
449
  - `task`: The task to run, by its kebab-case name, camelCase name, or an alias (default: the default export)
450
+ - `task args`: The [args and positionals](#task-arguments) to pass to the task
376
451
  - `-l`, `--list`: List the available tasks
452
+ - `-h`, `--help`: Show bask's help and the task list, or a task's help with `bask -h <task>`
377
453
 
378
- If the task doesn't exist, bask prints an error followed by the task list.
454
+ If the arguments are invalid, including an unknown task, bask prints the usage and an error.
379
455
 
380
456
  **Exit codes:**
381
457
 
382
458
  - `0`: The task succeeded
383
- - `1`: There's no `bask.ts`, it has a problem (e.g. a task exported twice), or the task doesn't exist
384
- - `2`: The arguments are invalid
459
+ - `1`: There's no `bask.ts`, or it has a problem (e.g. a task exported twice)
460
+ - `2`: The arguments are invalid, including an unknown task or the task's args
385
461
  - Otherwise, the exit code of the command that failed
@@ -1,6 +1,6 @@
1
- import { setLoadedBaskFile } from "./loaded.js";
2
1
  import { indexTasks } from "./task-index.js";
3
2
  import { isBaskConfig, resolveShellConfig } from "../config.js";
3
+ import { setLoadedBaskFile } from "../loaded-bask-file.js";
4
4
  import { addBinDirsToPath } from "../shell/bin-dirs.js";
5
5
  import { isTask } from "../task.js";
6
6
  import path from "node:path";
@@ -54,6 +54,6 @@ const loadBaskFile = async (baskPath) => {
54
54
  setLoadedBaskFile(baskFile);
55
55
  return baskFile;
56
56
  };
57
- export { loadBaskFile };
57
+ export { joinBaskFileErrors, loadBaskFile };
58
58
 
59
59
  //# sourceMappingURL=bask-file.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bask-file.js","names":[],"sources":["../../src/bask-file/bask-file.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { setLoadedBaskFile } from \"#bask-file/loaded.ts\"\nimport { indexTasks } from \"#bask-file/task-index.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { isBaskConfig, resolveShellConfig } from \"#config.ts\"\nimport type { BaskConfig, BaskConfigInput } from \"#config.ts\"\nimport { addBinDirsToPath } from \"#shell/bin-dirs.ts\"\nimport { isTask } from \"#task.ts\"\n\n/** The exports of `bask.ts`, before bask checks them. */\nexport interface BaskFileExports {\n default?: unknown\n baskConfig?: unknown\n [exportName: string]: unknown\n}\n\nexport interface BaskFile {\n tasks: TaskIndex\n /** The `baskConfig` export with its defaults filled in, and `shell.env` holding the whole starting environment. */\n config: BaskConfig\n}\n\n/** Returns a single error as is, or joins several into one error under a count with one per line. */\nconst joinBaskFileErrors = (baskFileErrors: Error[]) => {\n const [onlyError] = baskFileErrors\n if (onlyError && baskFileErrors.length === 1) return onlyError\n const lines = baskFileErrors.map((error) => ` ${messageChain(error)}`)\n return err([`bask.ts has ${baskFileErrors.length} problems:`, ...lines].join(\"\\n\"), undefined)\n}\n\n/** Imports `bask.ts`, and returns an error that marks it invalid instead of throwing it. */\nconst importBaskFile = async (baskPath: string): Promise<Result<BaskFileExports>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - a module namespace is always an object, and `resolveBaskFileExports` checks each export\n const baskFileExports = await attempt(async () => import(baskPath) as Promise<BaskFileExports>)\n if (isErr(baskFileExports) && getContext(baskFileExports, \"invalidBaskFile\")) return baskFileExports\n\n // Rethrow any other error, because a bug in `bask.ts` needs its stack trace.\n if (isErr(baskFileExports)) throw baskFileExports\n\n return baskFileExports\n}\n\n/** Validates the exports of `bask.ts` and indexes its tasks. */\nconst resolveBaskFileExports = (\n baskFileExports: BaskFileExports,\n): Result<{ tasks: TaskIndex; config: BaskConfigInput }> => {\n // Collect every error before returning, so one run reports all of them.\n const baskFileErrors: Error[] = []\n\n const { default: defaultExport, baskConfig } = baskFileExports\n\n // Reject a non-task default because bask runs it when no task is named, so it's always a mistake.\n if (defaultExport !== undefined && !isTask(defaultExport))\n baskFileErrors.push(err(\"the default export isn't a task. Wrap it in task().\", undefined))\n\n let config: BaskConfigInput = {}\n if (isBaskConfig(baskConfig)) config = baskConfig\n else if (baskConfig !== undefined)\n baskFileErrors.push(err(\"baskConfig isn't a config. Wrap it in defineConfig().\", undefined))\n\n const { tasks, errors: taskErrors } = indexTasks(baskFileExports)\n baskFileErrors.push(...taskErrors)\n\n if (baskFileErrors.length > 0) return joinBaskFileErrors(baskFileErrors)\n\n return { tasks, config }\n}\n\n/** Imports and validates `bask.ts`, then stores it for tasks to read when they run. */\nexport const loadBaskFile = async (baskPath: string): Promise<Result<BaskFile>> => {\n const baskDir = path.dirname(baskPath)\n if (!(await bun.file(baskPath).exists())) return err(`no bask.ts in ${baskDir}`, undefined)\n\n // Add the bin dirs before the import because loading copies `process.env` for every shell.\n addBinDirsToPath(baskDir)\n const baskFileExports = await importBaskFile(baskPath)\n if (isErr(baskFileExports)) return baskFileExports\n\n const resolvedExports = resolveBaskFileExports(baskFileExports)\n if (isErr(resolvedExports)) return resolvedExports\n\n const { tasks, config } = resolvedExports\n // Copy `process.env` once `bask.ts` has loaded, so later changes to it don't reach commands.\n const resolvedShellConfig = resolveShellConfig(config.shell ?? {}, process.env)\n const baskFile: BaskFile = { tasks, config: { shell: resolvedShellConfig } }\n setLoadedBaskFile(baskFile)\n\n return baskFile\n}\n"],"mappings":";;;;;;;;;;AA4BA,MAAM,sBAAsB,mBAA4B;CACtD,MAAM,CAAC,aAAa;CACpB,IAAI,aAAa,eAAe,WAAW,GAAG,OAAO;CACrD,MAAM,QAAQ,eAAe,KAAK,UAAU,KAAK,aAAa,KAAK,GAAG;CACtE,OAAO,IAAI,CAAC,eAAe,eAAe,OAAO,aAAa,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI,GAAG,KAAA,CAAS;AAC/F;;AAGA,MAAM,iBAAiB,OAAO,aAAuD;CAEnF,MAAM,kBAAkB,MAAM,QAAQ,YAAY,OAAO,SAAqC;CAC9F,IAAI,MAAM,eAAe,KAAK,WAAW,iBAAiB,iBAAiB,GAAG,OAAO;CAGrF,IAAI,MAAM,eAAe,GAAG,MAAM;CAElC,OAAO;AACT;;AAGA,MAAM,0BACJ,oBAC0D;CAE1D,MAAM,iBAA0B,CAAC;CAEjC,MAAM,EAAE,SAAS,eAAe,eAAe;CAG/C,IAAI,kBAAkB,KAAA,KAAa,CAAC,OAAO,aAAa,GACtD,eAAe,KAAK,IAAI,uDAAuD,KAAA,CAAS,CAAC;CAE3F,IAAI,SAA0B,CAAC;CAC/B,IAAI,aAAa,UAAU,GAAG,SAAS;MAClC,IAAI,eAAe,KAAA,GACtB,eAAe,KAAK,IAAI,yDAAyD,KAAA,CAAS,CAAC;CAE7F,MAAM,EAAE,OAAO,QAAQ,eAAe,WAAW,eAAe;CAChE,eAAe,KAAK,GAAG,UAAU;CAEjC,IAAI,eAAe,SAAS,GAAG,OAAO,mBAAmB,cAAc;CAEvE,OAAO;EAAE;EAAO;CAAO;AACzB;;AAGA,MAAa,eAAe,OAAO,aAAgD;CACjF,MAAM,UAAU,KAAK,QAAQ,QAAQ;CACrC,IAAI,CAAE,MAAM,IAAI,KAAK,QAAQ,CAAC,CAAC,OAAO,GAAI,OAAO,IAAI,iBAAiB,WAAW,KAAA,CAAS;CAG1F,iBAAiB,OAAO;CACxB,MAAM,kBAAkB,MAAM,eAAe,QAAQ;CACrD,IAAI,MAAM,eAAe,GAAG,OAAO;CAEnC,MAAM,kBAAkB,uBAAuB,eAAe;CAC9D,IAAI,MAAM,eAAe,GAAG,OAAO;CAEnC,MAAM,EAAE,OAAO,WAAW;CAG1B,MAAM,WAAqB;EAAE;EAAO,QAAQ,EAAE,OADlB,mBAAmB,OAAO,SAAS,CAAC,GAAG,QAAQ,GACJ,EAAE;CAAE;CAC3E,kBAAkB,QAAQ;CAE1B,OAAO;AACT"}
1
+ {"version":3,"file":"bask-file.js","names":[],"sources":["../../src/bask-file/bask-file.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { indexTasks } from \"#bask-file/task-index.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { isBaskConfig, resolveShellConfig } from \"#config.ts\"\nimport type { BaskConfig, BaskConfigInput } from \"#config.ts\"\nimport { setLoadedBaskFile } from \"#loaded-bask-file.ts\"\nimport { addBinDirsToPath } from \"#shell/bin-dirs.ts\"\nimport { isTask } from \"#task.ts\"\n\n/** The exports of `bask.ts`, before bask checks them. */\nexport interface BaskFileExports {\n default?: unknown\n baskConfig?: unknown\n [exportName: string]: unknown\n}\n\nexport interface BaskFile {\n tasks: TaskIndex\n /** The `baskConfig` export with its defaults filled in, and `shell.env` holding the whole starting environment. */\n config: BaskConfig\n}\n\n/** Returns a single error as is, or joins several into one error under a count with one per line. */\nexport const joinBaskFileErrors = (baskFileErrors: Error[]) => {\n const [onlyError] = baskFileErrors\n if (onlyError && baskFileErrors.length === 1) return onlyError\n const lines = baskFileErrors.map((error) => ` ${messageChain(error)}`)\n return err([`bask.ts has ${baskFileErrors.length} problems:`, ...lines].join(\"\\n\"), undefined)\n}\n\n/** Imports `bask.ts`, and returns an error that marks it invalid instead of throwing it. */\nconst importBaskFile = async (baskPath: string): Promise<Result<BaskFileExports>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - a module namespace is always an object, and `resolveBaskFileExports` checks each export\n const baskFileExports = await attempt(async () => import(baskPath) as Promise<BaskFileExports>)\n if (isErr(baskFileExports) && getContext(baskFileExports, \"invalidBaskFile\")) return baskFileExports\n\n // Rethrow any other error, because a bug in `bask.ts` needs its stack trace.\n if (isErr(baskFileExports)) throw baskFileExports\n\n return baskFileExports\n}\n\n/** Validates the exports of `bask.ts` and indexes its tasks. */\nconst resolveBaskFileExports = (\n baskFileExports: BaskFileExports,\n): Result<{ tasks: TaskIndex; config: BaskConfigInput }> => {\n // Collect every error before returning, so one run reports all of them.\n const baskFileErrors: Error[] = []\n\n const { default: defaultExport, baskConfig } = baskFileExports\n\n // Reject a non-task default because bask runs it when no task is named, so it's always a mistake.\n if (defaultExport !== undefined && !isTask(defaultExport))\n baskFileErrors.push(err(\"the default export isn't a task. Wrap it in task().\", undefined))\n\n let config: BaskConfigInput = {}\n if (isBaskConfig(baskConfig)) config = baskConfig\n else if (baskConfig !== undefined)\n baskFileErrors.push(err(\"baskConfig isn't a config. Wrap it in defineConfig().\", undefined))\n\n const { tasks, errors: taskErrors } = indexTasks(baskFileExports)\n baskFileErrors.push(...taskErrors)\n\n if (baskFileErrors.length > 0) return joinBaskFileErrors(baskFileErrors)\n\n return { tasks, config }\n}\n\n/** Imports and validates `bask.ts`, then stores it for tasks to read when they run. */\nexport const loadBaskFile = async (baskPath: string): Promise<Result<BaskFile>> => {\n const baskDir = path.dirname(baskPath)\n if (!(await bun.file(baskPath).exists())) return err(`no bask.ts in ${baskDir}`, undefined)\n\n // Add the bin dirs before the import because loading copies `process.env` for every shell.\n addBinDirsToPath(baskDir)\n const baskFileExports = await importBaskFile(baskPath)\n if (isErr(baskFileExports)) return baskFileExports\n\n const resolvedExports = resolveBaskFileExports(baskFileExports)\n if (isErr(resolvedExports)) return resolvedExports\n\n const { tasks, config } = resolvedExports\n // Copy `process.env` once `bask.ts` has loaded, so later changes to it don't reach commands.\n const resolvedShellConfig = resolveShellConfig(config.shell ?? {}, process.env)\n const baskFile: BaskFile = { tasks, config: { shell: resolvedShellConfig } }\n setLoadedBaskFile(baskFile)\n\n return baskFile\n}\n"],"mappings":";;;;;;;;;;AA4BA,MAAa,sBAAsB,mBAA4B;CAC7D,MAAM,CAAC,aAAa;CACpB,IAAI,aAAa,eAAe,WAAW,GAAG,OAAO;CACrD,MAAM,QAAQ,eAAe,KAAK,UAAU,KAAK,aAAa,KAAK,GAAG;CACtE,OAAO,IAAI,CAAC,eAAe,eAAe,OAAO,aAAa,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI,GAAG,KAAA,CAAS;AAC/F;;AAGA,MAAM,iBAAiB,OAAO,aAAuD;CAEnF,MAAM,kBAAkB,MAAM,QAAQ,YAAY,OAAO,SAAqC;CAC9F,IAAI,MAAM,eAAe,KAAK,WAAW,iBAAiB,iBAAiB,GAAG,OAAO;CAGrF,IAAI,MAAM,eAAe,GAAG,MAAM;CAElC,OAAO;AACT;;AAGA,MAAM,0BACJ,oBAC0D;CAE1D,MAAM,iBAA0B,CAAC;CAEjC,MAAM,EAAE,SAAS,eAAe,eAAe;CAG/C,IAAI,kBAAkB,KAAA,KAAa,CAAC,OAAO,aAAa,GACtD,eAAe,KAAK,IAAI,uDAAuD,KAAA,CAAS,CAAC;CAE3F,IAAI,SAA0B,CAAC;CAC/B,IAAI,aAAa,UAAU,GAAG,SAAS;MAClC,IAAI,eAAe,KAAA,GACtB,eAAe,KAAK,IAAI,yDAAyD,KAAA,CAAS,CAAC;CAE7F,MAAM,EAAE,OAAO,QAAQ,eAAe,WAAW,eAAe;CAChE,eAAe,KAAK,GAAG,UAAU;CAEjC,IAAI,eAAe,SAAS,GAAG,OAAO,mBAAmB,cAAc;CAEvE,OAAO;EAAE;EAAO;CAAO;AACzB;;AAGA,MAAa,eAAe,OAAO,aAAgD;CACjF,MAAM,UAAU,KAAK,QAAQ,QAAQ;CACrC,IAAI,CAAE,MAAM,IAAI,KAAK,QAAQ,CAAC,CAAC,OAAO,GAAI,OAAO,IAAI,iBAAiB,WAAW,KAAA,CAAS;CAG1F,iBAAiB,OAAO;CACxB,MAAM,kBAAkB,MAAM,eAAe,QAAQ;CACrD,IAAI,MAAM,eAAe,GAAG,OAAO;CAEnC,MAAM,kBAAkB,uBAAuB,eAAe;CAC9D,IAAI,MAAM,eAAe,GAAG,OAAO;CAEnC,MAAM,EAAE,OAAO,WAAW;CAG1B,MAAM,WAAqB;EAAE;EAAO,QAAQ,EAAE,OADlB,mBAAmB,OAAO,SAAS,CAAC,GAAG,QAAQ,GACJ,EAAE;CAAE;CAC3E,kBAAkB,QAAQ;CAE1B,OAAO;AACT"}
@@ -1,8 +1,7 @@
1
1
  import { isTask } from "../task.js";
2
+ import { toCamelCase, toKebabCase } from "../utils.js";
2
3
  import { err } from "ts-explicit-errors";
3
4
  // src/bask-file/task-index.ts
4
- const toKebabCase = (name) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`);
5
- const toCamelCase = (name) => name.replaceAll(/-[\da-z]/gv, (match) => match.slice(1).toUpperCase());
6
5
  /** Indexes the bask file's tasks under both spellings of their export names and aliases, collecting any errors. */
7
6
  const indexTasks = (baskFileExports) => {
8
7
  const errors = [];
@@ -1 +1 @@
1
- {"version":3,"file":"task-index.js","names":[],"sources":["../../src/bask-file/task-index.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFileExports } from \"#bask-file/bask-file.ts\"\nimport { isTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\ninterface TaskEntry {\n /** Export name as written in `bask.ts`, for error messages. */\n exportName: string\n /** Kebab-case export name, or `default` for a task that's only the default export. */\n name: string\n /** Kebab-case aliases from the task's `alias` option. */\n aliases: string[]\n task: Task\n}\n\nexport interface TaskIndex {\n /** Each entry under every name and alias that runs it. */\n byName: Map<string, TaskEntry>\n /** Each entry once, under its task, in export order. */\n byTask: Map<Task, TaskEntry>\n}\n\nconst toKebabCase = (name: string) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`)\nconst toCamelCase = (name: string) => name.replaceAll(/-[\\da-z]/gv, (match) => match.slice(1).toUpperCase())\n\n/** Indexes the bask file's tasks under both spellings of their export names and aliases, collecting any errors. */\nexport const indexTasks = (baskFileExports: BaskFileExports) => {\n const errors: Error[] = []\n\n // Put the default last so a task that's also exported by name keeps that name.\n const { default: defaultExport, ...namedExports } = baskFileExports\n const exportEntries = Object.entries(namedExports)\n if (defaultExport !== undefined) exportEntries.push([\"default\", defaultExport])\n\n // Index each task under its export name and kebab-case name, collecting tasks exported more than once.\n const byName: TaskIndex[\"byName\"] = new Map()\n const byTask: TaskIndex[\"byTask\"] = new Map()\n for (const [exportName, exportedTask] of exportEntries) {\n if (!isTask(exportedTask)) continue\n\n const existingEntry = byTask.get(exportedTask)\n // Point `default` at the existing entry, because exporting a named task as the default isn't a duplicate.\n if (existingEntry && exportName === \"default\") {\n byName.set(\"default\", existingEntry)\n continue\n }\n if (existingEntry) {\n errors.push(\n err(\n `task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`,\n undefined,\n ),\n )\n continue\n }\n\n const kebabName = toKebabCase(exportName)\n const entry: TaskEntry = { exportName, name: kebabName, aliases: [], task: exportedTask }\n byTask.set(exportedTask, entry)\n byName.set(exportName, entry)\n byName.set(kebabName, entry)\n }\n\n // Index each alias under every spelling, collecting aliases that are `default` or already taken.\n // Every export name is already indexed, so a clash with a name is reported against the alias.\n for (const entry of byTask.values()) {\n const aliases = [entry.task.options.alias ?? []].flat()\n\n for (const alias of aliases) {\n const kebabAlias = toKebabCase(alias)\n const camelAlias = toCamelCase(alias)\n\n if (kebabAlias === \"default\") {\n errors.push(\n err(\n `task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`,\n undefined,\n ),\n )\n continue\n }\n\n // Skip an alias that repeats the task's own name or another of its aliases.\n if (byName.get(kebabAlias) === entry) continue\n\n const keys = [alias, kebabAlias, camelAlias]\n const owner = keys.map((key) => byName.get(key)).find(Boolean)\n if (owner) {\n errors.push(\n err(\n `task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`,\n undefined,\n ),\n )\n } else {\n entry.aliases.push(kebabAlias)\n for (const key of keys) byName.set(key, entry)\n }\n }\n }\n\n const tasks: TaskIndex = { byName, byTask }\n return { tasks, errors }\n}\n"],"mappings":";;;AAuBA,MAAM,eAAe,SAAiB,KAAK,WAAW,YAAY,UAAU,IAAI,MAAM,YAAY,GAAG;AACrG,MAAM,eAAe,SAAiB,KAAK,WAAW,eAAe,UAAU,MAAM,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC;;AAG3G,MAAa,cAAc,oBAAqC;CAC9D,MAAM,SAAkB,CAAC;CAGzB,MAAM,EAAE,SAAS,eAAe,GAAG,iBAAiB;CACpD,MAAM,gBAAgB,OAAO,QAAQ,YAAY;CACjD,IAAI,kBAAkB,KAAA,GAAW,cAAc,KAAK,CAAC,WAAW,aAAa,CAAC;CAG9E,MAAM,yBAA8B,IAAI,IAAI;CAC5C,MAAM,yBAA8B,IAAI,IAAI;CAC5C,KAAK,MAAM,CAAC,YAAY,iBAAiB,eAAe;EACtD,IAAI,CAAC,OAAO,YAAY,GAAG;EAE3B,MAAM,gBAAgB,OAAO,IAAI,YAAY;EAE7C,IAAI,iBAAiB,eAAe,WAAW;GAC7C,OAAO,IAAI,WAAW,aAAa;GACnC;EACF;EACA,IAAI,eAAe;GACjB,OAAO,KACL,IACE,SAAS,WAAW,yBAAyB,cAAc,WAAW,mCACtE,KAAA,CACF,CACF;GACA;EACF;EAEA,MAAM,YAAY,YAAY,UAAU;EACxC,MAAM,QAAmB;GAAE;GAAY,MAAM;GAAW,SAAS,CAAC;GAAG,MAAM;EAAa;EACxF,OAAO,IAAI,cAAc,KAAK;EAC9B,OAAO,IAAI,YAAY,KAAK;EAC5B,OAAO,IAAI,WAAW,KAAK;CAC7B;CAIA,KAAK,MAAM,SAAS,OAAO,OAAO,GAAG;EACnC,MAAM,UAAU,CAAC,MAAM,KAAK,QAAQ,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK;EAEtD,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,aAAa,YAAY,KAAK;GACpC,MAAM,aAAa,YAAY,KAAK;GAEpC,IAAI,eAAe,WAAW;IAC5B,OAAO,KACL,IACE,SAAS,MAAM,WAAW,uEAC1B,KAAA,CACF,CACF;IACA;GACF;GAGA,IAAI,OAAO,IAAI,UAAU,MAAM,OAAO;GAEtC,MAAM,OAAO;IAAC;IAAO;IAAY;GAAU;GAC3C,MAAM,QAAQ,KAAK,KAAK,QAAQ,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO;GAC7D,IAAI,OACF,OAAO,KACL,IACE,SAAS,MAAM,WAAW,eAAe,MAAM,iBAAiB,MAAM,WAAW,iBACjF,KAAA,CACF,CACF;QACK;IACL,MAAM,QAAQ,KAAK,UAAU;IAC7B,KAAK,MAAM,OAAO,MAAM,OAAO,IAAI,KAAK,KAAK;GAC/C;EACF;CACF;CAGA,OAAO;EAAE,OAAA;GADkB;GAAQ;EACtB;EAAG;CAAO;AACzB"}
1
+ {"version":3,"file":"task-index.js","names":[],"sources":["../../src/bask-file/task-index.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFileExports } from \"#bask-file/bask-file.ts\"\nimport { isTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\nimport { toCamelCase, toKebabCase } from \"#utils.ts\"\n\nexport interface TaskEntry {\n /** Export name as written in `bask.ts`, for error messages. */\n exportName: string\n /** Kebab-case export name, or `default` for a task that's only the default export. */\n name: string\n /** Kebab-case aliases from the task's `alias` option. */\n aliases: string[]\n task: Task\n}\n\nexport interface TaskIndex {\n /** Each entry under every name and alias that runs it. */\n byName: Map<string, TaskEntry>\n /** Each entry once, under its task, in export order. */\n byTask: Map<Task, TaskEntry>\n}\n\n/** Indexes the bask file's tasks under both spellings of their export names and aliases, collecting any errors. */\nexport const indexTasks = (baskFileExports: BaskFileExports) => {\n const errors: Error[] = []\n\n // Put the default last so a task that's also exported by name keeps that name.\n const { default: defaultExport, ...namedExports } = baskFileExports\n const exportEntries = Object.entries(namedExports)\n if (defaultExport !== undefined) exportEntries.push([\"default\", defaultExport])\n\n // Index each task under its export name and kebab-case name, collecting tasks exported more than once.\n const byName: TaskIndex[\"byName\"] = new Map()\n const byTask: TaskIndex[\"byTask\"] = new Map()\n for (const [exportName, exportedTask] of exportEntries) {\n if (!isTask(exportedTask)) continue\n\n const existingEntry = byTask.get(exportedTask)\n // Point `default` at the existing entry, because exporting a named task as the default isn't a duplicate.\n if (existingEntry && exportName === \"default\") {\n byName.set(\"default\", existingEntry)\n continue\n }\n if (existingEntry) {\n errors.push(\n err(\n `task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`,\n undefined,\n ),\n )\n continue\n }\n\n const kebabName = toKebabCase(exportName)\n const entry: TaskEntry = { exportName, name: kebabName, aliases: [], task: exportedTask }\n byTask.set(exportedTask, entry)\n byName.set(exportName, entry)\n byName.set(kebabName, entry)\n }\n\n // Index each alias under every spelling, collecting aliases that are `default` or already taken.\n // Every export name is already indexed, so a clash with a name is reported against the alias.\n for (const entry of byTask.values()) {\n const aliases = [entry.task.options.alias ?? []].flat()\n\n for (const alias of aliases) {\n const kebabAlias = toKebabCase(alias)\n const camelAlias = toCamelCase(alias)\n\n if (kebabAlias === \"default\") {\n errors.push(\n err(\n `task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`,\n undefined,\n ),\n )\n continue\n }\n\n // Skip an alias that repeats the task's own name or another of its aliases.\n if (byName.get(kebabAlias) === entry) continue\n\n const keys = [alias, kebabAlias, camelAlias]\n const owner = keys.map((key) => byName.get(key)).find(Boolean)\n if (owner) {\n errors.push(\n err(\n `task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`,\n undefined,\n ),\n )\n } else {\n entry.aliases.push(kebabAlias)\n for (const key of keys) byName.set(key, entry)\n }\n }\n }\n\n const tasks: TaskIndex = { byName, byTask }\n return { tasks, errors }\n}\n"],"mappings":";;;;;AAyBA,MAAa,cAAc,oBAAqC;CAC9D,MAAM,SAAkB,CAAC;CAGzB,MAAM,EAAE,SAAS,eAAe,GAAG,iBAAiB;CACpD,MAAM,gBAAgB,OAAO,QAAQ,YAAY;CACjD,IAAI,kBAAkB,KAAA,GAAW,cAAc,KAAK,CAAC,WAAW,aAAa,CAAC;CAG9E,MAAM,yBAA8B,IAAI,IAAI;CAC5C,MAAM,yBAA8B,IAAI,IAAI;CAC5C,KAAK,MAAM,CAAC,YAAY,iBAAiB,eAAe;EACtD,IAAI,CAAC,OAAO,YAAY,GAAG;EAE3B,MAAM,gBAAgB,OAAO,IAAI,YAAY;EAE7C,IAAI,iBAAiB,eAAe,WAAW;GAC7C,OAAO,IAAI,WAAW,aAAa;GACnC;EACF;EACA,IAAI,eAAe;GACjB,OAAO,KACL,IACE,SAAS,WAAW,yBAAyB,cAAc,WAAW,mCACtE,KAAA,CACF,CACF;GACA;EACF;EAEA,MAAM,YAAY,YAAY,UAAU;EACxC,MAAM,QAAmB;GAAE;GAAY,MAAM;GAAW,SAAS,CAAC;GAAG,MAAM;EAAa;EACxF,OAAO,IAAI,cAAc,KAAK;EAC9B,OAAO,IAAI,YAAY,KAAK;EAC5B,OAAO,IAAI,WAAW,KAAK;CAC7B;CAIA,KAAK,MAAM,SAAS,OAAO,OAAO,GAAG;EACnC,MAAM,UAAU,CAAC,MAAM,KAAK,QAAQ,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK;EAEtD,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,aAAa,YAAY,KAAK;GACpC,MAAM,aAAa,YAAY,KAAK;GAEpC,IAAI,eAAe,WAAW;IAC5B,OAAO,KACL,IACE,SAAS,MAAM,WAAW,uEAC1B,KAAA,CACF,CACF;IACA;GACF;GAGA,IAAI,OAAO,IAAI,UAAU,MAAM,OAAO;GAEtC,MAAM,OAAO;IAAC;IAAO;IAAY;GAAU;GAC3C,MAAM,QAAQ,KAAK,KAAK,QAAQ,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO;GAC7D,IAAI,OACF,OAAO,KACL,IACE,SAAS,MAAM,WAAW,eAAe,MAAM,iBAAiB,MAAM,WAAW,iBACjF,KAAA,CACF,CACF;QACK;IACL,MAAM,QAAQ,KAAK,UAAU;IAC7B,KAAK,MAAM,OAAO,MAAM,OAAO,IAAI,KAAK,KAAK;GAC/C;EACF;CACF;CAGA,OAAO;EAAE,OAAA;GADkB;GAAQ;EACtB;EAAG;CAAO;AACzB"}
@@ -0,0 +1,37 @@
1
+ import { object } from "@optique/core/constructs";
2
+ import { commandLine, message } from "@optique/core/message";
3
+ import { optional, withDefault } from "@optique/core/modifiers";
4
+ import { argument, flag } from "@optique/core/primitives";
5
+ import { string } from "@optique/core/valueparser";
6
+ // src/cli/bask-parser.ts
7
+ /** Builds the parser for bask's own args, with `taskName` checking the task name. */
8
+ const toBaskParser = (taskName) => object({
9
+ list: withDefault(flag("-l", "--list", { description: message`List the tasks` }), false),
10
+ help: withDefault(flag("-h", "--help", { description: message`Show bask's help, or a task's help` }), false),
11
+ task: optional(argument(taskName, { description: message`The task to run (default: the default export)` }))
12
+ });
13
+ /** Accepts any task name, for parsing bask's args before bask.ts loads and its task names are known. */
14
+ const anyTaskName = string({ metavar: "TASK" });
15
+ /**
16
+ * Checks a task name against every name and alias that runs a task. It looks names up itself because `choice()` throws
17
+ * on an empty list, which a bask.ts with no tasks has.
18
+ */
19
+ const toTaskNameParser = (tasks) => ({
20
+ mode: "sync",
21
+ metavar: "TASK",
22
+ placeholder: "task",
23
+ parse: (input) => {
24
+ if (tasks.byName.has(input)) return {
25
+ success: true,
26
+ value: input
27
+ };
28
+ return {
29
+ success: false,
30
+ error: message`Unknown task ${input}. Run ${commandLine("bask --list")} to see the tasks.`
31
+ };
32
+ },
33
+ format: String
34
+ });
35
+ export { anyTaskName, toBaskParser, toTaskNameParser };
36
+
37
+ //# sourceMappingURL=bask-parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bask-parser.js","names":[],"sources":["../../src/cli/bask-parser.ts"],"sourcesContent":["import { object } from \"@optique/core/constructs\"\nimport { commandLine, message } from \"@optique/core/message\"\nimport { optional, withDefault } from \"@optique/core/modifiers\"\nimport { argument, flag } from \"@optique/core/primitives\"\nimport { string } from \"@optique/core/valueparser\"\nimport type { ValueParser } from \"@optique/core/valueparser\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\n\n/** Builds the parser for bask's own args, with `taskName` checking the task name. */\nexport const toBaskParser = (taskName: ValueParser<\"sync\", string>) =>\n object({\n list: withDefault(flag(\"-l\", \"--list\", { description: message`List the tasks` }), false),\n help: withDefault(flag(\"-h\", \"--help\", { description: message`Show bask's help, or a task's help` }), false),\n task: optional(argument(taskName, { description: message`The task to run (default: the default export)` })),\n })\n\n/** Accepts any task name, for parsing bask's args before bask.ts loads and its task names are known. */\nexport const anyTaskName = string({ metavar: \"TASK\" })\n\n/**\n * Checks a task name against every name and alias that runs a task. It looks names up itself because `choice()` throws\n * on an empty list, which a bask.ts with no tasks has.\n */\nexport const toTaskNameParser = (tasks: TaskIndex): ValueParser<\"sync\", string> => ({\n mode: \"sync\",\n metavar: \"TASK\",\n placeholder: \"task\",\n parse: (input) => {\n if (tasks.byName.has(input)) return { success: true, value: input }\n return {\n success: false,\n error: message`Unknown task ${input}. Run ${commandLine(\"bask --list\")} to see the tasks.`,\n }\n },\n format: String,\n})\n"],"mappings":";;;;;;;AAUA,MAAa,gBAAgB,aAC3B,OAAO;CACL,MAAM,YAAY,KAAK,MAAM,UAAU,EAAE,aAAa,OAAO,iBAAiB,CAAC,GAAG,KAAK;CACvF,MAAM,YAAY,KAAK,MAAM,UAAU,EAAE,aAAa,OAAO,qCAAqC,CAAC,GAAG,KAAK;CAC3G,MAAM,SAAS,SAAS,UAAU,EAAE,aAAa,OAAO,gDAAgD,CAAC,CAAC;AAC5G,CAAC;;AAGH,MAAa,cAAc,OAAO,EAAE,SAAS,OAAO,CAAC;;;;;AAMrD,MAAa,oBAAoB,WAAmD;CAClF,MAAM;CACN,SAAS;CACT,aAAa;CACb,QAAQ,UAAU;EAChB,IAAI,MAAM,OAAO,IAAI,KAAK,GAAG,OAAO;GAAE,SAAS;GAAM,OAAO;EAAM;EAClE,OAAO;GACL,SAAS;GACT,OAAO,OAAO,gBAAgB,MAAM,QAAQ,YAAY,aAAa,EAAE;EACzE;CACF;CACA,QAAQ;AACV"}
@@ -0,0 +1,32 @@
1
+ import { toOptiqueOutput } from "./optique.js";
2
+ import { toTaskParser } from "./task-parser.js";
3
+ import { commandLine, message, text } from "@optique/core/message";
4
+ import { formatDocPage } from "@optique/core/doc";
5
+ import { getDocPage } from "@optique/core/parser";
6
+ // src/cli/help.ts
7
+ const EMPTY_DOC_PAGE = { sections: [] };
8
+ const printHelpPage = (programName, page) => {
9
+ const helpPage = formatDocPage(programName, page, toOptiqueOutput(process.stdout));
10
+ process.stdout.write(`${helpPage.trimEnd()}\n`);
11
+ };
12
+ /** Prints bask's own help page, which points to `bask -h <task>` for a task's args. */
13
+ const printBaskHelp = (baskParser) => {
14
+ const page = getDocPage(baskParser) ?? EMPTY_DOC_PAGE;
15
+ printHelpPage("bask", {
16
+ ...page,
17
+ footer: message`Run ${commandLine("bask -h <task>")} to see a task's args.`
18
+ });
19
+ };
20
+ /** Prints a task's help page, with its `desc` above the usage line. */
21
+ const printTaskHelp = (entry) => {
22
+ const { name, task } = entry;
23
+ const page = getDocPage(toTaskParser(task.options)) ?? EMPTY_DOC_PAGE;
24
+ const { desc } = task.options;
25
+ printHelpPage(`bask ${name}`, desc === void 0 ? page : {
26
+ ...page,
27
+ brief: message`${text(desc)}`
28
+ });
29
+ };
30
+ export { printBaskHelp, printTaskHelp };
31
+
32
+ //# sourceMappingURL=help.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help.js","names":[],"sources":["../../src/cli/help.ts"],"sourcesContent":["import type { DocPage } from \"@optique/core/doc\"\nimport { formatDocPage } from \"@optique/core/doc\"\nimport { commandLine, message, text } from \"@optique/core/message\"\nimport type { Parser } from \"@optique/core/parser\"\nimport { getDocPage } from \"@optique/core/parser\"\n\nimport type { TaskEntry } from \"#bask-file/task-index.ts\"\nimport { toOptiqueOutput } from \"#cli/optique.ts\"\nimport { toTaskParser } from \"#cli/task-parser.ts\"\n\nconst EMPTY_DOC_PAGE: DocPage = { sections: [] }\n\nconst printHelpPage = (programName: string, page: DocPage) => {\n const helpPage = formatDocPage(programName, page, toOptiqueOutput(process.stdout))\n process.stdout.write(`${helpPage.trimEnd()}\\n`)\n}\n\n/** Prints bask's own help page, which points to `bask -h <task>` for a task's args. */\nexport const printBaskHelp = (baskParser: Parser) => {\n const page = getDocPage(baskParser) ?? EMPTY_DOC_PAGE\n printHelpPage(\"bask\", { ...page, footer: message`Run ${commandLine(\"bask -h <task>\")} to see a task's args.` })\n}\n\n/** Prints a task's help page, with its `desc` above the usage line. */\nexport const printTaskHelp = (entry: TaskEntry) => {\n const { name, task } = entry\n const page = getDocPage(toTaskParser(task.options)) ?? EMPTY_DOC_PAGE\n const { desc } = task.options\n printHelpPage(`bask ${name}`, desc === undefined ? page : { ...page, brief: message`${text(desc)}` })\n}\n"],"mappings":";;;;;;AAUA,MAAM,iBAA0B,EAAE,UAAU,CAAC,EAAE;AAE/C,MAAM,iBAAiB,aAAqB,SAAkB;CAC5D,MAAM,WAAW,cAAc,aAAa,MAAM,gBAAgB,QAAQ,MAAM,CAAC;CACjF,QAAQ,OAAO,MAAM,GAAG,SAAS,QAAQ,EAAE,GAAG;AAChD;;AAGA,MAAa,iBAAiB,eAAuB;CACnD,MAAM,OAAO,WAAW,UAAU,KAAK;CACvC,cAAc,QAAQ;EAAE,GAAG;EAAM,QAAQ,OAAO,OAAO,YAAY,gBAAgB,EAAE;CAAwB,CAAC;AAChH;;AAGA,MAAa,iBAAiB,UAAqB;CACjD,MAAM,EAAE,MAAM,SAAS;CACvB,MAAM,OAAO,WAAW,aAAa,KAAK,OAAO,CAAC,KAAK;CACvD,MAAM,EAAE,SAAS,KAAK;CACtB,cAAc,QAAQ,QAAQ,SAAS,KAAA,IAAY,OAAO;EAAE,GAAG;EAAM,OAAO,OAAO,GAAG,KAAK,IAAI;CAAI,CAAC;AACtG"}
@@ -0,0 +1,5 @@
1
+ import { NoArgs } from "../task/args.js";
2
+ import { Task } from "../task.js";
3
+ import "../bask-file/task-index.js";
4
+ export declare const list: Task<NoArgs>;
5
+ //# sourceMappingURL=list.d.ts.map
@@ -1,11 +1,18 @@
1
- import { getLoadedBaskFile } from "./loaded.js";
1
+ import { toTaskParser } from "./task-parser.js";
2
+ import { getLoadedBaskFile } from "../loaded-bask-file.js";
2
3
  import { task } from "../task.js";
3
- // src/bask-file/list.ts
4
+ import { formatUsage } from "@optique/core/usage";
5
+ // src/cli/list.ts
4
6
  const collator = new Intl.Collator();
5
7
  const formatAliases = (aliases) => {
6
8
  if (aliases.length === 0) return;
7
9
  return `[${aliases.length === 1 ? "alias" : "aliases"}: ${aliases.join(", ")}]`;
8
10
  };
11
+ /** Formats a task's args as its usage line, without the task name. */
12
+ const formatArgs = (name, parser) => {
13
+ if (parser.usage.length === 0) return;
14
+ return formatUsage(name, parser.usage, { colors: false }).slice(name.length + 1);
15
+ };
9
16
  const formatTaskList = (tasks) => {
10
17
  const defaultEntry = tasks.byName.get("default");
11
18
  const rows = [...tasks.byTask.values()].filter((entry) => !entry.task.options.hidden).map((entry) => {
@@ -13,7 +20,8 @@ const formatTaskList = (tasks) => {
13
20
  const comment = [
14
21
  entry.task.options.desc,
15
22
  defaultMarker,
16
- formatAliases(entry.aliases)
23
+ formatAliases(entry.aliases),
24
+ formatArgs(entry.name, toTaskParser(entry.task.options))
17
25
  ].filter(Boolean).join(" ");
18
26
  return {
19
27
  name: entry.name,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list.js","names":[],"sources":["../../src/cli/list.ts"],"sourcesContent":["import { formatUsage } from \"@optique/core/usage\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { toTaskParser } from \"#cli/task-parser.ts\"\nimport type { TaskParser } from \"#cli/task-parser.ts\"\nimport { getLoadedBaskFile } from \"#loaded-bask-file.ts\"\nimport { task } from \"#task.ts\"\n\nconst collator = new Intl.Collator()\n\nconst formatAliases = (aliases: string[]) => {\n if (aliases.length === 0) return\n return `[${aliases.length === 1 ? \"alias\" : \"aliases\"}: ${aliases.join(\", \")}]`\n}\n\n/** Formats a task's args as its usage line, without the task name. */\nconst formatArgs = (name: string, parser: TaskParser) => {\n if (parser.usage.length === 0) return\n // Format with the task's name and then remove it, because `formatUsage` requires a program name.\n return formatUsage(name, parser.usage, { colors: false }).slice(name.length + 1)\n}\n\nexport const formatTaskList = (tasks: TaskIndex) => {\n const defaultEntry = tasks.byName.get(\"default\")\n\n const rows = [...tasks.byTask.values()]\n .filter((entry) => !entry.task.options.hidden)\n .map((entry) => {\n const defaultMarker = entry === defaultEntry && entry.name !== \"default\" ? \"[default]\" : undefined\n const comment = [\n entry.task.options.desc,\n defaultMarker,\n formatAliases(entry.aliases),\n formatArgs(entry.name, toTaskParser(entry.task.options)),\n ]\n .filter(Boolean)\n .join(\" \")\n return { name: entry.name, comment }\n })\n .toSorted((a, b) => collator.compare(a.name, b.name))\n\n const nameWidth = Math.max(...rows.map((row) => row.name.length))\n const lines = rows.map(({ name, comment }) =>\n comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`,\n )\n return [\"Available tasks:\", ...lines].join(\"\\n\")\n}\n\nexport const list = task(() => {\n const { tasks } = getLoadedBaskFile()\n console.log(formatTaskList(tasks))\n})\n"],"mappings":";;;;;AAQA,MAAM,WAAW,IAAI,KAAK,SAAS;AAEnC,MAAM,iBAAiB,YAAsB;CAC3C,IAAI,QAAQ,WAAW,GAAG;CAC1B,OAAO,IAAI,QAAQ,WAAW,IAAI,UAAU,UAAU,IAAI,QAAQ,KAAK,IAAI,EAAE;AAC/E;;AAGA,MAAM,cAAc,MAAc,WAAuB;CACvD,IAAI,OAAO,MAAM,WAAW,GAAG;CAE/B,OAAO,YAAY,MAAM,OAAO,OAAO,EAAE,QAAQ,MAAM,CAAC,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC;AACjF;AAEA,MAAa,kBAAkB,UAAqB;CAClD,MAAM,eAAe,MAAM,OAAO,IAAI,SAAS;CAE/C,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,OAAO,CAAC,CAAC,CACpC,QAAQ,UAAU,CAAC,MAAM,KAAK,QAAQ,MAAM,CAAC,CAC7C,KAAK,UAAU;EACd,MAAM,gBAAgB,UAAU,gBAAgB,MAAM,SAAS,YAAY,cAAc,KAAA;EACzF,MAAM,UAAU;GACd,MAAM,KAAK,QAAQ;GACnB;GACA,cAAc,MAAM,OAAO;GAC3B,WAAW,MAAM,MAAM,aAAa,MAAM,KAAK,OAAO,CAAC;EACzD,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;EACX,OAAO;GAAE,MAAM,MAAM;GAAM;EAAQ;CACrC,CAAC,CAAC,CACD,UAAU,GAAG,MAAM,SAAS,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC;CAEtD,MAAM,YAAY,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,IAAI,KAAK,MAAM,CAAC;CAIhE,OAAO,CAAC,oBAAoB,GAHd,KAAK,KAAK,EAAE,MAAM,cAC9B,UAAU,OAAO,KAAK,OAAO,SAAS,EAAE,KAAK,YAAY,OAAO,MAE/B,CAAC,CAAC,CAAC,KAAK,IAAI;AACjD;AAEA,MAAa,OAAO,WAAW;CAC7B,MAAM,EAAE,UAAU,kBAAkB;CACpC,QAAQ,IAAI,eAAe,KAAK,CAAC;AACnC,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { styleText } from "node:util";
2
+ import { runParser } from "@optique/core/facade";
3
+ // src/cli/optique.ts
4
+ /**
5
+ * Returns Optique's output settings for `stream`: whether to use color, and the width to wrap to. Ask `styleText` about
6
+ * color so Optique follows the same rules as bask's own error line, including `NO_COLOR`.
7
+ */
8
+ const toOptiqueOutput = (stream) => ({
9
+ colors: styleText("red", "x", { stream }) !== "x",
10
+ ...stream.columns > 0 && { maxWidth: stream.columns }
11
+ });
12
+ /**
13
+ * Parses `argv`. Returns `undefined` when it's invalid, after Optique prints its usage line and error to stderr. The
14
+ * return type is written out because `runParser`'s sync overload leaves out what `onError` returns.
15
+ */
16
+ const parseWithOptique = (parser, programName, argv) => runParser(parser, programName, argv, {
17
+ ...toOptiqueOutput(process.stderr),
18
+ stderr: (line) => {
19
+ process.stderr.write(`${line}\n`);
20
+ },
21
+ onError: () => {}
22
+ });
23
+ export { parseWithOptique, toOptiqueOutput };
24
+
25
+ //# sourceMappingURL=optique.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"optique.js","names":[],"sources":["../../src/cli/optique.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\nimport { runParser } from \"@optique/core/facade\"\nimport type { Parser } from \"@optique/core/parser\"\n\n/**\n * Returns Optique's output settings for `stream`: whether to use color, and the width to wrap to. Ask `styleText` about\n * color so Optique follows the same rules as bask's own error line, including `NO_COLOR`.\n */\nexport const toOptiqueOutput = (stream: NodeJS.WriteStream) => ({\n colors: styleText(\"red\", \"x\", { stream }) !== \"x\",\n // Leave out a width of 0, which some terminals report and which wraps every usage term onto its own line.\n ...(stream.columns > 0 && { maxWidth: stream.columns }),\n})\n\n/**\n * Parses `argv`. Returns `undefined` when it's invalid, after Optique prints its usage line and error to stderr. The\n * return type is written out because `runParser`'s sync overload leaves out what `onError` returns.\n */\nexport const parseWithOptique = <T>(parser: Parser<\"sync\", T>, programName: string, argv: string[]): T | undefined =>\n runParser(parser, programName, argv, {\n ...toOptiqueOutput(process.stderr),\n stderr: (line) => {\n process.stderr.write(`${line}\\n`)\n },\n onError: () => {\n /* empty */\n },\n })\n"],"mappings":";;;;;;;AASA,MAAa,mBAAmB,YAAgC;CAC9D,QAAQ,UAAU,OAAO,KAAK,EAAE,OAAO,CAAC,MAAM;CAE9C,GAAI,OAAO,UAAU,KAAK,EAAE,UAAU,OAAO,QAAQ;AACvD;;;;;AAMA,MAAa,oBAAuB,QAA2B,aAAqB,SAClF,UAAU,QAAQ,aAAa,MAAM;CACnC,GAAG,gBAAgB,QAAQ,MAAM;CACjC,SAAS,SAAS;EAChB,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;CAClC;CACA,eAAe,CAEf;AACF,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { styleText } from "node:util";
2
+ // src/cli/print-error.ts
3
+ const printError = (message) => {
4
+ process.stderr.write(`${styleText(["bold", "red"], "error:", { stream: process.stderr })} ${message}\n`);
5
+ };
6
+ export { printError };
7
+
8
+ //# sourceMappingURL=print-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"print-error.js","names":[],"sources":["../../src/cli/print-error.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\n// Write to `process.stderr` directly because Bun colors all `console.error` output red in a terminal.\nexport const printError = (message: string) => {\n process.stderr.write(`${styleText([\"bold\", \"red\"], \"error:\", { stream: process.stderr })} ${message}\\n`)\n}\n"],"mappings":";;AAGA,MAAa,cAAc,YAAoB;CAC7C,QAAQ,OAAO,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,GAAG,UAAU,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG,QAAQ,GAAG;AACzG"}
@@ -0,0 +1,60 @@
1
+ import { loadBaskFile } from "../bask-file/bask-file.js";
2
+ import { anyTaskName, toBaskParser, toTaskNameParser } from "./bask-parser.js";
3
+ import { printBaskHelp, printTaskHelp } from "./help.js";
4
+ import { formatTaskList, list } from "./list.js";
5
+ import { parseWithOptique } from "./optique.js";
6
+ import { runTask } from "./run-task.js";
7
+ import { splitArgs } from "./split-args.js";
8
+ import { checkAllTaskArgs, toTaskParser } from "./task-parser.js";
9
+ import { runWithArgs } from "../task.js";
10
+ import { isErr } from "ts-explicit-errors";
11
+ // src/cli/run-bask.ts
12
+ const ARGS_ERROR_EXIT_CODE = 2;
13
+ /** Loads bask.ts and checks its tasks' arg declarations. */
14
+ const loadTasks = async (baskPath) => {
15
+ const baskFile = await loadBaskFile(baskPath);
16
+ if (isErr(baskFile)) return baskFile;
17
+ const checkResult = checkAllTaskArgs(baskFile.tasks);
18
+ if (isErr(checkResult)) return checkResult;
19
+ return baskFile.tasks;
20
+ };
21
+ /**
22
+ * Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. Returns the exit code, which is
23
+ * 2 when Optique has already reported invalid args. An error is one of bask's own problems.
24
+ */
25
+ const runBask = async (args, baskPath) => {
26
+ const { baskArgs, taskName, taskArgs } = splitArgs(args);
27
+ const baskInput = taskName === void 0 ? baskArgs : [...baskArgs, taskName];
28
+ const baskParser = toBaskParser(anyTaskName);
29
+ const baskFlags = parseWithOptique(baskParser, "bask", baskInput);
30
+ if (!baskFlags) return ARGS_ERROR_EXIT_CODE;
31
+ if (baskFlags.help && taskName === void 0) {
32
+ printBaskHelp(baskParser);
33
+ const listedTasks = await loadTasks(baskPath);
34
+ if (isErr(listedTasks)) return listedTasks;
35
+ process.stdout.write(`\n${formatTaskList(listedTasks)}\n`);
36
+ return 0;
37
+ }
38
+ const tasks = await loadTasks(baskPath);
39
+ if (isErr(tasks)) return tasks;
40
+ if (taskName !== void 0 && !parseWithOptique(toBaskParser(toTaskNameParser(tasks)), "bask", baskInput)) return ARGS_ERROR_EXIT_CODE;
41
+ const selectedTaskEntry = tasks.byName.get(taskName ?? "default");
42
+ if (baskFlags.help && selectedTaskEntry) {
43
+ printTaskHelp(selectedTaskEntry);
44
+ return 0;
45
+ }
46
+ if (baskFlags.list || !selectedTaskEntry) {
47
+ const listResult = await runTask(tasks, "list", async () => list());
48
+ if (isErr(listResult)) return listResult;
49
+ return 0;
50
+ }
51
+ const { name, task } = selectedTaskEntry;
52
+ const parsedTaskArgs = parseWithOptique(toTaskParser(task.options), `bask ${name}`, taskArgs);
53
+ if (!parsedTaskArgs) return ARGS_ERROR_EXIT_CODE;
54
+ const runResult = await runTask(tasks, name, async () => runWithArgs(task, parsedTaskArgs));
55
+ if (isErr(runResult)) return runResult;
56
+ return 0;
57
+ };
58
+ export { runBask };
59
+
60
+ //# sourceMappingURL=run-bask.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-bask.js","names":[],"sources":["../../src/cli/run-bask.ts"],"sourcesContent":["import type { Result } from \"ts-explicit-errors\"\nimport { isErr } from \"ts-explicit-errors\"\n\nimport { loadBaskFile } from \"#bask-file/bask-file.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { anyTaskName, toBaskParser, toTaskNameParser } from \"#cli/bask-parser.ts\"\nimport { printBaskHelp, printTaskHelp } from \"#cli/help.ts\"\nimport { formatTaskList, list } from \"#cli/list.ts\"\nimport { parseWithOptique } from \"#cli/optique.ts\"\nimport { runTask } from \"#cli/run-task.ts\"\nimport { splitArgs } from \"#cli/split-args.ts\"\nimport { checkAllTaskArgs, toTaskParser } from \"#cli/task-parser.ts\"\nimport { runWithArgs } from \"#task.ts\"\n\nconst ARGS_ERROR_EXIT_CODE = 2\n\n/** Loads bask.ts and checks its tasks' arg declarations. */\nconst loadTasks = async (baskPath: string): Promise<Result<TaskIndex>> => {\n const baskFile = await loadBaskFile(baskPath)\n if (isErr(baskFile)) return baskFile\n\n const checkResult = checkAllTaskArgs(baskFile.tasks)\n if (isErr(checkResult)) return checkResult\n\n return baskFile.tasks\n}\n\n/**\n * Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. Returns the exit code, which is\n * 2 when Optique has already reported invalid args. An error is one of bask's own problems.\n */\nexport const runBask = async (args: string[], baskPath: string): Promise<Result<number>> => {\n const { baskArgs, taskName, taskArgs } = splitArgs(args)\n const baskInput = taskName === undefined ? baskArgs : [...baskArgs, taskName]\n\n // Check bask's flags before loading bask.ts, so they work without one and before its top-level code runs.\n const baskParser = toBaskParser(anyTaskName)\n const baskFlags = parseWithOptique(baskParser, \"bask\", baskInput)\n if (!baskFlags) return ARGS_ERROR_EXIT_CODE\n\n if (baskFlags.help && taskName === undefined) {\n printBaskHelp(baskParser)\n const listedTasks = await loadTasks(baskPath)\n if (isErr(listedTasks)) return listedTasks\n process.stdout.write(`\\n${formatTaskList(listedTasks)}\\n`)\n return 0\n }\n\n const tasks = await loadTasks(baskPath)\n if (isErr(tasks)) return tasks\n\n // Check the task name now that bask.ts has loaded, so an unknown task gets Optique's error.\n const isUnknownTask =\n taskName !== undefined && !parseWithOptique(toBaskParser(toTaskNameParser(tasks)), \"bask\", baskInput)\n if (isUnknownTask) return ARGS_ERROR_EXIT_CODE\n\n const selectedTaskEntry = tasks.byName.get(taskName ?? \"default\")\n\n if (baskFlags.help && selectedTaskEntry) {\n printTaskHelp(selectedTaskEntry)\n return 0\n }\n\n // List the tasks when asked, or when no task is named and there's no default to run.\n if (baskFlags.list || !selectedTaskEntry) {\n const listResult = await runTask(tasks, \"list\", async () => list())\n if (isErr(listResult)) return listResult\n return 0\n }\n\n const { name, task } = selectedTaskEntry\n const parsedTaskArgs = parseWithOptique(toTaskParser(task.options), `bask ${name}`, taskArgs)\n if (!parsedTaskArgs) return ARGS_ERROR_EXIT_CODE\n\n const runResult = await runTask(tasks, name, async () => runWithArgs(task, parsedTaskArgs))\n if (isErr(runResult)) return runResult\n return 0\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAM,uBAAuB;;AAG7B,MAAM,YAAY,OAAO,aAAiD;CACxE,MAAM,WAAW,MAAM,aAAa,QAAQ;CAC5C,IAAI,MAAM,QAAQ,GAAG,OAAO;CAE5B,MAAM,cAAc,iBAAiB,SAAS,KAAK;CACnD,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,OAAO,SAAS;AAClB;;;;;AAMA,MAAa,UAAU,OAAO,MAAgB,aAA8C;CAC1F,MAAM,EAAE,UAAU,UAAU,aAAa,UAAU,IAAI;CACvD,MAAM,YAAY,aAAa,KAAA,IAAY,WAAW,CAAC,GAAG,UAAU,QAAQ;CAG5E,MAAM,aAAa,aAAa,WAAW;CAC3C,MAAM,YAAY,iBAAiB,YAAY,QAAQ,SAAS;CAChE,IAAI,CAAC,WAAW,OAAO;CAEvB,IAAI,UAAU,QAAQ,aAAa,KAAA,GAAW;EAC5C,cAAc,UAAU;EACxB,MAAM,cAAc,MAAM,UAAU,QAAQ;EAC5C,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,QAAQ,OAAO,MAAM,KAAK,eAAe,WAAW,EAAE,GAAG;EACzD,OAAO;CACT;CAEA,MAAM,QAAQ,MAAM,UAAU,QAAQ;CACtC,IAAI,MAAM,KAAK,GAAG,OAAO;CAKzB,IADE,aAAa,KAAA,KAAa,CAAC,iBAAiB,aAAa,iBAAiB,KAAK,CAAC,GAAG,QAAQ,SAAS,GACnF,OAAO;CAE1B,MAAM,oBAAoB,MAAM,OAAO,IAAI,YAAY,SAAS;CAEhE,IAAI,UAAU,QAAQ,mBAAmB;EACvC,cAAc,iBAAiB;EAC/B,OAAO;CACT;CAGA,IAAI,UAAU,QAAQ,CAAC,mBAAmB;EACxC,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,YAAY,KAAK,CAAC;EAClE,IAAI,MAAM,UAAU,GAAG,OAAO;EAC9B,OAAO;CACT;CAEA,MAAM,EAAE,MAAM,SAAS;CACvB,MAAM,iBAAiB,iBAAiB,aAAa,KAAK,OAAO,GAAG,QAAQ,QAAQ,QAAQ;CAC5F,IAAI,CAAC,gBAAgB,OAAO;CAE5B,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,YAAY,MAAM,cAAc,CAAC;CAC1F,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,OAAO;AACT"}
@@ -0,0 +1,21 @@
1
+ import { hasHiddenOutput } from "../shell/command.js";
2
+ import { getFailedTask } from "../task.js";
3
+ import bun from "bun";
4
+ import { attempt, err } from "ts-explicit-errors";
5
+ // src/cli/run-task.ts
6
+ /** Runs a task and returns a failed command as an error that names the innermost task that failed. */
7
+ const runTask = async (tasks, taskName, run) => {
8
+ const error = await attempt(run);
9
+ if (!error) return;
10
+ if (!(error instanceof bun.$.ShellError)) throw error;
11
+ if (hasHiddenOutput(error)) {
12
+ process.stdout.write(error.stdout);
13
+ process.stderr.write(error.stderr);
14
+ }
15
+ const failedTask = getFailedTask(error);
16
+ const failedName = (failedTask && tasks.byTask.get(failedTask))?.name ?? taskName;
17
+ return err(`task '${failedName}' failed with exit code ${error.exitCode}`, void 0, { exitCode: error.exitCode });
18
+ };
19
+ export { runTask };
20
+
21
+ //# sourceMappingURL=run-task.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-task.js","names":[],"sources":["../../src/cli/run-task.ts"],"sourcesContent":["import bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err } from \"ts-explicit-errors\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { hasHiddenOutput } from \"#shell/command.ts\"\nimport { getFailedTask } from \"#task.ts\"\n\n/** Runs a task and returns a failed command as an error that names the innermost task that failed. */\nexport const runTask = async (tasks: TaskIndex, taskName: string, run: () => Promise<void>): Promise<Result> => {\n const error = await attempt(run)\n if (!error) return\n // Rethrow anything else, because a bug in a task file needs its stack trace.\n if (!(error instanceof bun.$.ShellError)) throw error\n\n // Print the output of a command that hid it, because it usually explains the failure.\n if (hasHiddenOutput(error)) {\n process.stdout.write(error.stdout)\n process.stderr.write(error.stderr)\n }\n\n const failedTask = getFailedTask(error)\n const failedEntry = failedTask && tasks.byTask.get(failedTask)\n // Fall back to the task you ran, because a task that isn't exported has no name.\n const failedName = failedEntry?.name ?? taskName\n return err(`task '${failedName}' failed with exit code ${error.exitCode}`, undefined, { exitCode: error.exitCode })\n}\n"],"mappings":";;;;;;AASA,MAAa,UAAU,OAAO,OAAkB,UAAkB,QAA8C;CAC9G,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,IAAI,CAAC,OAAO;CAEZ,IAAI,EAAE,iBAAiB,IAAI,EAAE,aAAa,MAAM;CAGhD,IAAI,gBAAgB,KAAK,GAAG;EAC1B,QAAQ,OAAO,MAAM,MAAM,MAAM;EACjC,QAAQ,OAAO,MAAM,MAAM,MAAM;CACnC;CAEA,MAAM,aAAa,cAAc,KAAK;CAGtC,MAAM,cAFc,cAAc,MAAM,OAAO,IAAI,UAAU,EAAA,EAE7B,QAAQ;CACxC,OAAO,IAAI,SAAS,WAAW,0BAA0B,MAAM,YAAY,KAAA,GAAW,EAAE,UAAU,MAAM,SAAS,CAAC;AACpH"}
@@ -0,0 +1,25 @@
1
+ import { parseArgs } from "node:util";
2
+ // src/cli/split-args.ts
3
+ /** Splits `args` at the task name, so flags before it are bask's and args after it are the task's. */
4
+ const splitArgs = (args) => {
5
+ const { tokens } = parseArgs({
6
+ args,
7
+ strict: false,
8
+ allowPositionals: true,
9
+ tokens: true
10
+ });
11
+ const taskNameIndex = tokens.find((token) => token.kind === "positional")?.index;
12
+ if (taskNameIndex === void 0) return {
13
+ baskArgs: args,
14
+ taskName: void 0,
15
+ taskArgs: []
16
+ };
17
+ return {
18
+ baskArgs: args.slice(0, taskNameIndex),
19
+ taskName: args[taskNameIndex],
20
+ taskArgs: args.slice(taskNameIndex + 1)
21
+ };
22
+ };
23
+ export { splitArgs };
24
+
25
+ //# sourceMappingURL=split-args.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"split-args.js","names":[],"sources":["../../src/cli/split-args.ts"],"sourcesContent":["import { parseArgs } from \"node:util\"\n\n/** Splits `args` at the task name, so flags before it are bask's and args after it are the task's. */\nexport const splitArgs = (args: string[]) => {\n const { tokens } = parseArgs({ args, strict: false, allowPositionals: true, tokens: true })\n const taskNameIndex = tokens.find((token) => token.kind === \"positional\")?.index\n if (taskNameIndex === undefined) return { baskArgs: args, taskName: undefined, taskArgs: [] }\n return {\n baskArgs: args.slice(0, taskNameIndex),\n taskName: args[taskNameIndex],\n taskArgs: args.slice(taskNameIndex + 1),\n }\n}\n"],"mappings":";;;AAGA,MAAa,aAAa,SAAmB;CAC3C,MAAM,EAAE,WAAW,UAAU;EAAE;EAAM,QAAQ;EAAO,kBAAkB;EAAM,QAAQ;CAAK,CAAC;CAC1F,MAAM,gBAAgB,OAAO,MAAM,UAAU,MAAM,SAAS,YAAY,CAAC,EAAE;CAC3E,IAAI,kBAAkB,KAAA,GAAW,OAAO;EAAE,UAAU;EAAM,UAAU,KAAA;EAAW,UAAU,CAAC;CAAE;CAC5F,OAAO;EACL,UAAU,KAAK,MAAM,GAAG,aAAa;EACrC,UAAU,KAAK;EACf,UAAU,KAAK,MAAM,gBAAgB,CAAC;CACxC;AACF"}
@@ -0,0 +1,49 @@
1
+ import { joinBaskFileErrors } from "../bask-file/bask-file.js";
2
+ import { toEmptyArgs } from "../task/args.js";
3
+ import { toKebabCase } from "../utils.js";
4
+ import { object } from "@optique/core/constructs";
5
+ import { message, text } from "@optique/core/message";
6
+ import { map, multiple, optional, withDefault } from "@optique/core/modifiers";
7
+ import { argument, constant, flag, option } from "@optique/core/primitives";
8
+ import { string } from "@optique/core/valueparser";
9
+ import { attempt, err, isErr } from "ts-explicit-errors";
10
+ // src/cli/task-parser.ts
11
+ const SHORT_FLAG = /^[\dA-Za-z]$/v;
12
+ const toArgParser = (name, arg) => {
13
+ const longName = `--${toKebabCase(name)}`;
14
+ const names = arg.short === void 0 ? [longName] : [`-${arg.short}`, longName];
15
+ const argOptions = arg.desc === void 0 ? {} : { description: message`${text(arg.desc)}` };
16
+ if (arg.type === "string") return optional(option(...names, string({ metavar: "VALUE" }), argOptions));
17
+ return withDefault(flag(...names, argOptions), false);
18
+ };
19
+ /** Builds the Optique parser for a task's args. Throws Optique's error when two args share a flag. */
20
+ const toTaskParser = (options) => {
21
+ const argParsers = Object.entries(options.args ?? {}).map(([name, arg]) => [name, toArgParser(name, arg)]);
22
+ const positionals = options.positionals ? multiple(argument(string({ metavar: "ARG" }))) : constant([]);
23
+ const emptyArgs = toEmptyArgs(options);
24
+ const argsParser = object(Object.fromEntries(argParsers));
25
+ return map(object({
26
+ args: argsParser,
27
+ positionals
28
+ }), (parsed) => ({
29
+ args: {
30
+ ...emptyArgs.args,
31
+ ...parsed.args
32
+ },
33
+ positionals: parsed.positionals
34
+ }));
35
+ };
36
+ /** Checks one task's arg declarations, and returns why they're invalid. */
37
+ const checkTaskArgs = (exportName, options) => {
38
+ for (const [argName, { short }] of Object.entries(options.args ?? {})) if (short !== void 0 && !SHORT_FLAG.test(short)) return err(`task '${exportName}' has arg '${argName}' with short '${short}'. A short must be one letter or digit.`, void 0);
39
+ const parser = attempt(() => toTaskParser(options));
40
+ if (isErr(parser)) return err(`task '${exportName}' has invalid args: ${parser.message}`, void 0);
41
+ };
42
+ /** Checks every task's arg declarations, and returns every problem as a `bask.ts` problem. */
43
+ const checkAllTaskArgs = (tasks) => {
44
+ const taskArgErrors = Array.from(tasks.byTask.values(), ({ exportName, task }) => checkTaskArgs(exportName, task.options)).filter(isErr);
45
+ if (taskArgErrors.length > 0) return joinBaskFileErrors(taskArgErrors);
46
+ };
47
+ export { checkAllTaskArgs, toTaskParser };
48
+
49
+ //# sourceMappingURL=task-parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task-parser.js","names":[],"sources":["../../src/cli/task-parser.ts"],"sourcesContent":["import { object } from \"@optique/core/constructs\"\nimport { message, text } from \"@optique/core/message\"\nimport { map, multiple, optional, withDefault } from \"@optique/core/modifiers\"\nimport type { Parser } from \"@optique/core/parser\"\nimport { argument, constant, flag, option } from \"@optique/core/primitives\"\nimport type { OptionName } from \"@optique/core/usage\"\nimport { string } from \"@optique/core/valueparser\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, isErr } from \"ts-explicit-errors\"\n\nimport { joinBaskFileErrors } from \"#bask-file/bask-file.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { toEmptyArgs } from \"#task/args.ts\"\nimport type { ArgValue, ParsedTaskArgs, TaskArg, TaskArgOptions } from \"#task/args.ts\"\nimport { toKebabCase } from \"#utils.ts\"\n\nexport type TaskParser = Parser<\"sync\", ParsedTaskArgs>\n\ntype ArgParser = Parser<\"sync\", ArgValue>\n\nconst SHORT_FLAG = /^[\\dA-Za-z]$/v\n\nconst toArgParser = (name: string, arg: TaskArg): ArgParser => {\n const longName = `--${toKebabCase(name)}` as const\n const names: readonly [OptionName, ...OptionName[]] =\n arg.short === undefined ? [longName] : [`-${arg.short}`, longName]\n const argOptions = arg.desc === undefined ? {} : { description: message`${text(arg.desc)}` }\n if (arg.type === \"string\") return optional(option(...names, string({ metavar: \"VALUE\" }), argOptions))\n return withDefault(flag(...names, argOptions), false)\n}\n\n/** Builds the Optique parser for a task's args. Throws Optique's error when two args share a flag. */\nexport const toTaskParser = (options: TaskArgOptions): TaskParser => {\n const argParsers = Object.entries(options.args ?? {}).map(([name, arg]): [string, ArgParser] => [\n name,\n toArgParser(name, arg),\n ])\n const positionals = options.positionals ? multiple(argument(string({ metavar: \"ARG\" }))) : constant([])\n const emptyArgs = toEmptyArgs(options)\n // Merge over the empty args because Optique leaves out a string arg that wasn't passed.\n const argsParser = object(Object.fromEntries(argParsers))\n return map(object({ args: argsParser, positionals }), (parsed) => ({\n args: { ...emptyArgs.args, ...parsed.args },\n positionals: parsed.positionals,\n }))\n}\n\n/** Checks one task's arg declarations, and returns why they're invalid. */\nconst checkTaskArgs = (exportName: string, options: TaskArgOptions): Result => {\n for (const [argName, { short }] of Object.entries(options.args ?? {})) {\n if (short !== undefined && !SHORT_FLAG.test(short)) {\n return err(\n `task '${exportName}' has arg '${argName}' with short '${short}'. A short must be one letter or digit.`,\n undefined,\n )\n }\n }\n\n const parser = attempt(() => toTaskParser(options))\n // Copy Optique's message to leave out its error name, which `messageChain` prints.\n if (isErr(parser)) return err(`task '${exportName}' has invalid args: ${parser.message}`, undefined)\n}\n\n/** Checks every task's arg declarations, and returns every problem as a `bask.ts` problem. */\nexport const checkAllTaskArgs = (tasks: TaskIndex): Result => {\n const taskArgErrors = Array.from(tasks.byTask.values(), ({ exportName, task }) =>\n checkTaskArgs(exportName, task.options),\n ).filter(isErr)\n if (taskArgErrors.length > 0) return joinBaskFileErrors(taskArgErrors)\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,aAAa;AAEnB,MAAM,eAAe,MAAc,QAA4B;CAC7D,MAAM,WAAW,KAAK,YAAY,IAAI;CACtC,MAAM,QACJ,IAAI,UAAU,KAAA,IAAY,CAAC,QAAQ,IAAI,CAAC,IAAI,IAAI,SAAS,QAAQ;CACnE,MAAM,aAAa,IAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,OAAO,GAAG,KAAK,IAAI,IAAI,IAAI;CAC3F,IAAI,IAAI,SAAS,UAAU,OAAO,SAAS,OAAO,GAAG,OAAO,OAAO,EAAE,SAAS,QAAQ,CAAC,GAAG,UAAU,CAAC;CACrG,OAAO,YAAY,KAAK,GAAG,OAAO,UAAU,GAAG,KAAK;AACtD;;AAGA,MAAa,gBAAgB,YAAwC;CACnE,MAAM,aAAa,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,SAA8B,CAC9F,MACA,YAAY,MAAM,GAAG,CACvB,CAAC;CACD,MAAM,cAAc,QAAQ,cAAc,SAAS,SAAS,OAAO,EAAE,SAAS,MAAM,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC;CACtG,MAAM,YAAY,YAAY,OAAO;CAErC,MAAM,aAAa,OAAO,OAAO,YAAY,UAAU,CAAC;CACxD,OAAO,IAAI,OAAO;EAAE,MAAM;EAAY;CAAY,CAAC,IAAI,YAAY;EACjE,MAAM;GAAE,GAAG,UAAU;GAAM,GAAG,OAAO;EAAK;EAC1C,aAAa,OAAO;CACtB,EAAE;AACJ;;AAGA,MAAM,iBAAiB,YAAoB,YAAoC;CAC7E,KAAK,MAAM,CAAC,SAAS,EAAE,YAAY,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,GAClE,IAAI,UAAU,KAAA,KAAa,CAAC,WAAW,KAAK,KAAK,GAC/C,OAAO,IACL,SAAS,WAAW,aAAa,QAAQ,gBAAgB,MAAM,0CAC/D,KAAA,CACF;CAIJ,MAAM,SAAS,cAAc,aAAa,OAAO,CAAC;CAElD,IAAI,MAAM,MAAM,GAAG,OAAO,IAAI,SAAS,WAAW,sBAAsB,OAAO,WAAW,KAAA,CAAS;AACrG;;AAGA,MAAa,oBAAoB,UAA6B;CAC5D,MAAM,gBAAgB,MAAM,KAAK,MAAM,OAAO,OAAO,IAAI,EAAE,YAAY,WACrE,cAAc,YAAY,KAAK,OAAO,CACxC,CAAC,CAAC,OAAO,KAAK;CACd,IAAI,cAAc,SAAS,GAAG,OAAO,mBAAmB,aAAa;AACvE"}
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
- import { runBask } from "./run-bask.js";
3
- import { printError } from "./utils.js";
2
+ import { printError } from "./cli/print-error.js";
3
+ import { runBask } from "./cli/run-bask.js";
4
4
  import path from "node:path";
5
5
  import bun from "bun";
6
6
  import { attempt, getContext, isErr, messageChain } from "ts-explicit-errors";
@@ -12,7 +12,7 @@ const resolveLocalCli = () => {
12
12
  if (isErr(localCli)) return;
13
13
  return localCli;
14
14
  };
15
- /** Hands off to the project's own bask CLI, or runs bask from this one. */
15
+ /** Hands off to the project's own bask CLI, or runs bask from this one and returns its exit code. */
16
16
  const bask = async () => {
17
17
  const localCli = resolveLocalCli();
18
18
  if (localCli && localCli !== import.meta.path) {
@@ -22,11 +22,13 @@ const bask = async () => {
22
22
  return runBask(process.argv.slice(2), path.join(cwd, "bask.ts"));
23
23
  };
24
24
  const main = async () => {
25
- const result = await bask();
26
- if (isErr(result)) {
27
- printError(messageChain(result));
28
- process.exitCode = getContext(result, "exitCode") ?? 1;
25
+ const exitCode = await bask();
26
+ if (isErr(exitCode)) {
27
+ printError(messageChain(exitCode));
28
+ process.exitCode = getContext(exitCode, "exitCode") ?? 1;
29
+ return;
29
30
  }
31
+ if (exitCode !== void 0) process.exitCode = exitCode;
30
32
  };
31
33
  await main();
32
34
  export {};
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { runBask } from \"#run-bask.ts\"\nimport { printError } from \"#utils.ts\"\n\nconst cwd = process.cwd()\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n const localCli = attempt(() => bun.resolveSync(\"@adamhl8/bask/cli\", cwd))\n if (isErr(localCli)) return\n return localCli\n}\n\n/** Hands off to the project's own bask CLI, or runs bask from this one. */\nconst bask = async (): Promise<Result> => {\n // Import the local CLI and stop, because it runs its own `main` when loaded.\n // The local copy resolves to its own path, so it skips this and runs normally.\n const localCli = resolveLocalCli()\n if (localCli && localCli !== import.meta.path) {\n await import(localCli)\n return\n }\n\n return runBask(process.argv.slice(2), path.join(cwd, \"bask.ts\"))\n}\n\nconst main = async () => {\n const result = await bask()\n if (isErr(result)) {\n printError(messageChain(result))\n // Set the exit code only on an error, because the local CLI sets its own.\n process.exitCode = getContext<number>(result, \"exitCode\") ?? 1\n }\n}\n\nawait main()\n"],"mappings":";;;;;;;AAWA,MAAM,MAAM,QAAQ,IAAI;;AAGxB,MAAM,wBAAwB;CAC5B,MAAM,WAAW,cAAc,IAAI,YAAY,qBAAqB,GAAG,CAAC;CACxE,IAAI,MAAM,QAAQ,GAAG;CACrB,OAAO;AACT;;AAGA,MAAM,OAAO,YAA6B;CAGxC,MAAM,WAAW,gBAAgB;CACjC,IAAI,YAAY,aAAa,YAAY,MAAM;EAC7C,MAAM,OAAO;EACb;CACF;CAEA,OAAO,QAAQ,QAAQ,KAAK,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,SAAS,CAAC;AACjE;AAEA,MAAM,OAAO,YAAY;CACvB,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,MAAM,MAAM,GAAG;EACjB,WAAW,aAAa,MAAM,CAAC;EAE/B,QAAQ,WAAW,WAAmB,QAAQ,UAAU,KAAK;CAC/D;AACF;AAEA,MAAM,KAAK"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { printError } from \"#cli/print-error.ts\"\nimport { runBask } from \"#cli/run-bask.ts\"\n\nconst cwd = process.cwd()\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n const localCli = attempt(() => bun.resolveSync(\"@adamhl8/bask/cli\", cwd))\n if (isErr(localCli)) return\n return localCli\n}\n\n/** Hands off to the project's own bask CLI, or runs bask from this one and returns its exit code. */\nconst bask = async (): Promise<Result<number | undefined>> => {\n // Import the local CLI and stop, because it runs its own `main` when loaded.\n // The local copy resolves to its own path, so it skips this and runs normally.\n const localCli = resolveLocalCli()\n if (localCli && localCli !== import.meta.path) {\n await import(localCli)\n return\n }\n\n return runBask(process.argv.slice(2), path.join(cwd, \"bask.ts\"))\n}\n\nconst main = async () => {\n const exitCode = await bask()\n if (isErr(exitCode)) {\n printError(messageChain(exitCode))\n process.exitCode = getContext<number>(exitCode, \"exitCode\") ?? 1\n return\n }\n // Leave the exit code alone after a hand-off, because the local CLI sets its own.\n if (exitCode !== undefined) process.exitCode = exitCode\n}\n\nawait main()\n"],"mappings":";;;;;;;AAWA,MAAM,MAAM,QAAQ,IAAI;;AAGxB,MAAM,wBAAwB;CAC5B,MAAM,WAAW,cAAc,IAAI,YAAY,qBAAqB,GAAG,CAAC;CACxE,IAAI,MAAM,QAAQ,GAAG;CACrB,OAAO;AACT;;AAGA,MAAM,OAAO,YAAiD;CAG5D,MAAM,WAAW,gBAAgB;CACjC,IAAI,YAAY,aAAa,YAAY,MAAM;EAC7C,MAAM,OAAO;EACb;CACF;CAEA,OAAO,QAAQ,QAAQ,KAAK,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,SAAS,CAAC;AACjE;AAEA,MAAM,OAAO,YAAY;CACvB,MAAM,WAAW,MAAM,KAAK;CAC5B,IAAI,MAAM,QAAQ,GAAG;EACnB,WAAW,aAAa,QAAQ,CAAC;EACjC,QAAQ,WAAW,WAAmB,UAAU,UAAU,KAAK;EAC/D;CACF;CAEA,IAAI,aAAa,KAAA,GAAW,QAAQ,WAAW;AACjD;AAEA,MAAM,KAAK"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { BaskConfigInput, defineConfig } from "./config.js";
2
- import { list } from "./bask-file/list.js";
2
+ import { list } from "./cli/list.js";
3
3
  import { Task, isTask, task } from "./task.js";
4
4
  export { type BaskConfigInput, type Task, defineConfig, isTask, list, task };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { printError } from "./utils.js";
1
+ import { printError } from "./cli/print-error.js";
2
2
  import { defineConfig } from "./config.js";
3
- import { list } from "./bask-file/list.js";
3
+ import { list } from "./cli/list.js";
4
4
  import { isTask, task } from "./task.js";
5
5
  import path from "node:path";
6
6
  import bun from "bun";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\n\nimport { printError } from \"#utils.ts\"\n\n// Stop a `bun bask` run because Bun runs bask.ts itself instead of the bask CLI.\nif (path.basename(bun.main) === \"bask.ts\") {\n const command = [\"bask\", ...process.argv.slice(2)].join(\" \")\n printError(\n `bask.ts can't be run directly. Use \\`bunx\\` instead of \\`bun\\`.\\nEither run \\`bunx ${command}\\` or run \\`${command}\\` directly (if installed globally).`,\n )\n process.exit(1)\n}\n\nexport { defineConfig } from \"#config.ts\"\nexport type { BaskConfigInput } from \"#config.ts\"\nexport { list } from \"#bask-file/list.ts\"\nexport { isTask, task } from \"#task.ts\"\nexport type { Task } from \"#task.ts\"\n"],"mappings":";;;;;;;AAOA,IAAI,KAAK,SAAS,IAAI,IAAI,MAAM,WAAW;CACzC,MAAM,UAAU,CAAC,QAAQ,GAAG,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CAC3D,WACE,sFAAsF,QAAQ,cAAc,QAAQ,qCACtH;CACA,QAAQ,KAAK,CAAC;AAChB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\n\nimport { printError } from \"#cli/print-error.ts\"\n\n// Stop a `bun bask` run because Bun runs bask.ts itself instead of the bask CLI.\nif (path.basename(bun.main) === \"bask.ts\") {\n const command = [\"bask\", ...process.argv.slice(2)].join(\" \")\n printError(\n `bask.ts can't be run directly. Use \\`bunx\\` instead of \\`bun\\`.\\nEither run \\`bunx ${command}\\` or run \\`${command}\\` directly (if installed globally).`,\n )\n process.exit(1)\n}\n\nexport { defineConfig } from \"#config.ts\"\nexport type { BaskConfigInput } from \"#config.ts\"\nexport { list } from \"#cli/list.ts\"\nexport { isTask, task } from \"#task.ts\"\nexport type { Task } from \"#task.ts\"\n"],"mappings":";;;;;;;AAOA,IAAI,KAAK,SAAS,IAAI,IAAI,MAAM,WAAW;CACzC,MAAM,UAAU,CAAC,QAAQ,GAAG,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CAC3D,WACE,sFAAsF,QAAQ,cAAc,QAAQ,qCACtH;CACA,QAAQ,KAAK,CAAC;AAChB"}
@@ -1,5 +1,5 @@
1
1
  import { err } from "ts-explicit-errors";
2
- // src/bask-file/loaded.ts
2
+ // src/loaded-bask-file.ts
3
3
  let loadedBaskFile;
4
4
  /** Stores the validated `bask.ts` for tasks to read when they run. */
5
5
  const setLoadedBaskFile = (baskFile) => {
@@ -15,4 +15,4 @@ const getLoadedBaskFile = () => {
15
15
  };
16
16
  export { getLoadedBaskFile, setLoadedBaskFile };
17
17
 
18
- //# sourceMappingURL=loaded.js.map
18
+ //# sourceMappingURL=loaded-bask-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaded-bask-file.js","names":[],"sources":["../src/loaded-bask-file.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFile } from \"#bask-file/bask-file.ts\"\n\nlet loadedBaskFile: BaskFile | undefined\n\n/** Stores the validated `bask.ts` for tasks to read when they run. */\nexport const setLoadedBaskFile = (baskFile: BaskFile) => {\n loadedBaskFile = baskFile\n}\n\n/**\n * Returns the loaded `bask.ts`. Throws until the CLI has loaded it, because only a task called at the top level of\n * `bask.ts` gets here that early.\n */\nexport const getLoadedBaskFile = () => {\n if (loadedBaskFile) return loadedBaskFile\n throw err(\n \"a task ran while bask.ts was loading. Call tasks from inside other tasks, not at the top level.\",\n undefined,\n { invalidBaskFile: true },\n )\n}\n"],"mappings":";;AAIA,IAAI;;AAGJ,MAAa,qBAAqB,aAAuB;CACvD,iBAAiB;AACnB;;;;;AAMA,MAAa,0BAA0B;CACrC,IAAI,gBAAgB,OAAO;CAC3B,MAAM,IACJ,mGACA,KAAA,GACA,EAAE,iBAAiB,KAAK,CAC1B;AACF"}
@@ -0,0 +1,13 @@
1
+ export interface TaskArg {
2
+ /** A one-character short flag, like `w` for `-w`. */
3
+ short?: string;
4
+ /** A boolean is `true` when passed. A string takes a value. */
5
+ type?: "boolean" | "string";
6
+ /** Shown on the task's help page. */
7
+ desc?: string;
8
+ }
9
+ export type TaskArgs = Record<string, TaskArg>;
10
+ export type NoArgs = Record<never, never>;
11
+ /** The value each declared arg has in a task's context. */
12
+ export type ArgValues<A extends TaskArgs> = { [K in keyof A]: A[K]["type"] extends "string" ? string | undefined : boolean; };
13
+ //# sourceMappingURL=args.d.ts.map
@@ -0,0 +1,12 @@
1
+ // src/task/args.ts
2
+ /** Returns the args of a task that got none: every boolean `false`, every string `undefined`, and no positionals. */
3
+ const toEmptyArgs = (options) => {
4
+ const argEntries = Object.entries(options.args ?? {}).map(([name, arg]) => [name, arg.type === "string" ? void 0 : false]);
5
+ return {
6
+ args: Object.fromEntries(argEntries),
7
+ positionals: []
8
+ };
9
+ };
10
+ export { toEmptyArgs };
11
+
12
+ //# sourceMappingURL=args.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"args.js","names":[],"sources":["../../src/task/args.ts"],"sourcesContent":["export interface TaskArg {\n /** A one-character short flag, like `w` for `-w`. */\n short?: string\n /** A boolean is `true` when passed. A string takes a value. */\n type?: \"boolean\" | \"string\"\n /** Shown on the task's help page. */\n desc?: string\n}\n\nexport type TaskArgs = Record<string, TaskArg>\n\n// oxlint-disable-next-line typescript/no-generated-empty-object-type - a task with no args has no arg values\nexport type NoArgs = Record<never, never>\n\n/** The value each declared arg has in a task's context. */\nexport type ArgValues<A extends TaskArgs> = {\n [K in keyof A]: A[K][\"type\"] extends \"string\" ? string | undefined : boolean\n}\n\nexport type ArgValue = boolean | string | undefined\n\nexport interface ParsedTaskArgs {\n args: Record<string, ArgValue>\n positionals: readonly string[]\n}\n\nexport interface TaskArgOptions {\n args?: TaskArgs\n positionals?: boolean\n}\n\n/** Returns the args of a task that got none: every boolean `false`, every string `undefined`, and no positionals. */\nexport const toEmptyArgs = (options: TaskArgOptions): ParsedTaskArgs => {\n const argEntries = Object.entries(options.args ?? {}).map(([name, arg]): [string, ArgValue] => [\n name,\n arg.type === \"string\" ? undefined : false,\n ])\n return { args: Object.fromEntries(argEntries), positionals: [] }\n}\n"],"mappings":";;AAgCA,MAAa,eAAe,YAA4C;CACtE,MAAM,aAAa,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,SAA6B,CAC7F,MACA,IAAI,SAAS,WAAW,KAAA,IAAY,KACtC,CAAC;CACD,OAAO;EAAE,MAAM,OAAO,YAAY,UAAU;EAAG,aAAa,CAAC;CAAE;AACjE"}
package/dist/task.d.ts CHANGED
@@ -1,25 +1,36 @@
1
1
  import { Shell } from "./shell/shell.js";
2
+ import { ArgValues, NoArgs, TaskArgs } from "./task/args.js";
2
3
  type AsyncOrSyncReturn = Promise<void> | void;
3
- interface TaskOptions {
4
+ interface TaskOptions<A extends TaskArgs = NoArgs> {
4
5
  desc?: string;
5
6
  /** Keeps the task runnable but leaves it out of the task list. */
6
7
  hidden?: boolean;
7
8
  /** Additional names to run the task. */
8
9
  alias?: string | string[];
10
+ /** Args the task takes from the command line, by name. */
11
+ args?: A;
12
+ /** Lets the task take positionals, including everything after `--`. */
13
+ positionals?: boolean;
9
14
  }
10
- interface TaskContext {
15
+ interface TaskContext<A extends TaskArgs = NoArgs> {
11
16
  sh: Shell;
17
+ args: ArgValues<A>;
18
+ positionals: string[];
12
19
  }
13
- type TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn;
14
- export interface Task {
20
+ type TaskFn<A extends TaskArgs = NoArgs> = (ctx: TaskContext<A>) => AsyncOrSyncReturn;
21
+ /** A task used as a hook. It leaves out the call signature so TypeScript still infers an inline hook's parameter. */
22
+ type HookTask = Pick<Task, "options">;
23
+ /** A hook added with `before` or `after`: a function that gets the task's context, or another task. */
24
+ type Hook<A extends TaskArgs = NoArgs> = TaskFn<A> | HookTask;
25
+ export interface Task<A extends TaskArgs = NoArgs> {
15
26
  (): Promise<void>;
16
- options: TaskOptions;
17
- before: (...fns: TaskFn[]) => void;
18
- after: (...fns: TaskFn[]) => void;
27
+ options: TaskOptions<A>;
28
+ before: (...fns: Hook<A>[]) => void;
29
+ after: (...fns: Hook<A>[]) => void;
19
30
  }
20
31
  export declare const isTask: (value: unknown) => value is Task;
21
32
  /** Registers a task that runs at most once per bask invocation, however many times it's called. */
22
33
  export declare function task(fn: TaskFn): Task;
23
- export declare function task(options: TaskOptions, fn: TaskFn): Task;
34
+ export declare function task<const A extends TaskArgs = NoArgs>(options: TaskOptions<A>, fn: TaskFn<A>): Task<A>;
24
35
  export {};
25
36
  //# sourceMappingURL=task.d.ts.map
package/dist/task.js CHANGED
@@ -1,11 +1,18 @@
1
- import { getLoadedBaskFile } from "./bask-file/loaded.js";
1
+ import { getLoadedBaskFile } from "./loaded-bask-file.js";
2
2
  import { createShell } from "./shell/shell.js";
3
+ import { toEmptyArgs } from "./task/args.js";
3
4
  // src/task.ts
4
5
  const createdByTask = /* @__PURE__ */ new WeakSet();
5
6
  const isTask = (value) => typeof value === "function" && createdByTask.has(value);
6
7
  const failedTasks = /* @__PURE__ */ new WeakMap();
7
8
  /** Returns the innermost task that the error failed, so the CLI can name it. */
8
9
  const getFailedTask = (error) => failedTasks.get(error);
10
+ const commandLineArgs = /* @__PURE__ */ new WeakMap();
11
+ /** Runs the task the command line named, with the args parsed from it. */
12
+ const runWithArgs = async (taskToRun, taskArgs) => {
13
+ commandLineArgs.set(taskToRun, taskArgs);
14
+ await taskToRun();
15
+ };
9
16
  function task(optionsOrFn, maybeFn) {
10
17
  const [options, fn] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn];
11
18
  if (!fn) throw new Error("task() needs a callback");
@@ -24,15 +31,24 @@ function task(optionsOrFn, maybeFn) {
24
31
  assertNotStarted();
25
32
  afterFns.push(...fns);
26
33
  };
27
- const runAll = async (shellConfig) => {
34
+ const runAll = async (shellConfig, taskArgs) => {
28
35
  hasStarted = true;
29
- const runWithShell = async (taskFn) => taskFn({ sh: createShell(shellConfig) });
30
- for (const beforeFn of beforeFns) await runWithShell(beforeFn);
31
- await runWithShell(fn);
32
- for (const afterFn of afterFns) await runWithShell(afterFn);
36
+ const runHook = async (hook) => {
37
+ if (isTask(hook)) return hook();
38
+ if (typeof hook !== "function") return;
39
+ const args = taskArgs.args;
40
+ return hook({
41
+ sh: createShell(shellConfig),
42
+ args,
43
+ positionals: [...taskArgs.positionals]
44
+ });
45
+ };
46
+ for (const beforeFn of beforeFns) await runHook(beforeFn);
47
+ await runHook(fn);
48
+ for (const afterFn of afterFns) await runHook(afterFn);
33
49
  };
34
- const runOnce = async (shellConfig) => {
35
- runPromise ??= runAll(shellConfig);
50
+ const runOnce = async (shellConfig, taskArgs) => {
51
+ runPromise ??= runAll(shellConfig, taskArgs);
36
52
  try {
37
53
  await runPromise;
38
54
  } catch (error) {
@@ -42,7 +58,8 @@ function task(optionsOrFn, maybeFn) {
42
58
  };
43
59
  const run = () => {
44
60
  const baskFile = getLoadedBaskFile();
45
- return runOnce(baskFile.config.shell);
61
+ const taskArgs = commandLineArgs.get(newTask) ?? toEmptyArgs(options);
62
+ return runOnce(baskFile.config.shell, taskArgs);
46
63
  };
47
64
  const newTask = Object.assign(run, {
48
65
  options,
@@ -52,6 +69,6 @@ function task(optionsOrFn, maybeFn) {
52
69
  createdByTask.add(newTask);
53
70
  return newTask;
54
71
  }
55
- export { getFailedTask, isTask, task };
72
+ export { getFailedTask, isTask, runWithArgs, task };
56
73
 
57
74
  //# sourceMappingURL=task.js.map
package/dist/task.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import { getLoadedBaskFile } from \"#bask-file/loaded.ts\"\nimport type { ShellConfig } from \"#config.ts\"\nimport { createShell } from \"#shell/shell.ts\"\nimport type { Shell } from \"#shell/shell.ts\"\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ninterface TaskOptions {\n desc?: string\n /** Keeps the task runnable but leaves it out of the task list. */\n hidden?: boolean\n /** Additional names to run the task. */\n alias?: string | string[]\n}\n\ninterface TaskContext {\n sh: Shell\n}\n\ntype TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn\n\nexport interface Task {\n (): Promise<void>\n options: TaskOptions\n before: (...fns: TaskFn[]) => void\n after: (...fns: TaskFn[]) => void\n}\n\nconst createdByTask = new WeakSet<object>()\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && createdByTask.has(value)\n\nconst failedTasks = new WeakMap<Error, Task>()\n/** Returns the innermost task that the error failed, so the CLI can name it. */\nexport const getFailedTask = (error: Error) => failedTasks.get(error)\n\n/** Registers a task that runs at most once per bask invocation, however many times it's called. */\nexport function task(fn: TaskFn): Task\nexport function task(options: TaskOptions, fn: TaskFn): Task\nexport function task(optionsOrFn: TaskOptions | TaskFn, maybeFn?: TaskFn): Task {\n const [options, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n if (!fn) throw new Error(\"task() needs a callback\")\n\n const beforeFns: TaskFn[] = []\n const afterFns: TaskFn[] = []\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n // Track the start separately because `runAll` calls the task before `runPromise` is assigned.\n let hasStarted = false\n\n const assertNotStarted = () => {\n if (hasStarted) throw new Error(\"Can't add a hook to a task that has already started\")\n }\n\n const before = (...fns: TaskFn[]) => {\n assertNotStarted()\n beforeFns.push(...fns)\n }\n\n const after = (...fns: TaskFn[]) => {\n assertNotStarted()\n afterFns.push(...fns)\n }\n\n const runAll = async (shellConfig: ShellConfig) => {\n hasStarted = true\n // Give each hook and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n const runWithShell = async (taskFn: TaskFn) => taskFn({ sh: createShell(shellConfig) })\n\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await runWithShell(beforeFn)\n await runWithShell(fn)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await runWithShell(afterFn)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const runOnce = async (shellConfig: ShellConfig) => {\n runPromise ??= runAll(shellConfig)\n try {\n await runPromise\n } catch (error) {\n // Record this task only if no task has yet, because the innermost task's catch runs first.\n // oxlint-disable-next-line no-use-before-define - `runOnce` only runs after `newTask` is assigned\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, newTask)\n throw error\n }\n }\n\n // oxlint-disable-next-line typescript/promise-function-async - an async function would turn the throw into a rejection\n const run = () => {\n const baskFile = getLoadedBaskFile()\n return runOnce(baskFile.config.shell)\n }\n\n const newTask: Task = Object.assign(run, { options, before, after })\n createdByTask.add(newTask)\n return newTask\n}\n"],"mappings":";;;AA4BA,MAAM,gCAAgB,IAAI,QAAgB;AAC1C,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,cAAc,IAAI,KAAK;AAE/G,MAAM,8BAAc,IAAI,QAAqB;;AAE7C,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK;AAKpE,SAAgB,KAAK,aAAmC,SAAwB;CAC9E,MAAM,CAAC,SAAS,MAAM,OAAO,gBAAgB,aAAa,CAAC,CAAC,GAAG,WAAW,IAAI,CAAC,aAAa,OAAO;CACnG,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,yBAAyB;CAElD,MAAM,YAAsB,CAAC;CAC7B,MAAM,WAAqB,CAAC;CAG5B,IAAI;CAEJ,IAAI,aAAa;CAEjB,MAAM,yBAAyB;EAC7B,IAAI,YAAY,MAAM,IAAI,MAAM,qDAAqD;CACvF;CAEA,MAAM,UAAU,GAAG,QAAkB;EACnC,iBAAiB;EACjB,UAAU,KAAK,GAAG,GAAG;CACvB;CAEA,MAAM,SAAS,GAAG,QAAkB;EAClC,iBAAiB;EACjB,SAAS,KAAK,GAAG,GAAG;CACtB;CAEA,MAAM,SAAS,OAAO,gBAA6B;EACjD,aAAa;EAEb,MAAM,eAAe,OAAO,WAAmB,OAAO,EAAE,IAAI,YAAY,WAAW,EAAE,CAAC;EAGtF,KAAK,MAAM,YAAY,WAAW,MAAM,aAAa,QAAQ;EAC7D,MAAM,aAAa,EAAE;EAErB,KAAK,MAAM,WAAW,UAAU,MAAM,aAAa,OAAO;CAC5D;CAGA,MAAM,UAAU,OAAO,gBAA6B;EAClD,eAAe,OAAO,WAAW;EACjC,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,OAAO;GACrF,MAAM;EACR;CACF;CAGA,MAAM,YAAY;EAChB,MAAM,WAAW,kBAAkB;EACnC,OAAO,QAAQ,SAAS,OAAO,KAAK;CACtC;CAEA,MAAM,UAAgB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACnE,cAAc,IAAI,OAAO;CACzB,OAAO;AACT"}
1
+ {"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import type { ShellConfig } from \"#config.ts\"\nimport { getLoadedBaskFile } from \"#loaded-bask-file.ts\"\nimport { createShell } from \"#shell/shell.ts\"\nimport type { Shell } from \"#shell/shell.ts\"\nimport { toEmptyArgs } from \"#task/args.ts\"\nimport type { ArgValues, NoArgs, ParsedTaskArgs, TaskArgs } from \"#task/args.ts\"\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ninterface TaskOptions<A extends TaskArgs = NoArgs> {\n desc?: string\n /** Keeps the task runnable but leaves it out of the task list. */\n hidden?: boolean\n /** Additional names to run the task. */\n alias?: string | string[]\n /** Args the task takes from the command line, by name. */\n args?: A\n /** Lets the task take positionals, including everything after `--`. */\n positionals?: boolean\n}\n\ninterface TaskContext<A extends TaskArgs = NoArgs> {\n sh: Shell\n args: ArgValues<A>\n positionals: string[]\n}\n\ntype TaskFn<A extends TaskArgs = NoArgs> = (ctx: TaskContext<A>) => AsyncOrSyncReturn\n\n/** A task used as a hook. It leaves out the call signature so TypeScript still infers an inline hook's parameter. */\ntype HookTask = Pick<Task, \"options\">\n\n/** A hook added with `before` or `after`: a function that gets the task's context, or another task. */\ntype Hook<A extends TaskArgs = NoArgs> = TaskFn<A> | HookTask\n\nexport interface Task<A extends TaskArgs = NoArgs> {\n (): Promise<void>\n options: TaskOptions<A>\n before: (...fns: Hook<A>[]) => void\n after: (...fns: Hook<A>[]) => void\n}\n\nconst createdByTask = new WeakSet<object>()\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && createdByTask.has(value)\n\nconst failedTasks = new WeakMap<Error, Task>()\n/** Returns the innermost task that the error failed, so the CLI can name it. */\nexport const getFailedTask = (error: Error) => failedTasks.get(error)\n\n// Hold the command line's args for the task it named, because tasks are called without args.\nconst commandLineArgs = new WeakMap<Task, ParsedTaskArgs>()\n\n/** Runs the task the command line named, with the args parsed from it. */\nexport const runWithArgs = async (taskToRun: Task, taskArgs: ParsedTaskArgs) => {\n commandLineArgs.set(taskToRun, taskArgs)\n await taskToRun()\n}\n\n/** Registers a task that runs at most once per bask invocation, however many times it's called. */\nexport function task(fn: TaskFn): Task\nexport function task<const A extends TaskArgs = NoArgs>(options: TaskOptions<A>, fn: TaskFn<A>): Task<A>\nexport function task<A extends TaskArgs>(optionsOrFn: TaskOptions<A> | TaskFn<A>, maybeFn?: TaskFn<A>): Task<A> {\n const [options, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n if (!fn) throw new Error(\"task() needs a callback\")\n\n const beforeFns: Hook<A>[] = []\n const afterFns: Hook<A>[] = []\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n // Track the start separately because `runAll` calls the task before `runPromise` is assigned.\n let hasStarted = false\n\n const assertNotStarted = () => {\n if (hasStarted) throw new Error(\"Can't add a hook to a task that has already started\")\n }\n\n const before = (...fns: Hook<A>[]) => {\n assertNotStarted()\n beforeFns.push(...fns)\n }\n\n const after = (...fns: Hook<A>[]) => {\n assertNotStarted()\n afterFns.push(...fns)\n }\n\n const runAll = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => {\n hasStarted = true\n // Give each hook and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n // Call a task used as a hook bare, because this task's args aren't its args.\n const runHook = async (hook: Hook<A>) => {\n if (isTask(hook)) return hook()\n if (typeof hook !== \"function\") return\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - `taskArgs` was parsed from this task's own `args` declaration\n const args = taskArgs.args as ArgValues<A>\n return hook({ sh: createShell(shellConfig), args, positionals: [...taskArgs.positionals] })\n }\n\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await runHook(beforeFn)\n await runHook(fn)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await runHook(afterFn)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const runOnce = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => {\n runPromise ??= runAll(shellConfig, taskArgs)\n try {\n await runPromise\n } catch (error) {\n // Record this task only if no task has yet, because the innermost task's catch runs first.\n // oxlint-disable-next-line no-use-before-define - `runOnce` only runs after `newTask` is assigned\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, newTask)\n throw error\n }\n }\n\n // oxlint-disable-next-line typescript/promise-function-async - an async function would turn the throw into a rejection\n const run = () => {\n const baskFile = getLoadedBaskFile()\n // oxlint-disable-next-line no-use-before-define - `run` only runs after `newTask` is assigned\n const taskArgs = commandLineArgs.get(newTask) ?? toEmptyArgs(options)\n return runOnce(baskFile.config.shell, taskArgs)\n }\n\n const newTask: Task<A> = Object.assign(run, { options, before, after })\n createdByTask.add(newTask)\n return newTask\n}\n"],"mappings":";;;;AA0CA,MAAM,gCAAgB,IAAI,QAAgB;AAC1C,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,cAAc,IAAI,KAAK;AAE/G,MAAM,8BAAc,IAAI,QAAqB;;AAE7C,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK;AAGpE,MAAM,kCAAkB,IAAI,QAA8B;;AAG1D,MAAa,cAAc,OAAO,WAAiB,aAA6B;CAC9E,gBAAgB,IAAI,WAAW,QAAQ;CACvC,MAAM,UAAU;AAClB;AAKA,SAAgB,KAAyB,aAAyC,SAA8B;CAC9G,MAAM,CAAC,SAAS,MAAM,OAAO,gBAAgB,aAAa,CAAC,CAAC,GAAG,WAAW,IAAI,CAAC,aAAa,OAAO;CACnG,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,yBAAyB;CAElD,MAAM,YAAuB,CAAC;CAC9B,MAAM,WAAsB,CAAC;CAG7B,IAAI;CAEJ,IAAI,aAAa;CAEjB,MAAM,yBAAyB;EAC7B,IAAI,YAAY,MAAM,IAAI,MAAM,qDAAqD;CACvF;CAEA,MAAM,UAAU,GAAG,QAAmB;EACpC,iBAAiB;EACjB,UAAU,KAAK,GAAG,GAAG;CACvB;CAEA,MAAM,SAAS,GAAG,QAAmB;EACnC,iBAAiB;EACjB,SAAS,KAAK,GAAG,GAAG;CACtB;CAEA,MAAM,SAAS,OAAO,aAA0B,aAA6B;EAC3E,aAAa;EAGb,MAAM,UAAU,OAAO,SAAkB;GACvC,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK;GAC9B,IAAI,OAAO,SAAS,YAAY;GAEhC,MAAM,OAAO,SAAS;GACtB,OAAO,KAAK;IAAE,IAAI,YAAY,WAAW;IAAG;IAAM,aAAa,CAAC,GAAG,SAAS,WAAW;GAAE,CAAC;EAC5F;EAGA,KAAK,MAAM,YAAY,WAAW,MAAM,QAAQ,QAAQ;EACxD,MAAM,QAAQ,EAAE;EAEhB,KAAK,MAAM,WAAW,UAAU,MAAM,QAAQ,OAAO;CACvD;CAGA,MAAM,UAAU,OAAO,aAA0B,aAA6B;EAC5E,eAAe,OAAO,aAAa,QAAQ;EAC3C,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,OAAO;GACrF,MAAM;EACR;CACF;CAGA,MAAM,YAAY;EAChB,MAAM,WAAW,kBAAkB;EAEnC,MAAM,WAAW,gBAAgB,IAAI,OAAO,KAAK,YAAY,OAAO;EACpE,OAAO,QAAQ,SAAS,OAAO,OAAO,QAAQ;CAChD;CAEA,MAAM,UAAmB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACtE,cAAc,IAAI,OAAO;CACzB,OAAO;AACT"}
package/dist/utils.js CHANGED
@@ -1,8 +1,6 @@
1
- import { styleText } from "node:util";
2
1
  // src/utils.ts
3
- const printError = (message) => {
4
- process.stderr.write(`${styleText(["bold", "red"], "error:", { stream: process.stderr })} ${message}\n`);
5
- };
6
- export { printError };
2
+ const toKebabCase = (name) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`);
3
+ const toCamelCase = (name) => name.replaceAll(/-[\da-z]/gv, (match) => match.slice(1).toUpperCase());
4
+ export { toCamelCase, toKebabCase };
7
5
 
8
6
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\n// Write to `process.stderr` directly because Bun colors all `console.error` output red in a terminal.\nexport const printError = (message: string) => {\n process.stderr.write(`${styleText([\"bold\", \"red\"], \"error:\", { stream: process.stderr })} ${message}\\n`)\n}\n"],"mappings":";;AAGA,MAAa,cAAc,YAAoB;CAC7C,QAAQ,OAAO,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,GAAG,UAAU,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG,QAAQ,GAAG;AACzG"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["export const toKebabCase = (name: string) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`)\nexport const toCamelCase = (name: string) => name.replaceAll(/-[\\da-z]/gv, (match) => match.slice(1).toUpperCase())\n"],"mappings":";AAAA,MAAa,eAAe,SAAiB,KAAK,WAAW,YAAY,UAAU,IAAI,MAAM,YAAY,GAAG;AAC5G,MAAa,eAAe,SAAiB,KAAK,WAAW,eAAe,UAAU,MAAM,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamhl8/bask",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Write your tasks in TypeScript",
5
5
  "keywords": [
6
6
  "build-tool",
@@ -51,6 +51,7 @@
51
51
  "prepare": "tsdown && bun install --ignore-scripts --no-summary && bask prepare"
52
52
  },
53
53
  "dependencies": {
54
+ "@optique/core": "^1.3.7",
54
55
  "ts-explicit-errors": "^5.0.1"
55
56
  },
56
57
  "devDependencies": {
@@ -1,4 +0,0 @@
1
- import { Task } from "../task.js";
2
- import "./task-index.js";
3
- export declare const list: Task;
4
- //# sourceMappingURL=list.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"list.js","names":[],"sources":["../../src/bask-file/list.ts"],"sourcesContent":["import { getLoadedBaskFile } from \"#bask-file/loaded.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { task } from \"#task.ts\"\n\nconst collator = new Intl.Collator()\n\nconst formatAliases = (aliases: string[]) => {\n if (aliases.length === 0) return\n return `[${aliases.length === 1 ? \"alias\" : \"aliases\"}: ${aliases.join(\", \")}]`\n}\n\nexport const formatTaskList = (tasks: TaskIndex) => {\n const defaultEntry = tasks.byName.get(\"default\")\n\n const rows = [...tasks.byTask.values()]\n .filter((entry) => !entry.task.options.hidden)\n .map((entry) => {\n const defaultMarker = entry === defaultEntry && entry.name !== \"default\" ? \"[default]\" : undefined\n const comment = [entry.task.options.desc, defaultMarker, formatAliases(entry.aliases)].filter(Boolean).join(\" \")\n return { name: entry.name, comment }\n })\n .toSorted((a, b) => collator.compare(a.name, b.name))\n\n const nameWidth = Math.max(...rows.map((row) => row.name.length))\n const lines = rows.map(({ name, comment }) =>\n comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`,\n )\n return [\"Available tasks:\", ...lines].join(\"\\n\")\n}\n\nexport const list = task(() => {\n const { tasks } = getLoadedBaskFile()\n console.log(formatTaskList(tasks))\n})\n"],"mappings":";;;AAIA,MAAM,WAAW,IAAI,KAAK,SAAS;AAEnC,MAAM,iBAAiB,YAAsB;CAC3C,IAAI,QAAQ,WAAW,GAAG;CAC1B,OAAO,IAAI,QAAQ,WAAW,IAAI,UAAU,UAAU,IAAI,QAAQ,KAAK,IAAI,EAAE;AAC/E;AAEA,MAAa,kBAAkB,UAAqB;CAClD,MAAM,eAAe,MAAM,OAAO,IAAI,SAAS;CAE/C,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,OAAO,CAAC,CAAC,CACpC,QAAQ,UAAU,CAAC,MAAM,KAAK,QAAQ,MAAM,CAAC,CAC7C,KAAK,UAAU;EACd,MAAM,gBAAgB,UAAU,gBAAgB,MAAM,SAAS,YAAY,cAAc,KAAA;EACzF,MAAM,UAAU;GAAC,MAAM,KAAK,QAAQ;GAAM;GAAe,cAAc,MAAM,OAAO;EAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;EAC/G,OAAO;GAAE,MAAM,MAAM;GAAM;EAAQ;CACrC,CAAC,CAAC,CACD,UAAU,GAAG,MAAM,SAAS,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC;CAEtD,MAAM,YAAY,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,IAAI,KAAK,MAAM,CAAC;CAIhE,OAAO,CAAC,oBAAoB,GAHd,KAAK,KAAK,EAAE,MAAM,cAC9B,UAAU,OAAO,KAAK,OAAO,SAAS,EAAE,KAAK,YAAY,OAAO,MAE/B,CAAC,CAAC,CAAC,KAAK,IAAI;AACjD;AAEA,MAAa,OAAO,WAAW;CAC7B,MAAM,EAAE,UAAU,kBAAkB;CACpC,QAAQ,IAAI,eAAe,KAAK,CAAC;AACnC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"loaded.js","names":[],"sources":["../../src/bask-file/loaded.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFile } from \"#bask-file/bask-file.ts\"\n\nlet loadedBaskFile: BaskFile | undefined\n\n/** Stores the validated `bask.ts` for tasks to read when they run. */\nexport const setLoadedBaskFile = (baskFile: BaskFile) => {\n loadedBaskFile = baskFile\n}\n\n/**\n * Returns the loaded `bask.ts`. Throws until the CLI has loaded it, because only a task called at the top level of\n * `bask.ts` gets here that early.\n */\nexport const getLoadedBaskFile = () => {\n if (loadedBaskFile) return loadedBaskFile\n throw err(\n \"a task ran while bask.ts was loading. Call tasks from inside other tasks, not at the top level.\",\n undefined,\n { invalidBaskFile: true },\n )\n}\n"],"mappings":";;AAIA,IAAI;;AAGJ,MAAa,qBAAqB,aAAuB;CACvD,iBAAiB;AACnB;;;;;AAMA,MAAa,0BAA0B;CACrC,IAAI,gBAAgB,OAAO;CAC3B,MAAM,IACJ,mGACA,KAAA,GACA,EAAE,iBAAiB,KAAK,CAC1B;AACF"}
package/dist/run-bask.js DELETED
@@ -1,47 +0,0 @@
1
- import { loadBaskFile } from "./bask-file/bask-file.js";
2
- import { formatTaskList, list } from "./bask-file/list.js";
3
- import { hasHiddenOutput } from "./shell/command.js";
4
- import { getFailedTask } from "./task.js";
5
- import bun from "bun";
6
- import { parseArgs } from "node:util";
7
- import { attempt, err, isErr } from "ts-explicit-errors";
8
- // src/run-bask.ts
9
- /** Runs a task and returns a failed command as an error that names the innermost task that failed. */
10
- const runTask = async (tasks, taskToRun, taskName) => {
11
- const error = await attempt(async () => taskToRun());
12
- if (!error) return;
13
- if (!(error instanceof bun.$.ShellError)) throw error;
14
- if (hasHiddenOutput(error)) {
15
- process.stdout.write(error.stdout);
16
- process.stderr.write(error.stderr);
17
- }
18
- const failedTask = getFailedTask(error);
19
- const failedName = (failedTask && tasks.byTask.get(failedTask))?.name ?? taskName;
20
- return err(`task '${failedName}' failed with exit code ${error.exitCode}`, void 0, { exitCode: error.exitCode });
21
- };
22
- /** Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. */
23
- const runBask = async (args, baskPath) => {
24
- const parsedArgs = attempt(() => parseArgs({
25
- args,
26
- options: { list: {
27
- type: "boolean",
28
- short: "l"
29
- } },
30
- allowPositionals: true
31
- }));
32
- if (isErr(parsedArgs)) return err(parsedArgs.message, void 0, { exitCode: 2 });
33
- const { values: flags, positionals } = parsedArgs;
34
- const baskFile = await loadBaskFile(baskPath);
35
- if (isErr(baskFile)) return baskFile;
36
- const { tasks } = baskFile;
37
- const [taskName] = positionals;
38
- const resolvedTaskName = taskName ?? "default";
39
- const selectedTaskEntry = tasks.byName.get(resolvedTaskName);
40
- if (flags.list || taskName === void 0 && !selectedTaskEntry) return runTask(tasks, list, "list");
41
- if (!selectedTaskEntry) return err(`unknown task '${resolvedTaskName}'\n\n${formatTaskList(tasks)}`, void 0);
42
- const { task, name } = selectedTaskEntry;
43
- return runTask(tasks, task, name);
44
- };
45
- export { runBask };
46
-
47
- //# sourceMappingURL=run-bask.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-bask.js","names":[],"sources":["../src/run-bask.ts"],"sourcesContent":["import { parseArgs } from \"node:util\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, isErr } from \"ts-explicit-errors\"\n\nimport { loadBaskFile } from \"#bask-file/bask-file.ts\"\nimport { formatTaskList, list } from \"#bask-file/list.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { hasHiddenOutput } from \"#shell/command.ts\"\nimport { getFailedTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\n/** Runs a task and returns a failed command as an error that names the innermost task that failed. */\nconst runTask = async (tasks: TaskIndex, taskToRun: Task, taskName: string): Promise<Result> => {\n const error = await attempt(async () => taskToRun())\n if (!error) return\n // Rethrow anything else, because a bug in a task file needs its stack trace.\n if (!(error instanceof bun.$.ShellError)) throw error\n\n // Print the output of a command that hid it, because it usually explains the failure.\n if (hasHiddenOutput(error)) {\n process.stdout.write(error.stdout)\n process.stderr.write(error.stderr)\n }\n\n const failedTask = getFailedTask(error)\n const failedEntry = failedTask && tasks.byTask.get(failedTask)\n // Fall back to the task you ran, because a task that isn't exported has no name.\n const failedName = failedEntry?.name ?? taskName\n return err(`task '${failedName}' failed with exit code ${error.exitCode}`, undefined, { exitCode: error.exitCode })\n}\n\n/** Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. */\nexport const runBask = async (args: string[], baskPath: string): Promise<Result> => {\n const parsedArgs = attempt(() =>\n parseArgs({ args, options: { list: { type: \"boolean\", short: \"l\" } }, allowPositionals: true }),\n )\n // Copy the message to leave out the `TypeError` name, which `messageChain` prints.\n if (isErr(parsedArgs)) return err(parsedArgs.message, undefined, { exitCode: 2 })\n const { values: flags, positionals } = parsedArgs\n\n const baskFile = await loadBaskFile(baskPath)\n if (isErr(baskFile)) return baskFile\n const { tasks } = baskFile\n\n const [taskName] = positionals\n const resolvedTaskName = taskName ?? \"default\"\n const selectedTaskEntry = tasks.byName.get(resolvedTaskName)\n\n // List the tasks when asked, or when no task is named and there's no default to run.\n if (flags.list || (taskName === undefined && !selectedTaskEntry)) return runTask(tasks, list, \"list\")\n\n if (!selectedTaskEntry) return err(`unknown task '${resolvedTaskName}'\\n\\n${formatTaskList(tasks)}`, undefined)\n\n const { task, name } = selectedTaskEntry\n return runTask(tasks, task, name)\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,UAAU,OAAO,OAAkB,WAAiB,aAAsC;CAC9F,MAAM,QAAQ,MAAM,QAAQ,YAAY,UAAU,CAAC;CACnD,IAAI,CAAC,OAAO;CAEZ,IAAI,EAAE,iBAAiB,IAAI,EAAE,aAAa,MAAM;CAGhD,IAAI,gBAAgB,KAAK,GAAG;EAC1B,QAAQ,OAAO,MAAM,MAAM,MAAM;EACjC,QAAQ,OAAO,MAAM,MAAM,MAAM;CACnC;CAEA,MAAM,aAAa,cAAc,KAAK;CAGtC,MAAM,cAFc,cAAc,MAAM,OAAO,IAAI,UAAU,EAAA,EAE7B,QAAQ;CACxC,OAAO,IAAI,SAAS,WAAW,0BAA0B,MAAM,YAAY,KAAA,GAAW,EAAE,UAAU,MAAM,SAAS,CAAC;AACpH;;AAGA,MAAa,UAAU,OAAO,MAAgB,aAAsC;CAClF,MAAM,aAAa,cACjB,UAAU;EAAE;EAAM,SAAS,EAAE,MAAM;GAAE,MAAM;GAAW,OAAO;EAAI,EAAE;EAAG,kBAAkB;CAAK,CAAC,CAChG;CAEA,IAAI,MAAM,UAAU,GAAG,OAAO,IAAI,WAAW,SAAS,KAAA,GAAW,EAAE,UAAU,EAAE,CAAC;CAChF,MAAM,EAAE,QAAQ,OAAO,gBAAgB;CAEvC,MAAM,WAAW,MAAM,aAAa,QAAQ;CAC5C,IAAI,MAAM,QAAQ,GAAG,OAAO;CAC5B,MAAM,EAAE,UAAU;CAElB,MAAM,CAAC,YAAY;CACnB,MAAM,mBAAmB,YAAY;CACrC,MAAM,oBAAoB,MAAM,OAAO,IAAI,gBAAgB;CAG3D,IAAI,MAAM,QAAS,aAAa,KAAA,KAAa,CAAC,mBAAoB,OAAO,QAAQ,OAAO,MAAM,MAAM;CAEpG,IAAI,CAAC,mBAAmB,OAAO,IAAI,iBAAiB,iBAAiB,OAAO,eAAe,KAAK,KAAK,KAAA,CAAS;CAE9G,MAAM,EAAE,MAAM,SAAS;CACvB,OAAO,QAAQ,OAAO,MAAM,IAAI;AAClC"}