@10x-media/analytics 1.0.0-beta.16 → 1.0.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/adapters/ga4/ga4.js +33 -2
  3. package/dist/adapters/ga4/ga4.js.map +1 -1
  4. package/dist/adapters/ga4/measurementId.js +4 -1
  5. package/dist/adapters/ga4/measurementId.js.map +1 -1
  6. package/dist/adapters/ga4/propertyId.js +17 -0
  7. package/dist/adapters/ga4/propertyId.js.map +1 -0
  8. package/dist/adapters/http/fetchJson.js +24 -1
  9. package/dist/adapters/http/fetchJson.js.map +1 -1
  10. package/dist/adapters/plausible/plausible.js +16 -1
  11. package/dist/adapters/plausible/plausible.js.map +1 -1
  12. package/dist/adapters/plausible/siteId.js +31 -0
  13. package/dist/adapters/plausible/siteId.js.map +1 -0
  14. package/dist/adapters/posthog/posthog.js +17 -3
  15. package/dist/adapters/posthog/posthog.js.map +1 -1
  16. package/dist/adapters/umami/umami.js +34 -7
  17. package/dist/adapters/umami/umami.js.map +1 -1
  18. package/dist/charts/series.js +1 -1
  19. package/dist/core/contract.d.ts +16 -1
  20. package/dist/core/contract.js.map +1 -1
  21. package/dist/core/options.d.ts +1 -1
  22. package/dist/core/options.js +1 -1
  23. package/dist/core/options.js.map +1 -1
  24. package/dist/core/scopedRead.js +62 -14
  25. package/dist/core/scopedRead.js.map +1 -1
  26. package/dist/core/sourceErrors.js +12 -1
  27. package/dist/core/sourceErrors.js.map +1 -1
  28. package/dist/core/sourceOptions.js +1 -1
  29. package/dist/core/sourceOptions.js.map +1 -1
  30. package/dist/core/sourcePolicy.d.ts +8 -1
  31. package/dist/core/sourcePolicy.js.map +1 -1
  32. package/dist/core/throttle.js +3 -1
  33. package/dist/core/throttle.js.map +1 -1
  34. package/dist/exports/adapters/contract.d.ts +1 -1
  35. package/dist/exports/adapters/ga4.d.ts +2 -2
  36. package/dist/exports/adapters/native.d.ts +2 -2
  37. package/dist/exports/adapters/plausible.d.ts +2 -2
  38. package/dist/exports/adapters/posthog.d.ts +2 -2
  39. package/dist/exports/adapters/umami.d.ts +2 -2
  40. package/dist/exports/client.d.ts +3 -1
  41. package/dist/exports/client.js +3 -1
  42. package/dist/exports/next.d.ts +2 -2
  43. package/dist/exports/testing.d.ts +2 -2
  44. package/dist/exports/types.d.ts +3 -3
  45. package/dist/fields/config/fetchSources.js +1 -1
  46. package/dist/fields/config/fetchSources.js.map +1 -1
  47. package/dist/goals/collection.js +3 -2
  48. package/dist/goals/collection.js.map +1 -1
  49. package/dist/goals/resolver.js +1 -1
  50. package/dist/index.d.ts +4 -3
  51. package/dist/index.js +50 -4
  52. package/dist/index.js.map +1 -1
  53. package/dist/native/geo/maxmindResolver.js +1 -1
  54. package/dist/native/nativeAdapter.js +1 -1
  55. package/dist/plugin/createRuntime.js +57 -13
  56. package/dist/plugin/createRuntime.js.map +1 -1
  57. package/dist/plugin/pluginCollections.js +4 -1
  58. package/dist/plugin/pluginCollections.js.map +1 -1
  59. package/dist/plugin/providerStatusEndpoint.js +80 -0
  60. package/dist/plugin/providerStatusEndpoint.js.map +1 -0
  61. package/dist/plugin/queryEndpoint.js +1 -1
  62. package/dist/plugin/queryEndpoint.js.map +1 -1
  63. package/dist/plugin/readContextForRequest.d.ts +4 -3
  64. package/dist/plugin/readContextForRequest.js +2 -2
  65. package/dist/plugin/readContextForRequest.js.map +1 -1
  66. package/dist/plugin/refreshEndpoint.js +1 -1
  67. package/dist/plugin/routes.d.ts +5 -0
  68. package/dist/plugin/routes.js +1 -0
  69. package/dist/plugin/routes.js.map +1 -1
  70. package/dist/plugin/runtime.js.map +1 -1
  71. package/dist/providers/ProviderConnection.d.ts +12 -0
  72. package/dist/providers/ProviderConnection.js +105 -0
  73. package/dist/providers/ProviderConnection.js.map +1 -0
  74. package/dist/providers/ProviderConnectionTest.d.ts +12 -0
  75. package/dist/providers/ProviderConnectionTest.js +55 -0
  76. package/dist/providers/ProviderConnectionTest.js.map +1 -0
  77. package/dist/providers/ProvidersListNotice.d.ts +1 -1
  78. package/dist/providers/ProvidersListNotice.js +3 -2
  79. package/dist/providers/ProvidersListNotice.js.map +1 -1
  80. package/dist/providers/collection.d.ts +1 -1
  81. package/dist/providers/collection.js +97 -38
  82. package/dist/providers/collection.js.map +1 -1
  83. package/dist/providers/connectionCheck.d.ts +1 -0
  84. package/dist/providers/connectionCheck.js +80 -0
  85. package/dist/providers/connectionCheck.js.map +1 -0
  86. package/dist/providers/connectionState.js +53 -0
  87. package/dist/providers/connectionState.js.map +1 -0
  88. package/dist/providers/factory.d.ts +1 -3
  89. package/dist/providers/factory.js +18 -21
  90. package/dist/providers/factory.js.map +1 -1
  91. package/dist/providers/hosts.js +20 -6
  92. package/dist/providers/hosts.js.map +1 -1
  93. package/dist/providers/ids.d.ts +6 -0
  94. package/dist/providers/ids.js +32 -0
  95. package/dist/providers/ids.js.map +1 -0
  96. package/dist/providers/providerStatusClient.js +60 -0
  97. package/dist/providers/providerStatusClient.js.map +1 -0
  98. package/dist/providers/registry.js +56 -20
  99. package/dist/providers/registry.js.map +1 -1
  100. package/dist/providers/retarget.js +39 -8
  101. package/dist/providers/retarget.js.map +1 -1
  102. package/dist/providers/secrets.d.ts +1 -1
  103. package/dist/providers/secrets.js.map +1 -1
  104. package/dist/providers/status.d.ts +1 -0
  105. package/dist/providers/status.js +181 -0
  106. package/dist/providers/status.js.map +1 -0
  107. package/dist/surfacing/classifyError.js +37 -5
  108. package/dist/surfacing/classifyError.js.map +1 -1
  109. package/dist/surfacing/engine.js +2 -2
  110. package/dist/surfacing/engine.js.map +1 -1
  111. package/dist/surfacing/lanes.js +29 -22
  112. package/dist/surfacing/lanes.js.map +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/testing/settle.d.ts +2 -1
  115. package/dist/testing/settle.js +6 -2
  116. package/dist/testing/settle.js.map +1 -1
  117. package/dist/tracker/sinks/ga4.js +2 -2
  118. package/dist/translations/ar.js +40 -8
  119. package/dist/translations/ar.js.map +1 -1
  120. package/dist/translations/de.js +40 -8
  121. package/dist/translations/de.js.map +1 -1
  122. package/dist/translations/en.js +40 -8
  123. package/dist/translations/en.js.map +1 -1
  124. package/dist/translations/es.js +40 -8
  125. package/dist/translations/es.js.map +1 -1
  126. package/dist/translations/fr.js +40 -8
  127. package/dist/translations/fr.js.map +1 -1
  128. package/dist/translations/id.js +40 -8
  129. package/dist/translations/id.js.map +1 -1
  130. package/dist/translations/keys.d.ts +32 -0
  131. package/dist/translations/keys.js +32 -0
  132. package/dist/translations/keys.js.map +1 -1
  133. package/dist/translations/ko.js +40 -8
  134. package/dist/translations/ko.js.map +1 -1
  135. package/dist/translations/pt.js +40 -8
  136. package/dist/translations/pt.js.map +1 -1
  137. package/dist/translations/ru.js +40 -8
  138. package/dist/translations/ru.js.map +1 -1
  139. package/dist/translations/uk.js +40 -8
  140. package/dist/translations/uk.js.map +1 -1
  141. package/dist/translations/zh.js +40 -8
  142. package/dist/translations/zh.js.map +1 -1
  143. package/dist/ui/analytics.css +63 -0
  144. package/dist/ui/components/SourcesNoticeBanner.js +4 -3
  145. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
  146. package/dist/view/ViewSections.js +9 -2
  147. package/dist/view/ViewSections.js.map +1 -1
  148. package/dist/view/sections/EmptyStates.js +5 -4
  149. package/dist/view/sections/EmptyStates.js.map +1 -1
  150. package/dist/view/sections/OverviewCards.js +6 -2
  151. package/dist/view/sections/OverviewCards.js.map +1 -1
  152. package/dist/view/sections/SourceConnectionNote.js +56 -0
  153. package/dist/view/sections/SourceConnectionNote.js.map +1 -0
  154. package/dist/view/viewProps.d.ts +2 -0
  155. package/dist/view/viewProps.js +2 -1
  156. package/dist/view/viewProps.js.map +1 -1
  157. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","names":[],"sources":["../../src/providers/registry.ts"],"sourcesContent":["import { createLocalReq, type Payload } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport type { AnalyticsAdapter, AnalyticsCapabilities } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { ProvidersResolve } from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { SourceMisconfiguredError } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord, valueAt } from '../core/values'\nimport { loadEncrypted } from '../plugin/encrypted'\nimport { GA4_SDK_WARNING, isProductionBuild } from '../plugin/peers'\nimport { remember } from '../surfacing/bounded'\nimport { createEpochFallback, type EpochStore, FIXED_CONFIG_EPOCH } from '../surfacing/epoch'\nimport { createAdapterPool, type PooledDocument } from './adapterPool'\nimport {\n\tadapterFromProviderDoc,\n\tdocumentAdapterId,\n\tfailingAdapter,\n\tPROVIDER_IDS,\n\ttype ProviderDoc,\n\ttype ProviderFactoryContext,\n\ttype ProviderId,\n} from './factory'\nimport type { ProviderHostPolicy } from './hosts'\nimport { createCollectionProbe, type Probe, type ProbeRow, scopeOf, versionOf } from './probe'\nimport {\n\tcombineRegistries,\n\tnoGuardedConnection,\n\ttype ProviderAdapter,\n\tproviderScopeWhere,\n\ttype RegistryBase,\n} from './resolver'\nimport { SECRET_PATHS } from './secrets'\n\n/** How often a failing probe is reported, at most. */\nconst WARN_EVERY_MS = 60_000\n\n/**\n * How long a document whose adapter could not be built (its secrets did not decrypt, its settings\n * threw) stands in as a failing source before its scope's registry reads it again.\n */\nexport const FAILED_DOCUMENT_RETRY_MS = 60_000\n\n/** Where an install's runtime provider adapters come from. */\nexport type ProviderPlan =\n\t| { kind: 'static' }\n\t| {\n\t\t\tkind: 'collection'\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\t/** Types the install serves, every one when absent; a document of another is no source. */\n\t\t\ttypes?: readonly ProviderId[]\n\t\t\t/** The install's config native adapter, which a `native` document grants to its scope. */\n\t\t\tnativeAdapter?: AnalyticsAdapter\n\t }\n\t| { kind: 'resolve'; resolve: ProvidersResolve }\n\ninterface ProviderRegistryOptions {\n\tpayload: Payload\n\tplan: ProviderPlan\n\t/** How every document's adapter counts without consent beyond its own setting. */\n\twithoutConsent?: Pick<\n\t\tProviderFactoryContext,\n\t\t'heldWithoutConsent' | 'followingCountsWithoutConsent'\n\t>\n\t/** The config adapters every scope's registry starts from. */\n\tbase: RegistryBase\n\t/** The config registry as an install without runtime providers hands it out. */\n\tregistry: AdapterRegistry\n\t/** Applied to every scope's registry: revenue removed on an install that measures no money. */\n\tnarrow: (registry: AdapterRegistry) => AdapterRegistry\n\thosts: ProviderHostPolicy\n\t/** Missing, every document adapter refuses rather than going out unguarded. */\n\tfetch: FetchLike | undefined\n\tsdks: AnalyticsSdks\n\t/** A `providers.resolve` install's configuration tokens, which `refresh` bumps. */\n\ttokens?: EpochStore\n\tnow?: () => number\n}\n\n/** One instance's runtime provider adapters, and the epoch that says when they changed. */\ninterface ProviderRegistry {\n\tresolve: RegistryResolver\n\t/** The scope's provider configuration epoch, which every cache key carries. */\n\tepoch(scope: string | null): Promise<string>\n\t/**\n\t * Whether the scope's own available documents grant `adapterId`, as its registry does. The native\n\t * adapter is answered from the committed rows alone, decrypting nothing, so a beacon stays cheap.\n\t * Only on the providers collection.\n\t */\n\tgranted?(scope: string | null, adapterId: string): Promise<boolean>\n\t/** A save on this instance touched these scopes, which it then reads again as soon as it commits. */\n\tchanged(scopes: Iterable<string | null>): void\n\t/** Retires the scope's cached reads on every instance: `refreshProviders()`. */\n\trefresh(scope: string | null): Promise<void>\n\tclose(): Promise<void>\n}\n\ntype DecryptFieldValue = Awaited<ReturnType<typeof loadEncrypted>>['decryptFieldValue']\n\n/** Sets a `group.field` secret in place; a document without that group is left as it is. */\nconst setAtPath = (doc: Record<string, unknown>, path: string, value: string): void => {\n\tconst [group = '', field] = path.split('.')\n\tconst target = doc[group]\n\tif (field !== undefined && isRecord(target)) {\n\t\ttarget[field] = value\n\t}\n}\n\n/** The secrets a document stores, by path; blank ones are left out. */\nconst storedSecrets = (doc: Record<string, unknown>): Array<{ path: string; value: string }> =>\n\tSECRET_PATHS.flatMap(({ path }) => {\n\t\tconst value = valueAt(doc, path)\n\t\treturn typeof value === 'string' && value !== '' ? [{ path, value }] : []\n\t})\n\nconst refOf = (doc: { id: string; version: string }): string => `${doc.id}@${doc.version}`\n\n/** The registry of an install without runtime providers: the config adapters, for every scope. */\nconst staticRegistry = (options: ProviderRegistryOptions): ProviderRegistry => ({\n\tresolve: async () => ({ registry: options.registry, grants: NO_GRANTS }),\n\tepoch: async () => FIXED_CONFIG_EPOCH,\n\tchanged: () => {},\n\trefresh: async () => {},\n\tclose: async () => {},\n})\n\n/**\n * `providers.resolve`: the host's function answers every read, uncached, and the configuration\n * epoch is a token the host bumps through `refreshProviders()` once it changed its own storage.\n */\nconst resolveRegistry = (\n\toptions: ProviderRegistryOptions,\n\tresolve: ProvidersResolve\n): ProviderRegistry => {\n\tconst { tokens } = options\n\treturn {\n\t\tresolve: async ({ payload, req, scope }) => {\n\t\t\tconst adapters = await resolve({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tscope,\n\t\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\t\thosts: options.hosts,\n\t\t\t\tsdks: options.sdks,\n\t\t\t})\n\t\t\tconst combined = combineRegistries(\n\t\t\t\toptions.base,\n\t\t\t\tadapters.map((adapter) => ({ adapter, docId: adapter.id }))\n\t\t\t)\n\t\t\treturn { ...combined, registry: options.narrow(combined.registry) }\n\t\t},\n\t\tepoch: (scope) => tokens?.get(scope) ?? Promise.resolve(FIXED_CONFIG_EPOCH),\n\t\tchanged: () => {},\n\t\trefresh: async (scope) => {\n\t\t\tawait tokens?.bump(scope)\n\t\t},\n\t\tclose: async () => {},\n\t}\n}\n\ninterface CachedRegistry {\n\tepoch: string\n\tresolved: Promise<ScopeRegistry>\n\t/** The enabled documents it was built from, kept in use while it is handed out. */\n\tids: readonly string[]\n\t/** Each as `id@updatedAt`, so disposing a version drops exactly the registries built on it. */\n\trefs: ReadonlySet<string>\n\t/** Set when a document stood in as a failing source: the registry is built again from then on. */\n\tretryAt?: number\n}\n\n/** What one document built: its adapter, or a stand-in when it could not be read. */\ntype Built =\n\t| { ok: true; adapter: AnalyticsAdapter | null }\n\t| { ok: false; standIn: AnalyticsAdapter }\n\n/** What a stand-in declares when the document's settings build nothing even without its secrets. */\nconst STAND_IN_CAPABILITIES: AnalyticsCapabilities = {\n\trealtime: false,\n\tminGranularity: 'day',\n\tmaxLookbackDays: null,\n\tmetrics: new Set(['pageviews', 'visitors']),\n\tdimensions: new Set(),\n\tfilters: {},\n\trateLimit: null,\n\trecommendedTtl: { realtime: 60, aggregate: 60 },\n}\n\n/**\n * Stands in while a document's adapter cannot be built: keeps its identity, and its capabilities\n * where settings build without secrets; reads fail as `source_misconfigured`, capture none.\n */\nconst standInFor = (\n\traw: Record<string, unknown>,\n\tcause: unknown,\n\tbuild: (doc: Record<string, unknown>) => AnalyticsAdapter | null\n): AnalyticsAdapter => {\n\tconst blank = structuredClone(raw)\n\tfor (const { path } of storedSecrets(blank)) {\n\t\tsetAtPath(blank, path, '')\n\t}\n\tlet shape: AnalyticsAdapter | null = null\n\ttry {\n\t\tshape = build(blank)\n\t} catch {\n\t\tshape = null\n\t}\n\tconst id = documentAdapterId(raw.provider, raw.id)\n\treturn failingAdapter(\n\t\t{\n\t\t\tid,\n\t\t\tlabel: shape?.label ?? (typeof raw.name === 'string' && raw.name !== '' ? raw.name : id),\n\t\t\tcapabilities: shape?.capabilities ?? STAND_IN_CAPABILITIES,\n\t\t\trealtime: shape?.realtime,\n\t\t},\n\t\t() =>\n\t\t\tnew SourceMisconfiguredError(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" could not be read; check its settings and keys`,\n\t\t\t\t{ cause }\n\t\t\t)\n\t)\n}\n\n/**\n * A scope's registry is cached under the epoch the probe reads before any document, so it is never\n * filed under an older epoch. Only unseen document versions are read and decrypted.\n */\nconst collectionRegistry = (\n\toptions: ProviderRegistryOptions,\n\tplan: Extract<ProviderPlan, { kind: 'collection' }>\n): ProviderRegistry => {\n\tconst { payload, now } = options\n\tconst { slug } = plan\n\tconst probe = createCollectionProbe({\n\t\tpayload,\n\t\tslug,\n\t\tscopeField: plan.scopeField,\n\t\twhere: (scope) => providerScopeWhere(plan.scopeField, scope),\n\t\tprovider: true,\n\t\t...(now ? { now } : {}),\n\t})\n\tconst registries = new Map<string, CachedRegistry>()\n\tconst pool = createAdapterPool({\n\t\tpayload,\n\t\t...(now ? { now } : {}),\n\t\tonDispose: (doc) => {\n\t\t\tconst ref = refOf(doc)\n\t\t\tfor (const [key, cached] of registries) {\n\t\t\t\tif (cached.refs.has(ref)) {\n\t\t\t\t\tregistries.delete(key)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\tlet warnedGa4 = false\n\tconst clock = now ?? currentTime\n\tconst warnProbeFailed = throttled((message) => payload.logger?.warn(message), {\n\t\tnow: clock,\n\t\tintervalMs: WARN_EVERY_MS,\n\t})\n\t// A failing probe keys on the last epoch read, which the registry in use was built from.\n\tconst fallback = createEpochFallback(clock)\n\tconst types: readonly string[] = plan.types ?? PROVIDER_IDS\n\n\t/** An enabled document of a type the install serves, which its adapter may then make a source. */\n\tconst servable = (row: ProbeRow): boolean => row.enabled && types.includes(row.provider ?? '')\n\n\t/** A probed id as the collection stores it: rows carry every id as text. */\n\tconst idOf = (id: string): string | number => {\n\t\tconst custom = isCollectionSlug(payload, slug)\n\t\t\t? payload.collections[slug]?.customIDType\n\t\t\t: undefined\n\t\treturn (custom ?? payload.db.defaultIDType) === 'number' && /^\\d+$/.test(id) ? Number(id) : id\n\t}\n\n\tconst fromDocument = (doc: Record<string, unknown>): AnalyticsAdapter | null =>\n\t\t// A row of the providers collection, whose fields `ProviderDoc` mirrors.\n\t\tadapterFromProviderDoc(doc as ProviderDoc, {\n\t\t\t...(plan.nativeAdapter ? { native: plan.nativeAdapter } : {}),\n\t\t\thosts: options.hosts,\n\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\tsdks: options.sdks,\n\t\t\t...options.withoutConsent,\n\t\t})\n\n\tconst adapterOf = async (\n\t\traw: Record<string, unknown>,\n\t\tdecrypt: DecryptFieldValue\n\t): Promise<Built> => {\n\t\ttry {\n\t\t\tconst doc = structuredClone(raw)\n\t\t\tfor (const { path, value } of storedSecrets(doc)) {\n\t\t\t\tconst plain = await decrypt(payload, { collection: slug, path, value })\n\t\t\t\tsetAtPath(doc, path, typeof plain === 'string' ? plain : '')\n\t\t\t}\n\t\t\tconst adapter = fromDocument(doc)\n\t\t\t// The first GA4 document is the earliest this install shows it reads GA4 at all.\n\t\t\tif (raw.provider === 'ga4' && !options.sdks.ga4 && !warnedGa4 && isProductionBuild()) {\n\t\t\t\twarnedGa4 = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t\treturn { ok: true, adapter }\n\t\t} catch (err) {\n\t\t\t// A corrupt or key-rotated ciphertext must neither take the scope's registry down nor drop\n\t\t\t// the source silently: it stands in as a failing source until the retry.\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" (${String(raw.provider)}) could not be read, its reads fail until it can: ${String(err)}`\n\t\t\t)\n\t\t\treturn { ok: false, standIn: standInFor(raw, err, fromDocument) }\n\t\t}\n\t}\n\n\t/**\n\t * Reads and builds the documents the pool has no adapter for, answering each by id. A stand-in\n\t * is never pooled, so the document is read again once its registry expires.\n\t */\n\tconst buildDocuments = async (\n\t\tscope: string | null,\n\t\tids: readonly string[]\n\t): Promise<{ built: Map<string, AnalyticsAdapter | null>; failed: boolean }> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered for the providers`)\n\t\t}\n\t\tconst { decryptFieldValue, withRawEncrypted } = await loadEncrypted()\n\t\t// Never the caller's: the raw window is not a concurrency boundary, so a request shared with\n\t\t// other reads would hand them ciphertext, and it may also hold an uncommitted transaction.\n\t\tconst req = await createLocalReq({}, payload)\n\t\tconst { docs } = await withRawEncrypted(req, () =>\n\t\t\tpayload.find({\n\t\t\t\tcollection: slug,\n\t\t\t\twhere: {\n\t\t\t\t\tand: [\n\t\t\t\t\t\t{ id: { in: ids.map(idOf) } },\n\t\t\t\t\t\t{ enabled: { equals: true } },\n\t\t\t\t\t\tproviderScopeWhere(plan.scopeField, scope),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tlimit: ids.length,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t)\n\t\tconst found: unknown[] = docs\n\t\tconst built = new Map<string, AnalyticsAdapter | null>()\n\t\tlet failed = false\n\t\tfor (const raw of found.filter(isRecord)) {\n\t\t\tconst doc: PooledDocument = { id: String(raw.id), version: versionOf(raw.updatedAt), scope }\n\t\t\tconst outcome = await adapterOf(raw, decryptFieldValue)\n\t\t\tif (outcome.ok) {\n\t\t\t\tbuilt.set(doc.id, pool.put(doc, outcome.adapter, raw.provider !== 'native'))\n\t\t\t} else {\n\t\t\t\tbuilt.set(doc.id, outcome.standIn)\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t\treturn { built, failed }\n\t}\n\n\tconst build = async (\n\t\tscope: string | null,\n\t\tdocs: readonly PooledDocument[],\n\t\tflagged: ReadonlySet<string>\n\t): Promise<{ registry: ScopeRegistry; failed: boolean }> => {\n\t\tconst missing = docs.filter((doc) => pool.get(doc) === undefined).map((doc) => doc.id)\n\t\tconst read = missing.length > 0 ? await buildDocuments(scope, missing) : undefined\n\t\tconst extras: ProviderAdapter[] = []\n\t\tfor (const doc of docs) {\n\t\t\tconst adapter = read?.built.has(doc.id) ? read.built.get(doc.id) : pool.get(doc)\n\t\t\t// Lacking what its adapter reads with, a document is no source and grants nothing; a\n\t\t\t// stand-in for one that failed to decrypt still is, configured but failing.\n\t\t\tif (adapter?.isConfigured()) {\n\t\t\t\textras.push({ adapter, docId: doc.id, isDefault: flagged.has(doc.id) })\n\t\t\t}\n\t\t}\n\t\tpool.retain(scope, new Set(docs.map((doc) => doc.id)))\n\t\tconst combined = combineRegistries(options.base, extras)\n\t\treturn {\n\t\t\tregistry: { ...combined, registry: options.narrow(combined.registry) },\n\t\t\tfailed: read?.failed === true,\n\t\t}\n\t}\n\n\tconst probed = async (scope: string | null): Promise<Probe | undefined> => {\n\t\ttry {\n\t\t\treturn await probe.read(scope)\n\t\t} catch (err) {\n\t\t\twarnProbeFailed(\n\t\t\t\t`analytics: reading the provider documents failed, cached reads key on the last epoch this instance read: ${String(err)}`\n\t\t\t)\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tconst isCurrent = (cached: CachedRegistry, epoch: string): boolean =>\n\t\tcached.epoch === epoch && (cached.retryAt === undefined || clock() < cached.retryAt)\n\n\tconst registryOf = async (scope: string | null): Promise<ScopeRegistry> => {\n\t\tconst key = scope ?? ''\n\t\tconst state = await probe.read(scope)\n\t\tfallback.read(scope, state.epoch)\n\t\tconst cached = registries.get(key)\n\t\tif (cached && isCurrent(cached, state.epoch)) {\n\t\t\tpool.touch(cached.ids)\n\t\t\treturn cached.resolved\n\t\t}\n\t\tconst rows = state.rows.filter(servable)\n\t\tconst docs: PooledDocument[] = rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tversion: row.updatedAt,\n\t\t\tscope,\n\t\t}))\n\t\tconst flagged = new Set(rows.filter((row) => row.isDefault).map((row) => row.id))\n\t\tconst built = build(scope, docs, flagged)\n\t\tconst entry: CachedRegistry = {\n\t\t\tepoch: state.epoch,\n\t\t\tresolved: built.then((done) => done.registry),\n\t\t\tids: docs.map((doc) => doc.id),\n\t\t\trefs: new Set(docs.map(refOf)),\n\t\t}\n\t\tbuilt.then(\n\t\t\t(done) => {\n\t\t\t\tif (done.failed) {\n\t\t\t\t\tentry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\tremember(registries, [key, entry])\n\t\tentry.resolved.catch(() => {\n\t\t\tif (registries.get(key) === entry) {\n\t\t\t\tregistries.delete(key)\n\t\t\t}\n\t\t})\n\t\treturn entry.resolved\n\t}\n\n\treturn {\n\t\tresolve: (args) => registryOf(scopeOf(args.scope)),\n\t\tepoch: async (raw) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst state = await probed(scope)\n\t\t\treturn state ? fallback.read(scope, state.epoch) : fallback.failed(scope)\n\t\t},\n\t\tgranted: async (raw, adapterId) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst native = plan.nativeAdapter\n\t\t\tif (native && native.id === adapterId) {\n\t\t\t\tconst { rows } = await probe.read(scope)\n\t\t\t\treturn (\n\t\t\t\t\tnative.isConfigured() && rows.some((row) => row.provider === 'native' && servable(row))\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn (await registryOf(scope)).grants.has(adapterId)\n\t\t},\n\t\tchanged: (scopes) => probe.expedite(scopes),\n\t\trefresh: async (scope) => probe.expedite([scope]),\n\t\tclose: () => pool.close(),\n\t}\n}\n\n/** The runtime provider registry of one Payload instance, for the install's plan. */\nexport const createProviderRegistry = (options: ProviderRegistryOptions): ProviderRegistry => {\n\tconst { plan } = options\n\tswitch (plan.kind) {\n\t\tcase 'collection':\n\t\t\treturn collectionRegistry(options, plan)\n\t\tcase 'resolve':\n\t\t\treturn resolveRegistry(options, plan.resolve)\n\t\tdefault:\n\t\t\treturn staticRegistry(options)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0CA,MAAM,gBAAgB;;;;;AAMtB,MAAa,2BAA2B;;AA4DxC,MAAM,aAAa,KAA8B,MAAc,UAAwB;CACtF,MAAM,CAAC,QAAQ,IAAI,SAAS,KAAK,MAAM,GAAG;CAC1C,MAAM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,KAAK,MAAb;EACC,KAAK,cACJ,OAAO,mBAAmB,SAAS,IAAI;EACxC,KAAK,WACJ,OAAO,gBAAgB,SAAS,KAAK,OAAO;EAC7C,SACC,OAAO,eAAe,OAAO;CAC/B;AACD"}
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../src/providers/registry.ts"],"sourcesContent":["import { createLocalReq, type Payload } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport type { AnalyticsAdapter, AnalyticsCapabilities } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { ProvidersResolve } from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { SourceMisconfiguredError } from '../core/sourceErrors'\nimport { throttled, WARN_EVERY_MS } from '../core/throttle'\nimport { isRecord, valueAt } from '../core/values'\nimport { loadEncrypted } from '../plugin/encrypted'\nimport { GA4_SDK_WARNING, isProductionBuild } from '../plugin/peers'\nimport { remember } from '../surfacing/bounded'\nimport { createEpochFallback, type EpochStore, FIXED_CONFIG_EPOCH } from '../surfacing/epoch'\nimport { createAdapterPool, type PooledDocument } from './adapterPool'\nimport {\n\tadapterFromProviderDoc,\n\tfailingAdapter,\n\ttype ProviderDoc,\n\ttype ProviderFactoryContext,\n} from './factory'\nimport type { ProviderHostPolicy } from './hosts'\nimport { documentAdapterId, PROVIDER_IDS, type ProviderId } from './ids'\nimport { createCollectionProbe, type Probe, type ProbeRow, scopeOf, versionOf } from './probe'\nimport {\n\tcombineRegistries,\n\tnoGuardedConnection,\n\ttype ProviderAdapter,\n\tproviderScopeWhere,\n\ttype RegistryBase,\n} from './resolver'\nimport { SECRET_PATHS } from './secrets'\n\n/**\n * How long a document whose adapter could not be built (its secrets did not decrypt, its settings\n * threw) stands in as a failing source before its scope's registry reads it again.\n */\nexport const FAILED_DOCUMENT_RETRY_MS = 60_000\n\n/** Where an install's runtime provider adapters come from. */\nexport type ProviderPlan =\n\t| { kind: 'static' }\n\t| {\n\t\t\tkind: 'collection'\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\t/** Types the install serves, every one when absent; a document of another is no source. */\n\t\t\ttypes?: readonly ProviderId[]\n\t\t\t/** The install's config native adapter, which a `native` document grants to its scope. */\n\t\t\tnativeAdapter?: AnalyticsAdapter\n\t }\n\t| { kind: 'resolve'; resolve: ProvidersResolve }\n\ninterface ProviderRegistryOptions {\n\tpayload: Payload\n\tplan: ProviderPlan\n\t/** How every document's adapter counts without consent beyond its own setting. */\n\twithoutConsent?: Pick<\n\t\tProviderFactoryContext,\n\t\t'heldWithoutConsent' | 'followingCountsWithoutConsent'\n\t>\n\t/** The config adapters every scope's registry starts from. */\n\tbase: RegistryBase\n\t/** The config registry as an install without runtime providers hands it out. */\n\tregistry: AdapterRegistry\n\t/** Applied to every scope's registry: revenue removed on an install that measures no money. */\n\tnarrow: (registry: AdapterRegistry) => AdapterRegistry\n\thosts: ProviderHostPolicy\n\t/** Missing, every document adapter refuses rather than going out unguarded. */\n\tfetch: FetchLike | undefined\n\tsdks: AnalyticsSdks\n\t/** A `providers.resolve` install's configuration tokens, which `refresh` bumps. */\n\ttokens?: EpochStore\n\tnow?: () => number\n}\n\n/** One instance's runtime provider adapters, and the epoch that says when they changed. */\ninterface ProviderRegistry {\n\tresolve: RegistryResolver\n\t/** The scope's provider configuration epoch, which every cache key carries. */\n\tepoch(scope: string | null): Promise<string>\n\t/**\n\t * Whether the scope's own available documents grant `adapterId`, as its registry does. The native\n\t * adapter is answered from the committed rows alone, decrypting nothing, so a beacon stays cheap.\n\t * Only on the providers collection.\n\t */\n\tgranted?(scope: string | null, adapterId: string): Promise<boolean>\n\t/** A save on this instance touched these scopes, which it then reads again as soon as it commits. */\n\tchanged(scopes: Iterable<string | null>): void\n\t/** Retires the scope's cached reads on every instance: `refreshProviders()`. */\n\trefresh(scope: string | null): Promise<void>\n\t/**\n\t * A fresh adapter of one stored document, disabled ones included, for its Test connection\n\t * button: null when there is no such document or it builds none. Only on the providers collection.\n\t */\n\tdocumentAdapter?(id: string): Promise<AnalyticsAdapter | null>\n\t/**\n\t * The saved version (`updatedAt`) of the document an adapter of this registry was built from,\n\t * which the connection results it gives are stamped with.\n\t */\n\tversionOf?(adapter: AnalyticsAdapter): string | undefined\n\tclose(): Promise<void>\n}\n\ntype DecryptFieldValue = Awaited<ReturnType<typeof loadEncrypted>>['decryptFieldValue']\n\n/** Sets a `group.field` secret in place; a document without that group is left as it is. */\nconst setAtPath = (doc: Record<string, unknown>, path: string, value: string): void => {\n\tconst [group = '', field] = path.split('.')\n\tconst target = doc[group]\n\tif (field !== undefined && isRecord(target)) {\n\t\ttarget[field] = value\n\t}\n}\n\n/** The secrets a document stores, by path; blank ones are left out. */\nconst storedSecrets = (doc: Record<string, unknown>): Array<{ path: string; value: string }> =>\n\tSECRET_PATHS.flatMap(({ path }) => {\n\t\tconst value = valueAt(doc, path)\n\t\treturn typeof value === 'string' && value !== '' ? [{ path, value }] : []\n\t})\n\nconst refOf = (doc: { id: string; version: string }): string => `${doc.id}@${doc.version}`\n\n/** The registry of an install without runtime providers: the config adapters, for every scope. */\nconst staticRegistry = (options: ProviderRegistryOptions): ProviderRegistry => ({\n\tresolve: async () => ({ registry: options.registry, grants: NO_GRANTS }),\n\tepoch: async () => FIXED_CONFIG_EPOCH,\n\tchanged: () => {},\n\trefresh: async () => {},\n\tclose: async () => {},\n})\n\n/**\n * `providers.resolve`: the host's function answers every read, uncached, and the configuration\n * epoch is a token the host bumps through `refreshProviders()` once it changed its own storage.\n */\nconst resolveRegistry = (\n\toptions: ProviderRegistryOptions,\n\tresolve: ProvidersResolve\n): ProviderRegistry => {\n\tconst { tokens } = options\n\treturn {\n\t\tresolve: async ({ payload, req, scope }) => {\n\t\t\tconst adapters = await resolve({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tscope,\n\t\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\t\thosts: options.hosts,\n\t\t\t\tsdks: options.sdks,\n\t\t\t})\n\t\t\tconst combined = combineRegistries(\n\t\t\t\toptions.base,\n\t\t\t\tadapters.map((adapter) => ({ adapter, docId: adapter.id }))\n\t\t\t)\n\t\t\treturn { ...combined, registry: options.narrow(combined.registry) }\n\t\t},\n\t\tepoch: (scope) => tokens?.get(scope) ?? Promise.resolve(FIXED_CONFIG_EPOCH),\n\t\tchanged: () => {},\n\t\trefresh: async (scope) => {\n\t\t\tawait tokens?.bump(scope)\n\t\t},\n\t\tclose: async () => {},\n\t}\n}\n\ninterface CachedRegistry {\n\tepoch: string\n\tresolved: Promise<ScopeRegistry>\n\t/** The enabled documents it was built from, kept in use while it is handed out. */\n\tids: readonly string[]\n\t/** Each as `id@updatedAt`, so disposing a version drops exactly the registries built on it. */\n\trefs: ReadonlySet<string>\n\t/** Set when a document stood in as a failing source: the registry is built again from then on. */\n\tretryAt?: number\n}\n\n/** What one document built: its adapter, or a stand-in when it could not be read. */\ntype Built =\n\t| { ok: true; adapter: AnalyticsAdapter | null }\n\t| { ok: false; standIn: AnalyticsAdapter }\n\n/** What a stand-in declares when the document's settings build nothing even without its secrets. */\nconst STAND_IN_CAPABILITIES: AnalyticsCapabilities = {\n\trealtime: false,\n\tminGranularity: 'day',\n\tmaxLookbackDays: null,\n\tmetrics: new Set(['pageviews', 'visitors']),\n\tdimensions: new Set(),\n\tfilters: {},\n\trateLimit: null,\n\trecommendedTtl: { realtime: 60, aggregate: 60 },\n}\n\n/**\n * Stands in while a document's adapter cannot be built: keeps its identity, and its capabilities\n * where settings build without secrets; reads fail as `source_misconfigured`, capture none.\n */\nconst standInFor = (\n\traw: Record<string, unknown>,\n\tcause: unknown,\n\tbuild: (doc: Record<string, unknown>) => AnalyticsAdapter | null\n): AnalyticsAdapter => {\n\tconst blank = structuredClone(raw)\n\tfor (const { path } of storedSecrets(blank)) {\n\t\tsetAtPath(blank, path, '')\n\t}\n\tlet shape: AnalyticsAdapter | null = null\n\ttry {\n\t\tshape = build(blank)\n\t} catch {\n\t\tshape = null\n\t}\n\tconst id = documentAdapterId(raw.provider, raw.id)\n\treturn failingAdapter(\n\t\t{\n\t\t\tid,\n\t\t\tlabel: shape?.label ?? (typeof raw.name === 'string' && raw.name !== '' ? raw.name : id),\n\t\t\tcapabilities: shape?.capabilities ?? STAND_IN_CAPABILITIES,\n\t\t\trealtime: shape?.realtime,\n\t\t},\n\t\t() =>\n\t\t\tnew SourceMisconfiguredError(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" could not be read; check its settings and keys`,\n\t\t\t\t{ cause }\n\t\t\t)\n\t)\n}\n\n/**\n * A scope's registry is cached under the epoch the probe reads before any document, so it is never\n * filed under an older epoch. Only unseen document versions are read and decrypted.\n */\nconst collectionRegistry = (\n\toptions: ProviderRegistryOptions,\n\tplan: Extract<ProviderPlan, { kind: 'collection' }>\n): ProviderRegistry => {\n\tconst { payload, now } = options\n\tconst { slug } = plan\n\tconst probe = createCollectionProbe({\n\t\tpayload,\n\t\tslug,\n\t\tscopeField: plan.scopeField,\n\t\twhere: (scope) => providerScopeWhere(plan.scopeField, scope),\n\t\tprovider: true,\n\t\t...(now ? { now } : {}),\n\t})\n\tconst registries = new Map<string, CachedRegistry>()\n\tconst pool = createAdapterPool({\n\t\tpayload,\n\t\t...(now ? { now } : {}),\n\t\tonDispose: (doc) => {\n\t\t\tconst ref = refOf(doc)\n\t\t\tfor (const [key, cached] of registries) {\n\t\t\t\tif (cached.refs.has(ref)) {\n\t\t\t\t\tregistries.delete(key)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\tlet warnedGa4 = false\n\tconst clock = now ?? currentTime\n\tconst warnProbeFailed = throttled((message) => payload.logger?.warn(message), {\n\t\tnow: clock,\n\t\tintervalMs: WARN_EVERY_MS,\n\t})\n\t// A failing probe keys on the last epoch read, which the registry in use was built from.\n\tconst fallback = createEpochFallback(clock)\n\tconst types: readonly string[] = plan.types ?? PROVIDER_IDS\n\n\t/** An enabled document of a type the install serves, which its adapter may then make a source. */\n\tconst servable = (row: ProbeRow): boolean => row.enabled && types.includes(row.provider ?? '')\n\n\t/** A probed id as the collection stores it: rows carry every id as text. */\n\tconst idOf = (id: string): string | number => {\n\t\tconst custom = isCollectionSlug(payload, slug)\n\t\t\t? payload.collections[slug]?.customIDType\n\t\t\t: undefined\n\t\treturn (custom ?? payload.db.defaultIDType) === 'number' && /^\\d+$/.test(id) ? Number(id) : id\n\t}\n\n\tconst versions = new WeakMap<AnalyticsAdapter, string>()\n\tconst stamped = (adapter: AnalyticsAdapter | null, version: string): AnalyticsAdapter | null => {\n\t\tif (adapter) {\n\t\t\tversions.set(adapter, version)\n\t\t}\n\t\treturn adapter\n\t}\n\n\tconst fromDocument = (doc: Record<string, unknown>): AnalyticsAdapter | null =>\n\t\t// A row of the providers collection, whose fields `ProviderDoc` mirrors.\n\t\tadapterFromProviderDoc(doc as ProviderDoc, {\n\t\t\t...(plan.nativeAdapter ? { native: plan.nativeAdapter } : {}),\n\t\t\thosts: options.hosts,\n\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\tsdks: options.sdks,\n\t\t\t...options.withoutConsent,\n\t\t})\n\n\t/** A stored document with its secrets decrypted in a copy. */\n\tconst decrypted = async (\n\t\traw: Record<string, unknown>,\n\t\tdecrypt: DecryptFieldValue\n\t): Promise<Record<string, unknown>> => {\n\t\tconst doc = structuredClone(raw)\n\t\tfor (const { path, value } of storedSecrets(doc)) {\n\t\t\tconst plain = await decrypt(payload, { collection: slug, path, value })\n\t\t\tsetAtPath(doc, path, typeof plain === 'string' ? plain : '')\n\t\t}\n\t\treturn doc\n\t}\n\n\tconst adapterOf = async (\n\t\traw: Record<string, unknown>,\n\t\tdecrypt: DecryptFieldValue\n\t): Promise<Built> => {\n\t\ttry {\n\t\t\tconst adapter = fromDocument(await decrypted(raw, decrypt))\n\t\t\t// The first GA4 document is the earliest this install shows it reads GA4 at all.\n\t\t\tif (raw.provider === 'ga4' && !options.sdks.ga4 && !warnedGa4 && isProductionBuild()) {\n\t\t\t\twarnedGa4 = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t\treturn { ok: true, adapter }\n\t\t} catch (err) {\n\t\t\t// A corrupt or key-rotated ciphertext must neither take the scope's registry down nor drop\n\t\t\t// the source silently: it stands in as a failing source until the retry.\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" (${String(raw.provider)}) could not be read, its reads fail until it can: ${String(err)}`\n\t\t\t)\n\t\t\treturn { ok: false, standIn: standInFor(raw, err, fromDocument) }\n\t\t}\n\t}\n\n\t/**\n\t * Reads and builds the documents the pool has no adapter for, answering each by id. A stand-in\n\t * is never pooled, so the document is read again once its registry expires.\n\t */\n\tconst buildDocuments = async (\n\t\tscope: string | null,\n\t\tids: readonly string[]\n\t): Promise<{ built: Map<string, AnalyticsAdapter | null>; failed: boolean }> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered for the providers`)\n\t\t}\n\t\tconst { decryptFieldValue, withRawEncrypted } = await loadEncrypted()\n\t\t// Never the caller's: the raw window is not a concurrency boundary, so a request shared with\n\t\t// other reads would hand them ciphertext, and it may also hold an uncommitted transaction.\n\t\tconst req = await createLocalReq({}, payload)\n\t\tconst { docs } = await withRawEncrypted(req, () =>\n\t\t\tpayload.find({\n\t\t\t\tcollection: slug,\n\t\t\t\twhere: {\n\t\t\t\t\tand: [\n\t\t\t\t\t\t{ id: { in: ids.map(idOf) } },\n\t\t\t\t\t\t{ enabled: { equals: true } },\n\t\t\t\t\t\tproviderScopeWhere(plan.scopeField, scope),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tlimit: ids.length,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t)\n\t\tconst found: unknown[] = docs\n\t\tconst built = new Map<string, AnalyticsAdapter | null>()\n\t\tlet failed = false\n\t\tfor (const raw of found.filter(isRecord)) {\n\t\t\tconst doc: PooledDocument = { id: String(raw.id), version: versionOf(raw.updatedAt), scope }\n\t\t\tconst outcome = await adapterOf(raw, decryptFieldValue)\n\t\t\tif (outcome.ok) {\n\t\t\t\tconst pooled = pool.put(doc, outcome.adapter, raw.provider !== 'native')\n\t\t\t\t// A newer version pooled by an overlapping build keeps the version it was stamped with.\n\t\t\t\tbuilt.set(doc.id, pool.get(doc) === pooled ? stamped(pooled, doc.version) : pooled)\n\t\t\t} else {\n\t\t\t\tbuilt.set(doc.id, stamped(outcome.standIn, doc.version))\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t\treturn { built, failed }\n\t}\n\n\tconst build = async (\n\t\tscope: string | null,\n\t\tdocs: readonly PooledDocument[],\n\t\tflagged: ReadonlySet<string>\n\t): Promise<{ registry: ScopeRegistry; failed: boolean }> => {\n\t\tconst missing = docs.filter((doc) => pool.get(doc) === undefined).map((doc) => doc.id)\n\t\tconst read = missing.length > 0 ? await buildDocuments(scope, missing) : undefined\n\t\tconst extras: ProviderAdapter[] = []\n\t\tfor (const doc of docs) {\n\t\t\tconst adapter = read?.built.has(doc.id) ? read.built.get(doc.id) : pool.get(doc)\n\t\t\t// Lacking what its adapter reads with, a document is no source and grants nothing; a\n\t\t\t// stand-in for one that failed to decrypt still is, configured but failing.\n\t\t\tif (adapter?.isConfigured()) {\n\t\t\t\textras.push({ adapter, docId: doc.id, isDefault: flagged.has(doc.id) })\n\t\t\t}\n\t\t}\n\t\tpool.retain(scope, new Set(docs.map((doc) => doc.id)))\n\t\tconst combined = combineRegistries(options.base, extras)\n\t\tconst narrowed = options.narrow(combined.registry)\n\t\t// Reads reach the narrowed copy (an install without `revenue`), so it carries the version too.\n\t\tfor (const adapter of narrowed.all()) {\n\t\t\tconst version = versions.get(combined.registry.get(adapter.id))\n\t\t\tif (version !== undefined) {\n\t\t\t\tversions.set(adapter, version)\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tregistry: { ...combined, registry: narrowed },\n\t\t\tfailed: read?.failed === true,\n\t\t}\n\t}\n\n\tconst probed = async (scope: string | null): Promise<Probe | undefined> => {\n\t\ttry {\n\t\t\treturn await probe.read(scope)\n\t\t} catch (err) {\n\t\t\twarnProbeFailed(\n\t\t\t\t`analytics: reading the provider documents failed, cached reads key on the last epoch this instance read: ${String(err)}`\n\t\t\t)\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tconst isCurrent = (cached: CachedRegistry, epoch: string): boolean =>\n\t\tcached.epoch === epoch && (cached.retryAt === undefined || clock() < cached.retryAt)\n\n\tconst registryOf = async (scope: string | null): Promise<ScopeRegistry> => {\n\t\tconst key = scope ?? ''\n\t\tconst state = await probe.read(scope)\n\t\tfallback.read(scope, state.epoch)\n\t\tconst cached = registries.get(key)\n\t\tif (cached && isCurrent(cached, state.epoch)) {\n\t\t\tpool.touch(cached.ids)\n\t\t\treturn cached.resolved\n\t\t}\n\t\tconst rows = state.rows.filter(servable)\n\t\tconst docs: PooledDocument[] = rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tversion: row.updatedAt,\n\t\t\tscope,\n\t\t}))\n\t\tconst flagged = new Set(rows.filter((row) => row.isDefault).map((row) => row.id))\n\t\tconst built = build(scope, docs, flagged)\n\t\tconst entry: CachedRegistry = {\n\t\t\tepoch: state.epoch,\n\t\t\tresolved: built.then((done) => done.registry),\n\t\t\tids: docs.map((doc) => doc.id),\n\t\t\trefs: new Set(docs.map(refOf)),\n\t\t}\n\t\tbuilt.then(\n\t\t\t(done) => {\n\t\t\t\tif (done.failed) {\n\t\t\t\t\tentry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\tremember(registries, [key, entry])\n\t\tentry.resolved.catch(() => {\n\t\t\tif (registries.get(key) === entry) {\n\t\t\t\tregistries.delete(key)\n\t\t\t}\n\t\t})\n\t\treturn entry.resolved\n\t}\n\n\treturn {\n\t\tresolve: (args) => registryOf(scopeOf(args.scope)),\n\t\tepoch: async (raw) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst state = await probed(scope)\n\t\t\treturn state ? fallback.read(scope, state.epoch) : fallback.failed(scope)\n\t\t},\n\t\tgranted: async (raw, adapterId) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst native = plan.nativeAdapter\n\t\t\tif (native && native.id === adapterId) {\n\t\t\t\tconst { rows } = await probe.read(scope)\n\t\t\t\treturn (\n\t\t\t\t\tnative.isConfigured() && rows.some((row) => row.provider === 'native' && servable(row))\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn (await registryOf(scope)).grants.has(adapterId)\n\t\t},\n\t\tchanged: (scopes) => probe.expedite(scopes),\n\t\trefresh: async (scope) => probe.expedite([scope]),\n\t\tdocumentAdapter: async (id) => {\n\t\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tconst { decryptFieldValue, withRawEncrypted } = await loadEncrypted()\n\t\t\t// Never the caller's, as in buildDocuments.\n\t\t\tconst req = await createLocalReq({}, payload)\n\t\t\tconst raw: unknown = await withRawEncrypted(req, () =>\n\t\t\t\tpayload.findByID({\n\t\t\t\t\tcollection: slug,\n\t\t\t\t\tid: idOf(id),\n\t\t\t\t\tdepth: 0,\n\t\t\t\t\toverrideAccess: true,\n\t\t\t\t\tdisableErrors: true,\n\t\t\t\t\treq,\n\t\t\t\t})\n\t\t\t)\n\t\t\tif (!isRecord(raw)) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\t// As in adapterOf: a corrupt or key-rotated ciphertext stands in as a failing source, so\n\t\t\t// Test connection says to check the keys rather than answering a server error.\n\t\t\tconst version = versionOf(raw.updatedAt)\n\t\t\ttry {\n\t\t\t\treturn stamped(fromDocument(await decrypted(raw, decryptFieldValue)), version)\n\t\t\t} catch (err) {\n\t\t\t\treturn stamped(standInFor(raw, err, fromDocument), version)\n\t\t\t}\n\t\t},\n\t\tversionOf: (adapter) => versions.get(adapter),\n\t\tclose: () => pool.close(),\n\t}\n}\n\n/** The runtime provider registry of one Payload instance, for the install's plan. */\nexport const createProviderRegistry = (options: ProviderRegistryOptions): ProviderRegistry => {\n\tconst { plan } = options\n\tswitch (plan.kind) {\n\t\tcase 'collection':\n\t\t\treturn collectionRegistry(options, plan)\n\t\tcase 'resolve':\n\t\t\treturn resolveRegistry(options, plan.resolve)\n\t\tdefault:\n\t\t\treturn staticRegistry(options)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,2BAA2B;;AAsExC,MAAM,aAAa,KAA8B,MAAc,UAAwB;CACtF,MAAM,CAAC,QAAQ,IAAI,SAAS,KAAK,MAAM,GAAG;CAC1C,MAAM,SAAS,IAAI;CACnB,IAAI,UAAU,KAAA,KAAa,SAAS,MAAM,GACzC,OAAO,SAAS;AAElB;;AAGA,MAAM,iBAAiB,QACtB,aAAa,SAAS,EAAE,WAAW;CAClC,MAAM,QAAQ,QAAQ,KAAK,IAAI;CAC/B,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,CAAC;EAAE;EAAM;CAAM,CAAC,IAAI,CAAC;AACzE,CAAC;AAEF,MAAM,SAAS,QAAiD,GAAG,IAAI,GAAG,GAAG,IAAI;;AAGjF,MAAM,kBAAkB,aAAwD;CAC/E,SAAS,aAAa;EAAE,UAAU,QAAQ;EAAU,QAAQ;CAAU;CACtE,OAAO,YAAA;CACP,eAAe,CAAC;CAChB,SAAS,YAAY,CAAC;CACtB,OAAO,YAAY,CAAC;AACrB;;;;;AAMA,MAAM,mBACL,SACA,YACsB;CACtB,MAAM,EAAE,WAAW;CACnB,OAAO;EACN,SAAS,OAAO,EAAE,SAAS,KAAK,YAAY;GAC3C,MAAM,WAAW,MAAM,QAAQ;IAC9B;IACA;IACA;IACA,OAAO,QAAQ,SAAS;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;IACP,gBAAgB;IAChB,eAAe;IACf;GACD,CAAC,CACF;GACA,IAAI,CAAC,SAAS,GAAG,GAChB,OAAO;GAIR,MAAM,UAAU,UAAU,IAAI,SAAS;GACvC,IAAI;IACH,OAAO,QAAQ,aAAa,MAAM,UAAU,KAAK,iBAAiB,CAAC,GAAG,OAAO;GAC9E,SAAS,KAAK;IACb,OAAO,QAAQ,WAAW,KAAK,KAAK,YAAY,GAAG,OAAO;GAC3D;EACD;EACA,YAAY,YAAY,SAAS,IAAI,OAAO;EAC5C,aAAa,KAAK,MAAM;CACzB;AACD;;AAGA,MAAa,0BAA0B,YAAuD;CAC7F,MAAM,EAAE,SAAS;CACjB,QAAQ,KAAK,MAAb;EACC,KAAK,cACJ,OAAO,mBAAmB,SAAS,IAAI;EACxC,KAAK,WACJ,OAAO,gBAAgB,SAAS,KAAK,OAAO;EAC7C,SACC,OAAO,eAAe,OAAO;CAC/B;AACD"}
@@ -1,4 +1,5 @@
1
1
  import { isRecord, valueAt } from "../core/values.js";
2
+ import { cloudAppHost } from "../adapters/posthog/cloud.js";
2
3
  import { CONNECTION_PATHS, SECRET_PATHS } from "./secrets.js";
3
4
  //#region src/providers/retarget.ts
4
5
  /** A connection value as compared: blank is no value, and a relationship is its id. */
@@ -22,24 +23,54 @@ const withCleared = (doc, path) => {
22
23
  }
23
24
  } : doc;
24
25
  };
