@wyw-in-js/vite 1.1.0 → 2.0.0-alpha.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/README.md +8 -0
- package/esm/index.mjs +636 -656
- package/esm/index.mjs.map +1 -1
- package/package.json +12 -13
- package/types/index.d.ts +1 -1
- package/types/index.js +112 -127
- package/lib/index.js +0 -695
- package/lib/index.js.map +0 -1
package/lib/index.js
DELETED
|
@@ -1,695 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
Object.defineProperty(exports, "__esModule", {
|
|
4
|
-
value: true
|
|
5
|
-
});
|
|
6
|
-
exports.default = wywInJS;
|
|
7
|
-
var _fs = require("fs");
|
|
8
|
-
var _path = _interopRequireDefault(require("path"));
|
|
9
|
-
var _vite = require("vite");
|
|
10
|
-
var _shared = require("@wyw-in-js/shared");
|
|
11
|
-
var transformPkg = _interopRequireWildcard(require("@wyw-in-js/transform"));
|
|
12
|
-
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
|
|
13
|
-
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
14
|
-
/**
|
|
15
|
-
* This file contains a Vite loader for wyw-in-js.
|
|
16
|
-
* It uses the transform.ts function to generate class names from source code,
|
|
17
|
-
* returns transformed code without template literals and attaches generated source maps
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
const {
|
|
21
|
-
createTransformManifest,
|
|
22
|
-
createFileReporter,
|
|
23
|
-
getFileIdx,
|
|
24
|
-
stringifyTransformManifest,
|
|
25
|
-
transform,
|
|
26
|
-
TransformCacheCollection
|
|
27
|
-
} = transformPkg;
|
|
28
|
-
const createMetadataManifest = (metadata, context) => typeof createTransformManifest === 'function' ? createTransformManifest(metadata, context) : {
|
|
29
|
-
...metadata,
|
|
30
|
-
...context,
|
|
31
|
-
version: 1
|
|
32
|
-
};
|
|
33
|
-
const stringifyMetadataManifest = manifest => typeof stringifyTransformManifest === 'function' ? stringifyTransformManifest(manifest) : `${JSON.stringify(manifest, null, 2)}\n`;
|
|
34
|
-
const isWindowsAbsolutePath = value => /^[a-zA-Z]:[\\/]/.test(value);
|
|
35
|
-
const normalizeToPosix = value => value.replace(/\\/g, _path.default.posix.sep);
|
|
36
|
-
const isInside = (childPath, parentPath) => {
|
|
37
|
-
const rel = _path.default.relative(parentPath, childPath);
|
|
38
|
-
return rel === '' || !rel.startsWith('..') && !_path.default.isAbsolute(rel);
|
|
39
|
-
};
|
|
40
|
-
const isWywCssAssetName = value => value.endsWith('.wyw-in-js.css');
|
|
41
|
-
const normalizeAssetRelativePath = value => {
|
|
42
|
-
const normalized = _path.default.posix.normalize(normalizeToPosix(value).replace(/^\/+/, ''));
|
|
43
|
-
if (normalized.startsWith('..') || _path.default.posix.isAbsolute(normalized)) {
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
return normalized;
|
|
47
|
-
};
|
|
48
|
-
const stripExtension = value => {
|
|
49
|
-
const ext = _path.default.posix.extname(value);
|
|
50
|
-
return ext ? value.slice(0, -ext.length) : value;
|
|
51
|
-
};
|
|
52
|
-
const getComparableAssetPaths = (value, rootDir) => {
|
|
53
|
-
const variants = new Set();
|
|
54
|
-
const normalized = normalizeToPosix(value);
|
|
55
|
-
variants.add(normalized);
|
|
56
|
-
if (_path.default.isAbsolute(value) || isWindowsAbsolutePath(normalized)) {
|
|
57
|
-
if (isInside(value, rootDir)) {
|
|
58
|
-
const relativeToRoot = normalizeAssetRelativePath(_path.default.relative(rootDir, value));
|
|
59
|
-
if (relativeToRoot) {
|
|
60
|
-
variants.add(relativeToRoot);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
return variants;
|
|
64
|
-
}
|
|
65
|
-
const relativePath = normalizeAssetRelativePath(value);
|
|
66
|
-
if (relativePath) {
|
|
67
|
-
variants.add(relativePath);
|
|
68
|
-
}
|
|
69
|
-
return variants;
|
|
70
|
-
};
|
|
71
|
-
const getStringValues = value => {
|
|
72
|
-
if (!Array.isArray(value)) return [];
|
|
73
|
-
return value.filter(item => typeof item === 'string');
|
|
74
|
-
};
|
|
75
|
-
const getOutputAssetNames = asset => [...(typeof asset.name === 'string' ? [asset.name] : []), ...getStringValues(asset.names), ...(typeof asset.originalFileName === 'string' ? [asset.originalFileName] : []), ...getStringValues(asset.originalFileNames)];
|
|
76
|
-
const isOutputAssetLike = value => !!value && typeof value === 'object' && value.type === 'asset' && typeof value.fileName === 'string';
|
|
77
|
-
const isOutputChunkLike = value => !!value && typeof value === 'object' && value.type === 'chunk' && typeof value.fileName === 'string' && typeof value.code === 'string';
|
|
78
|
-
const getTrackedModuleIdForChunk = (chunk, cssFilesByModuleId) => {
|
|
79
|
-
if (typeof chunk.facadeModuleId === 'string' && cssFilesByModuleId.has(chunk.facadeModuleId)) {
|
|
80
|
-
return chunk.facadeModuleId;
|
|
81
|
-
}
|
|
82
|
-
if (!Array.isArray(chunk.moduleIds)) {
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
const moduleId = chunk.moduleIds.find(id => typeof id === 'string' && cssFilesByModuleId.has(id));
|
|
86
|
-
return moduleId !== null && moduleId !== void 0 ? moduleId : null;
|
|
87
|
-
};
|
|
88
|
-
const findWywCssAssetFileName = (bundle, cssFilename, rootDir) => {
|
|
89
|
-
const expectedNames = getComparableAssetPaths(cssFilename, rootDir);
|
|
90
|
-
for (const item of Object.values(bundle)) {
|
|
91
|
-
if (isOutputAssetLike(item) && item.fileName.endsWith('.css')) {
|
|
92
|
-
const isMatch = getOutputAssetNames(item).some(assetName => {
|
|
93
|
-
const variants = getComparableAssetPaths(assetName, rootDir);
|
|
94
|
-
return Array.from(variants).some(variant => expectedNames.has(variant));
|
|
95
|
-
});
|
|
96
|
-
if (isMatch) {
|
|
97
|
-
return normalizeToPosix(item.fileName);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
return null;
|
|
102
|
-
};
|
|
103
|
-
const getRelativeImportPath = (fromFileName, toFileName) => {
|
|
104
|
-
const fromDir = _path.default.posix.dirname(normalizeToPosix(fromFileName));
|
|
105
|
-
const relativePath = _path.default.posix.relative(fromDir, normalizeToPosix(toFileName));
|
|
106
|
-
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
|
|
107
|
-
};
|
|
108
|
-
const escapeForRegExp = value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
109
|
-
const hasStaticImport = (code, specifier) => new RegExp(`(^|\\n)\\s*import\\s*(?:["']${escapeForRegExp(specifier)}["']|[^\\n;]+\\s+from\\s+["']${escapeForRegExp(specifier)}["'])`, 'm').test(code);
|
|
110
|
-
const hasRequireCall = (code, specifier) => new RegExp(`(^|[;\\n])\\s*require\\(\\s*["']${escapeForRegExp(specifier)}["']\\s*\\)`, 'm').test(code);
|
|
111
|
-
const getCssLoadStatement = (format, specifier) => format === 'cjs' ? `require(${JSON.stringify(specifier)});\n` : `import ${JSON.stringify(specifier)};\n`;
|
|
112
|
-
const hasCssLoadStatement = (code, specifier, format) => format === 'cjs' ? hasRequireCall(code, specifier) : hasStaticImport(code, specifier);
|
|
113
|
-
const prependCssLoadStatement = (code, specifier, format) => {
|
|
114
|
-
const statement = getCssLoadStatement(format, specifier);
|
|
115
|
-
let insertAt = 0;
|
|
116
|
-
if (code.startsWith('#!')) {
|
|
117
|
-
const lineBreakIndex = code.indexOf('\n');
|
|
118
|
-
if (lineBreakIndex >= 0) {
|
|
119
|
-
insertAt = lineBreakIndex + 1;
|
|
120
|
-
} else {
|
|
121
|
-
return `${code}\n${statement}`;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
if (format === 'cjs') {
|
|
125
|
-
const directiveMatch = /^(?:\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*');)+/.exec(code.slice(insertAt));
|
|
126
|
-
if (directiveMatch) {
|
|
127
|
-
insertAt += directiveMatch[0].length;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return `${code.slice(0, insertAt)}${statement}${code.slice(insertAt)}`;
|
|
131
|
-
};
|
|
132
|
-
const VITE_FS_PREFIX = '/@fs/';
|
|
133
|
-
const safeDecodeURIComponent = value => {
|
|
134
|
-
try {
|
|
135
|
-
return decodeURIComponent(value);
|
|
136
|
-
} catch {
|
|
137
|
-
return value;
|
|
138
|
-
}
|
|
139
|
-
};
|
|
140
|
-
const normalizeViteFsPath = value => {
|
|
141
|
-
const fsPath = value.slice(VITE_FS_PREFIX.length);
|
|
142
|
-
return _path.default.normalize(safeDecodeURIComponent(fsPath));
|
|
143
|
-
};
|
|
144
|
-
const isCssReloadTarget = value => {
|
|
145
|
-
if (!value || typeof value !== 'object') return false;
|
|
146
|
-
const reloadTarget = value;
|
|
147
|
-
return !!reloadTarget.moduleGraph && typeof reloadTarget.moduleGraph.getModuleById === 'function' && typeof reloadTarget.reloadModule === 'function';
|
|
148
|
-
};
|
|
149
|
-
const getCssReloadTarget = (environment, server) => {
|
|
150
|
-
if (isCssReloadTarget(environment)) {
|
|
151
|
-
return environment;
|
|
152
|
-
}
|
|
153
|
-
if (server !== null && server !== void 0 && server.moduleGraph) {
|
|
154
|
-
return {
|
|
155
|
-
moduleGraph: server.moduleGraph,
|
|
156
|
-
reloadModule: module => server.reloadModule(module)
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
return null;
|
|
160
|
-
};
|
|
161
|
-
const getWywCssAssetFileNames = (resolvedConfig, output, originalAssetFileNames) => {
|
|
162
|
-
if (!output.preserveModules) return null;
|
|
163
|
-
const rootDir = resolvedConfig.root;
|
|
164
|
-
const preserveModulesRootValue = output.preserveModulesRoot;
|
|
165
|
-
let preserveModulesRootAbs = null;
|
|
166
|
-
if (typeof preserveModulesRootValue === 'string') {
|
|
167
|
-
preserveModulesRootAbs = _path.default.isAbsolute(preserveModulesRootValue) ? preserveModulesRootValue : _path.default.resolve(rootDir, preserveModulesRootValue);
|
|
168
|
-
}
|
|
169
|
-
const preserveModulesRootRel = preserveModulesRootAbs && isInside(preserveModulesRootAbs, rootDir) ? normalizeToPosix(_path.default.relative(rootDir, preserveModulesRootAbs)) : null;
|
|
170
|
-
return assetInfo => {
|
|
171
|
-
const template = typeof originalAssetFileNames === 'function' ? originalAssetFileNames(assetInfo) : originalAssetFileNames;
|
|
172
|
-
const assetName = assetInfo === null || assetInfo === void 0 ? void 0 : assetInfo.name;
|
|
173
|
-
if (typeof assetName !== 'string' || !isWywCssAssetName(assetName)) {
|
|
174
|
-
return template;
|
|
175
|
-
}
|
|
176
|
-
if (!template.includes('[')) {
|
|
177
|
-
return template;
|
|
178
|
-
}
|
|
179
|
-
let relativePath = null;
|
|
180
|
-
const assetNameNormalized = normalizeToPosix(assetName);
|
|
181
|
-
if (_path.default.isAbsolute(assetName) || isWindowsAbsolutePath(assetNameNormalized)) {
|
|
182
|
-
const preserveRel = preserveModulesRootAbs && isInside(assetName, preserveModulesRootAbs) ? _path.default.relative(preserveModulesRootAbs, assetName) : null;
|
|
183
|
-
if (preserveRel && !_path.default.isAbsolute(preserveRel) && !preserveRel.startsWith('..')) {
|
|
184
|
-
relativePath = preserveRel;
|
|
185
|
-
} else if (isInside(assetName, rootDir)) {
|
|
186
|
-
relativePath = _path.default.relative(rootDir, assetName);
|
|
187
|
-
}
|
|
188
|
-
} else if (preserveModulesRootRel && assetNameNormalized.startsWith(`${preserveModulesRootRel}/`)) {
|
|
189
|
-
relativePath = assetNameNormalized.slice(preserveModulesRootRel.length + 1);
|
|
190
|
-
} else {
|
|
191
|
-
relativePath = assetNameNormalized;
|
|
192
|
-
}
|
|
193
|
-
const normalized = relativePath ? normalizeAssetRelativePath(relativePath) : null;
|
|
194
|
-
if (!normalized) {
|
|
195
|
-
return template;
|
|
196
|
-
}
|
|
197
|
-
const withoutExt = stripExtension(normalized);
|
|
198
|
-
if (template.includes('[name]')) {
|
|
199
|
-
const dir = _path.default.posix.dirname(withoutExt);
|
|
200
|
-
if (dir === '.' || dir === '') {
|
|
201
|
-
return template;
|
|
202
|
-
}
|
|
203
|
-
return template.replace(/\[name\]/g, `${dir}/[name]`);
|
|
204
|
-
}
|
|
205
|
-
const dir = _path.default.posix.dirname(withoutExt);
|
|
206
|
-
if (dir === '.' || dir === '') {
|
|
207
|
-
return template;
|
|
208
|
-
}
|
|
209
|
-
const idx = template.indexOf('[');
|
|
210
|
-
if (idx < 0) {
|
|
211
|
-
return template;
|
|
212
|
-
}
|
|
213
|
-
const prefix = template.slice(0, idx);
|
|
214
|
-
if (prefix !== '' && !prefix.endsWith('/')) {
|
|
215
|
-
return template;
|
|
216
|
-
}
|
|
217
|
-
return `${prefix}${dir}/${template.slice(idx)}`;
|
|
218
|
-
};
|
|
219
|
-
};
|
|
220
|
-
function wywInJS({
|
|
221
|
-
debug,
|
|
222
|
-
include,
|
|
223
|
-
exclude,
|
|
224
|
-
sourceMap,
|
|
225
|
-
preserveCssPaths,
|
|
226
|
-
keepComments,
|
|
227
|
-
prefixer,
|
|
228
|
-
preprocessor,
|
|
229
|
-
ssrDevCss,
|
|
230
|
-
ssrDevCssPath,
|
|
231
|
-
transformLibraries,
|
|
232
|
-
...rest
|
|
233
|
-
} = {}) {
|
|
234
|
-
const supportedModuleExtensions = new Set(['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx']);
|
|
235
|
-
const filter = (0, _vite.createFilter)(include, exclude);
|
|
236
|
-
const cssLookup = {};
|
|
237
|
-
const cssFileLookup = {};
|
|
238
|
-
const metadataLookup = {};
|
|
239
|
-
const cssFilesByModuleId = new Map();
|
|
240
|
-
const pendingCssReloads = new WeakMap();
|
|
241
|
-
let ssrDevCssVersion = 0;
|
|
242
|
-
let config;
|
|
243
|
-
let devServer;
|
|
244
|
-
let importMetaEnvForEval = null;
|
|
245
|
-
const ssrDevCssEnabled = Boolean(ssrDevCss);
|
|
246
|
-
const [ssrDevCssPathname, ssrDevCssQuery] = (ssrDevCssPath !== null && ssrDevCssPath !== void 0 ? ssrDevCssPath : '/_wyw-in-js/ssr.css').split('?', 2);
|
|
247
|
-
const ssrDevCssRoute = ssrDevCssPathname.startsWith('/') ? ssrDevCssPathname : `/${ssrDevCssPathname}`;
|
|
248
|
-
const getSsrDevCssHref = () => {
|
|
249
|
-
const versionParam = `v=${ssrDevCssVersion}`;
|
|
250
|
-
const query = ssrDevCssQuery ? `${ssrDevCssQuery}&${versionParam}` : versionParam;
|
|
251
|
-
return `${ssrDevCssRoute}?${query}`;
|
|
252
|
-
};
|
|
253
|
-
const getSsrDevCssContents = () => {
|
|
254
|
-
const entries = Object.entries(cssLookup);
|
|
255
|
-
if (entries.length === 0) return '';
|
|
256
|
-
const merged = entries.sort(([a], [b]) => a.localeCompare(b)).map(([, cssText]) => cssText).join('\n');
|
|
257
|
-
return `${merged}\n`;
|
|
258
|
-
};
|
|
259
|
-
const {
|
|
260
|
-
emitter,
|
|
261
|
-
onDone
|
|
262
|
-
} = createFileReporter(debug !== null && debug !== void 0 ? debug : false);
|
|
263
|
-
const isSafeAssetPath = fileName => fileName !== '' && fileName !== '..' && !fileName.startsWith(`..${_path.default.posix.sep}`) && !_path.default.posix.isAbsolute(fileName) && !isWindowsAbsolutePath(fileName);
|
|
264
|
-
const replaceModuleExtension = (filename, nextExtension) => {
|
|
265
|
-
const extension = _path.default.extname(filename);
|
|
266
|
-
return supportedModuleExtensions.has(extension) ? `${filename.slice(0, -extension.length)}${nextExtension}` : `${filename}${nextExtension}`;
|
|
267
|
-
};
|
|
268
|
-
const toBundleRelativePath = filename => {
|
|
269
|
-
const relativePath = normalizeToPosix(_path.default.relative(config.root, filename));
|
|
270
|
-
if (isSafeAssetPath(relativePath)) {
|
|
271
|
-
return relativePath;
|
|
272
|
-
}
|
|
273
|
-
if (!_path.default.isAbsolute(relativePath) && !isWindowsAbsolutePath(relativePath)) {
|
|
274
|
-
return _path.default.posix.join('_wyw-in-js', 'external', ...relativePath.split(_path.default.posix.sep).filter(Boolean).map(segment => segment === '..' ? '__up__' : segment));
|
|
275
|
-
}
|
|
276
|
-
return _path.default.posix.join('_wyw-in-js', 'external', ...normalizeToPosix(_path.default.resolve(filename)).split(_path.default.posix.sep).filter(Boolean).map(segment => segment.replace(/:$/, '')));
|
|
277
|
-
};
|
|
278
|
-
const scheduleCssReload = (reloadTarget, cssFilename) => {
|
|
279
|
-
let state = pendingCssReloads.get(reloadTarget);
|
|
280
|
-
if (!state) {
|
|
281
|
-
state = {
|
|
282
|
-
files: new Set()
|
|
283
|
-
};
|
|
284
|
-
pendingCssReloads.set(reloadTarget, state);
|
|
285
|
-
}
|
|
286
|
-
state.files.add(cssFilename);
|
|
287
|
-
if (state.timer) return;
|
|
288
|
-
state.timer = setTimeout(() => {
|
|
289
|
-
state.timer = undefined;
|
|
290
|
-
const ids = Array.from(state.files);
|
|
291
|
-
state.files.clear();
|
|
292
|
-
const {
|
|
293
|
-
moduleGraph
|
|
294
|
-
} = reloadTarget;
|
|
295
|
-
for (const id of ids) {
|
|
296
|
-
const module = moduleGraph.getModuleById(id);
|
|
297
|
-
if (module) reloadTarget.reloadModule(module);
|
|
298
|
-
}
|
|
299
|
-
}, 0);
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
// <dependency id, targets>
|
|
303
|
-
const targets = [];
|
|
304
|
-
const clientCache = new TransformCacheCollection();
|
|
305
|
-
const ssrCache = new TransformCacheCollection();
|
|
306
|
-
const caches = new Set([clientCache, ssrCache]);
|
|
307
|
-
const getCache = isSsr => isSsr ? ssrCache : clientCache;
|
|
308
|
-
const isInsideCacheDir = filename => {
|
|
309
|
-
if (!config.cacheDir) {
|
|
310
|
-
return false;
|
|
311
|
-
}
|
|
312
|
-
const relative = _path.default.relative(config.cacheDir, filename);
|
|
313
|
-
return relative !== '' && !relative.startsWith('..') && !_path.default.isAbsolute(relative);
|
|
314
|
-
};
|
|
315
|
-
const getDepsOptimizer = () => {
|
|
316
|
-
var _ref, _ref2, _server$environments$, _server$environments;
|
|
317
|
-
if (!devServer) return null;
|
|
318
|
-
const server = devServer;
|
|
319
|
-
return (_ref = (_ref2 = (_server$environments$ = (_server$environments = server.environments) === null || _server$environments === void 0 || (_server$environments = _server$environments.client) === null || _server$environments === void 0 ? void 0 : _server$environments.depsOptimizer) !== null && _server$environments$ !== void 0 ? _server$environments$ : server.depsOptimizer) !== null && _ref2 !== void 0 ? _ref2 : server._depsOptimizer) !== null && _ref !== void 0 ? _ref : null;
|
|
320
|
-
};
|
|
321
|
-
const waitForOptimizedDep = async filename => {
|
|
322
|
-
var _depsOptimizer$isOpti, _depsOptimizer$init, _depsOptimizer$metada;
|
|
323
|
-
const depsOptimizer = getDepsOptimizer();
|
|
324
|
-
if (!(depsOptimizer !== null && depsOptimizer !== void 0 && (_depsOptimizer$isOpti = depsOptimizer.isOptimizedDepFile) !== null && _depsOptimizer$isOpti !== void 0 && _depsOptimizer$isOpti.call(depsOptimizer, filename))) {
|
|
325
|
-
return false;
|
|
326
|
-
}
|
|
327
|
-
await ((_depsOptimizer$init = depsOptimizer.init) === null || _depsOptimizer$init === void 0 ? void 0 : _depsOptimizer$init.call(depsOptimizer));
|
|
328
|
-
await depsOptimizer.scanProcessing;
|
|
329
|
-
const info = (_depsOptimizer$metada = depsOptimizer.metadata) === null || _depsOptimizer$metada === void 0 || (_depsOptimizer$metada = _depsOptimizer$metada.depInfoList) === null || _depsOptimizer$metada === void 0 ? void 0 : _depsOptimizer$metada.find(item => item.file === filename);
|
|
330
|
-
if (info !== null && info !== void 0 && info.processing) {
|
|
331
|
-
await info.processing;
|
|
332
|
-
}
|
|
333
|
-
return true;
|
|
334
|
-
};
|
|
335
|
-
let viteResolver = null;
|
|
336
|
-
const resolveClient = (what, importer) => {
|
|
337
|
-
if (!viteResolver) {
|
|
338
|
-
throw new Error('Vite resolver is not initialized yet');
|
|
339
|
-
}
|
|
340
|
-
return viteResolver(what, importer, false, false);
|
|
341
|
-
};
|
|
342
|
-
const resolveSsr = (what, importer) => {
|
|
343
|
-
if (!viteResolver) {
|
|
344
|
-
throw new Error('Vite resolver is not initialized yet');
|
|
345
|
-
}
|
|
346
|
-
return viteResolver(what, importer, false, true);
|
|
347
|
-
};
|
|
348
|
-
const createAsyncResolver = (0, _shared.asyncResolverFactory)(async (resolved, what, importer, stack) => {
|
|
349
|
-
const log = _shared.logger.extend('vite').extend(getFileIdx(importer));
|
|
350
|
-
if (resolved) {
|
|
351
|
-
log("resolve ✅ '%s'@'%s -> %O\n%s", what, importer, resolved);
|
|
352
|
-
|
|
353
|
-
// Vite adds param like `?v=667939b3` to cached modules
|
|
354
|
-
let resolvedId = resolved.split('?', 1)[0];
|
|
355
|
-
if (resolvedId.startsWith('\0')) {
|
|
356
|
-
// \0 is a special character in Rollup that tells Rollup to not include this in the bundle
|
|
357
|
-
// https://rollupjs.org/guide/en/#outputexports
|
|
358
|
-
return null;
|
|
359
|
-
}
|
|
360
|
-
if (resolvedId.startsWith(VITE_FS_PREFIX)) {
|
|
361
|
-
resolvedId = normalizeViteFsPath(resolvedId);
|
|
362
|
-
}
|
|
363
|
-
if (resolvedId.startsWith('/@')) {
|
|
364
|
-
return null;
|
|
365
|
-
}
|
|
366
|
-
if (!(0, _fs.existsSync)(resolvedId)) {
|
|
367
|
-
// When Vite resolves to an optimized deps entry (cacheDir) it may not be written yet.
|
|
368
|
-
// Wait for Vite's optimizer instead of calling optimizeDeps() manually (deprecated in Vite 7).
|
|
369
|
-
try {
|
|
370
|
-
await waitForOptimizedDep(resolvedId);
|
|
371
|
-
} catch {
|
|
372
|
-
// If optimizer failed, fall through to preserve previous behavior and surface the error.
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// Vite can return an optimized deps entry (from cacheDir) before it's written to disk.
|
|
376
|
-
// Manually calling optimizeDeps is deprecated in Vite 7 and can also get called many times.
|
|
377
|
-
// Instead, fall back to resolving the original module path directly.
|
|
378
|
-
if (!(0, _fs.existsSync)(resolvedId) && isInsideCacheDir(resolvedId)) {
|
|
379
|
-
try {
|
|
380
|
-
return (0, _shared.syncResolve)(what, importer, stack);
|
|
381
|
-
} catch {
|
|
382
|
-
// Fall through to preserve previous behavior: return resolvedId and let WyW surface the error.
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
if (!(0, _fs.existsSync)(resolvedId) && !_path.default.isAbsolute(resolvedId)) {
|
|
387
|
-
// Vite can resolve an import to a bare specifier when bundling for SSR and marking it as external.
|
|
388
|
-
// In that case we still need a real file path for WyW evaluation.
|
|
389
|
-
return (0, _shared.syncResolve)(what, importer, stack);
|
|
390
|
-
}
|
|
391
|
-
return resolvedId;
|
|
392
|
-
}
|
|
393
|
-
log("resolve ❌ '%s'@'%s", what, importer);
|
|
394
|
-
|
|
395
|
-
// Vite can inject virtual ids like /@react-refresh in dev.
|
|
396
|
-
if (what.startsWith('/@') || what.startsWith('\0')) {
|
|
397
|
-
return null;
|
|
398
|
-
}
|
|
399
|
-
if (!what.startsWith('.') && !what.startsWith('/') && !_path.default.isAbsolute(what)) {
|
|
400
|
-
// Keep compatibility with SSR externalization: fall back to Node resolution for bare specifiers.
|
|
401
|
-
return (0, _shared.syncResolve)(what, importer, stack);
|
|
402
|
-
}
|
|
403
|
-
throw new Error(`Could not resolve ${what}`);
|
|
404
|
-
}, (what, importer) => [what, importer]);
|
|
405
|
-
const asyncResolveClient = createAsyncResolver(resolveClient);
|
|
406
|
-
const asyncResolveSsr = createAsyncResolver(resolveSsr);
|
|
407
|
-
return {
|
|
408
|
-
name: 'wyw-in-js',
|
|
409
|
-
enforce: 'post',
|
|
410
|
-
buildStart() {
|
|
411
|
-
Object.keys(metadataLookup).forEach(key => {
|
|
412
|
-
delete metadataLookup[key];
|
|
413
|
-
});
|
|
414
|
-
},
|
|
415
|
-
buildEnd() {
|
|
416
|
-
onDone(process.cwd());
|
|
417
|
-
},
|
|
418
|
-
configResolved(resolvedConfig) {
|
|
419
|
-
var _config$envPrefix;
|
|
420
|
-
config = resolvedConfig;
|
|
421
|
-
viteResolver = config.createResolver();
|
|
422
|
-
if (preserveCssPaths && config.command === 'build') {
|
|
423
|
-
const outputs = config.build.rollupOptions.output;
|
|
424
|
-
let outputEntries = [];
|
|
425
|
-
if (Array.isArray(outputs)) {
|
|
426
|
-
outputEntries = outputs;
|
|
427
|
-
} else if (outputs) {
|
|
428
|
-
outputEntries = [outputs];
|
|
429
|
-
}
|
|
430
|
-
outputEntries.forEach(entry => {
|
|
431
|
-
var _output$assetFileName, _config$build$assetsD;
|
|
432
|
-
if (!entry || typeof entry !== 'object') return;
|
|
433
|
-
const output = entry;
|
|
434
|
-
if (!output.preserveModules) return;
|
|
435
|
-
const template = (_output$assetFileName = output.assetFileNames) !== null && _output$assetFileName !== void 0 ? _output$assetFileName : `${(_config$build$assetsD = config.build.assetsDir) !== null && _config$build$assetsD !== void 0 ? _config$build$assetsD : 'assets'}/[name].[hash].[ext]`;
|
|
436
|
-
const assetFileNames = getWywCssAssetFileNames(config, output, template);
|
|
437
|
-
if (assetFileNames) output.assetFileNames = assetFileNames;
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
const envPrefix = (_config$envPrefix = config.envPrefix) !== null && _config$envPrefix !== void 0 ? _config$envPrefix : 'VITE_';
|
|
441
|
-
const envDir =
|
|
442
|
-
// envDir is absolute in modern Vite, but keep a fallback for older versions
|
|
443
|
-
'envDir' in config && typeof config.envDir === 'string' ? config.envDir : config.root;
|
|
444
|
-
const loaded = (0, _vite.loadEnv)(config.mode, envDir, envPrefix);
|
|
445
|
-
const base = {
|
|
446
|
-
...loaded,
|
|
447
|
-
BASE_URL: config.base,
|
|
448
|
-
MODE: config.mode,
|
|
449
|
-
DEV: config.command === 'serve',
|
|
450
|
-
PROD: config.command === 'build'
|
|
451
|
-
};
|
|
452
|
-
importMetaEnvForEval = {
|
|
453
|
-
client: {
|
|
454
|
-
...base,
|
|
455
|
-
SSR: false
|
|
456
|
-
},
|
|
457
|
-
ssr: {
|
|
458
|
-
...base,
|
|
459
|
-
SSR: true
|
|
460
|
-
}
|
|
461
|
-
};
|
|
462
|
-
},
|
|
463
|
-
configureServer(_server) {
|
|
464
|
-
devServer = _server;
|
|
465
|
-
if (!ssrDevCssEnabled || config.command !== 'serve') return;
|
|
466
|
-
devServer.middlewares.use((req, res, next) => {
|
|
467
|
-
const {
|
|
468
|
-
url
|
|
469
|
-
} = req;
|
|
470
|
-
if (!url) {
|
|
471
|
-
next();
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
const [pathname] = url.split('?', 1);
|
|
475
|
-
if (pathname !== ssrDevCssRoute) {
|
|
476
|
-
next();
|
|
477
|
-
return;
|
|
478
|
-
}
|
|
479
|
-
const etag = `W/"${ssrDevCssVersion}"`;
|
|
480
|
-
const ifNoneMatch = req.headers['if-none-match'];
|
|
481
|
-
if (ifNoneMatch === etag) {
|
|
482
|
-
res.statusCode = 304;
|
|
483
|
-
res.end();
|
|
484
|
-
return;
|
|
485
|
-
}
|
|
486
|
-
res.statusCode = 200;
|
|
487
|
-
res.setHeader('Content-Type', 'text/css; charset=utf-8');
|
|
488
|
-
res.setHeader('Cache-Control', 'no-cache');
|
|
489
|
-
res.setHeader('ETag', etag);
|
|
490
|
-
res.end(getSsrDevCssContents());
|
|
491
|
-
});
|
|
492
|
-
},
|
|
493
|
-
transformIndexHtml(html) {
|
|
494
|
-
if (!ssrDevCssEnabled || config.command !== 'serve') return undefined;
|
|
495
|
-
return {
|
|
496
|
-
html,
|
|
497
|
-
tags: [{
|
|
498
|
-
tag: 'link',
|
|
499
|
-
attrs: {
|
|
500
|
-
rel: 'stylesheet',
|
|
501
|
-
href: getSsrDevCssHref()
|
|
502
|
-
},
|
|
503
|
-
injectTo: 'head-prepend'
|
|
504
|
-
}]
|
|
505
|
-
};
|
|
506
|
-
},
|
|
507
|
-
load(url) {
|
|
508
|
-
const [id] = url.split('?', 1);
|
|
509
|
-
return cssLookup[id];
|
|
510
|
-
},
|
|
511
|
-
/* eslint-disable-next-line consistent-return */
|
|
512
|
-
resolveId(importeeUrl) {
|
|
513
|
-
const [id] = importeeUrl.split('?', 1);
|
|
514
|
-
if (cssLookup[id]) return id;
|
|
515
|
-
return cssFileLookup[id];
|
|
516
|
-
},
|
|
517
|
-
handleHotUpdate(ctx) {
|
|
518
|
-
// it's module, so just transform it
|
|
519
|
-
if (ctx.modules.length) return ctx.modules;
|
|
520
|
-
|
|
521
|
-
// Select affected modules of changed dependency
|
|
522
|
-
const affected = targets.filter(x =>
|
|
523
|
-
// file is dependency of any target
|
|
524
|
-
x.dependencies.some(dep => dep === ctx.file) ||
|
|
525
|
-
// or changed module is a dependency of any target
|
|
526
|
-
x.dependencies.some(dep => ctx.modules.some(m => m.file === dep)));
|
|
527
|
-
const deps = affected.flatMap(target => target.dependencies);
|
|
528
|
-
|
|
529
|
-
// eslint-disable-next-line no-restricted-syntax
|
|
530
|
-
for (const depId of deps) {
|
|
531
|
-
for (const cache of caches) {
|
|
532
|
-
cache.invalidateForFile(depId);
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
return affected.map(target => devServer.moduleGraph.getModuleById(target.id)).concat(ctx.modules).filter(m => !!m);
|
|
536
|
-
},
|
|
537
|
-
generateBundle(outputOptions, bundle) {
|
|
538
|
-
Object.entries(metadataLookup).forEach(([fileName, source]) => {
|
|
539
|
-
this.emitFile({
|
|
540
|
-
fileName,
|
|
541
|
-
source,
|
|
542
|
-
type: 'asset'
|
|
543
|
-
});
|
|
544
|
-
});
|
|
545
|
-
if (config.command !== 'build') return;
|
|
546
|
-
if (!outputOptions.preserveModules) return;
|
|
547
|
-
if (config.build.cssCodeSplit === false) return;
|
|
548
|
-
Object.values(bundle).forEach(item => {
|
|
549
|
-
if (!isOutputChunkLike(item)) {
|
|
550
|
-
return;
|
|
551
|
-
}
|
|
552
|
-
const chunk = item;
|
|
553
|
-
const moduleId = getTrackedModuleIdForChunk(chunk, cssFilesByModuleId);
|
|
554
|
-
if (!moduleId) {
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
const cssFilename = cssFilesByModuleId.get(moduleId);
|
|
558
|
-
if (!cssFilename) {
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
const emittedCssFileName = findWywCssAssetFileName(bundle, cssFilename, config.root);
|
|
562
|
-
if (!emittedCssFileName) {
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
const relativeCssImport = getRelativeImportPath(chunk.fileName, emittedCssFileName);
|
|
566
|
-
if (hasCssLoadStatement(chunk.code, relativeCssImport, outputOptions.format)) {
|
|
567
|
-
return;
|
|
568
|
-
}
|
|
569
|
-
chunk.code = prependCssLoadStatement(chunk.code, relativeCssImport, outputOptions.format);
|
|
570
|
-
});
|
|
571
|
-
},
|
|
572
|
-
async transform(code, url, transformOptions) {
|
|
573
|
-
var _result$diagnostics;
|
|
574
|
-
const [id] = url.split('?', 1);
|
|
575
|
-
|
|
576
|
-
// Do not transform ignored and generated files
|
|
577
|
-
if (!transformLibraries && url.includes('node_modules') || !filter(url) || id in cssLookup) return;
|
|
578
|
-
const log = _shared.logger.extend('vite').extend(getFileIdx(id));
|
|
579
|
-
log('transform %s', id);
|
|
580
|
-
const isSsr = typeof transformOptions === 'boolean' ? transformOptions : Boolean(transformOptions === null || transformOptions === void 0 ? void 0 : transformOptions.ssr);
|
|
581
|
-
const overrideContext = (context, filename) => {
|
|
582
|
-
var _importMetaEnvForEval;
|
|
583
|
-
const env = (_importMetaEnvForEval = importMetaEnvForEval) === null || _importMetaEnvForEval === void 0 ? void 0 : _importMetaEnvForEval[isSsr ? 'ssr' : 'client'];
|
|
584
|
-
const withEnv = env ? {
|
|
585
|
-
...context,
|
|
586
|
-
__wyw_import_meta_env: env
|
|
587
|
-
} : context;
|
|
588
|
-
return rest.overrideContext ? rest.overrideContext(withEnv, filename) : withEnv;
|
|
589
|
-
};
|
|
590
|
-
const transformServices = {
|
|
591
|
-
options: {
|
|
592
|
-
filename: id,
|
|
593
|
-
root: process.cwd(),
|
|
594
|
-
prefixer,
|
|
595
|
-
keepComments,
|
|
596
|
-
preprocessor,
|
|
597
|
-
pluginOptions: {
|
|
598
|
-
...rest,
|
|
599
|
-
overrideContext
|
|
600
|
-
}
|
|
601
|
-
},
|
|
602
|
-
cache: getCache(isSsr),
|
|
603
|
-
emitWarning: message => this.warn(message),
|
|
604
|
-
eventEmitter: emitter
|
|
605
|
-
};
|
|
606
|
-
const asyncResolve = isSsr ? asyncResolveSsr : asyncResolveClient;
|
|
607
|
-
const result = await transform(transformServices, code, asyncResolve);
|
|
608
|
-
(_result$diagnostics = result.diagnostics) === null || _result$diagnostics === void 0 || _result$diagnostics.forEach(diagnostic => {
|
|
609
|
-
this.warn({
|
|
610
|
-
id: diagnostic.filename,
|
|
611
|
-
loc: diagnostic.start ? {
|
|
612
|
-
column: diagnostic.start.column,
|
|
613
|
-
file: diagnostic.filename,
|
|
614
|
-
line: diagnostic.start.line
|
|
615
|
-
} : undefined,
|
|
616
|
-
message: `[wyw-in-js] ${diagnostic.severity} [${diagnostic.category}] ${diagnostic.message}`,
|
|
617
|
-
pluginCode: diagnostic.category
|
|
618
|
-
});
|
|
619
|
-
});
|
|
620
|
-
const relativeId = normalizeToPosix(_path.default.relative(config.root, id));
|
|
621
|
-
const metadataFilename = replaceModuleExtension(id, '.wyw-in-js.json');
|
|
622
|
-
const metadataRelativePath = toBundleRelativePath(metadataFilename);
|
|
623
|
-
delete metadataLookup[metadataRelativePath];
|
|
624
|
-
if (result.metadata) {
|
|
625
|
-
const cssFile = typeof result.cssText === 'string' && result.cssText !== '' ? replaceModuleExtension(relativeId, '.wyw-in-js.css') : undefined;
|
|
626
|
-
metadataLookup[metadataRelativePath] = stringifyMetadataManifest(createMetadataManifest(result.metadata, {
|
|
627
|
-
cssFile,
|
|
628
|
-
source: relativeId
|
|
629
|
-
}));
|
|
630
|
-
}
|
|
631
|
-
let {
|
|
632
|
-
cssText,
|
|
633
|
-
dependencies
|
|
634
|
-
} = result;
|
|
635
|
-
|
|
636
|
-
// Heads up, there are three cases:
|
|
637
|
-
// 1. cssText is undefined, it means that file was not transformed
|
|
638
|
-
// 2. cssText is empty, it means that file was transformed, but it does not contain any styles
|
|
639
|
-
// 3. cssText is not empty, it means that file was transformed and it contains styles
|
|
640
|
-
|
|
641
|
-
if (typeof cssText === 'undefined') {
|
|
642
|
-
cssFilesByModuleId.delete(id);
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
if (cssText === '') {
|
|
646
|
-
cssFilesByModuleId.delete(id);
|
|
647
|
-
/* eslint-disable-next-line consistent-return */
|
|
648
|
-
return {
|
|
649
|
-
code: result.code,
|
|
650
|
-
map: result.sourceMap
|
|
651
|
-
};
|
|
652
|
-
}
|
|
653
|
-
dependencies !== null && dependencies !== void 0 ? dependencies : dependencies = [];
|
|
654
|
-
const cssFilename = normalizeToPosix(replaceModuleExtension(id, '.wyw-in-js.css'));
|
|
655
|
-
cssFilesByModuleId.set(id, cssFilename);
|
|
656
|
-
const cssRelativePath = normalizeToPosix(_path.default.relative(config.root, cssFilename));
|
|
657
|
-
const cssId = `/${cssRelativePath}`;
|
|
658
|
-
if (sourceMap && result.cssSourceMapText) {
|
|
659
|
-
const map = Buffer.from(result.cssSourceMapText).toString('base64');
|
|
660
|
-
cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
|
|
661
|
-
}
|
|
662
|
-
const didCssChange = cssLookup[cssFilename] !== cssText;
|
|
663
|
-
cssLookup[cssFilename] = cssText;
|
|
664
|
-
cssFileLookup[cssId] = cssFilename;
|
|
665
|
-
result.code += `\nimport ${JSON.stringify(cssFilename)};\n`;
|
|
666
|
-
for (let i = 0, end = dependencies.length; i < end; i++) {
|
|
667
|
-
// eslint-disable-next-line no-await-in-loop
|
|
668
|
-
const depModule = await this.resolve(dependencies[i], url, {
|
|
669
|
-
isEntry: false
|
|
670
|
-
});
|
|
671
|
-
if (depModule) dependencies[i] = depModule.id;
|
|
672
|
-
}
|
|
673
|
-
const target = targets.find(t => t.id === id);
|
|
674
|
-
if (!target) targets.push({
|
|
675
|
-
id,
|
|
676
|
-
dependencies
|
|
677
|
-
});else target.dependencies = dependencies;
|
|
678
|
-
if (didCssChange) {
|
|
679
|
-
const reloadTarget = getCssReloadTarget(this.environment, devServer);
|
|
680
|
-
if (reloadTarget) {
|
|
681
|
-
scheduleCssReload(reloadTarget, cssFilename);
|
|
682
|
-
}
|
|
683
|
-
if (ssrDevCssEnabled && config.command === 'serve') {
|
|
684
|
-
ssrDevCssVersion += 1;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
/* eslint-disable-next-line consistent-return */
|
|
688
|
-
return {
|
|
689
|
-
code: result.code,
|
|
690
|
-
map: result.sourceMap
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
};
|
|
694
|
-
}
|
|
695
|
-
//# sourceMappingURL=index.js.map
|