(event, allow_cookies, arg, validate, fn)
| 110 | * @param {(arg?: any) => T} fn |
| 111 | */ |
| 112 | export async function run_remote_function(event, allow_cookies, arg, validate, fn) { |
| 113 | /** @type {RequestEvent} */ |
| 114 | const cleansed = { |
| 115 | ...event, |
| 116 | // @ts-expect-error this isn't part of the public `RequestEvent` type |
| 117 | [EVENT_STATE]: event[EVENT_STATE], |
| 118 | setHeaders: () => { |
| 119 | throw new Error('setHeaders is not allowed in remote functions'); |
| 120 | }, |
| 121 | cookies: { |
| 122 | ...event.cookies, |
| 123 | set: (name, value, opts) => { |
| 124 | if (!allow_cookies) { |
| 125 | throw new Error('Cannot set cookies in `query` or `prerender` functions'); |
| 126 | } |
| 127 | |
| 128 | if (opts.path && !opts.path.startsWith('/')) { |
| 129 | throw new Error('Cookies set in remote functions must have an absolute path'); |
| 130 | } |
| 131 | |
| 132 | return event.cookies.set(name, value, opts); |
| 133 | }, |
| 134 | delete: (name, opts) => { |
| 135 | if (!allow_cookies) { |
| 136 | throw new Error('Cannot delete cookies in `query` or `prerender` functions'); |
| 137 | } |
| 138 | |
| 139 | if (opts.path && !opts.path.startsWith('/')) { |
| 140 | throw new Error('Cookies deleted in remote functions must have an absolute path'); |
| 141 | } |
| 142 | |
| 143 | return event.cookies.delete(name, opts); |
| 144 | } |
| 145 | }, |
| 146 | route: { id: null }, |
| 147 | url: new URL(event.url.origin) |
| 148 | }; |
| 149 | |
| 150 | // In two parts, each with_event, so that runtimes without async local storage can still get the event at the start of the function |
| 151 | const validated = await with_event(cleansed, () => validate(arg)); |
| 152 | return with_event(cleansed, () => fn(validated)); |
| 153 | } |
no test coverage detected