@adamhl8/bask 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +92 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/registry.d.ts +5 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +96 -0
- package/dist/registry.js.map +1 -0
- package/dist/shell.d.ts +6 -0
- package/dist/shell.d.ts.map +1 -0
- package/dist/shell.js +19 -0
- package/dist/shell.js.map +1 -0
- package/dist/task.d.ts +27 -0
- package/dist/task.d.ts.map +1 -0
- package/dist/task.js +51 -0
- package/dist/task.js.map +1 -0
- package/package.json +68 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 adamhl8
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bask
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A task runner for Bun where tasks are TypeScript functions.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- [Bun](https://bun.sh), because tasks run on Bun and shell out with Bun's `$`
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
bun add --dev @adamhl8/bask
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
To run tasks with a plain `bask` instead of `bunx bask`, also install it globally:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
bun add --global @adamhl8/bask
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The global `bask` hands off to the project's copy when there is one, so each project still runs the version it pins.
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
Export tasks from a `bask.ts` in your project root. Calling a task from another task makes it a dependency, and each task runs at most once per invocation.
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { task } from "@adamhl8/bask"
|
|
29
|
+
|
|
30
|
+
export const lint = task(async ({ sh }) => {
|
|
31
|
+
await sh`oxlint`
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
export const build = task({ desc: "Lint, then build" }, async ({ sh }) => {
|
|
35
|
+
await lint()
|
|
36
|
+
await sh`tsdown`
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
export const bumpDeps = task(async ({ sh }) => {
|
|
40
|
+
await sh`bunx npm-check-updates --upgrade`
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
export default build
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Run a task with `bask` if you installed it globally, or with `bunx bask` otherwise. Use `bunx` rather than `bun`, because `bun bask` runs your `bask.ts` instead of the `bask` bin. Task names are the export names in kebab-case, so `bump-deps` runs `bumpDeps`.
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
bask build
|
|
50
|
+
bask bump-deps
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Scripts and CI should use `bunx bask`, because they can't count on a global install.
|
|
54
|
+
|
|
55
|
+
### The default task and the task list
|
|
56
|
+
|
|
57
|
+
`bask` with no task name runs the default export. If `bask.ts` has no default export, it lists your tasks instead, the same as `bask --list` (or `-l`):
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
Available tasks:
|
|
61
|
+
build # Lint, then build [default]
|
|
62
|
+
bump-deps
|
|
63
|
+
lint
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`export * from` never re-exports a default, so a default from a shared tasks module only applies if you re-export it by name.
|
|
67
|
+
|
|
68
|
+
### Task options
|
|
69
|
+
|
|
70
|
+
- `desc`: shown next to the task in the list.
|
|
71
|
+
- `hidden`: keeps the task runnable but leaves it out of the list.
|
|
72
|
+
- `alias`: other names the task runs under, as a string or an array. Write them in kebab-case or camelCase, and either spelling runs the task.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
export const releaseRun = task({ desc: "Run from CI", hidden: true }, async ({ sh }) => {
|
|
76
|
+
await sh`bun release-it --ci`
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
export const bumpDeps = task({ alias: ["up", "update-deps"] }, async ({ sh }) => {
|
|
80
|
+
await sh`bunx npm-check-updates --upgrade`
|
|
81
|
+
})
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Aliases show next to the task in the list:
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
bump-deps # [aliases: up, update-deps]
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Use `alias` rather than exporting the same task under a second name. bask can't tell which export is the original, so exporting a task twice is an error. `export default` is the exception.
|
|
91
|
+
|
|
92
|
+
### Running commands
|
|
93
|
+
|
|
94
|
+
`sh` prints each command before running it with Bun's `$`. To run a command without printing it, use Bun's `$` directly.
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import { $ } from "bun"
|
|
98
|
+
|
|
99
|
+
export const release = task(async ({ sh }) => {
|
|
100
|
+
const branch = await $`git branch --show-current`.text()
|
|
101
|
+
if (branch.trim() === "main") await sh`gh workflow run release.yml`
|
|
102
|
+
})
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
When a command fails, bask stops and names the task it failed in, then exits with the command's exit code:
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
error: task 'lint' failed with exit code 2
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Any other error thrown in a task still shows its stack trace.
|
|
112
|
+
|
|
113
|
+
### Extending tasks
|
|
114
|
+
|
|
115
|
+
`before` and `after` add hooks that run around a task. A hook added in your `bask.ts` also runs when another task calls that task, including tasks you imported. This lets a project extend shared tasks without replacing them.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { task } from "@adamhl8/bask"
|
|
119
|
+
|
|
120
|
+
import { build, lint } from "./shared-tasks.ts"
|
|
121
|
+
|
|
122
|
+
export * from "./shared-tasks.ts"
|
|
123
|
+
|
|
124
|
+
export const astroSync = task(async ({ sh }) => {
|
|
125
|
+
await sh`bun astro sync`
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
lint.before(astroSync)
|
|
129
|
+
build.after(async ({ sh }) => {
|
|
130
|
+
await sh`bun astro build`
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Hooks take tasks or plain functions, run in the order they were added, and run once per invocation along with their task. Adding a hook to a task that has already started throws.
|
|
135
|
+
|
|
136
|
+
The built-in `list` task, which prints the task list, takes hooks too:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { list } from "@adamhl8/bask"
|
|
140
|
+
|
|
141
|
+
list.after(() => {
|
|
142
|
+
console.log("\nRun `bask <task>` to run a task.")
|
|
143
|
+
})
|
|
144
|
+
```
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { getFailedTask } from "./task.js";
|
|
3
|
+
import { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from "./registry.js";
|
|
4
|
+
import { parseArgs, styleText } from "node:util";
|
|
5
|
+
import bun from "bun";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
//#region src/cli.ts
|
|
8
|
+
const isModule = (value) => typeof value === "object" && Boolean(value);
|
|
9
|
+
const printError = (message) => {
|
|
10
|
+
process.stderr.write(`${styleText(["bold", "red"], "error:", { stream: process.stderr })} ${message}\n`);
|
|
11
|
+
};
|
|
12
|
+
const isParseArgsError = (error) => error instanceof TypeError && "code" in error && typeof error.code === "string" && error.code.startsWith("ERR_PARSE_ARGS_");
|
|
13
|
+
/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */
|
|
14
|
+
const resolveLocalCli = () => {
|
|
15
|
+
try {
|
|
16
|
+
return bun.resolveSync("@adamhl8/bask/cli", process.cwd());
|
|
17
|
+
} catch {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const parseCliArgs = () => {
|
|
22
|
+
try {
|
|
23
|
+
return parseArgs({
|
|
24
|
+
options: { list: {
|
|
25
|
+
type: "boolean",
|
|
26
|
+
short: "l"
|
|
27
|
+
} },
|
|
28
|
+
allowPositionals: true
|
|
29
|
+
});
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (!isParseArgsError(error)) throw error;
|
|
32
|
+
printError(error.message);
|
|
33
|
+
process.exitCode = 2;
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
/** Runs a task and reports a failed command in one line, naming the innermost task that failed. */
|
|
38
|
+
const runTask = async (taskToRun, taskName) => {
|
|
39
|
+
try {
|
|
40
|
+
await taskToRun();
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (!(error instanceof bun.$.ShellError)) throw error;
|
|
43
|
+
const failedTask = getFailedTask(error);
|
|
44
|
+
const failedName = getTaskIndex().values().find((entry) => entry.task === failedTask)?.name ?? taskName;
|
|
45
|
+
printError(`task '${failedName}' failed with exit code ${error.exitCode}`);
|
|
46
|
+
process.exitCode = error.exitCode;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const main = async () => {
|
|
50
|
+
const localCli = resolveLocalCli();
|
|
51
|
+
if (localCli && localCli !== import.meta.path) {
|
|
52
|
+
await import(localCli);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const args = parseCliArgs();
|
|
56
|
+
if (!args) return;
|
|
57
|
+
const { values, positionals } = args;
|
|
58
|
+
const baskPath = path.resolve("bask.ts");
|
|
59
|
+
if (!await bun.file(baskPath).exists()) {
|
|
60
|
+
printError(`no bask.ts in ${process.cwd()}`);
|
|
61
|
+
process.exitCode = 1;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const baskModule = await import(baskPath);
|
|
65
|
+
if (!isModule(baskModule)) throw new Error("failed to import bask.ts");
|
|
66
|
+
try {
|
|
67
|
+
setBaskModule(baskModule);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (!(error instanceof BaskFileError)) throw error;
|
|
70
|
+
printError(error.message);
|
|
71
|
+
process.exitCode = 1;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const [taskName] = positionals;
|
|
75
|
+
if (values.list || taskName === void 0 && !getTaskIndex().has("default")) {
|
|
76
|
+
await runTask(list, "list");
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const selectedEntry = getTaskIndex().get(taskName ?? "default");
|
|
80
|
+
if (!selectedEntry) {
|
|
81
|
+
printError(`unknown task '${taskName ?? "default"}'`);
|
|
82
|
+
process.stderr.write(`\n${formatTaskList()}\n`);
|
|
83
|
+
process.exitCode = 1;
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
await runTask(selectedEntry.task, selectedEntry.name);
|
|
87
|
+
};
|
|
88
|
+
await main();
|
|
89
|
+
//#endregion
|
|
90
|
+
export {};
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\nimport { parseArgs, styleText } from \"node:util\"\n\nimport bun from \"bun\"\n\nimport { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from \"#registry.ts\"\nimport { getFailedTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\nconst isModule = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && Boolean(value)\n\n// Write to `process.stderr` directly because Bun colors all `console.error` output red in a terminal.\nconst printError = (message: string) => {\n process.stderr.write(`${styleText([\"bold\", \"red\"], \"error:\", { stream: process.stderr })} ${message}\\n`)\n}\n\nconst isParseArgsError = (error: unknown): error is TypeError & { code: string } =>\n error instanceof TypeError &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code.startsWith(\"ERR_PARSE_ARGS_\")\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n try {\n return bun.resolveSync(\"@adamhl8/bask/cli\", process.cwd())\n } catch {\n return\n }\n}\n\nconst parseCliArgs = () => {\n try {\n return parseArgs({ options: { list: { type: \"boolean\", short: \"l\" } }, allowPositionals: true })\n } catch (error) {\n if (!isParseArgsError(error)) throw error\n printError(error.message)\n process.exitCode = 2\n return\n }\n}\n\n/** Runs a task and reports a failed command in one line, naming the innermost task that failed. */\nconst runTask = async (taskToRun: Task, taskName: string) => {\n try {\n await taskToRun()\n } catch (error) {\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 const failedTask = getFailedTask(error)\n const failedEntry = getTaskIndex()\n .values()\n .find((entry) => entry.task === 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 printError(`task '${failedName}' failed with exit code ${error.exitCode}`)\n process.exitCode = error.exitCode\n }\n}\n\nconst main = async () => {\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 const args = parseCliArgs()\n if (!args) return\n const { values, positionals } = args\n\n const baskPath = path.resolve(\"bask.ts\")\n if (!(await bun.file(baskPath).exists())) {\n printError(`no bask.ts in ${process.cwd()}`)\n process.exitCode = 1\n return\n }\n\n const baskModule: unknown = await import(baskPath)\n if (!isModule(baskModule)) throw new Error(\"failed to import bask.ts\")\n try {\n setBaskModule(baskModule)\n } catch (error) {\n if (!(error instanceof BaskFileError)) throw error\n printError(error.message)\n process.exitCode = 1\n return\n }\n\n const [taskName] = positionals\n\n if (values.list || (taskName === undefined && !getTaskIndex().has(\"default\"))) {\n await runTask(list, \"list\")\n return\n }\n\n const selectedEntry = getTaskIndex().get(taskName ?? \"default\")\n\n if (!selectedEntry) {\n printError(`unknown task '${taskName ?? \"default\"}'`)\n process.stderr.write(`\\n${formatTaskList()}\\n`)\n process.exitCode = 1\n return\n }\n\n await runTask(selectedEntry.task, selectedEntry.name)\n}\n\nawait main()\n"],"mappings":";;;;;;;AAWA,MAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,QAAQ,KAAK;AAGjH,MAAM,cAAc,YAAoB;CACtC,QAAQ,OAAO,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,GAAG,UAAU,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,G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EA,MAAM,aAAsB,MAAM,OAAO;CACzC,IAAI,CAAC,SAAS,UAAU,GAAG,MAAM,IAAI,MAAM,0BAA0B;CACrE,IAAI;EACF,cAAc,UAAU;CAC1B,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,gBAAgB,MAAM;EAC7C,WAAW,MAAM,OAAO;EACxB,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,CAAC,YAAY;CAEnB,IAAI,OAAO,QAAS,aAAa,KAAA,KAAa,CAAC,aAAa,CAAC,CAAC,IAAI,SAAS,GAAI;EAC7E,MAAM,QAAQ,MAAM,MAAM;EAC1B;CACF;CAEA,MAAM,gBAAgB,aAAa,CAAC,CAAC,IAAI,YAAY,SAAS;CAE9D,IAAI,CAAC,eAAe;EAClB,WAAW,iBAAiB,YAAY,UAAU,EAAE;EACpD,QAAQ,OAAO,MAAM,KAAK,eAAe,EAAE,GAAG;EAC9C,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,QAAQ,cAAc,MAAM,cAAc,IAAI;AACtD;AAEA,MAAM,KAAK"}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.d.ts","names":[],"sources":["../src/registry.ts"],"mappings":";;qBAgIa,MAAI"}
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { isTask, task } from "./task.js";
|
|
2
|
+
//#region src/registry.ts
|
|
3
|
+
/** Reports a mistake in `bask.ts` that the CLI prints without a stack trace. */
|
|
4
|
+
var BaskFileError = class extends Error {
|
|
5
|
+
name = "BaskFileError";
|
|
6
|
+
};
|
|
7
|
+
let taskIndex;
|
|
8
|
+
const toKebabCase = (name) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`);
|
|
9
|
+
const toCamelCase = (name) => name.replaceAll(/-[a-z\d]/gv, (match) => match.slice(1).toUpperCase());
|
|
10
|
+
/** Formats one problem as a single line, or several under a count with one per line. */
|
|
11
|
+
const formatProblems = (problems) => {
|
|
12
|
+
if (problems.length === 1) return problems.join("\n");
|
|
13
|
+
return [`bask.ts has ${problems.length} problems:`, ...problems.map((problem) => ` ${problem}`)].join("\n");
|
|
14
|
+
};
|
|
15
|
+
/** Indexes the loaded `bask.ts` module's tasks under both spellings of their export names and aliases. */
|
|
16
|
+
const setBaskModule = (baskModule) => {
|
|
17
|
+
const defaultTask = baskModule["default"];
|
|
18
|
+
const problems = [];
|
|
19
|
+
if ("default" in baskModule && !isTask(defaultTask)) problems.push("the default export isn't a task. Wrap it in task().");
|
|
20
|
+
const taskExports = Object.entries(baskModule).filter((entry) => entry[0] !== "default" && isTask(entry[1]));
|
|
21
|
+
const defaultHasName = taskExports.some(([, exportedTask]) => exportedTask === defaultTask);
|
|
22
|
+
if (isTask(defaultTask) && !defaultHasName) taskExports.push(["default", defaultTask]);
|
|
23
|
+
const index = /* @__PURE__ */ new Map();
|
|
24
|
+
for (const [exportName, exportedTask] of taskExports) {
|
|
25
|
+
const existingEntry = index.values().find((entry) => entry.task === exportedTask);
|
|
26
|
+
if (existingEntry) {
|
|
27
|
+
problems.push(`task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const kebabName = toKebabCase(exportName);
|
|
31
|
+
const entry = {
|
|
32
|
+
exportName,
|
|
33
|
+
name: kebabName,
|
|
34
|
+
aliases: [],
|
|
35
|
+
task: exportedTask
|
|
36
|
+
};
|
|
37
|
+
index.set(exportName, entry);
|
|
38
|
+
index.set(kebabName, entry);
|
|
39
|
+
}
|
|
40
|
+
for (const entry of new Set(index.values())) {
|
|
41
|
+
const aliases = [entry.task.options.alias ?? []].flat();
|
|
42
|
+
for (const alias of aliases) {
|
|
43
|
+
const kebabAlias = toKebabCase(alias);
|
|
44
|
+
if (index.get(kebabAlias) === entry) continue;
|
|
45
|
+
const keys = [
|
|
46
|
+
alias,
|
|
47
|
+
kebabAlias,
|
|
48
|
+
toCamelCase(alias)
|
|
49
|
+
];
|
|
50
|
+
const owner = keys.map((key) => index.get(key)).find(Boolean);
|
|
51
|
+
if (kebabAlias === "default") problems.push(`task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`);
|
|
52
|
+
else if (owner) problems.push(`task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`);
|
|
53
|
+
else {
|
|
54
|
+
entry.aliases.push(kebabAlias);
|
|
55
|
+
for (const key of keys) index.set(key, entry);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (problems.length > 0) throw new BaskFileError(formatProblems(problems));
|
|
60
|
+
const defaultEntry = index.values().find((entry) => entry.task === defaultTask);
|
|
61
|
+
if (defaultEntry) index.set("default", defaultEntry);
|
|
62
|
+
taskIndex = index;
|
|
63
|
+
};
|
|
64
|
+
const getTaskIndex = () => {
|
|
65
|
+
if (!taskIndex) throw new Error("Tasks were read before the CLI loaded bask.ts");
|
|
66
|
+
return taskIndex;
|
|
67
|
+
};
|
|
68
|
+
const formatAliases = (aliases) => {
|
|
69
|
+
if (aliases.length === 0) return;
|
|
70
|
+
return `[${aliases.length === 1 ? "alias" : "aliases"}: ${aliases.join(", ")}]`;
|
|
71
|
+
};
|
|
72
|
+
const formatTaskList = () => {
|
|
73
|
+
const index = getTaskIndex();
|
|
74
|
+
const defaultEntry = index.get("default");
|
|
75
|
+
const rows = [...new Set(index.values())].filter((entry) => !entry.task.options.hidden).map((entry) => {
|
|
76
|
+
const defaultMarker = entry === defaultEntry && entry.name !== "default" ? "[default]" : void 0;
|
|
77
|
+
const comment = [
|
|
78
|
+
entry.task.options.desc,
|
|
79
|
+
defaultMarker,
|
|
80
|
+
formatAliases(entry.aliases)
|
|
81
|
+
].filter(Boolean).join(" ");
|
|
82
|
+
return {
|
|
83
|
+
name: entry.name,
|
|
84
|
+
comment
|
|
85
|
+
};
|
|
86
|
+
}).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
87
|
+
const nameWidth = Math.max(...rows.map((row) => row.name.length));
|
|
88
|
+
return ["Available tasks:", ...rows.map(({ name, comment }) => comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`)].join("\n");
|
|
89
|
+
};
|
|
90
|
+
const list = task(() => {
|
|
91
|
+
console.log(formatTaskList());
|
|
92
|
+
});
|
|
93
|
+
//#endregion
|
|
94
|
+
export { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=registry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry.js","names":[],"sources":["../src/registry.ts"],"sourcesContent":["import { isTask, task } 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\ntype TaskIndex = Map<string, TaskEntry>\n\n/** Reports a mistake in `bask.ts` that the CLI prints without a stack trace. */\nexport class BaskFileError extends Error {\n public override name = \"BaskFileError\"\n}\n\nlet taskIndex: TaskIndex | undefined\n\nconst toKebabCase = (name: string) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`)\nconst toCamelCase = (name: string) => name.replaceAll(/-[a-z\\d]/gv, (match) => match.slice(1).toUpperCase())\n\n/** Formats one problem as a single line, or several under a count with one per line. */\nconst formatProblems = (problems: string[]) => {\n if (problems.length === 1) return problems.join(\"\\n\")\n return [`bask.ts has ${problems.length} problems:`, ...problems.map((problem) => ` ${problem}`)].join(\"\\n\")\n}\n\n/** Indexes the loaded `bask.ts` module's tasks under both spellings of their export names and aliases. */\nexport const setBaskModule = (baskModule: Record<string, unknown>) => {\n const defaultTask = baskModule[\"default\"]\n // Collect every problem before throwing, so one run reports all of them.\n const problems: string[] = []\n\n // Reject a non-task default because bask runs it when no task is named, so it's always a mistake.\n if (\"default\" in baskModule && !isTask(defaultTask))\n problems.push(\"the default export isn't a task. Wrap it in task().\")\n\n // Collect named task exports, then add the default under `default` only when it has no other name.\n const taskExports = Object.entries(baskModule).filter(\n (entry): entry is [string, Task] => entry[0] !== \"default\" && isTask(entry[1]),\n )\n const defaultHasName = taskExports.some(([, exportedTask]) => exportedTask === defaultTask)\n if (isTask(defaultTask) && !defaultHasName) taskExports.push([\"default\", defaultTask])\n\n // Index each task under its export name and kebab-case name, collecting tasks exported more than once.\n const index: TaskIndex = new Map()\n for (const [exportName, exportedTask] of taskExports) {\n const existingEntry = index.values().find((entry) => entry.task === exportedTask)\n if (existingEntry) {\n problems.push(\n `task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`,\n )\n continue\n }\n\n const kebabName = toKebabCase(exportName)\n const entry: TaskEntry = { exportName, name: kebabName, aliases: [], task: exportedTask }\n index.set(exportName, entry)\n index.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 // Collect the entries into a `Set` first because the loop adds alias keys to `index`.\n for (const entry of new Set(index.values())) {\n const aliases = [entry.task.options.alias ?? []].flat()\n\n for (const alias of aliases) {\n const kebabAlias = toKebabCase(alias)\n // Skip an alias that repeats the task's own name or another of its aliases.\n if (index.get(kebabAlias) === entry) continue\n\n const keys = [alias, kebabAlias, toCamelCase(alias)]\n const owner = keys.map((key) => index.get(key)).find(Boolean)\n if (kebabAlias === \"default\")\n problems.push(`task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`)\n else if (owner)\n problems.push(`task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`)\n else {\n entry.aliases.push(kebabAlias)\n for (const key of keys) index.set(key, entry)\n }\n }\n }\n\n if (problems.length > 0) throw new BaskFileError(formatProblems(problems))\n\n const defaultEntry = index.values().find((entry) => entry.task === defaultTask)\n if (defaultEntry) index.set(\"default\", defaultEntry)\n\n taskIndex = index\n}\n\nexport const getTaskIndex = () => {\n if (!taskIndex) throw new Error(\"Tasks were read before the CLI loaded bask.ts\")\n return taskIndex\n}\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 = () => {\n const index = getTaskIndex()\n const defaultEntry = index.get(\"default\")\n\n // Collect the entries into a `Set` because every name of a task shares one entry.\n const rows = [...new Set(index.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) => a.name.localeCompare(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 console.log(formatTaskList())\n})\n"],"mappings":";;;AAgBA,IAAa,gBAAb,cAAmC,MAAM;CACvC,OAAuB;AACzB;AAEA,IAAI;AAEJ,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,MAAM,kBAAkB,aAAuB;CAC7C,IAAI,SAAS,WAAW,GAAG,OAAO,SAAS,KAAK,IAAI;CACpD,OAAO,CAAC,eAAe,SAAS,OAAO,aAAa,GAAG,SAAS,KAAK,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI;AAC7G;;AAGA,MAAa,iBAAiB,eAAwC;CACpE,MAAM,cAAc,WAAW;CAE/B,MAAM,W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O,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,QAAQ,IAAI,eAAe,CAAC;AAC9B,CAAC"}
|
package/dist/shell.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { $, ShellExpression } from "bun";
|
|
2
|
+
//#region src/shell.d.ts
|
|
3
|
+
/** Prints each command to stderr, then runs it with Bun's `$`. */
|
|
4
|
+
export declare const ShellWrapper: (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => $.ShellPromise;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=shell.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shell.d.ts","names":["BunShell"],"sources":["../src/shell.ts"],"mappings":";;;qBAgBa,eAAY,SACd,yBAAoB,aACb,sBACfA,EAAS"}
|
package/dist/shell.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
import bun from "bun";
|
|
3
|
+
//#region src/shell.ts
|
|
4
|
+
/** Formats an interpolated value the way Bun's shell escapes it. */
|
|
5
|
+
const formatExpression = (expression) => {
|
|
6
|
+
if (Array.isArray(expression)) return expression.map(formatExpression).join(" ");
|
|
7
|
+
if (typeof expression === "object" && expression !== null && "raw" in expression) return expression.raw;
|
|
8
|
+
return bun.$.escape(String(expression));
|
|
9
|
+
};
|
|
10
|
+
/** Prints each command to stderr, then runs it with Bun's `$`. */
|
|
11
|
+
const ShellWrapper = (strings, ...expressions) => {
|
|
12
|
+
const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression));
|
|
13
|
+
process.stderr.write(`${styleText("bold", command.trim(), { stream: process.stderr })}\n`);
|
|
14
|
+
return bun.$(strings, ...expressions);
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
export { ShellWrapper };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=shell.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\nimport bun from \"bun\"\nimport type { $ as BunShell, ShellExpression } from \"bun\"\n\n/** Formats an interpolated value the way Bun's shell escapes it. */\nconst formatExpression = (expression: ShellExpression): string => {\n if (Array.isArray(expression)) return expression.map(formatExpression).join(\" \")\n if (typeof expression === \"object\" && expression !== null && \"raw\" in expression) return expression.raw\n // Print streams, files, and subprocesses as their default string because they have no command text.\n // oxlint-disable-next-line typescript/no-base-to-string\n return bun.$.escape(String(expression))\n}\n\n/** Prints each command to stderr, then runs it with Bun's `$`. */\n// oxlint-disable-next-line typescript/promise-function-async - return Bun's `ShellPromise` as is, because an async function would wrap it and drop `.quiet()` and `.text()`.\nexport const ShellWrapper = (\n strings: TemplateStringsArray,\n ...expressions: ShellExpression[]\n): BunShell.ShellPromise => {\n // Use `String.raw` because Bun's `$` also reads the raw template strings.\n const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression))\n // Write to `process.stderr` directly because Bun colors `console.error` output red in a terminal.\n process.stderr.write(`${styleText(\"bold\", command.trim(), { stream: process.stderr })}\\n`)\n return bun.$(strings, ...expressions)\n}\n"],"mappings":";;;;AAMA,MAAM,oBAAoB,eAAwC;CAChE,IAAI,MAAM,QAAQ,UAAU,GAAG,OAAO,WAAW,IAAI,gBAAgB,CAAC,CAAC,KAAK,GAAG;CAC/E,IAAI,OAAO,eAAe,YAAY,eAAe,QAAQ,SAAS,YAAY,OAAO,WAAW;CAGpG,OAAO,IAAI,EAAE,OAAO,OAAO,UAAU,CAAC;AACxC;;AAIA,MAAa,gBACX,SACA,GAAG,gBACuB;CAE1B,MAAM,UAAU,OAAO,IAAI,EAAE,KAAK,QAAQ,IAAI,GAAG,GAAG,YAAY,IAAI,gBAAgB,CAAC;CAErF,QAAQ,OAAO,MAAM,GAAG,UAAU,QAAQ,QAAQ,KAAK,GAAG,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG;CACzF,OAAO,IAAI,EAAE,SAAS,GAAG,WAAW;AACtC"}
|
package/dist/task.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ShellWrapper } from "./shell.js";
|
|
2
|
+
//#region src/task.d.ts
|
|
3
|
+
interface TaskOptions {
|
|
4
|
+
desc?: string;
|
|
5
|
+
/** Keeps the task runnable but leaves it out of the task list. */
|
|
6
|
+
hidden?: boolean;
|
|
7
|
+
/** Additional names to run the task. */
|
|
8
|
+
alias?: string | string[];
|
|
9
|
+
}
|
|
10
|
+
interface TaskContext {
|
|
11
|
+
sh: typeof ShellWrapper;
|
|
12
|
+
}
|
|
13
|
+
type AsyncOrSyncReturn = Promise<void> | void;
|
|
14
|
+
type TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn;
|
|
15
|
+
export interface Task {
|
|
16
|
+
(): Promise<void>;
|
|
17
|
+
options: TaskOptions;
|
|
18
|
+
before: (...fns: TaskFn[]) => void;
|
|
19
|
+
after: (...fns: TaskFn[]) => void;
|
|
20
|
+
}
|
|
21
|
+
export declare const isTask: (value: unknown) => value is Task;
|
|
22
|
+
/** Registers a task that runs at most once per bask invocation, however many times it's called. */
|
|
23
|
+
export declare function task(fn: TaskFn): Task;
|
|
24
|
+
export declare function task(options: TaskOptions, fn: TaskFn): Task;
|
|
25
|
+
//#endregion
|
|
26
|
+
export {};
|
|
27
|
+
//# sourceMappingURL=task.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task.d.ts","names":[],"sources":["../src/task.ts"],"mappings":";;UAEU;EACR;;EAEA;;EAEA;;UAGQ;EACR,WAAW;;KAGR,oBAAoB;KAEpB,UAAU,KAAK,gBAAgB;iBAEnB;MACX;EACJ,SAAS;EACT,YAAY,KAAK;EACjB,WAAW,KAAK;;qBAKL,SAAM,mBAAqB,SAAS;;wBAQjC,KAAK,IAAI,SAAS;wBAClB,KAAK,SAAS,aAAa,IAAI,SAAS"}
|
package/dist/task.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { ShellWrapper } from "./shell.js";
|
|
2
|
+
//#region src/task.ts
|
|
3
|
+
const tasks = /* @__PURE__ */ new WeakSet();
|
|
4
|
+
const isTask = (value) => typeof value === "function" && tasks.has(value);
|
|
5
|
+
const failedTasks = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
/** Returns the innermost task that the error failed, so the CLI can name it. */
|
|
7
|
+
const getFailedTask = (error) => failedTasks.get(error);
|
|
8
|
+
function task(optionsOrFn, maybeFn) {
|
|
9
|
+
const [options, fn] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn];
|
|
10
|
+
if (!fn) throw new Error("task() needs a callback");
|
|
11
|
+
const ctx = { sh: ShellWrapper };
|
|
12
|
+
const beforeFns = [];
|
|
13
|
+
const afterFns = [];
|
|
14
|
+
let runPromise;
|
|
15
|
+
const assertNotStarted = () => {
|
|
16
|
+
if (runPromise) throw new Error("Can't add a hook to a task that has already started");
|
|
17
|
+
};
|
|
18
|
+
const before = (...fns) => {
|
|
19
|
+
assertNotStarted();
|
|
20
|
+
beforeFns.push(...fns);
|
|
21
|
+
};
|
|
22
|
+
const after = (...fns) => {
|
|
23
|
+
assertNotStarted();
|
|
24
|
+
afterFns.push(...fns);
|
|
25
|
+
};
|
|
26
|
+
const runAll = async () => {
|
|
27
|
+
for (const beforeFn of beforeFns) await beforeFn(ctx);
|
|
28
|
+
await fn(ctx);
|
|
29
|
+
for (const afterFn of afterFns) await afterFn(ctx);
|
|
30
|
+
};
|
|
31
|
+
const run = async () => {
|
|
32
|
+
runPromise ??= runAll();
|
|
33
|
+
try {
|
|
34
|
+
await runPromise;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, run);
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const newTask = Object.assign(run, {
|
|
41
|
+
options,
|
|
42
|
+
before,
|
|
43
|
+
after
|
|
44
|
+
});
|
|
45
|
+
tasks.add(newTask);
|
|
46
|
+
return newTask;
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { getFailedTask, isTask, task };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=task.js.map
|
package/dist/task.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import { ShellWrapper } from \"#shell.ts\"\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: typeof ShellWrapper\n}\n\ntype AsyncOrSyncReturn = Promise<void> | void\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 tasks = new WeakSet<object>()\n\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && tasks.has(value)\n\nconst failedTasks = new WeakMap<Error, object>()\n\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 ctx: TaskContext = { sh: ShellWrapper }\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\n const assertNotStarted = () => {\n if (runPromise) 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 () => {\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await beforeFn(ctx)\n await fn(ctx)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await afterFn(ctx)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const run = async () => {\n runPromise ??= runAll()\n try {\n await runPromise\n } catch (error) {\n // Record `run` only if no task has yet, because the innermost task's catch runs first.\n // `run` is the same object as the returned task.\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, run)\n throw error\n }\n }\n\n const newTask: Task = Object.assign(run, { options, before, after })\n tasks.add(newTask)\n return newTask\n}\n"],"mappings":";;AAyBA,MAAM,wBAAQ,IAAI,QAAgB;AAElC,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,MAAM,IAAI,KAAK;AAEvG,MAAM,8BAAc,IAAI,QAAuB;;AAG/C,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,MAAmB,EAAE,IAAI,aAAa;CAC5C,MAAM,YAAsB,CAAC;CAC7B,MAAM,WAAqB,CAAC;CAG5B,IAAI;CAEJ,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,YAAY;EAEzB,KAAK,MAAM,YAAY,WAAW,MAAM,SAAS,GAAG;EACpD,MAAM,GAAG,GAAG;EAEZ,KAAK,MAAM,WAAW,UAAU,MAAM,QAAQ,GAAG;CACnD;CAGA,MAAM,MAAM,YAAY;EACtB,eAAe,OAAO;EACtB,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,GAAG;GACjF,MAAM;EACR;CACF;CAEA,MAAM,UAAgB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACnE,MAAM,IAAI,OAAO;CACjB,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adamhl8/bask",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Write your tasks in TypeScript",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"build-tool",
|
|
7
|
+
"bun",
|
|
8
|
+
"cli",
|
|
9
|
+
"make",
|
|
10
|
+
"task-runner",
|
|
11
|
+
"typescript"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/adamhl8/bask",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/adamhl8/bask/issues"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": {
|
|
19
|
+
"name": "Adam Langbert",
|
|
20
|
+
"email": "adamhl@pm.me",
|
|
21
|
+
"url": "https://github.com/adamhl8"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/adamhl8/bask.git"
|
|
26
|
+
},
|
|
27
|
+
"bin": {
|
|
28
|
+
"bask": "./dist/cli.js"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist/"
|
|
32
|
+
],
|
|
33
|
+
"type": "module",
|
|
34
|
+
"imports": {
|
|
35
|
+
"#*": "./src/*"
|
|
36
|
+
},
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.js"
|
|
41
|
+
},
|
|
42
|
+
"./cli": {
|
|
43
|
+
"types": "./dist/cli.d.ts",
|
|
44
|
+
"import": "./dist/cli.js"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"prepare": "just prepare"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@adamhl8/configs": "^2.8.2",
|
|
55
|
+
"@arethetypeswrong/core": "^0.18.5",
|
|
56
|
+
"@commitlint/cli": "^21.2.3",
|
|
57
|
+
"@commitlint/config-conventional": "^21.2.3",
|
|
58
|
+
"@types/bun": "^1.4.3",
|
|
59
|
+
"knip": "^6.41.0",
|
|
60
|
+
"markdown-toc": "^1.2.0",
|
|
61
|
+
"oxfmt": "^0.73.0",
|
|
62
|
+
"oxlint": "^1.88.0",
|
|
63
|
+
"oxlint-tsgolint": "^7.0.2004",
|
|
64
|
+
"publint": "^0.3.25",
|
|
65
|
+
"release-it": "^21.1.1",
|
|
66
|
+
"release-it-git-cliff": "^0.2.0",
|
|
67
|
+
"tsdown": "^0.23.1",
|
|
68
|
+
"typescript": "^7.0.2"
|
|
69
|
+
}
|
|
70
|
+
}
|