@oddsquad/vite-plugin-lit 0.0.3 → 0.1.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 (175) hide show
  1. package/index.d.ts +3 -2
  2. package/index.d.ts.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/lib/color-scheme.d.ts +30 -0
  6. package/lib/color-scheme.d.ts.map +1 -0
  7. package/lib/color-scheme.js +41 -0
  8. package/lib/color-scheme.js.map +1 -0
  9. package/lib/icons.d.ts +18 -0
  10. package/lib/icons.d.ts.map +1 -0
  11. package/lib/icons.js +23 -0
  12. package/lib/icons.js.map +1 -0
  13. package/lib/plugin.d.ts +117 -6
  14. package/lib/plugin.d.ts.map +1 -1
  15. package/lib/plugin.js +596 -20
  16. package/lib/plugin.js.map +1 -1
  17. package/lib/runtime/css.d.ts +94 -0
  18. package/lib/runtime/css.d.ts.map +1 -0
  19. package/lib/runtime/css.js +112 -0
  20. package/lib/runtime/css.js.map +1 -0
  21. package/lib/runtime/edge-panel.d.ts +18 -0
  22. package/lib/runtime/edge-panel.d.ts.map +1 -0
  23. package/lib/runtime/edge-panel.js +130 -0
  24. package/lib/runtime/edge-panel.js.map +1 -0
  25. package/lib/runtime/fonts.d.ts +18 -0
  26. package/lib/runtime/fonts.d.ts.map +1 -0
  27. package/lib/runtime/fonts.js +18 -0
  28. package/lib/runtime/fonts.js.map +1 -0
  29. package/lib/runtime/indicator.d.ts +7 -0
  30. package/lib/runtime/indicator.d.ts.map +1 -0
  31. package/lib/runtime/indicator.js +141 -0
  32. package/lib/runtime/indicator.js.map +1 -0
  33. package/lib/runtime/inspector/collect.d.ts +17 -0
  34. package/lib/runtime/inspector/collect.d.ts.map +1 -0
  35. package/lib/runtime/inspector/collect.js +132 -0
  36. package/lib/runtime/inspector/collect.js.map +1 -0
  37. package/lib/runtime/inspector/install.d.ts +7 -0
  38. package/lib/runtime/inspector/install.d.ts.map +1 -0
  39. package/lib/runtime/inspector/install.js +204 -0
  40. package/lib/runtime/inspector/install.js.map +1 -0
  41. package/lib/runtime/inspector/serialize.d.ts +10 -0
  42. package/lib/runtime/inspector/serialize.d.ts.map +1 -0
  43. package/lib/runtime/inspector/serialize.js +133 -0
  44. package/lib/runtime/inspector/serialize.js.map +1 -0
  45. package/lib/runtime/intern.d.ts.map +1 -1
  46. package/lib/runtime/intern.js +1 -1
  47. package/lib/runtime/intern.js.map +1 -1
  48. package/lib/runtime/overrides.d.ts +25 -0
  49. package/lib/runtime/overrides.d.ts.map +1 -0
  50. package/lib/runtime/overrides.js +33 -0
  51. package/lib/runtime/overrides.js.map +1 -0
  52. package/lib/runtime/patch.d.ts +6 -15
  53. package/lib/runtime/patch.d.ts.map +1 -1
  54. package/lib/runtime/patch.js +81 -28
  55. package/lib/runtime/patch.js.map +1 -1
  56. package/lib/runtime/source-meta.d.ts +16 -0
  57. package/lib/runtime/source-meta.d.ts.map +1 -0
  58. package/lib/runtime/source-meta.js +8 -0
  59. package/lib/runtime/source-meta.js.map +1 -0
  60. package/lib/runtime/source-overlay/editors.d.ts +9 -0
  61. package/lib/runtime/source-overlay/editors.d.ts.map +1 -0
  62. package/lib/runtime/source-overlay/editors.js +40 -0
  63. package/lib/runtime/source-overlay/editors.js.map +1 -0
  64. package/lib/runtime/source-overlay/mask-path.d.ts +7 -0
  65. package/lib/runtime/source-overlay/mask-path.d.ts.map +1 -0
  66. package/lib/runtime/source-overlay/mask-path.js +26 -0
  67. package/lib/runtime/source-overlay/mask-path.js.map +1 -0
  68. package/lib/runtime/source-overlay/overlay-element.d.ts +18 -0
  69. package/lib/runtime/source-overlay/overlay-element.d.ts.map +1 -0
  70. package/lib/runtime/source-overlay/overlay-element.js +381 -0
  71. package/lib/runtime/source-overlay/overlay-element.js.map +1 -0
  72. package/lib/runtime/source-overlay/source-host.d.ts +14 -0
  73. package/lib/runtime/source-overlay/source-host.d.ts.map +1 -0
  74. package/lib/runtime/source-overlay/source-host.js +94 -0
  75. package/lib/runtime/source-overlay/source-host.js.map +1 -0
  76. package/lib/runtime/source-overlay/template.d.ts +7 -0
  77. package/lib/runtime/source-overlay/template.d.ts.map +1 -0
  78. package/lib/runtime/source-overlay/template.js +125 -0
  79. package/lib/runtime/source-overlay/template.js.map +1 -0
  80. package/lib/runtime/source-overlay.d.ts +7 -0
  81. package/lib/runtime/source-overlay.d.ts.map +1 -0
  82. package/lib/runtime/source-overlay.js +11 -0
  83. package/lib/runtime/source-overlay.js.map +1 -0
  84. package/lib/runtime/timeline/clock.d.ts +10 -0
  85. package/lib/runtime/timeline/clock.d.ts.map +1 -0
  86. package/lib/runtime/timeline/clock.js +22 -0
  87. package/lib/runtime/timeline/clock.js.map +1 -0
  88. package/lib/runtime/timeline/identity.d.ts +37 -0
  89. package/lib/runtime/timeline/identity.d.ts.map +1 -0
  90. package/lib/runtime/timeline/identity.js +73 -0
  91. package/lib/runtime/timeline/identity.js.map +1 -0
  92. package/lib/runtime/timeline/input.d.ts +16 -0
  93. package/lib/runtime/timeline/input.d.ts.map +1 -0
  94. package/lib/runtime/timeline/input.js +87 -0
  95. package/lib/runtime/timeline/input.js.map +1 -0
  96. package/lib/runtime/timeline/install.d.ts +7 -0
  97. package/lib/runtime/timeline/install.d.ts.map +1 -0
  98. package/lib/runtime/timeline/install.js +69 -0
  99. package/lib/runtime/timeline/install.js.map +1 -0
  100. package/lib/runtime/timeline/lifecycle.d.ts +27 -0
  101. package/lib/runtime/timeline/lifecycle.d.ts.map +1 -0
  102. package/lib/runtime/timeline/lifecycle.js +225 -0
  103. package/lib/runtime/timeline/lifecycle.js.map +1 -0
  104. package/lib/runtime/timeline/public-api.d.ts +28 -0
  105. package/lib/runtime/timeline/public-api.d.ts.map +1 -0
  106. package/lib/runtime/timeline/public-api.js +44 -0
  107. package/lib/runtime/timeline/public-api.js.map +1 -0
  108. package/lib/runtime/timeline/render.d.ts +39 -0
  109. package/lib/runtime/timeline/render.d.ts.map +1 -0
  110. package/lib/runtime/timeline/render.js +109 -0
  111. package/lib/runtime/timeline/render.js.map +1 -0
  112. package/lib/runtime/timeline/transport.d.ts +42 -0
  113. package/lib/runtime/timeline/transport.d.ts.map +1 -0
  114. package/lib/runtime/timeline/transport.js +86 -0
  115. package/lib/runtime/timeline/transport.js.map +1 -0
  116. package/lib/segmented-tabs.d.ts +33 -0
  117. package/lib/segmented-tabs.d.ts.map +1 -0
  118. package/lib/segmented-tabs.js +129 -0
  119. package/lib/segmented-tabs.js.map +1 -0
  120. package/lib/source-meta.d.ts +26 -0
  121. package/lib/source-meta.d.ts.map +1 -0
  122. package/lib/source-meta.js +129 -0
  123. package/lib/source-meta.js.map +1 -0
  124. package/lib/timeline-plugin.d.ts +72 -0
  125. package/lib/timeline-plugin.d.ts.map +1 -0
  126. package/lib/timeline-plugin.js +376 -0
  127. package/lib/timeline-plugin.js.map +1 -0
  128. package/lib/tokens.d.ts +38 -0
  129. package/lib/tokens.d.ts.map +1 -0
  130. package/lib/tokens.js +263 -0
  131. package/lib/tokens.js.map +1 -0
  132. package/lib/transform.d.ts +5 -5
  133. package/lib/transform.d.ts.map +1 -1
  134. package/lib/transform.js +3 -3
  135. package/lib/transform.js.map +1 -1
  136. package/lib/types.d.ts +34 -0
  137. package/lib/types.d.ts.map +1 -0
  138. package/lib/types.js +7 -0
  139. package/lib/types.js.map +1 -0
  140. package/lib/wrap-table.d.ts.map +1 -1
  141. package/lib/wrap-table.js.map +1 -1
  142. package/package.json +18 -4
  143. package/panel/components-view.d.ts +60 -0
  144. package/panel/components-view.d.ts.map +1 -0
  145. package/panel/components-view.js +581 -0
  146. package/panel/components-view.js.map +1 -0
  147. package/panel/devtools-settings.d.ts +41 -0
  148. package/panel/devtools-settings.d.ts.map +1 -0
  149. package/panel/devtools-settings.js +463 -0
  150. package/panel/devtools-settings.js.map +1 -0
  151. package/panel/index.html +29 -0
  152. package/panel/lit-devtools-panel.d.ts +37 -0
  153. package/panel/lit-devtools-panel.d.ts.map +1 -0
  154. package/panel/lit-devtools-panel.js +183 -0
  155. package/panel/lit-devtools-panel.js.map +1 -0
  156. package/panel/timeline-event-list.d.ts +43 -0
  157. package/panel/timeline-event-list.d.ts.map +1 -0
  158. package/panel/timeline-event-list.js +416 -0
  159. package/panel/timeline-event-list.js.map +1 -0
  160. package/panel/timeline-layers.d.ts +25 -0
  161. package/panel/timeline-layers.d.ts.map +1 -0
  162. package/panel/timeline-layers.js +96 -0
  163. package/panel/timeline-layers.js.map +1 -0
  164. package/panel/timeline-view.d.ts +38 -0
  165. package/panel/timeline-view.d.ts.map +1 -0
  166. package/panel/timeline-view.js +234 -0
  167. package/panel/timeline-view.js.map +1 -0
  168. package/types/inspector.d.ts +130 -0
  169. package/types/inspector.d.ts.map +1 -0
  170. package/types/inspector.js +16 -0
  171. package/types/inspector.js.map +1 -0
  172. package/types/timeline.d.ts +98 -0
  173. package/types/timeline.d.ts.map +1 -0
  174. package/types/timeline.js +39 -0
  175. package/types/timeline.js.map +1 -0
