@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.
- package/README.md +176 -7
- package/package.json +18 -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 +439 -0
- package/src/transitions.ts +496 -0
package/src/context.ts
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
/** Independent host-free Astro request context, cookies, and global helpers. */
|
|
2
|
+
|
|
3
|
+
export interface AstroCookieGetOptions {
|
|
4
|
+
decode?: (value: string) => string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface AstroCookieSetOptions {
|
|
8
|
+
domain?: string;
|
|
9
|
+
expires?: Date;
|
|
10
|
+
httpOnly?: boolean;
|
|
11
|
+
maxAge?: number;
|
|
12
|
+
path?: string;
|
|
13
|
+
sameSite?: boolean | "lax" | "none" | "strict" | "Lax" | "None" | "Strict";
|
|
14
|
+
secure?: boolean;
|
|
15
|
+
partitioned?: boolean;
|
|
16
|
+
encode?: (value: string) => string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface AstroCookieDeleteOptions {
|
|
20
|
+
domain?: string;
|
|
21
|
+
path?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class AstroCookie {
|
|
25
|
+
readonly value: string;
|
|
26
|
+
|
|
27
|
+
constructor(value: string) {
|
|
28
|
+
this.value = value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
json<T = Record<string, unknown>>(): T {
|
|
32
|
+
if (this.value === undefined) {
|
|
33
|
+
throw new Error("Cannot convert undefined cookie to JSON.");
|
|
34
|
+
}
|
|
35
|
+
return JSON.parse(this.value) as T;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
number(): number {
|
|
39
|
+
return Number(this.value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
boolean(): boolean {
|
|
43
|
+
if (this.value === "false") return false;
|
|
44
|
+
if (this.value === "0") return false;
|
|
45
|
+
return Boolean(this.value);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface OutgoingCookie {
|
|
50
|
+
value: string;
|
|
51
|
+
options?: AstroCookieSetOptions;
|
|
52
|
+
isDeleted: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function defaultDecode(value: string): string {
|
|
56
|
+
try {
|
|
57
|
+
return decodeURIComponent(value);
|
|
58
|
+
} catch {
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseCookieHeader(header: string): Map<string, string> {
|
|
64
|
+
const map = new Map<string, string>();
|
|
65
|
+
if (!header) return map;
|
|
66
|
+
for (const part of header.split(";")) {
|
|
67
|
+
const eqIdx = part.indexOf("=");
|
|
68
|
+
if (eqIdx === -1) continue;
|
|
69
|
+
const key = part.slice(0, eqIdx).trim();
|
|
70
|
+
if (!key) continue;
|
|
71
|
+
let rawVal = part.slice(eqIdx + 1).trim();
|
|
72
|
+
if (rawVal.length >= 2 && rawVal.startsWith('"') && rawVal.endsWith('"')) {
|
|
73
|
+
rawVal = rawVal.slice(1, -1);
|
|
74
|
+
}
|
|
75
|
+
if (!map.has(key)) {
|
|
76
|
+
map.set(key, rawVal);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return map;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function serializeSetCookie(
|
|
83
|
+
key: string,
|
|
84
|
+
value: string,
|
|
85
|
+
options: AstroCookieSetOptions = {},
|
|
86
|
+
): string {
|
|
87
|
+
const encode = options.encode ?? encodeURIComponent;
|
|
88
|
+
const segments = [`${key}=${encode(value)}`];
|
|
89
|
+
if (options.maxAge !== undefined && Number.isFinite(options.maxAge)) {
|
|
90
|
+
segments.push(`Max-Age=${Math.trunc(options.maxAge)}`);
|
|
91
|
+
}
|
|
92
|
+
if (options.domain) {
|
|
93
|
+
segments.push(`Domain=${options.domain}`);
|
|
94
|
+
}
|
|
95
|
+
if (options.path) {
|
|
96
|
+
segments.push(`Path=${options.path}`);
|
|
97
|
+
}
|
|
98
|
+
if (options.expires instanceof Date) {
|
|
99
|
+
segments.push(`Expires=${options.expires.toUTCString()}`);
|
|
100
|
+
}
|
|
101
|
+
if (options.httpOnly) {
|
|
102
|
+
segments.push("HttpOnly");
|
|
103
|
+
}
|
|
104
|
+
if (options.secure) {
|
|
105
|
+
segments.push("Secure");
|
|
106
|
+
}
|
|
107
|
+
if (options.sameSite !== undefined && options.sameSite !== false) {
|
|
108
|
+
const mode =
|
|
109
|
+
options.sameSite === true
|
|
110
|
+
? "Strict"
|
|
111
|
+
: options.sameSite.charAt(0).toUpperCase() +
|
|
112
|
+
options.sameSite.slice(1).toLowerCase();
|
|
113
|
+
segments.push(`SameSite=${mode}`);
|
|
114
|
+
}
|
|
115
|
+
if (options.partitioned) {
|
|
116
|
+
segments.push("Partitioned");
|
|
117
|
+
}
|
|
118
|
+
return segments.join("; ");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class AstroCookies {
|
|
122
|
+
readonly #incoming: Map<string, string>;
|
|
123
|
+
readonly #outgoing = new Map<string, OutgoingCookie>();
|
|
124
|
+
|
|
125
|
+
constructor(
|
|
126
|
+
source?: Request | Headers | string | Record<string, string> | null,
|
|
127
|
+
) {
|
|
128
|
+
if (!source) {
|
|
129
|
+
this.#incoming = new Map();
|
|
130
|
+
} else if (typeof source === "string") {
|
|
131
|
+
this.#incoming = parseCookieHeader(source);
|
|
132
|
+
} else if (source instanceof Request) {
|
|
133
|
+
this.#incoming = parseCookieHeader(source.headers.get("cookie") ?? "");
|
|
134
|
+
} else if (source instanceof Headers) {
|
|
135
|
+
this.#incoming = parseCookieHeader(source.get("cookie") ?? "");
|
|
136
|
+
} else {
|
|
137
|
+
this.#incoming = new Map(Object.entries(source));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
get(key: string, options?: AstroCookieGetOptions): AstroCookie | undefined {
|
|
142
|
+
const outgoing = this.#outgoing.get(key);
|
|
143
|
+
if (outgoing) {
|
|
144
|
+
if (outgoing.isDeleted) return undefined;
|
|
145
|
+
return new AstroCookie(outgoing.value);
|
|
146
|
+
}
|
|
147
|
+
const rawVal = this.#incoming.get(key);
|
|
148
|
+
if (rawVal === undefined) return undefined;
|
|
149
|
+
const decode = options?.decode ?? defaultDecode;
|
|
150
|
+
return new AstroCookie(decode(rawVal));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
has(key: string, _options?: AstroCookieGetOptions): boolean {
|
|
154
|
+
const outgoing = this.#outgoing.get(key);
|
|
155
|
+
if (outgoing) return !outgoing.isDeleted;
|
|
156
|
+
return this.#incoming.has(key);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
set(
|
|
160
|
+
key: string,
|
|
161
|
+
value: string | number | boolean | Record<string, unknown>,
|
|
162
|
+
options?: AstroCookieSetOptions,
|
|
163
|
+
): void {
|
|
164
|
+
const serializedValue =
|
|
165
|
+
typeof value === "string" ? value : JSON.stringify(value);
|
|
166
|
+
this.#outgoing.set(key, {
|
|
167
|
+
value: serializedValue,
|
|
168
|
+
options,
|
|
169
|
+
isDeleted: false,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
delete(key: string, options?: AstroCookieDeleteOptions): void {
|
|
174
|
+
this.#outgoing.set(key, {
|
|
175
|
+
value: "",
|
|
176
|
+
options: {
|
|
177
|
+
...options,
|
|
178
|
+
expires: new Date(0),
|
|
179
|
+
maxAge: 0,
|
|
180
|
+
},
|
|
181
|
+
isDeleted: true,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
merge(cookies: AstroCookies): void {
|
|
186
|
+
for (const [key, entry] of cookies.#outgoing.entries()) {
|
|
187
|
+
this.#outgoing.set(key, entry);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
*headers(): Generator<string, void, unknown> {
|
|
192
|
+
for (const [key, entry] of this.#outgoing.entries()) {
|
|
193
|
+
yield serializeSetCookie(key, entry.value, entry.options);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface AstroSessionOptions {
|
|
199
|
+
cookie?: string;
|
|
200
|
+
cookieOptions?: AstroCookieSetOptions;
|
|
201
|
+
ttl?: number;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
interface SessionEntry {
|
|
205
|
+
value: unknown;
|
|
206
|
+
expiresAt?: number;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const SESSION_STORE = /* @__PURE__ */ new Map<
|
|
210
|
+
string,
|
|
211
|
+
Map<string, SessionEntry>
|
|
212
|
+
>();
|
|
213
|
+
|
|
214
|
+
let sessionIdCounter = 0;
|
|
215
|
+
|
|
216
|
+
function generateSessionId(): string {
|
|
217
|
+
if (
|
|
218
|
+
typeof crypto !== "undefined" &&
|
|
219
|
+
typeof crypto.randomUUID === "function"
|
|
220
|
+
) {
|
|
221
|
+
return crypto.randomUUID();
|
|
222
|
+
}
|
|
223
|
+
return `astro_sess_${Date.now()}_${++sessionIdCounter}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function clearAstroSessions(): void {
|
|
227
|
+
SESSION_STORE.clear();
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export class AstroSession {
|
|
231
|
+
readonly #cookies: AstroCookies;
|
|
232
|
+
readonly #cookieName: string;
|
|
233
|
+
readonly #cookieOptions: AstroCookieSetOptions;
|
|
234
|
+
readonly #defaultTtl?: number;
|
|
235
|
+
#sessionID: string;
|
|
236
|
+
#destroyed = false;
|
|
237
|
+
|
|
238
|
+
constructor(cookies: AstroCookies, options: AstroSessionOptions = {}) {
|
|
239
|
+
this.#cookies = cookies;
|
|
240
|
+
this.#cookieName = options.cookie ?? "astro-session";
|
|
241
|
+
this.#cookieOptions = options.cookieOptions ?? {
|
|
242
|
+
httpOnly: true,
|
|
243
|
+
path: "/",
|
|
244
|
+
sameSite: "lax",
|
|
245
|
+
};
|
|
246
|
+
this.#defaultTtl = options.ttl;
|
|
247
|
+
const existing = cookies.get(this.#cookieName)?.value;
|
|
248
|
+
if (existing) {
|
|
249
|
+
this.#sessionID = existing;
|
|
250
|
+
} else {
|
|
251
|
+
this.#sessionID = generateSessionId();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
get sessionID(): string {
|
|
256
|
+
return this.#sessionID;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
#ensureBucket(): Map<string, SessionEntry> {
|
|
260
|
+
let bucket = SESSION_STORE.get(this.#sessionID);
|
|
261
|
+
if (!bucket) {
|
|
262
|
+
bucket = new Map();
|
|
263
|
+
SESSION_STORE.set(this.#sessionID, bucket);
|
|
264
|
+
}
|
|
265
|
+
return bucket;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async get<T = any>(key: string): Promise<T | undefined> {
|
|
269
|
+
if (this.#destroyed) return undefined;
|
|
270
|
+
const bucket = SESSION_STORE.get(this.#sessionID);
|
|
271
|
+
if (!bucket) return undefined;
|
|
272
|
+
const entry = bucket.get(key);
|
|
273
|
+
if (!entry) return undefined;
|
|
274
|
+
if (entry.expiresAt !== undefined && Date.now() > entry.expiresAt) {
|
|
275
|
+
bucket.delete(key);
|
|
276
|
+
return undefined;
|
|
277
|
+
}
|
|
278
|
+
return entry.value as T;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async has(key: string): Promise<boolean> {
|
|
282
|
+
return (await this.get(key)) !== undefined;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async keys(): Promise<string[]> {
|
|
286
|
+
if (this.#destroyed) return [];
|
|
287
|
+
const bucket = SESSION_STORE.get(this.#sessionID);
|
|
288
|
+
if (!bucket) return [];
|
|
289
|
+
const now = Date.now();
|
|
290
|
+
const out: string[] = [];
|
|
291
|
+
for (const [k, entry] of bucket.entries()) {
|
|
292
|
+
if (entry.expiresAt !== undefined && now > entry.expiresAt) {
|
|
293
|
+
bucket.delete(k);
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
out.push(k);
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async entries(): Promise<Record<string, unknown>> {
|
|
302
|
+
if (this.#destroyed) return {};
|
|
303
|
+
const bucket = SESSION_STORE.get(this.#sessionID);
|
|
304
|
+
if (!bucket) return {};
|
|
305
|
+
const now = Date.now();
|
|
306
|
+
const out: Record<string, unknown> = {};
|
|
307
|
+
for (const [k, entry] of bucket.entries()) {
|
|
308
|
+
if (entry.expiresAt !== undefined && now > entry.expiresAt) {
|
|
309
|
+
bucket.delete(k);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
out[k] = entry.value;
|
|
313
|
+
}
|
|
314
|
+
return out;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
set(key: string, value: any, options?: { ttl?: number }): void {
|
|
318
|
+
this.#destroyed = false;
|
|
319
|
+
const bucket = this.#ensureBucket();
|
|
320
|
+
const ttlSeconds = options?.ttl ?? this.#defaultTtl;
|
|
321
|
+
const expiresAt =
|
|
322
|
+
ttlSeconds !== undefined && Number.isFinite(ttlSeconds)
|
|
323
|
+
? Date.now() + ttlSeconds * 1000
|
|
324
|
+
: undefined;
|
|
325
|
+
bucket.set(key, { value, expiresAt });
|
|
326
|
+
this.#cookies.set(this.#cookieName, this.#sessionID, this.#cookieOptions);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
delete(key: string): void {
|
|
330
|
+
const bucket = SESSION_STORE.get(this.#sessionID);
|
|
331
|
+
bucket?.delete(key);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async regenerate(): Promise<void> {
|
|
335
|
+
const oldBucket = SESSION_STORE.get(this.#sessionID);
|
|
336
|
+
const cloned = new Map<string, SessionEntry>(oldBucket ? oldBucket : []);
|
|
337
|
+
SESSION_STORE.delete(this.#sessionID);
|
|
338
|
+
this.#sessionID = generateSessionId();
|
|
339
|
+
SESSION_STORE.set(this.#sessionID, cloned);
|
|
340
|
+
this.#destroyed = false;
|
|
341
|
+
this.#cookies.set(this.#cookieName, this.#sessionID, this.#cookieOptions);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
destroy(): void {
|
|
345
|
+
SESSION_STORE.delete(this.#sessionID);
|
|
346
|
+
this.#destroyed = true;
|
|
347
|
+
this.#cookies.delete(this.#cookieName, {
|
|
348
|
+
path: this.#cookieOptions.path ?? "/",
|
|
349
|
+
domain: this.#cookieOptions.domain,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async load(sessionID: string): Promise<void> {
|
|
354
|
+
this.#sessionID = sessionID;
|
|
355
|
+
this.#destroyed = false;
|
|
356
|
+
this.#cookies.set(this.#cookieName, this.#sessionID, this.#cookieOptions);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export type ValidRedirectStatus =
|
|
361
|
+
300 | 301 | 302 | 303 | 304 | 307 | 308 | number;
|
|
362
|
+
|
|
363
|
+
export interface AstroResponseInit {
|
|
364
|
+
status: number;
|
|
365
|
+
statusText: string;
|
|
366
|
+
headers: Headers;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export type AstroSlotValue =
|
|
370
|
+
string | number | boolean | null | undefined | ((...args: any[]) => unknown);
|
|
371
|
+
|
|
372
|
+
export interface AstroSlots {
|
|
373
|
+
has(name: string): boolean;
|
|
374
|
+
render(name: string, args?: unknown[]): Promise<string>;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export interface AstroActionCallable<TInput = any, TResult = any> {
|
|
378
|
+
(input?: TInput): Promise<TResult>;
|
|
379
|
+
readonly queryString?: string;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export interface AstroServerIslandEntry {
|
|
383
|
+
id: string;
|
|
384
|
+
componentName: string;
|
|
385
|
+
props: Record<string, unknown>;
|
|
386
|
+
hasFallback: boolean;
|
|
387
|
+
deferred: boolean;
|
|
388
|
+
render: () => string;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export interface AstroGlobal<
|
|
392
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
393
|
+
Params extends Record<string, string | undefined> = Record<
|
|
394
|
+
string,
|
|
395
|
+
string | undefined
|
|
396
|
+
>,
|
|
397
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
398
|
+
> {
|
|
399
|
+
props: Props;
|
|
400
|
+
request: Request;
|
|
401
|
+
url: URL;
|
|
402
|
+
params: Params;
|
|
403
|
+
locals: Locals;
|
|
404
|
+
cookies: AstroCookies;
|
|
405
|
+
session: AstroSession;
|
|
406
|
+
slots: AstroSlots;
|
|
407
|
+
site: URL | undefined;
|
|
408
|
+
generator: string;
|
|
409
|
+
clientAddress: string;
|
|
410
|
+
response: AstroResponseInit;
|
|
411
|
+
originPathname: string;
|
|
412
|
+
routePattern: string;
|
|
413
|
+
isPrerendered: boolean;
|
|
414
|
+
preferredLocale: string | undefined;
|
|
415
|
+
preferredLocaleList: string[] | undefined;
|
|
416
|
+
currentLocale: string | undefined;
|
|
417
|
+
deferServerIslands: boolean;
|
|
418
|
+
serverIslands: AstroServerIslandEntry[];
|
|
419
|
+
resolveServerIsland(id: string): string | undefined;
|
|
420
|
+
resolveAllServerIslands(html: string): string;
|
|
421
|
+
redirect(path: string, status?: ValidRedirectStatus): Response;
|
|
422
|
+
rewrite(reroutePayload: string | URL | Request): Promise<Response>;
|
|
423
|
+
callAction<TAction extends AstroActionCallable<any, any>>(
|
|
424
|
+
action: TAction,
|
|
425
|
+
...args: Parameters<TAction>
|
|
426
|
+
): Promise<Awaited<ReturnType<TAction>>>;
|
|
427
|
+
getActionResult<TAction extends AstroActionCallable<any, any>>(
|
|
428
|
+
action: TAction | string,
|
|
429
|
+
): Awaited<ReturnType<TAction>> | undefined;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export interface AstroContextInit<
|
|
433
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
434
|
+
Params extends Record<string, string | undefined> = Record<
|
|
435
|
+
string,
|
|
436
|
+
string | undefined
|
|
437
|
+
>,
|
|
438
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
439
|
+
> {
|
|
440
|
+
props?: Props;
|
|
441
|
+
request?: Request;
|
|
442
|
+
url?: URL | string;
|
|
443
|
+
params?: Params;
|
|
444
|
+
locals?: Locals;
|
|
445
|
+
cookies?: AstroCookies;
|
|
446
|
+
session?: AstroSession;
|
|
447
|
+
sessionOptions?: AstroSessionOptions;
|
|
448
|
+
slots?: Record<string, AstroSlotValue>;
|
|
449
|
+
site?: URL | string;
|
|
450
|
+
generator?: string;
|
|
451
|
+
clientAddress?: string;
|
|
452
|
+
response?: Partial<AstroResponseInit>;
|
|
453
|
+
originPathname?: string;
|
|
454
|
+
routePattern?: string;
|
|
455
|
+
isPrerendered?: boolean;
|
|
456
|
+
preferredLocale?: string;
|
|
457
|
+
preferredLocaleList?: string[];
|
|
458
|
+
currentLocale?: string;
|
|
459
|
+
deferServerIslands?: boolean;
|
|
460
|
+
actionResults?: Map<unknown, unknown> | Record<string, unknown>;
|
|
461
|
+
rewriteHandler?: (
|
|
462
|
+
target: URL,
|
|
463
|
+
request: Request,
|
|
464
|
+
) => Response | Promise<Response>;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const ACTION_RESULTS_SYMBOL = Symbol.for("moonshine.astro.actionResults");
|
|
468
|
+
|
|
469
|
+
export function recordAstroActionResult(
|
|
470
|
+
actionKey: unknown,
|
|
471
|
+
result: unknown,
|
|
472
|
+
astro?: AstroGlobal<any, any, any>,
|
|
473
|
+
): void {
|
|
474
|
+
const ctx = astro ?? activeAstroContext;
|
|
475
|
+
if (!ctx) return;
|
|
476
|
+
const store = (ctx as any)[ACTION_RESULTS_SYMBOL] as
|
|
477
|
+
Map<unknown, unknown> | undefined;
|
|
478
|
+
if (!store) return;
|
|
479
|
+
store.set(actionKey, result);
|
|
480
|
+
const queryString =
|
|
481
|
+
typeof actionKey === "function" ||
|
|
482
|
+
(typeof actionKey === "object" && actionKey !== null)
|
|
483
|
+
? (actionKey as { queryString?: string }).queryString
|
|
484
|
+
: typeof actionKey === "string"
|
|
485
|
+
? actionKey.startsWith("?_action=")
|
|
486
|
+
? actionKey
|
|
487
|
+
: `?_action=${encodeURIComponent(actionKey)}`
|
|
488
|
+
: undefined;
|
|
489
|
+
if (queryString) {
|
|
490
|
+
store.set(queryString, result);
|
|
491
|
+
const rawName = queryString.startsWith("?_action=")
|
|
492
|
+
? decodeURIComponent(queryString.slice("?_action=".length))
|
|
493
|
+
: queryString;
|
|
494
|
+
store.set(rawName, result);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function createAstroSlots(
|
|
499
|
+
rawSlots: Record<string, AstroSlotValue> = {},
|
|
500
|
+
): AstroSlots {
|
|
501
|
+
return {
|
|
502
|
+
has(name: string): boolean {
|
|
503
|
+
return (
|
|
504
|
+
Object.hasOwn(rawSlots, name) &&
|
|
505
|
+
rawSlots[name] !== undefined &&
|
|
506
|
+
rawSlots[name] !== null &&
|
|
507
|
+
rawSlots[name] !== false
|
|
508
|
+
);
|
|
509
|
+
},
|
|
510
|
+
async render(name: string, args: unknown[] = []): Promise<string> {
|
|
511
|
+
if (!Object.hasOwn(rawSlots, name)) return "";
|
|
512
|
+
const slot = rawSlots[name];
|
|
513
|
+
const resolved =
|
|
514
|
+
typeof slot === "function" ? await slot(...args) : await slot;
|
|
515
|
+
if (resolved === undefined || resolved === null || resolved === false) {
|
|
516
|
+
return "";
|
|
517
|
+
}
|
|
518
|
+
return String(resolved);
|
|
519
|
+
},
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export function createAstroGlobal<
|
|
524
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
525
|
+
Params extends Record<string, string | undefined> = Record<
|
|
526
|
+
string,
|
|
527
|
+
string | undefined
|
|
528
|
+
>,
|
|
529
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
530
|
+
>(
|
|
531
|
+
init: AstroContextInit<Props, Params, Locals> = {},
|
|
532
|
+
): AstroGlobal<Props, Params, Locals> {
|
|
533
|
+
const resolvedUrl =
|
|
534
|
+
init.url instanceof URL
|
|
535
|
+
? init.url
|
|
536
|
+
: typeof init.url === "string"
|
|
537
|
+
? new URL(init.url, "http://localhost")
|
|
538
|
+
: init.request
|
|
539
|
+
? new URL(init.request.url)
|
|
540
|
+
: new URL("http://localhost/");
|
|
541
|
+
const request = init.request ?? new Request(resolvedUrl.href);
|
|
542
|
+
const cookies = init.cookies ?? new AstroCookies(request);
|
|
543
|
+
const session =
|
|
544
|
+
init.session ?? new AstroSession(cookies, init.sessionOptions);
|
|
545
|
+
const slots = createAstroSlots(init.slots);
|
|
546
|
+
const site =
|
|
547
|
+
init.site instanceof URL
|
|
548
|
+
? init.site
|
|
549
|
+
: typeof init.site === "string"
|
|
550
|
+
? new URL(init.site)
|
|
551
|
+
: undefined;
|
|
552
|
+
const responseHeaders =
|
|
553
|
+
init.response?.headers instanceof Headers
|
|
554
|
+
? init.response.headers
|
|
555
|
+
: new Headers(init.response?.headers);
|
|
556
|
+
const response: AstroResponseInit = {
|
|
557
|
+
status: init.response?.status ?? 200,
|
|
558
|
+
statusText: init.response?.statusText ?? "OK",
|
|
559
|
+
headers: responseHeaders,
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
const actionResults = new Map<unknown, unknown>();
|
|
563
|
+
if (init.actionResults instanceof Map) {
|
|
564
|
+
for (const [k, v] of init.actionResults.entries()) {
|
|
565
|
+
actionResults.set(k, v);
|
|
566
|
+
}
|
|
567
|
+
} else if (init.actionResults && typeof init.actionResults === "object") {
|
|
568
|
+
for (const [k, v] of Object.entries(init.actionResults)) {
|
|
569
|
+
actionResults.set(k, v);
|
|
570
|
+
actionResults.set(`?_action=${encodeURIComponent(k)}`, v);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const serverIslands: AstroServerIslandEntry[] = [];
|
|
575
|
+
|
|
576
|
+
const astro: AstroGlobal<Props, Params, Locals> = {
|
|
577
|
+
props: (init.props ?? {}) as Props,
|
|
578
|
+
request,
|
|
579
|
+
url: resolvedUrl,
|
|
580
|
+
params: (init.params ?? {}) as Params,
|
|
581
|
+
locals: (init.locals ?? {}) as Locals,
|
|
582
|
+
cookies,
|
|
583
|
+
session,
|
|
584
|
+
slots,
|
|
585
|
+
site,
|
|
586
|
+
generator: init.generator ?? "Moonshine Astro",
|
|
587
|
+
clientAddress:
|
|
588
|
+
init.clientAddress ??
|
|
589
|
+
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
|
590
|
+
"127.0.0.1",
|
|
591
|
+
response,
|
|
592
|
+
originPathname: init.originPathname ?? resolvedUrl.pathname,
|
|
593
|
+
routePattern: init.routePattern ?? resolvedUrl.pathname,
|
|
594
|
+
isPrerendered: init.isPrerendered ?? false,
|
|
595
|
+
preferredLocale: init.preferredLocale,
|
|
596
|
+
preferredLocaleList: init.preferredLocaleList,
|
|
597
|
+
currentLocale: init.currentLocale,
|
|
598
|
+
deferServerIslands: init.deferServerIslands ?? false,
|
|
599
|
+
serverIslands,
|
|
600
|
+
resolveServerIsland(id: string): string | undefined {
|
|
601
|
+
const entry = serverIslands.find((island) => island.id === id);
|
|
602
|
+
if (!entry) return undefined;
|
|
603
|
+
return withAstroContext(astro, () => entry.render());
|
|
604
|
+
},
|
|
605
|
+
resolveAllServerIslands(html: string): string {
|
|
606
|
+
let output = html;
|
|
607
|
+
for (const entry of serverIslands) {
|
|
608
|
+
const pattern = new RegExp(
|
|
609
|
+
`<astro-server-island[^>]*data-island-id="${entry.id}"[^>]*>[\\s\\S]*?<\\/astro-server-island>`,
|
|
610
|
+
"g",
|
|
611
|
+
);
|
|
612
|
+
if (pattern.test(output)) {
|
|
613
|
+
const rendered = withAstroContext(astro, () => entry.render());
|
|
614
|
+
output = output.replace(pattern, () => rendered);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return output;
|
|
618
|
+
},
|
|
619
|
+
redirect(path: string, status: ValidRedirectStatus = 302): Response {
|
|
620
|
+
const headers = new Headers(response.headers);
|
|
621
|
+
headers.set("Location", path);
|
|
622
|
+
for (const cookieHeader of cookies.headers()) {
|
|
623
|
+
headers.append("Set-Cookie", cookieHeader);
|
|
624
|
+
}
|
|
625
|
+
return new Response(null, { status, headers });
|
|
626
|
+
},
|
|
627
|
+
async rewrite(reroutePayload: string | URL | Request): Promise<Response> {
|
|
628
|
+
const targetUrl =
|
|
629
|
+
typeof reroutePayload === "string"
|
|
630
|
+
? new URL(reroutePayload, resolvedUrl)
|
|
631
|
+
: reroutePayload instanceof URL
|
|
632
|
+
? reroutePayload
|
|
633
|
+
: new URL(reroutePayload.url);
|
|
634
|
+
const nextRequest =
|
|
635
|
+
reroutePayload instanceof Request
|
|
636
|
+
? reroutePayload
|
|
637
|
+
: new Request(targetUrl.href, request);
|
|
638
|
+
if (init.rewriteHandler) {
|
|
639
|
+
return await init.rewriteHandler(targetUrl, nextRequest);
|
|
640
|
+
}
|
|
641
|
+
const headers = new Headers(response.headers);
|
|
642
|
+
headers.set("x-astro-rewrite", targetUrl.pathname + targetUrl.search);
|
|
643
|
+
return new Response(null, {
|
|
644
|
+
status: response.status,
|
|
645
|
+
statusText: response.statusText,
|
|
646
|
+
headers,
|
|
647
|
+
});
|
|
648
|
+
},
|
|
649
|
+
async callAction<TAction extends AstroActionCallable<any, any>>(
|
|
650
|
+
action: TAction,
|
|
651
|
+
...args: Parameters<TAction>
|
|
652
|
+
): Promise<Awaited<ReturnType<TAction>>> {
|
|
653
|
+
const res = await withAstroContext(astro, () =>
|
|
654
|
+
action(...(args as [any?])),
|
|
655
|
+
);
|
|
656
|
+
recordAstroActionResult(action, res, astro);
|
|
657
|
+
return res as Awaited<ReturnType<TAction>>;
|
|
658
|
+
},
|
|
659
|
+
getActionResult<TAction extends AstroActionCallable<any, any>>(
|
|
660
|
+
action: TAction | string,
|
|
661
|
+
): Awaited<ReturnType<TAction>> | undefined {
|
|
662
|
+
if (actionResults.has(action)) {
|
|
663
|
+
return actionResults.get(action) as Awaited<ReturnType<TAction>>;
|
|
664
|
+
}
|
|
665
|
+
const queryString =
|
|
666
|
+
typeof action === "function" ||
|
|
667
|
+
(typeof action === "object" && action !== null)
|
|
668
|
+
? (action as { queryString?: string }).queryString
|
|
669
|
+
: typeof action === "string"
|
|
670
|
+
? action
|
|
671
|
+
: undefined;
|
|
672
|
+
if (queryString && actionResults.has(queryString)) {
|
|
673
|
+
return actionResults.get(queryString) as Awaited<ReturnType<TAction>>;
|
|
674
|
+
}
|
|
675
|
+
return undefined;
|
|
676
|
+
},
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
Object.defineProperty(astro, ACTION_RESULTS_SYMBOL, {
|
|
680
|
+
value: actionResults,
|
|
681
|
+
enumerable: false,
|
|
682
|
+
});
|
|
683
|
+
|
|
684
|
+
return astro;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
let activeAstroContext: AstroGlobal<any, any, any> | undefined;
|
|
688
|
+
|
|
689
|
+
export function peekAstroContext(): AstroGlobal<any, any, any> | undefined {
|
|
690
|
+
return activeAstroContext;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function isAstroGlobal(value: unknown): value is AstroGlobal<any, any, any> {
|
|
694
|
+
return (
|
|
695
|
+
typeof value === "object" &&
|
|
696
|
+
value !== null &&
|
|
697
|
+
"cookies" in value &&
|
|
698
|
+
(value as AstroGlobal).cookies instanceof AstroCookies &&
|
|
699
|
+
typeof (value as AstroGlobal).redirect === "function"
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
export function withAstroContext<
|
|
704
|
+
T,
|
|
705
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
706
|
+
Params extends Record<string, string | undefined> = Record<
|
|
707
|
+
string,
|
|
708
|
+
string | undefined
|
|
709
|
+
>,
|
|
710
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
711
|
+
>(
|
|
712
|
+
initOrContext:
|
|
713
|
+
| AstroGlobal<Props, Params, Locals>
|
|
714
|
+
| AstroContextInit<Props, Params, Locals>,
|
|
715
|
+
fn: (astro: AstroGlobal<Props, Params, Locals>) => T,
|
|
716
|
+
): T {
|
|
717
|
+
const astro = isAstroGlobal(initOrContext)
|
|
718
|
+
? initOrContext
|
|
719
|
+
: createAstroGlobal(initOrContext);
|
|
720
|
+
const previous = activeAstroContext;
|
|
721
|
+
activeAstroContext = astro;
|
|
722
|
+
try {
|
|
723
|
+
const result = fn(astro);
|
|
724
|
+
if (
|
|
725
|
+
result !== null &&
|
|
726
|
+
typeof result === "object" &&
|
|
727
|
+
typeof (result as { then?: unknown }).then === "function"
|
|
728
|
+
) {
|
|
729
|
+
return Promise.resolve(result).finally(() => {
|
|
730
|
+
if (activeAstroContext === astro) {
|
|
731
|
+
activeAstroContext = previous;
|
|
732
|
+
}
|
|
733
|
+
}) as T;
|
|
734
|
+
}
|
|
735
|
+
activeAstroContext = previous;
|
|
736
|
+
return result;
|
|
737
|
+
} catch (error) {
|
|
738
|
+
activeAstroContext = previous;
|
|
739
|
+
throw error;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
export function useAstro<
|
|
744
|
+
Props extends Record<string, any> = Record<string, any>,
|
|
745
|
+
Params extends Record<string, string | undefined> = Record<
|
|
746
|
+
string,
|
|
747
|
+
string | undefined
|
|
748
|
+
>,
|
|
749
|
+
Locals extends Record<string, any> = Record<string, any>,
|
|
750
|
+
>(): AstroGlobal<Props, Params, Locals> {
|
|
751
|
+
return (activeAstroContext ?? createAstroGlobal()) as AstroGlobal<
|
|
752
|
+
Props,
|
|
753
|
+
Params,
|
|
754
|
+
Locals
|
|
755
|
+
>;
|
|
756
|
+
}
|