@tschk/moonshine-astro 0.4.49 → 0.4.80
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/README.md +63 -18
- package/package.json +17 -5
- package/src/actions.ts +556 -0
- package/src/assets.ts +710 -0
- package/src/config.ts +269 -0
- package/src/container.ts +560 -0
- package/src/content.ts +1523 -0
- package/src/context.ts +756 -0
- package/src/env.ts +361 -0
- package/src/i18n.ts +420 -0
- package/src/index.ts +264 -0
- package/src/loaders.ts +888 -0
- package/src/middleware.ts +206 -0
- package/src/routing.ts +239 -0
- package/src/ssr.ts +208 -2
- package/src/transitions.ts +496 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/** Independent host-free Astro middleware primitives (`astro:middleware`). */
|
|
2
|
+
import {
|
|
3
|
+
createAstroGlobal,
|
|
4
|
+
withAstroContext,
|
|
5
|
+
type AstroContextInit,
|
|
6
|
+
type AstroGlobal,
|
|
7
|
+
} from "./context";
|
|
8
|
+
|
|
9
|
+
export type APIContext<
|
|
10
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
11
|
+
Params extends Record<string, string | undefined> = Record<
|
|
12
|
+
string,
|
|
13
|
+
string | undefined
|
|
14
|
+
>,
|
|
15
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
16
|
+
> = AstroGlobal<Props, Params, Locals>;
|
|
17
|
+
|
|
18
|
+
export type MiddlewareNext = (
|
|
19
|
+
rewritePayload?: string | URL | Request,
|
|
20
|
+
) => Promise<Response>;
|
|
21
|
+
|
|
22
|
+
export type MiddlewareHandler<
|
|
23
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
24
|
+
Params extends Record<string, string | undefined> = Record<
|
|
25
|
+
string,
|
|
26
|
+
string | undefined
|
|
27
|
+
>,
|
|
28
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
29
|
+
> = (
|
|
30
|
+
context: APIContext<Props, Params, Locals>,
|
|
31
|
+
next: MiddlewareNext,
|
|
32
|
+
) => Promise<Response> | Response;
|
|
33
|
+
|
|
34
|
+
export function defineMiddleware<
|
|
35
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
36
|
+
Params extends Record<string, string | undefined> = Record<
|
|
37
|
+
string,
|
|
38
|
+
string | undefined
|
|
39
|
+
>,
|
|
40
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
41
|
+
>(
|
|
42
|
+
fn: MiddlewareHandler<Props, Params, Locals>,
|
|
43
|
+
): MiddlewareHandler<Props, Params, Locals> {
|
|
44
|
+
return fn;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createContext<
|
|
48
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
49
|
+
Params extends Record<string, string | undefined> = Record<
|
|
50
|
+
string,
|
|
51
|
+
string | undefined
|
|
52
|
+
>,
|
|
53
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
54
|
+
>(
|
|
55
|
+
init: AstroContextInit<Props, Params, Locals> = {},
|
|
56
|
+
): APIContext<Props, Params, Locals> {
|
|
57
|
+
return createAstroGlobal(init);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function applyRewritePayload(
|
|
61
|
+
context: APIContext<any, any, any>,
|
|
62
|
+
payload: string | URL | Request,
|
|
63
|
+
): void {
|
|
64
|
+
if (typeof payload === "string") {
|
|
65
|
+
const nextUrl = new URL(payload, context.url);
|
|
66
|
+
context.url = nextUrl;
|
|
67
|
+
context.request = new Request(nextUrl.href, context.request);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (payload instanceof URL) {
|
|
71
|
+
context.url = new URL(payload.href);
|
|
72
|
+
context.request = new Request(payload.href, context.request);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
context.url = new URL(payload.url);
|
|
76
|
+
context.request = payload;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function attachCookiesToResponse(
|
|
80
|
+
context: APIContext<any, any, any>,
|
|
81
|
+
response: Response,
|
|
82
|
+
): Response {
|
|
83
|
+
const cookieHeaders = Array.from(context.cookies.headers());
|
|
84
|
+
if (cookieHeaders.length === 0) {
|
|
85
|
+
return response;
|
|
86
|
+
}
|
|
87
|
+
const existing = response.headers.getSetCookie?.() ?? [];
|
|
88
|
+
const missing = cookieHeaders.filter((h) => !existing.includes(h));
|
|
89
|
+
if (missing.length === 0) {
|
|
90
|
+
return response;
|
|
91
|
+
}
|
|
92
|
+
const headers = new Headers(response.headers);
|
|
93
|
+
for (const cookieHeader of missing) {
|
|
94
|
+
headers.append("Set-Cookie", cookieHeader);
|
|
95
|
+
}
|
|
96
|
+
return new Response(response.body, {
|
|
97
|
+
status: response.status,
|
|
98
|
+
statusText: response.statusText,
|
|
99
|
+
headers,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function sequence(
|
|
104
|
+
...handlers: Array<MiddlewareHandler<any, any, any> | undefined | null>
|
|
105
|
+
): MiddlewareHandler {
|
|
106
|
+
const filtered = handlers.filter(
|
|
107
|
+
(h): h is MiddlewareHandler<any, any, any> => typeof h === "function",
|
|
108
|
+
);
|
|
109
|
+
if (filtered.length === 0) {
|
|
110
|
+
return defineMiddleware((context, next) =>
|
|
111
|
+
withAstroContext(context, async () => {
|
|
112
|
+
const res = await next();
|
|
113
|
+
return attachCookiesToResponse(context, res);
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return defineMiddleware((context, finalNext) =>
|
|
119
|
+
withAstroContext(context, async () => {
|
|
120
|
+
const dispatch = async (
|
|
121
|
+
index: number,
|
|
122
|
+
rewritePayload?: string | URL | Request,
|
|
123
|
+
): Promise<Response> => {
|
|
124
|
+
if (rewritePayload !== undefined) {
|
|
125
|
+
applyRewritePayload(context, rewritePayload);
|
|
126
|
+
}
|
|
127
|
+
if (index >= filtered.length) {
|
|
128
|
+
const terminalResponse = await finalNext(rewritePayload);
|
|
129
|
+
return attachCookiesToResponse(context, terminalResponse);
|
|
130
|
+
}
|
|
131
|
+
const handler = filtered[index]!;
|
|
132
|
+
const response = await handler(context, (nextRewrite) =>
|
|
133
|
+
dispatch(index + 1, nextRewrite),
|
|
134
|
+
);
|
|
135
|
+
return attachCookiesToResponse(context, response);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
return dispatch(0);
|
|
139
|
+
}),
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function assertSerializableValue(
|
|
144
|
+
value: unknown,
|
|
145
|
+
path: string,
|
|
146
|
+
seen: Set<unknown>,
|
|
147
|
+
): void {
|
|
148
|
+
if (
|
|
149
|
+
value === null ||
|
|
150
|
+
value === undefined ||
|
|
151
|
+
typeof value === "string" ||
|
|
152
|
+
typeof value === "number" ||
|
|
153
|
+
typeof value === "boolean"
|
|
154
|
+
) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (
|
|
158
|
+
typeof value === "function" ||
|
|
159
|
+
typeof value === "symbol" ||
|
|
160
|
+
typeof value === "bigint"
|
|
161
|
+
) {
|
|
162
|
+
throw new TypeError(
|
|
163
|
+
`locals.${path} cannot be serialized: unsupported type "${typeof value}".`,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
if (typeof value === "object") {
|
|
167
|
+
if (seen.has(value)) {
|
|
168
|
+
throw new TypeError(
|
|
169
|
+
`locals.${path} cannot be serialized: circular reference detected.`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (value instanceof Date || value instanceof RegExp) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
seen.add(value);
|
|
176
|
+
try {
|
|
177
|
+
if (Array.isArray(value)) {
|
|
178
|
+
for (let i = 0; i < value.length; i++) {
|
|
179
|
+
assertSerializableValue(value[i], `${path}[${i}]`, seen);
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const proto = Object.getPrototypeOf(value);
|
|
184
|
+
if (proto !== null && proto !== Object.prototype) {
|
|
185
|
+
throw new TypeError(
|
|
186
|
+
`locals.${path} cannot be serialized: only plain objects and arrays are supported.`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
for (const [key, propValue] of Object.entries(
|
|
190
|
+
value as Record<string, unknown>,
|
|
191
|
+
)) {
|
|
192
|
+
assertSerializableValue(propValue, path ? `${path}.${key}` : key, seen);
|
|
193
|
+
}
|
|
194
|
+
} finally {
|
|
195
|
+
seen.delete(value);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function trySerializeLocals(value: unknown): string {
|
|
201
|
+
if (typeof value !== "object" || value === null) {
|
|
202
|
+
throw new TypeError("locals must be a non-null object.");
|
|
203
|
+
}
|
|
204
|
+
assertSerializableValue(value, "", new Set());
|
|
205
|
+
return JSON.stringify(value);
|
|
206
|
+
}
|
package/src/routing.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/** Independent host-free Astro static path pagination, route inference, and endpoint helpers. */
|
|
2
|
+
import type { APIContext } from "./middleware";
|
|
3
|
+
|
|
4
|
+
export type Params = Record<string, string | number | undefined>;
|
|
5
|
+
export type Props = Record<string, any>;
|
|
6
|
+
|
|
7
|
+
export interface Page<T = any> {
|
|
8
|
+
/** Array of items for the current page. */
|
|
9
|
+
data: T[];
|
|
10
|
+
/** 0-based index of the first item on the page. */
|
|
11
|
+
start: number;
|
|
12
|
+
/** 0-based index of the last item on the page. */
|
|
13
|
+
end: number;
|
|
14
|
+
/** Number of items per page. */
|
|
15
|
+
size: number;
|
|
16
|
+
/** Total number of items across all pages. */
|
|
17
|
+
total: number;
|
|
18
|
+
/** 1-based current page number. */
|
|
19
|
+
currentPage: number;
|
|
20
|
+
/** Total number of pages. */
|
|
21
|
+
lastPage: number;
|
|
22
|
+
/** Navigation URLs for the current page. */
|
|
23
|
+
url: {
|
|
24
|
+
current: string;
|
|
25
|
+
prev: string | undefined;
|
|
26
|
+
next: string | undefined;
|
|
27
|
+
first: string | undefined;
|
|
28
|
+
last: string | undefined;
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PaginateOptions<
|
|
33
|
+
PaginateProps extends Props = Props,
|
|
34
|
+
PaginateParams extends Params = Params,
|
|
35
|
+
> {
|
|
36
|
+
pageSize?: number;
|
|
37
|
+
params?: PaginateParams;
|
|
38
|
+
props?: PaginateProps;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface GetStaticPathsItem<
|
|
42
|
+
ItemProps extends Props = Props,
|
|
43
|
+
ItemParams extends Params = Params,
|
|
44
|
+
> {
|
|
45
|
+
params: ItemParams;
|
|
46
|
+
props: ItemProps;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type GetStaticPathsResult<
|
|
50
|
+
ItemProps extends Props = Props,
|
|
51
|
+
ItemParams extends Params = Params,
|
|
52
|
+
> = GetStaticPathsItem<ItemProps, ItemParams>[];
|
|
53
|
+
|
|
54
|
+
export type PaginateFunction = <
|
|
55
|
+
T,
|
|
56
|
+
PaginateProps extends Props = Props,
|
|
57
|
+
PaginateParams extends Params = Params,
|
|
58
|
+
>(
|
|
59
|
+
data: readonly T[],
|
|
60
|
+
args?: PaginateOptions<PaginateProps, PaginateParams>,
|
|
61
|
+
) => GetStaticPathsResult<
|
|
62
|
+
PaginateProps & { page: Page<T> },
|
|
63
|
+
PaginateParams & { page?: string }
|
|
64
|
+
>;
|
|
65
|
+
|
|
66
|
+
export interface GetStaticPathsOptions {
|
|
67
|
+
paginate: PaginateFunction;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type GetStaticPaths = (
|
|
71
|
+
options: GetStaticPathsOptions,
|
|
72
|
+
) => Promise<GetStaticPathsResult<any, any>> | GetStaticPathsResult<any, any>;
|
|
73
|
+
|
|
74
|
+
export type InferGetStaticParamsType<T> = T extends (opts: any) => infer R
|
|
75
|
+
? Awaited<R> extends Array<{ params: infer P }>
|
|
76
|
+
? P
|
|
77
|
+
: never
|
|
78
|
+
: never;
|
|
79
|
+
|
|
80
|
+
export type InferGetStaticPropsType<T> = T extends (opts: any) => infer R
|
|
81
|
+
? Awaited<R> extends Array<{ props: infer P }>
|
|
82
|
+
? P
|
|
83
|
+
: never
|
|
84
|
+
: never;
|
|
85
|
+
|
|
86
|
+
export type APIRoute<
|
|
87
|
+
RouteProps extends Record<string, any> = Record<string, any>,
|
|
88
|
+
RouteParams extends Record<string, string | undefined> = Record<
|
|
89
|
+
string,
|
|
90
|
+
string | undefined
|
|
91
|
+
>,
|
|
92
|
+
> = (
|
|
93
|
+
context: APIContext<RouteProps, RouteParams>,
|
|
94
|
+
) => Response | Promise<Response>;
|
|
95
|
+
|
|
96
|
+
export interface CreatePaginateOptions {
|
|
97
|
+
/** Base path prefix (defaults to `""`). */
|
|
98
|
+
base?: string;
|
|
99
|
+
/** Trailing slash policy (defaults to `"ignore"`). */
|
|
100
|
+
trailingSlash?: "always" | "never" | "ignore";
|
|
101
|
+
/** Dynamic parameter name used for pagination (defaults to `"page"`). */
|
|
102
|
+
param?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function formatPagePath(
|
|
106
|
+
routePattern: string,
|
|
107
|
+
pageNum: number,
|
|
108
|
+
isRestParam: boolean,
|
|
109
|
+
paramName: string,
|
|
110
|
+
extraParams: Params | undefined,
|
|
111
|
+
base: string,
|
|
112
|
+
trailingSlash: "always" | "never" | "ignore",
|
|
113
|
+
): string {
|
|
114
|
+
let resolved = routePattern;
|
|
115
|
+
if (extraParams) {
|
|
116
|
+
for (const [key, val] of Object.entries(extraParams)) {
|
|
117
|
+
const replacement = val === undefined ? "" : String(val);
|
|
118
|
+
resolved = resolved
|
|
119
|
+
.replace(`[...${key}]`, replacement)
|
|
120
|
+
.replace(`[${key}]`, replacement);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const pageSegment = pageNum === 1 && isRestParam ? "" : String(pageNum);
|
|
124
|
+
resolved = resolved
|
|
125
|
+
.replace(`[...${paramName}]`, pageSegment)
|
|
126
|
+
.replace(`[${paramName}]`, pageSegment);
|
|
127
|
+
|
|
128
|
+
const normalizedBase =
|
|
129
|
+
base && base !== "/" ? `/${base.replace(/^\/+|\/+$/g, "")}` : "";
|
|
130
|
+
let full = `${normalizedBase}/${resolved}`.replace(/\/+/g, "/");
|
|
131
|
+
if (full.length > 1 && full.endsWith("/")) {
|
|
132
|
+
full = full.slice(0, -1);
|
|
133
|
+
}
|
|
134
|
+
if (!full.startsWith("/")) {
|
|
135
|
+
full = `/${full}`;
|
|
136
|
+
}
|
|
137
|
+
if (trailingSlash === "always" && !full.endsWith("/")) {
|
|
138
|
+
full = `${full}/`;
|
|
139
|
+
} else if (
|
|
140
|
+
trailingSlash === "never" &&
|
|
141
|
+
full.length > 1 &&
|
|
142
|
+
full.endsWith("/")
|
|
143
|
+
) {
|
|
144
|
+
full = full.slice(0, -1);
|
|
145
|
+
}
|
|
146
|
+
return full;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function createPaginate(
|
|
150
|
+
routePattern = "[...page]",
|
|
151
|
+
options: CreatePaginateOptions = {},
|
|
152
|
+
): PaginateFunction {
|
|
153
|
+
const paramName = options.param ?? "page";
|
|
154
|
+
const base = options.base ?? "";
|
|
155
|
+
const trailingSlash = options.trailingSlash ?? "ignore";
|
|
156
|
+
const isRestParam =
|
|
157
|
+
routePattern.includes(`[...${paramName}]`) ||
|
|
158
|
+
!routePattern.includes(`[${paramName}]`);
|
|
159
|
+
|
|
160
|
+
return function paginate<
|
|
161
|
+
T,
|
|
162
|
+
PaginateProps extends Props = Props,
|
|
163
|
+
PaginateParams extends Params = Params,
|
|
164
|
+
>(
|
|
165
|
+
data: readonly T[],
|
|
166
|
+
args: PaginateOptions<PaginateProps, PaginateParams> = {},
|
|
167
|
+
) {
|
|
168
|
+
const pageSize = args.pageSize ?? 10;
|
|
169
|
+
if (!Number.isFinite(pageSize) || pageSize <= 0) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`Invalid pageSize: ${String(pageSize)}. Expected a positive number.`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
const size = Math.trunc(pageSize);
|
|
175
|
+
const total = data.length;
|
|
176
|
+
const lastPage = Math.max(1, Math.ceil(total / size));
|
|
177
|
+
const extraParams = args.params;
|
|
178
|
+
const extraProps = args.props;
|
|
179
|
+
|
|
180
|
+
const urlFor = (pageNum: number): string =>
|
|
181
|
+
formatPagePath(
|
|
182
|
+
routePattern,
|
|
183
|
+
pageNum,
|
|
184
|
+
isRestParam,
|
|
185
|
+
paramName,
|
|
186
|
+
extraParams,
|
|
187
|
+
base,
|
|
188
|
+
trailingSlash,
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const results: GetStaticPathsResult<
|
|
192
|
+
PaginateProps & { page: Page<T> },
|
|
193
|
+
PaginateParams & { page?: string }
|
|
194
|
+
> = [];
|
|
195
|
+
|
|
196
|
+
for (let pageNum = 1; pageNum <= lastPage; pageNum++) {
|
|
197
|
+
const start = (pageNum - 1) * size;
|
|
198
|
+
const end = total === 0 ? -1 : Math.min(start + size - 1, total - 1);
|
|
199
|
+
const slice = total === 0 ? [] : data.slice(start, end + 1);
|
|
200
|
+
|
|
201
|
+
const pageParamValue =
|
|
202
|
+
pageNum === 1 && isRestParam ? undefined : String(pageNum);
|
|
203
|
+
|
|
204
|
+
const params = {
|
|
205
|
+
...extraParams,
|
|
206
|
+
[paramName]: pageParamValue,
|
|
207
|
+
} as PaginateParams & { page?: string };
|
|
208
|
+
|
|
209
|
+
const page: Page<T> = {
|
|
210
|
+
data: slice,
|
|
211
|
+
start,
|
|
212
|
+
end,
|
|
213
|
+
size,
|
|
214
|
+
total,
|
|
215
|
+
currentPage: pageNum,
|
|
216
|
+
lastPage,
|
|
217
|
+
url: {
|
|
218
|
+
current: urlFor(pageNum),
|
|
219
|
+
prev: pageNum > 1 ? urlFor(pageNum - 1) : undefined,
|
|
220
|
+
next: pageNum < lastPage ? urlFor(pageNum + 1) : undefined,
|
|
221
|
+
first: pageNum > 1 ? urlFor(1) : undefined,
|
|
222
|
+
last: pageNum < lastPage ? urlFor(lastPage) : undefined,
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const props = {
|
|
227
|
+
...extraProps,
|
|
228
|
+
page,
|
|
229
|
+
} as PaginateProps & { page: Page<T> };
|
|
230
|
+
|
|
231
|
+
results.push({ params, props });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return results;
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Default Astro `paginate()` helper using `[...page]` rest-parameter semantics. */
|
|
239
|
+
export const paginate: PaginateFunction = createPaginate("[...page]");
|
package/src/ssr.ts
CHANGED
|
@@ -5,13 +5,15 @@ import {
|
|
|
5
5
|
hAttributes,
|
|
6
6
|
hAttributeEntries,
|
|
7
7
|
defer,
|
|
8
|
+
renderToString,
|
|
8
9
|
scopeSSRChild,
|
|
9
10
|
type HTML,
|
|
10
11
|
type SSRChild,
|
|
11
12
|
} from "@tschk/moonshine-dom/ssr";
|
|
13
|
+
import { peekAstroContext, type AstroServerIslandEntry } from "./context";
|
|
12
14
|
|
|
13
|
-
const booleanAttributes = new Set(
|
|
14
|
-
"allowfullscreen async autofocus autoplay checked controls default defer disabled disablepictureinpicture disableremoteplayback formnovalidate inert loop muted nomodule novalidate open playsinline readonly required reversed scoped seamless selected itemscope".split(
|
|
15
|
+
const booleanAttributes = /* @__PURE__ */ new Set(
|
|
16
|
+
/* @__PURE__ */ "allowfullscreen async autofocus autoplay checked controls default defer disabled disablepictureinpicture disableremoteplayback formnovalidate inert loop muted nomodule novalidate open playsinline readonly required reversed scoped seamless selected itemscope".split(
|
|
15
17
|
" ",
|
|
16
18
|
),
|
|
17
19
|
);
|
|
@@ -64,6 +66,118 @@ function style(value: object): string {
|
|
|
64
66
|
.join(";");
|
|
65
67
|
}
|
|
66
68
|
|
|
69
|
+
/** Compiler-facing `define:vars` CSS custom property serialization. */
|
|
70
|
+
export function defineStyleVars(
|
|
71
|
+
vars: Record<string, unknown> | null | undefined,
|
|
72
|
+
): string {
|
|
73
|
+
if (!vars || typeof vars !== "object") return "";
|
|
74
|
+
const parts: string[] = [];
|
|
75
|
+
for (const [key, item] of Object.entries(vars)) {
|
|
76
|
+
if (item === undefined || item === null || typeof item === "boolean") {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const text = String(item).trim();
|
|
80
|
+
if (!text) continue;
|
|
81
|
+
const propName = key.startsWith("--") ? key : `--${key}`;
|
|
82
|
+
parts.push(`${propName}:${text}`);
|
|
83
|
+
}
|
|
84
|
+
return parts.join(";");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Merge an element's `style`, `define:vars`, and `transition:name` into a single `style` value. */
|
|
88
|
+
export function mergeDefineVars(
|
|
89
|
+
existingStyle: unknown,
|
|
90
|
+
vars?: Record<string, unknown> | null,
|
|
91
|
+
transitionName?: unknown,
|
|
92
|
+
): string | undefined {
|
|
93
|
+
const segments: string[] = [];
|
|
94
|
+
if (typeof existingStyle === "string") {
|
|
95
|
+
const trimmed = existingStyle.trim().replace(/;+$/, "");
|
|
96
|
+
if (trimmed) segments.push(trimmed);
|
|
97
|
+
} else if (existingStyle !== null && typeof existingStyle === "object") {
|
|
98
|
+
const serialized = Array.isArray(existingStyle)
|
|
99
|
+
? `${style(existingStyle[0] ?? {})};${existingStyle[1] ?? ""}`.replace(
|
|
100
|
+
/^;+|;+$/g,
|
|
101
|
+
"",
|
|
102
|
+
)
|
|
103
|
+
: style(existingStyle);
|
|
104
|
+
if (serialized) segments.push(serialized);
|
|
105
|
+
}
|
|
106
|
+
const varsStr = defineStyleVars(vars);
|
|
107
|
+
if (varsStr) segments.push(varsStr);
|
|
108
|
+
if (
|
|
109
|
+
transitionName !== undefined &&
|
|
110
|
+
transitionName !== null &&
|
|
111
|
+
transitionName !== false
|
|
112
|
+
) {
|
|
113
|
+
const nameStr = String(transitionName).trim();
|
|
114
|
+
if (nameStr) {
|
|
115
|
+
segments.push(`view-transition-name:${nameStr}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return segments.length > 0 ? segments.join(";") : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Compiler-facing `transition:animate` attribute value normalization. */
|
|
122
|
+
export function transitionAnimateValue(value: unknown): string | undefined {
|
|
123
|
+
if (value === undefined || value === null || value === false) {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
if (value === true || value === "") {
|
|
127
|
+
return "initial";
|
|
128
|
+
}
|
|
129
|
+
if (typeof value === "string") {
|
|
130
|
+
return value.trim() || "initial";
|
|
131
|
+
}
|
|
132
|
+
if (typeof value === "object") {
|
|
133
|
+
const candidate = value as Record<string, unknown>;
|
|
134
|
+
if (typeof candidate.name === "string" && candidate.name.trim()) {
|
|
135
|
+
return candidate.name.trim();
|
|
136
|
+
}
|
|
137
|
+
const forwards = candidate.forwards as Record<string, unknown> | undefined;
|
|
138
|
+
if (forwards && typeof forwards === "object") {
|
|
139
|
+
const next = forwards.new;
|
|
140
|
+
if (Array.isArray(next)) {
|
|
141
|
+
if (
|
|
142
|
+
next.some((item) =>
|
|
143
|
+
(item as { name?: string })?.name?.includes("Slide"),
|
|
144
|
+
)
|
|
145
|
+
) {
|
|
146
|
+
return "slide";
|
|
147
|
+
}
|
|
148
|
+
} else if (next && typeof next === "object") {
|
|
149
|
+
const animName = (next as { name?: string }).name;
|
|
150
|
+
if (animName === "astroFadeIn") return "fade";
|
|
151
|
+
if (animName === "none") return "none";
|
|
152
|
+
if (animName) return animName;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return "custom";
|
|
156
|
+
}
|
|
157
|
+
return String(value);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Compiler-facing `transition:persist` attribute value normalization. */
|
|
161
|
+
export function transitionPersistValue(value: unknown): string | undefined {
|
|
162
|
+
if (value === undefined || value === null || value === false) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
if (value === true || value === "") {
|
|
166
|
+
return "";
|
|
167
|
+
}
|
|
168
|
+
return String(value);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Compiler-facing `transition:persist-props` boolean attribute normalization. */
|
|
172
|
+
export function transitionPersistPropsValue(
|
|
173
|
+
value: unknown,
|
|
174
|
+
): string | undefined {
|
|
175
|
+
if (value === undefined || value === null || value === false) {
|
|
176
|
+
return undefined;
|
|
177
|
+
}
|
|
178
|
+
return "";
|
|
179
|
+
}
|
|
180
|
+
|
|
67
181
|
function attribute(
|
|
68
182
|
tag: string,
|
|
69
183
|
name: string,
|
|
@@ -137,6 +251,56 @@ export function sourceComponent<P extends object>(
|
|
|
137
251
|
);
|
|
138
252
|
}
|
|
139
253
|
|
|
254
|
+
/** Compiler-facing Astro 5 `<Component server:defer>` Server Island invocation. */
|
|
255
|
+
export function sourceServerIsland<P extends object>(
|
|
256
|
+
component: (props: P, slots: SourceSlots) => SSRChild,
|
|
257
|
+
componentName: string,
|
|
258
|
+
props: P,
|
|
259
|
+
slots: Readonly<Record<string, () => SSRChild>> = {},
|
|
260
|
+
): SSRChild {
|
|
261
|
+
const captured = captureProps(props);
|
|
262
|
+
const componentSlots: Record<string, () => SSRChild> = {};
|
|
263
|
+
for (const [name, render] of Object.entries(slots)) {
|
|
264
|
+
if (name !== "fallback") {
|
|
265
|
+
componentSlots[name] = render;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const hasFallback = Object.hasOwn(slots, "fallback");
|
|
269
|
+
const ctx = peekAstroContext();
|
|
270
|
+
const deferred = Boolean(ctx?.deferServerIslands);
|
|
271
|
+
const id = `island-${(ctx?.serverIslands.length ?? 0) + 1}`;
|
|
272
|
+
const renderIsland = () =>
|
|
273
|
+
renderToString(() => sourceComponent(component, captured, componentSlots));
|
|
274
|
+
|
|
275
|
+
if (ctx) {
|
|
276
|
+
const entry: AstroServerIslandEntry = {
|
|
277
|
+
id,
|
|
278
|
+
componentName,
|
|
279
|
+
props: { ...(captured as Record<string, unknown>) },
|
|
280
|
+
hasFallback,
|
|
281
|
+
deferred,
|
|
282
|
+
render: renderIsland,
|
|
283
|
+
};
|
|
284
|
+
ctx.serverIslands.push(entry);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (deferred) {
|
|
288
|
+
const fallbackContent = hasFallback
|
|
289
|
+
? scopeSSRChild(() => sourceChild(slots.fallback!()))
|
|
290
|
+
: undefined;
|
|
291
|
+
return h(
|
|
292
|
+
"astro-server-island",
|
|
293
|
+
{
|
|
294
|
+
"data-island-id": id,
|
|
295
|
+
"data-component": componentName,
|
|
296
|
+
},
|
|
297
|
+
fallbackContent,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return sourceComponent(component, captured, componentSlots);
|
|
302
|
+
}
|
|
303
|
+
|
|
140
304
|
/** Presence selects a slot, including an explicitly empty supplied slot. */
|
|
141
305
|
export function sourceSlot(
|
|
142
306
|
slots: SourceSlots,
|
|
@@ -151,6 +315,35 @@ export function sourceHasSlot(slots: SourceSlots, name: string): boolean {
|
|
|
151
315
|
return Object.hasOwn(slots, name);
|
|
152
316
|
}
|
|
153
317
|
|
|
318
|
+
/** Render a named slot synchronously to an HTML string (`Astro.slots.render(name, args?)`). */
|
|
319
|
+
export function sourceRenderSlot(
|
|
320
|
+
slots: SourceSlots,
|
|
321
|
+
name = "default",
|
|
322
|
+
args?: readonly unknown[],
|
|
323
|
+
): string {
|
|
324
|
+
if (Object.hasOwn(slots, name)) {
|
|
325
|
+
const slotEntry = slots[name];
|
|
326
|
+
if (
|
|
327
|
+
typeof slotEntry === "function" &&
|
|
328
|
+
Array.isArray(args) &&
|
|
329
|
+
args.length > 0
|
|
330
|
+
) {
|
|
331
|
+
return renderToString(() =>
|
|
332
|
+
sourceChild((slotEntry as (...a: unknown[]) => unknown)(...args)),
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
return renderToString(() => sourceChild(slotEntry));
|
|
336
|
+
}
|
|
337
|
+
const ctx = peekAstroContext();
|
|
338
|
+
if (ctx?.slots.has(name)) {
|
|
339
|
+
const rendered = ctx.slots.render(name, args ? [...args] : []);
|
|
340
|
+
if (typeof rendered === "string") {
|
|
341
|
+
return rendered;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return "";
|
|
345
|
+
}
|
|
346
|
+
|
|
154
347
|
export function h<P extends object>(
|
|
155
348
|
component: (props: P & { children?: SSRChild }) => SSRChild,
|
|
156
349
|
props: P | null,
|
|
@@ -231,3 +424,16 @@ export function sourceElement(
|
|
|
231
424
|
): HTML {
|
|
232
425
|
return hAttributeEntries(tag, entries, ...children.map(sourceChild));
|
|
233
426
|
}
|
|
427
|
+
|
|
428
|
+
export {
|
|
429
|
+
useAstro,
|
|
430
|
+
peekAstroContext,
|
|
431
|
+
withAstroContext,
|
|
432
|
+
createAstroGlobal,
|
|
433
|
+
AstroCookies,
|
|
434
|
+
AstroCookie,
|
|
435
|
+
type AstroGlobal,
|
|
436
|
+
type AstroContextInit,
|
|
437
|
+
type AstroSlots,
|
|
438
|
+
type AstroServerIslandEntry,
|
|
439
|
+
} from "./context";
|