package/lib/plugin.js CHANGED
@@ -4,9 +4,122 @@
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
5
  */
6
6
  import { existsSync } from 'node:fs';
7
+ import { resolve as resolvePath, sep } from 'node:path';
7
8
  import { fileURLToPath } from 'node:url';
9
+ import { loadEnv } from 'vite';
10
+ import MagicString from 'magic-string';
11
+ import { injectSourceMeta } from './source-meta.js';
8
12
  import { INSTALL_ID, VIRTUAL_PREFIX, transformLitModule } from './transform.js';
9
13
  import { WRAP_TABLE } from './wrap-table.js';
14
+ import { litTimelinePlugin } from './timeline-plugin.js';
15
+ const CSS_SHEET_BUILD_MODES = [
16
+ 'auto',
17
+ 'url',
18
+ 'inline',
19
+ 'inline-raw',
20
+ ];
21
+ /** Env var prefix consumed at config time. */
22
+ const ENV_PREFIX = 'LIT_PLUGIN';
23
+ /** Parse a boolean-ish env string; `undefined` when unset/unrecognized. */
24
+ const envBool = (v) => v === 'true' || v === '1'
25
+ ? true
26
+ : v === 'false' || v === '0'
27
+ ? false
28
+ : undefined;
29
+ /** Parse a numeric env string; `undefined` when unset/non-numeric. */
30
+ const envNum = (v) => {
31
+ if (v === undefined || v === '')
32
+ return undefined;
33
+ const n = Number(v);
34
+ return Number.isNaN(n) ? undefined : n;
35
+ };
36
+ /**
37
+ * Parse a string against a closed set of values; `undefined` (with a warning)
38
+ * when set to something outside it, so a typo falls back to the default
39
+ * instead of silently disabling a feature.
40
+ */
41
+ const envEnum = (v, allowed, source) => {
42
+ if (v === undefined || v === '')
43
+ return undefined;
44
+ if (allowed.includes(v))
45
+ return v;
46
+ console.warn(`[lit-plugin] ignoring ${source}=${JSON.stringify(v)}; expected one of ` +
47
+ allowed.map((a) => JSON.stringify(a)).join(', '));
48
+ return undefined;
49
+ };
50
+ /**
51
+ * Merge explicit options over env vars over defaults (in that precedence) into
52
+ * the flat shape the plugin hooks consume.
53
+ */
54
+ export const resolveOptions = (options, env) => {
55
+ const hmr = options.hmr;
56
+ const hmrObj = typeof hmr === 'object' ? hmr : undefined;
57
+ const hmrEnabled = (typeof hmr === 'boolean' ? hmr : hmrObj?.enabled) ??
58
+ envBool(env[`${ENV_PREFIX}_HMR`]) ??
59
+ true;
60
+ const reconnect = hmrObj?.reconnect ?? envBool(env[`${ENV_PREFIX}_HMR_RECONNECT`]) ?? false;
61
+ const onIncompatible = hmrObj?.onIncompatible ??
62
+ env[`${ENV_PREFIX}_HMR_ON_INCOMPATIBLE`] ??
63
+ 'reload';
64
+ const ind = hmrObj?.indicator;
65
+ const indObj = typeof ind === 'object' ? ind : undefined;
66
+ const indEnabled = (typeof ind === 'boolean' ? ind : indObj?.enabled) ??
67
+ envBool(env[`${ENV_PREFIX}_HMR_INDICATOR`]) ??
68
+ true;
69
+ const indCount = indObj?.count ?? envBool(env[`${ENV_PREFIX}_HMR_INDICATOR_COUNT`]) ?? false;
70
+ // The indicator is meaningless without HMR, so it follows the master toggle.
71
+ const indicator = hmrEnabled && indEnabled ? { count: indCount } : false;
72
+ const so = options.sourceOverlay;
73
+ const soExplicit = typeof so === 'boolean' ? so : so === undefined ? undefined : true;
74
+ const soEnabled = soExplicit ?? envBool(env[`${ENV_PREFIX}_SOURCE_OVERLAY`]) ?? false;
75
+ let sourceOverlay = false;
76
+ if (soEnabled) {
77
+ const base = typeof so === 'object' ? { ...so } : {};
78
+ base.key ??= env[`${ENV_PREFIX}_SOURCE_OVERLAY_KEY`] || undefined;
79
+ base.editor ??= env[`${ENV_PREFIX}_SOURCE_OVERLAY_EDITOR`] || undefined;
80
+ base.throttleMs ??= envNum(env[`${ENV_PREFIX}_SOURCE_OVERLAY_THROTTLE_MS`]);
81
+ sourceOverlay = base;
82
+ }
83
+ const timeline = options.timeline ?? envBool(env[`${ENV_PREFIX}_TIMELINE`]) ?? false;
84
+ const cssSheetBuild = envEnum(options.cssSheetBuild, CSS_SHEET_BUILD_MODES, 'cssSheetBuild') ??
85
+ envEnum(env[`${ENV_PREFIX}_CSS_SHEET_BUILD`], CSS_SHEET_BUILD_MODES, `${ENV_PREFIX}_CSS_SHEET_BUILD`) ??
86
+ 'auto';
87
+ return {
88
+ hmrEnabled,
89
+ reconnect,
90
+ onIncompatible,
91
+ indicator,
92
+ sourceOverlay,
93
+ timeline,
94
+ cssSheetBuild,
95
+ };
96
+ };
97
+ /**
98
+ * Flattens resolved options into the JSON-serializable shape the panel's
99
+ * Settings tab consumes (callback options like `exclude`/`onSelect` dropped;
100
+ * a custom editor object reported as `"custom"`). Default key/editor/throttle
101
+ * are applied here so the panel shows the effective values the runtime uses.
102
+ */
103
+ const toFeatureSettings = (r) => {
104
+ const so = r.sourceOverlay;
105
+ const editor = so === false ? undefined : so.editor;
106
+ return {
107
+ hmr: {
108
+ enabled: r.hmrEnabled,
109
+ reconnect: r.reconnect,
110
+ onIncompatible: r.onIncompatible,
111
+ indicatorEnabled: r.indicator !== false,
112
+ indicatorCount: r.indicator !== false && r.indicator.count,
113
+ },
114
+ sourceOverlay: {
115
+ enabled: so !== false,
116
+ key: (so === false ? undefined : so.key) ?? 's',
117
+ editor: typeof editor === 'string' ? editor : editor ? 'custom' : 'vscode',
118
+ throttleMs: (so === false ? undefined : so.throttleMs) ?? 50,
119
+ },
120
+ timeline: r.timeline,
121
+ };
122
+ };
10
123
  /**
11
124
  * Resolves a runtime module to an absolute fs path (served via `/@fs/`), so
12
125
  * the plugin works from any served root. Falls back from the built `.js` to
@@ -19,42 +132,448 @@ const resolveRuntimeModule = (name) => {
19
132
  return fileURLToPath(url).replace(/\\/g, '/');
20
133
  }
21
134
  }
22
- throw new Error(`[lit-hmr] runtime module not found: ${name}`);
135
+ throw new Error(`[lit-plugin] runtime module not found: ${name}`);
23
136
  };
24
137
  const JS_FILE_RE = /\.[cm]?[jt]sx?$/;
138
+ const OPEN_IN_EDITOR_PATH = '/__lit-open-in-editor';
139
+ /** Reject requests whose `Origin` is a different host than the dev server, so
140
+ * a page the developer happens to visit can't drive these local-only
141
+ * endpoints. Same-origin requests (no `Origin`, or matching `Host`) pass. */
142
+ const isSameOrigin = (headers) => {
143
+ const { origin, host } = headers;
144
+ if (origin === undefined || origin === 'null')
145
+ return true;
146
+ try {
147
+ return new URL(origin).host === host;
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ };
153
+ const createOpenInEditorMiddleware = (root) => {
154
+ return (req, res, next) => {
155
+ if (req.url === undefined) {
156
+ next();
157
+ return;
158
+ }
159
+ if (!isSameOrigin(req.headers ?? {})) {
160
+ res.statusCode = 403;
161
+ res.end('forbidden');
162
+ return;
163
+ }
164
+ const query = req.url.includes('?')
165
+ ? req.url.slice(req.url.indexOf('?') + 1)
166
+ : '';
167
+ const params = new URLSearchParams(query);
168
+ const file = params.get('file');
169
+ if (file === null) {
170
+ res.statusCode = 400;
171
+ res.end('missing file parameter');
172
+ return;
173
+ }
174
+ // Confine the open to the project root: resolve the requested path and
175
+ // reject anything that escapes `root` (path traversal, absolute paths to
176
+ // arbitrary files). `launch-editor` spawns the user's editor on this path,
177
+ // so an unvalidated `file` is a local-file-open / arg-injection vector.
178
+ const resolved = resolvePath(root, file);
179
+ if (resolved !== root && !resolved.startsWith(root + sep)) {
180
+ res.statusCode = 403;
181
+ res.end('file outside project root');
182
+ return;
183
+ }
184
+ if (!existsSync(resolved)) {
185
+ res.statusCode = 404;
186
+ res.end('file not found');
187
+ return;
188
+ }
189
+ // Coerce to integers so a crafted `line`/`column` can't smuggle extra
190
+ // shell-visible content through the `file:line:column` ref.
191
+ const line = String(Math.max(1, Number.parseInt(params.get('line') ?? '1', 10) || 1));
192
+ const column = String(Math.max(1, Number.parseInt(params.get('column') ?? '1', 10) || 1));
193
+ const fileRef = `${resolved}:${line}:${column}`;
194
+ import('launch-editor')
195
+ .then((mod) => {
196
+ const launch = (mod.default ?? mod);
197
+ launch(fileRef, (_fileName, errorMessage) => {
198
+ if (errorMessage !== null) {
199
+ res.statusCode = 500;
200
+ res.end(errorMessage);
201
+ return;
202
+ }
203
+ res.end('ok');
204
+ });
205
+ })
206
+ .catch(next);
207
+ };
208
+ };
209
+ /**
210
+ * `import href from './x.css?hmr-url'` — `?url` semantics with working HMR.
211
+ * The string is a real stylesheet URL (dev-served CSS file; hashed `.css`
212
+ * asset on build) for shadow-root `<link>` hrefs and `@import url()`s. In
213
+ * dev, each HMR re-execution yields a freshly cache-busted href, so the
214
+ * browser refetches the changed stylesheet; in build the `?url` asset URL
215
+ * passes through unchanged.
216
+ */
217
+ const CSS_URL_QUERY_RE = /^([^?]+\.css)\?(?:[^&]*&)*hmr-url(?:&.*)?$/;
218
+ const CSS_URL_VIRTUAL_PREFIX = '\0lit-plugin:hmr-url:';
25
219
  /**
26
- * Dev-only Vite plugin providing true HMR for Lit: template-strings
27
- * interning plus in-place custom element class patching.
220
+ * `import sheet from './x.css?css-sheet'` — a constructed, shareable
221
+ * `CSSStyleSheet` backed by the `.css` asset that hot-swaps in place. Adopt it
222
+ * from any number of components (`static styles = [sheet]`); a source edit
223
+ * re-fetches and `replaceSync()`s it, updating every shadow root that adopted
224
+ * it without re-rendering a component or reloading the page.
225
+ *
226
+ * This is the `urlSheet()` helper plus its irreducible HMR wiring, lifted into
227
+ * a plugin-generated module: the `import.meta.hot.accept` lives here (where
228
+ * Vite's static analysis sees the literal specifier), so callers write a bare
229
+ * import and never touch `import.meta.hot` themselves.
230
+ *
231
+ * Under `vite build` the generated module can instead inline the css text (see
232
+ * `cssSheetBuild`) — a library's consumers bundle its JS only, so a
233
+ * fetch-backed sheet would 404 on the `.css` asset that never reached their
234
+ * build.
28
235
  */
29
- export const litHmr = (options = {}) => {
30
- const runtimeOptions = {
31
- reconnect: options.reconnect ?? false,
32
- onIncompatible: options.onIncompatible ?? 'reload',
236
+ const CSS_SHEET_QUERY_RE = /^([^?]+\.css)\?(?:[^&]*&)*css-sheet(?:&.*)?$/;
237
+ const CSS_SHEET_VIRTUAL_PREFIX = '\0lit-plugin:css-sheet:';
238
+ // The virtual id must not end in `.css`, or Vite's CSS plugins (which match
239
+ // the id's extension regardless of `\0`) would compile the wrapper as CSS.
240
+ const CSS_VIRTUAL_SUFFIX = '.js';
241
+ /**
242
+ * Import-query support, served in dev and build alike (source code using
243
+ * `?hmr-url`/`?css-sheet` must keep working under `vite build`, where the HMR
244
+ * plugin doesn't apply). Exported for the baseline e2e run, which needs the
245
+ * queries working without the HMR plugin.
246
+ *
247
+ * `getCssSheetBuild` is a getter, not a value: `litPlugin()` re-resolves its
248
+ * options against the loaded env in a `config` hook, which runs after the
249
+ * plugin array is built. Standalone (no getter) it behaves like the `'auto'`
250
+ * default.
251
+ */
252
+ export const litCssQueries = (getCssSheetBuild = () => 'auto') => {
253
+ let isBuild = false;
254
+ let isLib = false;
255
+ return {
256
+ name: 'lit-css-query',
257
+ // Vite's core resolver claims `./x.css?hmr-url` for the CSS pipeline
258
+ // before normal plugins get a look, so resolve ahead of it.
259
+ enforce: 'pre',
260
+ configResolved(config) {
261
+ isBuild = config.command === 'build';
262
+ isLib = config.build.lib !== false && config.build.lib !== undefined;
263
+ },
264
+ async resolveId(id, importer) {
265
+ const prefix = CSS_URL_QUERY_RE.test(id)
266
+ ? CSS_URL_VIRTUAL_PREFIX
267
+ : CSS_SHEET_QUERY_RE.test(id)
268
+ ? CSS_SHEET_VIRTUAL_PREFIX
269
+ : null;
270
+ if (prefix === null) {
271
+ return null;
272
+ }
273
+ const file = id.slice(0, id.indexOf('?'));
274
+ const resolved = await this.resolve(file, importer);
275
+ if (resolved === null) {
276
+ return null;
277
+ }
278
+ return prefix + resolved.id + CSS_VIRTUAL_SUFFIX;
279
+ },
280
+ load(id) {
281
+ const helperPath = resolveRuntimeModule('css');
282
+ if (id.startsWith(CSS_URL_VIRTUAL_PREFIX)) {
283
+ const file = id.slice(CSS_URL_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length);
284
+ return {
285
+ code: `import url from ${JSON.stringify(`${file}?url`)};\n` +
286
+ `import {devCacheBust} from ${JSON.stringify(helperPath)};\n` +
287
+ `export default devCacheBust(url);\n`,
288
+ moduleType: 'js',
289
+ };
290
+ }
291
+ if (id.startsWith(CSS_SHEET_VIRTUAL_PREFIX)) {
292
+ const file = id.slice(CSS_SHEET_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length);
293
+ const mode = getCssSheetBuild();
294
+ const inlineQuery = !isBuild || mode === 'url' || (mode === 'auto' && !isLib)
295
+ ? null
296
+ : mode === 'inline-raw'
297
+ ? '?raw'
298
+ : '?inline';
299
+ if (inlineQuery !== null) {
300
+ // Build only, so no `import.meta.hot` block. The sheet is still
301
+ // constructed once per virtual module, so adopters share it exactly
302
+ // as they do in the fetch-backed form.
303
+ return {
304
+ code: `import css from ${JSON.stringify(`${file}${inlineQuery}`)};\n` +
305
+ `const sheet = new CSSStyleSheet();\n` +
306
+ `sheet.replaceSync(css);\n` +
307
+ `export default sheet;\n`,
308
+ moduleType: 'js',
309
+ };
310
+ }
311
+ // The accept specifier must be byte-identical to the import above —
312
+ // Vite resolves accepted HMR deps by static analysis. Generating both
313
+ // here is exactly what frees the caller from writing it. The swap is
314
+ // self-accepted at this boundary, so it never propagates to adopters.
315
+ const urlSpecifier = JSON.stringify(`${file}?url`);
316
+ return {
317
+ code: `import url from ${urlSpecifier};\n` +
318
+ `import {urlSheet} from ${JSON.stringify(helperPath)};\n` +
319
+ `const {sheet, onHotUpdate} = urlSheet(url);\n` +
320
+ `export default sheet;\n` +
321
+ `if (import.meta.hot) {\n` +
322
+ ` import.meta.hot.accept(${urlSpecifier}, onHotUpdate);\n` +
323
+ `}\n`,
324
+ moduleType: 'js',
325
+ };
326
+ }
327
+ return null;
328
+ },
33
329
  };
330
+ };
331
+ /**
332
+ * A `css` tagged template literal with no interpolations and no escape
333
+ * sequences — the only kind we can hand to a CSS parser as-is. Literals
334
+ * with `${…}` holes or backslashes simply don't match and stay untouched.
335
+ * The lookbehind keeps `unsafeCSS`/`myCss`-style tags from matching.
336
+ */
337
+ const CSS_LITERAL_RE = /(?<![\w$.])css`((?:[^`\\$]|\$(?!\{))*)`/g;
338
+ /**
339
+ * Runs Vite's configured Lightning CSS over `css` tagged template literals
340
+ * in user modules, which the CSS pipeline itself never sees (they're plain
341
+ * JS strings to it). Inert unless `css.transformer` is `'lightningcss'`;
342
+ * options come from `css.lightningcss`, so component styles get the same
343
+ * treatment (targets, drafts, …) as `.css` files. Applies in dev and build.
344
+ */
345
+ const litCssLiterals = () => {
346
+ let lightningcss = null;
347
+ let options;
348
+ let minify = false;
34
349
  return {
35
- name: 'lit-hmr',
350
+ name: 'lit-css-literals',
351
+ async configResolved(config) {
352
+ if (config.css.transformer !== 'lightningcss') {
353
+ return;
354
+ }
355
+ // The transformer setting guarantees the dependency: Vite itself
356
+ // can't process .css files without it.
357
+ lightningcss = await import('lightningcss');
358
+ // cssModules makes no sense for a literal; everything else carries
359
+ // over.
360
+ const { cssModules: _cssModules, ...rest } = config.css.lightningcss ?? {};
361
+ options = rest;
362
+ minify = config.command === 'build';
363
+ },
364
+ transform(code, id) {
365
+ if (lightningcss === null) {
366
+ return null;
367
+ }
368
+ if (id.startsWith('\0') || id.includes('/node_modules/')) {
369
+ return null;
370
+ }
371
+ const [file] = id.split('?', 2);
372
+ if (!JS_FILE_RE.test(file) || !code.includes('css`')) {
373
+ return null;
374
+ }
375
+ const ms = new MagicString(code);
376
+ let changed = false;
377
+ for (const m of code.matchAll(CSS_LITERAL_RE)) {
378
+ const literal = m[1];
379
+ if (literal.trim() === '') {
380
+ continue;
381
+ }
382
+ let out;
383
+ try {
384
+ const result = lightningcss.transform({
385
+ ...options,
386
+ filename: file,
387
+ code: Buffer.from(literal),
388
+ minify,
389
+ });
390
+ out = Buffer.from(result.code).toString();
391
+ }
392
+ catch (e) {
393
+ this.warn(`[lit-plugin] skipping css literal Lightning CSS couldn't parse: ${e.message}`);
394
+ continue;
395
+ }
396
+ // Re-escape for the template literal the output goes back into.
397
+ out = out.replace(/[\\`$]/g, '\\$&');
398
+ if (out !== literal) {
399
+ const start = m.index + 'css`'.length;
400
+ ms.overwrite(start, start + literal.length, out);
401
+ changed = true;
402
+ }
403
+ }
404
+ if (!changed) {
405
+ return null;
406
+ }
407
+ return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
408
+ },
409
+ };
410
+ };
411
+ /**
412
+ * Vite plugin set providing HMR, CSS helpers, and Lightning CSS processing
413
+ * for Lit projects.
414
+ */
415
+ export const litPlugin = (options = {}) => {
416
+ // Resolved from explicit options first, env vars second, defaults last. The
417
+ // `lit-plugin-options` `config` hook below re-resolves with the loaded env
418
+ // once Vite hands us the mode; this initial pass covers code paths that run
419
+ // before (or without) it.
420
+ let resolved = resolveOptions(options, {});
421
+ let root = '';
422
+ // Env resolution lives in its own always-applied plugin: `?css-sheet` is a
423
+ // build-time feature too, and the HMR plugin (`apply: 'serve'`) never gets a
424
+ // `config` hook under `vite build`. `enforce: 'pre'` and first position put
425
+ // it ahead of every other hook that reads `resolved`.
426
+ const optionsPlugin = {
427
+ name: 'lit-plugin-options',
428
+ enforce: 'pre',
429
+ config(viteConfig, { mode }) {
430
+ // `loadEnv` reads `.env*` files from the env dir (root by default) and
431
+ // merges in matching `process.env` keys, filtered to the `LIT_PLUGIN`
432
+ // prefix. Explicit options still win (handled in resolveOptions).
433
+ const envDir = viteConfig.envDir
434
+ ? resolvePath(viteConfig.envDir)
435
+ : viteConfig.root
436
+ ? resolvePath(viteConfig.root)
437
+ : process.cwd();
438
+ resolved = resolveOptions(options, loadEnv(mode, envDir, ENV_PREFIX));
439
+ },
440
+ };
441
+ const sourceOverlayPlugin = {
442
+ name: 'lit-source-overlay',
443
+ apply: 'serve',
444
+ // Run before Vite's esbuild TS transform so source-meta line numbers are
445
+ // measured against the author's raw source (and the `@customElement … class`
446
+ // forms are still intact), not against transpiled output.
447
+ enforce: 'pre',
448
+ configResolved(config) {
449
+ root = config.root;
450
+ },
451
+ resolveId(id) {
452
+ if (id === '@lit-labs/vite-plugin-lit/source-overlay.js') {
453
+ return resolveRuntimeModule('source-overlay');
454
+ }
455
+ return null;
456
+ },
457
+ configureServer(server) {
458
+ if (!resolved.sourceOverlay)
459
+ return;
460
+ server.middlewares.use(OPEN_IN_EDITOR_PATH, createOpenInEditorMiddleware(root));
461
+ },
462
+ transform(code, id, transformOptions) {
463
+ if (!resolved.sourceOverlay)
464
+ return null;
465
+ if (transformOptions?.ssr)
466
+ return null;
467
+ if (id.startsWith('\0') ||
468
+ id.includes('__x00__') ||
469
+ id.includes('lit-plugin:') ||
470
+ id.includes('/node_modules/')) {
471
+ return null;
472
+ }
473
+ const [file] = id.split('?', 2);
474
+ if (!JS_FILE_RE.test(file) && !id.includes('?html-proxy')) {
475
+ return null;
476
+ }
477
+ if (!code.includes('customElement') && !code.includes('customElements')) {
478
+ return null;
479
+ }
480
+ const ms = new MagicString(code);
481
+ const relativeFile = file.startsWith(root + '/')
482
+ ? file.slice(root.length + 1)
483
+ : file;
484
+ if (!injectSourceMeta(code, relativeFile, ms)) {
485
+ return null;
486
+ }
487
+ return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
488
+ },
489
+ transformIndexHtml() {
490
+ if (!resolved.sourceOverlay)
491
+ return;
492
+ const overlayUrl = `/@fs/${resolveRuntimeModule('source-overlay')}`;
493
+ const { exclude: _exclude, onSelect: _onSelect, ...overlayInit } = resolved.sourceOverlay;
494
+ const initConfig = {
495
+ ...overlayInit,
496
+ openInEditorPath: OPEN_IN_EDITOR_PATH,
497
+ };
498
+ return [
499
+ {
500
+ tag: 'script',
501
+ attrs: { type: 'module' },
502
+ children: `import {initSourceOverlay} from ${JSON.stringify(overlayUrl)};\ninitSourceOverlay(${JSON.stringify(initConfig)});\n`,
503
+ injectTo: 'body',
504
+ },
505
+ ];
506
+ },
507
+ };
508
+ const hmr = {
509
+ name: 'lit-plugin',
36
510
  apply: 'serve',
37
- // The injected runtime imports are invisible to the dep scanner. The
38
- // lit family stays prebundle-eligible on purpose: the wrapper modules'
39
- // bare imports then resolve to the same URL every other importer gets —
40
- // single lit instance, single template cache.
41
- config: () => ({
42
- optimizeDeps: { exclude: ['@lit-labs/vite-hmr'] },
43
- }),
511
+ config: () => {
512
+ // Options are already resolved against the loaded env by
513
+ // `lit-plugin-options`, which runs first.
514
+ if (!resolved.hmrEnabled) {
515
+ return;
516
+ }
517
+ // The injected runtime imports are invisible to the dep scanner. The
518
+ // lit family stays prebundle-eligible on purpose: the wrapper modules'
519
+ // bare imports then resolve to the same URL every other importer gets —
520
+ // single lit instance, single template cache.
521
+ return { optimizeDeps: { exclude: ['@lit-labs/vite-plugin-lit'] } };
522
+ },
44
523
  resolveId(id) {
45
- if (id.startsWith(VIRTUAL_PREFIX)) {
524
+ // Public timeline API virtual module.
525
+ if (id === 'virtual:lit-plugin/timeline') {
526
+ return '\0virtual:lit-plugin/timeline';
527
+ }
528
+ // Resolve the browser CSS helpers and indicator runtime to the copy
529
+ // shipped next to this plugin, so they work even when the package
530
+ // isn't reachable through node resolution from the served root (and
531
+ // stay out of prebundling).
532
+ if (id === '@lit-labs/vite-plugin-lit/css.js') {
533
+ return resolveRuntimeModule('css');
534
+ }
535
+ if (id === '@lit-labs/vite-plugin-lit/indicator.js') {
536
+ return resolveRuntimeModule('indicator');
537
+ }
538
+ if (id === '@lit-labs/vite-plugin-lit/source-overlay.js') {
539
+ return resolveRuntimeModule('source-overlay');
540
+ }
541
+ if (resolved.hmrEnabled && id.startsWith(VIRTUAL_PREFIX)) {
46
542
  return id;
47
543
  }
48
544
  return null;
49
545
  },
50
546
  load(id) {
51
- if (!id.startsWith(VIRTUAL_PREFIX)) {
547
+ // Public timeline API — re-export the runtime module when timeline is
548
+ // enabled, otherwise a no-op stub so imports don't throw in prod builds.
549
+ if (id === '\0virtual:lit-plugin/timeline') {
550
+ if (!resolved.timeline) {
551
+ return {
552
+ code: 'export const addTimelineEvent = () => {};\n' +
553
+ 'export const addTimelineLayer = () => {};\n',
554
+ moduleType: 'js',
555
+ };
556
+ }
557
+ const apiPath = resolveRuntimeModule('timeline/public-api');
558
+ return {
559
+ code: `export * from ${JSON.stringify(apiPath)};\n`,
560
+ moduleType: 'js',
561
+ };
562
+ }
563
+ if (!resolved.hmrEnabled || !id.startsWith(VIRTUAL_PREFIX)) {
52
564
  return null;
53
565
  }
54
566
  if (id === INSTALL_ID) {
55
567
  const patchPath = resolveRuntimeModule('patch');
56
- return (`import {install} from ${JSON.stringify(patchPath)};\n` +
57
- `install(${JSON.stringify(runtimeOptions)});\n`);
568
+ const runtimeOptions = {
569
+ reconnect: resolved.reconnect,
570
+ onIncompatible: resolved.onIncompatible,
571
+ };
572
+ return {
573
+ code: `import {install} from ${JSON.stringify(patchPath)};\n` +
574
+ `install(${JSON.stringify(runtimeOptions)});\n`,
575
+ moduleType: 'js',
576
+ };
58
577
  }
59
578
  const spec = id.slice(VIRTUAL_PREFIX.length);
60
579
  const wrappedTags = WRAP_TABLE.get(spec);
@@ -73,9 +592,12 @@ export const litHmr = (options = {}) => {
73
592
  for (const { exportName, ns } of wrappedTags) {
74
593
  lines.push(`export const ${exportName} = wrapTag(__lit.${exportName}, ${JSON.stringify(ns)});`);
75
594
  }
76
- return lines.join('\n') + '\n';
595
+ return { code: lines.join('\n') + '\n', moduleType: 'js' };
77
596
  },
78
597
  async transform(code, id, transformOptions) {
598
+ if (!resolved.hmrEnabled) {
599
+ return null;
600
+ }
79
601
  if (transformOptions?.ssr) {
80
602
  return null;
81
603
  }
@@ -89,6 +611,60 @@ export const litHmr = (options = {}) => {
89
611
  }
90
612
  return transformLitModule(code);
91
613
  },
614
+ transformIndexHtml() {
615
+ const tags = [];
616
+ const indicator = resolved.indicator;
617
+ if (indicator) {
618
+ const indicatorUrl = `/@fs/` + resolveRuntimeModule('indicator');
619
+ tags.push({
620
+ tag: 'script',
621
+ attrs: { type: 'module', src: indicatorUrl },
622
+ injectTo: 'body',
623
+ }, {
624
+ tag: 'lit-devtools-hmr-indicator',
625
+ attrs: indicator.count ? { count: '' } : undefined,
626
+ children: '',
627
+ injectTo: 'body',
628
+ });
629
+ }
630
+ if (resolved.timeline) {
631
+ const installUrl = `/@fs/` + resolveRuntimeModule('timeline/install');
632
+ tags.push({
633
+ tag: 'script',
634
+ attrs: { type: 'module', src: installUrl },
635
+ injectTo: 'body',
636
+ });
637
+ // Components inspector runtime — answers the panel's tree/details
638
+ // requests. Paired with the timeline panel, which hosts its tab.
639
+ const inspectorUrl = `/@fs/` + resolveRuntimeModule('inspector/install');
640
+ tags.push({
641
+ tag: 'script',
642
+ attrs: { type: 'module', src: inspectorUrl },
643
+ injectTo: 'body',
644
+ });
645
+ }
646
+ return tags.length > 0 ? tags : undefined;
647
+ },
92
648
  };
649
+ // The source-overlay plugin is always present; its hooks no-op when the
650
+ // feature is disabled (which env may decide), so inclusion can't be gated
651
+ // on the synchronously-known options here.
652
+ const plugins = [
653
+ optionsPlugin,
654
+ // Getter, not a snapshot: `resolved` is re-resolved against the loaded env
655
+ // in `optionsPlugin`'s `config` hook, which runs after this array is built.
656
+ litCssQueries(() => resolved.cssSheetBuild),
657
+ litCssLiterals(),
658
+ sourceOverlayPlugin,
659
+ hmr,
660
+ ];
661
+ if (resolved.timeline) {
662
+ // Pass a getter, not a snapshot: `resolved` is re-resolved against the
663
+ // loaded env in the `config` hook, which runs after this plugin array is
664
+ // built. The settings endpoint reads it per-request, by which point env is
665
+ // applied.
666
+ plugins.push(litTimelinePlugin(() => toFeatureSettings(resolved)));
667
+ }
668
+ return plugins;
93
669
  };
94
670
  //# sourceMappingURL=plugin.js.map