@aerogel/plugin-routing 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,120 @@
1
- import type { Plugin as Plugin_2 } from '@aerogel/core';
2
- import type { RouteRecordRaw } from 'vue-router';
1
+ import { ComponentOptionsMixin } from 'vue';
2
+ import { ComponentProvideOptions } from 'vue';
3
+ import { ComputedRef } from 'vue';
4
+ import { DefineComponent } from 'vue';
5
+ import { Facade } from '@noeldemartin/utils';
6
+ import { HTMLAttributes } from 'vue';
7
+ import { Plugin as Plugin_2 } from '@aerogel/core';
8
+ import { PublicProps } from 'vue';
9
+ import { Ref } from 'vue';
10
+ import { RouteLocationNormalizedLoaded } from 'vue-router';
11
+ import { RouteLocationRaw } from 'vue-router';
12
+ import { RouteParams } from 'vue-router';
13
+ import { RouteParamValue } from 'vue-router';
14
+ import { Router as Router_2 } from 'vue-router';
15
+ import { RouteRecordRaw } from 'vue-router';
16
+ import { ServiceWithState } from '@aerogel/core';
17
+ import { WatchStopHandle } from 'vue';
3
18
 
4
- declare interface Options {
19
+ declare const __VLS_component: DefineComponent<__VLS_Props, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, {}, string, PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, ComponentProvideOptions, false, {}, HTMLElement>;
20
+
21
+ declare type __VLS_Props = {
22
+ class?: HTMLAttributes['class'];
23
+ };
24
+
25
+ declare function __VLS_template(): {
26
+ attrs: Partial<{}>;
27
+ slots: {
28
+ default?(_: {}): any;
29
+ };
30
+ refs: {};
31
+ rootEl: HTMLElement;
32
+ };
33
+
34
+ declare type __VLS_TemplateResult = ReturnType<typeof __VLS_template>;
35
+
36
+ declare type __VLS_WithTemplateSlots<T, S> = T & {
37
+ new (): {
38
+ $slots: S;
39
+ };
40
+ };
41
+
42
+ export declare type AerogelRoute = RouteRecordRaw & {
43
+ title?: string | ((params: Record<string, unknown>) => string | undefined | null);
44
+ };
45
+
46
+ export declare class BindingNotFound {
47
+ value: string;
48
+ constructor(value: string);
49
+ }
50
+
51
+ declare const _default: ServiceWithState< {
52
+ flashRoute: RouteLocationRaw | null;
53
+ }, {}, Partial<{
54
+ flashRoute: RouteLocationRaw | null;
55
+ }>>;
56
+
57
+ export declare function defineRoute(route: AerogelRoute): RouteRecordRaw;
58
+
59
+ export declare function defineRouteBindings(bindings: RouteBindings): RouteBindings;
60
+
61
+ export declare function defineRoutes(routes: AerogelRoute[]): RouteRecordRaw[];
62
+
63
+ export declare type LoadedRoute = Omit<RouteLocationNormalizedLoaded, 'params'> & {
64
+ rawParams: RouteParams;
65
+ params?: Record<string, unknown>;
66
+ };
67
+
68
+ export declare interface Options {
5
69
  routes: RouteRecordRaw[];
70
+ bindings?: RouteBindings;
6
71
  basePath?: string;
7
72
  }
8
73
 
74
+ export declare const Page: __VLS_WithTemplateSlots<typeof __VLS_component, __VLS_TemplateResult["slots"]>;
75
+
76
+ export declare type RouteBinding = (slug: string, params: Record<string, unknown>) => unknown | Promise<unknown>;
77
+
78
+ export declare type RouteBindings = Record<string, RouteBinding>;
79
+
80
+ export declare const Router: Facade<RouterService>;
81
+
82
+ export declare class RouterService extends _default {
83
+ readonly currentRoute: ComputedRef<LoadedRoute | null>;
84
+ readonly routesParams: Ref<Record<string, Record<string, unknown>>>;
85
+ protected router: Ref<Router_2 | null>;
86
+ protected bindings: RouteBindings;
87
+ protected history: string[];
88
+ protected routesStopWatchers: Record<string, WatchStopHandle[]>;
89
+ constructor();
90
+ use(router: Router_2, options?: {
91
+ bindings?: RouteBindings;
92
+ }): void;
93
+ protected boot(): Promise<void>;
94
+ protected __get(property: string): unknown;
95
+ protected onEnterRoute(path: string, params: RouteParams): Promise<void>;
96
+ protected handleStatic404Redirect(): void;
97
+ protected storeFlashRoute(): void;
98
+ protected restoreFlashRoute(): Promise<void>;
99
+ protected resolveBinding(path: string, name: string, value: RouteParamValue | RouteParamValue[]): Promise<Ref<unknown>>;
100
+ }
101
+
102
+ export declare interface RouterService extends Omit<Router_2, 'currentRoute'> {
103
+ }
104
+
9
105
  declare function routing(options: Options): Plugin_2;
10
106
  export default routing;
11
107
 
108
+ export declare type RoutingServices = typeof services;
109
+
110
+ declare const services: {
111
+ $router: Facade<RouterService>;
112
+ };
113
+
12
114
  export { }
115
+
116
+
117
+ declare module '@aerogel/core' {
118
+ interface Services extends RoutingServices {
119
+ }
120
+ }
@@ -0,0 +1,244 @@
1
+ var k = Object.defineProperty;
2
+ var A = (e, s, t) => s in e ? k(e, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[s] = t;
3
+ var u = (e, s, t) => A(e, typeof s != "symbol" ? s + "" : s, t);
4
+ import W from "virtual:aerogel";
5
+ import { defineServiceState as $, Events as f, App as l, computedAsync as j, classes as T, Link as V, UI as O, setMarkdownRouter as C, bootServices as G } from "@aerogel/core";
6
+ import { useRoute as z, createRouter as L, createWebHistory as M, RouterLink as q } from "vue-router";
7
+ import { customRef as D, watch as E, shallowRef as R, computed as h, unref as N, ref as H, defineComponent as p, createElementBlock as I, openBlock as x, normalizeClass as U, renderSlot as J, createBlock as K, withCtx as y, createElementVNode as Q, createVNode as X, toDisplayString as g, createTextVNode as Y, watchEffect as Z, h as b } from "vue";
8
+ import { computedModel as ee } from "@aerogel/plugin-soukai";
9
+ import { objectWithout as P, tap as te, facade as se, once as re, objectOnly as d, Storage as oe } from "@noeldemartin/utils";
10
+ function ne(e, s) {
11
+ return D((t, r) => {
12
+ let o = P(c.routesParams.value[e] ?? {}, s);
13
+ return E(c.routesParams, () => {
14
+ const n = P(c.routesParams.value[e] ?? {}, s);
15
+ for (const [i, a] of Object.entries(n))
16
+ if (a === o[i]) {
17
+ o = n, r();
18
+ return;
19
+ }
20
+ }), {
21
+ get: () => te(o, () => t()),
22
+ // eslint-disable-next-line no-console
23
+ set: () => console.warn("Computed models ref was not set (it is immutable).")
24
+ };
25
+ });
26
+ }
27
+ const ae = $({
28
+ name: "router",
29
+ initialState: {
30
+ flashRoute: null
31
+ },
32
+ persist: ["flashRoute"]
33
+ });
34
+ class ue extends ae {
35
+ constructor() {
36
+ super();
37
+ u(this, "currentRoute");
38
+ u(this, "routesParams");
39
+ u(this, "router");
40
+ u(this, "bindings");
41
+ u(this, "history");
42
+ u(this, "routesStopWatchers");
43
+ this.router = R(null), this.bindings = {}, this.history = [], this.routesStopWatchers = {}, this.routesParams = R({}), this.currentRoute = h(() => {
44
+ const t = this.router.value, r = this.routesParams.value;
45
+ if (!t)
46
+ return null;
47
+ const o = N(t.currentRoute);
48
+ return {
49
+ ...o,
50
+ params: r == null ? void 0 : r[o.path],
51
+ rawParams: o.params
52
+ };
53
+ });
54
+ }
55
+ use(t, r = {}) {
56
+ this.router.value = t, this.bindings = r.bindings ?? {}, t.beforeEach(re(() => this.handleStatic404Redirect())), t.beforeEach((o) => this.onEnterRoute(o.path, o.params));
57
+ }
58
+ async boot() {
59
+ f.on("auth:before-login", () => this.storeFlashRoute()), f.on("auth:login", () => this.restoreFlashRoute()), f.on("purge-storage", () => this.push({ name: "home" }));
60
+ }
61
+ __get(t) {
62
+ return this.router.value ? super.__get(t) ?? Reflect.get(this.router.value, t) : super.__get(t);
63
+ }
64
+ async onEnterRoute(t, r) {
65
+ var i;
66
+ if (t in this.routesParams.value)
67
+ return;
68
+ const o = { ...r };
69
+ for (const [a, m] of Object.entries(r)) {
70
+ const v = await this.resolveBinding(t, a, m);
71
+ E(v, (B) => {
72
+ this.routesParams.value = {
73
+ ...this.routesParams.value,
74
+ [t]: {
75
+ ...this.routesParams.value[t],
76
+ [a]: B
77
+ }
78
+ };
79
+ }), o[a] = v.value;
80
+ }
81
+ this.history = this.history.slice(0, 3), this.history.unshift(t);
82
+ const n = {
83
+ ...this.routesParams.value,
84
+ [t]: {
85
+ ...o,
86
+ ...this.routesParams.value[t] ?? {}
87
+ }
88
+ };
89
+ for (const a in n)
90
+ this.history.includes(a) || (i = this.routesStopWatchers[a]) == null || i.forEach((m) => m());
91
+ this.routesParams.value = d(n, this.history), this.routesStopWatchers = d(this.routesStopWatchers, this.history);
92
+ }
93
+ handleStatic404Redirect() {
94
+ const t = oe.pull("static-404-redirect");
95
+ t && this.replace(t);
96
+ }
97
+ storeFlashRoute() {
98
+ this.flashRoute = d(this.currentRoute.value, [
99
+ "path",
100
+ "query",
101
+ "hash"
102
+ ]);
103
+ }
104
+ async restoreFlashRoute() {
105
+ if (!this.flashRoute)
106
+ return;
107
+ const t = this.flashRoute;
108
+ l.whenReady(() => this.replace(t)), this.flashRoute = null;
109
+ }
110
+ async resolveBinding(t, r, o) {
111
+ const n = this.bindings[r];
112
+ if (Array.isArray(o) || !n)
113
+ return H(o);
114
+ await l.ready;
115
+ const i = ne(t, r), a = j(() => Promise.resolve(n(o, i.value)));
116
+ return ee(() => a.value);
117
+ }
118
+ }
119
+ const c = se(ue);
120
+ class ie {
121
+ constructor(s) {
122
+ this.value = s;
123
+ }
124
+ }
125
+ const ce = /* @__PURE__ */ p({
126
+ __name: "Page",
127
+ props: {
128
+ class: {}
129
+ },
130
+ setup(e) {
131
+ const s = h(() => T("mx-auto flex w-full max-w-screen-content grow flex-col px-edge py-8", e.class));
132
+ return (t, r) => (x(), I("main", {
133
+ class: U(s.value)
134
+ }, [
135
+ J(t.$slots, "default")
136
+ ], 2));
137
+ }
138
+ }), le = { class: "text-2xl font-bold" }, F = /* @__PURE__ */ p({
139
+ __name: "NotFound",
140
+ setup(e) {
141
+ return (s, t) => (x(), K(ce, { class: "items-center justify-center" }, {
142
+ default: y(() => [
143
+ Q("h2", le, g(s.$td("notFound.title", "404: Not Found")), 1),
144
+ X(N(V), { route: "home" }, {
145
+ default: y(() => [
146
+ Y(g(s.$td("notFound.home", "Go home")), 1)
147
+ ]),
148
+ _: 1
149
+ })
150
+ ]),
151
+ _: 1
152
+ }));
153
+ }
154
+ });
155
+ function he(e, s) {
156
+ const t = z(), r = h(() => {
157
+ var n;
158
+ return (n = c.routesParams) == null ? void 0 : n.value[t.path];
159
+ }), o = h(() => !(s != null && s.title) || !r.value ? null : typeof s.title == "string" ? s.title : s.title(r.value));
160
+ return Z(() => de(o.value)), () => Object.values(r.value ?? {}).some((n) => n instanceof ie) ? b(F) : b(e, r.value);
161
+ }
162
+ function _(e, s) {
163
+ return p({
164
+ setup: () => he(e, s)
165
+ });
166
+ }
167
+ function me(e) {
168
+ if (e.component) {
169
+ if (typeof e.component == "function") {
170
+ const s = e.component;
171
+ e.component = async () => {
172
+ const { default: t } = await s();
173
+ return _(t, e);
174
+ };
175
+ return;
176
+ }
177
+ e.component = _(e.component, e);
178
+ }
179
+ }
180
+ function w(e) {
181
+ return async function(...s) {
182
+ return await l.ready, e.call(this, ...s);
183
+ };
184
+ }
185
+ function fe(e) {
186
+ if (e.beforeEnter) {
187
+ if (Array.isArray(e.beforeEnter)) {
188
+ e.beforeEnter = e.beforeEnter.map(w);
189
+ return;
190
+ }
191
+ e.beforeEnter = w(e.beforeEnter);
192
+ }
193
+ }
194
+ function de(e) {
195
+ if (globalThis.document) {
196
+ if (!e) {
197
+ globalThis.document.title = l.name;
198
+ return;
199
+ }
200
+ globalThis.document.title = `${e} | ${l.name}`;
201
+ }
202
+ }
203
+ function S(e) {
204
+ return me(e), fe(e), e;
205
+ }
206
+ function we(e) {
207
+ return e;
208
+ }
209
+ function Se(e) {
210
+ const s = e.map(S);
211
+ return s.some((t) => t.name === "not-found" || t.name === "404") || s.push(
212
+ S({
213
+ name: "not-found",
214
+ path: "/:path(.*)*",
215
+ component: F
216
+ })
217
+ ), s;
218
+ }
219
+ const pe = { $router: c };
220
+ function Ee(e) {
221
+ return {
222
+ async install(s) {
223
+ const t = L({
224
+ routes: e.routes,
225
+ history: M(e.basePath ?? W.basePath)
226
+ });
227
+ O.registerComponent("router-link", q), c.use(t, e), s.use(t), C({
228
+ resolve: (r) => t.resolve({ name: r }).href,
229
+ visit: async (r) => void await t.push({ name: r })
230
+ }), await G(s, pe);
231
+ }
232
+ };
233
+ }
234
+ export {
235
+ ie as BindingNotFound,
236
+ ce as Page,
237
+ c as Router,
238
+ ue as RouterService,
239
+ Ee as default,
240
+ S as defineRoute,
241
+ we as defineRouteBindings,
242
+ Se as defineRoutes
243
+ };
244
+ //# sourceMappingURL=aerogel-plugin-routing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aerogel-plugin-routing.js","sources":["../src/utils/internal.ts","../src/services/Router.state.ts","../src/services/Router.ts","../src/utils/BindingNotFound.ts","../src/components/Page.vue","../src/utils/routes.ts","../src/index.ts"],"sourcesContent":["import { objectWithout, tap } from '@noeldemartin/utils';\nimport { customRef, watch } from 'vue';\nimport type { ComputedRef } from 'vue';\n\nimport Router from '@aerogel/plugin-routing/services/Router';\n\nexport function computedRouteParams(path: string, exclude: string): ComputedRef<Record<string, unknown>> {\n return customRef((track, trigger) => {\n let value = objectWithout(Router.routesParams.value[path] ?? {}, exclude);\n\n watch(Router.routesParams, () => {\n const newParams = objectWithout(Router.routesParams.value[path] ?? {}, exclude);\n\n for (const [paramName, paramValue] of Object.entries(newParams)) {\n if (paramValue !== value[paramName as keyof typeof value]) {\n continue;\n }\n\n value = newParams;\n trigger();\n return;\n }\n });\n\n return {\n get: () => tap(value, () => track()),\n\n // eslint-disable-next-line no-console\n set: () => console.warn('Computed models ref was not set (it is immutable).'),\n };\n }) as ComputedRef<Record<string, unknown>>;\n}\n","import { defineServiceState } from '@aerogel/core';\nimport type { RouteLocationRaw } from 'vue-router';\n\nexport default defineServiceState({\n name: 'router',\n initialState: {\n flashRoute: null as RouteLocationRaw | null,\n },\n persist: ['flashRoute'],\n});\n","import { computed, ref, shallowRef, unref, watch } from 'vue';\nimport { computedModel } from '@aerogel/plugin-soukai';\nimport { App, Events, computedAsync } from '@aerogel/core';\nimport { Storage, facade, objectOnly, once } from '@noeldemartin/utils';\nimport type { ComputedRef, Ref, WatchStopHandle } from 'vue';\nimport type { RouteLocationNormalizedLoaded, RouteLocationRaw, RouteParamValue, RouteParams, Router } from 'vue-router';\n\nimport { computedRouteParams } from '@aerogel/plugin-routing/utils/internal';\n\nimport Service from './Router.state';\n\nexport type LoadedRoute = Omit<RouteLocationNormalizedLoaded, 'params'> & {\n rawParams: RouteParams;\n params?: Record<string, unknown>;\n};\nexport type RouteBinding = (slug: string, params: Record<string, unknown>) => unknown | Promise<unknown>;\nexport type RouteBindings = Record<string, RouteBinding>;\n\nexport class RouterService extends Service {\n\n public readonly currentRoute: ComputedRef<LoadedRoute | null>;\n public readonly routesParams: Ref<Record<string, Record<string, unknown>>>;\n protected router: Ref<Router | null>;\n protected bindings: RouteBindings;\n protected history: string[];\n protected routesStopWatchers: Record<string, WatchStopHandle[]>;\n\n constructor() {\n super();\n\n this.router = shallowRef(null);\n this.bindings = {};\n this.history = [];\n this.routesStopWatchers = {};\n this.routesParams = shallowRef({});\n this.currentRoute = computed(() => {\n const router = this.router.value;\n const routesParams = this.routesParams.value;\n\n if (!router) {\n return null;\n }\n\n const route = unref(router.currentRoute);\n\n return {\n ...route,\n params: routesParams?.[route.path],\n rawParams: route.params,\n };\n });\n }\n\n public use(router: Router, options: { bindings?: RouteBindings } = {}): void {\n this.router.value = router;\n this.bindings = options.bindings ?? {};\n\n router.beforeEach(once(() => this.handleStatic404Redirect()));\n router.beforeEach((to) => this.onEnterRoute(to.path, to.params));\n }\n\n protected override async boot(): Promise<void> {\n Events.on('auth:before-login', () => this.storeFlashRoute());\n Events.on('auth:login', () => this.restoreFlashRoute());\n Events.on('purge-storage', () => this.push({ name: 'home' }));\n }\n\n protected override __get(property: string): unknown {\n return this.router.value\n ? (super.__get(property) ?? Reflect.get(this.router.value, property))\n : super.__get(property);\n }\n\n protected async onEnterRoute(path: string, params: RouteParams): Promise<void> {\n if (path in this.routesParams.value) {\n return;\n }\n\n const resolvedParams: Record<string, unknown> = { ...params };\n const stopWatchers: WatchStopHandle[] = [];\n\n for (const [paramName, paramValue] of Object.entries(params)) {\n const resolvedValue = await this.resolveBinding(path, paramName, paramValue);\n const stopWatcher = watch(resolvedValue, (newValue) => {\n this.routesParams.value = {\n ...this.routesParams.value,\n [path]: {\n ...this.routesParams.value[path],\n [paramName]: newValue,\n },\n };\n });\n\n stopWatchers.push(stopWatcher);\n\n resolvedParams[paramName] = resolvedValue.value;\n }\n\n this.history = this.history.slice(0, 3);\n this.history.unshift(path);\n\n const routesParams = {\n ...this.routesParams.value,\n [path]: {\n ...resolvedParams,\n ...(this.routesParams.value[path] ?? {}),\n },\n };\n\n for (const routePath in routesParams) {\n if (this.history.includes(routePath)) {\n continue;\n }\n\n this.routesStopWatchers[routePath]?.forEach((stop) => stop());\n }\n\n this.routesParams.value = objectOnly(routesParams, this.history);\n this.routesStopWatchers = objectOnly(this.routesStopWatchers, this.history);\n }\n\n protected handleStatic404Redirect(): void {\n const route = Storage.pull<RouteLocationRaw>('static-404-redirect');\n\n route && this.replace(route);\n }\n\n protected storeFlashRoute(): void {\n this.flashRoute = objectOnly(this.currentRoute.value as unknown as Record<string, unknown>, [\n 'path',\n 'query',\n 'hash',\n ]) as RouteLocationRaw;\n }\n\n protected async restoreFlashRoute(): Promise<void> {\n if (!this.flashRoute) {\n return;\n }\n\n const flashRoute = this.flashRoute;\n\n App.whenReady(() => this.replace(flashRoute));\n\n this.flashRoute = null;\n }\n\n protected async resolveBinding(\n path: string,\n name: string,\n value: RouteParamValue | RouteParamValue[],\n ): Promise<Ref<unknown>> {\n const binding = this.bindings[name];\n\n if (Array.isArray(value) || !binding) {\n return ref(value);\n }\n\n await App.ready;\n\n const otherParams = computedRouteParams(path, name);\n const computedBinding = computedAsync(() => Promise.resolve(binding(value, otherParams.value)));\n\n return computedModel(() => computedBinding.value);\n }\n\n}\n\nexport interface RouterService extends Omit<Router, 'currentRoute'> {}\n\nexport default facade(RouterService);\n","export default class BindingNotFound {\n\n constructor(public value: string) {}\n\n}\n","<template>\n <main :class=\"renderedRootClasses\">\n <slot />\n </main>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport { classes } from '@aerogel/core';\nimport type { HTMLAttributes } from 'vue';\n\nconst { class: rootClasses } = defineProps<{ class?: HTMLAttributes['class'] }>();\n\nconst renderedRootClasses = computed(() =>\n classes('mx-auto flex w-full max-w-screen-content grow flex-col px-edge py-8', rootClasses));\n</script>\n","import { App } from '@aerogel/core';\nimport { computed, defineComponent, h, watchEffect } from 'vue';\nimport { useRoute } from 'vue-router';\nimport type { Component, ConcreteComponent } from 'vue';\nimport type { NavigationGuardWithThis, RouteRecordRaw } from 'vue-router';\n\nimport NotFound from '@aerogel/plugin-routing/pages/NotFound.vue';\nimport Router from '@aerogel/plugin-routing/services/Router';\nimport BindingNotFound from '@aerogel/plugin-routing/utils/BindingNotFound';\nimport type { RouteBindings } from '@aerogel/plugin-routing/services/Router';\n\nexport type AerogelRoute = RouteRecordRaw & {\n title?: string | ((params: Record<string, unknown>) => string | undefined | null);\n};\n\nfunction setupPageComponent(pageComponent: ConcreteComponent, routeConfig: AerogelRoute) {\n const route = useRoute();\n const pageParams = computed(() => Router.routesParams?.value[route.path]);\n const routeTitle = computed(() => {\n if (!routeConfig?.title || !pageParams.value) {\n return null;\n }\n\n if (typeof routeConfig.title === 'string') {\n return routeConfig.title;\n }\n\n return routeConfig.title(pageParams.value);\n });\n\n watchEffect(() => updateRouteTitle(routeTitle.value));\n\n return () =>\n Object.values(pageParams.value ?? {}).some((value) => value instanceof BindingNotFound)\n ? h(NotFound)\n : h(pageComponent, pageParams.value);\n}\n\nfunction defineRouteComponent(pageComponent: ConcreteComponent, route: AerogelRoute): Component {\n return defineComponent({\n setup: () => setupPageComponent(pageComponent, route),\n });\n}\n\nfunction enhanceRouteComponent(route: AerogelRoute): void {\n if (!route.component) {\n return;\n }\n\n if (typeof route.component === 'function') {\n const lazyComponent = route.component as () => Promise<{ default: ConcreteComponent }>;\n\n route.component = async () => {\n const { default: component } = await lazyComponent();\n\n return defineRouteComponent(component, route);\n };\n\n return;\n }\n\n route.component = defineRouteComponent(route.component, route);\n}\n\nfunction enhanceRouteNavigationGuard(guard: NavigationGuardWithThis<undefined>): NavigationGuardWithThis<undefined> {\n return async function(this, ...args) {\n await App.ready;\n\n return guard.call(this, ...args);\n };\n}\n\nfunction enhanceRouteNavigationGuards(route: AerogelRoute): void {\n if (!route.beforeEnter) {\n return;\n }\n\n if (Array.isArray(route.beforeEnter)) {\n route.beforeEnter = route.beforeEnter.map(enhanceRouteNavigationGuard);\n\n return;\n }\n\n route.beforeEnter = enhanceRouteNavigationGuard(route.beforeEnter);\n}\n\nfunction updateRouteTitle(title?: string | null): void {\n if (!globalThis.document) {\n return;\n }\n\n if (!title) {\n globalThis.document.title = App.name;\n\n return;\n }\n\n globalThis.document.title = `${title} | ${App.name}`;\n}\n\nexport function defineRoute(route: AerogelRoute): RouteRecordRaw {\n enhanceRouteComponent(route);\n enhanceRouteNavigationGuards(route);\n\n return route;\n}\n\nexport function defineRouteBindings(bindings: RouteBindings): RouteBindings {\n return bindings;\n}\n\nexport function defineRoutes(routes: AerogelRoute[]): RouteRecordRaw[] {\n const aerogelRoutes = routes.map(defineRoute);\n\n if (!aerogelRoutes.some((route) => route.name === 'not-found' || route.name === '404')) {\n aerogelRoutes.push(\n defineRoute({\n name: 'not-found',\n path: '/:path(.*)*',\n component: NotFound,\n }),\n );\n }\n\n return aerogelRoutes;\n}\n","import Aerogel from 'virtual:aerogel';\n\nimport { UI, bootServices, setMarkdownRouter } from '@aerogel/core';\nimport { RouterLink, createRouter, createWebHistory } from 'vue-router';\nimport type { Plugin } from '@aerogel/core';\nimport type { RouteRecordRaw } from 'vue-router';\n\nimport Router from './services/Router';\nimport type { RouteBindings } from './services/Router';\n\nconst services = { $router: Router };\n\nexport * from './services/Router';\nexport * from './utils';\nexport * from './components';\nexport { default as Router } from './services/Router';\n\nexport interface Options {\n routes: RouteRecordRaw[];\n bindings?: RouteBindings;\n basePath?: string;\n}\n\nexport type RoutingServices = typeof services;\n\nexport default function routing(options: Options): Plugin {\n return {\n async install(app) {\n const router = createRouter({\n routes: options.routes,\n history: createWebHistory(options.basePath ?? Aerogel.basePath),\n });\n\n UI.registerComponent('router-link', RouterLink);\n Router.use(router, options);\n app.use(router);\n\n setMarkdownRouter({\n resolve: (route) => router.resolve({ name: route }).href,\n visit: async (route) => void (await router.push({ name: route })),\n });\n\n await bootServices(app, services);\n },\n };\n}\n\ndeclare module '@aerogel/core' {\n interface Services extends RoutingServices {}\n}\n"],"names":["computedRouteParams","path","exclude","customRef","track","trigger","value","objectWithout","Router","watch","newParams","paramName","paramValue","tap","Service","defineServiceState","RouterService","__publicField","shallowRef","computed","router","routesParams","route","unref","options","once","to","Events","property","params","resolvedParams","resolvedValue","newValue","routePath","_a","stop","objectOnly","Storage","flashRoute","App","name","binding","ref","otherParams","computedBinding","computedAsync","computedModel","facade","BindingNotFound","renderedRootClasses","classes","__props","setupPageComponent","pageComponent","routeConfig","useRoute","pageParams","routeTitle","watchEffect","updateRouteTitle","h","NotFound","defineRouteComponent","defineComponent","enhanceRouteComponent","lazyComponent","component","enhanceRouteNavigationGuard","guard","args","enhanceRouteNavigationGuards","title","defineRoute","defineRouteBindings","bindings","defineRoutes","routes","aerogelRoutes","services","routing","app","createRouter","createWebHistory","Aerogel","UI","RouterLink","setMarkdownRouter","bootServices"],"mappings":";;;;;;;;;AAMgB,SAAAA,GAAoBC,GAAcC,GAAuD;AAC9F,SAAAC,EAAU,CAACC,GAAOC,MAAY;AAC7B,QAAAC,IAAQC,EAAcC,EAAO,aAAa,MAAMP,CAAI,KAAK,CAAC,GAAGC,CAAO;AAElE,WAAAO,EAAAD,EAAO,cAAc,MAAM;AACvB,YAAAE,IAAYH,EAAcC,EAAO,aAAa,MAAMP,CAAI,KAAK,CAAC,GAAGC,CAAO;AAE9E,iBAAW,CAACS,GAAWC,CAAU,KAAK,OAAO,QAAQF,CAAS;AACtD,YAAAE,MAAeN,EAAMK,CAA+B,GAIhD;AAAA,UAAAL,IAAAI,GACAL,EAAA;AACR;AAAA;AAAA,IACJ,CACH,GAEM;AAAA,M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AAaP,GAAKF,EAAQ;AAAA,IAAA;AAAA,EAExC;AACJ;"}
package/package.json CHANGED
@@ -1,42 +1,44 @@
1
1
  {
2
2
  "name": "@aerogel/plugin-routing",
3
- "description": "Aerogel routing plugin",
4
- "version": "0.0.0",
5
- "main": "dist/aerogel-plugin-routing.cjs.js",
6
- "module": "dist/aerogel-plugin-routing.esm.js",
7
- "types": "dist/aerogel-plugin-routing.d.ts",
3
+ "version": "0.1.0",
4
+ "type": "module",
8
5
  "sideEffects": false,
9
- "scripts": {
10
- "build": "rm dist -rf && npm run build:js && npm run build:types",
11
- "build:js": "noeldemartin-build-javascript",
12
- "build:types": "noeldemartin-build-types",
13
- "publish-next": "noeldemartin-publish-next",
14
- "lint": "noeldemartin-lint src"
15
- },
16
- "engines": {
17
- "node": ">=18.x"
6
+ "exports": {
7
+ "types": "./dist/aerogel-plugin-routing.d.ts",
8
+ "style": "./src/index.css",
9
+ "default": "./dist/aerogel-plugin-routing.js"
18
10
  },
19
- "repository": {
20
- "type": "git",
21
- "url": "https://github.com/NoelDeMartin/aerogeljs.git"
22
- },
23
- "keywords": [
24
- "javascript",
25
- "aerogel"
11
+ "files": [
12
+ "src",
13
+ "dist"
26
14
  ],
27
- "author": "Noel De Martin",
28
15
  "license": "MIT",
29
- "bugs": {
30
- "url": "https://github.com/NoelDeMartin/aerogeljs/issues"
16
+ "author": "Noel De Martin",
17
+ "repository": "github:NoelDeMartin/aerogel",
18
+ "scripts": {
19
+ "build": "vite build",
20
+ "lint": "noeldemartin-lint src",
21
+ "test": "vitest --run",
22
+ "test:ci": "vitest --run --reporter verbose",
23
+ "verify": "noeldemartin-verify"
31
24
  },
32
25
  "peerDependencies": {
33
- "@aerogel/core": "*"
26
+ "@aerogel/core": "*",
27
+ "@aerogel/plugin-soukai": "*",
28
+ "@aerogel/vite": "*",
29
+ "vue-router": "^4.5.0"
34
30
  },
35
31
  "dependencies": {
36
- "@noeldemartin/utils": "0.4.0-next.ac00beaecf32bb02ed8e335225d7948d946d73bd",
37
- "vue-router": "^4.2.1"
32
+ "@noeldemartin/utils": "^0.7.1"
38
33
  },
39
34
  "devDependencies": {
40
- "@aerogel/core": "*"
35
+ "@aerogel/core": "*",
36
+ "@aerogel/plugin-soukai": "*",
37
+ "@aerogel/plugin-solid": "0.0.1-next.4acd5ba45cff8f2ad835a2f7ed8132dcb161865e"
38
+ },
39
+ "eslintConfig": {
40
+ "extends": [
41
+ "@noeldemartin/eslint-config-vue"
42
+ ]
41
43
  }
42
44
  }
@@ -0,0 +1,16 @@
1
+ <template>
2
+ <main :class="renderedRootClasses">
3
+ <slot />
4
+ </main>
5
+ </template>
6
+
7
+ <script setup lang="ts">
8
+ import { computed } from 'vue';
9
+ import { classes } from '@aerogel/core';
10
+ import type { HTMLAttributes } from 'vue';
11
+
12
+ const { class: rootClasses } = defineProps<{ class?: HTMLAttributes['class'] }>();
13
+
14
+ const renderedRootClasses = computed(() =>
15
+ classes('mx-auto flex w-full max-w-screen-content grow flex-col px-edge py-8', rootClasses));
16
+ </script>
@@ -0,0 +1 @@
1
+ export { default as Page } from './Page.vue';
package/src/index.css ADDED
@@ -0,0 +1 @@
1
+ @source './';
@@ -0,0 +1,31 @@
1
+ import { createApp } from 'vue';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { noop } from '@noeldemartin/utils';
4
+
5
+ import Router from '@aerogel/plugin-routing/services/Router';
6
+
7
+ import routing from './index';
8
+
9
+ describe('Routing plugin', () => {
10
+
11
+ it('Initializes router', async () => {
12
+ // Arrange
13
+ const routes = [{ name: 'home', path: '/home', component: noop }];
14
+
15
+ vi.mock('vue-router', async () => {
16
+ const original = (await vi.importActual('vue-router')) as Object;
17
+
18
+ return {
19
+ ...original,
20
+ createWebHistory: vi.fn(() => ({})),
21
+ };
22
+ });
23
+
24
+ // Act
25
+ await routing({ routes }).install(createApp({}), {});
26
+
27
+ // Assert
28
+ expect(Router.hasRoute('home')).toBe(true);
29
+ });
30
+
31
+ });
package/src/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ import Aerogel from 'virtual:aerogel';
2
+
3
+ import { UI, bootServices, setMarkdownRouter } from '@aerogel/core';
4
+ import { RouterLink, createRouter, createWebHistory } from 'vue-router';
5
+ import type { Plugin } from '@aerogel/core';
6
+ import type { RouteRecordRaw } from 'vue-router';
7
+
8
+ import Router from './services/Router';
9
+ import type { RouteBindings } from './services/Router';
10
+
11
+ const services = { $router: Router };
12
+
13
+ export * from './services/Router';
14
+ export * from './utils';
15
+ export * from './components';
16
+ export { default as Router } from './services/Router';
17
+
18
+ export interface Options {
19
+ routes: RouteRecordRaw[];
20
+ bindings?: RouteBindings;
21
+ basePath?: string;
22
+ }
23
+
24
+ export type RoutingServices = typeof services;
25
+
26
+ export default function routing(options: Options): Plugin {
27
+ return {
28
+ async install(app) {
29
+ const router = createRouter({
30
+ routes: options.routes,
31
+ history: createWebHistory(options.basePath ?? Aerogel.basePath),
32
+ });
33
+
34
+ UI.registerComponent('router-link', RouterLink);
35
+ Router.use(router, options);
36
+ app.use(router);
37
+
38
+ setMarkdownRouter({
39
+ resolve: (route) => router.resolve({ name: route }).href,
40
+ visit: async (route) => void (await router.push({ name: route })),
41
+ });
42
+
43
+ await bootServices(app, services);
44
+ },
45
+ };
46
+ }
47
+
48
+ declare module '@aerogel/core' {
49
+ interface Services extends RoutingServices {}
50
+ }
@@ -0,0 +1,17 @@
1
+ <template>
2
+ <Page class="items-center justify-center">
3
+ <h2 class="text-2xl font-bold">
4
+ {{ $td('notFound.title', '404: Not Found') }}
5
+ </h2>
6
+
7
+ <Link route="home">
8
+ {{ $td('notFound.home', 'Go home') }}
9
+ </Link>
10
+ </Page>
11
+ </template>
12
+
13
+ <script setup lang="ts">
14
+ import { Link } from '@aerogel/core';
15
+
16
+ import Page from '@aerogel/plugin-routing/components/Page.vue';
17
+ </script>
@@ -0,0 +1,10 @@
1
+ import { defineServiceState } from '@aerogel/core';
2
+ import type { RouteLocationRaw } from 'vue-router';
3
+
4
+ export default defineServiceState({
5
+ name: 'router',
6
+ initialState: {
7
+ flashRoute: null as RouteLocationRaw | null,
8
+ },
9
+ persist: ['flashRoute'],
10
+ });
@@ -0,0 +1,171 @@
1
+ import { computed, ref, shallowRef, unref, watch } from 'vue';
2
+ import { computedModel } from '@aerogel/plugin-soukai';
3
+ import { App, Events, computedAsync } from '@aerogel/core';
4
+ import { Storage, facade, objectOnly, once } from '@noeldemartin/utils';
5
+ import type { ComputedRef, Ref, WatchStopHandle } from 'vue';
6
+ import type { RouteLocationNormalizedLoaded, RouteLocationRaw, RouteParamValue, RouteParams, Router } from 'vue-router';
7
+
8
+ import { computedRouteParams } from '@aerogel/plugin-routing/utils/internal';
9
+
10
+ import Service from './Router.state';
11
+
12
+ export type LoadedRoute = Omit<RouteLocationNormalizedLoaded, 'params'> & {
13
+ rawParams: RouteParams;
14
+ params?: Record<string, unknown>;
15
+ };
16
+ export type RouteBinding = (slug: string, params: Record<string, unknown>) => unknown | Promise<unknown>;
17
+ export type RouteBindings = Record<string, RouteBinding>;
18
+
19
+ export class RouterService extends Service {
20
+
21
+ public readonly currentRoute: ComputedRef<LoadedRoute | null>;
22
+ public readonly routesParams: Ref<Record<string, Record<string, unknown>>>;
23
+ protected router: Ref<Router | null>;
24
+ protected bindings: RouteBindings;
25
+ protected history: string[];
26
+ protected routesStopWatchers: Record<string, WatchStopHandle[]>;
27
+
28
+ constructor() {
29
+ super();
30
+
31
+ this.router = shallowRef(null);
32
+ this.bindings = {};
33
+ this.history = [];
34
+ this.routesStopWatchers = {};
35
+ this.routesParams = shallowRef({});
36
+ this.currentRoute = computed(() => {
37
+ const router = this.router.value;
38
+ const routesParams = this.routesParams.value;
39
+
40
+ if (!router) {
41
+ return null;
42
+ }
43
+
44
+ const route = unref(router.currentRoute);
45
+
46
+ return {
47
+ ...route,
48
+ params: routesParams?.[route.path],
49
+ rawParams: route.params,
50
+ };
51
+ });
52
+ }
53
+
54
+ public use(router: Router, options: { bindings?: RouteBindings } = {}): void {
55
+ this.router.value = router;
56
+ this.bindings = options.bindings ?? {};
57
+
58
+ router.beforeEach(once(() => this.handleStatic404Redirect()));
59
+ router.beforeEach((to) => this.onEnterRoute(to.path, to.params));
60
+ }
61
+
62
+ protected override async boot(): Promise<void> {
63
+ Events.on('auth:before-login', () => this.storeFlashRoute());
64
+ Events.on('auth:login', () => this.restoreFlashRoute());
65
+ Events.on('purge-storage', () => this.push({ name: 'home' }));
66
+ }
67
+
68
+ protected override __get(property: string): unknown {
69
+ return this.router.value
70
+ ? (super.__get(property) ?? Reflect.get(this.router.value, property))
71
+ : super.__get(property);
72
+ }
73
+
74
+ protected async onEnterRoute(path: string, params: RouteParams): Promise<void> {
75
+ if (path in this.routesParams.value) {
76
+ return;
77
+ }
78
+
79
+ const resolvedParams: Record<string, unknown> = { ...params };
80
+ const stopWatchers: WatchStopHandle[] = [];
81
+
82
+ for (const [paramName, paramValue] of Object.entries(params)) {
83
+ const resolvedValue = await this.resolveBinding(path, paramName, paramValue);
84
+ const stopWatcher = watch(resolvedValue, (newValue) => {
85
+ this.routesParams.value = {
86
+ ...this.routesParams.value,
87
+ [path]: {
88
+ ...this.routesParams.value[path],
89
+ [paramName]: newValue,
90
+ },
91
+ };
92
+ });
93
+
94
+ stopWatchers.push(stopWatcher);
95
+
96
+ resolvedParams[paramName] = resolvedValue.value;
97
+ }
98
+
99
+ this.history = this.history.slice(0, 3);
100
+ this.history.unshift(path);
101
+
102
+ const routesParams = {
103
+ ...this.routesParams.value,
104
+ [path]: {
105
+ ...resolvedParams,
106
+ ...(this.routesParams.value[path] ?? {}),
107
+ },
108
+ };
109
+
110
+ for (const routePath in routesParams) {
111
+ if (this.history.includes(routePath)) {
112
+ continue;
113
+ }
114
+
115
+ this.routesStopWatchers[routePath]?.forEach((stop) => stop());
116
+ }
117
+
118
+ this.routesParams.value = objectOnly(routesParams, this.history);
119
+ this.routesStopWatchers = objectOnly(this.routesStopWatchers, this.history);
120
+ }
121
+
122
+ protected handleStatic404Redirect(): void {
123
+ const route = Storage.pull<RouteLocationRaw>('static-404-redirect');
124
+
125
+ route && this.replace(route);
126
+ }
127
+
128
+ protected storeFlashRoute(): void {
129
+ this.flashRoute = objectOnly(this.currentRoute.value as unknown as Record<string, unknown>, [
130
+ 'path',
131
+ 'query',
132
+ 'hash',
133
+ ]) as RouteLocationRaw;
134
+ }
135
+
136
+ protected async restoreFlashRoute(): Promise<void> {
137
+ if (!this.flashRoute) {
138
+ return;
139
+ }
140
+
141
+ const flashRoute = this.flashRoute;
142
+
143
+ App.whenReady(() => this.replace(flashRoute));
144
+
145
+ this.flashRoute = null;
146
+ }
147
+
148
+ protected async resolveBinding(
149
+ path: string,
150
+ name: string,
151
+ value: RouteParamValue | RouteParamValue[],
152
+ ): Promise<Ref<unknown>> {
153
+ const binding = this.bindings[name];
154
+
155
+ if (Array.isArray(value) || !binding) {
156
+ return ref(value);
157
+ }
158
+
159
+ await App.ready;
160
+
161
+ const otherParams = computedRouteParams(path, name);
162
+ const computedBinding = computedAsync(() => Promise.resolve(binding(value, otherParams.value)));
163
+
164
+ return computedModel(() => computedBinding.value);
165
+ }
166
+
167
+ }
168
+
169
+ export interface RouterService extends Omit<Router, 'currentRoute'> {}
170
+
171
+ export default facade(RouterService);
@@ -0,0 +1 @@
1
+ /// <reference types="@aerogel/plugin-solid" />
@@ -0,0 +1,7 @@
1
+ declare module '*.vue' {
2
+ import type { ComponentOptions } from 'vue';
3
+
4
+ const component: ComponentOptions;
5
+
6
+ export default component;
7
+ }
@@ -0,0 +1,5 @@
1
+ export default class BindingNotFound {
2
+
3
+ constructor(public value: string) {}
4
+
5
+ }
@@ -0,0 +1,2 @@
1
+ export { default as BindingNotFound } from './BindingNotFound';
2
+ export * from './routes';
@@ -0,0 +1,32 @@
1
+ import { objectWithout, tap } from '@noeldemartin/utils';
2
+ import { customRef, watch } from 'vue';
3
+ import type { ComputedRef } from 'vue';
4
+
5
+ import Router from '@aerogel/plugin-routing/services/Router';
6
+
7
+ export function computedRouteParams(path: string, exclude: string): ComputedRef<Record<string, unknown>> {
8
+ return customRef((track, trigger) => {
9
+ let value = objectWithout(Router.routesParams.value[path] ?? {}, exclude);
10
+
11
+ watch(Router.routesParams, () => {
12
+ const newParams = objectWithout(Router.routesParams.value[path] ?? {}, exclude);
13
+
14
+ for (const [paramName, paramValue] of Object.entries(newParams)) {
15
+ if (paramValue !== value[paramName as keyof typeof value]) {
16
+ continue;
17
+ }
18
+
19
+ value = newParams;
20
+ trigger();
21
+ return;
22
+ }
23
+ });
24
+
25
+ return {
26
+ get: () => tap(value, () => track()),
27
+
28
+ // eslint-disable-next-line no-console
29
+ set: () => console.warn('Computed models ref was not set (it is immutable).'),
30
+ };
31
+ }) as ComputedRef<Record<string, unknown>>;
32
+ }
@@ -0,0 +1,126 @@
1
+ import { App } from '@aerogel/core';
2
+ import { computed, defineComponent, h, watchEffect } from 'vue';
3
+ import { useRoute } from 'vue-router';
4
+ import type { Component, ConcreteComponent } from 'vue';
5
+ import type { NavigationGuardWithThis, RouteRecordRaw } from 'vue-router';
6
+
7
+ import NotFound from '@aerogel/plugin-routing/pages/NotFound.vue';
8
+ import Router from '@aerogel/plugin-routing/services/Router';
9
+ import BindingNotFound from '@aerogel/plugin-routing/utils/BindingNotFound';
10
+ import type { RouteBindings } from '@aerogel/plugin-routing/services/Router';
11
+
12
+ export type AerogelRoute = RouteRecordRaw & {
13
+ title?: string | ((params: Record<string, unknown>) => string | undefined | null);
14
+ };
15
+
16
+ function setupPageComponent(pageComponent: ConcreteComponent, routeConfig: AerogelRoute) {
17
+ const route = useRoute();
18
+ const pageParams = computed(() => Router.routesParams?.value[route.path]);
19
+ const routeTitle = computed(() => {
20
+ if (!routeConfig?.title || !pageParams.value) {
21
+ return null;
22
+ }
23
+
24
+ if (typeof routeConfig.title === 'string') {
25
+ return routeConfig.title;
26
+ }
27
+
28
+ return routeConfig.title(pageParams.value);
29
+ });
30
+
31
+ watchEffect(() => updateRouteTitle(routeTitle.value));
32
+
33
+ return () =>
34
+ Object.values(pageParams.value ?? {}).some((value) => value instanceof BindingNotFound)
35
+ ? h(NotFound)
36
+ : h(pageComponent, pageParams.value);
37
+ }
38
+
39
+ function defineRouteComponent(pageComponent: ConcreteComponent, route: AerogelRoute): Component {
40
+ return defineComponent({
41
+ setup: () => setupPageComponent(pageComponent, route),
42
+ });
43
+ }
44
+
45
+ function enhanceRouteComponent(route: AerogelRoute): void {
46
+ if (!route.component) {
47
+ return;
48
+ }
49
+
50
+ if (typeof route.component === 'function') {
51
+ const lazyComponent = route.component as () => Promise<{ default: ConcreteComponent }>;
52
+
53
+ route.component = async () => {
54
+ const { default: component } = await lazyComponent();
55
+
56
+ return defineRouteComponent(component, route);
57
+ };
58
+
59
+ return;
60
+ }
61
+
62
+ route.component = defineRouteComponent(route.component, route);
63
+ }
64
+
65
+ function enhanceRouteNavigationGuard(guard: NavigationGuardWithThis<undefined>): NavigationGuardWithThis<undefined> {
66
+ return async function(this, ...args) {
67
+ await App.ready;
68
+
69
+ return guard.call(this, ...args);
70
+ };
71
+ }
72
+
73
+ function enhanceRouteNavigationGuards(route: AerogelRoute): void {
74
+ if (!route.beforeEnter) {
75
+ return;
76
+ }
77
+
78
+ if (Array.isArray(route.beforeEnter)) {
79
+ route.beforeEnter = route.beforeEnter.map(enhanceRouteNavigationGuard);
80
+
81
+ return;
82
+ }
83
+
84
+ route.beforeEnter = enhanceRouteNavigationGuard(route.beforeEnter);
85
+ }
86
+
87
+ function updateRouteTitle(title?: string | null): void {
88
+ if (!globalThis.document) {
89
+ return;
90
+ }
91
+
92
+ if (!title) {
93
+ globalThis.document.title = App.name;
94
+
95
+ return;
96
+ }
97
+
98
+ globalThis.document.title = `${title} | ${App.name}`;
99
+ }
100
+
101
+ export function defineRoute(route: AerogelRoute): RouteRecordRaw {
102
+ enhanceRouteComponent(route);
103
+ enhanceRouteNavigationGuards(route);
104
+
105
+ return route;
106
+ }
107
+
108
+ export function defineRouteBindings(bindings: RouteBindings): RouteBindings {
109
+ return bindings;
110
+ }
111
+
112
+ export function defineRoutes(routes: AerogelRoute[]): RouteRecordRaw[] {
113
+ const aerogelRoutes = routes.map(defineRoute);
114
+
115
+ if (!aerogelRoutes.some((route) => route.name === 'not-found' || route.name === '404')) {
116
+ aerogelRoutes.push(
117
+ defineRoute({
118
+ name: 'not-found',
119
+ path: '/:path(.*)*',
120
+ component: NotFound,
121
+ }),
122
+ );
123
+ }
124
+
125
+ return aerogelRoutes;
126
+ }
package/.eslintrc.js DELETED
@@ -1,7 +0,0 @@
1
- module.exports = {
2
- env: {
3
- browser: true,
4
- es2021: true,
5
- },
6
- extends: ['@noeldemartin/eslint-config-typescript'],
7
- };
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@noeldemartin/utils"),t=require("vue-router");function r(r){const o=t.createRouter({history:t.createWebHistory(r.basePath),routes:r.routes});return o.beforeEach(e.once((()=>function(t){const r=e.Storage.pull("static-404-redirect");r&&t.replace(r)}(o)))),o}exports.default=function(e){return{install(t){const o=r({routes:e.routes,basePath:e.basePath??__AG_BASE_PATH});t.use(o)}}};
2
- //# sourceMappingURL=aerogel-plugin-routing.cjs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aerogel-plugin-routing.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- import{once as t,Storage as e}from"@noeldemartin/utils";import{createRouter as r,createWebHistory as o}from"vue-router";function s(s){const u=r({history:o(s.basePath),routes:s.routes});return u.beforeEach(t((()=>function(t){const r=e.pull("static-404-redirect");r&&t.replace(r)}(u)))),u}function u(t){return{install(e){const r=s({routes:t.routes,basePath:t.basePath??__AG_BASE_PATH});e.use(r)}}}export{u as default};
2
- //# sourceMappingURL=aerogel-plugin-routing.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aerogel-plugin-routing.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/src/main.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { Plugin } from '@aerogel/core';
2
- import type { RouteRecordRaw } from 'vue-router';
3
-
4
- import { createAppRouter } from './router';
5
-
6
- interface Options {
7
- routes: RouteRecordRaw[];
8
- basePath?: string;
9
- }
10
-
11
- export default function routing(options: Options): Plugin {
12
- return {
13
- install(app) {
14
- const plugin = createAppRouter({
15
- routes: options.routes,
16
- basePath: options.basePath ?? __AG_BASE_PATH,
17
- });
18
-
19
- app.use(plugin);
20
- },
21
- };
22
- }
package/src/router.ts DELETED
@@ -1,21 +0,0 @@
1
- import { Storage, once } from '@noeldemartin/utils';
2
- import { createRouter, createWebHistory } from 'vue-router';
3
- import type { Plugin } from 'vue';
4
- import type { RouteLocationRaw, RouteRecordRaw, Router } from 'vue-router';
5
-
6
- function handleStatic404Redirect(router: Router): void {
7
- const route = Storage.pull<RouteLocationRaw>('static-404-redirect');
8
-
9
- route && router.replace(route);
10
- }
11
-
12
- export function createAppRouter(options: { routes: RouteRecordRaw[]; basePath?: string }): Plugin {
13
- const router = createRouter({
14
- history: createWebHistory(options.basePath),
15
- routes: options.routes,
16
- });
17
-
18
- router.beforeEach(once(() => handleStatic404Redirect(router)));
19
-
20
- return router;
21
- }
package/tsconfig.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "include": ["src/**/*.ts"]
4
- }