@slotform/vite 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,167 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { builtinModules } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import type { Plugin } from "vite";
5
+ import { z } from "zod";
6
+
7
+ // Why the optimizer needs these includes: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
8
+
9
+ const SOURCE = /^\.\/src\/.+\.(?:[cm]?[jt]sx?)$/;
10
+ const SUFFIXES = ["", ".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.js"];
11
+ const BUILTINS = new Set(builtinModules);
12
+
13
+ // The first directory up from `from` that holds `node_modules/<name>`.
14
+ function findPackage(name: string, from: string): string | undefined {
15
+ for (let dir = resolve(from); ; dir = dirname(dir)) {
16
+ const found = join(dir, "node_modules", name);
17
+ if (existsSync(join(found, "package.json"))) return realpathSync(found);
18
+ if (dirname(dir) === dir) return undefined;
19
+ }
20
+ }
21
+
22
+ // A malformed `exports` (a string or array shorthand) reads as no subpaths.
23
+ const manifestSchema = z.object({
24
+ exports: z.record(z.string(), z.unknown()).optional().catch(undefined),
25
+ });
26
+
27
+ // A subpath's file: a string target, or the `default`/`import` of a condition map.
28
+ function targetOf(value: unknown): string | undefined {
29
+ if (typeof value === "string") return value;
30
+ if (value && typeof value === "object") {
31
+ return targetOf(
32
+ Reflect.get(value, "default") ?? Reflect.get(value, "import"),
33
+ );
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ // The file a relative specifier names: as written, with a suffix, or a `.js`
39
+ // spelling of a TypeScript source.
40
+ function localFile(from: string, specifier: string): string | undefined {
41
+ const base = resolve(dirname(from), specifier);
42
+ const stem = base.replace(/\.[cm]?js$/, "");
43
+ return [base, stem]
44
+ .flatMap((path) => SUFFIXES.map((suffix) => path + suffix))
45
+ .find((path) => {
46
+ try {
47
+ return statSync(path).isFile();
48
+ } catch (err) {
49
+ if (isAbsent(err)) return false;
50
+ throw err;
51
+ }
52
+ });
53
+ }
54
+
55
+ // A missing path, or a file where a directory should be: the not-found answers.
56
+ function isAbsent(err: unknown): boolean {
57
+ const code = err instanceof Error && "code" in err ? err.code : undefined;
58
+ return code === "ENOENT" || code === "ENOTDIR";
59
+ }
60
+
61
+ function read(file: string): string {
62
+ try {
63
+ return readFileSync(file, "utf8");
64
+ } catch (err) {
65
+ if (isAbsent(err)) return "";
66
+ throw err;
67
+ }
68
+ }
69
+
70
+ const COMMENTS = /\/\*[\s\S]*?\*\/|(?<![:"'`\\])\/\/.*$/gm;
71
+ const IMPORTS =
72
+ /(?:\b(?:import|export)(?!\s+type\b)[^'"`;]*?\bfrom\s*|\bimport\s*\(?\s*)["']([^"']+)["']/g;
73
+
74
+ // The module specifiers a file writes: static and dynamic imports, re-exports.
75
+ export function importsOf(source: string): string[] {
76
+ return [...source.replace(COMMENTS, "").matchAll(IMPORTS)].flatMap((match) =>
77
+ match[1] ? [match[1]] : [],
78
+ );
79
+ }
80
+
81
+ function packageOf(specifier: string): string {
82
+ const parts = specifier.split("/");
83
+ return specifier.startsWith("@")
84
+ ? parts.slice(0, 2).join("/")
85
+ : (parts[0] ?? "");
86
+ }
87
+
88
+ // What the raw source of each excluded entry imports from outside it, for
89
+ // `optimizeDeps.include`. An entry is a package (all its raw source exports
90
+ // `./src/*`) or one of its subpaths (that export alone). A file's own package
91
+ // is followed into where the entry is the whole package, and otherwise named
92
+ // as it is (the optimizer bundles that subpath and what it imports); any other
93
+ // package is `entry package > specifier`. A package that is not installed, an
94
+ // import that does not resolve from the importer (an optional peer that is
95
+ // absent) and the names in `skip` (the app's singletons, which its own scan
96
+ // finds) are left out.
97
+ export function excludedImports(
98
+ excluded: readonly string[],
99
+ root: string,
100
+ skip: ReadonlySet<string> = new Set(),
101
+ ): string[] {
102
+ const found = new Set<string>();
103
+ for (const entry of excluded) {
104
+ const name = packageOf(entry);
105
+ const dir = findPackage(name, root);
106
+ if (!dir) continue;
107
+ const manifest = manifestSchema.parse(
108
+ JSON.parse(read(join(dir, "package.json")) || "{}"),
109
+ );
110
+ const subpaths = manifest.exports ?? {};
111
+ const whole = entry === name;
112
+ const isExcluded = (specifier: string): boolean =>
113
+ excluded.some((e) => specifier === e || specifier.startsWith(`${e}/`));
114
+ const files = new Set<string>();
115
+ const visit = (file: string): void => {
116
+ if (files.has(file)) return;
117
+ files.add(file);
118
+ for (const specifier of importsOf(read(file))) {
119
+ if (specifier.startsWith(".")) {
120
+ const own = localFile(file, specifier);
121
+ if (own) visit(own);
122
+ continue;
123
+ }
124
+ if (specifier.startsWith("node:") || BUILTINS.has(specifier)) continue;
125
+ // A `virtual:` module is served by a Vite plugin: no file to read.
126
+ if (specifier.startsWith("virtual:")) continue;
127
+ const owner = packageOf(specifier);
128
+ if (owner === name) {
129
+ if (whole) {
130
+ const target = targetOf(
131
+ subpaths[`.${specifier.slice(name.length)}`],
132
+ );
133
+ if (target) visit(join(dir, target));
134
+ } else if (!isExcluded(specifier)) found.add(specifier);
135
+ continue;
136
+ }
137
+ if (isExcluded(specifier) || skip.has(owner)) continue;
138
+ if (findPackage(owner, dir)) found.add(`${name} > ${specifier}`);
139
+ }
140
+ };
141
+ const seeds = whole
142
+ ? Object.values(subpaths)
143
+ .map(targetOf)
144
+ .filter((target) => target && SOURCE.test(target))
145
+ : [targetOf(subpaths[`.${entry.slice(name.length)}`])];
146
+ for (const target of seeds) if (target) visit(join(dir, target));
147
+ }
148
+ return [...found].sort();
149
+ }
150
+
151
+ // Adds `excludedImports` of the config's `optimizeDeps.exclude` to
152
+ // `optimizeDeps.include`, so the optimizer bundles them at start.
153
+ export function excludedImportsPlugin(): Plugin {
154
+ return {
155
+ name: "fcalell:excluded-imports",
156
+ config: (config) => {
157
+ const exclude = config.optimizeDeps?.exclude ?? [];
158
+ if (exclude.length === 0) return undefined;
159
+ const include = excludedImports(
160
+ exclude,
161
+ config.root ?? process.cwd(),
162
+ new Set(config.resolve?.dedupe ?? []),
163
+ );
164
+ return include.length > 0 ? { optimizeDeps: { include } } : undefined;
165
+ },
166
+ };
167
+ }
@@ -0,0 +1,2 @@
1
+ export type { ServerProxyEntry, ViteConfigValues } from "../types.ts";
2
+ export { renderViteConfig } from "./codegen.ts";
@@ -0,0 +1,46 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { GENERATED_DIR } from "@slotform/cli";
4
+ import type { Plugin } from "vite";
5
+
6
+ export { excludedImportsPlugin } from "./excluded.ts";
7
+
8
+ // A virtual module served by the generated file once `slotform generate` wrote
9
+ // it, by `fallback` before. The path resolves against the working directory,
10
+ // the consumer root every `slotform` command runs Vite from.
11
+ function virtualModule(id: string, file: string, fallback: string): Plugin {
12
+ const resolved = `\0${id}`;
13
+ const path = resolve(file);
14
+ return {
15
+ name: `fcalell:${id.replace("virtual:", "")}`,
16
+
17
+ resolveId(source) {
18
+ if (source !== id) return null;
19
+ if (existsSync(path)) return path;
20
+ return resolved;
21
+ },
22
+
23
+ load(source) {
24
+ if (source !== resolved) return null;
25
+ return fallback;
26
+ },
27
+ };
28
+ }
29
+
30
+ // `virtual:slotform-providers` and its pass-through stub: docs/architecture/plugins/vite.md, "Preset".
31
+ export function providersPlugin(): Plugin {
32
+ return virtualModule(
33
+ "virtual:slotform-providers",
34
+ `${GENERATED_DIR}/virtual-providers.tsx`,
35
+ "export default function Providers(props) {\n\treturn props.children;\n}\n",
36
+ );
37
+ }
38
+
39
+ // `virtual:slotform-schema`: docs/architecture/plugins/vite.md, "Preset".
40
+ export function schemaPlugin(): Plugin {
41
+ return virtualModule(
42
+ "virtual:slotform-schema",
43
+ `${GENERATED_DIR}/schema.ts`,
44
+ "export const SCHEMA = {};\n",
45
+ );
46
+ }
package/src/types.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { TsExpression, TsImportSpec } from "@slotform/cli/ast";
2
+ import { z } from "zod";
3
+
4
+ // Restart policy for vite's dev process. Defaults to "never" because vite
5
+ // already handles HMR; restarting on crash usually masks the underlying bug.
6
+ // Exposed so a consumer can opt into "on-crash" / "always" if they have a
7
+ // reason (e.g. flaky upstream dependency).
8
+ const restartPolicySchema = z.enum(["never", "on-crash", "always"]);
9
+
10
+ export const viteOptionsSchema = z.object({
11
+ port: z.number().int().min(1).max(65535).optional(),
12
+ restart: restartPolicySchema.optional(),
13
+ maxRestarts: z.number().int().min(0).optional(),
14
+ });
15
+
16
+ export type ViteOptions = z.input<typeof viteOptionsSchema>;
17
+
18
+ // `ws: true` also forwards WebSocket upgrades.
19
+ export interface ServerProxyEntry {
20
+ path: string;
21
+ target: string;
22
+ ws?: boolean;
23
+ }
24
+
25
+ // A plugin call with the imports it needs, for `vite.slots.appPlugins`.
26
+ export interface AppPlugin {
27
+ call: TsExpression;
28
+ imports: TsImportSpec[];
29
+ }
30
+
31
+ // The resolved values of vite's input slots, one field per slot under the
32
+ // slot's own name: `renderViteConfig` takes them as `graph.resolve` returns
33
+ // them, so a caller adjusts one field and passes the rest through.
34
+ export interface ViteConfigValues {
35
+ configImports: TsImportSpec[];
36
+ pluginCalls: TsExpression[];
37
+ resolveAliases: Array<{ find: string; replacement: string }>;
38
+ // `resolve.dedupe` specifiers: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
39
+ resolveDedupe: string[];
40
+ // `optimizeDeps.exclude` packages: docs/architecture/plugins/vite.md, "Singletons and the optimizer".
41
+ optimizeExclude: string[];
42
+ devServerPort: number;
43
+ // The client build's output directory, relative to the project root.
44
+ outDir: string;
45
+ serverProxy: ServerProxyEntry[];
46
+ // Extra `server.fs.allow` path expressions. Any entry switches the
47
+ // rendered config to an explicit allow list, so the renderer prepends
48
+ // the consumer's own workspace root (Vite disables its auto-detection
49
+ // the moment a custom list is set).
50
+ fsAllow: TsExpression[];
51
+ // Globs rendered into `server.watch.ignored`, which Vite adds to its own
52
+ // defaults (`.git`, `node_modules`, its cache dir).
53
+ watchIgnored: string[];
54
+ // Headers rendered into `server.headers`, names sorted.
55
+ clientHeaders: Record<string, string>;
56
+ }