@tschk/moonshine-astro 0.4.4 → 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.
@@ -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]");