@weapp-vite/hmr 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -0
- package/dist/index.d.mts +225 -0
- package/dist/index.mjs +470 -0
- package/package.json +43 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 ice breaker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# @weapp-vite/hmr
|
|
2
|
+
|
|
3
|
+
实验性的 Node 侧 HMR 编译与交付内核。宿主提供 DevEngine、监听、编译策略、原生输出和运行时协议;本包不依赖 Vite、Rolldown、Tailwind 或框架运行时。
|
|
4
|
+
|
|
5
|
+
- `HmrCompilerHost` 按实际读取的源码封存版本,并协调可选 `prepareHmr` provider。
|
|
6
|
+
- `captureHmrBatch` / `transformHmrBatch` 保留每个 client、补丁顺序、同名文件的不同版本与元数据,单独组合 sourcemap。
|
|
7
|
+
- `HmrAssetStore` 记录最后成功提交的字节与部分写入状态;宿主串行调用 `commit`,并通过原生 emit/write 持久化变更和删除。可传入第三个参数 `retainedFileNames`,保护已经转交给宿主 chunk 所有者的同名产物。
|
|
8
|
+
- `HmrTransaction` 区分准备、资产提交、持久发布与应用确认;`acknowledge` 不需要排入发布队列,过期和重复回报不改变状态。
|
|
9
|
+
- `HmrDeliveryCoordinator` 为需要自有交付队列的宿主提供串行协调。已有队列的宿主直接使用事务,避免叠加调度所有者。
|
|
10
|
+
|
|
11
|
+
`publish` 回调完成只代表宿主定义的发布边界。VPT 的 DevEngine 通知在持久发布后进行,应用回报继续由 PatchJournal 管理;weapp-vite 的适配器继续等待真实运行时确认。公共包不统一两者的传输协议。
|
|
12
|
+
|
|
13
|
+
API 为实验版本;发布应用前应使用本包类型与真实 DevEngine 验证自己的宿主适配器。
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
//#region src/assets.d.ts
|
|
2
|
+
export interface HmrAsset {
|
|
3
|
+
fileName: string;
|
|
4
|
+
source: string | Uint8Array;
|
|
5
|
+
}
|
|
6
|
+
export interface HmrAssetChanges<T extends HmrAsset> {
|
|
7
|
+
changed: T[];
|
|
8
|
+
removed: string[];
|
|
9
|
+
}
|
|
10
|
+
/** 保存最后成功提交的字节与可能部分落盘的文件;不拥有任何文件系统写入者。 */
|
|
11
|
+
export declare class HmrAssetStore<T extends HmrAsset = HmrAsset> {
|
|
12
|
+
private committed;
|
|
13
|
+
private attempted;
|
|
14
|
+
private reliable;
|
|
15
|
+
private committing;
|
|
16
|
+
values(): IterableIterator<T>;
|
|
17
|
+
ownedNames(): string[];
|
|
18
|
+
track(assets: Iterable<T>): void;
|
|
19
|
+
invalidate(): void;
|
|
20
|
+
adopt(assets: Iterable<T>): void;
|
|
21
|
+
diff(assets: readonly T[], retainedFileNames?: Iterable<string>): HmrAssetChanges<T>;
|
|
22
|
+
commit(assets: readonly T[], write: (changes: HmrAssetChanges<T>) => Promise<void>, retainedFileNames?: Iterable<string>): Promise<HmrAssetChanges<T>>;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/types.d.ts
|
|
26
|
+
export interface HmrCompilerOutputRequest {
|
|
27
|
+
fileName: string;
|
|
28
|
+
code: string;
|
|
29
|
+
sourcemap?: boolean;
|
|
30
|
+
entryId?: string;
|
|
31
|
+
state?: unknown;
|
|
32
|
+
}
|
|
33
|
+
export interface HmrCompilerTransformResult {
|
|
34
|
+
code: string;
|
|
35
|
+
entryId?: string;
|
|
36
|
+
map?: unknown;
|
|
37
|
+
dependencies?: string[];
|
|
38
|
+
invalidated?: string[];
|
|
39
|
+
handled?: boolean;
|
|
40
|
+
state?: unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface HmrCompilerRequest {
|
|
43
|
+
/** 宿主封存的输入版本,不等同于客户端执行版本。 */
|
|
44
|
+
revision: number;
|
|
45
|
+
changedFiles: readonly string[];
|
|
46
|
+
sources: ReadonlyMap<string, string | null>;
|
|
47
|
+
}
|
|
48
|
+
export interface HmrCompilerAsset {
|
|
49
|
+
fileName: string;
|
|
50
|
+
code: string;
|
|
51
|
+
}
|
|
52
|
+
export interface HmrCompilerPreparation {
|
|
53
|
+
assets?: readonly HmrCompilerAsset[];
|
|
54
|
+
dependencies?: readonly string[];
|
|
55
|
+
invalidated?: readonly string[];
|
|
56
|
+
transformJavaScript?: (request: HmrCompilerOutputRequest) => HmrCompilerTransformResult | null | Promise<HmrCompilerTransformResult | null>;
|
|
57
|
+
transformTemplate?: (request: HmrCompilerOutputRequest) => HmrCompilerTransformResult | null | Promise<HmrCompilerTransformResult | null>;
|
|
58
|
+
/** 批次确认或取消后释放固定的编译状态。 */
|
|
59
|
+
dispose?: () => void | Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
export interface HmrCompilerProvider {
|
|
62
|
+
prepareHmr?: (request: HmrCompilerRequest) => HmrCompilerPreparation | Promise<HmrCompilerPreparation>;
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/batch.d.ts
|
|
66
|
+
export interface HmrSourceMap {
|
|
67
|
+
version: number;
|
|
68
|
+
sources: string[];
|
|
69
|
+
names: string[];
|
|
70
|
+
mappings: string;
|
|
71
|
+
sourcesContent?: Array<string | null>;
|
|
72
|
+
file?: string;
|
|
73
|
+
sourceRoot?: string;
|
|
74
|
+
}
|
|
75
|
+
export interface HmrUpdate {
|
|
76
|
+
type: string;
|
|
77
|
+
code?: string;
|
|
78
|
+
filename?: string;
|
|
79
|
+
sourcemap?: string;
|
|
80
|
+
}
|
|
81
|
+
export interface HmrClientUpdate<U extends HmrUpdate = HmrUpdate> {
|
|
82
|
+
clientId: string;
|
|
83
|
+
update: U;
|
|
84
|
+
}
|
|
85
|
+
export interface HmrBatch<U extends HmrClientUpdate = HmrClientUpdate> {
|
|
86
|
+
changedFiles: readonly string[];
|
|
87
|
+
updates: readonly U[];
|
|
88
|
+
}
|
|
89
|
+
export type CapturedHmrBatch<B extends HmrBatch> = Readonly<Omit<B, 'changedFiles' | 'updates'>> & HmrBatch<B['updates'][number] & HmrClientUpdate>;
|
|
90
|
+
type TransformedUpdate<U extends HmrUpdate> = U extends HmrUpdate ? Omit<U, 'code' | 'sourcemap'> & Pick<HmrUpdate, 'sourcemap'> & (U extends {
|
|
91
|
+
code: string;
|
|
92
|
+
} ? {
|
|
93
|
+
code: string;
|
|
94
|
+
} : Pick<HmrUpdate, 'code'>) : never;
|
|
95
|
+
type TransformedClient<U extends HmrClientUpdate> = U extends HmrClientUpdate ? Omit<U, 'update'> & {
|
|
96
|
+
update: TransformedUpdate<U['update']>;
|
|
97
|
+
} : never;
|
|
98
|
+
export type TransformedHmrBatch<B extends HmrBatch> = Readonly<Omit<B, 'changedFiles' | 'updates'>> & HmrBatch<TransformedClient<B['updates'][number]>>;
|
|
99
|
+
/** 在回调入口保留完整元数据和原始顺序,不合并不同的源码代次。 */
|
|
100
|
+
export declare function captureHmrBatch<B extends HmrBatch>(batch: B): CapturedHmrBatch<B>;
|
|
101
|
+
export declare function normalizeHmrSourceMap(value: unknown): HmrSourceMap | null;
|
|
102
|
+
/** 每份补丁单独组合映射,同名 filename 的连续版本仍保持独立。 */
|
|
103
|
+
export declare function composeHmrSourceMaps(next: HmrSourceMap | null, previous: HmrSourceMap | null): HmrSourceMap | null;
|
|
104
|
+
export declare function transformHmrPatch(patch: {
|
|
105
|
+
code: string;
|
|
106
|
+
filename: string;
|
|
107
|
+
sourcemap?: string;
|
|
108
|
+
}, preparations: readonly HmrCompilerPreparation[], sourcemap: boolean): Promise<{
|
|
109
|
+
code: string;
|
|
110
|
+
map: HmrSourceMap | null;
|
|
111
|
+
}>;
|
|
112
|
+
/** 只转换 Patch 的代码和映射;宿主继续决定 FullReload、Noop 和每个 client 的处理。 */
|
|
113
|
+
export declare function transformHmrBatch<B extends HmrBatch>(batch: B, preparations: readonly HmrCompilerPreparation[], options: {
|
|
114
|
+
sourcemap: boolean;
|
|
115
|
+
}): Promise<TransformedHmrBatch<B>>;
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/compilerHost.d.ts
|
|
118
|
+
interface Provider {
|
|
119
|
+
prepare?: HmrCompilerProvider['prepareHmr'];
|
|
120
|
+
}
|
|
121
|
+
export interface HmrCompilerHostOptions {
|
|
122
|
+
sourceId?: (id: string) => string;
|
|
123
|
+
hasVisualChange?: (id: string, previous: string | null | undefined, current: string | null | undefined) => boolean;
|
|
124
|
+
}
|
|
125
|
+
/** 只保存宿主实际提供的输入;模块身份和框架语义由适配器决定。 */
|
|
126
|
+
export declare class HmrCompilerHost {
|
|
127
|
+
private readonly options;
|
|
128
|
+
onDependencyChange?: (file: string) => void;
|
|
129
|
+
private nativeSources;
|
|
130
|
+
private revision;
|
|
131
|
+
private readonly previousSources;
|
|
132
|
+
private readonly previousByBatch;
|
|
133
|
+
private readonly dependencies;
|
|
134
|
+
private readonly sources;
|
|
135
|
+
private readonly providers;
|
|
136
|
+
constructor(options?: HmrCompilerHostOptions);
|
|
137
|
+
private sourceId;
|
|
138
|
+
get supported(): boolean;
|
|
139
|
+
get enabled(): boolean;
|
|
140
|
+
ownsDependency(id: string): boolean;
|
|
141
|
+
readSource(id: string): string | null | undefined;
|
|
142
|
+
isNativeSource(id: string): boolean;
|
|
143
|
+
setNativeSources(ids: Iterable<string>): void;
|
|
144
|
+
captureNative(id: string, code: string): void;
|
|
145
|
+
seed(id: string, code: string | null): void;
|
|
146
|
+
capture(id: string, code: string | null): void;
|
|
147
|
+
hasVisualChanges(files: readonly string[], input?: HmrCompilerRequest): boolean;
|
|
148
|
+
register(name: string, prepare?: Provider['prepare']): void;
|
|
149
|
+
freeze(changedFiles: readonly string[]): HmrCompilerRequest;
|
|
150
|
+
prepare(request: HmrCompilerRequest): Promise<HmrCompilerPreparation[]>;
|
|
151
|
+
}
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/deliveryCoordinator.d.ts
|
|
154
|
+
export interface HmrDeliveryPreparation {
|
|
155
|
+
commit: () => Promise<void>;
|
|
156
|
+
publish: () => Promise<void>;
|
|
157
|
+
dispose?: () => void | Promise<void>;
|
|
158
|
+
}
|
|
159
|
+
export interface HmrDeliveryTask {
|
|
160
|
+
bytes?: number;
|
|
161
|
+
prepare: () => Promise<HmrDeliveryPreparation>;
|
|
162
|
+
}
|
|
163
|
+
/** 编译结果可以提前准备,资产提交与客户端执行确认必须保持同一条交付链。 */
|
|
164
|
+
export declare class HmrDeliveryCoordinator {
|
|
165
|
+
private readonly onError;
|
|
166
|
+
private readonly requestResynchronization?;
|
|
167
|
+
private readonly maxPending;
|
|
168
|
+
private generation;
|
|
169
|
+
private closed;
|
|
170
|
+
private pending;
|
|
171
|
+
private running?;
|
|
172
|
+
private failed;
|
|
173
|
+
private pendingBytes;
|
|
174
|
+
constructor(onError: (error: unknown) => void, requestResynchronization?: (() => void) | undefined, maxPending?: number);
|
|
175
|
+
enqueue(task: HmrDeliveryTask): void;
|
|
176
|
+
retry(): void;
|
|
177
|
+
reset(): void;
|
|
178
|
+
close(): Promise<void>;
|
|
179
|
+
private prepare;
|
|
180
|
+
private dispose;
|
|
181
|
+
private drain;
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/errors.d.ts
|
|
185
|
+
export declare class CompilerHmrResyncError extends Error {
|
|
186
|
+
readonly files: readonly string[];
|
|
187
|
+
constructor(files: readonly string[], message: string);
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/retention.d.ts
|
|
191
|
+
export declare const maxRetainedDeltaCount = 1000;
|
|
192
|
+
export declare const maxRetainedDeltaBytes: number;
|
|
193
|
+
export declare function shouldResetStatefulHmrRetention(count: number, bytes: number, nextBytes: number): boolean;
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/transaction.d.ts
|
|
196
|
+
export interface HmrBatchIdentity {
|
|
197
|
+
generation: string;
|
|
198
|
+
revision: number;
|
|
199
|
+
}
|
|
200
|
+
export interface HmrTransactionOptions<T> {
|
|
201
|
+
identity: HmrBatchIdentity;
|
|
202
|
+
prepare: () => T | Promise<T>;
|
|
203
|
+
commit: (prepared: T) => Promise<void>;
|
|
204
|
+
publish: (prepared: T) => Promise<void>;
|
|
205
|
+
dispose?: (prepared: T) => void | Promise<void>;
|
|
206
|
+
}
|
|
207
|
+
/** 可由现有宿主队列调度的单批事务;确认入口不占用或等待该队列。 */
|
|
208
|
+
export declare class HmrTransaction<T> {
|
|
209
|
+
private readonly options;
|
|
210
|
+
readonly identity: Readonly<HmrBatchIdentity>;
|
|
211
|
+
private preparation?;
|
|
212
|
+
private state;
|
|
213
|
+
private running?;
|
|
214
|
+
private disposal?;
|
|
215
|
+
constructor(options: HmrTransactionOptions<T>);
|
|
216
|
+
get phase(): "preparing" | "prepared" | "committed" | "published" | "applied" | "disposed";
|
|
217
|
+
prepare(): Promise<T>;
|
|
218
|
+
publish(): Promise<void>;
|
|
219
|
+
/** 旧代次、未来版本、未发布和重复回报不会推进应用状态。 */
|
|
220
|
+
acknowledge(identity: HmrBatchIdentity): boolean;
|
|
221
|
+
dispose(): Promise<void>;
|
|
222
|
+
private isDisposed;
|
|
223
|
+
private deliver;
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import remapping from "@jridgewell/remapping";
|
|
3
|
+
//#region src/assets.ts
|
|
4
|
+
function copyAsset(asset) {
|
|
5
|
+
return {
|
|
6
|
+
...asset,
|
|
7
|
+
source: typeof asset.source === "string" ? asset.source : Uint8Array.from(asset.source)
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/** 保存最后成功提交的字节与可能部分落盘的文件;不拥有任何文件系统写入者。 */
|
|
11
|
+
var HmrAssetStore = class {
|
|
12
|
+
committed = /* @__PURE__ */ new Map();
|
|
13
|
+
attempted = /* @__PURE__ */ new Set();
|
|
14
|
+
reliable = true;
|
|
15
|
+
committing = false;
|
|
16
|
+
values() {
|
|
17
|
+
return Array.from(this.committed.values(), copyAsset).values();
|
|
18
|
+
}
|
|
19
|
+
ownedNames() {
|
|
20
|
+
return [.../* @__PURE__ */ new Set([...this.committed.keys(), ...this.attempted])];
|
|
21
|
+
}
|
|
22
|
+
track(assets) {
|
|
23
|
+
for (const asset of assets) this.attempted.add(asset.fileName);
|
|
24
|
+
}
|
|
25
|
+
invalidate() {
|
|
26
|
+
this.reliable = false;
|
|
27
|
+
}
|
|
28
|
+
adopt(assets) {
|
|
29
|
+
this.committed = new Map(Array.from(assets, (asset) => [asset.fileName, copyAsset(asset)]));
|
|
30
|
+
this.attempted.clear();
|
|
31
|
+
this.reliable = true;
|
|
32
|
+
}
|
|
33
|
+
diff(assets, retainedFileNames = []) {
|
|
34
|
+
const names = /* @__PURE__ */ new Set();
|
|
35
|
+
const changed = [];
|
|
36
|
+
for (const asset of assets) {
|
|
37
|
+
if (names.has(asset.fileName)) throw new Error(`HMR asset has multiple owners: ${asset.fileName}`);
|
|
38
|
+
names.add(asset.fileName);
|
|
39
|
+
const previous = this.committed.get(asset.fileName);
|
|
40
|
+
if (!this.reliable || !previous || !(previous.source === asset.source || Buffer.from(previous.source).equals(Buffer.from(asset.source)))) changed.push(asset);
|
|
41
|
+
}
|
|
42
|
+
const retained = new Set(retainedFileNames);
|
|
43
|
+
return {
|
|
44
|
+
changed,
|
|
45
|
+
removed: this.ownedNames().filter((name) => !names.has(name) && !retained.has(name))
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
async commit(assets, write, retainedFileNames = []) {
|
|
49
|
+
if (this.committing) throw new Error("HMR asset commits must be serialized by the host");
|
|
50
|
+
const captured = assets.map(copyAsset);
|
|
51
|
+
const changes = this.diff(captured, retainedFileNames);
|
|
52
|
+
this.track(changes.changed);
|
|
53
|
+
this.committing = true;
|
|
54
|
+
try {
|
|
55
|
+
if (changes.changed.length || changes.removed.length) await write(changes);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
this.invalidate();
|
|
58
|
+
throw error;
|
|
59
|
+
} finally {
|
|
60
|
+
this.committing = false;
|
|
61
|
+
}
|
|
62
|
+
this.adopt(captured);
|
|
63
|
+
return changes;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/batch.ts
|
|
68
|
+
/** 在回调入口保留完整元数据和原始顺序,不合并不同的源码代次。 */
|
|
69
|
+
function captureHmrBatch(batch) {
|
|
70
|
+
const snapshot = structuredClone(batch);
|
|
71
|
+
return Object.freeze({
|
|
72
|
+
...snapshot,
|
|
73
|
+
changedFiles: Object.freeze([...snapshot.changedFiles]),
|
|
74
|
+
updates: Object.freeze(snapshot.updates.map((item) => Object.freeze({
|
|
75
|
+
...item,
|
|
76
|
+
update: Object.freeze({ ...item.update })
|
|
77
|
+
})))
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function normalizeHmrSourceMap(value) {
|
|
81
|
+
if (typeof value === "string") return normalizeHmrSourceMap(JSON.parse(value));
|
|
82
|
+
if (!value || typeof value !== "object") return null;
|
|
83
|
+
if ("version" in value && Number(value.version) === 3 && "sources" in value && Array.isArray(value.sources) && value.sources.every((source) => typeof source === "string") && "names" in value && Array.isArray(value.names) && value.names.every((name) => typeof name === "string") && "mappings" in value && typeof value.mappings === "string") {
|
|
84
|
+
const map = {
|
|
85
|
+
version: 3,
|
|
86
|
+
sources: [...value.sources],
|
|
87
|
+
names: [...value.names],
|
|
88
|
+
mappings: value.mappings
|
|
89
|
+
};
|
|
90
|
+
if ("file" in value && typeof value.file === "string") map.file = value.file;
|
|
91
|
+
if ("sourceRoot" in value && typeof value.sourceRoot === "string") map.sourceRoot = value.sourceRoot;
|
|
92
|
+
if ("sourcesContent" in value && Array.isArray(value.sourcesContent)) {
|
|
93
|
+
if (!value.sourcesContent.every((source) => source == null || typeof source === "string")) throw new TypeError("Invalid HMR source contents");
|
|
94
|
+
map.sourcesContent = value.sourcesContent.map((source) => source ?? null);
|
|
95
|
+
}
|
|
96
|
+
return map;
|
|
97
|
+
}
|
|
98
|
+
throw new TypeError("Invalid HMR source map");
|
|
99
|
+
}
|
|
100
|
+
/** 每份补丁单独组合映射,同名 filename 的连续版本仍保持独立。 */
|
|
101
|
+
function composeHmrSourceMaps(next, previous) {
|
|
102
|
+
if (!next) return previous;
|
|
103
|
+
if (!previous?.sources.length || !previous.mappings) return next;
|
|
104
|
+
return normalizeHmrSourceMap(remapping([{
|
|
105
|
+
...next,
|
|
106
|
+
version: 3
|
|
107
|
+
}, {
|
|
108
|
+
...previous,
|
|
109
|
+
version: 3
|
|
110
|
+
}], () => null));
|
|
111
|
+
}
|
|
112
|
+
async function transformHmrPatch(patch, preparations, sourcemap) {
|
|
113
|
+
let code = patch.code.replace(/(?:^|\r?\n)[ \t]*\/\/[#@] sourceMappingURL=[^\r\n'"`*<>]+(?:\r?\n[ \t]*)*$/, "");
|
|
114
|
+
let map = sourcemap && patch.sourcemap ? normalizeHmrSourceMap(patch.sourcemap) : null;
|
|
115
|
+
if (map && (!map.sources.length || !map.mappings)) map = null;
|
|
116
|
+
for (const preparation of preparations) {
|
|
117
|
+
const result = await preparation.transformJavaScript?.({
|
|
118
|
+
code,
|
|
119
|
+
fileName: patch.filename,
|
|
120
|
+
sourcemap
|
|
121
|
+
});
|
|
122
|
+
if (result) {
|
|
123
|
+
if (sourcemap && result.code !== code && !result.map) throw new Error("Compiler HMR transform changed code without a source map");
|
|
124
|
+
if (sourcemap) map = composeHmrSourceMaps(normalizeHmrSourceMap(result.map), map);
|
|
125
|
+
code = result.code;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
code,
|
|
130
|
+
map
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function withPatchTransform(item, update) {
|
|
134
|
+
return update ? {
|
|
135
|
+
...item,
|
|
136
|
+
update: {
|
|
137
|
+
...item.update,
|
|
138
|
+
...update
|
|
139
|
+
}
|
|
140
|
+
} : item;
|
|
141
|
+
}
|
|
142
|
+
/** 只转换 Patch 的代码和映射;宿主继续决定 FullReload、Noop 和每个 client 的处理。 */
|
|
143
|
+
async function transformHmrBatch(batch, preparations, options) {
|
|
144
|
+
const captured = captureHmrBatch(batch);
|
|
145
|
+
const updates = [];
|
|
146
|
+
for (const item of captured.updates) {
|
|
147
|
+
const patch = item.update;
|
|
148
|
+
if (patch.type !== "Patch" || typeof patch.code !== "string" || typeof patch.filename !== "string") {
|
|
149
|
+
updates.push(withPatchTransform(item));
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const transformed = await transformHmrPatch({
|
|
153
|
+
...patch,
|
|
154
|
+
code: patch.code,
|
|
155
|
+
filename: patch.filename
|
|
156
|
+
}, preparations, options.sourcemap);
|
|
157
|
+
updates.push(withPatchTransform(item, {
|
|
158
|
+
code: transformed.code,
|
|
159
|
+
sourcemap: transformed.map ? JSON.stringify(transformed.map) : void 0
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
...captured,
|
|
164
|
+
updates
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/errors.ts
|
|
169
|
+
var CompilerHmrResyncError = class extends Error {
|
|
170
|
+
files;
|
|
171
|
+
constructor(files, message) {
|
|
172
|
+
super(message);
|
|
173
|
+
this.files = files;
|
|
174
|
+
this.name = "CompilerHmrResyncError";
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
//#endregion
|
|
178
|
+
//#region src/compilerHost.ts
|
|
179
|
+
/** 只保存宿主实际提供的输入;模块身份和框架语义由适配器决定。 */
|
|
180
|
+
var HmrCompilerHost = class {
|
|
181
|
+
options;
|
|
182
|
+
onDependencyChange;
|
|
183
|
+
nativeSources = /* @__PURE__ */ new Set();
|
|
184
|
+
revision = 0;
|
|
185
|
+
previousSources = /* @__PURE__ */ new Map();
|
|
186
|
+
previousByBatch = /* @__PURE__ */ new WeakMap();
|
|
187
|
+
dependencies = /* @__PURE__ */ new Set();
|
|
188
|
+
sources = /* @__PURE__ */ new Map();
|
|
189
|
+
providers = /* @__PURE__ */ new Map();
|
|
190
|
+
constructor(options = {}) {
|
|
191
|
+
this.options = options;
|
|
192
|
+
}
|
|
193
|
+
sourceId(id) {
|
|
194
|
+
return this.options.sourceId?.(id) ?? id.replaceAll("\\", "/");
|
|
195
|
+
}
|
|
196
|
+
get supported() {
|
|
197
|
+
return [...this.providers.values()].every((provider) => provider.prepare);
|
|
198
|
+
}
|
|
199
|
+
get enabled() {
|
|
200
|
+
return this.providers.size > 0;
|
|
201
|
+
}
|
|
202
|
+
ownsDependency(id) {
|
|
203
|
+
return this.dependencies.has(this.sourceId(id));
|
|
204
|
+
}
|
|
205
|
+
readSource(id) {
|
|
206
|
+
return this.sources.get(this.sourceId(id));
|
|
207
|
+
}
|
|
208
|
+
isNativeSource(id) {
|
|
209
|
+
return this.nativeSources.has(this.sourceId(id));
|
|
210
|
+
}
|
|
211
|
+
setNativeSources(ids) {
|
|
212
|
+
this.nativeSources = new Set(Array.from(ids, (id) => this.sourceId(id)));
|
|
213
|
+
this.previousSources.clear();
|
|
214
|
+
for (const [id, source] of this.sources) this.previousSources.set(id, source);
|
|
215
|
+
}
|
|
216
|
+
captureNative(id, code) {
|
|
217
|
+
if (!id.includes("?") && !id.startsWith("\0")) {
|
|
218
|
+
this.nativeSources.add(this.sourceId(id));
|
|
219
|
+
this.capture(id, code);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
seed(id, code) {
|
|
223
|
+
this.dependencies.add(this.sourceId(id));
|
|
224
|
+
if (!this.sources.has(this.sourceId(id))) this.capture(id, code);
|
|
225
|
+
}
|
|
226
|
+
capture(id, code) {
|
|
227
|
+
if (id.includes("?") || id.startsWith("\0")) return;
|
|
228
|
+
id = this.sourceId(id);
|
|
229
|
+
if (this.sources.get(id) !== code) {
|
|
230
|
+
this.sources.set(id, code);
|
|
231
|
+
this.revision += 1;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
hasVisualChanges(files, input) {
|
|
235
|
+
return files.some((file) => {
|
|
236
|
+
const id = this.sourceId(file);
|
|
237
|
+
const previous = (input ? this.previousByBatch.get(input) : this.previousSources)?.get(id);
|
|
238
|
+
const current = (input?.sources ?? this.sources).get(id);
|
|
239
|
+
return this.options.hasVisualChange?.(id, previous, current) ?? previous !== current;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
register(name, prepare) {
|
|
243
|
+
this.providers.set(name, { prepare });
|
|
244
|
+
}
|
|
245
|
+
freeze(changedFiles) {
|
|
246
|
+
const input = Object.freeze({
|
|
247
|
+
revision: this.revision,
|
|
248
|
+
changedFiles: Object.freeze([...changedFiles]),
|
|
249
|
+
sources: new Map(this.sources)
|
|
250
|
+
});
|
|
251
|
+
const previous = /* @__PURE__ */ new Map();
|
|
252
|
+
for (const file of changedFiles) {
|
|
253
|
+
const id = this.sourceId(file);
|
|
254
|
+
const source = this.previousSources.get(id);
|
|
255
|
+
if (source !== void 0) previous.set(id, source);
|
|
256
|
+
const current = this.sources.get(id);
|
|
257
|
+
if (current !== void 0) this.previousSources.set(id, current);
|
|
258
|
+
}
|
|
259
|
+
this.previousByBatch.set(input, previous);
|
|
260
|
+
return input;
|
|
261
|
+
}
|
|
262
|
+
async prepare(request) {
|
|
263
|
+
const pending = [...this.providers].map(([name, provider]) => {
|
|
264
|
+
try {
|
|
265
|
+
if (!provider.prepare) throw new Error(`Compiler provider ${name} does not support versioned HMR preparation`);
|
|
266
|
+
return Promise.resolve(provider.prepare(request));
|
|
267
|
+
} catch (error) {
|
|
268
|
+
return Promise.reject(error);
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
const settled = await Promise.allSettled(pending);
|
|
272
|
+
const results = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
273
|
+
const failure = settled.find((result) => result.status === "rejected");
|
|
274
|
+
if (failure?.status === "rejected") {
|
|
275
|
+
await Promise.allSettled(results.map((result) => result.dispose?.()));
|
|
276
|
+
throw failure.reason;
|
|
277
|
+
}
|
|
278
|
+
const assets = /* @__PURE__ */ new Set();
|
|
279
|
+
for (const result of results) for (const asset of result.assets ?? []) {
|
|
280
|
+
const file = asset.fileName.replaceAll("\\", "/");
|
|
281
|
+
if (assets.has(file)) {
|
|
282
|
+
await Promise.allSettled(results.map((result) => result.dispose?.()));
|
|
283
|
+
throw new CompilerHmrResyncError(request.changedFiles, `Compiler HMR asset has multiple providers: ${file}`);
|
|
284
|
+
}
|
|
285
|
+
assets.add(file);
|
|
286
|
+
}
|
|
287
|
+
return results;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/retention.ts
|
|
292
|
+
const maxRetainedDeltaCount = 1e3;
|
|
293
|
+
const maxRetainedDeltaBytes = 16777216;
|
|
294
|
+
function shouldResetStatefulHmrRetention(count, bytes, nextBytes) {
|
|
295
|
+
return count >= 1e3 || bytes + nextBytes >= 16777216;
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/deliveryCoordinator.ts
|
|
299
|
+
/** 编译结果可以提前准备,资产提交与客户端执行确认必须保持同一条交付链。 */
|
|
300
|
+
var HmrDeliveryCoordinator = class {
|
|
301
|
+
onError;
|
|
302
|
+
requestResynchronization;
|
|
303
|
+
maxPending;
|
|
304
|
+
generation = 0;
|
|
305
|
+
closed = false;
|
|
306
|
+
pending = [];
|
|
307
|
+
running;
|
|
308
|
+
failed = false;
|
|
309
|
+
pendingBytes = 0;
|
|
310
|
+
constructor(onError, requestResynchronization, maxPending = maxRetainedDeltaCount) {
|
|
311
|
+
this.onError = onError;
|
|
312
|
+
this.requestResynchronization = requestResynchronization;
|
|
313
|
+
this.maxPending = maxPending;
|
|
314
|
+
}
|
|
315
|
+
enqueue(task) {
|
|
316
|
+
if (this.closed) return;
|
|
317
|
+
if (this.failed && this.requestResynchronization) {
|
|
318
|
+
this.requestResynchronization();
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (this.pending.length >= this.maxPending || shouldResetStatefulHmrRetention(0, this.pendingBytes, task.bytes ?? 0)) {
|
|
322
|
+
this.requestResynchronization?.();
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const item = {
|
|
326
|
+
task,
|
|
327
|
+
generation: this.generation
|
|
328
|
+
};
|
|
329
|
+
this.prepare(item);
|
|
330
|
+
this.pending.push(item);
|
|
331
|
+
this.pendingBytes += task.bytes ?? 0;
|
|
332
|
+
this.retry();
|
|
333
|
+
}
|
|
334
|
+
retry() {
|
|
335
|
+
this.failed = false;
|
|
336
|
+
if (!this.running && !this.closed) this.running = this.drain().finally(() => {
|
|
337
|
+
this.running = void 0;
|
|
338
|
+
if (this.pending.length && !this.failed && !this.closed) this.retry();
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
reset() {
|
|
342
|
+
this.generation += 1;
|
|
343
|
+
for (const item of this.pending) this.dispose(item);
|
|
344
|
+
this.pending = [];
|
|
345
|
+
this.pendingBytes = 0;
|
|
346
|
+
this.failed = false;
|
|
347
|
+
}
|
|
348
|
+
async close() {
|
|
349
|
+
this.closed = true;
|
|
350
|
+
this.reset();
|
|
351
|
+
await this.running;
|
|
352
|
+
}
|
|
353
|
+
prepare(item) {
|
|
354
|
+
if (!item.preparation) {
|
|
355
|
+
item.preparation = item.task.prepare();
|
|
356
|
+
item.preparation.catch(() => {
|
|
357
|
+
item.preparation = void 0;
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
return item.preparation;
|
|
361
|
+
}
|
|
362
|
+
async dispose(item) {
|
|
363
|
+
if (item.disposed) return;
|
|
364
|
+
item.disposed = true;
|
|
365
|
+
try {
|
|
366
|
+
await (await item.preparation)?.dispose?.();
|
|
367
|
+
} catch {}
|
|
368
|
+
}
|
|
369
|
+
async drain() {
|
|
370
|
+
while (!this.closed && this.pending.length) {
|
|
371
|
+
const item = this.pending[0];
|
|
372
|
+
try {
|
|
373
|
+
const prepared = await this.prepare(item);
|
|
374
|
+
if (item.generation !== this.generation) continue;
|
|
375
|
+
if (!item.committed) {
|
|
376
|
+
await prepared.commit();
|
|
377
|
+
item.committed = true;
|
|
378
|
+
}
|
|
379
|
+
if (item.generation !== this.generation) continue;
|
|
380
|
+
await prepared.publish();
|
|
381
|
+
if (this.pending[0] === item) {
|
|
382
|
+
this.pending.shift();
|
|
383
|
+
this.pendingBytes -= item.task.bytes ?? 0;
|
|
384
|
+
}
|
|
385
|
+
await this.dispose(item);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
if (item.generation === this.generation && !this.closed) {
|
|
388
|
+
this.failed = true;
|
|
389
|
+
this.onError(error);
|
|
390
|
+
if (item.generation === this.generation && this.pending.length > 1) this.requestResynchronization?.();
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region src/transaction.ts
|
|
399
|
+
/** 可由现有宿主队列调度的单批事务;确认入口不占用或等待该队列。 */
|
|
400
|
+
var HmrTransaction = class {
|
|
401
|
+
options;
|
|
402
|
+
identity;
|
|
403
|
+
preparation;
|
|
404
|
+
state = "preparing";
|
|
405
|
+
running;
|
|
406
|
+
disposal;
|
|
407
|
+
constructor(options) {
|
|
408
|
+
this.options = options;
|
|
409
|
+
this.identity = Object.freeze({ ...options.identity });
|
|
410
|
+
this.prepare();
|
|
411
|
+
}
|
|
412
|
+
get phase() {
|
|
413
|
+
return this.state;
|
|
414
|
+
}
|
|
415
|
+
prepare() {
|
|
416
|
+
if (this.isDisposed()) return Promise.reject(/* @__PURE__ */ new Error("HMR transaction is disposed"));
|
|
417
|
+
if (!this.preparation) {
|
|
418
|
+
try {
|
|
419
|
+
this.preparation = Promise.resolve(this.options.prepare()).then((value) => {
|
|
420
|
+
if (this.state === "preparing") this.state = "prepared";
|
|
421
|
+
return value;
|
|
422
|
+
});
|
|
423
|
+
} catch (error) {
|
|
424
|
+
this.preparation = Promise.reject(error);
|
|
425
|
+
}
|
|
426
|
+
this.preparation.catch(() => {
|
|
427
|
+
this.preparation = void 0;
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
return this.preparation;
|
|
431
|
+
}
|
|
432
|
+
publish() {
|
|
433
|
+
if (this.isDisposed()) return Promise.reject(/* @__PURE__ */ new Error("HMR transaction is disposed"));
|
|
434
|
+
this.running ??= this.deliver().finally(() => {
|
|
435
|
+
this.running = void 0;
|
|
436
|
+
});
|
|
437
|
+
return this.running;
|
|
438
|
+
}
|
|
439
|
+
/** 旧代次、未来版本、未发布和重复回报不会推进应用状态。 */
|
|
440
|
+
acknowledge(identity) {
|
|
441
|
+
if (identity.generation !== this.identity.generation || identity.revision !== this.identity.revision || this.state !== "published") return false;
|
|
442
|
+
this.state = "applied";
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
dispose() {
|
|
446
|
+
this.state = "disposed";
|
|
447
|
+
this.disposal ??= (async () => {
|
|
448
|
+
await this.running?.catch(() => {});
|
|
449
|
+
if (this.preparation) await this.preparation.then((prepared) => this.options.dispose?.(prepared), () => {});
|
|
450
|
+
})();
|
|
451
|
+
return this.disposal;
|
|
452
|
+
}
|
|
453
|
+
isDisposed() {
|
|
454
|
+
return this.state === "disposed";
|
|
455
|
+
}
|
|
456
|
+
async deliver() {
|
|
457
|
+
const prepared = await this.prepare();
|
|
458
|
+
if (this.state === "prepared") {
|
|
459
|
+
await this.options.commit(prepared);
|
|
460
|
+
if (this.isDisposed()) return;
|
|
461
|
+
this.state = "committed";
|
|
462
|
+
}
|
|
463
|
+
if (this.state === "committed") {
|
|
464
|
+
await this.options.publish(prepared);
|
|
465
|
+
if (!this.isDisposed()) this.state = "published";
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
//#endregion
|
|
470
|
+
export { CompilerHmrResyncError, HmrAssetStore, HmrCompilerHost, HmrDeliveryCoordinator, HmrTransaction, captureHmrBatch, composeHmrSourceMaps, maxRetainedDeltaBytes, maxRetainedDeltaCount, normalizeHmrSourceMap, shouldResetStatefulHmrRetention, transformHmrBatch, transformHmrPatch };
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@weapp-vite/hmr",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "小程序宿主共享的编译批次、资产提交与交付协调内核",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/weapp-vite/weapp-vite.git",
|
|
10
|
+
"directory": "packages/hmr"
|
|
11
|
+
},
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.mts",
|
|
16
|
+
"import": "./dist/index.mjs"
|
|
17
|
+
},
|
|
18
|
+
"./package.json": "./package.json"
|
|
19
|
+
},
|
|
20
|
+
"main": "./dist/index.mjs",
|
|
21
|
+
"types": "./dist/index.d.mts",
|
|
22
|
+
"files": [
|
|
23
|
+
"README.md",
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@jridgewell/remapping": "^2.3.5"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"registry": "https://registry.npmjs.org"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown",
|
|
38
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
39
|
+
"test": "vitest run -c vitest.config.ts",
|
|
40
|
+
"test:types": "tsd --files \"test-d/**/*.test-d.ts\"",
|
|
41
|
+
"lint": "eslint ."
|
|
42
|
+
}
|
|
43
|
+
}
|