ferrovue 0.5.0 → 0.7.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.
Files changed (108) hide show
  1. package/README.md +306 -62
  2. package/dist/args.d.ts +28 -0
  3. package/dist/args.js +69 -0
  4. package/dist/attrs.d.ts +2 -1
  5. package/dist/attrs.js +10 -4
  6. package/dist/calls.js +5 -2
  7. package/dist/children.d.ts +2 -2
  8. package/dist/children.js +84 -16
  9. package/dist/classes.d.ts +4 -0
  10. package/dist/classes.js +23 -1
  11. package/dist/cli.js +80 -81
  12. package/dist/client-render.d.ts +23 -0
  13. package/dist/client-render.js +143 -0
  14. package/dist/client.d.ts +74 -10
  15. package/dist/client.js +373 -42
  16. package/dist/compiler.d.ts +9 -5
  17. package/dist/compiler.js +80 -18
  18. package/dist/component.d.ts +7 -3
  19. package/dist/component.js +38 -27
  20. package/dist/conformance.d.ts +85 -0
  21. package/dist/conformance.js +327 -0
  22. package/dist/constants.js +4 -2
  23. package/dist/context.d.ts +66 -10
  24. package/dist/context.js +176 -5
  25. package/dist/diagnostics.d.ts +6 -4
  26. package/dist/diagnostics.js +7 -3
  27. package/dist/dynamic.d.ts +18 -0
  28. package/dist/dynamic.js +576 -0
  29. package/dist/editor.d.ts +18 -0
  30. package/dist/editor.js +59 -0
  31. package/dist/errors.d.ts +213 -4
  32. package/dist/errors.js +129 -4
  33. package/dist/expr.d.ts +2 -0
  34. package/dist/expr.js +91 -12
  35. package/dist/fallthrough.d.ts +1 -0
  36. package/dist/fallthrough.js +10 -2
  37. package/dist/file-routes.d.ts +33 -0
  38. package/dist/file-routes.js +224 -0
  39. package/dist/files.d.ts +13 -0
  40. package/dist/files.js +49 -0
  41. package/dist/fixture.d.ts +16 -0
  42. package/dist/fixture.js +22 -7
  43. package/dist/hydration.d.ts +12 -1
  44. package/dist/hydration.js +47 -1
  45. package/dist/index.d.ts +3 -3
  46. package/dist/index.js +1 -1
  47. package/dist/inputs.d.ts +24 -0
  48. package/dist/inputs.js +40 -0
  49. package/dist/link-router.d.ts +7 -3
  50. package/dist/link-router.js +8 -4
  51. package/dist/lists.d.ts +16 -1
  52. package/dist/lists.js +78 -4
  53. package/dist/loops.js +4 -4
  54. package/dist/model.d.ts +20 -1
  55. package/dist/model.js +46 -1
  56. package/dist/numbers.js +3 -2
  57. package/dist/page-routes.d.ts +10 -0
  58. package/dist/page-routes.js +10 -0
  59. package/dist/paths.d.ts +5 -0
  60. package/dist/paths.js +7 -0
  61. package/dist/plugin.d.ts +15 -1
  62. package/dist/plugin.js +3 -0
  63. package/dist/plugins/client-only.js +3 -0
  64. package/dist/plugins/css-modules.d.ts +39 -0
  65. package/dist/plugins/css-modules.js +135 -0
  66. package/dist/plugins/head.d.ts +15 -0
  67. package/dist/plugins/head.js +385 -0
  68. package/dist/plugins/i18n.js +5 -12
  69. package/dist/plugins/index.js +4 -1
  70. package/dist/plugins/provide.d.ts +44 -0
  71. package/dist/plugins/provide.js +530 -0
  72. package/dist/plugins/router-link.js +7 -3
  73. package/dist/plugins/router.d.ts +4 -1
  74. package/dist/plugins/router.js +58 -11
  75. package/dist/plugins/scoped.d.ts +10 -0
  76. package/dist/plugins/scoped.js +17 -4
  77. package/dist/plugins/shared-types.js +2 -1
  78. package/dist/plugins/stores.js +26 -15
  79. package/dist/routes.d.ts +5 -2
  80. package/dist/routes.js +8 -2
  81. package/dist/rust.d.ts +9 -1
  82. package/dist/rust.js +83 -32
  83. package/dist/schema.d.ts +25 -0
  84. package/dist/schema.js +73 -0
  85. package/dist/script.js +31 -8
  86. package/dist/settle.d.ts +2 -0
  87. package/dist/settle.js +5 -0
  88. package/dist/slots.js +20 -4
  89. package/dist/ssr.d.ts +3 -0
  90. package/dist/ssr.js +67 -0
  91. package/dist/strings.d.ts +3 -0
  92. package/dist/strings.js +16 -2
  93. package/dist/styles.d.ts +5 -1
  94. package/dist/styles.js +131 -4
  95. package/dist/template.js +92 -11
  96. package/dist/testing.d.ts +4 -4
  97. package/dist/testing.js +3 -30
  98. package/dist/types.d.ts +5 -0
  99. package/dist/typescript.d.ts +11 -1
  100. package/dist/typescript.js +131 -36
  101. package/dist/vhtml.d.ts +4 -0
  102. package/dist/vhtml.js +63 -0
  103. package/dist/vite.d.ts +25 -11
  104. package/dist/vite.js +166 -51
  105. package/dist/volar.d.ts +15 -0
  106. package/dist/volar.js +87 -0
  107. package/package.json +41 -7
  108. package/schema.json +333 -0
