@tearleads/client-sdk 0.1.43 → 0.1.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/containerDocumentDiscovery.js +71 -29
- package/client/containerDocumentDiscovery.js.map +1 -1
- package/client/deviceFirst.js +4 -5
- package/client/deviceFirst.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +2 -3
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerCreateIntentSettlement.js +16 -16
- package/data/persistence/container-contents/containerCreateIntentSettlement.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +5 -11
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerDocumentReassignment.js +13 -13
- package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
- package/data/persistence/container-contents/containerHydrationPersistence.js +7 -4
- package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerIntentPersistence.js +43 -42
- package/data/persistence/container-contents/containerIntentPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +15 -20
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -6
- package/data/persistence/container-contents/containerMoveAbandonPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMoveIntentRows.js +9 -8
- package/data/persistence/container-contents/containerMoveIntentRows.js.map +1 -1
- package/data/persistence/container-contents/containerReconcilePersistence.js +4 -8
- package/data/persistence/container-contents/containerReconcilePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRecoveryPersistence.js +20 -19
- package/data/persistence/container-contents/containerRecoveryPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRemovalWork.js +10 -10
- package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
- package/data/persistence/container-contents/containerStructuralRepair.js +21 -44
- package/data/persistence/container-contents/containerStructuralRepair.js.map +1 -1
- package/data/persistence/container-contents/documentLinkRemovalRepair.js +12 -11
- package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
- package/data/persistence/container-contents/documentMoveIntentPersistence.js +53 -28
- package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +9 -8
- package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
- package/data/persistence/container-contents/documentPurgePlacement.js +6 -6
- package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -1
- package/data/persistence/container-contents/dormantContainerMetadata.js +1 -5
- package/data/persistence/container-contents/dormantContainerMetadata.js.map +1 -1
- package/data/persistence/container-contents/pendingContainerCreate.js +5 -5
- package/data/persistence/container-contents/pendingContainerCreate.js.map +1 -1
- package/data/persistence/containers/containerPersistence.js +10 -27
- package/data/persistence/containers/containerPersistence.js.map +1 -1
- package/data/persistence/containers/containerSyncWatermarkPersistence.d.ts +11 -3
- package/data/persistence/containers/containerSyncWatermarkPersistence.js +46 -58
- package/data/persistence/containers/containerSyncWatermarkPersistence.js.map +1 -1
- package/data/persistence/containers/documentContainerProjectionPersistence.js +2 -2
- package/data/persistence/containers/documentContainerProjectionPersistence.js.map +1 -1
- package/data/persistence/containers/documentPlacement.js +10 -10
- package/data/persistence/containers/documentPlacement.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +5 -5
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -9
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +6 -8
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
- package/data/persistence/documents/internal/ensureDocumentsSchema.js.map +1 -1
- package/data/persistence/documents/internal/orphanSideRows.js +3 -22
- package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
- package/data/persistence/organizations/organizationDataUsagePersistence.js +31 -64
- package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +1 -5
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +24 -17
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/data/persistence/principalHistoryIncompleteRetention.js +3 -9
- package/data/persistence/principalHistoryIncompleteRetention.js.map +1 -1
- package/data/persistence/principalHistoryStagePersistence.d.ts +3 -9
- package/data/persistence/principalHistoryStagePersistence.js +15 -25
- package/data/persistence/principalHistoryStagePersistence.js.map +1 -1
- package/data/persistence/principalHistoryStageRetention.js +16 -15
- package/data/persistence/principalHistoryStageRetention.js.map +1 -1
- package/data/persistence/principalHistoryUnpublishedRetention.js +6 -13
- package/data/persistence/principalHistoryUnpublishedRetention.js.map +1 -1
- package/data/sqlite/containerSchema.d.ts +84 -180
- package/data/sqlite/containerSchema.js +14 -23
- package/data/sqlite/containerSchema.js.map +1 -1
- package/data/sqlite/documentPlacementIntentSchema.js +3 -50
- package/data/sqlite/documentPlacementIntentSchema.js.map +1 -1
- package/data/sqlite/documentSyncFailurePersistence.d.ts +16 -6
- package/data/sqlite/documentSyncFailurePersistence.js +44 -54
- package/data/sqlite/documentSyncFailurePersistence.js.map +1 -1
- package/data/sqlite/{documentPlacementIntentSchema.d.ts → localIntentSchema.d.ts} +162 -88
- package/data/sqlite/localIntentSchema.js +90 -0
- package/data/sqlite/localIntentSchema.js.map +1 -0
- package/data/sqlite/organizationDataUsageSchema.js +11 -17
- package/data/sqlite/organizationDataUsageSchema.js.map +1 -1
- package/data/sqlite/principalHistoryRetentionSchema.js +0 -15
- package/data/sqlite/principalHistoryRetentionSchema.js.map +1 -1
- package/data/sqlite/principalHistoryStageSchema.d.ts +44 -2
- package/data/sqlite/principalHistoryStageSchema.js +14 -2
- package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
- package/data/sqlite/schema.d.ts +1019 -2284
- package/data/sqlite/schema.js +48 -169
- package/data/sqlite/schema.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +6 -34
- package/internal/api-client/ApiClient.js +8 -10
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/apiRequestRuntime.d.ts +2 -0
- package/internal/api-client/apiRequestRuntime.js +4 -0
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/requestInternals.js +7 -7
- package/internal/api-client/requestInternals.js.map +1 -1
- package/internal/api-client/routes/containers/reads.d.ts +13 -7
- package/internal/api-client/routes/containers/reads.js +36 -15
- package/internal/api-client/routes/containers/reads.js.map +1 -1
- package/internal/api-client/types.d.ts +1 -5
- package/internal/api-client/types.js.map +1 -1
- package/internal/validators/containerReadRefinements.js +15 -5
- package/internal/validators/containerReadRefinements.js.map +1 -1
- package/internal/validators/containerReadSchemas.d.ts +36 -0
- package/internal/validators/containerReadSchemas.js +64 -1
- package/internal/validators/containerReadSchemas.js.map +1 -1
- package/internal/validators/operation/containerReads.d.ts +118 -182
- package/internal/validators/operation/containerReads.js +20 -54
- package/internal/validators/operation/containerReads.js.map +1 -1
- package/internal/validators/operation/index.d.ts +1 -1
- package/internal/validators/operation/index.js +1 -1
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/registry.d.ts +2 -2
- package/internal/validators/operation/registry.js +2 -2
- package/internal/validators/operation/registry.js.map +1 -1
- package/internal/validators/request/containerDocumentLanes.d.ts +23 -0
- package/internal/validators/request/containerDocumentLanes.js +23 -0
- package/internal/validators/request/containerDocumentLanes.js.map +1 -0
- package/internal/validators/request/containerParentLanes.js +5 -35
- package/internal/validators/request/containerParentLanes.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -0
- package/internal/validators/request/index.js +1 -0
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/response/containerDocumentLanes.d.ts +82 -0
- package/internal/validators/response/containerDocumentLanes.js +35 -0
- package/internal/validators/response/containerDocumentLanes.js.map +1 -0
- package/internal/validators/response/containerParentLanes.js +3 -15
- package/internal/validators/response/containerParentLanes.js.map +1 -1
- package/internal/validators/response/index.d.ts +2 -1
- package/internal/validators/response/index.js +1 -1
- package/internal/validators/response/index.js.map +1 -1
- package/package.json +1 -1
- package/sync/reconciliation/knownContainerSweep.js +57 -54
- package/sync/reconciliation/knownContainerSweep.js.map +1 -1
- package/sync/reconciliation/reconcileContainer.js +49 -17
- package/sync/reconciliation/reconcileContainer.js.map +1 -1
- package/sync/reconciliation/service.js +44 -16
- package/sync/reconciliation/service.js.map +1 -1
- package/sync/reconciliation/serviceTypes.d.ts +23 -2
- package/sync/reconciliation/serviceTypes.js.map +1 -1
- package/workflows/container-contents/containerDocumentListing.js +92 -38
- package/workflows/container-contents/containerDocumentListing.js.map +1 -1
- package/workflows/container-contents/containerPersistence.d.ts +8 -2
- package/workflows/container-contents/containerPersistence.js +6 -7
- package/workflows/container-contents/containerPersistence.js.map +1 -1
- package/workflows/container-contents/documentDiscovery.d.ts +3 -3
- package/workflows/container-contents/documentDiscovery.js +24 -96
- package/workflows/container-contents/documentDiscovery.js.map +1 -1
- package/workflows/container-contents/documentDiscoveryApply.js +65 -0
- package/workflows/container-contents/documentDiscoveryApply.js.map +1 -0
- package/workflows/container-contents/documentDiscoveryLanes.js +53 -0
- package/workflows/container-contents/documentDiscoveryLanes.js.map +1 -0
- package/workflows/container-contents/documentDiscoveryTypes.d.ts +25 -19
- package/workflows/container-contents/documentDiscoveryTypes.js.map +1 -1
- package/workflows/container-contents/documentPriming.js +6 -10
- package/workflows/container-contents/documentPriming.js.map +1 -1
- package/workflows/container-contents/documentQueries/sql.js +11 -10
- package/workflows/container-contents/documentQueries/sql.js.map +1 -1
- package/workflows/container-contents/documentQueries.js +2 -2
- package/workflows/container-contents/documentQueries.js.map +1 -1
- package/workflows/container-contents/pendingDownloads.js +2 -5
- package/workflows/container-contents/pendingDownloads.js.map +1 -1
- package/workflows/container-contents/pendingWrites/deferredTails.js +3 -11
- package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
- package/workflows/container-contents/pendingWrites/sources.js +56 -80
- package/workflows/container-contents/pendingWrites/sources.js.map +1 -1
- package/workflows/container-contents/pendingWrites.js +6 -4
- package/workflows/container-contents/pendingWrites.js.map +1 -1
- package/workflows/container-contents/remoteContainerState.js +2 -1
- package/workflows/container-contents/remoteContainerState.js.map +1 -1
- package/workflows/container-contents/remoteHydration/laneFetchMarkers.js +11 -17
- package/workflows/container-contents/remoteHydration/laneFetchMarkers.js.map +1 -1
- package/workflows/sync/remoteReset.js +16 -23
- package/workflows/sync/remoteReset.js.map +1 -1
- package/workflows/sync/remoteResetCursorScope.js +10 -18
- package/workflows/sync/remoteResetCursorScope.js.map +1 -1
- package/workflows/sync/remoteResetPrincipalScope.js +1 -2
- package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
- package/workflows/sync/remoteResetScope.js +18 -18
- package/workflows/sync/remoteResetScope.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAiBz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AE,IAAI,EAAE,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM;YACtC,OAAO,EAAE,GAAG,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC,MAAM,EAAE;YAC/H,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,YAAY,EAAE,CAAC,SAAS,IAAI,YAAY;YACxC,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,oBAAoB;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,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 authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n errorMessage,\n hasHeader,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport { SessionRenewalTracker } from \"./sessionRenewal\";\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 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 });\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 let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(this.baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\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 /** 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): boolean {\n const changed = this.authToken !== token;\n if (changed) this.sessionRenewals.tokenChanged();\n this.authToken = token;\n return changed;\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 buildHeaders(\n body: RequestBody | undefined,\n headers: Record<string, string> | undefined,\n authToken: string | null,\n ): Record<string, string> {\n return {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...headers,\n };\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 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 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 = {},\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\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 let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n const failure = responseBodyFailure(error, errorMessage(error));\n if (failure.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n kind: failure.kind,\n message: `${method} ${path}: ${failure.message}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\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 ): Promise<RequestResult<Response>> {\n const authToken = this.authToken;\n const responseResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n const response = responseResult.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: response, ok: true };\n }\n\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\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,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n const retryAuthToken = this.sessionRenewals.currentToken(authToken);\n // Recheck after the awaited helper and the host's renewal notification.\n if (shouldRetry && retryAuthToken) {\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n path,\n response,\n });\n const retryResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n retryAuthToken,\n failureOperation,\n );\n if (!retryResult.ok) return retryResult;\n const retryResponse = retryResult.data;\n if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: retryResponse, ok: true };\n }\n\n return this.httpFailure({\n errorDescription: await describeErrorResponse(\n retryResponse,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n ),\n failureOperation,\n method,\n options,\n path,\n response: retryResponse,\n });\n }\n\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\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 ): Promise<RequestResult<Response>> {\n const reportErrors = options.reportErrors ?? true;\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: this.buildHeaders(body, options.headers, authToken),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) {\n init.duplex = \"half\";\n }\n }\n\n let response: Response;\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 const cancelled = options.signal?.aborted === true;\n if (!cancelled) this.onNetworkError?.();\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${errorMessage(error)}`,\n method,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\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,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAiBzD,MAAM,OAAO,iBAAiB;IAmBT;IAlBX,SAAS,GAAkB,IAAI,CAAC;IACvB,eAAe,GAAG,IAAI,qBAAqB,CAC1D,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CACrB,CAAC;IACe,OAAO,CA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;YAC5C,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM;YACtC,OAAO,EAAE,GAAG,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC,MAAM,EAAE;YAC/H,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,YAAY,EAAE,CAAC,SAAS,IAAI,YAAY;YACxC,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,oBAAoB;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,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 authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport type { ApiRequestInstrumentation } from \"./apiRequestMetrics\";\nimport { measureApiRequest } from \"./measureApiRequest\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n errorMessage,\n hasHeader,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport { SessionRenewalTracker } from \"./sessionRenewal\";\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 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 });\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 let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(this.baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, 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 /** 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): boolean {\n const changed = this.authToken !== token;\n if (changed) this.sessionRenewals.tokenChanged();\n this.authToken = token;\n return changed;\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 buildHeaders(\n body: RequestBody | undefined,\n headers: Record<string, string> | undefined,\n authToken: string | null,\n ): Record<string, string> {\n return {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...headers,\n };\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 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 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 = {},\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\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 let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n const failure = responseBodyFailure(error, errorMessage(error));\n if (failure.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n kind: failure.kind,\n message: `${method} ${path}: ${failure.message}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\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 ): Promise<RequestResult<Response>> {\n const authToken = this.authToken;\n const responseResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n const response = responseResult.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: response, ok: true };\n }\n\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\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,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n const retryAuthToken = this.sessionRenewals.currentToken(authToken);\n // Recheck after the awaited helper and the host's renewal notification.\n if (shouldRetry && retryAuthToken) {\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n path,\n response,\n });\n const retryResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n retryAuthToken,\n failureOperation,\n );\n if (!retryResult.ok) return retryResult;\n const retryResponse = retryResult.data;\n if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: retryResponse, ok: true };\n }\n\n return this.httpFailure({\n errorDescription: await describeErrorResponse(\n retryResponse,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n ),\n failureOperation,\n method,\n options,\n path,\n response: retryResponse,\n });\n }\n\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\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 ): Promise<RequestResult<Response>> {\n const reportErrors = options.reportErrors ?? true;\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: this.buildHeaders(body, options.headers, authToken),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) {\n init.duplex = \"half\";\n }\n }\n\n let response: Response;\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 const cancelled = options.signal?.aborted === true;\n if (!cancelled) this.onNetworkError?.();\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${errorMessage(error)}`,\n method,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\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"]}
|
|
@@ -154,13 +154,13 @@ export function listContainerParentLanesRequestKey(input) {
|
|
|
154
154
|
watermark: syncWatermarkRequestKey(lane.watermark),
|
|
155
155
|
})));
|
|
156
156
|
}
|
|
157
|
-
export function
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
watermark: syncWatermarkRequestKey(watermark),
|
|
163
|
-
});
|
|
157
|
+
export function listContainerDocumentLanesRequestKey(input) {
|
|
158
|
+
return JSON.stringify(input.lanes.map((lane) => ({
|
|
159
|
+
containerId: lane.containerId,
|
|
160
|
+
laneId: lane.laneId,
|
|
161
|
+
limit: lane.limit ?? null,
|
|
162
|
+
watermark: syncWatermarkRequestKey(lane.watermark),
|
|
163
|
+
})));
|
|
164
164
|
}
|
|
165
165
|
export function cachedRequest(cache, cacheKey, request) {
|
|
166
166
|
const cached = cache.get(cacheKey);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestInternals.js","sourceRoot":"","sources":["requestInternals.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,+BAA+B,EAC/B,qCAAqC,EACrC,8BAA8B,EAC9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AC;QAC9C,0BAA0B,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,WAAW,EAAE,CAAC;QAChB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,OAAO,SAAS;QACd,CAAC,CAAC,6BAA6B;QAC/B,CAAC,CAAC,EAAE,GAAG,6BAA6B,EAAE,MAAM,EAAE,KAAK,YAAY,EAAE,EAAE,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,MAAc,EACd,IAAmB;IAEnB,OAAO,MAAM,KAAK,GAAG,IAAI,IAAI,KAAK,mBAAmB,CAAC,eAAe,CAAC;AACxE,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,yEAAyE;IACzE,oEAAoE;IACpE,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,SAAS,IAAI,KAAK;QAClB,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EACjC,CAAC;QACD,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n SyncWatermark,\n} from \"@tearleads/validators/response\";\nimport {\n CONTAINER_MUTATION_ERROR_CODES,\n ContainerMutationFailureResponseSchema,\n DocumentSyncErrorResponseSchema,\n isDocumentSyncStateStaleErrorResponse,\n isPaymentRequiredErrorResponse,\n isPrincipalPolicyStaleErrorResponse,\n PaymentRequiredErrorResponseSchema,\n SESSION_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type { ListContainerDocumentsOptions, RequestBody } from \"./types\";\n\n/**\n * True when a sync response advances the document's write material past what a\n * cached/primed writer projection holds, so the projection must be re-fetched\n * before the next write. Compares the content-key bundle and KEK target hashes\n * the projection authorizes against the ones the server just committed.\n */\nfunction documentSyncInvalidatesWriterProjection(\n projection: DocumentWriterProjectionResponse,\n response: DocumentSyncResponse,\n): boolean {\n return (\n projection.contentKeyBundle?.contentKeyEpoch !==\n response.contentKeyBundle?.contentKeyEpoch ||\n projection.contentKeyBundle?.linkSetManifestHash !==\n response.contentKeyBundle?.linkSetManifestHash ||\n projection.contentKeyBundle?.targetHash !==\n response.contentKeyBundle?.targetHash ||\n projection.documentKekTargets?.linkSetManifestHash !==\n response.documentKekTargets?.linkSetManifestHash ||\n projection.documentKekTargets?.documentKeyTargetHash !==\n response.documentKekTargets?.documentKeyTargetHash\n );\n}\n\n/**\n * Evict a cached/primed document writer projection iff the just-committed sync\n * response moved its write material. Re-checks the cache slot after awaiting so\n * a concurrent invalidation or refetch is not clobbered. `onEvicted` fires\n * whenever an invalidation is issued, so callers can invalidate parallel\n * bookkeeping (e.g. an in-flight result fetch that predates the sync).\n */\nexport async function evictWriterProjectionIfSyncChanged(\n cache: RequestCache<DocumentWriterProjectionResponse>,\n documentId: string,\n response: DocumentSyncResponse,\n onEvicted?: () => void,\n): Promise<void> {\n const cached = cache.get(documentId);\n if (!cached) {\n // No cached projection to compare against, so whether the sync moved the\n // write material is undecidable here — but a concurrent in-flight GET may\n // still predate it. Invalidate conservatively: deleting the (absent) slot\n // bumps the cache's eviction generation so such a fetch's success is not\n // cached, and onEvicted drops a shared in-flight result entry. The cost\n // when nothing is in flight is a skipped cache warm, never wrong data.\n cache.delete(documentId);\n onEvicted?.();\n return;\n }\n const projection = await cached.catch(() => null);\n if (cache.get(documentId) !== cached || !projection) {\n return;\n }\n if (documentSyncInvalidatesWriterProjection(projection, response)) {\n cache.delete(documentId);\n onEvicted?.();\n }\n}\n\nexport interface ErrorResponseDescription {\n readonly code: string | null;\n readonly detail: string;\n readonly error: string | null;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /** Descendant rekeys a refused rotation must carry, parent-first. */\n readonly requiredContainerIds?: readonly string[] | undefined;\n /** Set on a 402 body — the organization whose billing blocked the sync write. */\n readonly paymentRequiredOrganizationId?: string | undefined;\n}\n\nconst emptyErrorResponseDescription: ErrorResponseDescription = {\n code: null,\n detail: \"\",\n error: null,\n};\n\nconst invalidErrorResponseDescription: ErrorResponseDescription = {\n ...emptyErrorResponseDescription,\n detail: \": Invalid failure response body\",\n};\n\nfunction validatedFailureCode(\n value: object,\n schema: NonNullable<HttpOperation[\"failureResponses\"]>[number] | undefined,\n): string | null {\n if (\n !schema ||\n !(\"code\" in value) ||\n typeof value.code !== \"string\" ||\n value.code.length === 0\n ) {\n return null;\n }\n\n // Loose object schemas retain extension keys. A code is behavior-bearing\n // only when changing that field to an unregistered value breaks the selected\n // status schema, proving that the schema constrains rather than merely\n // preserves it.\n const unregisteredCode = `${value.code}\\u0000unregistered`;\n return schema.safeParse({ ...value, code: unregisteredCode }).success\n ? null\n : value.code;\n}\n\nfunction parsedErrorResponseDescription(\n value: unknown,\n schema?: NonNullable<HttpOperation[\"failureResponses\"]>[number],\n): ErrorResponseDescription | null {\n if (\n !value ||\n typeof value !== \"object\" ||\n !(\"error\" in value) ||\n typeof value.error !== \"string\"\n ) {\n return null;\n }\n\n const error = value.error.trim();\n const code = validatedFailureCode(value, schema);\n if (error.length === 0 && code === null) {\n return null;\n }\n return {\n code,\n detail: error.length === 0 ? \"\" : `: ${error}`,\n error: error.length === 0 ? null : error,\n // Container mutations and document sync with inline container rekeys can\n // carry advisory heads whose signed evidence can be recovered in pages.\n ...(schema === ContainerMutationFailureResponseSchema &&\n isPrincipalPolicyStaleErrorResponse(value)\n ? { stalePrincipalHeads: value.principalHeads }\n : schema === DocumentSyncErrorResponseSchema &&\n isDocumentSyncStateStaleErrorResponse(value) &&\n value.principalHeads !== undefined\n ? { stalePrincipalHeads: value.principalHeads }\n : {}),\n ...((code === CONTAINER_MUTATION_ERROR_CODES.descendantRekeysRequired ||\n code === CONTAINER_MUTATION_ERROR_CODES.descendantRekeysInaccessible) &&\n \"requiredContainerIds\" in value &&\n Array.isArray(value.requiredContainerIds) &&\n value.requiredContainerIds.length <= MAX_ROTATION_CONTAINER_REKEYS &&\n value.requiredContainerIds.every(\n (containerId: unknown): containerId is string =>\n typeof containerId === \"string\" && containerId.length > 0,\n )\n ? { requiredContainerIds: value.requiredContainerIds }\n : {}),\n // Sync-write 402s carry the target org for the billing prompt.\n ...(schema === PaymentRequiredErrorResponseSchema &&\n isPaymentRequiredErrorResponse(value)\n ? { paymentRequiredOrganizationId: value.organizationId }\n : {}),\n };\n}\n\nexport function bindPrototypeMethods(\n instance: object,\n prototype: object,\n): void {\n for (const propertyName of Object.getOwnPropertyNames(prototype)) {\n if (propertyName === \"constructor\") {\n continue;\n }\n\n const property = Reflect.get(prototype, propertyName);\n if (typeof property === \"function\") {\n Reflect.set(instance, propertyName, property.bind(instance));\n }\n }\n}\n\nexport function normalizeApiBaseUrl(\n baseUrl: string | null | undefined,\n): string {\n const trimmed = (baseUrl ?? \"\").trim();\n if (trimmed === \"\" || trimmed === \"/\") {\n return \"\";\n }\n\n // Scan from the end to avoid regex backtracking over internal slash runs.\n let end = trimmed.length;\n while (end > 0 && trimmed[end - 1] === \"/\") {\n end -= 1;\n }\n return trimmed.slice(0, end);\n}\n\nexport function hasHeader(\n headers: Record<string, string> | undefined,\n name: string,\n): boolean {\n const normalizedName = name.toLowerCase();\n return Object.keys(headers ?? {}).some(\n (headerName) => headerName.toLowerCase() === normalizedName,\n );\n}\n\nexport function requestFailureKey(input: {\n method: string;\n path: string;\n}): string {\n return `${input.method}\\u0000${input.path}`;\n}\n\nfunction syncWatermarkRequestKey(\n watermark: SyncWatermark | null | undefined,\n): string {\n return watermark ? `${watermark.updatedAt}\\u0000${watermark.id}` : \"\";\n}\n\nexport function listContainerParentLanesRequestKey(\n input: ListContainerParentLanesRequest,\n): string {\n return JSON.stringify(\n input.lanes.map((lane) => ({\n laneId: lane.laneId,\n limit: lane.limit ?? null,\n parentId: lane.parentId,\n watermark: syncWatermarkRequestKey(lane.watermark),\n })),\n );\n}\n\nexport function listContainerDocumentsRequestKey(\n containerId: string,\n options: ListContainerDocumentsOptions = {},\n): string {\n const { watermark, ...rest } = options;\n return JSON.stringify({\n containerId,\n ...rest,\n watermark: syncWatermarkRequestKey(watermark),\n });\n}\n\n/**\n * Minimal cache surface shared by `Map` and `ApiCache.BoundedCache`, so the\n * request helpers work with either backing store.\n */\ninterface RequestCache<T> {\n get(key: string): Promise<T | null> | undefined;\n has(key: string): boolean;\n set(key: string, value: Promise<T | null>): unknown;\n delete(key: string): unknown;\n}\n\nexport function cachedRequest<T>(\n cache: RequestCache<T>,\n cacheKey: string,\n request: () => Promise<T | null>,\n): Promise<T | null> {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n let pending: Promise<T | null>;\n pending = request()\n .then((response) => {\n if (!response && cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n return response;\n })\n .catch((error: unknown) => {\n if (cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n throw error;\n });\n cache.set(cacheKey, pending);\n return pending;\n}\n\nexport function dedupedRequest<T>(\n cache: RequestCache<T>,\n cacheKey: string,\n request: () => Promise<T | null>,\n): Promise<T | null> {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n let pending: Promise<T | null>;\n pending = request().finally(() => {\n if (cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n });\n cache.set(cacheKey, pending);\n return pending;\n}\n\nexport function isReplayableRequestBody(\n body: RequestBody | undefined,\n): boolean {\n return !(\n typeof ReadableStream === \"function\" && body instanceof ReadableStream\n );\n}\n\nexport function isSuccessfulResponse(\n response: Response,\n additionalSuccessStatuses: readonly number[],\n): boolean {\n return response.ok || additionalSuccessStatuses.includes(response.status);\n}\n\nfunction validatePaymentRequiredTarget(\n schema: NonNullable<HttpOperation[\"failureResponses\"]>[number] | undefined,\n parsed: unknown,\n expectedOrganizationId: string | undefined,\n): { readonly invalid: boolean; readonly organizationId?: string } {\n if (schema !== PaymentRequiredErrorResponseSchema) {\n return { invalid: false };\n }\n if (\n !isPaymentRequiredErrorResponse(parsed) ||\n (expectedOrganizationId !== undefined &&\n parsed.organizationId !== expectedOrganizationId)\n ) {\n return { invalid: true };\n }\n return { invalid: false, organizationId: parsed.organizationId };\n}\n\nfunction paymentRequiredDescription(\n organizationId: string | undefined,\n): ErrorResponseDescription | null {\n return organizationId === undefined\n ? null\n : {\n ...emptyErrorResponseDescription,\n paymentRequiredOrganizationId: organizationId,\n };\n}\n\nexport async function describeErrorResponse(\n response: Response,\n operation?: HttpOperation,\n expectedPaymentRequiredOrganizationId?: string,\n): Promise<ErrorResponseDescription> {\n const schema = operation?.failureResponses?.[response.status];\n if (operation && !schema) {\n // A cloned response can wait for its other branch to finish cancelling.\n // Cleanup must not delay reporting an already-invalid status.\n void response.body?.cancel().catch(() => {});\n return invalidErrorResponseDescription;\n }\n let responseText = \"\";\n\n try {\n responseText = (await response.text()).trim();\n } catch {\n return operation\n ? invalidErrorResponseDescription\n : emptyErrorResponseDescription;\n }\n\n if (responseText.length === 0) {\n return operation\n ? invalidErrorResponseDescription\n : emptyErrorResponseDescription;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(responseText);\n } catch {\n return operation\n ? invalidErrorResponseDescription\n : { ...emptyErrorResponseDescription, detail: `: ${responseText}` };\n }\n\n if (schema) {\n const result = schema.safeParse(parsed);\n if (!result.success) {\n return invalidErrorResponseDescription;\n }\n parsed = result.data;\n }\n\n const paymentTarget = validatePaymentRequiredTarget(\n schema,\n parsed,\n expectedPaymentRequiredOrganizationId,\n );\n if (paymentTarget.invalid) {\n return invalidErrorResponseDescription;\n }\n\n const description =\n parsedErrorResponseDescription(parsed, schema) ??\n paymentRequiredDescription(paymentTarget.organizationId);\n if (description) {\n return description;\n }\n\n return operation\n ? emptyErrorResponseDescription\n : { ...emptyErrorResponseDescription, detail: `: ${responseText}` };\n}\n\nexport function isRefreshableSessionError(\n status: number,\n code: string | null,\n): boolean {\n return status === 401 && code === SESSION_ERROR_CODES.refreshRequired;\n}\n\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n // `instanceof Error` fails for errors thrown across realms (web workers,\n // serialized payloads); fall back to a duck-typed string `message`.\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof error.message === \"string\"\n ) {\n return error.message;\n }\n return String(error);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"requestInternals.js","sourceRoot":"","sources":["requestInternals.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,+BAA+B,EAC/B,qCAAqC,EACrC,8BAA8B,EAC9B,mCAAmC,EACnC,kCAAkC,EAClC,mBAAmB,GACpB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAG3E;;;;;GAKG;AACH,SAAS,uCAAuC,CAC9C,UAA4C,EAC5C,QAA8B;IAE9B,OAAO,CACL,UAAU,CAAC,gBAAgB,EAAE,eAAe;QAC1C,QAAQ,CAAC,gBAAgB,EAAE,eAAe;QAC5C,UAAU,CAAC,gBAAgB,EAAE,mBAAmB;YAC9C,QAAQ,CAAC,gBAAgB,EAAE,mBAAmB;QAChD,UAAU,CAAC,gBAAgB,EAAE,UAAU;YACrC,QAAQ,CAAC,gBAAgB,EAAE,UAAU;QACvC,UAAU,CAAC,kBAAkB,EAAE,mBAAmB;YAChD,QAAQ,CAAC,kBAAkB,EAAE,mBAAmB;QAClD,UAAU,CAAC,kBAAkB,EAAE,qBAAqB;YAClD,QAAQ,CAAC,kBAAkB,EAAE,qBAAqB,CACrD,CAAC;AACJ,CAAC;AAED;;;;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AyE;IACzE,oEAAoE;IACpE,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,SAAS,IAAI,KAAK;QAClB,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EACjC,CAAC;QACD,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type { HttpOperation } from \"@tearleads/validators/operation\";\nimport type {\n ListContainerDocumentLanesRequest,\n ListContainerParentLanesRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n SyncWatermark,\n} from \"@tearleads/validators/response\";\nimport {\n CONTAINER_MUTATION_ERROR_CODES,\n ContainerMutationFailureResponseSchema,\n DocumentSyncErrorResponseSchema,\n isDocumentSyncStateStaleErrorResponse,\n isPaymentRequiredErrorResponse,\n isPrincipalPolicyStaleErrorResponse,\n PaymentRequiredErrorResponseSchema,\n SESSION_ERROR_CODES,\n} from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type { RequestBody } from \"./types\";\n\n/**\n * True when a sync response advances the document's write material past what a\n * cached/primed writer projection holds, so the projection must be re-fetched\n * before the next write. Compares the content-key bundle and KEK target hashes\n * the projection authorizes against the ones the server just committed.\n */\nfunction documentSyncInvalidatesWriterProjection(\n projection: DocumentWriterProjectionResponse,\n response: DocumentSyncResponse,\n): boolean {\n return (\n projection.contentKeyBundle?.contentKeyEpoch !==\n response.contentKeyBundle?.contentKeyEpoch ||\n projection.contentKeyBundle?.linkSetManifestHash !==\n response.contentKeyBundle?.linkSetManifestHash ||\n projection.contentKeyBundle?.targetHash !==\n response.contentKeyBundle?.targetHash ||\n projection.documentKekTargets?.linkSetManifestHash !==\n response.documentKekTargets?.linkSetManifestHash ||\n projection.documentKekTargets?.documentKeyTargetHash !==\n response.documentKekTargets?.documentKeyTargetHash\n );\n}\n\n/**\n * Evict a cached/primed document writer projection iff the just-committed sync\n * response moved its write material. Re-checks the cache slot after awaiting so\n * a concurrent invalidation or refetch is not clobbered. `onEvicted` fires\n * whenever an invalidation is issued, so callers can invalidate parallel\n * bookkeeping (e.g. an in-flight result fetch that predates the sync).\n */\nexport async function evictWriterProjectionIfSyncChanged(\n cache: RequestCache<DocumentWriterProjectionResponse>,\n documentId: string,\n response: DocumentSyncResponse,\n onEvicted?: () => void,\n): Promise<void> {\n const cached = cache.get(documentId);\n if (!cached) {\n // No cached projection to compare against, so whether the sync moved the\n // write material is undecidable here — but a concurrent in-flight GET may\n // still predate it. Invalidate conservatively: deleting the (absent) slot\n // bumps the cache's eviction generation so such a fetch's success is not\n // cached, and onEvicted drops a shared in-flight result entry. The cost\n // when nothing is in flight is a skipped cache warm, never wrong data.\n cache.delete(documentId);\n onEvicted?.();\n return;\n }\n const projection = await cached.catch(() => null);\n if (cache.get(documentId) !== cached || !projection) {\n return;\n }\n if (documentSyncInvalidatesWriterProjection(projection, response)) {\n cache.delete(documentId);\n onEvicted?.();\n }\n}\n\nexport interface ErrorResponseDescription {\n readonly code: string | null;\n readonly detail: string;\n readonly error: string | null;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /** Descendant rekeys a refused rotation must carry, parent-first. */\n readonly requiredContainerIds?: readonly string[] | undefined;\n /** Set on a 402 body — the organization whose billing blocked the sync write. */\n readonly paymentRequiredOrganizationId?: string | undefined;\n}\n\nconst emptyErrorResponseDescription: ErrorResponseDescription = {\n code: null,\n detail: \"\",\n error: null,\n};\n\nconst invalidErrorResponseDescription: ErrorResponseDescription = {\n ...emptyErrorResponseDescription,\n detail: \": Invalid failure response body\",\n};\n\nfunction validatedFailureCode(\n value: object,\n schema: NonNullable<HttpOperation[\"failureResponses\"]>[number] | undefined,\n): string | null {\n if (\n !schema ||\n !(\"code\" in value) ||\n typeof value.code !== \"string\" ||\n value.code.length === 0\n ) {\n return null;\n }\n\n // Loose object schemas retain extension keys. A code is behavior-bearing\n // only when changing that field to an unregistered value breaks the selected\n // status schema, proving that the schema constrains rather than merely\n // preserves it.\n const unregisteredCode = `${value.code}\\u0000unregistered`;\n return schema.safeParse({ ...value, code: unregisteredCode }).success\n ? null\n : value.code;\n}\n\nfunction parsedErrorResponseDescription(\n value: unknown,\n schema?: NonNullable<HttpOperation[\"failureResponses\"]>[number],\n): ErrorResponseDescription | null {\n if (\n !value ||\n typeof value !== \"object\" ||\n !(\"error\" in value) ||\n typeof value.error !== \"string\"\n ) {\n return null;\n }\n\n const error = value.error.trim();\n const code = validatedFailureCode(value, schema);\n if (error.length === 0 && code === null) {\n return null;\n }\n return {\n code,\n detail: error.length === 0 ? \"\" : `: ${error}`,\n error: error.length === 0 ? null : error,\n // Container mutations and document sync with inline container rekeys can\n // carry advisory heads whose signed evidence can be recovered in pages.\n ...(schema === ContainerMutationFailureResponseSchema &&\n isPrincipalPolicyStaleErrorResponse(value)\n ? { stalePrincipalHeads: value.principalHeads }\n : schema === DocumentSyncErrorResponseSchema &&\n isDocumentSyncStateStaleErrorResponse(value) &&\n value.principalHeads !== undefined\n ? { stalePrincipalHeads: value.principalHeads }\n : {}),\n ...((code === CONTAINER_MUTATION_ERROR_CODES.descendantRekeysRequired ||\n code === CONTAINER_MUTATION_ERROR_CODES.descendantRekeysInaccessible) &&\n \"requiredContainerIds\" in value &&\n Array.isArray(value.requiredContainerIds) &&\n value.requiredContainerIds.length <= MAX_ROTATION_CONTAINER_REKEYS &&\n value.requiredContainerIds.every(\n (containerId: unknown): containerId is string =>\n typeof containerId === \"string\" && containerId.length > 0,\n )\n ? { requiredContainerIds: value.requiredContainerIds }\n : {}),\n // Sync-write 402s carry the target org for the billing prompt.\n ...(schema === PaymentRequiredErrorResponseSchema &&\n isPaymentRequiredErrorResponse(value)\n ? { paymentRequiredOrganizationId: value.organizationId }\n : {}),\n };\n}\n\nexport function bindPrototypeMethods(\n instance: object,\n prototype: object,\n): void {\n for (const propertyName of Object.getOwnPropertyNames(prototype)) {\n if (propertyName === \"constructor\") {\n continue;\n }\n\n const property = Reflect.get(prototype, propertyName);\n if (typeof property === \"function\") {\n Reflect.set(instance, propertyName, property.bind(instance));\n }\n }\n}\n\nexport function normalizeApiBaseUrl(\n baseUrl: string | null | undefined,\n): string {\n const trimmed = (baseUrl ?? \"\").trim();\n if (trimmed === \"\" || trimmed === \"/\") {\n return \"\";\n }\n\n // Scan from the end to avoid regex backtracking over internal slash runs.\n let end = trimmed.length;\n while (end > 0 && trimmed[end - 1] === \"/\") {\n end -= 1;\n }\n return trimmed.slice(0, end);\n}\n\nexport function hasHeader(\n headers: Record<string, string> | undefined,\n name: string,\n): boolean {\n const normalizedName = name.toLowerCase();\n return Object.keys(headers ?? {}).some(\n (headerName) => headerName.toLowerCase() === normalizedName,\n );\n}\n\nexport function requestFailureKey(input: {\n method: string;\n path: string;\n}): string {\n return `${input.method}\\u0000${input.path}`;\n}\n\nfunction syncWatermarkRequestKey(\n watermark: SyncWatermark | null | undefined,\n): string {\n return watermark ? `${watermark.updatedAt}\\u0000${watermark.id}` : \"\";\n}\n\nexport function listContainerParentLanesRequestKey(\n input: ListContainerParentLanesRequest,\n): string {\n return JSON.stringify(\n input.lanes.map((lane) => ({\n laneId: lane.laneId,\n limit: lane.limit ?? null,\n parentId: lane.parentId,\n watermark: syncWatermarkRequestKey(lane.watermark),\n })),\n );\n}\n\nexport function listContainerDocumentLanesRequestKey(\n input: ListContainerDocumentLanesRequest,\n): string {\n return JSON.stringify(\n input.lanes.map((lane) => ({\n containerId: lane.containerId,\n laneId: lane.laneId,\n limit: lane.limit ?? null,\n watermark: syncWatermarkRequestKey(lane.watermark),\n })),\n );\n}\n\n/**\n * Minimal cache surface shared by `Map` and `ApiCache.BoundedCache`, so the\n * request helpers work with either backing store.\n */\ninterface RequestCache<T> {\n get(key: string): Promise<T | null> | undefined;\n has(key: string): boolean;\n set(key: string, value: Promise<T | null>): unknown;\n delete(key: string): unknown;\n}\n\nexport function cachedRequest<T>(\n cache: RequestCache<T>,\n cacheKey: string,\n request: () => Promise<T | null>,\n): Promise<T | null> {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n let pending: Promise<T | null>;\n pending = request()\n .then((response) => {\n if (!response && cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n return response;\n })\n .catch((error: unknown) => {\n if (cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n throw error;\n });\n cache.set(cacheKey, pending);\n return pending;\n}\n\nexport function dedupedRequest<T>(\n cache: RequestCache<T>,\n cacheKey: string,\n request: () => Promise<T | null>,\n): Promise<T | null> {\n const cached = cache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n let pending: Promise<T | null>;\n pending = request().finally(() => {\n if (cache.get(cacheKey) === pending) {\n cache.delete(cacheKey);\n }\n });\n cache.set(cacheKey, pending);\n return pending;\n}\n\nexport function isReplayableRequestBody(\n body: RequestBody | undefined,\n): boolean {\n return !(\n typeof ReadableStream === \"function\" && body instanceof ReadableStream\n );\n}\n\nexport function isSuccessfulResponse(\n response: Response,\n additionalSuccessStatuses: readonly number[],\n): boolean {\n return response.ok || additionalSuccessStatuses.includes(response.status);\n}\n\nfunction validatePaymentRequiredTarget(\n schema: NonNullable<HttpOperation[\"failureResponses\"]>[number] | undefined,\n parsed: unknown,\n expectedOrganizationId: string | undefined,\n): { readonly invalid: boolean; readonly organizationId?: string } {\n if (schema !== PaymentRequiredErrorResponseSchema) {\n return { invalid: false };\n }\n if (\n !isPaymentRequiredErrorResponse(parsed) ||\n (expectedOrganizationId !== undefined &&\n parsed.organizationId !== expectedOrganizationId)\n ) {\n return { invalid: true };\n }\n return { invalid: false, organizationId: parsed.organizationId };\n}\n\nfunction paymentRequiredDescription(\n organizationId: string | undefined,\n): ErrorResponseDescription | null {\n return organizationId === undefined\n ? null\n : {\n ...emptyErrorResponseDescription,\n paymentRequiredOrganizationId: organizationId,\n };\n}\n\nexport async function describeErrorResponse(\n response: Response,\n operation?: HttpOperation,\n expectedPaymentRequiredOrganizationId?: string,\n): Promise<ErrorResponseDescription> {\n const schema = operation?.failureResponses?.[response.status];\n if (operation && !schema) {\n // A cloned response can wait for its other branch to finish cancelling.\n // Cleanup must not delay reporting an already-invalid status.\n void response.body?.cancel().catch(() => {});\n return invalidErrorResponseDescription;\n }\n let responseText = \"\";\n\n try {\n responseText = (await response.text()).trim();\n } catch {\n return operation\n ? invalidErrorResponseDescription\n : emptyErrorResponseDescription;\n }\n\n if (responseText.length === 0) {\n return operation\n ? invalidErrorResponseDescription\n : emptyErrorResponseDescription;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(responseText);\n } catch {\n return operation\n ? invalidErrorResponseDescription\n : { ...emptyErrorResponseDescription, detail: `: ${responseText}` };\n }\n\n if (schema) {\n const result = schema.safeParse(parsed);\n if (!result.success) {\n return invalidErrorResponseDescription;\n }\n parsed = result.data;\n }\n\n const paymentTarget = validatePaymentRequiredTarget(\n schema,\n parsed,\n expectedPaymentRequiredOrganizationId,\n );\n if (paymentTarget.invalid) {\n return invalidErrorResponseDescription;\n }\n\n const description =\n parsedErrorResponseDescription(parsed, schema) ??\n paymentRequiredDescription(paymentTarget.organizationId);\n if (description) {\n return description;\n }\n\n return operation\n ? emptyErrorResponseDescription\n : { ...emptyErrorResponseDescription, detail: `: ${responseText}` };\n}\n\nexport function isRefreshableSessionError(\n status: number,\n code: string | null,\n): boolean {\n return status === 401 && code === SESSION_ERROR_CODES.refreshRequired;\n}\n\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n // `instanceof Error` fails for errors thrown across realms (web workers,\n // serialized payloads); fall back to a duck-typed string `message`.\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof error.message === \"string\"\n ) {\n return error.message;\n }\n return String(error);\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { ListContainerParentLanesRequest } from "../../../validators/request/index.js";
|
|
2
|
-
import type
|
|
3
|
-
import type {
|
|
1
|
+
import type { ListContainerDocumentLanesRequest, ListContainerParentLanesRequest } from "../../../validators/request/index.js";
|
|
2
|
+
import { type ListContainerDocumentLanesResponse, type ListContainerParentLanesResponse } from "../../../validators/response/index.js";
|
|
3
|
+
import type { RequestResult } from "../../types.js";
|
|
4
4
|
export interface ContainerKekLogOptions {
|
|
5
5
|
readonly afterKeyEpoch?: number;
|
|
6
6
|
readonly keyringForEpoch?: number;
|
|
@@ -10,10 +10,16 @@ export declare const containerKekLog: {
|
|
|
10
10
|
readonly method: "GET";
|
|
11
11
|
readonly path: (containerId: string, options?: ContainerKekLogOptions) => string;
|
|
12
12
|
};
|
|
13
|
-
export declare const
|
|
14
|
-
readonly
|
|
15
|
-
readonly method: "
|
|
16
|
-
readonly path:
|
|
13
|
+
export declare const containerDocumentLanes: {
|
|
14
|
+
readonly isResponseForRequest: (input: ListContainerDocumentLanesRequest, value: unknown) => value is ListContainerDocumentLanesResponse;
|
|
15
|
+
readonly method: "POST";
|
|
16
|
+
readonly path: string;
|
|
17
|
+
/**
|
|
18
|
+
* Identical concurrent batches share one silent fetch; each caller then
|
|
19
|
+
* applies its own reporting policy. A lane rejected for anything but a
|
|
20
|
+
* positive absence proof is reported like the failed request it replaces.
|
|
21
|
+
*/
|
|
22
|
+
readonly settle: (result: RequestResult<ListContainerDocumentLanesResponse> | null, reportErrors: boolean, reportError: (message: string) => void) => ListContainerDocumentLanesResponse | null;
|
|
17
23
|
};
|
|
18
24
|
export declare const containerParentLanes: {
|
|
19
25
|
readonly isResponseForRequest: (input: ListContainerParentLanesRequest, value: unknown) => value is ListContainerParentLanesResponse;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { getContainerKekLogOperation, isGetContainerKekLogOperationResponse,
|
|
1
|
+
import { getContainerKekLogOperation, isGetContainerKekLogOperationResponse, isListContainerDocumentLanesOperationResponse, isListContainerParentLanesOperationResponse, listContainerDocumentLanesOperation, listContainerParentLanesOperation, operationRequestPath, operationRequestPathWithQuery, } from "../../../validators/operation/index.js";
|
|
2
|
+
import { CONTAINER_NOT_FOUND_ERROR_CODE, } from "../../../validators/response/index.js";
|
|
2
3
|
export const containerKekLog = {
|
|
3
4
|
isResponse: isGetContainerKekLogOperationResponse,
|
|
4
5
|
method: getContainerKekLogOperation.method,
|
|
@@ -7,23 +8,43 @@ export const containerKekLog = {
|
|
|
7
8
|
afterKeyEpoch: options.afterKeyEpoch,
|
|
8
9
|
}),
|
|
9
10
|
};
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
11
|
+
function resultsMatchLanes(lanes, results) {
|
|
12
|
+
const expectedLaneIds = new Set(lanes.map((lane) => lane.laneId));
|
|
13
|
+
return (results.length === lanes.length &&
|
|
14
|
+
results.every((result) => expectedLaneIds.has(result.laneId)));
|
|
15
|
+
}
|
|
16
|
+
export const containerDocumentLanes = {
|
|
17
|
+
isResponseForRequest: (input, value) => isListContainerDocumentLanesOperationResponse(value) &&
|
|
18
|
+
resultsMatchLanes(input.lanes, value.results),
|
|
19
|
+
method: listContainerDocumentLanesOperation.method,
|
|
20
|
+
path: operationRequestPath(listContainerDocumentLanesOperation, {}),
|
|
21
|
+
/**
|
|
22
|
+
* Identical concurrent batches share one silent fetch; each caller then
|
|
23
|
+
* applies its own reporting policy. A lane rejected for anything but a
|
|
24
|
+
* positive absence proof is reported like the failed request it replaces.
|
|
25
|
+
*/
|
|
26
|
+
settle: (result, reportErrors, reportError) => {
|
|
27
|
+
if (result?.ok !== true) {
|
|
28
|
+
if (reportErrors)
|
|
29
|
+
result?.report();
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
if (reportErrors) {
|
|
33
|
+
for (const lane of result.data.results) {
|
|
34
|
+
// Only the exact 404 + absence-code pair proves the container is gone.
|
|
35
|
+
if ("failure" in lane &&
|
|
36
|
+
!(lane.failure.status === 404 &&
|
|
37
|
+
lane.failure.code === CONTAINER_NOT_FOUND_ERROR_CODE))
|
|
38
|
+
reportError(`${listContainerDocumentLanesOperation.method} ${listContainerDocumentLanesOperation.path}: ${lane.failure.status} ${lane.failure.error}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return result.data;
|
|
42
|
+
},
|
|
18
43
|
};
|
|
19
44
|
export const containerParentLanes = {
|
|
20
45
|
isResponseForRequest: (input, value) => {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
const expectedLaneIds = new Set(input.lanes.map((lane) => lane.laneId));
|
|
25
|
-
return (value.results.length === input.lanes.length &&
|
|
26
|
-
value.results.every((result) => expectedLaneIds.has(result.laneId)));
|
|
46
|
+
return (isListContainerParentLanesOperationResponse(value) &&
|
|
47
|
+
resultsMatchLanes(input.lanes, value.results));
|
|
27
48
|
},
|
|
28
49
|
method: listContainerParentLanesOperation.method,
|
|
29
50
|
path: operationRequestPath(listContainerParentLanesOperation, {}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reads.js","sourceRoot":"","sources":["reads.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,qCAAqC,EACrC,
|
|
1
|
+
{"version":3,"file":"reads.js","sourceRoot":"","sources":["reads.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,qCAAqC,EACrC,6CAA6C,EAC7C,2CAA2C,EAC3C,mCAAmC,EACnC,iCAAiC,EACjC,oBAAoB,EACpB,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AAKzC,OAAO,EACL,8BAA8B,GAG/B,MAAM,gCAAgC,CAAC;AAQxC,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,UAAU,EAAE,qCAAqC;IACjD,MAAM,EAAE,2BAA2B,CAAC,MAAM;IAC1C,IAAI,EAAE,CAAC,WAAmB,EAAE,UAAkC,EAAE,EAAE,EAAE,CAClE,6B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CAAC,MAAM,KAAK,GAAG;wBAC3B,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,8BAA8B,CACrD;oBAED,WAAW,CACT,GAAG,mCAAmC,CAAC,MAAM,IAAI,mCAAmC,CAAC,IAAI,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAC1I,CAAC;YACN,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;CACO,CAAC;AAEX,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,oBAAoB,EAAE,CACpB,KAAsC,EACtC,KAAc,EAC6B,EAAE;QAC7C,OAAO,CACL,2CAA2C,CAAC,KAAK,CAAC;YAClD,iBAAiB,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAC9C,CAAC;IACJ,CAAC;IACD,MAAM,EAAE,iCAAiC,CAAC,MAAM;IAChD,IAAI,EAAE,oBAAoB,CAAC,iCAAiC,EAAE,EAAE,CAAC;CACzD,CAAC","sourcesContent":["import {\n getContainerKekLogOperation,\n isGetContainerKekLogOperationResponse,\n isListContainerDocumentLanesOperationResponse,\n isListContainerParentLanesOperationResponse,\n listContainerDocumentLanesOperation,\n listContainerParentLanesOperation,\n operationRequestPath,\n operationRequestPathWithQuery,\n} from \"@tearleads/validators/operation\";\nimport type {\n ListContainerDocumentLanesRequest,\n ListContainerParentLanesRequest,\n} from \"@tearleads/validators/request\";\nimport {\n CONTAINER_NOT_FOUND_ERROR_CODE,\n type ListContainerDocumentLanesResponse,\n type ListContainerParentLanesResponse,\n} from \"@tearleads/validators/response\";\nimport type { RequestResult } from \"../../types\";\n\nexport interface ContainerKekLogOptions {\n readonly afterKeyEpoch?: number;\n readonly keyringForEpoch?: number;\n}\n\nexport const containerKekLog = {\n isResponse: isGetContainerKekLogOperationResponse,\n method: getContainerKekLogOperation.method,\n path: (containerId: string, options: ContainerKekLogOptions = {}) =>\n operationRequestPathWithQuery(\n getContainerKekLogOperation,\n { containerId },\n {\n keyringForEpoch: options.keyringForEpoch,\n afterKeyEpoch: options.afterKeyEpoch,\n },\n ),\n} as const;\n\nfunction resultsMatchLanes(\n lanes: ReadonlyArray<{ readonly laneId: string }>,\n results: ReadonlyArray<{ readonly laneId: string }>,\n): boolean {\n const expectedLaneIds = new Set(lanes.map((lane) => lane.laneId));\n return (\n results.length === lanes.length &&\n results.every((result) => expectedLaneIds.has(result.laneId))\n );\n}\n\nexport const containerDocumentLanes = {\n isResponseForRequest: (\n input: ListContainerDocumentLanesRequest,\n value: unknown,\n ): value is ListContainerDocumentLanesResponse =>\n isListContainerDocumentLanesOperationResponse(value) &&\n resultsMatchLanes(input.lanes, value.results),\n method: listContainerDocumentLanesOperation.method,\n path: operationRequestPath(listContainerDocumentLanesOperation, {}),\n /**\n * Identical concurrent batches share one silent fetch; each caller then\n * applies its own reporting policy. A lane rejected for anything but a\n * positive absence proof is reported like the failed request it replaces.\n */\n settle: (\n result: RequestResult<ListContainerDocumentLanesResponse> | null,\n reportErrors: boolean,\n reportError: (message: string) => void,\n ): ListContainerDocumentLanesResponse | null => {\n if (result?.ok !== true) {\n if (reportErrors) result?.report();\n return null;\n }\n if (reportErrors) {\n for (const lane of result.data.results) {\n // Only the exact 404 + absence-code pair proves the container is gone.\n if (\n \"failure\" in lane &&\n !(\n lane.failure.status === 404 &&\n lane.failure.code === CONTAINER_NOT_FOUND_ERROR_CODE\n )\n )\n reportError(\n `${listContainerDocumentLanesOperation.method} ${listContainerDocumentLanesOperation.path}: ${lane.failure.status} ${lane.failure.error}`,\n );\n }\n }\n return result.data;\n },\n} as const;\n\nexport const containerParentLanes = {\n isResponseForRequest: (\n input: ListContainerParentLanesRequest,\n value: unknown,\n ): value is ListContainerParentLanesResponse => {\n return (\n isListContainerParentLanesOperationResponse(value) &&\n resultsMatchLanes(input.lanes, value.results)\n );\n },\n method: listContainerParentLanesOperation.method,\n path: operationRequestPath(listContainerParentLanesOperation, {}),\n} as const;\n"]}
|
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
import type { DocumentAttributionRangesQuery, HttpOperation, HttpOperationMethod } from "../validators/operation/index.js";
|
|
2
|
-
import type { ReferencedPrincipalStateResponse
|
|
2
|
+
import type { ReferencedPrincipalStateResponse } from "../validators/response/index.js";
|
|
3
3
|
export type HttpMethod = HttpOperationMethod;
|
|
4
4
|
export type RequestBody = BodyInit;
|
|
5
|
-
export interface ListContainerDocumentsOptions {
|
|
6
|
-
limit?: number;
|
|
7
|
-
watermark?: SyncWatermark | null;
|
|
8
|
-
}
|
|
9
5
|
export type ListDocumentEditAttributionRangesOptions = Omit<DocumentAttributionRangesQuery, "cursor"> & {
|
|
10
6
|
cursor?: DocumentAttributionRangesQuery["cursor"] | null;
|
|
11
7
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
|
|
@@ -2,9 +2,17 @@ export const containerKekLogSingleKeyringRefinement = {
|
|
|
2
2
|
description: "a container KEK log page contains at most one sealed keyring",
|
|
3
3
|
id: "response.container-kek-log-single-keyring",
|
|
4
4
|
};
|
|
5
|
-
const
|
|
6
|
-
description: "container-
|
|
7
|
-
id: "request.container-
|
|
5
|
+
export const containerDocumentLaneRequestUniqueIdsRefinement = {
|
|
6
|
+
description: "container document-lane request lane ids must be unique",
|
|
7
|
+
id: "request.container-document-lane-unique-ids",
|
|
8
|
+
};
|
|
9
|
+
export const containerDocumentLaneRequestPageTotalRefinement = {
|
|
10
|
+
description: "container document-lane request page limits must total at most 500",
|
|
11
|
+
id: "request.container-document-lane-page-total",
|
|
12
|
+
};
|
|
13
|
+
export const containerDocumentLaneResponseUniqueIdsRefinement = {
|
|
14
|
+
description: "container document-lane response lane ids must be unique",
|
|
15
|
+
id: "response.container-document-lane-unique-ids",
|
|
8
16
|
};
|
|
9
17
|
export const containerParentLaneRequestUniqueIdsRefinement = {
|
|
10
18
|
description: "container parent-lane request lane ids must be unique",
|
|
@@ -21,8 +29,10 @@ export const containerParentLaneResponseUniqueIdsRefinement = {
|
|
|
21
29
|
export const containerKekLogResponseRuntimeRefinements = [
|
|
22
30
|
containerKekLogSingleKeyringRefinement,
|
|
23
31
|
];
|
|
24
|
-
export const
|
|
25
|
-
|
|
32
|
+
export const containerDocumentLaneRuntimeRefinements = [
|
|
33
|
+
containerDocumentLaneRequestUniqueIdsRefinement,
|
|
34
|
+
containerDocumentLaneRequestPageTotalRefinement,
|
|
35
|
+
containerDocumentLaneResponseUniqueIdsRefinement,
|
|
26
36
|
];
|
|
27
37
|
export const containerParentLaneRuntimeRefinements = [
|
|
28
38
|
containerParentLaneRequestUniqueIdsRefinement,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerReadRefinements.js","sourceRoot":"","sources":["containerReadRefinements.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,sCAAsC,GAAG;IACpD,WAAW,EAAE,8DAA8D;IAC3E,EAAE,EAAE,2CAA2C;CACvC,CAAC;AAEX,MAAM,
|
|
1
|
+
{"version":3,"file":"containerReadRefinements.js","sourceRoot":"","sources":["containerReadRefinements.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,sCAAsC,GAAG;IACpD,WAAW,EAAE,8DAA8D;IAC3E,EAAE,EAAE,2CAA2C;CACvC,CAAC;AAEX,MAAM,CAAC,MAAM,+CAA+C,GAAG;IAC7D,WAAW,EAAE,yDAAyD;IACtE,EAAE,EAAE,4CAA4C;CACxC,CAAC;AAEX,MAAM,CAAC,MAAM,+CAA+C,GAAG;IAC7D,WAAW,EACT,oEAAoE;IACtE,EAAE,EAAE,4CAA4C;CACxC,CAAC;AAEX,MAAM,CAAC,MAAM,gDAAgD,GAAG;IAC9D,WAAW,EAAE,0DAA0D;IACvE,EAAE,EAAE,6CAA6C;CACzC,CAAC;AAEX,MAAM,CAAC,MAAM,6CAA6C,GAAG;IAC3D,WAAW,EAAE,uDAAuD;IACpE,EAAE,EAAE,0CAA0C;CACtC,CAAC;AAEX,MAAM,CAAC,MAAM,6CAA6C,GAAG;IAC3D,WAAW,EACT,kEAAkE;IACpE,EAAE,EAAE,0CAA0C;CACtC,CAAC;AAEX,MAAM,CAAC,MAAM,8CAA8C,GAAG;IAC5D,WAAW,EAAE,wDAAwD;IACrE,EAAE,EAAE,2CAA2C;CACvC,CAAC;AAEX,MAAM,CAAC,MAAM,yCAAyC,GAAG;IACvD,sCAAsC;CAC9B,CAAC;AAEX,MAAM,CAAC,MAAM,uCAAuC,GAAG;IACrD,+CAA+C;IAC/C,+CAA+C;IAC/C,gDAAgD;CACxC,CAAC;AAEX,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACnD,6CAA6C;IAC7C,6CAA6C;IAC7C,8CAA8C;CACtC,CAAC","sourcesContent":["export const containerKekLogSingleKeyringRefinement = {\n description: \"a container KEK log page contains at most one sealed keyring\",\n id: \"response.container-kek-log-single-keyring\",\n} as const;\n\nexport const containerDocumentLaneRequestUniqueIdsRefinement = {\n description: \"container document-lane request lane ids must be unique\",\n id: \"request.container-document-lane-unique-ids\",\n} as const;\n\nexport const containerDocumentLaneRequestPageTotalRefinement = {\n description:\n \"container document-lane request page limits must total at most 500\",\n id: \"request.container-document-lane-page-total\",\n} as const;\n\nexport const containerDocumentLaneResponseUniqueIdsRefinement = {\n description: \"container document-lane response lane ids must be unique\",\n id: \"response.container-document-lane-unique-ids\",\n} as const;\n\nexport const containerParentLaneRequestUniqueIdsRefinement = {\n description: \"container parent-lane request lane ids must be unique\",\n id: \"request.container-parent-lane-unique-ids\",\n} as const;\n\nexport const containerParentLaneRequestPageTotalRefinement = {\n description:\n \"container parent-lane request page limits must total at most 500\",\n id: \"request.container-parent-lane-page-total\",\n} as const;\n\nexport const containerParentLaneResponseUniqueIdsRefinement = {\n description: \"container parent-lane response lane ids must be unique\",\n id: \"response.container-parent-lane-unique-ids\",\n} as const;\n\nexport const containerKekLogResponseRuntimeRefinements = [\n containerKekLogSingleKeyringRefinement,\n] as const;\n\nexport const containerDocumentLaneRuntimeRefinements = [\n containerDocumentLaneRequestUniqueIdsRefinement,\n containerDocumentLaneRequestPageTotalRefinement,\n containerDocumentLaneResponseUniqueIdsRefinement,\n] as const;\n\nexport const containerParentLaneRuntimeRefinements = [\n containerParentLaneRequestUniqueIdsRefinement,\n containerParentLaneRequestPageTotalRefinement,\n containerParentLaneResponseUniqueIdsRefinement,\n] as const;\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Caller-chosen id that pairs one batched lane request with its result. */
|
|
3
|
+
export declare const ContainerReadLaneIdSchema: z.ZodCustom<string, string>;
|
|
4
|
+
/** Opaque `(updatedAt, id)` cursor returned by an earlier page of the lane. */
|
|
5
|
+
export declare const ContainerReadLaneWatermarkSchema: z.ZodObject<{
|
|
6
|
+
id: z.ZodString;
|
|
7
|
+
updatedAt: z.ZodString;
|
|
8
|
+
}, z.core.$strict>;
|
|
9
|
+
/**
|
|
10
|
+
* Containers one document-listing request may name. Each lane runs the same
|
|
11
|
+
* readable-container gate and access resolver as a single listing, so this
|
|
12
|
+
* bounds per-request server work; the page total bounds returned rows.
|
|
13
|
+
*/
|
|
14
|
+
export declare const MAX_CONTAINER_DOCUMENT_LANES = 32;
|
|
15
|
+
/** Rows one batched lane request may ask for when it omits `limit`. */
|
|
16
|
+
export declare const DEFAULT_CONTAINER_READ_LANE_PAGE_LIMIT = 100;
|
|
17
|
+
/** Bound on the sum of every lane's page limit, the single-page maximum. */
|
|
18
|
+
export declare const MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL = 500;
|
|
19
|
+
interface ContainerReadLaneRequestShape {
|
|
20
|
+
readonly laneId: string;
|
|
21
|
+
readonly limit?: number | undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Batched container reads pair results to requests by lane id and bound the
|
|
25
|
+
* rows one request may return to the single-page maximum.
|
|
26
|
+
*/
|
|
27
|
+
export declare function refineContainerReadLaneRequests(label: string): ({ lanes }: {
|
|
28
|
+
readonly lanes: ReadonlyArray<ContainerReadLaneRequestShape>;
|
|
29
|
+
}, context: z.RefinementCtx) => void;
|
|
30
|
+
/** Each requested lane id appears at most once among the results. */
|
|
31
|
+
export declare function refineContainerReadLaneResults(label: string): ({ results, }: {
|
|
32
|
+
readonly results: ReadonlyArray<{
|
|
33
|
+
readonly laneId: string;
|
|
34
|
+
}>;
|
|
35
|
+
}, context: z.RefinementCtx) => void;
|
|
36
|
+
export {};
|
|
@@ -1,4 +1,67 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { registerJsonSchemaFragment } from "./jsonSchema.js";
|
|
3
|
-
|
|
3
|
+
/** Caller-chosen id that pairs one batched lane request with its result. */
|
|
4
|
+
export const ContainerReadLaneIdSchema = registerJsonSchemaFragment(z.custom((value) => typeof value === "string" && value.length > 0 && value.length <= 64), { maxLength: 64, minLength: 1, type: "string" });
|
|
5
|
+
/** Opaque `(updatedAt, id)` cursor returned by an earlier page of the lane. */
|
|
6
|
+
export const ContainerReadLaneWatermarkSchema = z.strictObject({
|
|
7
|
+
id: z.string().min(1),
|
|
8
|
+
updatedAt: registerJsonSchemaFragment(z
|
|
9
|
+
.string()
|
|
10
|
+
.refine((value) => !Number.isNaN(new Date(value).getTime()), "Invalid watermark date"), { minLength: 1, type: "string" }),
|
|
11
|
+
});
|
|
12
|
+
/**
|
|
13
|
+
* Containers one document-listing request may name. Each lane runs the same
|
|
14
|
+
* readable-container gate and access resolver as a single listing, so this
|
|
15
|
+
* bounds per-request server work; the page total bounds returned rows.
|
|
16
|
+
*/
|
|
17
|
+
export const MAX_CONTAINER_DOCUMENT_LANES = 32;
|
|
18
|
+
/** Rows one batched lane request may ask for when it omits `limit`. */
|
|
19
|
+
export const DEFAULT_CONTAINER_READ_LANE_PAGE_LIMIT = 100;
|
|
20
|
+
/** Bound on the sum of every lane's page limit, the single-page maximum. */
|
|
21
|
+
export const MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL = 500;
|
|
22
|
+
/**
|
|
23
|
+
* Batched container reads pair results to requests by lane id and bound the
|
|
24
|
+
* rows one request may return to the single-page maximum.
|
|
25
|
+
*/
|
|
26
|
+
export function refineContainerReadLaneRequests(label) {
|
|
27
|
+
return ({ lanes }, context) => {
|
|
28
|
+
const laneIds = new Set();
|
|
29
|
+
let requestedPageTotal = 0;
|
|
30
|
+
lanes.forEach((lane, index) => {
|
|
31
|
+
if (laneIds.has(lane.laneId)) {
|
|
32
|
+
context.addIssue({
|
|
33
|
+
code: "custom",
|
|
34
|
+
message: `${label} id is duplicated`,
|
|
35
|
+
path: ["lanes", index, "laneId"],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
laneIds.add(lane.laneId);
|
|
39
|
+
requestedPageTotal +=
|
|
40
|
+
lane.limit ?? DEFAULT_CONTAINER_READ_LANE_PAGE_LIMIT;
|
|
41
|
+
});
|
|
42
|
+
if (requestedPageTotal > MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL) {
|
|
43
|
+
context.addIssue({
|
|
44
|
+
code: "custom",
|
|
45
|
+
message: `${label} batch page total exceeds ${MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL}`,
|
|
46
|
+
path: ["lanes"],
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Each requested lane id appears at most once among the results. */
|
|
52
|
+
export function refineContainerReadLaneResults(label) {
|
|
53
|
+
return ({ results, }, context) => {
|
|
54
|
+
const laneIds = new Set();
|
|
55
|
+
results.forEach((result, index) => {
|
|
56
|
+
if (laneIds.has(result.laneId)) {
|
|
57
|
+
context.addIssue({
|
|
58
|
+
code: "custom",
|
|
59
|
+
message: `${label} result id is duplicated`,
|
|
60
|
+
path: ["results", index, "laneId"],
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
laneIds.add(result.laneId);
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
}
|
|
4
67
|
//# sourceMappingURL=containerReadSchemas.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerReadSchemas.js","sourceRoot":"","sources":["containerReadSchemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D,MAAM,CAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"containerReadSchemas.js","sourceRoot":"","sources":["containerReadSchemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAE1D,4EAA4E;AAC5E,MAAM,CAAC,MAAM,yBAAyB,GAAG,0BAA0B,CACjE,CAAC,CAAC,MAAM,C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n/** Caller-chosen id that pairs one batched lane request with its result. */\nexport const ContainerReadLaneIdSchema = registerJsonSchemaFragment(\n z.custom<string>(\n (value) =>\n typeof value === \"string\" && value.length > 0 && value.length <= 64,\n ),\n { maxLength: 64, minLength: 1, type: \"string\" },\n);\n\n/** Opaque `(updatedAt, id)` cursor returned by an earlier page of the lane. */\nexport const ContainerReadLaneWatermarkSchema = z.strictObject({\n id: z.string().min(1),\n updatedAt: registerJsonSchemaFragment(\n z\n .string()\n .refine(\n (value) => !Number.isNaN(new Date(value).getTime()),\n \"Invalid watermark date\",\n ),\n { minLength: 1, type: \"string\" },\n ),\n});\n\n/**\n * Containers one document-listing request may name. Each lane runs the same\n * readable-container gate and access resolver as a single listing, so this\n * bounds per-request server work; the page total bounds returned rows.\n */\nexport const MAX_CONTAINER_DOCUMENT_LANES = 32;\n\n/** Rows one batched lane request may ask for when it omits `limit`. */\nexport const DEFAULT_CONTAINER_READ_LANE_PAGE_LIMIT = 100;\n/** Bound on the sum of every lane's page limit, the single-page maximum. */\nexport const MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL = 500;\n\ninterface ContainerReadLaneRequestShape {\n readonly laneId: string;\n readonly limit?: number | undefined;\n}\n\n/**\n * Batched container reads pair results to requests by lane id and bound the\n * rows one request may return to the single-page maximum.\n */\nexport function refineContainerReadLaneRequests(label: string) {\n return (\n { lanes }: { readonly lanes: ReadonlyArray<ContainerReadLaneRequestShape> },\n context: z.RefinementCtx,\n ): void => {\n const laneIds = new Set<string>();\n let requestedPageTotal = 0;\n\n lanes.forEach((lane, index) => {\n if (laneIds.has(lane.laneId)) {\n context.addIssue({\n code: \"custom\",\n message: `${label} id is duplicated`,\n path: [\"lanes\", index, \"laneId\"],\n });\n }\n laneIds.add(lane.laneId);\n requestedPageTotal +=\n lane.limit ?? DEFAULT_CONTAINER_READ_LANE_PAGE_LIMIT;\n });\n\n if (requestedPageTotal > MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL) {\n context.addIssue({\n code: \"custom\",\n message: `${label} batch page total exceeds ${MAX_CONTAINER_READ_LANE_BATCH_PAGE_TOTAL}`,\n path: [\"lanes\"],\n });\n }\n };\n}\n\n/** Each requested lane id appears at most once among the results. */\nexport function refineContainerReadLaneResults(label: string) {\n return (\n {\n results,\n }: { readonly results: ReadonlyArray<{ readonly laneId: string }> },\n context: z.RefinementCtx,\n ): void => {\n const laneIds = new Set<string>();\n results.forEach((result, index) => {\n if (laneIds.has(result.laneId)) {\n context.addIssue({\n code: \"custom\",\n message: `${label} result id is duplicated`,\n path: [\"results\", index, \"laneId\"],\n });\n }\n laneIds.add(result.laneId);\n });\n };\n}\n"]}
|