@utoo/pack 1.1.3 → 1.1.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.
Files changed (65) hide show
  1. package/cjs/commands/build.d.ts +3 -0
  2. package/cjs/commands/build.js +165 -0
  3. package/cjs/commands/dev.d.ts +44 -0
  4. package/cjs/commands/dev.js +387 -0
  5. package/cjs/config/readWebpackConfig.d.ts +1 -0
  6. package/cjs/config/readWebpackConfig.js +14 -0
  7. package/cjs/config/types.d.ts +1 -0
  8. package/cjs/config/types.js +17 -0
  9. package/cjs/config/webpackCompat.d.ts +2 -0
  10. package/cjs/config/webpackCompat.js +7 -0
  11. package/cjs/core/hmr.d.ts +80 -0
  12. package/cjs/core/hmr.js +341 -0
  13. package/cjs/core/loaderWorkerPool.d.ts +1 -0
  14. package/cjs/core/loaderWorkerPool.js +35 -0
  15. package/cjs/core/project.d.ts +43 -0
  16. package/cjs/core/project.js +291 -0
  17. package/cjs/core/types.d.ts +94 -0
  18. package/cjs/core/types.js +2 -0
  19. package/cjs/plugins/HtmlPlugin.d.ts +9 -0
  20. package/cjs/plugins/HtmlPlugin.js +116 -0
  21. package/cjs/utils/common.d.ts +3 -0
  22. package/cjs/utils/common.js +32 -0
  23. package/cjs/utils/find-root.d.ts +4 -0
  24. package/cjs/utils/find-root.js +75 -0
  25. package/cjs/utils/html-entry.d.ts +2 -0
  26. package/cjs/utils/html-entry.js +47 -0
  27. package/cjs/utils/mkcert.d.ts +7 -0
  28. package/cjs/utils/mkcert.js +183 -0
  29. package/cjs/utils/print-server-info.d.ts +1 -0
  30. package/cjs/utils/print-server-info.js +50 -0
  31. package/cjs/utils/xcodeProfile.d.ts +1 -0
  32. package/cjs/utils/xcodeProfile.js +16 -0
  33. package/esm/commands/build.d.ts +3 -0
  34. package/esm/commands/build.js +129 -0
  35. package/esm/commands/dev.d.ts +44 -0
  36. package/esm/commands/dev.js +371 -0
  37. package/esm/config/readWebpackConfig.d.ts +1 -0
  38. package/esm/config/readWebpackConfig.js +8 -0
  39. package/esm/config/types.d.ts +1 -0
  40. package/esm/config/types.js +1 -0
  41. package/esm/config/webpackCompat.d.ts +2 -0
  42. package/esm/config/webpackCompat.js +2 -0
  43. package/esm/core/hmr.d.ts +80 -0
  44. package/esm/core/hmr.js +334 -0
  45. package/esm/core/loaderWorkerPool.d.ts +1 -0
  46. package/esm/core/loaderWorkerPool.js +32 -0
  47. package/esm/core/project.d.ts +43 -0
  48. package/esm/core/project.js +253 -0
  49. package/esm/core/types.d.ts +94 -0
  50. package/esm/core/types.js +1 -0
  51. package/esm/plugins/HtmlPlugin.d.ts +9 -0
  52. package/esm/plugins/HtmlPlugin.js +109 -0
  53. package/esm/utils/common.d.ts +3 -0
  54. package/esm/utils/common.js +18 -0
  55. package/esm/utils/find-root.d.ts +4 -0
  56. package/esm/utils/find-root.js +66 -0
  57. package/esm/utils/html-entry.d.ts +2 -0
  58. package/esm/utils/html-entry.js +41 -0
  59. package/esm/utils/mkcert.d.ts +7 -0
  60. package/esm/utils/mkcert.js +176 -0
  61. package/esm/utils/print-server-info.d.ts +1 -0
  62. package/esm/utils/print-server-info.js +44 -0
  63. package/esm/utils/xcodeProfile.d.ts +1 -0
  64. package/esm/utils/xcodeProfile.js +13 -0
  65. package/package.json +12 -14
