@dunx/create-app 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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @dunx/create-app
2
+
3
+ Scaffolds a new [dunx](https://github.com/petarzarkov/dunx) application.
4
+
5
+ ```bash
6
+ bunx @dunx/create-app my-api
7
+ ```
8
+
9
+ > `bun create dunx-app` does **not** work, and deliberately is not advertised:
10
+ > `bun create <template>` resolves the unscoped npm package
11
+ > `create-<template>`, which this package — being scoped — is not.
12
+
13
+ ```
14
+ cd my-api
15
+ bun install
16
+ bun run start # http://localhost:3000/greetings
17
+ ```
18
+
19
+ ## Options
20
+
21
+ | Flag | Default | Meaning |
22
+ | ------------------- | ------------------ | -------------------------------------------------- |
23
+ | `--name <name>` | the directory name | Package name for the generated app |
24
+ | `--template <name>` | `minimal` | Which template to write |
25
+ | `--force` | off | Write into a directory that already has files |
26
+ | `--help` | | Print usage |
27
+
28
+ The name is validated against npm's rules **before** anything is created, because
29
+ an invalid one would otherwise surface as a confusing `bun install` failure inside
30
+ a directory you just made.
31
+
32
+ ## What it generates
33
+
34
+ The `minimal` template, which is the same app as
35
+ [`examples/minimal`](https://github.com/petarzarkov/dunx/tree/main/examples/minimal)
36
+ — a service, a controller, a module, `HttpFactory.create`, one test against a real
37
+ server, and the `bunfig.toml` preload line that makes constructor injection work.
38
+
39
+ Its `src/` is a **byte-for-byte copy** of that example, and a test in this package
40
+ fails if the two ever drift. The example is the one CI boots, so keeping them
41
+ identical is what makes the template trustworthy rather than merely plausible.
42
+
43
+ ## Two details worth knowing
44
+
45
+ **Versions are resolved at run time, not written into the template.** Every
46
+ `@dunx/*` range in the template manifest is `__DUNX_VERSION__`, replaced with a
47
+ caret range on this package's own version. dunx versions in lockstep — every
48
+ package shares one number and ships together — so the version doing the
49
+ scaffolding is by definition a set that works together. Writing versions into the
50
+ template would go stale on the next release.
51
+
52
+ **The template's `.gitignore` ships as `_gitignore`.** npm renames a published
53
+ `.gitignore` to `.npmignore`, which would leave every scaffolded app without one.
54
+ The scaffolder puts the dot back on write.
55
+
56
+ ## Programmatic use
57
+
58
+ ```ts
59
+ import { scaffold } from '@dunx/create-app';
60
+
61
+ const { directory, files } = await scaffold({
62
+ target: 'my-api',
63
+ name: '@acme/my-api',
64
+ });
65
+ ```
66
+
67
+ `scaffold` throws `ScaffoldError` for anything the caller can fix — an unknown
68
+ template, an unusable package name, a non-empty target without `force` — and lets
69
+ everything else propagate.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import { parseArgs } from "util";
6
+ import { relative } from "path";
7
+
8
+ // src/scaffold.ts
9
+ import { existsSync, readdirSync } from "fs";
10
+ import { basename, dirname, join, resolve } from "path";
11
+ import { fileURLToPath } from "url";
12
+ var {Glob } = globalThis.Bun;
13
+ var TEMPLATES = Object.freeze(["minimal"]);
14
+ var VERSION_PLACEHOLDER = "__DUNX_VERSION__";
15
+ var RENAMED = Object.freeze({ _gitignore: ".gitignore" });
16
+
17
+ class ScaffoldError extends Error {
18
+ name = "ScaffoldError";
19
+ }
20
+ var templatesRoot = () => resolve(dirname(fileURLToPath(import.meta.url)), "..", "templates");
21
+ var isValidPackageName = (name) => /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name);
22
+ var readPackageVersion = async () => {
23
+ const file = Bun.file(join(templatesRoot(), "..", "package.json"));
24
+ const json = await file.json();
25
+ return json.version ?? "0.0.0";
26
+ };
27
+ var scaffold = async (options) => {
28
+ const template = options.template ?? "minimal";
29
+ if (!TEMPLATES.includes(template)) {
30
+ throw new ScaffoldError(`Unknown template "${template}". Available: ${TEMPLATES.join(", ")}.`);
31
+ }
32
+ const directory = resolve(options.cwd ?? process.cwd(), options.target);
33
+ const name = options.name ?? basename(directory);
34
+ if (!isValidPackageName(name)) {
35
+ throw new ScaffoldError(`"${name}" is not a usable package name. Pass --name to choose one.`);
36
+ }
37
+ if (existsSync(directory) && readdirSync(directory).length > 0 && options.force !== true) {
38
+ throw new ScaffoldError(`${directory} is not empty. Pass --force to write into it anyway.`);
39
+ }
40
+ const source = join(templatesRoot(), template);
41
+ if (!existsSync(source)) {
42
+ throw new ScaffoldError(`Template "${template}" is missing from ${source}.`);
43
+ }
44
+ const version = options.version ?? `^${await readPackageVersion()}`;
45
+ const written = [];
46
+ for await (const relative of new Glob("**/*").scan({
47
+ cwd: source,
48
+ dot: true,
49
+ onlyFiles: true
50
+ })) {
51
+ const base = relative.split("/").at(-1) ?? relative;
52
+ const renamed = RENAMED[base];
53
+ const target = renamed === undefined ? relative : join(dirname(relative), renamed);
54
+ const contents = await Bun.file(join(source, relative)).text();
55
+ await Bun.write(join(directory, target), contents.replaceAll(VERSION_PLACEHOLDER, version).replaceAll("__DUNX_APP_NAME__", name));
56
+ written.push(target);
57
+ }
58
+ return { directory, name, template, files: written.sort() };
59
+ };
60
+
61
+ // src/cli.ts
62
+ var USAGE = `Scaffold a new dunx application.
63
+
64
+ bunx @dunx/create-app <directory> [options]
65
+
66
+ Options:
67
+ --name <name> package name for the app (default: the directory name)
68
+ --template <name> ${TEMPLATES.join(" | ")} (default: minimal)
69
+ --force write into a directory that already has files in it
70
+ --help print this
71
+ `;
72
+ function fail(message) {
73
+ console.error(message);
74
+ process.exit(1);
75
+ }
76
+ var { values, positionals } = parseArgs({
77
+ args: Bun.argv.slice(2),
78
+ allowPositionals: true,
79
+ options: {
80
+ name: { type: "string" },
81
+ template: { type: "string" },
82
+ force: { type: "boolean", default: false },
83
+ help: { type: "boolean", default: false, short: "h" }
84
+ }
85
+ });
86
+ if (values.help === true) {
87
+ console.log(USAGE);
88
+ process.exit(0);
89
+ }
90
+ var target = positionals[0];
91
+ if (target === undefined) {
92
+ fail(`Missing the target directory.
93
+
94
+ ${USAGE}`);
95
+ }
96
+ try {
97
+ const result = await scaffold({
98
+ target,
99
+ ...values.name === undefined ? {} : { name: values.name },
100
+ ...values.template === undefined ? {} : { template: values.template },
101
+ force: values.force === true
102
+ });
103
+ const where = relative(process.cwd(), result.directory) || ".";
104
+ console.log(`Created ${result.name} in ${where}/`);
105
+ console.log(` ${result.files.length} files from the ${result.template} template
106
+ `);
107
+ console.log("Next:");
108
+ console.log(` cd ${where}`);
109
+ console.log(" bun install");
110
+ console.log(" bun run start");
111
+ } catch (error) {
112
+ if (error instanceof ScaffoldError)
113
+ fail(error.message);
114
+ throw error;
115
+ }
116
+
117
+ //# debugId=E45CB9A6B97979B864756E2164756E21
118
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cli.ts", "../src/scaffold.ts"],
4
+ "sourcesContent": [
5
+ "#!/usr/bin/env bun\nimport { parseArgs } from 'node:util';\nimport { relative } from 'node:path';\nimport { scaffold, ScaffoldError, TEMPLATES } from './scaffold.js';\nimport type { TemplateName } from './scaffold.js';\n\nconst USAGE = `Scaffold a new dunx application.\n\n bunx @dunx/create-app <directory> [options]\n\nOptions:\n --name <name> package name for the app (default: the directory name)\n --template <name> ${TEMPLATES.join(' | ')} (default: minimal)\n --force write into a directory that already has files in it\n --help print this\n`;\n\n// A declaration, not a `const` arrow: control-flow analysis only narrows past a\n// never-returning call when the callee is declared this way, so `target` stays\n// `string | undefined` below if this is an arrow.\nfunction fail(message: string): never {\n console.error(message);\n process.exit(1);\n}\n\nconst { values, positionals } = parseArgs({\n args: Bun.argv.slice(2),\n allowPositionals: true,\n options: {\n name: { type: 'string' },\n template: { type: 'string' },\n force: { type: 'boolean', default: false },\n help: { type: 'boolean', default: false, short: 'h' },\n },\n});\n\nif (values.help === true) {\n console.log(USAGE);\n process.exit(0);\n}\n\nconst target = positionals[0];\nif (target === undefined) {\n fail(`Missing the target directory.\\n\\n${USAGE}`);\n}\n\ntry {\n const result = await scaffold({\n target,\n ...(values.name === undefined ? {} : { name: values.name }),\n ...(values.template === undefined\n ? {}\n : { template: values.template as TemplateName }),\n force: values.force === true,\n });\n\n const where = relative(process.cwd(), result.directory) || '.';\n console.log(`Created ${result.name} in ${where}/`);\n console.log(\n ` ${result.files.length} files from the ${result.template} template\\n`,\n );\n console.log('Next:');\n console.log(` cd ${where}`);\n console.log(' bun install');\n console.log(' bun run start');\n} catch (error) {\n if (error instanceof ScaffoldError) fail(error.message);\n throw error;\n}\n",
6
+ "import { existsSync, readdirSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Glob } from 'bun';\n\n/** The templates that ship with the package, as `templates/<name>/`. */\nexport const TEMPLATES = Object.freeze(['minimal'] as const);\nexport type TemplateName = (typeof TEMPLATES)[number];\n\n/**\n * Every `@dunx/*` version in a template manifest is this placeholder. Versioning\n * is lockstep, so the right version to install is whatever version of\n * `@dunx/create-app` is doing the scaffolding — resolved at run time rather than\n * written into the template, which would go stale on the next release.\n */\nexport const VERSION_PLACEHOLDER = '__DUNX_VERSION__';\n\n/** npm renames a published `.gitignore` to `.npmignore`, so it ships prefixed. */\nconst RENAMED = Object.freeze({ _gitignore: '.gitignore' });\n\nexport interface ScaffoldOptions {\n /** Directory to create. Relative paths resolve against `cwd`. */\n readonly target: string;\n /** Package name for the generated app. Defaults to the target's basename. */\n readonly name?: string;\n readonly template?: TemplateName;\n /** Write into a directory that already has files in it. */\n readonly force?: boolean;\n readonly cwd?: string;\n /** Overrides the version written into the generated manifest. */\n readonly version?: string;\n}\n\nexport interface ScaffoldResult {\n readonly directory: string;\n readonly name: string;\n readonly template: TemplateName;\n readonly files: readonly string[];\n}\n\nexport class ScaffoldError extends Error {\n override readonly name = 'ScaffoldError';\n}\n\n/**\n * `dist/index.js` and `dist/cli.js` both sit one level under the package root, so\n * `../templates` resolves the same from either. In the source tree it resolves\n * from `src/`, which is the same depth — so tests exercise the real path rather\n * than a special case.\n *\n * `fileURLToPath`, not `new URL(...).pathname`: the latter stays percent-encoded,\n * so an install under a directory with a space in it looks for `space%20test/`\n * and reports the template missing. On Windows it is worse — it yields a\n * leading-slash, drive-lettered path that resolves nowhere.\n */\nconst templatesRoot = (): string =>\n resolve(dirname(fileURLToPath(import.meta.url)), '..', 'templates');\n\n/**\n * npm forbids uppercase and a leading dot or underscore, and a scope is legal.\n * Checked here because the failure would otherwise surface as a confusing\n * `bun install` error inside a directory the user just created.\n */\nconst isValidPackageName = (name: string): boolean =>\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name);\n\nconst readPackageVersion = async (): Promise<string> => {\n const file = Bun.file(join(templatesRoot(), '..', 'package.json'));\n const json = (await file.json()) as { version?: string };\n return json.version ?? '0.0.0';\n};\n\nexport const scaffold = async (\n options: ScaffoldOptions,\n): Promise<ScaffoldResult> => {\n const template = options.template ?? 'minimal';\n if (!TEMPLATES.includes(template)) {\n throw new ScaffoldError(\n `Unknown template \"${template}\". Available: ${TEMPLATES.join(', ')}.`,\n );\n }\n\n const directory = resolve(options.cwd ?? process.cwd(), options.target);\n const name = options.name ?? basename(directory);\n\n if (!isValidPackageName(name)) {\n throw new ScaffoldError(\n `\"${name}\" is not a usable package name. Pass --name to choose one.`,\n );\n }\n\n if (\n existsSync(directory) &&\n readdirSync(directory).length > 0 &&\n options.force !== true\n ) {\n throw new ScaffoldError(\n `${directory} is not empty. Pass --force to write into it anyway.`,\n );\n }\n\n const source = join(templatesRoot(), template);\n if (!existsSync(source)) {\n throw new ScaffoldError(\n `Template \"${template}\" is missing from ${source}.`,\n );\n }\n\n const version = options.version ?? `^${await readPackageVersion()}`;\n const written: string[] = [];\n\n // `**/*` with `dot: true` so a template can carry a dotfile that npm did not\n // rename; the explicit `_gitignore` mapping covers the one that it does.\n for await (const relative of new Glob('**/*').scan({\n cwd: source,\n dot: true,\n onlyFiles: true,\n })) {\n const base = relative.split('/').at(-1) ?? relative;\n const renamed = (RENAMED as Record<string, string | undefined>)[base];\n const target =\n renamed === undefined ? relative : join(dirname(relative), renamed);\n\n const contents = await Bun.file(join(source, relative)).text();\n // `Bun.write` creates parent directories, so there is no mkdir pass.\n await Bun.write(\n join(directory, target),\n contents\n .replaceAll(VERSION_PLACEHOLDER, version)\n .replaceAll('__DUNX_APP_NAME__', name),\n );\n written.push(target);\n }\n\n return { directory, name, template, files: written.sort() };\n};\n"
7
+ ],
8
+ "mappings": ";;;;AACA;AACA;;;ACFA;AACA;AACA;AACA;AAGO,IAAM,YAAY,OAAO,OAAO,CAAC,SAAS,CAAU;AASpD,IAAM,sBAAsB;AAGnC,IAAM,UAAU,OAAO,OAAO,EAAE,YAAY,aAAa,CAAC;AAAA;AAsBnD,MAAM,sBAAsB,MAAM;AAAA,EACrB,OAAO;AAC3B;AAaA,IAAM,gBAAgB,MACpB,QAAQ,QAAQ,cAAc,YAAY,GAAG,CAAC,GAAG,MAAM,WAAW;AAOpE,IAAM,qBAAqB,CAAC,SAC1B,6DAA6D,KAAK,IAAI;AAExE,IAAM,qBAAqB,YAA6B;AAAA,EACtD,MAAM,OAAO,IAAI,KAAK,KAAK,cAAc,GAAG,MAAM,cAAc,CAAC;AAAA,EACjE,MAAM,OAAQ,MAAM,KAAK,KAAK;AAAA,EAC9B,OAAO,KAAK,WAAW;AAAA;AAGlB,IAAM,WAAW,OACtB,YAC4B;AAAA,EAC5B,MAAM,WAAW,QAAQ,YAAY;AAAA,EACrC,IAAI,CAAC,UAAU,SAAS,QAAQ,GAAG;AAAA,IACjC,MAAM,IAAI,cACR,qBAAqB,yBAAyB,UAAU,KAAK,IAAI,IACnE;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,QAAQ,QAAQ,OAAO,QAAQ,IAAI,GAAG,QAA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AA,EACd,IAAI,iBAAiB;AAAA,IAAe,KAAK,MAAM,OAAO;AAAA,EACtD,MAAM;AAAA;",
9
+ "debugId": "E45CB9A6B97979B864756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1 @@
1
+ export { scaffold, ScaffoldError, TEMPLATES, VERSION_PLACEHOLDER, type ScaffoldOptions, type ScaffoldResult, type TemplateName, } from './scaffold.js';
package/dist/index.js ADDED
@@ -0,0 +1,62 @@
1
+ // @bun
2
+ // src/scaffold.ts
3
+ import { existsSync, readdirSync } from "fs";
4
+ import { basename, dirname, join, resolve } from "path";
5
+ import { fileURLToPath } from "url";
6
+ var {Glob } = globalThis.Bun;
7
+ var TEMPLATES = Object.freeze(["minimal"]);
8
+ var VERSION_PLACEHOLDER = "__DUNX_VERSION__";
9
+ var RENAMED = Object.freeze({ _gitignore: ".gitignore" });
10
+
11
+ class ScaffoldError extends Error {
12
+ name = "ScaffoldError";
13
+ }
14
+ var templatesRoot = () => resolve(dirname(fileURLToPath(import.meta.url)), "..", "templates");
15
+ var isValidPackageName = (name) => /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name);
16
+ var readPackageVersion = async () => {
17
+ const file = Bun.file(join(templatesRoot(), "..", "package.json"));
18
+ const json = await file.json();
19
+ return json.version ?? "0.0.0";
20
+ };
21
+ var scaffold = async (options) => {
22
+ const template = options.template ?? "minimal";
23
+ if (!TEMPLATES.includes(template)) {
24
+ throw new ScaffoldError(`Unknown template "${template}". Available: ${TEMPLATES.join(", ")}.`);
25
+ }
26
+ const directory = resolve(options.cwd ?? process.cwd(), options.target);
27
+ const name = options.name ?? basename(directory);
28
+ if (!isValidPackageName(name)) {
29
+ throw new ScaffoldError(`"${name}" is not a usable package name. Pass --name to choose one.`);
30
+ }
31
+ if (existsSync(directory) && readdirSync(directory).length > 0 && options.force !== true) {
32
+ throw new ScaffoldError(`${directory} is not empty. Pass --force to write into it anyway.`);
33
+ }
34
+ const source = join(templatesRoot(), template);
35
+ if (!existsSync(source)) {
36
+ throw new ScaffoldError(`Template "${template}" is missing from ${source}.`);
37
+ }
38
+ const version = options.version ?? `^${await readPackageVersion()}`;
39
+ const written = [];
40
+ for await (const relative of new Glob("**/*").scan({
41
+ cwd: source,
42
+ dot: true,
43
+ onlyFiles: true
44
+ })) {
45
+ const base = relative.split("/").at(-1) ?? relative;
46
+ const renamed = RENAMED[base];
47
+ const target = renamed === undefined ? relative : join(dirname(relative), renamed);
48
+ const contents = await Bun.file(join(source, relative)).text();
49
+ await Bun.write(join(directory, target), contents.replaceAll(VERSION_PLACEHOLDER, version).replaceAll("__DUNX_APP_NAME__", name));
50
+ written.push(target);
51
+ }
52
+ return { directory, name, template, files: written.sort() };
53
+ };
54
+ export {
55
+ scaffold,
56
+ VERSION_PLACEHOLDER,
57
+ TEMPLATES,
58
+ ScaffoldError
59
+ };
60
+
61
+ //# debugId=87D57428F30FA51264756E2164756E21
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/scaffold.ts"],
4
+ "sourcesContent": [
5
+ "import { existsSync, readdirSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Glob } from 'bun';\n\n/** The templates that ship with the package, as `templates/<name>/`. */\nexport const TEMPLATES = Object.freeze(['minimal'] as const);\nexport type TemplateName = (typeof TEMPLATES)[number];\n\n/**\n * Every `@dunx/*` version in a template manifest is this placeholder. Versioning\n * is lockstep, so the right version to install is whatever version of\n * `@dunx/create-app` is doing the scaffolding — resolved at run time rather than\n * written into the template, which would go stale on the next release.\n */\nexport const VERSION_PLACEHOLDER = '__DUNX_VERSION__';\n\n/** npm renames a published `.gitignore` to `.npmignore`, so it ships prefixed. */\nconst RENAMED = Object.freeze({ _gitignore: '.gitignore' });\n\nexport interface ScaffoldOptions {\n /** Directory to create. Relative paths resolve against `cwd`. */\n readonly target: string;\n /** Package name for the generated app. Defaults to the target's basename. */\n readonly name?: string;\n readonly template?: TemplateName;\n /** Write into a directory that already has files in it. */\n readonly force?: boolean;\n readonly cwd?: string;\n /** Overrides the version written into the generated manifest. */\n readonly version?: string;\n}\n\nexport interface ScaffoldResult {\n readonly directory: string;\n readonly name: string;\n readonly template: TemplateName;\n readonly files: readonly string[];\n}\n\nexport class ScaffoldError extends Error {\n override readonly name = 'ScaffoldError';\n}\n\n/**\n * `dist/index.js` and `dist/cli.js` both sit one level under the package root, so\n * `../templates` resolves the same from either. In the source tree it resolves\n * from `src/`, which is the same depth — so tests exercise the real path rather\n * than a special case.\n *\n * `fileURLToPath`, not `new URL(...).pathname`: the latter stays percent-encoded,\n * so an install under a directory with a space in it looks for `space%20test/`\n * and reports the template missing. On Windows it is worse — it yields a\n * leading-slash, drive-lettered path that resolves nowhere.\n */\nconst templatesRoot = (): string =>\n resolve(dirname(fileURLToPath(import.meta.url)), '..', 'templates');\n\n/**\n * npm forbids uppercase and a leading dot or underscore, and a scope is legal.\n * Checked here because the failure would otherwise surface as a confusing\n * `bun install` error inside a directory the user just created.\n */\nconst isValidPackageName = (name: string): boolean =>\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name);\n\nconst readPackageVersion = async (): Promise<string> => {\n const file = Bun.file(join(templatesRoot(), '..', 'package.json'));\n const json = (await file.json()) as { version?: string };\n return json.version ?? '0.0.0';\n};\n\nexport const scaffold = async (\n options: ScaffoldOptions,\n): Promise<ScaffoldResult> => {\n const template = options.template ?? 'minimal';\n if (!TEMPLATES.includes(template)) {\n throw new ScaffoldError(\n `Unknown template \"${template}\". Available: ${TEMPLATES.join(', ')}.`,\n );\n }\n\n const directory = resolve(options.cwd ?? process.cwd(), options.target);\n const name = options.name ?? basename(directory);\n\n if (!isValidPackageName(name)) {\n throw new ScaffoldError(\n `\"${name}\" is not a usable package name. Pass --name to choose one.`,\n );\n }\n\n if (\n existsSync(directory) &&\n readdirSync(directory).length > 0 &&\n options.force !== true\n ) {\n throw new ScaffoldError(\n `${directory} is not empty. Pass --force to write into it anyway.`,\n );\n }\n\n const source = join(templatesRoot(), template);\n if (!existsSync(source)) {\n throw new ScaffoldError(\n `Template \"${template}\" is missing from ${source}.`,\n );\n }\n\n const version = options.version ?? `^${await readPackageVersion()}`;\n const written: string[] = [];\n\n // `**/*` with `dot: true` so a template can carry a dotfile that npm did not\n // rename; the explicit `_gitignore` mapping covers the one that it does.\n for await (const relative of new Glob('**/*').scan({\n cwd: source,\n dot: true,\n onlyFiles: true,\n })) {\n const base = relative.split('/').at(-1) ?? relative;\n const renamed = (RENAMED as Record<string, string | undefined>)[base];\n const target =\n renamed === undefined ? relative : join(dirname(relative), renamed);\n\n const contents = await Bun.file(join(source, relative)).text();\n // `Bun.write` creates parent directories, so there is no mkdir pass.\n await Bun.write(\n join(directory, target),\n contents\n .replaceAll(VERSION_PLACEHOLDER, version)\n .replaceAll('__DUNX_APP_NAME__', name),\n );\n written.push(target);\n }\n\n return { directory, name, template, files: written.sort() };\n};\n"
6
+ ],
7
+ "mappings": ";;AAAA;AACA;AACA;AACA;AAGO,IAAM,YAAY,OAAO,OAAO,CAAC,SAAS,CAAU;AASpD,IAAM,sBAAsB;AAGnC,IAAM,UAAU,OAAO,OAAO,EAAE,YAAY,aAAa,CAAC;AAAA;AAsBnD,MAAM,sBAAsB,MAAM;AAAA,EACrB,OAAO;AAC3B;AAaA,IAAM,gBAAgB,MACpB,QAAQ,QAAQ,cAAc,YAAY,GAAG,CAAC,GAAG,MAAM,WAAW;AAOpE,IAAM,qBAAqB,CAAC,SAC1B,6DAA6D,KAAK,IAAI;AAExE,IAAM,qBAAqB,YAA6B;AAAA,EACtD,MAAM,OAAO,IAAI,KAAK,KAAK,cAAc,GAAG,MAAM,cAAc,CAAC;AAAA,EACjE,MAAM,OAAQ,MAAM,KAAK,KAAK;AAAA,EAC9B,OAAO,KAAK,WAAW;AAAA;AAGlB,IAAM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,SACG,WAAW,qBAAqB,OAAO,EACvC,WAAW,qBAAqB,IAAI,CACzC;AAAA,IACA,QAAQ,KAAK,MAAM;AAAA,EACrB;AAAA,EAEA,OAAO,EAAE,WAAW,MAAM,UAAU,OAAO,QAAQ,KAAK,EAAE;AAAA;",
8
+ "debugId": "87D57428F30FA51264756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,32 @@
1
+ /** The templates that ship with the package, as `templates/<name>/`. */
2
+ export declare const TEMPLATES: readonly ["minimal"];
3
+ export type TemplateName = (typeof TEMPLATES)[number];
4
+ /**
5
+ * Every `@dunx/*` version in a template manifest is this placeholder. Versioning
6
+ * is lockstep, so the right version to install is whatever version of
7
+ * `@dunx/create-app` is doing the scaffolding — resolved at run time rather than
8
+ * written into the template, which would go stale on the next release.
9
+ */
10
+ export declare const VERSION_PLACEHOLDER = "__DUNX_VERSION__";
11
+ export interface ScaffoldOptions {
12
+ /** Directory to create. Relative paths resolve against `cwd`. */
13
+ readonly target: string;
14
+ /** Package name for the generated app. Defaults to the target's basename. */
15
+ readonly name?: string;
16
+ readonly template?: TemplateName;
17
+ /** Write into a directory that already has files in it. */
18
+ readonly force?: boolean;
19
+ readonly cwd?: string;
20
+ /** Overrides the version written into the generated manifest. */
21
+ readonly version?: string;
22
+ }
23
+ export interface ScaffoldResult {
24
+ readonly directory: string;
25
+ readonly name: string;
26
+ readonly template: TemplateName;
27
+ readonly files: readonly string[];
28
+ }
29
+ export declare class ScaffoldError extends Error {
30
+ readonly name = "ScaffoldError";
31
+ }
32
+ export declare const scaffold: (options: ScaffoldOptions) => Promise<ScaffoldResult>;
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@dunx/create-app",
3
+ "version": "0.1.0",
4
+ "description": "Scaffold a new dunx application — bunx @dunx/create-app my-api",
5
+ "keywords": [
6
+ "bun",
7
+ "create",
8
+ "dunx",
9
+ "scaffold",
10
+ "starter"
11
+ ],
12
+ "homepage": "https://github.com/petarzarkov/dunx/tree/main/packages/create-app#readme",
13
+ "license": "MIT",
14
+ "author": {
15
+ "name": "Petar Zarkov",
16
+ "email": "pzarko1@gmail.com",
17
+ "url": "https://github.com/petarzarkov"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/petarzarkov/dunx.git",
22
+ "directory": "packages/create-app"
23
+ },
24
+ "bin": {
25
+ "create-dunx-app": "dist/cli.js"
26
+ },
27
+ "files": [
28
+ "LICENSE",
29
+ "README.md",
30
+ "dist",
31
+ "templates"
32
+ ],
33
+ "type": "module",
34
+ "main": "./dist/index.js",
35
+ "types": "./dist/index.d.ts",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/index.d.ts",
39
+ "import": "./dist/index.js"
40
+ }
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "scripts": {
46
+ "build": "bun ../../scripts/build-package.ts",
47
+ "test": "bun test --bail",
48
+ "test:cov": "bun test --coverage",
49
+ "typecheck": "tsc --noEmit"
50
+ },
51
+ "dependencies": {},
52
+ "peerDependencies": {
53
+ "@types/bun": ">=1.3.0"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "@types/bun": {
57
+ "optional": true
58
+ }
59
+ },
60
+ "engines": {
61
+ "bun": ">=1.3.0"
62
+ }
63
+ }
@@ -0,0 +1,45 @@
1
+ # __DUNX_APP_NAME__
2
+
3
+ A [dunx](https://github.com/petarzarkov/dunx) application.
4
+
5
+ ```bash
6
+ bun install
7
+ bun run start # http://localhost:3000/greetings
8
+ bun test
9
+ ```
10
+
11
+ ## What is here
12
+
13
+ | File | Why |
14
+ | --------------------------- | --------------------------------------------------------------- |
15
+ | `src/main.ts` | Builds the container, discovers routes, starts `Bun.serve` |
16
+ | `src/app.module.ts` | The root module — `controllers` get routes, `providers` do not |
17
+ | `src/greetings.service.ts` | A provider, injected by constructor type with no annotation |
18
+ | `src/greetings.controller.ts` | Routes, returning plain objects |
19
+ | `src/app.test.ts` | The whole app behind a real server on port 0 |
20
+ | `bunfig.toml` | The preload line that makes constructor injection work |
21
+
22
+ ## The one line that matters
23
+
24
+ ```toml
25
+ preload = ["@dunx/transform/preload"]
26
+ ```
27
+
28
+ `@dunx/transform` reads each class's constructor parameter types when the file
29
+ loads and records them, so the container can resolve them before calling `new`.
30
+ Without it, providers are constructed with no arguments and boot fails saying so —
31
+ it is not a silent `undefined`.
32
+
33
+ That is also why there is no `@Injectable()` and no `@Inject()`. Being listed in a
34
+ module's `providers` is what makes a class injectable, and TC39 standard decorators
35
+ have no parameter decorators, so `@Inject()` does not exist.
36
+
37
+ ## Next
38
+
39
+ - Add validation: give a route a schema and the body arrives typed and coerced.
40
+ Any Standard Schema validator works — zod, Valibot, ArkType.
41
+ - Add a database: `@dunx/infra/db` is drizzle over `bun:sqlite` and `Bun.SQL`.
42
+ - Serve an OpenAPI document and a page that can call your routes: `@dunx/openapi`.
43
+
44
+ The [examples](https://github.com/petarzarkov/dunx/tree/main/examples) go in that
45
+ order — `minimal`, then `databases` and `testing`, then `full`.
@@ -0,0 +1,5 @@
1
+ node_modules
2
+ dist
3
+ *.log
4
+ .env
5
+ .env.local
@@ -0,0 +1,7 @@
1
+ # The one line that makes constructor injection work. The compiler plugin records
2
+ # each class's constructor parameter types so the container can resolve them.
3
+ # Without it, providers are built with no arguments and boot fails saying so.
4
+ preload = ["@dunx/transform/preload"]
5
+
6
+ [test]
7
+ preload = ["@dunx/transform/preload"]
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "__DUNX_APP_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "start": "bun src/main.ts",
8
+ "test": "bun test",
9
+ "typecheck": "tsc --noEmit"
10
+ },
11
+ "dependencies": {
12
+ "@dunx/core": "__DUNX_VERSION__",
13
+ "@dunx/http": "__DUNX_VERSION__",
14
+ "@dunx/transform": "__DUNX_VERSION__"
15
+ },
16
+ "devDependencies": {
17
+ "@dunx/testing": "__DUNX_VERSION__",
18
+ "@types/bun": ">=1.3.0",
19
+ "typescript": "^5.7.0"
20
+ },
21
+ "engines": {
22
+ "bun": ">=1.3.0"
23
+ }
24
+ }
@@ -0,0 +1,14 @@
1
+ import { Module } from '@dunx/core';
2
+ import { GreetingsController } from './greetings.controller.js';
3
+ import { GreetingsService } from './greetings.service.js';
4
+
5
+ /**
6
+ * The root module. `controllers` are discovered for routes, `providers` are
7
+ * everything else. Import order is construction order, and shutdown runs in
8
+ * reverse — which matters once there is a database to close.
9
+ */
10
+ @Module({
11
+ controllers: [GreetingsController],
12
+ providers: [GreetingsService],
13
+ })
14
+ export class AppModule {}
@@ -0,0 +1,22 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createTestServer } from '@dunx/testing';
3
+ import { AppModule } from './app.module.js';
4
+
5
+ /**
6
+ * The whole app behind a real `Bun.serve` on port 0. This is also what CI runs to
7
+ * prove the example still boots — see `examples/testing` for overrides and the
8
+ * rest of `@dunx/testing`.
9
+ */
10
+ describe('minimal', () => {
11
+ test('serves the greeting', async () => {
12
+ const server = await createTestServer({ modules: [AppModule] });
13
+
14
+ const { status, body } = await server.json<{ greeting: string }>(
15
+ 'greetings/ada',
16
+ );
17
+
18
+ expect(status).toBe(200);
19
+ expect(body.greeting).toBe('hello, ada');
20
+ await server.close();
21
+ });
22
+ });
@@ -0,0 +1,29 @@
1
+ import { Controller, Get, type Input, type RouteSchemas } from '@dunx/http';
2
+ import { GreetingsService } from './greetings.service.js';
3
+
4
+ /**
5
+ * A controller is a provider with routes on it. `GreetingsService` in the
6
+ * constructor is resolved the same way the service's own `Logger` was.
7
+ *
8
+ * Returning a plain object is enough — `@dunx/http` serialises it. There is no
9
+ * `Response.json()` to remember and no `res` to forget to send.
10
+ */
11
+ @Controller('greetings')
12
+ export class GreetingsController {
13
+ constructor(private readonly greetings: GreetingsService) {}
14
+
15
+ @Get('/')
16
+ index(): { routes: readonly string[] } {
17
+ return { routes: ['GET /greetings', 'GET /greetings/:name'] };
18
+ }
19
+
20
+ /**
21
+ * No schemas are declared, so a path param stays on `input.req.params` as a
22
+ * string. Declaring a `params` schema is what makes it typed and coerced —
23
+ * `examples/full` does that; this one is showing the shape, not validation.
24
+ */
25
+ @Get('/:name')
26
+ one(input: Input<RouteSchemas>): { greeting: string; served: number } {
27
+ return this.greetings.greet(input.req.params['name'] ?? 'world');
28
+ }
29
+ }
@@ -0,0 +1,26 @@
1
+ import { Logger, type OnInit } from '@dunx/core';
2
+
3
+ /**
4
+ * A provider. No decorator, no registration boilerplate — being listed in a
5
+ * module's `providers` is what makes it injectable.
6
+ *
7
+ * `Logger` in the constructor is the whole dependency injection story: the
8
+ * container reads the parameter's type and resolves it. Nothing bound `Logger`
9
+ * here, so it gets core's default `ConsoleLogger`, which writes one JSON line
10
+ * per entry and needs no dependency.
11
+ */
12
+ export class GreetingsService implements OnInit {
13
+ #greeted = 0;
14
+
15
+ constructor(private readonly logger: Logger) {}
16
+
17
+ /** Runs after the whole graph is constructed, in dependency order. */
18
+ onInit(): void {
19
+ this.logger.info('greetings ready');
20
+ }
21
+
22
+ greet(name: string): { greeting: string; served: number } {
23
+ this.#greeted++;
24
+ return { greeting: `hello, ${name}`, served: this.#greeted };
25
+ }
26
+ }
@@ -0,0 +1,15 @@
1
+ import { HttpFactory } from '@dunx/http';
2
+ import { AppModule } from './app.module.js';
3
+
4
+ /**
5
+ * `create()` builds the container and discovers routes; `listen()` builds the
6
+ * `Bun.serve` route table and returns the URL. `enableShutdownHooks()` makes
7
+ * `ctrl-c` drain the graph in reverse construction order.
8
+ */
9
+ const app = await HttpFactory.create(AppModule);
10
+ app.enableShutdownHooks();
11
+
12
+ const url = await app.listen(3000);
13
+ console.log(`listening on ${url}greetings`);
14
+
15
+ await app.closed;
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "lib": ["ESNext"],
5
+ "module": "nodenext",
6
+ "moduleResolution": "nodenext",
7
+ "types": ["bun"],
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "exactOptionalPropertyTypes": true,
11
+ "noImplicitOverride": true,
12
+ "noPropertyAccessFromIndexSignature": true,
13
+ "verbatimModuleSyntax": true,
14
+ "skipLibCheck": true,
15
+ "noEmit": true
16
+ },
17
+ "include": ["src"],
18
+ "exclude": ["node_modules"]
19
+ }