| 1 | // post.mjs — the editor's same-origin form POST, which answers JSON. |
| 2 | // A request that has not answered in POST_TIMEOUT is aborted, so one hung |
| 3 | // autosave never blocks every later one with the status stuck at |
| 4 | // "Saving…": the saver takes the abort as offline and retries (review |
| 5 | // round 4). An aborted request may still have landed; every draft write |
| 6 | // is version-checked, so the retry meets a 409 carrying the text it sent, |
| 7 | // which the saver recognises as its own (saver.mjs, stale()). A |
| 8 | // keepalive POST (the closing tab's) has no page left to time it out. |
| 9 | |
| 10 | export const POST_TIMEOUT = 10000 |
| 11 | |
| 12 | export function poster (fetchImpl = (url, init) => fetch(url, init), timeout = POST_TIMEOUT) { |
| 13 | return async (url, fields, { keepalive = false } = {}) => { |
| 14 | const body = new URLSearchParams() |
| 15 | for (const [name, value] of Object.entries(fields)) { |
| 16 | for (const one of [].concat(value)) body.append(name, one) |
| 17 | } |
| 18 | const controller = keepalive ? null : new AbortController() |
| 19 | const timer = controller ? setTimeout(() => controller.abort(), timeout) : null |
| 20 | try { |
| 21 | const response = await fetchImpl(url, { |
| 22 | method: 'POST', body, credentials: 'same-origin', keepalive, |
| 23 | headers: { Accept: 'application/json' }, signal: controller?.signal |
| 24 | }) |
| 25 | let json = null |
| 26 | try { json = await response.json() } catch {} |
| 27 | return { status: response.status, json } |
| 28 | } finally { |
| 29 | if (timer !== null) clearTimeout(timer) |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | export const post = poster() |
| 35 | |