ferrovue 0.3.0 → 0.5.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 (106) hide show
  1. package/README.md +225 -42
  2. package/dist/attrs.d.ts +3 -53
  3. package/dist/attrs.js +41 -469
  4. package/dist/calls.d.ts +4 -0
  5. package/dist/calls.js +221 -0
  6. package/dist/children.d.ts +16 -0
  7. package/dist/children.js +286 -0
  8. package/dist/classes.d.ts +13 -0
  9. package/dist/classes.js +176 -0
  10. package/dist/cli.js +31 -22
  11. package/dist/client.d.ts +35 -2
  12. package/dist/client.js +77 -14
  13. package/dist/compiler.d.ts +1 -1
  14. package/dist/compiler.js +31 -92
  15. package/dist/component.d.ts +3 -1
  16. package/dist/component.js +123 -104
  17. package/dist/constants.d.ts +42 -0
  18. package/dist/constants.js +292 -0
  19. package/dist/context.d.ts +29 -67
  20. package/dist/context.js +13 -38
  21. package/dist/diagnostics.d.ts +23 -0
  22. package/dist/diagnostics.js +30 -0
  23. package/dist/diff.d.ts +0 -3
  24. package/dist/diff.js +0 -9
  25. package/dist/emitter.d.ts +0 -8
  26. package/dist/emitter.js +0 -12
  27. package/dist/errors.d.ts +867 -0
  28. package/dist/errors.js +330 -0
  29. package/dist/expr.d.ts +1 -70
  30. package/dist/expr.js +142 -934
  31. package/dist/fallthrough.d.ts +9 -0
  32. package/dist/fallthrough.js +78 -0
  33. package/dist/fixture.d.ts +4 -10
  34. package/dist/fixture.js +38 -27
  35. package/dist/hydration.d.ts +15 -0
  36. package/dist/hydration.js +80 -0
  37. package/dist/index.d.ts +3 -0
  38. package/dist/index.js +2 -0
  39. package/dist/islands.d.ts +1 -0
  40. package/dist/islands.js +1 -0
  41. package/dist/link-router.d.ts +24 -0
  42. package/dist/link-router.js +36 -0
  43. package/dist/lists.d.ts +0 -11
  44. package/dist/lists.js +34 -60
  45. package/dist/loops.d.ts +3 -0
  46. package/dist/loops.js +168 -0
  47. package/dist/model.d.ts +46 -144
  48. package/dist/model.js +150 -18
  49. package/dist/narrowing.d.ts +27 -0
  50. package/dist/narrowing.js +157 -0
  51. package/dist/numbers.d.ts +8 -0
  52. package/dist/numbers.js +73 -0
  53. package/dist/parens.d.ts +0 -27
  54. package/dist/parens.js +0 -44
  55. package/dist/plugin.d.ts +84 -0
  56. package/dist/plugin.js +26 -0
  57. package/dist/plugins/client-only.d.ts +8 -0
  58. package/dist/plugins/client-only.js +107 -0
  59. package/dist/plugins/i18n.d.ts +23 -0
  60. package/dist/{i18n.js → plugins/i18n.js} +88 -31
  61. package/dist/plugins/index.d.ts +2 -0
  62. package/dist/plugins/index.js +10 -0
  63. package/dist/plugins/router-link.d.ts +8 -0
  64. package/dist/{router.js → plugins/router-link.js} +52 -91
  65. package/dist/plugins/router.d.ts +42 -0
  66. package/dist/plugins/router.js +256 -0
  67. package/dist/plugins/scoped.d.ts +12 -0
  68. package/dist/plugins/scoped.js +125 -0
  69. package/dist/plugins/shared-types.d.ts +2 -0
  70. package/dist/plugins/shared-types.js +7 -0
  71. package/dist/plugins/stores.d.ts +37 -0
  72. package/dist/plugins/stores.js +379 -0
  73. package/dist/plugins/teleport.d.ts +5 -0
  74. package/dist/plugins/teleport.js +55 -0
  75. package/dist/plugins/twins.d.ts +10 -0
  76. package/dist/plugins/twins.js +164 -0
  77. package/dist/routes.d.ts +10 -0
  78. package/dist/routes.js +6 -0
  79. package/dist/rust.d.ts +1 -7
  80. package/dist/rust.js +56 -174
  81. package/dist/script.d.ts +3 -6
  82. package/dist/script.js +127 -140
  83. package/dist/settle.d.ts +6 -0
  84. package/dist/settle.js +34 -0
  85. package/dist/slots.d.ts +13 -0
  86. package/dist/slots.js +160 -0
  87. package/dist/strings.d.ts +13 -0
  88. package/dist/strings.js +208 -0
  89. package/dist/styles.d.ts +14 -0
  90. package/dist/styles.js +181 -0
  91. package/dist/template.d.ts +1 -42
  92. package/dist/template.js +25 -749
  93. package/dist/testing.d.ts +2 -0
  94. package/dist/testing.js +4 -10
  95. package/dist/types.d.ts +2 -0
  96. package/dist/typescript.d.ts +2 -14
  97. package/dist/typescript.js +53 -59
  98. package/dist/vite.d.ts +2 -1
  99. package/dist/vite.js +11 -32
  100. package/package.json +15 -6
  101. package/dist/i18n.d.ts +0 -27
  102. package/dist/router.d.ts +0 -17
  103. package/dist/scoped.d.ts +0 -24
  104. package/dist/scoped.js +0 -177
  105. package/dist/stores.d.ts +0 -6
  106. package/dist/stores.js +0 -229
