ferrovue 0.13.0 → 0.14.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 (51) hide show
  1. package/README.md +9 -5
  2. package/dist/attrs.js +62 -4
  3. package/dist/calls.js +18 -6
  4. package/dist/children.js +29 -8
  5. package/dist/classes.js +6 -1
  6. package/dist/client.d.ts +4 -4
  7. package/dist/client.js +4 -4
  8. package/dist/compiler.js +2 -1
  9. package/dist/component.js +2 -2
  10. package/dist/conditional.js +3 -3
  11. package/dist/config.d.ts +4 -0
  12. package/dist/conformance.js +2 -2
  13. package/dist/context.d.ts +4 -0
  14. package/dist/context.js +8 -0
  15. package/dist/errors.d.ts +14 -6
  16. package/dist/errors.js +14 -6
  17. package/dist/link-router.d.ts +5 -2
  18. package/dist/link-router.js +3 -1
  19. package/dist/link-routes.d.ts +35 -0
  20. package/dist/link-routes.js +435 -0
  21. package/dist/logical.js +3 -4
  22. package/dist/loops.js +16 -11
  23. package/dist/members.d.ts +3 -0
  24. package/dist/members.js +23 -11
  25. package/dist/model.d.ts +15 -0
  26. package/dist/model.js +33 -0
  27. package/dist/narrowing.js +13 -8
  28. package/dist/numbers.d.ts +2 -0
  29. package/dist/numbers.js +35 -1
  30. package/dist/operators.js +2 -2
  31. package/dist/page-routes.d.ts +1 -1
  32. package/dist/page-routes.js +1 -1
  33. package/dist/parens.d.ts +2 -0
  34. package/dist/parens.js +65 -1
  35. package/dist/plugins/router-link.js +39 -23
  36. package/dist/rust.d.ts +1 -1
  37. package/dist/rust.js +1 -1
  38. package/dist/schema.js +1 -0
  39. package/dist/script.d.ts +0 -2
  40. package/dist/script.js +24 -13
  41. package/dist/setup-writes.d.ts +15 -0
  42. package/dist/setup-writes.js +369 -0
  43. package/dist/slots.js +13 -2
  44. package/dist/ssr.d.ts +7 -1
  45. package/dist/ssr.js +4 -3
  46. package/dist/strings.js +24 -6
  47. package/dist/template.js +9 -1
  48. package/dist/vite.d.ts +1 -1
  49. package/dist/vite.js +30 -3
  50. package/package.json +5 -1
  51. package/schema.json +5 -0
package/dist/errors.js CHANGED
@@ -55,7 +55,7 @@ export const ERRORS = {
55
55
  },
56
56
  FV0105: {
57
57
  title: "Statement in setup that could change what renders",
58
- detail: "ferrovue translates setup to Rust and does not run it, so a statement that may change state the template reads (`count.value++`, `store.load()`, `items.push(x)`, a call of a function of another library) would render otherwise than Vue does. Lifecycle hooks such as `onMounted`, the compiler macros (`defineEmits`, `defineExpose`) and a `watch` without `immediate` are allowed. Move the statement into `onMounted` or an event handler, write the value as a `computed`, or compute it in Rust and pass it as a prop.",
58
+ detail: "ferrovue translates setup to Rust and does not run it, so a statement that may change state the template reads (`count.value++`, `store.load()`, `items.push(x)`, a call of a function of another library) would render otherwise than Vue does. The initial value of a `const` or `let` the compiler does not translate is refused the same way when running it could change that state: an assignment, `++` or `--`, a call of a function of setup, a method that changes a value of setup (`push`, `splice`), or a value of setup given to a function of another library. Lifecycle hooks such as `onMounted`, the compiler macros (`defineEmits`, `defineExpose`) and a `watch` without `immediate` are allowed. Move the statement into `onMounted` or an event handler, write the value as a `computed`, or compute it in Rust and pass it as a prop.",
59
59
  },
