@sveltejs/kit 3.0.0-next.1 → 3.0.0-next.11

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.
Files changed (144) hide show
  1. package/package.json +33 -21
  2. package/src/constants.js +2 -0
  3. package/src/core/adapt/builder.js +32 -49
  4. package/src/core/adapt/index.js +1 -4
  5. package/src/core/config/index.js +137 -71
  6. package/src/core/config/options.js +236 -244
  7. package/src/core/config/types.d.ts +1 -1
  8. package/src/core/env.js +121 -5
  9. package/src/core/generate_manifest/index.js +12 -15
  10. package/src/core/postbuild/analyse.js +7 -19
  11. package/src/core/postbuild/crawl.js +22 -6
  12. package/src/core/postbuild/fallback.js +2 -1
  13. package/src/core/postbuild/prerender.js +114 -48
  14. package/src/core/postbuild/queue.js +2 -1
  15. package/src/core/sync/create_manifest_data/index.js +53 -50
  16. package/src/core/sync/sync.js +0 -2
  17. package/src/core/sync/write_client_manifest.js +8 -15
  18. package/src/core/sync/write_env.js +2 -1
  19. package/src/core/sync/write_non_ambient.js +12 -9
  20. package/src/core/sync/write_server.js +14 -15
  21. package/src/core/sync/write_tsconfig.js +16 -8
  22. package/src/core/sync/write_tsconfig_test/package.json +7 -0
  23. package/src/core/sync/write_types/index.js +28 -24
  24. package/src/core/utils.js +30 -5
  25. package/src/exports/env/index.js +77 -0
  26. package/src/exports/hooks/index.js +3 -9
  27. package/src/exports/hooks/sequence.js +3 -2
  28. package/src/exports/index.js +35 -13
  29. package/src/exports/internal/client.js +5 -0
  30. package/src/exports/internal/env.js +8 -5
  31. package/src/exports/internal/index.js +1 -90
  32. package/src/exports/internal/{event.js → server/event.js} +1 -2
  33. package/src/exports/internal/server/index.js +33 -0
  34. package/src/exports/internal/shared.js +89 -0
  35. package/src/exports/node/index.js +62 -15
  36. package/src/exports/params.js +68 -0
  37. package/src/exports/public.d.ts +363 -189
  38. package/src/exports/url.js +86 -0
  39. package/src/exports/vite/build/build_server.js +53 -59
  40. package/src/exports/vite/build/remote.js +18 -11
  41. package/src/exports/vite/build/utils.js +0 -8
  42. package/src/exports/vite/dev/index.js +92 -50
  43. package/src/exports/vite/index.js +903 -681
  44. package/src/exports/vite/module_ids.js +0 -2
  45. package/src/exports/vite/preview/index.js +32 -24
  46. package/src/exports/vite/static_analysis/index.js +2 -4
  47. package/src/exports/vite/static_analysis/types.d.ts +14 -0
  48. package/src/exports/vite/utils.js +40 -35
  49. package/src/runtime/app/env/internal.js +4 -4
  50. package/src/runtime/app/env/types.d.ts +1 -1
  51. package/src/runtime/app/environment/index.js +3 -3
  52. package/src/runtime/app/forms.js +24 -7
  53. package/src/runtime/app/paths/client.js +4 -10
  54. package/src/runtime/app/paths/internal/client.js +4 -2
  55. package/src/runtime/app/paths/internal/server.js +2 -23
  56. package/src/runtime/app/paths/public.d.ts +0 -28
  57. package/src/runtime/app/paths/server.js +10 -6
  58. package/src/runtime/app/server/index.js +1 -1
  59. package/src/runtime/app/server/remote/command.js +0 -3
  60. package/src/runtime/app/server/remote/form.js +27 -15
  61. package/src/runtime/app/server/remote/prerender.js +29 -36
  62. package/src/runtime/app/server/remote/query.js +101 -99
  63. package/src/runtime/app/server/remote/requested.js +22 -14
  64. package/src/runtime/app/server/remote/shared.js +30 -26
  65. package/src/runtime/app/state/client.js +1 -2
  66. package/src/runtime/app/stores.js +13 -76
  67. package/src/runtime/client/bundle.js +1 -1
  68. package/src/runtime/client/client-entry.js +3 -0
  69. package/src/runtime/client/client.js +411 -318
  70. package/src/runtime/client/entry.js +24 -3
  71. package/src/runtime/client/fetcher.js +3 -2
  72. package/src/runtime/client/ndjson.js +6 -33
  73. package/src/runtime/client/payload.js +17 -0
  74. package/src/runtime/client/remote-functions/cache.svelte.js +3 -1
  75. package/src/runtime/client/remote-functions/command.svelte.js +7 -32
  76. package/src/runtime/client/remote-functions/form.svelte.js +183 -112
  77. package/src/runtime/client/remote-functions/prerender.svelte.js +29 -8
  78. package/src/runtime/client/remote-functions/query/index.js +7 -14
  79. package/src/runtime/client/remote-functions/query/instance.svelte.js +63 -18
  80. package/src/runtime/client/remote-functions/query/proxy.js +3 -3
  81. package/src/runtime/client/remote-functions/query-batch.svelte.js +60 -68
  82. package/src/runtime/client/remote-functions/query-live/instance.svelte.js +60 -18
  83. package/src/runtime/client/remote-functions/query-live/iterator.js +36 -55
  84. package/src/runtime/client/remote-functions/shared.svelte.js +88 -62
  85. package/src/runtime/client/sse.js +32 -0
  86. package/src/runtime/client/state.svelte.js +65 -49
  87. package/src/runtime/client/stream.js +39 -0
  88. package/src/runtime/client/types.d.ts +11 -7
  89. package/src/runtime/client/utils.js +0 -96
  90. package/src/runtime/components/root.svelte +66 -0
  91. package/src/runtime/env/dynamic/private.js +7 -0
  92. package/src/runtime/env/dynamic/public.js +7 -0
  93. package/src/runtime/env/static/private.js +6 -0
  94. package/src/runtime/env/static/public.js +6 -0
  95. package/src/runtime/form-utils.js +100 -22
  96. package/src/runtime/server/cookie.js +69 -52
  97. package/src/runtime/server/csrf.js +65 -0
  98. package/src/runtime/server/data/index.js +15 -19
  99. package/src/runtime/server/env_module.js +0 -5
  100. package/src/runtime/server/errors.js +135 -0
  101. package/src/runtime/server/fetch.js +1 -1
  102. package/src/runtime/server/index.js +22 -12
  103. package/src/runtime/server/internal.js +25 -0
  104. package/src/runtime/server/page/actions.js +43 -27
  105. package/src/runtime/server/page/data_serializer.js +10 -10
  106. package/src/runtime/server/page/index.js +12 -17
  107. package/src/runtime/server/page/load_data.js +2 -2
  108. package/src/runtime/server/page/render.js +114 -193
  109. package/src/runtime/server/page/respond_with_error.js +11 -11
  110. package/src/runtime/server/page/server_routing.js +27 -18
  111. package/src/runtime/server/remote-functions.js +596 -0
  112. package/src/runtime/server/respond.js +100 -68
  113. package/src/runtime/server/sourcemaps.js +183 -0
  114. package/src/runtime/server/utils.js +2 -134
  115. package/src/runtime/shared.js +83 -13
  116. package/src/runtime/telemetry/otel.js +1 -1
  117. package/src/runtime/types.d.ts +8 -0
  118. package/src/types/ambient-private.d.ts +2 -0
  119. package/src/types/ambient.d.ts +10 -5
  120. package/src/types/global-private.d.ts +13 -25
  121. package/src/types/internal.d.ts +95 -80
  122. package/src/types/private.d.ts +41 -1
  123. package/src/utils/error.js +24 -4
  124. package/src/utils/escape.js +9 -25
  125. package/src/utils/features.js +1 -1
  126. package/src/utils/fork.js +7 -2
  127. package/src/utils/import.js +6 -1
  128. package/src/utils/imports.js +83 -0
  129. package/src/utils/mime.js +9 -0
  130. package/src/utils/page_nodes.js +3 -5
  131. package/src/utils/params.js +66 -0
  132. package/src/utils/routing.js +90 -44
  133. package/src/utils/shared-iterator.js +5 -0
  134. package/src/utils/streaming.js +14 -4
  135. package/src/utils/url.js +20 -2
  136. package/src/version.js +1 -1
  137. package/types/index.d.ts +537 -557
  138. package/types/index.d.ts.map +24 -39
  139. package/src/core/sync/write_root.js +0 -148
  140. package/src/exports/internal/server.js +0 -22
  141. package/src/runtime/server/remote.js +0 -457
  142. package/src/runtime/shared-server.js +0 -7
  143. package/src/types/synthetic/$lib.md +0 -5
  144. /package/src/exports/internal/{remote-functions.js → server/remote-functions.js} +0 -0