package/dist/testing.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import type { Component } from "vue";
2
2
  export { fixtureApp, readFixture, routeRecords, type Fixture, type RouteEntry, type RouterOptions } from "./fixture.ts";
3
+ export { hydrateRecordedPage, type RecordedPage } from "./hydration.ts";
4
+ /** Give a component compiled for the browser the `ssrRender` its SSR build would have. */
3
5
  export declare function attachSsrRender(file: string, name: string, component: Component): void;
package/dist/testing.js CHANGED
@@ -1,19 +1,13 @@
1
- /* What a conformance suite needs from Vue: a component's real server render, and an app that
2
- * renders one fixture (`fixture.ts`, which describes a fixture's keys). */
3
1
  import { readFileSync } from "node:fs";
4
2
  import { compileScript, compileTemplate, parse as parseSfc } from "@vue/compiler-sfc";
5
3
  import * as vue from "vue";
6
4
  import * as serverRenderer from "vue/server-renderer";
7
5
  export { fixtureApp, readFixture, routeRecords } from "./fixture.js";
8
- /* A bundler compiles a `.vue` file for the browser, and `renderToString` on a component without
9
- * `ssrRender` falls back to rendering its virtual DOM — a different path with different output
10
- * (attribute order, `v-model` state, comment markers). So each component is given the `ssrRender`
11
- * its SSR build would have, which is also what the generator translates. */
6
+ export { hydrateRecordedPage } from "./hydration.js";
7
+ /** Give a component compiled for the browser the `ssrRender` its SSR build would have. */
12
8
  export function attachSsrRender(file, name, component) {
13
9
  const { descriptor } = parseSfc(readFileSync(file, "utf8"), { filename: file });
14
- const script = compileScript(descriptor, { id: name });
15
- // A `<style scoped>` component's id is the one `@vitejs/plugin-vue` gave it, which its client
16
- // build carries and which ferrovue computes the same way.
10
+ const script = descriptor.script || descriptor.scriptSetup ? compileScript(descriptor, { id: name }) : null;
17
11
  const scopeId = component.__scopeId;
18
12
  if (!scopeId && descriptor.styles.some((st) => st.scoped)) {
19
13
  throw new Error(`${file}: a \`<style scoped>\` component without \`__scopeId\`: load it through \`@vitejs/plugin-vue\``);
@@ -26,7 +20,7 @@ export function attachSsrRender(file, name, component) {
26
20
  slotted: descriptor.slotted,
27
21
  ssr: true,
28
22
  ssrCssVars: [],
29
- compilerOptions: { bindingMetadata: script.bindings },
23
+ compilerOptions: script ? { bindingMetadata: script.bindings } : {},
30
24
  });
31
25
  const body = code
32
26
  .replace(/import \{([^}]*)\} from "vue"/g, (_, names) => `const {${names.replace(/ as /g, ": ")}} = __vue;`)
package/dist/types.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  declare const trusted: unique symbol;
2
+ /** HTML already made safe: the only type `v-html` may render. */
2
3
  export type TrustedHtml = string & {
3
4
  readonly [trusted]: true;
4
5
  };
6
+ /** A number that may have a fractional part: an `f64` on the server, where a plain `number` is an `i64`. */
5
7
  export type Float = number;
6
8
  export {};
@@ -1,19 +1,11 @@
1
1
  import { type Component, type Field, type N, type Struct, type Ty } from "./model.ts";
2
- /** The local names \`TrustedHtml\` and \`Float\` are imported under from \`ferrovue/types\`. */
3
2
  export declare function typesImports(comp: Component, body: N[]): void;
3
+ export declare const ONE_NOTHING = "its Rust type is an `Option`, whose `None` cannot be both, as `=== null` and the props sent to the client would need";
4
4
  export declare function tyOfTs(comp: Component, t: N, structs: Map<string, Struct>, seen?: Set<string>): Ty;
5
- /** Every local name an interface or object type alias declares a struct for, and every other
6
- * alias: what a type in that block may name. */
7
5
  export declare function declareTypes(comp: Component, body: N[], structs: Map<string, Struct>, aliases: Map<string, N>): N[];
8
- /** A relative import's file, resolved as a bundler resolves a TypeScript import. */
9
6
  export declare function resolveImport(fromFile: string, spec: string): string | null;
10
- /** A shared `.ts` file of types, read once: its interfaces and object types become structs in
11
- * `types.rs`, its other aliases are resolved where they are used. */
12
7
  export declare function readTypeFile(file: string): void;
13
- /** A type read in the file that declares it, marked with where it lives for readers elsewhere. */
14
8
  export declare function markHome(ty: Ty, home: string): Ty;