26
+ /** The PostHog fields that decide where its reads, and so its personal key, go. */
27
+ const POSTHOG_READ_PATHS = new Set(["posthog.host", "posthog.region"]);
28
+ /**
29
+ * Where PostHog reads with these settings, as the adapter resolves it: the Host, else the Region's
30
+ * cloud, US when blank. A field the update leaves out keeps its stored value.
31
+ */
32
+ const posthogReadHost = (data, originalDoc) => {
33
+ const at = (path) => {
34
+ const next = valueAt(data, path);
35
+ return comparable(next === void 0 ? valueAt(originalDoc, path) : next);
36
+ };
37
+ const region = at("posthog.region");
38
+ return at("posthog.host")?.replace(/\/+$/, "") ?? cloudAppHost(region === "eu" ? "eu" : "us");
39
+ };
40
+ /** Which providers an update moves: every one on a new `provider` or scope, else those whose host or id changed. */
41
+ const movedBy = (data, originalDoc, scopeField) => {
42
+ const at = (doc, path) => path.endsWith(".host") ? comparable(valueAt(doc, path))?.replace(/\/+$/, "") ?? null : comparable(valueAt(doc, path));
43
+ const moved = (path) => valueAt(data, path) !== void 0 && at(data, path) !== at(originalDoc, path);
44
+ const retargeted = /* @__PURE__ */ new Set();
45
+ for (const { provider, path } of CONNECTION_PATHS) if (provider !== null && !POSTHOG_READ_PATHS.has(path) && moved(path)) retargeted.add(provider);
46
+ if (posthogReadHost(data, originalDoc) !== posthogReadHost(originalDoc, originalDoc)) retargeted.add("posthog");
47
+ return {
48
+ everyProvider: moved("provider") || moved(scopeField),
49
+ retargeted
50
+ };
51
+ };
25
52
  /**
26
53
  * On an update that changes where a document connects, nulls every secret not resent in plaintext:
27
54
  * a changed `provider` or scope reaches all providers, a changed host or id only its own.
28
55
  */
