dtwo 2.17.0 → 3.0.0-rc.14

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 (118) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +2 -41
  3. package/app.d.ts +1 -0
  4. package/bin/dtwo.mjs +2 -0
  5. package/config.cjs +7 -0
  6. package/config.d.ts +4 -0
  7. package/config.mjs +5 -0
  8. package/dist/app/compat/capi.d.ts +4 -0
  9. package/dist/app/compat/capi.mjs +19 -0
  10. package/dist/app/compat/kdu-demi.d.ts +4 -0
  11. package/dist/app/compat/kdu-demi.mjs +4 -0
  12. package/dist/app/components/client-only.d.mts +22 -0
  13. package/dist/app/components/client-only.mjs +75 -0
  14. package/dist/app/components/dev-only.d.mts +4 -0
  15. package/dist/app/components/dev-only.mjs +11 -0
  16. package/dist/app/components/dtwo-error-boundary.d.ts +8 -0
  17. package/dist/app/components/dtwo-error-boundary.mjs +21 -0
  18. package/dist/app/components/dtwo-error-page.kdu +46 -0
  19. package/dist/app/components/dtwo-link.d.ts +33 -0
  20. package/dist/app/components/dtwo-link.mjs +248 -0
  21. package/dist/app/components/dtwo-loading-indicator.d.ts +43 -0
  22. package/dist/app/components/dtwo-loading-indicator.mjs +107 -0
  23. package/dist/app/components/dtwo-root.kdu +35 -0
  24. package/dist/app/components/index.d.ts +2 -0
  25. package/dist/app/components/index.mjs +1 -0
  26. package/dist/app/components/layout.d.ts +17 -0
  27. package/dist/app/components/layout.mjs +66 -0
  28. package/dist/app/components/server-placeholder.d.ts +2 -0
  29. package/dist/app/components/server-placeholder.mjs +7 -0
  30. package/dist/app/components/utils.d.ts +11 -0
  31. package/dist/app/components/utils.mjs +9 -0
  32. package/dist/app/composables/asyncData.d.ts +40 -0
  33. package/dist/app/composables/asyncData.mjs +169 -0
  34. package/dist/app/composables/component.d.ts +3 -0
  35. package/dist/app/composables/component.mjs +46 -0
  36. package/dist/app/composables/cookie.d.ts +12 -0
  37. package/dist/app/composables/cookie.mjs +58 -0
  38. package/dist/app/composables/error.d.ts +17 -0
  39. package/dist/app/composables/error.mjs +31 -0
  40. package/dist/app/composables/fetch.d.ts +15 -0
  41. package/dist/app/composables/fetch.mjs +66 -0
  42. package/dist/app/composables/hydrate.d.ts +8 -0
  43. package/dist/app/composables/hydrate.mjs +14 -0
  44. package/dist/app/composables/index.d.ts +16 -0
  45. package/dist/app/composables/index.mjs +11 -0
  46. package/dist/app/composables/payload.d.ts +8 -0
  47. package/dist/app/composables/payload.mjs +58 -0
  48. package/dist/app/composables/preload.d.ts +17 -0
  49. package/dist/app/composables/preload.mjs +41 -0
  50. package/dist/app/composables/router.d.ts +28 -0
  51. package/dist/app/composables/router.mjs +111 -0
  52. package/dist/app/composables/ssr.d.ts +6 -0
  53. package/dist/app/composables/ssr.mjs +23 -0
  54. package/dist/app/composables/state.d.ts +9 -0
  55. package/dist/app/composables/state.mjs +27 -0
  56. package/dist/app/config.d.ts +13 -0
  57. package/dist/app/config.mjs +56 -0
  58. package/dist/app/dtwo.d.ts +122 -0
  59. package/dist/app/dtwo.mjs +168 -0
  60. package/dist/app/entry.async.d.ts +2 -0
  61. package/dist/app/entry.async.mjs +5 -0
  62. package/dist/app/entry.d.ts +3 -0
  63. package/dist/app/entry.mjs +59 -0
  64. package/dist/app/index.d.ts +10 -0
  65. package/dist/app/index.mjs +7 -0
  66. package/dist/app/plugins/cross-origin-prefetch.client.d.ts +2 -0
  67. package/dist/app/plugins/cross-origin-prefetch.client.mjs +28 -0
  68. package/dist/app/plugins/debug.d.ts +2 -0
  69. package/dist/app/plugins/debug.mjs +5 -0
  70. package/dist/app/plugins/payload.client.d.ts +2 -0
  71. package/dist/app/plugins/payload.client.mjs +22 -0
  72. package/dist/app/plugins/preload.server.d.ts +2 -0
  73. package/dist/app/plugins/preload.server.mjs +10 -0
  74. package/dist/app/plugins/router.d.ts +53 -0
  75. package/dist/app/plugins/router.mjs +176 -0
  76. package/dist/app/types/augments.d.ts +28 -0
  77. package/dist/core/runtime/hole/error.d.ts +3 -0
  78. package/dist/core/runtime/hole/error.mjs +58 -0
  79. package/dist/core/runtime/hole/paths.d.ts +4 -0
  80. package/dist/core/runtime/hole/paths.mjs +15 -0
  81. package/dist/core/runtime/hole/renderer.d.ts +16 -0
  82. package/dist/core/runtime/hole/renderer.mjs +219 -0
  83. package/dist/head/runtime/components.d.ts +796 -0
  84. package/dist/head/runtime/components.mjs +209 -0
  85. package/dist/head/runtime/composables.d.ts +10 -0
  86. package/dist/head/runtime/composables.mjs +4 -0
  87. package/dist/head/runtime/index.d.ts +4 -0
  88. package/dist/head/runtime/index.mjs +1 -0
  89. package/dist/head/runtime/lib/kdu-meta.plugin.d.ts +2 -0
  90. package/dist/head/runtime/lib/kdu-meta.plugin.mjs +31 -0
  91. package/dist/head/runtime/lib/kduse-head.plugin.d.ts +2 -0
  92. package/dist/head/runtime/lib/kduse-head.plugin.mjs +35 -0
  93. package/dist/head/runtime/types.d.ts +7 -0
  94. package/dist/head/runtime/types.mjs +0 -0
  95. package/dist/index.d.ts +9 -0
  96. package/dist/index.mjs +2274 -0
  97. package/dist/pages/runtime/app.kdu +5 -0
  98. package/dist/pages/runtime/composables.d.ts +42 -0
  99. package/dist/pages/runtime/composables.mjs +8 -0
  100. package/dist/pages/runtime/index.d.ts +1 -0
  101. package/dist/pages/runtime/index.mjs +1 -0
  102. package/dist/pages/runtime/page-placeholder.d.ts +4 -0
  103. package/dist/pages/runtime/page-placeholder.mjs +10 -0
  104. package/dist/pages/runtime/page.d.ts +15 -0
  105. package/dist/pages/runtime/page.mjs +107 -0
  106. package/dist/pages/runtime/router.d.ts +8 -0
  107. package/dist/pages/runtime/router.mjs +152 -0
  108. package/dist/pages/runtime/router.options.d.ts +2 -0
  109. package/dist/pages/runtime/router.options.mjs +51 -0
  110. package/dist/pages/runtime/utils.d.ts +9 -0
  111. package/dist/pages/runtime/utils.mjs +12 -0
  112. package/dist/pages/runtime/validate.d.ts +2 -0
  113. package/dist/pages/runtime/validate.mjs +11 -0
  114. package/package.json +79 -42
  115. package/types.d.ts +15 -0
  116. package/bin/dtwo.js +0 -10
  117. package/dist/dtwo.js +0 -37
  118. package/webpack.config.js +0 -4
