@morlay/dsh-client-modules 0.2.11-alpha.3 → 0.2.12

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/src/bundle.ts CHANGED
@@ -9,15 +9,16 @@
9
9
  * 两者产出的地址同构(`@client-modules/<pkg>@<version>/<file>`),所以运行时按 URL 取即可。
10
10
  */
11
11
  import { createHash } from "node:crypto";
12
- import { mkdir, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";
12
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
13
13
  import { createRequire } from "node:module";
14
14
  import { findPackageJSON } from "node:module";
15
- import { dirname, join, relative, resolve, sep } from "node:path";
15
+ import { basename, dirname, extname, join, relative, sep } from "node:path";
16
16
  import { pathToFileURL } from "node:url";
17
17
  import { clientAssetPlugin, NODE_BUILTIN } from "@morlay/dsh-cordis-assets/assets";
18
18
  import { cssInlinePlugins } from "@morlay/dsh-cordis-assets/styles";
19
19
  import { rolldown, type Plugin } from "rolldown";
20
20
  import { esmExternalRequirePlugin, type PluginOption } from "vite";
21
+ import { type ClientBuildMeta, clientBuildMeta, clientMetaDefines } from "./client-meta.ts";
21
22
  import { encodePackageName, entryFileNameOf, packageNameOf } from "./resolve.ts";
22
23
 
23
24
  /** 裸包名 → `^名(/|$)`:既覆盖子路径引用,也不会把 `node:fs`、`./x` 误判成包。 */
@@ -61,7 +62,7 @@ export function clientModulesAlias(options: {
61
62
  * 规则变了、源码没变时,旧产物必须作废,否则会继续复用带着老 URL 的字节。
62
63
  */
63
64
  /** 构建器**规则**版本:改解析 / 改写规则就 bump(见 {@link BUNDLER_REV})。 */
64
- const BUNDLER_RULES = "28";
65
+ const BUNDLER_RULES = "36";
65
66
 
66
67
  /**
67
68
  * 地址里的 `?v=`(与 vite 同一个写法):构建器**规则指纹**(`BUNDLER_RULES` 的哈希,形如 vite 的 `?v=`)。
@@ -96,7 +97,7 @@ export interface BundleOptions {
96
97
  name: string;
97
98
  /** 包版本(进缓存键与地址)。 */
98
99
  version: string;
99
- /** 入口名 → 源码文件(我们的包:出口名;三方:`index`)。 */
100
+ /** 出口名 → 入口文件(由调用方的清单解析得到:`exports` 条件 / `module` / `main`)。 */
100
101
  input: Record<string, string>;
101
102
  /** 指纹的输入文件集(我们的包给 `src`;三方给它的入口)。 */
102
103
  watch: readonly string[];
@@ -307,11 +308,15 @@ export function urlOf(
307
308
  * **只替换 `process.env` 系列**:裸的 `process` 不能碰——它可能只是个普通标识符(`zod` 里就有一个叫
308
309
  * `process` 的函数,替换掉直接把源码变成语法错误)。
309
310
  */
310
- function browserProcessPlugin(): PluginOption {
311
- const replace = (code: string): string =>
312
- code
313
- .replaceAll(/\bprocess\.env\.NODE_ENV\b/gu, JSON.stringify("development"))
314
- .replaceAll(/\bprocess\.env\b/gu, "({ env: {} })");
311
+ export function browserProcessPlugin(meta: ClientBuildMeta = {}): PluginOption {
312
+ // 版本元数据那几个键**先**换成字面量:它们要的是真值(设置页的版本行、侧栏的 `<commit>-dirty`),
313
+ // 而后面那条把 `process.env` 整个换成空壳的规则会连它们一起吞掉。
314
+ const metaDefines = Object.entries(clientMetaDefines(meta));
315
+ const replace = (code: string): string => {
316
+ let next = code.replaceAll(/\bprocess\.env\.NODE_ENV\b/gu, JSON.stringify("development"));
317
+ for (const [key, value] of metaDefines) next = next.replaceAll(key, value);
318
+ return next.replaceAll(/\bprocess\.env\b/gu, "({ env: {} })");
319
+ };
315
320
  return {
316
321
  name: "dsh-browser-process",
317
322
  enforce: "pre",
@@ -323,156 +328,262 @@ function browserProcessPlugin(): PluginOption {
323
328
  }
324
329
 
325
330
  /**
326
- * 入口是否按**它所属包的声明**是 CJS(Node 的 ESM 解析会做 `default = module.exports` 的那一侧)。
331
+ * `export const <名>` 用不了的键:JS 的保留字(`zod@4` 的 CJS 面有 `function` / `void` / `null`
332
+ * 这些键,原样拼出去就是 `SyntaxError`)。
333
+ */
334
+ const RESERVED_EXPORT_NAMES = new Set([
335
+ "await",
336
+ "break",
337
+ "case",
338
+ "catch",
339
+ "class",
340
+ "const",
341
+ "continue",
342
+ "debugger",
343
+ "default",
344
+ "delete",
345
+ "do",
346
+ "else",
347
+ "enum",
348
+ "eval",
349
+ "export",
350
+ "extends",
351
+ "false",
352
+ "finally",
353
+ "for",
354
+ "function",
355
+ "if",
356
+ "implements",
357
+ "import",
358
+ "in",
359
+ "instanceof",
360
+ "interface",
361
+ "let",
362
+ "new",
363
+ "null",
364
+ "package",
365
+ "private",
366
+ "protected",
367
+ "public",
368
+ "return",
369
+ "static",
370
+ "super",
371
+ "switch",
372
+ "this",
373
+ "throw",
374
+ "true",
375
+ "try",
376
+ "typeof",
377
+ "undefined",
378
+ "var",
379
+ "void",
380
+ "while",
381
+ "with",
382
+ "yield",
383
+ ]);
384
+
385
+ /** ESM 的顶层语法节点:`import` / `export` 声明。 */
386
+ const ESM_STATEMENT_TYPES = new Set([
387
+ "ImportDeclaration",
388
+ "ExportNamedDeclaration",
389
+ "ExportDefaultDeclaration",
390
+ "ExportAllDeclaration",
391
+ ]);
392
+
393
+ /**
394
+ * `.js` 且没有 `type` 时,按 **Node 的语法检测**判:有 ESM 语法(顶层 `import`/`export`)就是 ESM,
395
+ * 否则 CJS(Node 23+ 默认开启 `--experimental-detect-module`)。
396
+ *
397
+ * 用 rolldown 自带的解析器(`rolldown/parseAst`),不自己写词法扫描。
398
+ *
399
+ * @param entry - `.js` 入口的绝对路径。
400
+ * @returns 是否含 ESM 语法。
401
+ */
402
+ async function hasModuleSyntax(entry: string): Promise<boolean> {
403
+ try {
404
+ const [{ parseAst }, source] = await Promise.all([
405
+ import("rolldown/parseAst"),
406
+ readFile(entry, "utf8"),
407
+ ]);
408
+ const program = parseAst(source, null, entry) as unknown as {
409
+ body: readonly { type: string }[];
410
+ };
411
+ return program.body.some((node) => ESM_STATEMENT_TYPES.has(node.type));
412
+ } catch {
413
+ // 解析不了(CJS 专有语法在 module 模式下报错等):按 CJS 走,求值失败时保持原样。
414
+ return false;
415
+ }
416
+ }
417
+
418
+ /** 一个入口的模块类型。 */
419
+ export type ModuleKind = "esm" | "cjs" | "source" | "style" | "asset";
420
+
421
+ /**
422
+ * 一个入口的模块类型:**扩展名 + 最近的 `package.json`**,不猜源码。
423
+ *
424
+ * | 入口 | 类型 |
425
+ * | --- | --- |
426
+ * | `.mjs` / `.mts` | `esm` |
427
+ * | `.cjs` / `.cts` | `cjs` |
428
+ * | `.js` + `type: "module"` | `esm` |
429
+ * | `.js` + `module` 字段指向它 | `esm`(打包器约定) |
430
+ * | 其余 `.js` | `cjs` |
431
+ * | `.ts` / `.tsx` / `.jsx` | `source`(转译面,原样) |
432
+ * | `.css` | `style` |
433
+ * | 其他(图片 / 字体 / `.json` …) | `asset` |
327
434
  *
328
- * 判据只看声明,不看源码内容:
329
- * - `type: "module"` 的包 → 恒为 ESM(`.mjs` 同理);
330
- * - 否则是"老约定":`module` 字段指向的那份视为 ESM(打包器约定,Node 不认),其余 `.js` 视为 CJS、
331
- * `.cjs` 恒为 CJS;`.ts` 这类源码交给语法(rolldown 自己判)。
435
+ * 这是 `exports` 条件(`import` / `require`)选出入口之后的**第二步**:条件决定"哪个文件",这里决定
436
+ * "那个文件是什么模块"。只有 `cjs` 需要导出面适配,`esm` / `source` 一律原样。
332
437
  *
333
- * 以前这里是"读源码找 `module.exports =`",那是猜:`exports.` 出现在注释里就会误判,而 `type: module` 的
334
- * 包即使有 CJS 写法也不该被当 CJS。
438
+ * @param entry - 入口的绝对路径。
439
+ * @returns 模块类型。
335
440
  */
336
- async function declaresCjs(entry: string): Promise<boolean> {
337
- if (entry.endsWith(".mjs")) return false;
338
- if (entry.endsWith(".cjs")) return true;
339
- if (!entry.endsWith(".js")) return false;
441
+ export async function moduleKindOf(entry: string): Promise<ModuleKind> {
442
+ const extension = extname(entry).toLowerCase();
443
+ if (extension === ".css") return "style";
444
+ if (extension === ".mjs" || extension === ".mts") return "esm";
445
+ if (extension === ".cjs" || extension === ".cts") return "cjs";
446
+ if (extension === ".ts" || extension === ".tsx" || extension === ".jsx") return "source";
447
+ if (extension !== ".js") return "asset";
340
448
  const manifestPath = await packageJsonNear(entry);
341
449
  const manifest = JSON.parse(await readFile(manifestPath, "utf8").catch(() => "{}")) as {
342
450
  type?: string;
343
- module?: string;
344
451
  };
345
- if (manifest.type === "module") return false;
346
- const manifestModule = manifest.module;
347
- if (manifestModule === undefined) return true;
348
- return resolve(dirname(manifestPath), manifestModule) !== resolve(entry);
452
+ if (manifest.type === "module") return "esm";
453
+ if (manifest.type === "commonjs") return "cjs";
454
+ // 没有 `type`:Node 的规则是**语法检测**(`--experimental-detect-module`,Node 23+ 默认开启)。
455
+ return (await hasModuleSyntax(entry)) ? "esm" : "cjs";
349
456
  }
350
457
 
351
458
  /**
352
- * CJS 入口的**具名导出包装**(`react` 这类)。
459
+ * CJS 入口的**具名导出包装**(`react` / `@xterm/xterm` 这类)。
353
460
  *
354
- * `react` 的入口是 `module.exports = require('./cjs/react.development.js')`,rolldown 静态分析不出具名
355
- * 导出,产物只剩 `export default …`——而浏览器侧要 `import { Fragment } from "react"`,于是**整个 import
356
- * 阶段就失败**(入口一行都执行不了)。ESM 的导出必须**静态可枚举**(不能 `export * from` 一个运行期对象),
357
- * 所以这里求值入口拿到它的键,生成一份把它们写成 `export const` 的包装文件,拿包装文件当入口。
461
+ * rolldown 对 CJS 入口的产物的具名导出只能靠静态分析;`module.exports = require(…)` 与 UMD 包装它都分析
462
+ * 不出来,产物只剩 `export default …`——而浏览器侧要 `import { Fragment } from "react"`、`import { Terminal }
463
+ * from "@xterm/xterm"`,整个 import 阶段就失败。ESM 的导出必须**静态可枚举**,所以这里求值入口拿到它的键,
464
+ * 生成一份把它们写成 `export const` 的包装文件,拿包装文件当入口。
358
465
  *
359
- * @returns 包装文件路径;入口不是 CJS、或求值拿不到键时 undefined(保持原样)。
466
+ * 类型由 {@link moduleKindOf} 先按 **exports 落点 + 扩展名/type** 静态判定,只有 CJS 才进来;
467
+ * 这里求值一次只为**拿键**(`export const <键>` + `default = module.exports`)。ESM 原封不动。
468
+ *
469
+ * @returns 包装文件路径;入口不是 node 能求值的 CJS、或没有可静态导出的键时 undefined(保持原样)。
360
470
  */
361
471
  async function cjsShimOf(options: {
362
472
  name: string;
363
473
  exportName: string;
474
+ /** 具体文件:只用来求值判 CJS / 枚举键。 */
364
475
  entry: string;
365
- outDir: string;
476
+ /** 产物里的 import 来源:说明符(交给 rolldown 按 `exports` 解析)或文件路径。 */
477
+ from: string;
366
478
  log?: (message: string) => void;
367
- }): Promise<string | undefined> {
368
- if (!(await declaresCjs(options.entry))) return undefined;
369
- let keys: string[];
479
+ }): Promise<{ id: string; code: string } | undefined> {
480
+ let loaded: Record<string, unknown> | undefined;
370
481
  try {
371
- // 求值才知道键:CJS 的导出面是**运行期**的(静态分析只能看到 `module.exports = require(…)`)。
372
- const loaded = createRequire(options.entry)(options.entry) as
373
- | Record<string, unknown>
374
- | undefined;
375
- keys = Object.keys(loaded ?? {});
482
+ // 类型已由 {@link moduleKindOf} 静态判定(只有 CJS 会走到这里);这一句只为**拿键**:
483
+ // CJS 的导出面是运行期的(`module.exports = require(…)` / UMD 包装,静态分析看不到键)。
484
+ loaded = createRequire(options.entry)(options.entry) as Record<string, unknown> | undefined;
376
485
  } catch {
377
486
  // 求值有副作用、或本来就是不能在 node 里加载的东西:宁可只有 default 导出,也不要让构建挂掉。
378
487
  return undefined;
379
488
  }
380
- const named = keys.filter((key) => key !== "default" && /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key));
381
- if (named.length === 0) return undefined;
382
- const file = join(options.outDir, `${options.exportName.replaceAll("/", "+")}.cjs-shim.mjs`);
383
- await mkdir(dirname(file), { recursive: true });
384
- await writeFile(
385
- file,
386
- [
387
- `import mod from ${JSON.stringify(options.entry)};`,
388
- // 用**计算属性**读:`mod.jsxDEV` 这种静态属性访问会被 rolldown 按它对 CJS 命名空间的静态理解
389
- // 摇成 `void 0`(`react/jsx-dev-runtime` 就那么被摇空了,页面报 `jsxDEV is not a function`)。
390
- "const __cjs = mod ?? {};",
391
- "export default __cjs;",
392
- ...named.map((key) => `export const ${key} = __cjs[${JSON.stringify(key)}];`),
393
- "",
394
- ].join("\n"),
395
- "utf8",
489
+ const keys = Object.keys(loaded ?? {});
490
+ const named = keys.filter(
491
+ (key) =>
492
+ key !== "default" &&
493
+ /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key) &&
494
+ !RESERVED_EXPORT_NAMES.has(key),
396
495
  );
496
+ if (named.length === 0) return undefined;
497
+
498
+ // **不落盘**:这是一份只喂给 rolldown 的入口,用虚拟模块(`\0` 前缀 + resolveId/load)即可。
499
+ // 落成文件反而要操心"放哪、相对路径怎么算、缓存目录里会不会残留"——入口用绝对路径,rolldown 在
500
+ // **构建期**把它读进来(内联进产物),产物里不会出现这个路径。
501
+ const id = `\0dsh-cjs-shim:${options.name}:${options.exportName}`;
502
+ const code = [
503
+ `import mod from ${JSON.stringify(options.from)};`,
504
+ // 用**计算属性**读:`mod.jsxDEV` 这种静态属性访问会被 rolldown 按它对 CJS 命名空间的静态理解
505
+ // 摇成 `void 0`(`react/jsx-dev-runtime` 就那么被摇空了,页面报 `jsxDEV is not a function`)。
506
+ "const __cjs = mod ?? {};",
507
+ "export default __cjs;",
508
+ ...named.map((key) => `export const ${key} = __cjs[${JSON.stringify(key)}];`),
509
+ "",
510
+ ].join("\n");
397
511
  options.log?.(
398
512
  `[bundle-cjs] ${options.name}/${options.exportName}: 补 ${String(named.length)} 个具名导出\n`,
399
513
  );
400
- return file;
514
+ return { id, code };
401
515
  }
402
516
 
403
- /** 根出口的产物名(`urlOf` 对非 client 行写的就是它)。 */
404
- const ROOT_EXPORT = "index";
405
-
406
- /** 具名导出的合法标识符:补 default 时按它挑键(非标识符的导出名用不了简写)。 */
407
- const EXPORT_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
408
-
409
517
  /**
410
- * 这个入口是否需要「CJS 包的 ESM 便利入口」的 default 补偿。判据**只看 package.json 的声明**:
518
+ * CSS 出口的产物:**就是 CSS 文本**(不包装成 JS、不注入 `<style>`)。
411
519
  *
412
- * - `type: "module"` 的包:Node 与我们都按 `exports`(或 `main` 本身就是 ESM)解析,两边一致,不补;
413
- * - 其余是 CJS 包:`module` 只是打包器约定(视为 ESM),`main` 才是 CJS。这条链选 `module`(更小、没有
414
- * webpack 垫片),而 Node 的 `import pkg from 'pkg'` 落到 `main`、default 是它的 `module.exports`——
415
- * 所以浏览器侧得补一个 default,否则消费方那句 default import 直接报
416
- * `does not provide an export named 'default'`(`rrule` 就是这一例)。
417
- * - 有 `exports` 的包两边都按条件解析,不涉及这条约定;入口不是 `module` 的(选了 `main`)由
418
- * {@link cjsShimOf} 处理。`main`/`module` 只描述根出口,子路径不在此列。
419
- */
420
- async function needsCjsInterop(entry: string, exportName: string): Promise<boolean> {
421
- if (exportName !== ROOT_EXPORT) return false;
422
- const manifestPath = await packageJsonNear(entry);
423
- const manifest = JSON.parse(await readFile(manifestPath, "utf8").catch(() => "{}")) as {
424
- main?: string;
425
- module?: string;
426
- type?: string;
427
- exports?: unknown;
428
- };
429
- if (manifest.type === "module" || manifest.exports !== undefined) return false;
430
- const manifestModule = manifest.module;
431
- if (manifestModule === undefined || manifest.main === undefined) return false;
432
- const modulePath = resolve(dirname(manifestPath), manifestModule);
433
- const moduleEntry = await realpath(modulePath).catch(() => modulePath);
434
- const entryPath = await realpath(entry).catch(() => resolve(entry));
435
- return moduleEntry === entryPath || modulePath === resolve(entry);
436
- }
437
-
438
- /**
439
- * 给「CJS 包的 ESM 便利入口」补 default:**看产物的真实导出面**(`chunk.exports`),不猜源码。
440
- * 已经有 default 的(`jsbi` 的 `export default JSBI`)原样保留——补成对象会把它顶掉,
441
- * `@js-temporal/polyfill` 那句 `import e from "jsbi"` 于是拿到命名空间、运行期 `e.BigInt is not a function`;
442
- * 没有的补成 `{ 具名导出… }`,与 CJS 的 `module.exports` 同形(`rrule` 的 `ALL_WEEKDAYS` / `rrulestr` 那批)。
443
- */
444
- function cjsInteropPlugin(exportName: string): Plugin {
445
- return {
446
- name: "dsh-cjs-interop",
447
- generateBundle(_options, bundle) {
448
- for (const chunk of Object.values(bundle)) {
449
- if (chunk.type !== "chunk" || chunk.isEntry !== true || chunk.name !== exportName) continue;
450
- if (chunk.exports.includes("default")) continue;
451
- const named = chunk.exports.filter((name) => EXPORT_IDENTIFIER.test(name));
452
- if (named.length === 0) continue;
453
- chunk.code += `\nexport default { ${named.join(", ")} };\n`;
454
- }
455
- },
456
- };
457
- }
458
-
459
- /**
460
- * CSS 入口的包装:**样式文件不能直接当入口**——vite 的库模式固定 `cssCodeSplit: false`,遇到
461
- * `rolldownOptions.input` 里有 `.css` 直接报错。包一层 side-effect import,让样式插件按它一贯的方式
462
- * 把它编成"注入 `<style>`"的模块。
520
+ * JS 里的 `import "x.css"` 是另一条路(`cssInlinePlugins` 在构建期内联成注入样式的模块),与本函数无关。
521
+ * 这里的 `url()` 指向包内资产:读到字节、按内容 hash 落到 `assets/`、改写成联邦地址——否则浏览器会按
522
+ * CSS 的相对路径去请求 `.pnpm` 里的文件,路由按清单服务就是 404。
463
523
  *
464
- * @returns 包装文件路径;入口不是 CSS 时 undefined。
524
+ * `lightningcss` 的 visitor 是同步回调,所以分两遍:第一遍只收集相对 `url()`,异步读资产/算 hash;
525
+ * 第二遍按映射改写(全程异步 IO)。
526
+ *
527
+ * @param options - 入口文件、出口名、缓存目录、包键、产物清单。
465
528
  */
466
- async function cssShimOf(options: {
467
- exportName: string;
529
+ async function bundleStyleOf(options: {
468
530
  entry: string;
531
+ exportName: string;
469
532
  outDir: string;
470
- }): Promise<string | undefined> {
471
- if (!options.entry.endsWith(".css")) return undefined;
472
- const file = join(options.outDir, `${options.exportName.replaceAll("/", "+")}.css-shim.mjs`);
533
+ key: string;
534
+ files: Record<string, string>;
535
+ }): Promise<void> {
536
+ const { transform } = await import("lightningcss");
537
+ const source = await readFile(options.entry);
538
+ const relativeUrl = (ref: string): boolean =>
539
+ ref !== "" &&
540
+ !ref.startsWith("#") &&
541
+ !ref.startsWith("/") &&
542
+ !/^[a-z][a-z0-9+.-]*:/iu.test(ref);
543
+
544
+ const refs = new Set<string>();
545
+ transform({
546
+ filename: options.entry,
547
+ code: source,
548
+ minify: false,
549
+ visitor: {
550
+ Url(node) {
551
+ if (relativeUrl(node.url)) refs.add(node.url);
552
+ },
553
+ },
554
+ });
555
+
556
+ const mapping = new Map<string, string>();
557
+ for (const ref of refs) {
558
+ const absolute = join(dirname(options.entry), ref);
559
+ const bytes = await readFile(absolute).catch(() => undefined);
560
+ if (bytes === undefined) continue;
561
+ const extension = extname(absolute);
562
+ const name = `assets/${basename(absolute, extension)}-${createHash("sha256")
563
+ .update(bytes)
564
+ .digest("hex")
565
+ .slice(0, 8)}${extension}`;
566
+ mapping.set(ref, `${CLIENT_MODULES_PREFIX}/${options.key}/${name}`);
567
+ await mkdir(dirname(join(options.outDir, name)), { recursive: true });
568
+ await writeFile(join(options.outDir, name), bytes);
569
+ options.files[name] = `${options.key}/${name}`;
570
+ }
571
+
572
+ const result = transform({
573
+ filename: options.entry,
574
+ code: source,
575
+ minify: false,
576
+ visitor: {
577
+ Url(node) {
578
+ const rewritten = mapping.get(node.url);
579
+ return rewritten === undefined ? undefined : { ...node, url: rewritten };
580
+ },
581
+ },
582
+ });
583
+ const file = join(options.outDir, options.exportName);
473
584
  await mkdir(dirname(file), { recursive: true });
474
- await writeFile(file, `import ${JSON.stringify(options.entry)};\n`, "utf8");
475
- return file;
585
+ await writeFile(file, result.code);
586
+ options.files[options.exportName] = `${options.key}/${options.exportName}`;
476
587
  }
477
588
 
478
589
  /**
@@ -582,7 +693,13 @@ async function bundlePackageOnce(
582
693
  const outDir = join(options.cacheRoot, key);
583
694
  const manifestPath = join(outDir, ".files.json");
584
695
  options.log?.(`[bundle-rev] ${options.name}: hash-start watch=${options.watch.join(",")}\n`);
585
- const rev = `${BUNDLER_REV}:${await fingerprint(options.watch)}`;
696
+ // **包根路径**也进指纹(与出口无关,同一包的各个出口共享):入口是包根下的相对位置,包跟着 app
697
+ // 换目录后路径变了,只算内容就会复用上一套产物——CJS shim 里的相对路径指向的入口已经不在了。
698
+ const rootRev = createHash("sha1")
699
+ .update(dirname(options.watch[0] ?? options.manifestOf ?? ""))
700
+ .digest("hex")
701
+ .slice(0, 8);
702
+ const rev = `${BUNDLER_REV}:${rootRev}:${await fingerprint(options.watch)}`;
586
703
  options.log?.(`[bundle-rev] ${options.name}: hash=${rev}\n`);
587
704
  const cached = JSON.parse(await readFile(manifestPath, "utf8").catch(() => "{}")) as {
588
705
  rev?: string;
@@ -612,7 +729,24 @@ async function bundlePackageOnce(
612
729
  return undefined;
613
730
  },
614
731
  },
615
- browserProcessPlugin(),
732
+ browserProcessPlugin(await clientBuildMeta(options.repoRoot)),
733
+ // 裸说明符的样式引用(`katex/dist/katex.min.css`)先解析成真实文件:否则外置插件会把它当
734
+ // 包边界、改写成联邦 URL,浏览器按 ESM import 一个 `text/css` 响应直接报 MIME 错误。
735
+ // 解析成文件后由 `cssInlinePlugins` 在**引用方**产物里内联(JS 里的 CSS import 行为不变)。
736
+ {
737
+ name: "dsh-css-specifiers",
738
+ resolveId(source: string, importer: string | undefined): string | undefined {
739
+ if (!source.endsWith(".css") || source.startsWith(".") || source.startsWith("/")) {
740
+ return undefined;
741
+ }
742
+ try {
743
+ return createRequire(importer ?? join(options.repoRoot, "package.json")).resolve(source);
744
+ } catch {
745
+ return undefined;
746
+ }
747
+ },
748
+ },
749
+
616
750
  cssInlinePlugins({
617
751
  name: key,
618
752
  assets: "threshold",
@@ -637,32 +771,54 @@ async function bundlePackageOnce(
637
771
  esmExternalRequirePlugin({
638
772
  // **外置名单 = 这条链认识的那些包**(包名 → 版本表的键),node 内置除外(它们走替身)。
639
773
  // 不是包的(相对路径、内置、虚拟模块)留在产物里内联。
774
+ // 入口就是本包:它不能被外置成自己的 URL(否则入口解析会拿到 external,构建直接失败)。
640
775
  external: [...resolvable.keys()]
641
- .filter((name) => !NODE_BUILTIN.test(name))
776
+ .filter((name) => !NODE_BUILTIN.test(name) && name !== options.name)
642
777
  .map((name) => barePackageRegExp(name)),
643
778
  }),
644
779
  ];
645
780
  const startedAt = Date.now();
646
781
  options.log?.(`[bundle-build] ${options.name}: rolldown start\n`);
647
- // 入口补偿:CJS 要带具名导出的包装;CSS 不能直接当入口(vite 的库模式 `cssCodeSplit: false`,
648
- // 明确拒绝 `rolldownOptions.input` 里出现 CSS 文件),包一层 side-effect import 让样式插件处理它。
782
+ // 入口:调用方已经按清单解析好(`exports` 条件 / `module` / `main`),这里按模块类型决定直通 / CJS 包装 /
783
+ // CSS 产物。CSS 用虚拟空模块占位(rolldown 的入口管线只吃 JS 文件名),产物在构建后由 `bundleStyleOf` 写。
649
784
  const input: Record<string, string> = {};
650
- // 「CJS 包的 ESM 便利入口」这一形态要补一个 default(判据见 `needsCjsInterop`),补的时机在产物生成之后。
651
- let interopExport: string | undefined;
785
+ const entryShims = new Map<string, string>();
786
+ const styleEntries = new Map<string, string>();
652
787
  for (const [exportName, entry] of Object.entries(options.input)) {
653
- if (await needsCjsInterop(entry, exportName)) interopExport = exportName;
654
- input[exportName] =
655
- (await cjsShimOf({
788
+ const kind = await moduleKindOf(entry);
789
+ if (kind === "cjs") {
790
+ const shim = await cjsShimOf({
656
791
  name: options.name,
657
792
  exportName,
658
793
  entry,
794
+ from: entry,
659
795
  ...(options.log === undefined ? {} : { log: options.log }),
660
- outDir,
661
- })) ??
662
- (await cssShimOf({ exportName, entry, outDir })) ??
663
- entry;
796
+ });
797
+ if (shim !== undefined) entryShims.set(shim.id, shim.code);
798
+ input[exportName] = shim?.id ?? entry;
799
+ continue;
800
+ }
801
+ if (kind === "style") {
802
+ styleEntries.set(exportName, entry);
803
+ const styleId = `\0dsh-style:${options.name}:${exportName}:entry`;
804
+ entryShims.set(styleId, "export {};\n");
805
+ input[exportName] = styleId;
806
+ continue;
807
+ }
808
+ input[exportName] = entry;
809
+ }
810
+ if (entryShims.size !== 0) {
811
+ plugins.push({
812
+ name: "dsh-entry-shims",
813
+ resolveId(source: string): string | undefined {
814
+ return entryShims.has(source) ? source : undefined;
815
+ },
816
+ load(source: string): string | undefined {
817
+ return entryShims.get(source);
818
+ },
819
+ });
664
820
  }
665
- if (interopExport !== undefined) plugins.push(cjsInteropPlugin(interopExport));
821
+
666
822
  // **直接跑 rolldown**(不经过 `vite build`):插件本来就是 rolldown 的接口,而 vite 在这条路上只提供了
667
823
  // lib 模式的入口/输出命名与 `worker.format`——那几项自己写更直接,且 `build.rolldownOptions` 里的
668
824
  // `transform` / `resolve` 也不会再被 vite 吞掉(对照表见债文档,那份债随这次改动一起销)。
@@ -695,10 +851,10 @@ async function bundlePackageOnce(
695
851
  // 它与 tsconfig 那项**语义相同**,两处都声明时 rolldown 会提示"tsconfig 被 transform 覆盖"——这条提示
696
852
  // 对我们没有决策价值(见下面的 `onLog`),不是需要处理的冲突。
697
853
  decorator: { legacy: true },
698
- // 浏览器没有 `process`:精确替换 `process.env`,裸 `process` 再给一个空壳——`immer` 这类包会在
699
- // 模块顶层读它,漏掉就是一个 `process is not defined` 把整份产物带下去。
854
+ // 浏览器没有 `process`:裸 `process` 给一个空壳——`immer` 这类包会在模块顶层读它,漏掉就是一个
855
+ // `process is not defined` 把整份产物带下去。`process.env` 的替换在 `browserProcessPlugin` 里做
856
+ // (版本元数据要先于"整个 process.env 变空壳"那一步换成真值,顺序写在一处而不是两处)。
700
857
  define: {
701
- "process.env": "{ env: {} }",
702
858
  process: "{ env: {} }",
703
859
  },
704
860
  },
@@ -737,8 +893,11 @@ async function bundlePackageOnce(
737
893
  // 目录会把另一个进程刚写的产物一起带走,表现为偶发 404。产物名本身带语义(出口名 / 资产 hash),直接
738
894
  // 覆盖即可;旧的字节留在盘上不碍事。
739
895
  await mkdir(outDir, { recursive: true });
896
+ const styleExports = new Set(styleEntries.keys());
740
897
  for (const item of items) {
741
898
  if (item.type !== "chunk") continue;
899
+ // CSS 出口的 JS 占位不落盘:它只是让 rolldown 完成入口解析。
900
+ if (item.isEntry && styleExports.has(item.name)) continue;
742
901
  // 出口名可以含 `/`(子路径出口:`helpers/decorate`),落盘要先把父目录建出来。
743
902
  await mkdir(dirname(join(outDir, item.fileName)), { recursive: true });
744
903
  await writeFile(join(outDir, item.fileName), item.code, "utf8");
@@ -755,6 +914,9 @@ async function bundlePackageOnce(
755
914
  await writeFile(join(outDir, asset.fileName), asset.source ?? "");
756
915
  files[asset.fileName] = `${key}/${asset.fileName}`;
757
916
  }
917
+ for (const [exportName, entry] of styleEntries) {
918
+ await bundleStyleOf({ entry, exportName, outDir, key, files });
919
+ }
758
920
  await writeFile(manifestPath, `${JSON.stringify({ rev, files }, null, 2)}\n`, "utf8");
759
921
  // 指纹进地址用的表({@link revs}):**每次构建后更新**——同一会话里后构建的产物引用它时就能带上
760
922
  // 当前指纹(浏览器于是可以长缓存那一份)。