15
- /** Where a struct type is declared: its fields, the component whose types its fields name, and
16
- * the path the generated code names it by. */
17
9
  export declare function lookupStruct(comp: Component, ty: Ty & {
18
10
  k: "struct";
19
11
  }): {
@@ -22,10 +14,6 @@ export declare function lookupStruct(comp: Component, ty: Ty & {
22
14
  path: string;
23
15
  };
24
16
  export declare function structOf(comp: Component, name: string, members: N[], structs: Map<string, Struct>): Struct;
25
- /** The type literal (or interface) `defineProps<...>()` was given, seen through `withDefaults`. */
26
17
  export declare function definePropsType(call: N): N | null;
27
- /** The `default` of each prop in the runtime declaration `compileScript` wrote, by prop name. */
28
18
  export declare function runtimeDefaults(comp: Component, content: string): Map<string, N>;
29
- /** A prop's default as a Rust value of its type: a literal, or an empty list from `() => []`. */
30
- export declare function defaultValue(comp: Component, f: Field, node: N): string;
31
- export declare function markStore(ty: Ty): Ty;
19
+ export declare function defaultValue(comp: Component, f: Field, node: N, written?: N): string;
@@ -1,12 +1,11 @@
1
- /* TypeScript types read as Rust ones: props, interfaces, aliases, shared type files, defaults. */
2
1
  import { parse as parseJs } from "@babel/parser";
3
2
  import { readFileSync, statSync } from "node:fs";
4
- import { dirname, join, relative, resolve } from "node:path";
5
- import { BOOL, fail, FLOAT, INT, opt, RUST_PRELUDE, rustStr, sameTy, snake, STR, tagAst } from "./model.js";
3
+ import { basename, dirname, join, relative, resolve } from "node:path";
4
+ import { absence, blankComponent, BOOL, fail, FLOAT, GenError, INT, joinAbsence, opt, RUST_PRELUDE, rustStr, sameTy, snake, STR, tagAst, withAbsence } from "./model.js";
6
5
  import { CONFIG_FILE, ctx, TYPES_MODULE } from "./context.js";
7
6
  import { childOf } from "./expr.js";
8
- import { storeHome } from "./stores.js";
9
- /** The local names \`TrustedHtml\` and \`Float\` are imported under from \`ferrovue/types\`. */
7
+ import { claim } from "./plugin.js";
8
+ import { declareConsts, enumType } from "./constants.js";
10
9
  export function typesImports(comp, body) {
11
10
  for (const s of body) {
12
11
  if (s.type !== "ImportDeclaration" || s.source.value !== TYPES_MODULE)
@@ -22,6 +21,8 @@ export function typesImports(comp, body) {
22
21
  }
23
22
  }
24
23
  }
24
+ export const ONE_NOTHING = "its Rust type is an `Option`, whose `None` cannot be both, as `=== null` and the props sent to the client would need";
25
+ const NULL_OR_UNDEFINED = `a type that is both \`null\` and \`undefined\`: ${ONE_NOTHING}; keep one of them`;
25
26
  export function tyOfTs(comp, t, structs, seen = new Set()) {
26
27
  switch (t.type) {
27
28
  case "TSStringKeyword":
@@ -35,21 +36,18 @@ export function tyOfTs(comp, t, structs, seen = new Set()) {
35
36
  case "TSParenthesizedType":
36
37
  return tyOfTs(comp, t.typeAnnotation, structs, seen);
37
38
  case "TSTypeLiteral": {
38
- // `{ [key: string]: T }`, which is `Record<string, T>`. Any other object type is an interface.
39
39
  const [sig] = t.members;
40
40
  const key = sig?.parameters?.[0]?.typeAnnotation?.typeAnnotation;
41
41
  if (t.members.length === 1 && sig.type === "TSIndexSignature" && key?.type === "TSStringKeyword" && sig.typeAnnotation) {
42
42
  return recordOf(comp, sig.typeAnnotation.typeAnnotation, structs, seen);
43
43
  }
44
- return fail(comp, "an object type in place: declare it as an interface, or as `{ [key: string]: T }` for a dictionary", t);
44
+ return fail(comp, "FV0310", "an object type in place: declare it as an interface, or as `{ [key: string]: T }` for a dictionary", t);
45
45
  }
46
46
  case "TSTypeOperator":
47
- // `readonly string[]`: the same list, which the server never writes to anyway.
48
47
  if (t.operator === "readonly")
49
48
  return tyOfTs(comp, t.typeAnnotation, structs, seen);
50
49
  break;
51
50
  case "TSLiteralType":
52
- // A literal type is a value of its kind: `"sm"` a string, `3` a number.
53
51
  if (t.literal.type === "StringLiteral" || t.literal.type === "TemplateLiteral")
54
52
  return STR;
55
53
  if (t.literal.type === "NumericLiteral")
@@ -58,30 +56,38 @@ export function tyOfTs(comp, t, structs, seen = new Set()) {
58
56
  return BOOL;
59
57
  break;
60
58
  case "TSUnionType": {
61
- // `"sm" | "md"` is a string; `T | undefined` is an optional `T`. `null` is a different value.
62
- const parts = t.types.filter((u) => u.type !== "TSUndefinedKeyword");
63
- if (t.types.some((u) => u.type === "TSNullKeyword" || (u.type === "TSLiteralType" && u.literal.type === "NullLiteral"))) {
64
- return fail(comp, "`null` in a type: use `undefined`, which is what an absent value is", t);
59
+ const isNull = (u) => u.type === "TSNullKeyword" || (u.type === "TSLiteralType" && u.literal.type === "NullLiteral");
60
+ let none = null;
61
+ const tys = [];
62
+ for (const u of t.types) {
63
+ if (u.type === "TSUndefinedKeyword")
64
+ none = joinAbsence(none, "undefined");
65
+ else if (isNull(u))
66
+ none = joinAbsence(none, "null");
67
+ else {
68
+ const ty = tyOfTs(comp, u, structs, seen);
69
+ none = joinAbsence(none, absence(ty));
70
+ tys.push(ty.k === "opt" ? ty.of : ty);
71
+ }
65
72
  }
66
- const tys = parts.map((u) => tyOfTs(comp, u, structs, seen));
73
+ if (none === "either")
74
+ return fail(comp, "FV0311", NULL_OR_UNDEFINED, t);
67
75
  const first = tys[0];
68
76
  if (!first || tys.some((x) => !sameTy(x, first)))
69
- return fail(comp, "a union of different types has no Rust type", t);
70
- return parts.length < t.types.length ? opt(first) : first;
77
+ return fail(comp, "FV0312", "a union of different types has no Rust type", t);
78
+ return withAbsence(first, none);
71
79
  }
72
80
  case "TSTypeReference": {
73
81
  const name = t.typeName.type === "Identifier" ? t.typeName.name : undefined;
74
82
  if (name === undefined)
75
83
  break;
76
- // `Array<T>` and `ReadonlyArray<T>`, as `T[]`.
77
84
  if ((name === "Array" || name === "ReadonlyArray") && t.typeParameters?.params?.length === 1) {
78
85
  return { k: "list", of: tyOfTs(comp, t.typeParameters.params[0], structs, seen) };
79
86
  }
80
- // `Record<string, T>`, an object used as a dictionary.
81
87
  if (name === "Record" && t.typeParameters?.params?.length === 2) {
82
88
  const [key, value] = t.typeParameters.params;
83
89
  if (key.type !== "TSStringKeyword")
84
- fail(comp, "a `Record` is keyed by `string`", key);
90
+ fail(comp, "FV0313", "a `Record` is keyed by `string`", key);
85
91
  return recordOf(comp, value, structs, seen);
86
92
  }
87
93
  if (structs.has(name))
@@ -92,7 +98,7 @@ export function tyOfTs(comp, t, structs, seen = new Set()) {
92
98
  return FLOAT;
93
99
  if (comp.trustedName !== null && name === comp.trustedName) {
94
100
  if (ctx.trustedHtml === null) {
95
- fail(comp, `a \`TrustedHtml\` prop needs \`trustedHtml\` in ${CONFIG_FILE}: the Rust type it is`, t);
101
+ fail(comp, "FV1503", `a \`TrustedHtml\` prop needs \`trustedHtml\` in ${CONFIG_FILE}: the Rust type it is`, t);
96
102
  }
97
103
  return { k: "html" };
98
104
  }
@@ -102,25 +108,21 @@ export function tyOfTs(comp, t, structs, seen = new Set()) {
102
108
  const alias = comp.aliases.get(name);
103
109
  if (alias) {
104
110
  if (seen.has(name))
105
- fail(comp, `type \`${name}\` refers to itself through an alias`, t);
111
+ fail(comp, "FV0314", `type \`${name}\` refers to itself through an alias`, t);
106
112
  return tyOfTs(comp, alias, structs, new Set(seen).add(name));
107
113
  }
108
- return fail(comp, `unsupported prop type \`${name}\`: declare it as an interface in the component, or import it from a \`.ts\` file`, t);
114
+ return fail(comp, "FV0315", `unsupported prop type \`${name}\`: declare it as an interface in the component, or import it from a \`.ts\` file`, t);
109
115
  }
110
116
  }
111
- return fail(comp, `unsupported prop type \`${t.type}\``, t);
117
+ return fail(comp, "FV0316", `unsupported prop type \`${t.type}\``, t);
112
118
  }
113
- /** A dictionary's type: its values strings, numbers, booleans, objects or lists of those. A value
114
- * may not be optional: JSON has no `undefined` to hold. */
115
119
  function recordOf(comp, value, structs, seen) {
116
120
  const of = tyOfTs(comp, value, structs, seen);
117
121
  const plain = (t) => ["str", "int", "float", "bool", "struct", "child"].includes(t.k) || (t.k === "list" && plain(t.of));
118
122
  if (!plain(of))
119
- fail(comp, "a `Record`'s values are strings, numbers, booleans, objects or lists of those", value);
123
+ fail(comp, "FV0317", "a `Record`'s values are strings, numbers, booleans, objects or lists of those", value);
120
124
  return { k: "record", of };
121
125
  }
122
- /** Every local name an interface or object type alias declares a struct for, and every other
123
- * alias: what a type in that block may name. */
124
126
  export function declareTypes(comp, body, structs, aliases) {
125
127
  const decls = [];
126
128
  for (const st of body) {
@@ -128,23 +130,30 @@ export function declareTypes(comp, body, structs, aliases) {
128
130
  if (d?.type === "TSInterfaceDeclaration")
129
131
  decls.push({ name: d.id.name, members: d.body.body, node: d });
130
132
  else if (d?.type === "TSTypeAliasDeclaration") {
131
- // An object type is a struct — but for a dictionary, `{ [key: string]: T }`, an alias of its own.
132
133
  const dictionary = d.typeAnnotation.members?.some((m) => m.type === "TSIndexSignature");
133
134
  if (d.typeAnnotation.type === "TSTypeLiteral" && !dictionary)
134
135
  decls.push({ name: d.id.name, members: d.typeAnnotation.members, node: d });
135
136
  else
136
137
  aliases.set(d.id.name, d.typeAnnotation);
137
138
  }
139
+ else if (d?.type === "TSEnumDeclaration") {
140
+ try {
141
+ aliases.set(d.id.name, enumType(comp, d));
142
+ }
143
+ catch (e) {
144
+ if (!(e instanceof GenError))
145
+ throw e;
146
+ }
147
+ }
138
148
  }
139
149
  for (const d of decls) {
140
150
  if (RUST_PRELUDE.has(d.name)) {
141
- fail(comp, `an interface called \`${d.name}\` would hide Rust's own \`${d.name}\` in the generated code; rename it`, d.node);
151
+ fail(comp, "FV0318", `an interface called \`${d.name}\` would hide Rust's own \`${d.name}\` in the generated code; rename it`, d.node);
142
152
  }
143
153
  structs.set(d.name, { name: d.name, fields: [] });
144
154
  }
145
155
  return decls;
146
156
  }
147
- /** A relative import's file, resolved as a bundler resolves a TypeScript import. */
148
157
  export function resolveImport(fromFile, spec) {
149
158
  if (!spec.startsWith("."))
150
159
  return null;
@@ -155,31 +164,28 @@ export function resolveImport(fromFile, spec) {
155
164
  return candidate;
156
165
  }
157
166
  catch {
158
- // not this one
159
167
  }
160
168
  }
161
169
  return null;
162
170
  }
163
- /** A shared `.ts` file of types, read once: its interfaces and object types become structs in
164
- * `types.rs`, its other aliases are resolved where they are used. */
165
171
  export function readTypeFile(file) {
166
172
  if (ctx.typeRead.has(file))
167
173
  return;
168
174
  ctx.typeRead.add(file);
169
175
  const rel = relative(ctx.rootDir, file);
170
- const home = storeHome(rel);
171
- home.structs = ctx.typeStructs;
176
+ const home = blankComponent(basename(rel), "types", rel, ctx.typeStructs);
172
177
  home.aliases = ctx.typeAliases;
173
178
  home.source = readFileSync(file, "utf8");
174
179
  const body = parseJs(home.source, { sourceType: "module", plugins: ["typescript"] }).program.body;
175
180
  tagAst(body, "source");
176
181
  typesImports(home, body);
182
+ ctx.constDecls.set(file, declareConsts(home, body));
177
183
  const before = new Set(ctx.typeStructs.keys());
178
184
  const local = new Map();
179
185
  const decls = declareTypes(home, body, local, ctx.typeAliases);
180
186
  for (const d of decls) {
181
187
  if (before.has(d.name))
182
- fail(home, `\`${d.name}\` is declared by ${ctx.typeFiles.get(d.name)} too`, d.node);
188
+ fail(home, "FV0319", `\`${d.name}\` is declared by ${ctx.typeFiles.get(d.name)} too`, d.node);
183
189
  ctx.typeStructs.set(d.name, local.get(d.name));
184
190
  ctx.typeFiles.set(d.name, rel);
185
191
  }
@@ -190,20 +196,17 @@ export function readTypeFile(file) {
190
196
  ctx.typeStructs.set(d.name, st);
191
197
  }
192
198
  }
193
- /** A type read in the file that declares it, marked with where it lives for readers elsewhere. */
194
199
  export function markHome(ty, home) {
195
- if (ty.k === "struct" && !ty.store && !ty.home && ty.name !== "Props")
200
+ if (ty.k === "struct" && !claim((p) => p.struct?.(ty)) && !ty.home && ty.name !== "Props")
196
201
  return { ...ty, home };
197
202
  if (ty.k === "opt" || ty.k === "list" || ty.k === "record")
198
203
  return { ...ty, of: markHome(ty.of, home) };
199
204
  return ty;
200
205
  }
201
- /** Where a struct type is declared: its fields, the component whose types its fields name, and
202
- * the path the generated code names it by. */
203
206
  export function lookupStruct(comp, ty) {
204
- // Named from the module being written: plainly within its own, by path from any other.
205
- if (ty.store)
206
- return { st: ctx.storeStructs.get(ty.name), owner: comp, path: comp.module === "stores" ? "" : "super::stores::" };
207
+ const own = claim((p) => p.struct?.(ty));
208
+ if (own)
209
+ return { st: own.st, owner: comp, path: comp.module === own.module ? "" : `super::${own.module}::` };
207
210
  if (ty.home === "types")
208
211
  return { st: ctx.typeStructs.get(ty.name), owner: comp, path: comp.module === "types" ? "" : "super::types::" };
209
212
  if (ty.home !== undefined && ty.home !== comp.name) {
@@ -216,9 +219,12 @@ export function structOf(comp, name, members, structs) {
216
219
  const fields = [];
217
220
  for (const m of members) {
218
221
  if (m.type !== "TSPropertySignature" || m.key.type !== "Identifier") {
219
- fail(comp, `\`${name}\` may only hold plain named fields`, m);
222
+ fail(comp, "FV0320", `\`${name}\` may only hold plain named fields`, m);
220
223
  }
221
224
  const base = tyOfTs(comp, m.typeAnnotation.typeAnnotation, structs);
225
+ if (m.optional && absence(base) === "null") {
226
+ fail(comp, "FV0321", `\`${m.key.name}?: T | null\` may be absent, which is \`undefined\`, or \`null\`: ${ONE_NOTHING}; declare it \`${m.key.name}: T | null\` or \`${m.key.name}?: T\``, m);
227
+ }
222
228
  if (m.optional && base.k === "opt") {
223
229
  fields.push({ js: m.key.name, rust: snake(m.key.name), ty: base });
224
230
  continue;
@@ -227,7 +233,6 @@ export function structOf(comp, name, members, structs) {
227
233
  }
228
234
  return { name, fields };
229
235
  }
230
- /** The type literal (or interface) `defineProps<...>()` was given, seen through `withDefaults`. */
231
236
  export function definePropsType(call) {
232
237
  if (call?.type === "CallExpression" && call.callee.type === "Identifier" && call.callee.name === "withDefaults") {
233
238
  return definePropsType(call.arguments[0]);
@@ -239,7 +244,6 @@ export function definePropsType(call) {
239
244
  }
240
245
  return null;
241
246
  }
242
- /** The `default` of each prop in the runtime declaration `compileScript` wrote, by prop name. */
243
247
  export function runtimeDefaults(comp, content) {
244
248
  const out = new Map();
245
249
  let program;
@@ -249,7 +253,6 @@ export function runtimeDefaults(comp, content) {
249
253
  catch {
250
254
  return out;
251
255
  }
252
- /** An object literal's properties, with `...{ … }` spreads opened, as `defineModel` writes them. */
253
256
  const props = (o) => o?.type !== "ObjectExpression"
254
257
  ? []
255
258
  : o.properties.flatMap((p) => (p.type === "SpreadElement" ? props(p.argument) : [p]));
@@ -257,7 +260,6 @@ export function runtimeDefaults(comp, content) {
257
260
  if (!n || typeof n !== "object")
258
261
  return;
259
262
  if (n.type === "ObjectProperty" && !n.computed && (n.key.name ?? n.key.value) === "props") {
260
- // `props: { … }`, or `_mergeModels({ … }, { … })` when there is a `defineModel`.
261
263
  const objects = n.value.type === "CallExpression" ? n.value.arguments : [n.value];
262
264
  for (const o of objects) {
263
265
  for (const p of props(o)) {
@@ -284,8 +286,7 @@ export function runtimeDefaults(comp, content) {
284
286
  void comp;
285
287
  return out;
286
288
  }
287
- /** A prop's default as a Rust value of its type: a literal, or an empty list from `() => []`. */
288
- export function defaultValue(comp, f, node) {
289
+ export function defaultValue(comp, f, node, written) {
289
290
  const of = f.ty.k === "opt" ? f.ty.of : f.ty;
290
291
  if (of.k === "str" && node.type === "StringLiteral")
291
292
  return rustStr(node.value);
@@ -299,12 +300,5 @@ export function defaultValue(comp, f, node) {
299
300
  if (of.k === "list" && node.type === "ArrowFunctionExpression" && node.body.type === "ArrayExpression" && node.body.elements.length === 0) {
300
301
  return "&[]";
301
302
  }
302
- return fail(comp, `the default of \`${f.js}\` must be a literal of its type, or \`() => []\` for a list`, node);
303
- }
304
- export function markStore(ty) {
305
- if (ty.k === "struct")
306
- return { ...ty, store: true };
307
- if (ty.k === "opt" || ty.k === "list" || ty.k === "record")
308
- return { ...ty, of: markStore(ty.of) };
309
- return ty;
303
+ return fail(comp, "FV0322", `the default of \`${f.js}\` must be a literal of its type, or \`() => []\` for a list`, written ?? node);
310
304
  }
package/dist/vite.d.ts CHANGED
@@ -4,7 +4,7 @@ export interface FerrovueOptions {
4
4
  root?: string;
5
5
  }
6
6
  /** Whether a changed file can change what is generated: a component, a store or type file, the
7
- * routes or the configuration — anything but the output itself, dependencies and build output. */
7
+ * routes or the configuration: anything but the output itself, dependencies and build output. */
8
8
  export declare function affects(root: string, file: string): boolean;
9
9
  /** How `@vitejs/plugin-vue`, as this build configures it, computes a `<style scoped>` id: from the
10
10
  * path alone or the path and source, hashed from Vite's root. `null` without the plugin, or with an
@@ -20,4 +20,5 @@ export declare function scopeIdMismatch(root: string, vue: {
20
20
  mode: string;
21
21
  root: string;
22
22
  } | null): string | null;
23
+ /** The Rust renderers regenerated by a Vite build and its dev server, and the `ferrovue/islands` module. */
23
24
  export default function ferrovue(options?: FerrovueOptions): Plugin;
package/dist/vite.js CHANGED
@@ -1,20 +1,9 @@
1
- /* `ferrovue/vite`: the Rust renderers regenerated as part of a Vite build and its dev server.
2
- *
3
- * import ferrovue from "ferrovue/vite";
4
- * export default defineConfig({ plugins: [vue(), ferrovue()] });
5
- *
6
- * A build regenerates them once and fails on a construct ferrovue refuses, naming the line in the
7
- * `.vue` file. The dev server regenerates them whenever a component, store, type file, the routes
8
- * or the configuration changes, and shows a refusal in its error overlay. Only files whose text
9
- * changed are rewritten, so `cargo watch` rebuilds no more than it must.
10
- *
11
- * It also writes `ferrovue/islands`: every component that has an `island()`, by name, each a lazy
12
- * `import()` of its `.vue` file, for `mountIslands`. */
13
1
  import { readdirSync, readFileSync } from "node:fs";
14
2
  import { join, relative, resolve, sep } from "node:path";
15
- import { CONFIG_FILE, GenError, loadConfig, write } from "./compiler.js";
3
+ import { CONFIG_FILE, loadConfig, write } from "./compiler.js";
4
+ import { formatRefusal, isRefusal } from "./diagnostics.js";
16
5
  /** Whether a changed file can change what is generated: a component, a store or type file, the
17
- * routes or the configuration — anything but the output itself, dependencies and build output. */
6
+ * routes or the configuration: anything but the output itself, dependencies and build output. */
18
7
  export function affects(root, file) {
19
8
  const rel = relative(root, file);
20
9
  if (rel.startsWith("..") || !/\.(vue|ts|json)$/.test(rel))
@@ -24,7 +13,6 @@ export function affects(root, file) {
24
13
  out = loadConfig(root).out;
25
14
  }
26
15
  catch {
27
- // A broken configuration ignores nothing; regenerating reports it.
28
16
  }
29
17
  const parts = rel.split(sep);
30
18
  if (parts.some((p) => p === "node_modules" || p === "target" || p === ".git" || p === "dist"))
@@ -57,24 +45,20 @@ export function scopeIdMismatch(root, vue) {
57
45
  files = readdirSync(join(root, config.components)).filter((f) => f.endsWith(".vue"));
58
46
  }
59
47
  catch {
60
- // No components: generating reports it.
61
48
  }
62
49
  if (!files.some((f) => /<style\b[^>]*\bscoped\b/.test(readFileSync(join(root, config.components, f), "utf8"))))
63
50
  return null;
64
51
  return `\`<style scoped>\` ids: @vitejs/plugin-vue hashes "${vue.mode}" from ${vue.root}, ${CONFIG_FILE} "${mode}" from ${viteRoot}; set \`scopeId\` and \`viteRoot\` to match, or plugin-vue's \`features.componentIdGenerator\``;
65
52
  }
66
- /** The import that names the islands, and the id the plugin gives the module it writes for it. */
67
53
  const ISLANDS = "ferrovue/islands";
68
54
  const ISLANDS_ID = `\0${ISLANDS}`;
69
- /** The text of `ferrovue/islands`: each island's name, mapped to an `import()` of its `.vue` file,
70
- * which the bundler splits into a chunk of its own. */
71
55
  function islandsModule(root, islands) {
72
56
  const entries = Object.entries(islands).map(([name, file]) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(resolve(root, file).split(sep).join("/"))}),`);
73
57
  return `export default {\n${entries.join("\n")}\n};\n`;
74
58
  }
59
+ /** The Rust renderers regenerated by a Vite build and its dev server, and the `ferrovue/islands` module. */
75
60
  export default function ferrovue(options = {}) {
76
61
  const root = resolve(options.root ?? process.cwd());
77
- // The islands as the last generation found them, for `ferrovue/islands`.
78
62
  let islands = null;
79
63
  const regenerate = () => {
80
64
  const written = write(root, loadConfig(root));
@@ -85,7 +69,6 @@ export default function ferrovue(options = {}) {
85
69
  let building = true;
86
70
  return {
87
71
  name: "ferrovue",
88
- // Before Vite's own resolver, which would find `ferrovue/islands` in the package instead.
89
72
  enforce: "pre",
90
73
  resolveId(id) {
91
74
  return id === ISLANDS ? ISLANDS_ID : null;
@@ -97,8 +80,8 @@ export default function ferrovue(options = {}) {
97
80
  return islandsModule(root, islands ?? regenerate().islands);
98
81
  }
99
82
  catch (e) {
100
- if (e instanceof GenError || e instanceof SyntaxError)
101
- this.error(e.message);
83
+ if (isRefusal(e))
84
+ this.error(formatRefusal(e));
102
85
  throw e;
103
86
  }
104
87
  },
@@ -109,8 +92,6 @@ export default function ferrovue(options = {}) {
109
92
  buildStart() {
110
93
  try {
111
94
  regenerate();
112
- // A build whose styles would not apply to the server's pages fails, as a refusal does; the
113
- // dev server warns.
114
95
  const mismatch = scopeIdMismatch(root, vue);
115
96
  if (mismatch && building)
116
97
  this.error(`ferrovue: ${mismatch}`);
@@ -118,8 +99,8 @@ export default function ferrovue(options = {}) {
118
99
  this.warn(`ferrovue: ${mismatch}`);
119
100
  }
120
101
  catch (e) {
121
- if (e instanceof GenError || e instanceof SyntaxError)
122
- this.error(e.message);
102
+ if (isRefusal(e))
103
+ this.error(formatRefusal(e));
123
104
  throw e;
124
105
  }
125
106
  },
@@ -134,8 +115,6 @@ export default function ferrovue(options = {}) {
134
115
  if (changed.length || removed.length) {
135
116
  server.config.logger.info(`ferrovue: ${changed.length} changed, ${removed.length} removed`, { timestamp: true });
136
117
  }
137
- // A component that became an island, or stopped being one: the page loads the islands
138
- // afresh, as the server now writes them.
139
118
  const loaded = server.moduleGraph.getModuleById(ISLANDS_ID);
140
119
  if (loaded && JSON.stringify(islands) !== before) {
141
120
  server.moduleGraph.invalidateModule(loaded);
@@ -143,10 +122,10 @@ export default function ferrovue(options = {}) {
143
122
  }
144
123
  }
145
124
  catch (e) {
146
- if (!(e instanceof GenError || e instanceof SyntaxError))
125
+ if (!isRefusal(e))
147
126
  throw e;
148
- server.config.logger.error(`ferrovue: ${e.message}`, { timestamp: true });
149
- server.ws.send({ type: "error", err: { message: `ferrovue: ${e.message}`, stack: "", plugin: "ferrovue" } });
127
+ server.config.logger.error(`ferrovue: ${formatRefusal(e)}`, { timestamp: true });
128
+ server.ws.send({ type: "error", err: { message: `ferrovue: ${formatRefusal(e)}`, stack: "", plugin: "ferrovue" } });
150
129
  }
151
130
  };
152
131
  server.watcher.on("change", onChange);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ferrovue",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Vue templates compiled to Rust render functions: server-side rendering with no JavaScript at run time",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -29,6 +29,10 @@
29
29
  ],
30
30
  "exports": {
31
31
  ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "./compiler": {
32
36
  "types": "./dist/compiler.d.ts",
33
37
  "default": "./dist/compiler.js"
34
38
  },
@@ -44,6 +48,10 @@
44
48
  "types": "./dist/client.d.ts",
45
49
  "default": "./dist/client.js"
46
50
  },
51
+ "./link-router": {
52
+ "types": "./dist/link-router.d.ts",
53
+ "default": "./dist/link-router.js"
54
+ },
47
55
  "./islands": {
48
56
  "types": "./dist/islands.d.ts",
49
57
  "default": "./dist/islands.js"
@@ -53,11 +61,12 @@
53
61
  "default": "./dist/vite.js"
54
62
  }
55
63
  },
64
+ "sideEffects": false,
56
65
  "bin": {
57
66
  "ferrovue": "./dist/cli.js"
58
67
  },
59
68
  "scripts": {
60
- "build": "tsc -p tsconfig.build.json",
69
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
61
70
  "prepack": "pnpm run build && cp ../../README.md ../../LICENSE-MIT ../../LICENSE-APACHE ."
62
71
  },
63
72
  "dependencies": {
@@ -77,11 +86,11 @@
77
86
  "vue-router": "^5.3.1"
78
87
  },
79
88
  "peerDependencies": {
80
- "pinia": "^4.0.3",
89
+ "pinia": "~4.0.3",
81
90
  "vite": ">=6",
82
- "vue": "3.5.43",
83
- "vue-i18n": "^11.0.0",
84
- "vue-router": "^5.3.1"
91
+ "vue": "~3.5.43",
92
+ "vue-i18n": "~11.4.13",
93
+ "vue-router": "~5.3.1"
85
94
  },
86
95
  "peerDependenciesMeta": {
87
96
  "vue-router": {
package/dist/i18n.d.ts DELETED
@@ -1,27 +0,0 @@
1
- import { type N, type Scope, type Val } from "./model.ts";
2
- /** A locale's messages, each parsed by vue-i18n's own message compiler, by dotted key. */
3
- export interface LocaleMessages {
4
- name: string;
5
- file: string;
6
- messages: Map<string, N>;
7
- }
8
- /** The configured vue-i18n setup, read once per run. */
9
- export interface I18nSetup {
10
- /** The locale files' directory, as the configuration names it. */
11
- dir: string;
12
- locales: LocaleMessages[];
13
- /** The locale a fixture renders in when it names none, and the fallbacks in order. */
14
- locale: string;
15
- fallback: string[];
16
- }
17
- /** Every message of every `*.json` locale file in the directory: nested objects joined with dots,
18
- * as vue-i18n resolves a path — a nested key first, then a flat key of the same spelling. */
19
- export declare function readLocales(root: string, config: {
20
- messages: string;
21
- locale?: string;
22
- fallbackLocale?: string | string[];
23
- }): I18nSetup;
24
- export declare function i18nSource(setup: I18nSetup): string;
25
- /** `t(key)`, `t(key, plural)`, `t(key, { named })`, `t(key, [list])`, `t(key, { named }, plural)`:
26
- * the message translated in the request's locale. */
27
- export declare function translate(s: Scope, args: N[], n: N): Val;
package/dist/router.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { type N, type Scope, type Val } from "./model.ts";
2
- import { type RouteDef } from "./context.ts";
3
- import { Emitter } from "./emitter.ts";
4
- export declare const ROUTER_LINK_PROPS: Set<string>;
5
- /** `<RouterLink>` props that change only what a click does, which the server does not render. */
6
- export declare const ROUTER_LINK_INERT: Set<string>;
7
- /** The parameter names of a route path, in order. */
8
- export declare function routeParams(path: string): string[];
9
- /** A value written into a URL — a parameter or a query value — as the `&str` vue-router stringifies. */
10
- export declare function urlText(s: Scope, v: Val, n: N): string;
11
- /** \`let fv_link = …;\`: a \`<RouterLink>\`'s \`to\` resolved from the reader's route. */
12
- export declare function resolveLink(s: Scope, e: Emitter, to: N): void;
13
- /** \`<RouterLink to="...">\` as vue-router renders it: \`aria-current\` and the active classes when it
14
- * points where the reader is, then \`href\`, then the link's own class and attributes. */
15
- export declare function routerLink(s: Scope, e: Emitter, n: N): void;
16
- /** The routes file: vue-router paths, each a string or `{ "path", "name" }`. */
17
- export declare function readRoutes(root: string, file: string): RouteDef[];
package/dist/scoped.d.ts DELETED
@@ -1,24 +0,0 @@
1
- import { type Component, type N } from "./model.ts";
2
- /** Set every component's `inherits` and `passesSlotIds`, each a least fixed point: a component's
3
- * slot content may be given an id when one of its outlets passes one, or forwards what the slot
4
- * content it sits in was given; a root may be handed ids by a scoped parent, by a parent that
5
- * passes on what it inherits, or by slot content that may be given an id. */
6
- export declare function scopeFlow(read: {
7
- comp: Component;
8
- ssr: string;
9
- children: Map<string, string>;
10
- }[]): void;
11
- /** Whether `n` is the template's `$attrs`: `_ctx.$attrs`, or a setup binding of `useAttrs()`. */
12
- export declare function isDollarAttrs(n: N, bindings: Set<string>): boolean;
13
- /** Whether a key a parent passes a child reaches it as an attribute, unless it is a prop: not one
14
- * Vue reserves, not a listener (which the server drops), not a model's modifiers. */
15
- export declare function passedKey(child: Component, key: string): boolean;
16
- /** Set every component's `attrNames` and `idsInAttrs`: the attributes its parents' calls pass it
17
- * beyond its props, and those passed on to it — by a parent whose root it is, or that binds
18
- * `$attrs` to it — from that parent's own, a least fixed point. Runs after `scopeFlow`. */
19
- export declare function attrsFlow(read: {
20
- comp: Component;
21
- ssr: string;
22
- children: Map<string, string>;
23
- attrsBindings: Set<string>;
24
- }[]): void;