unplugin-atscript 0.1.110 → 0.2.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/dist/webpack.cjs CHANGED
@@ -68,17 +68,228 @@ function isResolvableFrom(specifier, from) {
68
68
  return false;
69
69
  }
70
70
  }
71
- const unpluginFactory = (opts) => {
71
+ /** The modules of `files` in `graph`. */ function modulesOf(graph, files) {
72
+ const out = [];
73
+ for (const file of files) out.push(...graph.getModulesByFile(file) ?? []);
74
+ return out;
75
+ }
76
+ /**
77
+ * Hard-invalidates (drops the transform of) the modules of `files` in every module graph of
78
+ * `server`: Vite reuses an importer's transform when one of its imports changed (soft
79
+ * invalidation), and the next import re-runs `load` only for a module invalidated this way.
80
+ */ function invalidateFiles(server, files) {
81
+ const graphs = server.environments ? Object.values(server.environments).map((env) => env.moduleGraph) : [server.moduleGraph];
82
+ const timestamp = Date.now();
83
+ for (const graph of graphs) for (const mod of modulesOf(graph, files)) graph.invalidateModule(mod, /* @__PURE__ */ new Set(), timestamp, false, false);
84
+ }
85
+ /** The import statements of generated code (`codes`): what the module graph is made of. */ function importLines(codes) {
86
+ return [...codes].map((code) => code.split("\n").filter((line) => line.startsWith("import ")).join("\n")).join("\n---\n");
87
+ }
88
+ /** The diagnostics `load` logs for `doc` (errors and warnings), as a key (see `logged`). */ function loggedOf(doc) {
89
+ return doc.getDiagMessages().filter((m) => m.severity === 1 || m.severity === 2).map((m) => `${m.severity}:${m.message}`).join("\n");
90
+ }
91
+ /** Whether `doc` has mutating `annotate` blocks. */ function hasBlocks(doc) {
92
+ return !!doc && (0, _atscript_core.hasMutatingAnnotates)(doc);
93
+ }
94
+ /**
95
+ * The files of the modules declaring the types the mutating `annotate` blocks of `doc` annotate
96
+ * (other than its own) — through plain aliases (see `blockTargetDocuments`).
97
+ */ function annotatedModules(doc) {
98
+ const out = /* @__PURE__ */ new Set();
99
+ for (const target of doc ? (0, _atscript_core.blockTargetDocuments)(doc) : []) if (target.id.startsWith("file://")) out.add((0, _atscript_core.fileUriToPath)(target.id));
100
+ return out;
101
+ }
102
+ const unpluginFactory = (opts, meta) => {
72
103
  const explicitRoot = opts?.root ? path.default.resolve(opts.root) : void 0;
73
104
  let detectedRoot;
105
+ /**
106
+ * A one-shot build (Vite's `build` command without `--watch`; Rollup / Rolldown not watching):
107
+ * its renders check the generated modules' loads (`loadCheck`). `undefined` until the bundler
108
+ * says, and for the bundlers that do not.
109
+ */ let building;
110
+ const detects = [
111
+ "vite",
112
+ "rollup",
113
+ "rolldown"
114
+ ].includes(meta?.framework ?? "");
74
115
  const getRoot = () => explicitRoot ?? detectedRoot ?? process.cwd();
75
116
  const strict = opts?.strict ?? true;
76
117
  let repo;
77
118
  let configPromise;
119
+ /** The documents of the `.as` modules loaded, by file. */ const loaded = /* @__PURE__ */ new Map();
120
+ /**
121
+ * What `load` returned for each `.as` module (by file), by render format: its generated code,
122
+ * or the error it threw (see `outcome`).
123
+ */ const served = /* @__PURE__ */ new Map();
124
+ /**
125
+ * The diagnostics each served module's `load` logged (errors and warnings): a module whose
126
+ * diagnostics change (derived from other documents) is loaded again to log them — also when
127
+ * its generated code (or the error it throws: the first one) stays the same (see `loggedOf`).
128
+ */ const logged = /* @__PURE__ */ new Map();
129
+ /**
130
+ * The `.as` modules (by file) importing each `.as` file (by file), as their import specifiers
131
+ * name it — also when it does not exist (a deleted file, one not created yet).
132
+ */ const importers = /* @__PURE__ */ new Map();
133
+ /** The `.as` files each loaded `.as` module imports (see `importers`). */ const importsOf = /* @__PURE__ */ new Map();
134
+ /**
135
+ * The other `.as` modules whose generated code changed with a changed `.as` file (by file,
136
+ * see `watchChange`), for the hot update that follows.
137
+ */ const affected = /* @__PURE__ */ new Map();
138
+ /** The changed `.as` files whose hot update is a full page reload. */ const reload = /* @__PURE__ */ new Set();
139
+ /** The Vite dev server (Vite only). */ let viteServer;
78
140
  const getConfig = () => configPromise ?? (configPromise = (async () => {
79
141
  const p = await (0, _atscript_core.resolveConfigFile)(getRoot());
80
142
  return p ? (0, _atscript_core.loadConfig)(p) : {};
81
143
  })());
144
+ /** Records the `.as` files `doc` (loaded from `file`) imports (see `importers`). */ const recordImports = (file, doc) => {
145
+ for (const imported of importsOf.get(file) ?? []) importers.get(imported)?.delete(file);
146
+ const files = /* @__PURE__ */ new Set();
147
+ for (const id of doc.imports.keys()) if (id.startsWith("file://")) files.add((0, _atscript_core.fileUriToPath)(id));
148
+ for (const imported of files) {
149
+ let set = importers.get(imported);
150
+ if (!set) {
151
+ set = /* @__PURE__ */ new Set();
152
+ importers.set(imported, set);
153
+ }
154
+ set.add(file);
155
+ }
156
+ importsOf.set(file, files);
157
+ };
158
+ /**
159
+ * What `load` returns for `doc` in render `format`: its generated code, or (`error:`) the
160
+ * first error it throws in strict mode. Logs the diagnostics when `report`.
161
+ */ const outcome = async (doc, format, report) => {
162
+ let error = "";
163
+ for (const m of [...doc.getDiagMessages()].reverse()) if (m.severity === 1) {
164
+ if (report) console.log(doc.renderDiagMessage(m, true, true));
165
+ if (strict && !error) error = m.message;
166
+ } else if (m.severity === 2 && report) console.log(doc.renderDiagMessage(m, false, true));
167
+ if (error) return {
168
+ error,
169
+ code: `error:${error}`
170
+ };
171
+ const options = { loadCheck: opts?.loadCheck ?? building };
172
+ let out = await doc.render(format, options);
173
+ if (!out?.[0]?.content && (format === _atscript_typescript.JS_COMPILED_FORMAT || format === _atscript_typescript.JS_INTERPRETED_FORMAT)) out = await doc.render("js", options);
174
+ return { code: out?.[0]?.content || "" };
175
+ };
176
+ /** The repo's document of `uri` as it is now (`undefined`: it does not open). */ const currentDoc = async (uri) => {
177
+ try {
178
+ const doc = await repo.openDocument(uri);
179
+ await repo.checkImports(doc);
180
+ return doc;
181
+ } catch {
182
+ return;
183
+ }
184
+ };
185
+ /**
186
+ * The `.as` modules (by file) importing `id`'s, directly or not, also through an import of it
187
+ * that did not resolve: evaluated again with it in a hot update.
188
+ */ const dependantsOf = (id) => {
189
+ const files = /* @__PURE__ */ new Set();
190
+ const add = (doc) => {
191
+ for (const d of doc?.transitive("dependants") ?? []) files.add((0, _atscript_core.fileUriToPath)(d.id));
192
+ };
193
+ add(loaded.get(id));
194
+ for (const file of importers.get(id) ?? []) {
195
+ files.add(file);
196
+ add(loaded.get(file));
197
+ }
198
+ files.delete(id);
199
+ return files;
200
+ };
201
+ const candidatesOf = (id) => {
202
+ const files = dependantsOf(id);
203
+ const uri = `file://${id}`;
204
+ for (const [file, ids] of reads) if (ids.has(uri)) files.add(file);
205
+ files.delete(id);
206
+ return files;
207
+ };
208
+ /**
209
+ * The documents (by id) each loaded `.as` module's `load` result was derived from: those its
210
+ * resolutions read (see `recordDocumentReads`) and those it imports.
211
+ */ const reads = /* @__PURE__ */ new Map();
212
+ /** Records `read` (and the documents `doc` imports) as what `file`'s `load` result read. */ const recordReads = (file, doc, read, merge) => {
213
+ const ids = merge ? reads.get(file) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();
214
+ for (const d of read) ids.add(d.id);
215
+ for (const id of doc.imports.keys()) ids.add(id);
216
+ reads.set(file, ids);
217
+ };
218
+ /**
219
+ * `candidates` (files) whose `load` result changes with document `uri` changed to `text`:
220
+ * the document is updated in place (its importers keep referring to it), and the candidates
221
+ * whose last `load` read it (see `reads`) are rendered again in every format they were loaded
222
+ * in — all of them when its generated imports changed (the import cycles they are in may
223
+ * change), or when a candidate rendered again has new imports. Its importers are parsed
224
+ * and checked again first (their diagnostics are those of its imports as they are now), from
225
+ * the repo's documents (from disk when the repo dropped one: deleted, created again) — never
226
+ * from a closed document; the checks share what they checked (each document's imports once).
227
+ */ const changedModules = async (uri, text, candidates) => {
228
+ const changedFile = (0, _atscript_core.fileUriToPath)(uri);
229
+ const before = served.get(changedFile);
230
+ const beforeImports = before ? importLines(before.values()) : void 0;
231
+ const checked = /* @__PURE__ */ new Set();
232
+ const changedDoc = await repo.openDocument(uri, text);
233
+ await repo.checkImports(changedDoc, checked);
234
+ let all = beforeImports === void 0;
235
+ if (!all) {
236
+ const after = [];
237
+ for (const format of before.keys()) after.push((await outcome(changedDoc, format, false)).code);
238
+ all = importLines(after) !== beforeImports;
239
+ }
240
+ const importing = importers.get(changedFile) ?? /* @__PURE__ */ new Set();
241
+ const changed = /* @__PURE__ */ new Set();
242
+ const docs = /* @__PURE__ */ new Map();
243
+ for (const file of candidates) if (!loaded.has(file) || !served.has(file)) changed.add(file);
244
+ else if (importing.has(file)) try {
245
+ const id = loaded.get(file).id;
246
+ const current = await repo.openDocument(id);
247
+ current.clearMessages();
248
+ docs.set(file, current);
249
+ } catch {
250
+ changed.add(file);
251
+ }
252
+ for (const doc of docs.values()) {
253
+ checked.delete(doc.id);
254
+ await repo.checkImports(doc, checked);
255
+ }
256
+ const rendered = /* @__PURE__ */ new Set();
257
+ const render = async (file) => {
258
+ rendered.add(file);
259
+ const doc = docs.get(file) ?? loaded.get(file);
260
+ if (!docs.has(file)) doc.clearMessages();
261
+ loaded.set(file, doc);
262
+ const formats = served.get(file);
263
+ const recording = (0, _atscript_core.recordDocumentReads)();
264
+ const codes = [];
265
+ try {
266
+ for (const format of formats.keys()) codes.push((await outcome(doc, format, false)).code);
267
+ } finally {
268
+ recordReads(file, doc, recording.stop(), false);
269
+ }
270
+ if (codes.some((code, i) => code !== [...formats.values()][i]) || loggedOf(doc) !== logged.get(file)) {
271
+ changed.add(file);
272
+ if (!all && importLines(codes) !== importLines(formats.values())) all = true;
273
+ }
274
+ };
275
+ const pending = () => [...candidates].filter((file) => !rendered.has(file) && !changed.has(file) && (all || importing.has(file) || !reads.has(file) || reads.get(file).has(uri)));
276
+ for (let queue = pending(); queue.length > 0; queue = pending()) for (const file of queue) await render(file);
277
+ for (const file of staleWarnings(new Set([...rendered, ...changed]))) changed.add(file);
278
+ return changed;
279
+ };
280
+ /**
281
+ * The served modules (but `skip`) whose mutating blocks annotate another module's type and
282
+ * whose diagnostics changed: the warning of a block not reachable from the files using the type
283
+ * derives from documents they need not import (those files, see `blockDependencies`), so it is
284
+ * computed again.
285
+ */ const staleWarnings = (skip) => {
286
+ const out = [];
287
+ for (const [file, doc] of loaded) if (!skip.has(file) && served.has(file) && annotatedModules(doc).size > 0) {
288
+ doc.clearMessages();
289
+ if (loggedOf(doc) !== logged.get(file)) out.push(file);
290
+ }
291
+ return out;
292
+ };
82
293
  return {
83
294
  name: "unplugin-atscript",
84
295
  vite: {
@@ -89,6 +300,26 @@ const unpluginFactory = (opts) => {
89
300
  },
90
301
  configResolved(config) {
91
302
  detectedRoot = config.root;
303
+ building = config.command === "build" && !config.build?.watch;
304
+ },
305
+ configureServer(server) {
306
+ viteServer = server;
307
+ },
308
+ hotUpdate(options) {
309
+ if (reload.has(options.file)) {
310
+ this.environment.hot?.send({ type: "full-reload" });
311
+ return [];
312
+ }
313
+ const files = affected.get(options.file);
314
+ return files && files.size > 0 ? [...new Set([...options.modules, ...modulesOf(this.environment.moduleGraph, files)])] : void 0;
315
+ },
316
+ handleHotUpdate(ctx) {
317
+ if (!ctx.server.environments && reload.has(ctx.file)) {
318
+ ctx.server.ws?.send({ type: "full-reload" });
319
+ return [];
320
+ }
321
+ const files = affected.get(ctx.file);
322
+ return ctx.server.environments || !files || files.size === 0 ? void 0 : [...new Set([...ctx.modules, ...modulesOf(ctx.server.moduleGraph, files)])];
92
323
  }
93
324
  },
94
325
  resolveId(id, importer) {
@@ -99,6 +330,9 @@ const unpluginFactory = (opts) => {
99
330
  return resolved;
100
331
  }
101
332
  },
333
+ buildStart() {
334
+ if (detects) building ?? (building = this.meta?.watchMode === false);
335
+ },
102
336
  async load(id, options) {
103
337
  const isDts = id.endsWith(".as.d.ts");
104
338
  const sourceId = isDts ? id.slice(0, -5) : id;
@@ -109,36 +343,83 @@ const unpluginFactory = (opts) => {
109
343
  repo = new _atscript_core.AtscriptRepo(getRoot(), config);
110
344
  }
111
345
  const code = (await (0, fs_promises.readFile)(sourceId, "utf8")).toString();
112
- const doc = await repo.openDocument(`file://${sourceId}`, code);
113
- await repo.checkDoc(doc);
346
+ const recording = isDts ? void 0 : (0, _atscript_core.recordDocumentReads)();
347
+ let doc;
348
+ let result;
349
+ let format = "js";
350
+ try {
351
+ doc = await repo.openDocument(`file://${sourceId}`, code);
352
+ await repo.checkDoc(doc);
353
+ if (!isDts) {
354
+ const compile = opts?.compileValidators;
355
+ format = compile === void 0 ? "js" : compile === true || compile === "ssr" && isServerLoad(this, options) ? _atscript_typescript.JS_COMPILED_FORMAT : _atscript_typescript.JS_INTERPRETED_FORMAT;
356
+ result = await outcome(doc, format, true);
357
+ }
358
+ } finally {
359
+ const read = recording?.stop();
360
+ if (read && doc) recordReads(sourceId, doc, read, served.has(sourceId));
361
+ }
114
362
  addTransitiveWatchFiles(this, doc);
115
- const messages = doc.getDiagMessages().reverse();
116
- let error = "";
117
- for (const m of messages) if (m.severity === 1) {
118
- console.log(doc.renderDiagMessage(m, true, true));
119
- if (strict && !error) error = m.message;
120
- } else if (m.severity === 2) console.log(doc.renderDiagMessage(m, false, true));
121
- if (error) throw new Error(error);
122
- if (isDts) return {
123
- code: ((await doc.render("dts"))?.[0]?.content || "").replace(/^\/{3}\s*<reference\s+path=[^\n]*\n/m, ""),
124
- map: null
125
- };
126
- const compile = opts?.compileValidators;
127
- const format = compile === void 0 ? "js" : compile === true || compile === "ssr" && isServerLoad(this, options) ? _atscript_typescript.JS_COMPILED_FORMAT : _atscript_typescript.JS_INTERPRETED_FORMAT;
128
- let out = await doc.render(format);
129
- if (!out?.[0]?.content && format !== "js") out = await doc.render("js");
130
- const hasMutatingAnnotates = doc.nodes.some((n) => (0, _atscript_core.isAnnotate)(n) && n.isMutating);
363
+ if (isDts) {
364
+ const { error, code: content } = await outcome(doc, "dts", true);
365
+ if (error) throw new Error(error);
366
+ return {
367
+ code: content.replace(/^\/{3}\s*<reference\s+path=[^\n]*\n/m, ""),
368
+ map: null
369
+ };
370
+ }
371
+ loaded.set(sourceId, doc);
372
+ recordImports(sourceId, doc);
373
+ let formats = served.get(sourceId);
374
+ if (!formats) {
375
+ formats = /* @__PURE__ */ new Map();
376
+ served.set(sourceId, formats);
377
+ }
378
+ formats.set(format, result.code);
379
+ logged.set(sourceId, loggedOf(doc));
380
+ if (result.error) throw new Error(result.error);
381
+ const sideEffects = hasBlocks(doc) || (0, _atscript_typescript.importCycle)(doc);
131
382
  return {
132
- code: out?.[0]?.content || "",
383
+ code: result.code,
133
384
  moduleType: "js",
134
385
  map: null,
135
- moduleSideEffects: hasMutatingAnnotates ? void 0 : false
386
+ moduleSideEffects: sideEffects ? void 0 : false
136
387
  };
137
388
  }
138
389
  },
139
- watchChange(id) {
390
+ async watchChange(id, change) {
140
391
  if (!repo || !id.endsWith(".as")) return;
141
- repo.closeDocument(`file://${id}`);
392
+ const uri = `file://${id}`;
393
+ const candidates = candidatesOf(id);
394
+ const evaluated = new Set([id, ...dependantsOf(id)]);
395
+ const blocksOutside = () => [...evaluated].some((f) => [...annotatedModules(loaded.get(f))].some((t) => !evaluated.has(t)));
396
+ const blocksBefore = hasBlocks(loaded.get(id)) || blocksOutside();
397
+ const text = viteServer && change?.event === "update" ? await (0, fs_promises.readFile)(id, "utf8").catch(() => void 0) : void 0;
398
+ let files = candidates;
399
+ if (text === void 0) {
400
+ repo.closeDocument(uri);
401
+ files = new Set([...candidates, id]);
402
+ if (change?.event === "create") try {
403
+ await repo.checkImports(await repo.openDocument(uri), /* @__PURE__ */ new Set());
404
+ } catch {
405
+ repo.closeDocument(uri);
406
+ }
407
+ for (const file of staleWarnings(files)) files.add(file);
408
+ } else try {
409
+ files = await changedModules(uri, text, candidates);
410
+ } catch {
411
+ repo.closeDocument(uri);
412
+ }
413
+ if (blocksBefore || hasBlocks(await currentDoc(uri)) || blocksOutside()) {
414
+ files = new Set([
415
+ ...files,
416
+ ...served.keys(),
417
+ id
418
+ ]);
419
+ reload.add(id);
420
+ } else reload.delete(id);
421
+ affected.set(id, files);
422
+ if (viteServer && files.size > 0) invalidateFiles(viteServer, files);
142
423
  }
143
424
  };
144
425
  };
package/dist/webpack.d.ts CHANGED
@@ -21,14 +21,28 @@ interface atscriptPluginOptions {
21
21
  /**
22
22
  * Overrides `tsPlugin({ compileValidators })` of the atscript config for the modules
23
23
  * this plugin renders:
24
- * - `true` / `false` — always / never emit build-time compiled validator checks.
25
- * - `'ssr'` — only for server builds: Vite's SSR / server environments get compiled
26
- * checks, client bundles stay lean (one Vite config for both). Bundlers that do not
27
- * report a server build (everything but Vite) get none.
24
+ * - `true` — compiled validator checks for every type.
25
+ * - `false` — none, not even for types annotated with `@emit.compiledValidator`
26
+ * (forced interpreted output, e.g. for bundles shipped to browsers).
27
+ * - `'ssr'` — `true` for server builds (Vite's SSR / server environments), `false` for
28
+ * client bundles (one Vite config for both). Bundlers that do not report a server build
29
+ * (everything but Vite) are treated as client builds.
28
30
  *
29
- * Unset: the atscript config decides (default: off).
31
+ * Unset: the atscript config decides (default: only `@emit.compiledValidator` types).
30
32
  */
31
33
  compileValidators?: boolean | 'ssr';
34
+ /**
35
+ * The build's load check: a production build loads every generated module (each import cycle
36
+ * from each of its modules) and fails when one does not load — an internal code generation
37
+ * error, never a half-built module at runtime.
38
+ * - `true` — checked in every build of this plugin (also in watch mode and on the dev server).
39
+ * - `false` — never checked.
40
+ *
41
+ * Unset: checked in one-shot Vite, Rollup and Rolldown builds; not in watch builds
42
+ * (`vite build --watch`, `rollup -w`, `rolldown --watch`), on the dev server or in HMR; not in
43
+ * other bundlers (esbuild, webpack, Rspack, Farm: they do not tell a build from a watch).
44
+ */
45
+ loadCheck?: boolean;
32
46
  }
33
47
 
34
48
  declare const _default: (options?: atscriptPluginOptions | undefined) => WebpackPluginInstance;