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

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 (175) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/ga4/ga4.d.ts +7 -0
  4. package/dist/adapters/ga4/ga4.js +17 -3
  5. package/dist/adapters/ga4/ga4.js.map +1 -1
  6. package/dist/adapters/plausible/plausible.d.ts +6 -0
  7. package/dist/adapters/plausible/plausible.js +6 -3
  8. package/dist/adapters/plausible/plausible.js.map +1 -1
  9. package/dist/adapters/posthog/cloud.js +20 -0
  10. package/dist/adapters/posthog/cloud.js.map +1 -0
  11. package/dist/adapters/posthog/credentials.js +20 -0
  12. package/dist/adapters/posthog/credentials.js.map +1 -0
  13. package/dist/adapters/posthog/posthog.d.ts +10 -3
  14. package/dist/adapters/posthog/posthog.js +100 -27
  15. package/dist/adapters/posthog/posthog.js.map +1 -1
  16. package/dist/adapters/posthog/projectCheck.js +56 -0
  17. package/dist/adapters/posthog/projectCheck.js.map +1 -0
  18. package/dist/adapters/umami/umami.d.ts +6 -0
  19. package/dist/adapters/umami/umami.js +3 -1
  20. package/dist/adapters/umami/umami.js.map +1 -1
  21. package/dist/capture/trackerConfig.js +29 -6
  22. package/dist/capture/trackerConfig.js.map +1 -1
  23. package/dist/capture/withoutConsent.js +91 -0
  24. package/dist/capture/withoutConsent.js.map +1 -0
  25. package/dist/core/capture.d.ts +41 -11
  26. package/dist/core/captureOptions.js +97 -8
  27. package/dist/core/captureOptions.js.map +1 -1
  28. package/dist/core/contract.d.ts +25 -0
  29. package/dist/core/contract.js.map +1 -1
  30. package/dist/core/options.d.ts +24 -2
  31. package/dist/core/options.js.map +1 -1
  32. package/dist/core/sourceOptions.js +2 -1
  33. package/dist/core/sourceOptions.js.map +1 -1
  34. package/dist/exports/adapters/contract.d.ts +3 -3
  35. package/dist/exports/adapters/ga4.d.ts +4 -4
  36. package/dist/exports/adapters/native.d.ts +5 -5
  37. package/dist/exports/adapters/plausible.d.ts +4 -4
  38. package/dist/exports/adapters/posthog.d.ts +4 -4
  39. package/dist/exports/adapters/umami.d.ts +4 -4
  40. package/dist/exports/next.d.ts +4 -4
  41. package/dist/exports/react.d.ts +3 -2
  42. package/dist/exports/site.d.ts +2 -2
  43. package/dist/exports/testing.d.ts +4 -4
  44. package/dist/exports/tracker.d.ts +3 -2
  45. package/dist/exports/types.d.ts +5 -5
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.js +2 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/native/collections/hits.js +1 -0
  50. package/dist/native/collections/hits.js.map +1 -1
  51. package/dist/native/engine/engine.js +5 -1
  52. package/dist/native/engine/engine.js.map +1 -1
  53. package/dist/native/engine/planner.js +2 -1
  54. package/dist/native/engine/planner.js.map +1 -1
  55. package/dist/native/engine/toHit.js +4 -2
  56. package/dist/native/engine/toHit.js.map +1 -1
  57. package/dist/native/ingest/endpoint.js +5 -2
  58. package/dist/native/ingest/endpoint.js.map +1 -1
  59. package/dist/native/ingest/normalizeEvent.d.ts +6 -1
  60. package/dist/native/ingest/normalizeEvent.js +17 -7
  61. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  62. package/dist/native/ingest/serverTrack.js +2 -1
  63. package/dist/native/ingest/serverTrack.js.map +1 -1
  64. package/dist/native/ingest/validate.js +3 -0
  65. package/dist/native/ingest/validate.js.map +1 -1
  66. package/dist/native/nativeAdapter.d.ts +10 -1
  67. package/dist/native/nativeAdapter.js +11 -1
  68. package/dist/native/nativeAdapter.js.map +1 -1
  69. package/dist/native/store/aggregate.js +1 -1
  70. package/dist/native/store/aggregate.js.map +1 -1
  71. package/dist/native/store/hitRow.js +3 -0
  72. package/dist/native/store/hitRow.js.map +1 -1
  73. package/dist/native/store/hits.js +3 -1
  74. package/dist/native/store/hits.js.map +1 -1
  75. package/dist/native/store/mongo/aggregatePipelines.js +10 -2
  76. package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
  77. package/dist/native/store/mongo/pipelines.js +15 -5
  78. package/dist/native/store/mongo/pipelines.js.map +1 -1
  79. package/dist/native/store/parts.js +9 -3
  80. package/dist/native/store/parts.js.map +1 -1
  81. package/dist/native/store/rawRead.js +6 -3
  82. package/dist/native/store/rawRead.js.map +1 -1
  83. package/dist/native/store/sql/aggregateSql.js +6 -2
  84. package/dist/native/store/sql/aggregateSql.js.map +1 -1
  85. package/dist/native/store/sql/columns.js +1 -0
  86. package/dist/native/store/sql/columns.js.map +1 -1
  87. package/dist/native/store/sql/compile.js +19 -7
  88. package/dist/native/store/sql/compile.js.map +1 -1
  89. package/dist/native/store/types.d.ts +7 -1
  90. package/dist/native/store/types.js +10 -0
  91. package/dist/native/store/types.js.map +1 -0
  92. package/dist/plugin/createRuntime.js +10 -1
  93. package/dist/plugin/createRuntime.js.map +1 -1
  94. package/dist/plugin/runtime.js.map +1 -1
  95. package/dist/providers/collection.d.ts +2 -0
  96. package/dist/providers/collection.js +36 -9
  97. package/dist/providers/collection.js.map +1 -1
  98. package/dist/providers/factory.d.ts +9 -1
  99. package/dist/providers/factory.js +14 -5
  100. package/dist/providers/factory.js.map +1 -1
  101. package/dist/providers/hosts.js +14 -6
  102. package/dist/providers/hosts.js.map +1 -1
  103. package/dist/providers/registry.js +2 -1
  104. package/dist/providers/registry.js.map +1 -1
  105. package/dist/react/AnalyticsProvider.d.ts +6 -0
  106. package/dist/react/AnalyticsProvider.js.map +1 -1
  107. package/dist/react/useAnalytics.js +9 -5
  108. package/dist/react/useAnalytics.js.map +1 -1
  109. package/dist/site/AnalyticsScripts.d.ts +4 -3
  110. package/dist/site/AnalyticsScripts.js +18 -4
  111. package/dist/site/AnalyticsScripts.js.map +1 -1
  112. package/dist/surfacing/todaySplit.js +7 -1
  113. package/dist/surfacing/todaySplit.js.map +1 -1
  114. package/dist/tracker/config.d.ts +26 -1
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/createTracker.d.ts +2 -1
  117. package/dist/tracker/createTracker.js +91 -59
  118. package/dist/tracker/createTracker.js.map +1 -1
  119. package/dist/tracker/gate.d.ts +8 -0
  120. package/dist/tracker/gate.js +61 -11
  121. package/dist/tracker/gate.js.map +1 -1
  122. package/dist/tracker/loadScript.js +2 -1
  123. package/dist/tracker/loadScript.js.map +1 -1
  124. package/dist/tracker/registry.js +14 -3
  125. package/dist/tracker/registry.js.map +1 -1
  126. package/dist/tracker/sinks/createSink.js +27 -8
  127. package/dist/tracker/sinks/createSink.js.map +1 -1
  128. package/dist/tracker/sinks/ga4.js +38 -6
  129. package/dist/tracker/sinks/ga4.js.map +1 -1
  130. package/dist/tracker/sinks/native.js +17 -3
  131. package/dist/tracker/sinks/native.js.map +1 -1
  132. package/dist/tracker/sinks/plausible.js +8 -2
  133. package/dist/tracker/sinks/plausible.js.map +1 -1
  134. package/dist/tracker/sinks/posthog.js +108 -16
  135. package/dist/tracker/sinks/posthog.js.map +1 -1
  136. package/dist/tracker/sinks/umami.js +2 -2
  137. package/dist/tracker/sinks/umami.js.map +1 -1
  138. package/dist/tracker/sinks/vendor.js +25 -11
  139. package/dist/tracker/sinks/vendor.js.map +1 -1
  140. package/dist/tracker/types.d.ts +10 -3
  141. package/dist/translations/ar.js +10 -0
  142. package/dist/translations/ar.js.map +1 -1
  143. package/dist/translations/de.js +10 -0
  144. package/dist/translations/de.js.map +1 -1
  145. package/dist/translations/en.js +10 -0
  146. package/dist/translations/en.js.map +1 -1
  147. package/dist/translations/es.js +10 -0
  148. package/dist/translations/es.js.map +1 -1
  149. package/dist/translations/fr.js +10 -0
  150. package/dist/translations/fr.js.map +1 -1
  151. package/dist/translations/id.js +10 -0
  152. package/dist/translations/id.js.map +1 -1
  153. package/dist/translations/keys.d.ts +10 -0
  154. package/dist/translations/keys.js +11 -1
  155. package/dist/translations/keys.js.map +1 -1
  156. package/dist/translations/ko.js +10 -0
  157. package/dist/translations/ko.js.map +1 -1
  158. package/dist/translations/pt.js +10 -0
  159. package/dist/translations/pt.js.map +1 -1
  160. package/dist/translations/ru.js +10 -0
  161. package/dist/translations/ru.js.map +1 -1
  162. package/dist/translations/uk.js +10 -0
  163. package/dist/translations/uk.js.map +1 -1
  164. package/dist/translations/zh.js +10 -0
  165. package/dist/translations/zh.js.map +1 -1
  166. package/dist/view/consentShare.js +15 -0
  167. package/dist/view/consentShare.js.map +1 -0
  168. package/dist/view/sections/OverviewCards.js +38 -28
  169. package/dist/view/sections/OverviewCards.js.map +1 -1
  170. package/dist/widgets/notices.js +6 -1
  171. package/dist/widgets/notices.js.map +1 -1
  172. package/dist/widgets/readMeta.d.ts +4 -0
  173. package/dist/widgets/readMeta.js +5 -0
  174. package/dist/widgets/readMeta.js.map +1 -1
  175. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import { isOneOf, isRecord } from "../../core/values.js";
2
2
  import { dateOf, jsonOf } from "./columnValues.js";
3
+ import { HIT_MODES } from "./types.js";
3
4
  //#region src/native/store/hitRow.ts
