feat(client): load package-local chunk dependencies (#9286)

* feat(client): load package-local chunk dependencies

Chunks of one dynamic Client package may now require each other
synchronously. A registration's deps names the chunks its factory
requires, and the module system registers them before the factory runs;
require.async takes a { deps } prefetch hint so a chunk group downloads
in one round. The dynamic preset writes both lists and moves the chunks
an entry requires into its client.js, shifting the entry source map.

Refs #9275

* fix(client): accept entry-carried chunks in the publication closure check

The dynamic Client build moves the chunks an entry requires into the
entry file and deletes their own files, so a require of such a chunk
names no published file. publint-all now accepts a ./client.<name>.js
request when a script in the same directory registers the package entry
and that chunk, using the shared chunk file-name rule.

Refs #9275

* fix(client): restart entry chunk arrival and keep entry-carried dynamic imports

- arrive() restarts from the entry script when the owner is invalidated
  while the entry's registration deps download, as importChunk already
  does for lazy chunks.
- A dynamic import of a chunk the entry file carries keeps Rolldown's
  synchronous require: the chunk has no file left to download. A chunk
  that imports the package entry dynamically now fails the build like a
  static import.
- The WebWorker packer reuses CLIENT_CHUNK_FILE from client-modules
  instead of its own pattern; the rule is bundled into the packer build.

Refs #9275

* refactor(client): order chunk arrival methods after importChunk

Place arriveChunk directly after importChunk so the download code it took
over from importChunk stays aligned with master, followed by arriveChunks
and requireChunk. No logic or comment changes.

Refs #9275

* fix(client): limit the entry-carried chunk exemption to factory requires

publint-all accepted any relative request for a chunk that the entry file
registers, including an ESM import that Node resolves itself. The
exemption now covers only a synchronous require inside the factory of a
__ModuleLoader__.load registration; every other relative request still
needs its published file.

Refs #9275

* fix(client): let a prefetch hint only start chunk downloads

With a hint, the hinted chunks shared the requested chunk's visited set,
so a failed dependency reached the caller without the registration chain.
Each hinted chunk now arrives with its own visited set and an ignored
failure; the requested chunk waits only for its registration deps and
wraps their failures, so a hinted chunk that no registration requires
cannot fail the request.

Refs #9275

* fix(client): wait for prefetch hint arrivals before a chunk request ends

A chunk request discarded its hinted arrivals, so after an owner
invalidation it could retry and register the new generation while a
hinted download of the dropped generation was still pending; that
download then deleted the new records. The request now waits for every
hinted arrival it started, on success, failure, and before a retry,
while still ignoring their failures.

Refs #9275
This commit is contained in:
imccyu authored and GitHub committed 2026-11-26 15:21:49 +08:00
1 parent 7b7eda62af
commit 28dfa06cca
37 files changed
+1310 -102

No files matched your search

@@ -15,8 +15,8 @@
en: 6af228b03e5e533f
zh: 276a522af6be5d7a
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/one-module-system-one-plugin-governor:
en: 5f5daec51b20db77
zh: e4d6f78fc1b4b835
en: 51df5a30c9337f22
zh: f4533cd731c86890
/agent-note-client-plugin-loading-lazy-factories-cordis-lifecycle-and-hot-reload/decision/combo-external-script-arrival-and-source-maps:
en: 04b9f0138b5d2288
zh: 2a749db57f6e7a10
@@ -34,7 +34,7 @@ The web kernel remains framework-free and imports no dynamic package value. Modu
The browser mirrors the host's division of labor. `dsh-client-modules` (`ClientModuleSystem`) takes the module-system seat that Node's internal ESM loader holds host-side; the same vendored `@cordisjs/plugin-loader` keeps the governance seat on both sides. The line between them in one sentence: **the module system owns module identity and bytes — how code arrives, registers, and becomes an exports; the Loader owns plugin lifecycle — when a plugin mounts, what it waits for, and how it is torn down.**
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. JavaScript module body side effects live inside the factory closure and run at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. The supported output is self-contained: an entry or chunk cannot synchronously require another relative `client*.js` output. The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owner identity, optional opaque metadata producers, and observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
`ClientModuleSystem` is a lazy CJS table. Executing a bundle only **registers** its factory — an entry calls `window.__ModuleLoader__.load({ id, factory })`, while a chunk also supplies its generated filename — and nothing else happens. JavaScript module body side effects live inside the factory closure and run at materialization: the first `require`/import of that id, memoized after that. Import and prefetch recursively register declared dynamic requests before their consumer; a factory then materializes any registered-but-unmaterialized request synchronously. The callable `require` resolves synchronous module-table requests; its `require.async` operation returns a Promise that loads, registers, and materializes one package-local chunk. The shared tsdown preset compiles source `import()` expressions for package-local chunks to that distinct operation. A factory may also synchronously require a chunk of its own package that is already registered; the chunk registration and request rules are in [package-local chunk dependencies](2026-11-26-package-local-chunk-dependencies.md). The table resolves through a fixed branch order: seed word → memoized record → graph-row classic-script registration → registered-factory materialization → loud throw. The modules factory is the bootstrap exception: the HTML facade materializes it first, and construction places those same exports directly in the memoized table. That final throw is the runtime mirror of the build-time purity gate. The system also keeps per-module bookkeeping — owner identity, optional opaque metadata producers, and observed require edges — and exposes the two verbs HMR needs: `prefetch(id)` (register the requested dynamic factories and the row's own factory; concurrent arrivals share one task) and `invalidate(id)` (advance the owner generation and drop a non-bootstrap package's entry and chunk factories and records so the next arrival reloads them). A chunk request captured under an older generation cannot populate the new generation.
The vendored Loader consumes the module system through its `internal` contract — the only call site is `tree.import` — and owns everything entry-shaped: entry creation, fiber activation through cordis service waiting (PENDING until injected services exist, cascading when a service is provided), update/refresh, teardown. The governance code is byte-identical to the host side, per vendor policy. Browserization is compile-time mapping in the shell's vite config: a `node:module` stub alias plus `process.*` defines make `ModuleLoader.fromInternal()` return undefined — exactly the empty slot the shell fills. The module system mounts as `ctx.modules`.
@@ -34,7 +34,7 @@ Web 内核保持不依赖框架,也不 import 任何动态包实体。Modules
浏览器复刻 host 侧的分工。`dsh-client-modules`(`ClientModuleSystem`)坐上 host 侧由 Node 内部 ESM loader 占据的模块系统席位;同一份 vendored `@cordisjs/plugin-loader` 在两侧都坐治理席。二者的分界线一句话说尽:**模块系统拥有模块身份与字节——代码怎么到达、怎么登记、怎么变成导出内容;Loader 拥有插件生命周期——插件何时挂载、等待什么、如何拆除。**
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。JavaScript 模块体副作用位于 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。受支持的产物必须自包含:入口或 chunk 不能同步 require 另一个相对 `client*.js` 产物。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——owner 身份、可选且不求值的元信息函数、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
`ClientModuleSystem` 是一张 lazy CJS 表。执行 bundle 只**登记**其 factory——入口调用 `window.__ModuleLoader__.load({ id, factory })`,chunk 还会提供其生成文件名——此外什么都不发生。JavaScript 模块体副作用位于 factory 闭包里,在物化时运行:物化即该 id 的首次 `require`/import,此后记忆化。Import 和 prefetch 会先递归登记已声明的动态请求,再登记消费者;随后 factory 会同步物化任何已登记但尚未物化的请求。可调用的 `require` 解析同步模块表请求;其 `require.async` 操作返回 Promise,负责加载、登记并物化一个包内 chunk。共享 tsdown 预设把源码中针对包内 chunk 的 `import()` 表达式编译到这个独立操作。factory 也可以同步 require 本包已登记的 chunk;chunk 登记与请求的规则见[包内分片之间的依赖](2026-11-26-package-local-chunk-dependencies.zh.md)。模块表按固定分支顺序解析:seed word → 记忆化记录 → graph row classic-script 登记 → 已登记 factory 物化 → 大声抛错。Modules factory 是自举例外:HTML facade 先物化它,构造过程再把同一 exports 直接写入记忆化表。最后这一抛是构建期纯度门禁在运行时的镜像。系统还保管逐模块簿记——owner 身份、可选且不求值的元信息函数、观测到的 require 边——并暴露 HMR(热模块替换)需要的两个动词:`prefetch(id)`(登记所请求的动态 factory 和本 row 自身的 factory;并发到达共享一个任务)与 `invalidate(id)`(推进 owner 代次并丢弃非 bootstrap 包的入口和 chunk factory 及记录,让下次到达重新加载它们)。在旧代次捕获的 chunk 请求不能填充新代次。
vendored Loader 经其 `internal` 约定消费模块系统——唯一调用点是 `tree.import`——并拥有一切 entry 形状的事务:entry 创建、fiber 经 cordis 服务等待的激活(注入的服务未就位即保持 PENDING,服务 provide 时级联激活)、update/refresh、拆除。治理代码按 vendor 政策与 host 侧逐字节相同。浏览器化是壳 vite 配置里的编译期映射:一个 `node:module` stub 别名加若干 `process.*` define,使 `ModuleLoader.fromInternal()` 返回 undefined——这正是留给壳来填的空槽。模块系统挂载为 `ctx.modules`。
@@ -21,8 +21,8 @@
en: 608b24ca97ab5bca
zh: 94bb28377c856b2e
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/separate-archives-for-lazily-loaded-chunks:
en: 428699f74f19e998
zh: 2e8fcdbc9616f70b
en: bb3f7f2737dddec6
zh: c514e53f6a4837ff
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/decision/watching-and-client-plugin-delivery:
en: 814c344e891f7f91
zh: a024d5e30607968b
@@ -52,7 +52,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
### Separate archives for lazily loaded chunks
- **Classification**: the client build preset emits package-local chunk requests only as `require.async("./client.<name>.js")`, and `verify-client-packages` forbids synchronous chunk requires. The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack.
- **Classification**: the client build preset emits asynchronous package-local chunk requests only as `require.async("./client.<name>.js")`, optionally with a `{ deps: [...] }` prefetch hint that names every other chunk the request needs ([chunk dependencies](2026-11-26-package-local-chunk-dependencies.md)). The packer's `lazyChunksOf` scans every page asset in the swept image (each package's `lib/client.js` and `lib/client.*.js`) for these literals, hint entries included, so a chunk that another chunk requests is found without following requests from the `./client` entry. A target that a package's `./client` export names under any condition (such as `client.browser.js`) loads eagerly and stays in the base image; every other target leaves it. A request for a chunk the package does not publish fails the pack.
- **Archives**: each chunk gets one deterministic tar.gz named `lazy/<sha256>.tar.gz` after the SHA-256 of the compressed archive. The base manifest's `lazy` list records each archive as `{ archive, files: [{ path, size }] }`, with no file mode. There is no size threshold.
- **Registration**: the Worker registers each listed file with `MemoryVfs.deferArchive`, which creates its parent directories and gives it the VFS default file mode; an image that lists lazy archives must be fetched from a URL, against which the archive names resolve. `exists`, `stat`, and `readdir` answer synchronously from the registration.
- **Fetch**: the asynchronous faces of the Worker's `node:fs` and `node:fs/promises` that read a registered file wait for its archive: `fs.promises.readFile`, `fs.promises.open` (so every FileHandle opens after arrival), `fs.promises.cp`, and `fs.createReadStream`. The first of them fetches the archive, inflates it, checks that it carries exactly the registered paths at the registered sizes, and materializes the files; concurrent readers share one fetch. The digest in the archive name is not verified. A failed fetch fails only the reads waiting on it; the files stay registered and the next asynchronous read fetches again.
@@ -52,7 +52,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
### 懒加载 chunk 独立归档
- **分类**:client 构建预设只以 `require.async("./client.<name>.js")` 的形式产出包内 chunk 请求,`verify-client-packages` 禁止同步 require chunk。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。
- **分类**:client 构建预设只以 `require.async("./client.<name>.js")` 的形式产出异步的包内 chunk 请求,可选带上 `{ deps: [...] }` 预取提示,列出该请求需要的其他所有 chunk([分片依赖](2026-11-26-package-local-chunk-dependencies.zh.md))。packer 的 `lazyChunksOf` 扫描清扫后镜像里的每个页面资源(各包的 `lib/client.js` 和 `lib/client.*.js`)中的这些字面量,包括提示中的项,因此 chunk 引用的 chunk 不必从 `./client` 入口沿请求追踪也能找到。在任一条件下被某个包的 `./client` 导出指向的目标(如 `client.browser.js`)会被立即加载,留在基础镜像;其余目标移出基础镜像。请求包未发布的 chunk 会让打包失败。
- **归档**:每个 chunk 一个确定性 tar.gz,按压缩后归档的 SHA-256 命名为 `lazy/<sha256>.tar.gz`。基础 manifest 的 `lazy` 列表把每个 archive 记录为 `{ archive, files: [{ path, size }] }`,不记录文件 mode。不设大小阈值。
- **登记**:Worker 用 `MemoryVfs.deferArchive` 登记列出的每个文件,同时创建其父目录,并赋予 VFS 默认文件 mode;列出懒加载 archive 的镜像必须从 URL 拉取,archive 名相对这个 URL 解析。`exists`、`stat`、`readdir` 依据登记同步作答。
- **拉取**:Worker 的 `node:fs` 和 `node:fs/promises` 中读取已登记文件的异步接口会等待其 archive:`fs.promises.readFile`、`fs.promises.open`(因此每个 FileHandle 都在到达后才打开)、`fs.promises.cp` 和 `fs.createReadStream`。其中第一个调用拉取 archive、解压,校验其中恰好是登记的路径和登记的大小,再物化文件;并发读取方共用一次拉取。archive 名里的摘要不做校验。拉取失败只让等待它的读取失败;文件保持登记,下一次异步读取再次拉取。
@@ -9,8 +9,8 @@
en: 590dbd303b44e903
zh: b536f88e6fcdbce2
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/decision:
en: 93d58b7585af3f6c
zh: a91c4717778dd5eb
en: 87e7d3b714915271
zh: b527931e3eac73b9
/agent-note-client-metadata-and-renderer-owned-stylesheet-installation/alternatives-considered:
en: 70adfc415b3a5328
zh: 16599d6feb06cae8
@@ -10,7 +10,7 @@ A script's execution environment need not be its presentation document. CSS inje
## Decision
Client artifacts contain `id` and `factory`, with optional `meta` and a `chunk` name for dynamic package-local chunks. `meta()` returns resource descriptions; `stylesheets` is an optional path-keyed record whose values expose independently evaluated `text(context)` functions. Resource paths identify stylesheets, not components. There is no stylesheet dependency field.
Client artifacts contain `id` and `factory`, with optional `meta`, a `chunk` name for dynamic package-local chunks, and [`deps`](2026-11-26-package-local-chunk-dependencies.md) naming the chunks a factory requires synchronously. `meta()` returns resource descriptions; `stylesheets` is an optional path-keyed record whose values expose independently evaluated `text(context)` functions. Resource paths identify stylesheets, not components. There is no stylesheet dependency field.
Modules owns JavaScript exports, module identity, owner ids, and observed dependency edges. It retains metadata functions without evaluating them and publishes generic module-record changes. Renderer owns metadata/text caches, dependency-ordered stylesheet collection, path deduplication, and main-document nodes. It explicitly installs existing resources before React mounting, updates them on module changes, and releases styles after the root unmounts. Component lifetimes do not own styles.
@@ -10,7 +10,7 @@ Status: implemented
## Decision
Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。
Client 产物包含 `id` 和 `factory`,可选带有 `meta`,动态包内 chunk 另带 `chunk` 名称,factory 同步 require 的 chunk 列在 [`deps`](2026-11-26-package-local-chunk-dependencies.zh.md) 中。`meta()` 返回资源描述;可选的 `stylesheets` 是以路径为键的字典,每个值提供独立求值的 `text(context)` 函数。资源路径标识样式表,而不是组件。当前没有样式表依赖字段。
Modules 拥有 JavaScript 导出、模块身份、owner id 和观察到的依赖边。它保存元信息函数而不求值,发布通用的模块记录变化。Renderer 拥有元信息/文本缓存、依赖有序的样式集合、路径去重与主文档节点。它在 React 挂载前显式安装已有资源,随模块变化更新,并在根卸载后释放样式。组件生命周期不拥有样式。
@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-11-26-package-local-chunk-dependencies.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md
/agent-note-package-local-chunk-dependencies:
en: be8e63e6d765fd9b
zh: 2301e5754a32f288
/agent-note-package-local-chunk-dependencies/problem:
en: 3a5fb76c845f5938
zh: 8da1557121ec5503
/agent-note-package-local-chunk-dependencies/decision:
en: dd2c654e49bbc659
zh: 2a461be554571a86
/agent-note-package-local-chunk-dependencies/alternatives-considered:
en: fa1b734a16a83dad
zh: c0f51477e123a8f9
/agent-note-package-local-chunk-dependencies/consequences:
en: 90a70c4127a31e0a
zh: 7874aabdd89159b2
/agent-note-package-local-chunk-dependencies/testing:
en: 5efdb48c7772afa9
zh: f81468f7d27cac8d
@@ -0,0 +1,49 @@
# Agent Note: Package-local chunk dependencies
Status: implemented
English | [中文](2026-11-26-package-local-chunk-dependencies.zh.md)
## Problem
The dynamic Client preset builds a package's browser half with Rolldown, which splits every source `import()` into a `client.<name>.js` chunk. Rolldown also moves code that several chunks share, including its CommonJS helper `\0rolldown/runtime.js`, into common chunks, and every chunk that uses them requires those chunks synchronously. The [loading model](2026-07-23-client-plugin-loading-model.md) required self-contained output: a factory's `require` answered only module-table requests, and `require.async` loaded exactly one chunk. A package whose lazy modules import each other, such as syntax grammars that embed other grammars, could not split by `import()`, and an entry that shared one module with a lazy chunk failed at runtime on its synchronous `require("./client.<name>.js")`.
## Decision
Chunks of one package may require each other synchronously. Two `deps` lists carry the chunk graph to the [module system](../../../../packages/client/modules/README.md), each with its own obligation:
- **Registration `deps`** in `__ModuleLoader__.load({ id, chunk, deps, factory })` is a precondition: the chunks of the same package (`./client.<name>.js`) that the factory requires synchronously. The module system downloads and registers each of them, and transitively their own `deps`, before the factory runs. The [preset](../../../../packages/client/tsdown.client.ts) writes the chunk's direct chunk imports from Rolldown's `RenderedChunk.imports` and omits the field when there are none.
- **`require.async(spec, { deps })`** is a prefetch hint: further chunks of the same package to download in parallel with the requested chunk. The preset writes the requested chunk's transitive synchronous closure, computed from the `meta.chunks` graph of `renderChunk`, minus the chunks the entry file carries, and keeps the one-argument call when nothing remains. A missing hint costs round trips only, because registration `deps` still load the group one level per round. A request for another package ignores the option.
The preset moves every chunk the entry requires synchronously, transitively and dependencies first, into the entry file ahead of the entry's own registration, and deletes their files and maps. One script may already register several factories, as combo batches do, so the entry needs no request beyond its own script. The move runs in `generateBundle` after input isolation has checked each chunk, and the entry map gains one empty line per inserted line, in both the emitted map asset and the in-memory chunk map. A chunk that imports the package entry, statically or dynamically, fails the build: the module system keys the entry by package id, so no relative specifier reaches it. A dynamic import of a chunk the entry file carries keeps Rolldown's synchronous `require` inside a resolved promise, because the entry file registers that chunk before any code of the package runs and no file is left to download.
In the module system, a synchronous `require("./client.<name>.js")` materializes a registered chunk of the same package and throws for an unregistered one. Arriving a graph row registers its entry script, then the entry's registration `deps`; a batch script can register the entry without the row's own download, so the dependency step also runs for an entry that was already registered, and an owner invalidation while those chunks download restarts the arrival from the entry script. A package-local `require.async` downloads the hinted chunks in parallel with the requested chunk and waits for those downloads to end before the chunk runs or the request retries, so a hinted download of a dropped generation cannot discard what the retry registers; the chunk itself needs only its registration `deps`, transitively and in parallel, and a hinted chunk that fails to download fails the request only through a registration that requires it. A failed dependency rejects with the chain of registrations that required it, with or without a hint, once every sibling arrival has ended; an owner invalidation during arrival restarts the request under the new revision; a cycle downloads once and fails when the factories run, as module-table cycles do. A `deps` entry that names no package-local chunk is rejected at registration and at the request.
[`src/chunks.ts`](../../../../packages/client/modules/src/chunks.ts) owns the chunk file-name pattern that the preset, the Host chunk route, the module system, and the WebWorker packer read. The publication closure check in [`publint-all`](../../../../scripts/publint-all.ts) accepts a `require("./client.<name>.js")` inside a registered module factory whose file is not published when a script in the same directory registers the package entry and that chunk, because the moved chunks no longer have files; an ESM `import` or any other relative request still needs its published file. The WebWorker packer treats hinted chunks as requested ones, so they leave the base image as well. Values of another package remain module-table requests composed by the Host graph; `deps` never names another package.
## Alternatives considered
**Self-contained chunks through Rolldown's chunking options.** Forcing shared modules into each importing chunk gives every chunk a private copy of each module it reaches. Grammar modules form a graph, so the copies multiply, and modules with state would exist once per chunk.
**Rolldown groups that keep the entry's shared modules in the entry chunk.** Lazy chunks would then require `./client.js`, which the module system does not address, and the group rule would duplicate Rolldown's reachability analysis. Concatenating the rendered chunks keeps Rolldown's chunk graph and every registration unchanged and costs one source-map offset.
**Separate files for the entry's chunks, loaded through registration `deps`.** Every package with shared code would add at least one request round before its entry can run during boot.
**One `deps` list with both meanings.** A hint that the loader trusted would turn a builder's closure mistake into a missing chunk at runtime, and a precondition that the loader treated as a hint would run a factory whose dependencies never arrived when no hint accompanies the request, as when one chunk requests another.
**Waiting for dependencies inside `require`.** A factory's `require` is synchronous; factory-form CommonJS cannot wait, so every chunk a factory requires must be registered before it runs.
## Consequences
- A hinted lazy group downloads in one round; registration `deps` alone take one round per dependency level.
- The entry file grows by the moved chunks. Boot only registers them; their factories still run at the first `require`.
- The moved chunks have no source mapping in the entry map, so browser tools show their generated code.
- During HMR replacement, old code that requests a chunk after its package was invalidated loads the new revision's chunk. If that chunk requires a chunk the new entry file carries, the request fails until the new entry has registered; the loader does not handle chunks specially for HMR.
- A package built outside this repository must write registration `deps` for every synchronous chunk require; the hint is optional.
## Testing
- [chunk-deps.client.spec.ts](../../../../packages/client/modules/tests/chunk-deps.client.spec.ts) covers level-by-level arrival, one-round hinted downloads, entry dependencies registered by the same script or completed after a preloaded registration, an entry arrival restarted by an invalidation during its chunk downloads, shared and cyclic dependencies, the failure chain with and without a hint, a failed hinted chunk that no registration requires, restart after invalidation, a retry that waits for the hinted downloads of the dropped generation and for every sibling of a failed dependency, re-execution of an entry script after invalidation, rejected `deps` entries, and synchronous requests of unregistered chunks.
- [client-bundle-chunk-deps.client.spec.ts](../../../../scripts/client-bundle-chunk-deps.client.spec.ts) builds a fixture whose entry and lazy chunks share modules and CommonJS packages, asserts the moved registrations, deleted files, registration `deps`, hints, the synchronous form of a dynamic import of an entry-carried chunk, and the shifted map, rejects a chunk that imports the entry statically or dynamically, and runs the written artifacts through the real module system.
- [lazy-chunks.spec.ts](../../../../packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts) moves hinted chunks out of the WebWorker base image.
- [publint-all.spec.ts](../../../../scripts/publint-all.spec.ts) accepts a factory's chunk request that the entry file registers and rejects one that only a chunk file registers, that nothing provides, or that an ESM import or code outside a factory makes.
@@ -0,0 +1,49 @@
# Agent Note: 包内分片之间的依赖
Status: implemented
[English](2026-11-26-package-local-chunk-dependencies.md) | 中文
## Problem
动态 Client 预设用 Rolldown 构建包的浏览器半侧,每个源码 `import()` 都会拆成一个 `client.<name>.js` 分片。Rolldown 还会把多个分片共用的代码,包括它的 CommonJS 辅助模块 `\0rolldown/runtime.js`,移进公共分片,用到这些代码的分片会同步 require 这些公共分片。[加载模型](2026-07-23-client-plugin-loading-model.zh.md)原先要求产物自包含:factory 的 `require` 只解析模块表请求,`require.async` 只加载一个分片。懒加载模块互相导入的包,例如嵌入其他语法的语法高亮模块,因此无法按 `import()` 拆分;入口只要和某个懒加载分片共用一个模块,运行时就会在同步的 `require("./client.<name>.js")` 上失败。
## Decision
同一个包的分片之间可以同步 require。分片依赖图通过两个 `deps` 列表交给[模块系统](../../../../packages/client/modules/README.zh.md),两者承担的义务不同:
- **登记信息里的 `deps`**(`__ModuleLoader__.load({ id, chunk, deps, factory })`)是前提条件:列出 factory 同步 require 的同包分片(`./client.<name>.js`)。模块系统先下载并登记其中每个分片,以及它们各自 `deps` 的传递闭包,再运行这个 factory。[预设](../../../../packages/client/tsdown.client.ts)从 Rolldown 的 `RenderedChunk.imports` 写入该分片直接导入的分片,没有时省略该字段。
- **`require.async(spec, { deps })`** 是预取提示:列出与所请求分片并行下载的其他同包分片。预设按 `renderChunk` 的 `meta.chunks` 分片图算出所请求分片的同步传递闭包,去掉入口文件已携带的分片后写入;结果为空时保留单参数调用。缺少提示只会多花请求轮次,因为登记信息里的 `deps` 仍会逐层加载整组分片。请求其他包时忽略该选项。
预设把入口同步 require 的所有分片(传递闭包,依赖在前)移进入口文件,放在入口自己的登记之前,并删除它们各自的文件和 map。一个脚本本来就可以登记多个 factory,combo 批次就是这样,因此入口除了自己的脚本不需要别的请求。移动发生在 `generateBundle` 阶段、输入隔离检查完每个分片之后;入口 map 按插入的行数补上同样数量的空行,输出的 map 资源和内存中的分片 map 都会更新。静态或动态导入包入口的分片会让构建失败:模块系统以包 id 作为入口的键,没有相对路径能指向它。对入口文件携带的分片的动态导入保留 Rolldown 生成的、包在已完成 Promise 里的同步 `require`,因为入口文件在该包任何代码运行之前就登记了这个分片,也没有文件可下载。
在模块系统里,同步的 `require("./client.<name>.js")` 会物化已登记的同包分片,对未登记的分片抛错。图行到达时先登记入口脚本,再处理入口登记信息里的 `deps`;批次脚本可能在这一行自己的下载之前就登记了入口,所以已经登记过的入口也会执行这一步;这些分片下载期间所属包被失效时,到达过程从入口脚本重新开始。包内 `require.async` 会把提示中的分片与分片本身并行下载,并等这些下载结束后才运行分片或重试请求,因此旧代次的提示下载不会删掉重试登记的分片;分片本身只需要自己登记信息里的 `deps`(递归、并行),提示中的分片下载失败,只有被某个登记信息依赖时才会让请求失败。依赖失败时,要等同一批的其余到达全部结束才拒绝,无论是否带提示,拒绝信息都会带出要求该分片的登记链;到达过程中所属包被失效时,请求在新 revision 下重新开始;有环时每个分片只下载一次,在 factory 运行时失败,与模块表的环相同。不指向包内分片的 `deps` 项在登记和请求时都会被拒绝。
[`src/chunks.ts`](../../../../packages/client/modules/src/chunks.ts) 持有分片文件名规则,预设、Host 分片路由、模块系统和 WebWorker 打包器都从这里读取。[`publint-all`](../../../../scripts/publint-all.ts) 的发布闭包检查遇到已登记模块 factory 里文件未发布的 `require("./client.<name>.js")` 时,若同一目录下有脚本登记了包入口和该分片,就视为满足,因为被移入的分片已经没有单独文件;ESM `import` 等其他相对请求仍要求对应文件已发布。WebWorker 打包器把提示中的分片当作被请求的分片,它们同样移出基础镜像。其他包的值仍是由 Host 图组合的模块表请求;`deps` 从不指向其他包。
## Alternatives considered
**用 Rolldown 的拆分选项保持分片自包含。** 把共用模块强行放进每个导入它的分片,会让每个分片都带上它能到达的每个模块的私有副本。语法模块之间是图结构,副本会成倍增加,有状态的模块也会在每个分片里各有一份。
**用 Rolldown 分组把入口共用的模块留在入口分片里。** 懒加载分片随后会 require `./client.js`,而模块系统无法定位它;分组规则还要重复 Rolldown 的可达性分析。把已渲染的分片拼接起来,Rolldown 的分片图和每个登记都保持不变,只需一次 source map 偏移。
**入口的分片保留为单独文件,靠登记信息里的 `deps` 加载。** 每个有共用代码的包都会在启动时、入口运行之前至少多一轮请求。
**一个 `deps` 列表兼具两种含义。** 加载器若信任提示,构建端算错闭包就会变成运行时缺分片;加载器若把前提条件当作提示,请求不带提示时(例如一个分片请求另一个分片)factory 就会在依赖未到达时运行。
**在 `require` 内部等待依赖。** factory 的 `require` 是同步的;factory 形式的 CommonJS 无法等待,所以 factory 会 require 的每个分片都必须在它运行前登记。
## Consequences
- 带提示的懒加载分组一轮下载完;只靠登记信息里的 `deps` 时,每层依赖一轮。
- 入口文件会增加被移入的分片。启动时只登记它们;它们的 factory 仍在首次 `require` 时运行。
- 被移入的分片在入口 map 中没有源码映射,浏览器工具只显示其生成代码。
- HMR 替换期间,包失效后旧代码请求分片时会加载新 revision 的分片。如果该分片 require 的分片由新的入口文件携带,在新入口登记之前该请求会失败;加载器不针对 HMR 特别处理分片。
- 在本仓库之外构建的包必须为每个同步分片 require 写出登记信息里的 `deps`;提示是可选的。
## Testing
- [chunk-deps.client.spec.ts](../../../../packages/client/modules/tests/chunk-deps.client.spec.ts) 覆盖逐层到达、带提示时一轮下载、由同一脚本登记或在预加载登记后补齐的入口依赖、分片下载期间失效导致的入口到达重启、共用与成环的依赖、带或不带提示时的失败链、提示中无登记依赖的分片下载失败、失效后重新开始、重试前等待旧代次的提示下载及失败依赖的同批到达全部结束、失效后重新执行入口脚本、被拒绝的 `deps` 项,以及同步请求未登记分片。
- [client-bundle-chunk-deps.client.spec.ts](../../../../scripts/client-bundle-chunk-deps.client.spec.ts) 构建一个入口与懒加载分片共用模块和 CommonJS 包的夹具,断言被移入的登记、被删除的文件、登记信息里的 `deps`、提示、对入口携带分片的动态导入保持同步形式以及偏移后的 map,拒绝静态或动态导入入口的分片,并用真实模块系统运行写出的产物。
- [lazy-chunks.spec.ts](../../../../packages/experimental/webworker-packer/tests/lazy-chunks.spec.ts) 把带提示的分片移出 WebWorker 基础镜像。
- [publint-all.spec.ts](../../../../scripts/publint-all.spec.ts) 接受 factory 中由入口文件登记过的分片请求,拒绝只有分片文件登记、无处提供、或来自 ESM import 及 factory 之外代码的请求。
+1 -1
View File
@@ -85,7 +85,7 @@ A dynamic browser half either carries a module privately or requests the shared
3. **Silence means a private copy.** Third-party implementation libraries outside the baseline may be bundled independently. A value reached only through `import type` is erased and creates no request.
4. **A request has two possible suppliers.** A dynamic package supplies its own row; `PLATFORM_MODULES` supplies an exact static-table key. There is no `dsh.client.provide` alias protocol.
5. **Validate both sides.** The dynamic build preset externalizes the baseline and rejects undeclared workspace value imports; [`verify-client-packages`](../../scripts/verify-client-packages.ts) rejects malformed or redundant requests, missing suppliers, and synchronous request cycles.
6. **Package-local dynamic chunks are self-contained.** Source uses `import()` and the shared preset emits `require.async("./client.<name>.js")`; an entry or chunk must not retain a synchronous relative `require("./client*.js")`. Keep every static relative dependency inside its owning output chunk rather than relying on a sibling-chunk graph the runtime does not support.
6. **Package-local chunks may require each other synchronously.** Source uses `import()`. The shared preset writes each chunk's synchronous chunk requires as its registration `deps`, which Modules registers before the factory runs, emits `require.async("./client.<name>.js", { deps })` with a prefetch hint for the rest of the target's chunk group, and moves the chunks the entry requires into the entry file. A chunk must not import the package entry, and `deps` never crosses packages ([decision](../../.agents/notes/implemented/architecture/2026-11-26-package-local-chunk-dependencies.md)).
### The module graph sits below cordis DI
+8 -8
View File
@@ -24,8 +24,8 @@
en: bc77e9c5d74134b0
zh: cd99a246d43472ea
/deepseek-ai-dsh-client-modules/use-this-package/what-the-browser-loads:
en: fabb527083efdf4b
zh: a110a9471e494f5e
en: 3402ce993a0f4a1d
zh: 683a4f16b64210b6
/deepseek-ai-dsh-client-modules/use-this-package/live-plugin-composition:
en: 09ed5277078f44ee
zh: 3643210476149b2a
@@ -48,8 +48,8 @@
en: 49dcadc166c2d06e
zh: bbf67c6dc47f4ead
/deepseek-ai-dsh-client-modules/understand-the-implementation/lazy-cjs-model:
en: c87fb35ad5800144
zh: b5dd02f4d5e9821e
en: 7685cf8d45d4e223
zh: 58cebfaaa6125151
/deepseek-ai-dsh-client-modules/understand-the-implementation/main-execution-environment:
en: 3b2d663c0304e78a
zh: 32aa738248e6080b
@@ -66,8 +66,8 @@
en: a0d8dbb15e079ec0
zh: 7d215cb85fa8b2c7
/deepseek-ai-dsh-client-modules/understand-the-implementation/source-map:
en: 232120cddca73330
zh: bd100d2e3e7094bc
en: cd4eb82cb19f94b4
zh: 1dac9abb0dbb334e
/deepseek-ai-dsh-client-modules/further-exploration:
en: 7e5b283efe4f1d16
zh: 79472b64a0d759fe
@@ -78,8 +78,8 @@
en: ca75c51c89c2c9b0
zh: de54f3467ef3b9be
/deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work:
en: 1b71a96e072e5d08
zh: 4f08ae822bb91192
en: 8ba377999c1cd27e
zh: 6e04e6dcb6704539
/deepseek-ai-dsh-client-modules/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
+4 -2
View File
@@ -40,7 +40,7 @@ The same `/plugins` route serves the images a client package publishes through i
### What the browser loads
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client.<name>.js")`; its versioned sibling script arrives only when that expression runs. Rows that share a combo URL share one in-flight script task. A combo whose `<script>` fails to load is requested once more; a combo that loads without registering a row is never re-executed, because the batch script registers its packages in sequence and a replay would stop at the first duplicate registration. In both cases each still-missing row then loads its own one-resource combo URL, so one failed batch costs at most three requests per missing row and leaves the rows it did register untouched. The module system records the last import failure per row (transport, registration, dependency cascade, or factory execution); the Web boot audit reports that text per entry. A transport failure's text names each failed attempt once, in the order the attempts first occurred, and ends a repeated attempt with its count, such as `(2 attempts)`; an attempt is led by its URL unless its reason already names that URL. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
The application combo scripts carry only each plugin's `client.js` entry and register those factories once during boot; module bodies remain lazy and run only at first import or materialization. A source `import()` split by tsdown compiles to `require.async("./client.<name>.js")`; its versioned sibling script arrives only when that expression runs. Chunks of one package may require each other synchronously: a chunk's registration lists those chunks as `deps`, and the module system downloads and registers them, transitively and in parallel, before the chunk runs. The build adds a `{ deps }` option naming the rest of the requested chunk's group, so the whole group downloads in one round, and moves the chunks an entry requires synchronously into its `client.js`, which registers them before the entry. Rows that share a combo URL share one in-flight script task. A combo whose `<script>` fails to load is requested once more; a combo that loads without registering a row is never re-executed, because the batch script registers its packages in sequence and a replay would stop at the first duplicate registration. In both cases each still-missing row then loads its own one-resource combo URL, so one failed batch costs at most three requests per missing row and leaves the rows it did register untouched. The module system records the last import failure per row (transport, registration, dependency cascade, or factory execution); the Web boot audit reports that text per entry. A transport failure's text names each failed attempt once, in the order the attempts first occurred, and ends a repeated attempt with its count, such as `(2 attempts)`; an attempt is led by its URL unless its reason already names that URL. HMR switches one changed row to its revisioned one-resource combo URL. `<id>/client` and the bare id resolve to the same exports, because a plugin bundle is its package's client half.
### Live plugin composition
@@ -82,7 +82,7 @@ The package has two sides: the Node half is the composition and serving side (`c
### Lazy-CJS model
Executing a plugin bundle registers its factory and optional `meta` without calling them. First import or synchronous require materializes JavaScript and caches its exports; recursive require cycles reject. The module record retains `ownerId`, the package’s isolation flags, observed dependency edges, and `meta` as supplied, without filling in a missing producer. Modules never evaluates stylesheet metadata: it exposes `activeRecords()`, `subscribeModules()` and the carrier asset resolver for consumers. `activeRecords()` lists every materialized record plus the previous records of a package under live replacement, which stay listed until its old runtime has been torn down. The [renderer](../ui-renderer/README.md) owns metadata evaluation and stylesheet installation. Package-local `require.async()` retains its lazy arrival and owner identity.
Executing a plugin bundle registers its factory and optional `meta` without calling them. First import or synchronous require materializes JavaScript and caches its exports; recursive require cycles reject. The module record retains `ownerId`, the package’s isolation flags, observed dependency edges, and `meta` as supplied, without filling in a missing producer. Modules never evaluates stylesheet metadata: it exposes `activeRecords()`, `subscribeModules()` and the carrier asset resolver for consumers. `activeRecords()` lists every materialized record plus the previous records of a package under live replacement, which stay listed until its old runtime has been torn down. The [renderer](../ui-renderer/README.md) owns metadata evaluation and stylesheet installation. Package-local `require.async()` retains its lazy arrival and owner identity. A synchronous `require("./client.<name>.js")` resolves only a chunk of the same package that a script has already registered; an unregistered chunk throws.
### Main execution environment
@@ -131,6 +131,7 @@ The host contributes structured index rows that inject, into `<head>`: the `wind
|---|---|
| [`src/index.ts`](src/index.ts) | Node half: `ClientModuleRegistry`, scan, artifact snapshots, optional combo route, structured index rows |
| [`src/assets.ts`](src/assets.ts) | Package-asset media types, export, content revision, revisioned file name, and browser reference shared by the build preset, the asset route, and gates |
| [`src/chunks.ts`](src/chunks.ts) | Package-local chunk file names shared by the build preset, the chunk route, the module system, the publication closure check, and the WebWorker packer |
| [`src/client/index.ts`](src/client/index.ts) | Browser half: bootstrap export, `ctx.modules` enrollment |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`: load/materialize/invalidate machinery |
| [`src/client/isolated-realms.ts`](src/client/isolated-realms.ts) | One Script Realm per script-isolated package, its creation and disposal |
@@ -183,6 +184,7 @@ These limits define what the module system does not do. They are current package
- **An unrequested prior-generation map reads the current map file** — combo revisions track executable bundles, not debug artifacts. If HMR rebuilds a map before the retained prior URL receives its first map `GET`, that response uses the current authored map with the prior bundle offsets; requesting the map before the rebuild fixes that URL's response.
- **A manifest edit alone is not observed** — the Host reads a package manifest when its Loader entry starts or restarts; editing only `package.json` takes effect at the next entry restart or Host restart. The asset route resolves through Node's package configuration cache, so a `./assets/*` export edited in place takes effect only after boot HMR expires that package or the Host restarts.
- **Script isolation is an unstable test switch** — a Realm is a same-origin iframe, not a security boundary: bare `window`, `document`, timers, and event targets in an isolated bundle are the iframe's own, so page-level listeners, selection, and `instanceof` checks against page constructors do not observe the main document.
- **Chunks carried by an entry file have no source mapping** — the build moves the chunks an entry requires synchronously into `client.js` ahead of the entry and leaves their lines unmapped, so browser tools show their generated code.
- **Desktop re-reads package assets on every display** — the Desktop forwarder rewrites every `/plugins/` cache header to `no-store`, so the immutable asset headers do not reach its browser cache.
<a id="dev-note"></a>
+4 -2
View File
@@ -40,7 +40,7 @@ kind: "package-reference"
### 浏览器加载什么
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会编译为 `require.async("./client.<name>.js")`;只有执行该表达式时,对应的带版本同级脚本才会到达。共享 combo URL 的 row 共用一个进行中的脚本任务。`<script>` 加载失败的 combo 会再请求一次;加载成功但没有注册某条 row 的 combo 绝不会重新执行,因为批量脚本按顺序注册各个包,重放会在第一个重复注册处停止。两种情况下,每条仍缺失的 row 随后加载自己的单资源 combo URL,因此一个失败的 batch 对每条缺失 row 最多花费三次请求,且不影响它已经注册的 row。模块系统按 row 记录最后一次 import 失败(传输、注册、依赖级联或 factory 执行);Web 启动审计按条目报告该文本。传输失败的文本按首次出现的顺序把每个失败的尝试写一次,重复的尝试以次数结尾,例如 `(2 attempts)`;尝试的原因已含其 URL 时,不再以该 URL 开头。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
application combo 脚本只携带每个插件的 `client.js` 入口,并在启动时仅注册一次这些 factory;模块主体仍保持惰性,只在首次 import 或物化时运行。经 tsdown 拆分的源码 `import()` 会编译为 `require.async("./client.<name>.js")`;只有执行该表达式时,对应的带版本同级脚本才会到达。同一个包的 chunk 之间可以同步引用:chunk 的登记信息用 `deps` 列出这些 chunk,模块系统会先递归、并行地下载并登记它们,再运行该 chunk。构建会加上 `{ deps }` 选项,列出所请求 chunk 所在分组的其余 chunk,使整组一轮下载完;入口同步引用的 chunk 会被移进入口的 `client.js`,在入口之前登记。共享 combo URL 的 row 共用一个进行中的脚本任务。`<script>` 加载失败的 combo 会再请求一次;加载成功但没有注册某条 row 的 combo 绝不会重新执行,因为批量脚本按顺序注册各个包,重放会在第一个重复注册处停止。两种情况下,每条仍缺失的 row 随后加载自己的单资源 combo URL,因此一个失败的 batch 对每条缺失 row 最多花费三次请求,且不影响它已经注册的 row。模块系统按 row 记录最后一次 import 失败(传输、注册、依赖级联或 factory 执行);Web 启动审计按条目报告该文本。传输失败的文本按首次出现的顺序把每个失败的尝试写一次,重复的尝试以次数结尾,例如 `(2 attempts)`;尝试的原因已含其 URL 时,不再以该 URL 开头。HMR(热模块替换)会让一条发生变化的 row 改用带 revision 的单资源 combo URL。`<id>/client` 与裸 id 解析到同一组导出,因为插件 bundle 就是其包的客户端半侧。
### 插件动态组合
@@ -82,7 +82,7 @@ application combo 脚本只携带每个插件的 `client.js` 入口,并在启
### 惰性 CJS 模型
执行插件 bundle 只登记其 factory 和可选的 `meta`,不调用它们。首次 import 或同步 require 会物化 JavaScript 并缓存导出;递归 require 环会被拒绝。模块记录保留 `ownerId`、所属包的隔离标志、观察到的依赖边和传入的 `meta`,不会为缺失的生产函数补值。Modules 不求值样式元信息,只向消费者提供 `activeRecords()`、`subscribeModules()` 和载体资源解析器。`activeRecords()` 列出所有已物化记录,以及正在实时替换的包的旧记录;旧记录保留到其旧运行时完成卸载。[Renderer](../ui-renderer/README.zh.md) 负责元信息求值与样式安装。包内 `require.async()` 保持惰性到达及所属模块身份。
执行插件 bundle 只登记其 factory 和可选的 `meta`,不调用它们。首次 import 或同步 require 会物化 JavaScript 并缓存导出;递归 require 环会被拒绝。模块记录保留 `ownerId`、所属包的隔离标志、观察到的依赖边和传入的 `meta`,不会为缺失的生产函数补值。Modules 不求值样式元信息,只向消费者提供 `activeRecords()`、`subscribeModules()` 和载体资源解析器。`activeRecords()` 列出所有已物化记录,以及正在实时替换的包的旧记录;旧记录保留到其旧运行时完成卸载。[Renderer](../ui-renderer/README.zh.md) 负责元信息求值与样式安装。包内 `require.async()` 保持惰性到达及所属模块身份。同步的 `require("./client.<name>.js")` 只能解析同一个包里已由脚本登记的 chunk;未登记的 chunk 会抛错。
### Main 执行环境
@@ -131,6 +131,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
|---|---|
| [`src/index.ts`](src/index.ts) | Node 半侧:`ClientModuleRegistry`、扫描、产物快照、可选 combo 路由、结构化 index 行 |
| [`src/assets.ts`](src/assets.ts) | 包资源的媒体类型、导出、内容 revision、带 revision 的文件名与浏览器引用,由构建预设、资源路由和门禁共用 |
| [`src/chunks.ts`](src/chunks.ts) | 包内 chunk 的文件名规则,由构建预设、chunk 路由、模块系统、发布闭包检查和 WebWorker 打包器共用 |
| [`src/client/index.ts`](src/client/index.ts) | 浏览器半侧:bootstrap 导出、`ctx.modules` 登记 |
| [`src/client/system.ts`](src/client/system.ts) | `ClientModuleSystem`:加载/物化/失效机制 |
| [`src/client/isolated-realms.ts`](src/client/isolated-realms.ts) | 每个脚本隔离包一个 Script Realm,及其创建与销毁 |
@@ -183,6 +184,7 @@ bundle 路由随注入的 `webServer` 生命周期注册:服务就绪时注册
- **从未请求的上一代 map 会读取当前 map 文件**——combo revision 跟踪可执行 bundle,而不跟踪调试产物。若 HMR 在保留的旧 URL 首次收到 map `GET` 前重建 map,该响应会把当前 authored map 与旧 bundle offset 组合;在重建前请求 map 会固定该 URL 的响应。
- **仅编辑 manifest 不会被察觉**——Host 在包的 Loader 条目启动或重启时读取包 manifest;只编辑 `package.json` 要到下一次条目重启或 Host 重启时才生效。资源路由经 Node 的包配置缓存解析,因此原地修改的 `./assets/*` 导出要等 boot HMR 让该包的缓存失效、或 Host 重启后才生效。
- **脚本隔离是不稳定的测试开关**——Realm 是同源 iframe,不是安全边界:隔离 bundle 中的裸 `window`、`document`、计时器与事件目标属于 iframe 自身,因此页面级监听、选区以及针对页面构造器的 `instanceof` 检查观察不到主文档。
- **入口文件携带的 chunk 没有源码映射**——构建把入口同步引用的 chunk 移进 `client.js`、放在入口之前,这些行在 map 中没有映射,浏览器工具只显示其生成代码。
- **Desktop 每次显示都重新读取包资源**——Desktop 转发器把每个 `/plugins/` 缓存头改写为 `no-store`,因此不可变的资源响应头到达不了其浏览器缓存。
<a id="dev-note"></a>
+14
View File
@@ -0,0 +1,14 @@
/**
* Package-local chunk file names shared by the client build preset, the Host
* chunk route, the browser module system, the publication closure check, and
* the WebWorker packer. The preset names split output files with this pattern,
* the route serves only matching names, the module system accepts only
* matching `chunk` registrations and `./client.<name>.js` requests, the closure
* check accepts such a request when the entry file registers the chunk, and the
* packer moves only matching requested chunks out of its base image, so all of
* them read it from this one module.
* @module @deepseek-ai/dsh-client-modules/src/chunks
*/
/** File name of one package-local chunk emitted beside a package's Client entry: `client.<name>.js`. */
export const CLIENT_CHUNK_FILE = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
@@ -20,7 +20,9 @@
* the runtime mirror of the build-time bundle purity gate).
* The synchronous `require` handed to factories walks the same order minus
* the load branch. Loading is async, so a requested dynamic package must have
* registered its factory before a consumer materializes.
* registered its factory before a consumer materializes; likewise a
* `./client.<name>.js` request answers only a registered chunk of the same
* package, which the registration `deps` of its requester bring in first.
*
* This file is the browser-safe contract face (zero node imports): the
* `__DSH_BOOT__` wire types, the boot-manifest parser, and the boundaries around
@@ -35,7 +37,7 @@ import type {
DshClientModuleManifest,
} from '@deepseek-ai/dsh-package-manifest'
import type { ScriptRealm, ScriptRealmRegistryHost } from '@deepseek-ai/dsh-client-script-realm/client'
export type { ClientBundleRequire } from '@deepseek-ai/dsh-package-manifest'
export type { ClientAsyncRequireOptions, ClientBundleRequire } from '@deepseek-ai/dsh-package-manifest'
import type { ClientEntries } from './entries.ts'
import type { ClientModuleSystem } from './system.ts'
+148 -18
View File
@@ -4,14 +4,15 @@
* documented on the public interfaces in `./manifest.ts`; this file owns the
* state tables and the load/materialize machinery.
*/
import { CLIENT_CHUNK_FILE } from '../chunks.ts'
import { NO_ISOLATION, stripClientSuffix } from './manifest.ts'
import { ClientEntries } from './entries.ts'
import { PackageRealms } from './isolated-realms.ts'
import { MainScriptRealm } from './main-realm.ts'
import { notifySubscribers } from './notify.ts'
import type {
BootManifest, BootModuleRow, ClientBundleRegistration, ClientBundleRequire, ClientModuleLoader, ClientModuleRecord,
ClientModuleSystemOptions,
BootManifest, BootModuleRow, ClientAsyncRequireOptions, ClientBundleRegistration, ClientBundleRequire, ClientModuleLoader,
ClientModuleRecord, ClientModuleSystemOptions,
} from './manifest.ts'
/** Replace the rev query while preserving absolute, protocol-relative, or path-relative form. */
@@ -22,8 +23,6 @@ function atRevision(url: string, rev: string): string {
return url.replace(/([?&]rev=)[^&#]*/, `$1${encodeURIComponent(rev)}`)
}
const CLIENT_CHUNK = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
/** The message of a thrown value: an Error's message, anything else stringified. */
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error)
@@ -55,6 +54,39 @@ function describeAttempts(failures: readonly string[]): string {
return [...counts].map(([failure, count]) => count === 1 ? failure : `${failure} (${count} attempts)`).join('; ')
}
/** File name of a package-local chunk specifier (`./client.<name>.js`), or undefined for any other specifier. */
function chunkFileOf(specifier: string): string | undefined {
const fileName = specifier.slice(2)
return specifier.startsWith('./') && CLIENT_CHUNK_FILE.test(fileName) ? fileName : undefined
}
/**
* Chunk file names of a `deps` list.
* @param specifiers - `./client.<name>.js` specifiers.
* @param subject - Registration or request named in the error.
* @returns The file names, in list order.
* @throws {Error} when an entry names no package-local chunk.
*/
function chunkFilesOf(specifiers: readonly string[], subject: string): string[] {
return specifiers.map((specifier) => {
const fileName = chunkFileOf(specifier)
if (fileName === undefined) throw new Error(`client-modules: invalid chunk dependency ${JSON.stringify(specifier)} of ${subject}`)
return fileName
})
}
/**
* Wait for every started task to end, then reject with the first failure in list order. A failure therefore never
* leaves a sibling task running past the caller's wait.
* @param tasks - Started tasks.
* @throws The reason of the first task in the list that rejected.
*/
async function settleAll(tasks: readonly Promise<void>[]): Promise<void> {
for (const result of await Promise.allSettled(tasks)) {
if (result.status === 'rejected') throw result.reason
}
}
/** Internal module-table key for one package-local chunk. */
function chunkId(ownerId: string, fileName: string): string {
return `${ownerId}/${fileName}`
@@ -196,10 +228,12 @@ export class ClientModuleSystem implements ClientModuleLoader {
/** Register one bundle factory, rejecting a script that executes twice without invalidation. */
private register(registration: ClientBundleRegistration): void {
const ownerId = registration.id
if (registration.chunk !== undefined && !CLIENT_CHUNK.test(registration.chunk)) {
if (registration.chunk !== undefined && !CLIENT_CHUNK_FILE.test(registration.chunk)) {
throw new Error(`client-modules: invalid package-local chunk ${JSON.stringify(registration.chunk)}`)
}
const id = registration.chunk === undefined ? ownerId : chunkId(ownerId, registration.chunk)
// A malformed dependency list fails the registering script instead of a later arrival.
chunkFilesOf(registration.deps ?? [], `"${id}"`)
if (this.loadCache.has(id) || this.factories.has(id)) {
const registrationName = registration.chunk === undefined ? registration.id : id
throw new Error(`client-modules: duplicate factory registration for "${registrationName}" (bundle executed twice without invalidate?)`)
@@ -235,8 +269,25 @@ export class ClientModuleSystem implements ClientModuleLoader {
}
/**
* Load one graph row so its factory is registered (idempotent per in-flight
* arrival). A batch script is one classic script that registers every
* Register one graph row's entry and every package-local chunk its
* registration requires. A batch script can register the entry without this
* row's own download, so the chunk step runs for an entry that was already
* registered as well. An owner invalidation while the chunks download drops
* the entry and the chunks registered so far, so the arrival restarts from
* the entry under the new revision.
*/
private async arrive(row: BootModuleRow): Promise<void> {
await this.arriveScript(row)
const deps = this.factories.get(row.id)?.manifest.deps
if (deps === undefined) return
const generation = this.generations.get(row.id) ?? 0
await this.arriveChunks(row.id, chunkFilesOf(deps, `"${row.id}"`), generation)
if ((this.generations.get(row.id) ?? 0) !== generation) await this.arrive(this.arrivalRow(row.id))
}
/**
* Load one graph row's entry script so its factory is registered (idempotent
* per in-flight arrival). A batch script is one classic script that registers every
* package in sequence, and {@link register} rejects a second registration,
* so the two failure kinds differ: a transport failure (`error` event, nothing
* executed) is retried once on the same URL; a script that loaded without
@@ -249,7 +300,7 @@ export class ClientModuleSystem implements ClientModuleLoader {
* failed batch costs at most three requests per missing row and never fails
* the rows that were registered.
*/
private async arrive(row: BootModuleRow): Promise<void> {
private async arriveScript(row: BootModuleRow): Promise<void> {
const { id } = row
if (row.isolation.script && this.staticIds.has(id)) {
throw new Error(`client-modules: "${id}" is loaded by the page shell and cannot isolate its scripts`)
@@ -370,13 +421,17 @@ export class ClientModuleSystem implements ClientModuleLoader {
return record
}
/** Build the synchronous module-table require, its asynchronous chunk operation, and its asset resolver. */
/**
* Build the synchronous module-table require, its asynchronous chunk operation, and its asset resolver. A
* synchronous `./client.<name>.js` request resolves only a chunk of the same package that is already registered.
*/
private makeRequire(
ownerId: string,
edges: Set<string>,
onEdgesChanged: () => void,
): ClientBundleRequire {
const resolve = (spec: string): unknown => {
if (spec.startsWith('./')) return this.requireChunk(ownerId, spec)
const id = this.resolveModuleId(spec)
const record = this.loadCache.get(id)
if (record !== undefined) return record.exports
@@ -398,30 +453,65 @@ export class ClientModuleSystem implements ClientModuleLoader {
return exports
}
require.asset = (reference: string): string => this.resolveAsset(reference)
require.async = async (spec: string): Promise<unknown> => {
require.async = async (spec: string, options?: ClientAsyncRequireOptions): Promise<unknown> => {
if (!spec.startsWith('./')) {
const exports = await this.import(spec)
recordEdge(spec)
return exports
}
const fileName = spec.slice(2)
if (!CLIENT_CHUNK.test(fileName)) {
const fileName = chunkFileOf(spec)
if (fileName === undefined) {
throw new Error(`client-modules: invalid relative chunk request ${JSON.stringify(spec)}`)
}
const exports = await this.importChunk(ownerId, fileName)
const preload = chunkFilesOf(options?.deps ?? [], `require.async(${JSON.stringify(spec)})`)
const exports = await this.importChunk(ownerId, fileName, preload)
recordEdge(spec)
return exports
}
return require
}
/** Load, register, and materialize one package-local dynamic chunk. */
private async importChunk(ownerId: string, fileName: string): Promise<unknown> {
/**
* Load, register, and materialize one package-local dynamic chunk. The prefetch hint downloads in parallel with the
* requested chunk, and the request waits for those downloads to end; the requested chunk's registration `deps`
* decide what the chunk needs, and their arrival reports a failure with its dependency chain, so a failed hinted
* download that no registration requires does not fail the request.
*/
private async importChunk(ownerId: string, fileName: string, preload: readonly string[]): Promise<unknown> {
const id = chunkId(ownerId, fileName)
const existing = this.loadCache.get(id)
if (existing !== undefined) return existing.exports
const generation = this.generations.get(ownerId) ?? 0
const arrival = this.arriveChunk(ownerId, fileName, generation, new Set())
// Each hint arrives with its own visited set, so the requested chunk's arrival still waits for every chunk its
// registrations require and reports their failures; the hinted arrival only shares the downloads and discards a
// factory registered after an owner invalidation, and its own failure is ignored.
const hints = preload.map(hinted => this.arriveChunk(ownerId, hinted, generation, new Set()).catch(() => undefined))
try {
await arrival
} finally {
// The request ends, or retries, only after every arrival it started has ended, so a hinted arrival of a dropped
// generation cannot discard the chunks that the retry registers.
await Promise.all(hints)
}
// An owner invalidation during arrival dropped every chunk registered so far.
if ((this.generations.get(ownerId) ?? 0) !== generation) return await this.importChunk(ownerId, fileName, preload)
return this.materialize(id).exports
}
/**
* Register one package-local chunk, downloading it unless a script already registered it, then the chunks its
* registration requires. A script requested before an owner invalidation can register a factory of the dropped
* generation; that factory is discarded, and the caller restarts the arrival under the new generation.
* @throws {Error} naming the dependency chain when a required chunk fails to arrive, once every dependency arrival
* it started has ended.
*/
private async arriveChunk(ownerId: string, fileName: string, generation: number, visited: Set<string>): Promise<void> {
if (visited.has(fileName)) return
visited.add(fileName)
const id = chunkId(ownerId, fileName)
if (this.loadCache.has(id)) return
if (!this.factories.has(id)) {
const generation = this.generations.get(ownerId) ?? 0
const row = this.graphRows.get(ownerId)
if (row === undefined) throw new Error(`client-modules: chunk owner "${ownerId}" is not a boot graph entry`)
/* v8 ignore next -- the final fallback needs an impossible graph-owned factory with no recorded revision. */
@@ -431,13 +521,53 @@ export class ClientModuleSystem implements ClientModuleLoader {
if ((this.generations.get(ownerId) ?? 0) !== generation) {
this.factories.delete(id)
if (this.loadCache.delete(id)) this.publishModules()
return await this.importChunk(ownerId, fileName)
return
}
if (!this.factories.has(id)) {
throw new Error(`client-modules: bundle ${url} loaded without registering "${id}" via __ModuleLoader__.load`)
}
}
return this.materialize(id).exports
const deps = chunkFilesOf(this.factories.get(id)?.manifest.deps ?? [], `"${id}"`)
await settleAll(deps.map(async (dependency) => {
try {
await this.arriveChunk(ownerId, dependency, generation, visited)
} catch (error) {
throw new Error(
`client-modules: "${id}" not loaded because dependency "${chunkId(ownerId, dependency)}" failed: ${describeError(error)}`,
{ cause: error },
)
}
}))
}
/**
* Register package-local chunks and, transitively, every chunk their registrations require, in parallel, and fail
* only after all of them have ended. One call requests each chunk at most once, so a shared or cyclic dependency
* does not repeat or stall it.
* @param ownerId - Package that owns the chunks.
* @param fileNames - Chunk file names.
* @param generation - Owner generation the arrival belongs to.
*/
private async arriveChunks(ownerId: string, fileNames: readonly string[], generation: number): Promise<void> {
const visited = new Set<string>()
await settleAll(fileNames.map(fileName => this.arriveChunk(ownerId, fileName, generation, visited)))
}
/**
* Resolve a synchronous package-local chunk request from the registered chunks.
* @param ownerId - Package whose factory requests the chunk.
* @param spec - `./client.<name>.js` specifier.
* @returns The chunk's exports, materializing it on first request.
* @throws {Error} when the specifier names no chunk, or no script has registered the chunk yet.
*/
private requireChunk(ownerId: string, spec: string): unknown {
const fileName = chunkFileOf(spec)
if (fileName === undefined) throw new Error(`client-modules: invalid relative chunk request ${JSON.stringify(spec)}`)
const id = chunkId(ownerId, fileName)
const record = this.loadCache.get(id)
if (record !== undefined) return record.exports
if (this.factories.has(id)) return this.materialize(id).exports
throw new Error(`client-modules: "${ownerId}" required chunk ${fileName} before it was registered`)
}
async import(specifier: string): Promise<unknown> {
+2 -3
View File
@@ -41,6 +41,7 @@ import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import { PACKAGE_ASSET_SEGMENT, packageAssetMediaType } from './assets.ts'
import { CLIENT_CHUNK_FILE } from './chunks.ts'
import { exactPackageSpecifier, parseClientIsolation, parseDshClient, stripClientSuffix } from './client/manifest.ts'
import { SyncedConfigPublisher } from './config-sync.ts'
import type {
@@ -216,8 +217,6 @@ const COMBO_REVISION_PLACEHOLDER = '0'.repeat(HASH_REVISION_LENGTH)
const SOURCE_MAP_TRAILER = /(?:\r?\n)?\/\/# sourceMappingURL=[^\r\n]*(?:\r?\n)?$/
/** Debugger source name appended to page bundles in the WebWorker image. */
const SOURCE_URL_TRAILER = /(?:\r?\n)?\/\/# sourceURL=([^\r\n]+)(?:\r?\n)?$/
/** Published package-local client chunk names accepted by the on-demand route. */
const CLIENT_CHUNK = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
/** Resolve `exports["./client"]` to a relative path, accepting the string and one-level conditional forms. */
function clientExportOf(pkgName: string, exportsField: unknown): string | undefined {
@@ -1226,7 +1225,7 @@ export class ClientModuleRegistry extends Service {
const fileName = sourceMap ? requested.slice(0, -'.map'.length) : requested
// The Node Client entry and its split chunks share this directory but
// must never be served as browser factory scripts.
if (!CLIENT_CHUNK.test(fileName) || fileName === 'client.node.js' || fileName.startsWith('client.node.')) return undefined
if (!CLIENT_CHUNK_FILE.test(fileName) || fileName === 'client.node.js' || fileName.startsWith('client.node.')) return undefined
if (resourceUrl !== chunkUrl(record.entry.id, fileName, record.entry.rev, sourceMap)) return undefined
return { record, fileName, sourceMap, resourceUrl }
}
@@ -0,0 +1,346 @@
/**
* Package-local chunk dependencies: a registration's `deps` must arrive before its factory runs, a
* `require.async` hint only widens the parallel download, and a synchronous chunk request resolves registered
* chunks only.
*/
import { describe, expect, it } from 'vitest'
import {
createClientModuleSystem,
type ClientBundleRegistration, type ClientModuleLoader, type ClientModuleLoaderTarget,
} from '../src/client/index.ts'
const OWNER = 'pkg'
const BATCH_URL = `plugins/??${OWNER}/client.js&rev=app`
const entryUrl = (rev = '0'): string => `plugins/??${OWNER}/client.js&rev=${rev}`
const chunkUrl = (fileName: string, rev = '0'): string => `plugins/${OWNER}/${fileName}?rev=${rev}`
/** One registration a fixture script performs for {@link OWNER}. */
type Registration = Omit<ClientBundleRegistration, 'id'>
/** Exports of an entry whose `load` requests a package-local chunk. */
interface LoaderEntry {
load(spec: string, options?: { deps?: readonly string[] }): Promise<unknown>
}
interface Bench {
system: ClientModuleLoader
target: ClientModuleLoaderTarget
fetched: string[]
/** Release callback of each gated URL, set once its download starts. */
gates: Map<string, () => void>
}
/**
* Module system over scripted URLs: each script registers its listed factories for {@link OWNER}. A gated URL
* waits for its release callback; a failing URL rejects like a `<script>` error event.
*/
function bench(
scripts: Readonly<Record<string, readonly Registration[]>>,
options: {
pending?: readonly Registration[]
seed?: readonly ClientBundleRegistration[]
gated?: readonly string[]
failing?: readonly string[]
/** URLs whose script keeps loading after a registration throws, as a browser still fires `load` after a script error. */
loadsAfterError?: readonly string[]
} = {},
): Bench {
const fetched: string[] = []
const gates = new Map<string, () => void>()
const target: ClientModuleLoaderTarget = {
mode: 'queue',
pendingQueue: (options.pending ?? []).map(registration => ({ id: OWNER, ...registration })),
load(registration) { target.pendingQueue.push(registration) },
create() { throw new Error('the bench creates its module system directly') },
}
const system = createClientModuleSystem(target, { id: '@deepseek-ai/dsh-client-modules', exports: {} }, {
boot: {
rev: 'graph',
entries: [{ id: OWNER, url: entryUrl(), rev: '0' }],
batches: [{ phase: 'application', url: BATCH_URL, rev: 'app', entries: [OWNER] }],
},
staticModules: options.seed ?? [],
loadBundle: async (url) => {
fetched.push(url)
if (options.gated?.includes(url) === true) await new Promise<void>((resolve) => { gates.set(url, resolve) })
if (options.failing?.includes(url) === true) throw new Error(`bundle script ${url} failed to load`)
try {
for (const registration of scripts[url] ?? []) target.load({ id: OWNER, ...registration })
} catch (error) {
if (options.loadsAfterError?.includes(url) !== true) throw error
}
},
})
return { system, target, fetched, gates }
}
/** Entry registration whose `load` forwards to `require.async`. */
const loaderEntry = (deps?: readonly string[]): Registration => ({
...(deps === undefined ? {} : { deps }),
factory: require => ({ load: (spec: string, options?: { deps?: readonly string[] }) => require.async(spec, options) }),
})
/** Chunk registration whose exports list the exports of the chunks it requires synchronously. */
const chunk = (fileName: string, deps: readonly string[] = []): Registration => ({
chunk: fileName,
...(deps.length === 0 ? {} : { deps }),
factory: require => ({ name: fileName, deps: deps.map(dependency => require(dependency)) }),
})
describe('chunk registration dependencies', () => {
it('runs a chunk only after the chunks its registration requires arrive, level by level without a hint', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js')]: [chunk('client.shared.js', ['./client.base.js'])],
[chunkUrl('client.base.js')]: [chunk('client.base.js')],
})
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
await expect(entry.load('./client.view.js')).resolves.toEqual({
name: 'client.view.js',
deps: [{ name: 'client.shared.js', deps: [{ name: 'client.base.js', deps: [] }] }],
})
expect(b.fetched).toEqual([
BATCH_URL, chunkUrl('client.view.js'), chunkUrl('client.shared.js'), chunkUrl('client.base.js'),
])
expect(b.system.loadCache.get(OWNER)?.edges).toEqual(new Set(['./client.view.js']))
expect(b.system.loadCache.get(`${OWNER}/client.view.js`)?.edges).toEqual(new Set(['./client.shared.js']))
})
it('starts every hinted download before any of them registers', async () => {
const files = ['client.view.js', 'client.shared.js', 'client.base.js']
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js')]: [chunk('client.shared.js', ['./client.base.js'])],
[chunkUrl('client.base.js')]: [chunk('client.base.js')],
}, { gated: files.map(file => chunkUrl(file)) })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const loaded = entry.load('./client.view.js', { deps: ['./client.shared.js', './client.base.js'] })
expect(b.fetched).toEqual([BATCH_URL, ...files.map(file => chunkUrl(file))])
for (const release of b.gates.values()) release()
await expect(loaded).resolves.toMatchObject({ name: 'client.view.js' })
expect(b.fetched).toHaveLength(4)
})
it('registers the chunks of an entry script before materializing the entry, without another download', async () => {
const b = bench({
[BATCH_URL]: [chunk('client.runtime.js'), {
deps: ['./client.runtime.js'],
factory: require => ({ runtime: require('./client.runtime.js') }),
}],
})
await expect(b.system.import(OWNER, '', {})).resolves.toEqual({ runtime: { name: 'client.runtime.js', deps: [] } })
expect(b.fetched).toEqual([BATCH_URL])
})
it('completes the dependencies of an entry registered before its own download', async () => {
const b = bench({ [chunkUrl('client.shared.js')]: [chunk('client.shared.js')] }, {
pending: [{ deps: ['./client.shared.js'], factory: require => ({ shared: require('./client.shared.js') }) }],
})
await expect(b.system.import(OWNER, '', {})).resolves.toEqual({ shared: { name: 'client.shared.js', deps: [] } })
expect(b.fetched).toEqual([chunkUrl('client.shared.js')])
})
it('materializes a dependency shared by two chunks once and never downloads a materialized chunk again', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.left.js', './client.right.js'])],
[chunkUrl('client.left.js')]: [chunk('client.left.js', ['./client.base.js'])],
[chunkUrl('client.right.js')]: [chunk('client.right.js', ['./client.base.js'])],
[chunkUrl('client.base.js')]: [chunk('client.base.js')],
[chunkUrl('client.other.js')]: [chunk('client.other.js', ['./client.base.js'])],
})
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const view = await entry.load('./client.view.js') as { deps: { deps: unknown[] }[] }
expect(view.deps[0]?.deps[0]).toBe(view.deps[1]?.deps[0])
const other = await entry.load('./client.other.js', { deps: ['./client.base.js'] }) as { deps: unknown[] }
expect(other.deps[0]).toBe(view.deps[0]?.deps[0])
expect(b.fetched.filter(url => url === chunkUrl('client.base.js'))).toHaveLength(1)
expect(b.fetched.at(-1)).toBe(chunkUrl('client.other.js'))
})
it('requests a shared or cyclic dependency once and rejects the cycle when the factories run', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.left.js', './client.right.js'])],
[chunkUrl('client.left.js')]: [chunk('client.left.js', ['./client.right.js'])],
[chunkUrl('client.right.js')]: [chunk('client.right.js', ['./client.left.js'])],
})
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
await expect(entry.load('./client.view.js')).rejects.toThrow(`require cycle through "${OWNER}/client.left.js"`)
expect(b.fetched).toEqual([
BATCH_URL, chunkUrl('client.view.js'), chunkUrl('client.left.js'), chunkUrl('client.right.js'),
])
})
it('names the dependency chain when a required chunk fails to download', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js')]: [chunk('client.shared.js', ['./client.base.js'])],
}, { failing: [chunkUrl('client.base.js')] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const failure = await entry.load('./client.view.js').then(() => undefined, (error: unknown) => error)
expect(failure).toBeInstanceOf(Error)
expect((failure as Error).message).toBe(
`client-modules: "${OWNER}/client.view.js" not loaded because dependency "${OWNER}/client.shared.js" failed: `
+ `client-modules: "${OWNER}/client.shared.js" not loaded because dependency "${OWNER}/client.base.js" failed: `
+ `bundle script ${chunkUrl('client.base.js')} failed to load`,
)
expect(((failure as Error).cause as Error).message).toContain(`"${OWNER}/client.shared.js" not loaded`)
expect(b.system.loadCache.has(`${OWNER}/client.view.js`)).toBe(false)
})
it('names the dependency chain when a hinted chunk fails to download', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js')]: [chunk('client.shared.js', ['./client.base.js'])],
}, { failing: [chunkUrl('client.base.js')] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const failure = await entry.load('./client.view.js', { deps: ['./client.shared.js', './client.base.js'] })
.then(() => undefined, (error: unknown) => error)
expect((failure as Error).message).toMatch(new RegExp(
`^client-modules: "${OWNER}/client\\.view\\.js" not loaded because dependency "${OWNER}/client\\.shared\\.js" failed: `
+ `client-modules: "${OWNER}/client\\.shared\\.js" not loaded because dependency "${OWNER}/client\\.base\\.js" failed: `,
))
expect(((failure as Error).cause as Error).message).toContain(`"${OWNER}/client.shared.js" not loaded`)
})
it('loads a chunk whose hint names a chunk that fails to download but no registration requires', async () => {
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js')],
}, { failing: [chunkUrl('client.extra.js')] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
await expect(entry.load('./client.view.js', { deps: ['./client.extra.js'] })).resolves.toEqual({ name: 'client.view.js', deps: [] })
expect(b.fetched).toEqual([BATCH_URL, chunkUrl('client.view.js'), chunkUrl('client.extra.js')])
})
it('restarts a chunk arrival under the new revision when its owner is invalidated mid-download', async () => {
const stale = chunkUrl('client.shared.js')
const b = bench({
[BATCH_URL]: [loaderEntry()],
[chunkUrl('client.view.js')]: [chunk('client.view.js', ['./client.shared.js'])],
[stale]: [chunk('client.shared.js')],
[chunkUrl('client.view.js', 'next')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js', 'next')]: [{ chunk: 'client.shared.js', factory: () => ({ name: 'next' }) }],
}, { gated: [stale] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const loaded = entry.load('./client.view.js')
await expect.poll(() => b.gates.has(stale)).toBe(true)
b.system.invalidate(OWNER, 'next')
b.gates.get(stale)?.()
await expect(loaded).resolves.toEqual({ name: 'client.view.js', deps: [{ name: 'next' }] })
expect(b.fetched.slice(-2)).toEqual([chunkUrl('client.view.js', 'next'), chunkUrl('client.shared.js', 'next')])
})
it('restarts an entry arrival from the entry script when its owner is invalidated while its chunks download', async () => {
const stale = chunkUrl('client.shared.js')
const entry: Registration = { deps: ['./client.shared.js'], factory: require => ({ shared: require('./client.shared.js') }) }
const b = bench({
[stale]: [chunk('client.shared.js')],
[entryUrl('next')]: [entry],
[chunkUrl('client.shared.js', 'next')]: [{ chunk: 'client.shared.js', factory: () => ({ name: 'next' }) }],
}, { pending: [entry], gated: [stale] })
const imported = b.system.import(OWNER, '', {})
await expect.poll(() => b.gates.has(stale)).toBe(true)
b.system.invalidate(OWNER, 'next')
b.gates.get(stale)?.()
await expect(imported).resolves.toEqual({ shared: { name: 'next' } })
expect(b.fetched).toEqual([stale, entryUrl('next'), chunkUrl('client.shared.js', 'next')])
})
it('retries an invalidated hinted request only after its hinted downloads end', async () => {
const [view, shared] = [chunkUrl('client.view.js'), chunkUrl('client.shared.js')]
const b = bench({
[BATCH_URL]: [loaderEntry()],
[view]: [chunk('client.view.js', ['./client.shared.js'])],
[shared]: [chunk('client.shared.js')],
[chunkUrl('client.view.js', 'next')]: [chunk('client.view.js', ['./client.shared.js'])],
[chunkUrl('client.shared.js', 'next')]: [{ chunk: 'client.shared.js', factory: () => ({ name: 'next' }) }],
}, { gated: [view, shared], loadsAfterError: [shared] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const loaded = entry.load('./client.view.js', { deps: ['./client.shared.js'] })
await expect.poll(() => b.gates.has(view) && b.gates.has(shared)).toBe(true)
b.system.invalidate(OWNER, 'next')
b.gates.get(view)?.()
// Bench transports settle through promise jobs only, so one macrotask lets a retry that does not wait run to its end.
await new Promise<void>((resolve) => { setTimeout(resolve, 0) })
expect(b.fetched).not.toContain(chunkUrl('client.view.js', 'next'))
b.gates.get(shared)?.()
await expect(loaded).resolves.toEqual({ name: 'client.view.js', deps: [{ name: 'next' }] })
await new Promise<void>((resolve) => { setTimeout(resolve, 0) })
expect(b.system.loadCache.get(`${OWNER}/client.shared.js`)?.exports).toEqual({ name: 'next' })
expect(b.fetched.slice(-2)).toEqual([chunkUrl('client.view.js', 'next'), chunkUrl('client.shared.js', 'next')])
})
it('retries an invalidated request only after every sibling of a failed dependency ends', async () => {
const [view, bad, shared] = [chunkUrl('client.view.js'), chunkUrl('client.bad.js'), chunkUrl('client.shared.js')]
const b = bench({
[BATCH_URL]: [loaderEntry()],
[view]: [chunk('client.view.js', ['./client.hint.js'])],
[chunkUrl('client.hint.js')]: [chunk('client.hint.js', ['./client.bad.js', './client.shared.js'])],
[shared]: [chunk('client.shared.js')],
[chunkUrl('client.view.js', 'next')]: [chunk('client.view.js', ['./client.hint.js'])],
[chunkUrl('client.hint.js', 'next')]: [chunk('client.hint.js', ['./client.bad.js', './client.shared.js'])],
[chunkUrl('client.bad.js', 'next')]: [chunk('client.bad.js')],
[chunkUrl('client.shared.js', 'next')]: [{ chunk: 'client.shared.js', factory: () => ({ name: 'next' }) }],
}, { gated: [view, bad, shared], failing: [bad], loadsAfterError: [shared] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
const loaded = entry.load('./client.view.js', { deps: ['./client.hint.js'] }) as Promise<{ deps: [{ deps: unknown[] }] }>
await expect.poll(() => [view, bad, shared].every(url => b.gates.has(url))).toBe(true)
b.system.invalidate(OWNER, 'next')
b.gates.get(view)?.()
b.gates.get(bad)?.()
// Bench transports settle through promise jobs only, so one macrotask lets a retry that does not wait run to its end.
await new Promise<void>((resolve) => { setTimeout(resolve, 0) })
expect(b.fetched).not.toContain(chunkUrl('client.view.js', 'next'))
b.gates.get(shared)?.()
expect((await loaded).deps[0].deps[1]).toEqual({ name: 'next' })
await new Promise<void>((resolve) => { setTimeout(resolve, 0) })
expect(b.system.loadCache.get(`${OWNER}/client.shared.js`)?.exports).toEqual({ name: 'next' })
})
it('re-executes an entry script that registers several chunks after invalidation', async () => {
const script: readonly Registration[] = [chunk('client.runtime.js'), {
deps: ['./client.runtime.js'],
factory: require => ({ runtime: require('./client.runtime.js') }),
}]
const b = bench({ [BATCH_URL]: script, [entryUrl('next')]: script })
await b.system.import(OWNER, '', {})
b.system.invalidate(OWNER, 'next')
expect([...b.system.loadCache.keys()].filter(id => id.startsWith(OWNER))).toEqual([])
await expect(b.system.import(OWNER, '', {})).resolves.toEqual({ runtime: { name: 'client.runtime.js', deps: [] } })
expect(b.fetched).toEqual([BATCH_URL, entryUrl('next')])
})
})
describe('chunk request validation', () => {
it('rejects a registration or hint whose dependency names no package-local chunk', async () => {
const b = bench({ [BATCH_URL]: [loaderEntry()] })
expect(() => { b.target.load({ id: OWNER, chunk: 'client.view.js', deps: ['../client.base.js'], factory: () => ({}) }) })
.toThrow(`invalid chunk dependency "../client.base.js" of "${OWNER}/client.view.js"`)
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
await expect(entry.load('./client.view.js', { deps: ['client.base.js'] }))
.rejects.toThrow('invalid chunk dependency "client.base.js" of require.async("./client.view.js")')
expect(b.fetched).toEqual([BATCH_URL])
})
it('ignores the options of a request for another package', async () => {
const b = bench({ [BATCH_URL]: [loaderEntry()] }, { seed: [{ id: 'other', factory: () => ({ name: 'other' }) }] })
const entry = await b.system.import(OWNER, '', {}) as LoaderEntry
await expect(entry.load('other', { deps: ['not a chunk'] })).resolves.toEqual({ name: 'other' })
})
it('resolves a synchronous chunk request only for a registered package-local chunk', async () => {
for (const [spec, message] of [
['./client.missing.js', `"${OWNER}" required chunk client.missing.js before it was registered`],
['./missing.js', 'invalid relative chunk request "./missing.js"'],
] as const) {
const b = bench({ [BATCH_URL]: [{ factory: require => ({ value: require(spec) }) }] })
await expect(b.system.import(OWNER, '', {})).rejects.toThrow(message)
}
})
})
+109 -10
View File
@@ -15,6 +15,13 @@
* `./lib/assets/*`, and its Node Client face rejects asset imports.
* Non-experimental client outputs reject experimental module and stylesheet
* inputs, including origins recorded by chained source maps.
* A source `import()` of a package module becomes `require.async` on a split
* `client.<name>.js` chunk. Chunks may require each other synchronously: each
* registration lists those chunks as `deps`, each `require.async` names the
* target's remaining chunk group in a `{ deps }` prefetch hint, and the chunks
* the entry requires move into `client.js` ahead of the entry's registration,
* without source mappings for their lines; a dynamic import of one of those
* chunks stays a synchronous `require` because no file is left to download.
*/
import { randomBytes } from 'node:crypto'
import { readFile, readdir, rm, rmdir, stat, utimes } from 'node:fs/promises'
@@ -34,6 +41,7 @@ import {
packageAssetRevision,
packageAssetRevisionedPath,
} from './modules/src/assets.ts'
import { CLIENT_CHUNK_FILE } from './modules/src/chunks.ts'
import { optionalStringArray } from './modules/src/client/manifest.ts'
import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS, STATIC_MODULE_MANIFEST_EXPORT } from './web/src/platform.ts'
import { clientBuildEnvironmentDefines, clientBuildValueDefines } from '../../scripts/client-build-environment.ts'
@@ -643,31 +651,117 @@ function matchesSpecifier(patterns: readonly RegExp[], specifier: string): boole
return patterns.some(pattern => pattern.test(specifier))
}
/** Render package-local dynamic imports through the Client module loader's asynchronous operation. */
function asyncChunkRequirePlugin(): TsdownPlugin {
/** The static imports of a rendered or emitted chunk, by emitted file name. */
interface ChunkImports {
readonly imports: readonly string[]
}
/**
* Package-local chunks one chunk requires synchronously.
* @param chunk - Rendered or emitted chunk.
* @returns The `client.<name>.js` file names among its static imports.
*/
function localImports(chunk: ChunkImports): string[] {
return chunk.imports.filter(file => CLIENT_CHUNK_FILE.test(file))
}
/**
* Package-local chunks reachable through synchronous requires, dependencies before their dependents.
* @param chunks - Chunks of one output by file name.
* @param start - Chunk whose synchronous requires are followed; not part of the result.
* @returns The reachable chunk file names.
*/
function localClosure(chunks: Readonly<Record<string, ChunkImports>>, start: string): string[] {
const order: string[] = []
const seen = new Set([start])
const visit = (file: string): void => {
for (const dependency of localImports(chunks[file] ?? { imports: [] })) {
if (seen.has(dependency)) continue
seen.add(dependency)
visit(dependency)
order.push(dependency)
}
}
visit(start)
return order
}
/** Trailing source-map reference of one emitted chunk, removed when the chunk moves into the entry file. */
const CHUNK_SOURCEMAP_COMMENT = /\n\/\/# sourceMappingURL=\S+\s*$/u
/**
* Render package-local chunk requests for the Client module loader. A dynamic import becomes `require.async`
* with a `deps` prefetch hint naming the target's synchronous chunk closure; the chunks the entry requires
* synchronously, transitively, move into the entry file ahead of its own registration. A dynamic import of such a
* chunk keeps Rolldown's synchronous `require` inside a resolved promise: the entry file registers the chunk before
* any code of the package runs, and the chunk has no file left to download.
* @param entryFileName - The package entry's emitted file name.
* @returns The rendering plugin.
*/
function asyncChunkRequirePlugin(entryFileName: string): TsdownPlugin {
return {
name: 'dsh-client-async-chunk-require',
renderChunk(code, chunk, outputOptions) {
renderChunk(code, chunk, outputOptions, meta) {
if (outputOptions.format !== 'cjs') return null
// The loader keys the entry by its package id, so a chunk has no relative specifier that reaches it.
if (!chunk.isEntry && [...chunk.imports, ...chunk.dynamicImports.map(file => file.replace(/^\.\//u, ''))].includes(entryFileName)) {
throw new Error(
`client bundle compiler: ${chunk.fileName} imports the package entry ${entryFileName}; `
+ 'move the code it shares with the entry into a module that both import',
)
}
const transformed = new Rolldown.RolldownMagicString(code)
const colocated = new Set(localClosure(meta.chunks, entryFileName))
for (const dynamicImport of chunk.dynamicImports) {
const fileName = dynamicImport.startsWith('./') ? dynamicImport.slice(2) : dynamicImport
if (!/^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/.test(fileName)) continue
if (!CLIENT_CHUNK_FILE.test(fileName) || colocated.has(fileName)) continue
const specifier = `./${fileName}`
const call = new RegExp(
const expression = new RegExp(
`Promise\\.resolve\\(\\)\\.then\\(\\(\\)\\s*=>\\s*require\\((['"])${escapeSpecifier(specifier)}\\1\\)\\)`,
'gu',
)
const matches = [...code.matchAll(call)]
const matches = [...code.matchAll(expression)]
if (matches.length === 0) {
throw new Error(`client bundle compiler: dynamic chunk ${JSON.stringify(specifier)} has no generated import expression`)
}
const preload = localClosure(meta.chunks, fileName).filter(file => !colocated.has(file)).map(file => `./${file}`)
const call = preload.length === 0
? `require.async(${JSON.stringify(specifier)})`
: `require.async(${JSON.stringify(specifier)}, { deps: ${JSON.stringify(preload)} })`
for (const match of matches) {
transformed.overwrite(match.index, match.index + match[0].length, `require.async(${JSON.stringify(specifier)})`)
transformed.overwrite(match.index, match.index + match[0].length, call)
}
}
return transformed.hasChanged() ? transformed : null
},
generateBundle: {
// After every other check, so input isolation still reads each chunk's own modules and imports.
order: 'post',
handler(_options, bundle) {
const entry = bundle[entryFileName]
if (entry?.type !== 'chunk') return
const chunks: Record<string, Rolldown.OutputChunk> = {}
for (const output of Object.values(bundle)) if (output.type === 'chunk') chunks[output.fileName] = output
const colocated = localClosure(chunks, entryFileName)
if (colocated.length === 0) return
// Each chunk keeps its own registration, so the entry file registers them before the entry.
const prefix = colocated.map(file => `${chunks[file]!.code.replace(CHUNK_SOURCEMAP_COMMENT, '')}\n`).join('')
entry.code = prefix + entry.code
// The moved chunks have no mappings; the entry's own lines move down by the inserted line count.
const shift = ';'.repeat(prefix.split('\n').length - 1)
if (entry.map !== null) entry.map.mappings = shift + entry.map.mappings
const mapAsset = bundle[`${entryFileName}.map`]
if (mapAsset?.type === 'asset' && typeof mapAsset.source === 'string') {
const map = JSON.parse(mapAsset.source) as { mappings: string }
map.mappings = shift + map.mappings
mapAsset.source = JSON.stringify(map)
}
for (const file of colocated) {
delete bundle[file]
delete bundle[`${file}.map`]
}
},
},
async writeBundle(outputOptions, bundle) {
const entry = Object.values(bundle).find(output => output.type === 'chunk' && output.isEntry)
if (entry === undefined || outputOptions.dir === undefined) return
@@ -966,6 +1060,7 @@ function clientConfig(
? packageRequire.resolve(source)
: importer === undefined ? source : sourceAssetPath(source, importer)
const styleMarker = `/*__dshChunkStyles_${randomBytes(16).toString('hex')}__*/`
const entryFileName = dualClient ? 'client.browser.js' : 'client.js'
return {
name: `${id}/client`,
entry: { client: entry },
@@ -1042,7 +1137,7 @@ function clientConfig(
+ '(type-only imports are erased and never reach this gate)',
)
},
}, tscSourceMapPlugin(), asyncChunkRequirePlugin(), isolation.plugin, {
}, tscSourceMapPlugin(), asyncChunkRequirePlugin(entryFileName), isolation.plugin, {
name: 'dsh-client-style-factory',
renderChunk(code, chunk) {
const marker = code.indexOf(styleMarker)
@@ -1132,7 +1227,7 @@ function clientConfig(
},
}, assets.plugin],
outputOptions: {
entryFileNames: dualClient ? 'client.browser.js' : 'client.js',
entryFileNames: entryFileName,
// The imported source basename becomes the published chunk name; package
// files lists and artifact tests pin every intentional chunk.
chunkFileNames: dualClient ? 'client.browser.[name].js' : 'client.[name].js',
@@ -1145,7 +1240,11 @@ function clientConfig(
isolation.sourcePath(source, mapPath)
return browserSourcePath(source, mapPath)
},
banner: chunk => `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}factory: (require) => {`,
banner: (chunk) => {
const deps = localImports(chunk).map(file => `./${file}`)
return `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, ${chunk.isEntry ? '' : `chunk: ${JSON.stringify(chunk.fileName)}, `}`
+ `${deps.length === 0 ? '' : `deps: ${JSON.stringify(deps)}, `}factory: (require) => {`
},
postBanner: (chunk) => {
const prefix = clientBanner?.(chunk.fileName)
return prefix === undefined ? '' : `${prefix}\n`
@@ -15,8 +15,8 @@
en: 4e53164159b5ce41
zh: 89582dc0294d0776
/deepseek-ai-dsh-experimental-webworker-packer/use-this-package:
en: c38e1dfbbe16d758
zh: c6a212da825ecd05
en: cfc34e955bec73b3
zh: 1811c884d03625cf
/deepseek-ai-dsh-experimental-webworker-packer/model-experience:
en: e16b355530dadc1c
zh: 8488e03b253b7b33
@@ -32,7 +32,7 @@ The pack is a three-layer standard stack:
1. **Roster** — the shipped profile template's bundles and every bundle in `OPTIONAL_BUNDLES` from [`dsh-official-bundles`](../../util/official-bundles/README.md), each resolved from the CLI manifest as the launcher resolves it, plus every package their patch files name (insert lists and grouped rows included), plus the preview profile patch's mock model package, plus the rows of every config tree the CLI declares in its `package.json` `dsh.configTrees`, materialized as a Node-style dependency closure. External peer edges never bind the worker; workspace peers stay on the chain. The CLI manifest itself enters the image alone at `node_modules/@deepseek-ai/dsh/package.json`, as the worker's bundle resolution anchor; the manifest records its name and the profile.
2. **Publish view** — each workspace or vendored package contributes its built npm slice (`files` through picomatch) without source or workspace `dist/`. External packages retain published JavaScript under both `src/` and `dist/` because their `main` or `exports` may point there; only generic test, map, declaration, and archive exclusions apply.
3. **Reachability sweep** — the runtime loader's own resolution walks from every non-wildcard workspace runtime export plus the worker assembly's seeds (`IMAGE_ENTRY_SEEDS`), lowering each reached module to the wrapper contract at pack time. Declaration-only condition trees do not seed the sweep; runtime requests for those exports still fail. The transform reports statically named imports, re-exports, and dynamic imports; calls through `require`; and module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named import from `node:module` or `module`, including an import alias. Page assets (`lib/client.js` behind `./client` exports) ship verbatim; an unresolvable request from our own code fails the pack, third-party ones are tolerated to fail loud at require time.
4. **Lazy chunks** — every page chunk a page asset requests as a literal `require.async("./client.<name>.js")`, the only form the dynamic Client build emits, leaves the base image unless a `./client` export names it. Each becomes its own deterministic archive named `lazy/<sha256 of the archive>.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack.
4. **Lazy chunks** — every page chunk a page asset requests as a literal `require.async("./client.<name>.js")`, or names in that call's `{ deps: [...] }` prefetch hint, the only forms the dynamic Client build emits, leaves the base image unless a `./client` export names it. Each becomes its own deterministic archive named `lazy/<sha256 of the archive>.tar.gz` beside the base image, and the manifest registers its path, size, and archive for the worker's lazy filesystem. A request for a chunk the package does not publish fails the pack.
`repository.ts` owns the repo-shaped inputs (workspace scan of `vendor/`, `packages/`, `native/system/packages/`, and `apps/`; the profile roster through the shipped templates and optional-bundle list of `dsh-official-bundles` and app-boot's bundle patch readers; the CLI manifest as the installation; the home patch, which sets the runtime's `PLATFORM_ENTRY_CONFIG` fields over each named row's config composed from the template's bundle layers; the preview profile patch, which inserts the keyless [`llm-mock`](../llm-mock/README.md) row, starts new Agents on its `mock` model, and sets `credentialOnboarding: false` on `ui-settings-models` so the first-run API-key prompt stays closed); `pack.ts` owns none of them, so the same library packs a different tree by being called differently. The native scan makes the Landlock entry package an ordinary published-view dependency while its executable remains a Worker platform implementation. The CLI is `dsh-pack-vfs-image --out <file> [--profile web]`; it writes the lazy archives beside the base image, and `apps/web`'s `build:preview` runs it after the preview shell build.
@@ -32,7 +32,7 @@ VFS 镜像打包器:把一份随附 profile 的 bundle 和安装提供的 opti
1. **Roster**——随附 profile 模板的 bundle 和 [`dsh-official-bundles`](../../util/official-bundles/README.zh.md) `OPTIONAL_BUNDLES` 中的每个 bundle(各自按启动器的方式从 CLI manifest 解析),加上它们 patch 文件点名的每个包(含 insert 列表与分组行),再加上 preview profile patch 中的 mock 模型包,再加上 CLI(命令行界面)在 `package.json` `dsh.configTrees` 里声明的每棵配置树的行,按 Node 式依赖闭包物化。外部 peer 边绝不会绑定到 worker,workspace peer 保留在链上。CLI manifest 本身单独进入镜像,位于 `node_modules/@deepseek-ai/dsh/package.json`,作为 worker 解析 bundle 的锚点;manifest 记录它的名称和 profile。
2. **发布视图**——每个 workspace 或 vendored 包贡献其构建后的 npm 切片(`files` 走 picomatch),不带源码和 workspace `dist/`。外部包的 `main` 或 `exports` 可能指向 `src/` 或 `dist/`,因此两处发布 JavaScript 都会保留,只应用通用的测试、map、声明与归档排除规则。
3. **可达性 sweep**——用运行时加载器自己的解析, 从全部不含通配符的 workspace 运行时导出加 worker 装配种子 (`IMAGE_ENTRY_SEEDS`) 出发, 打包时把每个可达模块转换为符合包装层约定的形式. 仅含类型声明的条件树不作为扫描入口; 运行时代码请求这些导出仍会失败. 该转换会报告名称可静态确定的 import、re-export 与动态 import、经 `require` 发起的调用, 以及通过 `node:module` 或 `module` 具名导入 (含导入别名) 在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用. 页面资产 (`./client` 导出背后的 `lib/client.js`) 原样直发; 自家代码的不可解析请求会让打包失败, 第三方不可解析请求则允许延后到 require 时明确失败.
4. **懒加载 chunk**——页面资产以字面量 `require.async("./client.<name>.js")`(动态 Client 构建产出的唯一形式)请求的每个页面 chunk,除非被 `./client` 导出点名,否则移出基础镜像。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。
4. **懒加载 chunk**——页面资产以字面量 `require.async("./client.<name>.js")` 请求、或在该调用的 `{ deps: [...] }` 预取提示中列出的每个页面 chunk(这是动态 Client 构建产出的仅有形式),除非被 `./client` 导出点名,否则移出基础镜像。每个 chunk 成为基础镜像旁的一个独立确定性归档,命名为 `lazy/<归档的 sha256>.tar.gz`;manifest 为 worker 的懒加载文件系统登记其路径、大小和归档。请求包未发布的 chunk 会让打包失败。
`repository.ts` 拥有仓库形态输入(`vendor/`、`packages/`、`native/system/packages/` 与 `apps/` 的 workspace 扫描;经 `dsh-official-bundles` 的随附模板、optional bundle 列表和 app-boot 的 bundle patch 读取器得出 profile roster;以 CLI manifest 作为安装清单;home patch 在模板各 bundle 层合成出的行配置之上设置运行时 `PLATFORM_ENTRY_CONFIG` 字段;preview profile patch 插入无需密钥的 [`llm-mock`](../llm-mock/README.zh.md) 行,让新 Agent 使用其 `mock` 模型启动,并在 `ui-settings-models` 上设置 `credentialOnboarding: false`,使首次运行的 API 密钥提示保持关闭);`pack.ts` 一概不拥有,同一库换参即可打另一棵树。Native 扫描使 Landlock 入口包成为普通发布视图依赖,其可执行文件仍由 Worker 平台实现。CLI 为 `dsh-pack-vfs-image --out <file> [--profile web]`;它把懒加载归档写在基础镜像旁,`apps/web` 的 `build:preview` 在预览壳构建后运行它。
@@ -47,6 +47,7 @@
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-client-modules": "workspace:*",
"@types/picomatch": "^4.0.3"
},
"peerDependencies": {
@@ -30,6 +30,7 @@ import {
import picomatch from 'picomatch'
import { parseEntryYaml, stringifyEntryYaml, type PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import { PROFILE_PATCH_FILENAME, PROFILES_DIR } from '@deepseek-ai/dsh-app-boot'
import { CLIENT_CHUNK_FILE } from '@deepseek-ai/dsh-client-modules/src/chunks.ts'
import { WRAPPER_CONTRACT, type ImageFiles, type TransformOutcome } from './transform-image.ts'
import { EXCLUDE, EXCLUDE_WORKSPACE, IMAGE_ENTRY_SEEDS, PAGE_ASSETS } from './rules.ts'
@@ -594,11 +595,19 @@ function materialize(
}
/**
* Request form the dynamic Client build emits for a package-local chunk: a
* literal `require.async("./client.<name>.js")`, served by the Host on demand.
* The minifier may print the literal with any quote, including a template without substitutions.
* One relative string literal. The minifier may print it with any quote,
* including a template without substitutions.
*/
const CHUNK_REQUEST = /\brequire\.async\(\s*(["'`])(\.\/client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\1\s*\)/g
const RELATIVE_LITERAL = /(["'`])\.\/([^"'`]+)\1/g
/**
* Request form the dynamic Client build emits for a package-local chunk: a
* literal `require.async("./client.<name>.js")`, served by the Host on demand,
* optionally followed by `{ deps: ["./client.<name>.js", …] }`, a prefetch hint
* naming the other chunks the request downloads in parallel. Only names that
* match `CLIENT_CHUNK_FILE` are chunk requests.
*/
const CHUNK_REQUEST = new RegExp(String.raw`\brequire\.async\(\s*${RELATIVE_LITERAL.source}\s*(?:,\s*\{\s*deps\s*:\s*\[([^\]]*)\]\s*\}\s*)?\)`, 'g')
/**
* Image paths every materialized package's `./client` export names, under any
@@ -624,7 +633,7 @@ function clientEntriesOf(files: ImageFiles, packages: Iterable<string>): Set<str
}
/**
* Page chunks requested only through `require.async`, in path order.
* Page chunks requested only through `require.async` or its prefetch hints, in path order.
* @param files - Image entries after the sweep.
* @param eager - Eager Client entry paths, never lazy.
* @returns Image paths to move into lazy archives.
@@ -637,12 +646,15 @@ function lazyChunksOf(files: ImageFiles, eager: ReadonlySet<string>): string[] {
if (!pageAsset(name)) continue
const directory = name.slice(0, name.lastIndexOf('/'))
for (const match of decoder.decode(bytes).matchAll(CHUNK_REQUEST)) {
const request = match[2] as string
const target = `${directory}/${request.slice(2)}`
if (files[target] === undefined) {
throw new Error(`vfs image: ${name} requests chunk "${request}", which the package does not publish`)
const hinted = [...(match[3] ?? '').matchAll(RELATIVE_LITERAL)].map(literal => literal[2] as string)
for (const chunk of [match[2] as string, ...hinted]) {
if (!CLIENT_CHUNK_FILE.test(chunk)) continue
const target = `${directory}/${chunk}`
if (files[target] === undefined) {
throw new Error(`vfs image: ${name} requests chunk "./${chunk}", which the package does not publish`)
}
if (!eager.has(target)) lazy.add(target)
}
if (!eager.has(target)) lazy.add(target)
}
}
return [...lazy].sort()
@@ -1,8 +1,8 @@
/**
* Page chunks reached only through `require.async("./client.<name>.js")` leave
* the base image: each one becomes its own deterministic, content-addressed
* archive, and the manifest registers its path and size for the Worker's lazy
* filesystem. Entries, eagerly loaded `./client` targets, and unreferenced
* Page chunks reached only through `require.async("./client.<name>.js")`, or
* named by its `{ deps }` prefetch hint, leave the base image: each one becomes
* its own deterministic, content-addressed archive, and the manifest registers
* its path and size for the Worker's lazy filesystem. Entries, eagerly loaded `./client` targets, and unreferenced
* siblings stay in the base image.
*/
import { createHash } from 'node:crypto'
@@ -89,6 +89,26 @@ it('refuses a chunk request whose file the package does not publish', (test) =>
expect(() => packVfsImage(options)).toThrow(/client\.browser\.js requests chunk "\.\/client\.missing\.js"/)
})
it('moves the chunks a prefetch hint names, in the forms the minifier prints', (test) => {
const result = packVfsImage(fixture(test, {
'client.browser.js': [
'module.exports = {',
' view: () => require.async(`./client.view.js`,{deps:[`./client.shared.js`,\'./client.deep.js\']}),',
' spaced: () => require.async("./client.spaced.js", { deps: ["./client.deep.js"] }),',
'}',
].join('\n'),
'client.view.js': 'module.exports = "view"',
'client.spaced.js': 'module.exports = "spaced"',
'client.shared.js': 'module.exports = "shared"',
'client.deep.js': 'module.exports = "deep"',
}))
expect(result.lazyArchives.map(archive => archive.files)).toEqual(
['deep', 'shared', 'spaced', 'view'].map(name => [`${PREFIX}/client.${name}.js`]),
)
const hinted = fixture(test, { 'client.browser.js': 'module.exports = () => require.async("./client.view.js", { deps: ["./client.gone.js"] })', 'client.view.js': '' })
expect(() => packVfsImage(hinted)).toThrow(/client\.browser\.js requests chunk "\.\/client\.gone\.js"/)
})
it('keeps a ./client export target in the base image even when a chunk requests it', (test) => {
const result = packVfsImage(fixture(test, {
'client.browser.js': 'module.exports = { load: () => require.async("./client.pdf.js") }',
@@ -17,6 +17,9 @@
{
"path": "../../boot/app-boot"
},
{
"path": "../../client/modules"
},
{
"path": "../../util/official-bundles"
},
@@ -22,14 +22,26 @@ export type ClientModuleMetaFactory = () => ClientModuleMeta
/** Dependency resolver supplied to a JavaScript module factory. */
export interface ClientBundleRequire {
/** Resolve a previously arrived shared module synchronously. */
/** Resolve a previously arrived shared module, or a registered chunk of the owning package (`./client.<name>.js`), synchronously. */
(specifier: string): unknown
/** Load a module or an owning package's relative chunk using the existing module request semantics. */
async(specifier: string): Promise<unknown>
/**
* Load a module or an owning package's relative chunk using the existing module request semantics.
* `options` applies only to a relative chunk request; another package's request ignores it.
*/
async(specifier: string, options?: ClientAsyncRequireOptions): Promise<unknown>
/** Resolve a package asset reference. */
asset(reference: string): string
}
/** Options of one asynchronous package-local chunk request. */
export interface ClientAsyncRequireOptions {
/**
* Chunks of the owning package (`./client.<name>.js`) to download in parallel with the requested chunk. The list
* only saves round trips: the requested chunk's registration `deps` still decide what must arrive before it runs.
*/
readonly deps?: readonly string[]
}
/** Materialize JavaScript exports without producing stylesheet resources. */
export type ClientModuleFactory = (require: ClientBundleRequire) => Record<string, unknown>
@@ -37,6 +49,11 @@ export type ClientModuleFactory = (require: ClientBundleRequire) => Record<strin
export interface DshClientModuleManifest {
readonly id: string
readonly chunk?: string
/**
* Chunks of the same package (`./client.<name>.js`) that the factory requires synchronously. The module system
* registers each of them, and their own `deps`, before it runs the factory.
*/
readonly deps?: readonly string[]
readonly factory: ClientModuleFactory
readonly meta?: ClientModuleMetaFactory
}
@@ -8,6 +8,7 @@ export type {
ClientModuleStyleContext,
ClientModuleMeta,
ClientModuleMetaFactory,
ClientAsyncRequireOptions,
ClientBundleRequire,
ClientModuleFactory,
DshClientModuleManifest,
+3
View File
@@ -13975,6 +13975,9 @@ importers:
'@deepseek-ai/cordis':
specifier: workspace:~
version: link:../../../vendor/cordis
'@deepseek-ai/dsh-client-modules':
specifier: workspace:*
version: link:../../client/modules
'@types/picomatch':
specifier: ^4.0.3
version: 4.0.3
@@ -0,0 +1,314 @@
/**
* Package-local chunk dependencies end to end: the dynamic Client preset builds a fixture package whose entry and
* lazy chunks share modules and a CommonJS dependency, and the real module system loads the written artifacts.
*/
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runInNewContext } from 'node:vm'
import { build } from 'tsdown'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { clientBundle } from '../packages/client/tsdown.client.ts'
import {
createClientModuleSystem,
type ClientBundleRegistration, type ClientModuleLoader, type ClientModuleLoaderTarget,
} from '../packages/client/modules/src/client/index.ts'
const PACKAGE = '@deepseek-ai/dsh-client-chunk-fixture'
const BATCH_URL = `plugins/??${PACKAGE}/client.js&rev=app`
const entryUrl = (rev = '0'): string => `plugins/??${PACKAGE}/client.js&rev=${rev}`
const chunkUrl = (fileName: string, rev = '0'): string => `plugins/${PACKAGE}/${fileName}?rev=${rev}`
/**
* Module graph: the entry shares `shared.js` with `a.js` and also imports it dynamically; `a.js` and `b.js` share
* `common.js`, which imports `deep.js`; `c.js` imports `deep.js` alone. The entry and `b.js` each import their own
* CommonJS package, so Rolldown's helper becomes a runtime chunk that both require.
*/
const SOURCES: Readonly<Record<string, string>> = {
'index.js': [
'import { shared } from "./shared.js"',
'import { marker } from "cjs-entry"',
'export const value = [shared, marker]',
'export const loadA = () => import("./a.js")',
'export const loadB = () => import("./b.js")',
'export const loadC = () => import("./c.js")',
'export const loadShared = () => import("./shared.js")',
].join('\n'),
'shared.js': 'export const shared = "shared"',
'common.js': 'import { deep } from "./deep.js"\nexport const common = ["common", deep]',
'deep.js': 'export const deep = "deep"',
'a.js': 'import { shared } from "./shared.js"\nimport { common } from "./common.js"\nexport const a = ["a", shared, common]',
'b.js': 'import { common } from "./common.js"\nimport { marker } from "cjs-b"\nexport const b = ["b", common, marker]',
'c.js': 'import { deep } from "./deep.js"\nexport const c = ["c", deep]',
}
/** Chunk group behind each lazy import, without the chunks the entry file carries. */
const LAZY = {
a: { file: 'client.a.js', hint: ['./client.deep.js', './client.common.js'], exports: { a: ['a', 'shared', ['common', 'deep']] } },
b: { file: 'client.b.js', hint: ['./client.deep.js', './client.common.js'], exports: { b: ['b', ['common', 'deep'], 'cjs-b'] } },
c: { file: 'client.c.js', hint: ['./client.deep.js'], exports: { c: ['c', 'deep'] } },
} as const
/** Exports of the fixture entry. */
interface FixtureEntry {
value: unknown
loadA(): Promise<unknown>
loadB(): Promise<unknown>
loadC(): Promise<unknown>
loadShared(): Promise<unknown>
}
let root: string
/** Written browser artifacts by file name. */
const artifacts = new Map<string, string>()
/** Mappings of the entry chunk's in-memory source map, which build API consumers read instead of the written file. */
let entryMappings: string | undefined
beforeAll(async () => {
root = mkdtempSync(join(tmpdir(), 'dsh-client-chunk-deps-'))
const sourceDir = join(root, 'lib/types/client')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(root, 'package.json'), JSON.stringify({ name: PACKAGE, type: 'module' }))
for (const [file, source] of Object.entries(SOURCES)) writeFileSync(join(sourceDir, file), `${source}\n`)
for (const name of ['cjs-entry', 'cjs-b']) {
const directory = join(root, 'node_modules', name)
mkdirSync(directory, { recursive: true })
writeFileSync(join(directory, 'package.json'), JSON.stringify({ name, main: 'index.js' }))
writeFileSync(join(directory, 'index.js'), `exports.marker = ${JSON.stringify(name)}\n`)
}
const config = clientBundle(root, ['lib/types/index.js'])({ env: { DSH_BUILD_FACE: 'client' } })
.find(candidate => candidate.platform === 'browser')
if (config === undefined) throw new Error('client config missing')
const builds = await build({ ...config, cwd: root, config: false, tsconfig: false, clean: false, exports: false, report: false, logLevel: 'silent' })
for (const bundle of builds) {
for (const output of bundle.chunks) if (output.type === 'chunk' && output.isEntry) entryMappings = output.map?.mappings
await bundle[Symbol.asyncDispose]()
}
for (const file of readdirSync(join(root, 'lib'))) {
if (file !== 'types') artifacts.set(file, readFileSync(join(root, 'lib', file), 'utf8'))
}
})
afterAll(() => { rmSync(root, { recursive: true, force: true }) })
function artifact(file: string): string {
const text = artifacts.get(file)
if (text === undefined) throw new Error(`fixture artifact missing: ${file}`)
return text
}
/** Registrations one script performs, in order. */
function registrationsOf(code: string): ClientBundleRegistration[] {
const registrations: ClientBundleRegistration[] = []
const load = (registration: ClientBundleRegistration): void => { registrations.push(registration) }
runInNewContext(code, { window: { __ModuleLoader__: { load } } })
return registrations
}
/** Package-local `require.async` calls of one script; the minifier chooses the quotes. */
function asyncRequests(code: string): { target: string; deps?: string[] }[] {
return [...code.matchAll(/require\.async\((["'`])([^"'`]+)\1(?:,\{deps:\[([^\]]*)\]\})?\)/gu)].map(match => ({
target: match[2]!,
...(match[3] === undefined ? {} : { deps: [...match[3].matchAll(/["'`]([^"'`]+)["'`]/gu)].map(item => item[1]!) }),
}))
}
/** Remove every prefetch hint, as a builder that writes only registration `deps` would. */
const withoutHints = (code: string): string => code.replace(/,\{deps:\[[^\]]*\]\}\)/gu, ')')
interface Harness {
system: ClientModuleLoader
target: ClientModuleLoaderTarget
fetched: string[]
}
/**
* Real module system over the written artifacts. Combo URLs serve `client.js`; chunk URLs serve their file.
* `scripts` overrides the text served at a URL; `pending` scripts run before the system exists, as
* parser-preloaded scripts do.
*/
function boot(options: {
scripts?: Readonly<Record<string, string>>
pending?: readonly string[]
failing?: readonly string[]
} = {}): Harness {
const fetched: string[] = []
const target: ClientModuleLoaderTarget = {
mode: 'queue',
pendingQueue: [],
load(registration) { target.pendingQueue.push(registration) },
create() { throw new Error('the harness creates its module system directly') },
}
const run = (code: string): void => { runInNewContext(code, { window: { __ModuleLoader__: target } }) }
for (const code of options.pending ?? []) run(code)
const system = createClientModuleSystem(target, { id: '@deepseek-ai/dsh-client-modules', exports: {} }, {
boot: {
rev: 'graph',
entries: [{ id: PACKAGE, url: entryUrl(), rev: '0' }],
batches: [{ phase: 'application', url: BATCH_URL, rev: 'app', entries: [PACKAGE] }],
},
staticModules: [],
loadBundle: async (url) => {
fetched.push(url)
if (options.failing?.includes(url) === true) throw new Error(`bundle script ${url} failed to load`)
const file = url.includes('/??') ? 'client.js' : /\/([^/?]+)\?rev=/u.exec(url)?.[1] ?? url
run(options.scripts?.[url] ?? artifact(file))
},
})
return { system, target, fetched }
}
describe('package-local chunk dependency build', () => {
it('moves the chunks the entry requires into the entry file and deletes their own files', () => {
expect([...artifacts.keys()].sort()).toEqual([
'client.a.js', 'client.a.js.map', 'client.b.js', 'client.b.js.map', 'client.c.js', 'client.c.js.map',
'client.common.js', 'client.common.js.map', 'client.deep.js', 'client.deep.js.map', 'client.js', 'client.js.map',
])
expect(existsSync(join(root, 'lib/client.shared.js'))).toBe(false)
expect(existsSync(join(root, 'lib/client.rolldown-runtime.js.map'))).toBe(false)
expect(registrationsOf(artifact('client.js')).map(({ chunk, deps }) => ({ chunk, deps }))).toEqual([
{ chunk: 'client.rolldown-runtime.js', deps: undefined },
// Rolldown's namespace helper for the dynamic import makes the shared chunk require the runtime chunk.
{ chunk: 'client.shared.js', deps: ['./client.rolldown-runtime.js'] },
{ chunk: undefined, deps: ['./client.rolldown-runtime.js', './client.shared.js'] },
])
})
it('writes each chunk registration with its direct synchronous chunk requires', () => {
const depsOf = (file: string): readonly string[] | undefined => registrationsOf(artifact(file))[0]?.deps
expect(depsOf('client.a.js')).toEqual(['./client.shared.js', './client.common.js'])
expect(depsOf('client.b.js')).toEqual(['./client.rolldown-runtime.js', './client.common.js'])
expect(depsOf('client.common.js')).toEqual(['./client.deep.js'])
expect(depsOf('client.c.js')).toEqual(['./client.deep.js'])
expect(Object.hasOwn(registrationsOf(artifact('client.deep.js'))[0]!, 'deps')).toBe(false)
})
it('hints every lazy chunk group except the chunks the entry file carries', () => {
expect(asyncRequests(artifact('client.js'))).toEqual(Object.values(LAZY).map(({ file, hint }) => ({ target: `./${file}`, deps: hint })))
expect(asyncRequests(artifact('client.c.js'))).toEqual([])
})
it('keeps a dynamic import of a chunk the entry file carries as a synchronous require', () => {
expect(artifact('client.js')).toMatch(/Promise\.resolve\(\)\.then\(\(\)\s*=>\s*require\((["'`])\.\/client\.shared\.js\1\)\)/u)
})
it('shifts the entry source map past the moved chunks', () => {
const lines = artifact('client.js').split('\n')
const map = JSON.parse(artifact('client.js.map')) as { mappings: string }
expect(entryMappings).toBe(map.mappings)
const firstMapped = /^;*/u.exec(map.mappings)![0].length
expect(registrationsOf(lines[firstMapped]!).map(registration => registration.chunk)).toEqual([undefined])
expect(registrationsOf(lines.slice(0, firstMapped).join('\n')).map(registration => registration.chunk))
.toEqual(['client.rolldown-runtime.js', 'client.shared.js'])
})
})
describe('package entry requests', () => {
it.each([
['statically', 'import { value } from "./index.js"\nexport const late = value\n'],
['dynamically', 'export const late = () => import("./index.js")\n'],
])('rejects a chunk that imports the package entry %s', async (_form, late) => {
const entryRoot = mkdtempSync(join(tmpdir(), 'dsh-client-entry-import-'))
try {
const sourceDir = join(entryRoot, 'lib/types/client')
mkdirSync(sourceDir, { recursive: true })
writeFileSync(join(entryRoot, 'package.json'), JSON.stringify({ name: PACKAGE, type: 'module' }))
writeFileSync(join(sourceDir, 'index.js'), 'export const value = "entry"\nexport const load = () => import("./late.js")\n')
writeFileSync(join(sourceDir, 'late.js'), late)
const config = clientBundle(entryRoot, ['lib/types/index.js'])({ env: { DSH_BUILD_FACE: 'client' } })
.find(candidate => candidate.platform === 'browser')
if (config === undefined) throw new Error('client config missing')
await expect(build({
...config, cwd: entryRoot, config: false, tsconfig: false,
write: false, clean: false, exports: false, report: false, logLevel: 'silent',
})).rejects.toThrow('client.late.js imports the package entry client.js;')
} finally {
rmSync(entryRoot, { recursive: true, force: true })
}
})
})
describe('package-local chunk dependency runtime', () => {
it('runs the entry from one script that also registers its chunks', async () => {
const { system, fetched } = boot()
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
expect(entry.value).toEqual(['shared', 'cjs-entry'])
await expect(entry.loadShared()).resolves.toMatchObject({ shared: 'shared' })
expect(fetched).toEqual([BATCH_URL])
})
it('downloads a hinted chunk group in one round', async () => {
const { system, fetched } = boot()
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
const loaded = entry.loadA()
expect(fetched).toEqual([BATCH_URL, chunkUrl(LAZY.a.file), ...LAZY.a.hint.map(spec => chunkUrl(spec.slice(2)))])
await expect(loaded).resolves.toEqual(LAZY.a.exports)
await expect(entry.loadB()).resolves.toEqual(LAZY.b.exports)
await expect(entry.loadC()).resolves.toEqual(LAZY.c.exports)
expect(fetched.slice(4)).toEqual([chunkUrl(LAZY.b.file), chunkUrl(LAZY.c.file)])
})
it('loads a chunk group through registration deps alone, one level per round', async () => {
const { system, fetched } = boot({ scripts: { [BATCH_URL]: withoutHints(artifact('client.js')) } })
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
const loaded = entry.loadA()
expect(fetched).toEqual([BATCH_URL, chunkUrl('client.a.js')])
await expect(loaded).resolves.toEqual(LAZY.a.exports)
expect(fetched).toEqual([BATCH_URL, chunkUrl('client.a.js'), chunkUrl('client.common.js'), chunkUrl('client.deep.js')])
})
it('names the dependency chain when a required chunk fails to download', async () => {
const { system } = boot({
scripts: { [BATCH_URL]: withoutHints(artifact('client.js')) },
failing: [chunkUrl('client.deep.js')],
})
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
await expect(entry.loadA()).rejects.toThrow(
`"${PACKAGE}/client.a.js" not loaded because dependency "${PACKAGE}/client.common.js" failed: `
+ `client-modules: "${PACKAGE}/client.common.js" not loaded because dependency "${PACKAGE}/client.deep.js" failed`,
)
})
it('names the dependency chain when a hinted chunk fails to download', async () => {
const { system } = boot({ failing: [chunkUrl('client.deep.js')] })
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
const failure = await entry.loadA().then(() => undefined, (error: unknown) => error)
expect((failure as Error).message).toContain(
`client-modules: "${PACKAGE}/client.a.js" not loaded because dependency "${PACKAGE}/client.common.js" failed: `
+ `client-modules: "${PACKAGE}/client.common.js" not loaded because dependency "${PACKAGE}/client.deep.js" failed`,
)
expect(((failure as Error).cause as Error).message).toContain(`"${PACKAGE}/client.common.js" not loaded`)
})
it('rejects a synchronous chunk request before the chunk is registered', async () => {
const { system, target } = boot()
runInNewContext(artifact('client.a.js'), { window: { __ModuleLoader__: target } })
await expect(system.import(`${PACKAGE}/client.a.js`, '', {}))
.rejects.toThrow(`"${PACKAGE}" required chunk client.shared.js before it was registered`)
})
it('completes the chunks of an entry that a preloaded script registered without them', async () => {
const parts = artifact('client.js').split(/\n(?=window\.__ModuleLoader__\.load\()/u).filter(part => part.trim() !== '')
const scripts: Record<string, string> = {}
let entryScript: string | undefined
for (const part of parts) {
const chunk = registrationsOf(part)[0]?.chunk
if (chunk === undefined) entryScript = part
else scripts[chunkUrl(chunk)] = part
}
const { system, fetched } = boot({ scripts, pending: [entryScript!] })
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
expect(entry.value).toEqual(['shared', 'cjs-entry'])
expect(fetched).toEqual([chunkUrl('client.rolldown-runtime.js'), chunkUrl('client.shared.js')])
})
it('re-executes the entry file after invalidation without a duplicate registration', async () => {
const { system, fetched } = boot()
await system.import(PACKAGE, '', {})
system.invalidate(PACKAGE, 'next')
const entry = await system.import(PACKAGE, '', {}) as FixtureEntry
expect(entry.value).toEqual(['shared', 'cjs-entry'])
await expect(entry.loadC()).resolves.toEqual(LAZY.c.exports)
expect(fetched).toEqual([BATCH_URL, entryUrl('next'), chunkUrl('client.c.js', 'next'), chunkUrl('client.deep.js', 'next')])
})
})
+1 -1
View File
@@ -140,7 +140,7 @@ function browserPlugins(packageDir: string): (name: PluginName) => BundlePlugin
return name => ({
...configPlugin(client, name),
stylesheetBundle(code, id) {
const chunk = { isEntry: true, fileName: 'client.js', modules: { [id]: {} } }
const chunk = { isEntry: true, fileName: 'client.js', imports: [] as string[], modules: { [id]: {} } }
const body = code.replace(/^export default (.*);$/mu, 'module.exports = $1;').replace(/^export \{\};$/mu, '')
const prefix = banner(chunk as Rolldown.RenderedChunk)
if (typeof prefix !== 'string') throw new Error('expected a synchronous manifest banner')
+1 -1
View File
@@ -66,7 +66,7 @@ describe('client bundle build faces', () => {
if (typeof outputOptions !== 'object' || typeof outputOptions.banner !== 'function') {
throw new Error('client banner missing')
}
expect(outputOptions.banner({ isEntry: true, fileName: 'client.js' } as Rolldown.RenderedChunk))
expect(outputOptions.banner({ isEntry: true, fileName: 'client.js', imports: [] as string[] } as Rolldown.RenderedChunk))
.toBe('window.__ModuleLoader__.load({ id: "@deepseek-ai/dsh-client-fixture", factory: (require) => {')
})
+46
View File
@@ -180,4 +180,50 @@ describe('publint package runner', () => {
expect(result.stderr).toContain('imports "./missing.js"')
expect(result.stderr).toContain('imports "./missing.css"')
})
it('accepts a chunk request that the package entry file registers', async ({ signal }) => {
const result = await run(fixture({ files: {
'lib/client.js': [
clientRegistration('chunk:`client.shared.js`,', 'return {shared:true}'),
clientRegistration('deps:[`./client.shared.js`],', 'return require("./client.shared.js")'),
].join('\n'),
'lib/client.lazy.js': clientRegistration('chunk:\'client.lazy.js\',deps:["./client.shared.js"],', 'return require("./client.shared.js")'),
} }), signal)
expect(result.exitCode, result.stderr).toBe(0)
})
it('rejects a chunk request that neither a published file nor an entry registration satisfies', async ({ signal }) => {
const result = await run(fixture({ files: {
'lib/client.js': clientRegistration('', 'return [require("./client.missing.js"), require("./client.lazy-only.js")]'),
// A chunk script's own registrations are not the entry file's, so they satisfy nothing.
'lib/client.lazy.js': [
clientRegistration('chunk:`client.lazy.js`,', 'return {}'),
clientRegistration('chunk:`client.lazy-only.js`,', 'return {}'),
].join('\n'),
} }), signal)
expect(result.exitCode).toBe(1)
expect(result.stderr).toContain('imports "./client.missing.js"')
expect(result.stderr).toContain('imports "./client.lazy-only.js"')
})
it('checks an entry-carried chunk outside a registered factory like any relative request', async ({ signal }) => {
const result = await run(fixture({
// Node resolves an ESM import itself, so the entry file's registration does not satisfy it.
indexSource: "import './client.shared.js'\nexport const probe = true\n",
files: { 'lib/client.js': [
clientRegistration('chunk:`client.shared.js`,', 'return {shared:true}'),
clientRegistration('', 'return require("./client.shared.js")'),
'require("./client.shared.js")',
].join('\n') },
}), signal)
expect(result.exitCode).toBe(1)
expect(result.stderr).toContain('lib/index.js:1 imports "./client.shared.js"')
expect(result.stderr).toContain('lib/client.js:3 imports "./client.shared.js"')
expect(result.stderr).not.toContain('lib/client.js:2')
})
})
/** One Client module registration in the minified form the dynamic build emits. */
function clientRegistration(fields: string, body: string): string {
return `window.__ModuleLoader__.load({id:\`@deepseek-ai/dsh-probe\`,${fields}factory:require=>{${body}}});`
}
+98 -21
View File
@@ -11,6 +11,7 @@ import { parseArgs } from 'node:util'
import { publint, type Message, type PackFile } from 'publint'
import { formatMessage } from 'publint/utils'
import ts from 'typescript'
import { CLIENT_CHUNK_FILE } from '../packages/client/modules/src/chunks.ts'
import { defaultParallelism } from './parallelism.ts'
import { isBrowserBundleFormatFalsePositive } from './publint-browser-format.ts'
@@ -121,21 +122,53 @@ function addPath(path: string, paths: Set<string>): void {
interface RelativeImport {
specifier: string
line: number
/** Whether the request is a synchronous `require` inside the factory of a `__ModuleLoader__.load` registration. */
factoryRequire: boolean
}
/** Return relative imports whose targets are absent from the publication view. */
/** Relative module requests of one published script and the Client module factories it registers. */
interface ScriptRequests {
imports: RelativeImport[]
/** Whether the script registers a package entry: a `__ModuleLoader__.load` call without `chunk`. */
registersEntry: boolean
/** `chunk` file names the script registers through `__ModuleLoader__.load`. */
registeredChunks: string[]
}
/**
* Return relative imports whose targets are absent from the publication view. A synchronous
* `require("./client.<name>.js")` inside a registered module factory is also satisfied when a published script in the
* requester's directory registers the package entry and that chunk, because the Client build moves the chunks an
* entry requires into the entry file and deletes their own files. Every other relative request, such as an ESM
* `import` that Node resolves itself, still needs its published file.
*/
function publicationClosureViolations(target: PackageTarget, files: readonly PackFile[]): string[] {
const published = new Set(files.map(file => file.name))
const violations: string[] = []
const scripts = new Map<string, ScriptRequests>()
for (const file of files) {
if (!/\.(?:js|mjs|cjs)$/.test(file.name)) continue
const bytes = file.data instanceof ArrayBuffer ? new Uint8Array(file.data) : file.data
const source = typeof bytes === 'string' ? bytes : Buffer.from(bytes).toString('utf8')
for (const imported of relativeImports(file.name, source)) {
const resolved = posix.normalize(posix.join(posix.dirname(file.name), imported.specifier))
scripts.set(file.name, scriptRequests(file.name, source))
}
/** Chunks registered by entry scripts, by directory. */
const entryChunks = new Map<string, Set<string>>()
for (const [name, script] of scripts) {
if (!script.registersEntry) continue
const directory = posix.dirname(name)
const chunks = entryChunks.get(directory) ?? new Set<string>()
for (const chunk of script.registeredChunks) chunks.add(chunk)
entryChunks.set(directory, chunks)
}
const violations: string[] = []
for (const [name, script] of scripts) {
const directory = posix.dirname(name)
for (const imported of script.imports) {
const resolved = posix.normalize(posix.join(directory, imported.specifier))
if (resolutionCandidates(resolved).some(candidate => published.has(candidate))) continue
if (imported.factoryRequire && isEntryCarriedChunk(imported.specifier, entryChunks.get(directory))) continue
violations.push(
`${target.path}/${file.name.slice('package/'.length)}:${String(imported.line)}`
`${target.path}/${name.slice('package/'.length)}:${String(imported.line)}`
+ ` imports ${JSON.stringify(imported.specifier)}, but ${target.manifest.name ?? target.path}`
+ ` does not publish ${JSON.stringify(resolved.slice('package/'.length))}`,
)
@@ -144,6 +177,17 @@ function publicationClosureViolations(target: PackageTarget, files: readonly Pac
return violations
}
/**
* Whether a relative request names a package-local chunk that an entry script in the requester's directory registers.
* @param specifier - Relative module request.
* @param entryChunks - Chunk file names the entry scripts of that directory register.
* @returns True for a `./client.<name>.js` request whose chunk the entry file carries.
*/
function isEntryCarriedChunk(specifier: string, entryChunks: ReadonlySet<string> | undefined): boolean {
const chunk = specifier.slice('./'.length)
return specifier.startsWith('./') && CLIENT_CHUNK_FILE.test(chunk) && entryChunks?.has(chunk) === true
}
/** Paths a relative JavaScript module request can resolve to in a published package. */
function resolutionCandidates(target: string): string[] {
const base = target.replace(/\/+$/, '')
@@ -153,29 +197,62 @@ function resolutionCandidates(target: string): string[] {
]
}
/** Extract relative static imports, re-exports, dynamic imports, and requires. */
function relativeImports(file: string, sourceText: string): RelativeImport[] {
/**
* Extract relative static imports, re-exports, dynamic imports, and requires, and the Client module factories the
* script registers through `__ModuleLoader__.load({ id, chunk?, factory })`.
*/
function scriptRequests(file: string, sourceText: string): ScriptRequests {
const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, false, ts.ScriptKind.JS)
const imports: RelativeImport[] = []
const record = (node: ts.Node, literal: ts.Expression | undefined): void => {
const requests: ScriptRequests = { imports: [], registersEntry: false, registeredChunks: [] }
const record = (node: ts.Node, literal: ts.Expression | undefined, factoryRequire: boolean): void => {
if (literal === undefined || !ts.isStringLiteralLike(literal) || !literal.text.startsWith('.')) return
imports.push({
requests.imports.push({
specifier: literal.text,
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
factoryRequire,
})
}
const visit = (node: ts.Node): void => {
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
record(node, node.moduleSpecifier)
} else if (ts.isCallExpression(node)
&& (node.expression.kind === ts.SyntaxKind.ImportKeyword
|| ts.isIdentifier(node.expression) && node.expression.text === 'require')) {
record(node, node.arguments[0])
}
ts.forEachChild(node, visit)
const register = (registration: ts.ObjectLiteralExpression): void => {
const chunk = registration.properties.find((property): property is ts.PropertyAssignment =>
ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'chunk')
if (chunk === undefined) requests.registersEntry = true
else if (ts.isStringLiteralLike(chunk.initializer)) requests.registeredChunks.push(chunk.initializer.text)
}
visit(source)
return imports
/** @param inFactory - Whether the node lies inside the `factory` of a `__ModuleLoader__.load` registration. */
const visit = (node: ts.Node, inFactory: boolean): void => {
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
record(node, node.moduleSpecifier, false)
} else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
record(node, node.arguments[0], false)
} else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'require') {
record(node, node.arguments[0], inFactory)
} else if (ts.isCallExpression(node) && isModuleLoaderLoad(node.expression)) {
const registration = node.arguments[0]
if (registration !== undefined && ts.isObjectLiteralExpression(registration)) {
register(registration)
for (const property of registration.properties) visit(property, inFactory || isFactoryProperty(property))
return
}
}
ts.forEachChild(node, (child) => { visit(child, inFactory) })
}
visit(source, false)
return requests
}
/** Whether a registration member is its `factory`. */
function isFactoryProperty(property: ts.ObjectLiteralElementLike): boolean {
return (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property))
&& ts.isIdentifier(property.name) && property.name.text === 'factory'
}
/** Whether a callee is `__ModuleLoader__.load`, directly or as a `window` property. */
function isModuleLoaderLoad(callee: ts.Expression): boolean {
if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'load') return false
const loader = callee.expression
if (ts.isIdentifier(loader)) return loader.text === '__ModuleLoader__'
return ts.isPropertyAccessExpression(loader) && loader.name.text === '__ModuleLoader__'
&& ts.isIdentifier(loader.expression) && loader.expression.text === 'window'
}
async function runPublint(target: PackageTarget): Promise<PublintResult> {