@@ -0,0 +1,66 @@
1
+ import { computed, unref, reactive } from "kdu";
2
+ import { hash } from "ohash";
3
+ import { useAsyncData } from "./asyncData.mjs";
4
+ export function useFetch(request, arg1, arg2) {
5
+ const [opts = {}, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
6
+ const _key = opts.key || hash([autoKey, unref(opts.baseURL), typeof request === "string" ? request : "", unref(opts.params)]);
7
+ if (!_key || typeof _key !== "string") {
8
+ throw new TypeError("[dtwo] [useFetch] key must be a string: " + _key);
9
+ }
10
+ if (!request) {
11
+ throw new Error("[dtwo] [useFetch] request is missing.");
12
+ }
13
+ const key = _key === autoKey ? "$f" + _key : _key;
14
+ const _request = computed(() => {
15
+ let r = request;
16
+ if (typeof r === "function") {
17
+ r = r();
18
+ }
19
+ return unref(r);
20
+ });
21
+ const {
22
+ server,
23
+ lazy,
24
+ default: defaultFn,
25
+ transform,
26
+ pick,
27
+ watch,
28
+ immediate,
29
+ ...fetchOptions
30
+ } = opts;
31
+ const _fetchOptions = reactive({
32
+ ...fetchOptions,
33
+ cache: typeof opts.cache === "boolean" ? void 0 : opts.cache
34
+ });
35
+ const _asyncDataOptions = {
36
+ server,
37
+ lazy,
38
+ default: defaultFn,
39
+ transform,
40
+ pick,
41
+ immediate,
42
+ watch: [
43
+ _fetchOptions,
44
+ _request,
45
+ ...watch || []
46
+ ]
47
+ };
48
+ let controller;
49
+ const asyncData = useAsyncData(key, () => {
50
+ controller?.abort?.();
51
+ controller = typeof AbortController !== "undefined" ? new AbortController() : {};
52
+ return $fetch(_request.value, { signal: controller.signal, ..._fetchOptions });
53
+ }, _asyncDataOptions);
54
+ return asyncData;
55
+ }
56
+ export function useLazyFetch(request, arg1, arg2) {
57
+ const [opts, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
58
+ return useFetch(
59
+ request,
60
+ {
61
+ ...opts,
62
+ lazy: true
63
+ },
64
+ autoKey
65
+ );
66
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Allows full control of the hydration cycle to set and receive data from the server.
3
+ *
4
+ * @param key a unique key to identify the data in the Dtwo payload
5
+ * @param get a function that returns the value to set the initial data
6
+ * @param set a function that will receive the data on the client-side
7
+ */
8
+ export declare const useHydration: <T>(key: string, get: () => T, set: (value: T) => void) => void;
@@ -0,0 +1,14 @@
1
+ import { useDtwoApp } from "../dtwo.mjs";
2
+ export const useHydration = (key, get, set) => {
3
+ const dtwo = useDtwoApp();
4
+ if (process.server) {
5
+ dtwo.hooks.hook("app:rendered", () => {
6
+ dtwo.payload[key] = get();
7
+ });
8
+ }
9
+ if (process.client) {
10
+ dtwo.hooks.hook("app:created", () => {
11
+ set(dtwo.payload[key]);
12
+ });
13
+ }
14
+ };
@@ -0,0 +1,16 @@
1
+ export { defineDtwoComponent } from './component';
2
+ export { useAsyncData, useLazyAsyncData, refreshDtwoData, clearDtwoData } from './asyncData';
3
+ export type { AsyncDataOptions, AsyncData } from './asyncData';
4
+ export { useHydration } from './hydrate';
5
+ export { useState } from './state';
6
+ export { clearError, createError, isDtwoError, showError, useError } from './error';
7
+ export type { DtwoError } from './error';
8
+ export { useFetch, useLazyFetch } from './fetch';
9
+ export type { FetchResult, UseFetchOptions } from './fetch';
10
+ export { useCookie } from './cookie';
11
+ export type { CookieOptions, CookieRef } from './cookie';
12
+ export { useRequestHeaders, useRequestEvent, setResponseStatus } from './ssr';
13
+ export { abortNavigation, addRouteMiddleware, defineDtwoRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from './router';
14
+ export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router';
15
+ export { preloadComponents, prefetchComponents, preloadRouteComponents } from './preload';
16
+ export { isPrerendered, loadPayload, preloadPayload } from './payload';
@@ -0,0 +1,11 @@
1
+ export { defineDtwoComponent } from "./component.mjs";
2
+ export { useAsyncData, useLazyAsyncData, refreshDtwoData, clearDtwoData } from "./asyncData.mjs";
3
+ export { useHydration } from "./hydrate.mjs";
4
+ export { useState } from "./state.mjs";
5
+ export { clearError, createError, isDtwoError, showError, useError } from "./error.mjs";
6
+ export { useFetch, useLazyFetch } from "./fetch.mjs";
7
+ export { useCookie } from "./cookie.mjs";
8
+ export { useRequestHeaders, useRequestEvent, setResponseStatus } from "./ssr.mjs";
9
+ export { abortNavigation, addRouteMiddleware, defineDtwoRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from "./router.mjs";
10
+ export { preloadComponents, prefetchComponents, preloadRouteComponents } from "./preload.mjs";
11
+ export { isPrerendered, loadPayload, preloadPayload } from "./payload.mjs";
@@ -0,0 +1,8 @@
1
+ interface LoadPayloadOptions {
2
+ fresh?: boolean;
3
+ hash?: string;
4
+ }
5
+ export declare function loadPayload(url: string, opts?: LoadPayloadOptions): any;
6
+ export declare function preloadPayload(url: string, opts?: LoadPayloadOptions): void;
7
+ export declare function isPrerendered(): boolean;
8
+ export {};
@@ -0,0 +1,58 @@
1
+ import { joinURL } from "ufo";
2
+ import { useDtwoApp } from "../dtwo.mjs";
3
+ import { useHead, useRuntimeConfig } from "../index.mjs";
4
+ export function loadPayload(url, opts = {}) {
5
+ if (process.server) {
6
+ return null;
7
+ }
8
+ const payloadURL = _getPayloadURL(url, opts);
9
+ const dtwoApp = useDtwoApp();
10
+ const cache = dtwoApp._payloadCache = dtwoApp._payloadCache || {};
11
+ if (cache[url]) {
12
+ return cache[url];
13
+ }
14
+ cache[url] = _importPayload(payloadURL).then((payload) => {
15
+ if (!payload) {
16
+ delete cache[url];
17
+ return null;
18
+ }
19
+ return payload;
20
+ });
21
+ return cache[url];
22
+ }
23
+ export function preloadPayload(url, opts = {}) {
24
+ const payloadURL = _getPayloadURL(url, opts);
25
+ useHead({
26
+ link: [
27
+ { rel: "modulepreload", href: payloadURL }
28
+ ]
29
+ });
30
+ }
31
+ function _getPayloadURL(url, opts = {}) {
32
+ const u = new URL(url, "http://localhost");
33
+ if (u.search) {
34
+ throw new Error("Payload URL cannot contain search params: " + url);
35
+ }
36
+ if (u.host !== "localhost") {
37
+ throw new Error("Payload URL cannot contain host: " + url);
38
+ }
39
+ const hash = opts.hash || (opts.fresh ? Date.now() : "");
40
+ return joinURL(useRuntimeConfig().app.baseURL, u.pathname, hash ? `_payload.${hash}.js` : "_payload.js");
41
+ }
42
+ async function _importPayload(payloadURL) {
43
+ if (process.server) {
44
+ return null;
45
+ }
46
+ const res = await import(
47
+ /* webpackIgnore: true */
48
+ /* @wite-ignore */
49
+ payloadURL
50
+ ).catch((err) => {
51
+ console.warn("[dtwo] Cannot load payload ", payloadURL, err);
52
+ });
53
+ return res?.default || null;
54
+ }
55
+ export function isPrerendered() {
56
+ const dtwoApp = useDtwoApp();
57
+ return !!dtwoApp.payload.prerenderedAt;
58
+ }
@@ -0,0 +1,17 @@
1
+ import type { Router } from 'kdu-router';
2
+ /**
3
+ * Preload a component or components that have been globally registered.
4
+ *
5
+ * @param components Pascal-cased name or names of components to prefetch
6
+ */
7
+ export declare const preloadComponents: (components: string | string[]) => Promise<void>;
8
+ /**
9
+ * Prefetch a component or components that have been globally registered.
10
+ *
11
+ * @param components Pascal-cased name or names of components to prefetch
12
+ */
13
+ export declare const prefetchComponents: (components: string | string[]) => Promise<void>;
14
+ export declare function preloadRouteComponents(to: string, router?: Router & {
15
+ _routePreloaded?: Set<string>;
16
+ _preloadPromises?: Array<Promise<any>>;
17
+ }): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import { useDtwoApp } from "../dtwo.mjs";
2
+ import { useRouter } from "./router.mjs";
3
+ export const preloadComponents = async (components) => {
4
+ if (process.server) {
5
+ return;
6
+ }
7
+ const dtwoApp = useDtwoApp();
8
+ components = Array.isArray(components) ? components : [components];
9
+ await Promise.all(components.map((name) => _loadAsyncComponent(dtwoApp.kduApp._context.components[name])));
10
+ };
11
+ export const prefetchComponents = (components) => {
12
+ return preloadComponents(components);
13
+ };
14
+ function _loadAsyncComponent(component) {
15
+ if (component?.__asyncLoader && !component.__asyncResolved) {
16
+ return component.__asyncLoader();
17
+ }
18
+ }
19
+ export async function preloadRouteComponents(to, router = useRouter()) {
20
+ if (process.server) {
21
+ return;
22
+ }
23
+ if (!router._routePreloaded) {
24
+ router._routePreloaded = /* @__PURE__ */ new Set();
25
+ }
26
+ if (router._routePreloaded.has(to)) {
27
+ return;
28
+ }
29
+ router._routePreloaded.add(to);
30
+ const promises = router._preloadPromises = router._preloadPromises || [];
31
+ if (promises.length > 4) {
32
+ return Promise.all(promises).then(() => preloadRouteComponents(to, router));
33
+ }
34
+ const components = router.resolve(to).matched.map((component) => component.components?.default).filter((component) => typeof component === "function");
35
+ for (const component of components) {
36
+ const promise = Promise.resolve(component()).catch(() => {
37
+ }).finally(() => promises.splice(promises.indexOf(promise)));
38
+ promises.push(promise);
39
+ }
40
+ await Promise.all(promises);
41
+ }
@@ -0,0 +1,28 @@
1
+ import type { NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure } from 'kdu-router';
2
+ import { DtwoError } from './error';
3
+ export declare const useRouter: () => Router;
4
+ export declare const useRoute: () => RouteLocationNormalizedLoaded;
5
+ export declare const onBeforeRouteLeave: (guard: NavigationGuard) => void;
6
+ export declare const onBeforeRouteUpdate: (guard: NavigationGuard) => void;
7
+ export interface RouteMiddleware {
8
+ (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>;
9
+ }
10
+ export declare const defineDtwoRouteMiddleware: (middleware: RouteMiddleware) => RouteMiddleware;
11
+ export interface AddRouteMiddlewareOptions {
12
+ global?: boolean;
13
+ }
14
+ interface AddRouteMiddleware {
15
+ (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void;
16
+ (middleware: RouteMiddleware): void;
17
+ }
18
+ export declare const addRouteMiddleware: AddRouteMiddleware;
19
+ export interface NavigateToOptions {
20
+ replace?: boolean;
21
+ redirectCode?: number;
22
+ external?: boolean;
23
+ }
24
+ export declare const navigateTo: (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions) => Promise<void | NavigationFailure> | RouteLocationRaw;
25
+ /** This will abort navigation within a Dtwo route middleware handler. */
26
+ export declare const abortNavigation: (err?: string | Partial<DtwoError>) => boolean;
27
+ export declare const setPageLayout: (layout: string) => void;
28
+ export {};
@@ -0,0 +1,111 @@
1
+ import { getCurrentInstance, inject, onUnmounted } from "kdu";
2
+ import { sendRedirect } from "h3";
3
+ import { hasProtocol, joinURL, parseURL } from "ufo";
4
+ import { useDtwoApp, useRuntimeConfig } from "../dtwo.mjs";
5
+ import { createError } from "./error.mjs";
6
+ import { useState } from "./state.mjs";
7
+ export const useRouter = () => {
8
+ return useDtwoApp()?.$router;
9
+ };
10
+ export const useRoute = () => {
11
+ if (getCurrentInstance()) {
12
+ return inject("_route", useDtwoApp()._route);
13
+ }
14
+ return useDtwoApp()._route;
15
+ };
16
+ export const onBeforeRouteLeave = (guard) => {
17
+ const unsubscribe = useRouter().beforeEach((to, from, next) => {
18
+ if (to === from) {
19
+ return;
20
+ }
21
+ return guard(to, from, next);
22
+ });
23
+ onUnmounted(unsubscribe);
24
+ };
25
+ export const onBeforeRouteUpdate = (guard) => {
26
+ const unsubscribe = useRouter().beforeEach(guard);
27
+ onUnmounted(unsubscribe);
28
+ };
29
+ export const defineDtwoRouteMiddleware = (middleware) => middleware;
30
+ export const addRouteMiddleware = (name, middleware, options = {}) => {
31
+ const dtwoApp = useDtwoApp();
32
+ if (options.global || typeof name === "function") {
33
+ dtwoApp._middleware.global.push(typeof name === "function" ? name : middleware);
34
+ } else {
35
+ dtwoApp._middleware.named[name] = middleware;
36
+ }
37
+ };
38
+ const isProcessingMiddleware = () => {
39
+ try {
40
+ if (useDtwoApp()._processingMiddleware) {
41
+ return true;
42
+ }
43
+ } catch {
44
+ return true;
45
+ }
46
+ return false;
47
+ };
48
+ export const navigateTo = (to, options) => {
49
+ if (!to) {
50
+ to = "/";
51
+ }
52
+ const toPath = typeof to === "string" ? to : to.path || "/";
53
+ const isExternal = hasProtocol(toPath, true);
54
+ if (isExternal && !options?.external) {
55
+ throw new Error("Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.");
56
+ }
57
+ if (isExternal && parseURL(toPath).protocol === "script:") {
58
+ throw new Error("Cannot navigate to an URL with script protocol.");
59
+ }
60
+ if (process.client && !isExternal && isProcessingMiddleware()) {
61
+ return to;
62
+ }
63
+ const router = useRouter();
64
+ if (process.server) {
65
+ const dtwoApp = useDtwoApp();
66
+ if (dtwoApp.ssrContext && dtwoApp.ssrContext.event) {
67
+ const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || "/");
68
+ return dtwoApp.callHook("app:redirected").then(() => sendRedirect(dtwoApp.ssrContext.event, redirectLocation, options?.redirectCode || 302));
69
+ }
70
+ }
71
+ if (isExternal) {
72
+ if (options?.replace) {
73
+ location.replace(toPath);
74
+ } else {
75
+ location.href = toPath;
76
+ }
77
+ return Promise.resolve();
78
+ }
79
+ return options?.replace ? router.replace(to) : router.push(to);
80
+ };
81
+ export const abortNavigation = (err) => {
82
+ if (process.dev && !isProcessingMiddleware()) {
83
+ throw new Error("abortNavigation() is only usable inside a route middleware handler.");
84
+ }
85
+ if (err) {
86
+ throw createError(err);
87
+ }
88
+ return false;
89
+ };
90
+ export const setPageLayout = (layout) => {
91
+ if (process.server) {
92
+ if (process.dev && getCurrentInstance() && useState("_layout").value !== layout) {
93
+ console.warn("[warn] [dtwo] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.");
94
+ }
95
+ useState("_layout").value = layout;
96
+ }
97
+ const dtwoApp = useDtwoApp();
98
+ if (process.dev && dtwoApp.isHydrating && useState("_layout").value !== layout) {
99
+ console.warn("[warn] [dtwo] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.");
100
+ }
101
+ const inMiddleware = isProcessingMiddleware();
102
+ if (inMiddleware || process.server || dtwoApp.isHydrating) {
103
+ const unsubscribe = useRouter().beforeResolve((to) => {
104
+ to.meta.layout = layout;
105
+ unsubscribe();
106
+ });
107
+ }
108
+ if (!inMiddleware) {
109
+ useRoute().meta.layout = layout;
110
+ }
111
+ };
@@ -0,0 +1,6 @@
1
+ import type { H3Event } from 'h3';
2
+ import { DtwoApp } from '../dtwo';
3
+ export declare function useRequestHeaders<K extends string = string>(include: K[]): Record<Lowercase<K>, string | undefined>;
4
+ export declare function useRequestHeaders(): Readonly<Record<string, string | undefined>>;
5
+ export declare function useRequestEvent(dtwoApp?: DtwoApp): H3Event;
6
+ export declare function setResponseStatus(code: number, message?: string): void;
@@ -0,0 +1,23 @@
1
+ import { useDtwoApp } from "../dtwo.mjs";
2
+ export function useRequestHeaders(include) {
3
+ if (process.client) {
4
+ return {};
5
+ }
6
+ const headers = useDtwoApp().ssrContext?.event.node.req.headers ?? {};
7
+ if (!include) {
8
+ return headers;
9
+ }
10
+ return Object.fromEntries(include.map((key) => key.toLowerCase()).filter((key) => headers[key]).map((key) => [key, headers[key]]));
11
+ }
12
+ export function useRequestEvent(dtwoApp = useDtwoApp()) {
13
+ return dtwoApp.ssrContext?.event;
14
+ }
15
+ export function setResponseStatus(code, message) {
16
+ const event = process.server && useRequestEvent();
17
+ if (event) {
18
+ event.node.res.statusCode = code;
19
+ if (message) {
20
+ event.node.res.statusMessage = message;
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,9 @@
1
+ import type { Ref } from 'kdu';
2
+ /**
3
+ * Create a global reactive ref that will be hydrated but not shared across ssr requests
4
+ *
5
+ * @param key a unique key ensuring that data fetching can be properly de-duplicated across requests
6
+ * @param init a function that provides initial value for the state when it's not initiated
7
+ */
8
+ export declare function useState<T>(key?: string, init?: (() => T | Ref<T>)): Ref<T>;
9
+ export declare function useState<T>(init?: (() => T | Ref<T>)): Ref<T>;
@@ -0,0 +1,27 @@
1
+ import { isRef, toRef } from "kdu";
2
+ import { useDtwoApp } from "../dtwo.mjs";
3
+ export function useState(...args) {
4
+ const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
5
+ if (typeof args[0] !== "string") {
6
+ args.unshift(autoKey);
7
+ }
8
+ const [_key, init] = args;
9
+ if (!_key || typeof _key !== "string") {
10
+ throw new TypeError("[dtwo] [useState] key must be a string: " + _key);
11
+ }
12
+ if (init !== void 0 && typeof init !== "function") {
13
+ throw new Error("[dtwo] [useState] init must be a function: " + init);
14
+ }
15
+ const key = "$s" + _key;
16
+ const dtwo = useDtwoApp();
17
+ const state = toRef(dtwo.payload.state, key);
18
+ if (state.value === void 0 && init) {
19
+ const initialValue = init();
20
+ if (isRef(initialValue)) {
21
+ dtwo.payload.state[key] = initialValue;
22
+ return initialValue;
23
+ }
24
+ state.value = initialValue;
25
+ }
26
+ return state;
27
+ }
@@ -0,0 +1,13 @@
1
+ import type { AppConfig } from '@dtwo/schema';
2
+ type DeepPartial<T> = T extends Function ? T : T extends Record<string, any> ? {
3
+ [P in keyof T]?: DeepPartial<T[P]>;
4
+ } : T;
5
+ export declare const _getAppConfig: () => AppConfig;
6
+ export declare function useAppConfig(): AppConfig;
7
+ /**
8
+ * Deep assign the current appConfig with the new one.
9
+ *
10
+ * Will preserve existing properties.
11
+ */
12
+ export declare function updateAppConfig(appConfig: DeepPartial<AppConfig>): void;
13
+ export {};
@@ -0,0 +1,56 @@
1
+ import { reactive } from "kdu";
2
+ import { useDtwoApp } from "./dtwo.mjs";
3
+ import __appConfig from "#build/app.config.mjs";
4
+ export const _getAppConfig = () => __appConfig;
5
+ function deepDelete(obj, newObj) {
6
+ for (const key in obj) {
7
+ const val = newObj[key];
8
+ if (!(key in newObj)) {
9
+ delete obj[key];
10
+ }
11
+ if (val !== null && typeof val === "object") {
12
+ deepDelete(obj[key], newObj[key]);
13
+ }
14
+ }
15
+ }
16
+ function deepAssign(obj, newObj) {
17
+ for (const key in newObj) {
18
+ const val = newObj[key];
19
+ if (val !== null && typeof val === "object") {
20
+ deepAssign(obj[key], val);
21
+ } else {
22
+ obj[key] = val;
23
+ }
24
+ }
25
+ }
26
+ export function useAppConfig() {
27
+ const dtwoApp = useDtwoApp();
28
+ if (!dtwoApp._appConfig) {
29
+ dtwoApp._appConfig = reactive(__appConfig);
30
+ }
31
+ return dtwoApp._appConfig;
32
+ }
33
+ export function updateAppConfig(appConfig) {
34
+ const _appConfig = useAppConfig();
35
+ deepAssign(_appConfig, appConfig);
36
+ }
37
+ if (process.dev) {
38
+ let applyHMR = function(newConfig) {
39
+ const appConfig = useAppConfig();
40
+ if (newConfig && appConfig) {
41
+ deepAssign(appConfig, newConfig);
42
+ deepDelete(appConfig, newConfig);
43
+ }
44
+ };
45
+ if (import.meta.hot) {
46
+ import.meta.hot.accept((newModule) => {
47
+ const newConfig = newModule._getAppConfig();
48
+ applyHMR(newConfig);
49
+ });
50
+ }
51
+ if (import.meta.webpackHot) {
52
+ import.meta.webpackHot.accept("#build/app.config.mjs", () => {
53
+ applyHMR(__appConfig);
54
+ });
55
+ }
56
+ }
@@ -0,0 +1,122 @@
1
+ import { Ref } from 'kdu';
2
+ import type { App, onErrorCaptured, KNode } from 'kdu';
3
+ import { Hookable } from 'hookable';
4
+ import type { RuntimeConfig, AppConfigInput } from '@dtwo/schema';
5
+ import type { SSRContext } from 'kdu-bundle-renderer/runtime';
6
+ import type { H3Event } from 'h3';
7
+ type DtwoMeta = {
8
+ htmlAttrs?: string;
9
+ headAttrs?: string;
10
+ bodyAttrs?: string;
11
+ headTags?: string;
12
+ bodyScriptsPrepend?: string;
13
+ bodyScripts?: string;
14
+ };
15
+ type HookResult = Promise<void> | void;
16
+ type AppRenderedContext = {
17
+ ssrContext: DtwoApp['ssrContext'];
18
+ };
19
+ export interface RuntimeDtwoHooks {
20
+ 'app:created': (app: App<Element>) => HookResult;
21
+ 'app:beforeMount': (app: App<Element>) => HookResult;
22
+ 'app:mounted': (app: App<Element>) => HookResult;
23
+ 'app:rendered': (ctx: AppRenderedContext) => HookResult;
24
+ 'app:redirected': () => HookResult;
25
+ 'app:suspense:resolve': (Component?: KNode) => HookResult;
26
+ 'app:error': (err: any) => HookResult;
27
+ 'app:error:cleared': (options: {
28
+ redirect?: string;
29
+ }) => HookResult;
30
+ 'app:data:refresh': (keys?: string[]) => HookResult;
31
+ 'link:prefetch': (link: string) => HookResult;
32
+ 'page:start': (Component?: KNode) => HookResult;
33
+ 'page:finish': (Component?: KNode) => HookResult;
34
+ 'page:transition:finish': (Component?: KNode) => HookResult;
35
+ 'kdu:setup': () => void;
36
+ 'kdu:error': (...args: Parameters<Parameters<typeof onErrorCaptured>[0]>) => HookResult;
37
+ }
38
+ export interface DtwoSSRContext extends SSRContext {
39
+ url: string;
40
+ event: H3Event;
41
+ runtimeConfig: RuntimeConfig;
42
+ noSSR: boolean;
43
+ /** whether we are rendering an SSR error */
44
+ error?: boolean;
45
+ dtwo: _DtwoApp;
46
+ payload: _DtwoApp['payload'];
47
+ teleports?: Record<string, string>;
48
+ renderMeta?: () => Promise<DtwoMeta> | DtwoMeta;
49
+ }
50
+ interface _DtwoApp {
51
+ kduApp: App<Element>;
52
+ globalName: string;
53
+ hooks: Hookable<RuntimeDtwoHooks>;
54
+ hook: _DtwoApp['hooks']['hook'];
55
+ callHook: _DtwoApp['hooks']['callHook'];
56
+ [key: string]: any;
57
+ _asyncDataPromises: Record<string, Promise<any> | undefined>;
58
+ _asyncData: Record<string, {
59
+ data: Ref<any>;
60
+ pending: Ref<boolean>;
61
+ error: Ref<any>;
62
+ } | undefined>;
63
+ isHydrating?: boolean;
64
+ deferHydration: () => () => void | Promise<void>;
65
+ ssrContext?: DtwoSSRContext;
66
+ payload: {
67
+ serverRendered?: boolean;
68
+ prerenderedAt?: number;
69
+ data: Record<string, any>;
70
+ state: Record<string, any>;
71
+ rendered?: Function;
72
+ error?: Error | {
73
+ url: string;
74
+ statusCode: string;
75
+ statusMessage: string;
76
+ message: string;
77
+ description: string;
78
+ data?: any;
79
+ } | null;
80
+ [key: string]: any;
81
+ };
82
+ static: {
83
+ data: Record<string, any>;
84
+ };
85
+ provide: (name: string, value: any) => void;
86
+ }
87
+ export interface DtwoApp extends _DtwoApp {
88
+ }
89
+ export declare const DtwoPluginIndicator = "__dtwo_plugin";
90
+ export interface Plugin<Injections extends Record<string, any> = Record<string, any>> {
91
+ (dtwo: _DtwoApp): Promise<void> | Promise<{
92
+ provide?: Injections;
93
+ }> | void | {
94
+ provide?: Injections;
95
+ };
96
+ [DtwoPluginIndicator]?: true;
97
+ }
98
+ export interface CreateOptions {
99
+ kduApp: DtwoApp['kduApp'];
100
+ ssrContext?: DtwoApp['ssrContext'];
101
+ globalName?: DtwoApp['globalName'];
102
+ }
103
+ export declare function createDtwoApp(options: CreateOptions): DtwoApp;
104
+ export declare function applyPlugin(dtwoApp: DtwoApp, plugin: Plugin): Promise<void>;
105
+ export declare function applyPlugins(dtwoApp: DtwoApp, plugins: Plugin[]): Promise<void>;
106
+ export declare function normalizePlugins(_plugins: Plugin[]): Plugin<Record<string, any>>[];
107
+ export declare function defineDtwoPlugin<T extends Record<string, any>>(plugin: Plugin<T>): Plugin<T>;
108
+ export declare function isDtwoPlugin(plugin: unknown): boolean;
109
+ /**
110
+ * Ensures that the setup function passed in has access to the Dtwo instance via `useDtwo`.
111
+ *
112
+ * @param dtwo A Dtwo instance
113
+ * @param setup The function to call
114
+ */
115
+ export declare function callWithDtwo<T extends (...args: any[]) => any>(dtwo: DtwoApp | _DtwoApp, setup: T, args?: Parameters<T>): any;
116
+ /**
117
+ * Returns the current Dtwo instance.
118
+ */
119
+ export declare function useDtwoApp(): DtwoApp;
120
+ export declare function useRuntimeConfig(): RuntimeConfig;
121
+ export declare function defineAppConfig<C extends AppConfigInput>(config: C): C;
122
+ export {};