@@ -0,0 +1,327 @@
1
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { relativePath } from "./paths.js";
4
+ import { renderToString } from "vue/server-renderer";
5
+ import { generate, loadConfig } from "./compiler.js";
6
+ import { unifiedDiff } from "./diff.js";
7
+ import { allPages, fileRoutes, pagesFolder, routeEntries } from "./file-routes.js";
8
+ import { fixtureApp, peer, readFixture } from "./fixture.js";
9
+ import { headRendered, settled } from "./settle.js";
10
+ import { attachSsrRender } from "./ssr.js";
11
+ import { applyCssVars, renderDifference, renderedShape } from "./client-render.js";
12
+ export const TELEPORTS = "<!--fv-teleports-->";
13
+ export const HEAD = "<!--fv-head-->";
14
+ /** The head a recorded render wrote after its body, if it wrote one. */
15
+ export function recordedHead(html) {
16
+ const at = html.indexOf(HEAD);
17
+ return at < 0 ? null : JSON.parse(html.slice(at + HEAD.length));
18
+ }
19
+ /** Render a fixture's app as the conformance suite records it: Vue's HTML, then what was teleported
20
+ * and what `useHead` asked for, each after its marker. */
21
+ export async function renderFixture(app) {
22
+ const ssr = {};
23
+ const main = await renderToString(app, ssr);
24
+ const teleported = Object.entries(ssr.teleports ?? {});
25
+ const html = teleported.length ? `${main}${TELEPORTS}${JSON.stringify(Object.fromEntries(teleported))}` : main;
26
+ const head = app.config.globalProperties.$unhead?.render();
27
+ return head && Object.values(head).some(Boolean) ? `${html}${HEAD}${JSON.stringify(head)}` : html;
28
+ }
29
+ /** Put a recorded render's head into the document, as a page would write it: its tags in `<head>`,
30
+ * and its attributes on `<html>` and `<body>`. */
31
+ export function placeHead(head, doc = document) {
32
+ doc.head.innerHTML = head?.headTags ?? "";
33
+ const attrs = (el, written) => {
34
+ for (const name of el.getAttributeNames())
35
+ el.removeAttribute(name);
36
+ const t = doc.createElement("template");
37
+ t.innerHTML = `<div${written}></div>`;
38
+ const parsed = t.content.firstElementChild;
39
+ for (const name of parsed.getAttributeNames())
40
+ el.setAttribute(name, parsed.getAttribute(name));
41
+ };
42
+ attrs(doc.documentElement, head?.htmlAttrs ?? "");
43
+ attrs(doc.body, head?.bodyAttrs ?? "");
44
+ }
45
+ /** A recorded render as a page body to hydrate: the main HTML in `<div id="root">`, what was
46
+ * teleported in each target, and the tags the head puts at the start and end of `<body>`. */
47
+ export function hydrationBody(html) {
48
+ const head = recordedHead(html);
49
+ const [main, teleported] = html.split(HEAD)[0].split(TELEPORTS);
50
+ const targets = Object.entries(JSON.parse(teleported ?? "{}"));
51
+ const intoBody = targets
52
+ .filter(([t]) => t === "body")
53
+ .map(([, content]) => content)
54
+ .join("");
55
+ const elsewhere = targets
56
+ .filter(([t]) => t !== "body")
57
+ .map(([t, content]) => `<div id="${t.replace(/^#/, "")}">${content}</div>`)
58
+ .join("");
59
+ return `${head?.bodyTagsOpen ?? ""}${intoBody}<div id="root">${main}</div>${elsewhere}${head?.bodyTags ?? ""}`;
60
+ }
61
+ /** Where two renders first differ, with the text around it in each. */
62
+ export function firstDifference(recorded, rendered) {
63
+ let at = 0;
64
+ while (at < recorded.length && at < rendered.length && recorded[at] === rendered[at])
65
+ at++;
66
+ const lines = recorded.slice(0, at).split("\n");
67
+ const around = (text) => JSON.stringify(text.slice(Math.max(0, at - 40), at + 40));
68
+ return `first difference at character ${at} (line ${lines.length}, column ${lines.at(-1).length + 1}):\n recorded: ${around(recorded)}\n rendered: ${around(rendered)}`;
69
+ }
70
+ function componentsByName(given, pages) {
71
+ const nameOf = (key) => {
72
+ const path = key.replaceAll("\\", "/");
73
+ return pages.find((p) => path.endsWith(`/${p.within}`))?.name ?? basename(key, ".vue");
74
+ };
75
+ return new Map(Object.entries(given).map(([key, value]) => [
76
+ nameOf(key),
77
+ value.default ?? value,
78
+ ]));
79
+ }
80
+ /** The routes and the router and vue-i18n options a project's fixtures render with, from its configuration. */
81
+ export function fixtureOptions(root, config) {
82
+ const router = config.router ?? (config.routes ? { routes: config.routes } : null);
83
+ const pages = pagesFolder(config);
84
+ const routes = pages !== null
85
+ ? routeEntries(fileRoutes(root, pages))
86
+ : typeof router?.routes === "string"
87
+ ? JSON.parse(readFileSync(join(root, router.routes), "utf8"))
88
+ : null;
89
+ const options = {};
90
+ if (router?.base !== undefined)
91
+ options.base = router.base;
92
+ if (router?.linkActiveClass !== undefined)
93
+ options.linkActiveClass = router.linkActiveClass;
94
+ if (router?.linkExactActiveClass !== undefined)
95
+ options.linkExactActiveClass = router.linkExactActiveClass;
96
+ if (config.i18n) {
97
+ const dir = join(root, config.i18n.messages);
98
+ options.i18n = {
99
+ messages: Object.fromEntries(readdirSync(dir)
100
+ .filter((f) => f.endsWith(".json"))
101
+ .map((f) => [basename(f, ".json"), JSON.parse(readFileSync(join(dir, f), "utf8"))])),
102
+ locale: config.i18n.locale ?? "en",
103
+ ...(config.i18n.fallbackLocale !== undefined ? { fallbackLocale: config.i18n.fallbackLocale } : {}),
104
+ };
105
+ }
106
+ return { routes, options };
107
+ }
108
+ function casesIn(fixtures) {
109
+ if (!existsSync(fixtures))
110
+ return [];
111
+ return readdirSync(fixtures, { withFileTypes: true })
112
+ .filter((d) => d.isDirectory())
113
+ .toSorted((a, b) => a.name.localeCompare(b.name))
114
+ .flatMap((d) => readdirSync(join(fixtures, d.name))
115
+ .filter((f) => f.endsWith(".json"))
116
+ .toSorted()
117
+ .map((f) => ({ component: d.name, name: f, base: join(fixtures, d.name, basename(f, ".json")) })));
118
+ }
119
+ function recordedHtml(c) {
120
+ try {
121
+ return readFileSync(`${c.base}.html`, "utf8");
122
+ }
123
+ catch {
124
+ throw new Error(`${c.component}/${c.name} has no recorded HTML: record it from Vue with FERROVUE_FIXTURES_WRITE=1`);
125
+ }
126
+ }
127
+ function coverageProblems(fixtures, components, cases, files, given) {
128
+ const problems = [];
129
+ if (!existsSync(fixtures))
130
+ problems.push(`there is no fixtures directory at ${fixtures}`);
131
+ if (!files.length)
132
+ problems.push(`there are no components in ${components}`);
133
+ const withFixtures = new Set(cases.map((c) => c.component));
134
+ for (const name of files) {
135
+ if (!withFixtures.has(name))
136
+ problems.push(`${name} has no fixtures: add ${name}/<case>.json under ${fixtures}`);
137
+ if (!given.has(name))
138
+ problems.push(`${name} is not in \`components\``);
139
+ }
140
+ for (const name of withFixtures)
141
+ if (!files.includes(name))
142
+ problems.push(`the fixtures in ${name}/ name no component`);
143
+ for (const name of given.keys())
144
+ if (!files.includes(name))
145
+ problems.push(`\`components\` has ${name}, which is not a .vue file the configuration compiles`);
146
+ return problems;
147
+ }
148
+ function driftProblems(root, config) {
149
+ const out = join(root, config.out);
150
+ const files = generate(root, config);
151
+ const problems = [];
152
+ for (const [file, text] of files) {
153
+ const path = join(out, file);
154
+ if (!existsSync(path))
155
+ problems.push(`${file} is missing`);
156
+ else {
157
+ const committed = readFileSync(path, "utf8");
158
+ if (committed !== text)
159
+ problems.push(unifiedDiff(relativePath(root, path), committed, text).trimEnd());
160
+ }
161
+ }
162
+ const stale = existsSync(out) ? readdirSync(out).filter((f) => f.endsWith(".rs") && !files.has(f)) : [];
163
+ for (const file of stale.toSorted())
164
+ problems.push(`${file} is no longer generated`);
165
+ return problems;
166
+ }
167
+ async function hydrateFixture(app, html) {
168
+ if (typeof document === "undefined")
169
+ throw new Error("hydrating a fixture needs a DOM: run the suite with `environment: \"happy-dom\"` (or jsdom)");
170
+ placeHead(recordedHead(html));
171
+ document.body.innerHTML = hydrationBody(html);
172
+ const root = document.getElementById("root");
173
+ const first = root.firstChild;
174
+ const problems = [];
175
+ const { warn, error } = console;
176
+ console.warn = (...args) => void problems.push(`console.warn: ${args.map(String).join(" ")}`);
177
+ console.error = (...args) => void problems.push(`console.error: ${args.map(String).join(" ")}`);
178
+ app.config.warnHandler = (message) => void problems.push(`warning: ${message}`);
179
+ try {
180
+ app.mount(root);
181
+ await settled(app);
182
+ await headRendered();
183
+ }
184
+ finally {
185
+ console.warn = warn;
186
+ console.error = error;
187
+ }
188
+ if (root.firstChild !== first)
189
+ problems.push("Vue replaced the server's first node");
190
+ app.unmount();
191
+ await headRendered();
192
+ document.body.innerHTML = "";
193
+ placeHead(null);
194
+ return problems;
195
+ }
196
+ /** Render a fixture's app on the client from scratch, with `createApp` (`fixtureApp`'s `client`
197
+ * option), into a document laid out as `hydrationBody` lays out its recorded render, and say where
198
+ * the client's DOM differs from the main HTML the browser parsed, as `renderedShape` compares
199
+ * them: as mounting leaves it, where `<ClientOnly>` still shows its fallback, and, where that
200
+ * differs while async components are loading, once they have loaded. What is teleported and the
201
+ * head are not compared. `null` where they agree. */
202
+ export async function clientRenderDifference(app, html) {
203
+ if (typeof document === "undefined")
204
+ throw new Error("rendering a fixture on the client needs a DOM: run the suite with `environment: \"happy-dom\"` (or jsdom)");
205
+ document.body.innerHTML = hydrationBody(html);
206
+ const root = document.getElementById("root");
207
+ const expected = renderedShape(root);
208
+ root.replaceChildren();
209
+ app.config.warnHandler = () => { };
210
+ const { warn } = console;
211
+ console.warn = () => { };
212
+ let difference;
213
+ try {
214
+ app.mount(root);
215
+ applyCssVars(app);
216
+ difference = await renderDifference(app, root, renderedShape(root), expected);
217
+ app.unmount();
218
+ await headRendered();
219
+ }
220
+ finally {
221
+ console.warn = warn;
222
+ }
223
+ document.body.innerHTML = "";
224
+ placeHead(null);
225
+ return difference;
226
+ }
227
+ /** Register the conformance suite with the given `describe` and `it`. */
228
+ export function registerConformance(api, options) {
229
+ const configFile = resolve(options.config);
230
+ const root = dirname(configFile);
231
+ const config = loadConfig(root, configFile);
232
+ const fixtures = resolve(root, options.fixtures ?? "fixtures");
233
+ const record = options.record ?? process.env.FERROVUE_FIXTURES_WRITE === "1";
234
+ const dir = join(root, config.components);
235
+ const pagesDir = pagesFolder(config)?.replace(/\/+$/, "") ?? null;
236
+ const pages = pagesDir === null
237
+ ? []
238
+ : allPages(fileRoutes(root, pagesDir)).map((p) => ({ name: p.component, file: join(root, p.file), within: `${basename(pagesDir)}/${p.file.slice(pagesDir.length + 1)}` }));
239
+ const sources = new Map([
240
+ ...(existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".vue")) : []).map((f) => [basename(f, ".vue"), join(dir, f)]),
241
+ ...pages.map((p) => [p.name, p.file]),
242
+ ]);
243
+ const files = [...sources.keys()].toSorted();
244
+ const given = componentsByName(options.components, pages);
245
+ for (const [name, component] of given) {
246
+ const source = sources.get(name);
247
+ if (source)
248
+ attachSsrRender(source, name, component);
249
+ }
250
+ const cases = casesIn(fixtures);
251
+ const { routes, options: configured } = fixtureOptions(root, config);
252
+ const appOptions = { ...configured, pinia: options.pinia, vueRouter: options.vueRouter, vueI18n: options.vueI18n };
253
+ const app = async (c, mode = {}) => {
254
+ const component = given.get(c.component);
255
+ if (!component)
256
+ throw new Error(`the fixtures in ${c.component}/ name no component in \`components\``);
257
+ const json = JSON.parse(readFileSync(`${c.base}.json`, "utf8"));
258
+ return fixtureApp(component, readFixture(json), routes, { ...appOptions, ...mode });
259
+ };
260
+ api.describe("conformance", () => {
261
+ api.it("has fixtures for every component, and a component for every fixture", () => {
262
+ const problems = coverageProblems(fixtures, dir, cases, files, given);
263
+ if (problems.length)
264
+ throw new Error(`the fixtures do not cover the components:\n${problems.join("\n")}`);
265
+ });
266
+ api.it("has generated Rust that is what the generator writes now", () => {
267
+ const problems = driftProblems(root, config);
268
+ if (problems.length) {
269
+ throw new Error(`the generated Rust in ${config.out} is not what ferrovue writes now: run \`ferrovue\` and commit the result\n${problems.join("\n")}`);
270
+ }
271
+ });
272
+ api.describe("Vue renders each fixture to its recorded HTML", () => {
273
+ for (const c of cases) {
274
+ api.it(`${c.component}/${c.name}`, async () => {
275
+ const html = await renderFixture(await app(c));
276
+ if (record) {
277
+ writeFileSync(`${c.base}.html`, html);
278
+ return;
279
+ }
280
+ const want = recordedHtml(c);
281
+ if (html !== want) {
282
+ const message = `${c.component}/${c.name}: Vue renders this fixture differently from its recorded HTML, ${firstDifference(want, html)}`;
283
+ throw Object.assign(new Error(message), { actual: html, expected: want, showDiff: true });
284
+ }
285
+ });
286
+ }
287
+ });
288
+ if (record)
289
+ return;
290
+ api.describe("the recorded HTML hydrates without a mismatch", () => {
291
+ for (const c of cases) {
292
+ api.it(`${c.component}/${c.name}`, async () => {
293
+ const problems = await hydrateFixture(await app(c, { hydrate: true }), recordedHtml(c));
294
+ if (problems.length)
295
+ throw new Error(`${c.component}/${c.name} did not hydrate exactly:\n${problems.join("\n")}`);
296
+ });
297
+ }
298
+ });
299
+ if (!(options.clientRender ?? options.clientDiffers !== undefined))
300
+ return;
301
+ const differs = new Set(options.clientDiffers ?? []);
302
+ api.describe("a fresh client render shows the recorded HTML", () => {
303
+ for (const c of cases) {
304
+ const key = `${c.component}/${c.name}`;
305
+ api.it(key, async () => {
306
+ const difference = await clientRenderDifference(await app(c, { client: true }), recordedHtml(c));
307
+ if (difference && !differs.has(key))
308
+ throw new Error(`${key}: ${difference}\n(list it in \`clientDiffers\` where Vue's own client render differs from its server render)`);
309
+ if (!difference && differs.has(key))
310
+ throw new Error(`${key} is in \`clientDiffers\`, but the client renders it as the server did: take it out`);
311
+ });
312
+ }
313
+ });
314
+ });
315
+ }
316
+ /** Register vitest tests holding a project's components to Vue, as ferrovue's own suite does:
317
+ * every component has fixtures and every fixture a component, the generated Rust is what the
318
+ * generator writes now, Vue renders each fixture to its recorded `.html` (or records it, with
319
+ * `FERROVUE_FIXTURES_WRITE=1`), each recorded `.html` hydrates with no warning and the server's
320
+ * nodes kept. With `clientRender` or `clientDiffers`, a fresh client render of each fixture shows
321
+ * its recorded `.html`, as `clientRenderDifference` compares them, except the fixtures listed in
322
+ * `clientDiffers`: what an application that navigates between pages relies on when it renders the
323
+ * next page from its record. Await it at the top of a test file run in a DOM environment such as happy-dom. */
324
+ export async function conformanceSuite(options) {
325
+ const vitest = await peer("vitest", "`conformanceSuite` registers vitest tests", () => import("vitest"));
326
+ registerConformance(vitest, options);
327
+ }
package/dist/constants.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { blankComponent, BOOL, fail, FLOAT, INT, NULL, RUST_PRELUDE, rustStr, sameTy, snake, STR, UNDEF, withAbsence } from "./model.js";
2
- import { ONE_NOTHING } from "./typescript.js";
2
+ import { ONE_NOTHING, reachType } from "./typescript.js";
3
3
  import { ctx } from "./context.js";