60
60
  FV0106: {
61
61
  title: "`defineAsyncComponent` of anything but a component of this project",
@@ -360,7 +360,7 @@ export const ERRORS = {
360
360
  },
361
361
  FV0413: {
362
362
  title: "`v-model` comparing values of types it cannot compare",
363
- detail: "`v-model` on a checkbox, a radio button or a `<select>` marks the option whose value is loosely equal to the model, which the server reproduces between two strings. Other pairs of types follow JavaScript's loose equality, which the server does not. Bind string values and a string model, or bind `:checked` or `:selected` yourself.",
363
+ detail: "`v-model` on a checkbox, a radio button or a `<select>` marks the option whose value is loosely equal to the model, which the server reproduces for a model that is a string, or a string that may be absent, against a string value, and for an `<option>` with no `value`, which Vue's server compares with `null`. Other pairs of types follow JavaScript's loose equality, which the server does not. Bind string values and a string model, or bind `:checked` or `:selected` yourself.",
364
364
  },
365
365
  FV0414: {
366
366
  title: "`v-model` over an array",
@@ -410,6 +410,10 @@ export const ERRORS = {
410
410
  title: "Element with no content given a custom directive and attributes that may hold its content",
411
411
  detail: "Vue's server renderer writes an element with no content and a custom directive with the `textContent` or `innerHTML` among the attributes it merges into the element: those passed to the component, when the element is its root, those of a `v-bind` of an object or an attribute named at run time, and a bound `textContent` or `innerHTML`. The compiler does not translate that reading. Wrap a root element in another element, such as a `<div>`, which then takes the attributes passed to the component, bind each attribute by its name, and write the content inside the element.",
412
412
  },
413
+ FV0426: {
414
+ title: "`v-model` on an `<input>` whose `type` is bound",
415
+ detail: "With a bound `type`, Vue's server renderer chooses as it renders what `v-model` writes: `checked` for a checkbox or a radio button, `value` for any other type, each by its own comparison with the model. The compiler translates `v-model` on an `<input>` of a literal `type`. Write the `type` as a literal, or write one `<input>` for each type under `v-if` and `v-else-if`.",
416
+ },
413
417
  FV0501: {
414
418
  title: "Child component that is not among the compiled components",
415
419
  detail: "A child component is rendered by calling its generated Rust module, so it must be a `.vue` file in the components directory that ferrovue compiles. A component imported from a library, from `node_modules` or from outside that directory has no module to call. Move the file into the components directory, or render it with a function of your own named under `twins` in `ferrovue.config.json`. See [`errors_and_limits`](crate::guide::errors_and_limits#rust-twins).",
@@ -452,7 +456,7 @@ export const ERRORS = {
452
456
  },
453
457
  FV0511: {
454
458
  title: "Prop given a value of another type",
455
- detail: "The prop's Rust type cannot hold the value, and Vue would hand it to the child as it is, so the child would read another type than it declares. The message names both types. Pass a value of the prop's type, convert it where it is passed, or change the prop's declared type.",
459
+ detail: "The prop's Rust type cannot hold the value, and Vue would hand it to the child as it is, so the child would read another type than it declares. The message names both types. Pass a value of the prop's type, convert it where it is passed, or change the prop's declared type. A `boolean` prop takes `true` from an attribute written bare, `\"\"` or the prop's name in kebab-case, which Vue casts; any other string reaches the child as a string.",
456
460
  },
457
461
  FV0512: {
458
462
  title: "Type imported from a component that is not compiled",
@@ -630,6 +634,10 @@ export const ERRORS = {
630
634
  title: "Comparison of a union of string literals with a literal outside it",
631
635
  detail: "A value typed as a union of string literals is a Rust enum, and `===` or `!==` with a literal compares it with one of its variants. A literal outside the union is no variant: the comparison would always be `false` (or `true` for `!==`), and TypeScript refuses it as a comparison of types with no overlap. Compare with one of the union's members, or fix the literal's spelling.",
632
636
  },
637
+ FV0638: {
638
+ title: "Member of a ref other than `.value` read in setup",
639
+ detail: "In `<script setup>`, a `ref`, a `shallowRef` or a `computed` is the ref object itself, whose only member is `.value`: `r.label` is `undefined`, `r.length` is `undefined` and `r.join()` throws. The template unwraps a ref, so there `r.label` reads the field of its value. Read the member through `.value` in setup: `r.value.label`.",
640
+ },
633
641
  FV0701: {
634
642
  title: "`Number()` of an unsupported value",
635
643
  detail: "`Number(x)` is translated for a string, read by JavaScript's grammar for numbers with `js_number`, a number and a boolean, each present. `Number()` gives `NaN` for `undefined` and `0` for `null`, and converts an object or a list through its `String()`, which the server's typed values do not reproduce. Narrow an optional value with `v-if` or give it a fallback with `??`, and read a date with `.getTime()`.",
@@ -723,8 +731,8 @@ export const ERRORS = {
723
731
  detail: "`String(x)`, `encodeURI(x)`, `encodeURIComponent(x)` and `s.concat(x)` take one value each and write it as `String()` does: strings, numbers and booleans, present or optional, and lists of them joined by `,`. An object writes `[object Object]`, and other values (a record, a date, a list of lists) by JavaScript rules the server does not reproduce. Pass the field you mean, format a date with `.toISOString()`, or build the string in Rust and pass it as a prop.",
724
732
  },
725
733
  FV0724: {
726
- title: "Integer beyond the range of `i64` where the template needs one, as it renders",
727
- detail: "Integer arithmetic is done on doubles, as JavaScript does it, and a result written into the page is written from the double. Where the template needs the result as an integer, as a child's `number` prop, an index or the count of a `v-for` over a range, it is held as an `i64`, which stops at ±2⁶³: a result beyond that is refused as the component renders, where a cast to `i64` would change the number. A generated `try_render` returns it as a `ferrovue::render::Refused`, with the component and the line and column of the expression, so a server can answer `400 Bad Request`; `render` panics with its message. See [`errors_and_limits`](crate::guide::errors_and_limits#refused-at-render-time). Keep integer props within ±2⁵³, where JavaScript's integers are exact, or type the child's prop `Float`. See [`numbers`](crate::guide::numbers).",
734
+ title: "Integer beyond the range of `i64` where the generated code holds one, as it renders",
735
+ detail: "Integer arithmetic is done on doubles, as JavaScript does it, and a result written into the page is written from the double. Where the generated code holds the result as an integer, as a child's `number` prop, an index, the count of a `v-for` over a range, or an integer a `computed`, a variable, a list or a callback such as `.reduce()`'s keeps, it is held as an `i64`, which stops at ±2⁶³: a result beyond that is refused as the component renders, where a cast to `i64` would change the number. A generated `try_render` returns it as a `ferrovue::render::Refused`, with the component and the line and column of the expression, so a server can answer `400 Bad Request`; `render` panics with its message. See [`errors_and_limits`](crate::guide::errors_and_limits#refused-at-render-time). Keep integer props within ±2⁵³, where JavaScript's integers are exact, or type the numbers it is computed from `Float`. See [`numbers`](crate::guide::numbers).",
728
736
  },
729
737
  FV0725: {
730
738
  title: "String longer than JavaScript allows, as it renders",
@@ -1561,7 +1569,7 @@ export const ERRORS = {
1561
1569
  },
1562
1570
  FV1708: {
1563
1571
  title: "`useHeadSafe`",
1564
- detail: "`useHeadSafe` passes its input through unhead's safe input plugin, which keeps only the tags and attributes it deems safe. ferrovue does not reproduce that filter. Use `useHead` with values the page trusts, and keep text you do not control out of `script` and `style`.",
1572
+ detail: "`useHeadSafe` passes its input through unhead's safe input plugin, which keeps only the tags and attributes it deems safe. ferrovue does not reproduce that filter. Use `useHead` with values the page trusts, and keep text you do not control out of `script`, `style` and `noscript`.",
1565
1573
  },
1566
1574
  FV1709: {
1567
1575
  title: "`useSeoMeta` key or value ferrovue does not translate",
@@ -1,6 +1,7 @@
1
1
  import { type RouteLocationNormalized, type Router, type RouterHistory } from "vue-router";
2
2
  import { type RouteEntry } from "./route-records.ts";
3
- /** What `linkRouter` hands navigations to, and the router options of `ferrovue.config.json`. */
3
+ /** What `linkRouter` hands navigations to, and the router options of `ferrovue.config.json`.
4
+ * @deprecated Use `linkRoutes` and `LinkRoutesOptions` from `ferrovue/link-routes`. */
4
5
  export interface LinkRouterOptions {
5
6
  /** The application's own navigation, called with the `href` of every navigation after the first
6
7
  * (the base included, as the link's `href` attribute has it) and the route it resolves to. */
@@ -23,5 +24,7 @@ export interface LinkRouterOptions {
23
24
  * layer leaves the page: built from the routes file the compiler reads, every route rendering
24
25
  * nothing. Its first navigation resolves the page the server rendered; every later one, a link's
25
26
  * click included, is handed to `navigate` and aborted, so the router stays on that page. Build one
26
- * for each page the application shows. */
27
+ * for each page the application shows.
28
+ * @deprecated Use `linkRoutes` from `ferrovue/link-routes`, which gives `<RouterLink>` and
29
+ * `useRoute()` the page's route with no router, in a fraction of the bytes. */
27
30
  export declare function linkRouter(routes: RouteEntry[], options: LinkRouterOptions): Router;
@@ -16,7 +16,9 @@ function pageHistory(base, location) {
16
16
  * layer leaves the page: built from the routes file the compiler reads, every route rendering
17
17
  * nothing. Its first navigation resolves the page the server rendered; every later one, a link's
18
18
  * click included, is handed to `navigate` and aborted, so the router stays on that page. Build one
19
- * for each page the application shows. */
19
+ * for each page the application shows.
20
+ * @deprecated Use `linkRoutes` from `ferrovue/link-routes`, which gives `<RouterLink>` and
21
+ * `useRoute()` the page's route with no router, in a fraction of the bytes. */
20
22
  export function linkRouter(routes, options) {
21
23
  const history = options.history ?? pageHistory(options.base, options.location);
22
24
  const router = createRouter({
@@ -0,0 +1,35 @@
1
+ import type { App } from "vue";
2
+ import { type RouteLocationNormalized, type RouteLocationNormalizedLoaded, type RouteLocationRaw, type RouteLocationResolved } from "vue-router";
3
+ import type { RouteEntry } from "./route-records.ts";
4
+ /** What `linkRoutes` hands navigations to, and the router options of `ferrovue.config.json`. */
5
+ export interface LinkRoutesOptions {
6
+ /** The application's own navigation, called with the `href` of every navigation (the base
7
+ * included, as the link's `href` attribute has it) and the route it resolves to. */
8
+ navigate: (href: string, to: RouteLocationNormalized) => void;
9
+ /** The base, as `router.base` in `ferrovue.config.json` gives it. Left out, there is no base,
10
+ * as on the server, whatever the page's `<base href>`. */
11
+ base?: string;
12
+ /** As `router.linkActiveClass` in `ferrovue.config.json`. */
13
+ linkActiveClass?: string;
14
+ /** As `router.linkExactActiveClass` in `ferrovue.config.json`. */
15
+ linkExactActiveClass?: string;
16
+ /** The location of the page, as an `href` with the base (the one `navigate` is given). The
17
+ * browser's location by default. */
18
+ location?: string;
19
+ }
20
+ /** A Vue plugin giving `<RouterLink>` and `useRoute()` the page's route, with no router. */
21
+ export interface LinkRoutes {
22
+ /** Registers vue-router's `<RouterLink>` and provides the page's route to it, to `useRoute()`
23
+ * and to `$route`. */
24
+ install(app: App): void;
25
+ /** `to` resolved as vue-router's `router.resolve(to)` resolves it on this page. */
26
+ resolve(to: RouteLocationRaw): RouteLocationResolved;
27
+ /** The page's route, as `useRoute()` gives it. */
28
+ readonly route: RouteLocationNormalizedLoaded;
29
+ }
30
+ /** `<RouterLink>` and `useRoute()` for an application whose own navigation layer leaves the page,
31
+ * with no router: a plugin that registers vue-router's `<RouterLink>` and gives it, `useRoute()`
32
+ * and `$route` the page's route, resolved from the routes file the compiler reads as vue-router
33
+ * resolves it. A link's click, the link to the current page included, is handed to `navigate`.
34
+ * Build one for each page the application shows. */
35
+ export declare function linkRoutes(routes: RouteEntry[], options: LinkRoutesOptions): LinkRoutes;
@@ -0,0 +1,435 @@
1
+ import { shallowReactive, shallowRef } from "vue";
2
+ import { RouterLink, routeLocationKey, routerKey } from "vue-router";
3
+ const isArray = Array.isArray;
4
+ const BASE_RE = "[^/]+?";
5
+ function tokenize(path) {
6
+ if (!path)
7
+ return [[]];
8
+ if (path === "/")
9
+ return [[""]];
10
+ if (path[0] !== "/")
11
+ throw new Error(`Invalid path "${path}"`);
12
+ const tokens = [];
13
+ let segment = [];
14
+ let state = 0;
15
+ let i = 0;
16
+ let char = "";
17
+ let buffer = "";
18
+ let custom = "";
19
+ const consume = () => {
20
+ if (buffer)
21
+ segment.push(state ? { name: buffer, re: custom, repeatable: char === "*" || char === "+", optional: char === "*" || char === "?" } : buffer);
22
+ buffer = "";
23
+ };
24
+ const close = () => {
25
+ consume();
26
+ state = 0;
27
+ if (char !== "*" && char !== "?" && char !== "+")
28
+ i--;
29
+ };
30
+ while (i < path.length) {
31
+ char = path[i++];
32
+ if (state === 0) {
33
+ if (char === "\\")
34
+ state = 4;
35
+ else if (char === "/") {
36
+ consume();
37
+ tokens.push(segment);
38
+ segment = [];
39
+ }
40
+ else if (char === ":") {
41
+ consume();
42
+ state = 1;
43
+ }
44
+ else
45
+ buffer += char;
46
+ }
47
+ else if (state === 4) {
48
+ buffer += char;
49
+ state = 0;
50
+ }
51
+ else if (state === 1) {
52
+ if (char === "(")
53
+ state = 2;
54
+ else if (/\w/.test(char))
55
+ buffer += char;
56
+ else
57
+ close();
58
+ }
59
+ else if (state === 2) {
60
+ if (char !== ")")
61
+ custom += char;
62
+ else if (custom.endsWith("\\"))
63
+ custom = custom.slice(0, -1) + char;
64
+ else
65
+ state = 3;
66
+ }
67
+ else {
68
+ close();
69
+ custom = "";
70
+ }
71
+ }
72
+ consume();
73
+ tokens.push(segment);
74
+ return tokens.slice(1);
75
+ }
76
+ function compareScores(a, b) {
77
+ for (let i = 0; i < a.length && i < b.length; i++)
78
+ if (b[i] - a[i])
79
+ return b[i] - a[i];
80
+ if (a.length < b.length)
81
+ return a.length === 1 && a[0] === 80 ? -1 : 1;
82
+ if (a.length > b.length)
83
+ return b.length === 1 && b[0] === 80 ? 1 : -1;
84
+ return 0;
85
+ }
86
+ const lastNegative = (score) => score.length > 0 && score.at(-1).at(-1) < 0;
87
+ function compare(a, b) {
88
+ for (let i = 0; i < a.score.length && i < b.score.length; i++) {
89
+ const c = compareScores(a.score[i], b.score[i]);
90
+ if (c)
91
+ return c;
92
+ }
93
+ if (Math.abs(b.score.length - a.score.length) === 1) {
94
+ if (lastNegative(a.score))
95
+ return 1;
96
+ if (lastNegative(b.score))
97
+ return -1;
98
+ }
99
+ return b.score.length - a.score.length;
100
+ }
101
+ function matcherOf(record, parent, matchable) {
102
+ const segments = tokenize(record.path);
103
+ const score = [];
104
+ const keys = [];
105
+ let pattern = "^";
106
+ for (const segment of segments) {
107
+ const scores = segment.length ? [] : [90];
108
+ segment.forEach((token, index) => {
109
+ let s = 40;
110
+ if (typeof token === "string") {
111
+ if (!index)
112
+ pattern += "/";
113
+ pattern += token.replace(/[.+*?^${}()[\]/\\]/g, "\\$&");
114
+ s += 40;
115
+ }
116
+ else {
117
+ keys.push(token);
118
+ const re = token.re || BASE_RE;
119
+ let sub = token.repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`;
120
+ if (!index)
121
+ sub = token.optional && segment.length < 2 ? `(?:/${sub})` : "/" + sub;
122
+ if (token.optional)
123
+ sub += "?";
124
+ pattern += sub;
125
+ s += (re === BASE_RE ? 20 : 30) - (token.optional ? 8 : 0) - (token.repeatable ? 20 : 0) - (re === ".*" ? 50 : 0);
126
+ }
127
+ scores.push(s);
128
+ });
129
+ score.push(scores);
130
+ }
131
+ return { re: new RegExp(pattern + "/?$", "i"), score, keys, segments, record, parent, matchable };
132
+ }
133
+ function stringify(matcher, params) {
134
+ let path = "";
135
+ let avoid = false;
136
+ for (const segment of matcher.segments) {
137
+ if (!avoid || !path.endsWith("/"))
138
+ path += "/";
139
+ avoid = false;
140
+ for (const token of segment) {
141
+ if (typeof token === "string") {
142
+ path += token;
143
+ continue;
144
+ }
145
+ const param = token.name in params ? params[token.name] : "";
146
+ if (isArray(param) && !token.repeatable)
147
+ throw new Error(`Param "${token.name}" is not repeatable`);
148
+ const text = isArray(param) ? param.join("/") : param;
149
+ if (!text) {
150
+ if (!token.optional)
151
+ throw new Error(`Missing required param "${token.name}"`);
152
+ if (segment.length < 2) {
153
+ if (path.endsWith("/"))
154
+ path = path.slice(0, -1);
155
+ else
156
+ avoid = true;
157
+ }
158
+ }
159
+ path += text;
160
+ }
161
+ }
162
+ return path || "/";
163
+ }
164
+ const encode = (text, re) => text == null ? "" : encodeURI(String(text)).replace(re, (m) => (m === "%20" ? "+" : m[0] === "%" ? decodeURIComponent(m) : encodeURIComponent(m)));
165
+ const encodeHash = (text) => encode(text, /%(5B|5D|7C|7B|7D|5E)/g);
166
+ const encodeQueryValue = (text) => encode(text, /%(5B|5D|7C|7B|7D|5E|60|20)|[+#&]/g);
167
+ const encodeParam = (text) => encode(text, /%(5B|5D|7C)|[#?/]/g);
168
+ function decode(text) {
169
+ if (text == null)
170
+ return null;
171
+ try {
172
+ return decodeURIComponent(String(text));
173
+ }
174
+ catch {
175
+ return String(text);
176
+ }
177
+ }
178
+ const mapParams = (f, params) => {
179
+ const out = {};
180
+ for (const key in params) {
181
+ const value = params[key];
182
+ out[key] = isArray(value) ? value.map(f) : f(value);
183
+ }
184
+ return out;
185
+ };
186
+ function parseQuery(search) {
187
+ const query = {};
188
+ if (search === "" || search === "?")
189
+ return query;
190
+ for (const part of (search[0] === "?" ? search.slice(1) : search).split("&")) {
191
+ const param = part.replace(/\+/g, " ");
192
+ const eq = param.indexOf("=");
193
+ const key = decode(eq < 0 ? param : param.slice(0, eq));
194
+ const value = eq < 0 ? null : decode(param.slice(eq + 1));
195
+ if (key in query) {
196
+ let current = query[key];
197
+ if (!isArray(current))
198
+ current = query[key] = [current];
199
+ current.push(value);
200
+ }
201
+ else
202
+ query[key] = value;
203
+ }
204
+ return query;
205
+ }
206
+ function stringifyQuery(query) {
207
+ let search = "";
208
+ for (const raw in query) {
209
+ const value = query[raw];
210
+ const key = encode(raw, /%(5B|5D|7C|7B|7D|5E|60|20)|[+#&=]/g);
211
+ if (value == null) {
212
+ if (value !== undefined)
213
+ search += (search.length ? "&" : "") + key;
214
+ continue;
215
+ }
216
+ for (const v of isArray(value) ? value.map((x) => x && encodeQueryValue(x)) : [value && encodeQueryValue(value)]) {
217
+ if (v !== undefined) {
218
+ search += (search.length ? "&" : "") + key;
219
+ if (v != null)
220
+ search += "=" + String(v);
221
+ }
222
+ }
223
+ }
224
+ return search;
225
+ }
226
+ function normalizeQuery(query) {
227
+ const out = {};
228
+ for (const key in query) {
229
+ const value = query[key];
230
+ if (value !== undefined)
231
+ out[key] = isArray(value) ? value.map((v) => (v == null ? null : String(v))) : value == null ? value : String(value);
232
+ }
233
+ return out;
234
+ }
235
+ function resolveRelativePath(to, from) {
236
+ if (to.startsWith("/"))
237
+ return to;
238
+ if (!to)
239
+ return from;
240
+ const fromSegments = from.split("/");
241
+ const toSegments = to.split("/");
242
+ const last = toSegments.at(-1);
243
+ if (last === ".." || last === ".")
244
+ toSegments.push("");
245
+ let position = fromSegments.length - 1;
246
+ let index = 0;
247
+ for (; index < toSegments.length; index++) {
248
+ const segment = toSegments[index];
249
+ if (segment === ".")
250
+ continue;
251
+ if (segment !== "..")
252
+ break;
253
+ if (position > 1)
254
+ position--;
255
+ }
256
+ return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(index).join("/");
257
+ }
258
+ function parseURL(location, current) {
259
+ let path;
260
+ let query = {};
261
+ let search = "";
262
+ let hash = "";
263
+ const hashPos = location.indexOf("#");
264
+ let searchPos = location.indexOf("?");
265
+ if (hashPos >= 0 && searchPos > hashPos)
266
+ searchPos = -1;
267
+ if (searchPos >= 0) {
268
+ path = location.slice(0, searchPos);
269
+ search = location.slice(searchPos, hashPos > 0 ? hashPos : location.length);
270
+ query = parseQuery(search.slice(1));
271
+ }
272
+ if (hashPos >= 0) {
273
+ path ||= location.slice(0, hashPos);
274
+ hash = location.slice(hashPos);
275
+ }
276
+ path = resolveRelativePath(path ?? location, current);
277
+ return { fullPath: path + search + hash, path, query, hash: decode(hash) };
278
+ }
279
+ function normalizeBase(base = "/") {
280
+ if (base[0] !== "/" && base[0] !== "#")
281
+ base = "/" + base;
282
+ return base.replace(/\/$/, "");
283
+ }
284
+ const START = { path: "/", name: undefined, params: {}, query: {}, hash: "", fullPath: "/", matched: [], meta: {}, redirectedFrom: undefined };
285
+ /** `<RouterLink>` and `useRoute()` for an application whose own navigation layer leaves the page,
286
+ * with no router: a plugin that registers vue-router's `<RouterLink>` and gives it, `useRoute()`
287
+ * and `$route` the page's route, resolved from the routes file the compiler reads as vue-router
288
+ * resolves it. A link's click, the link to the current page included, is handed to `navigate`.
289
+ * Build one for each page the application shows. */
290
+ export function linkRoutes(routes, options) {
291
+ const matchers = [];
292
+ const named = new Map();
293
+ const add = (entry, parent) => {
294
+ const raw = typeof entry === "string" ? { path: entry } : entry;
295
+ let path = raw.path;
296
+ if (parent && path[0] !== "/") {
297
+ const above = parent.record.path;
298
+ path = above + (path && (above.endsWith("/") ? "" : "/") + path);
299
+ }
300
+ const name = raw.name || undefined;
301
+ const matcher = matcherOf({ path, name, meta: {}, aliasOf: undefined }, parent, !!name || raw.view !== false);
302
+ if (matcher.matchable) {
303
+ let lower = 0;
304
+ let upper = matchers.length;
305
+ while (lower !== upper) {
306
+ const mid = (lower + upper) >> 1;
307
+ if (compare(matcher, matchers[mid]) < 0)
308
+ upper = mid;
309
+ else
310
+ lower = mid + 1;
311
+ }
312
+ for (let above = parent; above; above = above.parent) {
313
+ if (above.matchable && !compare(matcher, above)) {
314
+ upper = matchers.lastIndexOf(above, upper - 1);
315
+ break;
316
+ }
317
+ }
318
+ matchers.splice(upper, 0, matcher);
319
+ if (name)
320
+ named.set(name, matcher);
321
+ }
322
+ for (const child of raw.children ?? [])
323
+ add(child, matcher);
324
+ };
325
+ for (const entry of routes)
326
+ add(entry);
327
+ const pick = (params, keys) => {
328
+ const out = {};
329
+ for (const { name } of keys)
330
+ if (name in params)
331
+ out[name] = params[name];
332
+ return out;
333
+ };
334
+ const match = (location, current) => {
335
+ let matcher;
336
+ let params = {};
337
+ let path;
338
+ if (location.name) {
339
+ matcher = named.get(location.name);
340
+ if (!matcher)
341
+ throw new Error(`No match for ${JSON.stringify(location)}`);
342
+ params = Object.assign(pick(current.params, matcher.keys.filter((k) => !k.optional).concat(matcher.parent?.keys.filter((k) => k.optional) ?? [])), location.params && pick(location.params, matcher.keys));
343
+ path = stringify(matcher, params);
344
+ }
345
+ else if (location.path != null) {
346
+ path = location.path;
347
+ matcher = matchers.find((m) => m.re.test(path));
348
+ if (matcher) {
349
+ const found = path.match(matcher.re);
350
+ matcher.keys.forEach((key, i) => {
351
+ const value = found[i + 1] || "";
352
+ params[key.name] = value && key.repeatable ? value.split("/") : value;
353
+ });
354
+ for (const key of matcher.keys)
355
+ if (key.optional && !params[key.name])
356
+ delete params[key.name];
357
+ }
358
+ }
359
+ else {
360
+ matcher = current.name ? named.get(current.name) : matchers.find((m) => m.re.test(current.path));
361
+ if (!matcher)
362
+ throw new Error(`No match for ${JSON.stringify(location)}`);
363
+ params = Object.assign({}, current.params, location.params);
364
+ path = stringify(matcher, params);
365
+ }
366
+ const matched = [];
367
+ for (let m = matcher; m; m = m.parent)
368
+ matched.unshift(m.record);
369
+ return { name: matcher?.record.name, path, params, matched, meta: {} };
370
+ };
371
+ const base = normalizeBase(options.base);
372
+ const href = (fullPath) => base.replace(/^[^#]+#/, "#") + fullPath;
373
+ let current = START;
374
+ const resolve = (to) => {
375
+ if (typeof to === "string") {
376
+ const location = parseURL(to, current.path);
377
+ const matched = match({ path: location.path }, current);
378
+ return { ...location, ...matched, params: mapParams(decode, matched.params), redirectedFrom: undefined, href: href(location.fullPath) };
379
+ }
380
+ const raw = to;
381
+ const at = { ...current };
382
+ let location;
383
+ if (raw.path != null)
384
+ location = { ...raw, path: parseURL(raw.path, current.path).path };
385
+ else {
386
+ const params = { ...raw.params };
387
+ for (const key in params)
388
+ if (params[key] == null)
389
+ delete params[key];
390
+ location = { ...raw, params: mapParams(encodeParam, params) };
391
+ at.params = mapParams(encodeParam, at.params);
392
+ }
393
+ const matched = match(location, at);
394
+ const hash = raw.hash || "";
395
+ matched.params = mapParams(String, mapParams(decode, matched.params));
396
+ const query = raw.query ? stringifyQuery(raw.query) : "";
397
+ const fullPath = matched.path + (query && "?") + query + encodeHash(hash);
398
+ return { fullPath, hash, query: normalizeQuery(raw.query), ...matched, redirectedFrom: undefined, href: href(fullPath) };
399
+ };
400
+ const page = options.location ?? window.location.pathname + window.location.search + window.location.hash;
401
+ const end = page.search(/[?#]/);
402
+ const pathname = end < 0 ? page : page.slice(0, end);
403
+ current = resolve((base && pathname.toLowerCase().startsWith(base.toLowerCase()) ? pathname.slice(base.length) || "/" : pathname) + (end < 0 ? "" : page.slice(end)));
404
+ const route = {};
405
+ for (const key in START)
406
+ route[key] = current[key];
407
+ const reactive = shallowReactive(route);
408
+ const go = async (to) => {
409
+ const target = resolve(to);
410
+ try {
411
+ options.navigate(target.href, target);
412
+ }
413
+ catch (error) {
414
+ console.error(error);
415
+ throw error;
416
+ }
417
+ };
418
+ const router = {
419
+ currentRoute: shallowRef(current),
420
+ options: { linkActiveClass: options.linkActiveClass, linkExactActiveClass: options.linkExactActiveClass },
421
+ resolve,
422
+ push: go,
423
+ replace: (to) => go(typeof to === "string" ? parseURL(to, current.path) : to),
424
+ };
425
+ return {
426
+ route: reactive,
427
+ resolve: resolve,
428
+ install(app) {
429
+ app.component("RouterLink", RouterLink);
430
+ app.config.globalProperties.$route = current;
431
+ app.provide(routerKey, router);
432
+ app.provide(routeLocationKey, reactive);
433
+ },
434
+ };
435
+ }
package/dist/logical.js CHANGED
@@ -1,4 +1,4 @@
1
- import { absence, BOOL, enumOf, fail, falsyLiteral, FLOAT, joinTy, keptLiterals, literalsOf, nothing, opt, refusalAt, sameTy, STR, unionStr, variantPath, withAbsence } from "./model.js";
1
+ import { absence, BOOL, enumOf, fail, falsyLiteral, filledTy, FLOAT, joinTy, keptLiterals, literalsOf, nothing, opt, refusalAt, sameTy, STR, unionStr, variantPath, withAbsence } from "./model.js";
2
2
  import { enumListVal, exactlyEnum, intoEnum, knownLiteral } from "./enums.js";
3
3
  import { claim } from "./plugin.js";
4
4
  import { atom, bare, logical, strArg } from "./parens.js";
@@ -171,7 +171,8 @@ function orValues(comp, n, a, b) {
171
171
  function orUndefined(a) {
172
172
  const inner = keptLiterals(a.ty.k === "opt" ? a.ty.of : a.ty, (l) => !falsyLiteral(l));
173
173
  const src = a.ty.k === "opt" ? atom(a.code) : `Some(${bare(a.code)})`;
174
- return { code: `${src}.filter(|v| ${truthy({ code: "*v", ty: inner })})`, ty: opt(inner) };
174
+ const each = truthy({ code: "*v", ty: a.ty.k === "opt" ? a.ty.of : a.ty });
175
+ return { code: each === "true" ? src : `${src}.filter(|v| ${each})`, ty: opt(filledTy(inner)) };
175
176
  }
176
177
  function orSame(comp, n, a, b) {
177
178
  const k = known(a);
@@ -190,8 +191,6 @@ function notBooleans(comp, n, left, right) {
190
191
  return fail(comp, "FV0614", what, n, help);
191
192
  }
192
193
  function alwaysTruthy(ty) {
193
- if (ty.k === "html")
194
- return false;
195
194
  const literals = literalsOf(ty);
196
195
  if (literals !== undefined && literals.length > 0)
197
196
  return literals.every((l) => l !== "" && l !== 0);