@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/src/actions.ts ADDED
@@ -0,0 +1,556 @@
1
+ /** Independent host-free Astro Actions runtime (defineAction, ActionError, ActionInputError). */
2
+ import { recordAstroActionResult, useAstro, type AstroGlobal } from "./context";
3
+
4
+ export const ACTION_ERROR_CODES = {
5
+ BAD_REQUEST: 400,
6
+ UNAUTHORIZED: 401,
7
+ PAYMENT_REQUIRED: 402,
8
+ FORBIDDEN: 403,
9
+ NOT_FOUND: 404,
10
+ METHOD_NOT_ALLOWED: 405,
11
+ NOT_ACCEPTABLE: 406,
12
+ PROXY_AUTHENTICATION_REQUIRED: 407,
13
+ REQUEST_TIMEOUT: 408,
14
+ CONFLICT: 409,
15
+ GONE: 410,
16
+ LENGTH_REQUIRED: 411,
17
+ PRECONDITION_FAILED: 412,
18
+ CONTENT_TOO_LARGE: 413,
19
+ URI_TOO_LONG: 414,
20
+ UNSUPPORTED_MEDIA_TYPE: 415,
21
+ RANGE_NOT_SATISFIABLE: 416,
22
+ EXPECTATION_FAILED: 417,
23
+ MISDIRECTED_REQUEST: 421,
24
+ UNPROCESSABLE_CONTENT: 422,
25
+ LOCKED: 423,
26
+ FAILED_DEPENDENCY: 424,
27
+ TOO_EARLY: 425,
28
+ UPGRADE_REQUIRED: 426,
29
+ PRECONDITION_REQUIRED: 428,
30
+ TOO_MANY_REQUESTS: 429,
31
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
32
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451,
33
+ INTERNAL_SERVER_ERROR: 500,
34
+ NOT_IMPLEMENTED: 501,
35
+ BAD_GATEWAY: 502,
36
+ SERVICE_UNAVAILABLE: 503,
37
+ GATEWAY_TIMEOUT: 504,
38
+ HTTP_VERSION_NOT_SUPPORTED: 505,
39
+ VARIANT_ALSO_NEGOTIATES: 506,
40
+ INSUFFICIENT_STORAGE: 507,
41
+ LOOP_DETECTED: 508,
42
+ NETWORK_AUTHENTICATION_REQUIRED: 511,
43
+ } as const;
44
+
45
+ export type ActionErrorCode = keyof typeof ACTION_ERROR_CODES;
46
+
47
+ const STATUS_TO_CODE = /* @__PURE__ */ new Map<number, ActionErrorCode>(
48
+ Object.entries(ACTION_ERROR_CODES).map(([code, status]) => [
49
+ status,
50
+ code as ActionErrorCode,
51
+ ]),
52
+ );
53
+
54
+ export class ActionError<
55
+ TCode extends ActionErrorCode = ActionErrorCode,
56
+ > extends Error {
57
+ readonly type: string = "AstroActionError";
58
+ readonly code: TCode;
59
+ readonly status: number;
60
+
61
+ constructor(params: { code: TCode; message?: string; stack?: string }) {
62
+ super(params.message ?? params.code);
63
+ this.name = "ActionError";
64
+ this.code = params.code;
65
+ this.status = ActionError.codeToStatus(params.code);
66
+ if (params.stack) {
67
+ this.stack = params.stack;
68
+ }
69
+ }
70
+
71
+ static codeToStatus(code: ActionErrorCode): number {
72
+ return ACTION_ERROR_CODES[code] ?? 500;
73
+ }
74
+
75
+ static statusToCode(status: number): ActionErrorCode {
76
+ return STATUS_TO_CODE.get(status) ?? "INTERNAL_SERVER_ERROR";
77
+ }
78
+ }
79
+
80
+ export interface ActionInputIssue {
81
+ message: string;
82
+ path?: readonly (string | number)[];
83
+ code?: string;
84
+ }
85
+
86
+ export type ErrorInferenceObject = Record<string, unknown>;
87
+
88
+ export class ActionInputError<
89
+ TInput extends ErrorInferenceObject = ErrorInferenceObject,
90
+ > extends ActionError<"BAD_REQUEST"> {
91
+ override readonly type = "AstroActionInputError";
92
+ readonly issues: ActionInputIssue[];
93
+ readonly fields: { [P in keyof TInput]?: string[] } & Record<
94
+ string,
95
+ string[] | undefined
96
+ >;
97
+
98
+ constructor(issues: ActionInputIssue[]) {
99
+ super({
100
+ code: "BAD_REQUEST",
101
+ message: `Failed to validate: ${JSON.stringify(issues)}`,
102
+ });
103
+ this.name = "ActionInputError";
104
+ this.issues = issues;
105
+ const fieldMap: Record<string, string[] | undefined> = {};
106
+ for (const issue of issues) {
107
+ if (issue.path && issue.path.length > 0) {
108
+ const key = String(issue.path[0]);
109
+ let list = fieldMap[key];
110
+ if (!list) {
111
+ list = [];
112
+ fieldMap[key] = list;
113
+ }
114
+ list.push(issue.message);
115
+ }
116
+ }
117
+ this.fields = fieldMap as { [P in keyof TInput]?: string[] } & Record<
118
+ string,
119
+ string[] | undefined
120
+ >;
121
+ }
122
+ }
123
+
124
+ export function isActionError(error: unknown): error is ActionError {
125
+ return (
126
+ typeof error === "object" &&
127
+ error !== null &&
128
+ ((error as { type?: unknown }).type === "AstroActionError" ||
129
+ (error as { type?: unknown }).type === "AstroActionInputError" ||
130
+ error instanceof ActionError)
131
+ );
132
+ }
133
+
134
+ export function isInputError<
135
+ TInput extends ErrorInferenceObject = ErrorInferenceObject,
136
+ >(error: unknown): error is ActionInputError<TInput> {
137
+ return (
138
+ typeof error === "object" &&
139
+ error !== null &&
140
+ ((error as { type?: unknown }).type === "AstroActionInputError" ||
141
+ error instanceof ActionInputError) &&
142
+ Array.isArray((error as { issues?: unknown }).issues)
143
+ );
144
+ }
145
+
146
+ export type SafeResult<TInput, TOutput> =
147
+ | { data: TOutput; error: undefined }
148
+ | {
149
+ data: undefined;
150
+ error:
151
+ | ActionError
152
+ | ActionInputError<
153
+ TInput extends ErrorInferenceObject ? TInput : ErrorInferenceObject
154
+ >;
155
+ };
156
+
157
+ export type ActionAPIContext = Pick<
158
+ AstroGlobal,
159
+ | "request"
160
+ | "url"
161
+ | "params"
162
+ | "locals"
163
+ | "cookies"
164
+ | "session"
165
+ | "site"
166
+ | "generator"
167
+ | "clientAddress"
168
+ | "redirect"
169
+ | "rewrite"
170
+ | "originPathname"
171
+ | "routePattern"
172
+ | "isPrerendered"
173
+ | "preferredLocale"
174
+ | "preferredLocaleList"
175
+ | "currentLocale"
176
+ | "callAction"
177
+ | "getActionResult"
178
+ >;
179
+
180
+ export type SchemaValidator<TInput> =
181
+ | {
182
+ safeParseAsync: (input: unknown) => Promise<
183
+ | { success: true; data: TInput }
184
+ | {
185
+ success: false;
186
+ error: { issues: readonly ActionInputIssue[] };
187
+ }
188
+ >;
189
+ }
190
+ | {
191
+ safeParse: (input: unknown) =>
192
+ | { success: true; data: TInput }
193
+ | {
194
+ success: false;
195
+ error: { issues: readonly ActionInputIssue[] };
196
+ };
197
+ }
198
+ | {
199
+ parse: (input: unknown) => TInput | Promise<TInput>;
200
+ }
201
+ | ((input: unknown) => TInput | Promise<TInput>);
202
+
203
+ export type ActionAccept = "form" | "json" | undefined;
204
+
205
+ export type ActionHandler<TInput, TOutput> = (
206
+ input: TInput,
207
+ context: ActionAPIContext,
208
+ ) => TOutput | Promise<TOutput>;
209
+
210
+ export interface ActionClient<
211
+ TOutput,
212
+ TAccept extends ActionAccept = undefined,
213
+ TInput = undefined,
214
+ > {
215
+ (
216
+ ...args: undefined extends TInput
217
+ ? [input?: TAccept extends "form" ? FormData | TInput : TInput]
218
+ : [input: TAccept extends "form" ? FormData | TInput : TInput]
219
+ ): Promise<SafeResult<TInput, Awaited<TOutput>>>;
220
+ orThrow(
221
+ ...args: undefined extends TInput
222
+ ? [input?: TAccept extends "form" ? FormData | TInput : TInput]
223
+ : [input: TAccept extends "form" ? FormData | TInput : TInput]
224
+ ): Promise<Awaited<TOutput>>;
225
+ readonly queryString: string;
226
+ toString(): string;
227
+ }
228
+
229
+ function formDataToObject(formData: FormData): Record<string, unknown> {
230
+ const obj: Record<string, unknown> = {};
231
+ for (const [key, value] of formData.entries()) {
232
+ if (Object.hasOwn(obj, key)) {
233
+ const existing = obj[key];
234
+ if (Array.isArray(existing)) {
235
+ existing.push(value);
236
+ } else {
237
+ obj[key] = [existing, value];
238
+ }
239
+ } else {
240
+ obj[key] = value;
241
+ }
242
+ }
243
+ return obj;
244
+ }
245
+
246
+ async function validateInput<TInput>(
247
+ validator: SchemaValidator<TInput>,
248
+ rawInput: unknown,
249
+ ): Promise<TInput> {
250
+ try {
251
+ if (typeof validator === "function") {
252
+ return await validator(rawInput);
253
+ }
254
+ if (
255
+ "safeParseAsync" in validator &&
256
+ typeof validator.safeParseAsync === "function"
257
+ ) {
258
+ const res = await validator.safeParseAsync(rawInput);
259
+ if (!res.success) {
260
+ throw new ActionInputError([...res.error.issues]);
261
+ }
262
+ return res.data;
263
+ }
264
+ if ("safeParse" in validator && typeof validator.safeParse === "function") {
265
+ const res = validator.safeParse(rawInput);
266
+ if (!res.success) {
267
+ throw new ActionInputError([...res.error.issues]);
268
+ }
269
+ return res.data;
270
+ }
271
+ if ("parse" in validator && typeof validator.parse === "function") {
272
+ return await validator.parse(rawInput);
273
+ }
274
+ return rawInput as TInput;
275
+ } catch (err) {
276
+ if (isActionError(err)) throw err;
277
+ if (
278
+ typeof err === "object" &&
279
+ err !== null &&
280
+ Array.isArray((err as { issues?: unknown }).issues)
281
+ ) {
282
+ throw new ActionInputError(
283
+ (err as { issues: ActionInputIssue[] }).issues,
284
+ );
285
+ }
286
+ throw new ActionInputError([
287
+ {
288
+ message: err instanceof Error ? err.message : String(err),
289
+ },
290
+ ]);
291
+ }
292
+ }
293
+
294
+ export function getActionQueryString(name: string): string {
295
+ return `?_action=${encodeURIComponent(name)}`;
296
+ }
297
+
298
+ export function actionPathToString(path: readonly string[]): string {
299
+ return path.join(".");
300
+ }
301
+
302
+ export type SerializedActionResult =
303
+ | {
304
+ type: "data";
305
+ status: 200;
306
+ contentType: "application/json";
307
+ body: string;
308
+ }
309
+ | {
310
+ type: "empty";
311
+ status: 204;
312
+ }
313
+ | {
314
+ type: "error";
315
+ status: number;
316
+ contentType: "application/json";
317
+ body: string;
318
+ };
319
+
320
+ export function serializeActionResult<TInput, TOutput>(
321
+ res: SafeResult<TInput, TOutput>,
322
+ ): SerializedActionResult {
323
+ if (res.error) {
324
+ const status = res.error.status ?? 500;
325
+ return {
326
+ type: "error",
327
+ status,
328
+ contentType: "application/json",
329
+ body: JSON.stringify({
330
+ type: res.error.type,
331
+ code: res.error.code,
332
+ message: res.error.message,
333
+ issues: isInputError(res.error) ? res.error.issues : undefined,
334
+ }),
335
+ };
336
+ }
337
+ if (res.data === undefined) {
338
+ return {
339
+ type: "empty",
340
+ status: 204,
341
+ };
342
+ }
343
+ return {
344
+ type: "data",
345
+ status: 200,
346
+ contentType: "application/json",
347
+ body: JSON.stringify(res.data),
348
+ };
349
+ }
350
+
351
+ export function deserializeActionResult<TInput, TOutput>(
352
+ res: SerializedActionResult,
353
+ ): SafeResult<TInput, TOutput> {
354
+ if (res.type === "empty") {
355
+ return { data: undefined as unknown as TOutput, error: undefined };
356
+ }
357
+ if (res.type === "data") {
358
+ return {
359
+ data: JSON.parse(res.body) as TOutput,
360
+ error: undefined,
361
+ };
362
+ }
363
+ let parsed: {
364
+ type?: string;
365
+ code?: ActionErrorCode;
366
+ message?: string;
367
+ issues?: ActionInputIssue[];
368
+ } = {};
369
+ try {
370
+ parsed = JSON.parse(res.body);
371
+ } catch {
372
+ // Fallback to status code below
373
+ }
374
+ if (parsed.type === "AstroActionInputError" && Array.isArray(parsed.issues)) {
375
+ return {
376
+ data: undefined,
377
+ error: new ActionInputError(parsed.issues) as ActionInputError<
378
+ TInput extends ErrorInferenceObject ? TInput : ErrorInferenceObject
379
+ >,
380
+ };
381
+ }
382
+ return {
383
+ data: undefined,
384
+ error: new ActionError({
385
+ code: parsed.code ?? ActionError.statusToCode(res.status),
386
+ message: parsed.message,
387
+ }),
388
+ };
389
+ }
390
+
391
+ export interface AstroActionContext {
392
+ action?: {
393
+ calledFrom: "form" | "rpc";
394
+ name: string;
395
+ handler: () => Promise<SafeResult<unknown, unknown>>;
396
+ };
397
+ setActionResult(actionName: string, result: SerializedActionResult): void;
398
+ serializeActionResult: typeof serializeActionResult;
399
+ deserializeActionResult: typeof deserializeActionResult;
400
+ }
401
+
402
+ const registeredActions = /* @__PURE__ */ new Map<
403
+ string,
404
+ ActionClient<unknown, ActionAccept, unknown>
405
+ >();
406
+
407
+ export function getActionContext(
408
+ context?: Partial<ActionAPIContext>,
409
+ ): AstroActionContext {
410
+ const ctx = (context ?? useAstro()) as AstroGlobal;
411
+ const url = ctx.url ?? new URL(ctx.request?.url ?? "http://localhost/");
412
+ const queryAction = url.searchParams.get("_action");
413
+ const rpcMatch = url.pathname.startsWith("/_actions/")
414
+ ? decodeURIComponent(url.pathname.slice("/_actions/".length))
415
+ : null;
416
+ const actionName = queryAction ?? rpcMatch;
417
+ const calledFrom: "form" | "rpc" = queryAction ? "form" : "rpc";
418
+
419
+ let action: AstroActionContext["action"] = undefined;
420
+ if (actionName && (ctx.request?.method ?? "POST").toUpperCase() === "POST") {
421
+ const registered = registeredActions.get(actionName);
422
+ action = {
423
+ calledFrom,
424
+ name: actionName,
425
+ handler: async () => {
426
+ if (!registered) {
427
+ return {
428
+ data: undefined,
429
+ error: new ActionError({
430
+ code: "NOT_FOUND",
431
+ message: `Action "${actionName}" not found.`,
432
+ }),
433
+ };
434
+ }
435
+ let input: unknown = undefined;
436
+ if (ctx.request) {
437
+ const contentType =
438
+ ctx.request.headers.get("content-type")?.toLowerCase() ?? "";
439
+ if (
440
+ contentType.includes("multipart/form-data") ||
441
+ contentType.includes("application/x-www-form-urlencoded")
442
+ ) {
443
+ input = await ctx.request.clone().formData();
444
+ } else if (contentType.includes("application/json")) {
445
+ const text = await ctx.request.clone().text();
446
+ input = text.length > 0 ? JSON.parse(text) : undefined;
447
+ }
448
+ }
449
+ return await registered(input);
450
+ },
451
+ };
452
+ }
453
+
454
+ return {
455
+ action,
456
+ setActionResult(name: string, serialized: SerializedActionResult): void {
457
+ const deserialized = deserializeActionResult(serialized);
458
+ recordAstroActionResult(name, deserialized, ctx);
459
+ const registered = registeredActions.get(name);
460
+ if (registered) {
461
+ recordAstroActionResult(
462
+ registered as unknown as (...args: unknown[]) => unknown,
463
+ deserialized,
464
+ ctx,
465
+ );
466
+ }
467
+ },
468
+ serializeActionResult,
469
+ deserializeActionResult,
470
+ };
471
+ }
472
+
473
+ let actionIdCounter = 0;
474
+
475
+ export function defineAction<
476
+ TOutput,
477
+ TAccept extends ActionAccept = undefined,
478
+ TInput = TAccept extends "form" ? FormData : undefined,
479
+ >(config: {
480
+ accept?: TAccept;
481
+ input?: SchemaValidator<TInput>;
482
+ handler: ActionHandler<TInput, TOutput>;
483
+ name?: string;
484
+ }): ActionClient<TOutput, TAccept, TInput> {
485
+ const actionName = config.name ?? `action_${++actionIdCounter}`;
486
+ const queryString = getActionQueryString(actionName);
487
+
488
+ const executeOrThrow = async (
489
+ rawInput?: unknown,
490
+ ): Promise<Awaited<TOutput>> => {
491
+ let preparedInput = rawInput;
492
+ if (
493
+ config.accept === "form" &&
494
+ config.input &&
495
+ rawInput instanceof FormData
496
+ ) {
497
+ preparedInput = formDataToObject(rawInput);
498
+ }
499
+ const parsedInput = config.input
500
+ ? await validateInput(config.input, preparedInput)
501
+ : (preparedInput as TInput);
502
+ const context = useAstro();
503
+ return await config.handler(parsedInput, context);
504
+ };
505
+
506
+ const client = async (
507
+ ...args: unknown[]
508
+ ): Promise<SafeResult<TInput, Awaited<TOutput>>> => {
509
+ let result: SafeResult<TInput, Awaited<TOutput>>;
510
+ try {
511
+ const data = await executeOrThrow(args[0]);
512
+ result = { data, error: undefined };
513
+ } catch (err) {
514
+ if (isInputError(err)) {
515
+ result = {
516
+ data: undefined,
517
+ error: err as ActionInputError<
518
+ TInput extends ErrorInferenceObject ? TInput : ErrorInferenceObject
519
+ >,
520
+ };
521
+ } else if (isActionError(err)) {
522
+ result = { data: undefined, error: err };
523
+ } else {
524
+ result = {
525
+ data: undefined,
526
+ error: new ActionError({
527
+ code: "INTERNAL_SERVER_ERROR",
528
+ message: err instanceof Error ? err.message : String(err),
529
+ stack: err instanceof Error ? err.stack : undefined,
530
+ }),
531
+ };
532
+ }
533
+ }
534
+ recordAstroActionResult(
535
+ actionClient as unknown as (...args: unknown[]) => unknown,
536
+ result,
537
+ );
538
+ recordAstroActionResult(actionName, result);
539
+ return result;
540
+ };
541
+
542
+ const actionClient = Object.assign(client, {
543
+ orThrow: (...args: unknown[]) => executeOrThrow(args[0]),
544
+ queryString,
545
+ toString: () => queryString,
546
+ }) as ActionClient<TOutput, TAccept, TInput>;
547
+
548
+ registeredActions.set(
549
+ actionName,
550
+ actionClient as unknown as ActionClient<unknown, ActionAccept, unknown>,
551
+ );
552
+
553
+ return actionClient;
554
+ }
555
+
556
+ export { z } from "./content";