diff --git a/.eslintrc b/.eslintrc
index 93ac8338aa..01f1e369c8 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -1,10 +1,19 @@
{
- "extends": [
- "@nuxtjs/eslint-config-typescript"
- ],
+ "extends": ["eslint-config-unjs"],
"rules": {
- "import/no-named-as-default-member": "off",
- "import/default": "off",
- "no-console": "off"
+ "space-before-function-paren": 0,
+ "arrow-parens": 0,
+ "comma-dangle": 0,
+ "semi": 0,
+ "unicorn/prevent-abbreviations": 0,
+ "quotes": 0,
+ "keyword-spacing": 0,
+ "no-undef": 0,
+ "unicorn/catch-error-name": 0,
+ "unicorn/no-null": 0,
+ "unicorn/no-useless-undefined": 0,
+ "unicorn/no-await-expression-member": 0,
+ "unicorn/no-array-push-push": 0,
+ "unicorn/filename-case": 0
}
}
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index bcad0c0fc8..883c5354f0 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -35,4 +35,3 @@ Examples:
- [ ] I have linked an issue or discussion.
- [ ] I have updated the documentation accordingly.
-
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2317e2c463..8875ddc1ef 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -19,7 +19,7 @@ jobs:
- run: corepack enable
- uses: actions/setup-node@v3
with:
- node-version: '16'
+ node-version: "16"
cache: pnpm
- run: pnpm install
- run: pnpm lint
diff --git a/.prettierrc b/.prettierrc
new file mode 100644
index 0000000000..0967ef424b
--- /dev/null
+++ b/.prettierrc
@@ -0,0 +1 @@
+{}
diff --git a/README.md b/README.md
index 2c63f161ed..9661d0b775 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
-
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![npm-edge version][npm-edge-version-src]][npm-edge-version-href]
[![npm-edge downloads][npm-edge-downloads-src]][npm-edge-downloads-href]
+
⚗️ Nitro
@@ -12,18 +12,18 @@
Nitro provides a powerful toolchain and a runtime framework from the [UnJS](https://github.com/unjs) ecosystem to build and deploy **any JavaScript server, anywhere!**
- ❯ 🐇 **Rapid development** experience with hot module replacement
- ❯ 😌 **Multi-provider** deployments with a single codebase and zero-configuration
- ❯ 💼 **Portable and compact** deployments without `node_modules` dependency
- ❯ 📁 **Directory structure** aware to register API routes and more with zero configuration
- ❯ 🤏 **Minimal Design** to fit into any solution with minimum overhead
- ❯ 🚀 **Code-splitting** and async chunk loading for fast server startup time
- ❯ 👕 **TypeScript** fully supported
- ❯ 💾 **Multi-driver storage** and caching layer
- ❯ 💰 **Route caching** and static **pre-rendering** with built-in crawler
- ❯ 🐱 **Hackable** to extend almost any part of nitro using options
- ❯ ✨ **Auto imports** for lazy folks and a tidy minimal codebase
- ❯ 🏛️ **Best-effort compatibility** for using legacy npm packages and mocking Node.js modules
+❯ 🐇 **Rapid development** experience with hot module replacement
+❯ 😌 **Multi-provider** deployments with a single codebase and zero-configuration
+❯ 💼 **Portable and compact** deployments without `node_modules` dependency
+❯ 📁 **Directory structure** aware to register API routes and more with zero configuration
+❯ 🤏 **Minimal Design** to fit into any solution with minimum overhead
+❯ 🚀 **Code-splitting** and async chunk loading for fast server startup time
+❯ 👕 **TypeScript** fully supported
+❯ 💾 **Multi-driver storage** and caching layer
+❯ 💰 **Route caching** and static **pre-rendering** with built-in crawler
+❯ 🐱 **Hackable** to extend almost any part of nitro using options
+❯ ✨ **Auto imports** for lazy folks and a tidy minimal codebase
+❯ 🏛️ **Best-effort compatibility** for using legacy npm packages and mocking Node.js modules
## Who is using Nitro?
@@ -49,7 +49,7 @@ cd nitro-app
1️⃣ Create `routes/index.ts`:
```ts [routes/index.ts]
-export default defineEventHandler(() => 'nitro is amazing!')
+export default defineEventHandler(() => "nitro is amazing!");
```
2️⃣ Start development server:
@@ -66,7 +66,7 @@ Check `.nitro/dev/index.mjs` if want to know what is happening
```bash
npx nitropack build
-````
+```
4️⃣ Output is in the `.output` directory and ready to be deployed on almost any VPS with no dependencies. You can locally try it too:
@@ -76,34 +76,28 @@ node .output/server/index.mjs
That's it you got it! Read the [documentation](https://nitro.unjs.io) to learn more.
-
-
🌱 nitro is young and under development
-Check [🐛 open issues](https://github.com/unjs/nitro/issues) for the known issues and roadmap and tell us [💡your ideas](https://github.com/unjs/nitro/discussions/new)!
-
+Check [🐛 open issues](https://github.com/unjs/nitro/issues) for the known issues and roadmap and tell us [💡your ideas](https://github.com/unjs/nitro/discussions/new)!
+
## License
Made with 💛 Published under [MIT](./LICENSE).
+
[npm-version-src]: https://flat.badgen.net/npm/v/nitropack?style=flat-square&label=stable
[npm-version-href]: https://npmjs.com/package/nitropack
-
[npm-downloads-src]: https://flat.badgen.net/npm/dm/nitropack?style=flat-square&label=stable
[npm-downloads-href]: https://npmjs.com/package/nitropack
-
[npm-edge-version-src]: https://flat.badgen.net/npm/v/nitropack-edge?style=flat-square&label=edge
[npm-edge-version-href]: https://npmjs.com/package/nitropack-edge
-
[npm-edge-downloads-src]: https://flat.badgen.net/npm/dm/nitropack-edge?style=flat-square&label=edge
[npm-edge-downloads-href]: https://npmjs.com/package/nitropack-edge
-
[github-actions-src]: https://flat.badgen.net/github/status/unjs/nitro?style=flat-square
[github-actions-href]: https://github.com/unjs/nitro/actions?query=workflow%3Aci
-
[codecov-src]: https://flat.badgen.net/codecov/c/gh/unjs/nitro/main?style=flat-square
[codecov-href]: https://codecov.io/gh/unjs/nitro
diff --git a/build.config.ts b/build.config.ts
index be5082eb0a..113bb9985c 100644
--- a/build.config.ts
+++ b/build.config.ts
@@ -1,22 +1,20 @@
-import { defineBuildConfig } from 'unbuild'
+import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
declaration: true,
- name: 'nitro',
+ name: "nitro",
entries: [
- 'src/index',
- 'src/cli',
- { input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm' }
+ "src/index",
+ "src/cli",
+ { input: "src/runtime/", outDir: "dist/runtime", format: "esm" },
],
dependencies: [
- '@cloudflare/kv-asset-handler',
- '@netlify/functions',
- '@nuxt/devalue',
- 'destr',
- 'ofetch',
- 'ora'
+ "@cloudflare/kv-asset-handler",
+ "@netlify/functions",
+ "@nuxt/devalue",
+ "destr",
+ "ofetch",
+ "ora",
],
- externals: [
- '@nuxt/schema'
- ]
-})
+ externals: ["@nuxt/schema"],
+});
diff --git a/examples/api-routes/api/hello.ts b/examples/api-routes/api/hello.ts
index ec2770b4bc..21fe2776d8 100644
--- a/examples/api-routes/api/hello.ts
+++ b/examples/api-routes/api/hello.ts
@@ -1 +1 @@
-export default defineEventHandler(() => 'Nitro is amazing!')
+export default defineEventHandler(() => "Nitro is amazing!");
diff --git a/examples/api-routes/api/hello/[name].ts b/examples/api-routes/api/hello/[name].ts
index bfee85aa0f..ee43aab612 100644
--- a/examples/api-routes/api/hello/[name].ts
+++ b/examples/api-routes/api/hello/[name].ts
@@ -1 +1,3 @@
-export default defineEventHandler(event => `Hello ${event.context.params.name}!`)
+export default defineEventHandler(
+ (event) => `Hello ${event.context.params.name}!`
+);
diff --git a/examples/api-routes/api/test.get.ts b/examples/api-routes/api/test.get.ts
index 84e39cefcf..927dfd195e 100644
--- a/examples/api-routes/api/test.get.ts
+++ b/examples/api-routes/api/test.get.ts
@@ -1 +1 @@
-export default defineEventHandler(() => 'Test get handler')
+export default defineEventHandler(() => "Test get handler");
diff --git a/examples/api-routes/api/test.post.ts b/examples/api-routes/api/test.post.ts
index 79a8cc07f5..710f745b69 100644
--- a/examples/api-routes/api/test.post.ts
+++ b/examples/api-routes/api/test.post.ts
@@ -1 +1 @@
-export default defineEventHandler(() => 'Test post handler')
+export default defineEventHandler(() => "Test post handler");
diff --git a/examples/api-routes/nitro.config.ts b/examples/api-routes/nitro.config.ts
index a61d1d8e09..0d2ca51b59 100644
--- a/examples/api-routes/nitro.config.ts
+++ b/examples/api-routes/nitro.config.ts
@@ -1,4 +1,3 @@
-import { defineNitroConfig } from 'nitropack'
+import { defineNitroConfig } from "nitropack";
-export default defineNitroConfig({
-})
+export default defineNitroConfig({});
diff --git a/examples/api-routes/routes/[...].ts b/examples/api-routes/routes/[...].ts
index a58441c887..22a7d27ec0 100644
--- a/examples/api-routes/routes/[...].ts
+++ b/examples/api-routes/routes/[...].ts
@@ -6,5 +6,5 @@ export default defineEventHandler(() => {
/api/hello/world
/api/test
-`
-})
+`;
+});
diff --git a/examples/cached-handler/nitro.config.ts b/examples/cached-handler/nitro.config.ts
index a61d1d8e09..0d2ca51b59 100644
--- a/examples/cached-handler/nitro.config.ts
+++ b/examples/cached-handler/nitro.config.ts
@@ -1,4 +1,3 @@
-import { defineNitroConfig } from 'nitropack'
+import { defineNitroConfig } from "nitropack";
-export default defineNitroConfig({
-})
+export default defineNitroConfig({});
diff --git a/examples/cached-handler/routes/index.ts b/examples/cached-handler/routes/index.ts
index 3254a64f53..235e8977e0 100644
--- a/examples/cached-handler/routes/index.ts
+++ b/examples/cached-handler/routes/index.ts
@@ -1,4 +1,4 @@
export default defineCachedEventHandler(async () => {
- await new Promise(resolve => setTimeout(resolve, 1000))
- return `Response generated at ${new Date().toISOString()} (took 1 second)`
-})
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ return `Response generated at ${new Date().toISOString()} (took 1 second)`;
+});
diff --git a/examples/custom-error-handler/error.ts b/examples/custom-error-handler/error.ts
index a37a68a08c..3ad9cfb172 100644
--- a/examples/custom-error-handler/error.ts
+++ b/examples/custom-error-handler/error.ts
@@ -1,5 +1,5 @@
-import type { NitroErrorHandler } from 'nitropack'
+import type { NitroErrorHandler } from "nitropack";
-export default function (error, event) {
- event.res.end('[custom error handler] ' + error.stack)
-}
+export default function (error, event) {
+ event.res.end("[custom error handler] " + error.stack);
+};
diff --git a/examples/custom-error-handler/nitro.config.ts b/examples/custom-error-handler/nitro.config.ts
index 01d9ec5abf..ba0adbda20 100644
--- a/examples/custom-error-handler/nitro.config.ts
+++ b/examples/custom-error-handler/nitro.config.ts
@@ -1,7 +1,7 @@
-import { defineNitroConfig } from 'nitropack'
-import errorHandler from './error'
+import { defineNitroConfig } from "nitropack";
+import errorHandler from "./error";
export default defineNitroConfig({
- errorHandler: '~/error',
- devErrorHandler: errorHandler
-})
+ errorHandler: "~/error",
+ devErrorHandler: errorHandler,
+});
diff --git a/examples/custom-error-handler/routes/index.ts b/examples/custom-error-handler/routes/index.ts
index f747912de9..820c4b6596 100644
--- a/examples/custom-error-handler/routes/index.ts
+++ b/examples/custom-error-handler/routes/index.ts
@@ -1,3 +1,3 @@
export default defineEventHandler(() => {
- throw new Error('Example Error!')
-})
+ throw new Error("Example Error!");
+});
diff --git a/examples/hello-world/nitro.config.ts b/examples/hello-world/nitro.config.ts
index a61d1d8e09..0d2ca51b59 100644
--- a/examples/hello-world/nitro.config.ts
+++ b/examples/hello-world/nitro.config.ts
@@ -1,4 +1,3 @@
-import { defineNitroConfig } from 'nitropack'
+import { defineNitroConfig } from "nitropack";
-export default defineNitroConfig({
-})
+export default defineNitroConfig({});
diff --git a/examples/hello-world/routes/index.ts b/examples/hello-world/routes/index.ts
index db740e4bcd..815b6c7183 100644
--- a/examples/hello-world/routes/index.ts
+++ b/examples/hello-world/routes/index.ts
@@ -1 +1 @@
-export default defineEventHandler(() => 'nitro is amazing! ')
+export default defineEventHandler(() => "nitro is amazing! ");
diff --git a/examples/middleware/middleware/auth.ts b/examples/middleware/middleware/auth.ts
index 5035d76a83..00f610ce10 100644
--- a/examples/middleware/middleware/auth.ts
+++ b/examples/middleware/middleware/auth.ts
@@ -1,3 +1,3 @@
export default defineEventHandler((event) => {
- event.context.auth = { name: 'User ' + Math.round(Math.random() * 100) }
-})
+ event.context.auth = { name: "User " + Math.round(Math.random() * 100) };
+});
diff --git a/examples/middleware/nitro.config.ts b/examples/middleware/nitro.config.ts
index a61d1d8e09..0d2ca51b59 100644
--- a/examples/middleware/nitro.config.ts
+++ b/examples/middleware/nitro.config.ts
@@ -1,4 +1,3 @@
-import { defineNitroConfig } from 'nitropack'
+import { defineNitroConfig } from "nitropack";
-export default defineNitroConfig({
-})
+export default defineNitroConfig({});
diff --git a/examples/middleware/routes/index.ts b/examples/middleware/routes/index.ts
index 301814d72e..e7961fa36d 100644
--- a/examples/middleware/routes/index.ts
+++ b/examples/middleware/routes/index.ts
@@ -1,3 +1,3 @@
-export default defineEventHandler(event => ({
- auth: event.context.auth
-}))
+export default defineEventHandler((event) => ({
+ auth: event.context.auth,
+}));
diff --git a/examples/plugins/nitro.config.ts b/examples/plugins/nitro.config.ts
index 5b8e964d56..05e210f7fe 100644
--- a/examples/plugins/nitro.config.ts
+++ b/examples/plugins/nitro.config.ts
@@ -1,7 +1,5 @@
-import { defineNitroConfig } from 'nitropack'
+import { defineNitroConfig } from "nitropack";
export default defineNitroConfig({
- plugins: [
- '~/plugins/test'
- ]
-})
+ plugins: ["~/plugins/test"],
+});
diff --git a/examples/plugins/plugins/test.ts b/examples/plugins/plugins/test.ts
index 430ecb90cb..d6f5a24e88 100644
--- a/examples/plugins/plugins/test.ts
+++ b/examples/plugins/plugins/test.ts
@@ -1,3 +1,3 @@
export default defineNitroPlugin((_nitroApp) => {
- console.log('Nitro plugin!')
-})
+ console.log("Nitro plugin!");
+});
diff --git a/examples/plugins/routes/index.ts b/examples/plugins/routes/index.ts
index 1cc398b615..2b5a032a89 100644
--- a/examples/plugins/routes/index.ts
+++ b/examples/plugins/routes/index.ts
@@ -1,3 +1,3 @@
-import { eventHandler } from 'h3'
+import { eventHandler } from "h3";
-export default eventHandler(() => 'Hello Nitro! ')
+export default eventHandler(() => "Hello Nitro! ");
diff --git a/examples/tsconfig.json b/examples/tsconfig.json
index 3ae2a24af8..379a994d81 100644
--- a/examples/tsconfig.json
+++ b/examples/tsconfig.json
@@ -1,4 +1,4 @@
{
- "extends": "../tsconfig.json",
- "include": ["."]
+ "extends": "../tsconfig.json",
+ "include": ["."]
}
diff --git a/package.json b/package.json
index 6ed50e7d89..6788422ab2 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,7 @@
"docs:build": "vitepress build docs",
"docs:dev": "vitepress dev docs",
"docs:serve": "vitepress serve docs",
- "lint": "eslint --ext .ts,.mjs,.cjs .",
+ "lint": "eslint --ext .ts,.mjs,.cjs . && prettier -c src test",
"nitro": "jiti ./src/cli.ts",
"prepack": "pnpm build",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
@@ -80,8 +80,8 @@
"mlly": "^1.0.0",
"mri": "^1.2.0",
"node-fetch-native": "^1.0.1",
- "ohash": "^1.0.0",
"ofetch": "^1.0.0",
+ "ohash": "^1.0.0",
"pathe": "^1.0.0",
"perfect-debounce": "^0.1.3",
"pkg-types": "^1.0.1",
@@ -102,16 +102,14 @@
"unstorage": "^1.0.1"
},
"devDependencies": {
- "@nuxtjs/eslint-config-typescript": "^11.0.0",
"@types/aws-lambda": "^8.10.109",
"@types/etag": "^1.8.1",
"@types/fs-extra": "^9.0.13",
"@types/http-proxy": "^1.17.9",
"@types/node-fetch": "^2.6.2",
- "@types/object-hash": "^2.2.1",
"@types/semver": "^7.3.13",
"@types/serve-static": "^1.15.0",
- "@vitest/coverage-c8": "^0.25.5",
+ "@vitest/coverage-c8": "^0.25.6",
"c8": "^7.12.0",
"changelogen": "^0.4.0",
"edge-runtime": "2.0.2",
@@ -120,9 +118,10 @@
"execa": "^6.1.0",
"expect-type": "^0.15.0",
"miniflare": "^2.11.0",
+ "prettier": "^2.8.1",
"typescript": "^4.9.4",
"unbuild": "^1.0.2",
- "vitest": "^0.25.5"
+ "vitest": "^0.25.6"
},
"packageManager": "pnpm@7.18.1",
"engines": {
diff --git a/playground/nitro.config.ts b/playground/nitro.config.ts
index 14ed31af57..8185335729 100644
--- a/playground/nitro.config.ts
+++ b/playground/nitro.config.ts
@@ -1,4 +1,3 @@
-import { defineNitroConfig } from '../src'
+import { defineNitroConfig } from "../src";
-export default defineNitroConfig({
-})
+export default defineNitroConfig({});
diff --git a/playground/routes/index.ts b/playground/routes/index.ts
index 1cc398b615..2b5a032a89 100644
--- a/playground/routes/index.ts
+++ b/playground/routes/index.ts
@@ -1,3 +1,3 @@
-import { eventHandler } from 'h3'
+import { eventHandler } from "h3";
-export default eventHandler(() => 'Hello Nitro! ')
+export default eventHandler(() => "Hello Nitro! ");
diff --git a/playground/tsconfig.json b/playground/tsconfig.json
index dd14e743b0..a0e3fbad2e 100644
--- a/playground/tsconfig.json
+++ b/playground/tsconfig.json
@@ -2,15 +2,9 @@
"extends": "./.nitro/types/tsconfig.json",
"compilerOptions": {
"paths": {
- "nitropack": [
- "../src/index"
- ],
- "#internal/nitro": [
- "../src/runtime/index"
- ],
- "#internal/nitro/*": [
- "../src/runtime/*"
- ]
- },
+ "nitropack": ["../src/index"],
+ "#internal/nitro": ["../src/runtime/index"],
+ "#internal/nitro/*": ["../src/runtime/*"]
+ }
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ec9aaa53d3..0cbdd2e43f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -9,7 +9,6 @@ importers:
specifiers:
'@cloudflare/kv-asset-handler': ^0.2.0
'@netlify/functions': ^1.3.0
- '@nuxtjs/eslint-config-typescript': ^11.0.0
'@rollup/plugin-alias': ^4.0.2
'@rollup/plugin-commonjs': ^23.0.4
'@rollup/plugin-inject': ^5.0.2
@@ -23,11 +22,10 @@ importers:
'@types/fs-extra': ^9.0.13
'@types/http-proxy': ^1.17.9
'@types/node-fetch': ^2.6.2
- '@types/object-hash': ^2.2.1
'@types/semver': ^7.3.13
'@types/serve-static': ^1.15.0
'@vercel/nft': ^0.22.5
- '@vitest/coverage-c8': ^0.25.5
+ '@vitest/coverage-c8': ^0.25.6
archiver: ^5.3.1
c12: ^1.1.0
c8: ^7.12.0
@@ -68,6 +66,7 @@ importers:
pathe: ^1.0.0
perfect-debounce: ^0.1.3
pkg-types: ^1.0.1
+ prettier: ^2.8.1
pretty-bytes: ^6.0.0
radix3: ^1.0.0
rollup: ^2.79.1
@@ -85,7 +84,7 @@ importers:
unenv: ^1.0.0
unimport: ^1.0.1
unstorage: ^1.0.1
- vitest: ^0.25.5
+ vitest: ^0.25.6
dependencies:
'@cloudflare/kv-asset-handler': 0.2.0
'@netlify/functions': 1.3.0
@@ -146,16 +145,14 @@ importers:
unimport: 1.0.1_rollup@2.79.1
unstorage: 1.0.1
devDependencies:
- '@nuxtjs/eslint-config-typescript': 11.0.0_ha6vam6werchizxrnqvarmz2zu
'@types/aws-lambda': 8.10.109
'@types/etag': 1.8.1
'@types/fs-extra': 9.0.13
'@types/http-proxy': 1.17.9
'@types/node-fetch': 2.6.2
- '@types/object-hash': 2.2.1
'@types/semver': 7.3.13
'@types/serve-static': 1.15.0
- '@vitest/coverage-c8': 0.25.5
+ '@vitest/coverage-c8': 0.25.6
c8: 7.12.0
changelogen: 0.4.0
edge-runtime: 2.0.2
@@ -164,9 +161,10 @@ importers:
execa: 6.1.0
expect-type: 0.15.0
miniflare: 2.11.0
+ prettier: 2.8.1
typescript: 4.9.4
unbuild: 1.0.2
- vitest: 0.25.5
+ vitest: 0.25.6
examples/api-routes:
specifiers:
@@ -964,43 +962,6 @@ packages:
'@nodelib/fs.scandir': 2.1.5
fastq: 1.13.0
- /@nuxtjs/eslint-config-typescript/11.0.0_ha6vam6werchizxrnqvarmz2zu:
- resolution: {integrity: sha512-hmFjGtXT524ql8eTbK8BaRkamcXB6Z8YOW8nSQhosTP6oBw9WtOFUeWr7holyE278UhOmx+wDFG90BnyM9D+UA==}
- peerDependencies:
- eslint: ^8.23.0
- dependencies:
- '@nuxtjs/eslint-config': 11.0.0_xjely6t5wgwgvqnbbgk52l5je4
- '@typescript-eslint/eslint-plugin': 5.36.1_ujfdmtdxmqxe4a5dut33px3yhi
- '@typescript-eslint/parser': 5.36.1_ha6vam6werchizxrnqvarmz2zu
- eslint: 8.29.0
- eslint-import-resolver-typescript: 3.5.0_lt3hqehuojhfcbzgzqfngbtmrq
- eslint-plugin-import: 2.26.0_xjely6t5wgwgvqnbbgk52l5je4
- transitivePeerDependencies:
- - eslint-import-resolver-webpack
- - supports-color
- - typescript
- dev: true
-
- /@nuxtjs/eslint-config/11.0.0_xjely6t5wgwgvqnbbgk52l5je4:
- resolution: {integrity: sha512-o4zFOpU8gJgwrC/gLE7c2E0XEjkv2fEixCGG1y+dZYzBPyzTorkQmfxskSF3WRXcZkpkS9uUYlRkeOSdYB7z0w==}
- peerDependencies:
- eslint: ^8.23.0
- dependencies:
- eslint: 8.29.0
- eslint-config-standard: 17.0.0_l24xu3wzfjzwv252bimf7eavfq
- eslint-plugin-import: 2.26.0_xjely6t5wgwgvqnbbgk52l5je4
- eslint-plugin-n: 15.2.5_eslint@8.29.0
- eslint-plugin-node: 11.1.0_eslint@8.29.0
- eslint-plugin-promise: 6.0.1_eslint@8.29.0
- eslint-plugin-unicorn: 43.0.2_eslint@8.29.0
- eslint-plugin-vue: 9.4.0_eslint@8.29.0
- transitivePeerDependencies:
- - '@typescript-eslint/parser'
- - eslint-import-resolver-typescript
- - eslint-import-resolver-webpack
- - supports-color
- dev: true
-
/@pkgr/utils/2.3.1:
resolution: {integrity: sha512-wfzX8kc1PMyUILA+1Z/EqoE4UCXGy0iRGMhPwdfae1+f0OXlLqCk+By+aMzgJBzR9AzS4CDizioG6Ss1gvAFJw==}
engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}
@@ -1301,10 +1262,6 @@ packages:
resolution: {integrity: sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==}
dev: true
- /@types/object-hash/2.2.1:
- resolution: {integrity: sha512-i/rtaJFCsPljrZvP/akBqEwUP2y5cZLOmvO+JaYnz01aPknrQ+hB5MRcO7iqCUsFaYfTG8kGfKUyboA07xeDHQ==}
- dev: true
-
/@types/resolve/1.20.2:
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
@@ -1471,11 +1428,11 @@ packages:
- supports-color
dev: false
- /@vitest/coverage-c8/0.25.5:
- resolution: {integrity: sha512-tXlg0QVkTQ+7dqhsuwRFovP5vjgYGyBrRREFS55IQ20IsiSaRug9sRblRsckTXmGtz1OMJy/Lxv1gFVo24/ipA==}
+ /@vitest/coverage-c8/0.25.6:
+ resolution: {integrity: sha512-+Bcs1XZ8CuEe52QSOgzqmqiV82CXZRRj3yclPQqtLkUV4S6+kdOdfRTtMHOilwhZH70giDjBQx3jgiZoYgFVMA==}
dependencies:
c8: 7.12.0
- vitest: 0.25.5
+ vitest: 0.25.6
transitivePeerDependencies:
- '@edge-runtime/vm'
- '@vitest/browser'
@@ -1670,10 +1627,6 @@ packages:
readable-stream: 3.6.0
dev: false
- /boolbase/1.0.0:
- resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
- dev: true
-
/brace-expansion/1.1.11:
resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==}
dependencies:
@@ -2018,12 +1971,6 @@ packages:
shebang-command: 2.0.0
which: 2.0.2
- /cssesc/3.0.0:
- resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
- engines: {node: '>=4'}
- hasBin: true
- dev: true
-
/debug/2.6.9:
resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==}
peerDependencies:
@@ -2737,24 +2684,6 @@ packages:
strip-indent: 3.0.0
dev: true
- /eslint-plugin-vue/9.4.0_eslint@8.29.0:
- resolution: {integrity: sha512-Nzz2QIJ8FG+rtJaqT/7/ru5ie2XgT9KCudkbN0y3uFYhQ41nuHEaboLAiqwMcK006hZPQv/rVMRhUIwEGhIvfQ==}
- engines: {node: ^14.17.0 || >=16.0.0}
- peerDependencies:
- eslint: ^6.2.0 || ^7.0.0 || ^8.0.0
- dependencies:
- eslint: 8.29.0
- eslint-utils: 3.0.0_eslint@8.29.0
- natural-compare: 1.4.0
- nth-check: 2.0.1
- postcss-selector-parser: 6.0.10
- semver: 7.3.8
- vue-eslint-parser: 9.0.3_eslint@8.29.0
- xml-name-validator: 4.0.0
- transitivePeerDependencies:
- - supports-color
- dev: true
-
/eslint-scope/5.1.1:
resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==}
engines: {node: '>=8.0.0'}
@@ -4184,12 +4113,6 @@ packages:
validate-npm-package-name: 4.0.0
dev: true
- /nth-check/2.0.1:
- resolution: {integrity: sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w==}
- dependencies:
- boolbase: 1.0.0
- dev: true
-
/object-assign/4.1.1:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
@@ -4437,14 +4360,6 @@ packages:
engines: {node: '>=4'}
dev: true
- /postcss-selector-parser/6.0.10:
- resolution: {integrity: sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==}
- engines: {node: '>=4'}
- dependencies:
- cssesc: 3.0.0
- util-deprecate: 1.0.2
- dev: true
-
/postcss/8.4.17:
resolution: {integrity: sha512-UNxNOLQydcOFi41yHNMcKRZ39NeXlr8AxGuZJsdub8vIb12fHzcq37DTU/QtbI6WLxNg2gF9Z+8qtRwTj1UI1Q==}
engines: {node: ^10 || ^12 || >=14}
@@ -4459,6 +4374,12 @@ packages:
engines: {node: '>= 0.8.0'}
dev: true
+ /prettier/2.8.1:
+ resolution: {integrity: sha512-lqGoSJBQNJidqCHE80vqZJHWHRFoNYsSpP9AjFhlhi9ODCJA541svILes/+/1GM3VaL/abZi7cpFzOpdR9UPKg==}
+ engines: {node: '>=10.13.0'}
+ hasBin: true
+ dev: true
+
/pretty-bytes/5.6.0:
resolution: {integrity: sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==}
engines: {node: '>=6'}
@@ -5336,6 +5257,7 @@ packages:
/util-deprecate/1.0.2:
resolution: {integrity: sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=}
+ dev: false
/v8-to-istanbul/9.0.0:
resolution: {integrity: sha512-HcvgY/xaRm7isYmyx+lFKA4uQmfUbN0J4M0nNItvzTvH/iQ9kW5j/t4YSR+Ge323/lrgDAWJoF46tzGQHwBHFw==}
@@ -5387,8 +5309,8 @@ packages:
fsevents: 2.3.2
dev: true
- /vitest/0.25.5:
- resolution: {integrity: sha512-lFKSTZV+AjuL44/yNC0aDPKTiasYSqOQ97Gg2G4P2LnjyzQ21ZUs4rQOscHK3lrSnVuir3+1QavHzbDgH4tWQA==}
+ /vitest/0.25.6:
+ resolution: {integrity: sha512-jdPgmZ7BcDnm1+hmMPIl9BZjSy+b8Y8V0tQMsv7ECO90Qic7EZ5/+traILXLpsXgqK5KgVrUJmchevAUuKL/1w==}
engines: {node: '>=v14.16.0'}
hasBin: true
peerDependencies:
@@ -5431,24 +5353,6 @@ packages:
- terser
dev: true
- /vue-eslint-parser/9.0.3_eslint@8.29.0:
- resolution: {integrity: sha512-yL+ZDb+9T0ELG4VIFo/2anAOz8SvBdlqEnQnvJ3M7Scq56DvtjY0VY88bByRZB0D4J0u8olBcfrXTVONXsh4og==}
- engines: {node: ^14.17.0 || >=16.0.0}
- peerDependencies:
- eslint: '>=6.0.0'
- dependencies:
- debug: 4.3.4
- eslint: 8.29.0
- eslint-scope: 7.1.1
- eslint-visitor-keys: 3.3.0
- espree: 9.4.0
- esquery: 1.4.0
- lodash: 4.17.21
- semver: 7.3.8
- transitivePeerDependencies:
- - supports-color
- dev: true
-
/webidl-conversions/3.0.1:
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
dev: false
@@ -5546,11 +5450,6 @@ packages:
optional: true
dev: true
- /xml-name-validator/4.0.0:
- resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==}
- engines: {node: '>=12'}
- dev: true
-
/y18n/5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 444db3ff2c..c8506e68dc 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,2 +1,2 @@
packages:
- - 'examples/**'
+ - "examples/**"
diff --git a/renovate.json b/renovate.json
index a9971c80d6..57fe916b5c 100644
--- a/renovate.json
+++ b/renovate.json
@@ -1,5 +1,3 @@
{
- "extends": [
- "github>unjs/renovate-config"
- ]
+ "extends": ["github>unjs/renovate-config"]
}
diff --git a/scripts/bump-edge.ts b/scripts/bump-edge.ts
index f29a792cda..3bc50968b3 100755
--- a/scripts/bump-edge.ts
+++ b/scripts/bump-edge.ts
@@ -1,82 +1,96 @@
-import { promises as fsp } from 'fs'
-import { execaCommand } from 'execa'
-import { resolve } from 'pathe'
-import { globby } from 'globby'
+import { promises as fsp } from "node:fs";
+import { execaCommand } from "execa";
+import { resolve } from "pathe";
+import { globby } from "globby";
// Temporary forked from nuxt/framework
-async function loadPackage (dir: string) {
- const pkgPath = resolve(dir, 'package.json')
- const data = JSON.parse(await fsp.readFile(pkgPath, 'utf-8').catch(() => '{}'))
- const save = () => fsp.writeFile(pkgPath, JSON.stringify(data, null, 2) + '\n')
+async function loadPackage(dir: string) {
+ const pkgPath = resolve(dir, "package.json");
+ const data = JSON.parse(
+ await fsp.readFile(pkgPath, "utf8").catch(() => "{}")
+ );
+ const save = () =>
+ fsp.writeFile(pkgPath, JSON.stringify(data, null, 2) + "\n");
const updateDeps = (reviver: Function) => {
- for (const type of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
- if (!data[type]) { continue }
+ for (const type of [
+ "dependencies",
+ "devDependencies",
+ "optionalDependencies",
+ "peerDependencies",
+ ]) {
+ if (!data[type]) {
+ continue;
+ }
for (const e of Object.entries(data[type])) {
- const dep = { name: e[0], range: e[1], type }
- delete data[type][dep.name]
- const updated = reviver(dep) || dep
- data[updated.type] = data[updated.type] || {}
- data[updated.type][updated.name] = updated.range
+ const dep = { name: e[0], range: e[1], type };
+ delete data[type][dep.name];
+ const updated = reviver(dep) || dep;
+ data[updated.type] = data[updated.type] || {};
+ data[updated.type][updated.name] = updated.range;
}
}
- }
+ };
return {
dir,
data,
save,
- updateDeps
- }
+ updateDeps,
+ };
}
-type ThenArg = T extends PromiseLike ? U : T
-type Package = ThenArg>
+type ThenArg = T extends PromiseLike ? U : T;
+type Package = ThenArg>;
-async function loadWorkspace (dir: string) {
- const workspacePkg = await loadPackage(dir)
- const pkgDirs = await globby(workspacePkg.data.workspaces || [], { onlyDirectories: true })
+async function loadWorkspace(dir: string) {
+ const workspacePkg = await loadPackage(dir);
+ const pkgDirs = await globby(workspacePkg.data.workspaces || [], {
+ onlyDirectories: true,
+ });
- const packages: Package[] = [workspacePkg]
+ const packages: Package[] = [workspacePkg];
for (const pkgDir of pkgDirs) {
- const pkg = await loadPackage(pkgDir)
- if (!pkg.data.name) { continue }
- packages.push(pkg)
+ const pkg = await loadPackage(pkgDir);
+ if (!pkg.data.name) {
+ continue;
+ }
+ packages.push(pkg);
}
const find = (name: string) => {
- const pkg = packages.find(pkg => pkg.data.name === name)
+ const pkg = packages.find((pkg) => pkg.data.name === name);
if (!pkg) {
- throw new Error('Workspace package not found: ' + name)
+ throw new Error("Workspace package not found: " + name);
}
- return pkg
- }
+ return pkg;
+ };
const rename = (from: string, to: string) => {
- find(from).data.name = to
+ find(from).data.name = to;
for (const pkg of packages) {
pkg.updateDeps((dep) => {
- if (dep.name === from && !dep.range.startsWith('npm:')) {
- dep.range = 'npm:' + to + '@' + dep.range
+ if (dep.name === from && !dep.range.startsWith("npm:")) {
+ dep.range = "npm:" + to + "@" + dep.range;
}
- })
+ });
}
- }
+ };
const setVersion = (name: string, newVersion: string) => {
- find(name).data.version = newVersion
+ find(name).data.version = newVersion;
for (const pkg of packages) {
pkg.updateDeps((dep) => {
if (dep.name === name) {
- dep.range = newVersion
+ dep.range = newVersion;
}
- })
+ });
}
- }
+ };
- const save = () => Promise.all(packages.map(pkg => pkg.save()))
+ const save = () => Promise.all(packages.map((pkg) => pkg.save()));
return {
dir,
@@ -85,26 +99,33 @@ async function loadWorkspace (dir: string) {
save,
find,
rename,
- setVersion
- }
+ setVersion,
+ };
}
-async function main () {
- const workspace = await loadWorkspace(process.cwd())
+async function main() {
+ const workspace = await loadWorkspace(process.cwd());
- const commit = await execaCommand('git rev-parse --short HEAD').then(r => r.stdout.trim())
- const date = Math.round(Date.now() / (1000 * 60))
+ const commit = await execaCommand("git rev-parse --short HEAD").then((r) =>
+ r.stdout.trim()
+ );
+ const date = Math.round(Date.now() / (1000 * 60));
- for (const pkg of workspace.packages.filter(p => !p.data.private)) {
- workspace.setVersion(pkg.data.name, `${pkg.data.version}-${date}.${commit}`)
- workspace.rename(pkg.data.name, pkg.data.name + '-edge')
+ for (const pkg of workspace.packages.filter((p) => !p.data.private)) {
+ workspace.setVersion(
+ pkg.data.name,
+ `${pkg.data.version}-${date}.${commit}`
+ );
+ workspace.rename(pkg.data.name, pkg.data.name + "-edge");
}
- await workspace.save()
+ await workspace.save();
}
+// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch((err) => {
// eslint-disable-next-line no-console
- console.error(err)
- process.exit(1)
-})
+ console.error(err);
+ // eslint-disable-next-line unicorn/no-process-exit
+ process.exit(1);
+});
diff --git a/src/build.ts b/src/build.ts
index d729ae30af..28b40ac0c9 100644
--- a/src/build.ts
+++ b/src/build.ts
@@ -1,278 +1,342 @@
-import { promises as fsp } from 'fs'
-import { relative, resolve, join, dirname, isAbsolute } from 'pathe'
-import { resolveAlias } from 'pathe/utils'
-import * as rollup from 'rollup'
-import fse from 'fs-extra'
-import { defu } from 'defu'
-import { watch } from 'chokidar'
-import { debounce } from 'perfect-debounce'
-import type { TSConfig } from 'pkg-types'
-import type { RollupError } from 'rollup'
-import type { OnResolveResult, PartialMessage } from 'esbuild'
-import { printFSTree } from './utils/tree'
-import { getRollupConfig, RollupConfig } from './rollup/config'
-import { prettyPath, writeFile, isDirectory } from './utils'
-import { GLOB_SCAN_PATTERN, scanHandlers } from './scan'
-import type { Nitro } from './types'
-import { runtimeDir } from './dirs'
-import { snapshotStorage } from './storage'
-import { compressPublicAssets } from './compress'
-
-export async function prepare (nitro: Nitro) {
- await prepareDir(nitro.options.output.dir)
+import { promises as fsp } from "node:fs";
+import { relative, resolve, join, dirname, isAbsolute } from "pathe";
+import { resolveAlias } from "pathe/utils";
+import * as rollup from "rollup";
+import fse from "fs-extra";
+import { defu } from "defu";
+import { watch } from "chokidar";
+import { debounce } from "perfect-debounce";
+import type { TSConfig } from "pkg-types";
+import type { RollupError } from "rollup";
+import type { OnResolveResult, PartialMessage } from "esbuild";
+import { printFSTree } from "./utils/tree";
+import { getRollupConfig, RollupConfig } from "./rollup/config";
+import { prettyPath, writeFile, isDirectory } from "./utils";
+import { GLOB_SCAN_PATTERN, scanHandlers } from "./scan";
+import type { Nitro } from "./types";
+import { runtimeDir } from "./dirs";
+import { snapshotStorage } from "./storage";
+import { compressPublicAssets } from "./compress";
+
+export async function prepare(nitro: Nitro) {
+ await prepareDir(nitro.options.output.dir);
if (!nitro.options.noPublicDir) {
- await prepareDir(nitro.options.output.publicDir)
+ await prepareDir(nitro.options.output.publicDir);
}
- await prepareDir(nitro.options.output.serverDir)
+ await prepareDir(nitro.options.output.serverDir);
}
-async function prepareDir (dir: string) {
- await fsp.mkdir(dir, { recursive: true })
- await fse.emptyDir(dir)
+async function prepareDir(dir: string) {
+ await fsp.mkdir(dir, { recursive: true });
+ await fse.emptyDir(dir);
}
-export async function copyPublicAssets (nitro: Nitro) {
- if (nitro.options.noPublicDir) { return }
+export async function copyPublicAssets(nitro: Nitro) {
+ if (nitro.options.noPublicDir) {
+ return;
+ }
for (const asset of nitro.options.publicAssets) {
if (await isDirectory(asset.dir)) {
- await fse.copy(asset.dir, join(nitro.options.output.publicDir, asset.baseURL!))
+ await fse.copy(
+ asset.dir,
+ join(nitro.options.output.publicDir, asset.baseURL!)
+ );
}
}
if (nitro.options.compressPublicAssets) {
- await compressPublicAssets(nitro)
+ await compressPublicAssets(nitro);
}
- nitro.logger.success('Generated public ' + prettyPath(nitro.options.output.publicDir))
+ nitro.logger.success(
+ "Generated public " + prettyPath(nitro.options.output.publicDir)
+ );
}
-export async function build (nitro: Nitro) {
- const rollupConfig = getRollupConfig(nitro)
- await nitro.hooks.callHook('rollup:before', nitro)
- return nitro.options.dev ? _watch(nitro, rollupConfig) : _build(nitro, rollupConfig)
+export async function build(nitro: Nitro) {
+ const rollupConfig = getRollupConfig(nitro);
+ await nitro.hooks.callHook("rollup:before", nitro);
+ return nitro.options.dev
+ ? _watch(nitro, rollupConfig)
+ : _build(nitro, rollupConfig);
}
-export async function writeTypes (nitro: Nitro) {
- const routeTypes: Record = {}
+export async function writeTypes(nitro: Nitro) {
+ const routeTypes: Record = {};
- const middleware = [
- ...nitro.scannedHandlers,
- ...nitro.options.handlers
- ]
+ const middleware = [...nitro.scannedHandlers, ...nitro.options.handlers];
for (const mw of middleware) {
- if (typeof mw.handler !== 'string' || !mw.route) { continue }
- const relativePath = relative(join(nitro.options.buildDir, 'types'), mw.handler).replace(/\.[a-z]+$/, '')
- routeTypes[mw.route] = routeTypes[mw.route] || []
- routeTypes[mw.route].push(`Awaited>`)
+ if (typeof mw.handler !== "string" || !mw.route) {
+ continue;
+ }
+ const relativePath = relative(
+ join(nitro.options.buildDir, "types"),
+ mw.handler
+ ).replace(/\.[a-z]+$/, "");
+ routeTypes[mw.route] = routeTypes[mw.route] || [];
+ routeTypes[mw.route].push(
+ `Awaited>`
+ );
}
- let autoImportedTypes: string[] = []
+ let autoImportedTypes: string[] = [];
if (nitro.unimport) {
autoImportedTypes = [
- (await nitro.unimport
- .generateTypeDeclarations({
+ (
+ await nitro.unimport.generateTypeDeclarations({
exportHelper: false,
resolvePath: (i) => {
- if (i.from.startsWith('#internal/nitro')) {
- return resolveAlias(i.from, nitro.options.alias)
+ if (i.from.startsWith("#internal/nitro")) {
+ return resolveAlias(i.from, nitro.options.alias);
}
- return i.from
- }
- }))
- .trim()
- ]
+ return i.from;
+ },
+ })
+ ).trim(),
+ ];
}
const lines = [
- '// Generated by nitro',
- 'declare module \'nitropack\' {',
- ' type Awaited = T extends PromiseLike ? Awaited : T',
- ' interface InternalApi {',
- ...Object.entries(routeTypes).map(([path, types]) => ` '${path}': ${types.join(' | ')}`),
- ' }',
- '}',
+ "// Generated by nitro",
+ "declare module 'nitropack' {",
+ " type Awaited = T extends PromiseLike ? Awaited : T",
+ " interface InternalApi {",
+ ...Object.entries(routeTypes).map(
+ ([path, types]) => ` '${path}': ${types.join(" | ")}`
+ ),
+ " }",
+ "}",
...autoImportedTypes,
// Makes this a module for augmentation purposes
- 'export {}'
- ]
+ "export {}",
+ ];
- await writeFile(join(nitro.options.buildDir, 'types/nitro.d.ts'), lines.join('\n'))
+ await writeFile(
+ join(nitro.options.buildDir, "types/nitro.d.ts"),
+ lines.join("\n")
+ );
if (nitro.options.typescript.generateTsConfig) {
const tsConfig: TSConfig = {
compilerOptions: {
- target: 'ESNext',
- module: 'ESNext',
- moduleResolution: 'Node',
+ target: "ESNext",
+ module: "ESNext",
+ moduleResolution: "Node",
allowJs: true,
resolveJsonModule: true,
paths: nitro.options.typescript.internalPaths
? {
- '#internal/nitro': [
- join(runtimeDir, 'index')
- ],
- '#internal/nitro/*': [
- join(runtimeDir, '*')
- ]
+ "#internal/nitro": [join(runtimeDir, "index")],
+ "#internal/nitro/*": [join(runtimeDir, "*")],
}
- : {}
+ : {},
},
include: [
- './nitro.d.ts',
- join(relative(join(nitro.options.buildDir, 'types'), nitro.options.rootDir), '**/*'),
- ...nitro.options.srcDir !== nitro.options.rootDir ? [join(relative(join(nitro.options.buildDir, 'types'), nitro.options.srcDir), '**/*')] : []
- ]
- }
- await writeFile(join(nitro.options.buildDir, 'types/tsconfig.json'), JSON.stringify(tsConfig, null, 2))
+ "./nitro.d.ts",
+ join(
+ relative(
+ join(nitro.options.buildDir, "types"),
+ nitro.options.rootDir
+ ),
+ "**/*"
+ ),
+ ...(nitro.options.srcDir !== nitro.options.rootDir
+ ? [
+ join(
+ relative(
+ join(nitro.options.buildDir, "types"),
+ nitro.options.srcDir
+ ),
+ "**/*"
+ ),
+ ]
+ : []),
+ ],
+ };
+ await writeFile(
+ join(nitro.options.buildDir, "types/tsconfig.json"),
+ JSON.stringify(tsConfig, null, 2)
+ );
}
}
-async function _snapshot (nitro: Nitro) {
- if (!nitro.options.bundledStorage.length ||
- nitro.options.preset === 'nitro-prerender'
+async function _snapshot(nitro: Nitro) {
+ if (
+ nitro.options.bundledStorage.length === 0 ||
+ nitro.options.preset === "nitro-prerender"
) {
- return
+ return;
}
// TODO: Use virtual storage for server assets
- const storageDir = resolve(nitro.options.buildDir, 'snapshot')
+ const storageDir = resolve(nitro.options.buildDir, "snapshot");
nitro.options.serverAssets.push({
- baseName: 'nitro:bundled',
- dir: storageDir
- })
-
- const data = await snapshotStorage(nitro)
- await Promise.all(Object.entries(data).map(async ([path, contents]) => {
- if (typeof contents !== 'string') { contents = JSON.stringify(contents) }
- const fsPath = join(storageDir, path.replace(/:/g, '/'))
- await fsp.mkdir(dirname(fsPath), { recursive: true })
- await fsp.writeFile(fsPath, contents, 'utf8')
- }))
+ baseName: "nitro:bundled",
+ dir: storageDir,
+ });
+
+ const data = await snapshotStorage(nitro);
+ await Promise.all(
+ Object.entries(data).map(async ([path, contents]) => {
+ if (typeof contents !== "string") {
+ contents = JSON.stringify(contents);
+ }
+ const fsPath = join(storageDir, path.replace(/:/g, "/"));
+ await fsp.mkdir(dirname(fsPath), { recursive: true });
+ await fsp.writeFile(fsPath, contents, "utf8");
+ })
+ );
}
-async function _build (nitro: Nitro, rollupConfig: RollupConfig) {
- await scanHandlers(nitro)
- await writeTypes(nitro)
- await _snapshot(nitro)
+async function _build(nitro: Nitro, rollupConfig: RollupConfig) {
+ await scanHandlers(nitro);
+ await writeTypes(nitro);
+ await _snapshot(nitro);
- nitro.logger.info(`Building Nitro Server (preset: \`${nitro.options.preset}\`)`)
+ nitro.logger.info(
+ `Building Nitro Server (preset: \`${nitro.options.preset}\`)`
+ );
const build = await rollup.rollup(rollupConfig).catch((error) => {
- nitro.logger.error(formatRollupError(error))
- throw error
- })
+ nitro.logger.error(formatRollupError(error));
+ throw error;
+ });
- await build.write(rollupConfig.output)
+ await build.write(rollupConfig.output);
// Write build info
- const nitroConfigPath = resolve(nitro.options.output.dir, 'nitro.json')
+ const nitroConfigPath = resolve(nitro.options.output.dir, "nitro.json");
const buildInfo = {
date: new Date(),
preset: nitro.options.preset,
commands: {
preview: nitro.options.commands.preview,
- deploy: nitro.options.commands.deploy
- }
- }
- await writeFile(nitroConfigPath, JSON.stringify(buildInfo, null, 2))
+ deploy: nitro.options.commands.deploy,
+ },
+ };
+ await writeFile(nitroConfigPath, JSON.stringify(buildInfo, null, 2));
- nitro.logger.success('Nitro server built')
+ nitro.logger.success("Nitro server built");
if (nitro.options.logLevel > 1) {
- await printFSTree(nitro.options.output.serverDir)
+ await printFSTree(nitro.options.output.serverDir);
}
- await nitro.hooks.callHook('compiled', nitro)
+ await nitro.hooks.callHook("compiled", nitro);
// Show deploy and preview hints
- const rOutput = relative(process.cwd(), nitro.options.output.dir)
+ const rOutput = relative(process.cwd(), nitro.options.output.dir);
const rewriteRelativePaths = (input: string) => {
- return input.replace(/\s\.\/([^\s]*)/g, ` ${rOutput}/$1`)
- }
+ return input.replace(/\s\.\/(\S*)/g, ` ${rOutput}/$1`);
+ };
if (buildInfo.commands.preview) {
- nitro.logger.success(`You can preview this build using \`${rewriteRelativePaths(buildInfo.commands.preview)}\``)
+ nitro.logger.success(
+ `You can preview this build using \`${rewriteRelativePaths(
+ buildInfo.commands.preview
+ )}\``
+ );
}
if (buildInfo.commands.deploy) {
- nitro.logger.success(`You can deploy this build using \`${rewriteRelativePaths(buildInfo.commands.deploy)}\``)
+ nitro.logger.success(
+ `You can deploy this build using \`${rewriteRelativePaths(
+ buildInfo.commands.deploy
+ )}\``
+ );
}
}
-function startRollupWatcher (nitro: Nitro, rollupConfig: RollupConfig) {
- const watcher = rollup.watch(defu(rollupConfig, {
- watch: {
- chokidar: nitro.options.watchOptions
- }
- }))
- let start: number
+function startRollupWatcher(nitro: Nitro, rollupConfig: RollupConfig) {
+ const watcher = rollup.watch(
+ defu(rollupConfig, {
+ watch: {
+ chokidar: nitro.options.watchOptions,
+ },
+ })
+ );
+ let start: number;
- watcher.on('event', (event) => {
+ watcher.on("event", (event) => {
switch (event.code) {
// The watcher is (re)starting
- case 'START':
- return
+ case "START":
+ return;
// Building an individual bundle
- case 'BUNDLE_START':
- start = Date.now()
- return
+ case "BUNDLE_START":
+ start = Date.now();
+ return;
// Finished building all bundles
- case 'END':
- nitro.hooks.callHook('compiled', nitro)
- nitro.logger.success('Nitro built', start ? `in ${Date.now() - start} ms` : '')
- nitro.hooks.callHook('dev:reload')
- return
+ case "END":
+ nitro.hooks.callHook("compiled", nitro);
+ nitro.logger.success(
+ "Nitro built",
+ start ? `in ${Date.now() - start} ms` : ""
+ );
+ nitro.hooks.callHook("dev:reload");
+ return;
// Encountered an error while bundling
- case 'ERROR':
- nitro.logger.error(formatRollupError(event.error))
+ case "ERROR":
+ nitro.logger.error(formatRollupError(event.error));
}
- })
- return watcher
+ });
+ return watcher;
}
-async function _watch (nitro: Nitro, rollupConfig: RollupConfig) {
- let rollupWatcher: rollup.RollupWatcher
+async function _watch(nitro: Nitro, rollupConfig: RollupConfig) {
+ let rollupWatcher: rollup.RollupWatcher;
const reload = debounce(async () => {
- if (rollupWatcher) { await rollupWatcher.close() }
- await scanHandlers(nitro)
- rollupWatcher = startRollupWatcher(nitro, rollupConfig)
- await writeTypes(nitro)
- })
-
- const watchPatterns = nitro.options.scanDirs.flatMap(dir => [
- join(dir, 'api'),
- join(dir, 'routes'),
- join(dir, 'middleware', GLOB_SCAN_PATTERN)
- ])
-
- const watchReloadEvents = new Set(['add', 'addDir', 'unlink', 'unlinkDir'])
- const reloadWacher = watch(watchPatterns, { ignoreInitial: true }).on('all', (event) => {
- if (watchReloadEvents.has(event)) {
- reload()
+ if (rollupWatcher) {
+ await rollupWatcher.close();
+ }
+ await scanHandlers(nitro);
+ rollupWatcher = startRollupWatcher(nitro, rollupConfig);
+ await writeTypes(nitro);
+ });
+
+ const watchPatterns = nitro.options.scanDirs.flatMap((dir) => [
+ join(dir, "api"),
+ join(dir, "routes"),
+ join(dir, "middleware", GLOB_SCAN_PATTERN),
+ ]);
+
+ const watchReloadEvents = new Set(["add", "addDir", "unlink", "unlinkDir"]);
+ const reloadWacher = watch(watchPatterns, { ignoreInitial: true }).on(
+ "all",
+ (event) => {
+ if (watchReloadEvents.has(event)) {
+ reload();
+ }
}
- })
+ );
- nitro.hooks.hook('close', () => {
- rollupWatcher.close()
- reloadWacher.close()
- })
+ nitro.hooks.hook("close", () => {
+ rollupWatcher.close();
+ reloadWacher.close();
+ });
- await reload()
+ await reload();
}
-function formatRollupError (_error: RollupError | OnResolveResult) {
+function formatRollupError(_error: RollupError | OnResolveResult) {
try {
- const logs: string[] = []
- for (const error of ('errors' in _error ? _error.errors : [_error as RollupError])) {
- const id = (error as any).path || error.id || (_error as RollupError).id
- let path = isAbsolute(id) ? relative(process.cwd(), id) : id
- const location = (error as RollupError).loc || (error as PartialMessage).location
+ const logs: string[] = [];
+ for (const error of "errors" in _error
+ ? _error.errors
+ : [_error as RollupError]) {
+ const id = (error as any).path || error.id || (_error as RollupError).id;
+ let path = isAbsolute(id) ? relative(process.cwd(), id) : id;
+ const location =
+ (error as RollupError).loc || (error as PartialMessage).location;
if (location) {
- path += `:${location.line}:${location.column}`
+ path += `:${location.line}:${location.column}`;
}
- const text = (error as PartialMessage).text || (error as RollupError).frame
- logs.push(`Rollup error while processing \`${path}\`` + text ? '\n\n' + text : '')
+ const text =
+ (error as PartialMessage).text || (error as RollupError).frame;
+ logs.push(
+ `Rollup error while processing \`${path}\`` + text ? "\n\n" + text : ""
+ );
}
- return logs.join('\n\n')
+ return logs.join("\n\n");
} catch {
- return _error?.toString()
+ return _error?.toString();
}
}
diff --git a/src/cli.ts b/src/cli.ts
index 8dad53c5a8..eafebec635 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,48 +1,49 @@
#!/usr/bin/env node
-import mri from 'mri'
-import { resolve } from 'pathe'
-import { createNitro } from './nitro'
-import { build, prepare, copyPublicAssets } from './build'
-import { prerender } from './prerender'
-import { createDevServer } from './dev/server'
+import mri from "mri";
+import { resolve } from "pathe";
+import { createNitro } from "./nitro";
+import { build, prepare, copyPublicAssets } from "./build";
+import { prerender } from "./prerender";
+import { createDevServer } from "./dev/server";
-async function main () {
- const args = mri(process.argv.slice(2))
- const command = args._[0]
- const rootDir = resolve(args._[1] || '.')
+async function main() {
+ const args = mri(process.argv.slice(2));
+ const command = args._[0];
+ const rootDir = resolve(args._[1] || ".");
- if (command === 'dev') {
+ if (command === "dev") {
const nitro = await createNitro({
rootDir,
dev: true,
- preset: 'nitro-dev'
- })
- const server = createDevServer(nitro)
- await server.listen({})
- await prepare(nitro)
- await build(nitro)
- return
+ preset: "nitro-dev",
+ });
+ const server = createDevServer(nitro);
+ await server.listen({});
+ await prepare(nitro);
+ await build(nitro);
+ return;
}
- if (command === 'build') {
+ if (command === "build") {
const nitro = await createNitro({
rootDir,
- dev: false
- })
- await prepare(nitro)
- await copyPublicAssets(nitro)
- await prerender(nitro)
- await build(nitro)
- await nitro.close()
- process.exit(0)
+ dev: false,
+ });
+ await prepare(nitro);
+ await copyPublicAssets(nitro);
+ await prerender(nitro);
+ await build(nitro);
+ await nitro.close();
+ process.exit(0);
}
- console.error(`Unknown command ${command}! Usage: nitro dev|build [rootDir]`)
- process.exit(1)
+ console.error(`Unknown command ${command}! Usage: nitro dev|build [rootDir]`);
+ process.exit(1);
}
+// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch((err) => {
- console.error(err)
- process.exit(1)
-})
+ console.error(err);
+ process.exit(1);
+});
diff --git a/src/compress.ts b/src/compress.ts
index 229f211add..6f74109f59 100644
--- a/src/compress.ts
+++ b/src/compress.ts
@@ -1,65 +1,76 @@
-import zlib from 'node:zlib'
-import fsp from 'node:fs/promises'
-import { existsSync } from 'node:fs'
-import { globby } from 'globby'
-import { resolve } from 'pathe'
-import mime from 'mime'
-import type { Nitro } from './types'
+import zlib from "node:zlib";
+import fsp from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { globby } from "globby";
+import { resolve } from "pathe";
+import mime from "mime";
+import type { Nitro } from "./types";
-export async function compressPublicAssets (nitro: Nitro) {
- const publicFiles = await globby('**', {
+export async function compressPublicAssets(nitro: Nitro) {
+ const publicFiles = await globby("**", {
cwd: nitro.options.output.publicDir,
absolute: false,
dot: true,
- ignore: ['**/*.gz', '**/*.br']
- })
+ ignore: ["**/*.gz", "**/*.br"],
+ });
for (const fileName of publicFiles) {
- const filePath = resolve(nitro.options.output.publicDir, fileName)
- const fileContents = await fsp.readFile(filePath)
- if (existsSync(filePath + '.gz') || existsSync(filePath + '.br')) {
- continue
+ const filePath = resolve(nitro.options.output.publicDir, fileName);
+ const fileContents = await fsp.readFile(filePath);
+ if (existsSync(filePath + ".gz") || existsSync(filePath + ".br")) {
+ continue;
}
- const mimeType = mime.getType(fileName) || 'text/plain'
+ const mimeType = mime.getType(fileName) || "text/plain";
- if (fileContents.length < 1024 || fileName.endsWith('.map') || !isCompressableMime(mimeType)) {
- continue
+ if (
+ fileContents.length < 1024 ||
+ fileName.endsWith(".map") ||
+ !isCompressableMime(mimeType)
+ ) {
+ continue;
}
- const { gzip, brotli } = nitro.options.compressPublicAssets || {} as any
+ const { gzip, brotli } = nitro.options.compressPublicAssets || ({} as any);
- const encodings = [gzip !== false && 'gzip', brotli !== false && 'br'].filter(Boolean)
+ const encodings = [
+ gzip !== false && "gzip",
+ brotli !== false && "br",
+ ].filter(Boolean);
for (const encoding of encodings) {
- const suffix = '.' + (encoding === 'gzip' ? 'gz' : 'br')
- const compressedPath = filePath + suffix
- if (existsSync(compressedPath)) { continue }
- const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION }
+ const suffix = "." + (encoding === "gzip" ? "gz" : "br");
+ const compressedPath = filePath + suffix;
+ if (existsSync(compressedPath)) {
+ continue;
+ }
+ const gzipOptions = { level: zlib.constants.Z_BEST_COMPRESSION };
const brotliOptions = {
[zlib.constants.BROTLI_PARAM_MODE]: isTextMime(mimeType)
? zlib.constants.BROTLI_MODE_TEXT
: zlib.constants.BROTLI_MODE_GENERIC,
- [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length
- }
+ [zlib.constants.BROTLI_PARAM_QUALITY]:
+ zlib.constants.BROTLI_MAX_QUALITY,
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fileContents.length,
+ };
const compressedBuff: Buffer = await new Promise((resolve, reject) => {
- const cb = (error, result: Buffer) => error ? reject(error) : resolve(result)
- if (encoding === 'gzip') {
- zlib.gzip(fileContents, gzipOptions, cb)
+ const cb = (error, result: Buffer) =>
+ error ? reject(error) : resolve(result);
+ if (encoding === "gzip") {
+ zlib.gzip(fileContents, gzipOptions, cb);
} else {
- zlib.brotliCompress(fileContents, brotliOptions, cb)
+ zlib.brotliCompress(fileContents, brotliOptions, cb);
}
- })
- await fsp.writeFile(compressedPath, compressedBuff)
+ });
+ await fsp.writeFile(compressedPath, compressedBuff);
}
}
}
-function isTextMime (mimeType: string) {
- return /text|javascript|json|xml/.test(mimeType)
+function isTextMime(mimeType: string) {
+ return /text|javascript|json|xml/.test(mimeType);
}
-function isCompressableMime (mimeType: string) {
- return /image|text|font|json|xml|javascript/.test(mimeType)
+function isCompressableMime(mimeType: string) {
+ return /image|text|font|json|xml|javascript/.test(mimeType);
}
diff --git a/src/dev/error.ts b/src/dev/error.ts
index 9e540b14bc..12818f0101 100644
--- a/src/dev/error.ts
+++ b/src/dev/error.ts
@@ -1,18 +1,19 @@
-import { NitroErrorHandler } from '../types'
+import { NitroErrorHandler } from "../types";
-function errorHandler (error, event) {
- event.res.setHeader('Content-Type', 'text/html; charset=UTF-8')
- event.res.statusCode = 503
- event.res.statusMessage = 'Server Unavailable'
+function errorHandler(error, event) {
+ event.res.setHeader("Content-Type", "text/html; charset=UTF-8");
+ event.res.statusCode = 503;
+ event.res.statusMessage = "Server Unavailable";
- let body
- let title
+ let body;
+ let title;
if (error) {
- title = `${event.res.statusCode} ${event.res.statusMessage}`
- body = `${error.stack}
`
+ title = `${event.res.statusCode} ${event.res.statusMessage}`;
+ body = `${error.stack}
`;
} else {
- title = 'Reloading server...'
- body = ' '
+ title = "Reloading server...";
+ body =
+ " ";
}
event.res.end(`
@@ -20,7 +21,7 @@ function errorHandler (error, event) {
- ${error ? '' : ' '}
+ ${error ? "" : ' '}
${title}
@@ -38,7 +39,7 @@ function errorHandler (error, event) {