@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Drawcall
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @drawcall/cache
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cache expensive computation as bytes: the Vite plugin computes it once in Node, then browsers and Node reuse it.
4
+
5
+ ```sh
6
+ pnpm add @drawcall/cache
7
+ ```
8
+
9
+ Wrap a computation in a class named `Cached…Loader` and load with literal arguments, which can include inline functions:
10
+
11
+ ```ts
12
+ import { CacheEntry } from "@drawcall/cache"
13
+
14
+ export class CachedMeshLoader {
15
+ async loadAsync(settings: { ratio: number }) {
16
+ const entry = new CacheEntry({ version: "simplify@2", dependencies: { settings: { value: settings } } })
17
+ let bytes = await entry.load()
18
+ if (bytes === undefined) {
19
+ bytes = await simplify(settings)
20
+ await entry.save(bytes)
21
+ }
22
+ return bytes
23
+ }
24
+ }
25
+
26
+ const mesh = await new CachedMeshLoader().loadAsync({ ratio: 0.5 })
27
+ ```
28
+
29
+ Add the plugin:
30
+
31
+ ```ts
32
+ import { defineConfig } from "vite"
33
+ import { cache } from "@drawcall/cache/vite"
34
+
35
+ export default defineConfig({ plugins: [cache()] })
36
+ ```
37
+
38
+ The plugin finds these loads by scanning the project's source files, `.glts` scripts and other modules in `publicDir` included, computes them in Node during development and builds, and deletes entries no load uses. Browsers read the saved bytes.
39
+
40
+ For usage patterns, see the [cache skill](skills/cache/SKILL.md), also shipped in this package.
@@ -0,0 +1,15 @@
1
+ import { type CacheEntryOptions, type SaveOptions } from './entry.js';
2
+ export type { CacheEntryOptions, Dependency, Input, LoadFunction, SaveOptions, Value } from './entry.js';
3
+ /** A public file's path as an input: in browsers, its URL itself, since they save no entries. */
4
+ export declare function publicFile(url: string): string;
5
+ /** The URL to read a public file at: in browsers, its URL itself, since they load public files over HTTP. */
6
+ export declare function publicURL(url: string): string;
7
+ /** A cached result, read from the cache directory the app serves. Only Node writes entries. */
8
+ export declare class CacheEntry {
9
+ #private;
10
+ constructor(options: CacheEntryOptions);
11
+ /** The saved bytes, or undefined when the app serves none. */
12
+ load(): Promise<Uint8Array | undefined>;
13
+ /** Writes nothing, since browsers only read. Warns once per version that its result was computed here. */
14
+ save(_value: Uint8Array, _options?: SaveOptions): Promise<void>;
15
+ }
@@ -0,0 +1,41 @@
1
+ import { key } from './entry.js';
2
+ const warned = new Set();
3
+ /** A public file's path as an input: in browsers, its URL itself, since they save no entries. */
4
+ export function publicFile(url) {
5
+ return url;
6
+ }
7
+ /** The URL to read a public file at: in browsers, its URL itself, since they load public files over HTTP. */
8
+ export function publicURL(url) {
9
+ return url;
10
+ }
11
+ /** A cached result, read from the cache directory the app serves. Only Node writes entries. */
12
+ export class CacheEntry {
13
+ #version;
14
+ #url;
15
+ constructor(options) {
16
+ this.#version = options.version;
17
+ const base = new URL((options.basePath ?? '/_cache/').replace(/\/?$/, '/'), globalThis.location.href);
18
+ this.#url = new URL(`${key(options)}.bin`, base);
19
+ }
20
+ /** The saved bytes, or undefined when the app serves none. */
21
+ async load() {
22
+ // An entry keeps its name when its bytes change, so the HTTP cache must revalidate them.
23
+ const response = await fetch(this.#url, { cache: 'no-cache' });
24
+ if (response.status === 404)
25
+ return undefined;
26
+ if (!response.ok)
27
+ throw new Error(`cache load failed: HTTP ${response.status}`);
28
+ // Vite's dev server and SPA hosts answer a missing file with index.html.
29
+ if (response.headers.get('content-type')?.startsWith('text/html'))
30
+ return undefined;
31
+ return new Uint8Array(await response.arrayBuffer());
32
+ }
33
+ /** Writes nothing, since browsers only read. Warns once per version that its result was computed here. */
34
+ async save(_value, _options) {
35
+ if (warned.has(this.#version))
36
+ return;
37
+ warned.add(this.#version);
38
+ console.warn(`cache: ${this.#version} was computed in the browser, which does not save it.`);
39
+ }
40
+ }
41
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAA4C,MAAM,YAAY,CAAC;AAG3E,MAAM,MAAM,GAAG,IAAI,GAAG,EAAU,CAAC;AAEjC,iGAAiG;AACjG,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC;AACb,CAAC;AAED,6GAA6G;AAC7G,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,OAAO,GAAG,CAAC;AACb,CAAC;AAED,+FAA+F;AAC/F,MAAM,OAAO,UAAU;IACZ,QAAQ,CAAS;IACjB,IAAI,CAAM;IAEnB,YAAY,OAA0B;QACpC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;Q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, SaveOptions, Value } from './entry.js';\n\nconst warned = new Set<string>();\n\n/** A public file's path as an input: in browsers, its URL itself, since they save no entries. */\nexport function publicFile(url: string): string {\n return url;\n}\n\n/** The URL to read a public file at: in browsers, its URL itself, since they load public files over HTTP. */\nexport function publicURL(url: string): string {\n return url;\n}\n\n/** A cached result, read from the cache directory the app serves. Only Node writes entries. */\nexport class CacheEntry {\n readonly #version: string;\n readonly #url: URL;\n\n constructor(options: CacheEntryOptions) {\n this.#version = options.version;\n const base = new URL((options.basePath ?? '/_cache/').replace(/\\/?$/, '/'), globalThis.location.href);\n this.#url = new URL(`${key(options)}.bin`, base);\n }\n\n /** The saved bytes, or undefined when the app serves none. */\n async load(): Promise<Uint8Array | undefined> {\n // An entry keeps its name when its bytes change, so the HTTP cache must revalidate them.\n const response = await fetch(this.#url, { cache: 'no-cache' });\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(`cache load failed: HTTP ${response.status}`);\n // Vite's dev server and SPA hosts answer a missing file with index.html.\n if (response.headers.get('content-type')?.startsWith('text/html')) return undefined;\n return new Uint8Array(await response.arrayBuffer());\n }\n\n /** Writes nothing, since browsers only read. Warns once per version that its result was computed here. */\n async save(_value: Uint8Array, _options?: SaveOptions): Promise<void> {\n if (warned.has(this.#version)) return;\n warned.add(this.#version);\n console.warn(`cache: ${this.#version} was computed in the browser, which does not save it.`);\n }\n}\n"]}
@@ -0,0 +1,22 @@
1
+ /** A source range in the importer. */
2
+ export interface Range {
3
+ start: number;
4
+ end: number;
5
+ }
6
+ /** A `loadAsync(...args)` of a cached loader that discovery found, which warming repeats on a `new` loader in Node. */
7
+ export interface Load {
8
+ importer: string;
9
+ /** Where in the importer the load is, as `line:column`. */
10
+ position: string;
11
+ source: string;
12
+ name: string;
13
+ /** Each argument's source: JSON written as JavaScript literals, and inline functions. */
14
+ args: Range[];
15
+ /** The functions passed inline among the arguments, which warming repeats from their source. */
16
+ functions: Range[];
17
+ }
18
+ /**
19
+ * The cached loader loads in a module: `new Loader(...).loadAsync(...)`, or `loadAsync(...)` on a variable initialized
20
+ * with `new Loader(...)`. Any other use of a loader or such a variable fails, since warming could not repeat it.
21
+ */
22
+ export declare function discover(code: string, importer: string): Load[];
@@ -0,0 +1,245 @@
1
+ import { parseSync, Visitor } from 'vite';
2
+ const isNode = (value) => typeof value === 'object' && value !== null && typeof value.type === 'string';
3
+ /** TypeScript nodes that hold a value; other TypeScript nodes are types, which name nothing at runtime. */
4
+ const values = new Set([
5
+ 'TSAsExpression',
6
+ 'TSSatisfiesExpression',
7
+ 'TSNonNullExpression',
8
+ 'TSTypeAssertion',
9
+ 'TSInstantiationExpression',
10
+ 'TSParameterProperty',
11
+ ]);
12
+ /** Visits every node below `node` outside types, with the parent and the property holding it. */
13
+ function walk(node, visit) {
14
+ for (const [key, child] of Object.entries(node)) {
15
+ for (const item of [child].flat()) {
16
+ if (!isNode(item) || (item.type.startsWith('TS') && !values.has(item.type)))
17
+ continue;
18
+ visit(item, node, key);
19
+ walk(item, visit);
20
+ }
21
+ }
22
+ }
23
+ /** A root holding `node`, so that walking it visits `node` too. */
24
+ const holding = (node) => ({ type: 'Program', start: node.start, end: node.end, body: [node] });
25
+ /** The names a binding pattern declares. */
26
+ function bound(pattern, names) {
27
+ if (!isNode(pattern))
28
+ return;
29
+ if (pattern.type === 'Identifier')
30
+ names.add(pattern.name);
31
+ else if (pattern.type === 'ObjectPattern')
32
+ for (const property of pattern.properties)
33
+ bound(property.type === 'RestElement' ? property.argument : property.value, names);
34
+ else if (pattern.type === 'ArrayPattern')
35
+ for (const element of pattern.elements)
36
+ bound(element, names);
37
+ else if (pattern.type === 'AssignmentPattern')
38
+ bound(pattern.left, names);
39
+ else if (pattern.type === 'RestElement')
40
+ bound(pattern.argument, names);
41
+ else if (pattern.type === 'TSParameterProperty')
42
+ bound(pattern.parameter, names);
43
+ }
44
+ /** Every name declared below `node`, in any scope. */
45
+ function declared(node) {
46
+ const names = new Set();
47
+ walk(node, (child) => {
48
+ if (child.type === 'VariableDeclarator')
49
+ bound(child.id, names);
50
+ else if (child.type === 'CatchClause')
51
+ bound(child.param, names);
52
+ else if (/^Import\w*Specifier$/.test(child.type))
53
+ bound(child.local, names);
54
+ else if (/Function|Class|^TS(Enum|Module)Declaration$|^TSImportEquals/.test(child.type))
55
+ bound(child.id, names);
56
+ if (/Function/.test(child.type))
57
+ for (const param of child.params ?? [])
58
+ bound(param, names);
59
+ });
60
+ return names;
61
+ }
62
+ /** Whether an identifier at this place names a variable, rather than a property, label or meta property. */
63
+ function referenced(parent, key) {
64
+ if (parent.computed !== true && key === 'key')
65
+ return false;
66
+ if (parent.type === 'MemberExpression' && key === 'property' && parent.computed !== true)
67
+ return false;
68
+ return key !== 'label' && parent.type !== 'MetaProperty';
69
+ }
70
+ /**
71
+ * The convention that marks a class as a cached loader: its loadAsync computes a result once and saves it. Warming
72
+ * constructs it without arguments, so only loadAsync's arguments, and in a public file its path, may select the result.
73
+ */
74
+ const loader = /^Cached\w*Loader$/;
75
+ /**
76
+ * The cached loader loads in a module: `new Loader(...).loadAsync(...)`, or `loadAsync(...)` on a variable initialized
77
+ * with `new Loader(...)`. Any other use of a loader or such a variable fails, since warming could not repeat it.
78
+ */
79
+ export function discover(code, importer) {
80
+ const at = (offset) => {
81
+ const lines = code.slice(0, offset).split('\n');
82
+ return `${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}`;
83
+ };
84
+ const fail = (message, offset) => {
85
+ throw new Error(`${message} at ${importer}:${at(offset)}`);
86
+ };
87
+ // .glts asset scripts are TypeScript.
88
+ const { program, errors } = parseSync(importer, code, importer.endsWith('.glts') ? { lang: 'ts' } : undefined);
89
+ if (errors[0])
90
+ fail(errors[0].message, errors[0].labels[0]?.start ?? 0);
91
+ const imports = new Map();
92
+ const namespaces = new Map();
93
+ for (const statement of program.body) {
94
+ if (statement.type !== 'ImportDeclaration')
95
+ continue;
96
+ for (const specifier of statement.specifiers) {
97
+ if (specifier.type === 'ImportNamespaceSpecifier')
98
+ namespaces.set(specifier.local.name, statement.source.value);
99
+ if (specifier.type !== 'ImportSpecifier')
100
+ continue;
101
+ const name = specifier.imported.type === 'Literal' ? specifier.imported.value : specifier.imported.name;
102
+ if (loader.test(name))
103
+ imports.set(specifier.local.name, { source: statement.source.value, name });
104
+ }
105
+ }
106
+ /** Nodes that name a loader or loader variable without using its value. */
107
+ const allowed = new Set();
108
+ /** Names declared anywhere in the module, which an inline function must not use from outside itself. */
109
+ const context = declared(program);
110
+ /** Checks that a function uses no variable of its module, so that warming can repeat it from its source alone. */
111
+ const inline = (node) => {
112
+ const own = declared(holding(node));
113
+ walk(holding(node), (child, parent, key) => {
114
+ if (child.type !== 'Identifier' || !referenced(parent, key))
115
+ return;
116
+ const name = child.name;
117
+ if (context.has(name) && !own.has(name))
118
+ fail(`Inline functions in cached loader loads must not use ${name} from their module`, child.start);
119
+ });
120
+ return { start: node.start, end: node.end };
121
+ };
122
+ /** JSON written as JavaScript literals, and inline functions, which it collects. */
123
+ const literal = (node, functions) => {
124
+ const nested = (child) => literal(child, functions);
125
+ const invalid = () => fail('Cached loader loadAsync arguments must be literal JSON or inline functions', node.start);
126
+ switch (node.type) {
127
+ case 'ArrowFunctionExpression':
128
+ case 'FunctionExpression':
129
+ return void functions.push(inline(node));
130
+ case 'ParenthesizedExpression':
131
+ return nested(node.expression);
132
+ case 'Literal':
133
+ if (node.value === null || ['string', 'number', 'boolean'].includes(typeof node.value))
134
+ return;
135
+ return invalid();
136
+ case 'UnaryExpression':
137
+ if (/^[-+]$/.test(node.operator) && isNode(node.argument) && typeof node.argument.value === 'number')
138
+ return;
139
+ return invalid();
140
+ case 'ArrayExpression':
141
+ for (const element of node.elements) {
142
+ if (!isNode(element) || element.type === 'SpreadElement')
143
+ invalid();
144
+ nested(element);
145
+ }
146
+ return;
147
+ case 'ObjectExpression':
148
+ for (const property of node.properties) {
149
+ const { type, kind, method, shorthand, computed } = property;
150
+ if (type !== 'Property' || kind !== 'init' || method || shorthand || computed)
151
+ invalid();
152
+ nested(property.value);
153
+ }
154
+ return;
155
+ default:
156
+ return invalid();
157
+ }
158
+ };
159
+ const target = (node) => {
160
+ if (node.type === 'Identifier')
161
+ return imports.get(node.name);
162
+ if (node.type !== 'MemberExpression' || node.computed || node.object.type !== 'Identifier')
163
+ return undefined;
164
+ const source = namespaces.get(node.object.name);
165
+ return source !== undefined && loader.test(node.property.name) ? { source, name: node.property.name } : undefined;
166
+ };
167
+ const created = (node) => {
168
+ const loaded = target(node.callee);
169
+ if (loaded)
170
+ allowed.add(node.callee);
171
+ return loaded;
172
+ };
173
+ // A first pass, since a variable can be used above its declaration, as in a function declared earlier.
174
+ const instances = new Map();
175
+ new Visitor({
176
+ VariableDeclarator(node) {
177
+ if (node.id.type !== 'Identifier' || node.init?.type !== 'NewExpression')
178
+ return;
179
+ const instance = created(node.init);
180
+ if (!instance)
181
+ return;
182
+ instances.set(node.id.name, instance);
183
+ allowed.add(node.id);
184
+ },
185
+ }).visit(program);
186
+ const member = (node) => {
187
+ if (!node.computed)
188
+ allowed.add(node.key);
189
+ };
190
+ const misused = (node) => fail('Use cached loaders only as new Loader().loadAsync(), or a variable of one', node.start);
191
+ const loads = [];
192
+ new Visitor({
193
+ ImportSpecifier: (node) => allowed.add(node.local).add(node.imported),
194
+ // Loads through an exported loader variable happen in other modules, out of discovery's reach.
195
+ ExportSpecifier(node) {
196
+ if (node.local.type === 'Identifier' && instances.has(node.local.name))
197
+ misused(node);
198
+ allowed.add(node.local).add(node.exported);
199
+ },
200
+ ExportNamedDeclaration(node) {
201
+ if (node.declaration?.type !== 'VariableDeclaration')
202
+ return;
203
+ for (const { id } of node.declaration.declarations)
204
+ if (id.type === 'Identifier' && instances.has(id.name))
205
+ misused(id);
206
+ },
207
+ Property(node) {
208
+ if (!node.shorthand)
209
+ member(node);
210
+ },
211
+ MethodDefinition: member,
212
+ PropertyDefinition: member,
213
+ CallExpression(node) {
214
+ const { callee } = node;
215
+ if (callee.type !== 'MemberExpression' || callee.computed || callee.property.name !== 'loadAsync')
216
+ return;
217
+ const { object } = callee;
218
+ const instance = object.type === 'NewExpression'
219
+ ? created(object)
220
+ : object.type === 'Identifier'
221
+ ? instances.get(object.name)
222
+ : undefined;
223
+ if (!instance)
224
+ return;
225
+ allowed.add(object);
226
+ const functions = [];
227
+ for (const argument of node.arguments)
228
+ literal(argument, functions);
229
+ const args = node.arguments.map(({ start, end }) => ({ start, end }));
230
+ loads.push({ importer, position: at(node.start), ...instance, args, functions });
231
+ },
232
+ MemberExpression(node) {
233
+ if (!node.computed)
234
+ allowed.add(node.property);
235
+ if (target(node) && !allowed.has(node))
236
+ misused(node);
237
+ },
238
+ Identifier(node) {
239
+ if ((imports.has(node.name) || instances.has(node.name)) && !allowed.has(node))
240
+ misused(node);
241
+ },
242
+ }).visit(program);
243
+ return loads;
244
+ }
245
+ //# sourceMappingURL=discover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discover.js","sourceRoot":"","sources":["../src/discover.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAe,MAAM,MAAM,CAAC;AAwBvD,MAAM,MAAM,GAAG,CAAC,KAAc,EAAiB,EAAE,CAC/C,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ,CAAC;AAExG,2GAA2G;AAC3G,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC;IACrB,gBAAgB;IAChB,uBAAuB;IACvB,qBAAqB;IACrB,iBAAiB;IACjB,2BAA2B;IAC3B,qBAAqB;CACtB,CAAC,CAAC;AAEH,iGAAiG;AACjG,SAAS,IAAI,CAAC,IAAU,EAAE,KAAsD;IAC9E,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QAChD,KAAK,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,C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AC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,OAAO,CAAC,IAAI,CAAC,CAAC;QAChG,CAAC;KACF,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAClB,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { parseSync, Visitor, type ESTree } from 'vite';\n\n/** A source range in the importer. */\nexport interface Range {\n start: number;\n end: number;\n}\n\n/** A `loadAsync(...args)` of a cached loader that discovery found, which warming repeats on a `new` loader in Node. */\nexport interface Load {\n importer: string;\n /** Where in the importer the load is, as `line:column`. */\n position: string;\n source: string;\n name: string;\n /** Each argument's source: JSON written as JavaScript literals, and inline functions. */\n args: Range[];\n /** The functions passed inline among the arguments, which warming repeats from their source. */\n functions: Range[];\n}\n\n/** An AST node, walked generically by its properties. */\ntype Node = { type: string; start: number; end: number; [key: string]: unknown };\n\nconst isNode = (value: unknown): value is Node =>\n typeof value === 'object' && value !== null && typeof (value as { type?: unknown }).type === 'string';\n\n/** TypeScript nodes that hold a value; other TypeScript nodes are types, which name nothing at runtime. */\nconst values = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSNonNullExpression',\n 'TSTypeAssertion',\n 'TSInstantiationExpression',\n 'TSParameterProperty',\n]);\n\n/** Visits every node below `node` outside types, with the parent and the property holding it. */\nfunction walk(node: Node, visit: (node: Node, parent: Node, key: string) => void): void {\n for (const [key, child] of Object.entries(node)) {\n for (const item of [child].flat()) {\n if (!isNode(item) || (item.type.startsWith('TS') && !values.has(item.type))) continue;\n visit(item, node, key);\n walk(item, visit);\n }\n }\n}\n\n/** A root holding `node`, so that walking it visits `node` too. */\nconst holding = (node: Node): Node => ({ type: 'Program', start: node.start, end: node.end, body: [node] });\n\n/** The names a binding pattern declares. */\nfunction bound(pattern: unknown, names: Set<string>): void {\n if (!isNode(pattern)) return;\n if (pattern.type === 'Identifier') names.add(pattern.name as string);\n else if (pattern.type === 'ObjectPattern')\n for (const property of pattern.properties as Node[])\n bound(property.type === 'RestElement' ? property.argument : property.value, names);\n else if (pattern.type === 'ArrayPattern') for (const element of pattern.elements as unknown[]) bound(element, names);\n else if (pattern.type === 'AssignmentPattern') bound(pattern.left, names);\n else if (pattern.type === 'RestElement') bound(pattern.argument, names);\n else if (pattern.type === 'TSParameterProperty') bound(pattern.parameter, names);\n}\n\n/** Every name declared below `node`, in any scope. */\nfunction declared(node: Node): Set<string> {\n const names = new Set<string>();\n walk(node, (child) => {\n if (child.type === 'VariableDeclarator') bound(child.id, names);\n else if (child.type === 'CatchClause') bound(child.param, names);\n else if (/^Import\\w*Specifier$/.test(child.type)) bound(child.local, names);\n else if (/Function|Class|^TS(Enum|Module)Declaration$|^TSImportEquals/.test(child.type)) bound(child.id, names);\n if (/Function/.test(child.type)) for (const param of (child.params as unknown[]) ?? []) bound(param, names);\n });\n return names;\n}\n\n/** Whether an identifier at this place names a variable, rather than a property, label or meta property. */\nfunction referenced(parent: Node, key: string): boolean {\n if (parent.computed !== true && key === 'key') return false;\n if (parent.type === 'MemberExpression' && key === 'property' && parent.computed !== true) return false;\n return key !== 'label' && parent.type !== 'MetaProperty';\n}\n\n/**\n * The convention that marks a class as a cached loader: its loadAsync computes a result once and saves it. Warming\n * constructs it without arguments, so only loadAsync's arguments, and in a public file its path, may select the result.\n */\nconst loader = /^Cached\\w*Loader$/;\n\n/**\n * The cached loader loads in a module: `new Loader(...).loadAsync(...)`, or `loadAsync(...)` on a variable initialized\n * with `new Loader(...)`. Any other use of a loader or such a variable fails, since warming could not repeat it.\n */\nexport function discover(code: string, importer: string): Load[] {\n const at = (offset: number) => {\n const lines = code.slice(0, offset).split('\\n');\n return `${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}`;\n };\n const fail = (message: string, offset: number): never => {\n throw new Error(`${message} at ${importer}:${at(offset)}`);\n };\n // .glts asset scripts are TypeScript.\n const { program, errors } = parseSync(importer, code, importer.endsWith('.glts') ? { lang: 'ts' } : undefined);\n if (errors[0]) fail(errors[0].message, errors[0].labels[0]?.start ?? 0);\n const imports = new Map<string, { source: string; name: string }>();\n const namespaces = new Map<string, string>();\n for (const statement of program.body) {\n if (statement.type !== 'ImportDeclaration') continue;\n for (const specifier of statement.specifiers) {\n if (specifier.type === 'ImportNamespaceSpecifier') namespaces.set(specifier.local.name, statement.source.value);\n if (specifier.type !== 'ImportSpecifier') continue;\n const name = specifier.imported.type === 'Literal' ? specifier.imported.value : specifier.imported.name;\n if (loader.test(name)) imports.set(specifier.local.name, { source: statement.source.value, name });\n }\n }\n /** Nodes that name a loader or loader variable without using its value. */\n const allowed = new Set<ESTree.Node>();\n /** Names declared anywhere in the module, which an inline function must not use from outside itself. */\n const context = declared(program as unknown as Node);\n /** Checks that a function uses no variable of its module, so that warming can repeat it from its source alone. */\n const inline = (node: Node): Range => {\n const own = declared(holding(node));\n walk(holding(node), (child, parent, key) => {\n if (child.type !== 'Identifier' || !referenced(parent, key)) return;\n const name = child.name as string;\n if (context.has(name) && !own.has(name))\n fail(`Inline functions in cached loader loads must not use ${name} from their module`, child.start);\n });\n return { start: node.start, end: node.end };\n };\n /** JSON written as JavaScript literals, and inline functions, which it collects. */\n const literal = (node: Node, functions: Range[]): void => {\n const nested = (child: unknown) => literal(child as Node, functions);\n const invalid = () =>\n fail('Cached loader loadAsync arguments must be literal JSON or inline functions', node.start);\n switch (node.type) {\n case 'ArrowFunctionExpression':\n case 'FunctionExpression':\n return void functions.push(inline(node));\n case 'ParenthesizedExpression':\n return nested(node.expression);\n case 'Literal':\n if (node.value === null || ['string', 'number', 'boolean'].includes(typeof node.value)) return;\n return invalid();\n case 'UnaryExpression':\n if (/^[-+]$/.test(node.operator as string) && isNode(node.argument) && typeof node.argument.value === 'number')\n return;\n return invalid();\n case 'ArrayExpression':\n for (const element of node.elements as unknown[]) {\n if (!isNode(element) || element.type === 'SpreadElement') invalid();\n nested(element);\n }\n return;\n case 'ObjectExpression':\n for (const property of node.properties as Node[]) {\n const { type, kind, method, shorthand, computed } = property;\n if (type !== 'Property' || kind !== 'init' || method || shorthand || computed) invalid();\n nested(property.value);\n }\n return;\n default:\n return invalid();\n }\n };\n const target = (node: ESTree.Node) => {\n if (node.type === 'Identifier') return imports.get(node.name);\n if (node.type !== 'MemberExpression' || node.computed || node.object.type !== 'Identifier') return undefined;\n const source = namespaces.get(node.object.name);\n return source !== undefined && loader.test(node.property.name) ? { source, name: node.property.name } : undefined;\n };\n const created = (node: ESTree.NewExpression) => {\n const loaded = target(node.callee);\n if (loaded) allowed.add(node.callee);\n return loaded;\n };\n // A first pass, since a variable can be used above its declaration, as in a function declared earlier.\n const instances = new Map<string, { source: string; name: string }>();\n new Visitor({\n VariableDeclarator(node) {\n if (node.id.type !== 'Identifier' || node.init?.type !== 'NewExpression') return;\n const instance = created(node.init);\n if (!instance) return;\n instances.set(node.id.name, instance);\n allowed.add(node.id);\n },\n }).visit(program);\n const member = (node: { computed: boolean; key: ESTree.Node }) => {\n if (!node.computed) allowed.add(node.key);\n };\n const misused = (node: ESTree.Node) =>\n fail('Use cached loaders only as new Loader().loadAsync(), or a variable of one', node.start);\n const loads: Load[] = [];\n new Visitor({\n ImportSpecifier: (node) => allowed.add(node.local).add(node.imported),\n // Loads through an exported loader variable happen in other modules, out of discovery's reach.\n ExportSpecifier(node) {\n if (node.local.type === 'Identifier' && instances.has(node.local.name)) misused(node);\n allowed.add(node.local).add(node.exported);\n },\n ExportNamedDeclaration(node) {\n if (node.declaration?.type !== 'VariableDeclaration') return;\n for (const { id } of node.declaration.declarations)\n if (id.type === 'Identifier' && instances.has(id.name)) misused(id);\n },\n Property(node) {\n if (!node.shorthand) member(node);\n },\n MethodDefinition: member,\n PropertyDefinition: member,\n CallExpression(node) {\n const { callee } = node;\n if (callee.type !== 'MemberExpression' || callee.computed || callee.property.name !== 'loadAsync') return;\n const { object } = callee;\n const instance =\n object.type === 'NewExpression'\n ? created(object)\n : object.type === 'Identifier'\n ? instances.get(object.name)\n : undefined;\n if (!instance) return;\n allowed.add(object);\n const functions: Range[] = [];\n for (const argument of node.arguments) literal(argument as unknown as Node, functions);\n const args = node.arguments.map(({ start, end }) => ({ start, end }));\n loads.push({ importer, position: at(node.start), ...instance, args, functions });\n },\n MemberExpression(node) {\n if (!node.computed) allowed.add(node.property);\n if (target(node) && !allowed.has(node)) misused(node);\n },\n Identifier(node) {\n if ((imports.has(node.name) || instances.has(node.name)) && !allowed.has(node)) misused(node);\n },\n }).visit(program);\n return loads;\n}\n"]}
package/dist/disk.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { Recorded } from './inputs.js';
3
+ /** What a load uses while the plugin warms it, each input as it was when the load got it. */
4
+ export interface Warming {
5
+ /** The public files publicURL gave it. */
6
+ files: Recorded[];
7
+ /** The modules it has run, an installed package's as its package.json, as the module runner fetched them. */
8
+ modules: () => Recorded[];
9
+ }
10
+ declare global {
11
+ /**
12
+ * The cache plugin's project in this Node process, which CacheEntry and publicURL use when given no root, the
13
+ * keys loaded since its latest pass started, which it prunes by, and what the load it is warming uses. Set when its
14
+ * config resolves and kept for the process; global, because Vite's module runner gives loaders their own copy of
15
+ * cache. One plugin per process: a newer one, as a restarted dev server makes, takes it over, and an older one's
16
+ * passes then prune nothing.
17
+ */
18
+ var drawcallCache: {
19
+ root: string;
20
+ publicDir: string;
21
+ loaded: Set<string>;
22
+ warming: AsyncLocalStorage<Warming>;
23
+ } | undefined;
24
+ }
25
+ /** The cache directory's name in publicDir, which is also its URL below Vite's base. */
26
+ export declare const cacheName = "_cache";
27
+ export declare function missing(error: unknown): boolean;
28
+ /** The file's bytes, or undefined when it does not exist. */
29
+ export declare function read(path: string): Promise<Uint8Array | undefined>;
package/dist/disk.js ADDED
@@ -0,0 +1,19 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ /** The cache directory's name in publicDir, which is also its URL below Vite's base. */
3
+ export const cacheName = '_cache';
4
+ export function missing(error) {
5
+ return error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR');
6
+ }
7
+ /** The file's bytes, or undefined when it does not exist. */
8
+ export async function read(path) {
9
+ try {
10
+ // A plain Uint8Array owning its buffer, as a browser's response gives, rather than a Buffer.
11
+ return new Uint8Array(await readFile(path));
12
+ }
13
+ catch (error) {
14
+ if (missing(error))
15
+ return undefined;
16
+ throw error;
17
+ }
18
+ }
19
+ //# sourceMappingURL=disk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"disk.js","sourceRoot":"","sources":["../src/disk.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAwB5C,wFAAwF;AACxF,MAAM,CAAC,MAAM,SAAS,GAAG,QAAQ,CAAC;AAElC,MAAM,UAAU,OAAO,CAAC,KAAc;IACpC,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;AAC5G,CAAC;AAED,6DAA6D;AAC7D,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,IAAY;IACrC,IAAI,CAAC;QACH,6FAA6F;QAC7F,OAAO,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC9C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,SAAS,CAAC;QACrC,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type { AsyncLocalStorage } from 'node:async_hooks';\nimport { readFile } from 'node:fs/promises';\nimport type { Recorded } from './inputs.js';\n\n/** What a load uses while the plugin warms it, each input as it was when the load got it. */\nexport interface Warming {\n /** The public files publicURL gave it. */\n files: Recorded[];\n /** The modules it has run, an installed package's as its package.json, as the module runner fetched them. */\n modules: () => Recorded[];\n}\n\ndeclare global {\n /**\n * The cache plugin's project in this Node process, which CacheEntry and publicURL use when given no root, the\n * keys loaded since its latest pass started, which it prunes by, and what the load it is warming uses. Set when its\n * config resolves and kept for the process; global, because Vite's module runner gives loaders their own copy of\n * cache. One plugin per process: a newer one, as a restarted dev server makes, takes it over, and an older one's\n * passes then prune nothing.\n */\n var drawcallCache:\n | { root: string; publicDir: string; loaded: Set<string>; warming: AsyncLocalStorage<Warming> }\n | undefined;\n}\n\n/** The cache directory's name in publicDir, which is also its URL below Vite's base. */\nexport const cacheName = '_cache';\n\nexport function missing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR');\n}\n\n/** The file's bytes, or undefined when it does not exist. */\nexport async function read(path: string): Promise<Uint8Array | undefined> {\n try {\n // A plain Uint8Array owning its buffer, as a browser's response gives, rather than a Buffer.\n return new Uint8Array(await readFile(path));\n } catch (error) {\n if (missing(error)) return undefined;\n throw error;\n }\n}\n"]}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A file (a root-relative path, or on save() a `file:` URL) or an installed package, whose current state an entry is
3
+ * checked against.
4
+ */
5
+ export type Input = {
6
+ readonly path: string;
7
+ } | {
8
+ readonly package: string;
9
+ };
10
+ /** A function a load passes inline, which the cache plugin tags with its identity, which keys count it as. */
11
+ export type LoadFunction = (...args: never[]) => unknown;
12
+ /** JSON, which can hold functions that loads pass inline. */
13
+ export type Value = null | boolean | number | string | LoadFunction | readonly Value[] | {
14
+ readonly [key: string]: Value;
15
+ };
16
+ /** A value selects which result an entry holds; an input invalidates it when it changes. */
17
+ export type Dependency = {
18
+ readonly value: Value;
19
+ } | Input;
20
+ export interface CacheEntryOptions {
21
+ /** Identifies the computation and its implementation, for example "simplify@2". */
22
+ version: string;
23
+ /** Named dependencies. Names and declarations make up the entry's key; file contents and package versions do not. */
24
+ dependencies?: Readonly<Record<string, Dependency>>;
25
+ /**
26
+ * Node: the project root, whose public/_cache is the cache directory. Defaults to the Vite project, and its
27
+ * publicDir, while the cache plugin runs, else to process.cwd().
28
+ */
29
+ root?: string;
30
+ /** Browsers: the URL the cache directory is served at, including any Vite base. Defaults to /_cache/. */
31
+ basePath?: string;
32
+ }
33
+ export interface SaveOptions {
34
+ /** Inputs the computation turned out to read. Checked on every load like declared ones, without changing the key. */
35
+ dependencies?: readonly Input[];
36
+ }
37
+ /** The entry's name in the cache directory. Functions count as their identity. */
38
+ export declare function key(options: CacheEntryOptions): string;
package/dist/entry.js ADDED
@@ -0,0 +1,29 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ import { bytesToHex } from '@noble/hashes/utils.js';
3
+ import { configure } from 'safe-stable-stringify';
4
+ /**
5
+ * A function's identity, the SHA-256 of its importer's path and its source, which the plugin tags inline load arguments
6
+ * with under the global symbol `@drawcall/cache.function`.
7
+ */
8
+ function identity(value) {
9
+ const id = Reflect.get(value, Symbol.for('@drawcall/cache.function'));
10
+ if (typeof id !== 'string')
11
+ throw new TypeError('cache values can hold only functions passed inline to a load the plugin finds.');
12
+ return id;
13
+ }
14
+ /** JSON with sorted object keys, so that declaration order does not change the key; anything else throws. */
15
+ const stringify = configure({ strict: true });
16
+ /** The entry's name in the cache directory. Functions count as their identity. */
17
+ export function key(options) {
18
+ if (!options.version)
19
+ throw new TypeError('CacheEntry requires a version.');
20
+ for (const [name, dependency] of Object.entries(options.dependencies ?? {}))
21
+ if ('path' in dependency && dependency.path.startsWith('file:'))
22
+ throw new TypeError(`CacheEntry dependency ${name} is a file: URL, which would key differently per machine and in browsers. ` +
23
+ 'Pass it to save() instead.');
24
+ const declaration = stringify({ version: options.version, dependencies: options.dependencies ?? {} }, (_, value) => (typeof value === 'function' ? { function: identity(value) } : value));
25
+ if (declaration === undefined)
26
+ throw new TypeError('cache cannot key this declaration.');
27
+ return bytesToHex(sha256(new TextEncoder().encode(declaration)));
28
+ }
29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,CAAC,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,KAAqB,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAC7G,CAAC;IACF,IAAI,WAAW,KAAK,SAAS;QAAE,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;IACzF,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { configure } from 'safe-stable-stringify';\n\n/**\n * A file (a root-relative path, or on save() a `file:` URL) or an installed package, whose current state an entry is\n * checked against.\n */\nexport type Input = { readonly path: string } | { readonly package: string };\n\n/** A function a load passes inline, which the cache plugin tags with its identity, which keys count it as. */\nexport type LoadFunction = (...args: never[]) => unknown;\n\n/** JSON, which can hold functions that loads pass inline. */\nexport type Value =\n | null\n | boolean\n | number\n | string\n | LoadFunction\n | readonly Value[]\n | { readonly [key: string]: Value };\n\n/** A value selects which result an entry holds; an input invalidates it when it changes. */\nexport type Dependency = { readonly value: Value } | Input;\n\nexport interface CacheEntryOptions {\n /** Identifies the computation and its implementation, for example \"simplify@2\". */\n version: string;\n /** Named dependencies. Names and declarations make up the entry's key; file contents and package versions do not. */\n dependencies?: Readonly<Record<string, Dependency>>;\n /**\n * Node: the project root, whose public/_cache is the cache directory. Defaults to the Vite project, and its\n * publicDir, while the cache plugin runs, else to process.cwd().\n */\n root?: string;\n /** Browsers: the URL the cache directory is served at, including any Vite base. Defaults to /_cache/. */\n basePath?: string;\n}\n\nexport interface SaveOptions {\n /** Inputs the computation turned out to read. Checked on every load like declared ones, without changing the key. */\n dependencies?: readonly Input[];\n}\n\n/**\n * A function's identity, the SHA-256 of its importer's path and its source, which the plugin tags inline load arguments\n * with under the global symbol `@drawcall/cache.function`.\n */\nfunction identity(value: LoadFunction): string {\n const id: unknown = Reflect.get(value, Symbol.for('@drawcall/cache.function'));\n if (typeof id !== 'string')\n throw new TypeError('cache values can hold only functions passed inline to a load the plugin finds.');\n return id;\n}\n\n/** JSON with sorted object keys, so that declaration order does not change the key; anything else throws. */\nconst stringify = configure({ strict: true });\n\n/** The entry's name in the cache directory. Functions count as their identity. */\nexport function key(options: CacheEntryOptions): string {\n if (!options.version) throw new TypeError('CacheEntry requires a version.');\n for (const [name, dependency] of Object.entries(options.dependencies ?? {}))\n if ('path' in dependency && dependency.path.startsWith('file:'))\n throw new TypeError(\n `CacheEntry dependency ${name} is a file: URL, which would key differently per machine and in browsers. ` +\n 'Pass it to save() instead.',\n );\n const declaration = stringify(\n { version: options.version, dependencies: options.dependencies ?? {} },\n (_, value: unknown) => (typeof value === 'function' ? { function: identity(value as LoadFunction) } : value),\n );\n if (declaration === undefined) throw new TypeError('cache cannot key this declaration.');\n return bytesToHex(sha256(new TextEncoder().encode(declaration)));\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { Input } from './entry.js';
2
+ /** An input and its state when it was read: a file's hash or a package's version, undefined when it has neither. */
3
+ export interface Recorded {
4
+ dependency: Input;
5
+ state: string | undefined;
6
+ }
7
+ /** The state of a file with these bytes. */
8
+ export declare function hashOf(bytes: Uint8Array): string;
9
+ /** The current state of each input, a path read below `root`. */
10
+ export declare function record(root: string, inputs: readonly Input[]): Promise<Recorded[]>;
11
+ /**
12
+ * Whether the entry `key` in `directory` was saved from inputs that are all unchanged below `root`, and, given
13
+ * `warmed`, while the plugin warmed its load.
14
+ */
15
+ export declare function current(root: string, directory: string, key: string, warmed: boolean): Promise<boolean>;