@@ -0,0 +1,596 @@
1
+ /** @import { ActionResult, RemoteForm, RequestEvent, SSRManifest } from '@sveltejs/kit' */
2
+ /** @import { RemoteFormInternals, RemoteFunctionData, RemoteFunctionResponse, RemoteInternals, RequestState, SSROptions } from 'types' */
3
+
4
+ import { json, error } from '@sveltejs/kit';
5
+ import { Redirect, SvelteKitError } from '@sveltejs/kit/internal';
6
+ import { with_request_store, merge_tracing } from '@sveltejs/kit/internal/server';
7
+ import { app_dir, base } from '$app/paths/internal/server';
8
+ import { is_form_content_type } from '../../utils/http.js';
9
+ import { create_remote_key, parse_remote_arg, split_remote_key, stringify } from '../shared.js';
10
+ import { handle_error_and_jsonify } from './errors.js';
11
+ import { normalize_error } from '../../utils/error.js';
12
+ import { check_incorrect_fail_use } from './page/actions.js';
13
+ import { DEV } from 'esm-env';
14
+ import { record_span } from '../telemetry/record_span.js';
15
+ import { deserialize_binary_form } from '../form-utils.js';
16
+
17
+ /**
18
+ * How long (in milliseconds) to wait after the last message was sent before
19
+ * sending a `: keep-alive` SSE comment, to prevent proxies/load balancers with
20
+ * an idle timeout from closing an otherwise-quiet `query.live` connection.
21
+ */
22
+ const KEEP_ALIVE_INTERVAL = 30_000;
23
+
24
+ /** @type {typeof handle_remote_call_internal} */
25
+ export async function handle_remote_call(event, state, options, manifest, id) {
26
+ return record_span({
27
+ name: 'sveltekit.remote.call',
28
+ attributes: {
29
+ 'sveltekit.remote.call.id': id
30
+ },
31
+ fn: (current) => {
32
+ const traced_event = merge_tracing(event, current);
33
+ return with_request_store({ event: traced_event, state }, () =>
34
+ handle_remote_call_internal(traced_event, state, options, manifest, id)
35
+ );
36
+ }
37
+ });
38
+ }
39
+
40
+ /**
41
+ * @param {RequestEvent} event
42
+ * @param {RequestState} state
43
+ * @param {SSROptions} options
44
+ * @param {SSRManifest} manifest
45
+ * @param {string} id
46
+ */
47
+ async function handle_remote_call_internal(event, state, options, manifest, id) {
48
+ const [hash, name, additional_args] = id.split('/');
49
+ const remotes = manifest._.remotes;
50
+
51
+ if (!Object.hasOwn(remotes, hash)) error(404);
52
+
53
+ const module = await remotes[hash]();
54
+ const fn = Object.hasOwn(module.default, name) ? module.default[name] : undefined;
55
+
56
+ if (!fn) error(404);
57
+
58
+ /** @type {RemoteInternals} */
59
+ const internals = fn.__;
60
+ const transport = options.hooks.transport;
61
+
62
+ event.tracing.current.setAttributes({
63
+ 'sveltekit.remote.call.type': internals.type,
64
+ 'sveltekit.remote.call.name': internals.name
65
+ });
66
+
67
+ /** @type {HeadersInit | undefined} */
68
+ const headers = state.prerendering ? undefined : { 'cache-control': 'private, no-store' };
69
+
70
+ try {
71
+ /** @type {RemoteFunctionData} */
72
+ const data = {};
73
+
74
+ switch (internals.type) {
75
+ case 'query_live': {
76
+ if (event.request.method !== 'GET') {
77
+ throw new SvelteKitError(
78
+ 405,
79
+ 'Method Not Allowed',
80
+ `\`query.live\` functions must be invoked via GET request, not ${event.request.method}`
81
+ );
82
+ }
83
+
84
+ const payload = /** @type {string} */ (
85
+ new URL(event.request.url).searchParams.get('payload')
86
+ );
87
+
88
+ const generator = internals.run(event, state, parse_remote_arg(payload, transport));
89
+
90
+ const encoder = new TextEncoder();
91
+
92
+ let closed = false;
93
+
94
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
95
+ let keep_alive;
96
+
97
+ /**
98
+ * (Re)schedule the keep-alive comment. Called whenever a message is sent, so
99
+ * that a keep-alive is only emitted once `KEEP_ALIVE_INTERVAL` has elapsed
100
+ * without any other activity.
101
+ * @param {ReadableStreamDefaultController} controller
102
+ */
103
+ function schedule_keep_alive(controller) {
104
+ clearTimeout(keep_alive);
105
+ keep_alive = setTimeout(() => {
106
+ if (closed || event.request.signal.aborted) return;
107
+ // SSE comments (lines starting with `:`) are ignored by the client
108
+ controller.enqueue(encoder.encode(': keep-alive\n\n'));
109
+ schedule_keep_alive(controller);
110
+ }, KEEP_ALIVE_INTERVAL);
111
+ }
112
+
113
+ /**
114
+ * @param {ReadableStreamDefaultController} controller
115
+ * @param {any} payload
116
+ */
117
+ function send(controller, payload) {
118
+ controller.enqueue(encoder.encode('data: ' + JSON.stringify(payload) + '\n\n'));
119
+ schedule_keep_alive(controller);
120
+ }
121
+
122
+ /** @type {string | undefined} */
123
+ let result = undefined;
124
+
125
+ async function cancel() {
126
+ if (closed) return;
127
+ closed = true;
128
+ clearTimeout(keep_alive);
129
+ await generator.return(undefined);
130
+ }
131
+
132
+ event.request.signal.addEventListener('abort', cancel, { once: true });
133
+
134
+ return new Response(
135
+ new ReadableStream({
136
+ start(controller) {
137
+ schedule_keep_alive(controller);
138
+ },
139
+ async pull(controller) {
140
+ if (event.request.signal.aborted) {
141
+ await cancel();
142
+ controller.close();
143
+ return;
144
+ }
145
+
146
+ try {
147
+ while (true) {
148
+ const { value, done } = await generator.next();
149
+
150
+ if (done) {
151
+ await cancel();
152
+ controller.close();
153
+ return;
154
+ }
155
+
156
+ // only send changed data
157
+ if (result !== (result = stringify(value, transport))) {
158
+ send(controller, {
159
+ type: 'result',
160
+ result
161
+ });
162
+
163
+ return;
164
+ }
165
+ }
166
+ } catch (error) {
167
+ if (!event.request.signal.aborted) {
168
+ if (error instanceof Redirect) {
169
+ send(controller, {
170
+ type: 'redirect',
171
+ location: error.location
172
+ });
173
+ } else {
174
+ const transformed = await handle_error_and_jsonify(
175
+ event,
176
+ state,
177
+ options,
178
+ error
179
+ );
180
+
181
+ send(controller, {
182
+ type: 'error',
183
+ error: transformed
184
+ });
185
+ }
186
+ }
187
+
188
+ await cancel();
189
+ controller.close();
190
+ }
191
+ },
192
+ cancel
193
+ }),
194
+ {
195
+ headers: {
196
+ 'cache-control': 'private, no-store',
197
+ 'content-type': 'text/event-stream'
198
+ }
199
+ }
200
+ );
201
+ }
202
+
203
+ case 'query_batch': {
204
+ if (event.request.method !== 'POST') {
205
+ throw new SvelteKitError(
206
+ 405,
207
+ 'Method Not Allowed',
208
+ `\`query.batch\` functions must be invoked via POST request, not ${event.request.method}`
209
+ );
210
+ }
211
+
212
+ /** @type {{ payloads: string[] }} */
213
+ const { payloads } = await event.request.json();
214
+
215
+ const args = await Promise.all(
216
+ payloads.map((payload) => parse_remote_arg(payload, transport))
217
+ );
218
+
219
+ data._ = await with_request_store({ event, state }, () => internals.run(args, options));
220
+
221
+ break;
222
+ }
223
+
224
+ case 'form': {
225
+ if (event.request.method !== 'POST') {
226
+ throw new SvelteKitError(
227
+ 405,
228
+ 'Method Not Allowed',
229
+ `\`form\` functions must be invoked via POST request, not ${event.request.method}`
230
+ );
231
+ }
232
+
233
+ if (!is_form_content_type(event.request)) {
234
+ throw new SvelteKitError(
235
+ 415,
236
+ 'Unsupported Media Type',
237
+ `\`form\` functions expect form-encoded data — received ${event.request.headers.get(
238
+ 'content-type'
239
+ )}`
240
+ );
241
+ }
242
+
243
+ const { data: input, meta, form_data } = await deserialize_binary_form(event.request);
244
+ state.remote.requested = create_requested_map(meta.remote_refreshes);
245
+
246
+ // If this is a keyed form instance (created via form.for(key)), add the key to the form data (unless already set)
247
+ // Note that additional_args will only be set if the form is not enhanced, as enhanced forms transfer the key inside `data`.
248
+ if (additional_args && !('id' in input)) {
249
+ input.id = JSON.parse(decodeURIComponent(additional_args));
250
+ }
251
+
252
+ const fn = internals.fn;
253
+ data._ = await with_request_store(
254
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
255
+ () => fn(input, meta, form_data)
256
+ );
257
+
258
+ if (data._.issues) {
259
+ // special case — don't serialize refreshes/reconnects
260
+ return json(
261
+ /** @type {RemoteFunctionResponse} */ ({
262
+ type: 'result',
263
+ data: stringify(data, transport)
264
+ }),
265
+ { headers }
266
+ );
267
+ }
268
+
269
+ break;
270
+ }
271
+
272
+ case 'command': {
273
+ /** @type {{ payload: string, refreshes?: string[] }} */
274
+ const { payload, refreshes } = await event.request.json();
275
+ state.remote.requested = create_requested_map(refreshes);
276
+ const arg = parse_remote_arg(payload, transport);
277
+
278
+ data._ = await with_request_store(
279
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
280
+ () => fn(arg)
281
+ );
282
+
283
+ break;
284
+ }
285
+
286
+ case 'prerender': {
287
+ data._ = await with_request_store({ event, state }, () =>
288
+ fn(parse_remote_arg(additional_args, transport))
289
+ );
290
+
291
+ break;
292
+ }
293
+
294
+ case 'query': {
295
+ const payload = /** @type {string} */ (
296
+ // new URL(...) necessary because we're hiding the URL from the user in the event object
297
+ new URL(event.request.url).searchParams.get('payload')
298
+ );
299
+
300
+ data._ = await with_request_store({ event, state }, () =>
301
+ fn(parse_remote_arg(payload, transport))
302
+ );
303
+
304
+ break;
305
+ }
306
+ }
307
+
308
+ await collect_remote_data(data, event, state, options);
309
+
310
+ return json(
311
+ /** @type {RemoteFunctionResponse} */ ({
312
+ type: 'result',
313
+ data: stringify(data, transport)
314
+ }),
315
+ { headers }
316
+ );
317
+ } catch (error) {
318
+ if (error instanceof Redirect) {
319
+ const data = await collect_remote_data({ redirect: error.location }, event, state, options);
320
+
321
+ return json(
322
+ /** @type {RemoteFunctionResponse} */ ({
323
+ type: 'result',
324
+ data: stringify(data, transport)
325
+ }),
326
+ { headers }
327
+ );
328
+ }
329
+
330
+ const transformed = await handle_error_and_jsonify(event, state, options, error);
331
+
332
+ return json(
333
+ /** @type {RemoteFunctionResponse} */ ({
334
+ type: 'error',
335
+ error: transformed
336
+ }),
337
+ {
338
+ // By setting a non-200 during prerendering we fail the prerender process (unless handleHttpError handles it).
339
+ // Errors at runtime will be passed to the client and are handled there
340
+ status: state.prerendering ? transformed.status : undefined,
341
+ headers: {
342
+ 'cache-control': 'private, no-store'
343
+ }
344
+ }
345
+ );
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Collects all the query/prerender data that was retrieved
351
+ * during the request and adds it to `data`
352
+ * @param {RemoteFunctionData} data
353
+ * @param {RequestEvent} event
354
+ * @param {RequestState} state
355
+ * @param {SSROptions} options
356
+ */
357
+ export async function collect_remote_data(data, event, state, options) {
358
+ /**
359
+ *
360
+ * @param {unknown} error
361
+ * @returns {Promise<App.Error>}
362
+ */
363
+ function convert_error(error) {
364
+ // TODO 4.0 remove the `Promise.resolve(...)`
365
+ return Promise.resolve(handle_error_and_jsonify(event, state, options, error));
366
+ }
367
+
368
+ /** @type {Promise<any>[]} */
369
+ const promises = [];
370
+
371
+ if (state.remote.explicit) {
372
+ for (const [remote_key, { internals, fn }] of state.remote.explicit) {
373
+ // there were explicit refreshes/reconnects (via `refresh()`/`set()`/`reconnect()`),
374
+ // so the client should apply these single-flight updates instead of calling `invalidateAll()`
375
+ data.r = true;
376
+
377
+ const type = /** @type {'p' | 'q' | 'l'} */ (
378
+ internals.type === 'query_live' ? 'l' : internals.type[0]
379
+ );
380
+
381
+ // `fn` is deferred until now so the query runs after any state mutations
382
+ // in the command/form body. If the query was re-awaited in the meantime,
383
+ // `fn` returns the existing (fresh) cache entry rather than re-running.
384
+ // Kick off the query immediately and collect the promise so that multiple
385
+ // explicit refreshes run concurrently rather than serially.
386
+ const promise = fn();
387
+
388
+ promises.push(
389
+ promise.then(
390
+ (v) => {
391
+ ((data[type] ??= {})[remote_key] ??= {}).v = v;
392
+ },
393
+ async (e) => {
394
+ if (e instanceof Redirect) {
395
+ // already handled elsewhere
396
+ return;
397
+ }
398
+
399
+ ((data[type] ??= {})[remote_key] ??= {}).e = await convert_error(e);
400
+ }
401
+ )
402
+ );
403
+ }
404
+ }
405
+
406
+ await Promise.all(promises);
407
+
408
+ if (state.remote.implicit) {
409
+ for (const [internals, record] of state.remote.implicit) {
410
+ // Private (non-exported) remote functions have no `id` and must never be
411
+ // serialized into the response — otherwise their (potentially private) result
412
+ // would be shipped to the client under a malformed `undefined/...` key.
413
+ if (!internals.id) continue;
414
+
415
+ for (const key in record) {
416
+ // form outputs are registered under the client-side action id directly
417
+ const remote_key = internals.type === 'form' ? key : create_remote_key(internals.id, key);
418
+
419
+ const type = /** @type {'p' | 'q' | 'l' | 'f'} */ (
420
+ internals.type === 'query_live' ? 'l' : internals.type[0]
421
+ );
422
+
423
+ const promise = state.remote.data?.get(internals)?.[key] ?? record[key]();
424
+
425
+ // If the promise is still pending (e.g. the query was rendered in its loading
426
+ // state during SSR), omit it from the payload entirely so that the client
427
+ // fetches it itself — an entry without `v`/`e` would hydrate as `undefined`.
428
+ let resolved = true;
429
+
430
+ await Promise.race([
431
+ Promise.resolve(promise).then(
432
+ (v) => {
433
+ if (resolved) {
434
+ ((data[type] ??= {})[remote_key] ??= {}).v = v;
435
+ }
436
+ },
437
+ (e) => {
438
+ if (e instanceof Redirect) {
439
+ // already handled elsewhere
440
+ return;
441
+ }
442
+
443
+ if (resolved) {
444
+ promises.push(
445
+ convert_error(e).then((e) => {
446
+ ((data[type] ??= {})[remote_key] ??= {}).e = e;
447
+ })
448
+ );
449
+ }
450
+ }
451
+ ),
452
+ Promise.resolve().then(() => (resolved = false))
453
+ ]);
454
+ }
455
+ }
456
+ }
457
+
458
+ await Promise.all(promises);
459
+
460
+ return data;
461
+ }
462
+
463
+ /**
464
+ * @param {string[] | undefined} refreshes
465
+ */
466
+ function create_requested_map(refreshes) {
467
+ /** @type {Map<string, string[]>} */
468
+ const requested = new Map();
469
+
470
+ for (const key of refreshes ?? []) {
471
+ const parts = split_remote_key(key);
472
+
473
+ const existing = requested.get(parts.id);
474
+
475
+ if (existing) {
476
+ existing.push(parts.payload);
477
+ } else {
478
+ requested.set(parts.id, [parts.payload]);
479
+ }
480
+ }
481
+
482
+ return requested;
483
+ }
484
+
485
+ /** @type {typeof handle_remote_form_post_internal} */
486
+ export async function handle_remote_form_post(event, state, manifest, id) {
487
+ return record_span({
488
+ name: 'sveltekit.remote.form.post',
489
+ attributes: {
490
+ 'sveltekit.remote.form.post.id': id
491
+ },
492
+ fn: (current) => {
493
+ const traced_event = merge_tracing(event, current);
494
+ return with_request_store({ event: traced_event, state }, () =>
495
+ handle_remote_form_post_internal(traced_event, state, manifest, id)
496
+ );
497
+ }
498
+ });
499
+ }
500
+
501
+ /**
502
+ * @param {RequestEvent} event
503
+ * @param {RequestState} state
504
+ * @param {SSRManifest} manifest
505
+ * @param {string} id
506
+ * @returns {Promise<ActionResult>}
507
+ */
508
+ async function handle_remote_form_post_internal(event, state, manifest, id) {
509
+ // `hash` and `name` can never contain a `/`, but the JSON-stringified key of a
510
+ // keyed (`form.for(key)`) instance can — rejoin the remaining segments
511
+ const [hash, name, ...rest] = id.split('/');
512
+ const action_id = rest.join('/');
513
+ const remotes = manifest._.remotes;
514
+ const module = Object.hasOwn(remotes, hash) ? await remotes[hash]() : undefined;
515
+
516
+ let form = /** @type {RemoteForm<any, any>} */ (
517
+ module && Object.hasOwn(module.default, name) ? module.default[name] : undefined
518
+ );
519
+
520
+ if (!form) {
521
+ event.setHeaders({
522
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
523
+ // "The server must generate an Allow header field in a 405 status code response"
524
+ allow: 'GET'
525
+ });
526
+ return {
527
+ type: 'error',
528
+ // We're lying a bit with the types here; this will be transformed into a proper App.Error object later
529
+ error: new SvelteKitError(
530
+ 405,
531
+ 'Method Not Allowed',
532
+ `POST method not allowed. No form actions exist for ${DEV ? `the page at ${event.route.id}` : 'this page'}`
533
+ )
534
+ };
535
+ }
536
+
537
+ if (action_id) {
538
+ // @ts-expect-error
539
+ form = with_request_store({ event, state }, () => form.for(JSON.parse(action_id)));
540
+ }
541
+
542
+ try {
543
+ const fn = /** @type {RemoteFormInternals} */ (/** @type {any} */ (form).__).fn;
544
+
545
+ const { data, meta, form_data } = await deserialize_binary_form(event.request);
546
+
547
+ if (action_id && !('id' in data)) {
548
+ data.id = JSON.parse(decodeURIComponent(action_id));
549
+ }
550
+
551
+ await with_request_store(
552
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
553
+ () => fn(data, meta, form_data)
554
+ );
555
+
556
+ // We don't want the data to appear on `let { form } = $props()`, which is why we're not returning it.
557
+ // It is instead available on `myForm.result`, setting of which happens within the remote `form` function.
558
+ return {
559
+ type: 'success',
560
+ status: 200
561
+ };
562
+ } catch (e) {
563
+ const err = normalize_error(e);
564
+
565
+ if (err instanceof Redirect) {
566
+ return {
567
+ type: 'redirect',
568
+ status: err.status,
569
+ location: err.location
570
+ };
571
+ }
572
+
573
+ return {
574
+ type: 'error',
575
+ // @ts-expect-error We're lying a bit with the types here; this will be transformed into a proper App.Error object later
576
+ error: check_incorrect_fail_use(err)
577
+ };
578
+ }
579
+ }
580
+
581
+ /**
582
+ * @param {URL} url
583
+ */
584
+ export function get_remote_id(url) {
585
+ return (
586
+ url.pathname.startsWith(`${base}/${app_dir}/remote/`) &&
587
+ url.pathname.replace(`${base}/${app_dir}/remote/`, '')
588
+ );
589
+ }
590
+
591
+ /**
592
+ * @param {URL} url
593
+ */
594
+ export function get_remote_action(url) {
595
+ return url.searchParams.get('/remote');
596
+ }