@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.13

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 (194) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/adapters/ga4/ga4.d.ts +6 -0
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +2 -1
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +6 -0
  9. package/dist/adapters/posthog/posthog.js +21 -8
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/umami/umami.d.ts +6 -0
  12. package/dist/adapters/umami/umami.js +2 -1
  13. package/dist/adapters/umami/umami.js.map +1 -1
  14. package/dist/capture/exclusionEndpoint.js +1 -1
  15. package/dist/capture/exclusionEndpoint.js.map +1 -1
  16. package/dist/capture/slots.js +3 -3
  17. package/dist/capture/slots.js.map +1 -1
  18. package/dist/capture/trackerConfig.js +11 -3
  19. package/dist/capture/trackerConfig.js.map +1 -1
  20. package/dist/charts/series.js +1 -1
  21. package/dist/core/adminOptions.js +6 -1
  22. package/dist/core/adminOptions.js.map +1 -1
  23. package/dist/core/capture.d.ts +3 -1
  24. package/dist/core/contract.d.ts +13 -1
  25. package/dist/core/contract.js.map +1 -1
  26. package/dist/core/options.d.ts +37 -5
  27. package/dist/core/options.js +6 -2
  28. package/dist/core/options.js.map +1 -1
  29. package/dist/core/registry.js.map +1 -1
  30. package/dist/core/scopeOptions.js +2 -0
  31. package/dist/core/scopeOptions.js.map +1 -1
  32. package/dist/core/scopedRead.js +170 -21
  33. package/dist/core/scopedRead.js.map +1 -1
  34. package/dist/core/sourceLabel.d.ts +10 -0
  35. package/dist/core/sourceLabel.js +63 -0
  36. package/dist/core/sourceLabel.js.map +1 -0
  37. package/dist/core/sourceOptions.js +18 -6
  38. package/dist/core/sourceOptions.js.map +1 -1
  39. package/dist/core/sourcePolicy.d.ts +55 -0
  40. package/dist/core/sourcePolicy.js +51 -0
  41. package/dist/core/sourcePolicy.js.map +1 -0
  42. package/dist/exports/adapters/contract.d.ts +2 -1
  43. package/dist/exports/adapters/ga4.d.ts +3 -2
  44. package/dist/exports/adapters/native.d.ts +3 -2
  45. package/dist/exports/adapters/plausible.d.ts +3 -2
  46. package/dist/exports/adapters/posthog.d.ts +3 -2
  47. package/dist/exports/adapters/umami.d.ts +3 -2
  48. package/dist/exports/client.d.ts +7 -5
  49. package/dist/exports/client.js +2 -1
  50. package/dist/exports/next.d.ts +3 -2
  51. package/dist/exports/rsc.d.ts +7 -6
  52. package/dist/exports/testing.d.ts +3 -2
  53. package/dist/exports/types.d.ts +12 -8
  54. package/dist/fields/AnalyticsPanelClient.js.map +1 -1
  55. package/dist/fields/AnalyticsPanelField.d.ts +1 -1
  56. package/dist/fields/AnalyticsPanelField.js +3 -1
  57. package/dist/fields/AnalyticsPanelField.js.map +1 -1
  58. package/dist/fields/AnalyticsStatField.d.ts +1 -1
  59. package/dist/fields/AnalyticsStatField.js +1 -1
  60. package/dist/fields/PanelContent.js +6 -1
  61. package/dist/fields/PanelContent.js.map +1 -1
  62. package/dist/fields/config/fetchSources.d.ts +3 -0
  63. package/dist/fields/config/fetchSources.js +5 -3
  64. package/dist/fields/config/fetchSources.js.map +1 -1
  65. package/dist/fields/readForDocument.d.ts +5 -4
  66. package/dist/fields/readForDocument.js +6 -2
  67. package/dist/fields/readForDocument.js.map +1 -1
  68. package/dist/goals/collection.js +4 -31
  69. package/dist/goals/collection.js.map +1 -1
  70. package/dist/goals/resolver.js +2 -2
  71. package/dist/goals/trackGoalAction.js +1 -1
  72. package/dist/index.d.ts +14 -11
  73. package/dist/index.js +6 -5
  74. package/dist/index.js.map +1 -1
  75. package/dist/native/geo/maxmindResolver.js +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +1 -1
  77. package/dist/native/nativeAdapter.d.ts +6 -0
  78. package/dist/native/nativeAdapter.js +3 -2
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/plugin/createRuntime.js +6 -3
  81. package/dist/plugin/createRuntime.js.map +1 -1
  82. package/dist/plugin/documentEndpoint.js +1 -0
  83. package/dist/plugin/documentEndpoint.js.map +1 -1
  84. package/dist/plugin/pluginCollections.js +11 -5
  85. package/dist/plugin/pluginCollections.js.map +1 -1
  86. package/dist/plugin/queryEndpoint.js +1 -1
  87. package/dist/plugin/queryEndpoint.js.map +1 -1
  88. package/dist/plugin/readContextForRequest.d.ts +11 -0
  89. package/dist/plugin/readContextForRequest.js +25 -15
  90. package/dist/plugin/readContextForRequest.js.map +1 -1
  91. package/dist/plugin/runtime.js +13 -5
  92. package/dist/plugin/runtime.js.map +1 -1
  93. package/dist/plugin/sourcesEndpoint.js +8 -9
  94. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  95. package/dist/providers/ProvidersListNotice.d.ts +11 -0
  96. package/dist/providers/ProvidersListNotice.js +36 -0
  97. package/dist/providers/ProvidersListNotice.js.map +1 -0
  98. package/dist/providers/collection.d.ts +9 -1
  99. package/dist/providers/collection.js +107 -42
  100. package/dist/providers/collection.js.map +1 -1
  101. package/dist/providers/factory.d.ts +1 -1
  102. package/dist/providers/factory.js +8 -11
  103. package/dist/providers/factory.js.map +1 -1
  104. package/dist/providers/probe.js +5 -1
  105. package/dist/providers/probe.js.map +1 -1
  106. package/dist/providers/registry.js +49 -39
  107. package/dist/providers/registry.js.map +1 -1
  108. package/dist/providers/resolver.js +6 -3
  109. package/dist/providers/resolver.js.map +1 -1
  110. package/dist/providers/scopeUnique.js +41 -0
  111. package/dist/providers/scopeUnique.js.map +1 -0
  112. package/dist/query/fetchQuery.d.ts +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/tracker/config.d.ts +5 -0
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/sinks/createSink.js +4 -1
  117. package/dist/tracker/sinks/createSink.js.map +1 -1
  118. package/dist/tracker/sinks/ga4.js +2 -2
  119. package/dist/tracker/sinks/posthog.js +30 -2
  120. package/dist/tracker/sinks/posthog.js.map +1 -1
  121. package/dist/tracker/sinks/vendor.js +2 -2
  122. package/dist/tracker/sinks/vendor.js.map +1 -1
  123. package/dist/translations/ar.js +6 -0
  124. package/dist/translations/ar.js.map +1 -1
  125. package/dist/translations/de.js +6 -0
  126. package/dist/translations/de.js.map +1 -1
  127. package/dist/translations/en.js +6 -0
  128. package/dist/translations/en.js.map +1 -1
  129. package/dist/translations/es.js +6 -0
  130. package/dist/translations/es.js.map +1 -1
  131. package/dist/translations/fr.js +6 -0
  132. package/dist/translations/fr.js.map +1 -1
  133. package/dist/translations/id.js +6 -0
  134. package/dist/translations/id.js.map +1 -1
  135. package/dist/translations/keys.d.ts +6 -0
  136. package/dist/translations/keys.js +7 -1
  137. package/dist/translations/keys.js.map +1 -1
  138. package/dist/translations/ko.js +6 -0
  139. package/dist/translations/ko.js.map +1 -1
  140. package/dist/translations/pt.js +6 -0
  141. package/dist/translations/pt.js.map +1 -1
  142. package/dist/translations/ru.js +6 -0
  143. package/dist/translations/ru.js.map +1 -1
  144. package/dist/translations/uk.js +6 -0
  145. package/dist/translations/uk.js.map +1 -1
  146. package/dist/translations/zh.js +6 -0
  147. package/dist/translations/zh.js.map +1 -1
  148. package/dist/ui/analytics.css +5 -0
  149. package/dist/ui/components/SourcesNoticeBanner.js +20 -0
  150. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
  151. package/dist/view/ViewRoot.js +2 -0
  152. package/dist/view/ViewRoot.js.map +1 -1
  153. package/dist/view/registerView.js +5 -4
  154. package/dist/view/registerView.js.map +1 -1
  155. package/dist/view/viewContext.d.ts +1 -1
  156. package/dist/view/viewProps.d.ts +1 -1
  157. package/dist/view/viewProps.js +3 -2
  158. package/dist/view/viewProps.js.map +1 -1
  159. package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
  160. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  161. package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
  162. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  163. package/dist/widgets/AnalyticsMetricWidget.js +1 -0
  164. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  165. package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
  166. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  167. package/dist/widgets/AnalyticsTrendWidget.js +1 -0
  168. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  169. package/dist/widgets/defaultLayout.d.ts +26 -0
  170. package/dist/widgets/defaultLayout.js +51 -0
  171. package/dist/widgets/defaultLayout.js.map +1 -0
  172. package/dist/widgets/notices.js +1 -0
  173. package/dist/widgets/notices.js.map +1 -1
  174. package/dist/widgets/prepareWidgetRead.d.ts +14 -1
  175. package/dist/widgets/prepareWidgetRead.js +6 -2
  176. package/dist/widgets/prepareWidgetRead.js.map +1 -1
  177. package/dist/widgets/readForWidget.d.ts +4 -4
  178. package/dist/widgets/readForWidget.js +3 -1
  179. package/dist/widgets/readForWidget.js.map +1 -1
  180. package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
  181. package/dist/widgets/readForWidgetBreakdown.js +3 -1
  182. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  183. package/dist/widgets/readForWidgetGoals.d.ts +4 -4
  184. package/dist/widgets/readForWidgetGoals.js +3 -1
  185. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  186. package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
  187. package/dist/widgets/readForWidgetRealtime.js +3 -1
  188. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  189. package/dist/widgets/readForWidgetSeries.d.ts +4 -4
  190. package/dist/widgets/readForWidgetSeries.js +3 -1
  191. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  192. package/dist/widgets/registerWidgets.js +3 -1
  193. package/dist/widgets/registerWidgets.js.map +1 -1
  194. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"probe.js","names":[],"sources":["../../src/providers/probe.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Payload, SelectType, Where } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport { canonicalJson, isRecord } from '../core/values'\nimport { DETACHED } from '../db/openTransaction'\nimport { docScope } from '../plugin/scopeChange'\nimport { remember } from '../surfacing/bounded'\n\n/** How long an instance trusts a probe before asking the database again: the bound on convergence. */\nexport const PROBE_MEMO_MS = 10_000\n\n/** Far above any realistic document count for one scope. */\nconst MAX_ROWS = 1_000\n\n/** Scopes memoized before the expired ones are dropped. */\nconst PRUNE_AT = 1_000\n\n/** One document as the probe reads it: what tells a change apart, never a credential. */\nexport interface ProbeRow {\n\tid: string\n\t/** The last save as an ISO instant; empty for a document without one. */\n\tupdatedAt: string\n\tenabled: boolean\n\t/** The provider type, on rows of the providers collection only. */\n\tprovider?: string\n\tscope: string | null\n}\n\nexport interface Probe {\n\t/** In the order the database answers a lookup without a sort, which is the registry's order. */\n\trows: readonly ProbeRow[]\n\t/** Equal for equal committed states, whatever order the rows came in. */\n\tepoch: string\n}\n\n/** A stored date as an ISO instant, or empty when there is none. */\nexport const versionOf = (value: unknown): string => {\n\tif (!(value instanceof Date) && typeof value !== 'string' && typeof value !== 'number') {\n\t\treturn ''\n\t}\n\tconst ms = new Date(value).getTime()\n\treturn Number.isNaN(ms) ? '' : new Date(ms).toISOString()\n}\n\nconst byId = (a: ProbeRow, b: ProbeRow): number => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)\n\n/** A digest of the rows that ignores their order. */\nexport const probeEpoch = (rows: readonly ProbeRow[]): string =>\n\tcreateHash('sha256')\n\t\t.update(canonicalJson([...rows].sort(byId)))\n\t\t.digest('base64url')\n\n/** A scope as every read keys it: absent or empty is the install-wide scope, null. */\nexport const scopeOf = (scope: string | null | undefined): string | null =>\n\tscope === undefined || scope === '' ? null : scope\n\nexport interface CollectionProbe {\n\t/** The scope's rows and epoch as committed, read outside any transaction and memoized per instance. */\n\tread(scope: string | null | undefined): Promise<Probe>\n\t/**\n\t * A save on this instance touched these scopes: they are asked of the database on every read\n\t * for one memo window, so this instance sees the save as soon as it commits. Writes nothing.\n\t */\n\texpedite(scopes: Iterable<string | null>): void\n}\n\ninterface CollectionProbeOptions {\n\tpayload: Payload\n\tslug: string\n\tscopeField: string\n\t/** The clause selecting one scope's documents; absent, every scope reads every document. */\n\twhere?: (scope: string | null) => Where\n\t/** Whether the collection's rows carry a `provider`. */\n\tprovider?: boolean\n\tmemoMs?: number\n\tnow?: () => number\n}\n\ninterface Memoized {\n\tat: number\n\tprobe: Promise<Probe>\n}\n\n/**\n * Committed state of a collection's documents per scope, read on a detached request: an uncommitted\n * row is never seen, so nothing keyed on an epoch can roll back.\n */\nexport const createCollectionProbe = (options: CollectionProbeOptions): CollectionProbe => {\n\tconst { payload, slug, scopeField } = options\n\tconst memoMs = options.memoMs ?? PROBE_MEMO_MS\n\tconst now = options.now ?? currentTime\n\tconst select: SelectType = {\n\t\tupdatedAt: true,\n\t\tenabled: true,\n\t\t[scopeField]: true,\n\t\t...(options.provider ? { provider: true } : {}),\n\t}\n\tconst memo = new Map<string, Memoized>()\n\tconst expedited = new Map<string, number>()\n\n\tconst rowOf = (doc: Record<string, unknown>): ProbeRow => ({\n\t\tid: String(doc.id),\n\t\tupdatedAt: versionOf(doc.updatedAt),\n\t\tenabled: doc.enabled === true,\n\t\t...(options.provider ? { provider: typeof doc.provider === 'string' ? doc.provider : '' } : {}),\n\t\tscope: docScope(doc, scopeField),\n\t})\n\n\tconst query = async (scope: string | null): Promise<Probe> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered`)\n\t\t}\n\t\tconst { docs } = await payload.db.find<Record<string, unknown>>({\n\t\t\tcollection: slug,\n\t\t\tlimit: MAX_ROWS,\n\t\t\tpagination: false,\n\t\t\treq: DETACHED,\n\t\t\tselect,\n\t\t\t...(options.where ? { where: options.where(scope) } : {}),\n\t\t})\n\t\tconst rows = docs.filter(isRecord).map(rowOf)\n\t\treturn { rows, epoch: probeEpoch(rows) }\n\t}\n\n\tconst prune = (at: number): void => {\n\t\tfor (const [key, entry] of memo) {\n\t\t\tif (at - entry.at >= memoMs) {\n\t\t\t\tmemo.delete(key)\n\t\t\t}\n\t\t}\n\t\tfor (const [key, until] of expedited) {\n\t\t\tif (until <= at) {\n\t\t\t\texpedited.delete(key)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tread(raw) {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst key = scope ?? ''\n\t\t\tconst at = now()\n\t\t\tif ((expedited.get(key) ?? 0) > at) {\n\t\t\t\treturn query(scope)\n\t\t\t}\n\t\t\tconst hit = memo.get(key)\n\t\t\tif (hit && at - hit.at < memoMs) {\n\t\t\t\treturn hit.probe\n\t\t\t}\n\t\t\tif (memo.size >= PRUNE_AT) {\n\t\t\t\tprune(at)\n\t\t\t}\n\t\t\tconst probe = query(scope)\n\t\t\tremember(memo, [key, { at, probe }])\n\t\t\tprobe.catch(() => {\n\t\t\t\tif (memo.get(key)?.probe === probe) {\n\t\t\t\t\tmemo.delete(key)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn probe\n\t\t},\n\t\texpedite(scopes) {\n\t\t\tconst until = now() + memoMs\n\t\t\tfor (const raw of scopes) {\n\t\t\t\tconst key = scopeOf(raw) ?? ''\n\t\t\t\tmemo.delete(key)\n\t\t\t\tremember(expedited, [key, until])\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,gBAAgB;;AAG7B,MAAM,WAAW;;AAGjB,MAAM,WAAW;;AAqBjB,MAAa,aAAa,UAA2B;CACpD,IAAI,EAAE,iBAAiB,SAAS,OAAO,UAAU,YAAY,OAAO,UA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AE,OAAO,QAAQ,MAAM,KAAK,EAAE,IAAI,CAAC;EACxD,CAAC;EACD,MAAM,OAAO,KAAK,OAAO,QAAQ,EAAE,IAAI,KAAK;EAC5C,OAAO;GAAE;GAAM,OAAO,WAAW,IAAI;EAAE;CACxC;CAEA,MAAM,SAAS,OAAqB;EACnC,KAAK,MAAM,CAAC,KAAK,UAAU,MAC1B,IAAI,KAAK,MAAM,MAAM,QACpB,KAAK,OAAO,GAAG;EAGjB,KAAK,MAAM,CAAC,KAAK,UAAU,WAC1B,IAAI,SAAS,IACZ,UAAU,OAAO,GAAG;CAGvB;CAEA,OAAO;EACN,KAAK,KAAK;GACT,MAAM,QAAQ,QAAQ,GAAG;GACzB,MAAM,MAAM,SAAS;GACrB,MAAM,KAAK,IAAI;GACf,KAAK,UAAU,IAAI,GAAG,KAAK,KAAK,IAC/B,OAAO,MAAM,KAAK;GAEnB,MAAM,MAAM,KAAK,IAAI,GAAG;GACxB,IAAI,OAAO,KAAK,IAAI,KAAK,QACxB,OAAO,IAAI;GAEZ,IAAI,KAAK,QAAQ,UAChB,MAAM,EAAE;GAET,MAAM,QAAQ,MAAM,KAAK;GACzB,SAAS,MAAM,CAAC,KAAK;IAAE;IAAI;GAAM,CAAC,CAAC;GACnC,MAAM,YAAY;IACjB,IAAI,KAAK,IAAI,GAAG,GAAG,UAAU,OAC5B,KAAK,OAAO,GAAG;GAEjB,CAAC;GACD,OAAO;EACR;EACA,SAAS,QAAQ;GAChB,MAAM,QAAQ,IAAI,IAAI;GACtB,KAAK,MAAM,OAAO,QAAQ;IACzB,MAAM,MAAM,QAAQ,GAAG,KAAK;IAC5B,KAAK,OAAO,GAAG;IACf,SAAS,WAAW,CAAC,KAAK,KAAK,CAAC;GACjC;EACD;CACD;AACD"}
