@porotkin/vite-plugin-react-kotlinjs 0.0.1
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.md +201 -0
- package/README.md +66 -0
- package/package.json +31 -0
- package/src/index.js +28 -0
- package/src/refresh-runtime.js +663 -0
- package/src/refresh-wrapper.js +45 -0
- package/src/vite-babel.js +111 -0
- package/src/vite-react-refresh.js +50 -0
- package/src/warning.js +26 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Vite Plugin React KotlinJS
|
|
2
|
+
|
|
3
|
+
A Vite plugin that enables Fast Refresh support for Kotlin/JS React applications.
|
|
4
|
+
|
|
5
|
+
This plugin is inspired by the original
|
|
6
|
+
[@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/main) and adapted to work with Kotlin/JS.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
Add the following dependency to your `build.gradle.kts`:
|
|
11
|
+
```kotlin
|
|
12
|
+
dependencies {
|
|
13
|
+
jsMainImplementation(devNpm("@porotkin/vite-plugin-react-kotlinjs", "^0.0.1"))
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
> Source set can be changed to suit your needs (e.g. `webMain` instead)
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
Add the plugin to your `vite.config.js`:
|
|
22
|
+
```javascript
|
|
23
|
+
import reactRefresh from '@porotkin/vite-plugin-react-kotlinjs'
|
|
24
|
+
|
|
25
|
+
export default defineConfig(() => {
|
|
26
|
+
return {
|
|
27
|
+
plugins: [
|
|
28
|
+
reactRefresh(),
|
|
29
|
+
],
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Options
|
|
35
|
+
|
|
36
|
+
The plugin accepts the following options:
|
|
37
|
+
|
|
38
|
+
### `include`
|
|
39
|
+
|
|
40
|
+
- **Type:** `string | RegExp | Array<string | RegExp>`
|
|
41
|
+
- **Default:** `"**/*.mjs"`
|
|
42
|
+
|
|
43
|
+
Files to include for processing. By default, all `.mjs` files are included.
|
|
44
|
+
|
|
45
|
+
### `exclude`
|
|
46
|
+
|
|
47
|
+
- **Type:** `string | RegExp | Array<string | RegExp>`
|
|
48
|
+
- **Default:** `["**/use*.mjs", "**/Main.mjs"]`
|
|
49
|
+
|
|
50
|
+
Files to exclude from processing. By default, excludes hooks (files starting with `use`) and the main entry point.
|
|
51
|
+
|
|
52
|
+
### `getComponentName`
|
|
53
|
+
|
|
54
|
+
- **Type:** `(code: string) => string | undefined`
|
|
55
|
+
- **Default:** Extracts component names from Kotlin/JS lambda patterns
|
|
56
|
+
|
|
57
|
+
Custom function to extract React component names from the code. Useful if your Kotlin/JS compiler generates different patterns.
|
|
58
|
+
|
|
59
|
+
## How it works
|
|
60
|
+
|
|
61
|
+
This plugin combines Babel transformation with React Refresh runtime to provide hot module replacement for Kotlin/JS React components, preserving component state during development.
|
|
62
|
+
|
|
63
|
+
## Why @vitejs/plugin-react-refresh is not enough?
|
|
64
|
+
|
|
65
|
+
- Kotlin/JS generates named exports for components, which makes it impossible to use the default export.
|
|
66
|
+
- Standard React Refresh Babel plugin does not recognize the generated component variable that actually returns the React node.
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@porotkin/vite-plugin-react-kotlinjs",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Support React fast refresh in Kotlin/JS",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Mikhail Porotkin",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/porotkin/vite-plugin-react-kotlinjs.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"vite-plugin-react-kotlinjs",
|
|
13
|
+
"react-refresh-kotlinjs"
|
|
14
|
+
],
|
|
15
|
+
"files": [
|
|
16
|
+
"src"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": "./src/index.js",
|
|
20
|
+
"scripts": {
|
|
21
|
+
"postinstall": "node copyRefreshRuntime.js"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@babel/core": "^7.28.4",
|
|
25
|
+
"@rolldown/pluginutils": "1.0.0-beta.41",
|
|
26
|
+
"react-refresh": "^0.17.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@vitejs/plugin-react": "5.0.4"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {createFilter} from 'vite'
|
|
2
|
+
import {viteBabelPlugin} from './vite-babel.js'
|
|
3
|
+
import {viteReactRefreshPlugin} from './vite-react-refresh.js'
|
|
4
|
+
import {makeIdFiltersToMatchWithQuery} from "@rolldown/pluginutils";
|
|
5
|
+
|
|
6
|
+
export default (options) => {
|
|
7
|
+
const defaultIncludeRE = makeIdFiltersToMatchWithQuery("**/*.mjs");
|
|
8
|
+
const defaultExcludeRE = [
|
|
9
|
+
makeIdFiltersToMatchWithQuery("**/use*.mjs"),
|
|
10
|
+
"**/Main.mjs",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
const include = options?.include ?? defaultIncludeRE;
|
|
14
|
+
const exclude = options?.exclude ?? defaultExcludeRE;
|
|
15
|
+
const filter = createFilter(include, exclude);
|
|
16
|
+
|
|
17
|
+
const derivedOptions = {
|
|
18
|
+
skipFastRefresh: true,
|
|
19
|
+
getComponentName: (code) => code.match(/function ([A-Za-z]+)\$lambda\(\$this\$FC\) {/)?.[1],
|
|
20
|
+
filter,
|
|
21
|
+
...options,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
return [
|
|
25
|
+
viteBabelPlugin(derivedOptions),
|
|
26
|
+
viteReactRefreshPlugin(derivedOptions),
|
|
27
|
+
];
|
|
28
|
+
}
|
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
/* global window */
|
|
2
|
+
/* eslint-disable eqeqeq, prefer-const, @typescript-eslint/no-empty-function */
|
|
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
|
+
export 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 && current.memoizedState.element != null
|
|
410
|
+
|
|
411
|
+
if (!wasMounted && isMounted) {
|
|
412
|
+
// Mount a new root.
|
|
413
|
+
mountedRoots.add(root)
|
|
414
|
+
failedRoots.delete(root)
|
|
415
|
+
} else if (wasMounted && isMounted) {
|
|
416
|
+
// Update an existing root.
|
|
417
|
+
// This doesn't affect our mounted root Set.
|
|
418
|
+
} else if (wasMounted && !isMounted) {
|
|
419
|
+
// Unmount an existing root.
|
|
420
|
+
mountedRoots.delete(root)
|
|
421
|
+
if (didError) {
|
|
422
|
+
// We'll remount it on future edits.
|
|
423
|
+
failedRoots.add(root)
|
|
424
|
+
} else {
|
|
425
|
+
helpersByRoot.delete(root)
|
|
426
|
+
}
|
|
427
|
+
} else if (!wasMounted && !isMounted) {
|
|
428
|
+
if (didError) {
|
|
429
|
+
// We'll remount it on future edits.
|
|
430
|
+
failedRoots.add(root)
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
} else {
|
|
434
|
+
// Mount a new root.
|
|
435
|
+
mountedRoots.add(root)
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Always call the decorated DevTools hook.
|
|
440
|
+
return oldOnCommitFiberRoot.apply(this, arguments)
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// This is a wrapper over more primitive functions for setting signature.
|
|
445
|
+
// Signatures let us decide whether the Hook order has changed on refresh.
|
|
446
|
+
//
|
|
447
|
+
// This function is intended to be used as a transform target, e.g.:
|
|
448
|
+
// var _s = createSignatureFunctionForTransform()
|
|
449
|
+
//
|
|
450
|
+
// function Hello() {
|
|
451
|
+
// const [foo, setFoo] = useState(0);
|
|
452
|
+
// const value = useCustomHook();
|
|
453
|
+
// _s(); /* Call without arguments triggers collecting the custom Hook list.
|
|
454
|
+
// * This doesn't happen during the module evaluation because we
|
|
455
|
+
// * don't want to change the module order with inline requires.
|
|
456
|
+
// * Next calls are noops. */
|
|
457
|
+
// return <h1>Hi</h1>;
|
|
458
|
+
// }
|
|
459
|
+
//
|
|
460
|
+
// /* Call with arguments attaches the signature to the type: */
|
|
461
|
+
// _s(
|
|
462
|
+
// Hello,
|
|
463
|
+
// 'useState{[foo, setFoo]}(0)',
|
|
464
|
+
// () => [useCustomHook], /* Lazy to avoid triggering inline requires */
|
|
465
|
+
// );
|
|
466
|
+
export function createSignatureFunctionForTransform() {
|
|
467
|
+
let savedType
|
|
468
|
+
let hasCustomHooks
|
|
469
|
+
let didCollectHooks = false
|
|
470
|
+
return function (type, key, forceReset, getCustomHooks) {
|
|
471
|
+
if (typeof key === 'string') {
|
|
472
|
+
// We're in the initial phase that associates signatures
|
|
473
|
+
// with the functions. Note this may be called multiple times
|
|
474
|
+
// in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
|
|
475
|
+
if (!savedType) {
|
|
476
|
+
// We're in the innermost call, so this is the actual type.
|
|
477
|
+
// $FlowFixMe[escaped-generic] discovered when updating Flow
|
|
478
|
+
savedType = type
|
|
479
|
+
hasCustomHooks = typeof getCustomHooks === 'function'
|
|
480
|
+
}
|
|
481
|
+
// Set the signature for all types (even wrappers!) in case
|
|
482
|
+
// they have no signatures of their own. This is to prevent
|
|
483
|
+
// problems like https://github.com/facebook/react/issues/20417.
|
|
484
|
+
if (
|
|
485
|
+
type != null &&
|
|
486
|
+
(typeof type === 'function' || typeof type === 'object')
|
|
487
|
+
) {
|
|
488
|
+
setSignature(type, key, forceReset, getCustomHooks)
|
|
489
|
+
}
|
|
490
|
+
return type
|
|
491
|
+
} else {
|
|
492
|
+
// We're in the _s() call without arguments, which means
|
|
493
|
+
// this is the time to collect custom Hook signatures.
|
|
494
|
+
// Only do this once. This path is hot and runs *inside* every render!
|
|
495
|
+
if (!didCollectHooks && hasCustomHooks) {
|
|
496
|
+
didCollectHooks = true
|
|
497
|
+
collectCustomHooksForSignature(savedType)
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function isLikelyComponentType(type) {
|
|
504
|
+
switch (typeof type) {
|
|
505
|
+
case 'function': {
|
|
506
|
+
// First, deal with classes.
|
|
507
|
+
if (type.prototype != null) {
|
|
508
|
+
if (type.prototype.isReactComponent) {
|
|
509
|
+
// React class.
|
|
510
|
+
return true
|
|
511
|
+
}
|
|
512
|
+
const ownNames = Object.getOwnPropertyNames(type.prototype)
|
|
513
|
+
if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
|
|
514
|
+
// This looks like a class.
|
|
515
|
+
return false
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (type.prototype.__proto__ !== Object.prototype) {
|
|
519
|
+
// It has a superclass.
|
|
520
|
+
return false
|
|
521
|
+
}
|
|
522
|
+
// Pass through.
|
|
523
|
+
// This looks like a regular function with empty prototype.
|
|
524
|
+
}
|
|
525
|
+
// For plain functions and arrows, use name as a heuristic.
|
|
526
|
+
const name = type.name || type.displayName
|
|
527
|
+
return typeof name === 'string' && /^[A-Z]/.test(name)
|
|
528
|
+
}
|
|
529
|
+
case 'object': {
|
|
530
|
+
if (type != null) {
|
|
531
|
+
switch (getProperty(type, '$$typeof')) {
|
|
532
|
+
case REACT_FORWARD_REF_TYPE:
|
|
533
|
+
case REACT_MEMO_TYPE:
|
|
534
|
+
// Definitely React components.
|
|
535
|
+
return true
|
|
536
|
+
default:
|
|
537
|
+
return false
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
return false
|
|
541
|
+
}
|
|
542
|
+
default: {
|
|
543
|
+
return false
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function isCompoundComponent(type) {
|
|
549
|
+
if (!isPlainObject(type)) return false
|
|
550
|
+
for (const key in type) {
|
|
551
|
+
if (!isLikelyComponentType(type[key])) return false
|
|
552
|
+
}
|
|
553
|
+
return true
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function isPlainObject(obj) {
|
|
557
|
+
return (
|
|
558
|
+
Object.prototype.toString.call(obj) === '[object Object]' &&
|
|
559
|
+
(obj.constructor === Object || obj.constructor === undefined)
|
|
560
|
+
)
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Plugin utils
|
|
565
|
+
*/
|
|
566
|
+
|
|
567
|
+
// Taken from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/lib/runtime/RefreshUtils.js#L141
|
|
568
|
+
// This allows to resister components not detected by SWC like styled component
|
|
569
|
+
export function registerExportsForReactRefresh(filename, moduleExports) {
|
|
570
|
+
for (const key in moduleExports) {
|
|
571
|
+
if (key === '__esModule') continue
|
|
572
|
+
const exportValue = moduleExports[key]
|
|
573
|
+
if (isLikelyComponentType(exportValue)) {
|
|
574
|
+
// 'export' is required to avoid key collision when renamed exports that
|
|
575
|
+
// shadow a local component name: https://github.com/vitejs/vite-plugin-react/issues/116
|
|
576
|
+
// The register function has an identity check to not register twice the same component,
|
|
577
|
+
// so this is safe to not used the same key here.
|
|
578
|
+
register(exportValue, filename + ' export ' + key)
|
|
579
|
+
} else if (isCompoundComponent(exportValue)) {
|
|
580
|
+
for (const subKey in exportValue) {
|
|
581
|
+
register(
|
|
582
|
+
exportValue[subKey],
|
|
583
|
+
filename + ' export ' + key + '-' + subKey,
|
|
584
|
+
)
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function debounce(fn, delay) {
|
|
591
|
+
let handle
|
|
592
|
+
return () => {
|
|
593
|
+
clearTimeout(handle)
|
|
594
|
+
handle = setTimeout(fn, delay)
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const hooks = []
|
|
599
|
+
window.__registerBeforePerformReactRefresh = (cb) => {
|
|
600
|
+
hooks.push(cb)
|
|
601
|
+
}
|
|
602
|
+
const enqueueUpdate = debounce(async () => {
|
|
603
|
+
if (hooks.length) await Promise.all(hooks.map((cb) => cb()))
|
|
604
|
+
performReactRefresh()
|
|
605
|
+
}, 16)
|
|
606
|
+
|
|
607
|
+
export function validateRefreshBoundaryAndEnqueueUpdate(
|
|
608
|
+
id,
|
|
609
|
+
prevExports,
|
|
610
|
+
nextExports,
|
|
611
|
+
) {
|
|
612
|
+
const ignoredExports = window.__getReactRefreshIgnoredExports?.({ id }) ?? []
|
|
613
|
+
if (
|
|
614
|
+
predicateOnExport(
|
|
615
|
+
ignoredExports,
|
|
616
|
+
prevExports,
|
|
617
|
+
(key) => key in nextExports,
|
|
618
|
+
) !== true
|
|
619
|
+
) {
|
|
620
|
+
return 'Could not Fast Refresh (export removed)'
|
|
621
|
+
}
|
|
622
|
+
if (
|
|
623
|
+
predicateOnExport(
|
|
624
|
+
ignoredExports,
|
|
625
|
+
nextExports,
|
|
626
|
+
(key) => key in prevExports,
|
|
627
|
+
) !== true
|
|
628
|
+
) {
|
|
629
|
+
return 'Could not Fast Refresh (new export)'
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
let hasExports = false
|
|
633
|
+
const allExportsAreComponentsOrUnchanged = predicateOnExport(
|
|
634
|
+
ignoredExports,
|
|
635
|
+
nextExports,
|
|
636
|
+
(key, value) => {
|
|
637
|
+
hasExports = true
|
|
638
|
+
if (isLikelyComponentType(value)) return true
|
|
639
|
+
if (isCompoundComponent(value)) return true
|
|
640
|
+
return prevExports[key] === nextExports[key]
|
|
641
|
+
},
|
|
642
|
+
)
|
|
643
|
+
if (hasExports && allExportsAreComponentsOrUnchanged === true) {
|
|
644
|
+
enqueueUpdate()
|
|
645
|
+
} else {
|
|
646
|
+
return `Could not Fast Refresh ("${allExportsAreComponentsOrUnchanged}" export is incompatible). Learn more at __README_URL__#consistent-components-exports`
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function predicateOnExport(ignoredExports, moduleExports, predicate) {
|
|
651
|
+
for (const key in moduleExports) {
|
|
652
|
+
if (ignoredExports.includes(key)) continue
|
|
653
|
+
if (!predicate(key, moduleExports[key])) return key
|
|
654
|
+
}
|
|
655
|
+
return true
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Hides vite-ignored dynamic import so that Vite can skip analysis if no other
|
|
659
|
+
// dynamic import is present (https://github.com/vitejs/vite/pull/12732)
|
|
660
|
+
export const __hmr_import = (module) => import(/* @vite-ignore */ module)
|
|
661
|
+
|
|
662
|
+
// For backwards compatibility with @vitejs/plugin-react.
|
|
663
|
+
export default { injectIntoGlobalHook }
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export const runtimePublicPath = '/@react-refresh'
|
|
2
|
+
|
|
3
|
+
// NOTE: this is exposed publicly via plugin-react
|
|
4
|
+
export const preambleCode = `import { injectIntoGlobalHook } from "${runtimePublicPath.slice(1)}";
|
|
5
|
+
injectIntoGlobalHook(window);
|
|
6
|
+
window.$RefreshReg$ = () => {};
|
|
7
|
+
window.$RefreshSig$ = () => (type) => type;`
|
|
8
|
+
|
|
9
|
+
export const getPreambleCode = () => preambleCode
|
|
10
|
+
|
|
11
|
+
export function addRefreshWrapper(code, pluginName, id, getComponentName) {
|
|
12
|
+
const componentName = getComponentName?.(code)
|
|
13
|
+
if (!componentName) return code;
|
|
14
|
+
|
|
15
|
+
const registerHmr = `
|
|
16
|
+
import * as RefreshRuntime from "${runtimePublicPath}";
|
|
17
|
+
const inWebWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
|
|
18
|
+
if (import.meta.hot && !inWebWorker) {
|
|
19
|
+
const component = get_${componentName}?.()
|
|
20
|
+
$RefreshReg$(component, "${componentName}")
|
|
21
|
+
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
|
|
22
|
+
RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
|
|
23
|
+
import.meta.hot.accept((nextExports) => {
|
|
24
|
+
if (!nextExports) return;
|
|
25
|
+
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, normalizeExports(currentExports), normalizeExports(nextExports));
|
|
26
|
+
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function normalizeExports(value) {
|
|
31
|
+
const [[key, type]] = Object.entries(value)
|
|
32
|
+
const name = key.replace("get_", "");
|
|
33
|
+
return {
|
|
34
|
+
[name]: (...args) => type?.(...args),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function $RefreshReg$(type, id) {
|
|
38
|
+
return RefreshRuntime.register(type, "/Users/mikhail.porotkin_1/Projects/Open-source/use-action-state/src/App.tsx " + id);
|
|
39
|
+
}
|
|
40
|
+
function $RefreshSig$() {
|
|
41
|
+
return RefreshRuntime.createSignatureFunctionForTransform();
|
|
42
|
+
}
|
|
43
|
+
`
|
|
44
|
+
return code + registerHmr;
|
|
45
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import {addRefreshWrapper} from "./refresh-wrapper.js";
|
|
2
|
+
|
|
3
|
+
let babel;
|
|
4
|
+
|
|
5
|
+
async function loadBabel() {
|
|
6
|
+
if (!babel) babel = await import("@babel/core");
|
|
7
|
+
return babel;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
let isProduction = true;
|
|
11
|
+
let projectRoot = process.cwd();
|
|
12
|
+
let runPluginOverrides;
|
|
13
|
+
|
|
14
|
+
function canSkipBabel(plugins, babelOptions) {
|
|
15
|
+
return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const loadedPlugin = /* @__PURE__ */ new Map();
|
|
19
|
+
|
|
20
|
+
function loadPlugin(path) {
|
|
21
|
+
const cached = loadedPlugin.get(path);
|
|
22
|
+
if (cached) return cached;
|
|
23
|
+
const promise = import(path).then((module) => {
|
|
24
|
+
const value = module.default || module;
|
|
25
|
+
loadedPlugin.set(path, value);
|
|
26
|
+
return value;
|
|
27
|
+
});
|
|
28
|
+
loadedPlugin.set(path, promise);
|
|
29
|
+
return promise;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function createBabelOptions(rawOptions) {
|
|
33
|
+
const babelOptions = {
|
|
34
|
+
babelrc: false,
|
|
35
|
+
configFile: false,
|
|
36
|
+
...rawOptions
|
|
37
|
+
};
|
|
38
|
+
babelOptions.plugins ||= [];
|
|
39
|
+
babelOptions.presets ||= [];
|
|
40
|
+
babelOptions.overrides ||= [];
|
|
41
|
+
babelOptions.parserOpts ||= {};
|
|
42
|
+
babelOptions.parserOpts.plugins ||= [];
|
|
43
|
+
return babelOptions;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const viteBabelPlugin = (mainOptions) => ({
|
|
47
|
+
name: "vite:react-plugin-kotlinjs",
|
|
48
|
+
enforce: "pre",
|
|
49
|
+
configResolved(config) {
|
|
50
|
+
projectRoot = config.root;
|
|
51
|
+
isProduction = config.isProduction;
|
|
52
|
+
mainOptions.skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
|
|
53
|
+
const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(function (value) {
|
|
54
|
+
return value !== void 0;
|
|
55
|
+
});
|
|
56
|
+
if (hooks.length > 0) runPluginOverrides = (babelOptions, context) => {
|
|
57
|
+
hooks.forEach((hook) => hook(babelOptions, context, config));
|
|
58
|
+
};
|
|
59
|
+
},
|
|
60
|
+
transform: {
|
|
61
|
+
async handler(code, id, options) {
|
|
62
|
+
const [filepath] = id.split("?");
|
|
63
|
+
if (!mainOptions?.filter(filepath) || !mainOptions?.getComponentName(code)) return;
|
|
64
|
+
const ssr = options?.ssr === true;
|
|
65
|
+
const babelOptions = (() => {
|
|
66
|
+
const newBabelOptions = createBabelOptions({});
|
|
67
|
+
runPluginOverrides?.(newBabelOptions, {
|
|
68
|
+
id,
|
|
69
|
+
ssr
|
|
70
|
+
});
|
|
71
|
+
return newBabelOptions;
|
|
72
|
+
})();
|
|
73
|
+
const plugins = [...babelOptions.plugins];
|
|
74
|
+
const useFastRefresh = !mainOptions.skipFastRefresh;
|
|
75
|
+
if (useFastRefresh) plugins.push([await loadPlugin("react-refresh/babel"), {skipEnvCheck: true}]);
|
|
76
|
+
if (canSkipBabel(plugins, babelOptions)) return;
|
|
77
|
+
const parserPlugins = [...babelOptions.parserOpts.plugins];
|
|
78
|
+
if (!filepath.endsWith(".ts")) parserPlugins.push("jsx");
|
|
79
|
+
const result = await (await loadBabel()).transformAsync(code, {
|
|
80
|
+
...babelOptions,
|
|
81
|
+
root: projectRoot,
|
|
82
|
+
filename: id,
|
|
83
|
+
sourceFileName: filepath,
|
|
84
|
+
retainLines: !isProduction,
|
|
85
|
+
parserOpts: {
|
|
86
|
+
...babelOptions.parserOpts,
|
|
87
|
+
sourceType: "module",
|
|
88
|
+
allowAwaitOutsideFunction: true,
|
|
89
|
+
plugins: parserPlugins
|
|
90
|
+
},
|
|
91
|
+
generatorOpts: {
|
|
92
|
+
...babelOptions.generatorOpts,
|
|
93
|
+
importAttributesKeyword: "with",
|
|
94
|
+
decoratorsBeforeExport: true
|
|
95
|
+
},
|
|
96
|
+
plugins,
|
|
97
|
+
sourceMaps: true
|
|
98
|
+
});
|
|
99
|
+
if (result) {
|
|
100
|
+
if (!useFastRefresh) return {
|
|
101
|
+
code: result.code,
|
|
102
|
+
map: result.map
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
code: addRefreshWrapper(result.code, "vite:react-plugin-kotlinjs", id, mainOptions?.getComponentName) ?? result.code,
|
|
106
|
+
map: result.map
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
})
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import {dirname, join} from 'node:path'
|
|
2
|
+
import {fileURLToPath} from 'node:url'
|
|
3
|
+
import {exactRegex} from '@rolldown/pluginutils'
|
|
4
|
+
import {readFileSync} from 'node:fs'
|
|
5
|
+
import {runtimePublicPath} from "./refresh-wrapper.js";
|
|
6
|
+
import {silenceUseClientWarning} from "./warning.js";
|
|
7
|
+
|
|
8
|
+
const _dirname = dirname(fileURLToPath(import.meta.url))
|
|
9
|
+
const refreshRuntimePath = join(_dirname, 'refresh-runtime.js')
|
|
10
|
+
const dependencies = [
|
|
11
|
+
'react',
|
|
12
|
+
'react-dom',
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
export const viteReactRefreshPlugin = (options) => ({
|
|
16
|
+
name: 'vite:react-refresh',
|
|
17
|
+
enforce: 'pre',
|
|
18
|
+
config: (userConfig) => ({
|
|
19
|
+
build: silenceUseClientWarning(userConfig),
|
|
20
|
+
optimizeDeps: {
|
|
21
|
+
include: dependencies,
|
|
22
|
+
},
|
|
23
|
+
}),
|
|
24
|
+
resolveId: {
|
|
25
|
+
filter: {id: exactRegex(runtimePublicPath)},
|
|
26
|
+
handler(id) {
|
|
27
|
+
if (id === runtimePublicPath) {
|
|
28
|
+
return id
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
load: {
|
|
33
|
+
filter: {id: exactRegex(runtimePublicPath)},
|
|
34
|
+
handler(id) {
|
|
35
|
+
if (id === runtimePublicPath) {
|
|
36
|
+
return readFileSync(refreshRuntimePath, 'utf-8')
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
transformIndexHtml() {
|
|
41
|
+
if (!options?.skipFastRefresh)
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
tag: 'script',
|
|
45
|
+
attrs: {type: 'module'},
|
|
46
|
+
children: getPreambleCode(base),
|
|
47
|
+
},
|
|
48
|
+
]
|
|
49
|
+
},
|
|
50
|
+
})
|
package/src/warning.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const silenceUseClientWarning = (userConfig) => ({
|
|
2
|
+
rollupOptions: {
|
|
3
|
+
onwarn(warning, defaultHandler) {
|
|
4
|
+
if (
|
|
5
|
+
warning.code === 'MODULE_LEVEL_DIRECTIVE' &&
|
|
6
|
+
(warning.message.includes('use client') ||
|
|
7
|
+
warning.message.includes('use server'))
|
|
8
|
+
) {
|
|
9
|
+
return
|
|
10
|
+
}
|
|
11
|
+
// https://github.com/vitejs/vite/issues/15012
|
|
12
|
+
if (
|
|
13
|
+
warning.code === 'SOURCEMAP_ERROR' &&
|
|
14
|
+
warning.message.includes('resolve original location') &&
|
|
15
|
+
warning.pos === 0
|
|
16
|
+
) {
|
|
17
|
+
return
|
|
18
|
+
}
|
|
19
|
+
if (userConfig.build?.rollupOptions?.onwarn) {
|
|
20
|
+
userConfig.build.rollupOptions.onwarn(warning, defaultHandler)
|
|
21
|
+
} else {
|
|
22
|
+
defaultHandler(warning)
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
})
|