@drawcall/cache 0.0.0-stage → 0.8.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.
package/dist/vite.js ADDED
@@ -0,0 +1,441 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { appendFile, readdir, readFile, rm } from 'node:fs/promises';
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import { isAbsolute, join, relative, resolve } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import MagicString from 'magic-string';
7
+ import colors from 'picocolors';
8
+ import picomatch from 'picomatch';
9
+ import { glob } from 'tinyglobby';
10
+ import { createServer, normalizePath } from 'vite';
11
+ import { createNodeImportMeta, ESModulesEvaluator, ModuleRunner } from 'vite/module-runner';
12
+ import { cacheName, missing, read } from './disk.js';
13
+ import { discover } from './discover.js';
14
+ import { current, record } from './inputs.js';
15
+ /** Adds the cache directory to the project's .gitignore, since its entries are generated. */
16
+ async function ignore(root, directory) {
17
+ const line = `${relative(root, directory).split('\\').join('/')}/*`;
18
+ const file = join(root, '.gitignore');
19
+ const contents = new TextDecoder().decode(await read(file));
20
+ if (contents.split(/\r?\n/).includes(line))
21
+ return;
22
+ await appendFile(file, `${contents && !contents.endsWith('\n') ? '\n' : ''}${line}\n`);
23
+ }
24
+ function stack(error) {
25
+ return error instanceof Error ? (error.stack ?? error.message) : String(error);
26
+ }
27
+ const hash = (text) => createHash('sha256').update(text).digest('hex');
28
+ /**
29
+ * Wraps each of the loads' inline functions in a tag of its identity, the hash of its importer and source, which keys
30
+ * count it as.
31
+ */
32
+ function tag(code, loads, root) {
33
+ const importer = (load) => normalizePath(relative(root, load.importer));
34
+ for (const load of loads) {
35
+ for (const { start, end } of load.functions) {
36
+ const id = hash(`${importer(load)}\n${code.original.slice(start, end)}`);
37
+ code.prependRight(start, 'Object.defineProperty(');
38
+ code.appendLeft(end, `, Symbol.for("@drawcall/cache.function"), { value: ${JSON.stringify(id)} })`);
39
+ }
40
+ }
41
+ }
42
+ /** The input a module's file counts as: an installed package's module as its package.json, which covers its imports. */
43
+ function moduleInput(file) {
44
+ const installed = /^(.*\/node_modules\/(?:@[^/]+\/)?[^/]+)\//.exec(file)?.[1];
45
+ return installed ? `${installed}/package.json` : file;
46
+ }
47
+ /** The file a module runner's fetch answered with, or undefined for a built-in or a module cached in the runner. */
48
+ function fetchedFile(result) {
49
+ if (typeof result !== 'object' || result === null)
50
+ return undefined;
51
+ if ('file' in result && typeof result.file === 'string')
52
+ return result.file;
53
+ if ('externalize' in result && typeof result.externalize === 'string' && result.externalize.startsWith('file:'))
54
+ return fileURLToPath(result.externalize);
55
+ return undefined;
56
+ }
57
+ /**
58
+ * The inputs of the modules reachable from `ids` in a module runner's graph of what it evaluated, which holds each
59
+ * import as it ran, dynamic ones included. An installed package's imports are left out, since its package.json covers
60
+ * them.
61
+ */
62
+ function reachable(modules, ids) {
63
+ const inputs = new Set();
64
+ const seen = new Set();
65
+ const pending = [...ids];
66
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
67
+ const module = modules.getModuleById(id);
68
+ if (!module || seen.has(id))
69
+ continue;
70
+ seen.add(id);
71
+ // Built-in modules have no file, and virtual ones no absolute one, but a virtual module's imports still count.
72
+ if (!isAbsolute(module.file)) {
73
+ pending.push(...module.imports);
74
+ continue;
75
+ }
76
+ const input = moduleInput(module.file);
77
+ inputs.add(input);
78
+ if (input === module.file)
79
+ pending.push(...module.imports);
80
+ }
81
+ return [...inputs];
82
+ }
83
+ /** The query of the module that exports a load's arguments, whose value is the load's position in its importer. */
84
+ const query = '?drawcall-cache-load=';
85
+ /** The extensions of the JavaScript and TypeScript modules discovery scans, as Tailwind scans for class names. */
86
+ const extensions = 'js,jsx,ts,tsx,mjs,mts';
87
+ /** The path of `file` relative to `directory`, undefined for a file outside it. Both are normalized. */
88
+ function below(directory, file) {
89
+ return file.startsWith(`${directory}/`) ? file.slice(directory.length + 1) : undefined;
90
+ }
91
+ /** Marks the server the plugin warms with in a build, which loads the config, and so the plugin, again. */
92
+ const warmServerMarker = '@drawcall/cache:warm';
93
+ /**
94
+ * Finds cached loader loads in the project's source files, and in publicDir's `.glts` scripts and every JavaScript and
95
+ * TypeScript module there, and warms them in Node, so that browsers read what Node saved, then deletes the entries no
96
+ * load uses. In development it scans and warms at startup and again after every file change, and holds a request for an
97
+ * entry whose inputs changed, or that does not exist, until warming finishes. A build scans and warms once.
98
+ */
99
+ export function cache() {
100
+ /** Each scanned file with loads, and its loads. */
101
+ const files = new Map();
102
+ let config;
103
+ const loaded = new Set();
104
+ let directory;
105
+ /** Runs loaders: the dev server itself, or in a build a server started for that, once, by the first load. */
106
+ let server;
107
+ /**
108
+ * The plugin's own module runner on the server, whose graph records what each load ran. Not the environment's
109
+ * runner, whose graph a full reload after a change clears while a load runs. And it asks the environment directly,
110
+ * not over the hot channel, whose close removes the listener of its answers while closeBundle waits for the loads.
111
+ */
112
+ let runner;
113
+ /** The inputs of the modules the runner fetched, each as it was just after Vite answered the fetch. */
114
+ let fetched = new Map();
115
+ /** What the load being warmed uses, shared with CacheEntry through the global. */
116
+ let warming;
117
+ let queue = Promise.resolve();
118
+ /** Whether a pass is queued but has not started, which the next change then need not queue again. */
119
+ let queued = false;
120
+ /** Whether a load of the latest pass failed, which leaves the entries in place. */
121
+ let failed = false;
122
+ /** Set once the dev server closes, after which a running pass stops and nothing is pruned. */
123
+ let closing = false;
124
+ /** The directories discovery scans, with patterns relative to each: the root, and publicDir. */
125
+ let trees;
126
+ /** Records a file's loads. Development logs failures, since a file being edited can fail to parse. */
127
+ async function scan(file) {
128
+ try {
129
+ const code = new TextDecoder().decode(await read(file));
130
+ if (!/Cached\w*Loader/.test(code))
131
+ return void files.delete(file);
132
+ const loads = discover(code, file);
133
+ // Browsers run public scripts as they are, so nothing tags their functions.
134
+ const inline = below(config.publicDir, file) === undefined ? undefined : loads.find((load) => load.functions[0]);
135
+ if (inline)
136
+ throw new Error(`Public scripts cannot pass inline functions to loads, at ${file}:${inline.position}`);
137
+ files.set(file, { code, loads });
138
+ }
139
+ catch (error) {
140
+ if (config.command === 'build')
141
+ throw error;
142
+ log(`${colors.red('cannot scan')} ${error instanceof Error ? error.message : String(error)}`, 'error');
143
+ }
144
+ }
145
+ /** Whether discovery scans `file`. */
146
+ function scanned(file) {
147
+ return trees.some(({ root, matches }) => {
148
+ const path = below(root, file);
149
+ return path !== undefined && matches(path);
150
+ });
151
+ }
152
+ /**
153
+ * Serves each load's arguments as a module of its importer, so that its inline functions import as they do there, and
154
+ * tags inline functions in the app's modules alike. The server a build warms with gets these hooks too.
155
+ */
156
+ const tagging = {
157
+ name: '@drawcall/cache:tagging',
158
+ enforce: 'pre',
159
+ resolveId(id) {
160
+ return id.includes(query) ? id : undefined;
161
+ },
162
+ // Vite invalidates the module when its importer changes, since it shares its file.
163
+ load(id) {
164
+ const [importer = '', position] = id.split(query);
165
+ const file = files.get(importer);
166
+ const load = file?.loads.find((load) => load.position === position);
167
+ if (!file || !load)
168
+ return undefined;
169
+ const code = new MagicString(file.code);
170
+ tag(code, [load], config.root);
171
+ return `export default [${load.args.map(({ start, end }) => code.slice(start, end)).join(', ')}];`;
172
+ },
173
+ async transform(code, id) {
174
+ if (id.includes('?') || !scanned(id) || !/Cached\w*Loader/.test(code))
175
+ return;
176
+ let loads;
177
+ try {
178
+ loads = discover(code, id);
179
+ }
180
+ catch {
181
+ // The scan reports it.
182
+ return;
183
+ }
184
+ if (!loads.some((load) => load.functions.length))
185
+ return;
186
+ // Warming hashes functions as the file holds them, which a plugin transforming before this one would change. Read
187
+ // as Vite reads it, keeping a byte order mark.
188
+ if (code !== (await readFile(id, 'utf8')))
189
+ throw new Error(`cache must come before plugins that transform ${id}`);
190
+ const tagged = new MagicString(code);
191
+ tag(tagged, loads, config.root);
192
+ return { code: tagged.toString(), map: tagged.generateMap({ hires: 'boundary', source: id }) };
193
+ },
194
+ };
195
+ async function run({ importer, source, name, position }) {
196
+ server ??= createServer({
197
+ configFile: config.configFile ?? false,
198
+ root: config.root,
199
+ mode: config.mode,
200
+ logLevel: 'warn',
201
+ server: { middlewareMode: true, hmr: false, ws: false, watch: null },
202
+ plugins: [{ name: warmServerMarker }, tagging],
203
+ });
204
+ const environment = (await server).environments.ssr;
205
+ runner ??= new ModuleRunner({
206
+ transport: {
207
+ async invoke(payload) {
208
+ const answer = await environment.hot.handleInvoke(payload);
209
+ const file = 'result' in answer ? fetchedFile(answer.result) : undefined;
210
+ if (!file)
211
+ return answer;
212
+ const input = moduleInput(file);
213
+ // Before the runner evaluates the module, which may change the file. Vite read it a little earlier, and a
214
+ // write in between goes unseen.
215
+ const [state] = await record(config.root, [{ path: pathToFileURL(input).href }]);
216
+ if (state)
217
+ fetched.set(input, state);
218
+ return answer;
219
+ },
220
+ },
221
+ createImportMeta: createNodeImportMeta,
222
+ hmr: false,
223
+ sourcemapInterceptor: false,
224
+ }, new ESModulesEvaluator());
225
+ const { evaluatedModules } = runner;
226
+ const resolved = await environment.pluginContainer.resolveId(source, importer);
227
+ if (!resolved)
228
+ throw new Error(`cache cannot resolve ${source} from ${importer}`);
229
+ const module = await runner.import(resolved.id);
230
+ const exported = module[name];
231
+ if (typeof exported !== 'function')
232
+ throw new Error(`${source} does not export a class ${name}`);
233
+ const instance = Reflect.construct(exported, []);
234
+ const loadable = typeof instance === 'object' && instance !== null && 'loadAsync' in instance;
235
+ if (!loadable || typeof instance.loadAsync !== 'function')
236
+ throw new Error(`${name} has no loadAsync method`);
237
+ const path = below(config.publicDir, importer);
238
+ if (path !== undefined) {
239
+ // A browser resolves a public file's relative URLs against its served URL, and a loader against its path. The
240
+ // path leaves out Vite's base, so that keys do not depend on where the app is deployed.
241
+ if (!('setPath' in instance) || typeof instance.setPath !== 'function')
242
+ throw new Error(`${name} has no setPath method, which a load in a public file needs`);
243
+ // Encoded by the URL parser, as a browser requests it; it would read these as delimiters or escapes.
244
+ const folder = path.slice(0, path.lastIndexOf('/') + 1).replace(/[%#?\\]/g, encodeURIComponent);
245
+ instance.setPath(new URL(`/${folder}`, 'http://host').pathname);
246
+ }
247
+ const argumentsId = `${importer}${query}${position}`;
248
+ const { default: args } = await runner.import(argumentsId);
249
+ if (!Array.isArray(args))
250
+ throw new Error(`cache cannot load the arguments of ${name}`);
251
+ // What the loader's module and the arguments' functions import, not the importer the arguments module shares.
252
+ const modules = () => {
253
+ const ids = [resolved.id, ...(evaluatedModules.getModuleById(argumentsId)?.imports ?? [])];
254
+ return reachable(evaluatedModules, ids).map((input) => {
255
+ const state = fetched.get(input);
256
+ if (!state)
257
+ throw new Error(`cache did not see the runner fetch ${input}`);
258
+ return state;
259
+ });
260
+ };
261
+ const { loadAsync } = instance;
262
+ await warming.run({ files: [], modules }, () => loadAsync.apply(instance, args));
263
+ }
264
+ /** Logs as Vite does with a timestamp, but tagged [cache], since Vite's own timestamp option tags lines [vite]. */
265
+ function log(message, level = 'info') {
266
+ const tag = colors.bold(level === 'info' ? colors.cyan('[cache]') : colors.red('[cache]'));
267
+ config.logger[level](`${colors.dim(new Date().toLocaleTimeString())} ${tag} ${message}`);
268
+ }
269
+ /**
270
+ * Runs every load once, all at once, so that one waiting on the GPU or a worker leaves the others to run, then,
271
+ * unless a load failed, deletes the entries none of them loaded. A pass still running after half a second is
272
+ * announced, and so is its end.
273
+ */
274
+ async function pass() {
275
+ queued = false;
276
+ failed = false;
277
+ loaded.clear();
278
+ if (closing)
279
+ return;
280
+ const loads = [...files.values()].flatMap((file) => file.loads);
281
+ const started = performance.now();
282
+ let slow = false;
283
+ const timer = setTimeout(() => {
284
+ slow = true;
285
+ log(`${colors.yellow('computing')} ${loads.length} loads…`);
286
+ }, 500);
287
+ await Promise.all(loads.map(async (load) => {
288
+ try {
289
+ await run(load);
290
+ }
291
+ catch (error) {
292
+ failed = true;
293
+ const file = normalizePath(relative(config.root, load.importer));
294
+ log(`${colors.red('failed')} ${load.name} ${colors.dim(`${file}:${load.position}`)}\n${stack(error)}`, 'error');
295
+ }
296
+ }));
297
+ clearTimeout(timer);
298
+ if (slow)
299
+ log(`warmed in ${((performance.now() - started) / 1000).toFixed(1)} s`);
300
+ // Another plugin in this process may have replaced the global since, as a restarted dev server does.
301
+ if (failed || closing || globalThis.drawcallCache?.loaded !== loaded)
302
+ return;
303
+ try {
304
+ await prune();
305
+ }
306
+ catch (error) {
307
+ if (config.command === 'build')
308
+ throw error;
309
+ log(`${colors.red('cannot prune')} ${stack(error)}`, 'error');
310
+ }
311
+ }
312
+ /** Queues a pass unless one is already waiting. */
313
+ function warm() {
314
+ if (!queued) {
315
+ queued = true;
316
+ queue = queue.then(pass);
317
+ }
318
+ return idle();
319
+ }
320
+ async function idle() {
321
+ let current;
322
+ do {
323
+ current = queue;
324
+ await current;
325
+ } while (current !== queue);
326
+ }
327
+ /** Deletes the entries whose keys are not in `loaded`. */
328
+ async function prune() {
329
+ const names = await readdir(directory).catch((error) => {
330
+ if (missing(error))
331
+ return [];
332
+ throw error;
333
+ });
334
+ for (const name of names) {
335
+ const key = /^([a-f0-9]{64})\.(?:bin|json)$/.exec(name)?.[1];
336
+ if (key && !loaded.has(key))
337
+ await rm(join(directory, name), { force: true });
338
+ }
339
+ }
340
+ async function scanAll() {
341
+ for (const { root, pattern, excluded } of trees)
342
+ for (const file of await glob(pattern, { cwd: root, absolute: true, ignore: excluded }))
343
+ await scan(file);
344
+ }
345
+ // The warm server's copy of the plugin stays out, since this one warms, and gives it `tagging`.
346
+ const apply = (config) => !config.plugins?.some((plugin) => plugin && 'name' in plugin && plugin.name === warmServerMarker);
347
+ return [
348
+ { ...tagging, apply },
349
+ {
350
+ name: '@drawcall/cache',
351
+ apply,
352
+ async configResolved(resolved) {
353
+ config = resolved;
354
+ if (!config.publicDir)
355
+ throw new Error('cache requires Vite publicDir');
356
+ // Its files are scanned as public scripts, so it cannot also hold the sources.
357
+ if (`${config.root}/`.startsWith(`${config.publicDir}/`))
358
+ throw new Error('cache requires a Vite publicDir that does not contain the root');
359
+ // Normalized, as are the files hotUpdate is given.
360
+ directory = normalizePath(join(config.publicDir, cacheName));
361
+ // The same storage, so that a load an older plugin still warms records what it uses.
362
+ warming = globalThis.drawcallCache?.warming ?? new AsyncLocalStorage();
363
+ globalThis.drawcallCache = { root: config.root, publicDir: config.publicDir, loaded, warming };
364
+ const outputs = [config.build.outDir, config.publicDir].map((path) => relative(config.root, resolve(config.root, path)));
365
+ const tree = (root, pattern, excluded) => ({
366
+ root,
367
+ pattern,
368
+ excluded,
369
+ matches: picomatch(pattern, { ignore: excluded }),
370
+ });
371
+ trees = [
372
+ // Not dependencies or outputs. An output at the root itself excludes nothing, since the root holds the sources.
373
+ tree(config.root, `**/*.{${extensions}}`, [
374
+ '**/node_modules/**',
375
+ ...outputs.filter(Boolean).map((path) => `${normalizePath(path)}/**`),
376
+ ]),
377
+ tree(config.publicDir, `**/*.{glts,${extensions}}`, ['**/node_modules/**', `${cacheName}/**`]),
378
+ ];
379
+ await ignore(config.root, directory);
380
+ },
381
+ async buildStart() {
382
+ if (config.command !== 'build' || this.environment.name !== 'client')
383
+ return;
384
+ try {
385
+ await scanAll();
386
+ await warm();
387
+ if (failed)
388
+ throw new Error('cache: warming failed, see the errors above.');
389
+ }
390
+ finally {
391
+ await runner?.close();
392
+ runner = undefined;
393
+ fetched = new Map();
394
+ await (await server)?.close();
395
+ server = undefined;
396
+ }
397
+ },
398
+ configureServer(devServer) {
399
+ server = Promise.resolve(devServer);
400
+ const prefix = `${config.base}${cacheName}/`;
401
+ // Serves entries itself, since Vite's public file serving learns of new files only through its watcher: an entry
402
+ // whose inputs are unchanged at once, any other once warming has saved or pruned it.
403
+ devServer.middlewares.use((request, response, next) => {
404
+ if (!request.url?.startsWith(prefix))
405
+ return next();
406
+ const name = new URL(request.url, 'http://cache').pathname.slice(prefix.length);
407
+ const key = /^([a-f0-9]{64})\.bin$/.exec(name)?.[1];
408
+ if (!key)
409
+ return next();
410
+ void current(config.root, directory, key, false)
411
+ .then((fresh) => (fresh ? undefined : idle()))
412
+ .then(() => read(join(directory, name)))
413
+ .then((bytes) => {
414
+ if (!bytes)
415
+ return next();
416
+ response.setHeader('Content-Type', 'application/octet-stream');
417
+ response.setHeader('Cache-Control', 'no-cache');
418
+ response.end(bytes);
419
+ }, next);
420
+ });
421
+ const report = (error) => log(stack(error), 'error');
422
+ // Queued, so that requests wait for the scan too.
423
+ queue = queue.then(scanAll).catch(report);
424
+ void warm().catch(report);
425
+ },
426
+ async hotUpdate({ file }) {
427
+ if (this.environment.name !== 'client' || file.startsWith(directory))
428
+ return;
429
+ if (scanned(file))
430
+ await scan(file);
431
+ // Any file can be an input, and an unchanged entry warms with one load. Saves are file changes too.
432
+ void warm();
433
+ },
434
+ async closeBundle() {
435
+ closing = true;
436
+ await idle();
437
+ },
438
+ },
439
+ ];
440
+ }
441
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite.js","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,MAAM,MAAM,YAAY,CAAC;AAChC,OAAO,SAAS,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,aAAa,EAAwD,MAAM,MAAM,CAAC;AACzG,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,YAAY,EAAyB,MAAM,oBAAoB,CAAC;AACnH,OAAO,EAAE,S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AC,CAAC;gBACpC,oGAAoG;gBACpG,KAAK,IAAI,EAAE,CAAC;YACd,CAAC;YACD,KAAK,CAAC,WAAW;gBACf,OAAO,GAAG,IAAI,CAAC;gBACf,MAAM,IAAI,EAAE,CAAC;YACf,CAAC;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { appendFile, readdir, readFile, rm } from 'node:fs/promises';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport MagicString from 'magic-string';\nimport colors from 'picocolors';\nimport picomatch from 'picomatch';\nimport { glob } from 'tinyglobby';\nimport { createServer, normalizePath, type Plugin, type ResolvedConfig, type ViteDevServer } from 'vite';\nimport { createNodeImportMeta, ESModulesEvaluator, ModuleRunner, type EvaluatedModules } from 'vite/module-runner';\nimport { cacheName, missing, read, type Warming } from './disk.js';\nimport { discover, type Load } from './discover.js';\nimport { current, record, type Recorded } from './inputs.js';\n\n/** Adds the cache directory to the project's .gitignore, since its entries are generated. */\nasync function ignore(root: string, directory: string): Promise<void> {\n const line = `${relative(root, directory).split('\\\\').join('/')}/*`;\n const file = join(root, '.gitignore');\n const contents = new TextDecoder().decode(await read(file));\n if (contents.split(/\\r?\\n/).includes(line)) return;\n await appendFile(file, `${contents && !contents.endsWith('\\n') ? '\\n' : ''}${line}\\n`);\n}\n\nfunction stack(error: unknown): string {\n return error instanceof Error ? (error.stack ?? error.message) : String(error);\n}\n\nconst hash = (text: string) => createHash('sha256').update(text).digest('hex');\n\n/**\n * Wraps each of the loads' inline functions in a tag of its identity, the hash of its importer and source, which keys\n * count it as.\n */\nfunction tag(code: MagicString, loads: Load[], root: string): void {\n const importer = (load: Load) => normalizePath(relative(root, load.importer));\n for (const load of loads) {\n for (const { start, end } of load.functions) {\n const id = hash(`${importer(load)}\\n${code.original.slice(start, end)}`);\n code.prependRight(start, 'Object.defineProperty(');\n code.appendLeft(end, `, Symbol.for(\"@drawcall/cache.function\"), { value: ${JSON.stringify(id)} })`);\n }\n }\n}\n\n/** The input a module's file counts as: an installed package's module as its package.json, which covers its imports. */\nfunction moduleInput(file: string): string {\n const installed = /^(.*\\/node_modules\\/(?:@[^/]+\\/)?[^/]+)\\//.exec(file)?.[1];\n return installed ? `${installed}/package.json` : file;\n}\n\n/** The file a module runner's fetch answered with, or undefined for a built-in or a module cached in the runner. */\nfunction fetchedFile(result: unknown): string | undefined {\n if (typeof result !== 'object' || result === null) return undefined;\n if ('file' in result && typeof result.file === 'string') return result.file;\n if ('externalize' in result && typeof result.externalize === 'string' && result.externalize.startsWith('file:'))\n return fileURLToPath(result.externalize);\n return undefined;\n}\n\n/**\n * The inputs of the modules reachable from `ids` in a module runner's graph of what it evaluated, which holds each\n * import as it ran, dynamic ones included. An installed package's imports are left out, since its package.json covers\n * them.\n */\nfunction reachable(modules: EvaluatedModules, ids: Iterable<string>): string[] {\n const inputs = new Set<string>();\n const seen = new Set<string>();\n const pending = [...ids];\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n const module = modules.getModuleById(id);\n if (!module || seen.has(id)) continue;\n seen.add(id);\n // Built-in modules have no file, and virtual ones no absolute one, but a virtual module's imports still count.\n if (!isAbsolute(module.file)) {\n pending.push(...module.imports);\n continue;\n }\n const input = moduleInput(module.file);\n inputs.add(input);\n if (input === module.file) pending.push(...module.imports);\n }\n return [...inputs];\n}\n\n/** The query of the module that exports a load's arguments, whose value is the load's position in its importer. */\nconst query = '?drawcall-cache-load=';\n\n/** The extensions of the JavaScript and TypeScript modules discovery scans, as Tailwind scans for class names. */\nconst extensions = 'js,jsx,ts,tsx,mjs,mts';\n\n/** A directory discovery scans, with patterns relative to it. */\ninterface Tree {\n root: string;\n pattern: string;\n excluded: string[];\n matches: (path: string) => boolean;\n}\n\n/** The path of `file` relative to `directory`, undefined for a file outside it. Both are normalized. */\nfunction below(directory: string, file: string): string | undefined {\n return file.startsWith(`${directory}/`) ? file.slice(directory.length + 1) : undefined;\n}\n\n/** Marks the server the plugin warms with in a build, which loads the config, and so the plugin, again. */\nconst warmServerMarker = '@drawcall/cache:warm';\n\n/**\n * Finds cached loader loads in the project's source files, and in publicDir's `.glts` scripts and every JavaScript and\n * TypeScript module there, and warms them in Node, so that browsers read what Node saved, then deletes the entries no\n * load uses. In development it scans and warms at startup and again after every file change, and holds a request for an\n * entry whose inputs changed, or that does not exist, until warming finishes. A build scans and warms once.\n */\nexport function cache(): Plugin[] {\n /** Each scanned file with loads, and its loads. */\n const files = new Map<string, { code: string; loads: Load[] }>();\n let config: ResolvedConfig;\n const loaded = new Set<string>();\n let directory: string;\n /** Runs loaders: the dev server itself, or in a build a server started for that, once, by the first load. */\n let server: Promise<ViteDevServer> | undefined;\n /**\n * The plugin's own module runner on the server, whose graph records what each load ran. Not the environment's\n * runner, whose graph a full reload after a change clears while a load runs. And it asks the environment directly,\n * not over the hot channel, whose close removes the listener of its answers while closeBundle waits for the loads.\n */\n let runner: ModuleRunner | undefined;\n /** The inputs of the modules the runner fetched, each as it was just after Vite answered the fetch. */\n let fetched = new Map<string, Recorded>();\n /** What the load being warmed uses, shared with CacheEntry through the global. */\n let warming: AsyncLocalStorage<Warming>;\n let queue = Promise.resolve();\n /** Whether a pass is queued but has not started, which the next change then need not queue again. */\n let queued = false;\n /** Whether a load of the latest pass failed, which leaves the entries in place. */\n let failed = false;\n /** Set once the dev server closes, after which a running pass stops and nothing is pruned. */\n let closing = false;\n\n /** The directories discovery scans, with patterns relative to each: the root, and publicDir. */\n let trees: Tree[];\n\n /** Records a file's loads. Development logs failures, since a file being edited can fail to parse. */\n async function scan(file: string): Promise<void> {\n try {\n const code = new TextDecoder().decode(await read(file));\n if (!/Cached\\w*Loader/.test(code)) return void files.delete(file);\n const loads = discover(code, file);\n // Browsers run public scripts as they are, so nothing tags their functions.\n const inline = below(config.publicDir, file) === undefined ? undefined : loads.find((load) => load.functions[0]);\n if (inline)\n throw new Error(`Public scripts cannot pass inline functions to loads, at ${file}:${inline.position}`);\n files.set(file, { code, loads });\n } catch (error) {\n if (config.command === 'build') throw error;\n log(`${colors.red('cannot scan')} ${error instanceof Error ? error.message : String(error)}`, 'error');\n }\n }\n\n /** Whether discovery scans `file`. */\n function scanned(file: string): boolean {\n return trees.some(({ root, matches }) => {\n const path = below(root, file);\n return path !== undefined && matches(path);\n });\n }\n\n /**\n * Serves each load's arguments as a module of its importer, so that its inline functions import as they do there, and\n * tags inline functions in the app's modules alike. The server a build warms with gets these hooks too.\n */\n const tagging: Plugin = {\n name: '@drawcall/cache:tagging',\n enforce: 'pre',\n resolveId(id) {\n return id.includes(query) ? id : undefined;\n },\n // Vite invalidates the module when its importer changes, since it shares its file.\n load(id) {\n const [importer = '', position] = id.split(query);\n const file = files.get(importer);\n const load = file?.loads.find((load) => load.position === position);\n if (!file || !load) return undefined;\n const code = new MagicString(file.code);\n tag(code, [load], config.root);\n return `export default [${load.args.map(({ start, end }) => code.slice(start, end)).join(', ')}];`;\n },\n async transform(code, id) {\n if (id.includes('?') || !scanned(id) || !/Cached\\w*Loader/.test(code)) return;\n let loads: Load[];\n try {\n loads = discover(code, id);\n } catch {\n // The scan reports it.\n return;\n }\n if (!loads.some((load) => load.functions.length)) return;\n // Warming hashes functions as the file holds them, which a plugin transforming before this one would change. Read\n // as Vite reads it, keeping a byte order mark.\n if (code !== (await readFile(id, 'utf8')))\n throw new Error(`cache must come before plugins that transform ${id}`);\n const tagged = new MagicString(code);\n tag(tagged, loads, config.root);\n return { code: tagged.toString(), map: tagged.generateMap({ hires: 'boundary', source: id }) };\n },\n };\n\n async function run({ importer, source, name, position }: Load): Promise<void> {\n server ??= createServer({\n configFile: config.configFile ?? false,\n root: config.root,\n mode: config.mode,\n logLevel: 'warn',\n server: { middlewareMode: true, hmr: false, ws: false, watch: null },\n plugins: [{ name: warmServerMarker }, tagging],\n });\n const environment = (await server).environments.ssr;\n runner ??= new ModuleRunner(\n {\n transport: {\n async invoke(payload) {\n const answer = await environment.hot.handleInvoke(payload);\n const file = 'result' in answer ? fetchedFile(answer.result) : undefined;\n if (!file) return answer;\n const input = moduleInput(file);\n // Before the runner evaluates the module, which may change the file. Vite read it a little earlier, and a\n // write in between goes unseen.\n const [state] = await record(config.root, [{ path: pathToFileURL(input).href }]);\n if (state) fetched.set(input, state);\n return answer;\n },\n },\n createImportMeta: createNodeImportMeta,\n hmr: false,\n sourcemapInterceptor: false,\n },\n new ESModulesEvaluator(),\n );\n const { evaluatedModules } = runner;\n const resolved = await environment.pluginContainer.resolveId(source, importer);\n if (!resolved) throw new Error(`cache cannot resolve ${source} from ${importer}`);\n const module: Record<string, unknown> = await runner.import(resolved.id);\n const exported = module[name];\n if (typeof exported !== 'function') throw new Error(`${source} does not export a class ${name}`);\n const instance: unknown = Reflect.construct(exported, []);\n const loadable = typeof instance === 'object' && instance !== null && 'loadAsync' in instance;\n if (!loadable || typeof instance.loadAsync !== 'function') throw new Error(`${name} has no loadAsync method`);\n const path = below(config.publicDir, importer);\n if (path !== undefined) {\n // A browser resolves a public file's relative URLs against its served URL, and a loader against its path. The\n // path leaves out Vite's base, so that keys do not depend on where the app is deployed.\n if (!('setPath' in instance) || typeof instance.setPath !== 'function')\n throw new Error(`${name} has no setPath method, which a load in a public file needs`);\n // Encoded by the URL parser, as a browser requests it; it would read these as delimiters or escapes.\n const folder = path.slice(0, path.lastIndexOf('/') + 1).replace(/[%#?\\\\]/g, encodeURIComponent);\n instance.setPath(new URL(`/${folder}`, 'http://host').pathname);\n }\n const argumentsId = `${importer}${query}${position}`;\n const { default: args }: Record<string, unknown> = await runner.import(argumentsId);\n if (!Array.isArray(args)) throw new Error(`cache cannot load the arguments of ${name}`);\n // What the loader's module and the arguments' functions import, not the importer the arguments module shares.\n const modules = () => {\n const ids = [resolved.id, ...(evaluatedModules.getModuleById(argumentsId)?.imports ?? [])];\n return reachable(evaluatedModules, ids).map((input) => {\n const state = fetched.get(input);\n if (!state) throw new Error(`cache did not see the runner fetch ${input}`);\n return state;\n });\n };\n const { loadAsync } = instance;\n await warming.run({ files: [], modules }, () => loadAsync.apply(instance, args));\n }\n\n /** Logs as Vite does with a timestamp, but tagged [cache], since Vite's own timestamp option tags lines [vite]. */\n function log(message: string, level: 'info' | 'error' = 'info'): void {\n const tag = colors.bold(level === 'info' ? colors.cyan('[cache]') : colors.red('[cache]'));\n config.logger[level](`${colors.dim(new Date().toLocaleTimeString())} ${tag} ${message}`);\n }\n\n /**\n * Runs every load once, all at once, so that one waiting on the GPU or a worker leaves the others to run, then,\n * unless a load failed, deletes the entries none of them loaded. A pass still running after half a second is\n * announced, and so is its end.\n */\n async function pass(): Promise<void> {\n queued = false;\n failed = false;\n loaded.clear();\n if (closing) return;\n const loads = [...files.values()].flatMap((file) => file.loads);\n const started = performance.now();\n let slow = false;\n const timer = setTimeout(() => {\n slow = true;\n log(`${colors.yellow('computing')} ${loads.length} loads…`);\n }, 500);\n await Promise.all(\n loads.map(async (load) => {\n try {\n await run(load);\n } catch (error) {\n failed = true;\n const file = normalizePath(relative(config.root, load.importer));\n log(\n `${colors.red('failed')} ${load.name} ${colors.dim(`${file}:${load.position}`)}\\n${stack(error)}`,\n 'error',\n );\n }\n }),\n );\n clearTimeout(timer);\n if (slow) log(`warmed in ${((performance.now() - started) / 1000).toFixed(1)} s`);\n // Another plugin in this process may have replaced the global since, as a restarted dev server does.\n if (failed || closing || globalThis.drawcallCache?.loaded !== loaded) return;\n try {\n await prune();\n } catch (error) {\n if (config.command === 'build') throw error;\n log(`${colors.red('cannot prune')} ${stack(error)}`, 'error');\n }\n }\n\n /** Queues a pass unless one is already waiting. */\n function warm(): Promise<void> {\n if (!queued) {\n queued = true;\n queue = queue.then(pass);\n }\n return idle();\n }\n\n async function idle(): Promise<void> {\n let current: Promise<void>;\n do {\n current = queue;\n await current;\n } while (current !== queue);\n }\n\n /** Deletes the entries whose keys are not in `loaded`. */\n async function prune(): Promise<void> {\n const names = await readdir(directory).catch((error: unknown) => {\n if (missing(error)) return [];\n throw error;\n });\n for (const name of names) {\n const key = /^([a-f0-9]{64})\\.(?:bin|json)$/.exec(name)?.[1];\n if (key && !loaded.has(key)) await rm(join(directory, name), { force: true });\n }\n }\n\n async function scanAll(): Promise<void> {\n for (const { root, pattern, excluded } of trees)\n for (const file of await glob(pattern, { cwd: root, absolute: true, ignore: excluded })) await scan(file);\n }\n\n // The warm server's copy of the plugin stays out, since this one warms, and gives it `tagging`.\n const apply: Plugin['apply'] = (config) =>\n !config.plugins?.some((plugin) => plugin && 'name' in plugin && plugin.name === warmServerMarker);\n return [\n { ...tagging, apply },\n {\n name: '@drawcall/cache',\n apply,\n async configResolved(resolved) {\n config = resolved;\n if (!config.publicDir) throw new Error('cache requires Vite publicDir');\n // Its files are scanned as public scripts, so it cannot also hold the sources.\n if (`${config.root}/`.startsWith(`${config.publicDir}/`))\n throw new Error('cache requires a Vite publicDir that does not contain the root');\n // Normalized, as are the files hotUpdate is given.\n directory = normalizePath(join(config.publicDir, cacheName));\n // The same storage, so that a load an older plugin still warms records what it uses.\n warming = globalThis.drawcallCache?.warming ?? new AsyncLocalStorage<Warming>();\n globalThis.drawcallCache = { root: config.root, publicDir: config.publicDir, loaded, warming };\n const outputs = [config.build.outDir, config.publicDir].map((path) =>\n relative(config.root, resolve(config.root, path)),\n );\n const tree = (root: string, pattern: string, excluded: string[]): Tree => ({\n root,\n pattern,\n excluded,\n matches: picomatch(pattern, { ignore: excluded }),\n });\n trees = [\n // Not dependencies or outputs. An output at the root itself excludes nothing, since the root holds the sources.\n tree(config.root, `**/*.{${extensions}}`, [\n '**/node_modules/**',\n ...outputs.filter(Boolean).map((path) => `${normalizePath(path)}/**`),\n ]),\n tree(config.publicDir, `**/*.{glts,${extensions}}`, ['**/node_modules/**', `${cacheName}/**`]),\n ];\n await ignore(config.root, directory);\n },\n async buildStart() {\n if (config.command !== 'build' || this.environment.name !== 'client') return;\n try {\n await scanAll();\n await warm();\n if (failed) throw new Error('cache: warming failed, see the errors above.');\n } finally {\n await runner?.close();\n runner = undefined;\n fetched = new Map();\n await (await server)?.close();\n server = undefined;\n }\n },\n configureServer(devServer) {\n server = Promise.resolve(devServer);\n const prefix = `${config.base}${cacheName}/`;\n // Serves entries itself, since Vite's public file serving learns of new files only through its watcher: an entry\n // whose inputs are unchanged at once, any other once warming has saved or pruned it.\n devServer.middlewares.use((request, response, next) => {\n if (!request.url?.startsWith(prefix)) return next();\n const name = new URL(request.url, 'http://cache').pathname.slice(prefix.length);\n const key = /^([a-f0-9]{64})\\.bin$/.exec(name)?.[1];\n if (!key) return next();\n void current(config.root, directory, key, false)\n .then((fresh) => (fresh ? undefined : idle()))\n .then(() => read(join(directory, name)))\n .then((bytes) => {\n if (!bytes) return next();\n response.setHeader('Content-Type', 'application/octet-stream');\n response.setHeader('Cache-Control', 'no-cache');\n response.end(bytes);\n }, next);\n });\n const report = (error: unknown) => log(stack(error), 'error');\n // Queued, so that requests wait for the scan too.\n queue = queue.then(scanAll).catch(report);\n void warm().catch(report);\n },\n async hotUpdate({ file }) {\n if (this.environment.name !== 'client' || file.startsWith(directory)) return;\n if (scanned(file)) await scan(file);\n // Any file can be an input, and an unchanged entry warms with one load. Saves are file changes too.\n void warm();\n },\n async closeBundle() {\n closing = true;\n await idle();\n },\n },\n ];\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "@drawcall/cache",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "Persistent binary caching for expensive computation, warmed in Node by a Vite plugin and read in browsers and Node.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/drawcall-ai/cache.git",
10
+ "directory": "packages/cache"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/drawcall-ai/cache/issues"
14
+ },
15
+ "homepage": "https://github.com/drawcall-ai/cache#readme",
16
+ "keywords": [
17
+ "vite",
18
+ "cache",
19
+ "precompute",
20
+ "browser",
21
+ "node",
22
+ "typescript"
23
+ ],
24
+ "sideEffects": false,
25
+ "main": "./dist/browser.js",
26
+ "types": "./dist/browser.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/browser.d.ts",
30
+ "browser": "./dist/browser.js",
31
+ "node": "./dist/node.js",
32
+ "default": "./dist/browser.js"
33
+ },
34
+ "./vite": {
35
+ "types": "./dist/vite.d.ts",
36
+ "default": "./dist/vite.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "skills",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
50
+ "prepack": "pnpm build && pnpm typecheck && pnpm test",
51
+ "test": "vitest run",
52
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit"
53
+ },
54
+ "dependencies": {
55
+ "@noble/hashes": "^2.0.1",
56
+ "magic-string": "0.30.21",
57
+ "picocolors": "1.1.1",
58
+ "picomatch": "4.0.3",
59
+ "safe-stable-stringify": "2.5.0",
60
+ "tinyglobby": "0.2.15",
61
+ "write-file-atomic": "6.0.0"
62
+ },
63
+ "peerDependencies": {
64
+ "vite": ">=8.0.0"
65
+ },
66
+ "peerDependenciesMeta": {
67
+ "vite": {
68
+ "optional": true
69
+ }
70
+ },
71
+ "devDependencies": {
72
+ "@types/picomatch": "4.0.2",
73
+ "@types/write-file-atomic": "4.0.3",
74
+ "vite": "^8.0.0",
75
+ "vitest": "^4.0.17"
76
+ },
77
+ "engines": {
78
+ "node": ">=20.19.0"
79
+ }
80
+ }