vite-plugin-rnw 0.0.1 → 0.0.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/README.md CHANGED
@@ -10,7 +10,7 @@ A vite plugin for React Native Web projects. (edited from a version of the react
10
10
  ```js
11
11
  // vite.config.js
12
12
  import { defineConfig } from "vite";
13
- import rnw from "vite-plugin-rnw";
13
+ import { rnw } from "vite-plugin-rnw";
14
14
 
15
15
  export default defineConfig({
16
16
  plugins: [rnw()],
@@ -25,7 +25,7 @@ Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to ad
25
25
 
26
26
  ```js
27
27
  import { defineConfig } from "vite";
28
- import rnw from "vite-plugin-rnw";
28
+ import { rnw } from "vite-plugin-rnw";
29
29
 
30
30
  export default defineConfig({
31
31
  plugins: [rnw({ include: /\.(js|jsx|ts|tsx)$/ })],
package/dist/index.cjs CHANGED
@@ -1,4 +1,3 @@
1
- Object.defineProperty(exports, '__esModule', { value: true });
2
1
  //#region rolldown:runtime
3
2
  var __create = Object.create;
4
3
  var __defProp = Object.defineProperty;
@@ -151,7 +150,7 @@ const getInitialOptions = (opts) => {
151
150
  optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
152
151
  };
153
152
  };
154
- function viteReactNativeWeb(opts = {}) {
153
+ function rnw(opts = {}) {
155
154
  var _opts$babel;
156
155
  const include = opts.include ?? defaultIncludeRE;
157
156
  const exclude = opts.exclude ?? defaultExcludeRE;
@@ -350,7 +349,7 @@ function viteReactNativeWeb(opts = {}) {
350
349
  viteReactRefresh
351
350
  ];
352
351
  }
353
- viteReactNativeWeb.preambleCode = preambleCode;
352
+ rnw.preambleCode = preambleCode;
354
353
  const loadedPlugin = /* @__PURE__ */ new Map();
355
354
  function loadPlugin(path) {
356
355
  const cached = loadedPlugin.get(path);
@@ -400,6 +399,6 @@ function ensureArray(value) {
400
399
  }
401
400
 
402
401
  //#endregion
403
- exports.default = viteReactNativeWeb;
402
+ exports.rnw = rnw;
404
403
  exports.silenceUseClientWarning = silenceUseClientWarning;
405
404
  module.exports.default = module.exports
package/dist/index.d.cts CHANGED
@@ -60,9 +60,9 @@ type ViteReactPluginApi = {
60
60
  */
61
61
  reactBabel?: ReactBabelHook;
62
62
  };
63
- declare function viteReactNativeWeb(opts?: Options): Plugin[];
64
- declare namespace viteReactNativeWeb {
63
+ declare function rnw(opts?: Options): Plugin[];
64
+ declare namespace rnw {
65
65
  var preambleCode: string;
66
66
  }
67
67
  //#endregion
68
- export { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi, viteReactNativeWeb as default, silenceUseClientWarning };
68
+ export { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi, rnw, silenceUseClientWarning };
package/dist/index.d.ts CHANGED
@@ -60,9 +60,9 @@ type ViteReactPluginApi = {
60
60
  */
61
61
  reactBabel?: ReactBabelHook;
62
62
  };
63
- declare function viteReactNativeWeb(opts?: Options): Plugin[];
64
- declare namespace viteReactNativeWeb {
63
+ declare function rnw(opts?: Options): Plugin[];
64
+ declare namespace rnw {
65
65
  var preambleCode: string;
66
66
  }
67
67
  //#endregion
68
- export { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi, viteReactNativeWeb as default, silenceUseClientWarning };
68
+ export { BabelOptions, Options, ReactBabelOptions, ViteReactPluginApi, rnw, silenceUseClientWarning };
package/dist/index.js CHANGED
@@ -128,7 +128,7 @@ const getInitialOptions = (opts) => {
128
128
  optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
129
129
  };
130
130
  };
131
- function viteReactNativeWeb(opts = {}) {
131
+ function rnw(opts = {}) {
132
132
  var _opts$babel;
133
133
  const include = opts.include ?? defaultIncludeRE;
134
134
  const exclude = opts.exclude ?? defaultExcludeRE;
@@ -327,7 +327,7 @@ function viteReactNativeWeb(opts = {}) {
327
327
  viteReactRefresh
328
328
  ];
329
329
  }
330
- viteReactNativeWeb.preambleCode = preambleCode;
330
+ rnw.preambleCode = preambleCode;
331
331
  const loadedPlugin = /* @__PURE__ */ new Map();
332
332
  function loadPlugin(path) {
333
333
  const cached = loadedPlugin.get(path);
@@ -377,4 +377,4 @@ function ensureArray(value) {
377
377
  }
378
378
 
379
379
  //#endregion
380
- export { viteReactNativeWeb as default, silenceUseClientWarning };
380
+ export { rnw, silenceUseClientWarning };
@@ -0,0 +1,648 @@
1
+ // from https://github.com/vitejs/vite-plugin-react/blob/main/packages/common/refresh-runtime.js
2
+ /* global window */
3
+
4
+ /*! Copyright (c) Meta Platforms, Inc. and affiliates. **/
5
+ /**
6
+ * This is simplified pure-js version of https://github.com/facebook/react/blob/main/packages/react-refresh/src/ReactFreshRuntime.js
7
+ * without IE11 compatibility and verbose isDev checks.
8
+ * Some utils are appended at the bottom for HMR integration.
9
+ */
10
+
11
+ const REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
12
+ const REACT_MEMO_TYPE = Symbol.for("react.memo");
13
+
14
+ // We never remove these associations.
15
+ // It's OK to reference families, but use WeakMap/Set for types.
16
+ let allFamiliesByID = new Map();
17
+ let allFamiliesByType = new WeakMap();
18
+ let allSignaturesByType = new WeakMap();
19
+
20
+ // This WeakMap is read by React, so we only put families
21
+ // that have actually been edited here. This keeps checks fast.
22
+ const updatedFamiliesByType = new WeakMap();
23
+
24
+ // This is cleared on every performReactRefresh() call.
25
+ // It is an array of [Family, NextType] tuples.
26
+ let pendingUpdates = [];
27
+
28
+ // This is injected by the renderer via DevTools global hook.
29
+ const helpersByRendererID = new Map();
30
+
31
+ const helpersByRoot = new Map();
32
+
33
+ // We keep track of mounted roots so we can schedule updates.
34
+ const mountedRoots = new Set();
35
+ // If a root captures an error, we remember it so we can retry on edit.
36
+ const failedRoots = new Set();
37
+
38
+ // We also remember the last element for every root.
39
+ // It needs to be weak because we do this even for roots that failed to mount.
40
+ // If there is no WeakMap, we won't attempt to do retrying.
41
+ let rootElements = new WeakMap();
42
+ let isPerformingRefresh = false;
43
+
44
+ function computeFullKey(signature) {
45
+ if (signature.fullKey !== null) {
46
+ return signature.fullKey;
47
+ }
48
+
49
+ let fullKey = signature.ownKey;
50
+ let hooks;
51
+ try {
52
+ hooks = signature.getCustomHooks();
53
+ } catch (err) {
54
+ // This can happen in an edge case, e.g. if expression like Foo.useSomething
55
+ // depends on Foo which is lazily initialized during rendering.
56
+ // In that case just assume we'll have to remount.
57
+ signature.forceReset = true;
58
+ signature.fullKey = fullKey;
59
+ return fullKey;
60
+ }
61
+
62
+ for (let i = 0; i < hooks.length; i++) {
63
+ const hook = hooks[i];
64
+ if (typeof hook !== "function") {
65
+ // Something's wrong. Assume we need to remount.
66
+ signature.forceReset = true;
67
+ signature.fullKey = fullKey;
68
+ return fullKey;
69
+ }
70
+ const nestedHookSignature = allSignaturesByType.get(hook);
71
+ if (nestedHookSignature === undefined) {
72
+ // No signature means Hook wasn't in the source code, e.g. in a library.
73
+ // We'll skip it because we can assume it won't change during this session.
74
+ continue;
75
+ }
76
+ const nestedHookKey = computeFullKey(nestedHookSignature);
77
+ if (nestedHookSignature.forceReset) {
78
+ signature.forceReset = true;
79
+ }
80
+ fullKey += "\n---\n" + nestedHookKey;
81
+ }
82
+
83
+ signature.fullKey = fullKey;
84
+ return fullKey;
85
+ }
86
+
87
+ function haveEqualSignatures(prevType, nextType) {
88
+ const prevSignature = allSignaturesByType.get(prevType);
89
+ const nextSignature = allSignaturesByType.get(nextType);
90
+
91
+ if (prevSignature === undefined && nextSignature === undefined) {
92
+ return true;
93
+ }
94
+ if (prevSignature === undefined || nextSignature === undefined) {
95
+ return false;
96
+ }
97
+ if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
98
+ return false;
99
+ }
100
+ if (nextSignature.forceReset) {
101
+ return false;
102
+ }
103
+
104
+ return true;
105
+ }
106
+
107
+ function isReactClass(type) {
108
+ return type.prototype && type.prototype.isReactComponent;
109
+ }
110
+
111
+ function canPreserveStateBetween(prevType, nextType) {
112
+ if (isReactClass(prevType) || isReactClass(nextType)) {
113
+ return false;
114
+ }
115
+ if (haveEqualSignatures(prevType, nextType)) {
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+
121
+ function resolveFamily(type) {
122
+ // Only check updated types to keep lookups fast.
123
+ return updatedFamiliesByType.get(type);
124
+ }
125
+
126
+ // This is a safety mechanism to protect against rogue getters and Proxies.
127
+ function getProperty(object, property) {
128
+ try {
129
+ return object[property];
130
+ } catch (err) {
131
+ // Intentionally ignore.
132
+ return undefined;
133
+ }
134
+ }
135
+
136
+ function performReactRefresh() {
137
+ if (pendingUpdates.length === 0) {
138
+ return null;
139
+ }
140
+ if (isPerformingRefresh) {
141
+ return null;
142
+ }
143
+
144
+ isPerformingRefresh = true;
145
+ try {
146
+ const staleFamilies = new Set();
147
+ const updatedFamilies = new Set();
148
+
149
+ const updates = pendingUpdates;
150
+ pendingUpdates = [];
151
+ updates.forEach(([family, nextType]) => {
152
+ // Now that we got a real edit, we can create associations
153
+ // that will be read by the React reconciler.
154
+ const prevType = family.current;
155
+ updatedFamiliesByType.set(prevType, family);
156
+ updatedFamiliesByType.set(nextType, family);
157
+ family.current = nextType;
158
+
159
+ // Determine whether this should be a re-render or a re-mount.
160
+ if (canPreserveStateBetween(prevType, nextType)) {
161
+ updatedFamilies.add(family);
162
+ } else {
163
+ staleFamilies.add(family);
164
+ }
165
+ });
166
+
167
+ // TODO: rename these fields to something more meaningful.
168
+ const update = {
169
+ updatedFamilies, // Families that will re-render preserving state
170
+ staleFamilies, // Families that will be remounted
171
+ };
172
+
173
+ helpersByRendererID.forEach((helpers) => {
174
+ // Even if there are no roots, set the handler on first update.
175
+ // This ensures that if *new* roots are mounted, they'll use the resolve handler.
176
+ helpers.setRefreshHandler(resolveFamily);
177
+ });
178
+
179
+ let didError = false;
180
+ let firstError = null;
181
+
182
+ // We snapshot maps and sets that are mutated during commits.
183
+ // If we don't do this, there is a risk they will be mutated while
184
+ // we iterate over them. For example, trying to recover a failed root
185
+ // may cause another root to be added to the failed list -- an infinite loop.
186
+ const failedRootsSnapshot = new Set(failedRoots);
187
+ const mountedRootsSnapshot = new Set(mountedRoots);
188
+ const helpersByRootSnapshot = new Map(helpersByRoot);
189
+
190
+ failedRootsSnapshot.forEach((root) => {
191
+ const helpers = helpersByRootSnapshot.get(root);
192
+ if (helpers === undefined) {
193
+ throw new Error(
194
+ "Could not find helpers for a root. This is a bug in React Refresh."
195
+ );
196
+ }
197
+ if (!failedRoots.has(root)) {
198
+ // No longer failed.
199
+ }
200
+ if (rootElements === null) {
201
+ return;
202
+ }
203
+ if (!rootElements.has(root)) {
204
+ return;
205
+ }
206
+ const element = rootElements.get(root);
207
+ try {
208
+ helpers.scheduleRoot(root, element);
209
+ } catch (err) {
210
+ if (!didError) {
211
+ didError = true;
212
+ firstError = err;
213
+ }
214
+ // Keep trying other roots.
215
+ }
216
+ });
217
+ mountedRootsSnapshot.forEach((root) => {
218
+ const helpers = helpersByRootSnapshot.get(root);
219
+ if (helpers === undefined) {
220
+ throw new Error(
221
+ "Could not find helpers for a root. This is a bug in React Refresh."
222
+ );
223
+ }
224
+ if (!mountedRoots.has(root)) {
225
+ // No longer mounted.
226
+ }
227
+ try {
228
+ helpers.scheduleRefresh(root, update);
229
+ } catch (err) {
230
+ if (!didError) {
231
+ didError = true;
232
+ firstError = err;
233
+ }
234
+ // Keep trying other roots.
235
+ }
236
+ });
237
+ if (didError) {
238
+ throw firstError;
239
+ }
240
+ return update;
241
+ } finally {
242
+ isPerformingRefresh = false;
243
+ }
244
+ }
245
+
246
+ function register(type, id) {
247
+ if (type === null) {
248
+ return;
249
+ }
250
+ if (typeof type !== "function" && typeof type !== "object") {
251
+ return;
252
+ }
253
+
254
+ // This can happen in an edge case, e.g. if we register
255
+ // return value of a HOC but it returns a cached component.
256
+ // Ignore anything but the first registration for each type.
257
+ if (allFamiliesByType.has(type)) {
258
+ return;
259
+ }
260
+ // Create family or remember to update it.
261
+ // None of this bookkeeping affects reconciliation
262
+ // until the first performReactRefresh() call above.
263
+ let family = allFamiliesByID.get(id);
264
+ if (family === undefined) {
265
+ family = { current: type };
266
+ allFamiliesByID.set(id, family);
267
+ } else {
268
+ pendingUpdates.push([family, type]);
269
+ }
270
+ allFamiliesByType.set(type, family);
271
+
272
+ // Visit inner types because we might not have registered them.
273
+ if (typeof type === "object" && type !== null) {
274
+ switch (getProperty(type, "$$typeof")) {
275
+ case REACT_FORWARD_REF_TYPE:
276
+ register(type.render, id + "$render");
277
+ break;
278
+ case REACT_MEMO_TYPE:
279
+ register(type.type, id + "$type");
280
+ break;
281
+ }
282
+ }
283
+ }
284
+
285
+ function setSignature(type, key, forceReset, getCustomHooks) {
286
+ if (!allSignaturesByType.has(type)) {
287
+ allSignaturesByType.set(type, {
288
+ forceReset,
289
+ ownKey: key,
290
+ fullKey: null,
291
+ getCustomHooks: getCustomHooks || (() => []),
292
+ });
293
+ }
294
+ // Visit inner types because we might not have signed them.
295
+ if (typeof type === "object" && type !== null) {
296
+ switch (getProperty(type, "$$typeof")) {
297
+ case REACT_FORWARD_REF_TYPE:
298
+ setSignature(type.render, key, forceReset, getCustomHooks);
299
+ break;
300
+ case REACT_MEMO_TYPE:
301
+ setSignature(type.type, key, forceReset, getCustomHooks);
302
+ break;
303
+ }
304
+ }
305
+ }
306
+
307
+ // This is lazily called during first render for a type.
308
+ // It captures Hook list at that time so inline requires don't break comparisons.
309
+ function collectCustomHooksForSignature(type) {
310
+ const signature = allSignaturesByType.get(type);
311
+ if (signature !== undefined) {
312
+ computeFullKey(signature);
313
+ }
314
+ }
315
+
316
+ export function injectIntoGlobalHook(globalObject) {
317
+ // For React Native, the global hook will be set up by require('react-devtools-core').
318
+ // That code will run before us. So we need to monkeypatch functions on existing hook.
319
+
320
+ // For React Web, the global hook will be set up by the extension.
321
+ // This will also run before us.
322
+ let hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__;
323
+ if (hook === undefined) {
324
+ // However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
325
+ // Note that in this case it's important that renderer code runs *after* this method call.
326
+ // Otherwise, the renderer will think that there is no global hook, and won't do the injection.
327
+ let nextID = 0;
328
+ globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
329
+ renderers: new Map(),
330
+ supportsFiber: true,
331
+ inject: (injected) => nextID++,
332
+ onScheduleFiberRoot: (id, root, children) => {},
333
+ onCommitFiberRoot: (id, root, maybePriorityLevel, didError) => {},
334
+ onCommitFiberUnmount() {},
335
+ };
336
+ }
337
+
338
+ if (hook.isDisabled) {
339
+ // This isn't a real property on the hook, but it can be set to opt out
340
+ // of DevTools integration and associated warnings and logs.
341
+ // Using console['warn'] to evade Babel and ESLint
342
+ console["warn"](
343
+ "Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). " +
344
+ "Fast Refresh is not compatible with this shim and will be disabled."
345
+ );
346
+ return;
347
+ }
348
+
349
+ // Here, we just want to get a reference to scheduleRefresh.
350
+ const oldInject = hook.inject;
351
+ hook.inject = function (injected) {
352
+ const id = oldInject.apply(this, arguments);
353
+ if (
354
+ typeof injected.scheduleRefresh === "function" &&
355
+ typeof injected.setRefreshHandler === "function"
356
+ ) {
357
+ // This version supports React Refresh.
358
+ helpersByRendererID.set(id, injected);
359
+ }
360
+ return id;
361
+ };
362
+
363
+ // Do the same for any already injected roots.
364
+ // This is useful if ReactDOM has already been initialized.
365
+ // https://github.com/facebook/react/issues/17626
366
+ hook.renderers.forEach((injected, id) => {
367
+ if (
368
+ typeof injected.scheduleRefresh === "function" &&
369
+ typeof injected.setRefreshHandler === "function"
370
+ ) {
371
+ // This version supports React Refresh.
372
+ helpersByRendererID.set(id, injected);
373
+ }
374
+ });
375
+
376
+ // We also want to track currently mounted roots.
377
+ const oldOnCommitFiberRoot = hook.onCommitFiberRoot;
378
+ const oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || (() => {});
379
+ hook.onScheduleFiberRoot = function (id, root, children) {
380
+ if (!isPerformingRefresh) {
381
+ // If it was intentionally scheduled, don't attempt to restore.
382
+ // This includes intentionally scheduled unmounts.
383
+ failedRoots.delete(root);
384
+ if (rootElements !== null) {
385
+ rootElements.set(root, children);
386
+ }
387
+ }
388
+ return oldOnScheduleFiberRoot.apply(this, arguments);
389
+ };
390
+ hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
391
+ const helpers = helpersByRendererID.get(id);
392
+ if (helpers !== undefined) {
393
+ helpersByRoot.set(root, helpers);
394
+
395
+ const current = root.current;
396
+ const alternate = current.alternate;
397
+
398
+ // We need to determine whether this root has just (un)mounted.
399
+ // This logic is copy-pasted from similar logic in the DevTools backend.
400
+ // If this breaks with some refactoring, you'll want to update DevTools too.
401
+
402
+ if (alternate !== null) {
403
+ const wasMounted =
404
+ alternate.memoizedState != null &&
405
+ alternate.memoizedState.element != null &&
406
+ mountedRoots.has(root);
407
+
408
+ const isMounted =
409
+ current.memoizedState != null &&
410
+ current.memoizedState.element != null;
411
+
412
+ if (!wasMounted && isMounted) {
413
+ // Mount a new root.
414
+ mountedRoots.add(root);
415
+ failedRoots.delete(root);
416
+ } else if (wasMounted && isMounted) {
417
+ // Update an existing root.
418
+ // This doesn't affect our mounted root Set.
419
+ } else if (wasMounted && !isMounted) {
420
+ // Unmount an existing root.
421
+ mountedRoots.delete(root);
422
+ if (didError) {
423
+ // We'll remount it on future edits.
424
+ failedRoots.add(root);
425
+ } else {
426
+ helpersByRoot.delete(root);
427
+ }
428
+ } else if (!wasMounted && !isMounted) {
429
+ if (didError) {
430
+ // We'll remount it on future edits.
431
+ failedRoots.add(root);
432
+ }
433
+ }
434
+ } else {
435
+ // Mount a new root.
436
+ mountedRoots.add(root);
437
+ }
438
+ }
439
+
440
+ // Always call the decorated DevTools hook.
441
+ return oldOnCommitFiberRoot.apply(this, arguments);
442
+ };
443
+ }
444
+
445
+ // This is a wrapper over more primitive functions for setting signature.
446
+ // Signatures let us decide whether the Hook order has changed on refresh.
447
+ //
448
+ // This function is intended to be used as a transform target, e.g.:
449
+ // var _s = createSignatureFunctionForTransform()
450
+ //
451
+ // function Hello() {
452
+ // const [foo, setFoo] = useState(0);
453
+ // const value = useCustomHook();
454
+ // _s(); /* Call without arguments triggers collecting the custom Hook list.
455
+ // * This doesn't happen during the module evaluation because we
456
+ // * don't want to change the module order with inline requires.
457
+ // * Next calls are noops. */
458
+ // return <h1>Hi</h1>;
459
+ // }
460
+ //
461
+ // /* Call with arguments attaches the signature to the type: */
462
+ // _s(
463
+ // Hello,
464
+ // 'useState{[foo, setFoo]}(0)',
465
+ // () => [useCustomHook], /* Lazy to avoid triggering inline requires */
466
+ // );
467
+ export function createSignatureFunctionForTransform() {
468
+ let savedType;
469
+ let hasCustomHooks;
470
+ let didCollectHooks = false;
471
+ return function (type, key, forceReset, getCustomHooks) {
472
+ if (typeof key === "string") {
473
+ // We're in the initial phase that associates signatures
474
+ // with the functions. Note this may be called multiple times
475
+ // in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
476
+ if (!savedType) {
477
+ // We're in the innermost call, so this is the actual type.
478
+ // $FlowFixMe[escaped-generic] discovered when updating Flow
479
+ savedType = type;
480
+ hasCustomHooks = typeof getCustomHooks === "function";
481
+ }
482
+ // Set the signature for all types (even wrappers!) in case
483
+ // they have no signatures of their own. This is to prevent
484
+ // problems like https://github.com/facebook/react/issues/20417.
485
+ if (
486
+ type != null &&
487
+ (typeof type === "function" || typeof type === "object")
488
+ ) {
489
+ setSignature(type, key, forceReset, getCustomHooks);
490
+ }
491
+ return type;
492
+ } else {
493
+ // We're in the _s() call without arguments, which means
494
+ // this is the time to collect custom Hook signatures.
495
+ // Only do this once. This path is hot and runs *inside* every render!
496
+ if (!didCollectHooks && hasCustomHooks) {
497
+ didCollectHooks = true;
498
+ collectCustomHooksForSignature(savedType);
499
+ }
500
+ }
501
+ };
502
+ }
503
+
504
+ function isLikelyComponentType(type) {
505
+ switch (typeof type) {
506
+ case "function": {
507
+ // First, deal with classes.
508
+ if (type.prototype != null) {
509
+ if (type.prototype.isReactComponent) {
510
+ // React class.
511
+ return true;
512
+ }
513
+ const ownNames = Object.getOwnPropertyNames(type.prototype);
514
+ if (ownNames.length > 1 || ownNames[0] !== "constructor") {
515
+ // This looks like a class.
516
+ return false;
517
+ }
518
+
519
+ if (type.prototype.__proto__ !== Object.prototype) {
520
+ // It has a superclass.
521
+ return false;
522
+ }
523
+ // Pass through.
524
+ // This looks like a regular function with empty prototype.
525
+ }
526
+ // For plain functions and arrows, use name as a heuristic.
527
+ const name = type.name || type.displayName;
528
+ return typeof name === "string" && /^[A-Z]/.test(name);
529
+ }
530
+ case "object": {
531
+ if (type != null) {
532
+ switch (getProperty(type, "$$typeof")) {
533
+ case REACT_FORWARD_REF_TYPE:
534
+ case REACT_MEMO_TYPE:
535
+ // Definitely React components.
536
+ return true;
537
+ default:
538
+ return false;
539
+ }
540
+ }
541
+ return false;
542
+ }
543
+ default: {
544
+ return false;
545
+ }
546
+ }
547
+ }
548
+
549
+ /**
550
+ * Plugin utils
551
+ */
552
+
553
+ export function getRefreshReg(filename) {
554
+ return (type, id) => register(type, filename + " " + id);
555
+ }
556
+
557
+ // Taken from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/lib/runtime/RefreshUtils.js#L141
558
+ // This allows to resister components not detected by SWC like styled component
559
+ export function registerExportsForReactRefresh(filename, moduleExports) {
560
+ for (const key in moduleExports) {
561
+ if (key === "__esModule") continue;
562
+ const exportValue = moduleExports[key];
563
+ if (isLikelyComponentType(exportValue)) {
564
+ // 'export' is required to avoid key collision when renamed exports that
565
+ // shadow a local component name: https://github.com/vitejs/vite-plugin-react/issues/116
566
+ // The register function has an identity check to not register twice the same component,
567
+ // so this is safe to not used the same key here.
568
+ register(exportValue, filename + " export " + key);
569
+ }
570
+ }
571
+ }
572
+
573
+ function debounce(fn, delay) {
574
+ let handle;
575
+ return () => {
576
+ clearTimeout(handle);
577
+ handle = setTimeout(fn, delay);
578
+ };
579
+ }
580
+
581
+ const hooks = [];
582
+ window.__registerBeforePerformReactRefresh = (cb) => {
583
+ hooks.push(cb);
584
+ };
585
+ const enqueueUpdate = debounce(async () => {
586
+ if (hooks.length) await Promise.all(hooks.map((cb) => cb()));
587
+ performReactRefresh();
588
+ }, 16);
589
+
590
+ export function validateRefreshBoundaryAndEnqueueUpdate(
591
+ id,
592
+ prevExports,
593
+ nextExports
594
+ ) {
595
+ const ignoredExports = window.__getReactRefreshIgnoredExports?.({ id }) ?? [];
596
+ if (
597
+ predicateOnExport(
598
+ ignoredExports,
599
+ prevExports,
600
+ (key) => key in nextExports
601
+ ) !== true
602
+ ) {
603
+ return "Could not Fast Refresh (export removed)";
604
+ }
605
+ if (
606
+ predicateOnExport(
607
+ ignoredExports,
608
+ nextExports,
609
+ (key) => key in prevExports
610
+ ) !== true
611
+ ) {
612
+ return "Could not Fast Refresh (new export)";
613
+ }
614
+
615
+ let hasExports = false;
616
+ const allExportsAreComponentsOrUnchanged = predicateOnExport(
617
+ ignoredExports,
618
+ nextExports,
619
+ (key, value) => {
620
+ hasExports = true;
621
+ if (isLikelyComponentType(value)) return true;
622
+ return prevExports[key] === nextExports[key];
623
+ }
624
+ );
625
+ if (hasExports && allExportsAreComponentsOrUnchanged === true) {
626
+ enqueueUpdate();
627
+ } else {
628
+ return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`;
629
+ }
630
+ }
631
+
632
+ function predicateOnExport(ignoredExports, moduleExports, predicate) {
633
+ for (const key in moduleExports) {
634
+ if (key === "__esModule") continue;
635
+ if (ignoredExports.includes(key)) continue;
636
+ const desc = Object.getOwnPropertyDescriptor(moduleExports, key);
637
+ if (desc && desc.get) return key;
638
+ if (!predicate(key, moduleExports[key])) return key;
639
+ }
640
+ return true;
641
+ }
642
+
643
+ // Hides vite-ignored dynamic import so that Vite can skip analysis if no other
644
+ // dynamic import is present (https://github.com/vitejs/vite/pull/12732)
645
+ export const __hmr_import = (module) => import(/* @vite-ignore */ module);
646
+
647
+ // For backwards compatibility with @vitejs/plugin-react.
648
+ export default { injectIntoGlobalHook };
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1",
2
+ "version": "0.0.3",
3
3
  "name": "vite-plugin-rnw",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",