@uniformdev/canvas-sveltekit 20.48.1-alpha.17
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.
- package/LICENSE.txt +2 -0
- package/README.md +3 -0
- package/dist/components/UniformRichText.svelte +49 -0
- package/dist/components/UniformRichText.svelte.d.ts +16 -0
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.js +1 -0
- package/dist/helpers/index.d.ts +1 -0
- package/dist/helpers/index.js +1 -0
- package/dist/helpers/resolvePathFromParams.d.ts +19 -0
- package/dist/helpers/resolvePathFromParams.js +19 -0
- package/dist/hooks/createUniformHandle.d.ts +41 -0
- package/dist/hooks/createUniformHandle.js +43 -0
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.js +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +16 -0
- package/dist/isr/config.d.ts +49 -0
- package/dist/isr/config.js +30 -0
- package/dist/isr/createRevalidateHandler.d.ts +33 -0
- package/dist/isr/createRevalidateHandler.js +50 -0
- package/dist/isr/index.d.ts +2 -0
- package/dist/isr/index.js +2 -0
- package/dist/logging/index.d.ts +6 -0
- package/dist/logging/index.js +6 -0
- package/dist/logging/logCompositionIssues.d.ts +19 -0
- package/dist/logging/logCompositionIssues.js +49 -0
- package/dist/logging/logCompositionResponse.d.ts +5 -0
- package/dist/logging/logCompositionResponse.js +40 -0
- package/dist/logging/logCompositionRouteResponse.d.ts +5 -0
- package/dist/logging/logCompositionRouteResponse.js +20 -0
- package/dist/logging/logNotFoundRouteResponse.d.ts +5 -0
- package/dist/logging/logNotFoundRouteResponse.js +8 -0
- package/dist/logging/logRedirectRouteResponse.d.ts +5 -0
- package/dist/logging/logRedirectRouteResponse.js +8 -0
- package/dist/logging/logRouteResponse.d.ts +5 -0
- package/dist/logging/logRouteResponse.js +17 -0
- package/dist/models.d.ts +61 -0
- package/dist/models.js +4 -0
- package/dist/preview/createPreviewHandler.d.ts +29 -0
- package/dist/preview/createPreviewHandler.js +35 -0
- package/dist/preview/index.d.ts +4 -0
- package/dist/preview/index.js +4 -0
- package/dist/preview/previewCookie.d.ts +33 -0
- package/dist/preview/previewCookie.js +58 -0
- package/dist/preview/previewHandlerGet.d.ts +29 -0
- package/dist/preview/previewHandlerGet.js +138 -0
- package/dist/preview/previewHandlerPost.d.ts +29 -0
- package/dist/preview/previewHandlerPost.js +44 -0
- package/dist/route/createRouteFetcher.d.ts +20 -0
- package/dist/route/createRouteFetcher.js +90 -0
- package/dist/route/createUniformEntries.d.ts +26 -0
- package/dist/route/createUniformEntries.js +72 -0
- package/dist/route/createUniformLoad.d.ts +33 -0
- package/dist/route/createUniformLoad.js +71 -0
- package/dist/route/index.d.ts +4 -0
- package/dist/route/index.js +3 -0
- package/dist/route/types.d.ts +69 -0
- package/dist/route/types.js +1 -0
- package/package.json +75 -0
package/dist/models.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { CompositionGetParameters, RootComponentInstance } from '@uniformdev/canvas';
|
|
2
|
+
/**
|
|
3
|
+
* Preview data stored in cookies for draft mode support.
|
|
4
|
+
* This is the SvelteKit equivalent of Next.js PreviewData.
|
|
5
|
+
*/
|
|
6
|
+
export type UniformPreviewData = {
|
|
7
|
+
/** Whether this is a contextual editing session from Canvas editor */
|
|
8
|
+
isUniformContextualEditing: boolean;
|
|
9
|
+
/** The composition ID being edited */
|
|
10
|
+
compositionId?: string;
|
|
11
|
+
/** The slug of the composition */
|
|
12
|
+
compositionSlug?: string;
|
|
13
|
+
/** The path of the composition in the project map */
|
|
14
|
+
compositionPath?: string;
|
|
15
|
+
/** The locale being previewed */
|
|
16
|
+
locale?: string;
|
|
17
|
+
/** Whether this is a playground preview (component/pattern preview) */
|
|
18
|
+
isPlayground?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* The type of pattern being previewed in Canvas editor.
|
|
21
|
+
* Only set when `isPlayground` is `true`.
|
|
22
|
+
* "component" for component patterns, "composition" for composition patterns
|
|
23
|
+
*/
|
|
24
|
+
patternType?: Exclude<CompositionGetParameters['patternType'], 'all'>;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The name of the cookie used to store preview data.
|
|
28
|
+
*/
|
|
29
|
+
export declare const UNIFORM_PREVIEW_COOKIE_NAME = "uniform-preview";
|
|
30
|
+
/**
|
|
31
|
+
* Result returned from route fetching when a composition is found.
|
|
32
|
+
*/
|
|
33
|
+
export type RouteCompositionResult<TData = RootComponentInstance> = {
|
|
34
|
+
/** The matched route pattern from the project map */
|
|
35
|
+
matchedRoute: string;
|
|
36
|
+
/** Dynamic input values extracted from the route */
|
|
37
|
+
dynamicInputs: Record<string, string>;
|
|
38
|
+
/** The composition data */
|
|
39
|
+
data: TData;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Props passed to a page component from the load function.
|
|
43
|
+
*/
|
|
44
|
+
export type UniformPageData<TData = RootComponentInstance> = RouteCompositionResult<TData>;
|
|
45
|
+
/**
|
|
46
|
+
* Options for resolving the full path for preview redirect.
|
|
47
|
+
*/
|
|
48
|
+
export type ResolveFullPathOptions = {
|
|
49
|
+
/** The ID of the composition */
|
|
50
|
+
id?: string;
|
|
51
|
+
/** The slug of the composition */
|
|
52
|
+
slug?: string;
|
|
53
|
+
/** The path of the project map node attached to the composition */
|
|
54
|
+
path?: string;
|
|
55
|
+
/** The preview locale selected in Visual Canvas */
|
|
56
|
+
locale?: string;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Function to resolve the full path for preview redirect.
|
|
60
|
+
*/
|
|
61
|
+
export type ResolveFullPath = (options: ResolveFullPathOptions) => string | undefined;
|
package/dist/models.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { RequestHandler } from '@sveltejs/kit';
|
|
2
|
+
import { type CreatePreviewHandlerGetOptions } from './previewHandlerGet.js';
|
|
3
|
+
import { type CreatePreviewHandlerPostOptions } from './previewHandlerPost.js';
|
|
4
|
+
/**
|
|
5
|
+
* Options for creating the combined preview handler.
|
|
6
|
+
*/
|
|
7
|
+
export type CreatePreviewHandlerOptions = CreatePreviewHandlerGetOptions & CreatePreviewHandlerPostOptions;
|
|
8
|
+
/**
|
|
9
|
+
* Creates a combined preview handler that handles both GET and POST requests.
|
|
10
|
+
* Returns an object with GET, POST, and OPTIONS handlers.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // In src/routes/api/preview/+server.ts
|
|
14
|
+
* import { createPreviewHandler } from '@uniformdev/canvas-sveltekit/preview';
|
|
15
|
+
*
|
|
16
|
+
* const handlers = createPreviewHandler({
|
|
17
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
18
|
+
* playgroundPath: '/playground',
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* export const GET = handlers.GET;
|
|
22
|
+
* export const POST = handlers.POST;
|
|
23
|
+
* export const OPTIONS = handlers.OPTIONS;
|
|
24
|
+
*/
|
|
25
|
+
export declare function createPreviewHandler(options?: CreatePreviewHandlerOptions): {
|
|
26
|
+
GET: RequestHandler;
|
|
27
|
+
POST: RequestHandler;
|
|
28
|
+
OPTIONS: RequestHandler;
|
|
29
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createPreviewHandlerGet } from './previewHandlerGet.js';
|
|
2
|
+
import { createPreviewHandlerPost } from './previewHandlerPost.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a combined preview handler that handles both GET and POST requests.
|
|
5
|
+
* Returns an object with GET, POST, and OPTIONS handlers.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* // In src/routes/api/preview/+server.ts
|
|
9
|
+
* import { createPreviewHandler } from '@uniformdev/canvas-sveltekit/preview';
|
|
10
|
+
*
|
|
11
|
+
* const handlers = createPreviewHandler({
|
|
12
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
13
|
+
* playgroundPath: '/playground',
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* export const GET = handlers.GET;
|
|
17
|
+
* export const POST = handlers.POST;
|
|
18
|
+
* export const OPTIONS = handlers.OPTIONS;
|
|
19
|
+
*/
|
|
20
|
+
export function createPreviewHandler(options) {
|
|
21
|
+
const { secret, resolveFullPath, playgroundPath, enhance } = options ?? {};
|
|
22
|
+
const GET = createPreviewHandlerGet({ secret, resolveFullPath, playgroundPath });
|
|
23
|
+
const POST = createPreviewHandlerPost({ secret, enhance });
|
|
24
|
+
const OPTIONS = async () => {
|
|
25
|
+
return new Response(null, {
|
|
26
|
+
status: 204,
|
|
27
|
+
headers: {
|
|
28
|
+
'Access-Control-Allow-Origin': '*',
|
|
29
|
+
'Access-Control-Allow-Headers': '*',
|
|
30
|
+
'Access-Control-Allow-Methods': 'GET, POST, HEAD, OPTIONS',
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
return { GET, POST, OPTIONS };
|
|
35
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createPreviewHandler, type CreatePreviewHandlerOptions } from './createPreviewHandler.js';
|
|
2
|
+
export { clearPreviewData, deserializePreviewData, getPreviewData, isPreviewMode, serializePreviewData, setPreviewData, } from './previewCookie.js';
|
|
3
|
+
export { createPreviewHandlerGet, type CreatePreviewHandlerGetOptions } from './previewHandlerGet.js';
|
|
4
|
+
export { createPreviewHandlerPost, type CreatePreviewHandlerPostOptions } from './previewHandlerPost.js';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createPreviewHandler } from './createPreviewHandler.js';
|
|
2
|
+
export { clearPreviewData, deserializePreviewData, getPreviewData, isPreviewMode, serializePreviewData, setPreviewData, } from './previewCookie.js';
|
|
3
|
+
export { createPreviewHandlerGet } from './previewHandlerGet.js';
|
|
4
|
+
export { createPreviewHandlerPost } from './previewHandlerPost.js';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Cookies } from '@sveltejs/kit';
|
|
2
|
+
import { type UniformPreviewData } from '../models.js';
|
|
3
|
+
/**
|
|
4
|
+
* Serializes preview data to a cookie value.
|
|
5
|
+
*/
|
|
6
|
+
export declare function serializePreviewData(data: UniformPreviewData): string;
|
|
7
|
+
/**
|
|
8
|
+
* Deserializes preview data from a cookie value.
|
|
9
|
+
*/
|
|
10
|
+
export declare function deserializePreviewData(value: string): UniformPreviewData | null;
|
|
11
|
+
/**
|
|
12
|
+
* Gets preview data from cookies.
|
|
13
|
+
*/
|
|
14
|
+
export declare function getPreviewData(cookies: Cookies): UniformPreviewData | null;
|
|
15
|
+
/**
|
|
16
|
+
* Sets preview data in cookies.
|
|
17
|
+
*
|
|
18
|
+
* @param cookies - SvelteKit Cookies object
|
|
19
|
+
* @param data - Preview data to set
|
|
20
|
+
* @param options - Cookie options
|
|
21
|
+
*/
|
|
22
|
+
export declare function setPreviewData(cookies: Cookies, data: UniformPreviewData, options?: {
|
|
23
|
+
/** Max age in seconds. For contextual editing, use a short value (10s). */
|
|
24
|
+
maxAge?: number;
|
|
25
|
+
}): void;
|
|
26
|
+
/**
|
|
27
|
+
* Clears preview data from cookies.
|
|
28
|
+
*/
|
|
29
|
+
export declare function clearPreviewData(cookies: Cookies): void;
|
|
30
|
+
/**
|
|
31
|
+
* Checks if preview mode is active.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isPreviewMode(cookies: Cookies): boolean;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { UNIFORM_PREVIEW_COOKIE_NAME } from '../models.js';
|
|
2
|
+
/**
|
|
3
|
+
* Serializes preview data to a cookie value.
|
|
4
|
+
*/
|
|
5
|
+
export function serializePreviewData(data) {
|
|
6
|
+
return Buffer.from(JSON.stringify(data)).toString('base64');
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Deserializes preview data from a cookie value.
|
|
10
|
+
*/
|
|
11
|
+
export function deserializePreviewData(value) {
|
|
12
|
+
try {
|
|
13
|
+
const decoded = Buffer.from(value, 'base64').toString('utf-8');
|
|
14
|
+
return JSON.parse(decoded);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Gets preview data from cookies.
|
|
22
|
+
*/
|
|
23
|
+
export function getPreviewData(cookies) {
|
|
24
|
+
const cookie = cookies.get(UNIFORM_PREVIEW_COOKIE_NAME);
|
|
25
|
+
if (!cookie) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return deserializePreviewData(cookie);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Sets preview data in cookies.
|
|
32
|
+
*
|
|
33
|
+
* @param cookies - SvelteKit Cookies object
|
|
34
|
+
* @param data - Preview data to set
|
|
35
|
+
* @param options - Cookie options
|
|
36
|
+
*/
|
|
37
|
+
export function setPreviewData(cookies, data, options) {
|
|
38
|
+
const value = serializePreviewData(data);
|
|
39
|
+
cookies.set(UNIFORM_PREVIEW_COOKIE_NAME, value, {
|
|
40
|
+
path: '/',
|
|
41
|
+
httpOnly: true,
|
|
42
|
+
sameSite: 'none', // Required for iframe embedding in Canvas editor
|
|
43
|
+
secure: true,
|
|
44
|
+
maxAge: options?.maxAge,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Clears preview data from cookies.
|
|
49
|
+
*/
|
|
50
|
+
export function clearPreviewData(cookies) {
|
|
51
|
+
cookies.delete(UNIFORM_PREVIEW_COOKIE_NAME, { path: '/' });
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Checks if preview mode is active.
|
|
55
|
+
*/
|
|
56
|
+
export function isPreviewMode(cookies) {
|
|
57
|
+
return cookies.get(UNIFORM_PREVIEW_COOKIE_NAME) !== undefined;
|
|
58
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type RequestHandler } from '@sveltejs/kit';
|
|
2
|
+
import { type ResolveFullPath } from '../models.js';
|
|
3
|
+
/**
|
|
4
|
+
* Options for creating the preview GET handler.
|
|
5
|
+
*/
|
|
6
|
+
export type CreatePreviewHandlerGetOptions = {
|
|
7
|
+
/** Function that returns the preview secret. If set, requests must include matching secret. */
|
|
8
|
+
secret?: () => string;
|
|
9
|
+
/**
|
|
10
|
+
* Resolves the full path to redirect to.
|
|
11
|
+
* Defaults to returning `path` if truthy, otherwise returns `slug`.
|
|
12
|
+
*/
|
|
13
|
+
resolveFullPath?: ResolveFullPath;
|
|
14
|
+
/** The path to the playground page for live previewing components/patterns */
|
|
15
|
+
playgroundPath?: string;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Creates a SvelteKit GET request handler for preview mode.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* // In +server.ts
|
|
22
|
+
* import { createPreviewHandlerGet } from '@uniformdev/canvas-sveltekit/preview';
|
|
23
|
+
*
|
|
24
|
+
* export const GET = createPreviewHandlerGet({
|
|
25
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
26
|
+
* playgroundPath: '/playground',
|
|
27
|
+
* });
|
|
28
|
+
*/
|
|
29
|
+
export declare function createPreviewHandlerGet(options?: CreatePreviewHandlerGetOptions): RequestHandler;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { error, redirect } from '@sveltejs/kit';
|
|
2
|
+
import { IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM, IN_CONTEXT_EDITOR_QUERY_STRING_PARAM, isAllowedReferrer, SECRET_QUERY_STRING_PARAM, } from '@uniformdev/canvas';
|
|
3
|
+
import {} from '../models.js';
|
|
4
|
+
import { clearPreviewData, setPreviewData } from './previewCookie.js';
|
|
5
|
+
const BASE_URL_EXAMPLE = 'https://example.com';
|
|
6
|
+
const compositionQueryParams = {
|
|
7
|
+
id: 'id',
|
|
8
|
+
slug: 'slug',
|
|
9
|
+
path: 'path',
|
|
10
|
+
locale: 'locale',
|
|
11
|
+
};
|
|
12
|
+
const contextualEditingQueryParams = [
|
|
13
|
+
IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
|
|
14
|
+
IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM,
|
|
15
|
+
];
|
|
16
|
+
const resolveFullPathDefault = ({ slug, path }) => {
|
|
17
|
+
return path || slug;
|
|
18
|
+
};
|
|
19
|
+
function validateLocalRedirectUrl(pathToRedirectTo) {
|
|
20
|
+
// Prevent open redirection to any complete URL with a protocol
|
|
21
|
+
if (pathToRedirectTo?.match(/^[a-z]+:\/\//g)) {
|
|
22
|
+
throw new Error('Tried to redirect to absolute URL with protocol. Disallowing open redirect.');
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Creates a SvelteKit GET request handler for preview mode.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* // In +server.ts
|
|
30
|
+
* import { createPreviewHandlerGet } from '@uniformdev/canvas-sveltekit/preview';
|
|
31
|
+
*
|
|
32
|
+
* export const GET = createPreviewHandlerGet({
|
|
33
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
34
|
+
* playgroundPath: '/playground',
|
|
35
|
+
* });
|
|
36
|
+
*/
|
|
37
|
+
export function createPreviewHandlerGet(options) {
|
|
38
|
+
const { secret, resolveFullPath = resolveFullPathDefault, playgroundPath } = options ?? {};
|
|
39
|
+
return async ({ url, cookies, request }) => {
|
|
40
|
+
const searchParams = url.searchParams;
|
|
41
|
+
// Config check endpoint
|
|
42
|
+
const isConfigCheck = searchParams.get('is_config_check') === 'true';
|
|
43
|
+
if (isConfigCheck) {
|
|
44
|
+
return new Response(JSON.stringify({
|
|
45
|
+
hasPlayground: Boolean(playgroundPath),
|
|
46
|
+
isUsingCustomFullPathResolver: resolveFullPath !== resolveFullPathDefault,
|
|
47
|
+
}), {
|
|
48
|
+
headers: {
|
|
49
|
+
'Content-Type': 'application/json',
|
|
50
|
+
'Access-Control-Allow-Origin': '*',
|
|
51
|
+
'Access-Control-Allow-Headers': '*',
|
|
52
|
+
'Access-Control-Allow-Methods': 'GET, HEAD',
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
// Handle no-cors preflight from Canvas editor
|
|
57
|
+
if (request.headers.get('sec-fetch-mode') === 'no-cors') {
|
|
58
|
+
if (searchParams.has('disable')) {
|
|
59
|
+
clearPreviewData(cookies);
|
|
60
|
+
}
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 204,
|
|
63
|
+
headers: {
|
|
64
|
+
'Access-Control-Allow-Origin': '*',
|
|
65
|
+
'Access-Control-Allow-Headers': '*',
|
|
66
|
+
'Access-Control-Allow-Methods': 'GET, HEAD',
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const isPlayground = searchParams.get(IN_CONTEXT_EDITOR_PLAYGROUND_QUERY_STRING_PARAM) === 'true';
|
|
71
|
+
let pathToRedirectTo;
|
|
72
|
+
if (isPlayground && playgroundPath) {
|
|
73
|
+
pathToRedirectTo = playgroundPath;
|
|
74
|
+
}
|
|
75
|
+
const id = searchParams.get(compositionQueryParams.id) ?? undefined;
|
|
76
|
+
const slug = searchParams.get(compositionQueryParams.slug) ?? undefined;
|
|
77
|
+
const path = searchParams.get(compositionQueryParams.path) ?? undefined;
|
|
78
|
+
const locale = searchParams.get(compositionQueryParams.locale) ?? undefined;
|
|
79
|
+
if (typeof pathToRedirectTo === 'undefined') {
|
|
80
|
+
pathToRedirectTo = resolveFullPath({ id, slug, path, locale });
|
|
81
|
+
}
|
|
82
|
+
validateLocalRedirectUrl(pathToRedirectTo);
|
|
83
|
+
if (!pathToRedirectTo) {
|
|
84
|
+
error(400, 'Could not resolve the full path of the preview page');
|
|
85
|
+
}
|
|
86
|
+
// Handle disable preview
|
|
87
|
+
if (searchParams.has('disable')) {
|
|
88
|
+
clearPreviewData(cookies);
|
|
89
|
+
redirect(307, pathToRedirectTo);
|
|
90
|
+
}
|
|
91
|
+
// Validate secret if configured
|
|
92
|
+
const previewSecret = typeof secret === 'function' ? secret() : secret;
|
|
93
|
+
const isUsingPreviewSecret = Boolean(previewSecret);
|
|
94
|
+
if (isUsingPreviewSecret && searchParams.get(SECRET_QUERY_STRING_PARAM) !== previewSecret) {
|
|
95
|
+
error(401, 'Invalid token');
|
|
96
|
+
}
|
|
97
|
+
// Check if this is valid contextual editing
|
|
98
|
+
const isUniformContextualEditing = searchParams.get(IN_CONTEXT_EDITOR_QUERY_STRING_PARAM) === 'true' &&
|
|
99
|
+
isAllowedReferrer(request.headers.get('referer') ?? undefined);
|
|
100
|
+
// Set preview cookie
|
|
101
|
+
const previewData = {
|
|
102
|
+
isUniformContextualEditing,
|
|
103
|
+
compositionId: id,
|
|
104
|
+
compositionSlug: slug,
|
|
105
|
+
compositionPath: path,
|
|
106
|
+
locale,
|
|
107
|
+
isPlayground,
|
|
108
|
+
patternType: !isPlayground
|
|
109
|
+
? undefined
|
|
110
|
+
: searchParams.get('patternType'),
|
|
111
|
+
};
|
|
112
|
+
setPreviewData(cookies, previewData, {
|
|
113
|
+
// Short max age for contextual editing to avoid stale preview state
|
|
114
|
+
maxAge: isUniformContextualEditing ? 10 : undefined,
|
|
115
|
+
});
|
|
116
|
+
// Build redirect URL with query params
|
|
117
|
+
const redirectionUrl = new URL(pathToRedirectTo, BASE_URL_EXAMPLE);
|
|
118
|
+
const compositionQueryParamNames = Object.values(compositionQueryParams);
|
|
119
|
+
// Copy query params except secret and composition params
|
|
120
|
+
searchParams.forEach((value, name) => {
|
|
121
|
+
if (name === SECRET_QUERY_STRING_PARAM) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (compositionQueryParamNames.includes(name)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
redirectionUrl.searchParams.append(name, value);
|
|
128
|
+
});
|
|
129
|
+
// Remove contextual editing params if not in contextual editing mode
|
|
130
|
+
if (!isUniformContextualEditing) {
|
|
131
|
+
contextualEditingQueryParams.forEach((param) => {
|
|
132
|
+
redirectionUrl.searchParams.delete(param);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const fullPathToRedirectTo = redirectionUrl.href.replace(BASE_URL_EXAMPLE, '');
|
|
136
|
+
redirect(307, fullPathToRedirectTo);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type RequestEvent, type RequestHandler } from '@sveltejs/kit';
|
|
2
|
+
import { type RootComponentInstance } from '@uniformdev/canvas';
|
|
3
|
+
/**
|
|
4
|
+
* Options for creating the preview POST handler.
|
|
5
|
+
*/
|
|
6
|
+
export type CreatePreviewHandlerPostOptions = {
|
|
7
|
+
/** Function that returns the preview secret for hash validation. */
|
|
8
|
+
secret?: () => string;
|
|
9
|
+
/** Function to enhance the composition after receiving it. */
|
|
10
|
+
enhance?: (composition: RootComponentInstance, context: {
|
|
11
|
+
event: RequestEvent;
|
|
12
|
+
}) => Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Creates a SvelteKit POST request handler for preview mode.
|
|
16
|
+
* This handler is used by the Canvas editor to send enhanced compositions.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* // In +server.ts
|
|
20
|
+
* import { createPreviewHandlerPost } from '@uniformdev/canvas-sveltekit/preview';
|
|
21
|
+
*
|
|
22
|
+
* export const POST = createPreviewHandlerPost({
|
|
23
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
24
|
+
* enhance: async (composition, { event }) => {
|
|
25
|
+
* // Enhance composition with additional data
|
|
26
|
+
* },
|
|
27
|
+
* });
|
|
28
|
+
*/
|
|
29
|
+
export declare function createPreviewHandlerPost(options?: CreatePreviewHandlerPostOptions): RequestHandler;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { error, json } from '@sveltejs/kit';
|
|
2
|
+
import { generateHash } from '@uniformdev/canvas';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a SvelteKit POST request handler for preview mode.
|
|
5
|
+
* This handler is used by the Canvas editor to send enhanced compositions.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* // In +server.ts
|
|
9
|
+
* import { createPreviewHandlerPost } from '@uniformdev/canvas-sveltekit/preview';
|
|
10
|
+
*
|
|
11
|
+
* export const POST = createPreviewHandlerPost({
|
|
12
|
+
* secret: () => process.env.UNIFORM_PREVIEW_SECRET,
|
|
13
|
+
* enhance: async (composition, { event }) => {
|
|
14
|
+
* // Enhance composition with additional data
|
|
15
|
+
* },
|
|
16
|
+
* });
|
|
17
|
+
*/
|
|
18
|
+
export function createPreviewHandlerPost(options) {
|
|
19
|
+
const { secret, enhance } = options ?? {};
|
|
20
|
+
return async (event) => {
|
|
21
|
+
const body = (await event.request.json());
|
|
22
|
+
const { composition, hash } = body;
|
|
23
|
+
if (!composition) {
|
|
24
|
+
error(422, 'Missing "composition" parameter');
|
|
25
|
+
}
|
|
26
|
+
const previewSecret = typeof secret === 'function' ? secret() : secret;
|
|
27
|
+
const hasProvidedHash = Boolean(hash);
|
|
28
|
+
const hasConfiguredHash = Boolean(previewSecret);
|
|
29
|
+
if (hasProvidedHash && hasConfiguredHash) {
|
|
30
|
+
const calculatedHash = generateHash({
|
|
31
|
+
composition,
|
|
32
|
+
secret: previewSecret,
|
|
33
|
+
});
|
|
34
|
+
if (calculatedHash !== hash) {
|
|
35
|
+
error(401, 'Not authorized');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else if (hasConfiguredHash) {
|
|
39
|
+
error(401, 'Not authorized');
|
|
40
|
+
}
|
|
41
|
+
await enhance?.(composition, { event });
|
|
42
|
+
return json({ composition });
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { RouteHandlerOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a route fetcher function that fetches compositions from the Uniform Route API.
|
|
4
|
+
* This is an internal utility used by createUniformLoad and other route handlers.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createRouteFetcher<TContext, TResult, TSuccessResult>(options: RouteHandlerOptions<TContext, TResult, TSuccessResult> & {
|
|
7
|
+
parseContext: (context: TContext) => {
|
|
8
|
+
/** The composition ID when in contextual editing mode */
|
|
9
|
+
contextualEditingCompositionId: string | undefined;
|
|
10
|
+
/** The path being edited in contextual editing mode */
|
|
11
|
+
contextualEditingPath?: string;
|
|
12
|
+
/** The URL path to fetch */
|
|
13
|
+
resolvedUrl: string;
|
|
14
|
+
/** Default state (draft/published) for fetching */
|
|
15
|
+
defaultFetchState?: number | undefined;
|
|
16
|
+
};
|
|
17
|
+
defaultHandleNotFound: NonNullable<typeof options.handleNotFound>;
|
|
18
|
+
defaultHandleComposition: NonNullable<typeof options.handleComposition>;
|
|
19
|
+
defaultHandleRedirect: NonNullable<typeof options.handleRedirect>;
|
|
20
|
+
}): (context: TContext) => Promise<TResult | TSuccessResult>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ApiClientError, CANVAS_PUBLISHED_STATE, EMPTY_COMPOSITION, getDataSourceVariantFromRouteGetParams, RouteClient, } from '@uniformdev/canvas';
|
|
2
|
+
import { red } from 'colorette';
|
|
3
|
+
import { logRouteResponse } from '../logging/logRouteResponse.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates a route fetcher function that fetches compositions from the Uniform Route API.
|
|
6
|
+
* This is an internal utility used by createUniformLoad and other route handlers.
|
|
7
|
+
*/
|
|
8
|
+
export function createRouteFetcher(options) {
|
|
9
|
+
const { handleNotFound, handleComposition, handleRedirect, defaultHandleComposition, defaultHandleNotFound, defaultHandleRedirect, modifyPath, projectMapId = process.env.UNIFORM_PROJECT_MAP_ID, client, prefix, requestOptions, silent, parseContext, } = options;
|
|
10
|
+
const routeClient = client ||
|
|
11
|
+
new RouteClient({
|
|
12
|
+
apiKey: process.env.UNIFORM_API_KEY,
|
|
13
|
+
projectId: process.env.UNIFORM_PROJECT_ID,
|
|
14
|
+
edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL,
|
|
15
|
+
});
|
|
16
|
+
const handleModifyPath = modifyPath ?? ((path) => decodeURI(path));
|
|
17
|
+
return async function fetcher(context) {
|
|
18
|
+
const { contextualEditingCompositionId, contextualEditingPath, resolvedUrl, defaultFetchState: defaultPreviewState, } = parseContext(context);
|
|
19
|
+
let nodePath = prefix ? resolvedUrl.replace(new RegExp(`^${prefix}`), '') : resolvedUrl;
|
|
20
|
+
nodePath = handleModifyPath(nodePath, context);
|
|
21
|
+
const invokeRedirectResult = (redirect, duration) => (handleRedirect ?? defaultHandleRedirect)(nodePath, redirect, context, (response) => defaultHandleRedirect(nodePath, response, context, () => {
|
|
22
|
+
throw new Error('Default handler called recursively');
|
|
23
|
+
}, duration), duration);
|
|
24
|
+
const invokeNotFoundResult = (response, duration) => (handleNotFound ?? defaultHandleNotFound)(response, context, (response) => defaultHandleNotFound(response, context, () => {
|
|
25
|
+
throw new Error('Default handler called recursively');
|
|
26
|
+
}, duration), duration);
|
|
27
|
+
const invokeCompositionResult = (response, duration) => (handleComposition ?? defaultHandleComposition)(response, context, (response) => defaultHandleComposition(response, context, () => {
|
|
28
|
+
throw new Error('Default handler called recursively');
|
|
29
|
+
}, duration), duration);
|
|
30
|
+
// Skip fetching in contextual editing mode - composition comes from Canvas Editor
|
|
31
|
+
// Only do this if the requested path matches the path being edited
|
|
32
|
+
const shouldUseContextualEditing = contextualEditingCompositionId &&
|
|
33
|
+
(contextualEditingPath === undefined || contextualEditingPath === nodePath);
|
|
34
|
+
if (shouldUseContextualEditing) {
|
|
35
|
+
const previewEmptyComposition = await invokeCompositionResult({
|
|
36
|
+
type: 'composition',
|
|
37
|
+
matchedRoute: 'contextual-editing',
|
|
38
|
+
dynamicInputs: {},
|
|
39
|
+
compositionApiResponse: {
|
|
40
|
+
composition: {
|
|
41
|
+
...EMPTY_COMPOSITION,
|
|
42
|
+
_id: contextualEditingCompositionId ?? EMPTY_COMPOSITION._id,
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
}, 0);
|
|
46
|
+
return previewEmptyComposition;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
if (!silent) {
|
|
50
|
+
// eslint-disable-next-line no-console
|
|
51
|
+
console.log('Fetch route', nodePath);
|
|
52
|
+
}
|
|
53
|
+
const resolvedOptions = typeof requestOptions === 'function' ? requestOptions(context) : requestOptions;
|
|
54
|
+
const time = Date.now();
|
|
55
|
+
const response = await routeClient.getRoute({
|
|
56
|
+
...resolvedOptions,
|
|
57
|
+
state: resolvedOptions?.state ?? defaultPreviewState ?? CANVAS_PUBLISHED_STATE,
|
|
58
|
+
dataSourceVariant: getDataSourceVariantFromRouteGetParams(resolvedOptions ?? {}, defaultPreviewState),
|
|
59
|
+
projectMapId: projectMapId,
|
|
60
|
+
path: nodePath,
|
|
61
|
+
});
|
|
62
|
+
const duration = Date.now() - time;
|
|
63
|
+
if (!silent) {
|
|
64
|
+
logRouteResponse(response, duration);
|
|
65
|
+
}
|
|
66
|
+
if (response.type === 'redirect') {
|
|
67
|
+
return invokeRedirectResult(response, duration);
|
|
68
|
+
}
|
|
69
|
+
if (response.type === 'notFound') {
|
|
70
|
+
return invokeNotFoundResult(response, duration);
|
|
71
|
+
}
|
|
72
|
+
const handleResult = await invokeCompositionResult(response, duration);
|
|
73
|
+
if (!handleResult) {
|
|
74
|
+
return invokeNotFoundResult({ type: 'notFound' }, duration);
|
|
75
|
+
}
|
|
76
|
+
return handleResult;
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
// eslint-disable-next-line no-console
|
|
80
|
+
console.error(red('Failed to fetch route'), e);
|
|
81
|
+
if (e instanceof ApiClientError) {
|
|
82
|
+
if (e.statusCode === 404) {
|
|
83
|
+
return invokeNotFoundResult({ type: 'notFound' }, 0);
|
|
84
|
+
}
|
|
85
|
+
throw new Error(`Failed to fetch route. See preceding server logs for details.`);
|
|
86
|
+
}
|
|
87
|
+
throw e;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { CreateUniformEntriesOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Entry type for SvelteKit prerendering.
|
|
4
|
+
*/
|
|
5
|
+
export type UniformEntry = {
|
|
6
|
+
path: string;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Creates a SvelteKit entries function for prerendering routes from the project map.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* // In +page.server.ts with [...path] route
|
|
13
|
+
* import { createUniformEntries } from '@uniformdev/canvas-sveltekit/route';
|
|
14
|
+
*
|
|
15
|
+
* export const prerender = true;
|
|
16
|
+
* export const entries = createUniformEntries();
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* // With custom options
|
|
20
|
+
* export const entries = createUniformEntries({
|
|
21
|
+
* rootPath: '/blog',
|
|
22
|
+
* prefix: '/blog',
|
|
23
|
+
* preview: false,
|
|
24
|
+
* });
|
|
25
|
+
*/
|
|
26
|
+
export declare function createUniformEntries(options?: CreateUniformEntriesOptions): () => Promise<UniformEntry[]>;
|