4
4
  import { numberVal } from "./numbers.js";
5
5
  import { structLifetime } from "./rust.js";
@@ -190,6 +190,8 @@ function listVal(c) {
190
190
  if (!c.items.every((i) => i.k === "object"))
191
191
  fail(c.home, "FV0211", "a constant list holds plain values of one kind, or objects", c.node);
192
192
  const objects = c.items;
193
+ if (c.typed !== null)
194
+ reachType(c.typed);
193
195
  const st = c.typed !== null ? ctx.typeStructs.get(c.typed) : itemStruct(c, objects);
194
196
  const name = rustConstName(c.path);
195
197
  const owner = ctx.typeConsts.get(name);
@@ -198,7 +200,7 @@ function listVal(c) {
198
200
  const life = structLifetime(st, blankComponent("types", "types", "types", ctx.typeStructs)) ? "<'static>" : "";
199
201
  const rows = objects.map((o, i) => {
200
202
  for (const key of o.fields.keys())
201
- if (!st.fields.some((f) => f.js === key))
203
+ if (!st.fields.some((f) => f.js === key) && !st.refused?.has(key))
202
204
  fail(c.home, "FV0204", `\`${st.name}\` has no field \`${key}\``, o.node);
203
205
  const inits = st.fields.map((f) => `${f.rust}: ${fieldLiteral(c, f, o.fields.get(f.js), objects[i].node)}`);
204
206
  return ` ${st.name} { ${inits.join(", ")} },`;
package/dist/context.d.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import type { Plugin } from "./plugin.ts";
2
2
  import type { Declared } from "./constants.ts";
3
- import { type Component, type Struct, type Ty } from "./model.ts";
3
+ import { type Component, type N, type Struct, type Ty, GenError } from "./model.ts";
4
+ import { type Schema } from "./schema.ts";
4
5
  /** A type a helper takes or returns, as the configuration spells it. */
5
6
  export type TypeName = "string" | "string?" | "int" | "int?" | "float" | "float?" | "bool";
6
7
  /** A function a template may call, and the Rust function that is its twin. */
7
8
  export interface HelperSpec {
8
9
  /** The Rust path the generated code calls, e.g. `crate::helpers::format_count`. */
9
10
  rust: string;
11
+ /** The type of each argument, in order. */
10
12
  params: TypeName[];
13
+ /** The type it returns. */
11
14
  returns: TypeName;
12
15
  /** The longest string it returns, which is what a call adds to the buffer reservation. */
13
16
  maxLen?: number;
@@ -24,13 +27,18 @@ export interface TwinSpec {
24
27
  }
25
28
  /** What `ferrovue.config.json` holds. Paths are relative to the project root. */
26
29
  export interface Config {
30
+ /** The JSON Schema an editor checks the file against. ferrovue does not read it. */
31
+ $schema?: string;
27
32
  /** The directory of `.vue` files to compile. */
28
33
  components: string;
29
- /** The directory the Rust modules are written to. Everything in it is replaced. */
34
+ /** The directory the Rust modules are written to. A module ferrovue wrote there is replaced or
35
+ * removed; any other file is left alone. */
30
36
  out: string;
31
37
  /** The module components import their helpers from, and the Rust twin of each export. */
32
38
  helpers?: {
39
+ /** The module a component imports the helpers from, as its imports name it: `./helpers`. */
33
40
  module: string;
41
+ /** Each function a template may call, by its name in that module. */
34
42
  functions: Record<string, HelperSpec>;
35
43
  };
36
44
  /** Components ferrovue does not compile, by the name a template gives them (`VBtn`, which
@@ -38,17 +46,23 @@ export interface Config {
38
46
  twins?: Record<string, TwinSpec>;
39
47
  /** The Rust type a `TrustedHtml` prop is, which must implement `ferrovue::TrustedHtml`, e.g.
40
48
  * `crate::sanitize::SafeHtml`. A type that borrows names the props' lifetime, `'a`:
41
- * `crate::render::Trusted<'a>`. Without it, a component cannot use `v-html` at all. */
49
+ * `crate::render::Trusted<'a>`. `ferrovue::InlineHtml` makes every `TrustedHtml` prop inline HTML.
50
+ * Without it, only an `InlineHtml` prop may reach `v-html`. */
42
51
  trustedHtml?: string;
43
52
  /** A JSON file listing the app's routes as vue-router paths (`/users/:id`), which `<RouterLink>`
44
- * resolves against. Without it, a component cannot use `<RouterLink>`. */
45
- routes?: string;
46
- /** The router, in full: its routes file, the history's base, and the class names
47
- * `createRouter` gives active links. `routes` alone is shorthand for `{ routes }`. */
53
+ * resolves against, or `{ pages }`: a folder of pages whose file names give the routes, as
54
+ * vue-router's file-based routing reads them. Without it, a component cannot use `<RouterLink>`. */
55
+ routes?: RoutesSource;
56
+ /** The router, in full: its routes, the history's base, and the class names `createRouter`
57
+ * gives active links. `routes` alone is shorthand for `{ routes }`. */
48
58
  router?: {
49
- routes: string;
59
+ /** Where the routes come from, as `routes` takes them. */
60
+ routes: RoutesSource;
61
+ /** The base `createWebHistory` is given, which every link starts with. */
50
62
  base?: string;
63
+ /** The class of a link to the current route or one of its parents. */
51
64
  linkActiveClass?: string;
65
+ /** The class of a link to exactly the current route. */
52
66
  linkExactActiveClass?: string;
53
67
  };
54
68
  /** The directory of Pinia stores (`.ts` files), whose state a component may read while it renders
@@ -61,8 +75,11 @@ export interface Config {
61
75
  /** vue-i18n: the directory of locale files (`en.json`, `nl.json`), the locale a page renders in
62
76
  * when it names none, and the locales a missing message falls back to. */
63
77
  i18n?: {
78
+ /** The directory of locale files, one per locale: `en.json`, `nl.json`. */
64
79
  messages: string;
80
+ /** The locale a page renders in when it names none. */
65
81
  locale?: string;
82
+ /** The locale or locales, in order, a message missing from the page's locale is looked up in. */
66
83
  fallbackLocale?: string | string[];
67
84
  };
68
85
  /** How a `<style scoped>` component's `data-v-` id is computed, which must be how
@@ -72,15 +89,43 @@ export interface Config {
72
89
  scopeId?: ScopeIdMode;
73
90
  /** Vite's root, from which a scope id hashes a component's path: the project root by default. */
74
91
  viteRoot?: string;
92
+ /** Whether `@vitejs/plugin-vue` compiles for production, as Vite's `isProduction`: `true` (the
93
+ * default) for `vite build`, `false` for the dev server. It decides the names of the CSS
94
+ * variables `v-bind()` in `<style>` sets: a hash in production, the expression in development. */
95
+ isProduction?: boolean;
96
+ /** CSS modules (`<style module>`): how Vite's `css.modules` names their classes, which ferrovue
97
+ * computes as postcss-modules does. Without it, `<style module>` is refused. */
98
+ cssModules?: {
99
+ /** The pattern of a class's name, as Vite's `css.modules.generateScopedName`:
100
+ * `"[local]_[hash:base64:5]"`. */
101
+ generateScopedName: string;
102
+ /** Vite's `css.modules.hashPrefix`, hashed before a module's path. */
103
+ hashPrefix?: string;
104
+ /** The directory Vite runs in, its working directory, from which a hash takes a module's path,
105
+ * relative to this file's directory: `viteRoot` by default. */
106
+ context?: string;
107
+ };
75
108
  /** Whether each props struct and shared type gets `new()` and a chainable setter per optional
76
109
  * field: `true` by default. With `false`, props are built as struct literals. */
77
110
  builders?: boolean;
78
111
  }
79
112
  export type ScopeIdMode = "filepath" | "filepath-source";
113
+ /** The options of Vite's `css.modules` that decide a class's name, as postcss-modules reads them. */
114
+ export type CssModulesConfig = NonNullable<Config["cssModules"]>;
115
+ /** Where the routes come from: a JSON file of routes, or a folder of pages. */
116
+ export type RoutesSource = string | {
117
+ /** The folder of pages, each a component, whose file names give the routes. */
118
+ pages: string;
119
+ };
80
120
  export declare const CONFIG_FILE = "ferrovue.config.json";
81
- /** Read the project's configuration. */
82
- export declare function loadConfig(root: string, configPath?: string): Config;
121
+ /** Read the project's configuration, handing `warn` a warning for each deprecated key it holds. */
122
+ export declare function loadConfig(root: string, configPath?: string, warn?: (warning: GenError) => void): Config;
123
+ /** Check what a configuration file holds against `schema`, naming the first key that is unknown or
124
+ * of the wrong shape, and handing `warn` a warning for each deprecated key. */
125
+ export declare function checkConfig(raw: unknown, file: string, warn: (warning: GenError) => void, schema?: Schema): Config;
83
126
  export declare function tyOfName(name: TypeName): Ty;
127
+ /** The Rust type of an `InlineHtml` prop, and of a `TrustedHtml` one when `trustedHtml` names it. */
128
+ export declare const INLINE_HTML = "ferrovue::InlineHtml";
84
129
  /** Where `TrustedHtml` comes from. Only that import names the type `v-html` will write raw. */
85
130
  export declare const TYPES_MODULE = "ferrovue/types";
86
131
  export declare const ctx: {
@@ -100,6 +145,12 @@ export declare const ctx: {
100
145
  typeStructs: Map<string, Struct>;
101
146
  typeAliases: Map<string, any>;
102
147
  typeFiles: Map<string, string>;
148
+ typeDecls: Map<string, {
149
+ home: Component;
150
+ members: N[];
151
+ node: N;
152
+ }[]>;
153
+ typeReached: Set<string>;
103
154
  typeRead: Set<string>;
104
155
  constDecls: Map<string, Map<string, Declared>>;
105
156
  typeConsts: Map<string, {
@@ -110,4 +161,9 @@ export declare const ctx: {
110
161
  components: Map<string, Component>;
111
162
  narrowCount: number;
112
163
  componentsDir: string;
164
+ vnodeTag: string | null;
165
+ sources: Map<string, string>;
113
166
  };
167
+ /** A component's text: what the run was given for its path, as an editor's unsaved buffer, or the
168
+ * file on disk. */
169
+ export declare function readSource(file: string): string;