tempest-react-sdk 0.79.0 → 0.81.0
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/README.md +35 -4
- package/bin/lib/component/generate.test.mjs +13 -1
- package/bin/lib/openapi/generate.hostile.test.mjs +58 -5
- package/bin/lib/openapi/generate.mjs +145 -34
- package/bin/lib/openapi/generate.test.mjs +216 -5
- package/bin/lib/openapi/schema-to-zod.mjs +4 -3
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +172 -103
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/br/boleto.cjs +1 -1
- package/dist/br/boleto.cjs.map +1 -1
- package/dist/br/boleto.js +2 -1
- package/dist/br/boleto.js.map +1 -1
- package/dist/br.d.ts +22 -3
- package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
- package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
- package/dist/components/AuthForm/AuthFieldControl.js +85 -0
- package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.cjs +2 -0
- package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.js +83 -0
- package/dist/components/AuthForm/AuthForm.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
- package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.js +14 -0
- package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
- package/dist/components/AuthForm/AuthLinks.cjs +2 -0
- package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
- package/dist/components/AuthForm/AuthLinks.js +29 -0
- package/dist/components/AuthForm/AuthLinks.js.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/LoginForm.cjs +2 -0
- package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
- package/dist/components/AuthForm/LoginForm.js +39 -0
- package/dist/components/AuthForm/LoginForm.js.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
- package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/SignUpForm.cjs +2 -0
- package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
- package/dist/components/AuthForm/SignUpForm.js +32 -0
- package/dist/components/AuthForm/SignUpForm.js.map +1 -0
- package/dist/components/AuthForm/auth-defaults.cjs +2 -0
- package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
- package/dist/components/AuthForm/auth-defaults.js +54 -0
- package/dist/components/AuthForm/auth-defaults.js.map +1 -0
- package/dist/components/AuthForm/auth-schemas.cjs +2 -0
- package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
- package/dist/components/AuthForm/auth-schemas.js +26 -0
- package/dist/components/AuthForm/auth-schemas.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.cjs +2 -0
- package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.js +91 -0
- package/dist/components/AuthPage/AuthPage.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
- package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.js +24 -0
- package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
- package/dist/components/FilterBar/filter-apply.cjs +1 -1
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
- package/dist/components/FilterBar/filter-apply.js +7 -7
- package/dist/forms/index.js +7 -7
- package/dist/forms/masked-inputs.cjs +1 -1
- package/dist/forms/masked-inputs.cjs.map +1 -1
- package/dist/forms/masked-inputs.js +15 -15
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +104 -97
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/build-url.cjs +1 -1
- package/dist/http/build-url.cjs.map +1 -1
- package/dist/http/build-url.js +3 -1
- package/dist/http/build-url.js.map +1 -1
- package/dist/http/presigned-post.cjs +2 -0
- package/dist/http/presigned-post.cjs.map +1 -0
- package/dist/http/presigned-post.js +73 -0
- package/dist/http/presigned-post.js.map +1 -0
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +97 -97
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js +12 -12
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +9 -9
- package/dist/offline/create-offline-sync.cjs +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js +78 -56
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/sse/create-event-stream.cjs +1 -1
- package/dist/sse/create-event-stream.cjs.map +1 -1
- package/dist/sse/create-event-stream.js +44 -30
- package/dist/sse/create-event-stream.js.map +1 -1
- package/dist/sse/ticket-event-stream.cjs +2 -0
- package/dist/sse/ticket-event-stream.cjs.map +1 -0
- package/dist/sse/ticket-event-stream.js +41 -0
- package/dist/sse/ticket-event-stream.js.map +1 -0
- package/dist/sse/use-event-stream.cjs +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js +7 -4
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/styles/AuthForm.css +2 -0
- package/dist/styles/AuthPage.css +2 -0
- package/dist/styles/component/AuthForm.css +9 -0
- package/dist/styles/component/AuthPage.css +29 -0
- package/dist/styles/forms.css +36 -0
- package/dist/styles/manifest.json +63 -0
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +124 -106
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw.d.ts +49 -15
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +809 -22
- package/dist/tempest-react-sdk.js +373 -363
- package/dist/utils/format.cjs +1 -1
- package/dist/utils/format.cjs.map +1 -1
- package/dist/utils/format.js +25 -25
- package/dist/utils/numbers.cjs +1 -1
- package/dist/utils/numbers.cjs.map +1 -1
- package/dist/utils/numbers.js +7 -7
- package/package.json +1 -1
- package/template-pwa/src/sw.ts +10 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-with-progress.cjs","names":["randomId","isTrustedCredentialTarget","csrfHeaders","TempestApiError","buildApiError","require_ids","require_credential_scope","require_csrf","require_errors","parseErrorBody","raw","uploadWithProgress","options","signal","reject","xhr","method","url","withCredentials","token","getToken","sentRequestId","requestId","finalHeaders","headers","credentialOrigin","trustedOrigins","key","value","onProgress","event","handleAbort","isSuccess","contentType","errorBody","name","resolve","parser","err","body"],"sources":["../../src/http/upload-with-progress.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — XMLHttpRequest is used instead of fetch precisely\n * because it reports upload progress, and its API is event-based: the body wires\n * load, error, abort, timeout and progress against one request object, plus the\n * AbortSignal bridge.\n */\nimport { randomId } from \"../utils\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, TempestApiError } from \"./errors\";\n\nexport interface UploadProgressEvent {\n /** Bytes already uploaded. */\n loaded: number;\n /** Total payload size in bytes — only meaningful when `lengthComputable` is true. */\n total: number;\n /** Fraction between 0 and 1, or null when total is unknown. */\n fraction: number | null;\n lengthComputable: boolean;\n}\n\nexport interface UploadWithProgressOptions {\n url: string;\n body: FormData | Blob | File;\n method?: \"POST\" | \"PUT\" | \"PATCH\";\n headers?: Record<string, string>;\n /** Returns the current bearer token. */\n getToken?: () => string | null | undefined;\n /**\n * Origin the `getToken` credential belongs to, normally the API's.\n *\n * Unlike `createApiClient`, this helper has no base URL to infer a scope\n * from — the caller names the destination on every call. Set this when the\n * `url` can come from somewhere other than your own code (a signed URL the\n * API handed back, a value from a response body) and the token must not\n * follow it off-origin. Left unset, the header goes wherever `url` points,\n * which is the behaviour every version before 0.66.0 had.\n */\n credentialOrigin?: string;\n /**\n * Extra origins allowed to receive the credential, on top of\n * {@link credentialOrigin}. Ignored when that one is unset.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Defaults to false. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token with the upload, as `createApiClient`'s `csrf` does.\n * Off by default; `true` reads the `csrf_token` cookie into `X-CSRF-Token`.\n *\n * Scoped to {@link credentialOrigin} plus {@link trustedOrigins} — and,\n * unlike the bearer token, scoped even when `credentialOrigin` is unset:\n * then the scope is the page's own origin. The bearer default stays open\n * only for compatibility with every version before 0.66.0; this option is\n * new, so it starts closed. An API on another origin sets\n * `credentialOrigin` to receive the token.\n */\n csrf?: boolean | CsrfOptions;\n /** Called on every `progress` event from the XHR upload channel. */\n onProgress?: (event: UploadProgressEvent) => void;\n /** Abort the request. */\n signal?: AbortSignal;\n /** Override the JSON parser. Defaults to `JSON.parse`. */\n parser?: (raw: string) => unknown;\n /**\n * Per-request correlation id sent as `X-Request-ID` (Tempest convention).\n * Defaults to a generated id. Return an empty string to disable.\n */\n requestId?: () => string;\n}\n\nfunction parseErrorBody(raw: string): unknown {\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Upload a file (or any payload) with byte-level progress reporting.\n *\n * `fetch` cannot report upload progress in browsers, so this helper falls\n * back to `XMLHttpRequest`. It mirrors the error contract used by\n * {@link createApiClient}: non-2xx responses reject with a `TempestApiError`.\n *\n * @returns The parsed JSON response, or the raw text when the response is not JSON.\n */\nexport function uploadWithProgress<T = unknown>(options: UploadWithProgressOptions): Promise<T> {\n const {\n url,\n body,\n method = \"POST\",\n headers = {},\n getToken,\n credentialOrigin,\n trustedOrigins,\n withCredentials = false,\n csrf,\n onProgress,\n signal,\n parser = JSON.parse,\n requestId,\n } = options;\n\n return new Promise<T>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.withCredentials = withCredentials;\n\n const token = getToken?.();\n const sentRequestId = requestId ? requestId() : randomId();\n const finalHeaders: Record<string, string> = { ...headers };\n if (token && !(\"Authorization\" in finalHeaders)) {\n if (\n credentialOrigin === undefined ||\n isTrustedCredentialTarget(url, credentialOrigin, trustedOrigins)\n ) {\n finalHeaders.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(url, credentialOrigin);\n }\n }\n Object.assign(\n finalHeaders,\n csrfHeaders({\n method,\n url,\n reference: credentialOrigin ?? globalThis.location?.origin ?? url,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\n if (sentRequestId && !(\"X-Request-ID\" in finalHeaders)) {\n finalHeaders[\"X-Request-ID\"] = sentRequestId;\n }\n for (const [key, value] of Object.entries(finalHeaders)) {\n xhr.setRequestHeader(key, value);\n }\n\n if (onProgress) {\n xhr.upload.onprogress = (event) => {\n onProgress({\n loaded: event.loaded,\n total: event.total,\n fraction: event.lengthComputable ? event.loaded / event.total : null,\n lengthComputable: event.lengthComputable,\n });\n };\n }\n\n function handleAbort(): void {\n xhr.abort();\n }\n signal?.addEventListener(\"abort\", handleAbort);\n\n xhr.onload = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n const isSuccess = xhr.status >= 200 && xhr.status < 300;\n const contentType = xhr.getResponseHeader(\"content-type\") ?? \"\";\n\n if (!isSuccess) {\n const errorBody = parseErrorBody(xhr.responseText);\n reject(\n new TempestApiError(\n buildApiError(\n xhr.status,\n errorBody,\n { get: (name) => xhr.getResponseHeader(name) },\n sentRequestId,\n ),\n ),\n );\n return;\n }\n\n if (xhr.status === 204 || !xhr.responseText) {\n resolve(undefined as T);\n return;\n }\n\n if (contentType.includes(\"application/json\")) {\n try {\n resolve(parser(xhr.responseText) as T);\n } catch (err) {\n reject(err);\n }\n } else {\n resolve(xhr.responseText as unknown as T);\n }\n };\n\n xhr.onerror = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload.\",\n requestId: sentRequestId || undefined,\n }),\n );\n };\n\n xhr.onabort = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n };\n\n xhr.send(body);\n });\n}\n"],"mappings":"A,0HAwEA,SAASS,EAAe,EAAsB,CAC1C,GAAI,CAACC,EAAK,OAAO,KACjB,GAAI,CACA,OAAO,KAAK,MAAMA,CAAG,CACzB,MAAQ,CACJ,OAAOA,CACX,CACJ,CAWA,SAAgBC,EAAgC,EAAgD,CAC5F,GAAM,CACF,MACA,OACA,SAAS,OACT,UAAU,CAAC,EACX,WACA,mBACA,iBACA,kBAAkB,GAClB,OACA,aACA,SACA,SAAS,KAAK,MACd,aACAC,EAEJ,OAAO,IAAI,SAAY,EAAS,IAAW,CACvC,GAAIC,GAAQ,QAAS,CACjBC,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,MACJ,CAEA,IAAMC,EAAM,IAAI,eAChBA,EAAI,KAAKC,EAAQC,CAAG,EACpB,EAAI,gBAAkBC,EAEtB,IAAMC,EAAQC,IAAW,EACnBC,EAAgBC,EAAYA,EAAU,EAAItB,EAAAA,SAAS,EACnDuB,EAAuC,CAAE,GAAGC,CAAQ,EACtDL,GAAS,EAAE,k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,CAAG,CACd,MAEAF,EAAQrB,EAAI,YAA4B,CAEhD,EAEA,EAAI,YAAgB,CAChBF,GAAQ,oBAAoB,QAASkB,CAAW,EAChDjB,EACI,IAAIX,EAAAA,gBAAgB,CAChB,OAAQ,EACR,OAAQ,2BACR,UAAWkB,GAAiB,IAAA,EAChC,CAAC,CACL,CACJ,EAEA,EAAI,YAAgB,CAChBR,GAAQ,oBAAoB,QAASkB,CAAW,EAChDjB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,CACpD,EAEAC,EAAI,KAAKwB,CAAI,CACjB,CAAC,CACL,C"}
|
|
1
|
+
{"version":3,"file":"upload-with-progress.cjs","names":["randomId","isTrustedCredentialTarget","csrfHeaders","TempestApiError","buildApiError","require_errors","require_ids","require_credential_scope","require_csrf","parseErrorBody","raw","uploadWithProgress","options","signal","reject","xhr","method","url","withCredentials","token","getToken","sentRequestId","requestId","finalHeaders","headers","credentialOrigin","trustedOrigins","key","value","onProgress","event","handleAbort","isSuccess","contentType","errorBody","name","resolve","parser","err","body"],"sources":["../../src/http/upload-with-progress.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — XMLHttpRequest is used instead of fetch precisely\n * because it reports upload progress, and its API is event-based: the body wires\n * load, error, abort, timeout and progress against one request object, plus the\n * AbortSignal bridge.\n */\nimport { randomId } from \"../utils\";\nimport { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport type { CsrfOptions } from \"./csrf\";\nimport { buildApiError, TempestApiError } from \"./errors\";\n\nexport interface UploadProgressEvent {\n /** Bytes already uploaded. */\n loaded: number;\n /** Total payload size in bytes — only meaningful when `lengthComputable` is true. */\n total: number;\n /** Fraction between 0 and 1, or null when total is unknown. */\n fraction: number | null;\n lengthComputable: boolean;\n}\n\nexport interface UploadWithProgressOptions {\n url: string;\n body: FormData | Blob | File;\n method?: \"POST\" | \"PUT\" | \"PATCH\";\n headers?: Record<string, string>;\n /** Returns the current bearer token. */\n getToken?: () => string | null | undefined;\n /**\n * Origin the `getToken` credential belongs to, normally the API's.\n *\n * Unlike `createApiClient`, this helper has no base URL to infer a scope\n * from — the caller names the destination on every call. Set this when the\n * `url` can come from somewhere other than your own code (a signed URL the\n * API handed back, a value from a response body) and the token must not\n * follow it off-origin. Left unset, the header goes wherever `url` points,\n * which is the behaviour every version before 0.66.0 had.\n */\n credentialOrigin?: string;\n /**\n * Extra origins allowed to receive the credential, on top of\n * {@link credentialOrigin}. Ignored when that one is unset.\n */\n trustedOrigins?: readonly string[];\n /** Send cookies. Defaults to false. */\n withCredentials?: boolean;\n /**\n * Send a CSRF token with the upload, as `createApiClient`'s `csrf` does.\n * Off by default; `true` reads the `csrf_token` cookie into `X-CSRF-Token`.\n *\n * Scoped to {@link credentialOrigin} plus {@link trustedOrigins} — and,\n * unlike the bearer token, scoped even when `credentialOrigin` is unset:\n * then the scope is the page's own origin. The bearer default stays open\n * only for compatibility with every version before 0.66.0; this option is\n * new, so it starts closed. An API on another origin sets\n * `credentialOrigin` to receive the token.\n */\n csrf?: boolean | CsrfOptions;\n /** Called on every `progress` event from the XHR upload channel. */\n onProgress?: (event: UploadProgressEvent) => void;\n /** Abort the request. */\n signal?: AbortSignal;\n /** Override the JSON parser. Defaults to `JSON.parse`. */\n parser?: (raw: string) => unknown;\n /**\n * Per-request correlation id sent as `X-Request-ID` (Tempest convention).\n * Defaults to a generated id. Return an empty string to disable.\n */\n requestId?: () => string;\n}\n\nfunction parseErrorBody(raw: string): unknown {\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Upload a file (or any payload) with byte-level progress reporting.\n *\n * `fetch` cannot report upload progress in browsers, so this helper falls\n * back to `XMLHttpRequest`. It mirrors the error contract used by\n * {@link createApiClient}: non-2xx responses reject with a `TempestApiError`.\n *\n * @returns The parsed JSON response, or the raw text when the response is not JSON.\n */\nexport function uploadWithProgress<T = unknown>(options: UploadWithProgressOptions): Promise<T> {\n const {\n url,\n body,\n method = \"POST\",\n headers = {},\n getToken,\n credentialOrigin,\n trustedOrigins,\n withCredentials = false,\n csrf,\n onProgress,\n signal,\n parser = JSON.parse,\n requestId,\n } = options;\n\n return new Promise<T>((resolve, reject) => {\n if (signal?.aborted) {\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.withCredentials = withCredentials;\n\n const token = getToken?.();\n const sentRequestId = requestId ? requestId() : randomId();\n const finalHeaders: Record<string, string> = { ...headers };\n if (token && !(\"Authorization\" in finalHeaders)) {\n if (\n credentialOrigin === undefined ||\n isTrustedCredentialTarget(url, credentialOrigin, trustedOrigins)\n ) {\n finalHeaders.Authorization = `Bearer ${token}`;\n } else {\n reportSuppressedCredential(url, credentialOrigin);\n }\n }\n Object.assign(\n finalHeaders,\n csrfHeaders({\n method,\n url,\n reference: credentialOrigin ?? globalThis.location?.origin ?? url,\n csrf,\n trustedOrigins,\n headers,\n }),\n );\n if (sentRequestId && !(\"X-Request-ID\" in finalHeaders)) {\n finalHeaders[\"X-Request-ID\"] = sentRequestId;\n }\n for (const [key, value] of Object.entries(finalHeaders)) {\n xhr.setRequestHeader(key, value);\n }\n\n if (onProgress) {\n xhr.upload.onprogress = (event) => {\n onProgress({\n loaded: event.loaded,\n total: event.total,\n fraction: event.lengthComputable ? event.loaded / event.total : null,\n lengthComputable: event.lengthComputable,\n });\n };\n }\n\n function handleAbort(): void {\n xhr.abort();\n }\n signal?.addEventListener(\"abort\", handleAbort);\n\n xhr.onload = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n const isSuccess = xhr.status >= 200 && xhr.status < 300;\n const contentType = xhr.getResponseHeader(\"content-type\") ?? \"\";\n\n if (!isSuccess) {\n const errorBody = parseErrorBody(xhr.responseText);\n reject(\n new TempestApiError(\n buildApiError(\n xhr.status,\n errorBody,\n { get: (name) => xhr.getResponseHeader(name) },\n sentRequestId,\n ),\n ),\n );\n return;\n }\n\n if (xhr.status === 204 || !xhr.responseText) {\n resolve(undefined as T);\n return;\n }\n\n if (contentType.includes(\"application/json\")) {\n try {\n resolve(parser(xhr.responseText) as T);\n } catch (err) {\n reject(err);\n }\n } else {\n resolve(xhr.responseText as unknown as T);\n }\n };\n\n xhr.onerror = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n reject(\n new TempestApiError({\n status: 0,\n detail: \"Falha de rede no upload.\",\n requestId: sentRequestId || undefined,\n }),\n );\n };\n\n xhr.onabort = () => {\n signal?.removeEventListener(\"abort\", handleAbort);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n };\n\n xhr.send(body);\n });\n}\n"],"mappings":"A,0HAwEA,SAASS,EAAe,EAAsB,CAC1C,GAAI,CAACC,EAAK,OAAO,KACjB,GAAI,CACA,OAAO,KAAK,MAAMA,CAAG,CACzB,MAAQ,CACJ,OAAOA,CACX,CACJ,CAWA,SAAgBC,EAAgC,EAAgD,CAC5F,GAAM,CACF,MACA,OACA,SAAS,OACT,UAAU,CAAC,EACX,WACA,mBACA,iBACA,kBAAkB,GAClB,OACA,aACA,SACA,SAAS,KAAK,MACd,aACAC,EAEJ,OAAO,IAAI,SAAY,EAAS,IAAW,CACvC,GAAIC,GAAQ,QAAS,CACjBC,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,EAChD,MACJ,CAEA,IAAMC,EAAM,IAAI,eAChBA,EAAI,KAAKC,EAAQC,CAAG,EACpB,EAAI,gBAAkBC,EAEtB,IAAMC,EAAQC,IAAW,EACnBC,EAAgBC,EAAYA,EAAU,EAAItB,EAAAA,SAAS,EACnDuB,EAAuC,CAAE,GAAGC,CAAQ,EACtDL,GAAS,EAAE,kBAAmBI,KAE1BE,IAAqB,IAAA,IACrBxB,EAAAA,0BAA0BgB,EAAKQ,EAAkBC,CAAc,EAE/D,EAAa,cAAgB,UAAUP,IAEvCZ,EAAA,2BAA2BU,EAAKQ,CAAgB,GAGxD,OAAO,OACHF,EACArB,EAAAA,YAAY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B,IAAA,EAChC,CAAC,CACL,CACJ,EAEA,EAAI,YAAgB,CAChBR,GAAQ,oBAAoB,QAASkB,CAAW,EAChDjB,EAAO,IAAI,aAAa,UAAW,YAAY,CAAC,CACpD,EAEAC,EAAI,KAAKwB,CAAI,CACjB,CAAC,CACL,C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { TempestApiError as e, buildApiError as t } from "./errors.js";
|
|
2
|
+
import { randomId as n } from "../utils/ids.js";
|
|
3
|
+
import { isTrustedCredentialTarget as r, reportSuppressedCredential as i } from "./credential-scope.js";
|
|
4
|
+
import { csrfHeaders as a } from "./csrf.js";
|
|
5
5
|
//#region src/http/upload-with-progress.ts
|
|
6
6
|
function o(e) {
|
|
7
7
|
if (!e) return null;
|
|
@@ -20,8 +20,8 @@ function s(s) {
|
|
|
20
20
|
}
|
|
21
21
|
let S = new XMLHttpRequest();
|
|
22
22
|
S.open(u, c), S.withCredentials = h;
|
|
23
|
-
let C = f?.(), w = b ? b() :
|
|
24
|
-
C && !("Authorization" in T) && (p === void 0 ||
|
|
23
|
+
let C = f?.(), w = b ? b() : n(), T = { ...d };
|
|
24
|
+
C && !("Authorization" in T) && (p === void 0 || r(c, p, m) ? T.Authorization = `Bearer ${C}` : i(c, p)), Object.assign(T, a({
|
|
25
25
|
method: u,
|
|
26
26
|
url: c,
|
|
27
27
|
reference: p ?? globalThis.location?.origin ?? c,
|
|
@@ -43,19 +43,19 @@ function s(s) {
|
|
|
43
43
|
}
|
|
44
44
|
v?.addEventListener("abort", E), S.onload = () => {
|
|
45
45
|
v?.removeEventListener("abort", E);
|
|
46
|
-
let
|
|
47
|
-
if (!
|
|
48
|
-
let
|
|
49
|
-
x(new
|
|
46
|
+
let n = S.status >= 200 && S.status < 300, r = S.getResponseHeader("content-type") ?? "";
|
|
47
|
+
if (!n) {
|
|
48
|
+
let n = o(S.responseText);
|
|
49
|
+
x(new e(t(S.status, n, { get: (e) => S.getResponseHeader(e) }, w)));
|
|
50
50
|
} else if (S.status === 204 || !S.responseText) s(void 0);
|
|
51
|
-
else if (
|
|
51
|
+
else if (r.includes("application/json")) try {
|
|
52
52
|
s(y(S.responseText));
|
|
53
53
|
} catch (e) {
|
|
54
54
|
x(e);
|
|
55
55
|
}
|
|
56
56
|
else s(S.responseText);
|
|
57
57
|
}, S.onerror = () => {
|
|
58
|
-
v?.removeEventListener("abort", E), x(new
|
|
58
|
+
v?.removeEventListener("abort", E), x(new e({
|
|
59
59
|
status: 0,
|
|
60
60
|
detail: "Falha de rede no upload.",
|
|
61
61
|
requestId: w || void 0
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("
|
|
1
|
+
const e=require("../i18n/I18nProvider.cjs"),t=require("./describe-api-error.cjs");let n=require("react");function r(e,n,r){let i=t.DEFAULT_API_ERROR_STRINGS[r];return e?.(n,void 0,{default:i})??i}function i(){let i=e.useOptionalI18n()?.t;return(0,n.useCallback)((e,n,a)=>t.describeApiError(e,n,{offline:r(i,t.API_ERROR_OFFLINE_KEY,`offline`),validation:r(i,t.API_ERROR_VALIDATION_KEY,`validation`),...a}),[i])}exports.useDescribeApiError=i;
|
|
2
2
|
//# sourceMappingURL=use-describe-api-error.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-describe-api-error.cjs","names":["DEFAULT_API_ERROR_STRINGS","useOptionalI18n","useCallback","describeApiError","API_ERROR_OFFLINE_KEY","API_ERROR_VALIDATION_KEY","
|
|
1
|
+
{"version":3,"file":"use-describe-api-error.cjs","names":["DEFAULT_API_ERROR_STRINGS","useOptionalI18n","useCallback","describeApiError","API_ERROR_OFFLINE_KEY","API_ERROR_VALIDATION_KEY","require_I18nProvider","require_describe_api_error","react","resolve","fallback","fallbackKey","translate","key","useDescribeApiError","error","options"],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport type { DescribeApiErrorOptions } from \"./describe-api-error\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * The per-call options are the pure function's, so a screen that knows the\n * backend codes it can hit passes them at the call site while the translated\n * sentences keep coming from the provider.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback, options?) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string, options?: DescribeApiErrorOptions) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n ...options,\n });\n },\n [translate],\n );\n}\n"],"mappings":"A,yGAuDA,SAASS,EACL,EACA,EACA,EACM,CACN,IAAMC,EAAWV,EAAAA,0BAA0BW,GAC3C,OAAOC,IAAYC,EAAK,IAAA,GAAW,CAAE,QAASH,CAAS,CAAC,GAAKA,CACjE,CAEA,SAAgBI,GAIJ,CAER,IAAMF,EADOX,EAAAA,gBACK,CAAA,EAAM,EAExB,OAAA,EAAOC,EAAAA,YAAAA,EACF,EAAgB,EAAkB,IACxBC,EAAAA,iBAAiBY,EAAOL,EAAU,CACrC,QAASD,EAAQG,EAAWR,EAAAA,sBAAuB,SAAS,EAC5D,WAAYK,EAAQG,EAAWP,EAAAA,yBAA0B,YAAY,EACrE,GAAGW,CACP,CAAC,EAEL,CAACJ,CAAS,CACd,CACJ,C"}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { useOptionalI18n as e } from "../i18n/I18nProvider.js";
|
|
2
|
+
import { API_ERROR_OFFLINE_KEY as t, API_ERROR_VALIDATION_KEY as n, DEFAULT_API_ERROR_STRINGS as r, describeApiError as i } from "./describe-api-error.js";
|
|
3
3
|
import { useCallback as a } from "react";
|
|
4
4
|
//#region src/http/use-describe-api-error.ts
|
|
5
|
-
function o(e, t,
|
|
6
|
-
let i = n
|
|
5
|
+
function o(e, t, n) {
|
|
6
|
+
let i = r[n];
|
|
7
7
|
return e?.(t, void 0, { default: i }) ?? i;
|
|
8
8
|
}
|
|
9
9
|
function s() {
|
|
10
|
-
let
|
|
11
|
-
return a((
|
|
12
|
-
offline: o(
|
|
13
|
-
validation: o(
|
|
10
|
+
let r = e()?.t;
|
|
11
|
+
return a((e, a, s) => i(e, a, {
|
|
12
|
+
offline: o(r, t, "offline"),
|
|
13
|
+
validation: o(r, n, "validation"),
|
|
14
14
|
...s
|
|
15
|
-
}), [
|
|
15
|
+
}), [r]);
|
|
16
16
|
}
|
|
17
17
|
//#endregion
|
|
18
18
|
export { s as useDescribeApiError };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/ids.cjs"),t=require("./create-offline-store.cjs");function n(e){let t=typeof localStorage<`u`;return{get:()=>t?localStorage.getItem(e):null,set:n=>{t&&localStorage.setItem(e,n)},clear:()=>{t&&localStorage.removeItem(e)}}}function r(r){let i=t.createOfflineStore({databaseName:r.databaseName,version:r.version??1,tableName:r.tableName??`outbox`,indexes:`&id, recordId, enqueuedAt`,keyPath:`id`}),a=`get`in r.watermark?r.watermark:n(r.watermark.storageKey),o=r.idPrefix??`outbox`,s=r.isOnline??(()=>typeof navigator<`u`?navigator.onLine:!0),c=null,l=new Set,
|
|
1
|
+
const e=require("../utils/ids.cjs"),t=require("./create-offline-store.cjs");function n(e){let t=typeof localStorage<`u`;return{get:()=>t?localStorage.getItem(e):null,set:n=>{t&&localStorage.setItem(e,n)},clear:()=>{t&&localStorage.removeItem(e)}}}function r(r){let i=t.createOfflineStore({databaseName:r.databaseName,version:r.version??1,tableName:r.tableName??`outbox`,indexes:`&id, recordId, enqueuedAt`,keyPath:`id`}),a=`get`in r.watermark?r.watermark:n(r.watermark.storageKey),o=r.idPrefix??`outbox`,s=r.isOnline??(()=>typeof navigator<`u`?navigator.onLine:!0),c=null,l=0,u=new Set,d={phase:`idle`,pending:0,lastSummary:null,lastError:null,lastSyncedAt:null},f=r.crossTab===!0,p=r.broadcastChannelName??`tempest-sync:${r.databaseName}`,m=f&&typeof BroadcastChannel<`u`?new BroadcastChannel(p):null,h=!1;function g(){for(let e of u)e(d)}function _(e){d={...d,...e},g(),m&&!h&&m.postMessage(d)}m&&(m.onmessage=e=>{h||(d=e.data,g())});async function v(){_({pending:await i.count()})}function y(){l+=1,c&&(c=null,_({phase:`idle`}))}async function b(e,t){let n=await i.list(void 0,{orderBy:`enqueuedAt`}),a=new Set;for(let o of n){if(a.has(o.recordId)){e.deferred+=1;continue}let n=await i.get(o.id);if(l!==t)return!1;if(n)try{if(await r.deliver(o),await i.delete(o.id),e.succeeded+=1,l!==t)return!1;await r.onEntryDelivered?.(o)}catch(n){let s=n instanceof Error?n.message:`delivery failed`;if(await i.update(o.id,{attempts:o.attempts+1,lastError:s}),a.add(o.recordId),e.failed+=1,e.lastError=s,l!==t)return!1;await r.onEntryFailed?.(o,n)}}return l===t}async function x(e){let t=a.get(),n=null,i;do{let a=await r.pullPage(t,n);for(let t of a.items){if(l!==e)return!1;await r.applyRemote(t)}if(l!==e)return!1;n=a.nextCursor,i=a.serverTime}while(n);return i&&a.set(i),!0}async function S(e,t){let n=Date.now(),r={trigger:e,succeeded:0,failed:0,deferred:0,durationMs:0,skipped:!1,lastError:null};return s()?(await b(r,t)&&await x(t)||(r.interrupted=!0),r.durationMs=Date.now()-n,r):(r.skipped=!0,r.durationMs=Date.now()-n,r)}async function C(e,t){let n=typeof navigator<`u`?navigator.locks:void 0;return!f||!n?S(e,t):await n.request(`${p}:flush`,{ifAvailable:!0},async n=>n?S(e,t):null)??{trigger:e,succeeded:0,failed:0,deferred:0,durationMs:0,skipped:!1,lastError:null}}v();let w=0;function T(){let e=Date.now();return w=e>w?e:w+1,w}return{async enqueue(t,n,r){let a={id:e.randomId(o),op:t,recordId:n,enqueuedAt:T(),attempts:0,payload:r};return await i.put(a),await v(),a.id},flush(e=`manual`){if(!c){_({phase:`syncing`});let t=l,n=C(e,t).then(async e=>(await v(),l===t&&_({phase:e.skipped?`offline`:e.failed>0?`error`:`idle`,lastSummary:e,lastError:e.lastError,lastSyncedAt:e.skipped?d.lastSyncedAt:Date.now()}),e)).finally(()=>{c===n&&(c=null)});c=n}return c},pendingCount(){return i.count()},listPending(){return i.list(void 0,{orderBy:`enqueuedAt`})},async clearOutbox(){y(),await i.clear(),await v()},resetWatermark(){y(),a.clear()},getState(){return d},subscribe(e){return u.add(e),()=>{u.delete(e)}},dispose(){h=!0,m?.close()}}}exports.createOfflineSync=r;
|
|
2
2
|
//# sourceMappingURL=create-offline-sync.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-offline-sync.cjs","names":["createOfflineStore","randomId","require_ids","require_create_offline_store","localStorageWatermark","available","key","value","createOfflineSync","outbox","config","watermark","idPrefix","isOnline","inflight","listeners","state","crossTab","channelName","channel","closed","notify","listener","setState","patch","event","refreshPending","push","entries","blocked","entry","cause","message","pull","since","cursor","serverTime","page","item","runOnce","startedAt","summary","runGuarded","locks","trigger","lock","lastEnqueuedAt","nextEnqueuedAt","now"],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — outbox drain, pull-with-watermark,\n * conflict resolution and the single-flight guard are one loop by necessity: a pull\n * that lands mid-drain must not advance the watermark past records the outbox has\n * not pushed yet. Splitting the phases hands that ordering to whoever calls them in\n * the right sequence.\n */\nimport { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /**\n * Epoch milliseconds when the mutation was queued, and the FIFO sort key for\n * `listPending()` and the delivery loop. Strictly increasing per engine\n * instance: entries queued inside the same millisecond are spaced by 1ms so\n * the order never depends on how the index breaks a tie.\n */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /**\n * Entries left untried because an earlier entry for the **same record**\n * failed this run.\n *\n * They stay queued and are attempted next run, in order. Counted apart from\n * `failed` because they were never sent: reporting them as failures would\n * blame the server for a decision this engine made, and folding them in would\n * make `succeeded + failed` stop accounting for the queue.\n */\n deferred: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /** Drop every queued mutation (e.g. on logout). */\n clearOutbox: () => Promise<void>;\n /** Reset the pull watermark (e.g. on logout / account switch). */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n /**\n * Drain the outbox in `enqueuedAt` order, one record at a time.\n *\n * Once an entry for a record fails, the remaining entries **for that record**\n * are left untried this run. `enqueuedAt` is a FIFO guarantee the engine goes\n * out of its way to keep (see `nextEnqueuedAt`), precisely because delivering\n * an `update` before the `create` it depends on is wrong — and continuing past\n * a failure broke exactly that guarantee. With a `PUT` upsert `deliver`, which\n * is the usual shape, the server would create the record from the *update*\n * payload and the retried `create` would then overwrite it with the older\n * snapshot: the user's edit disappears with nothing reported.\n *\n * Skipping is per record, not per run. Records are independent, so a record\n * the server is rejecting must not hold up every other pending change.\n *\n * @param summary - Mutated with the per-entry outcome counts.\n */\n async function push(summary: SyncRunSummary): Promise<void> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n const blocked = new Set<string>();\n for (const entry of entries) {\n if (blocked.has(entry.recordId)) {\n summary.deferred += 1;\n continue;\n }\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n await config.onEntryDelivered?.(entry);\n summary.succeeded += 1;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n await config.onEntryFailed?.(entry, cause);\n blocked.add(entry.recordId);\n summary.failed += 1;\n summary.lastError = message;\n }\n }\n }\n\n async function pull(): Promise<void> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n await config.applyRemote(item);\n }\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n }\n\n async function runOnce(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n await push(summary);\n await pull();\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(trigger: SyncTrigger): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n let lastEnqueuedAt = 0;\n\n /**\n * Timestamp for a new outbox entry, guaranteed to be strictly greater than\n * the previous one.\n *\n * `enqueuedAt` is the sort key for both `listPending()` and the delivery loop\n * in `flush()`. A plain `Date.now()` ties whenever two mutations are queued\n * within the same millisecond — which is normal in a burst — and a tie leaves\n * the order to the index, so a `create` could be delivered *after* the\n * `update` that depends on it. Advancing by 1ms on a tie keeps the queue FIFO\n * at the cost of a timestamp that can run a few milliseconds ahead of the wall\n * clock during a burst.\n *\n * Scope: this is per engine instance. Two tabs enqueueing in the same\n * millisecond can still tie; cross-tab FIFO would need a persisted sequence,\n * and the delivery loop is already single-flight across tabs via Web Locks.\n */\n function nextEnqueuedAt(): number {\n const now = Date.now();\n lastEnqueuedAt = now > lastEnqueuedAt ? now : lastEnqueuedAt + 1;\n return lastEnqueuedAt;\n }\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: nextEnqueuedAt(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n inflight = runGuarded(trigger)\n .then(async (summary) => {\n await refreshPending();\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n inflight = null;\n });\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":"A,4EAiQA,SAASI,EAAsB,EAA6B,CACxD,IAAMC,EAAY,OAAO,aAAiB,IAC1C,MAAO,CACH,QAAYA,EAAY,aAAa,QAAQC,CAAG,EAAI,KACpD,IAAM,GAAkB,CAChBD,GAAW,aAAa,QAAQC,EAAKC,CAAK,CAClD,EACA,UAAa,CACLF,GAAW,aAAa,WAA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P,EAAU,OAAOO,CAAQ,CAC7B,CACJ,EACA,SAAU,CACN,EAAS,GACTH,GAAS,MAAM,CACnB,CACJ,CACJ,C"}
|
|
1
|
+
{"version":3,"file":"create-offline-sync.cjs","names":["createOfflineStore","randomId","require_ids","require_create_offline_store","localStorageWatermark","available","key","value","createOfflineSync","outbox","config","watermark","idPrefix","isOnline","inflight","generation","listeners","state","crossTab","channelName","channel","closed","notify","listener","setState","patch","event","refreshPending","endSession","push","entries","blocked","entry","stillQueued","runGeneration","cause","message","pull","since","cursor","serverTime","page","item","runOnce","startedAt","summary","runGuarded","locks","trigger","lock","lastEnqueuedAt","nextEnqueuedAt","now","run"],"sources":["../../src/offline/create-offline-sync.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — outbox drain, pull-with-watermark,\n * conflict resolution and the single-flight guard are one loop by necessity: a pull\n * that lands mid-drain must not advance the watermark past records the outbox has\n * not pushed yet. Splitting the phases hands that ordering to whoever calls them in\n * the right sequence.\n */\nimport { randomId } from \"../utils/ids\";\nimport { createOfflineStore } from \"./create-offline-store\";\n\n/**\n * Mutation kinds queued in the outbox.\n *\n * `create`/`update` carry a snapshot of the record; `delete` needs only the\n * record id. The distinction between `create` and `update` is advisory — the\n * engine treats both as \"deliver this record\" and leaves the create-vs-update\n * decision to the app's `deliver` callback (a `PUT` upsert usually ignores it).\n */\nexport type OutboxOp = \"create\" | \"update\" | \"delete\";\n\n/**\n * A single queued mutation.\n *\n * @typeParam TPayload - The record snapshot shape carried by\n * `create`/`update` entries (omitted for `delete`).\n */\nexport interface OutboxEntry<TPayload = unknown> {\n /** Stable per-entry id (generated with {@link randomId}). */\n id: string;\n /** The mutation kind. */\n op: OutboxOp;\n /** Primary key of the record the mutation targets. */\n recordId: string;\n /**\n * Epoch milliseconds when the mutation was queued, and the FIFO sort key for\n * `listPending()` and the delivery loop. Strictly increasing per engine\n * instance: entries queued inside the same millisecond are spaced by 1ms so\n * the order never depends on how the index breaks a tie.\n */\n enqueuedAt: number;\n /** How many delivery attempts have been made so far. */\n attempts: number;\n /** Last delivery error message, kept for UI/debug. */\n lastError?: string;\n /** Record snapshot for `create`/`update`. Omitted for `delete`. */\n payload?: TPayload;\n}\n\n/**\n * Why a sync run was triggered. The listed values are the common ones; any\n * string is accepted so apps can add their own telemetry labels.\n */\nexport type SyncTrigger =\n \"boot\" | \"online-event\" | \"after-mutation\" | \"manual\" | \"interval\" | (string & {});\n\n/**\n * One page of the server delta pull.\n *\n * @typeParam TRemote - The server-side item shape.\n */\nexport interface PullPage<TRemote> {\n /** Items changed since the watermark, in this page. */\n items: TRemote[];\n /** Cursor for the next page, or `null` when this is the last page. */\n nextCursor: string | null;\n /**\n * Server clock to persist as the next watermark once the whole delta is\n * applied. `null` leaves the watermark unchanged.\n */\n serverTime: string | null;\n}\n\n/** Outcome of a single {@link OfflineSync.flush} run. */\nexport interface SyncRunSummary {\n /** The trigger passed to `flush`. */\n trigger: SyncTrigger;\n /** Entries delivered to the server this run. */\n succeeded: number;\n /** Entries that failed and stay queued for the next run. */\n failed: number;\n /**\n * Entries left untried because an earlier entry for the **same record**\n * failed this run.\n *\n * They stay queued and are attempted next run, in order. Counted apart from\n * `failed` because they were never sent: reporting them as failures would\n * blame the server for a decision this engine made, and folding them in would\n * make `succeeded + failed` stop accounting for the queue.\n */\n deferred: number;\n /** Total wall-clock milliseconds the run took. */\n durationMs: number;\n /** `true` when the run was skipped because the device was offline. */\n skipped: boolean;\n /** Last delivery error message seen this run, or `null` when none failed. */\n lastError: string | null;\n /**\n * `true` when {@link OfflineSync.clearOutbox} or {@link OfflineSync.resetWatermark}\n * ended the session while this run was in flight, so it stopped early.\n *\n * The counts cover only what happened before the stop: a delivery already in\n * progress at logout is still counted, but no later entry was sent, no further\n * page was pulled or applied, and the watermark was not written. Absent on a\n * run that went to completion.\n */\n interrupted?: true;\n}\n\n/**\n * Coarse lifecycle phase of the sync engine, surfaced through\n * {@link OfflineSync.getState} / {@link OfflineSync.subscribe} for reactive UI.\n *\n * - `\"idle\"` — nothing in flight and the last run (if any) fully succeeded.\n * - `\"syncing\"` — a `flush` run is currently in progress.\n * - `\"offline\"` — the last run was skipped because the device was offline.\n * - `\"error\"` — the last run left at least one entry queued after a failure.\n */\nexport type SyncPhase = \"idle\" | \"syncing\" | \"offline\" | \"error\";\n\n/**\n * Immutable snapshot of the engine's reactive state. A fresh object is emitted\n * to subscribers on every change, so it is safe to use as a\n * `useSyncExternalStore` snapshot (reference equality signals \"no change\").\n */\nexport interface SyncState {\n /** Current lifecycle phase. */\n phase: SyncPhase;\n /** Number of mutations still queued in the outbox. */\n pending: number;\n /** Summary of the most recent `flush` run, or `null` before the first. */\n lastSummary: SyncRunSummary | null;\n /** Message of the most recent delivery failure, or `null`. */\n lastError: string | null;\n /** Epoch ms of the last non-skipped run, or `null` before the first. */\n lastSyncedAt: number | null;\n}\n\n/**\n * Pluggable persistence for the pull watermark (the \"changed since\" cursor).\n * Pass an object with a `storageKey` to use a `localStorage`-backed default.\n */\nexport interface WatermarkStore {\n /** Read the current watermark, or `null` when none is stored. */\n get: () => string | null;\n /** Persist a new watermark. */\n set: (value: string) => void;\n /** Drop the watermark (e.g. on logout / account switch). */\n clear: () => void;\n}\n\n/**\n * Configuration for {@link createOfflineSync}.\n *\n * The engine owns the outbox, the single-flight flush, the offline guard, the\n * paginated pull loop and the watermark; the three transport callbacks\n * (`deliver`, `pullPage`, `applyRemote`) are where the app plugs in its own\n * endpoints, record shape and conflict resolution.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n */\nexport interface OfflineSyncConfig<TPayload, TRemote> {\n /** IndexedDB database name for the outbox (kept separate per queue). */\n databaseName: string;\n /** Outbox object-store name. Default `\"outbox\"`. */\n tableName?: string;\n /** Outbox schema version. Default `1`. */\n version?: number;\n /** Prefix for generated entry ids. Default `\"outbox\"`. */\n idPrefix?: string;\n /**\n * Deliver one queued mutation to the server. Throwing keeps the entry\n * queued (its `attempts`/`lastError` are bumped) for the next run.\n */\n deliver: (entry: OutboxEntry<TPayload>) => Promise<void>;\n /** Fetch one page of the server delta since `since`, from `cursor`. */\n pullPage: (since: string | null, cursor: string | null) => Promise<PullPage<TRemote>>;\n /**\n * Merge one pulled item into the local store. The app owns conflict\n * resolution here (e.g. last-write-wins, keeping newer local pending\n * edits, resolving tombstones and downloading blobs).\n */\n applyRemote: (item: TRemote) => Promise<void>;\n /** Watermark persistence, or `{ storageKey }` for a `localStorage` default. */\n watermark: WatermarkStore | { storageKey: string };\n /** Called after an entry is delivered and acked. */\n onEntryDelivered?: (entry: OutboxEntry<TPayload>) => void | Promise<void>;\n /** Called after an entry fails delivery (it stays queued). */\n onEntryFailed?: (entry: OutboxEntry<TPayload>, error: unknown) => void | Promise<void>;\n /**\n * Connectivity check. Default reads `navigator.onLine` (always online in\n * non-browser environments). When it returns `false`, `flush` is skipped.\n */\n isOnline?: () => boolean;\n /**\n * Broadcast {@link SyncState} across browser tabs of the same origin via a\n * `BroadcastChannel`, so every tab shows a coherent pending count / phase\n * (e.g. one tab flushing drops the badge to zero everywhere). The outbox is\n * already a shared IndexedDB; this only shares the in-memory state. Silently\n * ignored where `BroadcastChannel` is unavailable. Default `false`.\n *\n * When the Web Locks API is available, `flush` is additionally coordinated\n * *across* tabs: only one tab runs at a time and others skip while the lock\n * is held (they pick up the result via the broadcast). Delivery should still\n * be idempotent (upsert by client id). Without Web Locks, `flush` falls back\n * to per-tab single-flight.\n */\n crossTab?: boolean;\n /** Channel name when `crossTab` is on. Default `tempest-sync:${databaseName}`. */\n broadcastChannelName?: string;\n}\n\n/**\n * Offline-first sync engine: a durable outbox plus a paginated delta pull.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n */\nexport interface OfflineSync<TPayload> {\n /**\n * Queue a mutation. Returns the generated entry id.\n *\n * @param op - The mutation kind.\n * @param recordId - Primary key of the affected record.\n * @param payload - Record snapshot (for `create`/`update`).\n */\n enqueue: (op: OutboxOp, recordId: string, payload?: TPayload) => Promise<string>;\n /**\n * Run a full sync (drain the outbox, then pull the delta). Concurrent\n * calls share one in-flight promise, so triggers never overlap.\n *\n * @param trigger - Label for why the run happened. Default `\"manual\"`.\n */\n flush: (trigger?: SyncTrigger) => Promise<SyncRunSummary>;\n /** Number of mutations still queued. */\n pendingCount: () => Promise<number>;\n /** The queued mutations in FIFO order. */\n listPending: () => Promise<OutboxEntry<TPayload>[]>;\n /**\n * Drop every queued mutation (e.g. on logout).\n *\n * Also ends the current session for any `flush` already in flight: that run\n * delivers no further entry, pulls and applies nothing more and writes no\n * watermark, and resolves with `interrupted: true`. A `flush` called after this\n * starts a fresh run instead of joining the abandoned one.\n */\n clearOutbox: () => Promise<void>;\n /**\n * Reset the pull watermark (e.g. on logout / account switch).\n *\n * Ends the current session for an in-flight `flush` exactly like\n * {@link OfflineSync.clearOutbox}, so the run cannot write the ended\n * session's watermark back after the reset.\n */\n resetWatermark: () => void;\n /** Read the current reactive {@link SyncState} snapshot synchronously. */\n getState: () => SyncState;\n /**\n * Subscribe to {@link SyncState} changes. The listener fires on every\n * enqueue, flush transition and outbox clear.\n *\n * @param listener - Called with the new snapshot on each change.\n * @returns An unsubscribe function.\n */\n subscribe: (listener: (state: SyncState) => void) => () => void;\n /**\n * Release resources held by the engine — currently the cross-tab\n * `BroadcastChannel` when `crossTab` is enabled. Safe to call when none was\n * opened. Optional in long-lived apps (the channel is reclaimed on tab\n * close); call it in tests and on teardown.\n */\n dispose: () => void;\n}\n\n/**\n * Build a `localStorage`-backed {@link WatermarkStore}. Reads/writes are no-ops\n * when `localStorage` is unavailable (SSR / non-browser).\n *\n * @param key - The `localStorage` key.\n * @returns A watermark store persisting to `localStorage`.\n */\nfunction localStorageWatermark(key: string): WatermarkStore {\n const available = typeof localStorage !== \"undefined\";\n return {\n get: () => (available ? localStorage.getItem(key) : null),\n set: (value: string) => {\n if (available) localStorage.setItem(key, value);\n },\n clear: () => {\n if (available) localStorage.removeItem(key);\n },\n };\n}\n\n/**\n * Create an offline-first sync engine over an IndexedDB outbox.\n *\n * The engine drains queued mutations to the server (`deliver`) and pulls the\n * server delta back (`pullPage` + `applyRemote`), advancing a watermark so each\n * run only fetches what changed. `flush` is single-flight and skips cleanly\n * while offline; failed deliveries stay queued with their attempt count bumped.\n *\n * Dexie is an **optional peer dependency** (via {@link createOfflineStore}) —\n * install it (`npm i dexie`) when you use this engine.\n *\n * @typeParam TPayload - Record snapshot carried by outbox entries.\n * @typeParam TRemote - Server item shape returned by `pullPage`.\n * @param config - Transport callbacks + outbox/watermark configuration.\n * @returns The sync handle (`enqueue`, `flush`, `pendingCount`, …).\n *\n * @example\n * const sync = createOfflineSync<Note, NoteDto>({\n * databaseName: \"NotesOutbox\",\n * watermark: { storageKey: \"notes.watermark\" },\n * deliver: async (entry) => {\n * if (entry.op === \"delete\") return api.remove(entry.recordId);\n * await api.upsert(entry.recordId, entry.payload!);\n * },\n * pullPage: async (since, cursor) => {\n * const page = await api.changes(since, cursor);\n * return { items: page.items, nextCursor: page.next, serverTime: page.now };\n * },\n * applyRemote: async (dto) => {\n * if (dto.deleted) return localStore.remove(dto.id);\n * await localStore.save(fromDto(dto));\n * },\n * });\n * await sync.enqueue(\"create\", note.id, note);\n * await sync.flush(\"after-mutation\");\n */\nexport function createOfflineSync<TPayload = unknown, TRemote = unknown>(\n config: OfflineSyncConfig<TPayload, TRemote>,\n): OfflineSync<TPayload> {\n const outbox = createOfflineStore<OutboxEntry<TPayload>, string>({\n databaseName: config.databaseName,\n version: config.version ?? 1,\n tableName: config.tableName ?? \"outbox\",\n indexes: \"&id, recordId, enqueuedAt\",\n keyPath: \"id\",\n });\n\n const watermark: WatermarkStore =\n \"get\" in config.watermark\n ? config.watermark\n : localStorageWatermark(config.watermark.storageKey);\n\n const idPrefix = config.idPrefix ?? \"outbox\";\n const isOnline =\n config.isOnline ?? (() => (typeof navigator !== \"undefined\" ? navigator.onLine : true));\n\n let inflight: Promise<SyncRunSummary> | null = null;\n let generation = 0;\n\n const listeners = new Set<(state: SyncState) => void>();\n let state: SyncState = {\n phase: \"idle\",\n pending: 0,\n lastSummary: null,\n lastError: null,\n lastSyncedAt: null,\n };\n\n const crossTab = config.crossTab === true;\n const channelName = config.broadcastChannelName ?? `tempest-sync:${config.databaseName}`;\n const channel: BroadcastChannel | null =\n crossTab && typeof BroadcastChannel !== \"undefined\"\n ? new BroadcastChannel(channelName)\n : null;\n let closed = false;\n\n function notify(): void {\n for (const listener of listeners) listener(state);\n }\n\n function setState(patch: Partial<SyncState>): void {\n state = { ...state, ...patch };\n notify();\n if (channel && !closed) channel.postMessage(state);\n }\n\n if (channel) {\n channel.onmessage = (event: MessageEvent<SyncState>) => {\n if (closed) return;\n state = event.data;\n notify();\n };\n }\n\n async function refreshPending(): Promise<void> {\n setState({ pending: await outbox.count() });\n }\n\n /**\n * End the current session: every run started before this call is fenced off.\n *\n * Runs capture `generation` when they start and re-check it after every\n * `await`, so the next step of a run started under the previous user — the\n * next `deliver`, the next `pullPage`, an `applyRemote`, the watermark write —\n * never executes under the next user's session. The await already pending (a\n * `deliver` in flight) cannot be recalled; it was issued under the old session\n * and is only bookkept.\n *\n * Detaching `inflight` is what lets the next session's `flush` start its own\n * run instead of joining the abandoned one, which would hand the new user a\n * summary of the old user's queue and leave their own entries waiting. The\n * phase drops back to `\"idle\"` because nothing of the current session is\n * syncing any more.\n */\n function endSession(): void {\n generation += 1;\n if (inflight) {\n inflight = null;\n setState({ phase: \"idle\" });\n }\n }\n\n /**\n * Drain the outbox in `enqueuedAt` order, one record at a time.\n *\n * Once an entry for a record fails, the remaining entries **for that record**\n * are left untried this run. `enqueuedAt` is a FIFO guarantee the engine goes\n * out of its way to keep (see `nextEnqueuedAt`), precisely because delivering\n * an `update` before the `create` it depends on is wrong — and continuing past\n * a failure broke exactly that guarantee. With a `PUT` upsert `deliver`, which\n * is the usual shape, the server would create the record from the *update*\n * payload and the retried `create` would then overwrite it with the older\n * snapshot: the user's edit disappears with nothing reported.\n *\n * Skipping is per record, not per run. Records are independent, so a record\n * the server is rejecting must not hold up every other pending change.\n *\n * The entry list is a snapshot, so before each `deliver` the run checks that\n * its session is still current (see `endSession`) and that the entry is still\n * in the outbox — another tab sharing the IndexedDB may have cleared it on\n * logout. A delivery already in progress when the session ended still has its\n * row deleted or its attempt bumped, because that outcome is true for the\n * server; its `onEntryDelivered`/`onEntryFailed` callback is not fired, since\n * it would act on the next user's local state.\n *\n * @param summary - Mutated with the per-entry outcome counts.\n * @param runGeneration - The session the run started under.\n * @returns `false` when the session ended mid-drain and the run must stop.\n */\n async function push(summary: SyncRunSummary, runGeneration: number): Promise<boolean> {\n const entries = await outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n const blocked = new Set<string>();\n for (const entry of entries) {\n if (blocked.has(entry.recordId)) {\n summary.deferred += 1;\n continue;\n }\n const stillQueued = await outbox.get(entry.id);\n if (generation !== runGeneration) return false;\n if (!stillQueued) continue;\n try {\n await config.deliver(entry);\n await outbox.delete(entry.id);\n summary.succeeded += 1;\n if (generation !== runGeneration) return false;\n await config.onEntryDelivered?.(entry);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : \"delivery failed\";\n await outbox.update(entry.id, {\n attempts: entry.attempts + 1,\n lastError: message,\n } as Partial<OutboxEntry<TPayload>>);\n blocked.add(entry.recordId);\n summary.failed += 1;\n summary.lastError = message;\n if (generation !== runGeneration) return false;\n await config.onEntryFailed?.(entry, cause);\n }\n }\n return generation === runGeneration;\n }\n\n /**\n * Pull the server delta page by page, then advance the watermark.\n *\n * Checks the session (see `endSession`) before every `applyRemote`, before the\n * next `pullPage` and before the watermark write: a page fetched under the\n * previous user is never merged into the local store after logout, the next\n * page is never requested with the previous user's cursor, and\n * `resetWatermark()` is never undone by the run it was meant to end.\n *\n * @param runGeneration - The session the run started under.\n * @returns `false` when the session ended mid-pull and the run stopped.\n */\n async function pull(runGeneration: number): Promise<boolean> {\n const since = watermark.get();\n let cursor: string | null = null;\n let serverTime: string | null;\n do {\n const page = await config.pullPage(since, cursor);\n for (const item of page.items) {\n if (generation !== runGeneration) return false;\n await config.applyRemote(item);\n }\n if (generation !== runGeneration) return false;\n cursor = page.nextCursor;\n serverTime = page.serverTime;\n } while (cursor);\n if (serverTime) watermark.set(serverTime);\n return true;\n }\n\n /**\n * One push-then-pull pass, stopped early when the session it belongs to ends.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @param runGeneration - The session captured when `flush` was called, not\n * when the pass starts: with Web Locks the pass can start after a logout that\n * happened while the lock was being granted, and must not adopt the new\n * session.\n * @returns The run summary, with `interrupted: true` when the session ended.\n */\n async function runOnce(trigger: SyncTrigger, runGeneration: number): Promise<SyncRunSummary> {\n const startedAt = Date.now();\n const summary: SyncRunSummary = {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n };\n if (!isOnline()) {\n summary.skipped = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n const completed = (await push(summary, runGeneration)) && (await pull(runGeneration));\n if (!completed) summary.interrupted = true;\n summary.durationMs = Date.now() - startedAt;\n return summary;\n }\n\n /**\n * Run one sync pass, serialized across tabs when possible.\n *\n * With `crossTab` on and the Web Locks API available, the pass is wrapped in\n * an `ifAvailable` lock request: whichever tab holds the lock runs, and the\n * others get `null` back instead of duplicating the work — their `SyncState`\n * catches up through the `BroadcastChannel`. The no-op summary keeps\n * `skipped: false` on purpose: `skipped` means \"device offline\" (it maps to\n * `phase: \"offline\"`), which is not what happened here. Falls back to a plain\n * per-tab run when `crossTab` is off or Web Locks is missing.\n *\n * @param trigger - What asked for this run, carried into the summary.\n * @param runGeneration - The session the run belongs to (see `runOnce`).\n * @returns The run summary, or an empty summary when another tab held the lock.\n */\n async function runGuarded(\n trigger: SyncTrigger,\n runGeneration: number,\n ): Promise<SyncRunSummary> {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!crossTab || !locks) return runOnce(trigger, runGeneration);\n const result = await locks.request(\n `${channelName}:flush`,\n { ifAvailable: true },\n async (lock) => (lock ? runOnce(trigger, runGeneration) : null),\n );\n return (\n result ?? {\n trigger,\n succeeded: 0,\n failed: 0,\n deferred: 0,\n durationMs: 0,\n skipped: false,\n lastError: null,\n }\n );\n }\n\n void refreshPending();\n\n let lastEnqueuedAt = 0;\n\n /**\n * Timestamp for a new outbox entry, guaranteed to be strictly greater than\n * the previous one.\n *\n * `enqueuedAt` is the sort key for both `listPending()` and the delivery loop\n * in `flush()`. A plain `Date.now()` ties whenever two mutations are queued\n * within the same millisecond — which is normal in a burst — and a tie leaves\n * the order to the index, so a `create` could be delivered *after* the\n * `update` that depends on it. Advancing by 1ms on a tie keeps the queue FIFO\n * at the cost of a timestamp that can run a few milliseconds ahead of the wall\n * clock during a burst.\n *\n * Scope: this is per engine instance. Two tabs enqueueing in the same\n * millisecond can still tie; cross-tab FIFO would need a persisted sequence,\n * and the delivery loop is already single-flight across tabs via Web Locks.\n */\n function nextEnqueuedAt(): number {\n const now = Date.now();\n lastEnqueuedAt = now > lastEnqueuedAt ? now : lastEnqueuedAt + 1;\n return lastEnqueuedAt;\n }\n\n return {\n async enqueue(op, recordId, payload) {\n const entry: OutboxEntry<TPayload> = {\n id: randomId(idPrefix),\n op,\n recordId,\n enqueuedAt: nextEnqueuedAt(),\n attempts: 0,\n payload,\n };\n await outbox.put(entry);\n await refreshPending();\n return entry.id;\n },\n flush(trigger: SyncTrigger = \"manual\") {\n if (!inflight) {\n setState({ phase: \"syncing\" });\n const runGeneration = generation;\n const run: Promise<SyncRunSummary> = runGuarded(trigger, runGeneration)\n .then(async (summary) => {\n await refreshPending();\n if (generation !== runGeneration) return summary;\n setState({\n phase: summary.skipped\n ? \"offline\"\n : summary.failed > 0\n ? \"error\"\n : \"idle\",\n lastSummary: summary,\n lastError: summary.lastError,\n lastSyncedAt: summary.skipped ? state.lastSyncedAt : Date.now(),\n });\n return summary;\n })\n .finally(() => {\n if (inflight === run) inflight = null;\n });\n inflight = run;\n }\n return inflight;\n },\n pendingCount() {\n return outbox.count();\n },\n listPending() {\n return outbox.list(undefined, { orderBy: \"enqueuedAt\" });\n },\n async clearOutbox() {\n endSession();\n await outbox.clear();\n await refreshPending();\n },\n resetWatermark() {\n endSession();\n watermark.clear();\n },\n getState() {\n return state;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n closed = true;\n channel?.close();\n },\n };\n}\n"],"mappings":"A,4EAwRA,SAASI,EAAsB,EAA6B,CACxD,IAAMC,EAAY,OAAO,aAAiB,IAC1C,MAAO,CACH,QAAYA,EAAY,aAAa,QAAQC,CAAG,EAAI,KACpD,IAAM,GAAkB,CAChBD,GAAW,aAAa,QAAQC,EAAKC,CAAK,CAClD,EACA,UAAa,CACLF,GAAW,aAAa,WAAWC,CAAG,CAC9C,CACJ,CACJ,CAsCA,SAAgBE,EACZ,EACqB,CACrB,IAAMC,EAAST,EAAAA,mBAAkD,CAC7D,aAAcU,EAAO,aACrB,QAASA,EAAO,SAAW,EAC3B,UAAWA,EAAO,WAAa,SAC/B,QAAS,4BACT,QAAS,IACb,CAAC,EAEKC,EACF,QAASD,EAAO,UACVA,EAAO,UACPN,EAAsBM,EAAO,UAAU,UAAU,EAErDE,EAAWF,EAAO,UAAY,SAC9BG,EACFH,EAAO,eAAoB,OAAO,UAAc,IAAc,UAAU,OAAS,IAEjFI,EAA2C,KAC3CC,EAAa,EAEXC,EAAY,IAAI,IAClBC,EAAmB,CACnB,MAAO,OACP,QAAS,EACT,YAAa,KACb,UAAW,KACX,aAAc,IAClB,EAEMC,EAAWR,EAAO,WAAa,GAC/BS,EAAcT,EAAO,sBAAwB,gBAAgBA,EAAO,eACpEU,EACFF,GAAY,OAAO,iBAAqB,IAClC,IAAI,iBAAiBC,CAAW,EAChC,KACNE,EAAS,GAEb,SAASC,GAAe,CACpB,IAAK,IAAMC,KAAYP,EAAWO,EAASN,CAAK,CACpD,CAEA,SAASO,EAAS,EAAiC,CAC/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 function r(r) {
|
|
|
20
20
|
tableName: r.tableName ?? "outbox",
|
|
21
21
|
indexes: "&id, recordId, enqueuedAt",
|
|
22
22
|
keyPath: "id"
|
|
23
|
-
}), a = "get" in r.watermark ? r.watermark : n(r.watermark.storageKey), o = r.idPrefix ?? "outbox", s = r.isOnline ?? (() => typeof navigator < "u" ? navigator.onLine : !0), c = null, l = /* @__PURE__ */ new Set(),
|
|
23
|
+
}), a = "get" in r.watermark ? r.watermark : n(r.watermark.storageKey), o = r.idPrefix ?? "outbox", s = r.isOnline ?? (() => typeof navigator < "u" ? navigator.onLine : !0), c = null, l = 0, u = /* @__PURE__ */ new Set(), d = {
|
|
24
24
|
phase: "idle",
|
|
25
25
|
pending: 0,
|
|
26
26
|
lastSummary: null,
|
|
27
27
|
lastError: null,
|
|
28
28
|
lastSyncedAt: null
|
|
29
|
-
},
|
|
30
|
-
function
|
|
31
|
-
for (let e of
|
|
29
|
+
}, f = r.crossTab === !0, p = r.broadcastChannelName ?? `tempest-sync:${r.databaseName}`, m = f && typeof BroadcastChannel < "u" ? new BroadcastChannel(p) : null, h = !1;
|
|
30
|
+
function g() {
|
|
31
|
+
for (let e of u) e(d);
|
|
32
32
|
}
|
|
33
|
-
function
|
|
34
|
-
|
|
35
|
-
...
|
|
33
|
+
function _(e) {
|
|
34
|
+
d = {
|
|
35
|
+
...d,
|
|
36
36
|
...e
|
|
37
|
-
},
|
|
37
|
+
}, g(), m && !h && m.postMessage(d);
|
|
38
38
|
}
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
m && (m.onmessage = (e) => {
|
|
40
|
+
h || (d = e.data, g());
|
|
41
41
|
});
|
|
42
|
-
async function
|
|
43
|
-
|
|
42
|
+
async function v() {
|
|
43
|
+
_({ pending: await i.count() });
|
|
44
44
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
45
|
+
function y() {
|
|
46
|
+
l += 1, c && (c = null, _({ phase: "idle" }));
|
|
47
|
+
}
|
|
48
|
+
async function b(e, t) {
|
|
49
|
+
let n = await i.list(void 0, { orderBy: "enqueuedAt" }), a = /* @__PURE__ */ new Set();
|
|
50
|
+
for (let o of n) {
|
|
51
|
+
if (a.has(o.recordId)) {
|
|
52
|
+
e.deferred += 1;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
let n = await i.get(o.id);
|
|
56
|
+
if (l !== t) return !1;
|
|
57
|
+
if (n) try {
|
|
58
|
+
if (await r.deliver(o), await i.delete(o.id), e.succeeded += 1, l !== t) return !1;
|
|
59
|
+
await r.onEntryDelivered?.(o);
|
|
60
|
+
} catch (n) {
|
|
61
|
+
let s = n instanceof Error ? n.message : "delivery failed";
|
|
62
|
+
if (await i.update(o.id, {
|
|
63
|
+
attempts: o.attempts + 1,
|
|
64
|
+
lastError: s
|
|
65
|
+
}), a.add(o.recordId), e.failed += 1, e.lastError = s, l !== t) return !1;
|
|
66
|
+
await r.onEntryFailed?.(o, n);
|
|
67
|
+
}
|
|
56
68
|
}
|
|
69
|
+
return l === t;
|
|
57
70
|
}
|
|
58
|
-
async function
|
|
59
|
-
let
|
|
71
|
+
async function x(e) {
|
|
72
|
+
let t = a.get(), n = null, i;
|
|
60
73
|
do {
|
|
61
|
-
let
|
|
62
|
-
for (let
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
74
|
+
let a = await r.pullPage(t, n);
|
|
75
|
+
for (let t of a.items) {
|
|
76
|
+
if (l !== e) return !1;
|
|
77
|
+
await r.applyRemote(t);
|
|
78
|
+
}
|
|
79
|
+
if (l !== e) return !1;
|
|
80
|
+
n = a.nextCursor, i = a.serverTime;
|
|
81
|
+
} while (n);
|
|
82
|
+
return i && a.set(i), !0;
|
|
66
83
|
}
|
|
67
|
-
async function
|
|
68
|
-
let
|
|
84
|
+
async function S(e, t) {
|
|
85
|
+
let n = Date.now(), r = {
|
|
69
86
|
trigger: e,
|
|
70
87
|
succeeded: 0,
|
|
71
88
|
failed: 0,
|
|
@@ -74,11 +91,11 @@ function r(r) {
|
|
|
74
91
|
skipped: !1,
|
|
75
92
|
lastError: null
|
|
76
93
|
};
|
|
77
|
-
return s() ? (await
|
|
94
|
+
return s() ? (await b(r, t) && await x(t) || (r.interrupted = !0), r.durationMs = Date.now() - n, r) : (r.skipped = !0, r.durationMs = Date.now() - n, r);
|
|
78
95
|
}
|
|
79
|
-
async function
|
|
80
|
-
let
|
|
81
|
-
return !
|
|
96
|
+
async function C(e, t) {
|
|
97
|
+
let n = typeof navigator < "u" ? navigator.locks : void 0;
|
|
98
|
+
return !f || !n ? S(e, t) : await n.request(`${p}:flush`, { ifAvailable: !0 }, async (n) => n ? S(e, t) : null) ?? {
|
|
82
99
|
trigger: e,
|
|
83
100
|
succeeded: 0,
|
|
84
101
|
failed: 0,
|
|
@@ -88,11 +105,11 @@ function r(r) {
|
|
|
88
105
|
lastError: null
|
|
89
106
|
};
|
|
90
107
|
}
|
|
91
|
-
|
|
92
|
-
let
|
|
93
|
-
function
|
|
108
|
+
v();
|
|
109
|
+
let w = 0;
|
|
110
|
+
function T() {
|
|
94
111
|
let e = Date.now();
|
|
95
|
-
return
|
|
112
|
+
return w = e > w ? e : w + 1, w;
|
|
96
113
|
}
|
|
97
114
|
return {
|
|
98
115
|
async enqueue(t, n, r) {
|
|
@@ -100,21 +117,26 @@ function r(r) {
|
|
|
100
117
|
id: e(o),
|
|
101
118
|
op: t,
|
|
102
119
|
recordId: n,
|
|
103
|
-
enqueuedAt:
|
|
120
|
+
enqueuedAt: T(),
|
|
104
121
|
attempts: 0,
|
|
105
122
|
payload: r
|
|
106
123
|
};
|
|
107
|
-
return await i.put(a), await
|
|
124
|
+
return await i.put(a), await v(), a.id;
|
|
108
125
|
},
|
|
109
126
|
flush(e = "manual") {
|
|
110
|
-
|
|
111
|
-
phase:
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
127
|
+
if (!c) {
|
|
128
|
+
_({ phase: "syncing" });
|
|
129
|
+
let t = l, n = C(e, t).then(async (e) => (await v(), l === t && _({
|
|
130
|
+
phase: e.skipped ? "offline" : e.failed > 0 ? "error" : "idle",
|
|
131
|
+
lastSummary: e,
|
|
132
|
+
lastError: e.lastError,
|
|
133
|
+
lastSyncedAt: e.skipped ? d.lastSyncedAt : Date.now()
|
|
134
|
+
}), e)).finally(() => {
|
|
135
|
+
c === n && (c = null);
|
|
136
|
+
});
|
|
137
|
+
c = n;
|
|
138
|
+
}
|
|
139
|
+
return c;
|
|
118
140
|
},
|
|
119
141
|
pendingCount() {
|
|
120
142
|
return i.count();
|
|
@@ -123,21 +145,21 @@ function r(r) {
|
|
|
123
145
|
return i.list(void 0, { orderBy: "enqueuedAt" });
|
|
124
146
|
},
|
|
125
147
|
async clearOutbox() {
|
|
126
|
-
await i.clear(), await
|
|
148
|
+
y(), await i.clear(), await v();
|
|
127
149
|
},
|
|
128
150
|
resetWatermark() {
|
|
129
|
-
a.clear();
|
|
151
|
+
y(), a.clear();
|
|
130
152
|
},
|
|
131
153
|
getState() {
|
|
132
|
-
return
|
|
154
|
+
return d;
|
|
133
155
|
},
|
|
134
156
|
subscribe(e) {
|
|
135
|
-
return
|
|
136
|
-
|
|
157
|
+
return u.add(e), () => {
|
|
158
|
+
u.delete(e);
|
|
137
159
|
};
|
|
138
160
|
},
|
|
139
161
|
dispose() {
|
|
140
|
-
|
|
162
|
+
h = !0, m?.close();
|
|
141
163
|
}
|
|
142
164
|
};
|
|
143
165
|
}
|