@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1
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/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- package/src/unrenderable.ts +35 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// O(1) row selection primitive: zero WeakSet overhead per row.
|
|
2
2
|
|
|
3
3
|
import type { Owner, Signal } from './index'
|
|
4
|
-
import { effect, getOwner, onCleanup, signal } from './index'
|
|
4
|
+
import { effect, getOwner, isTracking, onCleanup, signal } from './index'
|
|
5
5
|
|
|
6
6
|
export interface Selector<K> {
|
|
7
7
|
is(key: K): boolean
|
|
@@ -9,8 +9,7 @@ export interface Selector<K> {
|
|
|
9
9
|
|
|
10
10
|
interface Entry {
|
|
11
11
|
s: Signal<boolean>
|
|
12
|
-
|
|
13
|
-
r: number
|
|
12
|
+
owners: Set<Owner>
|
|
14
13
|
}
|
|
15
14
|
|
|
16
15
|
export function selector<K>(source: () => K): Selector<K> {
|
|
@@ -34,19 +33,22 @@ export function selector<K>(source: () => K): Selector<K> {
|
|
|
34
33
|
|
|
35
34
|
return {
|
|
36
35
|
is(key: K): boolean {
|
|
36
|
+
const owner = getOwner()
|
|
37
|
+
if (owner === undefined && !isTracking())
|
|
38
|
+
return Object.is(current, key)
|
|
39
|
+
|
|
37
40
|
let entry = subs.get(key)
|
|
38
41
|
if (entry === undefined) {
|
|
39
|
-
entry = { s: signal(Object.is(current, key)),
|
|
42
|
+
entry = { s: signal(Object.is(current, key)), owners: new Set() }
|
|
40
43
|
subs.set(key, entry)
|
|
41
44
|
}
|
|
42
45
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
entry.o = owner
|
|
46
|
-
entry.r++
|
|
46
|
+
if (owner !== undefined && !entry.owners.has(owner)) {
|
|
47
|
+
entry.owners.add(owner)
|
|
47
48
|
const target = entry
|
|
48
49
|
onCleanup(() => {
|
|
49
|
-
|
|
50
|
+
target.owners.delete(owner)
|
|
51
|
+
if (target.owners.size === 0)
|
|
50
52
|
subs.delete(key)
|
|
51
53
|
})
|
|
52
54
|
}
|
package/src/reactivity/store.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
// Deep reactive proxy store (tree-shakable: 0 B if unused).
|
|
2
2
|
|
|
3
3
|
import type { Signal } from './index'
|
|
4
|
-
import { signal, untrack } from './index'
|
|
4
|
+
import { batch, isTracking, signal, untrack } from './index'
|
|
5
5
|
|
|
6
6
|
const RAW = Symbol('kay.store.raw')
|
|
7
7
|
const OWN_KEYS = Symbol('kay.store.keys')
|
|
8
8
|
|
|
9
|
+
// An array method that moves several entries writes each one in turn; batched, its readers see only the finished array.
|
|
10
|
+
const batchedMutators = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>(
|
|
11
|
+
(['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
|
|
12
|
+
const method = Array.prototype[name] as (...args: unknown[]) => unknown
|
|
13
|
+
return [name, function (this: unknown[], ...args: unknown[]) {
|
|
14
|
+
return batch(() => method.apply(this, args))
|
|
15
|
+
}]
|
|
16
|
+
}),
|
|
17
|
+
)
|
|
18
|
+
|
|
9
19
|
const proxyCache = new WeakMap<object, object>()
|
|
10
20
|
const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
|
|
11
21
|
|
|
@@ -18,6 +28,11 @@ function isPlain(value: unknown): value is Record<PropertyKey, unknown> {
|
|
|
18
28
|
return proto === Object.prototype || proto === null
|
|
19
29
|
}
|
|
20
30
|
|
|
31
|
+
// The target behind a store proxy, or the value itself.
|
|
32
|
+
function unwrap<T>(value: T): T {
|
|
33
|
+
return typeof value === 'object' && value !== null && RAW in value ? (value as Record<symbol, T>)[RAW]! : value
|
|
34
|
+
}
|
|
35
|
+
|
|
21
36
|
function getDep(target: object, key: PropertyKey): Signal<number> {
|
|
22
37
|
let map = depsCache.get(target)
|
|
23
38
|
if (map === undefined) {
|
|
@@ -35,7 +50,7 @@ function getDep(target: object, key: PropertyKey): Signal<number> {
|
|
|
35
50
|
function notifyKey(target: object, key: PropertyKey): void {
|
|
36
51
|
const dep = depsCache.get(target)?.get(key)
|
|
37
52
|
if (dep !== undefined)
|
|
38
|
-
dep.value
|
|
53
|
+
dep.value = dep.peek() + 1
|
|
39
54
|
}
|
|
40
55
|
|
|
41
56
|
function wrap<T extends object>(target: T): T {
|
|
@@ -47,16 +62,22 @@ function wrap<T extends object>(target: T): T {
|
|
|
47
62
|
get(obj, key, receiver) {
|
|
48
63
|
if (key === RAW)
|
|
49
64
|
return obj
|
|
50
|
-
|
|
65
|
+
const mutator = Array.isArray(obj) ? batchedMutators.get(key) : undefined
|
|
66
|
+
if (mutator !== undefined)
|
|
67
|
+
return mutator
|
|
68
|
+
if (isTracking()) {
|
|
69
|
+
getDep(obj, key).value
|
|
70
|
+
// A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
|
|
71
|
+
if (key === 'length' && Array.isArray(obj))
|
|
72
|
+
getDep(obj, OWN_KEYS).value
|
|
73
|
+
}
|
|
51
74
|
const value = Reflect.get(obj, key, receiver)
|
|
52
75
|
return isPlain(value) ? wrap(value) : value
|
|
53
76
|
},
|
|
54
77
|
set(obj, key, value, receiver) {
|
|
55
|
-
const rawValue =
|
|
56
|
-
? (value as Record<symbol, unknown>)[RAW]
|
|
57
|
-
: value
|
|
78
|
+
const rawValue = unwrap(value)
|
|
58
79
|
const had = Object.prototype.hasOwnProperty.call(obj, key)
|
|
59
|
-
const prev = Reflect.get(obj, key,
|
|
80
|
+
const prev = Reflect.get(obj, key, obj)
|
|
60
81
|
const prevLength = Array.isArray(obj) ? obj.length : 0
|
|
61
82
|
const ok = Reflect.set(obj, key, rawValue, receiver)
|
|
62
83
|
if (!had || !Object.is(prev, rawValue)) {
|
|
@@ -79,11 +100,15 @@ function wrap<T extends object>(target: T): T {
|
|
|
79
100
|
return ok
|
|
80
101
|
},
|
|
81
102
|
has(obj, key) {
|
|
82
|
-
|
|
103
|
+
if (key === RAW)
|
|
104
|
+
return true
|
|
105
|
+
if (isTracking())
|
|
106
|
+
getDep(obj, key).value
|
|
83
107
|
return Reflect.has(obj, key)
|
|
84
108
|
},
|
|
85
109
|
ownKeys(obj) {
|
|
86
|
-
|
|
110
|
+
if (isTracking())
|
|
111
|
+
getDep(obj, OWN_KEYS).value
|
|
87
112
|
return Reflect.ownKeys(obj)
|
|
88
113
|
},
|
|
89
114
|
})
|
|
@@ -103,9 +128,9 @@ export function snapshot<T>(value: T): T {
|
|
|
103
128
|
}
|
|
104
129
|
|
|
105
130
|
function cloneRaw<T>(value: T): T {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
131
|
+
const raw = unwrap(value)
|
|
132
|
+
if (typeof raw !== 'object' || raw === null)
|
|
133
|
+
return raw
|
|
109
134
|
if (Array.isArray(raw))
|
|
110
135
|
return raw.map(item => cloneRaw(item)) as unknown as T
|
|
111
136
|
if (isPlain(raw)) {
|
package/src/server/action.ts
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
// Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
|
|
2
2
|
|
|
3
3
|
import type { Cookies } from './cookies'
|
|
4
|
-
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
|
|
5
|
-
import {
|
|
4
|
+
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
|
|
5
|
+
import type { TrustProxy } from './security'
|
|
6
|
+
import { wantsJson } from './http'
|
|
7
|
+
import { isTrustedOrigin } from './security'
|
|
6
8
|
import { validateSchema } from './standard-schema'
|
|
7
9
|
|
|
8
10
|
export const ACTION_ERROR_COOKIE = '__kay_action_err'
|
|
9
11
|
|
|
12
|
+
const MAX_FLASH_COOKIE_BYTES = 3500
|
|
13
|
+
const MAX_FLASH_FIELD_CHARS = 512
|
|
14
|
+
const SENSITIVE_FIELD_RE = /password|passwd|pwd|secret|token|pin|cvv|cvc|iban|ssn|card|credit|auth|key|otp|code|routing|account|bank|tax/i
|
|
15
|
+
|
|
16
|
+
export interface ActionOptions {
|
|
17
|
+
/** Explicit allowlist of form field names permitted in the progressive-form validation error flash cookie. */
|
|
18
|
+
flashFields?: readonly string[] | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
10
21
|
export interface ActionErrorFlash {
|
|
11
22
|
action: string
|
|
12
23
|
error: string
|
|
@@ -21,9 +32,9 @@ export function getActionError(locals?: Record<string, unknown>): ActionErrorFla
|
|
|
21
32
|
export interface ActionContext {
|
|
22
33
|
request: Request
|
|
23
34
|
url: URL
|
|
24
|
-
params: Record<string, string>
|
|
25
35
|
cookies: Cookies
|
|
26
36
|
locals: Record<string, unknown>
|
|
37
|
+
ip?: string | undefined
|
|
27
38
|
redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
|
|
28
39
|
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
29
40
|
}
|
|
@@ -37,6 +48,7 @@ export interface ServerAction<Input, Output> {
|
|
|
37
48
|
readonly __kayAction: true
|
|
38
49
|
readonly url: string
|
|
39
50
|
readonly schema: StandardSchemaV1 | undefined
|
|
51
|
+
readonly flashFields: readonly string[] | undefined
|
|
40
52
|
readonly handler: (input: never, ctx: ActionContext) => Output | Response | Promise<Output | Response>
|
|
41
53
|
toString(): string
|
|
42
54
|
}
|
|
@@ -49,19 +61,23 @@ export function actionHash(relFile: string, exportName: string): string {
|
|
|
49
61
|
export function action<S extends StandardSchemaV1, Output>(
|
|
50
62
|
schema: S,
|
|
51
63
|
handler: (input: InferOutput<S>, ctx: ActionContext) => Output | Response | Promise<Output | Response>,
|
|
64
|
+
options?: ActionOptions,
|
|
52
65
|
): ServerAction<InferInput<S>, Exclude<Output, Response>>
|
|
53
66
|
export function action<Output>(
|
|
54
67
|
handler: (ctx: ActionContext) => Output | Response | Promise<Output | Response>,
|
|
68
|
+
options?: ActionOptions,
|
|
55
69
|
): ServerAction<void, Exclude<Output, Response>>
|
|
56
70
|
export function action(
|
|
57
71
|
schemaOrHandler: StandardSchemaV1 | ((ctx: ActionContext) => unknown),
|
|
58
|
-
|
|
72
|
+
maybeHandlerOrOpts?: ((input: never, ctx: ActionContext) => unknown) | ActionOptions,
|
|
73
|
+
maybeOpts?: ActionOptions,
|
|
59
74
|
): ServerAction<unknown, unknown> {
|
|
60
75
|
const hasSchema = typeof schemaOrHandler !== 'function'
|
|
61
76
|
const schema = hasSchema ? schemaOrHandler : undefined
|
|
62
77
|
const handler = hasSchema
|
|
63
|
-
?
|
|
78
|
+
? (maybeHandlerOrOpts as (input: never, ctx: ActionContext) => unknown)
|
|
64
79
|
: ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
|
|
80
|
+
const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
|
|
65
81
|
|
|
66
82
|
const fn = (async () => {
|
|
67
83
|
throw new Error('kay: server action cannot be called directly without a request context; invoke it from an island or via HTTP POST')
|
|
@@ -70,6 +86,7 @@ export function action(
|
|
|
70
86
|
Object.defineProperties(fn, {
|
|
71
87
|
__kayAction: { value: true, enumerable: false },
|
|
72
88
|
schema: { value: schema, enumerable: false },
|
|
89
|
+
flashFields: { value: options?.flashFields, enumerable: false },
|
|
73
90
|
handler: { value: handler, enumerable: false },
|
|
74
91
|
url: { value: '', writable: true, enumerable: true },
|
|
75
92
|
toString: {
|
|
@@ -87,45 +104,204 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
|
|
|
87
104
|
return typeof value === 'function' && (value as { __kayAction?: boolean }).__kayAction === true
|
|
88
105
|
}
|
|
89
106
|
|
|
90
|
-
async function parseActionBody(
|
|
91
|
-
const contentType =
|
|
107
|
+
async function parseActionBody(boundedReq: Request): Promise<unknown> {
|
|
108
|
+
const contentType = boundedReq.headers.get('content-type') ?? ''
|
|
92
109
|
if (contentType.includes('application/json'))
|
|
93
|
-
return
|
|
110
|
+
return boundedReq.json()
|
|
94
111
|
|
|
95
112
|
if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
for (const [key, val] of
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
113
|
+
// A Map then fromEntries makes every name an own property, `constructor` and `__proto__` included.
|
|
114
|
+
const fields = new Map<string, FormDataEntryValue | FormDataEntryValue[]>()
|
|
115
|
+
for (const [key, val] of (await boundedReq.formData()).entries()) {
|
|
116
|
+
const prev = fields.get(key)
|
|
117
|
+
if (prev === undefined) {
|
|
118
|
+
fields.set(key, val)
|
|
119
|
+
}
|
|
120
|
+
else if (Array.isArray(prev)) {
|
|
121
|
+
prev.push(val)
|
|
102
122
|
}
|
|
103
123
|
else {
|
|
104
|
-
|
|
124
|
+
fields.set(key, [prev, val])
|
|
105
125
|
}
|
|
106
126
|
}
|
|
107
|
-
return
|
|
127
|
+
return Object.fromEntries(fields)
|
|
108
128
|
}
|
|
109
129
|
|
|
110
130
|
return undefined
|
|
111
131
|
}
|
|
112
132
|
|
|
133
|
+
function isJsonBody(request: Request): boolean {
|
|
134
|
+
return (request.headers.get('content-type') ?? '').includes('application/json')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
|
|
138
|
+
function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy): URL | undefined {
|
|
139
|
+
const referer = request.headers.get('referer')
|
|
140
|
+
if (!referer)
|
|
141
|
+
return undefined
|
|
142
|
+
let refUrl: URL
|
|
143
|
+
try {
|
|
144
|
+
refUrl = new URL(referer)
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return undefined
|
|
148
|
+
}
|
|
149
|
+
return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy) ? refUrl : undefined
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function topLevelKey(issue: StandardSchemaIssue): string | undefined {
|
|
153
|
+
const seg = issue.path?.length === 1 ? issue.path[0] : undefined
|
|
154
|
+
const key = typeof seg === 'object' && seg !== null ? seg.key : seg
|
|
155
|
+
return typeof key === 'string' ? key : undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function setField(target: Record<string, unknown>, key: string, value: unknown): void {
|
|
159
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing top-level field is retried as an array, and the array is kept only where it clears that field's issue.
|
|
163
|
+
async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string, unknown>, failed: ValidationFailure): Promise<ValidationResult<unknown>> {
|
|
164
|
+
const retried = { ...body }
|
|
165
|
+
const wrapped: string[] = []
|
|
166
|
+
for (const issue of failed.issues) {
|
|
167
|
+
const key = topLevelKey(issue)
|
|
168
|
+
if (key === undefined || Array.isArray(retried[key]) || wrapped.includes(key))
|
|
169
|
+
continue
|
|
170
|
+
setField(retried, key, Object.hasOwn(body, key) ? [body[key]] : [])
|
|
171
|
+
wrapped.push(key)
|
|
172
|
+
}
|
|
173
|
+
if (wrapped.length === 0)
|
|
174
|
+
return failed
|
|
175
|
+
const second = await validateSchema(schema, retried)
|
|
176
|
+
if (second.ok)
|
|
177
|
+
return second
|
|
178
|
+
const stillFailing = new Set(second.issues.map(topLevelKey))
|
|
179
|
+
const kept = wrapped.filter(key => !stillFailing.has(key))
|
|
180
|
+
if (kept.length === 0)
|
|
181
|
+
return failed
|
|
182
|
+
for (const key of wrapped) {
|
|
183
|
+
if (kept.includes(key))
|
|
184
|
+
continue
|
|
185
|
+
if (Object.hasOwn(body, key))
|
|
186
|
+
setField(retried, key, body[key])
|
|
187
|
+
else
|
|
188
|
+
delete retried[key]
|
|
189
|
+
}
|
|
190
|
+
return kept.length === wrapped.length ? second : validateSchema(schema, retried)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function encodedFlashSize(flash: ActionErrorFlash): number {
|
|
194
|
+
return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function buildActionErrorFlash(
|
|
198
|
+
actionUrl: string,
|
|
199
|
+
fieldErrors: Record<string, string>,
|
|
200
|
+
rawBody: unknown,
|
|
201
|
+
flashFields?: readonly string[],
|
|
202
|
+
): string {
|
|
203
|
+
const safeErrors: Record<string, string> = {}
|
|
204
|
+
const base: ActionErrorFlash = {
|
|
205
|
+
action: actionUrl,
|
|
206
|
+
error: 'Validation failed',
|
|
207
|
+
fieldErrors: safeErrors,
|
|
208
|
+
}
|
|
209
|
+
for (const [k, msg] of Object.entries(fieldErrors)) {
|
|
210
|
+
const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
|
|
211
|
+
safeErrors[k] = trimmed
|
|
212
|
+
if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
|
|
213
|
+
delete safeErrors[k]
|
|
214
|
+
break
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const allowSet = flashFields !== undefined ? new Set(flashFields) : undefined
|
|
219
|
+
const values: Record<string, string> = {}
|
|
220
|
+
if (rawBody !== null && typeof rawBody === 'object') {
|
|
221
|
+
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
222
|
+
if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS)
|
|
223
|
+
continue
|
|
224
|
+
if (allowSet !== undefined) {
|
|
225
|
+
if (!allowSet.has(k))
|
|
226
|
+
continue
|
|
227
|
+
}
|
|
228
|
+
else if (SENSITIVE_FIELD_RE.test(k)) {
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
values[k] = v
|
|
232
|
+
const candidate: ActionErrorFlash = { ...base, values }
|
|
233
|
+
if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
|
|
234
|
+
delete values[k]
|
|
235
|
+
break
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const finalFlash: ActionErrorFlash = {
|
|
241
|
+
...base,
|
|
242
|
+
...(Object.keys(values).length > 0 ? { values } : {}),
|
|
243
|
+
}
|
|
244
|
+
return JSON.stringify(finalFlash)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
|
|
248
|
+
export async function invokeActionCore<I, O>(
|
|
249
|
+
act: ServerAction<I, O>,
|
|
250
|
+
input: I,
|
|
251
|
+
ctx: ActionContext,
|
|
252
|
+
): Promise<ActionResult<O>> {
|
|
253
|
+
let validated: unknown = input
|
|
254
|
+
if (act.schema !== undefined) {
|
|
255
|
+
const checked = await validateSchema(act.schema, input)
|
|
256
|
+
if (!checked.ok) {
|
|
257
|
+
return {
|
|
258
|
+
ok: false,
|
|
259
|
+
status: 400,
|
|
260
|
+
error: 'Validation failed',
|
|
261
|
+
fieldErrors: checked.fieldErrors,
|
|
262
|
+
issues: checked.issues,
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
validated = checked.value
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const result = await act.handler(validated as never, ctx)
|
|
269
|
+
if (result instanceof Response) {
|
|
270
|
+
if (result.status >= 300 && result.status < 400)
|
|
271
|
+
return { ok: true, data: result as unknown as O }
|
|
272
|
+
const ok = result.status >= 200 && result.status < 300
|
|
273
|
+
const ct = result.headers.get('content-type') ?? ''
|
|
274
|
+
if (ct.includes('application/json')) {
|
|
275
|
+
try {
|
|
276
|
+
const body = await result.clone().json() as Record<string, unknown>
|
|
277
|
+
if (typeof body === 'object' && body !== null && 'ok' in body)
|
|
278
|
+
return body as unknown as ActionResult<O>
|
|
279
|
+
return ok
|
|
280
|
+
? { ok: true, data: body as O }
|
|
281
|
+
: {
|
|
282
|
+
ok: false,
|
|
283
|
+
status: result.status,
|
|
284
|
+
error: typeof body.error === 'string' ? body.error : result.statusText,
|
|
285
|
+
...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
catch {}
|
|
289
|
+
}
|
|
290
|
+
return ok
|
|
291
|
+
? { ok: true, data: undefined as O }
|
|
292
|
+
: { ok: false, status: result.status, error: (await result.clone().text().catch(() => '')) || result.statusText }
|
|
293
|
+
}
|
|
294
|
+
return { ok: true, data: result as O }
|
|
295
|
+
}
|
|
296
|
+
|
|
113
297
|
export async function executeAction(
|
|
114
298
|
act: ServerAction<unknown, unknown>,
|
|
115
299
|
request: Request,
|
|
116
300
|
ctx: ActionContext,
|
|
117
301
|
trustedOrigins?: ReadonlySet<string>,
|
|
302
|
+
trustProxy: TrustProxy = false,
|
|
118
303
|
): Promise<Response> {
|
|
119
|
-
const
|
|
120
|
-
if (!originCheck.ok) {
|
|
121
|
-
return Response.json(
|
|
122
|
-
{ ok: false, status: 403, error: originCheck.reason },
|
|
123
|
-
{ status: 403 },
|
|
124
|
-
)
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const wantsJson = (request.headers.get('accept') ?? '').includes('application/json')
|
|
128
|
-
|| (request.headers.get('content-type') ?? '').includes('application/json')
|
|
304
|
+
const json = wantsJson(request)
|
|
129
305
|
|
|
130
306
|
let input: unknown
|
|
131
307
|
if (act.schema !== undefined) {
|
|
@@ -137,41 +313,19 @@ export async function executeAction(
|
|
|
137
313
|
return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
|
|
138
314
|
}
|
|
139
315
|
|
|
140
|
-
|
|
316
|
+
let checked = await validateSchema(act.schema, rawBody)
|
|
317
|
+
if (!checked.ok && !isJsonBody(request) && rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody))
|
|
318
|
+
checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
|
|
141
319
|
if (!checked.ok) {
|
|
142
|
-
// Zero-JS progressive HTML <form> submit: flash fieldErrors + submitted
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
refUrl = undefined
|
|
152
|
-
}
|
|
153
|
-
if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins)) {
|
|
154
|
-
const values: Record<string, string> = {}
|
|
155
|
-
if (rawBody !== null && typeof rawBody === 'object') {
|
|
156
|
-
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
157
|
-
if (typeof v === 'string' && !/password|secret|token/i.test(k) && v.length <= 512)
|
|
158
|
-
values[k] = v
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
const flash: ActionErrorFlash = {
|
|
162
|
-
action: act.url,
|
|
163
|
-
error: 'Validation failed',
|
|
164
|
-
fieldErrors: checked.fieldErrors,
|
|
165
|
-
...(Object.keys(values).length > 0 ? { values } : {}),
|
|
166
|
-
}
|
|
167
|
-
ctx.cookies.set(ACTION_ERROR_COOKIE, JSON.stringify(flash), {
|
|
168
|
-
httpOnly: true,
|
|
169
|
-
sameSite: 'lax',
|
|
170
|
-
maxAge: 60,
|
|
171
|
-
})
|
|
172
|
-
return Response.redirect(refUrl.href, 303)
|
|
173
|
-
}
|
|
174
|
-
}
|
|
320
|
+
// Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
|
|
321
|
+
const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
|
|
322
|
+
if (back !== undefined) {
|
|
323
|
+
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields), {
|
|
324
|
+
httpOnly: true,
|
|
325
|
+
sameSite: 'lax',
|
|
326
|
+
maxAge: 60,
|
|
327
|
+
})
|
|
328
|
+
return new Response(null, { status: 303, headers: { location: back.href } })
|
|
175
329
|
}
|
|
176
330
|
return Response.json(
|
|
177
331
|
{ ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
|
|
@@ -185,20 +339,9 @@ export async function executeAction(
|
|
|
185
339
|
if (result instanceof Response)
|
|
186
340
|
return result
|
|
187
341
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
let refUrl: URL | undefined
|
|
192
|
-
try {
|
|
193
|
-
refUrl = new URL(referer)
|
|
194
|
-
}
|
|
195
|
-
catch {
|
|
196
|
-
refUrl = undefined
|
|
197
|
-
}
|
|
198
|
-
if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins))
|
|
199
|
-
return Response.redirect(refUrl.href, 303)
|
|
200
|
-
}
|
|
201
|
-
}
|
|
342
|
+
const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
|
|
343
|
+
if (back !== undefined)
|
|
344
|
+
return new Response(null, { status: 303, headers: { location: back.href } })
|
|
202
345
|
|
|
203
346
|
return Response.json({ ok: true, data: result }, { status: 200 })
|
|
204
347
|
}
|