@tearleads/client-sdk 0.1.256 → 0.1.257

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/client/documents/index.d.ts +5 -2
  2. package/client/documents/index.js +6 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/blobs/attachments/types.d.ts +4 -2
  7. package/data/blobs/attachments/types.js.map +1 -1
  8. package/data/documents/documentContent.d.ts +2 -0
  9. package/data/documents/documentContent.js +7 -0
  10. package/data/documents/documentContent.js.map +1 -1
  11. package/data/documents/shared/manifestBundleReaders.js +1 -1
  12. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  13. package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
  14. package/data/documents/shared/projection/documentCreateSigner.js +49 -0
  15. package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
  16. package/data/documents/shared/projection/index.d.ts +1 -0
  17. package/data/documents/shared/projection/index.js +1 -0
  18. package/data/documents/shared/projection/index.js.map +1 -1
  19. package/data/documents/shared/readers.js +1 -1
  20. package/data/documents/shared/readers.js.map +1 -1
  21. package/data/documents/shared/types.d.ts +1 -0
  22. package/data/documents/shared/types.js.map +1 -1
  23. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  24. package/data/persistence/documents/documentsPersistence.js +4 -1
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/index.d.ts +3 -3
  27. package/index.js +2 -2
  28. package/index.js.map +1 -1
  29. package/internal/api-client/ApiClient.d.ts +2 -2
  30. package/internal/api-client/apiRequestRuntime.js +12 -8
  31. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  32. package/internal/api-client/binaryResponseOperationTransport.js +2 -2
  33. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  34. package/internal/api-client/client/blobs.d.ts +2 -2
  35. package/internal/api-client/client/blobs.js +21 -9
  36. package/internal/api-client/client/blobs.js.map +1 -1
  37. package/internal/api-client/client/writerProjections.js +2 -1
  38. package/internal/api-client/client/writerProjections.js.map +1 -1
  39. package/internal/api-client/operationResponse.js +3 -3
  40. package/internal/api-client/operationResponse.js.map +1 -1
  41. package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
  42. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  43. package/internal/api-client/sessionRefresh.js +6 -1
  44. package/internal/api-client/sessionRefresh.js.map +1 -1
  45. package/internal/api-client/sessionResponse.js +5 -2
  46. package/internal/api-client/sessionResponse.js.map +1 -1
  47. package/internal/api-client/types.d.ts +2 -0
  48. package/internal/api-client/types.js.map +1 -1
  49. package/package.json +1 -1
  50. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  51. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  52. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  53. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  54. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  55. package/stores/documents/documentStore/state.js +3 -1
  56. package/stores/documents/documentStore/state.js.map +1 -1
  57. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  58. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  59. package/stores/documents/index.d.ts +1 -0
  60. package/stores/documents/index.js +1 -0
  61. package/stores/documents/index.js.map +1 -1
  62. package/stores/documents/types.d.ts +1 -0
  63. package/stores/documents/types.js.map +1 -1
  64. package/workflows/blobs/upload/index.d.ts +1 -1
  65. package/workflows/blobs/upload/index.js +36 -18
  66. package/workflows/blobs/upload/index.js.map +1 -1
  67. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  68. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  69. package/workflows/blobs/upload/multipartUpload.js +10 -2
  70. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  71. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  72. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  73. package/workflows/container-contents/documentQueries/index.js +2 -2
  74. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  75. package/workflows/container-contents/index.d.ts +1 -0
  76. package/workflows/container-contents/index.js +1 -0
  77. package/workflows/container-contents/index.js.map +1 -1
  78. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  79. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  80. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  81. package/workflows/documents/create/createAdoption.js +2 -50
  82. package/workflows/documents/create/createAdoption.js.map +1 -1
  83. package/workflows/documents/create/createResponse.js +12 -1
  84. package/workflows/documents/create/createResponse.js.map +1 -1
  85. package/workflows/documents/create/createSubmission.js +14 -0
  86. package/workflows/documents/create/createSubmission.js.map +1 -0
  87. package/workflows/documents/create/index.d.ts +3 -14
  88. package/workflows/documents/create/index.js +76 -67
  89. package/workflows/documents/create/index.js.map +1 -1
  90. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  91. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  92. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  93. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  94. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  95. package/workflows/documents/purge/index.d.ts +1 -0
  96. package/workflows/documents/purge/index.js +1 -0
  97. package/workflows/documents/purge/index.js.map +1 -1
  98. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  99. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAA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\"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport {\n type SessionBoundary,\n SessionRenewalTracker,\n sessionAuthChallengeBytes,\n} from \"./sessionRenewal\";\nimport { sessionRequestInit } from \"./sessionRequestInit\";\nimport { readSessionJson, retiredRequest } from \"./sessionResponse\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n sessionSignal: () => this.sessionRenewals.signal,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null, boundary?: SessionBoundary): boolean {\n const changed = Boolean(boundary) || this.authToken !== token;\n if (boundary) this.requestFailuresByKey.clear();\n if (changed) this.sessionRenewals.tokenChanged(boundary);\n this.authToken = token;\n return changed;\n }\n\n captureCredential() {\n return this.sessionRenewals.captureCredential();\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n return this.sessionRenewals.withSessionSignal(options);\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const session = this.sessionRenewals.signal;\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n const decoded = await readSessionJson(\n this.responseRequest,\n response,\n method,\n path,\n options ?? {},\n session,\n );\n if (session.aborted) return retiredRequest(method, path);\n if (!decoded.ok) return decoded;\n const data = decoded.data;\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n authToken = this.authToken,\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const callerOptions = options;\n const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);\n options = this.sessionRenewals.withSessionSignal(options);\n const result = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n attempt,\n );\n if (!result.ok) return result;\n if (session.aborted)\n return this.retiredResponse(session, method, path, result.data);\n const response = result.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return result;\n }\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const retired = () =>\n this.retiredResponse(\n session,\n method,\n path,\n response,\n errorDescription.code,\n );\n if (session.aborted) return retired();\n const failure = {\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n };\n if (attempt === 2) return this.httpFailure(failure);\n\n // An independent replacement or caller cancellation ends this wait. A\n // refusal from the renewal itself must finish reporting its typed error.\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options: waitOptions,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n if (session.aborted) return retired();\n const retryToken = this.sessionRenewals.currentToken(authToken);\n if (!shouldRetry || !retryToken) return this.httpFailure(failure);\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n ...failure,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n });\n return this.makeResponseRequest(\n path,\n method,\n body,\n callerOptions,\n additionalSuccessStatuses,\n failureOperation,\n retryToken,\n 2,\n );\n }\n\n private retiredResponse(\n session: AbortSignal,\n method: HttpMethod,\n path: string,\n response: Response,\n code?: string | null,\n ): RequestFailure {\n const retired = retiredRequest(method, path);\n // Principal writes refused before dispatch have a definitive outcome.\n if (response.status !== 401 || !this.sessionRenewals.refused(session))\n return retired;\n return {\n ...retired,\n kind: \"http\",\n status: 401,\n statusText: response.statusText,\n code: code ?? undefined,\n message: `${method} ${path}: 401 ${response.statusText}`,\n };\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const reportErrors = options.reportErrors ?? true;\n const { headers, init } = sessionRequestInit(\n method,\n body,\n options,\n authToken,\n );\n\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n );\n } catch (error) {\n if (session.aborted) return retiredRequest(method, path);\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n if (session.aborted) return retiredRequest(method, path);\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n if (session.aborted)\n return this.retiredResponse(session, method, path, response);\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAEL,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EACL,eAAe,EACf,cAAc,EACd,cAAc,GACf,MAAM,mBAAmB,CAAC;AAiB3B,MAAM,OAAO,iBAAiB;IAoBT;IAnBX,SAAS,GAAkB,IAAI,CAAC;IACvB,eAAe,GAAG,IAAI,qBAAqB,CAC1D,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CACrB,CAAC;IACe,OAAO,CAAS;IACzB,OAAO,GAAuC,IAAI,CAAC;IACnD,cAAc,GAAwB,IAAI,CAAC;IAC3C,gBAAgB,GAAwB,IAAI,CAAC;IAC7C,gBAAgB,GAA8C,IAAI,CAAC;IACnE,YAAY,GAAuC,IAAI,CAAC;IACxD,gBAAgB,GAA0B,IAAI,CAAC;IAC/C,iBAAiB,GAAkC,IAAI,CAAC;IAC/C,oBAAoB,GAAG,IAAI,GAAG,EAA0B,CAAC;IACjE,OAAO,CAAqB;IAC5B,aAAa,CAA2B;IACxC,eAAe,CAA6B;IAErD,YAC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YACjE,mBAAmB,EAAE,KAAK,CAAC,gBAAgB,CAAC,mBAAmB;YAC/D,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;YAC7B,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAEO,4BAA4B,CAClC,KAA4C;QAE5C,IAAI,KAAK,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,KAAK;YAC3C,OAAO,cAAc,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAClD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n type ApiNetworkError,\n networkFailureMessage,\n settleNetworkFailure,\n} from \"./networkFailure\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport {\n type SessionBoundary,\n SessionRenewalTracker,\n sessionAuthChallengeBytes,\n} from \"./sessionRenewal\";\nimport { sessionRequestInit } from \"./sessionRequestInit\";\nimport {\n readSessionJson,\n requestRetired,\n retiredRequest,\n} from \"./sessionResponse\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onNetworkFailure: ((error: ApiNetworkError) => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(\n baseUrl?: string | null,\n private readonly instrumentation?: ApiRequestInstrumentation,\n ) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n sessionSignal: () => this.sessionRenewals.signal,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n return sessionAuthChallengeBytes(this.baseUrl, challengeHex, fingerprint);\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n /** Reports a failure carried inside a successful batched response. */\n reportError(message: string): void {\n this.onError?.(message);\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Every fetch that threw without a response, except plain cancellations. */\n setOnNetworkFailure(handler: ((e: ApiNetworkError) => void) | null): void {\n this.onNetworkFailure = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null, boundary?: SessionBoundary): boolean {\n const changed = Boolean(boundary) || this.authToken !== token;\n if (boundary) this.requestFailuresByKey.clear();\n if (changed) this.sessionRenewals.tokenChanged(boundary);\n this.authToken = token;\n return changed;\n }\n\n captureCredential() {\n return this.sessionRenewals.captureCredential();\n }\n\n withSessionSignal(options: RequestResultOptions): RequestResultOptions {\n return this.sessionRenewals.withSessionSignal(options);\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n networkError?: ApiNetworkError | undefined;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ...(input.networkError ? { networkError: input.networkError } : {}),\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const session = this.sessionRenewals.signal;\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options ?? {},\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options?.reportErrors ?? true;\n const decoded = await readSessionJson(\n this.responseRequest,\n response,\n method,\n path,\n options ?? {},\n session,\n );\n if (requestRetired(session, options)) return retiredRequest(method, path);\n if (!decoded.ok) return decoded;\n const data = decoded.data;\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n authToken = this.authToken,\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n const callerOptions = options;\n const waitOptions = this.sessionRenewals.withRenewalWaitSignal(options);\n options = this.sessionRenewals.withSessionSignal(options);\n const result = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n attempt,\n );\n if (!result.ok) return result;\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, result.data);\n const response = result.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return result;\n }\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const retired = () =>\n this.retiredResponse(\n session,\n method,\n path,\n response,\n errorDescription.code,\n );\n if (requestRetired(session, options)) return retired();\n const failure = {\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n };\n if (attempt === 2) return this.httpFailure(failure);\n\n // An independent replacement or caller cancellation ends this wait. A\n // refusal from the renewal itself must finish reporting its typed error.\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options: waitOptions,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n if (requestRetired(session, options)) return retired();\n const retryToken = this.sessionRenewals.currentToken(authToken);\n if (!shouldRetry || !retryToken) return this.httpFailure(failure);\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n ...failure,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n });\n return this.makeResponseRequest(\n path,\n method,\n body,\n callerOptions,\n additionalSuccessStatuses,\n failureOperation,\n retryToken,\n 2,\n );\n }\n\n private retiredResponse(\n session: AbortSignal,\n method: HttpMethod,\n path: string,\n response: Response,\n code?: string | null,\n ): RequestFailure {\n const retired = retiredRequest(method, path);\n // Principal writes refused before dispatch have a definitive outcome.\n if (response.status !== 401 || !this.sessionRenewals.refused(session))\n return retired;\n return {\n ...retired,\n kind: \"http\",\n status: 401,\n statusText: response.statusText,\n code: code ?? undefined,\n message: `${method} ${path}: 401 ${response.statusText}`,\n };\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n operation: Parameters<OperationResponseRequestFn>[5],\n /** 2 is the retry after a session renewal. */\n attempt = 1,\n ): Promise<RequestResult<Response>> {\n const session = this.sessionRenewals.signal;\n if (options.stillCurrent?.() === false) return retiredRequest(method, path);\n const reportErrors = options.reportErrors ?? true;\n const { headers, init } = sessionRequestInit(\n method,\n body,\n options,\n authToken,\n );\n\n let response: Response;\n const startedAt = Date.now();\n try {\n response = await measureApiRequest(\n this.instrumentation,\n operation,\n () => fetch(`${this.baseUrl}${path}`, init),\n options.signal,\n );\n } catch (error) {\n if (requestRetired(session, options)) return retiredRequest(method, path);\n const { cancelled, networkError } = await settleNetworkFailure({\n attempt,\n baseUrl: this.baseUrl,\n elapsedMs: Date.now() - startedAt,\n error,\n headers,\n isOnline: this.instrumentation?.isOnline,\n method,\n onNetworkError: () => this.onNetworkError?.(),\n pathTemplate: operation.path,\n probe: this.instrumentation?.networkFailureProbe,\n signal: options.signal,\n onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),\n });\n if (requestRetired(session, options)) return retiredRequest(method, path);\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${networkFailureMessage(error, networkError)}`,\n method,\n networkError,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n if (requestRetired(session, options))\n return this.retiredResponse(session, method, path, response);\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.options?.stillCurrent?.() === false)\n return retiredRequest(input.method, input.path);\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import { additionalOperationSuccessStatuses, decodeOperationResponseHeaders, operationResponseFailure, } from "./operationResponse.js";
