nuxt-kirby 4.2.0 → 5.0.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 (35) hide show
  1. package/README.md +4 -4
  2. package/dist/module.d.mts +49 -41
  3. package/dist/module.json +2 -2
  4. package/dist/module.mjs +159 -136
  5. package/dist/runtime/composables/$kirby.d.ts +7 -32
  6. package/dist/runtime/composables/$kirby.js +48 -61
  7. package/dist/runtime/composables/$kql.d.ts +1 -28
  8. package/dist/runtime/composables/$kql.js +7 -48
  9. package/dist/runtime/composables/useKirbyData.d.ts +31 -20
  10. package/dist/runtime/composables/useKirbyData.js +19 -30
  11. package/dist/runtime/composables/useKql.d.ts +5 -23
  12. package/dist/runtime/composables/useKql.js +10 -26
  13. package/dist/runtime/server/cache.d.ts +2 -0
  14. package/dist/runtime/server/cache.js +77 -0
  15. package/dist/runtime/server/imports.d.ts +3 -21
  16. package/dist/runtime/server/imports.js +11 -20
  17. package/dist/runtime/server/path.d.ts +9 -0
  18. package/dist/runtime/server/path.js +56 -0
  19. package/dist/runtime/server/proxy.d.ts +20 -0
  20. package/dist/runtime/server/proxy.js +118 -0
  21. package/dist/runtime/server/stream.d.ts +5 -0
  22. package/dist/runtime/server/stream.js +20 -0
  23. package/dist/runtime/types.d.ts +50 -15
  24. package/dist/runtime/types.js +1 -0
  25. package/dist/runtime/utils.d.ts +5 -16
  26. package/dist/runtime/utils.js +10 -15
  27. package/package.json +5 -4
  28. package/dist/runtime/cache.d.ts +0 -11
  29. package/dist/runtime/cache.js +0 -25
  30. package/dist/runtime/kirby-types.d.ts +0 -1
  31. package/dist/runtime/kirby-types.js +0 -0
  32. package/dist/runtime/path.d.ts +0 -6
  33. package/dist/runtime/path.js +0 -10
  34. package/dist/runtime/server/handler.d.ts +0 -2
  35. package/dist/runtime/server/handler.js +0 -179
