@sveltejs/vite-plugin-svelte 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/package.json +7 -12
  2. package/src/{handle-hot-update.ts → handle-hot-update.js} +35 -20
  3. package/src/index.d.ts +215 -0
  4. package/src/{index.ts → index.js} +39 -67
  5. package/src/{preprocess.ts → preprocess.js} +37 -28
  6. package/src/types/compile.d.ts +48 -0
  7. package/src/types/id.d.ts +31 -0
  8. package/src/types/log.d.ts +24 -0
  9. package/src/types/options.d.ts +20 -0
  10. package/src/types/plugin-api.d.ts +11 -0
  11. package/src/types/vite-plugin-svelte-stats.d.ts +30 -0
  12. package/src/utils/{compile.ts → compile.js} +32 -63
  13. package/src/utils/{dependencies.ts → dependencies.js} +14 -11
  14. package/src/utils/{error.ts → error.js} +21 -14
  15. package/src/utils/{esbuild.ts → esbuild.js} +23 -17
  16. package/src/utils/{hash.ts → hash.js} +14 -3
  17. package/src/utils/{id.ts → id.js} +59 -60
  18. package/src/utils/{load-raw.ts → load-raw.js} +16 -16
  19. package/src/utils/{load-svelte-config.ts → load-svelte-config.js} +12 -10
  20. package/src/utils/{log.ts → log.js} +81 -48
  21. package/src/utils/{optimizer.ts → optimizer.js} +15 -7
  22. package/src/utils/{options.ts → options.js} +146 -296
  23. package/src/utils/{preprocess.ts → preprocess.js} +28 -12
  24. package/src/utils/{resolve.ts → resolve.js} +18 -9
  25. package/src/utils/{sourcemaps.ts → sourcemaps.js} +22 -14
  26. package/src/utils/{svelte-version.ts → svelte-version.js} +15 -7
  27. package/src/utils/vite-plugin-svelte-cache.js +253 -0
  28. package/src/utils/{vite-plugin-svelte-stats.ts → vite-plugin-svelte-stats.js} +66 -62
  29. package/src/utils/{watch.ts → watch.js} +30 -22
  30. package/dist/index.d.ts +0 -193
  31. package/dist/index.js +0 -2272
  32. package/dist/index.js.map +0 -1
  33. package/src/__tests__/fixtures/preprocess/foo.scss +0 -3
  34. package/src/__tests__/preprocess.spec.ts +0 -51
  35. package/src/utils/__tests__/compile.spec.ts +0 -49
  36. package/src/utils/__tests__/sourcemaps.spec.ts +0 -79
  37. package/src/utils/__tests__/svelte-version.spec.ts +0 -102
  38. package/src/utils/vite-plugin-svelte-cache.ts +0 -182
  39. /package/src/utils/{constants.ts → constants.js} +0 -0
@@ -1,18 +1,16 @@
1
- import { ResolvedOptions } from './options';
2
1
  import fs from 'fs';
3
- import { toRollupError } from './error';
4
- import { log } from './log';
5
- import type { SvelteRequest } from './id';
6
- import { type CompileData, CompileSvelte } from './compile';
2
+ import { toRollupError } from './error.js';
3
+ import { log } from './log.js';
7
4
 
8
5
  /**
9
6
  * utility function to compile ?raw and ?direct requests in load hook
7
+ *
8
+ * @param {import('../types/id.d.ts').SvelteRequest} svelteRequest
9
+ * @param {import('../types/compile.d.ts').CompileSvelte} compileSvelte
10
+ * @param {import('../types/options.d.ts').ResolvedOptions} options
11
+ * @returns {Promise<string>}
10
12
  */