@@ -0,0 +1,3 @@
1
+ import { WebpackConfig } from "../config/webpackCompat";
2
+ import { BundleOptions } from "../core/types";
3
+ export declare function build(options: BundleOptions | WebpackConfig, projectPath?: string, rootPath?: string): Promise<void>;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.build = build;
37
+ const pack_shared_1 = require("@utoo/pack-shared");
38
+ const child_process_1 = require("child_process");
39
+ const fs_1 = __importStar(require("fs"));
40
+ const nanoid_1 = require("nanoid");
41
+ const path_1 = require("path");
42
+ const webpackCompat_1 = require("../config/webpackCompat");
43
+ const project_1 = require("../core/project");
44
+ const HtmlPlugin_1 = require("../plugins/HtmlPlugin");
45
+ const common_1 = require("../utils/common");
46
+ const find_root_1 = require("../utils/find-root");
47
+ const html_entry_1 = require("../utils/html-entry");
48
+ const xcodeProfile_1 = require("../utils/xcodeProfile");
49
+ function build(options, projectPath, rootPath) {
50
+ let bundleOptions;
51
+ if (options.webpackMode) {
52
+ let webpackConfig = options;
53
+ if (!webpackConfig.entry) {
54
+ const loadedConfig = (0, webpackCompat_1.readWebpackConfig)(projectPath, rootPath);
55
+ webpackConfig = { ...webpackConfig, ...loadedConfig };
56
+ }
57
+ bundleOptions = (0, webpackCompat_1.compatOptionsFromWebpack)(webpackConfig);
58
+ }
59
+ else {
60
+ bundleOptions = options;
61
+ }
62
+ if (!rootPath) {
63
+ // help user to find the rootDir automatically.
64
+ rootPath = (0, find_root_1.findRootDir)(projectPath || process.cwd());
65
+ }
66
+ return buildInternal(bundleOptions, projectPath, rootPath);
67
+ }
68
+ async function buildInternal(bundleOptions, projectPath, rootPath) {
69
+ var _a, _b, _c, _d, _e, _f;
70
+ (0, common_1.blockStdout)();
71
+ if (process.env.XCODE_PROFILE) {
72
+ await (0, xcodeProfile_1.xcodeProfilingReady)();
73
+ }
74
+ (0, html_entry_1.processHtmlEntry)(bundleOptions.config, projectPath || process.cwd());
75
+ const createProject = (0, project_1.projectFactory)();
76
+ const project = await createProject({
77
+ processEnv: (_a = bundleOptions.processEnv) !== null && _a !== void 0 ? _a : {},
78
+ defineEnv: (0, common_1.createDefineEnv)({
79
+ config: bundleOptions.config,
80
+ dev: (_b = bundleOptions.dev) !== null && _b !== void 0 ? _b : false,
81
+ optionDefineEnv: bundleOptions.defineEnv,
82
+ }),
83
+ watch: {
84
+ enable: false,
85
+ },
86
+ dev: (_c = bundleOptions.dev) !== null && _c !== void 0 ? _c : false,
87
+ buildId: bundleOptions.buildId || (0, nanoid_1.nanoid)(),
88
+ config: {
89
+ ...bundleOptions.config,
90
+ stats: Boolean(process.env.ANALYZE) ||
91
+ bundleOptions.config.stats ||
92
+ bundleOptions.config.entry.some((e) => !!e.html),
93
+ },
94
+ projectPath: projectPath || process.cwd(),
95
+ rootPath: rootPath || projectPath || process.cwd(),
96
+ packPath: (0, common_1.getPackPath)(),
97
+ }, {
98
+ persistentCaching: false,
99
+ });
100
+ const entrypoints = await project.writeAllEntrypointsToDisk();
101
+ (0, pack_shared_1.handleIssues)(entrypoints.issues);
102
+ const htmlConfigs = [
103
+ ...(Array.isArray(bundleOptions.config.html)
104
+ ? bundleOptions.config.html
105
+ : bundleOptions.config.html
106
+ ? [bundleOptions.config.html]
107
+ : []),
108
+ ...bundleOptions.config.entry.filter((e) => !!e.html).map((e) => e.html),
109
+ ];
110
+ if (htmlConfigs.length > 0) {
111
+ const assets = { js: [], css: [] };
112
+ const outputDir = ((_d = bundleOptions.config.output) === null || _d === void 0 ? void 0 : _d.path) || (0, path_1.join)(process.cwd(), "dist");
113
+ if (assets.js.length === 0 && assets.css.length === 0) {
114
+ const statsPath = (0, path_1.join)(outputDir, "stats.json");
115
+ if ((0, fs_1.existsSync)(statsPath)) {
116
+ try {
117
+ const stats = JSON.parse(fs_1.default.readFileSync(statsPath, "utf-8"));
118
+ if (stats.assets) {
119
+ stats.assets.forEach((asset) => {
120
+ if (asset.name.endsWith(".js"))
121
+ assets.js.push(asset.name);
122
+ if (asset.name.endsWith(".css"))
123
+ assets.css.push(asset.name);
124
+ });
125
+ }
126
+ }
127
+ catch (e) {
128
+ console.warn("Failed to read stats.json for assets discovery", e);
129
+ }
130
+ }
131
+ }
132
+ const publicPath = (_e = bundleOptions.config.output) === null || _e === void 0 ? void 0 : _e.publicPath;
133
+ for (const config of htmlConfigs) {
134
+ const plugin = new HtmlPlugin_1.HtmlPlugin(config);
135
+ await plugin.generate(outputDir, assets, publicPath);
136
+ }
137
+ }
138
+ if (process.env.ANALYZE) {
139
+ await analyzeBundle(((_f = bundleOptions.config.output) === null || _f === void 0 ? void 0 : _f.path) || "dist");
140
+ }
141
+ await project.shutdown();
142
+ // TODO: Maybe run tasks in worker is a better way, see
143
+ // https://github.com/vercel/next.js/blob/512d8283054407ab92b2583ecce3b253c3be7b85/packages/next/src/lib/worker.ts
144
+ }
145
+ async function analyzeBundle(outputPath) {
146
+ const statsPath = (0, path_1.join)(outputPath, "stats.json");
147
+ if (!(0, fs_1.existsSync)(statsPath)) {
148
+ console.warn(`Stats file not found at ${statsPath}. Make sure to enable stats in your configuration.`);
149
+ return;
150
+ }
151
+ return new Promise((resolve, reject) => {
152
+ const analyzer = (0, child_process_1.spawn)("npx", ["webpack-bundle-analyzer", statsPath], {
153
+ stdio: "inherit",
154
+ shell: true,
155
+ });
156
+ analyzer.on("error", (error) => {
157
+ reject(new Error(`Failed to start bundle analyzer: ${error.message}`));
158
+ });
159
+ analyzer.on("close", () => {
160
+ // The analyzer process has finished, so we can resolve the promise
161
+ // to allow the build process to exit gracefully.
162
+ resolve();
163
+ });
164
+ });
165
+ }
@@ -0,0 +1,44 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ import send from "send";
3
+ import { Duplex, Writable } from "stream";
4
+ import { WebpackConfig } from "../config/webpackCompat";
5
+ import { BundleOptions } from "../core/types";
6
+ export declare function serve(options: BundleOptions | WebpackConfig, projectPath?: string, rootPath?: string, serverOptions?: StartServerOptions): Promise<void>;
7
+ export interface SelfSignedCertificate {
8
+ key: string;
9
+ cert: string;
10
+ rootCA?: string;
11
+ }
12
+ export interface StartServerOptions {
13
+ port: number;
14
+ https?: boolean;
15
+ hostname?: string;
16
+ logServerInfo?: boolean;
17
+ selfSignedCertificate?: SelfSignedCertificate;
18
+ }
19
+ export type RequestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
20
+ export type UpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => Promise<void>;
21
+ export type ServerInitResult = {
22
+ requestHandler: RequestHandler;
23
+ upgradeHandler: UpgradeHandler;
24
+ closeUpgraded: () => void;
25
+ };
26
+ export declare function startServer(serverOptions: StartServerOptions, bundleOptions: BundleOptions, projectPath: string, rootPath?: string): Promise<void>;
27
+ export declare function initialize(bundleOptions: BundleOptions, projectPath: string, rootPath?: string): Promise<ServerInitResult>;
28
+ export declare function pipeToNodeResponse(readable: ReadableStream<Uint8Array>, res: ServerResponse, waitUntilForEnd?: Promise<unknown>): Promise<void>;
29
+ export declare function createAbortController(response: Writable): AbortController;
30
+ export declare function isAbortError(e: any): e is Error & {
31
+ name: "AbortError";
32
+ };
33
+ export declare const ResponseAbortedName = "ResponseAborted";
34
+ export declare class ResponseAborted extends Error {
35
+ readonly name = "ResponseAborted";
36
+ }
37
+ export declare class DetachedPromise<T = any> {
38
+ readonly resolve: (value: T | PromiseLike<T>) => void;
39
+ readonly reject: (reason: any) => void;
40
+ readonly promise: Promise<T>;
41
+ constructor();
42
+ }
43
+ export declare function serveStatic(req: IncomingMessage, res: ServerResponse, path: string, opts?: Parameters<typeof send>[2]): Promise<void>;
44
+ export declare function formatHostname(hostname: string): string;
@@ -0,0 +1,387 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DetachedPromise = exports.ResponseAborted = exports.ResponseAbortedName = void 0;
7
+ exports.serve = serve;
8
+ exports.startServer = startServer;
9
+ exports.initialize = initialize;
10
+ exports.pipeToNodeResponse = pipeToNodeResponse;
11
+ exports.createAbortController = createAbortController;
12
+ exports.isAbortError = isAbortError;
13
+ exports.serveStatic = serveStatic;
14
+ exports.formatHostname = formatHostname;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const http_1 = __importDefault(require("http"));
17
+ const https_1 = __importDefault(require("https"));
18
+ const net_1 = require("net");
19
+ const path_1 = __importDefault(require("path"));
20
+ const send_1 = __importDefault(require("send"));
21
+ const url_1 = __importDefault(require("url"));
22
+ const webpackCompat_1 = require("../config/webpackCompat");
23
+ const hmr_1 = require("../core/hmr");
24
+ const common_1 = require("../utils/common");
25
+ const find_root_1 = require("../utils/find-root");
26
+ const mkcert_1 = require("../utils/mkcert");
27
+ const print_server_info_1 = require("../utils/print-server-info");
28
+ const xcodeProfile_1 = require("../utils/xcodeProfile");
29
+ function serve(options, projectPath, rootPath, serverOptions) {
30
+ let bundleOptions;
31
+ if (options.webpackMode) {
32
+ let webpackConfig = options;
33
+ if (!webpackConfig.entry) {
34
+ const loadedConfig = (0, webpackCompat_1.readWebpackConfig)(projectPath, rootPath);
35
+ webpackConfig = { ...webpackConfig, ...loadedConfig };
36
+ }
37
+ bundleOptions = (0, webpackCompat_1.compatOptionsFromWebpack)(webpackConfig);
38
+ }
39
+ else {
40
+ bundleOptions = options;
41
+ }
42
+ if (!rootPath) {
43
+ // help user to find the rootDir automatically
44
+ rootPath = (0, find_root_1.findRootDir)(projectPath || process.cwd());
45
+ }
46
+ return serveInternal(bundleOptions, projectPath, rootPath, serverOptions);
47
+ }
48
+ async function serveInternal(options, projectPath, rootPath, serverOptions) {
49
+ (0, common_1.blockStdout)();
50
+ if (process.env.XCODE_PROFILE) {
51
+ await (0, xcodeProfile_1.xcodeProfilingReady)();
52
+ }
53
+ await startServer({
54
+ hostname: (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.hostname) || "localhost",
55
+ port: (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.port) || 3000,
56
+ https: serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.https,
57
+ logServerInfo: serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.logServerInfo,
58
+ selfSignedCertificate: (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.https)
59
+ ? await (0, mkcert_1.createSelfSignedCertificate)((serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.hostname) || "localhost")
60
+ : undefined,
61
+ }, {
62
+ ...options,
63
+ config: {
64
+ ...options.config,
65
+ devServer: { hot: true },
66
+ },
67
+ packPath: (0, common_1.getPackPath)(),
68
+ }, projectPath || process.cwd(), rootPath);
69
+ }
70
+ async function startServer(serverOptions, bundleOptions, projectPath, rootPath) {
71
+ let { port, hostname, selfSignedCertificate } = serverOptions;
72
+ process.title = "utoopack-dev-server";
73
+ let handlersReady = () => { };
74
+ let handlersError = () => { };
75
+ let handlersPromise = new Promise((resolve, reject) => {
76
+ handlersReady = resolve;
77
+ handlersError = reject;
78
+ });
79
+ let requestHandler = async (req, res) => {
80
+ if (handlersPromise) {
81
+ await handlersPromise;
82
+ return requestHandler(req, res);
83
+ }
84
+ throw new Error("Invariant request handler was not setup");
85
+ };
86
+ let upgradeHandler = async (req, socket, head) => {
87
+ if (handlersPromise) {
88
+ await handlersPromise;
89
+ return upgradeHandler(req, socket, head);
90
+ }
91
+ throw new Error("Invariant upgrade handler was not setup");
92
+ };
93
+ async function requestListener(req, res) {
94
+ try {
95
+ if (handlersPromise) {
96
+ await handlersPromise;
97
+ handlersPromise = undefined;
98
+ }
99
+ await requestHandler(req, res);
100
+ }
101
+ catch (err) {
102
+ res.statusCode = 500;
103
+ res.end("Internal Server Error");
104
+ console.error(`Failed to handle request for ${req.url}`);
105
+ console.error(err);
106
+ }
107
+ }
108
+ const server = selfSignedCertificate
109
+ ? https_1.default.createServer({
110
+ key: fs_1.default.readFileSync(selfSignedCertificate.key),
111
+ cert: fs_1.default.readFileSync(selfSignedCertificate.cert),
112
+ }, requestListener)
113
+ : http_1.default.createServer(requestListener);
114
+ server.on("upgrade", async (req, socket, head) => {
115
+ try {
116
+ await upgradeHandler(req, socket, head);
117
+ }
118
+ catch (err) {
119
+ socket.destroy();
120
+ console.error(`Failed to handle request for ${req.url}`);
121
+ console.error(err);
122
+ }
123
+ });
124
+ let portRetryCount = 0;
125
+ const originalPort = port;
126
+ server.on("error", (err) => {
127
+ if (port && err.code === "EADDRINUSE" && portRetryCount < 10) {
128
+ port += 1;
129
+ portRetryCount += 1;
130
+ server.listen(port, hostname);
131
+ }
132
+ else {
133
+ console.error(`Failed to start server`);
134
+ console.error(err);
135
+ process.exit(1);
136
+ }
137
+ });
138
+ await new Promise((resolve) => {
139
+ server.on("listening", async () => {
140
+ const addr = server.address();
141
+ const actualHostname = formatHostname(typeof addr === "object"
142
+ ? (addr === null || addr === void 0 ? void 0 : addr.address) || hostname || "localhost"
143
+ : addr);
144
+ const formattedHostname = !hostname || actualHostname === "0.0.0.0"
145
+ ? "localhost"
146
+ : actualHostname === "[::]"
147
+ ? "[::1]"
148
+ : formatHostname(hostname);
149
+ port = typeof addr === "object" ? (addr === null || addr === void 0 ? void 0 : addr.port) || port : port;
150
+ if (portRetryCount) {
151
+ console.warn(`Port ${originalPort} is in use, using available port ${port} instead.`);
152
+ }
153
+ if (serverOptions.logServerInfo !== false) {
154
+ (0, print_server_info_1.printServerInfo)(serverOptions.https ? "https" : "http", formattedHostname, port);
155
+ }
156
+ try {
157
+ let cleanupStarted = false;
158
+ let closeUpgraded = null;
159
+ const cleanup = () => {
160
+ if (cleanupStarted) {
161
+ return;
162
+ }
163
+ cleanupStarted = true;
164
+ (async () => {
165
+ console.debug("start-server process cleanup");
166
+ await new Promise((res) => {
167
+ server.close((err) => {
168
+ if (err)
169
+ console.error(err);
170
+ res();
171
+ });
172
+ server.closeAllConnections();
173
+ closeUpgraded === null || closeUpgraded === void 0 ? void 0 : closeUpgraded();
174
+ });
175
+ console.debug("start-server process cleanup finished");
176
+ process.exit(0);
177
+ })();
178
+ };
179
+ const exception = (err) => {
180
+ console.error(err);
181
+ };
182
+ process.on("SIGINT", cleanup);
183
+ process.on("SIGTERM", cleanup);
184
+ process.on("rejectionHandled", () => { });
185
+ process.on("uncaughtException", exception);
186
+ process.on("unhandledRejection", exception);
187
+ const initResult = await initialize(bundleOptions, projectPath, rootPath);
188
+ requestHandler = initResult.requestHandler;
189
+ upgradeHandler = initResult.upgradeHandler;
190
+ closeUpgraded = initResult.closeUpgraded;
191
+ handlersReady();
192
+ }
193
+ catch (err) {
194
+ handlersError();
195
+ console.error(err);
196
+ process.exit(1);
197
+ }
198
+ resolve();
199
+ });
200
+ server.listen(port, hostname);
201
+ });
202
+ }
203
+ async function initialize(bundleOptions, projectPath, rootPath) {
204
+ process.env.NODE_ENV = "development";
205
+ const hotReloader = await (0, hmr_1.createHotReloader)(bundleOptions, projectPath, rootPath);
206
+ await hotReloader.start();
207
+ const requestHandlerImpl = async (req, res) => {
208
+ req.on("error", console.error);
209
+ res.on("error", console.error);
210
+ const handleRequest = async () => {
211
+ var _a;
212
+ if (!(req.method === "GET" || req.method === "HEAD")) {
213
+ res.setHeader("Allow", ["GET", "HEAD"]);
214
+ res.statusCode = 405;
215
+ res.end();
216
+ }
217
+ const distRoot = path_1.default.resolve(projectPath, ((_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.path) || "./dist");
218
+ try {
219
+ const reqUrl = req.url || "";
220
+ const path = url_1.default.parse(reqUrl).pathname || "";
221
+ return await serveStatic(req, res, path, { root: distRoot });
222
+ }
223
+ catch (err) {
224
+ res.setHeader("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
225
+ res.statusCode = 404;
226
+ res.end();
227
+ }
228
+ };
229
+ try {
230
+ await handleRequest();
231
+ }
232
+ catch (err) {
233
+ res.statusCode = 500;
234
+ res.end("Internal Server Error");
235
+ }
236
+ };
237
+ let requestHandler = requestHandlerImpl;
238
+ const logError = async (type, err) => {
239
+ if (type === "unhandledRejection") {
240
+ console.error("unhandledRejection: ", err);
241
+ }
242
+ else if (type === "uncaughtException") {
243
+ console.error("uncaughtException: ", err);
244
+ }
245
+ };
246
+ process.on("uncaughtException", logError.bind(null, "uncaughtException"));
247
+ process.on("unhandledRejection", logError.bind(null, "unhandledRejection"));
248
+ const upgradeHandler = async (req, socket, head) => {
249
+ var _a;
250
+ try {
251
+ const isHMRRequest = (_a = req.url) === null || _a === void 0 ? void 0 : _a.includes("turbopack-hmr");
252
+ if (isHMRRequest) {
253
+ hotReloader.onHMR(req, socket, head);
254
+ }
255
+ else {
256
+ socket.end();
257
+ }
258
+ }
259
+ catch (err) {
260
+ console.error("Error handling upgrade request", err);
261
+ socket.end();
262
+ }
263
+ };
264
+ return {
265
+ requestHandler,
266
+ upgradeHandler,
267
+ closeUpgraded() {
268
+ hotReloader.close();
269
+ },
270
+ };
271
+ }
272
+ async function pipeToNodeResponse(readable, res, waitUntilForEnd) {
273
+ try {
274
+ const { errored, destroyed } = res;
275
+ if (errored || destroyed)
276
+ return;
277
+ const controller = createAbortController(res);
278
+ const writer = createWriterFromResponse(res, waitUntilForEnd);
279
+ await readable.pipeTo(writer, { signal: controller.signal });
280
+ }
281
+ catch (err) {
282
+ if (isAbortError(err))
283
+ return;
284
+ throw new Error("failed to pipe response", { cause: err });
285
+ }
286
+ }
287
+ function createAbortController(response) {
288
+ const controller = new AbortController();
289
+ response.once("close", () => {
290
+ if (response.writableFinished)
291
+ return;
292
+ controller.abort(new ResponseAborted());
293
+ });
294
+ return controller;
295
+ }
296
+ function isAbortError(e) {
297
+ return (e === null || e === void 0 ? void 0 : e.name) === "AbortError" || (e === null || e === void 0 ? void 0 : e.name) === exports.ResponseAbortedName;
298
+ }
299
+ exports.ResponseAbortedName = "ResponseAborted";
300
+ class ResponseAborted extends Error {
301
+ constructor() {
302
+ super(...arguments);
303
+ this.name = exports.ResponseAbortedName;
304
+ }
305
+ }
306
+ exports.ResponseAborted = ResponseAborted;
307
+ function createWriterFromResponse(res, waitUntilForEnd) {
308
+ let started = false;
309
+ let drained = new DetachedPromise();
310
+ function onDrain() {
311
+ drained.resolve();
312
+ }
313
+ res.on("drain", onDrain);
314
+ res.once("close", () => {
315
+ res.off("drain", onDrain);
316
+ drained.resolve();
317
+ });
318
+ const finished = new DetachedPromise();
319
+ res.once("finish", () => {
320
+ finished.resolve();
321
+ });
322
+ return new WritableStream({
323
+ write: async (chunk) => {
324
+ if (!started) {
325
+ started = true;
326
+ res.flushHeaders();
327
+ }
328
+ try {
329
+ const ok = res.write(chunk);
330
+ if ("flush" in res && typeof res.flush === "function") {
331
+ res.flush();
332
+ }
333
+ if (!ok) {
334
+ await drained.promise;
335
+ drained = new DetachedPromise();
336
+ }
337
+ }
338
+ catch (err) {
339
+ res.end();
340
+ throw new Error("failed to write chunk to response", { cause: err });
341
+ }
342
+ },
343
+ abort: (err) => {
344
+ if (res.writableFinished)
345
+ return;
346
+ res.destroy(err);
347
+ },
348
+ close: async () => {
349
+ if (waitUntilForEnd) {
350
+ await waitUntilForEnd;
351
+ }
352
+ if (res.writableFinished)
353
+ return;
354
+ res.end();
355
+ return finished.promise;
356
+ },
357
+ });
358
+ }
359
+ class DetachedPromise {
360
+ constructor() {
361
+ let resolve;
362
+ let reject;
363
+ this.promise = new Promise((res, rej) => {
364
+ resolve = res;
365
+ reject = rej;
366
+ });
367
+ this.resolve = resolve;
368
+ this.reject = reject;
369
+ }
370
+ }
371
+ exports.DetachedPromise = DetachedPromise;
372
+ function serveStatic(req, res, path, opts) {
373
+ return new Promise((resolve, reject) => {
374
+ (0, send_1.default)(req, path, opts)
375
+ .on("directory", () => {
376
+ const err = new Error("No directory access");
377
+ err.code = "ENOENT";
378
+ reject(err);
379
+ })
380
+ .on("error", reject)
381
+ .pipe(res)
382
+ .on("finish", resolve);
383
+ });
384
+ }
385
+ function formatHostname(hostname) {
386
+ return (0, net_1.isIPv6)(hostname) ? `[${hostname}]` : hostname;
387
+ }
@@ -0,0 +1 @@
1
+ export declare function readWebpackConfig(projectPath?: string, rootPath?: string): any;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readWebpackConfig = readWebpackConfig;
7
+ const path_1 = __importDefault(require("path"));
8
+ function readWebpackConfig(projectPath, rootPath) {
9
+ const projectPathOutOfRoot = projectPath === undefined
10
+ ? process.cwd()
11
+ : path_1.default.join(rootPath !== null && rootPath !== void 0 ? rootPath : "", projectPath);
12
+ const configPath = path_1.default.join(projectPathOutOfRoot, "webpack.config.js");
13
+ return require(configPath);
14
+ }
@@ -0,0 +1 @@
1
+ export * from "@utoo/pack-shared";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("@utoo/pack-shared"), exports);
@@ -0,0 +1,2 @@
1
+ export { compatOptionsFromWebpack, type WebpackConfig, } from "@utoo/pack-shared";
2
+ export { readWebpackConfig } from "./readWebpackConfig";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readWebpackConfig = exports.compatOptionsFromWebpack = void 0;
4
+ var pack_shared_1 = require("@utoo/pack-shared");
5
+ Object.defineProperty(exports, "compatOptionsFromWebpack", { enumerable: true, get: function () { return pack_shared_1.compatOptionsFromWebpack; } });
6
+ var readWebpackConfig_1 = require("./readWebpackConfig");
7
+ Object.defineProperty(exports, "readWebpackConfig", { enumerable: true, get: function () { return readWebpackConfig_1.readWebpackConfig; } });