2
2
  import { deriveRuntimeOperationRequest, mergeOperationRequestHeaders, } from "./operationTransport.js";
3
3
  import { requireOperationTransportSurface } from "./operationTransportSurface.js";
4
- import { retiredRequest } from "./sessionResponse.js";
4
+ import { requestRetired, retiredRequest } from "./sessionResponse.js";
5
5
  async function decodeBinaryOperationResponse(request, operation, response, path, options, session) {
6
- if (session?.aborted)
6
+ if (requestRetired(session, options))
7
7
  return retiredRequest(operation.method, path);
8
8
  if (!operation.responses[response.status] ||
9
9
  operation.responseMediaTypes[response.status] !== "application/octet-stream") {
@@ -1 +1 @@
1
- {"version":3,"file":"binaryResponseOperationTransport.js","sourceRoot":"","sources":["binaryResponseOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAE9B,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAgDnD,KAAK,UAAU,6BAA6B,CAC1C,OAAmC,EACnC,SAAkC,EAClC,QAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAqB;IAErB,IAAI,OAAO,EAAE,OAAO;QAAE,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACpE,IACE,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC;QACrC,SAAS,CAAC,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,0BAA0B,EAC5E,CAAC;QACD,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,kCAAkC,QAAQ,CAAC,MAAM,QAAQ,IAAI,EAAE,CAChE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,8BAA8B,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACpE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,gCAAgC,IAAI,EAAE,CACvC,CAAC;IACJ,CAAC;IAED,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,KAAK,EACL,OAAO,CACR,CAAC;YACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,2BAA2B;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeOperationResponseHeaders,\n type OperationResponseHeadersForStatus,\n operationResponseFailure,\n} from \"./operationResponse\";\nimport {\n deriveRuntimeOperationRequest,\n mergeOperationRequestHeaders,\n type OperationRequestInput,\n type RuntimeOperationRequestInput,\n} from \"./operationTransport\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport { retiredRequest } from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface BinaryResponseOperation extends HttpOperation {\n readonly requestMediaType?: \"application/json\";\n readonly responseMediaTypes: Readonly<\n Record<number, \"application/octet-stream\">\n >;\n}\n\ntype BinaryResponseStatus<Operation extends BinaryResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\nexport type BinaryOperationResponseEnvelope<\n Operation extends BinaryResponseOperation,\n> = {\n [Status in BinaryResponseStatus<Operation>]: {\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly response: Response;\n readonly status: Status;\n };\n}[BinaryResponseStatus<Operation>];\n\ninterface RuntimeBinaryOperationResponseEnvelope {\n readonly headers: unknown;\n readonly response: Response;\n readonly status: number;\n}\n\nexport interface BinaryResponseOperationTransport {\n requestBinaryResponse<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<BinaryOperationResponseEnvelope<Operation> | null>;\n requestBinaryResponseResult<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n}\n\nasync function decodeBinaryOperationResponse(\n request: OperationResponseRequestFn,\n operation: BinaryResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n if (session?.aborted) return retiredRequest(operation.method, path);\n if (\n !operation.responses[response.status] ||\n operation.responseMediaTypes[response.status] !== \"application/octet-stream\"\n ) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid binary response status ${response.status} for ${path}`,\n );\n }\n\n const headers = decodeOperationResponseHeaders(operation, response);\n if (!headers.ok) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response headers for ${path}`,\n );\n }\n\n return {\n data: {\n headers: headers.data,\n response,\n status: response.status,\n },\n ok: true,\n };\n}\n\nexport function createBinaryResponseOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): BinaryResponseOperationTransport {\n function requestBinaryResponseResult<\n Operation extends BinaryResponseOperation,\n >(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n async function requestBinaryResponseResult(\n operation: BinaryResponseOperation,\n input: RuntimeOperationRequestInput,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n requireOperationTransportSurface(operation, \"binaryResponse\");\n const derived = deriveRuntimeOperationRequest(operation, input);\n const headers = mergeOperationRequestHeaders(\n derived.headers,\n options.headers,\n );\n const requestOptions =\n Object.keys(headers).length === 0 ? options : { ...options, headers };\n const session = responseRequest.sessionSignal?.();\n const result = await responseRequest(\n derived.path,\n derived.method,\n derived.body,\n requestOptions,\n additionalOperationSuccessStatuses(operation),\n operation,\n );\n if (!result.ok) {\n return result;\n }\n return decodeBinaryOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n options,\n session,\n );\n }\n\n return {\n async requestBinaryResponse(operation, input, options) {\n const result = await requestBinaryResponseResult(\n operation,\n input,\n options,\n );\n return result.ok ? result.data : null;\n },\n requestBinaryResponseResult,\n };\n}\n"]}
1
+ {"version":3,"file":"binaryResponseOperationTransport.js","sourceRoot":"","sources":["binaryResponseOperationTransport.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,8BAA8B,EAE9B,wBAAwB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAG7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAgDnE,KAAK,UAAU,6BAA6B,CAC1C,OAAmC,EACnC,SAAkC,EAClC,QAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAqB;IAErB,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;QAClC,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAChD,IACE,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC;QACrC,SAAS,CAAC,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,0BAA0B,EAC5E,CAAC;QACD,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,kCAAkC,QAAQ,CAAC,MAAM,QAAQ,IAAI,EAAE,CAChE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,8BAA8B,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IACpE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,gCAAgC,IAAI,EAAE,CACvC,CAAC;IACJ,CAAC;IAED,OAA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AK,EACL,OAAO,CACR,CAAC;YACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;QACD,2BAA2B;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport {\n additionalOperationSuccessStatuses,\n decodeOperationResponseHeaders,\n type OperationResponseHeadersForStatus,\n operationResponseFailure,\n} from \"./operationResponse\";\nimport {\n deriveRuntimeOperationRequest,\n mergeOperationRequestHeaders,\n type OperationRequestInput,\n type RuntimeOperationRequestInput,\n} from \"./operationTransport\";\nimport { requireOperationTransportSurface } from \"./operationTransportSurface\";\nimport { requestRetired, retiredRequest } from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface BinaryResponseOperation extends HttpOperation {\n readonly requestMediaType?: \"application/json\";\n readonly responseMediaTypes: Readonly<\n Record<number, \"application/octet-stream\">\n >;\n}\n\ntype BinaryResponseStatus<Operation extends BinaryResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\nexport type BinaryOperationResponseEnvelope<\n Operation extends BinaryResponseOperation,\n> = {\n [Status in BinaryResponseStatus<Operation>]: {\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly response: Response;\n readonly status: Status;\n };\n}[BinaryResponseStatus<Operation>];\n\ninterface RuntimeBinaryOperationResponseEnvelope {\n readonly headers: unknown;\n readonly response: Response;\n readonly status: number;\n}\n\nexport interface BinaryResponseOperationTransport {\n requestBinaryResponse<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<BinaryOperationResponseEnvelope<Operation> | null>;\n requestBinaryResponseResult<Operation extends BinaryResponseOperation>(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n}\n\nasync function decodeBinaryOperationResponse(\n request: OperationResponseRequestFn,\n operation: BinaryResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n if (requestRetired(session, options))\n return retiredRequest(operation.method, path);\n if (\n !operation.responses[response.status] ||\n operation.responseMediaTypes[response.status] !== \"application/octet-stream\"\n ) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid binary response status ${response.status} for ${path}`,\n );\n }\n\n const headers = decodeOperationResponseHeaders(operation, response);\n if (!headers.ok) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response headers for ${path}`,\n );\n }\n\n return {\n data: {\n headers: headers.data,\n response,\n status: response.status,\n },\n ok: true,\n };\n}\n\nexport function createBinaryResponseOperationTransport(\n responseRequest: OperationResponseRequestFn,\n): BinaryResponseOperationTransport {\n function requestBinaryResponseResult<\n Operation extends BinaryResponseOperation,\n >(\n operation: Operation,\n input: OperationRequestInput<Operation>,\n options?: RequestResultOptions,\n ): Promise<RequestResult<BinaryOperationResponseEnvelope<Operation>>>;\n async function requestBinaryResponseResult(\n operation: BinaryResponseOperation,\n input: RuntimeOperationRequestInput,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<RuntimeBinaryOperationResponseEnvelope>> {\n requireOperationTransportSurface(operation, \"binaryResponse\");\n const derived = deriveRuntimeOperationRequest(operation, input);\n const headers = mergeOperationRequestHeaders(\n derived.headers,\n options.headers,\n );\n const requestOptions =\n Object.keys(headers).length === 0 ? options : { ...options, headers };\n const session = responseRequest.sessionSignal?.();\n const result = await responseRequest(\n derived.path,\n derived.method,\n derived.body,\n requestOptions,\n additionalOperationSuccessStatuses(operation),\n operation,\n );\n if (!result.ok) {\n return result;\n }\n return decodeBinaryOperationResponse(\n responseRequest,\n operation,\n result.data,\n derived.path,\n options,\n session,\n );\n }\n\n return {\n async requestBinaryResponse(operation, input, options) {\n const result = await requestBinaryResponseResult(\n operation,\n input,\n options,\n );\n return result.ok ? result.data : null;\n },\n requestBinaryResponseResult,\n };\n}\n"]}
@@ -23,7 +23,7 @@ export declare class BlobArea {
23
23
  private cacheBlobAttachmentBindResponse;
24
24
  private cacheBlobAttachmentDetachResponse;
25
25
  private attachmentWrite;
26
- initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest): Promise<{
26
+ initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest, options?: RequestResultOptions): Promise<{
27
27
  organizationId: string;
28
28
  byteLength: number;
29
29
  expiresAt: string;
@@ -48,7 +48,7 @@ export declare class BlobArea {
48
48
  }[];
49
49
  uploadId: string;
50
50
  } | null>;
51
- getMultipartBlobStage(stageId: string): Promise<{
51
+ getMultipartBlobStage(stageId: string, options?: RequestResultOptions): Promise<{
52
52
  organizationId: string;
53
53
  byteLength: number;
54
54
  completed: boolean;
@@ -1,3 +1,4 @@
1
+ import { isPlainObject } from "../../validators/isPlainObject.js";
1
2
  import { bindBlobAttachmentOperation, detachBlobAttachmentOperation, getMultipartBlobStageOperation, initiateMultipartBlobStageOperation, listDocumentAttachmentsOperation, } from "../../validators/operation/index.js";
2
3
  import { blobAttachmentSummaryFromStagedBind } from "../../validators/response/index.js";
3
4
  import { bindPrototypeMethods, cachedRequest } from "../requestInternals.js";
@@ -74,11 +75,22 @@ export class BlobArea {
74
75
  }
75
76
  // An attachment write updates the cached listing from its response; a
76
77
  // refused or failed write leaves every listing unknown, so all are dropped.
77
- attachmentWrite(write, cacheResponse) {
78
+ attachmentWrite(write, cacheResponse, body, stillCurrent) {
78
79
  const session = this.context.runtime.responseRequest.sessionSignal?.();
80
+ const { documentId } = isPlainObject(body) ? body : {};
81
+ const current = () => {
82
+ if (session?.aborted)
83
+ return false;
84
+ if (stillCurrent?.() !== false)
85
+ return true;
86
+ // Even a fresh listing from this session may have arrived before the write committed.
87
+ if (typeof documentId === "string")
88
+ this.attachmentLists.delete(documentId);
89
+ return false;
90
+ };
79
91
  return write
80
92
  .then((response) => {
81
- if (session?.aborted)
93
+ if (!current())
82
94
  return null;
83
95
  if (response) {
84
96
  cacheResponse(response);
@@ -89,16 +101,16 @@ export class BlobArea {
89
101
  return response;
90
102
  })
91
103
  .catch((error) => {
92
- if (!session?.aborted)
104
+ if (current())
93
105
  this.attachmentLists.clear();
94
106
  throw error;
95
107
  });
96
108
  }
97
- initiateMultipartBlobStage(input) {
98
- return this.context.send(multipartInitiate, multipartInitiate.path, initiateMultipartBlobStageOperation, input);
109
+ initiateMultipartBlobStage(input, options) {
110
+ return this.context.send(multipartInitiate, multipartInitiate.path, initiateMultipartBlobStageOperation, input, options);
99
111
  }
100
- getMultipartBlobStage(stageId) {
101
- return this.context.send(multipartGet, multipartGet.path(stageId), getMultipartBlobStageOperation);
112
+ getMultipartBlobStage(stageId, options) {
113
+ return this.context.send(multipartGet, multipartGet.path(stageId), getMultipartBlobStageOperation, undefined, options);
102
114
  }
103
115
  uploadMultipartBlobPartBytes(stageId, partNumber, input, options = {}) {
104
116
  return this.transfer(options, (scoped) => uploadMultipartBlobPartBytes(this.context.transport, stageId, partNumber, input, undefined, scoped));
@@ -112,10 +124,10 @@ export class BlobArea {
112
124
  return scoped.signal?.aborted ? null : result;
113
125
  }
114
126
  bindBlobAttachment(blobId, input, options = {}) {
115
- return this.attachmentWrite(this.context.send(blobAttachmentBind, blobAttachmentBind.path(blobId), bindBlobAttachmentOperation, input, options), (response) => this.cacheBlobAttachmentBindResponse(input, response));
127
+ return this.attachmentWrite(this.context.send(blobAttachmentBind, blobAttachmentBind.path(blobId), bindBlobAttachmentOperation, input, options), (response) => this.cacheBlobAttachmentBindResponse(input, response), input.body, options.stillCurrent);
116
128
  }
117
129
  detachBlobAttachment(blobId, bindingId, input, options = {}) {
118
- return this.attachmentWrite(this.context.send(blobAttachmentDetach, blobAttachmentDetach.path(blobId, bindingId), detachBlobAttachmentOperation, input, options), this.cacheBlobAttachmentDetachResponse);
130
+ return this.attachmentWrite(this.context.send(blobAttachmentDetach, blobAttachmentDetach.path(blobId, bindingId), detachBlobAttachmentOperation, input, options), this.cacheBlobAttachmentDetachResponse, input.body, options.stillCurrent);
119
131
  }
120
132
  listDocumentAttachments(documentId, options = {}) {
121
133
  if (options.refresh) {
@@ -1 +1 @@
1
- {"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,GACjC,MAAM,iCAAiC,CAAC;AAWzC,OAAO,EAAE,mCAAmC,EAAE,MAAM,gCAAgC,CAAC;AACrF,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,kBAAkB,IAAI,kBAAkB,EACxC,oBAAoB,IAAI,oBAAoB,GAC7C,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,YAAY,GAEb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,qBAAqB,IAAI,YAAY,EACrC,0BAA0B,IAAI,iBAAiB,GAChD,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,uBAAuB,IAAI,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAMrG;;;GAGG;AACH,MAAM,OAAO,QAAQ;IAGU;IAFZ,eAAe,CAAiE;IAEjG,YAA6B,OAAyB;QAAzB,YAAO,GAAP,OAAO,CAAkB;QACpD,oBAAoB,CAAC,IAAI,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC/C,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,0CAA0C,CAAC;IAC5E,CAAC;IAEO,kCAAkC,CACxC,UAAkB,EAClB,MAAuD;QAEvD,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACpD,IA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AC,EAC/B,2BAA2B,EAC3B,KAAK,EACL,OAAO,CACR,EACD,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,+BAA+B,CAAC,KAAK,EAAE,QAAQ,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,oBAAoB,CAClB,MAAc,EACd,SAAiB,EACjB,KAAkC,EAClC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,oBAAoB,EACpB,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAC5C,6BAA6B,EAC7B,KAAK,EACL,OAAO,CACR,EACD,IAAI,CAAC,iCAAiC,CACvC,CAAC;IACJ,CAAC;IAED,uBAAuB,CACrB,UAAkB,EAClB,UAAiC,EAAE;QAEnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,CAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,uBAAuB,EACvB,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n ): Promise<R | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n return write\n .then((response) => {\n if (session?.aborted) return null;\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n if (!session?.aborted) this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(input: InitiateMultipartBlobStageRequest) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n );\n }\n\n getMultipartBlobStage(stageId: string) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return this.transfer(options, (scoped) =>\n uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n scoped,\n ),\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return this.transfer(options, (scoped) =>\n getBlobBytes(this.context.transport, blobId, undefined, scoped),\n );\n }\n\n private async transfer<T>(\n options: RequestResultOptions,\n run: (scoped: RequestResultOptions) => Promise<T | null>,\n ): Promise<T | null> {\n const scoped = this.context.runtime.withSessionSignal(options);\n const result = await run(scoped);\n return scoped.signal?.aborted ? null : result;\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"blobs.js","sourceRoot":"","sources":["blobs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,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AChB,MAAc,EACd,KAAgC,EAChC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,kBAAkB,EAClB,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,EAC/B,2BAA2B,EAC3B,KAAK,EACL,OAAO,CACR,EACD,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,+BAA+B,CAAC,KAAK,EAAE,QAAQ,CAAC,EACnE,KAAK,CAAC,IAAI,EACV,OAAO,CAAC,YAAY,CACrB,CAAC;IACJ,CAAC;IAED,oBAAoB,CAClB,MAAc,EACd,SAAiB,EACjB,KAAkC,EAClC,UAAgC,EAAE;QAElC,OAAO,IAAI,CAAC,eAAe,CACzB,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,oBAAoB,EACpB,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAC5C,6BAA6B,EAC7B,KAAK,EACL,OAAO,CACR,EACD,IAAI,CAAC,iCAAiC,EACtC,KAAK,CAAC,IAAI,EACV,OAAO,CAAC,YAAY,CACrB,CAAC;IACJ,CAAC;IAED,uBAAuB,CACrB,UAAkB,EAClB,UAAiC,EAAE;QAEnC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,CAAC,eAAe,EAAE,UAAU,EAAE,GAAG,EAAE,CAC1D,IAAI,CAAC,OAAO,CAAC,IAAI,CACf,uBAAuB,EACvB,uBAAuB,CAAC,IAAI,CAAC,UAAU,CAAC,EACxC,gCAAgC,CACjC,CACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { isPlainObject } from \"@tearleads/validators/isPlainObject\";\nimport {\n bindBlobAttachmentOperation,\n detachBlobAttachmentOperation,\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n listDocumentAttachmentsOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport { blobAttachmentSummaryFromStagedBind } from \"@tearleads/validators/response\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n bindBlobAttachment as blobAttachmentBind,\n detachBlobAttachment as blobAttachmentDetach,\n} from \"../routes/blobs/attachments\";\nimport {\n getBlobBytes,\n type UploadMultipartBlobPartBytesRequest,\n} from \"../routes/blobs/get\";\nimport {\n getMultipartBlobStage as multipartGet,\n initiateMultipartBlobStage as multipartInitiate,\n} from \"../routes/blobs/multipart\";\nimport { uploadMultipartBlobPartBytes } from \"../routes/blobs/multipartUpload\";\nimport { listDocumentAttachments as documentAttachmentsList } from \"../routes/documents/attachments\";\nimport type { RequestResultOptions } from \"../types\";\nimport type { ApiClientContext } from \"./apiClientContext\";\n\ntype AttachmentList = ListDocumentAttachmentsResponse;\n\n/**\n * Multipart blob staging, blob bytes, and document attachment bindings, with\n * the per-document attachment listing cache they keep current.\n */\nexport class BlobArea {\n private readonly attachmentLists: ApiClientContext[\"documentAttachmentListRequestsByDocumentId\"];\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, BlobArea.prototype);\n this.attachmentLists = context.documentAttachmentListRequestsByDocumentId;\n }\n\n private updateCachedDocumentAttachmentList(\n documentId: string,\n update: (attachments: AttachmentList) => AttachmentList,\n ): void {\n const cached = this.attachmentLists.get(documentId);\n if (!cached) {\n return;\n }\n\n let next: Promise<AttachmentList | null>;\n next = cached\n .then((attachments) => {\n if (!attachments) {\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return attachments;\n }\n\n return update(attachments);\n })\n .catch(() => {\n // The underlying list fetch failed. Drop this derived cache entry so the\n // next read refetches, and resolve to null (the cache's miss semantics)\n // rather than rethrowing: nothing awaits this derived promise directly,\n // so a rethrow would surface as an unhandled rejection. Callers already\n // awaiting the original request still observe its rejection.\n if (this.attachmentLists.get(documentId) === next) {\n this.attachmentLists.delete(documentId);\n }\n return null;\n });\n this.attachmentLists.set(documentId, next);\n }\n\n /**\n * The bind acknowledges by hash, so the cached listing entry is rebuilt\n * from the request it acknowledged: a staged upload's bind creates the blob,\n * so its one binding's KEK targets are the ones its content-key bundle wraps\n * to, and it stores exactly the signed event, bundle, and write header it\n * carried. Any other bind (no staged blob, or a target set other than the\n * one the bundle names) keeps material the response does not carry, so it\n * drops the cached listing instead.\n */\n private cacheBlobAttachmentBindResponse(\n request: BlobAttachmentBindRequest,\n response: BlobAttachmentBindResponse,\n ): void {\n const { stagedBlob } = request;\n if (\n !stagedBlob ||\n response.blobKeyTargetHash !== request.contentKeyBundle.targetHash\n ) {\n this.attachmentLists.delete(response.documentId);\n return;\n }\n const binding = blobAttachmentSummaryFromStagedBind(\n { ...request, stagedBlob },\n response,\n );\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) => [\n ...attachments.filter(\n (cachedBinding) => cachedBinding.slotId !== response.slotId,\n ),\n binding,\n ],\n );\n }\n\n private cacheBlobAttachmentDetachResponse(\n response: BlobAttachmentDetachResponse,\n ): void {\n this.updateCachedDocumentAttachmentList(\n response.documentId,\n (attachments) =>\n attachments.filter(\n (binding) => binding.bindingId !== response.bindingId,\n ),\n );\n }\n\n // An attachment write updates the cached listing from its response; a\n // refused or failed write leaves every listing unknown, so all are dropped.\n private attachmentWrite<R>(\n write: Promise<R | null>,\n cacheResponse: (response: R) => void,\n body: unknown,\n stillCurrent: RequestResultOptions[\"stillCurrent\"],\n ): Promise<R | null> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const { documentId } = isPlainObject(body) ? body : {};\n\n const current = () => {\n if (session?.aborted) return false;\n if (stillCurrent?.() !== false) return true;\n // Even a fresh listing from this session may have arrived before the write committed.\n if (typeof documentId === \"string\")\n this.attachmentLists.delete(documentId);\n return false;\n };\n return write\n .then((response) => {\n if (!current()) return null;\n if (response) {\n cacheResponse(response);\n } else {\n this.attachmentLists.clear();\n }\n return response;\n })\n .catch((error: unknown) => {\n if (current()) this.attachmentLists.clear();\n throw error;\n });\n }\n\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\n ) {\n return this.context.send(\n multipartInitiate,\n multipartInitiate.path,\n initiateMultipartBlobStageOperation,\n input,\n options,\n );\n }\n\n getMultipartBlobStage(stageId: string, options?: RequestResultOptions) {\n return this.context.send(\n multipartGet,\n multipartGet.path(stageId),\n getMultipartBlobStageOperation,\n undefined,\n options,\n );\n }\n\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options: RequestResultOptions = {},\n ) {\n return this.transfer(options, (scoped) =>\n uploadMultipartBlobPartBytes(\n this.context.transport,\n stageId,\n partNumber,\n input,\n undefined,\n scoped,\n ),\n );\n }\n\n getBlobBytes(blobId: string, options: RequestResultOptions = {}) {\n return this.transfer(options, (scoped) =>\n getBlobBytes(this.context.transport, blobId, undefined, scoped),\n );\n }\n\n private async transfer<T>(\n options: RequestResultOptions,\n run: (scoped: RequestResultOptions) => Promise<T | null>,\n ): Promise<T | null> {\n const scoped = this.context.runtime.withSessionSignal(options);\n const result = await run(scoped);\n return scoped.signal?.aborted ? null : result;\n }\n\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentBind,\n blobAttachmentBind.path(blobId),\n bindBlobAttachmentOperation,\n input,\n options,\n ),\n (response) => this.cacheBlobAttachmentBindResponse(input, response),\n input.body,\n options.stillCurrent,\n );\n }\n\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options: RequestResultOptions = {},\n ) {\n return this.attachmentWrite(\n this.context.send(\n blobAttachmentDetach,\n blobAttachmentDetach.path(blobId, bindingId),\n detachBlobAttachmentOperation,\n input,\n options,\n ),\n this.cacheBlobAttachmentDetachResponse,\n input.body,\n options.stillCurrent,\n );\n }\n\n listDocumentAttachments(\n documentId: string,\n options: { refresh?: boolean } = {},\n ) {\n if (options.refresh) {\n this.attachmentLists.delete(documentId);\n }\n return cachedRequest(this.attachmentLists, documentId, () =>\n this.context.send(\n documentAttachmentsList,\n documentAttachmentsList.path(documentId),\n listDocumentAttachmentsOperation,\n ),\n );\n }\n}\n"]}
@@ -33,7 +33,8 @@ export class WriterProjectionArea {
33
33
  // request directly with the caller's options, join no shared fetch, and
34
34
  // never publish the outcome to the shared caches. Only reporting-only
35
35
  // callers below participate in coalescing and cache warming.
36
- if (options.headers !== undefined ||
36
+ if (options.stillCurrent !== undefined ||
37
+ options.headers !== undefined ||
37
38
  options.retryOnSessionExpired !== undefined) {
38
39
  return this.context.requestResult(path, validator, "GET", undefined, options, failureOperation);
39
40
  }
@@ -1 +1 @@
1
- {"version":3,"file":"writerProjections.js","sourceRoot":"","sources":["writerProjections.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AAMzC,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAkBrE;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAIF;IAHZ,UAAU,CAAqD;IAC/D,SAAS,CAAoD;IAE9E,YAA6B,OAAyB;QAAzB,YAAO,GAAP,OAAO,CAAkB;QACpD,oBAAoB,CAAC,IAAI,EAAE,oBAAo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riterProjectionOperation,\n type HttpOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { BoundedCache } from \"../ApiCache\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n containerWriterProjection,\n documentWriterProjection,\n} from \"../routes/writerProjections\";\nimport { retiredRequest } from \"../sessionResponse\";\nimport type { RequestResult, RequestResultOptions } from \"../types\";\nimport type { WriterProjectionListing } from \"../verifiedManifestCitations\";\nimport { primeWriterProjectionSlot } from \"../writerProjectionPrime\";\nimport type {\n ApiClientContext,\n InFlightWriterProjectionResult,\n} from \"./apiClientContext\";\n\ninterface ProjectionSlots<T> {\n readonly cache: BoundedCache<Promise<T | null>>;\n readonly inFlightResults: Map<string, InFlightWriterProjectionResult<T>>;\n}\n\ninterface ProjectionRead<T> {\n readonly cacheKey: string;\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n readonly failureOperation: HttpOperation;\n}\n\n/**\n * Container and document writer projections: plain cached reads, coalesced\n * status-bearing reads, and primes from just-authored mutation material.\n */\nexport class WriterProjectionArea {\n private readonly containers: ProjectionSlots<ContainerWriterProjectionResponse>;\n private readonly documents: ProjectionSlots<DocumentWriterProjectionResponse>;\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, WriterProjectionArea.prototype);\n this.containers = {\n cache: context.containerWriterProjectionRequestsByContainerId,\n inFlightResults:\n context.containerWriterProjectionResultsInFlightByContainerId,\n };\n this.documents = {\n cache: context.documentWriterProjectionRequestsByDocumentId,\n inFlightResults:\n context.documentWriterProjectionResultsInFlightByDocumentId,\n };\n }\n\n // Shared by the writer-projection result variants: coalesce concurrent\n // result callers onto one in-flight fetch, reuse a cached success, fetch a\n // result otherwise, and reconcile the cache without ever clobbering an entry\n // that changed while the fetch was in flight.\n private writerProjectionResult<T>(\n { cache, inFlightResults }: ProjectionSlots<T>,\n read: ProjectionRead<T>,\n options: RequestResultOptions,\n ): Promise<RequestResult<T>> {\n const { cacheKey, path, validator, failureOperation } = read;\n // Request-affecting options make the response caller-specific: run the\n // request directly with the caller's options, join no shared fetch, and\n // never publish the outcome to the shared caches. Only reporting-only\n // callers below participate in coalescing and cache warming.\n if (\n options.headers !== undefined ||\n options.retryOnSessionExpired !== undefined\n ) {\n return this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n options,\n failureOperation,\n );\n }\n\n // A concurrent burst shares one fetch — failure included — so it cannot\n // repeat the HTTP request or the 402 billing signal. The entry lives only\n // while the fetch is in flight: failures are shared, never cached, so a\n // later retry refetches. An in-flight fetch is joinable only while the\n // value slot and per-key invalidation stamp it started against are\n // unchanged: a prime, a completed plain GET, or an eviction of THIS id\n // that lands mid-flight makes the older fetch unadoptable, so a later\n // caller reads the current cache state (or fetches fresh) instead of\n // joining a fetch that predates it — while invalidations of other ids\n // leave the coalescing intact. Eviction and priming also delete the\n // entry outright; the identity guard keeps a late settle from deleting a\n // successor's entry.\n //\n // The shared fetch itself is always silent; each caller applies its OWN\n // reporting policy to the shared outcome below. Coalescing therefore\n // never lets one caller's reportErrors suppress (or force) another's,\n // and caller options never reach the request — the fetch takes none.\n const slot = cache.get(cacheKey);\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const inFlight = inFlightResults.get(cacheKey);\n let shared: Promise<RequestResult<T>>;\n if (\n inFlight &&\n inFlight.slot === slot &&\n inFlight.invalidationStamp === invalidationStamp\n ) {\n shared = inFlight.resultPromise;\n } else {\n const entry: InFlightWriterProjectionResult<T> = {\n invalidationStamp,\n resultPromise: this.fetchWriterProjectionResult(cache, read).finally(\n () => {\n if (inFlightResults.get(cacheKey) === entry) {\n inFlightResults.delete(cacheKey);\n }\n },\n ),\n slot,\n };\n inFlightResults.set(cacheKey, entry);\n shared = entry.resultPromise;\n }\n\n if (options.reportErrors === false) {\n return shared;\n }\n return shared.then((result) => {\n if (!result.ok) {\n result.report();\n }\n return result;\n });\n }\n\n // The fetch half of writerProjectionResult. Cache reconciliation guards\n // against both mid-flight slot replacement (identity comparison) and\n // mid-flight eviction of an empty slot (the per-key invalidation stamp),\n // so a projection an eviction (e.g. after a revoke) meant to drop is never\n // re-cached.\n private async fetchWriterProjectionResult<T>(\n cache: BoundedCache<Promise<T | null>>,\n { cacheKey, path, validator, failureOperation }: ProjectionRead<T>,\n ): Promise<RequestResult<T>> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const retired = () => retiredRequest(\"GET\", path);\n let cached = cache.get(cacheKey);\n while (cached) {\n // Rejected and empty entries both fall through to the current slot.\n const data = await cached.catch(() => null);\n if (session?.aborted) return retired();\n if (data) return { data, ok: true };\n // A newer entry installed during the wait must be reused.\n const current = cache.get(cacheKey);\n if (current === cached) {\n break;\n }\n cached = current;\n }\n\n // The plain value cache never sees this fetch while it is in flight: a\n // published always-silent entry would hand a concurrent PLAIN caller a\n // null without its normal error reporting. Plain callers keep their own\n // fetch-and-report behavior instead, and only a success is published.\n // Always silent here: reporting is per-caller in writerProjectionResult,\n // and taking no caller options is what guarantees nothing\n // request-affecting can be smuggled into the shared fetch.\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const result = await this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n {\n reportErrors: false,\n },\n failureOperation,\n );\n\n if (session?.aborted) return retired();\n if (result.ok) {\n // Publish the success unless the slot changed or this id was\n // invalidated mid-flight. The stamp check is what makes an eviction of\n // THIS id visible even when the slot was empty before and after the\n // flight — the case the identity comparison alone cannot see — and it\n // never caches a projection an eviction meant to drop.\n if (\n cache.get(cacheKey) === cached &&\n cache.invalidationStamp(cacheKey) === invalidationStamp\n ) {\n cache.set(cacheKey, Promise.resolve(result.data));\n }\n } else if (cached && cache.get(cacheKey) === cached) {\n // The adopted entry settled empty and the fetch confirmed there is\n // nothing to serve: drop it so a later read refetches.\n cache.delete(cacheKey);\n }\n\n return result;\n }\n\n /** `listing` only picks which held bytes an unstored container cites. */\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ) {\n return cachedRequest(this.containers.cache, containerId, () =>\n this.context.request(\n containerWriterProjection.path(containerId),\n containerWriterProjection.isResponseFor(containerId),\n containerWriterProjection.method,\n undefined,\n listing ? { projectionListing: listing } : undefined,\n getContainerWriterProjectionOperation,\n ),\n );\n }\n\n getContainerWriterProjectionResult(\n containerId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<ContainerWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.containers,\n {\n cacheKey: containerId,\n path: containerWriterProjection.path(containerId),\n validator: containerWriterProjection.isResponseFor(containerId),\n failureOperation: getContainerWriterProjectionOperation,\n },\n options,\n );\n }\n\n getDocumentWriterProjection(documentId: string) {\n return cachedRequest(this.documents.cache, documentId, () =>\n this.context.request(\n documentWriterProjection.path(documentId),\n documentWriterProjection.isResponseFor(documentId),\n documentWriterProjection.method,\n undefined,\n undefined,\n getDocumentWriterProjectionOperation,\n ),\n );\n }\n\n getDocumentWriterProjectionResult(\n documentId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.documents,\n {\n cacheKey: documentId,\n path: documentWriterProjection.path(documentId),\n validator: documentWriterProjection.isResponseFor(documentId),\n failureOperation: getDocumentWriterProjectionOperation,\n },\n options,\n );\n }\n\n /**\n * Seed the writer-projection cache from a mutation response the client just\n * authored, so the next read resolves locally instead of a cold\n * `GET /documents/:documentId/writer-projection`. The seed is the same\n * material a fresh fetch returns (create/link/sync responses carry the\n * manifest, content-key bundle, and KEK targets; authorizing paths are the\n * projection the client supplied). No-op when a fetch is in flight or the\n * slot is primed — never clobber an existing entry. The existing invalidation\n * paths (sync-change, share/rekey/move, link/unlink) evict a primed\n * projection that later goes stale, exactly as they evict a fetched one.\n */\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.documents.cache,\n describes: documentWriterProjection.isResponseFor(documentId),\n id: documentId,\n inFlightResults: this.documents.inFlightResults,\n label: \"Document\",\n projection,\n });\n }\n\n /**\n * Container counterpart of {@link primeDocumentWriterProjection}: seed the\n * container writer-projection cache from a create the client just authored so\n * the next write under that container (a child folder, a document) resolves\n * locally instead of a cold `GET /containers/:containerId/writer-projection`.\n * The seed is the same material a fresh fetch returns — the create plan's\n * authorizing path and container KEKs — validated by the caller against the\n * create response before priming. No-op when a fetch is in flight or the slot\n * is already primed, so it never clobbers a newer entry. The existing\n * invalidation (share/revoke/rekey/move/delete -> clearWriterProjectionCaches)\n * evicts a primed projection that later goes stale exactly as it evicts a\n * fetched one, so a subsequent write on stale access still fails closed and\n * retries with a fresh projection.\n */\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.containers.cache,\n describes: containerWriterProjection.isResponseFor(containerId),\n id: containerId,\n inFlightResults: this.containers.inFlightResults,\n label: \"Container\",\n projection,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"writerProjections.js","sourceRoot":"","sources":["writerProjections.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oCAAoC,GAErC,MAAM,iCAAiC,CAAC;AAMzC,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAkBrE;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAIF;IAHZ,UAAU,CAAqD;IAC/D,SAAS,CAAoD;IAE9E,YAA6B,OAAyB;QAAzB,YAAO,GAAP,OAAO,CAAkB;QACpD,oBAAoB,CAAC,IAAI,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;QAC3D,IAAI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ProjectionOperation,\n type HttpOperation,\n} from \"@tearleads/validators/operation\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { BoundedCache } from \"../ApiCache\";\nimport { bindPrototypeMethods, cachedRequest } from \"../requestInternals\";\nimport {\n containerWriterProjection,\n documentWriterProjection,\n} from \"../routes/writerProjections\";\nimport { retiredRequest } from \"../sessionResponse\";\nimport type { RequestResult, RequestResultOptions } from \"../types\";\nimport type { WriterProjectionListing } from \"../verifiedManifestCitations\";\nimport { primeWriterProjectionSlot } from \"../writerProjectionPrime\";\nimport type {\n ApiClientContext,\n InFlightWriterProjectionResult,\n} from \"./apiClientContext\";\n\ninterface ProjectionSlots<T> {\n readonly cache: BoundedCache<Promise<T | null>>;\n readonly inFlightResults: Map<string, InFlightWriterProjectionResult<T>>;\n}\n\ninterface ProjectionRead<T> {\n readonly cacheKey: string;\n readonly path: string;\n readonly validator: (value: unknown) => value is T;\n readonly failureOperation: HttpOperation;\n}\n\n/**\n * Container and document writer projections: plain cached reads, coalesced\n * status-bearing reads, and primes from just-authored mutation material.\n */\nexport class WriterProjectionArea {\n private readonly containers: ProjectionSlots<ContainerWriterProjectionResponse>;\n private readonly documents: ProjectionSlots<DocumentWriterProjectionResponse>;\n\n constructor(private readonly context: ApiClientContext) {\n bindPrototypeMethods(this, WriterProjectionArea.prototype);\n this.containers = {\n cache: context.containerWriterProjectionRequestsByContainerId,\n inFlightResults:\n context.containerWriterProjectionResultsInFlightByContainerId,\n };\n this.documents = {\n cache: context.documentWriterProjectionRequestsByDocumentId,\n inFlightResults:\n context.documentWriterProjectionResultsInFlightByDocumentId,\n };\n }\n\n // Shared by the writer-projection result variants: coalesce concurrent\n // result callers onto one in-flight fetch, reuse a cached success, fetch a\n // result otherwise, and reconcile the cache without ever clobbering an entry\n // that changed while the fetch was in flight.\n private writerProjectionResult<T>(\n { cache, inFlightResults }: ProjectionSlots<T>,\n read: ProjectionRead<T>,\n options: RequestResultOptions,\n ): Promise<RequestResult<T>> {\n const { cacheKey, path, validator, failureOperation } = read;\n // Request-affecting options make the response caller-specific: run the\n // request directly with the caller's options, join no shared fetch, and\n // never publish the outcome to the shared caches. Only reporting-only\n // callers below participate in coalescing and cache warming.\n if (\n options.stillCurrent !== undefined ||\n options.headers !== undefined ||\n options.retryOnSessionExpired !== undefined\n ) {\n return this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n options,\n failureOperation,\n );\n }\n\n // A concurrent burst shares one fetch — failure included — so it cannot\n // repeat the HTTP request or the 402 billing signal. The entry lives only\n // while the fetch is in flight: failures are shared, never cached, so a\n // later retry refetches. An in-flight fetch is joinable only while the\n // value slot and per-key invalidation stamp it started against are\n // unchanged: a prime, a completed plain GET, or an eviction of THIS id\n // that lands mid-flight makes the older fetch unadoptable, so a later\n // caller reads the current cache state (or fetches fresh) instead of\n // joining a fetch that predates it — while invalidations of other ids\n // leave the coalescing intact. Eviction and priming also delete the\n // entry outright; the identity guard keeps a late settle from deleting a\n // successor's entry.\n //\n // The shared fetch itself is always silent; each caller applies its OWN\n // reporting policy to the shared outcome below. Coalescing therefore\n // never lets one caller's reportErrors suppress (or force) another's,\n // and caller options never reach the request — the fetch takes none.\n const slot = cache.get(cacheKey);\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const inFlight = inFlightResults.get(cacheKey);\n let shared: Promise<RequestResult<T>>;\n if (\n inFlight &&\n inFlight.slot === slot &&\n inFlight.invalidationStamp === invalidationStamp\n ) {\n shared = inFlight.resultPromise;\n } else {\n const entry: InFlightWriterProjectionResult<T> = {\n invalidationStamp,\n resultPromise: this.fetchWriterProjectionResult(cache, read).finally(\n () => {\n if (inFlightResults.get(cacheKey) === entry) {\n inFlightResults.delete(cacheKey);\n }\n },\n ),\n slot,\n };\n inFlightResults.set(cacheKey, entry);\n shared = entry.resultPromise;\n }\n\n if (options.reportErrors === false) {\n return shared;\n }\n return shared.then((result) => {\n if (!result.ok) {\n result.report();\n }\n return result;\n });\n }\n\n // The fetch half of writerProjectionResult. Cache reconciliation guards\n // against both mid-flight slot replacement (identity comparison) and\n // mid-flight eviction of an empty slot (the per-key invalidation stamp),\n // so a projection an eviction (e.g. after a revoke) meant to drop is never\n // re-cached.\n private async fetchWriterProjectionResult<T>(\n cache: BoundedCache<Promise<T | null>>,\n { cacheKey, path, validator, failureOperation }: ProjectionRead<T>,\n ): Promise<RequestResult<T>> {\n const session = this.context.runtime.responseRequest.sessionSignal?.();\n const retired = () => retiredRequest(\"GET\", path);\n let cached = cache.get(cacheKey);\n while (cached) {\n // Rejected and empty entries both fall through to the current slot.\n const data = await cached.catch(() => null);\n if (session?.aborted) return retired();\n if (data) return { data, ok: true };\n // A newer entry installed during the wait must be reused.\n const current = cache.get(cacheKey);\n if (current === cached) {\n break;\n }\n cached = current;\n }\n\n // The plain value cache never sees this fetch while it is in flight: a\n // published always-silent entry would hand a concurrent PLAIN caller a\n // null without its normal error reporting. Plain callers keep their own\n // fetch-and-report behavior instead, and only a success is published.\n // Always silent here: reporting is per-caller in writerProjectionResult,\n // and taking no caller options is what guarantees nothing\n // request-affecting can be smuggled into the shared fetch.\n const invalidationStamp = cache.invalidationStamp(cacheKey);\n const result = await this.context.requestResult(\n path,\n validator,\n \"GET\",\n undefined,\n {\n reportErrors: false,\n },\n failureOperation,\n );\n\n if (session?.aborted) return retired();\n if (result.ok) {\n // Publish the success unless the slot changed or this id was\n // invalidated mid-flight. The stamp check is what makes an eviction of\n // THIS id visible even when the slot was empty before and after the\n // flight — the case the identity comparison alone cannot see — and it\n // never caches a projection an eviction meant to drop.\n if (\n cache.get(cacheKey) === cached &&\n cache.invalidationStamp(cacheKey) === invalidationStamp\n ) {\n cache.set(cacheKey, Promise.resolve(result.data));\n }\n } else if (cached && cache.get(cacheKey) === cached) {\n // The adopted entry settled empty and the fetch confirmed there is\n // nothing to serve: drop it so a later read refetches.\n cache.delete(cacheKey);\n }\n\n return result;\n }\n\n /** `listing` only picks which held bytes an unstored container cites. */\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ) {\n return cachedRequest(this.containers.cache, containerId, () =>\n this.context.request(\n containerWriterProjection.path(containerId),\n containerWriterProjection.isResponseFor(containerId),\n containerWriterProjection.method,\n undefined,\n listing ? { projectionListing: listing } : undefined,\n getContainerWriterProjectionOperation,\n ),\n );\n }\n\n getContainerWriterProjectionResult(\n containerId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<ContainerWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.containers,\n {\n cacheKey: containerId,\n path: containerWriterProjection.path(containerId),\n validator: containerWriterProjection.isResponseFor(containerId),\n failureOperation: getContainerWriterProjectionOperation,\n },\n options,\n );\n }\n\n getDocumentWriterProjection(documentId: string) {\n return cachedRequest(this.documents.cache, documentId, () =>\n this.context.request(\n documentWriterProjection.path(documentId),\n documentWriterProjection.isResponseFor(documentId),\n documentWriterProjection.method,\n undefined,\n undefined,\n getDocumentWriterProjectionOperation,\n ),\n );\n }\n\n getDocumentWriterProjectionResult(\n documentId: string,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<DocumentWriterProjectionResponse>> {\n return this.writerProjectionResult(\n this.documents,\n {\n cacheKey: documentId,\n path: documentWriterProjection.path(documentId),\n validator: documentWriterProjection.isResponseFor(documentId),\n failureOperation: getDocumentWriterProjectionOperation,\n },\n options,\n );\n }\n\n /**\n * Seed the writer-projection cache from a mutation response the client just\n * authored, so the next read resolves locally instead of a cold\n * `GET /documents/:documentId/writer-projection`. The seed is the same\n * material a fresh fetch returns (create/link/sync responses carry the\n * manifest, content-key bundle, and KEK targets; authorizing paths are the\n * projection the client supplied). No-op when a fetch is in flight or the\n * slot is primed — never clobber an existing entry. The existing invalidation\n * paths (sync-change, share/rekey/move, link/unlink) evict a primed\n * projection that later goes stale, exactly as they evict a fetched one.\n */\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.documents.cache,\n describes: documentWriterProjection.isResponseFor(documentId),\n id: documentId,\n inFlightResults: this.documents.inFlightResults,\n label: \"Document\",\n projection,\n });\n }\n\n /**\n * Container counterpart of {@link primeDocumentWriterProjection}: seed the\n * container writer-projection cache from a create the client just authored so\n * the next write under that container (a child folder, a document) resolves\n * locally instead of a cold `GET /containers/:containerId/writer-projection`.\n * The seed is the same material a fresh fetch returns — the create plan's\n * authorizing path and container KEKs — validated by the caller against the\n * create response before priming. No-op when a fetch is in flight or the slot\n * is already primed, so it never clobbers a newer entry. The existing\n * invalidation (share/revoke/rekey/move/delete -> clearWriterProjectionCaches)\n * evicts a primed projection that later goes stale exactly as it evicts a\n * fetched one, so a subsequent write on stale access still fails closed and\n * retries with a fresh projection.\n */\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void {\n primeWriterProjectionSlot({\n cache: this.containers.cache,\n describes: containerWriterProjection.isResponseFor(containerId),\n id: containerId,\n inFlightResults: this.containers.inFlightResults,\n label: \"Container\",\n projection,\n });\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { operationResponseHeaderNames, } from "../validators/operation/index.js";
2
- import { readSessionJson, retiredRequest } from "./sessionResponse.js";
2
+ import { readSessionJson, requestRetired, retiredRequest, } from "./sessionResponse.js";
3
3
  export function additionalOperationSuccessStatuses(operation) {
4
4
  return [
5
5
  ...Object.keys(operation.responses).map(Number),
@@ -33,7 +33,7 @@ export function decodeOperationResponseHeaders(operation, response) {
33
33
  return parsed.success ? { data: parsed.data, ok: true } : { ok: false };
34
34
  }
35
35
  export async function decodeJsonOperationResponse(request, operation, response, path, options, session) {
36
- if (session?.aborted)
36
+ if (requestRetired(session, options))
37
37
  return retiredRequest(operation.method, path);
38
38
  const schema = operation.responses[response.status];
39
39
  const isEmpty = operation.emptyResponseStatuses?.includes(response.status) ?? false;
@@ -47,7 +47,7 @@ export async function decodeJsonOperationResponse(request, operation, response,
47
47
  let data;
48
48
  if (!isEmpty && schema) {
49
49
  const result = await readSessionJson(request, response, operation.method, path, options, session);
50
- if (session?.aborted)
50
+ if (requestRetired(session, options))
51
51
  return retiredRequest(operation.method, path);
52
52
  if (!result.ok)
53
53
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"operationResponse.js","sourceRoot":"","sources":["operationResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAC7B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAkEpE,MAAM,UAAU,kCAAkC,CAChD,SAAwB;IAExB,OAAO;QACL,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC;QAC/C,GAAG,CAAC,SAAS,CAAC,qBAAqB,IAAI,EAAE,CAAC;KAC3C,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,GAAG,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC;AACtD,CAAC;AAQD,MAAM,UAAU,wBAAwB,CACtC,OAAmC,EACnC,SAAwB,EACxB,QAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAe;IAEf,OAAO,OAAO,CAAC,aAAa,CAAC;QAC3B,IAAI,EAAE,OAAO;QACb,OAAO;QACP,MAAM,EAAE,SAAS,CAAC,MAAM;QACxB,OAAO;QACP,IAAI;QACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;KAChC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,SAAwB,EACxB,QAAkB;IAElB,MAAM,MAAM,GAAG,SAAS,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5D,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,EAAE,CAA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SAAS,EAAE,QAAQ,CAAC,CAAC;IACpE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,gCAAgC,IAAI,EAAE,CACvC,CAAC;IACJ,CAAC;IAED,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC,OAAO,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,OAAO,EACP,QAAQ,EACR,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,OAAO,EACP,OAAO,CACR,CAAC;QACF,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,8BAA8B,IAAI,EAAE,CACrC,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,OAAO;QACL,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC9D,EAAE,EAAE,IAAI;KACT,CAAC;AACJ,CAAC","sourcesContent":["import {\n type HttpOperation,\n type OperationSchemaOutput,\n operationResponseHeaderNames,\n} from \"@tearleads/validators/operation\";\nimport { readSessionJson, retiredRequest } from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface JsonResponseOperation extends HttpOperation {\n readonly responseMediaTypes?: Readonly<Record<number, \"application/json\">>;\n}\n\ntype BodyResponseStatus<Operation extends JsonResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\ntype EmptyResponseStatus<Operation extends JsonResponseOperation> =\n Operation extends {\n readonly emptyResponseStatuses: readonly (infer Status)[];\n }\n ? Extract<Status, number>\n : never;\n\ntype SuccessStatus<Operation extends JsonResponseOperation> =\n | BodyResponseStatus<Operation>\n | EmptyResponseStatus<Operation>;\n\ntype ResponseBodyForStatus<\n Operation extends JsonResponseOperation,\n Status extends number,\n> = Status extends keyof Operation[\"responses\"]\n ? OperationSchemaOutput<\n Extract<Operation[\"responses\"][Status], HttpOperation[\"params\"]>\n >\n : undefined;\n\nexport type OperationResponseHeadersForStatus<\n Operation extends HttpOperation,\n Status extends number,\n> = Operation extends {\n readonly responseHeaders: infer Headers extends Readonly<\n Record<number, HttpOperation[\"params\"]>\n >;\n}\n ? Status extends keyof Headers\n ? OperationSchemaOutput<Extract<Headers[Status], HttpOperation[\"params\"]>>\n : undefined\n : undefined;\n\nexport type JsonOperationResponseEnvelope<\n Operation extends JsonResponseOperation,\n> = {\n [Status in SuccessStatus<Operation>]: {\n readonly data: ResponseBodyForStatus<Operation, Status>;\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly status: Status;\n };\n}[SuccessStatus<Operation>];\n\nexport type JsonOperationResponse<Operation extends JsonResponseOperation> = {\n [Status in SuccessStatus<Operation>]: ResponseBodyForStatus<\n Operation,\n Status\n >;\n}[SuccessStatus<Operation>];\n\nexport function additionalOperationSuccessStatuses(\n operation: HttpOperation,\n): readonly number[] {\n return [\n ...Object.keys(operation.responses).map(Number),\n ...(operation.emptyResponseStatuses ?? []),\n ].filter((status) => status < 200 || status >= 300);\n}\n\ninterface RuntimeJsonOperationResponseEnvelope {\n readonly data: unknown;\n readonly headers: unknown;\n readonly status: number;\n}\n\nexport function operationResponseFailure(\n request: OperationResponseRequestFn,\n operation: HttpOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n message: string,\n) {\n return request.reportFailure({\n kind: \"shape\",\n message,\n method: operation.method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nexport function decodeOperationResponseHeaders(\n operation: HttpOperation,\n response: Response,\n): { readonly data: unknown; readonly ok: true } | { readonly ok: false } {\n const schema = operation.responseHeaders?.[response.status];\n if (!schema) {\n return { data: undefined, ok: true };\n }\n\n const values: Record<string, string> = {};\n for (const name of operationResponseHeaderNames(operation, response.status)) {\n const value = response.headers.get(name);\n if (value !== null) {\n values[name] = value;\n }\n }\n\n const parsed = schema.safeParse(values);\n return parsed.success ? { data: parsed.data, ok: true } : { ok: false };\n}\n\nexport async function decodeJsonOperationResponse(\n request: OperationResponseRequestFn,\n operation: JsonResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>> {\n if (session?.aborted) return retiredRequest(operation.method, path);\n const schema = operation.responses[response.status];\n const isEmpty =\n operation.emptyResponseStatuses?.includes(response.status) ?? false;\n if (!schema && !isEmpty) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response status ${response.status} for ${path}`,\n );\n }\n\n const headers = decodeOperationResponseHeaders(operation, response);\n if (!headers.ok) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response headers for ${path}`,\n );\n }\n\n let data: unknown;\n if (!isEmpty && schema) {\n const result = await readSessionJson(\n request,\n response,\n operation.method,\n path,\n options,\n session,\n );\n if (session?.aborted) return retiredRequest(operation.method, path);\n if (!result.ok) return result;\n const parsed = schema.safeParse(result.data);\n if (!parsed.success) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response shape for ${path}`,\n );\n }\n data = parsed.data;\n }\n\n return {\n data: { data, headers: headers.data, status: response.status },\n ok: true,\n };\n}\n"]}
1
+ {"version":3,"file":"operationRespon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R,IAAI,EACJ,OAAO,EACP,gCAAgC,IAAI,EAAE,CACvC,CAAC;IACJ,CAAC;IAED,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC,OAAO,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,MAAM,eAAe,CAClC,OAAO,EACP,QAAQ,EACR,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,OAAO,EACP,OAAO,CACR,CAAC;QACF,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;YAClC,OAAO,cAAc,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAChD,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,OAAO,MAAM,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,wBAAwB,CAC7B,OAAO,EACP,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,8BAA8B,IAAI,EAAE,CACrC,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IAED,OAAO;QACL,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE;QAC9D,EAAE,EAAE,IAAI;KACT,CAAC;AACJ,CAAC","sourcesContent":["import {\n type HttpOperation,\n type OperationSchemaOutput,\n operationResponseHeaderNames,\n} from \"@tearleads/validators/operation\";\nimport {\n readSessionJson,\n requestRetired,\n retiredRequest,\n} from \"./sessionResponse\";\nimport type {\n OperationResponseRequestFn,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport interface JsonResponseOperation extends HttpOperation {\n readonly responseMediaTypes?: Readonly<Record<number, \"application/json\">>;\n}\n\ntype BodyResponseStatus<Operation extends JsonResponseOperation> = Extract<\n keyof Operation[\"responses\"],\n number\n>;\n\ntype EmptyResponseStatus<Operation extends JsonResponseOperation> =\n Operation extends {\n readonly emptyResponseStatuses: readonly (infer Status)[];\n }\n ? Extract<Status, number>\n : never;\n\ntype SuccessStatus<Operation extends JsonResponseOperation> =\n | BodyResponseStatus<Operation>\n | EmptyResponseStatus<Operation>;\n\ntype ResponseBodyForStatus<\n Operation extends JsonResponseOperation,\n Status extends number,\n> = Status extends keyof Operation[\"responses\"]\n ? OperationSchemaOutput<\n Extract<Operation[\"responses\"][Status], HttpOperation[\"params\"]>\n >\n : undefined;\n\nexport type OperationResponseHeadersForStatus<\n Operation extends HttpOperation,\n Status extends number,\n> = Operation extends {\n readonly responseHeaders: infer Headers extends Readonly<\n Record<number, HttpOperation[\"params\"]>\n >;\n}\n ? Status extends keyof Headers\n ? OperationSchemaOutput<Extract<Headers[Status], HttpOperation[\"params\"]>>\n : undefined\n : undefined;\n\nexport type JsonOperationResponseEnvelope<\n Operation extends JsonResponseOperation,\n> = {\n [Status in SuccessStatus<Operation>]: {\n readonly data: ResponseBodyForStatus<Operation, Status>;\n readonly headers: OperationResponseHeadersForStatus<Operation, Status>;\n readonly status: Status;\n };\n}[SuccessStatus<Operation>];\n\nexport type JsonOperationResponse<Operation extends JsonResponseOperation> = {\n [Status in SuccessStatus<Operation>]: ResponseBodyForStatus<\n Operation,\n Status\n >;\n}[SuccessStatus<Operation>];\n\nexport function additionalOperationSuccessStatuses(\n operation: HttpOperation,\n): readonly number[] {\n return [\n ...Object.keys(operation.responses).map(Number),\n ...(operation.emptyResponseStatuses ?? []),\n ].filter((status) => status < 200 || status >= 300);\n}\n\ninterface RuntimeJsonOperationResponseEnvelope {\n readonly data: unknown;\n readonly headers: unknown;\n readonly status: number;\n}\n\nexport function operationResponseFailure(\n request: OperationResponseRequestFn,\n operation: HttpOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n message: string,\n) {\n return request.reportFailure({\n kind: \"shape\",\n message,\n method: operation.method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\nexport function decodeOperationResponseHeaders(\n operation: HttpOperation,\n response: Response,\n): { readonly data: unknown; readonly ok: true } | { readonly ok: false } {\n const schema = operation.responseHeaders?.[response.status];\n if (!schema) {\n return { data: undefined, ok: true };\n }\n\n const values: Record<string, string> = {};\n for (const name of operationResponseHeaderNames(operation, response.status)) {\n const value = response.headers.get(name);\n if (value !== null) {\n values[name] = value;\n }\n }\n\n const parsed = schema.safeParse(values);\n return parsed.success ? { data: parsed.data, ok: true } : { ok: false };\n}\n\nexport async function decodeJsonOperationResponse(\n request: OperationResponseRequestFn,\n operation: JsonResponseOperation,\n response: Response,\n path: string,\n options: RequestResultOptions,\n session?: AbortSignal,\n): Promise<RequestResult<RuntimeJsonOperationResponseEnvelope>> {\n if (requestRetired(session, options))\n return retiredRequest(operation.method, path);\n const schema = operation.responses[response.status];\n const isEmpty =\n operation.emptyResponseStatuses?.includes(response.status) ?? false;\n if (!schema && !isEmpty) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response status ${response.status} for ${path}`,\n );\n }\n\n const headers = decodeOperationResponseHeaders(operation, response);\n if (!headers.ok) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response headers for ${path}`,\n );\n }\n\n let data: unknown;\n if (!isEmpty && schema) {\n const result = await readSessionJson(\n request,\n response,\n operation.method,\n path,\n options,\n session,\n );\n if (requestRetired(session, options))\n return retiredRequest(operation.method, path);\n if (!result.ok) return result;\n const parsed = schema.safeParse(result.data);\n if (!parsed.success) {\n return operationResponseFailure(\n request,\n operation,\n response,\n path,\n options,\n `Invalid response shape for ${path}`,\n );\n }\n data = parsed.data;\n }\n\n return {\n data: { data, headers: headers.data, status: response.status },\n ok: true,\n };\n}\n"]}
@@ -118,7 +118,8 @@ function firstAttemptSource(attempt, source) {
118
118
  return attempt === 0 && isUsableIssuedSource(source) ? source : null;
119
119
  }
120
120
  export async function uploadMultipartBlobPartBytes(transport, stageId, partNumber, input, uploadFetch = (url, init) => fetch(url, init), options = {}) {
121
- if (options.signal?.aborted)
121
+ const current = () => !options.signal?.aborted && options.stillCurrent?.() !== false;
122
+ if (!current())
122
123
  return null;
123
124
  const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {
124
125
  stageId,
@@ -137,21 +138,27 @@ export async function uploadMultipartBlobPartBytes(transport, stageId, partNumbe
137
138
  stageId,
138
139
  transport,
139
140
  };
141
+ return transferPreparedPart(context, file, uploadFetch, current);
142
+ }
143
+ async function transferPreparedPart(context, file, uploadFetch, current) {
144
+ const { input } = context;
140
145
  let status = null;
141
146
  // The first attempt uses the source the stage initiation issued, if any. A
142
147
  // network failure may be an expired URL hidden by R2 CORS, or a lost success
143
148
  // response; reauthorize once and send the same immutable bytes to the same
144
149
  // part number.
145
150
  for (let attempt = 0; attempt < 2; attempt += 1) {
146
- if (options.signal?.aborted)
151
+ if (!current())
147
152
  return null;
148
153
  const source = firstAttemptSource(attempt, input.source) ??
149
154
  (await authorizePart(context));
150
- if (!source || options.signal?.aborted)
155
+ if (!source || !current())
151
156
  return null;
152
157
  if (source.kind === "api")
153
158
  return uploadThroughApi(context, file);
154
159
  const outcome = await putStoragePart(context, file, source.url, uploadFetch, attempt);
160
+ if (!current())
161
+ return null;
155
162
  if (outcome.kind === "uploaded")
156
163
  return outcome.response;
157
164
  status = outcome.status;