29
56
  const retargetSecrets = (args) => ({ data, operation, originalDoc }) => {
30
57
  if (operation !== "update" || !isRecord(data) || !isRecord(originalDoc)) return data;
31
- const moved = (path) => {
32
- const next = valueAt(data, path);
33
- return next !== void 0 && comparable(next) !== comparable(valueAt(originalDoc, path));
34
- };
35
- const everyProvider = moved("provider") || moved(args.scopeField);
36
- const retargeted = /* @__PURE__ */ new Set();
37
- for (const { provider, path } of CONNECTION_PATHS) if (provider !== null && moved(path)) retargeted.add(provider);
58
+ const { everyProvider, retargeted } = movedBy(data, originalDoc, args.scopeField);
38
59
  let next = data;
39
60
  for (const { provider, path } of SECRET_PATHS) if ((everyProvider || retargeted.has(provider)) && !freshlySent(valueAt(next, path), args.isSealed)) next = withCleared(next, path);
40
61
  return next;
41
62
  };
63
+ /**
64
+ * Whether an update changes how a document connects: where it connects, as {@link retargetSecrets}
65
+ * reads it, or a secret sent anew in plaintext. Its last connection result is about the old setup.
66
+ */
67
+ const reconnects = (args) => {
68
+ if (!isRecord(args.data) || !isRecord(args.originalDoc)) return false;
69
+ const { everyProvider, retargeted } = movedBy(args.data, args.originalDoc, args.scopeField);
70
+ const data = args.data;
71
+ return everyProvider || retargeted.size > 0 || SECRET_PATHS.some(({ path }) => freshlySent(valueAt(data, path), args.isSealed));
72
+ };
42
73
  //#endregion
