@prairielearn/vite-plugin-express 1.0.2 → 1.0.4
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/CHANGELOG.md +12 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +1 -0
package/CHANGELOG.md
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAIL,KAAK,MAAM,EAIZ,MAAM,MAAM,CAAC;AAuLd,KAAK,oBAAoB,GAAG,KAAK,GAAG,KAAK,GAAG,IAAI,GAAG,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;AAC7E,KAAK,YAAY,GAAG,oBAAoB,GAAG,UAAU,GAAG,KAAK,GAAG,QAAQ,GAAG,UAAU,CAAC;AACtF,UAAU,uBAAuB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAMD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,uBAAuB,GAAG,MAAM,EAAE,CA2CxE"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,IAAI,MAAM,WAAW,CAAC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,EAAE;gBAChC,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC;YACzD,CAAC;SACF;KACF,CAAC;IAEF,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport path from 'node:path';\nimport { exit } from 'node:process';\nimport util from 'node:util';\n\nimport debounce from 'debounce';\nimport picomatch from 'picomatch';\nimport stripAnsi from 'strip-ansi';\nimport {\n type ConfigEnv,\n type Connect,\n type ModuleNode,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n isRunnableDevEnvironment,\n} from 'vite';\n\nconst env: ConfigEnv = { command: 'serve', mode: '' };\n\n/**\n * Attempt to format an error for display to the user. Currently only ESBuild\n * transform errors are special-cased: they'll be formatted with the error\n * location and a frame indicating where the error is. All other errors are\n * formatted with {@link util.inspect}.\n */\nfunction formatError(err: any) {\n if (\n !((err as any) instanceof Error) ||\n !err.message?.includes('Transform failed with') ||\n !err.frame ||\n !err.loc\n ) {\n return util.inspect(err);\n }\n\n const location = `${err.loc.file}:${err.loc.line}:${err.loc.column}`;\n return [location, err.frame].map((s) => s.trim()).join('\\n');\n}\n\nasync function getPluginConfig(server: ViteDevServer): Promise<VitePluginExpressConfig> {\n // Ugly type hack to get the plugin config\n const plugin = server.config.plugins.find((p) => p.name === PLUGIN_NAME) as unknown as {\n config: (...args: any[]) => UserConfig & { VitePluginExpressConfig: VitePluginExpressConfig };\n };\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n let userConfig: UserConfig | null | void = null;\n\n if (typeof plugin.config === 'function') {\n userConfig = plugin.config({}, env);\n }\n\n if (userConfig) {\n return (userConfig as ViteConfig).VitePluginExpressConfig;\n }\n\n console.error('Please setup VitePluginExpress in your vite.config.ts first');\n exit(1);\n}\n\nfunction recursivelyGetImporters(\n moduleNode: ModuleNode,\n visited = new Set<ModuleNode>(),\n): Set<ModuleNode> {\n if (!visited.has(moduleNode)) {\n visited.add(moduleNode);\n for (const importer of moduleNode.importers) {\n recursivelyGetImporters(importer, visited);\n }\n }\n\n return visited;\n}\n\nasync function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFunction> {\n const config = await getPluginConfig(server);\n const logger = server.config.logger;\n\n // Store a cached copy of the most recent app module that we can use while\n // doing a full restart.\n let _mostRecentAppModule: any;\n async function _loadApp(config: VitePluginExpressConfig) {\n if (!isRunnableDevEnvironment(server.environments.ssr)) {\n throw new Error('VitePluginExpress can only be used with a runnable dev environment');\n }\n\n // We use `runner.import(...)` instead of `ssrLoadModule(...)` because a)\n // the latter will be deprecated soon and b) `runner.import(...)` will\n // automatically produce correct stack traces that account for code\n // transformations done by Vite.\n const appModule = await server.environments.ssr.runner.import(config.appPath);\n\n if (appModule) {\n _mostRecentAppModule = appModule;\n }\n\n const app = appModule[config.exportName!];\n if (!app) {\n logger.error(`Failed to find a named ${config.exportName} from ${config.appPath}`, {\n timestamp: true,\n });\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n }\n return app;\n }\n\n if (config.initAppOnBoot) {\n server.httpServer!.once('listening', async () => {\n await _loadApp(config).catch(() => {});\n });\n }\n\n // We'll always normalize the paths to absolute globs.\n const fullRestartPaths = (config.fullRestartPaths ?? []).map((p) =>\n path.resolve(server.config.root, p),\n );\n const fullRestartPathMatchers = fullRestartPaths.map((p) => picomatch(p));\n server.watcher.add(fullRestartPaths);\n\n const debouncedLoadApp = debounce(async () => await _loadApp(config).catch(() => {}), 500, {\n immediate: true,\n });\n const debouncedRestart = debounce(() => server.restart(), 500, { immediate: true });\n\n function needsFullRestart(file: string): boolean {\n // This is the easy case: we had a direct change to a file that is supposed\n // to trigger a full reload.\n if (fullRestartPathMatchers.some((matcher) => matcher(file))) return true;\n\n const modules = Array.from(server.moduleGraph.getModulesByFile(file) ?? []);\n if (modules.length === 0) {\n // This file isn't part of the module graph. No need to do anything.\n return false;\n }\n\n if (modules.length !== 1) {\n throw new Error(`Unexpected module graph state: ${modules.length} modules found for ${file}`);\n }\n\n // If the file is directly or indirectly imported by a module that matches\n // the full restart paths, then we need to do a full restart.\n const importers = recursivelyGetImporters(modules[0]);\n const importerPaths = Array.from(importers)\n .map((m) => m.file)\n .filter((p): p is string => p !== null);\n return importerPaths.some((p) => fullRestartPathMatchers.some((matcher) => matcher(p)));\n }\n\n // We'll manually react to changes in two cases:\n //\n // 1. If the file matches any of the full paths, we'll immediately restart\n // the server. These paths may not be part of the Vite module graph (e.g.\n // SQL files), or they may be part of the module graph but may contain state\n // that can't be hot-reloaded (e.g. database connection pools or worker pools).\n //\n // 2. If we're configured to watch file changes, we'll reload the app (root) module.\n // This gives us a head start over waiting for the next request to trigger a reload.\n server.watcher.on('change', (file) => {\n if (needsFullRestart(path.resolve(server.config.root, file))) {\n logger.info(`Change to ${file} requires a full restart`, { timestamp: true });\n debouncedRestart();\n } else if (config.watchFileChanges) {\n debouncedLoadApp();\n }\n });\n\n // Hook into the environment's `close` method so we can do cleanup when the\n // server is closed. Crucially, this allows us to hook into the `k+Enter` key\n // combo in the Vite dev server to gracefully shut down the server so that it\n // can be restarted cleanly.\n //\n // This uses a hardcoded `close` export from the app module.\n const originalClose = server.environments.ssr.close.bind(server.environments.ssr);\n server.environments.ssr.close = async () => {\n await originalClose();\n\n if (typeof _mostRecentAppModule?.close === 'function') {\n await _mostRecentAppModule.close();\n }\n };\n\n return async function (req: IncomingMessage, res: ServerResponse): Promise<void> {\n const app = await _loadApp(config).catch((err) => {\n const formattedError = formatError(err);\n logger.error(formattedError);\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(stripAnsi(formattedError));\n return null;\n });\n if (!app) return;\n\n app(req, res);\n };\n}\n\nconst PLUGIN_NAME = 'vite-plugin-express';\n\ntype InternalModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd';\ntype ModuleFormat = InternalModuleFormat | 'commonjs' | 'esm' | 'module' | 'systemjs';\ninterface VitePluginExpressConfig {\n appPath: string;\n appName?: string;\n initAppOnBoot?: boolean;\n exportName?: string;\n outputFormat?: ModuleFormat;\n watchFileChanges?: boolean;\n /**\n * A set of globs for which a direct modification or modification of a dependency\n * should trigger a full restart of the server.\n */\n fullRestartPaths?: string[];\n}\n\ndeclare interface ViteConfig extends UserConfig {\n VitePluginExpressConfig: VitePluginExpressConfig;\n}\n\nexport function VitePluginExpress(cfg: VitePluginExpressConfig): Plugin[] {\n const config: VitePluginExpressConfig = {\n appPath: cfg.appPath,\n appName: cfg.appName ?? 'app',\n exportName: cfg.exportName ?? 'viteExpressApp',\n initAppOnBoot: cfg.initAppOnBoot ?? true,\n outputFormat: cfg.outputFormat ?? 'cjs',\n watchFileChanges: cfg.watchFileChanges ?? true,\n fullRestartPaths: cfg.fullRestartPaths ?? [],\n };\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n config: () => {\n const pluginConfig: UserConfig & { VitePluginExpressConfig: VitePluginExpressConfig } = {\n build: {\n ssr: config.appPath,\n rollupOptions: {\n input: config.appPath,\n output: {\n format: config.outputFormat,\n },\n },\n },\n optimizeDeps: {\n noDiscovery: true,\n },\n server: {\n hmr: false,\n },\n VitePluginExpressConfig: config,\n };\n\n return pluginConfig;\n },\n configureServer: async (server) => {\n server.middlewares.use(await createMiddleware(server));\n },\n },\n ];\n\n return plugins;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACpC,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,SAAS,MAAM,YAAY,CAAC;AACnC,OAAO,EAOL,wBAAwB,GACzB,MAAM,MAAM,CAAC;AAEd,MAAM,GAAG,GAAc,EAAE,OAAO,EAAE,OAAO,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path';\nimport { exit } from 'node:process';\nimport util from 'node:util';\n\nimport debounce from 'debounce';\nimport picomatch from 'picomatch';\nimport stripAnsi from 'strip-ansi';\nimport {\n type ConfigEnv,\n type Connect,\n type ModuleNode,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n isRunnableDevEnvironment,\n} from 'vite';\n\nconst env: ConfigEnv = { command: 'serve', mode: '' };\n\n/**\n * Attempt to format an error for display to the user. Currently only ESBuild\n * transform errors are special-cased: they'll be formatted with the error\n * location and a frame indicating where the error is. All other errors are\n * formatted with {@link util.inspect}.\n */\nfunction formatError(err: any) {\n if (\n !((err as any) instanceof Error) ||\n !err.message?.includes('Transform failed with') ||\n !err.frame ||\n !err.loc\n ) {\n return util.inspect(err);\n }\n\n const location = `${err.loc.file}:${err.loc.line}:${err.loc.column}`;\n return [location, err.frame].map((s) => s.trim()).join('\\n');\n}\n\nasync function getPluginConfig(server: ViteDevServer): Promise<VitePluginExpressConfig> {\n // Ugly type hack to get the plugin config\n const plugin = server.config.plugins.find((p) => p.name === PLUGIN_NAME) as unknown as {\n config: (...args: any[]) => UserConfig & { VitePluginExpressConfig: VitePluginExpressConfig };\n };\n // eslint-disable-next-line @typescript-eslint/no-invalid-void-type\n let userConfig: UserConfig | null | void = null;\n\n if (typeof plugin.config === 'function') {\n userConfig = plugin.config({}, env);\n }\n\n if (userConfig) {\n return (userConfig as ViteConfig).VitePluginExpressConfig;\n }\n\n console.error('Please setup VitePluginExpress in your vite.config.ts first');\n exit(1);\n}\n\nfunction recursivelyGetImporters(\n moduleNode: ModuleNode,\n visited = new Set<ModuleNode>(),\n): Set<ModuleNode> {\n if (!visited.has(moduleNode)) {\n visited.add(moduleNode);\n for (const importer of moduleNode.importers) {\n recursivelyGetImporters(importer, visited);\n }\n }\n\n return visited;\n}\n\nasync function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFunction> {\n const config = await getPluginConfig(server);\n const logger = server.config.logger;\n\n // Store a cached copy of the most recent app module that we can use while\n // doing a full restart.\n let _mostRecentAppModule: any;\n\n async function _loadApp(config: VitePluginExpressConfig) {\n if (!isRunnableDevEnvironment(server.environments.ssr)) {\n throw new Error('VitePluginExpress can only be used with a runnable dev environment');\n }\n\n // We use `runner.import(...)` instead of `ssrLoadModule(...)` because a)\n // the latter will be deprecated soon and b) `runner.import(...)` will\n // automatically produce correct stack traces that account for code\n // transformations done by Vite.\n const appModule = await server.environments.ssr.runner.import(config.appPath);\n\n if (appModule) {\n _mostRecentAppModule = appModule;\n }\n\n const app = appModule[config.exportName!];\n if (!app) {\n logger.error(`Failed to find a named ${config.exportName} from ${config.appPath}`, {\n timestamp: true,\n });\n // eslint-disable-next-line unicorn/no-process-exit\n process.exit(1);\n }\n return app;\n }\n\n if (config.initAppOnBoot) {\n server.httpServer!.once('listening', async () => {\n await _loadApp(config).catch(() => {});\n });\n }\n\n // We'll always normalize the paths to absolute globs.\n const fullRestartPaths = (config.fullRestartPaths ?? []).map((p) =>\n path.resolve(server.config.root, p),\n );\n const fullRestartPathMatchers = fullRestartPaths.map((p) => picomatch(p));\n server.watcher.add(fullRestartPaths);\n\n const debouncedLoadApp = debounce(async () => await _loadApp(config).catch(() => {}), 500, {\n immediate: true,\n });\n const debouncedRestart = debounce(() => server.restart(), 500, { immediate: true });\n\n function needsFullRestart(file: string): boolean {\n // This is the easy case: we had a direct change to a file that is supposed\n // to trigger a full reload.\n if (fullRestartPathMatchers.some((matcher) => matcher(file))) return true;\n\n const modules = Array.from(server.moduleGraph.getModulesByFile(file) ?? []);\n if (modules.length === 0) {\n // This file isn't part of the module graph. No need to do anything.\n return false;\n }\n\n if (modules.length !== 1) {\n throw new Error(`Unexpected module graph state: ${modules.length} modules found for ${file}`);\n }\n\n // If the file is directly or indirectly imported by a module that matches\n // the full restart paths, then we need to do a full restart.\n const importers = recursivelyGetImporters(modules[0]);\n const importerPaths = Array.from(importers)\n .map((m) => m.file)\n .filter((p): p is string => p !== null);\n return importerPaths.some((p) => fullRestartPathMatchers.some((matcher) => matcher(p)));\n }\n\n // We'll manually react to changes in two cases:\n //\n // 1. If the file matches any of the full paths, we'll immediately restart\n // the server. These paths may not be part of the Vite module graph (e.g.\n // SQL files), or they may be part of the module graph but may contain state\n // that can't be hot-reloaded (e.g. database connection pools or worker pools).\n //\n // 2. If we're configured to watch file changes, we'll reload the app (root) module.\n // This gives us a head start over waiting for the next request to trigger a reload.\n server.watcher.on('change', (file) => {\n if (needsFullRestart(path.resolve(server.config.root, file))) {\n logger.info(`Change to ${file} requires a full restart`, { timestamp: true });\n debouncedRestart();\n } else if (config.watchFileChanges) {\n debouncedLoadApp();\n }\n });\n\n // Hook into the environment's `close` method so we can do cleanup when the\n // server is closed. Crucially, this allows us to hook into the `k+Enter` key\n // combo in the Vite dev server to gracefully shut down the server so that it\n // can be restarted cleanly.\n //\n // This uses a hardcoded `close` export from the app module.\n const originalClose = server.environments.ssr.close.bind(server.environments.ssr);\n server.environments.ssr.close = async () => {\n await originalClose();\n\n if (typeof _mostRecentAppModule?.close === 'function') {\n await _mostRecentAppModule.close();\n }\n };\n\n return async function (req: IncomingMessage, res: ServerResponse): Promise<void> {\n const app = await _loadApp(config).catch((err) => {\n const formattedError = formatError(err);\n logger.error(formattedError);\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n res.end(stripAnsi(formattedError));\n return null;\n });\n if (!app) return;\n\n app(req, res);\n };\n}\n\nconst PLUGIN_NAME = 'vite-plugin-express';\n\ntype InternalModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd';\ntype ModuleFormat = InternalModuleFormat | 'commonjs' | 'esm' | 'module' | 'systemjs';\ninterface VitePluginExpressConfig {\n appPath: string;\n appName?: string;\n initAppOnBoot?: boolean;\n exportName?: string;\n outputFormat?: ModuleFormat;\n watchFileChanges?: boolean;\n /**\n * A set of globs for which a direct modification or modification of a dependency\n * should trigger a full restart of the server.\n */\n fullRestartPaths?: string[];\n}\n\ndeclare interface ViteConfig extends UserConfig {\n VitePluginExpressConfig: VitePluginExpressConfig;\n}\n\nexport function VitePluginExpress(cfg: VitePluginExpressConfig): Plugin[] {\n const config: VitePluginExpressConfig = {\n appPath: cfg.appPath,\n appName: cfg.appName ?? 'app',\n exportName: cfg.exportName ?? 'viteExpressApp',\n initAppOnBoot: cfg.initAppOnBoot ?? true,\n outputFormat: cfg.outputFormat ?? 'cjs',\n watchFileChanges: cfg.watchFileChanges ?? true,\n fullRestartPaths: cfg.fullRestartPaths ?? [],\n };\n\n const plugins: Plugin[] = [\n {\n name: PLUGIN_NAME,\n config: () => {\n const pluginConfig: UserConfig & { VitePluginExpressConfig: VitePluginExpressConfig } = {\n build: {\n ssr: config.appPath,\n rollupOptions: {\n input: config.appPath,\n output: {\n format: config.outputFormat,\n },\n },\n },\n optimizeDeps: {\n noDiscovery: true,\n },\n server: {\n hmr: false,\n },\n VitePluginExpressConfig: config,\n };\n\n return pluginConfig;\n },\n configureServer: async (server) => {\n server.middlewares.use(await createMiddleware(server));\n },\n },\n ];\n\n return plugins;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prairielearn/vite-plugin-express",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -14,13 +14,13 @@
|
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"debounce": "^2.2.0",
|
|
17
|
-
"picomatch": "^4.0.
|
|
17
|
+
"picomatch": "^4.0.3",
|
|
18
18
|
"strip-ansi": "^7.1.2",
|
|
19
|
-
"vite": "^7.1.
|
|
19
|
+
"vite": "^7.1.12"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@prairielearn/tsconfig": "^0.0.0",
|
|
23
|
-
"@types/node": "^22.18.
|
|
23
|
+
"@types/node": "^22.18.13",
|
|
24
24
|
"@types/picomatch": "^4.0.2",
|
|
25
25
|
"typescript": "^5.9.3"
|
|
26
26
|
}
|
package/src/index.ts
CHANGED
|
@@ -79,6 +79,7 @@ async function createMiddleware(server: ViteDevServer): Promise<Connect.HandleFu
|
|
|
79
79
|
// Store a cached copy of the most recent app module that we can use while
|
|
80
80
|
// doing a full restart.
|
|
81
81
|
let _mostRecentAppModule: any;
|
|
82
|
+
|
|
82
83
|
async function _loadApp(config: VitePluginExpressConfig) {
|
|
83
84
|
if (!isRunnableDevEnvironment(server.environments.ssr)) {
|
|
84
85
|
throw new Error('VitePluginExpress can only be used with a runnable dev environment');
|