4
5
  const HIT_TYPES = [
5
6
  "pageview",
@@ -94,6 +95,8 @@ const hitRowOf = (read) => {
94
95
  };
95
96
  const lastAt = dateOf(read("lastAt"));
96
97
  if (lastAt !== null) hit.lastAt = lastAt;
98
+ const mode = read("mode");
99
+ if (isOneOf(HIT_MODES, mode)) hit.mode = mode;
97
100
  for (const field of TEXT_FIELDS) {
98
101
  const value = read(field);
99
102
  if (typeof value === "string") hit[field] = value;
@@ -1 +1 @@
1
- {"version":3,"file":"hitRow.js","names":[],"sources":["../../../src/native/store/hitRow.ts"],"sourcesContent":["import { isOneOf, isRecord } from '../../core/values'\nimport type { GoalCompletion } from '../../goals/match'\nimport { dateOf, jsonOf } from './columnValues'\nimport type { HitRow, HitType } from './types'\n\nconst HIT_TYPES: readonly HitType[] = ['pageview', 'event', 'goal', 'engagement']\n\n/** The optional text fields of a hit. */\nconst TEXT_FIELDS = [\n\t'name',\n\t'ref',\n\t'source',\n\t'channel',\n\t'clickId',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'device',\n\t'browser',\n\t'os',\n\t'currency',\n\t'originalCurrency',\n\t'item',\n] as const satisfies ReadonlyArray<keyof HitRow>\n\n/** The optional number fields of a hit. */\nconst NUMBER_FIELDS = [\n\t'channelVersion',\n\t'durationMs',\n\t'scrollDepth',\n\t'value',\n\t'originalValue',\n\t'conversions',\n\t'revenue',\n] as const satisfies ReadonlyArray<keyof HitRow>\n\n/**\n * A number, or numeric text as node-postgres answers one; a blank string or any other value is\n * absent, where `numberOf` would read a blank as 0.\n */\nconst optionalNumberOf = (value: unknown): number | undefined => {\n\tconst n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value\n\treturn typeof n === 'number' && Number.isFinite(n) ? n : undefined\n}\n\n/** A boolean column: `true` on Postgres and MongoDB, `1` on SQLite. */\nconst flagOf = (value: unknown): boolean => value === true || value === 1\n\nconst completionsOf = (value: unknown): GoalCompletion[] | undefined => {\n\tconst parsed = jsonOf(value)\n\tif (!Array.isArray(parsed)) {\n\t\treturn undefined\n\t}\n\treturn parsed.flatMap((entry): GoalCompletion[] => {\n\t\tif (!isRecord(entry) || typeof entry.slug !== 'string') {\n\t\t\treturn []\n\t\t}\n\t\tconst value = optionalNumberOf(entry.value) ?? 0\n\t\tconst sent = optionalNumberOf(entry.sent)\n\t\treturn [{ slug: entry.slug, value, ...(sent === undefined ? {} : { sent }) }]\n\t})\n}\n\nconst textsOf = (value: unknown): string[] | undefined => {\n\tconst parsed = jsonOf(value)\n\treturn Array.isArray(parsed)\n\t\t? parsed.filter((entry): entry is string => typeof entry === 'string')\n\t\t: undefined\n}\n\n/**\n * A stored hit read back, each field through `read` (a document's own field, or a row's column), a\n * null or missing one left out; null when what was read is no hit (no id, time or type).\n */\nexport const hitRowOf = (read: (field: keyof HitRow) => unknown): HitRow | null => {\n\tconst id = read('id')\n\tconst ts = dateOf(read('ts'))\n\tconst type = read('type')\n\tif (typeof id !== 'string' || ts === null || !isOneOf(HIT_TYPES, type)) {\n\t\treturn null\n\t}\n\tconst text = (field: keyof HitRow): string => {\n\t\tconst value = read(field)\n\t\treturn typeof value === 'string' ? value : ''\n\t}\n\tconst hit: HitRow = {\n\t\tid,\n\t\tscope: text('scope'),\n\t\tts,\n\t\ttype,\n\t\thostname: text('hostname'),\n\t\tpath: text('path'),\n\t\tv: text('v'),\n\t\tlanding: flagOf(read('landing')),\n\t\tserver: flagOf(read('server')),\n\t}\n\tconst lastAt = dateOf(read('lastAt'))\n\tif (lastAt !== null) {\n\t\thit.lastAt = lastAt\n\t}\n\tfor (const field of TEXT_FIELDS) {\n\t\tconst value = read(field)\n\t\tif (typeof value === 'string') {\n\t\t\thit[field] = value\n\t\t}\n\t}\n\tfor (const field of NUMBER_FIELDS) {\n\t\tconst value = optionalNumberOf(read(field))\n\t\tif (value !== undefined) {\n\t\t\thit[field] = value\n\t\t}\n\t}\n\tconst props = jsonOf(read('props'))\n\tif (isRecord(props)) {\n\t\thit.props = props\n\t}\n\tconst goals = completionsOf(read('goals'))\n\tif (goals !== undefined) {\n\t\thit.goals = goals\n\t}\n\tconst impressions = textsOf(read('impressions'))\n\tif (impressions !== undefined) {\n\t\thit.impressions = impressions\n\t}\n\treturn hit\n}\n"],"mappings":";;;AAKA,MAAM,YAAgC;CAAC;CAAY;CAAS;CAAQ;AAAY;;AAGhF,MAAM,cAAc;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,gBAAgB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAM,oBAAoB,UAAuC;CAChE,MAAM,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI;CAC7E,OAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,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AS;CAEd,KAAK,MAAM,SAAS,aAAa;EAChC,MAAM,QAAQ,KAAK,KAAK;EACxB,IAAI,OAAO,UAAU,UACpB,IAAI,SAAS;CAEf;CACA,KAAK,MAAM,SAAS,eAAe;EAClC,MAAM,QAAQ,iBAAiB,KAAK,KAAK,CAAC;EAC1C,IAAI,UAAU,KAAA,GACb,IAAI,SAAS;CAEf;CACA,MAAM,QAAQ,OAAO,KAAK,OAAO,CAAC;CAClC,IAAI,SAAS,KAAK,GACjB,IAAI,QAAQ;CAEb,MAAM,QAAQ,cAAc,KAAK,OAAO,CAAC;CACzC,IAAI,UAAU,KAAA,GACb,IAAI,QAAQ;CAEb,MAAM,cAAc,QAAQ,KAAK,aAAa,CAAC;CAC/C,IAAI,gBAAgB,KAAA,GACnB,IAAI,cAAc;CAEnB,OAAO;AACR"}
1
+ {"version":3,"file":"hitRow.js","names":[],"sources":["../../../src/native/store/hitRow.ts"],"sourcesContent":["import { isOneOf, isRecord } from '../../core/values'\nimport type { GoalCompletion } from '../../goals/match'\nimport { dateOf, jsonOf } from './columnValues'\nimport { HIT_MODES, type HitRow, type HitType } from './types'\n\nconst HIT_TYPES: readonly HitType[] = ['pageview', 'event', 'goal', 'engagement']\n\n/** The optional text fields of a hit. */\nconst TEXT_FIELDS = [\n\t'name',\n\t'ref',\n\t'source',\n\t'channel',\n\t'clickId',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'device',\n\t'browser',\n\t'os',\n\t'currency',\n\t'originalCurrency',\n\t'item',\n] as const satisfies ReadonlyArray<keyof HitRow>\n\n/** The optional number fields of a hit. */\nconst NUMBER_FIELDS = [\n\t'channelVersion',\n\t'durationMs',\n\t'scrollDepth',\n\t'value',\n\t'originalValue',\n\t'conversions',\n\t'revenue',\n] as const satisfies ReadonlyArray<keyof HitRow>\n\n/**\n * A number, or numeric text as node-postgres answers one; a blank string or any other value is\n * absent, where `numberOf` would read a blank as 0.\n */\nconst optionalNumberOf = (value: unknown): number | undefined => {\n\tconst n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value\n\treturn typeof n === 'number' && Number.isFinite(n) ? n : undefined\n}\n\n/** A boolean column: `true` on Postgres and MongoDB, `1` on SQLite. */\nconst flagOf = (value: unknown): boolean => value === true || value === 1\n\nconst completionsOf = (value: unknown): GoalCompletion[] | undefined => {\n\tconst parsed = jsonOf(value)\n\tif (!Array.isArray(parsed)) {\n\t\treturn undefined\n\t}\n\treturn parsed.flatMap((entry): GoalCompletion[] => {\n\t\tif (!isRecord(entry) || typeof entry.slug !== 'string') {\n\t\t\treturn []\n\t\t}\n\t\tconst value = optionalNumberOf(entry.value) ?? 0\n\t\tconst sent = optionalNumberOf(entry.sent)\n\t\treturn [{ slug: entry.slug, value, ...(sent === undefined ? {} : { sent }) }]\n\t})\n}\n\nconst textsOf = (value: unknown): string[] | undefined => {\n\tconst parsed = jsonOf(value)\n\treturn Array.isArray(parsed)\n\t\t? parsed.filter((entry): entry is string => typeof entry === 'string')\n\t\t: undefined\n}\n\n/**\n * A stored hit read back, each field through `read` (a document's own field, or a row's column), a\n * null or missing one left out; null when what was read is no hit (no id, time or type).\n */\nexport const hitRowOf = (read: (field: keyof HitRow) => unknown): HitRow | null => {\n\tconst id = read('id')\n\tconst ts = dateOf(read('ts'))\n\tconst type = read('type')\n\tif (typeof id !== 'string' || ts === null || !isOneOf(HIT_TYPES, type)) {\n\t\treturn null\n\t}\n\tconst text = (field: keyof HitRow): string => {\n\t\tconst value = read(field)\n\t\treturn typeof value === 'string' ? value : ''\n\t}\n\tconst hit: HitRow = {\n\t\tid,\n\t\tscope: text('scope'),\n\t\tts,\n\t\ttype,\n\t\thostname: text('hostname'),\n\t\tpath: text('path'),\n\t\tv: text('v'),\n\t\tlanding: flagOf(read('landing')),\n\t\tserver: flagOf(read('server')),\n\t}\n\tconst lastAt = dateOf(read('lastAt'))\n\tif (lastAt !== null) {\n\t\thit.lastAt = lastAt\n\t}\n\tconst mode = read('mode')\n\tif (isOneOf(HIT_MODES, mode)) {\n\t\thit.mode = mode\n\t}\n\tfor (const field of TEXT_FIELDS) {\n\t\tconst value = read(field)\n\t\tif (typeof value === 'string') {\n\t\t\thit[field] = value\n\t\t}\n\t}\n\tfor (const field of NUMBER_FIELDS) {\n\t\tconst value = optionalNumberOf(read(field))\n\t\tif (value !== undefined) {\n\t\t\thit[field] = value\n\t\t}\n\t}\n\tconst props = jsonOf(read('props'))\n\tif (isRecord(props)) {\n\t\thit.props = props\n\t}\n\tconst goals = completionsOf(read('goals'))\n\tif (goals !== undefined) {\n\t\thit.goals = goals\n\t}\n\tconst impressions = textsOf(read('impressions'))\n\tif (impressions !== undefined) {\n\t\thit.impressions = impressions\n\t}\n\treturn hit\n}\n"],"mappings":";;;;AAKA,MAAM,YAAgC;CAAC;CAAY;CAAS;CAAQ;AAAY;;AAGhF,MAAM,cAAc;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAGA,MAAM,gBAAgB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAM,oBAAoB,UAAuC;CAChE,MAAM,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI;CAC7E,OAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,IAAI,IAAI,KAAA;AAC1D;;AAGA,MAAM,UAAU,UAA4B,UAAU,QAAQ,UAAU;AAExE,MAAM,iBAAiB,UAAiD;CACvE,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,MAAM,QAAQ,MAAM,GACxB;CAED,OAAO,OAAO,SAAS,UAA4B;EAClD,IAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,UAC7C,OAAO,CAAC;EAET,MAAM,QAAQ,iBAAiB,MAAM,KAAK,KAAK;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f;CACA,MAAM,QAAQ,OAAO,KAAK,OAAO,CAAC;CAClC,IAAI,SAAS,KAAK,GACjB,IAAI,QAAQ;CAEb,MAAM,QAAQ,cAAc,KAAK,OAAO,CAAC;CACzC,IAAI,UAAU,KAAA,GACb,IAAI,QAAQ;CAEb,MAAM,cAAc,QAAQ,KAAK,aAAa,CAAC;CAC/C,IAAI,gBAAgB,KAAA,GACnB,IAAI,cAAc;CAEnB,OAAO;AACR"}
@@ -1,4 +1,6 @@
1
1
  //#region src/native/store/hits.ts
2
+ /** The modes a page measures in before or without consent. */
3
+ const WITHOUT_CONSENT_MODES = ["c", "a"];
2
4
  /** The sale a hit records, which the server's record of an order hands to the browser's. */
3
5
  const SALE_FIELDS = [
4
6
  "conversions",
@@ -58,6 +60,6 @@ const TOMBSTONE_CLEARED = [
58
60
  "impressions"
59
61
  ];
60
62
  //#endregion
61
- export { SALE_FIELDS, TOMBSTONE_CLEARED, TWIN_WINDOW_MS, distinctHits, twinsWithin };
63
+ export { SALE_FIELDS, TOMBSTONE_CLEARED, TWIN_WINDOW_MS, WITHOUT_CONSENT_MODES, distinctHits, twinsWithin };
62
64
 
63
65
  //# sourceMappingURL=hits.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hits.js","names":[],"sources":["../../../src/native/store/hits.ts"],"sourcesContent":["import { serverTwinOf, wireTwinOf } from './ids'\nimport type { HitRow } from './types'\n\n/**\n * Hits one statement writes, on every database: a row binds at most 40 values, which keeps a\n * chunk well under the 32,766 parameters SQLite allows.\n */\nexport const HIT_CHUNK = 500\n\n/** The sale a hit records, which the server's record of an order hands to the browser's. */\nexport const SALE_FIELDS: ReadonlyArray<keyof HitRow> = [\n\t'conversions',\n\t'revenue',\n\t'goals',\n\t'value',\n\t'originalValue',\n\t'currency',\n\t'originalCurrency',\n]\n\n/**\n * How far apart an order's browser and server records may lie to count as one sale: a checkout\n * lasts at most a day, and a record forged ahead of a guessed order id must land inside it.\n */\nexport const TWIN_WINDOW_MS = 86_400_000\n\n/** Whether two records of one order are close enough in time to be counted as one sale. */\nexport const twinsWithin = (a: Date, b: Date, windowMs: number | null): boolean =>\n\twindowMs === null || Math.abs(a.getTime() - b.getTime()) <= windowMs\n\n/** Every sale field left out: the browser's record of an order whose sale the server records. */\nconst withoutSale = (wire: HitRow): HitRow => {\n\tconst counted = { ...wire }\n\tfor (const field of SALE_FIELDS) {\n\t\tReflect.deleteProperty(counted, field)\n\t}\n\treturn counted\n}\n\n/**\n * The browser's record of an order, carrying the server's sale in place of its own, and the\n * server's item when it names one. That item came from no page, so it lands on none (`server`).\n */\nconst credited = (wire: HitRow, server: HitRow): HitRow => {\n\tconst counted = withoutSale(wire)\n\tfor (const field of SALE_FIELDS) {\n\t\tconst value = server[field]\n\t\tif (value !== undefined) {\n\t\t\tReflect.set(counted, field, value)\n\t\t}\n\t}\n\treturn server.item === undefined ? counted : { ...counted, item: server.item, server: true }\n}\n\n/**\n * A hit as reads and aggregation count it. An order both sides recorded within `windowMs` is one\n * sale on the browser's record, the server's null; further apart, only the server's keeps a sale.\n */\nexport const countedHit = (\n\thit: HitRow,\n\tstored: ReadonlyMap<string, HitRow>,\n\twindowMs: number | null\n): HitRow | null => {\n\tconst server = serverTwinOf(hit.id)\n\tif (server !== undefined) {\n\t\tconst twin = stored.get(server)\n\t\tif (twin === undefined) {\n\t\t\treturn hit\n\t\t}\n\t\treturn twinsWithin(hit.ts, twin.ts, windowMs) ? credited(hit, twin) : withoutSale(hit)\n\t}\n\tconst wire = wireTwinOf(hit.id)\n\tconst twin = wire === undefined ? undefined : stored.get(wire)\n\treturn twin !== undefined && twinsWithin(hit.ts, twin.ts, windowMs) ? null : hit\n}\n\n/** Every hit as {@link countedHit} counts it, the server's records of orders credited left out. */\nexport const countedHits = (hits: readonly HitRow[], windowMs: number | null): HitRow[] => {\n\tconst stored = new Map(hits.map((hit) => [hit.id, hit]))\n\treturn hits.flatMap((hit) => {\n\t\tconst counted = countedHit(hit, stored, windowMs)\n\t\treturn counted === null ? [] : [counted]\n\t})\n}\n\n/** A call's hits with each id once, the first of a repeated id kept, and how many were left out. */\nexport const distinctHits = (hits: readonly HitRow[]): { unique: HitRow[]; repeated: number } => {\n\tconst seen = new Set<string>()\n\tconst unique: HitRow[] = []\n\tfor (const hit of hits) {\n\t\tif (!seen.has(hit.id)) {\n\t\t\tseen.add(hit.id)\n\t\t\tunique.push(hit)\n\t\t}\n\t}\n\treturn { unique, repeated: hits.length - unique.length }\n}\n\n/**\n * Fields a tombstone clears from an order's record past raw retention (`v` emptied too); its key,\n * scope, time and sale stay, so the order's other record still finds it and counts as it did.\n */\nexport const TOMBSTONE_CLEARED: ReadonlyArray<keyof HitRow> = [\n\t'lastAt',\n\t'ref',\n\t'source',\n\t'channel',\n\t'channelVersion',\n\t'clickId',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'device',\n\t'browser',\n\t'os',\n\t'durationMs',\n\t'scrollDepth',\n\t'props',\n\t'impressions',\n]\n\n/** An order's record as a tombstone: see {@link TOMBSTONE_CLEARED}. */\nexport const tombstoneOf = (hit: HitRow): HitRow => {\n\tconst kept: HitRow = { ...hit, v: '' }\n\tfor (const field of TOMBSTONE_CLEARED) {\n\t\tReflect.deleteProperty(kept, field)\n\t}\n\treturn kept\n}\n\n/** Whether an order's record still holds anything a tombstone clears. */\nexport const holdsVisit = (hit: HitRow): boolean =>\n\thit.v !== '' || TOMBSTONE_CLEARED.some((field) => hit[field] !== undefined)\n"],"mappings":";;AAUA,MAAa,cAA2C;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAa,iBAAiB;;AAG9B,MAAa,eAAe,GAAS,GAAS,aAC7C,aAAa,QAAQ,KAAK,IAAI,EAAE,QAAQ,IAAI,EAAE,QAAQ,CAAC,KAAK;;AA0D7D,MAAa,gBAAgB,SAAoE;CAChG,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,MACjB,IAAI,CAAC,KAAK,IAAI,IAAI,EAAE,GAAG;EACtB,KAAK,IAAI,IAAI,EAAE;EACf,OAAO,KAAK,GAAG;CAChB;CAED,OAAO;EAAE;EAAQ,UAAU,KAAK,SAAS,OAAO;CAAO;AACxD;;;;;AAMA,MAAa,oBAAiD;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
1
+ {"version":3,"file":"hits.js","names":[],"sources":["../../../src/native/store/hits.ts"],"sourcesContent":["import { serverTwinOf, wireTwinOf } from './ids'\nimport type { HitMode, HitRow } from './types'\n\n/**\n * Hits one statement writes, on every database: a row binds at most 41 values, which keeps a\n * chunk well under the 32,766 parameters SQLite allows.\n */\nexport const HIT_CHUNK = 500\n\n/** The modes a page measures in before or without consent. */\nexport const WITHOUT_CONSENT_MODES: readonly HitMode[] = ['c', 'a']\n\n/** Whether a page measured a hit before or without consent; a hit stored before modes was full. */\nexport const isWithoutConsent = (hit: Pick<HitRow, 'mode'>): boolean =>\n\thit.mode !== undefined && WITHOUT_CONSENT_MODES.includes(hit.mode)\n\n/** The sale a hit records, which the server's record of an order hands to the browser's. */\nexport const SALE_FIELDS: ReadonlyArray<keyof HitRow> = [\n\t'conversions',\n\t'revenue',\n\t'goals',\n\t'value',\n\t'originalValue',\n\t'currency',\n\t'originalCurrency',\n]\n\n/**\n * How far apart an order's browser and server records may lie to count as one sale: a checkout\n * lasts at most a day, and a record forged ahead of a guessed order id must land inside it.\n */\nexport const TWIN_WINDOW_MS = 86_400_000\n\n/** Whether two records of one order are close enough in time to be counted as one sale. */\nexport const twinsWithin = (a: Date, b: Date, windowMs: number | null): boolean =>\n\twindowMs === null || Math.abs(a.getTime() - b.getTime()) <= windowMs\n\n/** Every sale field left out: the browser's record of an order whose sale the server records. */\nconst withoutSale = (wire: HitRow): HitRow => {\n\tconst counted = { ...wire }\n\tfor (const field of SALE_FIELDS) {\n\t\tReflect.deleteProperty(counted, field)\n\t}\n\treturn counted\n}\n\n/**\n * The browser's record of an order, carrying the server's sale in place of its own, and the\n * server's item when it names one. That item came from no page, so it lands on none (`server`).\n */\nconst credited = (wire: HitRow, server: HitRow): HitRow => {\n\tconst counted = withoutSale(wire)\n\tfor (const field of SALE_FIELDS) {\n\t\tconst value = server[field]\n\t\tif (value !== undefined) {\n\t\t\tReflect.set(counted, field, value)\n\t\t}\n\t}\n\treturn server.item === undefined ? counted : { ...counted, item: server.item, server: true }\n}\n\n/**\n * A hit as reads and aggregation count it. An order both sides recorded within `windowMs` is one\n * sale on the browser's record, the server's null; further apart, only the server's keeps a sale.\n */\nexport const countedHit = (\n\thit: HitRow,\n\tstored: ReadonlyMap<string, HitRow>,\n\twindowMs: number | null\n): HitRow | null => {\n\tconst server = serverTwinOf(hit.id)\n\tif (server !== undefined) {\n\t\tconst twin = stored.get(server)\n\t\tif (twin === undefined) {\n\t\t\treturn hit\n\t\t}\n\t\treturn twinsWithin(hit.ts, twin.ts, windowMs) ? credited(hit, twin) : withoutSale(hit)\n\t}\n\tconst wire = wireTwinOf(hit.id)\n\tconst twin = wire === undefined ? undefined : stored.get(wire)\n\treturn twin !== undefined && twinsWithin(hit.ts, twin.ts, windowMs) ? null : hit\n}\n\n/** Every hit as {@link countedHit} counts it, the server's records of orders credited left out. */\nexport const countedHits = (hits: readonly HitRow[], windowMs: number | null): HitRow[] => {\n\tconst stored = new Map(hits.map((hit) => [hit.id, hit]))\n\treturn hits.flatMap((hit) => {\n\t\tconst counted = countedHit(hit, stored, windowMs)\n\t\treturn counted === null ? [] : [counted]\n\t})\n}\n\n/** A call's hits with each id once, the first of a repeated id kept, and how many were left out. */\nexport const distinctHits = (hits: readonly HitRow[]): { unique: HitRow[]; repeated: number } => {\n\tconst seen = new Set<string>()\n\tconst unique: HitRow[] = []\n\tfor (const hit of hits) {\n\t\tif (!seen.has(hit.id)) {\n\t\t\tseen.add(hit.id)\n\t\t\tunique.push(hit)\n\t\t}\n\t}\n\treturn { unique, repeated: hits.length - unique.length }\n}\n\n/**\n * Fields a tombstone clears from an order's record past raw retention (`v` emptied too); its key,\n * scope, time and sale stay, so the order's other record still finds it and counts as it did.\n */\nexport const TOMBSTONE_CLEARED: ReadonlyArray<keyof HitRow> = [\n\t'lastAt',\n\t'ref',\n\t'source',\n\t'channel',\n\t'channelVersion',\n\t'clickId',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'device',\n\t'browser',\n\t'os',\n\t'durationMs',\n\t'scrollDepth',\n\t'props',\n\t'impressions',\n]\n\n/** An order's record as a tombstone: see {@link TOMBSTONE_CLEARED}. */\nexport const tombstoneOf = (hit: HitRow): HitRow => {\n\tconst kept: HitRow = { ...hit, v: '' }\n\tfor (const field of TOMBSTONE_CLEARED) {\n\t\tReflect.deleteProperty(kept, field)\n\t}\n\treturn kept\n}\n\n/** Whether an order's record still holds anything a tombstone clears. */\nexport const holdsVisit = (hit: HitRow): boolean =>\n\thit.v !== '' || TOMBSTONE_CLEARED.some((field) => hit[field] !== undefined)\n"],"mappings":";;AAUA,MAAa,wBAA4C,CAAC,KAAK,GAAG;;AAOlE,MAAa,cAA2C;CACvD;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAa,iBAAiB;;AAG9B,MAAa,eAAe,GAAS,GAAS,aAC7C,aAAa,QAAQ,KAAK,IAAI,EAAE,QAAQ,IAAI,EAAE,QAAQ,CAAC,KAAK;;AA0D7D,MAAa,gBAAgB,SAAoE;CAChG,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,OAAO,MACjB,IAAI,CAAC,KAAK,IAAI,IAAI,EAAE,GAAG;EACtB,KAAK,IAAI,IAAI,EAAE;EACf,OAAO,KAAK,GAAG;CAChB;CAED,OAAO;EAAE;EAAQ,UAAU,KAAK,SAAS,OAAO;CAAO;AACxD;;;;;AAMA,MAAa,oBAAiD;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
@@ -34,7 +34,13 @@ const VISIT_PARTS = {
34
34
  conversions: "$v_conv",
35
35
  revenue: "$v_rev",
36
36
  impressions: 0,
37
- interactions: "$v_int"
37
+ interactions: "$v_int",
38
+ pageviewsWithoutVisitor: { $cond: [
39
+ { $eq: ["$v", ""] },
40
+ "$s_pv",
41
+ 0
42
+ ] },
43
+ pageviewsWithoutConsent: "$v_npc"
38
44
  };
39
45
  /** What one item clicked (`impressions` 0) or seen (1) adds; parts an item never counts are 0. */
40
46
  const itemParts = (seen) => ({
@@ -51,7 +57,9 @@ const itemParts = (seen) => ({
51
57
  conversions: { $ifNull: ["$conversions", 0] },
52
58
  revenue: { $ifNull: ["$revenue", 0] },
53
59
  impressions: seen,
54
- interactions: one(isItemClick)
60
+ interactions: one(isItemClick),
61
+ pageviewsWithoutVisitor: 0,
62
+ pageviewsWithoutConsent: 0
55
63
  });
56
64
  const fact = (kind, values, parts) => ({
57
65
  k: kind.index,
@@ -1 +1 @@
1
- {"version":3,"file":"aggregatePipelines.js","names":[],"sources":["../../../../src/native/store/mongo/aggregatePipelines.ts"],"sourcesContent":["import {\n\ttype AggregateKind,\n\ttype AggregatePlan,\n\tKIND_DIMS,\n\tKIND_DIMS2,\n\tkindsWritten,\n} from '../aggregate'\nimport { type CardinalityCaps, UNKNOWN_WHEN_FOLDED } from '../caps'\nimport { type MetricParts, PART_KEYS } from '../parts'\nimport { KEPT_PARTS, SESSION_ATTRIBUTES } from '../rawRead'\nimport type { DayWindow, FoldRead, TimeWindow } from '../types'\nimport {\n\tcompletionConverts,\n\tHIT_PARTS,\n\thitsWithTwins,\n\tisInteraction,\n\tisItemClick,\n\tone,\n\torderStages,\n\ttype Parts,\n\tprojection,\n\ttype Stage,\n\tscopeMatch,\n\ttype TwinLookup,\n\tvisitStages,\n\twindowMatch,\n} from './pipelines'\n\n/** A field holding a string other than `''`; missing and null fields hold none. */\nconst nonEmpty = (field: string): Record<string, unknown> => ({\n\t$and: [{ $eq: [{ $type: field }, 'string'] }, { $ne: [field, ''] }],\n})\n\n/** A `$group`'s `$sum` of each of `parts`, read from the field `${from}${part}`. */\nconst sumsOf = (parts: ReadonlyArray<keyof MetricParts>, from = '$'): Record<string, unknown> =>\n\tObject.fromEntries(parts.map((part) => [part, { $sum: `${from}${part}` }]))\n\n/** What one hit adds to its currency's row: its revenue as sent. */\nconst SENT_PARTS: Parts = { ...HIT_PARTS, revenue: { $ifNull: ['$sentRevenue', 0] } }\n\n/** What one goal completion (`$$this` of the goals) adds; a refund's counts no conversion. */\nconst GOAL_PARTS: Parts = {\n\t...HIT_PARTS,\n\tconversions: completionConverts,\n\trevenue: { $ifNull: ['$$this.value', 0] },\n}\n\n/** What one visit adds to a visit kind, read off its representative hit. */\nconst VISIT_PARTS: Parts = {\n\tpageviews: '$s_pv',\n\tevents: '$s_int',\n\tvisitors: one({ $and: [{ $eq: ['$v_act', 1] }, { $ne: ['$v', ''] }] }),\n\tsessions: one({ $and: [{ $eq: ['$v_act', 1] }, { $ne: ['$sn', null] }] }),\n\tentries: '$entry',\n\tbounces: '$bounce',\n\tsessionMs: '$s_ms',\n\tdurationMs: '$s_ms',\n\tscrollSum: '$v_ss',\n\tscrollSamples: '$v_sc',\n\tconversions: '$v_conv',\n\trevenue: '$v_rev',\n\timpressions: 0,\n\tinteractions: '$v_int',\n}\n\n/** What one item clicked (`impressions` 0) or seen (1) adds; parts an item never counts are 0. */\nconst itemParts = (seen: 0 | 1): Parts => ({\n\tpageviews: 0,\n\tevents: one(isInteraction),\n\tvisitors: one({ $ne: ['$v', ''] }),\n\tsessions: 0,\n\tentries: 0,\n\tbounces: 0,\n\tsessionMs: 0,\n\tdurationMs: 0,\n\tscrollSum: 0,\n\tscrollSamples: 0,\n\tconversions: { $ifNull: ['$conversions', 0] },\n\trevenue: { $ifNull: ['$revenue', 0] },\n\timpressions: seen,\n\tinteractions: one(isItemClick),\n})\n\nconst fact = (kind: AggregateKind, values: [unknown, unknown], parts: Parts): object => ({\n\tk: kind.index,\n\ta: values[0],\n\tb: values[1],\n\t...parts,\n})\n\n/** `[fact]` when `test` holds, else no fact. */\nconst factIf = (test: unknown, made: object): object => ({ $cond: [test, [made], []] })\n\n/** A visit kind's fact: one per visit already, so its visits are counted as they come (`once`). */\nconst visitFact = (kind: AggregateKind, value: unknown): object => ({\n\t...fact(kind, [value, ''], VISIT_PARTS),\n\tonce: 1,\n})\n\nconst visitFacts = (kinds: readonly AggregateKind[]): object => ({\n\t$concatArrays: kinds.map((kind) => {\n\t\tif (kind.source.from !== 'visit') {\n\t\t\treturn [visitFact(kind, '')]\n\t\t}\n\t\tconst field = `$e_${kind.source.attribute}`\n\t\treturn factIf(nonEmpty(field), visitFact(kind, field))\n\t}),\n})\n\n/** The field each hit kind's value is read from: a currency's row is keyed by the currency sent in. */\nconst HIT_FIELDS = { path: '$path', name: '$name', currency: '$sentCurrency' } as const\n\n/** Hit kinds' facts: a name's on events alone, a currency's with its revenue as sent. */\nconst hitFacts = (kinds: readonly AggregateKind[]): object[] =>\n\tkinds.flatMap((kind) => {\n\t\tif (kind.source.from !== 'hit') {\n\t\t\treturn []\n\t\t}\n\t\tconst field = HIT_FIELDS[kind.source.field]\n\t\tconst test =\n\t\t\tkind.source.field === 'name'\n\t\t\t\t? { $and: [{ $eq: ['$type', 'event'] }, nonEmpty(field)] }\n\t\t\t\t: nonEmpty(field)\n\t\tconst parts = kind.source.field === 'currency' ? SENT_PARTS : HIT_PARTS\n\t\treturn [factIf(test, fact(kind, [field, ''], parts))]\n\t})\n\nconst goalFacts = (kinds: readonly AggregateKind[]): object => ({\n\t$reduce: {\n\t\tinput: '$goals',\n\t\tinitialValue: [],\n\t\tin: {\n\t\t\t$concatArrays: [\n\t\t\t\t'$$value',\n\t\t\t\t{\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\tnonEmpty('$$this.slug'),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$concatArrays: kinds.map((kind) => {\n\t\t\t\t\t\t\t\tif (kind.source.from !== 'goal' || kind.source.attribute === null) {\n\t\t\t\t\t\t\t\t\treturn [fact(kind, ['$$this.slug', ''], GOAL_PARTS)]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst field = `$e_${kind.source.attribute}`\n\t\t\t\t\t\t\t\treturn factIf(nonEmpty(field), fact(kind, ['$$this.slug', field], GOAL_PARTS))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[],\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t},\n})\n\n/** Each item kind's facts of `ref`, the item clicked or seen; server hits get no page row. */\nconst itemFacts = (kinds: readonly AggregateKind[], ref: string, seen: 0 | 1): object => ({\n\t$concatArrays: kinds.map((kind) =>\n\t\tkind.source.from === 'item' && kind.source.page\n\t\t\t? factIf(\n\t\t\t\t\t{ $and: [{ $ne: ['$server', true] }, nonEmpty('$path')] },\n\t\t\t\t\tfact(kind, [ref, '$path'], itemParts(seen))\n\t\t\t\t)\n\t\t\t: [fact(kind, [ref, ''], itemParts(seen))]\n\t),\n})\n\n/** Each additive part of the facts summed; a fold counts visitors and visits distinct instead. */\nconst FACT_SUMS = sumsOf(\n\tPART_KEYS.filter((part) => part !== 'visitors' && part !== 'sessions' && part !== 'sessionMs'),\n\t'$facts.'\n)\n\nconst isOnce = { $eq: ['$facts.once', 1] }\nconst isSession = { $eq: ['$facts.sessions', 1] }\n\n/**\n * Hits up to which a day always folds in sets: under 56 bytes per hit keeps a row's two sets under\n * 16 MB. A bigger day folds in sets too, and per visitor when a set outgrows its limit.\n */\nexport const SET_FOLD_HITS = 150_000\n\n/**\n * Facts straight into rows, visitors and visits as sets (a visit kind's visits come one fact each):\n * the fast fold, safe up to {@link SET_FOLD_HITS} hits.\n */\nconst setFold: Stage[] = [\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$facts.k', a: '$facts.a', b: '$facts.b', h: '$h' },\n\t\t\tpeople: {\n\t\t\t\t$addToSet: { $cond: [{ $eq: ['$facts.visitors', 1] }, '$v', '$$REMOVE'] },\n\t\t\t},\n\t\t\tvisits: {\n\t\t\t\t$addToSet: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $and: [isSession, { $ne: ['$facts.once', 1] }] },\n\t\t\t\t\t\t{ v: '$v', n: '$n', ms: '$facts.sessionMs' },\n\t\t\t\t\t\t'$$REMOVE',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t\tonce: { $sum: { $cond: [isOnce, '$facts.sessions', 0] } },\n\t\t\tonceMs: { $sum: { $cond: [{ $and: [isOnce, isSession] }, '$facts.sessionMs', 0] } },\n\t\t\t...FACT_SUMS,\n\t\t},\n\t},\n\t{\n\t\t$set: {\n\t\t\tvisitors: { $size: '$people' },\n\t\t\tsessions: { $add: ['$once', { $size: '$visits' }] },\n\t\t\tsessionMs: { $add: ['$onceMs', { $sum: '$visits.ms' }] },\n\t\t},\n\t},\n\t{ $unset: ['people', 'visits', 'once', 'onceMs'] },\n]\n\n/**\n * Facts per visitor, then per row: each visitor's own visits in a set, never more than one\n * visitor's day. Slower than {@link setFold}, and bounded by nothing but the disk.\n */\nconst visitorFold: Stage[] = [\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$facts.k', a: '$facts.a', b: '$facts.b', h: '$h', v: '$v' },\n\t\t\tvisitors: { $max: '$facts.visitors' },\n\t\t\tvisits: {\n\t\t\t\t$addToSet: { $cond: [isSession, { n: '$n', ms: '$facts.sessionMs' }, '$$REMOVE'] },\n\t\t\t},\n\t\t\t...FACT_SUMS,\n\t\t},\n\t},\n\t{ $set: { sessions: { $size: '$visits' }, sessionMs: { $sum: '$visits.ms' } } },\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$_id.k', a: '$_id.a', b: '$_id.b', h: '$_id.h' },\n\t\t\t...sumsOf(PART_KEYS),\n\t\t},\n\t},\n]\n\n/**\n * `capDay` in the pipeline: rows ranked within their cap's group, those past the cap folded into\n * its `(other)` row (`_id.o` 1), so a day answers at most the caps however many values it holds.\n */\nconst rankAndFold = (kinds: readonly AggregateKind[], caps: CardinalityCaps): Stage[] => {\n\tconst capped = kinds.flatMap((kind): Array<[number, number]> => {\n\t\tconst cap = kind.cap === null ? null : caps[kind.cap]\n\t\treturn cap === null ? [] : [[kind.index, cap]]\n\t})\n\tif (capped.length === 0) {\n\t\treturn []\n\t}\n\tconst capOf = capped.reduceRight<unknown>(\n\t\t(otherwise, [index, cap]) => ({ $cond: [{ $eq: ['$_id.k', index] }, cap, otherwise] }),\n\t\tnull\n\t)\n\tconst pairs = kinds.filter((kind) => kind.dim2 !== '').map((kind) => kind.index)\n\tconst items = kinds.filter((kind) => kind.source.from === 'item').map((kind) => kind.index)\n\tconst group = { $cond: [{ $in: ['$_id.k', pairs] }, '$_id.a', ''] }\n\treturn [\n\t\t{\n\t\t\t$set: {\n\t\t\t\tviews: { $cond: [{ $in: ['$_id.k', items] }, '$impressions', '$pageviews'] },\n\t\t\t\tcap: capOf,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: { k: '$_id.k', h: '$_id.h', a: group },\n\t\t\t\tsortBy: { views: -1, events: -1, '_id.a': 1, '_id.b': 1 },\n\t\t\t\t// A running count, as `$documentNumber` takes one sort key alone.\n\t\t\t\toutput: { rn: { $sum: 1, window: { documents: ['unbounded', 'current'] } } },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\to: one({ $and: [{ $ne: ['$cap', null] }, { $gt: ['$rn', '$cap'] }] }),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: {\n\t\t\t\t\tk: '$_id.k',\n\t\t\t\t\ta: { $cond: ['$o', group, '$_id.a'] },\n\t\t\t\t\tb: { $cond: ['$o', '', '$_id.b'] },\n\t\t\t\t\th: '$_id.h',\n\t\t\t\t\to: '$o',\n\t\t\t\t},\n\t\t\t\t...sumsOf(PART_KEYS),\n\t\t\t},\n\t\t},\n\t]\n}\n\n/**\n * A day's count in one pipeline: the visit chain, every hit's facts, a fold, then the caps (see\n * {@link rankAndFold}); an order both sides recorded counts once (`twinStages`). Uses disk.\n */\nexport const dayAggregationPipeline = (\n\twindow: TimeWindow,\n\toptions: {\n\t\titemPages: boolean\n\t\tfold: 'sets' | 'visitors'\n\t\ttwins: TwinLookup\n\t\tcaps: CardinalityCaps\n\t}\n): Stage[] => {\n\tconst kinds = kindsWritten(options.itemPages)\n\tconst of = (from: string) => kinds.filter((kind) => kind.source.from === from)\n\tconst items = of('item')\n\treturn [\n\t\t...hitsWithTwins(windowMatch(window), options.twins),\n\t\tprojection({\n\t\t\tsessionize: true,\n\t\t\tattributes: SESSION_ATTRIBUTES,\n\t\t\tgoals: true,\n\t\t\timpressions: true,\n\t\t\tsent: true,\n\t\t}),\n\t\t...visitStages({ sums: true, attributes: SESSION_ATTRIBUTES, attributedOnly: true }),\n\t\t{\n\t\t\t$set: {\n\t\t\t\tfacts: {\n\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t{ $cond: [{ $eq: ['$rep', 1] }, visitFacts([...of('site'), ...of('visit')]), []] },\n\t\t\t\t\t\t...hitFacts(of('hit')),\n\t\t\t\t\t\tgoalFacts(of('goal')),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $and: [{ $eq: ['$eng', 0] }, nonEmpty('$item')] },\n\t\t\t\t\t\t\t\titemFacts(items, '$item', 0),\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$eng', 1] },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$reduce: {\n\t\t\t\t\t\t\t\t\t\tinput: '$impressions',\n\t\t\t\t\t\t\t\t\t\tinitialValue: [],\n\t\t\t\t\t\t\t\t\t\tin: {\n\t\t\t\t\t\t\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t\t\t\t\t\t\t'$$value',\n\t\t\t\t\t\t\t\t\t\t\t\t{ $cond: [nonEmpty('$$this'), itemFacts(items, '$$this', 1), []] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ $project: { _id: 0, h: '$hostname', v: 1, n: '$sn', facts: 1 } },\n\t\t{ $unwind: '$facts' },\n\t\t...(options.fold === 'sets' ? setFold : visitorFold),\n\t\t...rankAndFold(kinds, options.caps),\n\t]\n}\n\n/** How many hits a day's window holds. */\nexport const dayHitsPipeline = (window: TimeWindow): Stage[] => [\n\t{ $match: windowMatch(window) },\n\t{ $count: 'n' },\n]\n\n/** One day's rows of every kind, as its `dim` and `dim2` values bound the aggregates index. */\nexport const dayRowsFilter = (\n\twindow: Pick<DayWindow, 'scope' | 'day'>\n): Record<string, unknown> => ({\n\tscope: window.scope,\n\tday: window.day,\n\tdim: { $in: [...KIND_DIMS] },\n\tdim2: { $in: [...KIND_DIMS2] },\n})\n\n/**\n * Ranges of days as one bound an index serves, with the ranges themselves where there are several.\n * Throws for no range, which every read checked before already refuses.\n */\nexport const daysMatch = (\n\tdays: ReadonlyArray<readonly [number, number]>\n): Record<string, unknown> => {\n\tconst [first] = days\n\tif (first === undefined) {\n\t\tthrow new Error('analytics: a read of days needs at least one range of them')\n\t}\n\tconst from = Math.min(...days.map(([start]) => start))\n\tconst to = Math.max(...days.map(([, end]) => end))\n\treturn days.length === 1\n\t\t? { day: { $gte: from, $lte: to } }\n\t\t: {\n\t\t\t\tday: { $gte: from, $lte: to },\n\t\t\t\t$or: days.map(([start, end]) => ({ day: { $gte: start, $lte: end } })),\n\t\t\t}\n}\n\n/**\n * A fold read's rows: the value's and its `(other)` row, or a pair's `(other)` rows. A generation\n * is one run's of one day, so matching the markers' generations alone is exact.\n */\nexport const foldReadPipeline = (\n\tread: FoldRead,\n\tkind: AggregateKind,\n\tgens: readonly string[]\n): Stage[] => [\n\t{\n\t\t$match: {\n\t\t\tscope: read.scope,\n\t\t\tdim: kind.dim,\n\t\t\tdim2: kind.dim2,\n\t\t\t...(read.hostname === undefined ? {} : { hostname: read.hostname }),\n\t\t\t...(kind.dim2 === ''\n\t\t\t\t? { value: { $in: [read.value, ''] } }\n\t\t\t\t: { value: read.value, value2: '' }),\n\t\t\t...daysMatch(read.days),\n\t\t\tgen: { $in: [...gens] },\n\t\t},\n\t},\n\t{ $project: { _id: 0, day: 1, hostname: 1, value: 1, value2: 1 } },\n]\n\n/**\n * Completed days' rows of the days' generations (see {@link foldReadPipeline}), summed, filtered,\n * ranked and cut in the database; a sum is null where no row counted its part.\n */\nexport const aggregateReadPipeline = (plan: AggregatePlan, gens: readonly string[]): Stage[] => {\n\tconst { read, kind } = plan\n\tconst grouped = plan.group === null ? null : `$${plan.group}`\n\tconst valueGroup = plan.group === 'value' || plan.group === 'value2' ? plan.group : null\n\tconst match: Record<string, unknown> = {\n\t\t...scopeMatch(read),\n\t\tdim: kind.dim,\n\t\tdim2: kind.dim2,\n\t\t...(read.hostname === undefined ? {} : { hostname: read.hostname }),\n\t\t...(read.value === undefined ? {} : { value: read.value }),\n\t\t...(read.values === undefined || valueGroup === null\n\t\t\t? {}\n\t\t\t: { [valueGroup]: { $in: [...read.values] } }),\n\t\t...daysMatch(read.days),\n\t\tgen: { $in: [...gens] },\n\t\t// An `(other)` row folds many values together: it is part of a total, never a value. Under\n\t\t// `$and`, so it joins an `$in` on the same field rather than replacing it.\n\t\t...(valueGroup === null ? {} : { $and: [{ [valueGroup]: { $ne: '' } }] }),\n\t}\n\tconst counted = PART_KEYS.filter((part) => kind.counted.has(part))\n\t// The only counted parts a stored row holds as null, so the only sums told apart from 0.\n\tconst unknowable = counted.filter((part) => UNKNOWN_WHEN_FOLDED.includes(part))\n\tconst stages: Stage[] = [\n\t\t{ $match: match },\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: grouped,\n\t\t\t\t...sumsOf(counted),\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tunknowable.map((part) => [`${part}_n`, { $sum: one({ $isNumber: `$${part}` }) }])\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: Object.fromEntries([\n\t\t\t\t...unknowable.map((part) => [\n\t\t\t\t\tpart,\n\t\t\t\t\t{ $cond: [{ $gt: [`$${part}_n`, 0] }, `$${part}`, null] },\n\t\t\t\t]),\n\t\t\t\t...PART_KEYS.filter((part) => !kind.counted.has(part)).map((part) => [part, null]),\n\t\t\t]),\n\t\t},\n\t\t...(unknowable.length > 0 ? [{ $unset: unknowable.map((part) => `${part}_n`) }] : []),\n\t]\n\tif (plan.group !== null) {\n\t\tstages.push({\n\t\t\t$match: {\n\t\t\t\t$expr: {\n\t\t\t\t\t$gt: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$add: KEPT_PARTS.map((part) => ({\n\t\t\t\t\t\t\t\t$ifNull: [`$${part}`, 0],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t0,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\tconst ties: Record<string, 1> = plan.group === null ? {} : { _id: 1 }\n\treturn [...stages, ...orderStages(read, kind.counted, ties)]\n}\n"],"mappings":";;;;;;;AA6BA,MAAM,YAAY,WAA4C,EAC7D,MAA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;GAAG,IAAI;GAAQ;EAAI,EAAE,CACzD,CAAC,GACD,GAAG,UAAU,QAAQ,SAAS,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE,KAAK,SAAS,CAAC,MAAM,IAAI,CAAC,CAClF,CAAC,EACF;EACA,GAAI,WAAW,SAAS,IAAI,CAAC,EAAE,QAAQ,WAAW,KAAK,SAAS,GAAG,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC;CACpF;CACA,IAAI,KAAK,UAAU,MAClB,OAAO,KAAK,EACX,QAAQ,EACP,OAAO,EACN,KAAK,CACJ,EACC,MAAM,WAAW,KAAK,UAAU,EAC/B,SAAS,CAAC,IAAI,QAAQ,CAAC,EACxB,EAAE,EACH,GACA,CACD,EACD,EACD,EACD,CAAC;CAEF,MAAM,OAA0B,KAAK,UAAU,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE;CACpE,OAAO,CAAC,GAAG,QAAQ,GAAG,YAAY,MAAM,KAAK,SAAS,IAAI,CAAC;AAC5D"}
1
+ {"version":3,"file":"aggregatePipelines.js","names":[],"sources":["../../../../src/native/store/mongo/aggregatePipelines.ts"],"sourcesContent":["import {\n\ttype AggregateKind,\n\ttype AggregatePlan,\n\tKIND_DIMS,\n\tKIND_DIMS2,\n\tkindsWritten,\n} from '../aggregate'\nimport { type CardinalityCaps, UNKNOWN_WHEN_FOLDED } from '../caps'\nimport { type MetricParts, PART_KEYS } from '../parts'\nimport { KEPT_PARTS, SESSION_ATTRIBUTES } from '../rawRead'\nimport type { DayWindow, FoldRead, TimeWindow } from '../types'\nimport {\n\tcompletionConverts,\n\tHIT_PARTS,\n\thitsWithTwins,\n\tisInteraction,\n\tisItemClick,\n\tone,\n\torderStages,\n\ttype Parts,\n\tprojection,\n\ttype Stage,\n\tscopeMatch,\n\ttype TwinLookup,\n\tvisitStages,\n\twindowMatch,\n} from './pipelines'\n\n/** A field holding a string other than `''`; missing and null fields hold none. */\nconst nonEmpty = (field: string): Record<string, unknown> => ({\n\t$and: [{ $eq: [{ $type: field }, 'string'] }, { $ne: [field, ''] }],\n})\n\n/** A `$group`'s `$sum` of each of `parts`, read from the field `${from}${part}`. */\nconst sumsOf = (parts: ReadonlyArray<keyof MetricParts>, from = '$'): Record<string, unknown> =>\n\tObject.fromEntries(parts.map((part) => [part, { $sum: `${from}${part}` }]))\n\n/** What one hit adds to its currency's row: its revenue as sent. */\nconst SENT_PARTS: Parts = { ...HIT_PARTS, revenue: { $ifNull: ['$sentRevenue', 0] } }\n\n/** What one goal completion (`$$this` of the goals) adds; a refund's counts no conversion. */\nconst GOAL_PARTS: Parts = {\n\t...HIT_PARTS,\n\tconversions: completionConverts,\n\trevenue: { $ifNull: ['$$this.value', 0] },\n}\n\n/** What one visit adds to a visit kind, read off its representative hit. */\nconst VISIT_PARTS: Parts = {\n\tpageviews: '$s_pv',\n\tevents: '$s_int',\n\tvisitors: one({ $and: [{ $eq: ['$v_act', 1] }, { $ne: ['$v', ''] }] }),\n\tsessions: one({ $and: [{ $eq: ['$v_act', 1] }, { $ne: ['$sn', null] }] }),\n\tentries: '$entry',\n\tbounces: '$bounce',\n\tsessionMs: '$s_ms',\n\tdurationMs: '$s_ms',\n\tscrollSum: '$v_ss',\n\tscrollSamples: '$v_sc',\n\tconversions: '$v_conv',\n\trevenue: '$v_rev',\n\timpressions: 0,\n\tinteractions: '$v_int',\n\tpageviewsWithoutVisitor: { $cond: [{ $eq: ['$v', ''] }, '$s_pv', 0] },\n\tpageviewsWithoutConsent: '$v_npc',\n}\n\n/** What one item clicked (`impressions` 0) or seen (1) adds; parts an item never counts are 0. */\nconst itemParts = (seen: 0 | 1): Parts => ({\n\tpageviews: 0,\n\tevents: one(isInteraction),\n\tvisitors: one({ $ne: ['$v', ''] }),\n\tsessions: 0,\n\tentries: 0,\n\tbounces: 0,\n\tsessionMs: 0,\n\tdurationMs: 0,\n\tscrollSum: 0,\n\tscrollSamples: 0,\n\tconversions: { $ifNull: ['$conversions', 0] },\n\trevenue: { $ifNull: ['$revenue', 0] },\n\timpressions: seen,\n\tinteractions: one(isItemClick),\n\tpageviewsWithoutVisitor: 0,\n\tpageviewsWithoutConsent: 0,\n})\n\nconst fact = (kind: AggregateKind, values: [unknown, unknown], parts: Parts): object => ({\n\tk: kind.index,\n\ta: values[0],\n\tb: values[1],\n\t...parts,\n})\n\n/** `[fact]` when `test` holds, else no fact. */\nconst factIf = (test: unknown, made: object): object => ({ $cond: [test, [made], []] })\n\n/** A visit kind's fact: one per visit already, so its visits are counted as they come (`once`). */\nconst visitFact = (kind: AggregateKind, value: unknown): object => ({\n\t...fact(kind, [value, ''], VISIT_PARTS),\n\tonce: 1,\n})\n\nconst visitFacts = (kinds: readonly AggregateKind[]): object => ({\n\t$concatArrays: kinds.map((kind) => {\n\t\tif (kind.source.from !== 'visit') {\n\t\t\treturn [visitFact(kind, '')]\n\t\t}\n\t\tconst field = `$e_${kind.source.attribute}`\n\t\treturn factIf(nonEmpty(field), visitFact(kind, field))\n\t}),\n})\n\n/** The field each hit kind's value is read from: a currency's row is keyed by the currency sent in. */\nconst HIT_FIELDS = { path: '$path', name: '$name', currency: '$sentCurrency' } as const\n\n/** Hit kinds' facts: a name's on events alone, a currency's with its revenue as sent. */\nconst hitFacts = (kinds: readonly AggregateKind[]): object[] =>\n\tkinds.flatMap((kind) => {\n\t\tif (kind.source.from !== 'hit') {\n\t\t\treturn []\n\t\t}\n\t\tconst field = HIT_FIELDS[kind.source.field]\n\t\tconst test =\n\t\t\tkind.source.field === 'name'\n\t\t\t\t? { $and: [{ $eq: ['$type', 'event'] }, nonEmpty(field)] }\n\t\t\t\t: nonEmpty(field)\n\t\tconst parts = kind.source.field === 'currency' ? SENT_PARTS : HIT_PARTS\n\t\treturn [factIf(test, fact(kind, [field, ''], parts))]\n\t})\n\nconst goalFacts = (kinds: readonly AggregateKind[]): object => ({\n\t$reduce: {\n\t\tinput: '$goals',\n\t\tinitialValue: [],\n\t\tin: {\n\t\t\t$concatArrays: [\n\t\t\t\t'$$value',\n\t\t\t\t{\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\tnonEmpty('$$this.slug'),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$concatArrays: kinds.map((kind) => {\n\t\t\t\t\t\t\t\tif (kind.source.from !== 'goal' || kind.source.attribute === null) {\n\t\t\t\t\t\t\t\t\treturn [fact(kind, ['$$this.slug', ''], GOAL_PARTS)]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst field = `$e_${kind.source.attribute}`\n\t\t\t\t\t\t\t\treturn factIf(nonEmpty(field), fact(kind, ['$$this.slug', field], GOAL_PARTS))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t[],\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t},\n})\n\n/** Each item kind's facts of `ref`, the item clicked or seen; server hits get no page row. */\nconst itemFacts = (kinds: readonly AggregateKind[], ref: string, seen: 0 | 1): object => ({\n\t$concatArrays: kinds.map((kind) =>\n\t\tkind.source.from === 'item' && kind.source.page\n\t\t\t? factIf(\n\t\t\t\t\t{ $and: [{ $ne: ['$server', true] }, nonEmpty('$path')] },\n\t\t\t\t\tfact(kind, [ref, '$path'], itemParts(seen))\n\t\t\t\t)\n\t\t\t: [fact(kind, [ref, ''], itemParts(seen))]\n\t),\n})\n\n/** Each additive part of the facts summed; a fold counts visitors and visits distinct instead. */\nconst FACT_SUMS = sumsOf(\n\tPART_KEYS.filter((part) => part !== 'visitors' && part !== 'sessions' && part !== 'sessionMs'),\n\t'$facts.'\n)\n\nconst isOnce = { $eq: ['$facts.once', 1] }\nconst isSession = { $eq: ['$facts.sessions', 1] }\n\n/**\n * Hits up to which a day always folds in sets: under 56 bytes per hit keeps a row's two sets under\n * 16 MB. A bigger day folds in sets too, and per visitor when a set outgrows its limit.\n */\nexport const SET_FOLD_HITS = 150_000\n\n/**\n * Facts straight into rows, visitors and visits as sets (a visit kind's visits come one fact each):\n * the fast fold, safe up to {@link SET_FOLD_HITS} hits.\n */\nconst setFold: Stage[] = [\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$facts.k', a: '$facts.a', b: '$facts.b', h: '$h' },\n\t\t\tpeople: {\n\t\t\t\t$addToSet: { $cond: [{ $eq: ['$facts.visitors', 1] }, '$v', '$$REMOVE'] },\n\t\t\t},\n\t\t\tvisits: {\n\t\t\t\t$addToSet: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $and: [isSession, { $ne: ['$facts.once', 1] }] },\n\t\t\t\t\t\t{ v: '$v', n: '$n', ms: '$facts.sessionMs' },\n\t\t\t\t\t\t'$$REMOVE',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t\tonce: { $sum: { $cond: [isOnce, '$facts.sessions', 0] } },\n\t\t\tonceMs: { $sum: { $cond: [{ $and: [isOnce, isSession] }, '$facts.sessionMs', 0] } },\n\t\t\t...FACT_SUMS,\n\t\t},\n\t},\n\t{\n\t\t$set: {\n\t\t\tvisitors: { $size: '$people' },\n\t\t\tsessions: { $add: ['$once', { $size: '$visits' }] },\n\t\t\tsessionMs: { $add: ['$onceMs', { $sum: '$visits.ms' }] },\n\t\t},\n\t},\n\t{ $unset: ['people', 'visits', 'once', 'onceMs'] },\n]\n\n/**\n * Facts per visitor, then per row: each visitor's own visits in a set, never more than one\n * visitor's day. Slower than {@link setFold}, and bounded by nothing but the disk.\n */\nconst visitorFold: Stage[] = [\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$facts.k', a: '$facts.a', b: '$facts.b', h: '$h', v: '$v' },\n\t\t\tvisitors: { $max: '$facts.visitors' },\n\t\t\tvisits: {\n\t\t\t\t$addToSet: { $cond: [isSession, { n: '$n', ms: '$facts.sessionMs' }, '$$REMOVE'] },\n\t\t\t},\n\t\t\t...FACT_SUMS,\n\t\t},\n\t},\n\t{ $set: { sessions: { $size: '$visits' }, sessionMs: { $sum: '$visits.ms' } } },\n\t{\n\t\t$group: {\n\t\t\t_id: { k: '$_id.k', a: '$_id.a', b: '$_id.b', h: '$_id.h' },\n\t\t\t...sumsOf(PART_KEYS),\n\t\t},\n\t},\n]\n\n/**\n * `capDay` in the pipeline: rows ranked within their cap's group, those past the cap folded into\n * its `(other)` row (`_id.o` 1), so a day answers at most the caps however many values it holds.\n */\nconst rankAndFold = (kinds: readonly AggregateKind[], caps: CardinalityCaps): Stage[] => {\n\tconst capped = kinds.flatMap((kind): Array<[number, number]> => {\n\t\tconst cap = kind.cap === null ? null : caps[kind.cap]\n\t\treturn cap === null ? [] : [[kind.index, cap]]\n\t})\n\tif (capped.length === 0) {\n\t\treturn []\n\t}\n\tconst capOf = capped.reduceRight<unknown>(\n\t\t(otherwise, [index, cap]) => ({ $cond: [{ $eq: ['$_id.k', index] }, cap, otherwise] }),\n\t\tnull\n\t)\n\tconst pairs = kinds.filter((kind) => kind.dim2 !== '').map((kind) => kind.index)\n\tconst items = kinds.filter((kind) => kind.source.from === 'item').map((kind) => kind.index)\n\tconst group = { $cond: [{ $in: ['$_id.k', pairs] }, '$_id.a', ''] }\n\treturn [\n\t\t{\n\t\t\t$set: {\n\t\t\t\tviews: { $cond: [{ $in: ['$_id.k', items] }, '$impressions', '$pageviews'] },\n\t\t\t\tcap: capOf,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: { k: '$_id.k', h: '$_id.h', a: group },\n\t\t\t\tsortBy: { views: -1, events: -1, '_id.a': 1, '_id.b': 1 },\n\t\t\t\t// A running count, as `$documentNumber` takes one sort key alone.\n\t\t\t\toutput: { rn: { $sum: 1, window: { documents: ['unbounded', 'current'] } } },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\to: one({ $and: [{ $ne: ['$cap', null] }, { $gt: ['$rn', '$cap'] }] }),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: {\n\t\t\t\t\tk: '$_id.k',\n\t\t\t\t\ta: { $cond: ['$o', group, '$_id.a'] },\n\t\t\t\t\tb: { $cond: ['$o', '', '$_id.b'] },\n\t\t\t\t\th: '$_id.h',\n\t\t\t\t\to: '$o',\n\t\t\t\t},\n\t\t\t\t...sumsOf(PART_KEYS),\n\t\t\t},\n\t\t},\n\t]\n}\n\n/**\n * A day's count in one pipeline: the visit chain, every hit's facts, a fold, then the caps (see\n * {@link rankAndFold}); an order both sides recorded counts once (`twinStages`). Uses disk.\n */\nexport const dayAggregationPipeline = (\n\twindow: TimeWindow,\n\toptions: {\n\t\titemPages: boolean\n\t\tfold: 'sets' | 'visitors'\n\t\ttwins: TwinLookup\n\t\tcaps: CardinalityCaps\n\t}\n): Stage[] => {\n\tconst kinds = kindsWritten(options.itemPages)\n\tconst of = (from: string) => kinds.filter((kind) => kind.source.from === from)\n\tconst items = of('item')\n\treturn [\n\t\t...hitsWithTwins(windowMatch(window), options.twins),\n\t\tprojection({\n\t\t\tsessionize: true,\n\t\t\tattributes: SESSION_ATTRIBUTES,\n\t\t\tgoals: true,\n\t\t\timpressions: true,\n\t\t\tsent: true,\n\t\t}),\n\t\t...visitStages({ sums: true, attributes: SESSION_ATTRIBUTES, attributedOnly: true }),\n\t\t{\n\t\t\t$set: {\n\t\t\t\tfacts: {\n\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t{ $cond: [{ $eq: ['$rep', 1] }, visitFacts([...of('site'), ...of('visit')]), []] },\n\t\t\t\t\t\t...hitFacts(of('hit')),\n\t\t\t\t\t\tgoalFacts(of('goal')),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $and: [{ $eq: ['$eng', 0] }, nonEmpty('$item')] },\n\t\t\t\t\t\t\t\titemFacts(items, '$item', 0),\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t{ $eq: ['$eng', 1] },\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$reduce: {\n\t\t\t\t\t\t\t\t\t\tinput: '$impressions',\n\t\t\t\t\t\t\t\t\t\tinitialValue: [],\n\t\t\t\t\t\t\t\t\t\tin: {\n\t\t\t\t\t\t\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t\t\t\t\t\t\t'$$value',\n\t\t\t\t\t\t\t\t\t\t\t\t{ $cond: [nonEmpty('$$this'), itemFacts(items, '$$this', 1), []] },\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ $project: { _id: 0, h: '$hostname', v: 1, n: '$sn', facts: 1 } },\n\t\t{ $unwind: '$facts' },\n\t\t...(options.fold === 'sets' ? setFold : visitorFold),\n\t\t...rankAndFold(kinds, options.caps),\n\t]\n}\n\n/** How many hits a day's window holds. */\nexport const dayHitsPipeline = (window: TimeWindow): Stage[] => [\n\t{ $match: windowMatch(window) },\n\t{ $count: 'n' },\n]\n\n/** One day's rows of every kind, as its `dim` and `dim2` values bound the aggregates index. */\nexport const dayRowsFilter = (\n\twindow: Pick<DayWindow, 'scope' | 'day'>\n): Record<string, unknown> => ({\n\tscope: window.scope,\n\tday: window.day,\n\tdim: { $in: [...KIND_DIMS] },\n\tdim2: { $in: [...KIND_DIMS2] },\n})\n\n/**\n * Ranges of days as one bound an index serves, with the ranges themselves where there are several.\n * Throws for no range, which every read checked before already refuses.\n */\nexport const daysMatch = (\n\tdays: ReadonlyArray<readonly [number, number]>\n): Record<string, unknown> => {\n\tconst [first] = days\n\tif (first === undefined) {\n\t\tthrow new Error('analytics: a read of days needs at least one range of them')\n\t}\n\tconst from = Math.min(...days.map(([start]) => start))\n\tconst to = Math.max(...days.map(([, end]) => end))\n\treturn days.length === 1\n\t\t? { day: { $gte: from, $lte: to } }\n\t\t: {\n\t\t\t\tday: { $gte: from, $lte: to },\n\t\t\t\t$or: days.map(([start, end]) => ({ day: { $gte: start, $lte: end } })),\n\t\t\t}\n}\n\n/**\n * A fold read's rows: the value's and its `(other)` row, or a pair's `(other)` rows. A generation\n * is one run's of one day, so matching the markers' generations alone is exact.\n */\nexport const foldReadPipeline = (\n\tread: FoldRead,\n\tkind: AggregateKind,\n\tgens: readonly string[]\n): Stage[] => [\n\t{\n\t\t$match: {\n\t\t\tscope: read.scope,\n\t\t\tdim: kind.dim,\n\t\t\tdim2: kind.dim2,\n\t\t\t...(read.hostname === undefined ? {} : { hostname: read.hostname }),\n\t\t\t...(kind.dim2 === ''\n\t\t\t\t? { value: { $in: [read.value, ''] } }\n\t\t\t\t: { value: read.value, value2: '' }),\n\t\t\t...daysMatch(read.days),\n\t\t\tgen: { $in: [...gens] },\n\t\t},\n\t},\n\t{ $project: { _id: 0, day: 1, hostname: 1, value: 1, value2: 1 } },\n]\n\n/**\n * Completed days' rows of the days' generations (see {@link foldReadPipeline}), summed, filtered,\n * ranked and cut in the database; a sum is null where no row counted its part.\n */\nexport const aggregateReadPipeline = (plan: AggregatePlan, gens: readonly string[]): Stage[] => {\n\tconst { read, kind } = plan\n\tconst grouped = plan.group === null ? null : `$${plan.group}`\n\tconst valueGroup = plan.group === 'value' || plan.group === 'value2' ? plan.group : null\n\tconst match: Record<string, unknown> = {\n\t\t...scopeMatch(read),\n\t\tdim: kind.dim,\n\t\tdim2: kind.dim2,\n\t\t...(read.hostname === undefined ? {} : { hostname: read.hostname }),\n\t\t...(read.value === undefined ? {} : { value: read.value }),\n\t\t...(read.values === undefined || valueGroup === null\n\t\t\t? {}\n\t\t\t: { [valueGroup]: { $in: [...read.values] } }),\n\t\t...daysMatch(read.days),\n\t\tgen: { $in: [...gens] },\n\t\t// An `(other)` row folds many values together: it is part of a total, never a value. Under\n\t\t// `$and`, so it joins an `$in` on the same field rather than replacing it.\n\t\t...(valueGroup === null ? {} : { $and: [{ [valueGroup]: { $ne: '' } }] }),\n\t}\n\tconst counted = PART_KEYS.filter((part) => kind.counted.has(part))\n\t// The only counted parts a stored row holds as null, so the only sums told apart from 0.\n\tconst unknowable = counted.filter((part) => UNKNOWN_WHEN_FOLDED.includes(part))\n\tconst stages: Stage[] = [\n\t\t{ $match: match },\n\t\t{\n\t\t\t$group: {\n\t\t\t\t_id: grouped,\n\t\t\t\t...sumsOf(counted),\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tunknowable.map((part) => [`${part}_n`, { $sum: one({ $isNumber: `$${part}` }) }])\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: Object.fromEntries([\n\t\t\t\t...unknowable.map((part) => [\n\t\t\t\t\tpart,\n\t\t\t\t\t{ $cond: [{ $gt: [`$${part}_n`, 0] }, `$${part}`, null] },\n\t\t\t\t]),\n\t\t\t\t...PART_KEYS.filter((part) => !kind.counted.has(part)).map((part) => [part, null]),\n\t\t\t]),\n\t\t},\n\t\t...(unknowable.length > 0 ? [{ $unset: unknowable.map((part) => `${part}_n`) }] : []),\n\t]\n\tif (plan.group !== null) {\n\t\tstages.push({\n\t\t\t$match: {\n\t\t\t\t$expr: {\n\t\t\t\t\t$gt: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$add: KEPT_PARTS.map((part) => ({\n\t\t\t\t\t\t\t\t$ifNull: [`$${part}`, 0],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t0,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\tconst ties: Record<string, 1> = plan.group === null ? {} : { _id: 1 }\n\treturn [...stages, ...orderStages(read, kind.counted, ties)]\n}\n"],"mappings":";;;;;;;AA6BA,MAAM,YAAY,WAA4C,EAC7D,MAAM,CAAC,EAAE,KAAK,CAAC,EAAE,OAAO,MAAM,GA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W,KAAK,SAAS,CAC3B,MACA,EAAE,OAAO;GAAC,EAAE,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,EAAE;GAAG,IAAI;GAAQ;EAAI,EAAE,CACzD,CAAC,GACD,GAAG,UAAU,QAAQ,SAAS,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE,KAAK,SAAS,CAAC,MAAM,IAAI,CAAC,CAClF,CAAC,EACF;EACA,GAAI,WAAW,SAAS,IAAI,CAAC,EAAE,QAAQ,WAAW,KAAK,SAAS,GAAG,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC;CACpF;CACA,IAAI,KAAK,UAAU,MAClB,OAAO,KAAK,EACX,QAAQ,EACP,OAAO,EACN,KAAK,CACJ,EACC,MAAM,WAAW,KAAK,UAAU,EAC/B,SAAS,CAAC,IAAI,QAAQ,CAAC,EACxB,EAAE,EACH,GACA,CACD,EACD,EACD,EACD,CAAC;CAEF,MAAM,OAA0B,KAAK,UAAU,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE;CACpE,OAAO,CAAC,GAAG,QAAQ,GAAG,YAAY,MAAM,KAAK,SAAS,IAAI,CAAC;AAC5D"}
@@ -2,7 +2,7 @@ import { ITEM_CLICK_EVENT } from "../../../goals/constants.js";
2
2
  import { PART_KEYS } from "../parts.js";
3
3
  import { KEPT_PARTS, SESSION_DIMENSIONS, SESSION_GAP_MS, isAcquisition, isRawDimension, readWindow, visitAttributesOf } from "../rawRead.js";
4
4
  import { ORDER_PREFIX, SERVER_ORDER_PREFIX, WIRE_ORDER_PREFIX } from "../ids.js";
5
- import { SALE_FIELDS } from "../hits.js";
5
+ import { SALE_FIELDS, WITHOUT_CONSENT_MODES } from "../hits.js";
6
6
  //#region src/native/store/mongo/pipelines.ts
7
7
  /** `1` where `test` holds, else `0`: what a document adds to a count. */
8
8
  const one = (test) => ({ $cond: [
@@ -11,6 +11,8 @@ const one = (test) => ({ $cond: [
11
11
  0
12
12
  ] });
13
13
  const isPageview = { $eq: ["$type", "pageview"] };
14
+ /** A pageview the page measured before or without consent. */
15
+ const isPageviewWithoutConsent = { $and: [isPageview, { $in: ["$mode", [...WITHOUT_CONSENT_MODES]] }] };
14
16
  /** An event or a goal completion, as `events` counts them. */
15
17
  const isInteraction = { $in: ["$type", ["event", "goal"]] };
16
18
  /** `isItemClick` of `items/ref`, as an aggregation expression. */
@@ -167,7 +169,9 @@ const HIT_PARTS = {
167
169
  conversions: { $ifNull: ["$conversions", 0] },
168
170
  revenue: { $ifNull: ["$revenue", 0] },
169
171
  impressions: 0,
170
- interactions: one(isItemClick)
172
+ interactions: one(isItemClick),
173
+ pageviewsWithoutVisitor: one({ $and: [isPageview, { $eq: ["$v", ""] }] }),
174
+ pageviewsWithoutConsent: one(isPageviewWithoutConsent)
171
175
  };
172
176
  /** A completion's amount as sent, of `$$this` in a `$map` over the goals. */
173
177
  const SENT_AMOUNT = { $ifNull: ["$$this.sent", "$$this.value"] };
@@ -189,6 +193,7 @@ const projection = (plan) => {
189
193
  item: orNull("item"),
190
194
  durationMs: orNull("durationMs"),
191
195
  scrollDepth: orNull("scrollDepth"),
196
+ mode: orNull("mode"),
192
197
  conversions: orNull("conversions"),
193
198
  revenue: orNull("revenue"),
194
199
  eng: one({ $eq: ["$type", "engagement"] })
@@ -256,6 +261,10 @@ const VISIT_SUMS = {
256
261
  v_int: {
257
262
  $sum: one(isItemClick),
258
263
  window: WHOLE
264
+ },
265
+ v_npc: {
266
+ $sum: one(isPageviewWithoutConsent),
267
+ window: WHOLE
259
268
  }
260
269
  };
261
270
  /**
@@ -634,12 +643,13 @@ const foldStages = (plan) => {
634
643
  const orderStages = ({ order, limit }, counted, ties) => {
635
644
  const stages = [];
636
645
  const sort = {};
637
- if (order && counted.has(order.part) && (!order.per || counted.has(order.per))) {
646
+ if (order && counted.has(order.part) && (!order.per || counted.has(order.per)) && (!order.less || counted.has(order.less))) {
638
647
  const part = `$${order.part}`;
648
+ const per = order.less === void 0 ? `$${order.per}` : { $subtract: [`$${order.per}`, { $ifNull: [`$${order.less}`, 0] }] };
639
649
  const rank = order.per === void 0 ? part : { $cond: [
640
- { $or: [{ $eq: [`$${order.per}`, 0] }, { $eq: [`$${order.per}`, null] }] },
650
+ { $or: [{ $eq: [per, 0] }, { $eq: [per, null] }] },
641
651
  null,
642
- { $divide: [part, `$${order.per}`] }
652
+ { $divide: [part, per] }
643
653
  ] };
644
654
  stages.push({ $set: {
645
655
  rank,
@@ -1 +1 @@
1
- {"version":3,"file":"pipelines.js","names":[],"sources":["../../../../src/native/store/mongo/pipelines.ts"],"sourcesContent":["import type { AnalyticsFilter } from '../../../core/contract'\nimport { ITEM_CLICK_EVENT } from '../../../goals/constants'\nimport { SALE_FIELDS } from '../hits'\nimport { ORDER_PREFIX, SERVER_ORDER_PREFIX, WIRE_ORDER_PREFIX } from '../ids'\nimport { type MetricParts, PART_KEYS } from '../parts'\nimport {\n\ttype HitFilter,\n\tisAcquisition,\n\tisRawDimension,\n\tKEPT_PARTS,\n\ttype RawDimension,\n\ttype RawPlan,\n\treadWindow,\n\tSESSION_DIMENSIONS,\n\tSESSION_GAP_MS,\n\ttype SessionAttribute,\n\ttype VisitorCondition,\n\tvisitAttributesOf,\n} from '../rawRead'\nimport type { HitWindow, RawOrder } from '../types'\n\n/** One aggregation stage, as the driver takes it. */\nexport type Stage = Record<string, unknown>\n\n/** `1` where `test` holds, else `0`: what a document adds to a count. */\nexport const one = (test: unknown): Record<string, unknown> => ({ $cond: [test, 1, 0] })\n\nexport const isPageview = { $eq: ['$type', 'pageview'] }\n\n/** An event or a goal completion, as `events` counts them. */\nexport const isInteraction = { $in: ['$type', ['event', 'goal']] }\n\n/** `isItemClick` of `items/ref`, as an aggregation expression. */\nexport const isItemClick = {\n\t$and: [\n\t\t{ $eq: ['$type', 'event'] },\n\t\t{ $eq: ['$name', ITEM_CLICK_EVENT] },\n\t\t{ $eq: [{ $type: '$item' }, 'string'] },\n\t\t{ $ne: ['$item', ''] },\n\t],\n}\n\n/** A window's scope as a `$match` takes it: one scope, a list of them, or none. */\nexport const scopeMatch = (window: Pick<HitWindow, 'scope' | 'scopes'>): Record<string, unknown> =>\n\twindow.scopes !== undefined\n\t\t? { scope: { $in: [...window.scopes] } }\n\t\t: window.scope === undefined\n\t\t\t? {}\n\t\t\t: { scope: window.scope }\n\n/** The hits of a window: an equality on `scope` first, then the `ts` range, as the index reads. */\nexport const windowMatch = (window: HitWindow): Record<string, unknown> => ({\n\t...scopeMatch(window),\n\tts: { $gte: window.start, $lt: window.end },\n\t...(window.hostname === undefined ? {} : { hostname: window.hostname }),\n})\n\n/** Visitors of one scope and hostname a read keeps; `scope` is absent on a read of one scope. */\nexport interface KeptVisitors {\n\tscope?: string\n\thostname: string\n\tids: readonly string[]\n}\n\n/** A window's hits, of the kept visitors alone when a read keeps some. */\nconst keptMatch = (\n\twindow: HitWindow,\n\tkept: readonly KeptVisitors[] | null\n): Record<string, unknown> => ({\n\t...windowMatch(window),\n\t...(kept === null\n\t\t? {}\n\t\t: {\n\t\t\t\t$or: kept.map((group) => ({\n\t\t\t\t\t...(group.scope === undefined ? {} : { scope: group.scope }),\n\t\t\t\t\thostname: group.hostname,\n\t\t\t\t\tv: { $in: [...group.ids] },\n\t\t\t\t})),\n\t\t\t}),\n})\n\n/** The ids starting with `prefix`, as a range of the primary key: `ow.` up to `ow/`. */\nconst keyRange = (prefix: string): Record<string, string> => ({\n\t$gte: prefix,\n\t$lt: `${prefix.slice(0, -1)}${String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1)}`,\n})\n\n/** Whether the document's `_id` starts with `prefix` (`ow.` or `os.`, which are as long). */\nconst idStartsWith = (prefix: string): Record<string, unknown> => ({\n\t$eq: [{ $substrBytes: ['$_id', 0, prefix.length] }, prefix],\n})\n\n/** How a pipeline finds an order's other record. */\nexport interface TwinLookup {\n\t/** The hits collection's name, which `$lookup` reads the other record from. */\n\tfrom: string\n\t/** How far apart an order's two records may lie to count as one sale; null for any distance. */\n\twindowMs: number | null\n}\n\n/** `ow.` and `os.` are as long, so one offset reads the digest out of either. */\nconst PREFIX_BYTES = WIRE_ORDER_PREFIX.length\n\nconst DIGEST = {\n\t$substrBytes: ['$_id', PREFIX_BYTES, { $subtract: [{ $strLenBytes: '$_id' }, PREFIX_BYTES] }],\n}\n\n/** The id of an order record's other record, for an `ow.` or `os.` id; null for any other. */\nconst TWIN_ID = {\n\t$cond: [\n\t\tidStartsWith(WIRE_ORDER_PREFIX),\n\t\t{ $concat: [SERVER_ORDER_PREFIX, DIGEST] },\n\t\t{\n\t\t\t$cond: [idStartsWith(SERVER_ORDER_PREFIX), { $concat: [WIRE_ORDER_PREFIX, DIGEST] }, null],\n\t\t},\n\t],\n}\n\n/** What a hit reads of its order's other record: its time, its sale, and its item. */\nconst TWIN_FIELDS: Record<string, 1> = Object.fromEntries(\n\t['ts', 'item', ...SALE_FIELDS].map((field) => [field, 1])\n)\n\n/**\n * Counts each order record as `countedHit` does, its twin looked up by `_id`. Run over order\n * records alone (see {@link hitsWithTwins}): a lookup per hit would double a day's cost.\n */\nexport const twinStages = (twins: TwinLookup): Stage[] => {\n\tconst found = { $eq: [{ $type: '$tw' }, 'object'] }\n\tconst close =\n\t\ttwins.windowMs === null\n\t\t\t? true\n\t\t\t: { $lte: [{ $abs: { $subtract: ['$tw.ts', '$ts'] } }, twins.windowMs] }\n\tconst credited = { $eq: ['$cr', 1] }\n\treturn [\n\t\t{ $set: { tid: TWIN_ID } },\n\t\t{\n\t\t\t$lookup: {\n\t\t\t\tfrom: twins.from,\n\t\t\t\tlocalField: 'tid',\n\t\t\t\tforeignField: '_id',\n\t\t\t\tpipeline: [{ $project: TWIN_FIELDS }],\n\t\t\t\tas: 'tw',\n\t\t\t},\n\t\t},\n\t\t{ $set: { tw: { $first: '$tw' } } },\n\t\t{\n\t\t\t$match: {\n\t\t\t\t$expr: { $not: [{ $and: [idStartsWith(SERVER_ORDER_PREFIX), found, close] }] },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\tcr: {\n\t\t\t\t\t$cond: [{ $and: [idStartsWith(WIRE_ORDER_PREFIX), found] }, one(close), null],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tSALE_FIELDS.map((field) => [\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\tcredited,\n\t\t\t\t\t\t\t\t{ $ifNull: [`$tw.${field}`, null] },\n\t\t\t\t\t\t\t\t{ $cond: [{ $eq: ['$cr', 0] }, null, `$${field}`] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t])\n\t\t\t\t),\n\t\t\t\titem: { $cond: [credited, { $ifNull: ['$tw.item', '$item'] }, '$item'] },\n\t\t\t\tserver: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $and: [credited, { $eq: [{ $type: '$tw.item' }, 'string'] }] },\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t'$server',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ $unset: ['tid', 'tw', 'cr'] },\n\t]\n}\n\n/** Every order record's id (`o`), which no ULID starts with, as a range of the primary key. */\nexport const ORDER_RANGE = keyRange(ORDER_PREFIX)\n\n/**\n * The hits `match` selects, each order counted as `countedHit` does: order records are joined in\n * by `$unionWith` with their twins looked up ({@link twinStages}), so only an order pays a lookup.\n */\nexport const hitsWithTwins = (match: Record<string, unknown>, twins: TwinLookup): Stage[] => [\n\t{ $match: { ...match, _id: { $not: ORDER_RANGE } } },\n\t{\n\t\t$unionWith: {\n\t\t\tcoll: twins.from,\n\t\t\tpipeline: [{ $match: { ...match, _id: ORDER_RANGE } }, ...twinStages(twins)],\n\t\t},\n\t},\n]\n\n/**\n * A visitor match widened to every browser record of an order, whose own sale fields are not the\n * ones it is counted with: the server's record may hand it goals, a currency or an item it lacks.\n */\nconst orWireOrder = (match: Record<string, unknown>): Record<string, unknown> => ({\n\t$or: [match, { _id: keyRange(WIRE_ORDER_PREFIX) }],\n})\n\nconst orNull = (field: string): Record<string, unknown> => ({ $ifNull: [`$${field}`, null] })\n\n/** Each metric part as an aggregation expression. */\nexport type Parts = Record<keyof MetricParts, unknown>\n\n/** What one hit adds to each part, as the SQL compiler's contributions. */\nexport const HIT_PARTS: Parts = {\n\tpageviews: one(isPageview),\n\tevents: one(isInteraction),\n\tvisitors: one({ $and: [{ $eq: ['$eng', 0] }, { $ne: ['$v', ''] }] }),\n\tsessions: one({ $and: [{ $eq: ['$eng', 0] }, { $ne: ['$sn', null] }] }),\n\tentries: '$entry',\n\tbounces: '$bounce',\n\tsessionMs: '$s_ms',\n\tdurationMs: { $ifNull: ['$durationMs', 0] },\n\tscrollSum: { $ifNull: ['$scrollDepth', 0] },\n\tscrollSamples: one({ $and: [isPageview, { $ne: ['$scrollDepth', null] }] }),\n\tconversions: { $ifNull: ['$conversions', 0] },\n\trevenue: { $ifNull: ['$revenue', 0] },\n\timpressions: 0,\n\tinteractions: one(isItemClick),\n}\n\n/** What a read projects beside every read's own fields, as the SQL hits CTE selects. */\nexport interface ProjectedFields {\n\tsessionize: boolean\n\t/** The visit attributes the visit chain takes from each hit (`a`). */\n\tattributes: readonly SessionAttribute[]\n\tgoals: boolean\n\timpressions: boolean\n\t/**\n\t * Money as it was sent: `sentCurrency`, and `sentRevenue`, each goal it completed counted with\n\t * its amount as sent (its `sent`, else its `value`).\n\t */\n\tsent: boolean\n}\n\n/** A completion's amount as sent, of `$$this` in a `$map` over the goals. */\nconst SENT_AMOUNT = { $ifNull: ['$$this.sent', '$$this.value'] }\n\n/**\n * Only the fields the read needs, an absent one made null so every stage sees the same shape. The\n * sale fields are read after {@link twinStages}, as the read counts them.\n */\nexport const projection = (plan: ProjectedFields): Stage => {\n\tconst fields: Record<string, unknown> = {\n\t\t_id: 1,\n\t\tscope: 1,\n\t\tts: 1,\n\t\thostname: 1,\n\t\tv: 1,\n\t\ttype: 1,\n\t\tpath: 1,\n\t\tserver: { $ifNull: ['$server', false] },\n\t\tname: orNull('name'),\n\t\titem: orNull('item'),\n\t\tdurationMs: orNull('durationMs'),\n\t\tscrollDepth: orNull('scrollDepth'),\n\t\tconversions: orNull('conversions'),\n\t\trevenue: orNull('revenue'),\n\t\teng: one({ $eq: ['$type', 'engagement'] }),\n\t}\n\tif (plan.sent) {\n\t\tfields.sentCurrency = { $ifNull: ['$originalCurrency', orNull('currency')] }\n\t\tfields.sentRevenue = {\n\t\t\t$sum: { $map: { input: { $ifNull: ['$goals', []] }, in: SENT_AMOUNT } },\n\t\t}\n\t}\n\tif (plan.sessionize) {\n\t\tfields.act = { $ifNull: ['$lastAt', '$ts'] }\n\t\tfields.landing = { $ifNull: ['$landing', false] }\n\t\tif (plan.attributes.length > 0) {\n\t\t\t// An engagement carries none of them; an attribute the hit lacks is left out, not null.\n\t\t\tfields.a = {\n\t\t\t\t$cond: [\n\t\t\t\t\t{ $eq: ['$type', 'engagement'] },\n\t\t\t\t\t'$$REMOVE',\n\t\t\t\t\tObject.fromEntries(plan.attributes.map((attribute) => [attribute, `$${attribute}`])),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t}\n\tif (plan.goals) {\n\t\tfields.goals = { $ifNull: ['$goals', []] }\n\t}\n\tif (plan.impressions) {\n\t\tfields.impressions = { $ifNull: ['$impressions', []] }\n\t}\n\treturn { $project: fields }\n}\n\nconst VISITOR = { s: '$scope', h: '$hostname', v: '$v' }\nconst WHOLE = { documents: ['unbounded', 'unbounded'] }\nconst SO_FAR = { documents: ['unbounded', 'current'] }\n\nconst visitNumberIsNull = { $eq: ['$sn', null] }\n\n/** The visit's first hit, engagements last: `$documentNumber` takes no compound sort. */\nconst isEntry = { $eq: ['$_id', '$entryId'] }\n\nconst isLandingEntry = { $and: [isEntry, { $eq: ['$eng', 0] }, { $eq: ['$landing', true] }] }\n\n/**\n * Each visit's own totals, for a day's aggregation to count the visit kinds once per visit: on its\n * representative, the first of its hits in entry order (`rep`), beside `s_pv`, `s_int` and `s_ms`.\n */\nconst VISIT_SUMS = {\n\tv_act: { $max: one({ $eq: ['$eng', 0] }), window: WHOLE },\n\tv_ss: { $sum: { $ifNull: ['$scrollDepth', 0] }, window: WHOLE },\n\tv_sc: { $sum: one({ $and: [isPageview, { $ne: ['$scrollDepth', null] }] }), window: WHOLE },\n\tv_conv: { $sum: { $ifNull: ['$conversions', 0] }, window: WHOLE },\n\tv_rev: { $sum: { $ifNull: ['$revenue', 0] }, window: WHOLE },\n\tv_int: { $sum: one(isItemClick), window: WHOLE },\n}\n\nexport interface VisitOptions {\n\t/** Each hit also carries its visit's totals and whether it represents the visit. */\n\tsums: boolean\n\t/** The visit attributes taken, as `e_*`: the projection's `a` holds these alone. */\n\tattributes: readonly SessionAttribute[]\n\t/**\n\t * Only the hits a day's aggregation reads them on take the attributes: a visit's\n\t * representative, and a hit completing a goal.\n\t */\n\tattributedOnly?: boolean\n}\n\n/**\n * Visits cut by the SQL frames, with each visit's entry, totals and attributes. MongoDB sorts every\n * window in full, so documents stay lean: `a` holds the attributes taken, on non-engagements alone.\n */\nexport const visitStages = (options: VisitOptions): Stage[] => {\n\tconst { sums, attributes } = options\n\tconst acquisition = attributes.filter(isAcquisition)\n\tconst own = attributes.filter((attribute) => !isAcquisition(attribute))\n\tconst taken = attributes.length > 0\n\tconst hasGoals = { $gt: [{ $size: { $ifNull: ['$goals', []] } }, 0] }\n\tconst carried = (attribute: SessionAttribute): unknown =>\n\t\tisAcquisition(attribute)\n\t\t\t? { $cond: [{ $eq: ['$landed', null] }, `$f.${attribute}`, `$landed.a.${attribute}`] }\n\t\t\t: `$f.${attribute}`\n\treturn [\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\tsortBy: { ts: 1, _id: 1 },\n\t\t\t\toutput: { prevAct: { $max: '$act', window: { documents: ['unbounded', -1] } } },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\tstarts: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $eq: ['$v', ''] },\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tone({\n\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t{ $eq: ['$prevAct', null] },\n\t\t\t\t\t\t\t\t{ $gt: ['$ts', { $add: ['$prevAct', SESSION_GAP_MS] }] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\tsortBy: { ts: 1, _id: 1 },\n\t\t\t\toutput: { sn: { $sum: '$starts', window: SO_FAR } },\n\t\t\t},\n\t\t},\n\t\t{ $set: { sn: { $cond: [{ $eq: ['$v', ''] }, null, '$sn'] } } },\n\t\t{ $unset: ['act', 'prevAct', 'starts'] },\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\t// A day's count takes a hit without a visitor as a visit of its own, totalled alone.\n\t\t\t\tpartitionBy: {\n\t\t\t\t\t...VISITOR,\n\t\t\t\t\tsn: '$sn',\n\t\t\t\t\t...(sums ? { x: { $cond: [visitNumberIsNull, '$_id', null] } } : {}),\n\t\t\t\t},\n\t\t\t\tsortBy: { eng: 1, ts: 1, _id: 1 },\n\t\t\t\toutput: {\n\t\t\t\t\tentryId: { $first: '$_id', window: WHOLE },\n\t\t\t\t\t...(taken ? { f: { $first: '$a', window: WHOLE } } : {}),\n\t\t\t\t\ts_pv: { $sum: one(isPageview), window: WHOLE },\n\t\t\t\t\ts_int: { $sum: one(isInteraction), window: WHOLE },\n\t\t\t\t\ts_ms: { $sum: { $ifNull: ['$durationMs', 0] }, window: WHOLE },\n\t\t\t\t\t...(sums ? VISIT_SUMS : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(taken && options.attributedOnly\n\t\t\t? [{ $set: { f: { $cond: [{ $or: [isEntry, hasGoals] }, '$f', '$$REMOVE'] } } }]\n\t\t\t: []),\n\t\t...(taken\n\t\t\t? [{ $set: { o: { $cond: [visitNumberIsNull, '$a', '$$REMOVE'] } } }, { $unset: 'a' }]\n\t\t\t: []),\n\t\t...(acquisition.length > 0\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\t$setWindowFields: {\n\t\t\t\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\t\t\t\tsortBy: { sn: 1, eng: 1, ts: 1, _id: 1 },\n\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t// BSON compares field by field: the largest `{ n, a }` is the latest landing.\n\t\t\t\t\t\t\t\tlanded: {\n\t\t\t\t\t\t\t\t\t$max: { $cond: [isLandingEntry, { n: '$sn', a: '$f' }, null] },\n\t\t\t\t\t\t\t\t\twindow: SO_FAR,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t{\n\t\t\t$set: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t[...acquisition, ...own].map((attribute) => [\n\t\t\t\t\t\t`e_${attribute}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\tvisitNumberIsNull,\n\t\t\t\t\t\t\t\t{ $ifNull: [`$o.${attribute}`, null] },\n\t\t\t\t\t\t\t\tcarried(attribute),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t])\n\t\t\t\t),\n\t\t\t\tentry: one({ $and: [{ $ne: ['$sn', null] }, isEntry, { $eq: ['$eng', 0] }] }),\n\t\t\t\tbounce: one({\n\t\t\t\t\t$and: [\n\t\t\t\t\t\t{ $ne: ['$sn', null] },\n\t\t\t\t\t\tisEntry,\n\t\t\t\t\t\t{ $eq: ['$eng', 0] },\n\t\t\t\t\t\t{ $eq: ['$s_pv', 1] },\n\t\t\t\t\t\t{ $eq: ['$s_int', 0] },\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t\t...(sums ? { rep: one(isEntry) } : {}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$unset: [\n\t\t\t\t...(taken ? ['f', 'o'] : []),\n\t\t\t\t...(acquisition.length > 0 ? ['landed'] : []),\n\t\t\t\t'entryId',\n\t\t\t\t'landing',\n\t\t\t\t...(sums ? [] : ['s_pv', 's_int']),\n\t\t\t],\n\t\t},\n\t]\n}\n\n/** A goal completion counts a conversion unless its hit counts none, which is a refund. */\nexport const completionConverts = one({ $gt: [{ $ifNull: ['$conversions', 0] }, 0] })\n\n/** Each goal completion, or each item clicked or seen, as a document of its own. */\nconst factStages = (plan: RawPlan): Stage[] => {\n\tconst own = {\n\t\tconv: { $ifNull: ['$conversions', 0] },\n\t\trev: { $ifNull: [plan.sent ? '$sentRevenue' : '$revenue', 0] },\n\t}\n\tif (plan.axis === 'goal') {\n\t\tconst completion = { $ifNull: ['$goals.value', 0] }\n\t\treturn [\n\t\t\t{ $unwind: '$goals' },\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tx: '$goals.slug',\n\t\t\t\t\tconv: completionConverts,\n\t\t\t\t\trev: plan.sent ? { $ifNull: ['$goals.sent', completion] } : completion,\n\t\t\t\t\timp: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t}\n\tif (plan.axis === 'item') {\n\t\tconst clicked = {\n\t\t\t$and: [{ $eq: ['$eng', 0] }, { $eq: [{ $type: '$item' }, 'string'] }, { $ne: ['$item', ''] }],\n\t\t}\n\t\treturn [\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tfacts: {\n\t\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t\t{ $cond: [clicked, [{ x: '$item', imp: 0 }], []] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{ $eq: ['$eng', 1] },\n\t\t\t\t\t\t\t\t\t{ $map: { input: '$impressions', as: 'ref', in: { x: '$$ref', imp: 1 } } },\n\t\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$facts' },\n\t\t\t{ $set: { x: '$facts.x', imp: '$facts.imp', ...own } },\n\t\t]\n\t}\n\treturn [{ $set: { x: null, imp: 0, ...own } }]\n}\n\n/** A dimension's value on a fact document. */\nconst dimension = (plan: RawPlan, key: RawDimension): unknown => {\n\tswitch (key) {\n\t\tcase 'page':\n\t\t\treturn plan.axis === 'item' ? { $cond: ['$server', null, '$path'] } : '$path'\n\t\tcase 'event':\n\t\t\treturn { $cond: [{ $eq: ['$type', 'event'] }, '$name', null] }\n\t\tcase 'goal':\n\t\tcase 'item':\n\t\t\treturn '$x'\n\t\tcase 'currency':\n\t\t\treturn '$sentCurrency'\n\t\tdefault:\n\t\t\treturn `$e_${SESSION_DIMENSIONS[key]}`\n\t}\n}\n\nconst escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nconst condition = (filter: AnalyticsFilter): unknown => {\n\tif (filter.operator === 'eq') {\n\t\treturn filter.value\n\t}\n\tconst pattern = filter.operator === 'contains' ? escapeRegex(filter.value) : filter.value\n\treturn { $regex: pattern, $options: 'i' }\n}\n\n/** What a hit's own value must match for a visitor condition (see `VisitorCondition`). */\nconst hitMatch = (filter: HitFilter): Record<string, unknown> => {\n\tconst test = condition(filter)\n\tswitch (filter.dimension) {\n\t\tcase 'page':\n\t\t\treturn { path: test }\n\t\tcase 'event':\n\t\t\treturn { type: 'event', name: test }\n\t\tcase 'currency':\n\t\t\treturn orWireOrder({\n\t\t\t\t$or: [{ originalCurrency: test }, { originalCurrency: null, currency: test }],\n\t\t\t})\n\t\tcase 'goal':\n\t\t\treturn orWireOrder({ 'goals.slug': test })\n\t\tcase 'item':\n\t\t\treturn orWireOrder({ $or: [{ item: test }, { impressions: test }] })\n\t\tdefault:\n\t\t\treturn { [SESSION_DIMENSIONS[filter.dimension]]: test }\n\t}\n}\n\n/**\n * The visitors one condition of a planned read keeps, as `{ _id: { s, h, v } }` documents: at most\n * `limit` + 1, so a condition keeping too many to be worth it is told by the count.\n */\nexport const keptVisitorsPipeline = (\n\tplan: RawPlan,\n\tkept: VisitorCondition,\n\tlimit: number\n): Stage[] => [\n\t{\n\t\t$match: {\n\t\t\t...windowMatch(readWindow(plan.read, kept.start)),\n\t\t\t...(kept.filter === undefined ? {} : hitMatch(kept.filter)),\n\t\t},\n\t},\n\t{ $group: { _id: VISITOR } },\n\t{ $limit: limit + 1 },\n]\n\n/** Every filter applied to the facts, after the visits were cut. */\nconst filterStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst fields: Record<string, unknown> = {}\n\tconst conditions: Array<Record<string, unknown>> = []\n\tif (plan.from < read.start) {\n\t\tconditions.push({ ts: { $gte: read.start } })\n\t}\n\tread.filters.forEach((filter, index) => {\n\t\tif (!isRawDimension(filter.dimension)) {\n\t\t\tthrow new Error(`analytics: raw reads cannot filter by \"${filter.dimension}\"`)\n\t\t}\n\t\tfields[`d${index}`] = dimension(plan, filter.dimension)\n\t\tconditions.push({ [`d${index}`]: condition(filter) })\n\t})\n\tif (read.path !== undefined) {\n\t\tfields.dp = dimension(plan, 'page')\n\t\tconditions.push({ dp: read.path })\n\t}\n\tif (read.item !== undefined) {\n\t\tconditions.push({ x: read.item })\n\t}\n\tif (plan.group !== undefined) {\n\t\tfields.gv = dimension(plan, plan.group)\n\t\tconditions.push({ gv: { $nin: [null, ''] } })\n\t\tif (read.values !== undefined) {\n\t\t\tconditions.push({ gv: { $in: [...read.values] } })\n\t\t}\n\t}\n\treturn [\n\t\t...(Object.keys(fields).length > 0 ? [{ $set: fields }] : []),\n\t\t...(conditions.length > 0 ? [{ $match: { $and: conditions } }] : []),\n\t]\n}\n\n/** The bucket of a fact's time, halving the starts as the SQL one does. */\nconst bucketExpression = (buckets: readonly Date[], low: number, high: number): unknown => {\n\tconst middle = Math.ceil((low + high) / 2)\n\tconst start = buckets[middle]\n\tif (low >= high || start === undefined) {\n\t\treturn low\n\t}\n\treturn {\n\t\t$cond: [\n\t\t\t{ $lt: ['$ts', start] },\n\t\t\tbucketExpression(buckets, low, middle - 1),\n\t\t\tbucketExpression(buckets, middle, high),\n\t\t],\n\t}\n}\n\n/**\n * What one fact adds to each counted part: a hit's own, but for the conversions, revenue and\n * impressions {@link factStages} set per fact.\n */\nconst contributions = (plan: RawPlan): Array<[keyof MetricParts, unknown]> => {\n\tconst parts: Parts = {\n\t\t...HIT_PARTS,\n\t\t...(plan.axis === 'item' ? { visitors: one({ $ne: ['$v', ''] }) } : {}),\n\t\tconversions: '$conv',\n\t\trevenue: '$rev',\n\t\timpressions: '$imp',\n\t}\n\treturn PART_KEYS.filter((part) => plan.counted.has(part)).map((part) => [part, parts[part]])\n}\n\ntype Level = 'visit' | 'visitor' | 'row'\n\nconst fold = (part: keyof MetricParts, level: Level): unknown => {\n\tif (part === 'visitors' && level !== 'row') {\n\t\treturn { $max: `$${part}` }\n\t}\n\tif ((part === 'sessions' || part === 'sessionMs') && level === 'visit') {\n\t\treturn { $max: `$${part}` }\n\t}\n\tif (part === 'sessionMs' && level === 'visitor') {\n\t\treturn { $sum: { $cond: [{ $eq: ['$sessions', 1] }, '$sessionMs', 0] } }\n\t}\n\treturn { $sum: `$${part}` }\n}\n\n/**\n * The three folds of the SQL statement as `$group` stages: facts to visits, visits to visitors,\n * visitors to rows, so a distinct count never collects a set of ids in one document.\n */\nconst foldStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst parts = contributions(plan)\n\tconst keys = [\n\t\t...(plan.group === undefined ? [] : ['g']),\n\t\t...(read.buckets === undefined ? [] : ['b']),\n\t]\n\tconst visits = plan.counted.has('sessions')\n\tconst bucket = read.buckets && bucketExpression(read.buckets, 0, read.buckets.length - 1)\n\tconst projected: Record<string, unknown> = {\n\t\t_id: 0,\n\t\ts: '$scope',\n\t\th: '$hostname',\n\t\tv: '$v',\n\t\t...(visits ? { n: '$sn' } : {}),\n\t\t...(plan.group === undefined ? {} : { g: '$gv' }),\n\t\t// A bare number in `$project` would include or exclude the field: one bucket is index 0.\n\t\t...(bucket === undefined\n\t\t\t? {}\n\t\t\t: { b: typeof bucket === 'number' ? { $literal: bucket } : bucket }),\n\t\t...Object.fromEntries(parts),\n\t}\n\tconst names = parts.map(([part]) => part)\n\tconst accumulate = (level: Level) =>\n\t\tObject.fromEntries(names.map((part) => [part, fold(part, level)]))\n\tconst keyOf = (fields: readonly string[], nested: boolean) =>\n\t\tObject.fromEntries(fields.map((field) => [field, nested ? `$_id.${field}` : `$${field}`]))\n\tconst stages: Stage[] = [{ $project: projected }]\n\tif (visits) {\n\t\tstages.push({\n\t\t\t$group: { _id: keyOf([...keys, 's', 'h', 'v', 'n'], false), ...accumulate('visit') },\n\t\t})\n\t}\n\tstages.push({\n\t\t$group: { _id: keyOf([...keys, 's', 'h', 'v'], visits), ...accumulate('visitor') },\n\t})\n\tstages.push({\n\t\t$group: { _id: keys.length > 0 ? keyOf(keys, true) : null, ...accumulate('row') },\n\t})\n\treturn stages\n}\n\n/**\n * Rows ranked by a read's `order` where every part it names is counted, a ratio without a\n * denominator last (`unranked`), then by `ties`, then cut to its `limit`.\n */\nexport const orderStages = (\n\t{ order, limit }: { order?: RawOrder; limit?: number },\n\tcounted: ReadonlySet<keyof MetricParts>,\n\tties: Record<string, 1>\n): Stage[] => {\n\tconst stages: Stage[] = []\n\tconst sort: Record<string, 1 | -1> = {}\n\tif (order && counted.has(order.part) && (!order.per || counted.has(order.per))) {\n\t\tconst part = `$${order.part}`\n\t\tconst rank =\n\t\t\torder.per === undefined\n\t\t\t\t? part\n\t\t\t\t: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $or: [{ $eq: [`$${order.per}`, 0] }, { $eq: [`$${order.per}`, null] }] },\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{ $divide: [part, `$${order.per}`] },\n\t\t\t\t\t\t],\n\t\t\t\t\t}\n\t\tstages.push({ $set: { rank, unranked: one({ $eq: [rank, null] }) } })\n\t\tsort.unranked = 1\n\t\tsort.rank = order.dir === 'asc' ? 1 : -1\n\t}\n\tObject.assign(sort, ties)\n\tif (Object.keys(sort).length > 0) {\n\t\tstages.push({ $sort: sort })\n\t}\n\tif (limit !== undefined) {\n\t\tstages.push({ $limit: limit })\n\t}\n\treturn stages\n}\n\n/** Rows that counted something, ranked (nothing to rank last), then cut to the limit. */\nconst outputStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst stages: Stage[] = []\n\tif (plan.group !== undefined || read.buckets !== undefined) {\n\t\tconst kept = KEPT_PARTS.filter((part) => plan.counted.has(part)).map((part) => `$${part}`)\n\t\tstages.push({ $match: { $expr: { $gt: [{ $add: kept }, 0] } } })\n\t}\n\tconst ties: Record<string, 1> = {\n\t\t...(plan.group === undefined ? {} : { '_id.g': 1 }),\n\t\t...(read.buckets === undefined ? {} : { '_id.b': 1 }),\n\t}\n\treturn [...stages, ...orderStages(read, plan.counted, ties)]\n}\n\n/**\n * The pipeline answering a planned raw read, of the `kept` visitors alone when it names them. Run\n * with `allowDiskUse` and `maxTimeMS`; needs MongoDB 5.0 or later.\n */\nexport const rawReadPipeline = (\n\tplan: RawPlan,\n\ttwins: TwinLookup,\n\tkept: readonly KeptVisitors[] | null = null\n): Stage[] => [\n\t...hitsWithTwins(keptMatch(readWindow(plan.read, plan.from), kept), twins),\n\tprojection({\n\t\tsessionize: plan.sessionize,\n\t\tattributes: visitAttributesOf(plan),\n\t\tgoals: plan.axis === 'goal',\n\t\timpressions: plan.axis === 'item',\n\t\tsent: plan.sent,\n\t}),\n\t...(plan.sessionize ? visitStages({ sums: false, attributes: visitAttributesOf(plan) }) : []),\n\t...factStages(plan),\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AE,EAAE,CAAC;CAChE;CACA,MAAM,OAA0B;EAC/B,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,EAAE;EACjD,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,EAAE;CACpD;CACA,OAAO,CAAC,GAAG,QAAQ,GAAG,YAAY,MAAM,KAAK,SAAS,IAAI,CAAC;AAC5D;;;;;AAMA,MAAa,mBACZ,MACA,OACA,OAAuC,SAC1B;CACb,GAAG,cAAc,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI,GAAG,IAAI,GAAG,KAAK;CACzE,WAAW;EACV,YAAY,KAAK;EACjB,YAAY,kBAAkB,IAAI;EAClC,OAAO,KAAK,SAAS;EACrB,aAAa,KAAK,SAAS;EAC3B,MAAM,KAAK;CACZ,CAAC;CACD,GAAI,KAAK,aAAa,YAAY;EAAE,MAAM;EAAO,YAAY,kBAAkB,IAAI;CAAE,CAAC,IAAI,CAAC;CAC3F,GAAG,WAAW,IAAI;CAClB,GAAG,aAAa,IAAI;CACpB,GAAG,WAAW,IAAI;CAClB,GAAG,aAAa,IAAI;AACrB"}
1
+ {"version":3,"file":"pipelines.js","names":[],"sources":["../../../../src/native/store/mongo/pipelines.ts"],"sourcesContent":["import type { AnalyticsFilter } from '../../../core/contract'\nimport { ITEM_CLICK_EVENT } from '../../../goals/constants'\nimport { SALE_FIELDS, WITHOUT_CONSENT_MODES } from '../hits'\nimport { ORDER_PREFIX, SERVER_ORDER_PREFIX, WIRE_ORDER_PREFIX } from '../ids'\nimport { type MetricParts, PART_KEYS } from '../parts'\nimport {\n\ttype HitFilter,\n\tisAcquisition,\n\tisRawDimension,\n\tKEPT_PARTS,\n\ttype RawDimension,\n\ttype RawPlan,\n\treadWindow,\n\tSESSION_DIMENSIONS,\n\tSESSION_GAP_MS,\n\ttype SessionAttribute,\n\ttype VisitorCondition,\n\tvisitAttributesOf,\n} from '../rawRead'\nimport type { HitWindow, RawOrder } from '../types'\n\n/** One aggregation stage, as the driver takes it. */\nexport type Stage = Record<string, unknown>\n\n/** `1` where `test` holds, else `0`: what a document adds to a count. */\nexport const one = (test: unknown): Record<string, unknown> => ({ $cond: [test, 1, 0] })\n\nexport const isPageview = { $eq: ['$type', 'pageview'] }\n\n/** A pageview the page measured before or without consent. */\nexport const isPageviewWithoutConsent = {\n\t$and: [isPageview, { $in: ['$mode', [...WITHOUT_CONSENT_MODES]] }],\n}\n\n/** An event or a goal completion, as `events` counts them. */\nexport const isInteraction = { $in: ['$type', ['event', 'goal']] }\n\n/** `isItemClick` of `items/ref`, as an aggregation expression. */\nexport const isItemClick = {\n\t$and: [\n\t\t{ $eq: ['$type', 'event'] },\n\t\t{ $eq: ['$name', ITEM_CLICK_EVENT] },\n\t\t{ $eq: [{ $type: '$item' }, 'string'] },\n\t\t{ $ne: ['$item', ''] },\n\t],\n}\n\n/** A window's scope as a `$match` takes it: one scope, a list of them, or none. */\nexport const scopeMatch = (window: Pick<HitWindow, 'scope' | 'scopes'>): Record<string, unknown> =>\n\twindow.scopes !== undefined\n\t\t? { scope: { $in: [...window.scopes] } }\n\t\t: window.scope === undefined\n\t\t\t? {}\n\t\t\t: { scope: window.scope }\n\n/** The hits of a window: an equality on `scope` first, then the `ts` range, as the index reads. */\nexport const windowMatch = (window: HitWindow): Record<string, unknown> => ({\n\t...scopeMatch(window),\n\tts: { $gte: window.start, $lt: window.end },\n\t...(window.hostname === undefined ? {} : { hostname: window.hostname }),\n})\n\n/** Visitors of one scope and hostname a read keeps; `scope` is absent on a read of one scope. */\nexport interface KeptVisitors {\n\tscope?: string\n\thostname: string\n\tids: readonly string[]\n}\n\n/** A window's hits, of the kept visitors alone when a read keeps some. */\nconst keptMatch = (\n\twindow: HitWindow,\n\tkept: readonly KeptVisitors[] | null\n): Record<string, unknown> => ({\n\t...windowMatch(window),\n\t...(kept === null\n\t\t? {}\n\t\t: {\n\t\t\t\t$or: kept.map((group) => ({\n\t\t\t\t\t...(group.scope === undefined ? {} : { scope: group.scope }),\n\t\t\t\t\thostname: group.hostname,\n\t\t\t\t\tv: { $in: [...group.ids] },\n\t\t\t\t})),\n\t\t\t}),\n})\n\n/** The ids starting with `prefix`, as a range of the primary key: `ow.` up to `ow/`. */\nconst keyRange = (prefix: string): Record<string, string> => ({\n\t$gte: prefix,\n\t$lt: `${prefix.slice(0, -1)}${String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1)}`,\n})\n\n/** Whether the document's `_id` starts with `prefix` (`ow.` or `os.`, which are as long). */\nconst idStartsWith = (prefix: string): Record<string, unknown> => ({\n\t$eq: [{ $substrBytes: ['$_id', 0, prefix.length] }, prefix],\n})\n\n/** How a pipeline finds an order's other record. */\nexport interface TwinLookup {\n\t/** The hits collection's name, which `$lookup` reads the other record from. */\n\tfrom: string\n\t/** How far apart an order's two records may lie to count as one sale; null for any distance. */\n\twindowMs: number | null\n}\n\n/** `ow.` and `os.` are as long, so one offset reads the digest out of either. */\nconst PREFIX_BYTES = WIRE_ORDER_PREFIX.length\n\nconst DIGEST = {\n\t$substrBytes: ['$_id', PREFIX_BYTES, { $subtract: [{ $strLenBytes: '$_id' }, PREFIX_BYTES] }],\n}\n\n/** The id of an order record's other record, for an `ow.` or `os.` id; null for any other. */\nconst TWIN_ID = {\n\t$cond: [\n\t\tidStartsWith(WIRE_ORDER_PREFIX),\n\t\t{ $concat: [SERVER_ORDER_PREFIX, DIGEST] },\n\t\t{\n\t\t\t$cond: [idStartsWith(SERVER_ORDER_PREFIX), { $concat: [WIRE_ORDER_PREFIX, DIGEST] }, null],\n\t\t},\n\t],\n}\n\n/** What a hit reads of its order's other record: its time, its sale, and its item. */\nconst TWIN_FIELDS: Record<string, 1> = Object.fromEntries(\n\t['ts', 'item', ...SALE_FIELDS].map((field) => [field, 1])\n)\n\n/**\n * Counts each order record as `countedHit` does, its twin looked up by `_id`. Run over order\n * records alone (see {@link hitsWithTwins}): a lookup per hit would double a day's cost.\n */\nexport const twinStages = (twins: TwinLookup): Stage[] => {\n\tconst found = { $eq: [{ $type: '$tw' }, 'object'] }\n\tconst close =\n\t\ttwins.windowMs === null\n\t\t\t? true\n\t\t\t: { $lte: [{ $abs: { $subtract: ['$tw.ts', '$ts'] } }, twins.windowMs] }\n\tconst credited = { $eq: ['$cr', 1] }\n\treturn [\n\t\t{ $set: { tid: TWIN_ID } },\n\t\t{\n\t\t\t$lookup: {\n\t\t\t\tfrom: twins.from,\n\t\t\t\tlocalField: 'tid',\n\t\t\t\tforeignField: '_id',\n\t\t\t\tpipeline: [{ $project: TWIN_FIELDS }],\n\t\t\t\tas: 'tw',\n\t\t\t},\n\t\t},\n\t\t{ $set: { tw: { $first: '$tw' } } },\n\t\t{\n\t\t\t$match: {\n\t\t\t\t$expr: { $not: [{ $and: [idStartsWith(SERVER_ORDER_PREFIX), found, close] }] },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\tcr: {\n\t\t\t\t\t$cond: [{ $and: [idStartsWith(WIRE_ORDER_PREFIX), found] }, one(close), null],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tSALE_FIELDS.map((field) => [\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\tcredited,\n\t\t\t\t\t\t\t\t{ $ifNull: [`$tw.${field}`, null] },\n\t\t\t\t\t\t\t\t{ $cond: [{ $eq: ['$cr', 0] }, null, `$${field}`] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t])\n\t\t\t\t),\n\t\t\t\titem: { $cond: [credited, { $ifNull: ['$tw.item', '$item'] }, '$item'] },\n\t\t\t\tserver: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $and: [credited, { $eq: [{ $type: '$tw.item' }, 'string'] }] },\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t'$server',\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ $unset: ['tid', 'tw', 'cr'] },\n\t]\n}\n\n/** Every order record's id (`o`), which no ULID starts with, as a range of the primary key. */\nexport const ORDER_RANGE = keyRange(ORDER_PREFIX)\n\n/**\n * The hits `match` selects, each order counted as `countedHit` does: order records are joined in\n * by `$unionWith` with their twins looked up ({@link twinStages}), so only an order pays a lookup.\n */\nexport const hitsWithTwins = (match: Record<string, unknown>, twins: TwinLookup): Stage[] => [\n\t{ $match: { ...match, _id: { $not: ORDER_RANGE } } },\n\t{\n\t\t$unionWith: {\n\t\t\tcoll: twins.from,\n\t\t\tpipeline: [{ $match: { ...match, _id: ORDER_RANGE } }, ...twinStages(twins)],\n\t\t},\n\t},\n]\n\n/**\n * A visitor match widened to every browser record of an order, whose own sale fields are not the\n * ones it is counted with: the server's record may hand it goals, a currency or an item it lacks.\n */\nconst orWireOrder = (match: Record<string, unknown>): Record<string, unknown> => ({\n\t$or: [match, { _id: keyRange(WIRE_ORDER_PREFIX) }],\n})\n\nconst orNull = (field: string): Record<string, unknown> => ({ $ifNull: [`$${field}`, null] })\n\n/** Each metric part as an aggregation expression. */\nexport type Parts = Record<keyof MetricParts, unknown>\n\n/** What one hit adds to each part, as the SQL compiler's contributions. */\nexport const HIT_PARTS: Parts = {\n\tpageviews: one(isPageview),\n\tevents: one(isInteraction),\n\tvisitors: one({ $and: [{ $eq: ['$eng', 0] }, { $ne: ['$v', ''] }] }),\n\tsessions: one({ $and: [{ $eq: ['$eng', 0] }, { $ne: ['$sn', null] }] }),\n\tentries: '$entry',\n\tbounces: '$bounce',\n\tsessionMs: '$s_ms',\n\tdurationMs: { $ifNull: ['$durationMs', 0] },\n\tscrollSum: { $ifNull: ['$scrollDepth', 0] },\n\tscrollSamples: one({ $and: [isPageview, { $ne: ['$scrollDepth', null] }] }),\n\tconversions: { $ifNull: ['$conversions', 0] },\n\trevenue: { $ifNull: ['$revenue', 0] },\n\timpressions: 0,\n\tinteractions: one(isItemClick),\n\tpageviewsWithoutVisitor: one({ $and: [isPageview, { $eq: ['$v', ''] }] }),\n\tpageviewsWithoutConsent: one(isPageviewWithoutConsent),\n}\n\n/** What a read projects beside every read's own fields, as the SQL hits CTE selects. */\nexport interface ProjectedFields {\n\tsessionize: boolean\n\t/** The visit attributes the visit chain takes from each hit (`a`). */\n\tattributes: readonly SessionAttribute[]\n\tgoals: boolean\n\timpressions: boolean\n\t/**\n\t * Money as it was sent: `sentCurrency`, and `sentRevenue`, each goal it completed counted with\n\t * its amount as sent (its `sent`, else its `value`).\n\t */\n\tsent: boolean\n}\n\n/** A completion's amount as sent, of `$$this` in a `$map` over the goals. */\nconst SENT_AMOUNT = { $ifNull: ['$$this.sent', '$$this.value'] }\n\n/**\n * Only the fields the read needs, an absent one made null so every stage sees the same shape. The\n * sale fields are read after {@link twinStages}, as the read counts them.\n */\nexport const projection = (plan: ProjectedFields): Stage => {\n\tconst fields: Record<string, unknown> = {\n\t\t_id: 1,\n\t\tscope: 1,\n\t\tts: 1,\n\t\thostname: 1,\n\t\tv: 1,\n\t\ttype: 1,\n\t\tpath: 1,\n\t\tserver: { $ifNull: ['$server', false] },\n\t\tname: orNull('name'),\n\t\titem: orNull('item'),\n\t\tdurationMs: orNull('durationMs'),\n\t\tscrollDepth: orNull('scrollDepth'),\n\t\tmode: orNull('mode'),\n\t\tconversions: orNull('conversions'),\n\t\trevenue: orNull('revenue'),\n\t\teng: one({ $eq: ['$type', 'engagement'] }),\n\t}\n\tif (plan.sent) {\n\t\tfields.sentCurrency = { $ifNull: ['$originalCurrency', orNull('currency')] }\n\t\tfields.sentRevenue = {\n\t\t\t$sum: { $map: { input: { $ifNull: ['$goals', []] }, in: SENT_AMOUNT } },\n\t\t}\n\t}\n\tif (plan.sessionize) {\n\t\tfields.act = { $ifNull: ['$lastAt', '$ts'] }\n\t\tfields.landing = { $ifNull: ['$landing', false] }\n\t\tif (plan.attributes.length > 0) {\n\t\t\t// An engagement carries none of them; an attribute the hit lacks is left out, not null.\n\t\t\tfields.a = {\n\t\t\t\t$cond: [\n\t\t\t\t\t{ $eq: ['$type', 'engagement'] },\n\t\t\t\t\t'$$REMOVE',\n\t\t\t\t\tObject.fromEntries(plan.attributes.map((attribute) => [attribute, `$${attribute}`])),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t}\n\tif (plan.goals) {\n\t\tfields.goals = { $ifNull: ['$goals', []] }\n\t}\n\tif (plan.impressions) {\n\t\tfields.impressions = { $ifNull: ['$impressions', []] }\n\t}\n\treturn { $project: fields }\n}\n\nconst VISITOR = { s: '$scope', h: '$hostname', v: '$v' }\nconst WHOLE = { documents: ['unbounded', 'unbounded'] }\nconst SO_FAR = { documents: ['unbounded', 'current'] }\n\nconst visitNumberIsNull = { $eq: ['$sn', null] }\n\n/** The visit's first hit, engagements last: `$documentNumber` takes no compound sort. */\nconst isEntry = { $eq: ['$_id', '$entryId'] }\n\nconst isLandingEntry = { $and: [isEntry, { $eq: ['$eng', 0] }, { $eq: ['$landing', true] }] }\n\n/**\n * Each visit's own totals, for a day's aggregation to count the visit kinds once per visit: on its\n * representative, the first of its hits in entry order (`rep`), beside `s_pv`, `s_int` and `s_ms`.\n */\nconst VISIT_SUMS = {\n\tv_act: { $max: one({ $eq: ['$eng', 0] }), window: WHOLE },\n\tv_ss: { $sum: { $ifNull: ['$scrollDepth', 0] }, window: WHOLE },\n\tv_sc: { $sum: one({ $and: [isPageview, { $ne: ['$scrollDepth', null] }] }), window: WHOLE },\n\tv_conv: { $sum: { $ifNull: ['$conversions', 0] }, window: WHOLE },\n\tv_rev: { $sum: { $ifNull: ['$revenue', 0] }, window: WHOLE },\n\tv_int: { $sum: one(isItemClick), window: WHOLE },\n\tv_npc: { $sum: one(isPageviewWithoutConsent), window: WHOLE },\n}\n\nexport interface VisitOptions {\n\t/** Each hit also carries its visit's totals and whether it represents the visit. */\n\tsums: boolean\n\t/** The visit attributes taken, as `e_*`: the projection's `a` holds these alone. */\n\tattributes: readonly SessionAttribute[]\n\t/**\n\t * Only the hits a day's aggregation reads them on take the attributes: a visit's\n\t * representative, and a hit completing a goal.\n\t */\n\tattributedOnly?: boolean\n}\n\n/**\n * Visits cut by the SQL frames, with each visit's entry, totals and attributes. MongoDB sorts every\n * window in full, so documents stay lean: `a` holds the attributes taken, on non-engagements alone.\n */\nexport const visitStages = (options: VisitOptions): Stage[] => {\n\tconst { sums, attributes } = options\n\tconst acquisition = attributes.filter(isAcquisition)\n\tconst own = attributes.filter((attribute) => !isAcquisition(attribute))\n\tconst taken = attributes.length > 0\n\tconst hasGoals = { $gt: [{ $size: { $ifNull: ['$goals', []] } }, 0] }\n\tconst carried = (attribute: SessionAttribute): unknown =>\n\t\tisAcquisition(attribute)\n\t\t\t? { $cond: [{ $eq: ['$landed', null] }, `$f.${attribute}`, `$landed.a.${attribute}`] }\n\t\t\t: `$f.${attribute}`\n\treturn [\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\tsortBy: { ts: 1, _id: 1 },\n\t\t\t\toutput: { prevAct: { $max: '$act', window: { documents: ['unbounded', -1] } } },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$set: {\n\t\t\t\tstarts: {\n\t\t\t\t\t$cond: [\n\t\t\t\t\t\t{ $eq: ['$v', ''] },\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tone({\n\t\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t\t{ $eq: ['$prevAct', null] },\n\t\t\t\t\t\t\t\t{ $gt: ['$ts', { $add: ['$prevAct', SESSION_GAP_MS] }] },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\tsortBy: { ts: 1, _id: 1 },\n\t\t\t\toutput: { sn: { $sum: '$starts', window: SO_FAR } },\n\t\t\t},\n\t\t},\n\t\t{ $set: { sn: { $cond: [{ $eq: ['$v', ''] }, null, '$sn'] } } },\n\t\t{ $unset: ['act', 'prevAct', 'starts'] },\n\t\t{\n\t\t\t$setWindowFields: {\n\t\t\t\t// A day's count takes a hit without a visitor as a visit of its own, totalled alone.\n\t\t\t\tpartitionBy: {\n\t\t\t\t\t...VISITOR,\n\t\t\t\t\tsn: '$sn',\n\t\t\t\t\t...(sums ? { x: { $cond: [visitNumberIsNull, '$_id', null] } } : {}),\n\t\t\t\t},\n\t\t\t\tsortBy: { eng: 1, ts: 1, _id: 1 },\n\t\t\t\toutput: {\n\t\t\t\t\tentryId: { $first: '$_id', window: WHOLE },\n\t\t\t\t\t...(taken ? { f: { $first: '$a', window: WHOLE } } : {}),\n\t\t\t\t\ts_pv: { $sum: one(isPageview), window: WHOLE },\n\t\t\t\t\ts_int: { $sum: one(isInteraction), window: WHOLE },\n\t\t\t\t\ts_ms: { $sum: { $ifNull: ['$durationMs', 0] }, window: WHOLE },\n\t\t\t\t\t...(sums ? VISIT_SUMS : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(taken && options.attributedOnly\n\t\t\t? [{ $set: { f: { $cond: [{ $or: [isEntry, hasGoals] }, '$f', '$$REMOVE'] } } }]\n\t\t\t: []),\n\t\t...(taken\n\t\t\t? [{ $set: { o: { $cond: [visitNumberIsNull, '$a', '$$REMOVE'] } } }, { $unset: 'a' }]\n\t\t\t: []),\n\t\t...(acquisition.length > 0\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\t$setWindowFields: {\n\t\t\t\t\t\t\tpartitionBy: VISITOR,\n\t\t\t\t\t\t\tsortBy: { sn: 1, eng: 1, ts: 1, _id: 1 },\n\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t// BSON compares field by field: the largest `{ n, a }` is the latest landing.\n\t\t\t\t\t\t\t\tlanded: {\n\t\t\t\t\t\t\t\t\t$max: { $cond: [isLandingEntry, { n: '$sn', a: '$f' }, null] },\n\t\t\t\t\t\t\t\t\twindow: SO_FAR,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t{\n\t\t\t$set: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t[...acquisition, ...own].map((attribute) => [\n\t\t\t\t\t\t`e_${attribute}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\tvisitNumberIsNull,\n\t\t\t\t\t\t\t\t{ $ifNull: [`$o.${attribute}`, null] },\n\t\t\t\t\t\t\t\tcarried(attribute),\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t])\n\t\t\t\t),\n\t\t\t\tentry: one({ $and: [{ $ne: ['$sn', null] }, isEntry, { $eq: ['$eng', 0] }] }),\n\t\t\t\tbounce: one({\n\t\t\t\t\t$and: [\n\t\t\t\t\t\t{ $ne: ['$sn', null] },\n\t\t\t\t\t\tisEntry,\n\t\t\t\t\t\t{ $eq: ['$eng', 0] },\n\t\t\t\t\t\t{ $eq: ['$s_pv', 1] },\n\t\t\t\t\t\t{ $eq: ['$s_int', 0] },\n\t\t\t\t\t],\n\t\t\t\t}),\n\t\t\t\t...(sums ? { rep: one(isEntry) } : {}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t$unset: [\n\t\t\t\t...(taken ? ['f', 'o'] : []),\n\t\t\t\t...(acquisition.length > 0 ? ['landed'] : []),\n\t\t\t\t'entryId',\n\t\t\t\t'landing',\n\t\t\t\t...(sums ? [] : ['s_pv', 's_int']),\n\t\t\t],\n\t\t},\n\t]\n}\n\n/** A goal completion counts a conversion unless its hit counts none, which is a refund. */\nexport const completionConverts = one({ $gt: [{ $ifNull: ['$conversions', 0] }, 0] })\n\n/** Each goal completion, or each item clicked or seen, as a document of its own. */\nconst factStages = (plan: RawPlan): Stage[] => {\n\tconst own = {\n\t\tconv: { $ifNull: ['$conversions', 0] },\n\t\trev: { $ifNull: [plan.sent ? '$sentRevenue' : '$revenue', 0] },\n\t}\n\tif (plan.axis === 'goal') {\n\t\tconst completion = { $ifNull: ['$goals.value', 0] }\n\t\treturn [\n\t\t\t{ $unwind: '$goals' },\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tx: '$goals.slug',\n\t\t\t\t\tconv: completionConverts,\n\t\t\t\t\trev: plan.sent ? { $ifNull: ['$goals.sent', completion] } : completion,\n\t\t\t\t\timp: 0,\n\t\t\t\t},\n\t\t\t},\n\t\t]\n\t}\n\tif (plan.axis === 'item') {\n\t\tconst clicked = {\n\t\t\t$and: [{ $eq: ['$eng', 0] }, { $eq: [{ $type: '$item' }, 'string'] }, { $ne: ['$item', ''] }],\n\t\t}\n\t\treturn [\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tfacts: {\n\t\t\t\t\t\t$concatArrays: [\n\t\t\t\t\t\t\t{ $cond: [clicked, [{ x: '$item', imp: 0 }], []] },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t\t\t{ $eq: ['$eng', 1] },\n\t\t\t\t\t\t\t\t\t{ $map: { input: '$impressions', as: 'ref', in: { x: '$$ref', imp: 1 } } },\n\t\t\t\t\t\t\t\t\t[],\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ $unwind: '$facts' },\n\t\t\t{ $set: { x: '$facts.x', imp: '$facts.imp', ...own } },\n\t\t]\n\t}\n\treturn [{ $set: { x: null, imp: 0, ...own } }]\n}\n\n/** A dimension's value on a fact document. */\nconst dimension = (plan: RawPlan, key: RawDimension): unknown => {\n\tswitch (key) {\n\t\tcase 'page':\n\t\t\treturn plan.axis === 'item' ? { $cond: ['$server', null, '$path'] } : '$path'\n\t\tcase 'event':\n\t\t\treturn { $cond: [{ $eq: ['$type', 'event'] }, '$name', null] }\n\t\tcase 'goal':\n\t\tcase 'item':\n\t\t\treturn '$x'\n\t\tcase 'currency':\n\t\t\treturn '$sentCurrency'\n\t\tdefault:\n\t\t\treturn `$e_${SESSION_DIMENSIONS[key]}`\n\t}\n}\n\nconst escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nconst condition = (filter: AnalyticsFilter): unknown => {\n\tif (filter.operator === 'eq') {\n\t\treturn filter.value\n\t}\n\tconst pattern = filter.operator === 'contains' ? escapeRegex(filter.value) : filter.value\n\treturn { $regex: pattern, $options: 'i' }\n}\n\n/** What a hit's own value must match for a visitor condition (see `VisitorCondition`). */\nconst hitMatch = (filter: HitFilter): Record<string, unknown> => {\n\tconst test = condition(filter)\n\tswitch (filter.dimension) {\n\t\tcase 'page':\n\t\t\treturn { path: test }\n\t\tcase 'event':\n\t\t\treturn { type: 'event', name: test }\n\t\tcase 'currency':\n\t\t\treturn orWireOrder({\n\t\t\t\t$or: [{ originalCurrency: test }, { originalCurrency: null, currency: test }],\n\t\t\t})\n\t\tcase 'goal':\n\t\t\treturn orWireOrder({ 'goals.slug': test })\n\t\tcase 'item':\n\t\t\treturn orWireOrder({ $or: [{ item: test }, { impressions: test }] })\n\t\tdefault:\n\t\t\treturn { [SESSION_DIMENSIONS[filter.dimension]]: test }\n\t}\n}\n\n/**\n * The visitors one condition of a planned read keeps, as `{ _id: { s, h, v } }` documents: at most\n * `limit` + 1, so a condition keeping too many to be worth it is told by the count.\n */\nexport const keptVisitorsPipeline = (\n\tplan: RawPlan,\n\tkept: VisitorCondition,\n\tlimit: number\n): Stage[] => [\n\t{\n\t\t$match: {\n\t\t\t...windowMatch(readWindow(plan.read, kept.start)),\n\t\t\t...(kept.filter === undefined ? {} : hitMatch(kept.filter)),\n\t\t},\n\t},\n\t{ $group: { _id: VISITOR } },\n\t{ $limit: limit + 1 },\n]\n\n/** Every filter applied to the facts, after the visits were cut. */\nconst filterStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst fields: Record<string, unknown> = {}\n\tconst conditions: Array<Record<string, unknown>> = []\n\tif (plan.from < read.start) {\n\t\tconditions.push({ ts: { $gte: read.start } })\n\t}\n\tread.filters.forEach((filter, index) => {\n\t\tif (!isRawDimension(filter.dimension)) {\n\t\t\tthrow new Error(`analytics: raw reads cannot filter by \"${filter.dimension}\"`)\n\t\t}\n\t\tfields[`d${index}`] = dimension(plan, filter.dimension)\n\t\tconditions.push({ [`d${index}`]: condition(filter) })\n\t})\n\tif (read.path !== undefined) {\n\t\tfields.dp = dimension(plan, 'page')\n\t\tconditions.push({ dp: read.path })\n\t}\n\tif (read.item !== undefined) {\n\t\tconditions.push({ x: read.item })\n\t}\n\tif (plan.group !== undefined) {\n\t\tfields.gv = dimension(plan, plan.group)\n\t\tconditions.push({ gv: { $nin: [null, ''] } })\n\t\tif (read.values !== undefined) {\n\t\t\tconditions.push({ gv: { $in: [...read.values] } })\n\t\t}\n\t}\n\treturn [\n\t\t...(Object.keys(fields).length > 0 ? [{ $set: fields }] : []),\n\t\t...(conditions.length > 0 ? [{ $match: { $and: conditions } }] : []),\n\t]\n}\n\n/** The bucket of a fact's time, halving the starts as the SQL one does. */\nconst bucketExpression = (buckets: readonly Date[], low: number, high: number): unknown => {\n\tconst middle = Math.ceil((low + high) / 2)\n\tconst start = buckets[middle]\n\tif (low >= high || start === undefined) {\n\t\treturn low\n\t}\n\treturn {\n\t\t$cond: [\n\t\t\t{ $lt: ['$ts', start] },\n\t\t\tbucketExpression(buckets, low, middle - 1),\n\t\t\tbucketExpression(buckets, middle, high),\n\t\t],\n\t}\n}\n\n/**\n * What one fact adds to each counted part: a hit's own, but for the conversions, revenue and\n * impressions {@link factStages} set per fact.\n */\nconst contributions = (plan: RawPlan): Array<[keyof MetricParts, unknown]> => {\n\tconst parts: Parts = {\n\t\t...HIT_PARTS,\n\t\t...(plan.axis === 'item' ? { visitors: one({ $ne: ['$v', ''] }) } : {}),\n\t\tconversions: '$conv',\n\t\trevenue: '$rev',\n\t\timpressions: '$imp',\n\t}\n\treturn PART_KEYS.filter((part) => plan.counted.has(part)).map((part) => [part, parts[part]])\n}\n\ntype Level = 'visit' | 'visitor' | 'row'\n\nconst fold = (part: keyof MetricParts, level: Level): unknown => {\n\tif (part === 'visitors' && level !== 'row') {\n\t\treturn { $max: `$${part}` }\n\t}\n\tif ((part === 'sessions' || part === 'sessionMs') && level === 'visit') {\n\t\treturn { $max: `$${part}` }\n\t}\n\tif (part === 'sessionMs' && level === 'visitor') {\n\t\treturn { $sum: { $cond: [{ $eq: ['$sessions', 1] }, '$sessionMs', 0] } }\n\t}\n\treturn { $sum: `$${part}` }\n}\n\n/**\n * The three folds of the SQL statement as `$group` stages: facts to visits, visits to visitors,\n * visitors to rows, so a distinct count never collects a set of ids in one document.\n */\nconst foldStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst parts = contributions(plan)\n\tconst keys = [\n\t\t...(plan.group === undefined ? [] : ['g']),\n\t\t...(read.buckets === undefined ? [] : ['b']),\n\t]\n\tconst visits = plan.counted.has('sessions')\n\tconst bucket = read.buckets && bucketExpression(read.buckets, 0, read.buckets.length - 1)\n\tconst projected: Record<string, unknown> = {\n\t\t_id: 0,\n\t\ts: '$scope',\n\t\th: '$hostname',\n\t\tv: '$v',\n\t\t...(visits ? { n: '$sn' } : {}),\n\t\t...(plan.group === undefined ? {} : { g: '$gv' }),\n\t\t// A bare number in `$project` would include or exclude the field: one bucket is index 0.\n\t\t...(bucket === undefined\n\t\t\t? {}\n\t\t\t: { b: typeof bucket === 'number' ? { $literal: bucket } : bucket }),\n\t\t...Object.fromEntries(parts),\n\t}\n\tconst names = parts.map(([part]) => part)\n\tconst accumulate = (level: Level) =>\n\t\tObject.fromEntries(names.map((part) => [part, fold(part, level)]))\n\tconst keyOf = (fields: readonly string[], nested: boolean) =>\n\t\tObject.fromEntries(fields.map((field) => [field, nested ? `$_id.${field}` : `$${field}`]))\n\tconst stages: Stage[] = [{ $project: projected }]\n\tif (visits) {\n\t\tstages.push({\n\t\t\t$group: { _id: keyOf([...keys, 's', 'h', 'v', 'n'], false), ...accumulate('visit') },\n\t\t})\n\t}\n\tstages.push({\n\t\t$group: { _id: keyOf([...keys, 's', 'h', 'v'], visits), ...accumulate('visitor') },\n\t})\n\tstages.push({\n\t\t$group: { _id: keys.length > 0 ? keyOf(keys, true) : null, ...accumulate('row') },\n\t})\n\treturn stages\n}\n\n/**\n * Rows ranked by a read's `order` where every part it names is counted, a ratio without a\n * denominator last (`unranked`), then by `ties`, then cut to its `limit`.\n */\nexport const orderStages = (\n\t{ order, limit }: { order?: RawOrder; limit?: number },\n\tcounted: ReadonlySet<keyof MetricParts>,\n\tties: Record<string, 1>\n): Stage[] => {\n\tconst stages: Stage[] = []\n\tconst sort: Record<string, 1 | -1> = {}\n\tif (\n\t\torder &&\n\t\tcounted.has(order.part) &&\n\t\t(!order.per || counted.has(order.per)) &&\n\t\t(!order.less || counted.has(order.less))\n\t) {\n\t\tconst part = `$${order.part}`\n\t\tconst per =\n\t\t\torder.less === undefined\n\t\t\t\t? `$${order.per}`\n\t\t\t\t: { $subtract: [`$${order.per}`, { $ifNull: [`$${order.less}`, 0] }] }\n\t\tconst rank =\n\t\t\torder.per === undefined\n\t\t\t\t? part\n\t\t\t\t: {\n\t\t\t\t\t\t$cond: [\n\t\t\t\t\t\t\t{ $or: [{ $eq: [per, 0] }, { $eq: [per, null] }] },\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t{ $divide: [part, per] },\n\t\t\t\t\t\t],\n\t\t\t\t\t}\n\t\tstages.push({ $set: { rank, unranked: one({ $eq: [rank, null] }) } })\n\t\tsort.unranked = 1\n\t\tsort.rank = order.dir === 'asc' ? 1 : -1\n\t}\n\tObject.assign(sort, ties)\n\tif (Object.keys(sort).length > 0) {\n\t\tstages.push({ $sort: sort })\n\t}\n\tif (limit !== undefined) {\n\t\tstages.push({ $limit: limit })\n\t}\n\treturn stages\n}\n\n/** Rows that counted something, ranked (nothing to rank last), then cut to the limit. */\nconst outputStages = (plan: RawPlan): Stage[] => {\n\tconst { read } = plan\n\tconst stages: Stage[] = []\n\tif (plan.group !== undefined || read.buckets !== undefined) {\n\t\tconst kept = KEPT_PARTS.filter((part) => plan.counted.has(part)).map((part) => `$${part}`)\n\t\tstages.push({ $match: { $expr: { $gt: [{ $add: kept }, 0] } } })\n\t}\n\tconst ties: Record<string, 1> = {\n\t\t...(plan.group === undefined ? {} : { '_id.g': 1 }),\n\t\t...(read.buckets === undefined ? {} : { '_id.b': 1 }),\n\t}\n\treturn [...stages, ...orderStages(read, plan.counted, ties)]\n}\n\n/**\n * The pipeline answering a planned raw read, of the `kept` visitors alone when it names them. Run\n * with `allowDiskUse` and `maxTimeMS`; needs MongoDB 5.0 or later.\n */\nexport const rawReadPipeline = (\n\tplan: RawPlan,\n\ttwins: TwinLookup,\n\tkept: readonly KeptVisitors[] | null = null\n): Stage[] => [\n\t...hitsWithTwins(keptMatch(readWindow(plan.read, plan.from), kept), twins),\n\tprojection({\n\t\tsessionize: plan.sessionize,\n\t\tattributes: visitAttributesOf(plan),\n\t\tgoals: plan.axis === 'goal',\n\t\timpressions: plan.axis === 'item',\n\t\tsent: plan.sent,\n\t}),\n\t...(plan.sessionize ? visitStages({ sums: false, attributes: visitAttributesOf(plan) }) : []),\n\t...factStages(plan),\n\t...filterStages(plan),\n\t...foldStages(plan),\n\t...outputStages(plan),\n]\n"],"mappings":";;;;;;;AAyBA,MAAa,OAAO,UAA4C,EAAE,OAAO;CAAC;CAAM;CAAG;AAAC,EAAE;AAEtF,MAAa,aAAa,EAAE,KAAK,CAAC,SAAS,UAAU,EAAE;;AAGvD,MAAa,2BAA2B,EACvC,MAAM,CAAC,YAAY,EAAE,KAAK,CAAC,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,CAAC,EAClE;;AAGA,MAAa,gBAAgB,EAAE,KAAK,CAAC,SAAS,CAAC,SAAS,M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KAAK,SAAS,IAAI,MAAM;EACzF,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC;CAChE;CACA,MAAM,OAA0B;EAC/B,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,EAAE;EACjD,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,EAAE;CACpD;CACA,OAAO,CAAC,GAAG,QAAQ,GAAG,YAAY,MAAM,KAAK,SAAS,IAAI,CAAC;AAC5D;;;;;AAMA,MAAa,mBACZ,MACA,OACA,OAAuC,SAC1B;CACb,GAAG,cAAc,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI,GAAG,IAAI,GAAG,KAAK;CACzE,WAAW;EACV,YAAY,KAAK;EACjB,YAAY,kBAAkB,IAAI;EAClC,OAAO,KAAK,SAAS;EACrB,aAAa,KAAK,SAAS;EAC3B,MAAM,KAAK;CACZ,CAAC;CACD,GAAI,KAAK,aAAa,YAAY;EAAE,MAAM;EAAO,YAAY,kBAAkB,IAAI;CAAE,CAAC,IAAI,CAAC;CAC3F,GAAG,WAAW,IAAI;CAClB,GAAG,aAAa,IAAI;CACpB,GAAG,WAAW,IAAI;CAClB,GAAG,aAAa,IAAI;AACrB"}
@@ -13,7 +13,9 @@ const PART_KEYS = [
13
13
  "conversions",
14
14
  "revenue",
15
15
  "impressions",
16
- "interactions"
16
+ "interactions",
17
+ "pageviewsWithoutVisitor",
18
+ "pageviewsWithoutConsent"
17
19
  ];
18
20
  /** Nothing counted, the identity of {@link addParts}. */
19
21
  const emptyParts = () => ({
@@ -30,7 +32,9 @@ const emptyParts = () => ({
30
32
  conversions: null,
31
33
  revenue: null,
32
34
  impressions: null,
33
- interactions: null
35
+ interactions: null,
36
+ pageviewsWithoutVisitor: null,
37
+ pageviewsWithoutConsent: null
34
38
  });
35
39
  /** One part of two rows together: a count with nothing beside it stays that count. */
36
40
  const addPart = (a, b) => {
@@ -57,6 +61,8 @@ const ratio = (numerator, denominator, scale = 1) => {
57
61
  return Math.round(numerator / denominator * scale);
58
62
  };
59
63
  const count = (part) => part ?? void 0;
64
+ /** The pageviews time on page averages over: those with a visitor. */
65
+ const timedPageviews = (parts) => parts.pageviews === null ? null : parts.pageviews - (parts.pageviewsWithoutVisitor ?? 0);
60
66
  const metricOf = (parts, metric) => {
61
67
  switch (metric) {
62
68
  case "pageviews": return count(parts.pageviews);
@@ -68,7 +74,7 @@ const metricOf = (parts, metric) => {
68
74
  case "revenue": return count(parts.revenue);
69
75
  case "impressions": return count(parts.impressions);
70
76
  case "interactions": return count(parts.interactions);
71
- case "avgDuration": return ratio(parts.durationMs, parts.pageviews);
77
+ case "avgDuration": return ratio(parts.durationMs, timedPageviews(parts));
72
78
  case "visitDuration": return ratio(parts.sessionMs, parts.sessions);
73
79
  case "bounceRate": return ratio(parts.bounces, parts.entries, 100);
74
80
  case "scrollDepth": {