43
- export { retargetSecrets };
74
+ export { reconnects, retargetSecrets };
44
75
 
45
76
  //# sourceMappingURL=retarget.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"retarget.js","names":[],"sources":["../../src/providers/retarget.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\nimport { isRecord, valueAt } from '../core/values'\nimport type { ProviderId } from './factory'\nimport { CONNECTION_PATHS, SECRET_PATHS } from './secrets'\n\ninterface RetargetArgs {\n\t/** The field a document's scope is stored in, a connection value like the rest. */\n\tscopeField: string\n\t/** The fields plugin's own test for a value it sealed. */\n\tisSealed: (value: unknown) => boolean\n}\n\ntype Doc = Record<string, unknown>\n\n/** A connection value as compared: blank is no value, and a relationship is its id. */\nconst comparable = (value: unknown): string | null => {\n\tif (isRecord(value)) {\n\t\treturn comparable(value.id ?? value.value)\n\t}\n\tif (typeof value === 'string') {\n\t\treturn value.trim() === '' ? null : value.trim()\n\t}\n\treturn typeof value === 'number' ? String(value) : null\n}\n\n/** A secret the request sent itself, in plaintext: the only kind a retarget keeps. */\nconst freshlySent = (value: unknown, isSealed: RetargetArgs['isSealed']): boolean =>\n\ttypeof value === 'string' && value !== '' && !isSealed(value)\n\n/** `doc` with one secret set to null; a doc whose group is missing is left as it is. */\nconst withCleared = (doc: Doc, path: string): Doc => {\n\tconst [group, field] = path.split('.')\n\tif (group === undefined || field === undefined) {\n\t\treturn doc\n\t}\n\tconst current = doc[group]\n\treturn isRecord(current) ? { ...doc, [group]: { ...current, [field]: null } } : doc\n}\n\n/**\n * On an update that changes where a document connects, nulls every secret not resent in plaintext:\n * a changed `provider` or scope reaches all providers, a changed host or id only its own.\n */\nexport const retargetSecrets =\n\t(args: RetargetArgs): CollectionBeforeChangeHook =>\n\t({ data, operation, originalDoc }) => {\n\t\tif (operation !== 'update' || !isRecord(data) || !isRecord(originalDoc)) {\n\t\t\treturn data\n\t\t}\n\t\tconst moved = (path: string): boolean => {\n\t\t\tconst next = valueAt(data, path)\n\t\t\treturn next !== undefined && comparable(next) !== comparable(valueAt(originalDoc, path))\n\t\t}\n\t\tconst everyProvider = moved('provider') || moved(args.scopeField)\n\t\tconst retargeted = new Set<ProviderId>()\n\t\tfor (const { provider, path } of CONNECTION_PATHS) {\n\t\t\tif (provider !== null && moved(path)) {\n\t\t\t\tretargeted.add(provider)\n\t\t\t}\n\t\t}\n\t\tlet next: Doc = data\n\t\tfor (const { provider, path } of SECRET_PATHS) {\n\t\t\tconst reached = everyProvider || retargeted.has(provider)\n\t\t\tif (reached && !freshlySent(valueAt(next, path), args.isSealed)) {\n\t\t\t\tnext = withCleared(next, path)\n\t\t\t}\n\t\t}\n\t\treturn next\n\t}\n"],"mappings":";;;;AAeA,MAAM,cAAc,UAAkC;CACrD,IAAI,SAAS,KAAK,GACjB,OAAO,WAAW,MAAM,MAAM,MAAM,KAAK;CAE1C,IAAI,OAAO,UAAU,UACpB,OAAO,MAAM,KAAK,MAAM,KAAK,OAAO,MAAM,KAAK;CAEhD,OAAO,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;AACpD;;AAGA,MAAM,eAAe,OAAgB,aACpC,OAAO,UAAU,YAAY,UAAU,MAAM,CAAC,SAAS,KAAK;;AAG7D,MAAM,eAAe,KAAU,SAAsB;CACpD,MAAM,CAAC,OAAO,SAAS,KAAK,MAAM,GAAG;CACrC,IAAI,UAAU,KAAA,KAAa,UAAU,KAAA,GACpC,OAAO;CAER,MAAM,UAAU,IAAI;CACpB,OAAO,SAAS,OAAO,IAAI;EAAE,GAAG;GAAM,QAAQ;GAAE,GAAG;IAAU,QAAQ;EAAK;CAAE,IAAI;AACjF;;;;;AAMA,MAAa,mBACX,UACA,EAAE,MAAM,WAAW,kBAAkB;CACrC,IAAI,cAAc,YAAY,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,WAAW,GACrE,OAAO;CAER,MAAM,SAAS,SAA0B;EACxC,MAAM,OAAO,QAAQ,MAAM,IAAI;EAC/B,OAAO,SAAS,KAAA,KAAa,WAAW,IAAI,MAAM,WAAW,QAAQ,aAAa,IAAI,CAAC;CACxF;CACA,MAAM,gBAAgB,MAAM,UAAU,KAAK,MAAM,KAAK,UAAU;CAChE,MAAM,6BAAa,IAAI,IAAgB;CACvC,KAAK,MAAM,EAAE,UAAU,UAAU,kBAChC,IAAI,aAAa,QAAQ,MAAM,IAAI,GAClC,WAAW,IAAI,QAAQ;CAGzB,IAAI,OAAY;CAChB,KAAK,MAAM,EAAE,UAAU,UAAU,cAEhC,KADgB,iBAAiB,WAAW,IAAI,QAAQ,MACzC,CAAC,YAAY,QAAQ,MAAM,IAAI,GAAG,KAAK,QAAQ,GAC7D,OAAO,YAAY,MAAM,IAAI;CAG/B,OAAO;AACR"}