1
+ {"version":3,"file":"probe.js","names":[],"sources":["../../src/providers/probe.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\nimport type { Payload, SelectType, Where } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport { canonicalJson, isRecord } from '../core/values'\nimport { DETACHED } from '../db/openTransaction'\nimport { docScope } from '../plugin/scopeChange'\nimport { remember } from '../surfacing/bounded'\n\n/** How long an instance trusts a probe before asking the database again: the bound on convergence. */\nexport const PROBE_MEMO_MS = 10_000\n\n/** Far above any realistic document count for one scope. */\nconst MAX_ROWS = 1_000\n\n/** Scopes memoized before the expired ones are dropped. */\nconst PRUNE_AT = 1_000\n\n/** One document as the probe reads it: what tells a change apart, never a credential. */\nexport interface ProbeRow {\n\tid: string\n\t/** The last save as an ISO instant; empty for a document without one. */\n\tupdatedAt: string\n\tenabled: boolean\n\t/** The provider type, on rows of the providers collection only. */\n\tprovider?: string\n\t/** Only on a flagged providers row, so the epoch of rows nobody flagged stays as it was. */\n\tisDefault?: true\n\tscope: string | null\n}\n\nexport interface Probe {\n\t/** In the order the database answers a lookup without a sort, which is the registry's order. */\n\trows: readonly ProbeRow[]\n\t/** Equal for equal committed states, whatever order the rows came in. */\n\tepoch: string\n}\n\n/** A stored date as an ISO instant, or empty when there is none. */\nexport const versionOf = (value: unknown): string => {\n\tif (!(value instanceof Date) && typeof value !== 'string' && typeof value !== 'number') {\n\t\treturn ''\n\t}\n\tconst ms = new Date(value).getTime()\n\treturn Number.isNaN(ms) ? '' : new Date(ms).toISOString()\n}\n\nconst byId = (a: ProbeRow, b: ProbeRow): number => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)\n\n/** A digest of the rows that ignores their order. */\nexport const probeEpoch = (rows: readonly ProbeRow[]): string =>\n\tcreateHash('sha256')\n\t\t.update(canonicalJson([...rows].sort(byId)))\n\t\t.digest('base64url')\n\n/** A scope as every read keys it: absent or empty is the install-wide scope, null. */\nexport const scopeOf = (scope: string | null | undefined): string | null =>\n\tscope === undefined || scope === '' ? null : scope\n\nexport interface CollectionProbe {\n\t/** The scope's rows and epoch as committed, read outside any transaction and memoized per instance. */\n\tread(scope: string | null | undefined): Promise<Probe>\n\t/**\n\t * A save on this instance touched these scopes: they are asked of the database on every read\n\t * for one memo window, so this instance sees the save as soon as it commits. Writes nothing.\n\t */\n\texpedite(scopes: Iterable<string | null>): void\n}\n\ninterface CollectionProbeOptions {\n\tpayload: Payload\n\tslug: string\n\tscopeField: string\n\t/** The clause selecting one scope's documents; absent, every scope reads every document. */\n\twhere?: (scope: string | null) => Where\n\t/** Whether the collection's rows carry a `provider`. */\n\tprovider?: boolean\n\tmemoMs?: number\n\tnow?: () => number\n}\n\ninterface Memoized {\n\tat: number\n\tprobe: Promise<Probe>\n}\n\n/**\n * Committed state of a collection's documents per scope, read on a detached request: an uncommitted\n * row is never seen, so nothing keyed on an epoch can roll back.\n */\nexport const createCollectionProbe = (options: CollectionProbeOptions): CollectionProbe => {\n\tconst { payload, slug, scopeField } = options\n\tconst memoMs = options.memoMs ?? PROBE_MEMO_MS\n\tconst now = options.now ?? currentTime\n\tconst select: SelectType = {\n\t\tupdatedAt: true,\n\t\tenabled: true,\n\t\t[scopeField]: true,\n\t\t...(options.provider ? { provider: true, isDefault: true } : {}),\n\t}\n\tconst memo = new Map<string, Memoized>()\n\tconst expedited = new Map<string, number>()\n\n\tconst rowOf = (doc: Record<string, unknown>): ProbeRow => ({\n\t\tid: String(doc.id),\n\t\tupdatedAt: versionOf(doc.updatedAt),\n\t\tenabled: doc.enabled === true,\n\t\t...(options.provider ? { provider: typeof doc.provider === 'string' ? doc.provider : '' } : {}),\n\t\t...(options.provider && doc.isDefault === true ? { isDefault: true as const } : {}),\n\t\tscope: docScope(doc, scopeField),\n\t})\n\n\tconst query = async (scope: string | null): Promise<Probe> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered`)\n\t\t}\n\t\tconst { docs } = await payload.db.find<Record<string, unknown>>({\n\t\t\tcollection: slug,\n\t\t\tlimit: MAX_ROWS,\n\t\t\tpagination: false,\n\t\t\treq: DETACHED,\n\t\t\tselect,\n\t\t\t...(options.where ? { where: options.where(scope) } : {}),\n\t\t})\n\t\tconst rows = docs.filter(isRecord).map(rowOf)\n\t\treturn { rows, epoch: probeEpoch(rows) }\n\t}\n\n\tconst prune = (at: number): void => {\n\t\tfor (const [key, entry] of memo) {\n\t\t\tif (at - entry.at >= memoMs) {\n\t\t\t\tmemo.delete(key)\n\t\t\t}\n\t\t}\n\t\tfor (const [key, until] of expedited) {\n\t\t\tif (until <= at) {\n\t\t\t\texpedited.delete(key)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tread(raw) {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst key = scope ?? ''\n\t\t\tconst at = now()\n\t\t\tif ((expedited.get(key) ?? 0) > at) {\n\t\t\t\treturn query(scope)\n\t\t\t}\n\t\t\tconst hit = memo.get(key)\n\t\t\tif (hit && at - hit.at < memoMs) {\n\t\t\t\treturn hit.probe\n\t\t\t}\n\t\t\tif (memo.size >= PRUNE_AT) {\n\t\t\t\tprune(at)\n\t\t\t}\n\t\t\tconst probe = query(scope)\n\t\t\tremember(memo, [key, { at, probe }])\n\t\t\tprobe.catch(() => {\n\t\t\t\tif (memo.get(key)?.probe === probe) {\n\t\t\t\t\tmemo.delete(key)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn probe\n\t\t},\n\t\texpedite(scopes) {\n\t\t\tconst until = now() + memoMs\n\t\t\tfor (const raw of scopes) {\n\t\t\t\tconst key = scopeOf(raw) ?? ''\n\t\t\t\tmemo.delete(key)\n\t\t\t\tremember(expedited, [key, until])\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;AAUA,MAAa,gBAAgB;;AAG7B,MAAM,WAAW;;AAGjB,MAAM,WAAW;;AAuBjB,MAAa,aAAa,UAA2B;CACpD,IAAI,EAAE,iBAAiB,SAAS,OAAO,UAAU,YAAY,OAAO,UAAU,UAC7E,OAAO;CAER,MAAM,KAAK,IAAI,KAAK,KAAK,EAAE,QAAQ;CACnC,OAAO,OAAO,MAAM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,OAAO,QAAQ,MAAM,KAAK,EAAE,IAAI,CAAC;EACxD,CAAC;EACD,MAAM,OAAO,KAAK,OAAO,QAAQ,EAAE,IAAI,KAAK;EAC5C,OAAO;GAAE;GAAM,OAAO,WAAW,IAAI;EAAE;CACxC;CAEA,MAAM,SAAS,OAAqB;EACnC,KAAK,MAAM,CAAC,KAAK,UAAU,MAC1B,IAAI,KAAK,MAAM,MAAM,QACpB,KAAK,OAAO,GAAG;EAGjB,KAAK,MAAM,CAAC,KAAK,UAAU,WAC1B,IAAI,SAAS,IACZ,UAAU,OAAO,GAAG;CAGvB;CAEA,OAAO;EACN,KAAK,KAAK;GACT,MAAM,QAAQ,QAAQ,GAAG;GACzB,MAAM,MAAM,SAAS;GACrB,MAAM,KAAK,IAAI;GACf,KAAK,UAAU,IAAI,GAAG,KAAK,KAAK,IAC/B,OAAO,MAAM,KAAK;GAEnB,MAAM,MAAM,KAAK,IAAI,GAAG;GACxB,IAAI,OAAO,KAAK,IAAI,KAAK,QACxB,OAAO,IAAI;GAEZ,IAAI,KAAK,QAAQ,UAChB,MAAM,EAAE;GAET,MAAM,QAAQ,MAAM,KAAK;GACzB,SAAS,MAAM,CAAC,KAAK;IAAE;IAAI;GAAM,CAAC,CAAC;GACnC,MAAM,YAAY;IACjB,IAAI,KAAK,IAAI,GAAG,GAAG,UAAU,OAC5B,KAAK,OAAO,GAAG;GAEjB,CAAC;GACD,OAAO;EACR;EACA,SAAS,QAAQ;GAChB,MAAM,QAAQ,IAAI,IAAI;GACtB,KAAK,MAAM,OAAO,QAAQ;IACzB,MAAM,MAAM,QAAQ,GAAG,KAAK;IAC5B,KAAK,OAAO,GAAG;IACf,SAAS,WAAW,CAAC,KAAK,KAAK,CAAC;GACjC;EACD;CACD;AACD"}
@@ -5,14 +5,14 @@ import { combineRegistries, noGuardedConnection, providerScopeWhere } from "./re
5
5
  import { currentTime } from "../core/clock.js";
6
6
  import { remember } from "../surfacing/bounded.js";
7
7
  import { createEpochFallback } from "../surfacing/epoch.js";
8
+ import { GA4_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
9
+ import { PROVIDER_IDS, adapterFromProviderDoc, documentAdapterId, failingAdapter } from "./factory.js";
8
10
  import { SECRET_PATHS } from "./secrets.js";
9
11
  import { isCollectionSlug } from "../core/collectionSlug.js";
10
12
  import { createCollectionProbe, scopeOf, versionOf } from "./probe.js";
11
13
  import { throttled } from "../core/throttle.js";
12
- import { GA4_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
13
14
  import { loadEncrypted } from "../plugin/encrypted.js";
14
15
  import { createAdapterPool } from "./adapterPool.js";
15
- import { adapterFromProviderDoc, documentAdapterId, failingAdapter } from "./factory.js";
16
16
  import { createLocalReq } from "payload";
17
17
  //#region src/providers/registry.ts
18
18
  /** How often a failing probe is reported, at most. */
@@ -147,6 +147,9 @@ const collectionRegistry = (options, plan) => {
147
147
  intervalMs: WARN_EVERY_MS
148
148
  });
149
149
  const fallback = createEpochFallback(clock);
150
+ const types = plan.types ?? PROVIDER_IDS;
151
+ /** An enabled document of a type the install serves, which its adapter may then make a source. */
152
+ const servable = (row) => row.enabled && types.includes(row.provider ?? "");
150
153
  /** A probed id as the collection stores it: rows carry every id as text. */
151
154
  const idOf = (id) => {
152
155
  return ((isCollectionSlug(payload, slug) ? payload.collections[slug]?.customIDType : void 0) ?? payload.db.defaultIDType) === "number" && /^\d+$/.test(id) ? Number(id) : id;
@@ -227,15 +230,16 @@ const collectionRegistry = (options, plan) => {
227
230
  failed
228
231
  };
229
232
  };
230
- const build = async (scope, docs) => {
233
+ const build = async (scope, docs, flagged) => {
231
234
  const missing = docs.filter((doc) => pool.get(doc) === void 0).map((doc) => doc.id);
232
235
  const read = missing.length > 0 ? await buildDocuments(scope, missing) : void 0;
233
236
  const extras = [];
234
237
  for (const doc of docs) {
235
238
  const adapter = read?.built.has(doc.id) ? read.built.get(doc.id) : pool.get(doc);
236
- if (adapter) extras.push({
239
+ if (adapter?.isConfigured()) extras.push({
237
240
  adapter,
238
- docId: doc.id
241
+ docId: doc.id,
242
+ isDefault: flagged.has(doc.id)
239
243
  });
240
244
  }
241
245
  pool.retain(scope, new Set(docs.map((doc) => doc.id)));
@@ -257,46 +261,52 @@ const collectionRegistry = (options, plan) => {
257
261
  }
258
262
  };
259
263
  const isCurrent = (cached, epoch) => cached.epoch === epoch && (cached.retryAt === void 0 || clock() < cached.retryAt);
264
+ const registryOf = async (scope) => {
265
+ const key = scope ?? "";
266
+ const state = await probe.read(scope);
267
+ fallback.read(scope, state.epoch);
268
+ const cached = registries.get(key);
269
+ if (cached && isCurrent(cached, state.epoch)) {
270
+ pool.touch(cached.ids);
271
+ return cached.resolved;
272
+ }
273
+ const rows = state.rows.filter(servable);
274
+ const docs = rows.map((row) => ({
275
+ id: row.id,
276
+ version: row.updatedAt,
277
+ scope
278
+ }));
279
+ const built = build(scope, docs, new Set(rows.filter((row) => row.isDefault).map((row) => row.id)));
280
+ const entry = {
281
+ epoch: state.epoch,
282
+ resolved: built.then((done) => done.registry),
283
+ ids: docs.map((doc) => doc.id),
284
+ refs: new Set(docs.map(refOf))
285
+ };
286
+ built.then((done) => {
287
+ if (done.failed) entry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS;
288
+ }, () => {});
289
+ remember(registries, [key, entry]);
290
+ entry.resolved.catch(() => {
291
+ if (registries.get(key) === entry) registries.delete(key);
292
+ });
293
+ return entry.resolved;
294
+ };
260
295
  return {
261
- resolve: async (args) => {
262
- const scope = scopeOf(args.scope);
263
- const key = scope ?? "";
264
- const state = await probe.read(scope);
265
- fallback.read(scope, state.epoch);
266
- const cached = registries.get(key);
267
- if (cached && isCurrent(cached, state.epoch)) {
268
- pool.touch(cached.ids);
269
- return cached.resolved;
270
- }
271
- const docs = state.rows.filter((row) => row.enabled).map((row) => ({
272
- id: row.id,
273
- version: row.updatedAt,
274
- scope
275
- }));
276
- const built = build(scope, docs);
277
- const entry = {
278
- epoch: state.epoch,
279
- resolved: built.then((done) => done.registry),
280
- ids: docs.map((doc) => doc.id),
281
- refs: new Set(docs.map(refOf))
282
- };
283
- built.then((done) => {
284
- if (done.failed) entry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS;
285
- }, () => {});
286
- remember(registries, [key, entry]);
287
- entry.resolved.catch(() => {
288
- if (registries.get(key) === entry) registries.delete(key);
289
- });
290
- return entry.resolved;
291
- },
296
+ resolve: (args) => registryOf(scopeOf(args.scope)),
292
297
  epoch: async (raw) => {
293
298
  const scope = scopeOf(raw);
294
299
  const state = await probed(scope);
295
300
  return state ? fallback.read(scope, state.epoch) : fallback.failed(scope);
296
301
  },
297
- granted: async (scope, adapterId) => {
298
- const { rows } = await probe.read(scopeOf(scope));
299
- return rows.some((row) => row.enabled && (row.provider === "native" ? plan.nativeAdapter?.id === adapterId : documentAdapterId(row.provider, row.id) === adapterId));
302
+ granted: async (raw, adapterId) => {
303
+ const scope = scopeOf(raw);
304
+ const native = plan.nativeAdapter;
305
+ if (native && native.id === adapterId) {
306
+ const { rows } = await probe.read(scope);
307
+ return native.isConfigured() && rows.some((row) => row.provider === "native" && servable(row));
308
+ }
309
+ return (await registryOf(scope)).grants.has(adapterId);
300
310
  },
301
311
  changed: (scopes) => probe.expedite(scopes),
302
312
  refresh: async (scope) => probe.expedite([scope]),
@@ -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\ttype ProviderDoc,\n} from './factory'\nimport type { ProviderHostPolicy } from './hosts'\nimport { createCollectionProbe, type Probe, 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/** 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/** 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 enabled documents grant `adapterId`, from the committed rows alone:\n\t * nothing is read beyond them and nothing is decrypted. 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\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})\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): 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\tif (adapter) {\n\t\t\t\textras.push({ adapter, docId: 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\treturn {\n\t\tresolve: async (args) => {\n\t\t\tconst scope = scopeOf(args.scope)\n\t\t\tconst key = scope ?? ''\n\t\t\tconst state = await probe.read(scope)\n\t\t\tfallback.read(scope, state.epoch)\n\t\t\tconst cached = registries.get(key)\n\t\t\tif (cached && isCurrent(cached, state.epoch)) {\n\t\t\t\tpool.touch(cached.ids)\n\t\t\t\treturn cached.resolved\n\t\t\t}\n\t\t\tconst docs: PooledDocument[] = state.rows\n\t\t\t\t.filter((row) => row.enabled)\n\t\t\t\t.map((row) => ({ id: row.id, version: row.updatedAt, scope }))\n\t\t\tconst built = build(scope, docs)\n\t\t\tconst entry: CachedRegistry = {\n\t\t\t\tepoch: state.epoch,\n\t\t\t\tresolved: built.then((done) => done.registry),\n\t\t\t\tids: docs.map((doc) => doc.id),\n\t\t\t\trefs: new Set(docs.map(refOf)),\n\t\t\t}\n\t\t\tbuilt.then(\n\t\t\t\t(done) => {\n\t\t\t\t\tif (done.failed) {\n\t\t\t\t\t\tentry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {}\n\t\t\t)\n\t\t\tremember(registries, [key, entry])\n\t\t\tentry.resolved.catch(() => {\n\t\t\t\tif (registries.get(key) === entry) {\n\t\t\t\t\tregistries.delete(key)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn entry.resolved\n\t\t},\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 (scope, adapterId) => {\n\t\t\tconst { rows } = await probe.read(scopeOf(scope))\n\t\t\treturn rows.some(\n\t\t\t\t(row) =>\n\t\t\t\t\trow.enabled &&\n\t\t\t\t\t(row.provider === 'native'\n\t\t\t\t\t\t? plan.nativeAdapter?.id === adapterId\n\t\t\t\t\t\t: documentAdapterId(row.provider, row.id) === adapterId)\n\t\t\t)\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)\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K,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 } 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 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/** 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})\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":";;;;;;;;;;;;;;;;;;AAyCA,MAAM,gBAAgB;;;;;AAMtB,MAAa,2BAA2B;;AAuDxC,MAAM,aAAa,KAA8B,MAAc,UAAwB;CACtF,MAAM,CAAC,QAAQ,IAAI,SAAS,KAAK,MAAM,GAAG;CAC1C,MAAM,SAAS,IAAI;CACn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mBAAmB,SAAS,IAAI;EACxC,KAAK,WACJ,OAAO,gBAAgB,SAAS,KAAK,OAAO;EAC7C,SACC,OAAO,eAAe,OAAO;CAC/B;AACD"}
@@ -4,13 +4,15 @@ import { HostRefusedError } from "../core/sourceErrors.js";
4
4
  /**
5
5
  * Appends document adapters to the config base and records their grants; one sharing a base id (a
6
6
  * `native` document) takes its place, keeping the id, default and grant lookups. The first document
7
- * per id wins.
7
+ * per id wins; the first flagged document names `defaultGrant`, its adapter granted either way.
8
8
  */
9
9
  const combineRegistries = (base, extra) => {
10
10
  const indexById = new Map(base.adapters.map((adapter, index) => [adapter.id, index]));
11
11
  const merged = [...base.adapters];
12
12
  const grants = /* @__PURE__ */ new Map();
13
- for (const { adapter, docId } of extra) {
13
+ let defaultGrant;
14
+ for (const { adapter, docId, isDefault } of extra) {
15
+ if (isDefault && defaultGrant === void 0) defaultGrant = adapter.id;
14
16
  if (grants.has(adapter.id)) continue;
15
17
  grants.set(adapter.id, docId);
16
18
  const index = indexById.get(adapter.id);
@@ -19,7 +21,8 @@ const combineRegistries = (base, extra) => {
19
21
  }
20
22
  return {
21
23
  registry: createRegistry(merged, base.defaultId),
22
- grants
24
+ grants,
25
+ ...defaultGrant === void 0 ? {} : { defaultGrant }
23
26
  };
24
27
  };
25
28
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"resolver.js","names":[],"sources":["../../src/providers/resolver.ts"],"sourcesContent":["import type { Where } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport { createRegistry, type ScopeRegistry } from '../core/registry'\nimport { HostRefusedError } from '../core/sourceErrors'\n\n/** One provider document's adapter, tagged with the document that configured it. */\nexport interface ProviderAdapter {\n\tadapter: AnalyticsAdapter\n\t/** Document id, or the adapter's own id for a `providers.resolve` adapter with no document. */\n\tdocId: string\n}\n\nexport interface RegistryBase {\n\tadapters: AnalyticsAdapter[]\n\tdefaultId?: string\n}\n\n/**\n * Appends document adapters to the config base and records their grants; one sharing a base id (a\n * `native` document) takes its place, keeping the id, default and grant lookups. The first document\n * per id wins.\n */\nexport const combineRegistries = (base: RegistryBase, extra: ProviderAdapter[]): ScopeRegistry => {\n\tconst indexById = new Map(base.adapters.map((adapter, index) => [adapter.id, index]))\n\tconst merged = [...base.adapters]\n\tconst grants = new Map<string, string>()\n\tfor (const { adapter, docId } of extra) {\n\t\tif (grants.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tgrants.set(adapter.id, docId)\n\t\tconst index = indexById.get(adapter.id)\n\t\tif (index === undefined) {\n\t\t\tmerged.push(adapter)\n\t\t} else {\n\t\t\tmerged[index] = adapter\n\t\t}\n\t}\n\treturn { registry: createRegistry(merged, base.defaultId), grants }\n}\n\n/**\n * One scope's provider documents. '' is not castable on a relationship scope field, so install-wide\n * lookups there resolve config adapters only; readable lookups share this clause.\n */\nexport const providerScopeWhere = (scopeField: string, scope: string | null): Where =>\n\tscope === null\n\t\t? { or: [{ [scopeField]: { equals: null } }, { [scopeField]: { equals: '' } }] }\n\t\t: { [scopeField]: { equals: scope } }\n\n/** A fetch that refuses every request, for an adapter that would otherwise go out unguarded. */\nexport const noGuardedConnection: FetchLike = async (input) => {\n\tthrow new HostRefusedError(new URL(input).host, 'no guarded connection is available')\n}\n"],"mappings":";;;;;;;;AAuBA,MAAa,qBAAqB,MAAoB,UAA4C;CACjG,MAAM,YAAY,IAAI,IAAI,KAAK,SAAS,KAAK,SAAS,UAAU,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAC;CACpF,MAAM,SAAS,CAAC,GAAG,KAAK,QAAQ;CAChC,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,EAAE,SAAS,WAAW,OAAO;EACvC,IAAI,OAAO,IAAI,QAAQ,EAAE,GACxB;EAED,OAAO,IAAI,QAAQ,IAAI,KAAK;EAC5B,MAAM,QAAQ,UAAU,IAAI,QAAQ,EAAE;EACtC,IAAI,UAAU,KAAA,GACb,OAAO,KAAK,OAAO;OAEnB,OAAO,SAAS;CAElB;CACA,OAAO;EAAE,UAAU,eAAe,QAAQ,KAAK,SAAS;EAAG;CAAO;AACnE;;;;;AAMA,MAAa,sBAAsB,YAAoB,UACtD,UAAU,OACP,EAAE,IAAI,CAAC,GAAG,aAAa,EAAE,QAAQ,KAAK,EAAE,GAAG,GAAG,aAAa,EAAE,QAAQ,GAAG,EAAE,CAAC,EAAE,IAC7E,GAAG,aAAa,EAAE,QAAQ,MAAM,EAAE;;AAGtC,MAAa,sBAAiC,OAAO,UAAU;CAC9D,MAAM,IAAI,iBAAiB,IAAI,IAAI,KAAK,EAAE,MAAM,oCAAoC;AACrF"}
1
+ {"version":3,"file":"resolver.js","names":[],"sources":["../../src/providers/resolver.ts"],"sourcesContent":["import type { Where } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport { createRegistry, type ScopeRegistry } from '../core/registry'\nimport { HostRefusedError } from '../core/sourceErrors'\n\n/** One provider document's adapter, tagged with the document that configured it. */\nexport interface ProviderAdapter {\n\tadapter: AnalyticsAdapter\n\t/** Document id, or the adapter's own id for a `providers.resolve` adapter with no document. */\n\tdocId: string\n\t/** The document is flagged \"Default for this site\". */\n\tisDefault?: boolean\n}\n\nexport interface RegistryBase {\n\tadapters: AnalyticsAdapter[]\n\tdefaultId?: string\n}\n\n/**\n * Appends document adapters to the config base and records their grants; one sharing a base id (a\n * `native` document) takes its place, keeping the id, default and grant lookups. The first document\n * per id wins; the first flagged document names `defaultGrant`, its adapter granted either way.\n */\nexport const combineRegistries = (base: RegistryBase, extra: ProviderAdapter[]): ScopeRegistry => {\n\tconst indexById = new Map(base.adapters.map((adapter, index) => [adapter.id, index]))\n\tconst merged = [...base.adapters]\n\tconst grants = new Map<string, string>()\n\tlet defaultGrant: string | undefined\n\tfor (const { adapter, docId, isDefault } of extra) {\n\t\tif (isDefault && defaultGrant === undefined) {\n\t\t\tdefaultGrant = adapter.id\n\t\t}\n\t\tif (grants.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tgrants.set(adapter.id, docId)\n\t\tconst index = indexById.get(adapter.id)\n\t\tif (index === undefined) {\n\t\t\tmerged.push(adapter)\n\t\t} else {\n\t\t\tmerged[index] = adapter\n\t\t}\n\t}\n\treturn {\n\t\tregistry: createRegistry(merged, base.defaultId),\n\t\tgrants,\n\t\t...(defaultGrant === undefined ? {} : { defaultGrant }),\n\t}\n}\n\n/**\n * One scope's provider documents. '' is not castable on a relationship scope field, so install-wide\n * lookups there resolve config adapters only; readable lookups share this clause.\n */\nexport const providerScopeWhere = (scopeField: string, scope: string | null): Where =>\n\tscope === null\n\t\t? { or: [{ [scopeField]: { equals: null } }, { [scopeField]: { equals: '' } }] }\n\t\t: { [scopeField]: { equals: scope } }\n\n/** A fetch that refuses every request, for an adapter that would otherwise go out unguarded. */\nexport const noGuardedConnection: FetchLike = async (input) => {\n\tthrow new HostRefusedError(new URL(input).host, 'no guarded connection is available')\n}\n"],"mappings":";;;;;;;;AAyBA,MAAa,qBAAqB,MAAoB,UAA4C;CACjG,MAAM,YAAY,IAAI,IAAI,KAAK,SAAS,KAAK,SAAS,UAAU,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAC;CACpF,MAAM,SAAS,CAAC,GAAG,KAAK,QAAQ;CAChC,MAAM,yBAAS,IAAI,IAAoB;CACvC,IAAI;CACJ,KAAK,MAAM,EAAE,SAAS,OAAO,eAAe,OAAO;EAClD,IAAI,aAAa,iBAAiB,KAAA,GACjC,eAAe,QAAQ;EAExB,IAAI,OAAO,IAAI,QAAQ,EAAE,GACxB;EAED,OAAO,IAAI,QAAQ,IAAI,KAAK;EAC5B,MAAM,QAAQ,UAAU,IAAI,QAAQ,EAAE;EACtC,IAAI,UAAU,KAAA,GACb,OAAO,KAAK,OAAO;OAEnB,OAAO,SAAS;CAElB;CACA,OAAO;EACN,UAAU,eAAe,QAAQ,KAAK,SAAS;EAC/C;EACA,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;CACtD;AACD;;;;;AAMA,MAAa,sBAAsB,YAAoB,UACtD,UAAU,OACP,EAAE,IAAI,CAAC,GAAG,aAAa,EAAE,QAAQ,KAAK,EAAE,GAAG,GAAG,aAAa,EAAE,QAAQ,GAAG,EAAE,CAAC,EAAE,IAC7E,GAAG,aAAa,EAAE,QAAQ,MAAM,EAAE;;AAGtC,MAAa,sBAAiC,OAAO,UAAU;CAC9D,MAAM,IAAI,iBAAiB,IAAI,IAAI,KAAK,EAAE,MAAM,oCAAoC;AACrF"}
@@ -0,0 +1,41 @@
1
+ import { providerScopeWhere } from "./resolver.js";
2
+ import { memberScopeOf } from "./access.js";
3
+ //#region src/providers/scopeUnique.ts
4
+ const asScope = (value) => value === null || value === void 0 || value === "" ? null : String(value);
5
+ /**
6
+ * The scope the stamp will land the write in. Only a platform admin's declared scope is trusted:
7
+ * anyone else's would turn "already taken" into an oracle for what another tenant owns.
8
+ */
9
+ const writeScope = async (args, write) => {
10
+ const { data, originalDoc, req } = write;
11
+ try {
12
+ if (await args.crossScope({ req })) return asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField]);
13
+ return await memberScopeOf(args, req);
14
+ } catch {
15
+ return null;
16
+ }
17
+ };
18
+ /**
19
+ * Whether another document of the collection already matches `match` in the scope the write lands
20
+ * in, or anywhere on an unscoped install. Read past access, so a row the writer cannot see counts.
21
+ */
22
+ const takenInScope = async (args, write, match) => {
23
+ const where = [match];
24
+ if (args.scoped) where.push(providerScopeWhere(args.scopeField, await writeScope(args, write)));
25
+ const id = write.originalDoc?.id;
26
+ if (id !== void 0 && id !== null) where.push({ id: { not_equals: id } });
27
+ const { docs } = await write.req.payload.find({
28
+ collection: args.slug,
29
+ where: { and: where },
30
+ limit: 1,
31
+ pagination: false,
32
+ depth: 0,
33
+ overrideAccess: true,
34
+ req: write.req
35
+ });
36
+ return docs.length > 0;
37
+ };
38
+ //#endregion
39
+ export { takenInScope };
40
+
41
+ //# sourceMappingURL=scopeUnique.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scopeUnique.js","names":[],"sources":["../../src/providers/scopeUnique.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest, Where } from 'payload'\nimport { memberScopeOf, type ProviderAccessArgs } from './access'\nimport { providerScopeWhere } from './resolver'\n\n/** A write to one of the plugin's scoped collections, as its `beforeValidate` hook sees it. */\nexport interface ScopedWrite {\n\tdata?: Record<string, unknown>\n\toriginalDoc?: Record<string, unknown>\n\treq: PayloadRequest\n}\n\nconst asScope = (value: unknown): string | null =>\n\tvalue === null || value === undefined || value === '' ? null : String(value)\n\n/**\n * The scope the stamp will land the write in. Only a platform admin's declared scope is trusted:\n * anyone else's would turn \"already taken\" into an oracle for what another tenant owns.\n */\nconst writeScope = async (args: ProviderAccessArgs, write: ScopedWrite): Promise<string | null> => {\n\tconst { data, originalDoc, req } = write\n\ttry {\n\t\tif (await args.crossScope({ req })) {\n\t\t\t// No declared scope means an install-wide document, not one in whatever scope the\n\t\t\t// admin's own request happens to resolve to.\n\t\t\treturn asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField])\n\t\t}\n\t\treturn await memberScopeOf(args, req)\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/**\n * Whether another document of the collection already matches `match` in the scope the write lands\n * in, or anywhere on an unscoped install. Read past access, so a row the writer cannot see counts.\n */\nexport const takenInScope = async (\n\targs: ProviderAccessArgs & { slug: string },\n\twrite: ScopedWrite,\n\tmatch: Where\n): Promise<boolean> => {\n\tconst where: Where[] = [match]\n\tif (args.scoped) {\n\t\twhere.push(providerScopeWhere(args.scopeField, await writeScope(args, write)))\n\t}\n\tconst id = write.originalDoc?.id\n\tif (id !== undefined && id !== null) {\n\t\twhere.push({ id: { not_equals: id } })\n\t}\n\t// pagination:false is load-bearing: a paginated read fires its count and its find in\n\t// parallel on one Mongo session, which the write's open transaction refuses.\n\tconst { docs } = await write.req.payload.find({\n\t\t// Only the collection's own hooks call this, so its slug is registered.\n\t\tcollection: args.slug as CollectionSlug,\n\t\twhere: { and: where },\n\t\tlimit: 1,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq: write.req,\n\t})\n\treturn docs.length > 0\n}\n"],"mappings":";;;AAWA,MAAM,WAAW,UAChB,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,KAAK,OAAO,OAAO,KAAK;;;;;AAM5E,MAAM,aAAa,OAAO,MAA0B,UAA+C;CAClG,MAAM,EAAE,MAAM,aAAa,QAAQ;CACnC,IAAI;EACH,IAAI,MAAM,KAAK,WAAW,EAAE,IAAI,CAAC,GAGhC,OAAO,QAAQ,OAAO,KAAK,WAAW,KAAK,QAAQ,cAAc,KAAK,WAAW;EAElF,OAAO,MAAM,cAAc,MAAM,GAAG;CACrC,QAAQ;EACP,OAAO;CACR;AACD;;;;;AAMA,MAAa,eAAe,OAC3B,MACA,OACA,UACsB;CACtB,MAAM,QAAiB,CAAC,KAAK;CAC7B,IAAI,KAAK,QACR,MAAM,KAAK,mBAAmB,KAAK,YAAY,MAAM,WAAW,MAAM,KAAK,CAAC,CAAC;CAE9E,MAAM,KAAK,MAAM,aAAa;CAC9B,IAAI,OAAO,KAAA,KAAa,OAAO,MAC9B,MAAM,KAAK,EAAE,IAAI,EAAE,YAAY,GAAG,EAAE,CAAC;CAItC,MAAM,EAAE,SAAS,MAAM,MAAM,IAAI,QAAQ,KAAK;EAE7C,YAAY,KAAK;EACjB,OAAO,EAAE,KAAK,MAAM;EACpB,OAAO;EACP,YAAY;EACZ,OAAO;EACP,gBAAgB;EAChB,KAAK,MAAM;CACZ,CAAC;CACD,OAAO,KAAK,SAAS;AACtB"}
@@ -1,6 +1,6 @@
1
1
  import { AnalyticsFilter, DimensionKey, Granularity, MetricKey } from "../core/contract.js";
2
- import { TimeframePreset } from "../timeframe/presets.js";
3
2
  import { QueryResponse } from "./response.js";
3
+ import { TimeframePreset } from "../timeframe/presets.js";
4
4
  import { QueryFetchError } from "../ui/data/request.js";
5
5
 
6
6
  //#region src/query/fetchQuery.d.ts
@@ -1,8 +1,8 @@
1
1
  import { supportsGranularity } from "../core/granularity.js";
2
2
  import "../timeframe/tz.js";
3
+ import { isAverageMetric } from "../core/metricValues.js";
3
4
  import { calendarDayOf, parseCalendarDay } from "../timeframe/calendar.js";
4
5
  import { bucketInstant, bucketStartOf } from "../native/engine/buckets.js";
5
- import { isAverageMetric } from "../core/metricValues.js";
6
6
  //#region src/surfacing/rebucket.ts
7
7
  /**
8
8
  * The count an average is taken over, for a row that does not say (`AnalyticsRow.samples`):
@@ -104,6 +104,11 @@ interface TrackerSlotConfig {
104
104
  client: {
105
105
  kind: CaptureClientKind;
106
106
  } & Record<string, string | number | boolean>;
107
+ /**
108
+ * The named vendor client this slot captures with, beside the other slot's client of the same
109
+ * vendor: PostHog's `window.posthog[instance]`. Absent, the vendor's primary client.
110
+ */
111
+ instance?: string;
107
112
  /**
108
113
  * True when `capture.gate` holds this slot until the host's consent manager answers. Was
109
114
  * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../src/tracker/config.ts"],"sourcesContent":["/**\n * What the browser tracker is booted with, shared with the server that builds it. Imports\n * nothing, so `/tracker`, `/react` and `/site` declare it without reaching Payload or Node.\n */\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4'\n\nexport interface SnippetScript {\n\tsrc?: string\n\tinline?: string\n\tattrs?: Record<string, string>\n\tasync?: boolean\n\tdefer?: boolean\n\ttype?: string\n}\n\nexport interface CaptureSnippet {\n\tscripts: SnippetScript[]\n}\n\n/**\n * How an incoming event is recognized as a completion of a goal. `goal` matches an explicit\n * `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\n/** The goal fields the browser tracker needs; a goal's admin-facing name never leaves the server. */\nexport interface TrackerGoal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/**\n * One line of a sale, shaped like a GA4 `items` entry so a vendor sink forwards it as it stands.\n * Only the id is required.\n */\nexport interface RevenueItem {\n\tid: string\n\tname?: string\n\tquantity?: number\n\tprice?: number\n}\n\n/** `capture.autoCapture.items` with every default filled in. */\nexport interface ResolvedItemCapture {\n\timpressions: boolean\n\tclicks: boolean\n\tpages: boolean\n}\n\n/** `capture.autoCapture` with every default filled in. */\nexport interface ResolvedAutoCapture {\n\tscrollDepth: boolean\n\toutboundLinks: boolean\n\tfileDownloads: boolean\n\tgoalAttribute: boolean\n\tquery: boolean\n\titems: ResolvedItemCapture\n}\n\nexport const DEFAULT_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: true,\n\tclicks: true,\n\tpages: true,\n}\n\n/** Item capture off: what `items: false` asks for, and what an install binding no item collection gets. */\nexport const NO_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: false,\n\tclicks: false,\n\tpages: false,\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n\tquery: true,\n\titems: DEFAULT_ITEM_CAPTURE,\n}\n\n/**\n * The exclusion link while `capture.exclusion` is on: its parameter and the SHA-256 (lowercase hex)\n * of the value that excludes. The token itself never reaches a page.\n */\nexport interface TrackerExclusion {\n\tparam: string\n\ttokenHash: string\n}\n\n/** What the tracker leaves uncounted (`capture.skip`), each on unless the install turns it off. */\nexport interface TrackerSkip {\n\t/** A browser driven by automation, which says so in `navigator.webdriver`. */\n\tautomation: boolean\n\t/** A page rendered in draft mode, and one shown in Payload's live preview. */\n\tpreviews: boolean\n}\n\n/**\n * Where Payload's admin answers, as SHA-256 digests (lowercase hex) a page can check an address\n * against but never read the admin's address from.\n */\nexport interface AdminDigest {\n\t/** Of the admin's origin; absent when the admin is served from the page's own origin. */\n\torigin?: string\n\t/** Of the admin route's path, behind the Next basePath, with no trailing slash (`/` for the root). */\n\tpath: string\n}\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to, relative and behind the Next basePath. */\n\tpath: string\n\tsnippet: CaptureSnippet\n\t/** What the adapter hands its browser client: public settings only, never a credential. */\n\tclient: { kind: CaptureClientKind } & Record<string, string | number | boolean>\n\t/**\n\t * True when `capture.gate` holds this slot until the host's consent manager answers. Was\n\t * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.\n\t */\n\tgated: boolean\n}\n\n/**\n * Everything the browser tracker needs, served to any visitor: adapters' public `client` and\n * `snippet` settings only, never a query credential or a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\t/**\n\t * The request scope's goals, config merged with the collection. Built-in `purchase` stays out: it\n\t * matches by slug, and shipping it would tell every site it has a goal.\n\t */\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, relative and behind the Next basePath. */\n\tingestPath: string\n\t/**\n\t * The exclusion link for this request's scope, while `capture.exclusion` is on: its\n\t * parameter and the hash of its token. Absent, the tracker ignores the parameter.\n\t */\n\texclusion?: TrackerExclusion\n\t/** `capture.skip`, present only when the install turned one off. Absent, every skip is on. */\n\tskip?: TrackerSkip\n\t/** The page was rendered in draft mode (`getTrackerConfig`'s `draft`). */\n\tdraft?: true\n\t/**\n\t * Where Payload's admin answers, while previews are skipped: a page shown by one of its pages is\n\t * its live preview. Digests alone, so no page names the admin's host or route.\n\t */\n\tadmin?: AdminDigest\n}\n"],"mappings":";AAuEA,MAAa,uBAA4C;CACxD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,kBAAuC;CACnD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;CACf,OAAO;CACP,OAAO;AACR"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../src/tracker/config.ts"],"sourcesContent":["/**\n * What the browser tracker is booted with, shared with the server that builds it. Imports\n * nothing, so `/tracker`, `/react` and `/site` declare it without reaching Payload or Node.\n */\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4'\n\nexport interface SnippetScript {\n\tsrc?: string\n\tinline?: string\n\tattrs?: Record<string, string>\n\tasync?: boolean\n\tdefer?: boolean\n\ttype?: string\n}\n\nexport interface CaptureSnippet {\n\tscripts: SnippetScript[]\n}\n\n/**\n * How an incoming event is recognized as a completion of a goal. `goal` matches an explicit\n * `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\n/** The goal fields the browser tracker needs; a goal's admin-facing name never leaves the server. */\nexport interface TrackerGoal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/**\n * One line of a sale, shaped like a GA4 `items` entry so a vendor sink forwards it as it stands.\n * Only the id is required.\n */\nexport interface RevenueItem {\n\tid: string\n\tname?: string\n\tquantity?: number\n\tprice?: number\n}\n\n/** `capture.autoCapture.items` with every default filled in. */\nexport interface ResolvedItemCapture {\n\timpressions: boolean\n\tclicks: boolean\n\tpages: boolean\n}\n\n/** `capture.autoCapture` with every default filled in. */\nexport interface ResolvedAutoCapture {\n\tscrollDepth: boolean\n\toutboundLinks: boolean\n\tfileDownloads: boolean\n\tgoalAttribute: boolean\n\tquery: boolean\n\titems: ResolvedItemCapture\n}\n\nexport const DEFAULT_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: true,\n\tclicks: true,\n\tpages: true,\n}\n\n/** Item capture off: what `items: false` asks for, and what an install binding no item collection gets. */\nexport const NO_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: false,\n\tclicks: false,\n\tpages: false,\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n\tquery: true,\n\titems: DEFAULT_ITEM_CAPTURE,\n}\n\n/**\n * The exclusion link while `capture.exclusion` is on: its parameter and the SHA-256 (lowercase hex)\n * of the value that excludes. The token itself never reaches a page.\n */\nexport interface TrackerExclusion {\n\tparam: string\n\ttokenHash: string\n}\n\n/** What the tracker leaves uncounted (`capture.skip`), each on unless the install turns it off. */\nexport interface TrackerSkip {\n\t/** A browser driven by automation, which says so in `navigator.webdriver`. */\n\tautomation: boolean\n\t/** A page rendered in draft mode, and one shown in Payload's live preview. */\n\tpreviews: boolean\n}\n\n/**\n * Where Payload's admin answers, as SHA-256 digests (lowercase hex) a page can check an address\n * against but never read the admin's address from.\n */\nexport interface AdminDigest {\n\t/** Of the admin's origin; absent when the admin is served from the page's own origin. */\n\torigin?: string\n\t/** Of the admin route's path, behind the Next basePath, with no trailing slash (`/` for the root). */\n\tpath: string\n}\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to, relative and behind the Next basePath. */\n\tpath: string\n\tsnippet: CaptureSnippet\n\t/** What the adapter hands its browser client: public settings only, never a credential. */\n\tclient: { kind: CaptureClientKind } & Record<string, string | number | boolean>\n\t/**\n\t * The named vendor client this slot captures with, beside the other slot's client of the same\n\t * vendor: PostHog's `window.posthog[instance]`. Absent, the vendor's primary client.\n\t */\n\tinstance?: string\n\t/**\n\t * True when `capture.gate` holds this slot until the host's consent manager answers. Was\n\t * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.\n\t */\n\tgated: boolean\n}\n\n/**\n * Everything the browser tracker needs, served to any visitor: adapters' public `client` and\n * `snippet` settings only, never a query credential or a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\t/**\n\t * The request scope's goals, config merged with the collection. Built-in `purchase` stays out: it\n\t * matches by slug, and shipping it would tell every site it has a goal.\n\t */\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, relative and behind the Next basePath. */\n\tingestPath: string\n\t/**\n\t * The exclusion link for this request's scope, while `capture.exclusion` is on: its\n\t * parameter and the hash of its token. Absent, the tracker ignores the parameter.\n\t */\n\texclusion?: TrackerExclusion\n\t/** `capture.skip`, present only when the install turned one off. Absent, every skip is on. */\n\tskip?: TrackerSkip\n\t/** The page was rendered in draft mode (`getTrackerConfig`'s `draft`). */\n\tdraft?: true\n\t/**\n\t * Where Payload's admin answers, while previews are skipped: a page shown by one of its pages is\n\t * its live preview. Digests alone, so no page names the admin's host or route.\n\t */\n\tadmin?: AdminDigest\n}\n"],"mappings":";AAuEA,MAAa,uBAA4C;CACxD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,kBAAuC;CACnD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;CACf,OAAO;CACP,OAAO;AACR"}