@@ -1,64 +1,51 @@
1
- import { hash } from "ohash";
2
- import { useRequestFetch, useRuntimeConfig } from "#imports";
3
- import { sendCachedRequest } from "../cache.js";
4
- import { assertPathBelowBase } from "../path.js";
5
- import { buildApiProxyPath, createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
6
- export async function $kirby(path, opts = {}) {
7
- const { payloadCache = true, ...requestOptions } = opts;
8
- const key = opts.key || `$kirby${hash([
9
- path,
10
- opts.method,
11
- opts.query,
12
- opts.body,
13
- opts.language,
14
- opts.forwardCookies,
15
- headersToObject(opts.headers)
16
- ])}`;
17
- return sendCachedRequest(key, payloadCache, () => sendKirbyRequest(path, { ...requestOptions, key }));
1
+ import { joinURL } from "ufo";
2
+ import { toValue } from "vue";
3
+ import { proxyRoute } from "#build/module/nuxt-kirby.config";
4
+ import { useNuxtApp, useRequestEvent, useRequestHeaders, useRuntimeConfig } from "#imports";
5
+ import { assertPathBelowBase } from "../server/path.js";
6
+ import { createAuthHeader, createLanguageHeader, mergeHeaders } from "../utils.js";
7
+ let hasWarnedAboutHydration = false;
8
+ export function $kirby(path, opts = {}) {
9
+ warnAboutHydration("$kirby", "useKirbyData");
10
+ return createKirbyFetch()(path, opts);
18
11
  }
19
- export function sendKirbyRequest(path, opts) {
20
- const kirby = useRuntimeConfig().public.kirby;
21
- const {
22
- method,
23
- headers,
24
- query,
25
- body,
26
- language,
27
- key,
28
- forwardCookies,
29
- ...fetchOptions
30
- } = opts;
31
- if (kirby.client)
32
- assertPathBelowBase(path);
33
- const sharedHeaders = {
34
- ...headersToObject(headers),
35
- ...createLanguageHeader(language)
36
- };
37
- const _serverFetchOptions = {
38
- method: "POST",
39
- body: {
40
- path,
41
- method,
42
- query,
43
- body,
44
- headers: sharedHeaders,
45
- forwardCookies
46
- }
47
- };
48
- const _clientFetchOptions = {
49
- baseURL: kirby.url,
50
- query,
51
- method,
52
- headers: {
53
- ...sharedHeaders,
54
- ...createAuthHeader(kirby)
55
- },
56
- body,
57
- // There is no proxy to forward anything here, so the browser has to attach the cookie itself.
58
- credentials: forwardCookies ?? kirby.forwardCookies ? "include" : void 0
12
+ export function warnAboutHydration(functionName, composableName) {
13
+ if (!import.meta.dev || !import.meta.client || hasWarnedAboutHydration)
14
+ return;
15
+ const nuxt = useNuxtApp();
16
+ if (nuxt.isHydrating && nuxt.payload.serverRendered) {
17
+ hasWarnedAboutHydration = true;
18
+ console.warn(`[nuxt-kirby] \`${functionName}\` sent a request during hydration. If the server sent it as well while rendering the page, wrap the call in \`useAsyncData\` or use \`${composableName}\` to reuse the server's response.`);
19
+ }
20
+ }
21
+ export function createKirbyFetch() {
22
+ const runtimeConfig = useRuntimeConfig();
23
+ const kirby = runtimeConfig.public.kirby;
24
+ const baseURL = kirby.client ? kirby.url : joinURL(runtimeConfig.app.baseURL, proxyRoute);
25
+ const kirbyFetch = globalThis.$fetch;
26
+ const requestEvent = import.meta.server && !kirby.client ? useRequestEvent() : void 0;
27
+ const visitorHeaders = requestEvent ? useRequestHeaders(["cookie"]) : {};
28
+ return async function(path, opts = {}) {
29
+ const { language, headers, ...fetchOptions } = opts;
30
+ if (kirby.client)
31
+ assertPathBelowBase(path);
32
+ const encodedBody = requestEvent && (fetchOptions.body instanceof FormData || fetchOptions.body instanceof URLSearchParams || fetchOptions.body instanceof Blob) ? new Response(fetchOptions.body) : void 0;
33
+ return kirbyFetch(joinURL(baseURL, path), {
34
+ ...fetchOptions,
35
+ headers: mergeHeaders(
36
+ visitorHeaders,
37
+ encodedBody?.headers,
38
+ headers,
39
+ createLanguageHeader(toValue(language)),
40
+ kirby.client ? createAuthHeader(kirby) : void 0
41
+ ),
42
+ ...encodedBody && {
43
+ body: new Uint8Array(await encodedBody.arrayBuffer())
44
+ },
45
+ // Hands the proxy the page request's platform bindings, such as `event.context.cloudflare`, as `useRequestFetch` does.
46
+ ...requestEvent && { context: requestEvent.context },
47
+ // Without it, `$fetch` would prepend `app.baseURL`.
48
+ baseURL: ""
49
+ });
59
50
  };
60
- return useRequestFetch()(kirby.client ? path : buildApiProxyPath(key), {
61
- ...fetchOptions,
62
- ...kirby.client ? _clientFetchOptions : _serverFetchOptions
63
- });
64
51
  }
@@ -1,30 +1,3 @@
1
1
  import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
- import type { NitroFetchOptions } from 'nitropack';
3
- export type KqlOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
4
- /**
5
- * Language code to fetch data for in multi-language Kirby setups.
6
- */
7
- language?: string;
8
- /**
9
- * Serve a repeated request from the Nuxt payload instead of sending it again.
10
- * @default true
11
- */
12
- payloadCache?: boolean;
13
- /**
14
- * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
15
- *
16
- * @remarks
17
- * Such a request never reads from or writes to the server-side cache, since one stored response
18
- * is shared between all visitors.
19
- */
20
- forwardCookies?: boolean;
21
- /**
22
- * Cache key, generated from the request options by default.
23
- */
24
- key?: string;
25
- };
2
+ import type { KqlOptions } from '../types.js';
26
3
  export declare function $kql<T extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse>(query: KirbyQueryRequest, opts?: KqlOptions): Promise<T>;
27
- /** Sends the query with nothing cached in front of it. */
28
- export declare function sendKqlRequest<T extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse>(query: KirbyQueryRequest, opts: Omit<KqlOptions, 'payloadCache'> & {
29
- key: string;
30
- }): Promise<T>;
@@ -1,51 +1,10 @@
1
- import { hash } from "ohash";
2
- import { useRequestFetch, useRuntimeConfig } from "#imports";
3
- import { sendCachedRequest } from "../cache.js";
4
- import { buildApiProxyPath, createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
5
- export async function $kql(query, opts = {}) {
6
- const { payloadCache = true, ...requestOptions } = opts;
7
- const key = opts.key || `$kql${hash([
8
- query,
9
- opts.language,
10
- opts.forwardCookies,
11
- headersToObject(opts.headers)
12
- ])}`;
13
- return sendCachedRequest(key, payloadCache, () => sendKqlRequest(query, { ...requestOptions, key }));
14
- }
15
- export function sendKqlRequest(query, opts) {
16
- const kirby = useRuntimeConfig().public.kirby;
17
- const {
18
- headers,
19
- language,
20
- key,
21
- forwardCookies,
22
- ...fetchOptions
23
- } = opts;
24
- const sharedHeaders = {
25
- ...headersToObject(headers),
26
- ...createLanguageHeader(language)
27
- };
28
- const _serverFetchOptions = {
29
- method: "POST",
30
- body: {
31
- query,
32
- headers: sharedHeaders,
33
- forwardCookies
34
- }
35
- };
36
- const _clientFetchOptions = {
37
- baseURL: kirby.url,
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { createKirbyFetch, warnAboutHydration } from "./$kirby.js";
3
+ export function $kql(query, opts = {}) {
4
+ warnAboutHydration("$kql", "useKql");
5
+ return createKirbyFetch()(useRuntimeConfig().public.kirby.kqlPath, {
6
+ ...opts,
38
7
  method: "POST",
39
- headers: {
40
- ...sharedHeaders,
41
- ...createAuthHeader(kirby)
42
- },
43
- body: query,
44
- // There is no proxy to forward anything here, so the browser has to attach the cookie itself.
45
- credentials: forwardCookies ?? kirby.forwardCookies ? "include" : void 0
46
- };
47
- return useRequestFetch()(kirby.client ? kirby.kqlPath : buildApiProxyPath(key), {
48
- ...fetchOptions,
49
- ...kirby.client ? _clientFetchOptions : _serverFetchOptions
8
+ body: query
50
9
  });
51
10
  }
@@ -1,27 +1,38 @@
1
- import type { NitroFetchOptions } from 'nitropack';
2
- import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
3
- import type { MaybeRefOrGetter, MultiWatchSources } from 'vue';
4
- export type UseKirbyDataOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'method' | 'headers' | 'query' | 'body' | 'retry' | 'retryDelay' | 'retryStatusCodes'> & {
1
+ import type { AsyncData, KeysOf, NuxtError, PickFrom, UseFetchOptions } from 'nuxt/app';
2
+ import type { FetchOptions } from 'ofetch';
3
+ import type { MaybeRef, MaybeRefOrGetter } from 'vue';
4
+ import type { RequestMethod } from '../types.js';
5
+ /**
6
+ * Copy of the type Nuxt maps its own fetch options through, which it does not export. `headers` stays out of it:
7
+ * Nuxt watches a ref there, but never calls a getter to see a change.
8
+ */
9
+ type ComputedOptions<T extends Record<string, any>> = {
10
+ [K in keyof T]: T[K] extends Function ? T[K] : ComputedOptions<T[K]> | MaybeRefOrGetter<T[K]>;
11
+ };
12
+ /** Headers in a ref, or a plain record of them with a ref per value, both of which Nuxt unwraps and watches. */
13
+ type MaybeRefHeaders<T> = MaybeRef<T> | (T extends Headers | readonly unknown[] ? never : T extends Record<string, any> ? {
14
+ [K in keyof T]: MaybeRef<T[K]>;
15
+ } : never);
16
+ /** Nuxt's own `useFetch` options, less those that type the request against the app's server routes or that the module decides. */
17
+ export type AsyncDataFetchOptions<ResT, DataT, PickKeys extends KeysOf<DataT>, DefaultT> = Omit<UseFetchOptions<ResT, DataT, PickKeys, DefaultT>, 'baseURL' | '$fetch' | 'method' | 'query' | 'params' | 'body' | 'headers'> & {
18
+ headers?: MaybeRefHeaders<FetchOptions['headers']>;
5
19
  /**
6
- * Language code to fetch data for in multi-language Kirby setups.
20
+ * Language to ask the content in. Each language gets a key of its own.
7
21
  *
8
22
  * @remarks
9
23
  * Travels as the `X-Language` header, which Kirby reads on API routes. Kirby Headless 8.1 also
10
24
  * reads it on the global-routes catch-all, but only for a path that names no language itself.
11
25
  */
12
- language?: MaybeRefOrGetter<string>;
13
- /**
14
- * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
15
- *
16
- * @remarks
17
- * Such a request never reads from or writes to the server-side cache, since one stored response
18
- * is shared between all visitors.
19
- */
20
- forwardCookies?: boolean;
21
- /**
22
- * Watch an array of reactive sources and auto-refresh the fetch result when they change.
23
- * Path and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
24
- */
25
- watch?: MultiWatchSources | false;
26
+ language?: MaybeRefOrGetter<string | undefined>;
26
27
  };
27
- export declare function useKirbyData<T = any>(path: MaybeRefOrGetter<string>, opts?: UseKirbyDataOptions<T>): AsyncData<T | undefined, NuxtError>;
28
+ export type UseKirbyDataOptions<ResT, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined> = AsyncDataFetchOptions<ResT, DataT, PickKeys, DefaultT> & ComputedOptions<{
29
+ method?: RequestMethod;
30
+ query?: FetchOptions['query'];
31
+ body?: FetchOptions['body'];
32
+ }>;
33
+ export declare const _useKirbyFetch: import("nuxt/app").UseFetch<unknown, KeysOf<unknown>, undefined, "", {
34
+ language?: MaybeRefOrGetter<string | undefined>;
35
+ }, {}>;
36
+ export declare function splitAutoKey<T>(optionsOrKey: T | string | undefined, autoKey: string | undefined): [T | undefined, string | undefined];
37
+ export declare function useKirbyData<ResT = any, ErrorT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(path: MaybeRefOrGetter<string>, arg1?: UseKirbyDataOptions<ResT, DataT, PickKeys, DefaultT> | string, arg2?: string): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, NuxtError<ErrorT> | undefined>;
38
+ export {};
@@ -1,31 +1,20 @@
1
- import { hash } from "ohash";
2
- import { computed, toValue } from "vue";
3
- import { useFetch } from "#imports";
4
- import { headersToObject } from "../utils.js";
5
- import { sendKirbyRequest } from "./$kirby.js";
6
- export function useKirbyData(path, opts = {}) {
7
- const { language, forwardCookies, ...fetchOptions } = opts;
8
- const _language = computed(() => toValue(language));
9
- const _path = computed(() => toValue(path).replace(/^\//, ""));
10
- const key = computed(() => `$kirby${hash([
11
- _path.value,
12
- _language.value,
13
- toValue(fetchOptions.query),
14
- toValue(fetchOptions.method),
15
- toValue(fetchOptions.body),
16
- forwardCookies,
17
- headersToObject(toValue(fetchOptions.headers))
18
- ])}`);
19
- if (!_path.value)
20
- console.warn("[nuxt-kirby] Empty Kirby path");
21
- return useFetch(_path, {
22
- ...fetchOptions,
23
- key,
24
- $fetch: ((_request, options) => sendKirbyRequest(_path.value, {
25
- ...options,
26
- language: _language.value,
27
- forwardCookies,
28
- key: key.value
29
- }))
30
- });
1
+ import { toValue } from "vue";
2
+ import { defineUseFetchAddon } from "#app/composables/addons";
3
+ import { createUseFetch } from "#app/composables/fetch";
4
+ import { createKirbyFetch } from "./$kirby.js";
5
+ const kirbyAddon = defineUseFetchAddon({
6
+ key: (options) => toValue(options.language),
7
+ setup(options) {
8
+ options.$fetch = createKirbyFetch();
9
+ }
10
+ });
11
+ export const _useKirbyFetch = createUseFetch({
12
+ addons: [kirbyAddon]
13
+ });
14
+ export function splitAutoKey(optionsOrKey, autoKey) {
15
+ return typeof optionsOrKey === "string" ? [void 0, optionsOrKey] : [optionsOrKey, autoKey];
16
+ }
17
+ export function useKirbyData(path, arg1, arg2) {
18
+ const [opts = {}, autoKey] = splitAutoKey(arg1, arg2);
19
+ return _useKirbyFetch(path, opts, autoKey);
31
20
  }
@@ -1,24 +1,6 @@
1
1
  import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
- import type { NitroFetchOptions } from 'nitropack';
3
- import type { AsyncData, AsyncDataOptions, NuxtError } from 'nuxt/app';
4
- import type { MaybeRefOrGetter, MultiWatchSources } from 'vue';
5
- export type UseKqlOptions<T> = Omit<AsyncDataOptions<T>, 'watch'> & Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes'> & {
6
- /**
7
- * Language code to fetch data for in multi-language Kirby setups.
8
- */
9
- language?: MaybeRefOrGetter<string>;
10
- /**
11
- * Forward the visitor's cookies to Kirby, overriding the module's `forwardCookies`.
12
- *
13
- * @remarks
14
- * Such a request never reads from or writes to the server-side cache, since one stored response
15
- * is shared between all visitors.
16
- */
17
- forwardCookies?: boolean;
18
- /**
19
- * Watch an array of reactive sources and auto-refresh the fetch result when they change.
20
- * Query and language are watched by default. You can completely ignore reactive sources by using `watch: false`.
21
- */
22
- watch?: MultiWatchSources | false;
23
- };
24
- export declare function useKql<ResT extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse, ReqT extends KirbyQueryRequest = KirbyQueryRequest>(query: MaybeRefOrGetter<ReqT>, opts?: UseKqlOptions<ResT>): AsyncData<ResT | undefined, NuxtError>;
2
+ import type { AsyncData, KeysOf, NuxtError, PickFrom } from 'nuxt/app';
3
+ import type { MaybeRefOrGetter } from 'vue';
4
+ import type { AsyncDataFetchOptions } from './useKirbyData.js';
5
+ export type UseKqlOptions<ResT, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined> = AsyncDataFetchOptions<ResT, DataT, PickKeys, DefaultT>;
6
+ export declare function useKql<ResT extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse, ReqT extends KirbyQueryRequest = KirbyQueryRequest, ErrorT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(query: MaybeRefOrGetter<ReqT>, arg1?: UseKqlOptions<ResT, DataT, PickKeys, DefaultT> | string, arg2?: string): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, NuxtError<ErrorT> | undefined>;
@@ -1,28 +1,12 @@
1
- import { hash } from "ohash";
2
1
  import { computed, toValue } from "vue";
3
- import { useFetch } from "#imports";
4
- import { headersToObject } from "../utils.js";
5
- import { sendKqlRequest } from "./$kql.js";
6
- export function useKql(query, opts = {}) {
7
- const { language, forwardCookies, ...fetchOptions } = opts;
8
- const _query = computed(() => toValue(query));
9
- const _language = computed(() => toValue(language));
10
- const key = computed(() => `$kql${hash([
11
- _query.value,
12
- _language.value,
13
- forwardCookies,
14
- headersToObject(toValue(fetchOptions.headers))
15
- ])}`);
16
- if (Object.keys(_query.value).length === 0 || !_query.value.query)
17
- console.error("[nuxt-kirby] Empty KQL query");
18
- return useFetch(key, {
19
- ...fetchOptions,
20
- key,
21
- $fetch: ((_request, options) => sendKqlRequest(_query.value, {
22
- ...options,
23
- language: _language.value,
24
- forwardCookies,
25
- key: key.value
26
- }))
27
- });
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { _useKirbyFetch, splitAutoKey } from "./useKirbyData.js";
4
+ export function useKql(query, arg1, arg2) {
5
+ const [opts = {}, autoKey] = splitAutoKey(arg1, arg2);
6
+ return _useKirbyFetch(useRuntimeConfig().public.kirby.kqlPath, {
7
+ ...opts,
8
+ method: "POST",
9
+ // Nuxt hashes the body into the key, so each query gets an entry of its own and a new query refetches.
10
+ body: computed(() => toValue(query))
11
+ }, autoKey);
28
12
  }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void | ReadableStream<Uint8Array<ArrayBufferLike>> | Uint8Array<ArrayBuffer> | null>>;
2
+ export default _default;
@@ -0,0 +1,77 @@
1
+ import { destr } from "destr";
2
+ import { createError, defineEventHandler, readRawBody } from "h3";
3
+ import { defineCachedFunction, useRuntimeConfig } from "nitropack/runtime";
4
+ import { hash } from "ohash";
5
+ import { withLeadingSlash, withoutTrailingSlash } from "ufo";
6
+ import { base64ToUint8Array, uint8ArrayToBase64 } from "uint8array-extras";
7
+ import proxy, { relayResponseHead, resolveProxyRequest, WITHHELD_RESPONSE_HEADERS } from "./proxy.js";
8
+ let cachedFetcher;
9
+ export default defineEventHandler(async (event) => {
10
+ const kirby = useRuntimeConfig(event).kirby;
11
+ const { method } = event;
12
+ if (!kirby.server.cache || kirby.forwardCookies || method !== "GET" && method !== "POST")
13
+ return proxy(event);
14
+ const { url, routePath, headers } = resolveProxyRequest(event);
15
+ const isKqlQuery = withoutTrailingSlash(routePath) === withLeadingSlash(withoutTrailingSlash(kirby.kqlPath));
16
+ if (method === "POST" && !isKqlQuery)
17
+ return proxy(event);
18
+ cachedFetcher ??= createCachedFetcher(kirby);
19
+ const response = await cachedFetcher(event, {
20
+ method,
21
+ url,
22
+ headers,
23
+ body: method === "POST" ? await readRawBody(event) : void 0
24
+ });
25
+ relayResponseHead(event, response);
26
+ return base64ToUint8Array(response.data);
27
+ });
28
+ function createCachedFetcher(kirby) {
29
+ return defineCachedFunction(
30
+ // Nitro reads the event from the first argument only, and hands the cache write to
31
+ // `event.waitUntil()` – without it an edge worker is torn down before the entry reaches storage.
32
+ (_event, request) => fetchFromKirby(request),
33
+ {
34
+ name: "nuxt-kirby",
35
+ base: kirby.server.storage,
36
+ swr: kirby.server.swr,
37
+ maxAge: kirby.server.maxAge,
38
+ // The credentials are the same for every request, so they add nothing to the key.
39
+ getKey: (_event, { method, url, headers, body }) => hash([
40
+ method,
41
+ url,
42
+ headers["x-language"],
43
+ // Two spellings of one query share an entry.
44
+ destr(body)
45
+ ]),
46
+ // A 404 or 410 is stored, so that with `swr` a page Kirby no longer has replaces the stored one.
47
+ // Any other error would answer every visitor for as long as the entry lives.
48
+ validate: (entry) => entry.value !== void 0 && (entry.value.status < 400 || entry.value.status === 404 || entry.value.status === 410)
49
+ }
50
+ );
51
+ }
52
+ async function fetchFromKirby({ method, url, headers, body }) {
53
+ let response;
54
+ try {
55
+ response = await globalThis.$fetch.raw(url, {
56
+ method,
57
+ headers,
58
+ body,
59
+ responseType: "arrayBuffer",
60
+ redirect: "manual",
61
+ ignoreResponseError: true
62
+ });
63
+ } catch (error) {
64
+ console.error("[nuxt-kirby]", error);
65
+ throw createError({
66
+ statusCode: 502,
67
+ statusMessage: "Bad Gateway"
68
+ });
69
+ }
70
+ return {
71
+ status: response.status,
72
+ statusText: response.statusText,
73
+ // A stored `set-cookie` would put Kirby's session in the shared store.
74
+ headers: [...response.headers].filter(([name]) => !WITHHELD_RESPONSE_HEADERS.has(name)),
75
+ data: uint8ArrayToBase64(new Uint8Array(response._data ?? []))
76
+ };
77
+ }
@@ -1,24 +1,6 @@
1
1
  import type { KirbyQueryRequest, KirbyQueryResponse } from 'kirby-types';
2
- import type { NitroFetchOptions } from 'nitropack';
3
- export type NitroKirbyFetchOptions = Omit<NitroFetchOptions<string>, 'baseURL'> & {
4
- /**
5
- * Language code to fetch data for in multi-language Kirby setups.
6
- *
7
- * @remarks
8
- * Travels as the `X-Language` header, which Kirby reads on API routes. Kirby Headless 8.1 also
9
- * reads it on the global-routes catch-all, but only for a path that names no language itself.
10
- */
11
- language?: string;
12
- };
13
- export type NitroKqlFetchOptions = Pick<NitroFetchOptions<string>, 'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | 'retry' | 'retryDelay' | 'retryStatusCodes' | 'timeout' | 'signal'> & {
14
- /**
15
- * Language code to fetch data for in multi-language Kirby setups.
16
- *
17
- * @remarks
18
- * Travels as the `X-Language` header, which Kirby reads on API routes. Kirby Headless 8.1 also
19
- * reads it on the global-routes catch-all, but only for a path that names no language itself.
20
- */
21
- language?: string;
22
- };
2
+ import type { KirbyFetchOptions, KqlOptions } from '../types.js';
3
+ export type NitroKirbyFetchOptions = KirbyFetchOptions;
4
+ export type NitroKqlFetchOptions = KqlOptions;
23
5
  export declare function $kirby<T = any>(path: string, opts?: NitroKirbyFetchOptions): Promise<T>;
24
6
  export declare function $kql<T extends KirbyQueryResponse<any, boolean> = KirbyQueryResponse>(query: KirbyQueryRequest, opts?: NitroKqlFetchOptions): Promise<T>;
@@ -1,32 +1,23 @@
1
- import { useRuntimeConfig } from "#imports";
2
- import { assertPathBelowBase } from "../path.js";
3
- import { createAuthHeader, createLanguageHeader, headersToObject } from "../utils.js";
1
+ import { useRuntimeConfig } from "nitropack/runtime";
2
+ import { joinURL } from "ufo";
3
+ import { createAuthHeader, createLanguageHeader, mergeHeaders } from "../utils.js";
4
+ import { assertPathBelowBase } from "./path.js";
4
5
  export async function $kirby(path, opts = {}) {
5
6
  const { headers, language, ...fetchOptions } = opts;
6
7
  const kirby = useRuntimeConfig().kirby;
7
8
  assertPathBelowBase(path);
8
- return globalThis.$fetch(path, {
9
+ return globalThis.$fetch(joinURL(kirby.url, path), {
9
10
  ...fetchOptions,
10
- baseURL: kirby.url,
11
- headers: {
12
- ...headersToObject(headers),
13
- ...createLanguageHeader(language),
14
- ...createAuthHeader(kirby)
15
- }
11
+ // Without it, `$fetch` would prepend `app.baseURL`.
12
+ baseURL: "",
13
+ headers: mergeHeaders(headers, createLanguageHeader(language), createAuthHeader(kirby))
16
14
  });
17
15
  }
18
16
  export async function $kql(query, opts = {}) {
19
- const { headers, language, ...fetchOptions } = opts;
20
17
  const kirby = useRuntimeConfig().kirby;
21
- return globalThis.$fetch(kirby.kqlPath, {
22
- ...fetchOptions,
23
- baseURL: kirby.url,
18
+ return $kirby(kirby.kqlPath, {
19
+ ...opts,
24
20
  method: "POST",
25
- body: query,
26
- headers: {
27
- ...headersToObject(headers),
28
- ...createLanguageHeader(language),
29
- ...createAuthHeader(kirby)
30
- }
21
+ body: query
31
22
  });
32
23
  }
@@ -0,0 +1,9 @@
1
+ import type { AllowedRoute } from '../types.js';
2
+ /**
3
+ * Throws a 400 for a path that a URL parser or the API behind it could read as absolute or as
4
+ * climbing above the base URL: a scheme, an authority, a tab or line break, or a dot segment, also
5
+ * percent-encoded or with a `;` parameter.
6
+ */
7
+ export declare function assertPathBelowBase(path: string): void;
8
+ export declare function resolveRoutePath(requestURL: string, baseURL: string): string;
9
+ export declare function assertAllowedRoute(allowedRoutes: AllowedRoute[] | undefined, routePath: string, method: string): void;
@@ -0,0 +1,56 @@
1
+ import { createError } from "h3";
2
+ export function assertPathBelowBase(path) {
3
+ const segments = path.split("?", 1)[0].replace(/%2e/gi, ".").replace(/%3b/gi, ";").split(/[/\\#]|%2f|%5c/i);
4
+ if (/[\t\n\r\u2028\u2029]/.test(path) || /^[^/?#]*:/.test(path) || /^[\s\u0000-\u001F]*(?:[/\\]\s*){2}/.test(path) || segments.some((segment) => /^\.{1,2}(?:;|[\u0000-\u0020]*$)/.test(segment))) {
5
+ throw createError({
6
+ statusCode: 400,
7
+ statusMessage: "Path must stay below the base URL"
8
+ });
9
+ }
10
+ }
11
+ export function resolveRoutePath(requestURL, baseURL) {
12
+ const base = new URL(baseURL, "http://localhost");
13
+ const target = new URL(requestURL, base);
14
+ const basePath = base.pathname.replace(/\/$/, "");
15
+ if (target.origin !== base.origin || target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) {
16
+ throw createError({
17
+ statusCode: 400,
18
+ statusMessage: "Path must stay below the base URL"
19
+ });
20
+ }
21
+ return target.pathname.slice(basePath.length) || "/";
22
+ }
23
+ export function assertAllowedRoute(allowedRoutes, routePath, method) {
24
+ if (!allowedRoutes)
25
+ return;
26
+ const requestMethod = method.toUpperCase();
27
+ const pathSegments = splitPath(routePath);
28
+ const isAllowed = allowedRoutes.some(
29
+ (route) => (!route.methods || route.methods.some((routeMethod) => routeMethod.toUpperCase() === requestMethod)) && matchesPattern(splitPath(route.path).map(encodePathSegment), pathSegments)
30
+ );
31
+ if (!isAllowed) {
32
+ throw createError({
33
+ statusCode: 403,
34
+ statusMessage: "Route is not allowed"
35
+ });
36
+ }
37
+ }
38
+ function splitPath(path) {
39
+ return path.replace(/^\/|\/$/g, "").split("/");
40
+ }
41
+ function encodePathSegment(segment) {
42
+ return segment.replace(/[\u0000-\u0020"#<>?^`{}\u007F-\u{10FFFF}]/gu, (character) => encodeURIComponent(character));
43
+ }
44
+ function matchesPattern(patternSegments, pathSegments) {
45
+ for (const [index, patternSegment] of patternSegments.entries()) {
46
+ if (patternSegment === "**" && index === patternSegments.length - 1)
47
+ return true;
48
+ const pathSegment = pathSegments[index];
49
+ if (pathSegment === void 0)
50
+ return false;
51
+ if (patternSegment === "*" ? pathSegment === "" : patternSegment !== pathSegment) {
52
+ return false;
53
+ }
54
+ }
55
+ return patternSegments.length === pathSegments.length;
56
+ }
@@ -0,0 +1,20 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare const WITHHELD_RESPONSE_HEADERS: Set<string>;
3
+ export interface ProxyRequest {
4
+ url: string;
5
+ /** Path below the Kirby URL, with a leading slash. */
6
+ routePath: string;
7
+ headers: Record<string, string>;
8
+ }
9
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void | ReadableStream<Uint8Array<ArrayBufferLike>> | null>>;
10
+ export default _default;
11
+ export declare function relayResponseHead(event: H3Event, { status, statusText, headers }: {
12
+ status: number;
13
+ statusText: string;
14
+ headers: Iterable<[string, string]>;
15
+ }): void;
16
+ /**
17
+ * Runs the checks every forwarded request has to pass and resolves what Kirby is sent: the URL and
18
+ * the headers, with the Kirby credentials among them.
19
+ */
20
+ export declare function resolveProxyRequest(event: H3Event): ProxyRequest;