1
+ {"version":3,"file":"retarget.js","names":[],"sources":["../../src/providers/retarget.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook } from 'payload'\nimport { cloudAppHost } from '../adapters/posthog/cloud'\nimport { isRecord, valueAt } from '../core/values'\nimport type { ProviderId } from './ids'\nimport { CONNECTION_PATHS, SECRET_PATHS } from './secrets'\n\ninterface RetargetArgs {\n\t/** The field a document's scope is stored in, a connection value like the rest. */\n\tscopeField: string\n\t/** The fields plugin's own test for a value it sealed. */\n\tisSealed: (value: unknown) => boolean\n}\n\ntype Doc = Record<string, unknown>\n\n/** A connection value as compared: blank is no value, and a relationship is its id. */\nconst comparable = (value: unknown): string | null => {\n\tif (isRecord(value)) {\n\t\treturn comparable(value.id ?? value.value)\n\t}\n\tif (typeof value === 'string') {\n\t\treturn value.trim() === '' ? null : value.trim()\n\t}\n\treturn typeof value === 'number' ? String(value) : null\n}\n\n/** A secret the request sent itself, in plaintext: the only kind a retarget keeps. */\nconst freshlySent = (value: unknown, isSealed: RetargetArgs['isSealed']): boolean =>\n\ttypeof value === 'string' && value !== '' && !isSealed(value)\n\n/** `doc` with one secret set to null; a doc whose group is missing is left as it is. */\nconst withCleared = (doc: Doc, path: string): Doc => {\n\tconst [group, field] = path.split('.')\n\tif (group === undefined || field === undefined) {\n\t\treturn doc\n\t}\n\tconst current = doc[group]\n\treturn isRecord(current) ? { ...doc, [group]: { ...current, [field]: null } } : doc\n}\n\n/** The PostHog fields that decide where its reads, and so its personal key, go. */\nconst POSTHOG_READ_PATHS = new Set(['posthog.host', 'posthog.region'])\n\n/**\n * Where PostHog reads with these settings, as the adapter resolves it: the Host, else the Region's\n * cloud, US when blank. A field the update leaves out keeps its stored value.\n */\nconst posthogReadHost = (data: Doc, originalDoc: Doc): string => {\n\tconst at = (path: string): string | null => {\n\t\tconst next = valueAt(data, path)\n\t\treturn comparable(next === undefined ? valueAt(originalDoc, path) : next)\n\t}\n\tconst region = at('posthog.region')\n\treturn at('posthog.host')?.replace(/\\/+$/, '') ?? cloudAppHost(region === 'eu' ? 'eu' : 'us')\n}\n\n/** Which providers an update moves: every one on a new `provider` or scope, else those whose host or id changed. */\nconst movedBy = (\n\tdata: Doc,\n\toriginalDoc: Doc,\n\tscopeField: string\n): { everyProvider: boolean; retargeted: ReadonlySet<ProviderId> } => {\n\t// A host with and without a trailing slash is the same address.\n\tconst at = (doc: Doc, path: string): string | null =>\n\t\tpath.endsWith('.host')\n\t\t\t? (comparable(valueAt(doc, path))?.replace(/\\/+$/, '') ?? null)\n\t\t\t: comparable(valueAt(doc, path))\n\tconst moved = (path: string): boolean =>\n\t\tvalueAt(data, path) !== undefined && at(data, path) !== at(originalDoc, path)\n\tconst retargeted = new Set<ProviderId>()\n\tfor (const { provider, path } of CONNECTION_PATHS) {\n\t\tif (provider !== null && !POSTHOG_READ_PATHS.has(path) && moved(path)) {\n\t\t\tretargeted.add(provider)\n\t\t}\n\t}\n\tif (posthogReadHost(data, originalDoc) !== posthogReadHost(originalDoc, originalDoc)) {\n\t\tretargeted.add('posthog')\n\t}\n\treturn { everyProvider: moved('provider') || moved(scopeField), retargeted }\n}\n\n/**\n * On an update that changes where a document connects, nulls every secret not resent in plaintext:\n * a changed `provider` or scope reaches all providers, a changed host or id only its own.\n */\nexport const retargetSecrets =\n\t(args: RetargetArgs): CollectionBeforeChangeHook =>\n\t({ data, operation, originalDoc }) => {\n\t\tif (operation !== 'update' || !isRecord(data) || !isRecord(originalDoc)) {\n\t\t\treturn data\n\t\t}\n\t\tconst { everyProvider, retargeted } = movedBy(data, originalDoc, args.scopeField)\n\t\tlet next: Doc = data\n\t\tfor (const { provider, path } of SECRET_PATHS) {\n\t\t\tconst reached = everyProvider || retargeted.has(provider)\n\t\t\tif (reached && !freshlySent(valueAt(next, path), args.isSealed)) {\n\t\t\t\tnext = withCleared(next, path)\n\t\t\t}\n\t\t}\n\t\treturn next\n\t}\n\n/**\n * Whether an update changes how a document connects: where it connects, as {@link retargetSecrets}\n * reads it, or a secret sent anew in plaintext. Its last connection result is about the old setup.\n */\nexport const reconnects = (\n\targs: RetargetArgs & { data: unknown; originalDoc: unknown }\n): boolean => {\n\tif (!isRecord(args.data) || !isRecord(args.originalDoc)) {\n\t\treturn false\n\t}\n\tconst { everyProvider, retargeted } = movedBy(args.data, args.originalDoc, args.scopeField)\n\tconst data = args.data\n\treturn (\n\t\teveryProvider ||\n\t\tretargeted.size > 0 ||\n\t\tSECRET_PATHS.some(({ path }) => freshlySent(valueAt(data, path), args.isSealed))\n\t)\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc,UAAkC;CACrD,IAAI,SAAS,KAAK,GACjB,OAAO,WAAW,MAAM,MAAM,MAAM,KAAK;CAE1C,IAAI,OAAO,UAAU,UACpB,OAAO,MAAM,KAAK,MAAM,KAAK,OAAO,MAAM,KAAK;CAEhD,OAAO,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;AACpD;;AAGA,MAAM,eAAe,OAAgB,aACpC,OAAO,UAAU,YAAY,UAAU,MAAM,CAAC,SAAS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U;EAAG;CAAW;AAC5E;;;;;AAMA,MAAa,mBACX,UACA,EAAE,MAAM,WAAW,kBAAkB;CACrC,IAAI,cAAc,YAAY,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,WAAW,GACrE,OAAO;CAER,MAAM,EAAE,eAAe,eAAe,QAAQ,MAAM,aAAa,KAAK,UAAU;CAChF,IAAI,OAAY;CAChB,KAAK,MAAM,EAAE,UAAU,UAAU,cAEhC,KADgB,iBAAiB,WAAW,IAAI,QAAQ,MACzC,CAAC,YAAY,QAAQ,MAAM,IAAI,GAAG,KAAK,QAAQ,GAC7D,OAAO,YAAY,MAAM,IAAI;CAG/B,OAAO;AACR;;;;;AAMD,MAAa,cACZ,SACa;CACb,IAAI,CAAC,SAAS,KAAK,IAAI,KAAK,CAAC,SAAS,KAAK,WAAW,GACrD,OAAO;CAER,MAAM,EAAE,eAAe,eAAe,QAAQ,KAAK,MAAM,KAAK,aAAa,KAAK,UAAU;CAC1F,MAAM,OAAO,KAAK;CAClB,OACC,iBACA,WAAW,OAAO,KAClB,aAAa,MAAM,EAAE,WAAW,YAAY,QAAQ,MAAM,IAAI,GAAG,KAAK,QAAQ,CAAC;AAEjF"}
@@ -1,4 +1,4 @@
1
- import { ProviderId } from "./factory.js";
1
+ import { ProviderId } from "./ids.js";
2
2
 
3
3
  //#region src/providers/secrets.d.ts
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"secrets.js","names":[],"sources":["../../src/providers/secrets.ts"],"sourcesContent":["import type { ProviderId } from './factory'\n\n/**\n * Every credential path in the providers collection; `collection.test.ts` holds it to the\n * collection's secret fields.\n *\n * @beta\n */\nexport const SECRET_PATHS: ReadonlyArray<{ provider: ProviderId; path: string }> = [\n\t{ provider: 'plausible', path: 'plausible.apiKey' },\n\t{ provider: 'umami', path: 'umami.apiKey' },\n\t{ provider: 'umami', path: 'umami.token' },\n\t{ provider: 'ga4', path: 'ga4.privateKey' },\n\t{ provider: 'posthog', path: 'posthog.apiKey' },\n]\n\n/**\n * Values that decide where a document's credentials go: changing one clears its stored secrets\n * unless they are sent again. `provider: null` marks the one every provider shares.\n *\n * @beta\n */\nexport const CONNECTION_PATHS: ReadonlyArray<{ provider: ProviderId | null; path: string }> = [\n\t{ provider: null, path: 'provider' },\n\t{ provider: 'plausible', path: 'plausible.host' },\n\t{ provider: 'plausible', path: 'plausible.siteId' },\n\t{ provider: 'umami', path: 'umami.host' },\n\t{ provider: 'umami', path: 'umami.websiteId' },\n\t{ provider: 'ga4', path: 'ga4.propertyId' },\n\t{ provider: 'ga4', path: 'ga4.projectId' },\n\t{ provider: 'ga4', path: 'ga4.clientEmail' },\n\t{ provider: 'posthog', path: 'posthog.host' },\n\t{ provider: 'posthog', path: 'posthog.region' },\n\t{ provider: 'posthog', path: 'posthog.projectId' },\n\t{ provider: 'posthog', path: 'posthog.scopeProperty' },\n]\n"],"mappings":";;;;;;;AAQA,MAAa,eAAsE;CAClF;EAAE,UAAU;EAAa,MAAM;CAAmB;CAClD;EAAE,UAAU;EAAS,MAAM;CAAe;CAC1C;EAAE,UAAU;EAAS,MAAM;CAAc;CACzC;EAAE,UAAU;EAAO,MAAM;CAAiB;CAC1C;EAAE,UAAU;EAAW,MAAM;CAAiB;AAC/C;;;;;;;AAQA,MAAa,mBAAiF;CAC7F;EAAE,UAAU;EAAM,MAAM;CAAW;CACnC;EAAE,UAAU;EAAa,MAAM;CAAiB;CAChD;EAAE,UAAU;EAAa,MAAM;CAAmB;CAClD;EAAE,UAAU;EAAS,MAAM;CAAa;CACxC;EAAE,UAAU;EAAS,MAAM;CAAkB;CAC7C;EAAE,UAAU;EAAO,MAAM;CAAiB;CAC1C;EAAE,UAAU;EAAO,MAAM;CAAgB;CACzC;EAAE,UAAU;EAAO,MAAM;CAAkB;CAC3C;EAAE,UAAU;EAAW,MAAM;CAAe;CAC5C;EAAE,UAAU;EAAW,MAAM;CAAiB;CAC9C;EAAE,UAAU;EAAW,MAAM;CAAoB;CACjD;EAAE,UAAU;EAAW,MAAM;CAAwB;AACtD"}
1
+ {"version":3,"file":"secrets.js","names":[],"sources":["../../src/providers/secrets.ts"],"sourcesContent":["import type { ProviderId } from './ids'\n\n/**\n * Every credential path in the providers collection; `collection.test.ts` holds it to the\n * collection's secret fields.\n *\n * @beta\n */\nexport const SECRET_PATHS: ReadonlyArray<{ provider: ProviderId; path: string }> = [\n\t{ provider: 'plausible', path: 'plausible.apiKey' },\n\t{ provider: 'umami', path: 'umami.apiKey' },\n\t{ provider: 'umami', path: 'umami.token' },\n\t{ provider: 'ga4', path: 'ga4.privateKey' },\n\t{ provider: 'posthog', path: 'posthog.apiKey' },\n]\n\n/**\n * Values that decide where a document's credentials go: changing one clears its stored secrets\n * unless they are sent again. `provider: null` marks the one every provider shares.\n *\n * @beta\n */\nexport const CONNECTION_PATHS: ReadonlyArray<{ provider: ProviderId | null; path: string }> = [\n\t{ provider: null, path: 'provider' },\n\t{ provider: 'plausible', path: 'plausible.host' },\n\t{ provider: 'plausible', path: 'plausible.siteId' },\n\t{ provider: 'umami', path: 'umami.host' },\n\t{ provider: 'umami', path: 'umami.websiteId' },\n\t{ provider: 'ga4', path: 'ga4.propertyId' },\n\t{ provider: 'ga4', path: 'ga4.projectId' },\n\t{ provider: 'ga4', path: 'ga4.clientEmail' },\n\t{ provider: 'posthog', path: 'posthog.host' },\n\t{ provider: 'posthog', path: 'posthog.region' },\n\t{ provider: 'posthog', path: 'posthog.projectId' },\n\t{ provider: 'posthog', path: 'posthog.scopeProperty' },\n]\n"],"mappings":";;;;;;;AAQA,MAAa,eAAsE;CAClF;EAAE,UAAU;EAAa,MAAM;CAAmB;CAClD;EAAE,UAAU;EAAS,MAAM;CAAe;CAC1C;EAAE,UAAU;EAAS,MAAM;CAAc;CACzC;EAAE,UAAU;EAAO,MAAM;CAAiB;CAC1C;EAAE,UAAU;EAAW,MAAM;CAAiB;AAC/C;;;;;;;AAQA,MAAa,mBAAiF;CAC7F;EAAE,UAAU;EAAM,MAAM;CAAW;CACnC;EAAE,UAAU;EAAa,MAAM;CAAiB;CAChD;EAAE,UAAU;EAAa,MAAM;CAAmB;CAClD;EAAE,UAAU;EAAS,MAAM;CAAa;CACxC;EAAE,UAAU;EAAS,MAAM;CAAkB;CAC7C;EAAE,UAAU;EAAO,MAAM;CAAiB;CAC1C;EAAE,UAAU;EAAO,MAAM;CAAgB;CACzC;EAAE,UAAU;EAAO,MAAM;CAAkB;CAC3C;EAAE,UAAU;EAAW,MAAM;CAAe;CAC5C;EAAE,UAAU;EAAW,MAAM;CAAiB;CAC9C;EAAE,UAAU;EAAW,MAAM;CAAoB;CACjD;EAAE,UAAU;EAAW,MAAM;CAAwB;AACtD"}
@@ -0,0 +1 @@
1
+ import { Payload } from "payload";
@@ -0,0 +1,181 @@
1
+ import { isRecord } from "../core/values.js";
2
+ import { isUnknownSite } from "../core/sourceErrors.js";
3
+ import { currentDate } from "../core/clock.js";
4
+ import { connectionFailureReasonOf, connectionStateOf } from "./connectionState.js";
5
+ import { vendorAnswerOf } from "../surfacing/classifyError.js";
6
+ //#region src/providers/status.ts
7
+ /**
8
+ * How long the rows a scope's reads look up (`readMany`) are answered from this instance's memory;
9
+ * its own writes and forgets clear them at once, another instance's show this much later.
10
+ */
11
+ const STATUS_MEMO_MS = 5e3;
12
+ /** The `payload.kv` key of one provider document's last connection result. */
13
+ const providerStatusKey = (docId) => `analytics:provider-status:${docId}`;
14
+ /**
15
+ * What a read that reached the source says about the connection; undefined for a read refused as
16
+ * asked or held back by the plugin's own limits, which says nothing about it. A refused host keeps
17
+ * no detail, which can name the address it resolved to; only the vendor's own answer is kept as
18
+ * detail (`vendorAnswerOf`).
19
+ */
20
+ const connectionOutcomeOf = (outcome, health) => {
21
+ if (outcome.ok) return { ok: true };
22
+ const { failure, error } = outcome;
23
+ if (failure.kind === "invalid_param" || failure.kind === "rate_limited") return;
24
+ const vendorAnswer = failure.hostRefused ? void 0 : vendorAnswerOf(error);
25
+ return {
26
+ ok: false,
27
+ kind: failure.kind,
28
+ ...isUnknownSite(error) ? { reason: "unknownSite" } : {},
29
+ ...vendorAnswer === void 0 ? {} : { detail: vendorAnswer },
30
+ ...health.retryAfterMs ? { pausedForMs: health.retryAfterMs } : {}
31
+ };
32
+ };
33
+ /** A vendor's message is a sentence or two; a longer one is an HTML page or a stack. */
34
+ const DETAIL_MAX = 300;
35
+ const READ_FAILURE_KINDS = [
36
+ "invalid_param",
37
+ "source_misconfigured",
38
+ "unavailable",
39
+ "rate_limited"
40
+ ];
41
+ const isoOf = (value) => {
42
+ if (value instanceof Date) return value.toISOString();
43
+ return typeof value === "string" && value !== "" ? value : void 0;
44
+ };
45
+ const statusOf = (row) => {
46
+ const lastSuccessAt = isoOf(row.lastSuccessAt);
47
+ const lastErrorAt = isoOf(row.lastErrorAt);
48
+ const pausedUntil = isoOf(row.pausedUntil);
49
+ const errorKind = READ_FAILURE_KINDS.find((kind) => kind === row.errorKind);
50
+ const errorReason = connectionFailureReasonOf(row.errorReason);
51
+ const errorDetail = typeof row.errorDetail === "string" ? row.errorDetail : void 0;
52
+ return {
53
+ ...lastSuccessAt ? { lastSuccessAt } : {},
54
+ ...lastErrorAt ? { lastErrorAt } : {},
55
+ ...errorKind ? { errorKind } : {},
56
+ ...errorReason ? { errorReason } : {},
57
+ ...errorDetail ? { errorDetail } : {},
58
+ ...pausedUntil ? { pausedUntil } : {}
59
+ };
60
+ };
61
+ /**
62
+ * Each provider document's last connection result in `payload.kv`, outside any transaction. Each
63
+ * document's writes run one after another, so a late success never lands over the failure that
64
+ * followed it.
65
+ */
66
+ const providerStatusStore = (payload, options = {}) => {
67
+ const now = options.now ?? currentDate;
68
+ const successWrittenAt = /* @__PURE__ */ new Map();
69
+ const queues = /* @__PURE__ */ new Map();
70
+ const memo = /* @__PURE__ */ new Map();
71
+ const rowOf = async (id) => {
72
+ const row = await payload.kv.get(providerStatusKey(id));
73
+ return isRecord(row) ? row : void 0;
74
+ };
75
+ /**
76
+ * A row this instance reads, which another instance may have written: none when it is about
77
+ * another saved version, and one that no longer says the source works lets this instance's next
78
+ * success through its throttle.
79
+ */
80
+ const seen = (id, row, version) => {
81
+ const about = typeof row?.version === "string" ? row.version : void 0;
82
+ const status = row && (version === void 0 || about === void 0 || about === version) ? statusOf(row) : void 0;
83
+ if (!status || connectionStateOf(status) !== "works") successWrittenAt.delete(id);
84
+ return status;
85
+ };
86
+ /** Merges `data` over the stored row, so a success keeps the last failure beside it. */
87
+ const put = async (id, data) => {
88
+ await payload.kv.set(providerStatusKey(id), {
89
+ ...await rowOf(id),
90
+ ...data
91
+ });
92
+ };
93
+ /** Runs `work` after the document's writes already queued, so a late one never lands over it. */
94
+ const enqueue = (docId, work) => {
95
+ const queued = (queues.get(docId) ?? Promise.resolve()).then(work);
96
+ const settled = queued.catch(() => {});
97
+ queues.set(docId, settled);
98
+ settled.then(() => {
99
+ if (queues.get(docId) === settled) queues.delete(docId);
100
+ });
101
+ return queued;
102
+ };
103
+ const dataOf = (outcome, at) => outcome.ok ? {
104
+ lastSuccessAt: at.toISOString(),
105
+ pausedUntil: null
106
+ } : {
107
+ lastErrorAt: at.toISOString(),
108
+ errorKind: outcome.kind,
109
+ errorReason: outcome.reason ?? null,
110
+ errorDetail: outcome.detail ? outcome.detail.slice(0, DETAIL_MAX) : null,
111
+ pausedUntil: outcome.pausedForMs && outcome.pausedForMs > 0 ? new Date(at.getTime() + outcome.pausedForMs).toISOString() : null
112
+ };
113
+ return {
114
+ record(docId, outcome, { throttle = false, version } = {}) {
115
+ const at = now();
116
+ if (outcome.ok) {
117
+ const written = successWrittenAt.get(docId);
118
+ if (throttle && written !== void 0 && at.getTime() - written < 9e5) return Promise.resolve();
119
+ successWrittenAt.set(docId, at.getTime());
120
+ } else successWrittenAt.delete(docId);
121
+ const data = {
122
+ ...dataOf(outcome, at),
123
+ version: version ?? null
124
+ };
125
+ return enqueue(docId, async () => {
126
+ await put(docId, data);
127
+ memo.delete(docId);
128
+ }).catch((err) => {
129
+ successWrittenAt.delete(docId);
130
+ throw err;
131
+ });
132
+ },
133
+ async readMany(docIds, versionOf) {
134
+ const entries = await Promise.all(docIds.map(async (id) => {
135
+ const at = now().getTime();
136
+ let held = memo.get(id);
137
+ if (!held || held.until <= at) {
138
+ const reading = {
139
+ row: rowOf(id),
140
+ until: at + STATUS_MEMO_MS
141
+ };
142
+ reading.row.catch(() => memo.get(id) === reading && memo.delete(id));
143
+ memo.set(id, reading);
144
+ held = reading;
145
+ }
146
+ const status = seen(id, await held.row, versionOf?.(id));
147
+ return status ? [id, status] : void 0;
148
+ }));
149
+ return new Map(entries.filter((entry) => entry !== void 0));
150
+ },
151
+ forget(docId) {
152
+ successWrittenAt.delete(docId);
153
+ return enqueue(docId, async () => {
154
+ await payload.kv.delete(providerStatusKey(docId));
155
+ memo.delete(docId);
156
+ });
157
+ },
158
+ carry(docId, from, to) {
159
+ return enqueue(docId, async () => {
160
+ const row = await rowOf(docId);
161
+ if (row?.version === from) {
162
+ await payload.kv.set(providerStatusKey(docId), {
163
+ ...row,
164
+ version: to
165
+ });
166
+ memo.delete(docId);
167
+ }
168
+ });
169
+ },
170
+ async idle() {
171
+ await Promise.all(queues.values());
172
+ },
173
+ async read(docId, version) {
174
+ return seen(docId, await rowOf(docId), version);
175
+ }
176
+ };
177
+ };
178
+ //#endregion
179
+ export { connectionOutcomeOf, providerStatusStore };
180
+
181
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.js","names":[],"sources":["../../src/providers/status.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { currentDate } from '../core/clock'\nimport { isUnknownSite } from '../core/sourceErrors'\nimport { isRecord } from '../core/values'\nimport { type ReadFailureKind, vendorAnswerOf } from '../surfacing/classifyError'\nimport type { LaneHealth, LaneOutcome } from '../surfacing/lanes'\nimport {\n\ttype ConnectionOutcome,\n\tconnectionFailureReasonOf,\n\tconnectionStateOf,\n\ttype ProviderStatus,\n} from './connectionState'\n\n/**\n * How long the rows a scope's reads look up (`readMany`) are answered from this instance's memory;\n * its own writes and forgets clear them at once, another instance's show this much later.\n */\nexport const STATUS_MEMO_MS = 5_000\n\n/** How long a read's success goes unwritten after the last one was, unless a failure came between. */\nexport const STATUS_SUCCESS_EVERY_MS = 15 * 60_000\n\n/** The `payload.kv` key of one provider document's last connection result. */\nexport const providerStatusKey = (docId: string): string => `analytics:provider-status:${docId}`\n\n/**\n * What a read that reached the source says about the connection; undefined for a read refused as\n * asked or held back by the plugin's own limits, which says nothing about it. A refused host keeps\n * no detail, which can name the address it resolved to; only the vendor's own answer is kept as\n * detail (`vendorAnswerOf`).\n */\nexport const connectionOutcomeOf = (\n\toutcome: LaneOutcome,\n\thealth: LaneHealth\n): ConnectionOutcome | undefined => {\n\tif (outcome.ok) {\n\t\treturn { ok: true }\n\t}\n\tconst { failure, error } = outcome\n\tif (failure.kind === 'invalid_param' || failure.kind === 'rate_limited') {\n\t\treturn undefined\n\t}\n\tconst vendorAnswer = failure.hostRefused ? undefined : vendorAnswerOf(error)\n\treturn {\n\t\tok: false,\n\t\tkind: failure.kind,\n\t\t...(isUnknownSite(error) ? { reason: 'unknownSite' } : {}),\n\t\t...(vendorAnswer === undefined ? {} : { detail: vendorAnswer }),\n\t\t...(health.retryAfterMs ? { pausedForMs: health.retryAfterMs } : {}),\n\t}\n}\n\n/** A vendor's message is a sentence or two; a longer one is an HTML page or a stack. */\nconst DETAIL_MAX = 300\n\nconst READ_FAILURE_KINDS: readonly ReadFailureKind[] = [\n\t'invalid_param',\n\t'source_misconfigured',\n\t'unavailable',\n\t'rate_limited',\n]\n\nconst isoOf = (value: unknown): string | undefined => {\n\tif (value instanceof Date) {\n\t\treturn value.toISOString()\n\t}\n\treturn typeof value === 'string' && value !== '' ? value : undefined\n}\n\nconst statusOf = (row: Record<string, unknown>): ProviderStatus => {\n\tconst lastSuccessAt = isoOf(row.lastSuccessAt)\n\tconst lastErrorAt = isoOf(row.lastErrorAt)\n\tconst pausedUntil = isoOf(row.pausedUntil)\n\tconst errorKind = READ_FAILURE_KINDS.find((kind) => kind === row.errorKind)\n\tconst errorReason = connectionFailureReasonOf(row.errorReason)\n\tconst errorDetail = typeof row.errorDetail === 'string' ? row.errorDetail : undefined\n\treturn {\n\t\t...(lastSuccessAt ? { lastSuccessAt } : {}),\n\t\t...(lastErrorAt ? { lastErrorAt } : {}),\n\t\t...(errorKind ? { errorKind } : {}),\n\t\t...(errorReason ? { errorReason } : {}),\n\t\t...(errorDetail ? { errorDetail } : {}),\n\t\t...(pausedUntil ? { pausedUntil } : {}),\n\t}\n}\n\nexport interface ProviderStatusStore {\n\t/**\n\t * Writes what a read or a check told. `throttle` skips a success written less than\n\t * {@link STATUS_SUCCESS_EVERY_MS} ago with no failure since, so reads cost no write each.\n\t * `version` is the saved version of the document the outcome is about.\n\t */\n\trecord(\n\t\tdocId: string,\n\t\toutcome: ConnectionOutcome,\n\t\toptions?: { throttle?: boolean; version?: string }\n\t): Promise<void>\n\t/**\n\t * The document's row; none when it is about another saved version than `version`, which a read\n\t * of the settings before a save can write after the save.\n\t */\n\tread(docId: string, version?: string): Promise<ProviderStatus | undefined>\n\t/** The rows of `docIds` that exist and are about the version `versionOf` names, keyed by id. */\n\treadMany(\n\t\tdocIds: readonly string[],\n\t\tversionOf?: (docId: string) => string | undefined\n\t): Promise<Map<string, ProviderStatus>>\n\t/**\n\t * Deletes a document's row, outside any transaction, after its writes already queued: on its\n\t * delete, and on a save that changes how it connects, whose last result was about the old setup.\n\t */\n\tforget(docId: string): Promise<void>\n\t/**\n\t * Moves a row about the saved version `from` to `to`, after its writes already queued: a save\n\t * that leaves how the document connects as it was keeps its last result.\n\t */\n\tcarry(docId: string, from: string, to: string): Promise<void>\n\t/** Waits for every write already queued, for a runtime that closes or a test that settles. */\n\tidle(): Promise<void>\n}\n\n/**\n * Each provider document's last connection result in `payload.kv`, outside any transaction. Each\n * document's writes run one after another, so a late success never lands over the failure that\n * followed it.\n */\nexport const providerStatusStore = (\n\tpayload: Payload,\n\toptions: { now?: () => Date } = {}\n): ProviderStatusStore => {\n\tconst now = options.now ?? currentDate\n\tconst successWrittenAt = new Map<string, number>()\n\tconst queues = new Map<string, Promise<void>>()\n\tconst memo = new Map<\n\t\tstring,\n\t\t{ row: Promise<Record<string, unknown> | undefined>; until: number }\n\t>()\n\n\tconst rowOf = async (id: string): Promise<Record<string, unknown> | undefined> => {\n\t\tconst row: unknown = await payload.kv.get(providerStatusKey(id))\n\t\treturn isRecord(row) ? row : undefined\n\t}\n\n\t/**\n\t * A row this instance reads, which another instance may have written: none when it is about\n\t * another saved version, and one that no longer says the source works lets this instance's next\n\t * success through its throttle.\n\t */\n\tconst seen = (\n\t\tid: string,\n\t\trow: Record<string, unknown> | undefined,\n\t\tversion: string | undefined\n\t): ProviderStatus | undefined => {\n\t\tconst about = typeof row?.version === 'string' ? row.version : undefined\n\t\tconst current = version === undefined || about === undefined || about === version\n\t\tconst status = row && current ? statusOf(row) : undefined\n\t\tif (!status || connectionStateOf(status) !== 'works') {\n\t\t\tsuccessWrittenAt.delete(id)\n\t\t}\n\t\treturn status\n\t}\n\n\t/** Merges `data` over the stored row, so a success keeps the last failure beside it. */\n\tconst put = async (id: string, data: Record<string, unknown>): Promise<void> => {\n\t\tawait payload.kv.set(providerStatusKey(id), { ...(await rowOf(id)), ...data })\n\t}\n\n\t/** Runs `work` after the document's writes already queued, so a late one never lands over it. */\n\tconst enqueue = (docId: string, work: () => Promise<void>): Promise<void> => {\n\t\tconst queued = (queues.get(docId) ?? Promise.resolve()).then(work)\n\t\tconst settled = queued.catch(() => {})\n\t\tqueues.set(docId, settled)\n\t\tvoid settled.then(() => {\n\t\t\tif (queues.get(docId) === settled) {\n\t\t\t\tqueues.delete(docId)\n\t\t\t}\n\t\t})\n\t\treturn queued\n\t}\n\n\tconst dataOf = (outcome: ConnectionOutcome, at: Date): Record<string, unknown> =>\n\t\toutcome.ok\n\t\t\t? { lastSuccessAt: at.toISOString(), pausedUntil: null }\n\t\t\t: {\n\t\t\t\t\tlastErrorAt: at.toISOString(),\n\t\t\t\t\terrorKind: outcome.kind,\n\t\t\t\t\terrorReason: outcome.reason ?? null,\n\t\t\t\t\terrorDetail: outcome.detail ? outcome.detail.slice(0, DETAIL_MAX) : null,\n\t\t\t\t\tpausedUntil:\n\t\t\t\t\t\toutcome.pausedForMs && outcome.pausedForMs > 0\n\t\t\t\t\t\t\t? new Date(at.getTime() + outcome.pausedForMs).toISOString()\n\t\t\t\t\t\t\t: null,\n\t\t\t\t}\n\n\treturn {\n\t\trecord(docId, outcome, { throttle = false, version } = {}) {\n\t\t\tconst at = now()\n\t\t\tif (outcome.ok) {\n\t\t\t\tconst written = successWrittenAt.get(docId)\n\t\t\t\tif (throttle && written !== undefined && at.getTime() - written < STATUS_SUCCESS_EVERY_MS) {\n\t\t\t\t\treturn Promise.resolve()\n\t\t\t\t}\n\t\t\t\tsuccessWrittenAt.set(docId, at.getTime())\n\t\t\t} else {\n\t\t\t\tsuccessWrittenAt.delete(docId)\n\t\t\t}\n\t\t\tconst data = { ...dataOf(outcome, at), version: version ?? null }\n\t\t\treturn enqueue(docId, async () => {\n\t\t\t\tawait put(docId, data)\n\t\t\t\tmemo.delete(docId)\n\t\t\t}).catch((err: unknown) => {\n\t\t\t\t// Unwritten, so the next success is written whatever the throttle says.\n\t\t\t\tsuccessWrittenAt.delete(docId)\n\t\t\t\tthrow err\n\t\t\t})\n\t\t},\n\n\t\tasync readMany(docIds, versionOf) {\n\t\t\t// One read per document: `payload.kv` has no batch read, and a scope holds a few.\n\t\t\tconst entries = await Promise.all(\n\t\t\t\tdocIds.map(async (id): Promise<[string, ProviderStatus] | undefined> => {\n\t\t\t\t\tconst at = now().getTime()\n\t\t\t\t\tlet held = memo.get(id)\n\t\t\t\t\tif (!held || held.until <= at) {\n\t\t\t\t\t\t// Held before it answers, so requests arriving together share one read.\n\t\t\t\t\t\tconst reading = { row: rowOf(id), until: at + STATUS_MEMO_MS }\n\t\t\t\t\t\treading.row.catch(() => memo.get(id) === reading && memo.delete(id))\n\t\t\t\t\t\tmemo.set(id, reading)\n\t\t\t\t\t\theld = reading\n\t\t\t\t\t}\n\t\t\t\t\tconst status = seen(id, await held.row, versionOf?.(id))\n\t\t\t\t\treturn status ? [id, status] : undefined\n\t\t\t\t})\n\t\t\t)\n\t\t\treturn new Map(entries.filter((entry) => entry !== undefined))\n\t\t},\n\n\t\tforget(docId) {\n\t\t\tsuccessWrittenAt.delete(docId)\n\t\t\treturn enqueue(docId, async () => {\n\t\t\t\tawait payload.kv.delete(providerStatusKey(docId))\n\t\t\t\tmemo.delete(docId)\n\t\t\t})\n\t\t},\n\n\t\tcarry(docId, from, to) {\n\t\t\treturn enqueue(docId, async () => {\n\t\t\t\tconst row = await rowOf(docId)\n\t\t\t\tif (row?.version === from) {\n\t\t\t\t\tawait payload.kv.set(providerStatusKey(docId), { ...row, version: to })\n\t\t\t\t\tmemo.delete(docId)\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\n\t\tasync idle() {\n\t\t\tawait Promise.all(queues.values())\n\t\t},\n\n\t\tasync read(docId, version) {\n\t\t\treturn seen(docId, await rowOf(docId), version)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAa,iBAAiB;;AAM9B,MAAa,qBAAqB,UAA0B,6BAA6B;;;;;;;AAQzF,MAAa,uBACZ,SACA,WACmC;CACnC,IAAI,QAAQ,IACX,OAAO,EAAE,IAAI,KAAK;CAEnB,MAAM,EAAE,SAAS,UAAU;CAC3B,IAAI,QAAQ,SAAS,mBAAmB,QAAQ,SAAS,gBACxD;CAED,MAAM,eAAe,QAAQ,cAAc,KAAA,IAAY,eAAe,KAAK;CAC3E,OAAO;EACN,IAAI;EACJ,MAAM,QAAQ;EACd,GAAI,cAAc,KAAK,IAAI,EAAE,QAAQ,cAAc,IAAI,CAAC;EACxD,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,aAAa;EAC7D,GAAI,OAAO,eAAe,EAAE,aAAa,OAAO,aAAa,IAAI,C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AAkB,KAAK,GAAG;MAAE,GAAG;MAAK,SAAS;KAAG,CAAC;KACtE,KAAK,OAAO,KAAK;IAClB;GACD,CAAC;EACF;EAEA,MAAM,OAAO;GACZ,MAAM,QAAQ,IAAI,OAAO,OAAO,CAAC;EAClC;EAEA,MAAM,KAAK,OAAO,SAAS;GAC1B,OAAO,KAAK,OAAO,MAAM,MAAM,KAAK,GAAG,OAAO;EAC/C;CACD;AACD"}
@@ -77,6 +77,11 @@ const GRPC_MISCONFIGURED = new Set([
77
77
  const GRPC_TIMEOUT = new Set([1, 4]);
78
78
  /** RESOURCE_EXHAUSTED: the quota is spent, which a retry a second later only spends again. */
79
79
  const GRPC_QUOTA = 8;
80
+ /**
81
+ * Codes the gRPC client sets itself when no answer came (CANCELLED, DEADLINE_EXCEEDED,
82
+ * UNAVAILABLE), with its own words, which can name the address it tried.
83
+ */
84
+ const GRPC_CLIENT_SIDE = new Set([...GRPC_TIMEOUT, 14]);
80
85
  /** What a gRPC status code means for the read; anything not named above is an outage. */
81
86
  const grpcCodeKind = (code) => {
82
87
  if (GRPC_INVALID.has(code)) return "invalid_param";
@@ -192,6 +197,19 @@ const retryAfterOf = (value) => {
192
197
  const retryAfterMs = numberAt(value, "retryAfterMs");
193
198
  return retryAfterMs !== void 0 && retryAfterMs >= 0 ? { retryAfterMs: Math.min(retryAfterMs, BREAKER_MAX_MS) } : {};
194
199
  };
200
+ /** A link's HTTP status, when it carries one. */
201
+ const httpStatusAt = (link) => {
202
+ const status = numberAt(link, "status");
203
+ return status !== void 0 && status >= 100 && status < 600 ? status : void 0;
204
+ };
205
+ /**
206
+ * A link's gRPC status code, as GA4's client rejects with; Node's own network errors carry string
207
+ * codes, and a DOMException's legacy numeric code means nothing here.
208
+ */
209
+ const grpcCodeAt = (link) => {
210
+ const code = link instanceof DOMException ? void 0 : numberAt(link, "code");
211
+ return code !== void 0 && Number.isInteger(code) && code >= 1 && code <= 16 ? code : void 0;
212
+ };
195
213
  /** Links of an error's cause chain {@link classifyError} reads at most. */
196
214
  const MAX_CAUSE_DEPTH = 5;
197
215
  /** The signal one link of an error's cause chain carries, or null when it carries none. */
@@ -217,15 +235,15 @@ const classifyLink = (link) => {
217
235
  timeout: true,
218
236
  ...Reflect.get(link, "refused") === true ? { refused: true } : {}
219
237
  };
220
- const status = numberAt(link, "status");
221
- if (status !== void 0 && status >= 100 && status < 600) return {
238
+ const status = httpStatusAt(link);
239
+ if (status !== void 0) return {
222
240
  kind: httpStatusKind(status),
223
241
  ...retryAfterOf(link)
224
242
  };
225
243
  const database = databaseFailure(link);
226
244
  if (database) return database;
227
- const code = link instanceof DOMException ? void 0 : numberAt(link, "code");
228
- if (code !== void 0 && Number.isInteger(code) && code >= 1 && code <= 16) return {
245
+ const code = grpcCodeAt(link);
246
+ if (code !== void 0) return {
229
247
  kind: grpcCodeKind(code),
230
248
  ...GRPC_TIMEOUT.has(code) ? { timeout: true } : {},
231
249
  ...code === GRPC_QUOTA ? { quota: true } : {},
@@ -263,6 +281,20 @@ const classifyError = (err) => {
263
281
  }
264
282
  return { kind: "unavailable" };
265
283
  };
284
+ /**
285
+ * What the vendor itself said about a failure: the message of the first link in the cause chain
286
+ * that carries an HTTP status or a gRPC code. The plugin's own refusals and the runtime's network
287
+ * errors are not the vendor's words, so a surface shows its own translated text for them instead.
288
+ */
289
+ const vendorAnswerOf = (err) => {
290
+ let current = err;
291
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && isRecord(current); depth++) {
292
+ const code = grpcCodeAt(current);
293
+ const message = Reflect.get(current, "message");
294
+ if (typeof message === "string" && (httpStatusAt(current) !== void 0 || code !== void 0 && !GRPC_CLIENT_SIDE.has(code))) return message;
295
+ current = Reflect.get(current, "cause");
296
+ }
297
+ };
266
298
  /** A failed read as a surface shows it. */
267
299
  const readFailureOf = (err) => {
268
300
  const failure = classifyError(err);
@@ -277,6 +309,6 @@ const readFailureOf = (err) => {
277
309
  }
278
310
  };
279
311
  //#endregion
280
- export { LaneRefusedError, PROVIDER_READ_TIMEOUT_MESSAGE, ReadFailedError, ScopeBusyError, classifyError, isLaneRefused, readFailureOf };
312
+ export { LaneRefusedError, PROVIDER_READ_TIMEOUT_MESSAGE, ReadFailedError, ScopeBusyError, classifyError, isLaneRefused, readFailureOf, vendorAnswerOf };
281
313
 
282
314
  //# sourceMappingURL=classifyError.js.map