11
- export async function loadRaw(
12
- svelteRequest: SvelteRequest,
13
- compileSvelte: CompileSvelte,
14
- options: ResolvedOptions
15
- ) {
13
+ export async function loadRaw(svelteRequest, compileSvelte, options) {
16
14
  const { id, filename, query } = svelteRequest;
17
15
 
18
16
  // raw svelte subrequest, compile on the fly and return requested subpart
@@ -88,12 +86,13 @@ export async function loadRaw(
88
86
  /**
89
87
  * turn compileData and source into a flat list of raw exports
90
88
  *
91
- * @param compileData
92
- * @param source
89
+ * @param {import('../types/compile.d.ts').CompileData} compileData
90
+ * @param {string} source
93
91
  */
94
- function allToRawExports(compileData: CompileData, source: string) {
92
+ function allToRawExports(compileData, source) {
95
93
  // flatten CompileData
96
- const exports: Partial<CompileData & { source: string }> = {
94
+ /** @type {Partial<import('../types/compile.d.ts').CompileData & { source: string }>} */
95
+ const exports = {
97
96
  ...compileData,
98
97
  ...compileData.compiled,
99
98
  source
@@ -115,9 +114,10 @@ function allToRawExports(compileData: CompileData, source: string) {
115
114
  * export const foo='bar'
116
115
  * export default code
117
116
  * ```
118
- * @param object
117
+ * @param {object} object
118
+ * @returns {string}
119
119
  */
120
- function toRawExports(object: object) {
120
+ function toRawExports(object) {
121
121
  let exports =
122
122
  Object.entries(object)
123
123
  //eslint-disable-next-line no-unused-vars
@@ -2,14 +2,13 @@ import { createRequire } from 'module';
2
2
  import path from 'path';
3
3
  import fs from 'fs';
4
4
  import { pathToFileURL } from 'url';
5
- import { log } from './log';
6
- import { Options, SvelteOptions } from './options';
7
- import { UserConfig } from 'vite';
5
+ import { log } from './log.js';
8
6
 
9
7
  // used to require cjs config in esm.
10
8
  // NOTE dynamic import() cjs technically works, but timestamp query cache bust
11
9
  // have no effect, likely because it has another internal cache?
12
- let esmRequire: NodeRequire;
10
+ /** @type {NodeRequire}*/
11
+ let esmRequire;
13
12
 
14
13
  export const knownSvelteConfigNames = [
15
14
  'svelte.config.js',
@@ -26,10 +25,8 @@ const dynamicImportDefault = new Function(
26
25
  'return import(path + "?t=" + timestamp).then(m => m.default)'
27
26
  );
28
27
 
29
- export async function loadSvelteConfig(
30
- viteConfig?: UserConfig,
31
- inlineOptions?: Partial<Options>
32
- ): Promise<Partial<SvelteOptions> | undefined> {
28
+ /** @type {import('../index.d.ts').loadSvelteConfig} */
29
+ export async function loadSvelteConfig(viteConfig, inlineOptions) {
33
30
  if (inlineOptions?.configFile === false) {
34
31
  return;
35
32
  }
@@ -61,7 +58,7 @@ export async function loadSvelteConfig(
61
58
  try {
62
59
  // identify which require function to use (esm and cjs mode)
63
60
  const _require = import.meta.url
64
- ? (esmRequire ??= createRequire(import.meta.url))
61
+ ? esmRequire ?? (esmRequire = createRequire(import.meta.url))
65
62
  : require;
66
63
 
67
64
  // avoid loading cached version on reload
@@ -87,7 +84,12 @@ export async function loadSvelteConfig(
87
84
  }
88
85
  }
89
86
 
90
- function findConfigToLoad(viteConfig?: UserConfig, inlineOptions?: Partial<Options>) {
87
+ /**
88
+ * @param {import('vite').UserConfig | undefined} viteConfig
89
+ * @param {Partial<import('../index.d.ts').Options> | undefined} inlineOptions
90
+ * @returns {string | undefined}
91
+ */
92
+ function findConfigToLoad(viteConfig, inlineOptions) {
91
93
  const root = viteConfig?.root || process.cwd();
92
94
  if (inlineOptions?.configFile) {
93
95
  const abolutePath = path.isAbsolute(inlineOptions.configFile)
@@ -1,11 +1,12 @@
1
- /* eslint-disable no-unused-vars,no-console */
2
- import { cyan, yellow, red } from 'kleur/colors';
1
+ /* eslint-disable no-console */
2
+ import { cyan, red, yellow } from 'kleur/colors';
3
3
  import debug from 'debug';
4
- import { ResolvedOptions, Warning } from './options';
5
- import { SvelteRequest } from './id';
6
- const levels: string[] = ['debug', 'info', 'warn', 'error', 'silent'];
4
+
5
+ /** @type {import('../types/log.d.ts').LogLevel[]} */
6
+ const levels = ['debug', 'info', 'warn', 'error', 'silent'];
7
7
  const prefix = 'vite-plugin-svelte';
8
- const loggers: { [key: string]: any } = {
8
+ /** @type {Record<import('../types/log.d.ts').LogLevel, any>} */
9
+ const loggers = {
9
10
  debug: {
10
11
  log: debug(`vite:${prefix}`),
11
12
  enabled: false,
@@ -31,8 +32,13 @@ const loggers: { [key: string]: any } = {
31
32
  }
32
33
  };
33
34
 
34
- let _level: string = 'info';
35
- function setLevel(level: string) {
35
+ /** @type {import('../types/log.d.ts').LogLevel} */
36
+ let _level = 'info';
37
+ /**
38
+ * @param {import('../types/log.d.ts').LogLevel} level
39
+ * @returns {void}
40
+ */
41
+ function setLevel(level) {
36
42
  if (level === _level) {
37
43
  return;
38
44
  }
@@ -47,7 +53,14 @@ function setLevel(level: string) {
47
53
  }
48
54
  }
49
55
 
50
- function _log(logger: any, message: string, payload?: any, namespace?: string) {
56
+ /**
57
+ * @param {any} logger
58
+ * @param {string} message
59
+ * @param {any} [payload]
60
+ * @param {string} [namespace]
61
+ * @returns
62
+ */
63
+ function _log(logger, message, payload, namespace) {
51
64
  if (!logger.enabled) {
52
65
  return;
53
66
  }
@@ -68,17 +81,17 @@ function _log(logger: any, message: string, payload?: any, namespace?: string) {
68
81
  }
69
82
  }
70
83
 
71
- export interface LogFn {
72
- (message: string, payload?: any, namespace?: string): void;
73
- enabled: boolean;
74
- once: (message: string, payload?: any, namespace?: string) => void;
75
- }
76
-
77
- function createLogger(level: string): LogFn {
84
+ /**
85
+ * @param {import('../types/log.d.ts').LogLevel} level
86
+ * @returns {import('../types/log.d.ts').LogFn}
87
+ */
88
+ function createLogger(level) {
78
89
  const logger = loggers[level];
79
- const logFn: LogFn = _log.bind(null, logger) as LogFn;
80
- const logged = new Set<String>();
81
- const once = function (message: string, payload?: any, namespace?: string) {
90
+ const logFn = /** @type {import('../types/log.d.ts').LogFn} */ (_log.bind(null, logger));
91
+ /** @type {Set<string>} */
92
+ const logged = new Set();
93
+ /** @type {import('../types/log.d.ts').SimpleLogFn} */
94
+ const once = function (message, payload, namespace) {
82
95
  if (!logger.enabled || logged.has(message)) {
83
96
  return;
84
97
  }
@@ -106,31 +119,24 @@ export const log = {
106
119
  setLevel
107
120
  };
108
121
 
109
- export type SvelteWarningsMessage = {
110
- id: string;
111
- filename: string;
112
- normalizedFilename: string;
113
- timestamp: number;
114
- warnings: Warning[]; // allWarnings filtered by warnings where onwarn did not call the default handler
115
- allWarnings: Warning[]; // includes warnings filtered by onwarn and our extra vite plugin svelte warnings
116
- rawWarnings: Warning[]; // raw compiler output
117
- };
118
-
119
- export function logCompilerWarnings(
120
- svelteRequest: SvelteRequest,
121
- warnings: Warning[],
122
- options: ResolvedOptions
123
- ) {
122
+ /**
123
+ * @param {import('../types/id.d.ts').SvelteRequest} svelteRequest
124
+ * @param {import('svelte/types/compiler/interfaces').Warning[]} warnings
125
+ * @param {import('../types/options.d.ts').ResolvedOptions} options
126
+ */
127
+ export function logCompilerWarnings(svelteRequest, warnings, options) {
124
128
  const { emitCss, onwarn, isBuild } = options;
125
129
  const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser;
126
130
  let warn = isBuild ? warnBuild : warnDev;
127
- const handledByDefaultWarn: Warning[] = [];
131
+ /** @type {import('svelte/types/compiler/interfaces').Warning[]} */
132
+ const handledByDefaultWarn = [];
128
133
  const notIgnored = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
129
134
  const extra = buildExtraWarnings(warnings, isBuild);
130
135
  const allWarnings = [...notIgnored, ...extra];
131
136
  if (sendViaWS) {
132
137
  const _warn = warn;
133
- warn = (w: Warning) => {
138
+ /** @type {(w: import('svelte/types/compiler/interfaces').Warning) => void} */
139
+ warn = (w) => {
134
140
  handledByDefaultWarn.push(w);
135
141
  _warn(w);
136
142
  };
@@ -143,7 +149,8 @@ export function logCompilerWarnings(
143
149
  }
144
150
  });
145
151
  if (sendViaWS) {
146
- const message: SvelteWarningsMessage = {
152
+ /** @type {import('../types/log.d.ts').SvelteWarningsMessage} */
153
+ const message = {
147
154
  id: svelteRequest.id,
148
155
  filename: svelteRequest.filename,
149
156
  normalizedFilename: svelteRequest.normalizedFilename,
@@ -157,23 +164,36 @@ export function logCompilerWarnings(
157
164
  }
158
165
  }
159
166
 
160
- function ignoreCompilerWarning(
161
- warning: Warning,
162
- isBuild: boolean,
163
- emitCss: boolean | undefined
164
- ): boolean {
167
+ /**
168
+ * @param {import('svelte/types/compiler/interfaces').Warning} warning
169
+ * @param {boolean} isBuild
170
+ * @param {boolean} [emitCss]
171
+ * @returns {boolean}
172
+ */
173
+ function ignoreCompilerWarning(warning, isBuild, emitCss) {
165
174
  return (
166
175
  (!emitCss && warning.code === 'css-unused-selector') || // same as rollup-plugin-svelte
167
176
  (!isBuild && isNoScopableElementWarning(warning))
168
177
  );
169
178
  }
170
179
 
171
- function isNoScopableElementWarning(warning: Warning) {
180
+ /**
181
+ *
182
+ * @param {import('svelte/types/compiler/interfaces').Warning} warning
183
+ * @returns {boolean}
184
+ */
185
+ function isNoScopableElementWarning(warning) {
172
186
  // see https://github.com/sveltejs/vite-plugin-svelte/issues/153
173
187
  return warning.code === 'css-unused-selector' && warning.message.includes('"*"');
174
188
  }
175
189
 
176
- function buildExtraWarnings(warnings: Warning[], isBuild: boolean): Warning[] {
190
+ /**
191
+ *
192
+ * @param {import('svelte/types/compiler/interfaces').Warning[]} warnings
193
+ * @param {boolean} isBuild
194
+ * @returns {import('svelte/types/compiler/interfaces').Warning[]}
195
+ */
196
+ function buildExtraWarnings(warnings, isBuild) {
177
197
  const extraWarnings = [];
178
198
  if (!isBuild) {
179
199
  const noScopableElementWarnings = warnings.filter((w) => isNoScopableElementWarning(w));
@@ -191,15 +211,24 @@ function buildExtraWarnings(warnings: Warning[], isBuild: boolean): Warning[] {
191
211
  return extraWarnings;
192
212
  }
193
213
 
194
- function warnDev(w: Warning) {
214
+ /**
215
+ * @param {import('svelte/types/compiler/interfaces').Warning} w
216
+ */
217
+ function warnDev(w) {
195
218
  log.info.enabled && log.info(buildExtendedLogMessage(w));
196
219
  }
197
220
 
198
- function warnBuild(w: Warning) {
221
+ /**
222
+ * @param {import('svelte/types/compiler/interfaces').Warning} w
223
+ */
224
+ function warnBuild(w) {
199
225
  log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame);
200
226
  }
201
227
 
202
- export function buildExtendedLogMessage(w: Warning) {
228
+ /**
229
+ * @param {import('svelte/types/compiler/interfaces').Warning} w
230
+ */
231
+ export function buildExtendedLogMessage(w) {
203
232
  const parts = [];
204
233
  if (w.filename) {
205
234
  parts.push(w.filename);
@@ -216,6 +245,10 @@ export function buildExtendedLogMessage(w: Warning) {
216
245
  return parts.join('');
217
246
  }
218
247
 
219
- export function isDebugNamespaceEnabled(namespace: string) {
248
+ /**
249
+ * @param {string} namespace
250
+ * @returns {boolean}
251
+ */
252
+ export function isDebugNamespaceEnabled(namespace) {
220
253
  return debug.enabled(`vite:${prefix}:${namespace}`);
221
254
  }
@@ -1,9 +1,9 @@
1
1
  import { promises as fs } from 'fs';
2
2
  import path from 'path';
3
- import { ResolvedOptions } from './options';
4
3
 
5
4
  // List of options that changes the prebundling result
6
- const PREBUNDLE_SENSITIVE_OPTIONS: (keyof ResolvedOptions)[] = [
5
+ /** @type {(keyof import('../types/options.d.ts').ResolvedOptions)[]} */
6
+ const PREBUNDLE_SENSITIVE_OPTIONS = [
7
7
  'compilerOptions',
8
8
  'configFile',
9
9
  'experimental',
@@ -13,9 +13,11 @@ const PREBUNDLE_SENSITIVE_OPTIONS: (keyof ResolvedOptions)[] = [
13
13
  ];
14
14
 
15
15
  /**
16
- * @returns Whether the Svelte metadata has changed
16
+ * @param {string} cacheDir
17
+ * @param {import('../types/options.d.ts').ResolvedOptions} options
18
+ * @returns {Promise<boolean>} Whether the Svelte metadata has changed
17
19
  */
18
- export async function saveSvelteMetadata(cacheDir: string, options: ResolvedOptions) {
20
+ export async function saveSvelteMetadata(cacheDir, options) {
19
21
  const svelteMetadata = generateSvelteMetadata(options);
20
22
  const svelteMetadataPath = path.resolve(cacheDir, '_svelte_metadata.json');
21
23
 
@@ -24,7 +26,8 @@ export async function saveSvelteMetadata(cacheDir: string, options: ResolvedOpti
24
26
  return typeof value === 'function' ? value.toString() : value;
25
27
  });
26
28
 
27
- let existingSvelteMetadata: string | undefined;
29
+ /** @type {string | undefined} */
30
+ let existingSvelteMetadata;
28
31
  try {
29
32
  existingSvelteMetadata = await fs.readFile(svelteMetadataPath, 'utf8');
30
33
  } catch {
@@ -36,8 +39,13 @@ export async function saveSvelteMetadata(cacheDir: string, options: ResolvedOpti
36
39
  return currentSvelteMetadata !== existingSvelteMetadata;
37
40
  }
38
41
 
39
- function generateSvelteMetadata(options: ResolvedOptions) {
40
- const metadata: Record<string, any> = {};
42
+ /**
43
+ * @param {import('../types/options.d.ts').ResolvedOptions} options
44
+ * @returns {Partial<import('../types/options.d.ts').ResolvedOptions>}
45
+ */
46
+ function generateSvelteMetadata(options) {
47
+ /** @type {Record<string, any>} */
48
+ const metadata = {};
41
49
  for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
42
50
  metadata[key] = options[key];
43
51
  }