@lwc/hmr-client 7.0.0-6.6.3

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.txt ADDED
@@ -0,0 +1,21 @@
1
+ Terms of Use
2
+
3
+ Copyright 2022 Salesforce, Inc. All rights reserved.
4
+
5
+ These Terms of Use govern the download, installation, and/or use of this software provided by Salesforce, Inc. (“Salesforce”) (the “Software”), were last updated on April 15, 2022, ** and constitute a legally binding agreement between you and Salesforce. If you do not agree to these Terms of Use, do not install or use the Software.
6
+
7
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute the Software and derivative works subject to these Terms. These Terms shall be included in all copies or substantial portions of the Software.
8
+
9
+ Subject to the limited rights expressly granted hereunder, Salesforce reserves all rights, title, and interest in and to all intellectual property subsisting in the Software. No rights are granted to you hereunder other than as expressly set forth herein. Users residing in countries on the United States Office of Foreign Assets Control sanction list, or which are otherwise subject to a US export embargo, may not use the Software.
10
+
11
+ Implementation of the Software may require development work, for which you are responsible. The Software may contain bugs, errors and incompatibilities and is made available on an AS IS basis without support, updates, or service level commitments.
12
+
13
+ Salesforce reserves the right at any time to modify, suspend, or discontinue, the Software (or any part thereof) with or without notice. You agree that Salesforce shall not be liable to you or to any third party for any modification, suspension, or discontinuance.
14
+
15
+ You agree to defend Salesforce against any claim, demand, suit or proceeding made or brought against Salesforce by a third party arising out of or accruing from (a) your use of the Software, and (b) any application you develop with the Software that infringes any copyright, trademark, trade secret, trade dress, patent, or other intellectual property right of any person or defames any person or violates their rights of publicity or privacy (each a “Claim Against Salesforce”), and will indemnify Salesforce from any damages, attorney fees, and costs finally awarded against Salesforce as a result of, or for any amounts paid by Salesforce under a settlement approved by you in writing of, a Claim Against Salesforce, provided Salesforce (x) promptly gives you written notice of the Claim Against Salesforce, (y) gives you sole control of the defense and settlement of the Claim Against Salesforce (except that you may not settle any Claim Against Salesforce unless it unconditionally releases Salesforce of all liability), and (z) gives you all reasonable assistance, at your expense.
16
+
17
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA, OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
18
+
19
+ These Terms of Use shall be governed exclusively by the internal laws of the State of California, without regard to its conflicts of laws rules. Each party hereby consents to the exclusive jurisdiction of the state and federal courts located in San Francisco County, California to adjudicate any dispute arising out of or relating to these Terms of Use and the download, installation, and/or use of the Software. Except as expressly stated herein, these Terms of Use constitute the entire agreement between the parties, and supersede all prior and contemporaneous agreements, proposals, or representations, written or oral, concerning their subject matter. No modification, amendment, or waiver of any provision of these Terms of Use shall be effective unless it is by an update to these Terms of Use that Salesforce makes available, or is in writing and signed by the party against whom the modification, amendment, or waiver is to be asserted.
20
+
21
+ Data Privacy: Salesforce may collect, process, and store device, system, and other information related to your use of the Software. This information includes, but is not limited to, IP address, user metrics, and other data (“Usage Data”). Salesforce may use Usage Data for analytics, product development, and marketing purposes. You acknowledge that files generated in conjunction with the Software may contain sensitive or confidential data, and you are solely responsible for anonymizing and protecting such data.
package/dist/api.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Module, HMR_Register } from '@lwc/lwc-dev-server-types';
2
+ import type { TransformOptions } from '@lwc/compiler';
3
+ export type HotModuleCallback = (mod: Module) => void;
4
+ /**
5
+ * API call to self update.
6
+ * @param modulePath {string} The module path.
7
+ * @param cb {function} The callback function to invoke for self update.
8
+ */
9
+ export declare function accept(modulePath: string, cb: HotModuleCallback): void;
10
+ /**
11
+ * API call for owner module to ingest updates to dependencies.
12
+ * @param ownerPath {string} The owner module's path or module identifier.
13
+ * @param modulePath {string} The module path.
14
+ * @param cb {function} The callback function to invoke for self update.
15
+ */
16
+ export declare function acceptDeps(_ownerPath: string, modulePath: string, cb: HotModuleCallback): void;
17
+ export declare const activeModules: Map<string, HMR_Register['data']>;
18
+ /**
19
+ * Register a module path used by the client along with its state.
20
+ * @param modulePath {string} The module path.
21
+ * @param hash {string} A hash representation of the module's source to perform freshness check.
22
+ * @param compileOptions {object} The compiler config that was used to bundle this module.
23
+ */
24
+ export declare function register(modulePath: string, hash: string, compileOptions: TransformOptions): void;
25
+ export type UpdateHandler = (mod: Module) => void;
26
+ export declare function updateHandler(modulePath: string): UpdateHandler | undefined;
27
+ /**
28
+ * Provide a list of all module paths that of interest to the current page.
29
+ * This will be registered with the dev server as modules of interest.
30
+ * @returns A list of all the paths that was used to load the current page.
31
+ */
32
+ export declare function getActiveModulePaths(): string[];
33
+ /**
34
+ * Get module state for all active modules on the client.
35
+ * @returns An array of objects containing modulePath, hash and compiler config.
36
+ */
37
+ export declare function getActiveModules(): HMR_Register['data'][];
@@ -0,0 +1,25 @@
1
+ import { ModuleUpdateObserver } from './notify/notify';
2
+ export declare function initializeClient(protocol: 'ws' | 'wss', host: string, port: string, hotModuleHandler: HotModuleHandler, errorCallback?: (error: Error) => void, observer?: ModuleUpdateObserver): void;
3
+ /**
4
+ * This interface defines capabilities that need to be implemented by the container to handle hot module
5
+ * updates.
6
+ */
7
+ export interface HotModuleHandler {
8
+ /**
9
+ * Fetch all dependencies that are required for a hot module before its evaluation.
10
+ * @param moduleSpecifiers List of dependent modules specifiers.
11
+ */
12
+ fetchDependencies(moduleSpecifiers: string[]): Promise<any>;
13
+ /**
14
+ * Give an dependency's module specifier, return the module definition.
15
+ * @param moduleSpecifier Module id in the format of
16
+ * <namespace>/<name> in the case of LWCs
17
+ * <name> in the case of standard modules like 'lwc', 'wire-service' etc.
18
+ */
19
+ getDependency(moduleSpecifier: string): any;
20
+ /**
21
+ * Evalaute a given Javascript source code.
22
+ * @param source Javascript in string format.
23
+ */
24
+ evaluateModule(ownerModuleId: string, hotModulePath: string, source: string): Promise<unknown>;
25
+ }
@@ -0,0 +1,12 @@
1
+ import type { HMR_Data } from '@lwc/lwc-dev-server-types';
2
+ export declare class Connection {
3
+ protocol: string;
4
+ host: string;
5
+ port: string;
6
+ socket: WebSocket | undefined;
7
+ init(protocol: string, host: string, port: string): void;
8
+ fetchModule(modulePath: string): void;
9
+ initializeConnection(initCallback: () => void, messageCallback: (data: HMR_Data) => void, errorCallback?: (error: Error) => void): void;
10
+ send(data: HMR_Data): void;
11
+ close(): void;
12
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * LWC Hot Module Replacement(HMR) client code
3
+ */
4
+ 'use strict';
5
+
6
+ Object.defineProperty(exports, '__esModule', { value: true });
7
+
8
+ const hotModuleCbs = new Map();
9
+ function accept(modulePath, cb) {
10
+ const callbacks = hotModuleCbs.get(modulePath) || [];
11
+ callbacks.push(cb);
12
+ hotModuleCbs.set(modulePath, callbacks);
13
+ }
14
+ /**
15
+ * API call for owner module to ingest updates to dependencies.
16
+ * @param ownerPath {string} The owner module's path or module identifier.
17
+ * @param modulePath {string} The module path.
18
+ * @param cb {function} The callback function to invoke for self update.
19
+ */
20
+ function acceptDeps(_ownerPath, modulePath, cb) {
21
+ const callbacks = hotModuleCbs.get(modulePath) || [];
22
+ callbacks.push(cb);
23
+ hotModuleCbs.set(modulePath, callbacks);
24
+ }
25
+ const activeModules = new Map();
26
+ const staleModules = new Map();
27
+ /**
28
+ * Register a module path used by the client along with its state.
29
+ * @param modulePath {string} The module path.
30
+ * @param hash {string} A hash representation of the module's source to perform freshness check.
31
+ * @param compileOptions {object} The compiler config that was used to bundle this module.
32
+ */
33
+ function register(modulePath, hash, compileOptions) {
34
+ const moduleState = {
35
+ modulePath,
36
+ hash,
37
+ compileOptions,
38
+ };
39
+ const staleModule = activeModules.get(moduleState.modulePath);
40
+ if (staleModule) {
41
+ // This is a new version of an existing module
42
+ // Potentially clean up old handlers, call dispose()
43
+ staleModules.set(modulePath, staleModule);
44
+ }
45
+ activeModules.set(modulePath, moduleState);
46
+ }
47
+ function updateHandler(modulePath) {
48
+ let callbacks = [];
49
+ if (activeModules.has(modulePath)) {
50
+ // Create a copy of the callbacks to retain the current list in a closure for when the hot
51
+ // module is available. Otherwise, the incoming hot module's callback will also be invoked
52
+ // and removed. Thus future updates won't have a callback to process.
53
+ callbacks = [...hotModuleCbs.get(modulePath)];
54
+ return (hotModule) => {
55
+ callbacks.forEach((cb) => {
56
+ cb(hotModule);
57
+ });
58
+ const existingCbs = hotModuleCbs.get(modulePath) || [];
59
+ hotModuleCbs.set(modulePath, existingCbs.filter((cb) => !callbacks.includes(cb)));
60
+ };
61
+ }
62
+ }
63
+ /**
64
+ * Get module state for all active modules on the client.
65
+ * @returns An array of objects containing modulePath, hash and compiler config.
66
+ */
67
+ function getActiveModules() {
68
+ return Array.from(activeModules.values());
69
+ }
70
+
71
+ /**
72
+ * This module is responsible for notfying the user about module updates in the server
73
+ **/
74
+ class NotifyModuleUpdate {
75
+ constructor() {
76
+ this.observers = new Set();
77
+ }
78
+ register(observer) {
79
+ if (observer) {
80
+ this.observers.add(observer);
81
+ }
82
+ }
83
+ deregister(observer) {
84
+ if (observer) {
85
+ this.observers.delete(observer);
86
+ }
87
+ }
88
+ notify(message) {
89
+ this.observers.forEach((observer) => observer.notify(message));
90
+ }
91
+ }
92
+
93
+ class Connection {
94
+ constructor() {
95
+ this.protocol = 'ws';
96
+ this.host = 'localhost';
97
+ this.port = '8080';
98
+ }
99
+ init(protocol, host, port) {
100
+ this.protocol = protocol;
101
+ this.host = host;
102
+ this.port = port;
103
+ }
104
+ fetchModule(modulePath) {
105
+ const fetchData = { type: 'fetch', data: { modulePath } };
106
+ // fetch the new module from the server
107
+ // eval it and return the new module
108
+ this.send(fetchData);
109
+ }
110
+ initializeConnection(initCallback, messageCallback, errorCallback) {
111
+ const socket = new WebSocket(`${this.protocol}://${this.host}:${this.port}`);
112
+ this.socket = socket;
113
+ this.socket.addEventListener('error', () => {
114
+ if (errorCallback) {
115
+ errorCallback(new Error('Failed to start a WebSocket connection. Running page without Local Development support.'));
116
+ }
117
+ });
118
+ this.socket.addEventListener('open', () => {
119
+ initCallback();
120
+ });
121
+ this.socket.addEventListener('message', ({ data }) => {
122
+ if (data) {
123
+ // When there is an update, handle the incoming message and request an updated module
124
+ messageCallback(JSON.parse(data));
125
+ }
126
+ });
127
+ }
128
+ send(data) {
129
+ if (this.socket && this.socket.readyState === this.socket.OPEN) {
130
+ this.socket.send(JSON.stringify(data));
131
+ }
132
+ }
133
+ close() {
134
+ var _a;
135
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
136
+ }
137
+ }
138
+
139
+ class ConsoleNotifier {
140
+ notify(message) {
141
+ switch (message.eventType) {
142
+ case 'create':
143
+ console.log(`A new module was added at ${message.modulePath}`);
144
+ break;
145
+ case 'delete':
146
+ console.log(`A module was deleted at ${message.modulePath}`);
147
+ break;
148
+ case 'update':
149
+ console.log(`A source change detected at ${message.modulePath}`);
150
+ break;
151
+ case 'hot-swapped':
152
+ console.log(`Receipt a hot module with path ${message.modulePath}, attempting to hot swap`);
153
+ break;
154
+ }
155
+ if (message.action) {
156
+ console.log(`Taking the following action on module update ${message.action.message}`);
157
+ }
158
+ }
159
+ }
160
+
161
+ function initCallback() {
162
+ const activeModules = getActiveModules();
163
+ const initData = {
164
+ type: 'init',
165
+ data: {
166
+ url: window.location.href,
167
+ activePaths: activeModules.map((m) => {
168
+ return { type: 'register', data: m };
169
+ }),
170
+ target: 'LEX',
171
+ },
172
+ };
173
+ if (activeModules.length) {
174
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.connection.send(initData);
175
+ }
176
+ }
177
+ const pendingHandlers = new Map();
178
+ let hotModuleCounter = 0;
179
+ function messageCallback(data) {
180
+ switch (data.type) {
181
+ // Some paths were updated
182
+ case 'update': {
183
+ const moduleUpdate = data;
184
+ moduleUpdate.data.forEach(({ modulePath }) => {
185
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
186
+ eventType: 'update',
187
+ modulePath,
188
+ });
189
+ const handler = updateHandler(modulePath);
190
+ if (handler) {
191
+ // Possibly use the module hash as key and allow overlapping handlers for same path.
192
+ pendingHandlers.set(modulePath, handler);
193
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.connection.fetchModule(modulePath);
194
+ }
195
+ });
196
+ break;
197
+ }
198
+ // In coming hot module
199
+ case 'module-update': {
200
+ const hotModules = data;
201
+ // Process each incoming hot module
202
+ hotModules.data.forEach(async ({ modulePath, src }) => {
203
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
204
+ eventType: 'hot-swapped',
205
+ modulePath,
206
+ });
207
+ // Step 1: extract the dependencies and owner path
208
+ const descriptors = extractDescriptorsFromSource(src);
209
+ if (descriptors && hmrClient) {
210
+ // Step 2: Wait for dependencies to be fetched, waiting here also pauses the hot module processing
211
+ await hmrClient.moduleHandlerHooks.fetchDependencies(descriptors.deps);
212
+ // Step 3: Evaluate the hot module
213
+ // Create temporary descriptor for the hot module
214
+ const hotModulePath = modulePath + `-hmr-${hotModuleCounter++}`;
215
+ const evaledModule = await (hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.moduleHandlerHooks.evaluateModule(descriptors.parentDescriptor, hotModulePath, adaptSourceForLex(src, hotModulePath, descriptors.parentDescriptor)));
216
+ // Step 4: Invoke callback handler to use the hot module
217
+ const handler = pendingHandlers.get(modulePath);
218
+ handler(evaledModule);
219
+ }
220
+ });
221
+ break;
222
+ }
223
+ case 'module-delete': {
224
+ const deletedModule = data;
225
+ deletedModule.data.forEach(({ modulePath }) => {
226
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
227
+ eventType: 'delete',
228
+ modulePath,
229
+ });
230
+ });
231
+ // A module was deleted
232
+ // reload page?
233
+ break;
234
+ }
235
+ case 'error':
236
+ // eslint-disable-next-line no-console
237
+ console.log('LWC dev server encountered an error, reloading page');
238
+ window.location.reload();
239
+ break;
240
+ }
241
+ }
242
+ function extractDescriptorsFromSource(src) {
243
+ const amdPattern = /^define\('([^']+)',\s*\[([^\]]*)\],/;
244
+ const match = amdPattern.exec(src);
245
+ if (match) {
246
+ return {
247
+ parentDescriptor: match[1],
248
+ deps: match[2].split(',').map((i) => i.trim().replace(/[']/g, '')),
249
+ };
250
+ }
251
+ }
252
+ /**
253
+ * Adapt source provided by dev server to LEX format.
254
+ * Note: This logic comes from [core:]BundleModuleDefFactory.processCompiledCode()
255
+ * @param src compiled module file
256
+ */
257
+ function adaptSourceForLex(src, hotModulePath, parentDescriptor) {
258
+ return src
259
+ .replace(`define('${parentDescriptor}',`, `function() { $A.componentService.addModule('${hotModulePath}', '${hotModulePath}',`)
260
+ .concat('}');
261
+ }
262
+ class HMRClient {
263
+ constructor(moduleHandlerHooks) {
264
+ this.notifyModuleUpdate = new NotifyModuleUpdate();
265
+ this.connection = new Connection();
266
+ this.moduleHandlerHooks = moduleHandlerHooks;
267
+ }
268
+ }
269
+ let hmrClient;
270
+ function initializeClient(protocol, host, port, hotModuleHandler, errorCallback, observer) {
271
+ if (hmrClient)
272
+ return;
273
+ hmrClient = new HMRClient(hotModuleHandler);
274
+ // Register any container specific observers
275
+ hmrClient.notifyModuleUpdate.register(observer);
276
+ // Register a console logger
277
+ hmrClient.notifyModuleUpdate.register(new ConsoleNotifier());
278
+ // Initialize connection to dev server
279
+ hmrClient.connection.init(protocol, host, port);
280
+ hmrClient.connection.initializeConnection(initCallback, messageCallback, errorCallback);
281
+ }
282
+
283
+ exports.accept = accept;
284
+ exports.acceptDeps = acceptDeps;
285
+ exports.initializeHmrClient = initializeClient;
286
+ exports.register = register;
287
+ //# sourceMappingURL=index.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/api.ts","../src/notify/notify.ts","../src/connection.ts","../src/notify/consoleNotifier.ts","../src/client.ts"],"sourcesContent":[null,null,null,null,null],"names":[],"mappings":";;;;;;;AAKA,MAAM,YAAY,GAAqC,IAAI,GAAG,EAAE,CAAC;AAOjD,SAAA,MAAM,CAAC,UAAkB,EAAE,EAAqB,EAAA;IAC5D,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;AACrD,IAAA,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACnB,IAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;AAKG;SACa,UAAU,CAAC,UAAkB,EAAE,UAAkB,EAAE,EAAqB,EAAA;IACpF,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;AACrD,IAAA,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACnB,IAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC;AAEM,MAAM,aAAa,GAAsC,IAAI,GAAG,EAAE,CAAC;AAC1E,MAAM,YAAY,GAAsC,IAAI,GAAG,EAAE,CAAC;AAClE;;;;;AAKG;SACa,QAAQ,CAAC,UAAkB,EAAE,IAAY,EAAE,cAAgC,EAAA;AACvF,IAAA,MAAM,WAAW,GAAyB;QACtC,UAAU;QACV,IAAI;QACJ,cAAc;KACjB,CAAC;IACF,MAAM,WAAW,GAAG,aAAa,CAAC,GAAG,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;IAC9D,IAAI,WAAW,EAAE;;;AAGb,QAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,WAAW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'./client';
2
+ export { accept, register, acceptDeps } from './api';
package/dist/index.js ADDED
@@ -0,0 +1,280 @@
1
+ /**
2
+ * LWC Hot Module Replacement(HMR) client code
3
+ */
4
+ const hotModuleCbs = new Map();
5
+ function accept(modulePath, cb) {
6
+ const callbacks = hotModuleCbs.get(modulePath) || [];
7
+ callbacks.push(cb);
8
+ hotModuleCbs.set(modulePath, callbacks);
9
+ }
10
+ /**
11
+ * API call for owner module to ingest updates to dependencies.
12
+ * @param ownerPath {string} The owner module's path or module identifier.
13
+ * @param modulePath {string} The module path.
14
+ * @param cb {function} The callback function to invoke for self update.
15
+ */
16
+ function acceptDeps(_ownerPath, modulePath, cb) {
17
+ const callbacks = hotModuleCbs.get(modulePath) || [];
18
+ callbacks.push(cb);
19
+ hotModuleCbs.set(modulePath, callbacks);
20
+ }
21
+ const activeModules = new Map();
22
+ const staleModules = new Map();
23
+ /**
24
+ * Register a module path used by the client along with its state.
25
+ * @param modulePath {string} The module path.
26
+ * @param hash {string} A hash representation of the module's source to perform freshness check.
27
+ * @param compileOptions {object} The compiler config that was used to bundle this module.
28
+ */
29
+ function register(modulePath, hash, compileOptions) {
30
+ const moduleState = {
31
+ modulePath,
32
+ hash,
33
+ compileOptions,
34
+ };
35
+ const staleModule = activeModules.get(moduleState.modulePath);
36
+ if (staleModule) {
37
+ // This is a new version of an existing module
38
+ // Potentially clean up old handlers, call dispose()
39
+ staleModules.set(modulePath, staleModule);
40
+ }
41
+ activeModules.set(modulePath, moduleState);
42
+ }
43
+ function updateHandler(modulePath) {
44
+ let callbacks = [];
45
+ if (activeModules.has(modulePath)) {
46
+ // Create a copy of the callbacks to retain the current list in a closure for when the hot
47
+ // module is available. Otherwise, the incoming hot module's callback will also be invoked
48
+ // and removed. Thus future updates won't have a callback to process.
49
+ callbacks = [...hotModuleCbs.get(modulePath)];
50
+ return (hotModule) => {
51
+ callbacks.forEach((cb) => {
52
+ cb(hotModule);
53
+ });
54
+ const existingCbs = hotModuleCbs.get(modulePath) || [];
55
+ hotModuleCbs.set(modulePath, existingCbs.filter((cb) => !callbacks.includes(cb)));
56
+ };
57
+ }
58
+ }
59
+ /**
60
+ * Get module state for all active modules on the client.
61
+ * @returns An array of objects containing modulePath, hash and compiler config.
62
+ */
63
+ function getActiveModules() {
64
+ return Array.from(activeModules.values());
65
+ }
66
+
67
+ /**
68
+ * This module is responsible for notfying the user about module updates in the server
69
+ **/
70
+ class NotifyModuleUpdate {
71
+ constructor() {
72
+ this.observers = new Set();
73
+ }
74
+ register(observer) {
75
+ if (observer) {
76
+ this.observers.add(observer);
77
+ }
78
+ }
79
+ deregister(observer) {
80
+ if (observer) {
81
+ this.observers.delete(observer);
82
+ }
83
+ }
84
+ notify(message) {
85
+ this.observers.forEach((observer) => observer.notify(message));
86
+ }
87
+ }
88
+
89
+ class Connection {
90
+ constructor() {
91
+ this.protocol = 'ws';
92
+ this.host = 'localhost';
93
+ this.port = '8080';
94
+ }
95
+ init(protocol, host, port) {
96
+ this.protocol = protocol;
97
+ this.host = host;
98
+ this.port = port;
99
+ }
100
+ fetchModule(modulePath) {
101
+ const fetchData = { type: 'fetch', data: { modulePath } };
102
+ // fetch the new module from the server
103
+ // eval it and return the new module
104
+ this.send(fetchData);
105
+ }
106
+ initializeConnection(initCallback, messageCallback, errorCallback) {
107
+ const socket = new WebSocket(`${this.protocol}://${this.host}:${this.port}`);
108
+ this.socket = socket;
109
+ this.socket.addEventListener('error', () => {
110
+ if (errorCallback) {
111
+ errorCallback(new Error('Failed to start a WebSocket connection. Running page without Local Development support.'));
112
+ }
113
+ });
114
+ this.socket.addEventListener('open', () => {
115
+ initCallback();
116
+ });
117
+ this.socket.addEventListener('message', ({ data }) => {
118
+ if (data) {
119
+ // When there is an update, handle the incoming message and request an updated module
120
+ messageCallback(JSON.parse(data));
121
+ }
122
+ });
123
+ }
124
+ send(data) {
125
+ if (this.socket && this.socket.readyState === this.socket.OPEN) {
126
+ this.socket.send(JSON.stringify(data));
127
+ }
128
+ }
129
+ close() {
130
+ var _a;
131
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
132
+ }
133
+ }
134
+
135
+ class ConsoleNotifier {
136
+ notify(message) {
137
+ switch (message.eventType) {
138
+ case 'create':
139
+ console.log(`A new module was added at ${message.modulePath}`);
140
+ break;
141
+ case 'delete':
142
+ console.log(`A module was deleted at ${message.modulePath}`);
143
+ break;
144
+ case 'update':
145
+ console.log(`A source change detected at ${message.modulePath}`);
146
+ break;
147
+ case 'hot-swapped':
148
+ console.log(`Receipt a hot module with path ${message.modulePath}, attempting to hot swap`);
149
+ break;
150
+ }
151
+ if (message.action) {
152
+ console.log(`Taking the following action on module update ${message.action.message}`);
153
+ }
154
+ }
155
+ }
156
+
157
+ function initCallback() {
158
+ const activeModules = getActiveModules();
159
+ const initData = {
160
+ type: 'init',
161
+ data: {
162
+ url: window.location.href,
163
+ activePaths: activeModules.map((m) => {
164
+ return { type: 'register', data: m };
165
+ }),
166
+ target: 'LEX',
167
+ },
168
+ };
169
+ if (activeModules.length) {
170
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.connection.send(initData);
171
+ }
172
+ }
173
+ const pendingHandlers = new Map();
174
+ let hotModuleCounter = 0;
175
+ function messageCallback(data) {
176
+ switch (data.type) {
177
+ // Some paths were updated
178
+ case 'update': {
179
+ const moduleUpdate = data;
180
+ moduleUpdate.data.forEach(({ modulePath }) => {
181
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
182
+ eventType: 'update',
183
+ modulePath,
184
+ });
185
+ const handler = updateHandler(modulePath);
186
+ if (handler) {
187
+ // Possibly use the module hash as key and allow overlapping handlers for same path.
188
+ pendingHandlers.set(modulePath, handler);
189
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.connection.fetchModule(modulePath);
190
+ }
191
+ });
192
+ break;
193
+ }
194
+ // In coming hot module
195
+ case 'module-update': {
196
+ const hotModules = data;
197
+ // Process each incoming hot module
198
+ hotModules.data.forEach(async ({ modulePath, src }) => {
199
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
200
+ eventType: 'hot-swapped',
201
+ modulePath,
202
+ });
203
+ // Step 1: extract the dependencies and owner path
204
+ const descriptors = extractDescriptorsFromSource(src);
205
+ if (descriptors && hmrClient) {
206
+ // Step 2: Wait for dependencies to be fetched, waiting here also pauses the hot module processing
207
+ await hmrClient.moduleHandlerHooks.fetchDependencies(descriptors.deps);
208
+ // Step 3: Evaluate the hot module
209
+ // Create temporary descriptor for the hot module
210
+ const hotModulePath = modulePath + `-hmr-${hotModuleCounter++}`;
211
+ const evaledModule = await (hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.moduleHandlerHooks.evaluateModule(descriptors.parentDescriptor, hotModulePath, adaptSourceForLex(src, hotModulePath, descriptors.parentDescriptor)));
212
+ // Step 4: Invoke callback handler to use the hot module
213
+ const handler = pendingHandlers.get(modulePath);
214
+ handler(evaledModule);
215
+ }
216
+ });
217
+ break;
218
+ }
219
+ case 'module-delete': {
220
+ const deletedModule = data;
221
+ deletedModule.data.forEach(({ modulePath }) => {
222
+ hmrClient === null || hmrClient === void 0 ? void 0 : hmrClient.notifyModuleUpdate.notify({
223
+ eventType: 'delete',
224
+ modulePath,
225
+ });
226
+ });
227
+ // A module was deleted
228
+ // reload page?
229
+ break;
230
+ }
231
+ case 'error':
232
+ // eslint-disable-next-line no-console
233
+ console.log('LWC dev server encountered an error, reloading page');
234
+ window.location.reload();
235
+ break;
236
+ }
237
+ }
238
+ function extractDescriptorsFromSource(src) {
239
+ const amdPattern = /^define\('([^']+)',\s*\[([^\]]*)\],/;
240
+ const match = amdPattern.exec(src);
241
+ if (match) {
242
+ return {
243
+ parentDescriptor: match[1],
244
+ deps: match[2].split(',').map((i) => i.trim().replace(/[']/g, '')),
245
+ };
246
+ }
247
+ }
248
+ /**
249
+ * Adapt source provided by dev server to LEX format.
250
+ * Note: This logic comes from [core:]BundleModuleDefFactory.processCompiledCode()
251
+ * @param src compiled module file
252
+ */
253
+ function adaptSourceForLex(src, hotModulePath, parentDescriptor) {
254
+ return src
255
+ .replace(`define('${parentDescriptor}',`, `function() { $A.componentService.addModule('${hotModulePath}', '${hotModulePath}',`)
256
+ .concat('}');
257
+ }
258
+ class HMRClient {
259
+ constructor(moduleHandlerHooks) {
260
+ this.notifyModuleUpdate = new NotifyModuleUpdate();
261
+ this.connection = new Connection();
262
+ this.moduleHandlerHooks = moduleHandlerHooks;
263
+ }
264
+ }
265
+ let hmrClient;
266
+ function initializeClient(protocol, host, port, hotModuleHandler, errorCallback, observer) {
267
+ if (hmrClient)
268
+ return;
269
+ hmrClient = new HMRClient(hotModuleHandler);
270
+ // Register any container specific observers
271
+ hmrClient.notifyModuleUpdate.register(observer);
272
+ // Register a console logger
273
+ hmrClient.notifyModuleUpdate.register(new ConsoleNotifier());
274
+ // Initialize connection to dev server
275
+ hmrClient.connection.init(protocol, host, port);
276
+ hmrClient.connection.initializeConnection(initCallback, messageCallback, errorCallback);
277
+ }
278
+
279
+ export { accept, acceptDeps, initializeClient as initializeHmrClient, register };
280
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/api.ts","../src/notify/notify.ts","../src/connection.ts","../src/notify/consoleNotifier.ts","../src/client.ts"],"sourcesContent":[null,null,null,null,null],"names":[],"mappings":";;;AAKA,MAAM,YAAY,GAAqC,IAAI,GAAG,EAAE,CAAC;AAOjD,SAAA,MAAM,CAAC,UAAkB,EAAE,EAAqB,EAAA;IAC5D,MAAM,SAAS,GAAG,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;AACrD,IAAA,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACnB,IAAA,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;AAKG;SACa,UAAU,CAAC,UAAkB,EAAE,UAAkB,EAAE,EAAqB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,CAAA;AAED,IAAI,SAAgC,CAAC;AACrB,SAAA,gBAAgB,CAC5B,QAAsB,EACtB,IAAY,EACZ,IAAY,EACZ,gBAAkC,EAClC,aAAsC,EACtC,QAA+B,EAAA;AAE/B,IAAA,IAAI,SAAS;QAAE,OAAO;AACtB,IAAA,SAAS,GAAG,IAAI,SAAS,CAAC,gBAAgB,CAAC,CAAC;;AAE5C,IAAA,SAAS,CAAC,kBAAkB,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;;IAEhD,SAAS,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,eAAe,EAAE,CAAC,CAAC;;IAE7D,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAChD,SAAS,CAAC,UAAU,CAAC,oBAAoB,CAAC,YAAY,EAAE,eAAe,EAAE,aAAa,CAAC,CAAC;AAC5F;;;;"}
@@ -0,0 +1,4 @@
1
+ import { ModuleUpdateMessage, ModuleUpdateObserver } from './notify';
2
+ export declare class ConsoleNotifier implements ModuleUpdateObserver {
3
+ notify(message: ModuleUpdateMessage): void;
4
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * This module is responsible for notfying the user about module updates in the server
3
+ **/
4
+ interface HMRAction {
5
+ message: string;
6
+ }
7
+ interface PageReloadAction {
8
+ message: string;
9
+ action?: () => boolean;
10
+ }
11
+ declare type ModuleUpdateAction = HMRAction | PageReloadAction;
12
+ export type ModuleUpdateMessage = {
13
+ modulePath: string;
14
+ eventType: 'update' | 'delete' | 'create' | 'hot-swapped';
15
+ action?: ModuleUpdateAction;
16
+ };
17
+ export type ModuleUpdateObserver = {
18
+ notify: (message: ModuleUpdateMessage) => void;
19
+ };
20
+ export declare class NotifyModuleUpdate {
21
+ observers: Set<ModuleUpdateObserver>;
22
+ register(observer: ModuleUpdateObserver | undefined): void;
23
+ deregister(observer: ModuleUpdateObserver | undefined): void;
24
+ notify(message: ModuleUpdateMessage): void;
25
+ }
26
+ export {};
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@lwc/hmr-client",
3
+ "description": "Provide hot module reloading capabilities to @lwc/engine-dom.",
4
+ "version": "7.0.0-6.6.3",
5
+ "keywords": [
6
+ "lwc dev server",
7
+ "lwc hmr plugin"
8
+ ],
9
+ "main": "dist/index.cjs.js",
10
+ "typings": "dist/index.d.ts",
11
+ "module": "dist/index.js",
12
+ "files": [
13
+ "dist",
14
+ "LICENSE.txt"
15
+ ],
16
+ "license": "SEE LICENSE IN LICENSE.txt",
17
+ "scripts": {
18
+ "build": "rollup --config ./scripts/rollup.config.js"
19
+ },
20
+ "dependencies": {},
21
+ "devDependencies": {
22
+ "@lwc/compiler": "6.6.3",
23
+ "@types/websocket": "^1.0.10",
24
+ "@lwc/lwc-dev-server-types": "7.0.0-6.6.3"
25
+ }
26
+ }