@ttsc/unplugin 0.19.3 → 0.20.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.
@@ -0,0 +1,178 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathIdentityKey } from './transform.mjs';
4
+
5
+ /**
6
+ * How often each registered missing watch input is stat-polled, in
7
+ * milliseconds.
8
+ *
9
+ * Polling is the only watch primitive that covers the whole class: the dev
10
+ * server's chokidar watcher ignores every `node_modules` directory, which is
11
+ * exactly where superseding resolution candidates usually live, and `fs.watch`
12
+ * cannot observe a path whose parent directories do not exist yet. One `stat`
13
+ * every half second per missing path is negligible against a dev server's
14
+ * baseline.
15
+ */
16
+ const MISSING_INPUT_POLL_INTERVAL = 500;
17
+ /** Create an empty missing-input watch for one plugin instance. */
18
+ function createViteServeMissingInputWatch() {
19
+ const entries = new Map();
20
+ let server;
21
+ const unwatch = (identity, entry) => {
22
+ fs.unwatchFile(entry.spelling, entry.listener);
23
+ entries.delete(identity);
24
+ };
25
+ return {
26
+ attach(next) {
27
+ server = next;
28
+ },
29
+ dispose() {
30
+ for (const [identity, entry] of entries) {
31
+ unwatch(identity, entry);
32
+ }
33
+ // The server reference deliberately survives: `vite.restartServer`
34
+ // configures the replacement server (attach) before it closes the old
35
+ // one (whose buildEnd runs this dispose), so unsetting it here would
36
+ // detach the freshly attached replacement and revive the 500 this
37
+ // module exists to prevent. A same-instance `vite build` after a serve
38
+ // is instead excluded by the adapter's `config.command` gate.
39
+ },
40
+ serving() {
41
+ return server !== undefined;
42
+ },
43
+ watch(input, importer) {
44
+ const spelling = path.resolve(input);
45
+ const identity = pathIdentityKey(spelling);
46
+ const existing = entries.get(identity);
47
+ if (existing !== undefined) {
48
+ existing.importers.add(path.resolve(importer));
49
+ return;
50
+ }
51
+ const entry = {
52
+ importers: new Set([path.resolve(importer)]),
53
+ listener: (current) => {
54
+ // `fs.watchFile` reports a missing path as zeroed stats (and fires
55
+ // once with them right after registration); only a poll that
56
+ // observes a real file is a creation event.
57
+ if (current.mtimeMs === 0 && !fs.existsSync(entry.spelling)) {
58
+ return;
59
+ }
60
+ unwatch(identity, entry);
61
+ if (server === undefined) {
62
+ return;
63
+ }
64
+ invalidateImporters(server, entry.importers);
65
+ sendFullReload(server);
66
+ },
67
+ spelling,
68
+ };
69
+ entries.set(identity, entry);
70
+ const watcher = fs.watchFile(spelling, { interval: MISSING_INPUT_POLL_INTERVAL }, entry.listener);
71
+ // A poller must never keep the dev-server process alive on its own.
72
+ watcher.unref?.();
73
+ // `fs.watchFile` snapshots the path's stats at registration and fires
74
+ // only on a subsequent change, so a file created between the adapter's
75
+ // existence check and this registration would count as "unchanged" and
76
+ // never fire. One deferred recheck closes that window; routing through
77
+ // the listener keeps a single finalization path.
78
+ const recheck = setTimeout(() => {
79
+ if (entries.get(identity) !== entry) {
80
+ return;
81
+ }
82
+ try {
83
+ entry.listener(fs.statSync(entry.spelling));
84
+ }
85
+ catch {
86
+ // Still missing (or deleted again): the ordinary poll stays armed.
87
+ }
88
+ }, MISSING_INPUT_POLL_INTERVAL);
89
+ recheck.unref?.();
90
+ },
91
+ };
92
+ }
93
+ /**
94
+ * Invalidate every module-graph node of the registered importers so the next
95
+ * request retransforms them. Importers keep their original absolute spelling so
96
+ * the module graph's exact-key lookup can hit; graph lookups still go through
97
+ * {@link selectModulesByFile} because module-graph file keys are
98
+ * slash-normalized and, on case-insensitive filesystems, may not match the
99
+ * compiler's spelling byte for byte.
100
+ */
101
+ function invalidateImporters(server, importers) {
102
+ for (const graph of selectModuleGraphs(server)) {
103
+ for (const importer of importers) {
104
+ for (const node of selectModulesByFile(graph, importer)) {
105
+ try {
106
+ graph.invalidateModule?.(node);
107
+ }
108
+ catch {
109
+ // A graph shape this structural view mispredicts must not crash the
110
+ // poll; the full-reload below still forces a refetch, and the
111
+ // transform cache's external-input hashes force the recompile.
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
117
+ /**
118
+ * Enumerate the server's module graphs: one per environment under the
119
+ * environment API (Vite 6+), otherwise the mixed module graph (Vite 5).
120
+ */
121
+ function selectModuleGraphs(server) {
122
+ const graphs = [];
123
+ for (const environment of Object.values(server.environments ?? {})) {
124
+ if (environment?.moduleGraph !== undefined) {
125
+ graphs.push(environment.moduleGraph);
126
+ }
127
+ }
128
+ if (graphs.length === 0 && server.moduleGraph !== undefined) {
129
+ graphs.push(server.moduleGraph);
130
+ }
131
+ return graphs;
132
+ }
133
+ /**
134
+ * Look up the module nodes registered for one importer spelling: the fast
135
+ * slash-normalized `getModulesByFile` lookup first, then an identity scan of
136
+ * `fileToModulesMap` for spellings that differ only by separator or case.
137
+ */
138
+ function selectModulesByFile(graph, importer) {
139
+ const direct = graph.getModulesByFile?.(importer.replace(/\\/g, "/"));
140
+ if (direct !== undefined && direct.size !== 0) {
141
+ return [...direct];
142
+ }
143
+ const identity = pathIdentityKey(importer);
144
+ const output = [];
145
+ for (const [file, nodes] of graph.fileToModulesMap ?? []) {
146
+ if (typeof file === "string" && pathIdentityKey(file) === identity) {
147
+ output.push(...nodes);
148
+ }
149
+ }
150
+ return output;
151
+ }
152
+ /**
153
+ * Deliver one full-reload so connected clients refetch the invalidated
154
+ * importers. The channels differ across Vite majors (`ws`, deprecated `hot`,
155
+ * per-environment `hot`); the first one that accepts the payload wins.
156
+ */
157
+ function sendFullReload(server) {
158
+ for (const channel of [
159
+ server.ws,
160
+ server.hot,
161
+ server.environments?.client?.hot,
162
+ ]) {
163
+ if (channel?.send === undefined) {
164
+ continue;
165
+ }
166
+ try {
167
+ channel.send({ path: "*", type: "full-reload" });
168
+ return;
169
+ }
170
+ catch {
171
+ // Try the next channel; an unsupported payload on one major must not
172
+ // suppress delivery through another.
173
+ }
174
+ }
175
+ }
176
+
177
+ export { createViteServeMissingInputWatch };
178
+ //# sourceMappingURL=viteServe.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viteServe.mjs","sources":["../../src/core/viteServe.ts"],"sourcesContent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MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;QACvB;IACF;AACA,IAAA,OAAO,MAAM;AACf;AAEA;;;;AAIG;AACH,SAAS,cAAc,CAAC,MAAyB,EAAA;IAC/C,KAAK,MAAM,OAAO,IAAI;AACpB,QAAA,MAAM,CAAC,EAAE;AACT,QAAA,MAAM,CAAC,GAAG;AACV,QAAA,MAAM,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG;AACjC,KAAA,EAAE;AACD,QAAA,IAAI,OAAO,EAAE,IAAI,KAAK,SAAS,EAAE;YAC/B;QACF;AACA,QAAA,IAAI;AACF,YAAA,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;YAChD;QACF;AAAE,QAAA,MAAM;;;QAGR;IACF;AACF;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ttsc/unplugin",
3
- "version": "0.19.3",
3
+ "version": "0.20.1",
4
4
  "description": "Bundler adapters for ttsc plugins.",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.mjs",
@@ -95,7 +95,7 @@
95
95
  "unplugin": "^2.3.11"
96
96
  },
97
97
  "peerDependencies": {
98
- "ttsc": "0.19.3"
98
+ "ttsc": "^0.20.1"
99
99
  },
100
100
  "devDependencies": {
101
101
  "@rollup/plugin-commonjs": "^29.0.2",
@@ -108,7 +108,7 @@
108
108
  "tslib": "^2.8.1",
109
109
  "typescript": "^7.0.2",
110
110
  "vite": "^7.1.12",
111
- "ttsc": "0.19.3"
111
+ "ttsc": "0.20.1"
112
112
  },
113
113
  "repository": {
114
114
  "type": "git",
package/src/core/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import type { UnpluginFactory, UnpluginInstance } from "unplugin";
2
4
  import { createUnplugin } from "unplugin";
3
5
 
@@ -12,6 +14,7 @@ import {
12
14
  stripQuery,
13
15
  transformTtsc,
14
16
  } from "./transform";
17
+ import { createViteServeMissingInputWatch } from "./viteServe";
15
18
 
16
19
  const name = "ttsc-unplugin";
17
20
  /**
@@ -44,7 +47,9 @@ const unpluginFactory: UnpluginFactory<
44
47
  > = (rawOptions = {}) => {
45
48
  const options = resolveOptions(rawOptions);
46
49
  const transformCache = createTtscTransformCache();
50
+ const missingInputs = createViteServeMissingInputWatch();
47
51
  let aliases: unknown;
52
+ let viteCommand: string | undefined;
48
53
 
49
54
  return {
50
55
  name,
@@ -53,6 +58,25 @@ const unpluginFactory: UnpluginFactory<
53
58
  vite: {
54
59
  configResolved(config) {
55
60
  aliases = config.resolve.alias;
61
+ // Re-read per config resolution: a plugin instance reused across a
62
+ // serve and a later build must stop routing missing inputs to the
63
+ // serve-time poll, even though the closed server stays attached
64
+ // (see the dispose note in viteServe.ts).
65
+ viteCommand = config.command;
66
+ },
67
+ // Vite serve funnels every transform-context `addWatchFile()` into the
68
+ // module's added-import graph (`_addedImports`), which import-analysis
69
+ // resolves like real imports. Capture the dev server so the transform
70
+ // hook can route watch inputs that do not exist yet — superseding
71
+ // resolution candidates above all — around that graph and still
72
+ // invalidate their importers when the path is created.
73
+ configureServer(server) {
74
+ missingInputs.attach(server);
75
+ },
76
+ // Vite calls buildEnd when the dev server (or build) closes; drop every
77
+ // poller so a stopped server leaks no watch state.
78
+ buildEnd() {
79
+ missingInputs.dispose();
56
80
  },
57
81
  },
58
82
 
@@ -75,8 +99,23 @@ const unpluginFactory: UnpluginFactory<
75
99
  // unioned with the host-owned reference graph) so type-only inputs
76
100
  // invalidate this module in watch mode and persistent caches;
77
101
  // bundlers erase type-only imports from their own module graph and
78
- // would otherwise serve stale generated code.
79
- addWatchFile: (watched) => this.addWatchFile(watched),
102
+ // would otherwise serve stale generated code. Under Vite serve a
103
+ // missing input must not enter `addWatchFile`: import-analysis
104
+ // resolves added imports and 500s on a path that is absent by design
105
+ // (a superseding resolution candidate, a not-yet-generated
106
+ // dependency), so those are watched on the filesystem instead and
107
+ // invalidate this module when created.
108
+ addWatchFile: (watched) => {
109
+ if (
110
+ viteCommand === "serve" &&
111
+ missingInputs.serving() &&
112
+ !fs.existsSync(watched)
113
+ ) {
114
+ missingInputs.watch(watched, path.resolve(file));
115
+ return;
116
+ }
117
+ this.addWatchFile(watched);
118
+ },
80
119
  // A module the plugin declared volatile depends on non-file inputs,
81
120
  // which no file-dependency snapshot can represent; mark it
82
121
  // uncacheable where the bundler exposes that control.