@@ -20,7 +20,10 @@ const createSink = (args) => {
20
20
  win,
21
21
  url: ingestPath
22
22
  });
23
- case "posthog": return createPosthogSink(vendor);
23
+ case "posthog": return createPosthogSink({
24
+ ...vendor,
25
+ ...slot.instance === void 0 ? {} : { instance: slot.instance }
26
+ });
24
27
  case "plausible": return createPlausibleSink(vendor);
25
28
  case "umami": return createUmamiSink(vendor);
26
29
  case "ga4": {
@@ -1 +1 @@
1
- {"version":3,"file":"createSink.js","names":[],"sources":["../../../src/tracker/sinks/createSink.ts"],"sourcesContent":["import type { TrackerSlotConfig } from '../config'\nimport type { LoadScript, Sink, TrackerWindow } from '../types'\nimport { createGa4Sink } from './ga4'\nimport { createNativeSink } from './native'\nimport { createPlausibleSink } from './plausible'\nimport { createPosthogSink } from './posthog'\nimport { createUmamiSink } from './umami'\n\n/** The sink delivering one slot's events, by the kind of adapter filling it. */\nexport const createSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\t/** False when the host loads the vendor scripts itself. */\n\tsnippets: boolean\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, snippets } = args\n\t// With no scripts a vendor sink injects nothing and forwards once the vendor's global exists.\n\tconst scripts = snippets ? slot.snippet.scripts : []\n\tconst vendor = { slot: slot.slot, win, scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath })\n\t\tcase 'posthog':\n\t\t\treturn createPosthogSink(vendor)\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t\tcase 'ga4': {\n\t\t\tconst { measurementId } = slot.client\n\t\t\treturn createGa4Sink({\n\t\t\t\t...vendor,\n\t\t\t\t...(typeof measurementId === 'string' ? { measurementId } : {}),\n\t\t\t})\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAa,cAAc,SAOf;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,YAAY,aAAa;CAExD,MAAM,UAAU,WAAW,KAAK,QAAQ,UAAU,CAAC;CACnD,MAAM,SAAS;EAAE,MAAM,KAAK;EAAM;EAAK;EAAS;CAAW;CAC3D,QAAQ,KAAK,MAAb;EACC,KAAK,UACJ,OAAO,iBAAiB;GAAE,MAAM,KAAK;GAAM;GAAK,KAAK;EAAW,CAAC;EAClE,KAAK,WACJ,OAAO,kBAAkB,MAAM;EAChC,KAAK,aACJ,OAAO,oBAAoB,MAAM;EAClC,KAAK,SACJ,OAAO,gBAAgB,MAAM;EAC9B,KAAK,OAAO;GACX,MAAM,EAAE,kBAAkB,KAAK;GAC/B,OAAO,cAAc;IACpB,GAAG;IACH,GAAI,OAAO,kBAAkB,WAAW,EAAE,cAAc,IAAI,CAAC;GAC9D,CAAC;EACF;CACD;AACD"}
1
+ {"version":3,"file":"createSink.js","names":[],"sources":["../../../src/tracker/sinks/createSink.ts"],"sourcesContent":["import type { TrackerSlotConfig } from '../config'\nimport type { LoadScript, Sink, TrackerWindow } from '../types'\nimport { createGa4Sink } from './ga4'\nimport { createNativeSink } from './native'\nimport { createPlausibleSink } from './plausible'\nimport { createPosthogSink } from './posthog'\nimport { createUmamiSink } from './umami'\n\n/** The sink delivering one slot's events, by the kind of adapter filling it. */\nexport const createSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\t/** False when the host loads the vendor scripts itself. */\n\tsnippets: boolean\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, snippets } = args\n\t// With no scripts a vendor sink injects nothing and forwards once the vendor's global exists.\n\tconst scripts = snippets ? slot.snippet.scripts : []\n\tconst vendor = { slot: slot.slot, win, scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath })\n\t\tcase 'posthog':\n\t\t\treturn createPosthogSink({\n\t\t\t\t...vendor,\n\t\t\t\t...(slot.instance === undefined ? {} : { instance: slot.instance }),\n\t\t\t})\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t\tcase 'ga4': {\n\t\t\tconst { measurementId } = slot.client\n\t\t\treturn createGa4Sink({\n\t\t\t\t...vendor,\n\t\t\t\t...(typeof measurementId === 'string' ? { measurementId } : {}),\n\t\t\t})\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAa,cAAc,SAOf;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,YAAY,aAAa;CAExD,MAAM,UAAU,WAAW,KAAK,QAAQ,UAAU,CAAC;CACnD,MAAM,SAAS;EAAE,MAAM,KAAK;EAAM;EAAK;EAAS;CAAW;CAC3D,QAAQ,KAAK,MAAb;EACC,KAAK,UACJ,OAAO,iBAAiB;GAAE,MAAM,KAAK;GAAM;GAAK,KAAK;EAAW,CAAC;EAClE,KAAK,WACJ,OAAO,kBAAkB;GACxB,GAAG;GACH,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EAClE,CAAC;EACF,KAAK,aACJ,OAAO,oBAAoB,MAAM;EAClC,KAAK,SACJ,OAAO,gBAAgB,MAAM;EAC9B,KAAK,OAAO;GACX,MAAM,EAAE,kBAAkB,KAAK;GAC/B,OAAO,cAAc;IACpB,GAAG;IACH,GAAI,OAAO,kBAAkB,WAAW,EAAE,cAAc,IAAI,CAAC;GAC9D,CAAC;EACF;CACD;AACD"}
@@ -1,7 +1,7 @@
1
- import "../../goals/constants.js";
2
- import { bareItemRef } from "../../items/ref.js";
3
1
  import { ga4DisableKey } from "../../adapters/ga4/disableKey.js";
4
2
  import { ga4EventName } from "../../adapters/ga4/eventName.js";
3
+ import "../../goals/constants.js";
4
+ import { bareItemRef } from "../../items/ref.js";
5
5
  import { createVendorSink, flatProps, vendorEventName, vendorGlobal } from "./vendor.js";
6
6
  //#region src/tracker/sinks/ga4.ts
7
7
  /**
@@ -1,11 +1,34 @@
1
1
  import { createVendorSink, flatProps, vendorEventName, vendorGlobal } from "./vendor.js";
2
2
  //#region src/tracker/sinks/posthog.ts
3
+ const namedClient = (primary, instance) => {
4
+ if (typeof primary !== "object" || primary === null) return;
5
+ return Reflect.get(primary, instance);
6
+ };
7
+ /**
8
+ * Where a pageview was, since a queued one is captured after the address may have moved on; the URL
9
+ * carries only the query the tracker kept (campaign keys), as the event does.
10
+ */
11
+ const pageviewProps = (event, protocol) => ({
12
+ $current_url: `${protocol}//${event.hostname}${event.path}${event.query ? `?${event.query}` : ""}`,
13
+ $pathname: event.path,
14
+ $host: event.hostname
15
+ });
3
16
  /**
4
17
  * Forwards events and goals to `posthog.capture`, revenue as `value` and `currency`. Exclusion is
5
- * PostHog's opt-out; lifting it captures no `$opt_in`, since an open gate lifts it every load.
18
+ * PostHog's opt-out; lifting it captures no `$opt_in`, since an open gate lifts it every load. A
19
+ * named client also gets the tracker's pageviews, as it counts none of its own.
6
20
  */
7
21
  const createPosthogSink = (args) => {
8
- const posthog = () => vendorGlobal(args.win, "posthog");
22
+ const { instance } = args;
23
+ /**
24
+ * The slot's client once it can capture. A posthog-js the other slot's snippet loaded holds the
25
+ * primary client uninitialised until this slot's own `init` runs, and drops what it is given.
26
+ */
27
+ const posthog = () => {
28
+ const primary = vendorGlobal(args.win, "posthog");
29
+ const client = instance === void 0 ? primary : namedClient(primary, instance);
30
+ return client?.__loaded === false ? void 0 : client;
31
+ };
9
32
  let lifted = null;
10
33
  return createVendorSink(args, {
11
34
  exclude: (excluded) => {
@@ -20,7 +43,12 @@ const createPosthogSink = (args) => {
20
43
  sdk.opt_in_capturing?.({ captureEventName: false });
21
44
  },
22
45
  has: () => typeof posthog()?.capture === "function",
46
+ ...instance === void 0 ? {} : { pageviews: true },
23
47
  dispatch: (event) => {
48
+ if (event.type === "pageview") {
49
+ posthog()?.capture("$pageview", pageviewProps(event, args.win.location.protocol));
50
+ return;
51
+ }
24
52
  posthog()?.capture(vendorEventName(event), {
25
53
  ...flatProps(event),
26
54
  ...event.items === void 0 ? {} : { items: event.items }
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/tracker/sinks/posthog.ts"],"sourcesContent":["import type { Sink } from '../types'\nimport {\n\tcreateVendorSink,\n\tflatProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n} from './vendor'\n\ninterface PosthogGlobal {\n\tcapture(name: string, properties?: Record<string, unknown>): void\n\t/** https://posthog.com/docs/privacy/data-collection, and both are in the snippet's stub. */\n\topt_out_capturing?(): void\n\t/** `captureEventName: false` skips the `$opt_in` event it would otherwise capture. */\n\topt_in_capturing?(options?: { captureEventName?: string | false }): void\n}\n\n/**\n * Forwards events and goals to `posthog.capture`, revenue as `value` and `currency`. Exclusion is\n * PostHog's opt-out; lifting it captures no `$opt_in`, since an open gate lifts it every load.\n */\nexport const createPosthogSink = (args: VendorSinkArgs): Sink => {\n\tconst posthog = () => vendorGlobal<PosthogGlobal>(args.win, 'posthog')\n\tlet lifted: PosthogGlobal | null = null\n\treturn createVendorSink(args, {\n\t\texclude: (excluded) => {\n\t\t\tconst sdk = posthog()\n\t\t\tif (excluded) {\n\t\t\t\tlifted = null\n\t\t\t\tsdk?.opt_out_capturing?.()\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// The tracker lifts again once the snippet ran, which reaches only a global the first lift missed.\n\t\t\tif (sdk === undefined || sdk === lifted) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlifted = sdk\n\t\t\tsdk.opt_in_capturing?.({ captureEventName: false })\n\t\t},\n\t\thas: () => typeof posthog()?.capture === 'function',\n\t\tdispatch: (event) => {\n\t\t\tposthog()?.capture(vendorEventName(event), {\n\t\t\t\t...flatProps(event),\n\t\t\t\t// PostHog properties are arbitrary JSON, so the lines of a sale travel whole.\n\t\t\t\t...(event.items === undefined ? {} : { items: event.items }),\n\t\t\t})\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;AAqBA,MAAa,qBAAqB,SAA+B;CAChE,MAAM,gBAAgB,aAA4B,KAAK,KAAK,SAAS;CACrE,IAAI,SAA+B;CACnC,OAAO,iBAAiB,MAAM;EAC7B,UAAU,aAAa;GACtB,MAAM,MAAM,QAAQ;GACpB,IAAI,UAAU;IACb,SAAS;IACT,KAAK,oBAAoB;IACzB;GACD;GAEA,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAChC;GAED,SAAS;GACT,IAAI,mBAAmB,EAAE,kBAAkB,MAAM,CAAC;EACnD;EACA,WAAW,OAAO,QAAQ,GAAG,YAAY;EACzC,WAAW,UAAU;GACpB,QAAQ,GAAG,QAAQ,gBAAgB,KAAK,GAAG;IAC1C,GAAG,UAAU,KAAK;IAElB,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;GAC3D,CAAC;EACF;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/tracker/sinks/posthog.ts"],"sourcesContent":["import type { Sink, TrackerEvent } from '../types'\nimport {\n\tcreateVendorSink,\n\tflatProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n} from './vendor'\n\ninterface PosthogClient {\n\tcapture(name: string, properties?: Record<string, unknown>): void\n\t/** https://posthog.com/docs/privacy/data-collection, and both are in the snippet's stub. */\n\topt_out_capturing?(): void\n\t/** `captureEventName: false` skips the `$opt_in` event it would otherwise capture. */\n\topt_in_capturing?(options?: { captureEventName?: string | false }): void\n\t/** Set by a loaded posthog-js, false until the client's own `init` ran; the stub has none. */\n\t__loaded?: boolean\n}\n\nexport interface PosthogSinkArgs extends VendorSinkArgs {\n\t/** The named client (`window.posthog[instance]`) the slot captures with; absent, the primary one. */\n\tinstance?: string\n}\n\nconst namedClient = (primary: unknown, instance: string): PosthogClient | undefined => {\n\tif (typeof primary !== 'object' || primary === null) {\n\t\treturn undefined\n\t}\n\tconst client: unknown = Reflect.get(primary, instance)\n\treturn client as PosthogClient | undefined\n}\n\n/**\n * Where a pageview was, since a queued one is captured after the address may have moved on; the URL\n * carries only the query the tracker kept (campaign keys), as the event does.\n */\nconst pageviewProps = (event: TrackerEvent, protocol: string): Record<string, unknown> => ({\n\t$current_url: `${protocol}//${event.hostname}${event.path}${event.query ? `?${event.query}` : ''}`,\n\t$pathname: event.path,\n\t$host: event.hostname,\n})\n\n/**\n * Forwards events and goals to `posthog.capture`, revenue as `value` and `currency`. Exclusion is\n * PostHog's opt-out; lifting it captures no `$opt_in`, since an open gate lifts it every load. A\n * named client also gets the tracker's pageviews, as it counts none of its own.\n */\nexport const createPosthogSink = (args: PosthogSinkArgs): Sink => {\n\tconst { instance } = args\n\t/**\n\t * The slot's client once it can capture. A posthog-js the other slot's snippet loaded holds the\n\t * primary client uninitialised until this slot's own `init` runs, and drops what it is given.\n\t */\n\tconst posthog = (): PosthogClient | undefined => {\n\t\tconst primary = vendorGlobal<PosthogClient>(args.win, 'posthog')\n\t\tconst client = instance === undefined ? primary : namedClient(primary, instance)\n\t\treturn client?.__loaded === false ? undefined : client\n\t}\n\tlet lifted: PosthogClient | null = null\n\treturn createVendorSink(args, {\n\t\texclude: (excluded) => {\n\t\t\tconst sdk = posthog()\n\t\t\tif (excluded) {\n\t\t\t\tlifted = null\n\t\t\t\tsdk?.opt_out_capturing?.()\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// The tracker lifts again once the snippet ran, which reaches only a global the first lift missed.\n\t\t\tif (sdk === undefined || sdk === lifted) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlifted = sdk\n\t\t\tsdk.opt_in_capturing?.({ captureEventName: false })\n\t\t},\n\t\thas: () => typeof posthog()?.capture === 'function',\n\t\t...(instance === undefined ? {} : { pageviews: true }),\n\t\tdispatch: (event) => {\n\t\t\tif (event.type === 'pageview') {\n\t\t\t\tposthog()?.capture('$pageview', pageviewProps(event, args.win.location.protocol))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tposthog()?.capture(vendorEventName(event), {\n\t\t\t\t...flatProps(event),\n\t\t\t\t// PostHog properties are arbitrary JSON, so the lines of a sale travel whole.\n\t\t\t\t...(event.items === undefined ? {} : { items: event.items }),\n\t\t\t})\n\t\t},\n\t})\n}\n"],"mappings":";;AAwBA,MAAM,eAAe,SAAkB,aAAgD;CACtF,IAAI,OAAO,YAAY,YAAY,YAAY,MAC9C;CAGD,OADwB,QAAQ,IAAI,SAAS,QACjC;AACb;;;;;AAMA,MAAM,iBAAiB,OAAqB,cAA+C;CAC1F,cAAc,GAAG,SAAS,IAAI,MAAM,WAAW,MAAM,OAAO,MAAM,QAAQ,IAAI,MAAM,UAAU;CAC9F,WAAW,MAAM;CACjB,OAAO,MAAM;AACd;;;;;;AAOA,MAAa,qBAAqB,SAAgC;CACjE,MAAM,EAAE,aAAa;;;;;CAKrB,MAAM,gBAA2C;EAChD,MAAM,UAAU,aAA4B,KAAK,KAAK,SAAS;EAC/D,MAAM,SAAS,aAAa,KAAA,IAAY,UAAU,YAAY,SAAS,QAAQ;EAC/E,OAAO,QAAQ,aAAa,QAAQ,KAAA,IAAY;CACjD;CACA,IAAI,SAA+B;CACnC,OAAO,iBAAiB,MAAM;EAC7B,UAAU,aAAa;GACtB,MAAM,MAAM,QAAQ;GACpB,IAAI,UAAU;IACb,SAAS;IACT,KAAK,oBAAoB;IACzB;GACD;GAEA,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAChC;GAED,SAAS;GACT,IAAI,mBAAmB,EAAE,kBAAkB,MAAM,CAAC;EACnD;EACA,WAAW,OAAO,QAAQ,GAAG,YAAY;EACzC,GAAI,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,KAAK;EACpD,WAAW,UAAU;GACpB,IAAI,MAAM,SAAS,YAAY;IAC9B,QAAQ,GAAG,QAAQ,aAAa,cAAc,OAAO,KAAK,IAAI,SAAS,QAAQ,CAAC;IAChF;GACD;GACA,QAAQ,GAAG,QAAQ,gBAAgB,KAAK,GAAG;IAC1C,GAAG,UAAU,KAAK;IAElB,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;GAC3D,CAAC;EACF;CACD,CAAC;AACF"}
@@ -30,7 +30,7 @@ const whenPresent = (win, target) => {
30
30
  };
31
31
  /**
32
32
  * Loads the slot's snippets once, in order, and dispatches when the vendor global exists, since Umami
33
- * has no stub. Pageviews and engagements are dropped: every vendor measures its own.
33
+ * has no stub. Engagements are dropped, and pageviews unless the target asks: each vendor measures its own.
34
34
  */
35
35
  const createVendorSink = (args, target) => {
36
36
  let loading = null;
@@ -43,7 +43,7 @@ const createVendorSink = (args, target) => {
43
43
  ready,
44
44
  ...target.exclude ? { exclude: target.exclude } : {},
45
45
  send(event) {
46
- if (event.type === "pageview" || event.type === "engagement") return;
46
+ if (event.type === "engagement" || event.type === "pageview" && !target.pageviews) return;
47
47
  if (target.has()) {
48
48
  target.dispatch(event);
49
49
  return;