@timefoldai/viz-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { randomBytes } from "node:crypto";
4
+ import {
5
+ copyFileSync,
6
+ existsSync,
7
+ mkdtempSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ realpathSync,
11
+ rmSync,
12
+ statSync,
13
+ } from "node:fs";
14
+ import { createRequire } from "node:module";
15
+ import { tmpdir } from "node:os";
16
+ import { basename, dirname, join, relative, resolve } from "node:path";
17
+ import process from "node:process";
18
+ import { pathToFileURL } from "node:url";
19
+ import { parseArgs } from "node:util";
20
+
21
+ import { runBin } from "./run-bin.mjs";
22
+
23
+ const MIN_ARTIFACT_SCAN_LENGTH = 8;
24
+
25
+ const BUILD_MODE = "production";
26
+
27
+ const BUILD_NODE_ENV = "production";
28
+
29
+ const DEFAULT_OUT_DIR = "dist";
30
+
31
+ const EXTRA_OUTPUT_DIRS = ["storybook-static"];
32
+
33
+ class GuardFailure extends Error {}
34
+
35
+ function selectLocal(repoRoot, paths) {
36
+ return paths.filter((path) => {
37
+ const { status, stderr } = spawnSync(
38
+ "git",
39
+ ["ls-files", "--error-unmatch", "--", path],
40
+ { cwd: repoRoot, encoding: "utf8" },
41
+ );
42
+
43
+ if (status !== 0 && status !== 1) {
44
+ throw new GuardFailure(
45
+ `git ls-files --error-unmatch ${path} failed (status ${status}): ${stderr}`,
46
+ );
47
+ }
48
+
49
+ return status === 1;
50
+ });
51
+ }
52
+
53
+ async function appEnvOptions(dir) {
54
+ const require = createRequire(join(dir, "package.json"));
55
+
56
+ try {
57
+ const vite = await import(pathToFileURL(require.resolve("vite")).href);
58
+ const config = await vite.resolveConfig(
59
+ { root: dir, mode: BUILD_MODE, logLevel: "silent" },
60
+ "build",
61
+ BUILD_MODE,
62
+ BUILD_NODE_ENV,
63
+ );
64
+
65
+ return {
66
+ loadEnv: vite.loadEnv,
67
+ envDir: config.envDir,
68
+ prefixes: vite.resolveEnvPrefix(config),
69
+ };
70
+ } catch (error) {
71
+ throw new GuardFailure(
72
+ `could not resolve the vite config of ${dir}, so the guard cannot tell which env files ` +
73
+ `and keys a build reads: ${error.message}`,
74
+ );
75
+ }
76
+ }
77
+
78
+ function localEnvValues(env, localEnvFiles, committedEnvFiles) {
79
+ if (localEnvFiles.length === 0) return [];
80
+
81
+ const resolved = env.loadEnv(BUILD_MODE, env.envDir, env.prefixes);
82
+ const committedOnlyDir = mkdtempSync(join(tmpdir(), "check-env-leak-"));
83
+
84
+ try {
85
+ for (const file of committedEnvFiles) {
86
+ copyFileSync(file, join(committedOnlyDir, basename(file)));
87
+ }
88
+
89
+ const committed = env.loadEnv(
90
+ BUILD_MODE,
91
+ committedOnlyDir,
92
+ env.prefixes,
93
+ );
94
+
95
+ return Object.entries(resolved).filter(
96
+ ([key, value]) => value && committed[key] !== value,
97
+ );
98
+ } finally {
99
+ rmSync(committedOnlyDir, { recursive: true, force: true });
100
+ }
101
+ }
102
+
103
+ const isScannable = (name) =>
104
+ /\.(js|mjs|cjs|css|html|json|map|svg|txt)$/.test(name);
105
+
106
+ function walk(dir, predicate) {
107
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
108
+ const path = join(dir, entry.name);
109
+ if (entry.isDirectory()) return walk(path, predicate);
110
+ return predicate(entry.name) ? [path] : [];
111
+ });
112
+ }
113
+
114
+ const sentinelFor = (key) =>
115
+ `tfEnvLeakProbe${key.replaceAll(/[^A-Za-z0-9]/g, "")}${randomBytes(12).toString("hex")}`;
116
+
117
+ const VITE_CONFIG_NAMES = [
118
+ "vite.config.ts",
119
+ "vite.config.mts",
120
+ "vite.config.js",
121
+ "vite.config.mjs",
122
+ ];
123
+
124
+ function inlinedKeys(dir, keys) {
125
+ if (keys.length === 0) return [];
126
+
127
+ if (!VITE_CONFIG_NAMES.some((name) => existsSync(join(dir, name)))) {
128
+ throw new GuardFailure(
129
+ `${dir} has local env values but no vite config, so the inlining probe cannot run.\n` +
130
+ "Add a vite.config file, or remove the local env file.",
131
+ );
132
+ }
133
+
134
+ const require = createRequire(join(dir, "package.json"));
135
+ const viteBin = join(
136
+ dirname(require.resolve("vite/package.json")),
137
+ "bin",
138
+ "vite.js",
139
+ );
140
+ const sentinels = keys.map((key) => [key, sentinelFor(key)]);
141
+ const outDir = mkdtempSync(join(tmpdir(), "check-env-leak-probe-"));
142
+
143
+ try {
144
+ const { status, stdout, stderr } = spawnSync(
145
+ process.execPath,
146
+ [
147
+ viteBin,
148
+ "build",
149
+ "--mode",
150
+ BUILD_MODE,
151
+ "--outDir",
152
+ outDir,
153
+ "--emptyOutDir",
154
+ "--logLevel",
155
+ "error",
156
+ ],
157
+ {
158
+ cwd: dir,
159
+ encoding: "utf8",
160
+ env: { ...process.env, ...Object.fromEntries(sentinels) },
161
+ },
162
+ );
163
+
164
+ if (status !== 0) {
165
+ throw new GuardFailure(
166
+ `the inlining probe build of ${dir} failed (status ${status}):\n${stdout}${stderr}`,
167
+ );
168
+ }
169
+
170
+ const files = walk(outDir, isScannable).map((path) => ({
171
+ path,
172
+ text: readFileSync(path, "utf8"),
173
+ }));
174
+
175
+ return sentinels
176
+ .filter(([, sentinel]) =>
177
+ files.some((file) => file.text.includes(sentinel)),
178
+ )
179
+ .map(([key]) => key);
180
+ } finally {
181
+ rmSync(outDir, { recursive: true, force: true });
182
+ }
183
+ }
184
+
185
+ const isSearchableSource = (path) =>
186
+ /\.(m?[jt]sx?|c[jt]s|css|html?|json|svg|txt)$/i.test(path) ||
187
+ /(^|\/)\.env(\.|$)/.test(path);
188
+
189
+ function sourceExplainer(repoRoot) {
190
+ let corpus = null;
191
+
192
+ function committedSources() {
193
+ if (corpus) return corpus;
194
+
195
+ const { status, stdout, stderr } = spawnSync(
196
+ "git",
197
+ ["ls-files", "-z", "--full-name"],
198
+ { cwd: repoRoot, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
199
+ );
200
+
201
+ if (status !== 0) {
202
+ throw new GuardFailure(
203
+ `git ls-files failed (status ${status}): ${stderr}`,
204
+ );
205
+ }
206
+
207
+ corpus = stdout
208
+ .split("\0")
209
+ .filter((name) => name && isSearchableSource(name))
210
+ .map((name) => join(repoRoot, name))
211
+ .filter((path) => existsSync(path) && statSync(path).isFile())
212
+ .map((path) => ({ path, text: readFileSync(path, "utf8") }));
213
+
214
+ return corpus;
215
+ }
216
+
217
+ return (value) =>
218
+ committedSources()
219
+ .filter((file) => file.text.includes(value))
220
+ .map((file) => relative(repoRoot, file.path));
221
+ }
222
+
223
+ function gitTopLevel(cwd) {
224
+ const { status, stdout, stderr } = spawnSync(
225
+ "git",
226
+ ["rev-parse", "--show-toplevel"],
227
+ { cwd, encoding: "utf8" },
228
+ );
229
+
230
+ if (status !== 0) {
231
+ throw new GuardFailure(
232
+ `git rev-parse --show-toplevel failed in ${cwd} (status ${status}): ${stderr.trim()}\n` +
233
+ "This guard asks git which env files are local, so the app must sit in a git repository.",
234
+ );
235
+ }
236
+
237
+ return stdout.trim();
238
+ }
239
+
240
+ function appDirectory(positionals) {
241
+ if (positionals.length > 1) {
242
+ throw new GuardFailure(`expected one app directory\n${USAGE}`);
243
+ }
244
+
245
+ const name = positionals[0] ?? ".";
246
+ const dir = resolve(name);
247
+
248
+ if (!existsSync(join(dir, "package.json"))) {
249
+ throw new GuardFailure(
250
+ `${name} has no package.json, so it is not an app directory`,
251
+ );
252
+ }
253
+
254
+ return realpathSync(dir);
255
+ }
256
+
257
+ const USAGE = "usage: viz-check-leaked-env [<appDir>] [--out-dir <dir>]";
258
+
259
+ function parseCli(args) {
260
+ try {
261
+ return parseArgs({
262
+ args,
263
+ allowPositionals: true,
264
+ options: { "out-dir": { type: "string" } },
265
+ });
266
+ } catch (error) {
267
+ if (error.code?.startsWith("ERR_PARSE_ARGS")) {
268
+ throw new GuardFailure(`${error.message}\n${USAGE}`);
269
+ }
270
+
271
+ throw error;
272
+ }
273
+ }
274
+
275
+ function assertExplicitOutDirExists(dir, explicitOutDir) {
276
+ const outDir = resolve(dir, explicitOutDir);
277
+
278
+ if (!existsSync(outDir)) {
279
+ throw new GuardFailure(
280
+ `${outDir} does not exist; build the app first or fix --out-dir`,
281
+ );
282
+ }
283
+ }
284
+
285
+ function envFilesIn(envDir) {
286
+ if (envDir === false || !existsSync(envDir)) return [];
287
+
288
+ return readdirSync(envDir, { withFileTypes: true })
289
+ .filter((entry) => entry.isFile() && entry.name.startsWith(".env"))
290
+ .map((entry) => join(envDir, entry.name));
291
+ }
292
+
293
+ async function checkApp({ dir, repoRoot, explicitOutDir, sourcesExplaining }) {
294
+ if (explicitOutDir !== undefined) {
295
+ assertExplicitOutDirExists(dir, explicitOutDir);
296
+ }
297
+
298
+ const result = { failed: false, checkedKeys: 0, scannedFiles: 0 };
299
+ const label = relative(repoRoot, dir) || ".";
300
+ const env = await appEnvOptions(dir);
301
+ const envCandidates = envFilesIn(env.envDir);
302
+ const localEnvFiles = selectLocal(repoRoot, envCandidates);
303
+ const values = localEnvValues(
304
+ env,
305
+ localEnvFiles,
306
+ envCandidates.filter((path) => !localEnvFiles.includes(path)),
307
+ );
308
+ if (values.length === 0) return result;
309
+ result.checkedKeys = values.length;
310
+
311
+ const leakingKeys = new Set(
312
+ inlinedKeys(
313
+ dir,
314
+ values.map(([key]) => key),
315
+ ),
316
+ );
317
+
318
+ for (const key of leakingKeys) {
319
+ console.error(
320
+ `INLINED ${key} (local env of ${label}) — a production build bakes this key's value into the bundle`,
321
+ );
322
+ result.failed = true;
323
+ }
324
+
325
+ const outputs = [explicitOutDir ?? DEFAULT_OUT_DIR, ...EXTRA_OUTPUT_DIRS]
326
+ .map((name) => resolve(dir, name))
327
+ .filter((path) => existsSync(path));
328
+ if (outputs.length === 0) {
329
+ console.log(
330
+ `check-no-leaked-env: ${label} has a local env file but no built output — only the inlining probe ran`,
331
+ );
332
+ return result;
333
+ }
334
+
335
+ const builtFiles = outputs
336
+ .flatMap((path) => walk(path, isScannable))
337
+ .map((path) => ({ path, text: readFileSync(path, "utf8") }));
338
+ result.scannedFiles = builtFiles.length;
339
+
340
+ for (const [key, value] of values) {
341
+ if (leakingKeys.has(key)) continue;
342
+ if (value.length < MIN_ARTIFACT_SCAN_LENGTH) {
343
+ console.log(
344
+ `check-no-leaked-env: ${key} (${label}) is under ${MIN_ARTIFACT_SCAN_LENGTH} chars — too short to match built output reliably, so only the inlining probe covered it (it did)`,
345
+ );
346
+ continue;
347
+ }
348
+
349
+ const hits = builtFiles.filter((file) => file.text.includes(value));
350
+
351
+ if (hits.length === 0) continue;
352
+
353
+ const explanations = sourcesExplaining(value);
354
+
355
+ if (explanations.length > 0) {
356
+ console.log(
357
+ `check-no-leaked-env: ${key} (${label}) matches ${hits.length} built file(s), but the same string is a literal in committed source (${explanations.join(", ")}) and the probe proved the key is not inlined — not a leak`,
358
+ );
359
+ continue;
360
+ }
361
+
362
+ console.error(
363
+ `LEAKED ${key} (local env of ${label}) into ${hits.map((hit) => hit.path).join(", ")}`,
364
+ );
365
+ result.failed = true;
366
+ }
367
+
368
+ return result;
369
+ }
370
+
371
+ const FAILURE_GUIDANCE =
372
+ "\ncheck-no-leaked-env: FAIL — a local env value can reach, or already sits in, a production bundle.\n" +
373
+ "A production bundle must never carry local config. Three ways to resolve this:\n\n" +
374
+ " * INLINED — a local-dev value: read it only inside an `import.meta.env.DEV` branch,\n" +
375
+ " so the production build strips it.\n" +
376
+ " * INLINED — deployment config that is meant to be inlined: move it out of the local\n" +
377
+ " env file into a committed `.env.production` or a CI environment variable, so the\n" +
378
+ " value in the bundle is a reviewed one.\n" +
379
+ " * LEAKED — the value sits in the built output although the current source cannot inline\n" +
380
+ " it: the output is stale. Delete the output directory and build again, so the bundle\n" +
381
+ " matches the source that was checked.";
382
+
383
+ async function main(args) {
384
+ const { values, positionals } = parseCli(args);
385
+ const dir = appDirectory(positionals);
386
+ const repoRoot = gitTopLevel(dir);
387
+ const { failed, checkedKeys, scannedFiles } = await checkApp({
388
+ dir,
389
+ repoRoot,
390
+ explicitOutDir: values["out-dir"],
391
+ sourcesExplaining: sourceExplainer(repoRoot),
392
+ });
393
+
394
+ if (failed) {
395
+ console.error(FAILURE_GUIDANCE);
396
+ } else {
397
+ console.log(
398
+ checkedKeys === 0
399
+ ? "check-no-leaked-env: OK — no local env value could have been inlined"
400
+ : `check-no-leaked-env: OK — ${checkedKeys} local env key(s) are not inlined by the source and absent from ${scannedFiles} built file(s)`,
401
+ );
402
+ }
403
+
404
+ process.exit(failed ? 1 : 0);
405
+ }
406
+
407
+ async function runCli(args) {
408
+ try {
409
+ await main(args);
410
+ } catch (error) {
411
+ if (!(error instanceof GuardFailure)) throw error;
412
+ console.error(`check-no-leaked-env: FAIL — ${error.message}`);
413
+ process.exit(1);
414
+ }
415
+ }
416
+
417
+ await runBin(import.meta, "check-no-leaked-env", runCli);
@@ -0,0 +1,222 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readlinkSync,
8
+ realpathSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import {
12
+ basename,
13
+ dirname,
14
+ isAbsolute,
15
+ join,
16
+ relative,
17
+ resolve,
18
+ sep,
19
+ } from "node:path";
20
+ import process from "node:process";
21
+ import { isDeepStrictEqual } from "node:util";
22
+
23
+ import openapiTS, { astToString, COMMENT_HEADER } from "openapi-typescript";
24
+
25
+ import { runBin } from "./run-bin.mjs";
26
+
27
+ const SCHEMA_REF = "#/components/schemas/";
28
+
29
+ function schemaName(ref) {
30
+ return ref.startsWith(SCHEMA_REF)
31
+ ? ref.slice(SCHEMA_REF.length)
32
+ : undefined;
33
+ }
34
+
35
+ function referencedSchema(schemas, ref, referrer) {
36
+ const name = schemaName(ref);
37
+ if (name === undefined) return undefined;
38
+ const schema = schemas[name];
39
+ if (schema === undefined) {
40
+ throw new Error(
41
+ `${referrer} references ${ref}, which the spec does not define`,
42
+ );
43
+ }
44
+
45
+ return { name, schema };
46
+ }
47
+
48
+ function listsAsVariant(parent, childName) {
49
+ return (parent.oneOf ?? []).some(
50
+ (variant) => variant.$ref === SCHEMA_REF + childName,
51
+ );
52
+ }
53
+
54
+ function mergeParentInto(child, parent) {
55
+ child.type ??= parent.type;
56
+ child.properties = { ...parent.properties, ...child.properties };
57
+ child.required = [
58
+ ...new Set([...(parent.required ?? []), ...(child.required ?? [])]),
59
+ ];
60
+ }
61
+
62
+ function parentLoops(schemas) {
63
+ return Object.entries(schemas).flatMap(([childName, child]) =>
64
+ (child.allOf ?? []).flatMap((entry) => {
65
+ const parent =
66
+ entry.$ref && referencedSchema(schemas, entry.$ref, childName);
67
+ return parent && listsAsVariant(parent.schema, childName)
68
+ ? [{ childName, child, entry, ...parent }]
69
+ : [];
70
+ }),
71
+ );
72
+ }
73
+
74
+ const PROSE_KEYWORDS = new Set(["description", "externalDocs"]);
75
+
76
+ function propertyShape(property) {
77
+ return Object.fromEntries(
78
+ Object.entries(property).filter(
79
+ ([keyword]) => !PROSE_KEYWORDS.has(keyword),
80
+ ),
81
+ );
82
+ }
83
+
84
+ function assertMergeable({ childName, child, name, schema }) {
85
+ if (schema.allOf !== undefined) {
86
+ throw new Error(
87
+ `${name} is a discriminated parent with its own allOf, which the flattening does not resolve`,
88
+ );
89
+ }
90
+ const discriminator = schema.discriminator?.propertyName;
91
+ for (const [property, parentShape] of Object.entries(
92
+ schema.properties ?? {},
93
+ )) {
94
+ const childShape = child.properties?.[property];
95
+ if (
96
+ property !== discriminator &&
97
+ childShape !== undefined &&
98
+ !isDeepStrictEqual(
99
+ propertyShape(childShape),
100
+ propertyShape(parentShape),
101
+ )
102
+ ) {
103
+ throw new Error(
104
+ `${childName}.${property} differs from ${name}.${property}, so inlining ${name} would drop one of them`,
105
+ );
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Inlines each discriminated parent into the children its `oneOf` lists, in place, so the
112
+ * generated types carry no parent-child cycle. Returns each flattened `{ child, parent }` pair.
113
+ */
114
+ export function flattenDiscriminatedChildren(spec) {
115
+ const loops = parentLoops(spec.components?.schemas ?? {});
116
+ loops.forEach(assertMergeable);
117
+
118
+ for (const { child, entry, schema } of loops) {
119
+ mergeParentInto(child, schema);
120
+ child.allOf = child.allOf.filter((kept) => kept !== entry);
121
+ if (child.allOf.length === 0) delete child.allOf;
122
+ }
123
+
124
+ return loops.map(({ childName, name }) => ({
125
+ child: childName,
126
+ parent: name,
127
+ }));
128
+ }
129
+
130
+ /** Renders a parsed OpenAPI document to the text the `openapi-typescript` CLI writes. */
131
+ export async function renderTypes(spec) {
132
+ return (
133
+ COMMENT_HEADER + astToString(await openapiTS(spec, { silent: true }))
134
+ );
135
+ }
136
+
137
+ async function readSpec(source) {
138
+ const text = /^https?:\/\//.test(source)
139
+ ? await fetchSpec(source)
140
+ : readFileSync(source, "utf8");
141
+ try {
142
+ return JSON.parse(text);
143
+ } catch (error) {
144
+ throw new Error(
145
+ `${source} is not a JSON OpenAPI document: ${error.message}`,
146
+ );
147
+ }
148
+ }
149
+
150
+ async function fetchSpec(url) {
151
+ const response = await fetch(url, {
152
+ headers: { Accept: "application/json" },
153
+ });
154
+ if (!response.ok) {
155
+ throw new Error(
156
+ `${url} answered ${response.status} ${response.statusText}`,
157
+ );
158
+ }
159
+
160
+ return response.text();
161
+ }
162
+
163
+ const USAGE = "usage: viz-codegen <spec url or file> <output .d.ts>";
164
+
165
+ const MAX_SYMLINK_HOPS = 40;
166
+
167
+ function isSymlink(path) {
168
+ return (
169
+ lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() ?? false
170
+ );
171
+ }
172
+
173
+ function realPath(path, hops = 0) {
174
+ const absolute = resolve(path);
175
+ const parent = dirname(absolute);
176
+ if (parent === absolute) return absolute;
177
+ const realParent = realPath(parent, hops);
178
+ if (realParent === null) return null;
179
+ const joined = join(realParent, basename(absolute));
180
+ if (existsSync(joined)) return realpathSync(joined);
181
+ if (!isSymlink(joined)) return joined;
182
+ if (hops === MAX_SYMLINK_HOPS) return null;
183
+
184
+ return realPath(resolve(realParent, readlinkSync(joined)), hops + 1);
185
+ }
186
+
187
+ function isInside(directory, path) {
188
+ const fromDirectory = relative(directory, path);
189
+ return (
190
+ fromDirectory !== "" &&
191
+ fromDirectory !== ".." &&
192
+ !fromDirectory.startsWith(`..${sep}`) &&
193
+ !isAbsolute(fromDirectory)
194
+ );
195
+ }
196
+
197
+ function refuse(reason) {
198
+ console.error(`viz-codegen: FAIL — ${reason}; ${USAGE}`);
199
+ process.exit(1);
200
+ }
201
+
202
+ async function main([source, output]) {
203
+ if (!source || !output) {
204
+ console.error(`viz-codegen: FAIL — ${USAGE}`);
205
+ process.exit(1);
206
+ }
207
+ const target = realPath(output);
208
+ if (target === null) refuse(`${output} is a symlink loop`);
209
+ if (!isInside(realpathSync(process.cwd()), target)) {
210
+ refuse(`${output} is outside the current directory`);
211
+ }
212
+ const spec = await readSpec(source);
213
+ const flattened = flattenDiscriminatedChildren(spec);
214
+ const parents = new Set(flattened.map(({ parent }) => parent));
215
+ mkdirSync(dirname(output), { recursive: true });
216
+ writeFileSync(output, await renderTypes(spec), "utf8");
217
+ console.info(
218
+ `${source} -> ${output} (${flattened.length} children flattened into ${[...parents].join(", ") || "no parent"})`,
219
+ );
220
+ }
221
+
222
+ await runBin(import.meta, "viz-codegen", main);
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The `@layer` order statement that the theme stylesheet resolved from `appDir` opens with.
3
+ * An app declares it before any of its CSS loads.
4
+ *
5
+ * @param themeStylesheet - the module specifier of the theme stylesheet
6
+ */
7
+ export declare function declaredLayerOrder(appDir: string, themeStylesheet?: string): string;
@@ -0,0 +1,17 @@
1
+ import { createRequire } from "node:module";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ // src/layer-order.ts
5
+ /**
6
+ * The `@layer` order statement that the theme stylesheet resolved from `appDir` opens with.
7
+ * An app declares it before any of its CSS loads.
8
+ *
9
+ * @param themeStylesheet - the module specifier of the theme stylesheet
10
+ */
11
+ function declaredLayerOrder(appDir, themeStylesheet = "@timefoldai/viz-react/theme.css") {
12
+ const themeCss = createRequire(path.join(appDir, "package.json")).resolve(themeStylesheet);
13
+ const statement = /^@layer [^;{]+;/m.exec(readFileSync(themeCss, "utf8"))?.[0];
14
+ if (!statement) throw new Error(`${themeCss} has no @layer order statement, such as "@layer theme, base, components, utilities;"`);
15
+ return statement;
16
+ }
17
+ export { declaredLayerOrder };
@@ -0,0 +1,19 @@
1
+ import { PluginOption, UserConfig } from "vite";
2
+ /** The options of the shared Vite config for a model visualisation app. */
3
+ export interface AppViteOptions {
4
+ appDir: string;
5
+ port: number;
6
+ plugins?: PluginOption[];
7
+ alias?: Record<string, string>;
8
+ /** @defaultValue `"@timefoldai/viz-react/theme.css"` */
9
+ themeStylesheet?: string;
10
+ }
11
+ /**
12
+ * The shared Vite config every visualisation app builds on.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * export default appViteConfig({ appDir: import.meta.dirname, port: 5173 });
17
+ * ```
18
+ */
19
+ export declare function appViteConfig({ appDir, port, plugins, alias, themeStylesheet }: AppViteOptions): UserConfig;