@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/dist/adapters/ga4/ga4.d.ts +6 -0
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +6 -0
- package/dist/adapters/posthog/posthog.js +21 -8
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +2 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/exclusionEndpoint.js +1 -1
- package/dist/capture/exclusionEndpoint.js.map +1 -1
- package/dist/capture/slots.js +3 -3
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.js +11 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/adminOptions.js +6 -1
- package/dist/core/adminOptions.js.map +1 -1
- package/dist/core/capture.d.ts +3 -1
- package/dist/core/contract.d.ts +13 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +37 -5
- package/dist/core/options.js +6 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.js.map +1 -1
- package/dist/core/scopeOptions.js +2 -0
- package/dist/core/scopeOptions.js.map +1 -1
- package/dist/core/scopedRead.js +170 -21
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceLabel.d.ts +10 -0
- package/dist/core/sourceLabel.js +63 -0
- package/dist/core/sourceLabel.js.map +1 -0
- package/dist/core/sourceOptions.js +18 -6
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +55 -0
- package/dist/core/sourcePolicy.js +51 -0
- package/dist/core/sourcePolicy.js.map +1 -0
- package/dist/exports/adapters/contract.d.ts +2 -1
- package/dist/exports/adapters/ga4.d.ts +3 -2
- package/dist/exports/adapters/native.d.ts +3 -2
- package/dist/exports/adapters/plausible.d.ts +3 -2
- package/dist/exports/adapters/posthog.d.ts +3 -2
- package/dist/exports/adapters/umami.d.ts +3 -2
- package/dist/exports/client.d.ts +7 -5
- package/dist/exports/client.js +2 -1
- package/dist/exports/next.d.ts +3 -2
- package/dist/exports/rsc.d.ts +7 -6
- package/dist/exports/testing.d.ts +3 -2
- package/dist/exports/types.d.ts +12 -8
- package/dist/fields/AnalyticsPanelClient.js.map +1 -1
- package/dist/fields/AnalyticsPanelField.d.ts +1 -1
- package/dist/fields/AnalyticsPanelField.js +3 -1
- package/dist/fields/AnalyticsPanelField.js.map +1 -1
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +1 -1
- package/dist/fields/PanelContent.js +6 -1
- package/dist/fields/PanelContent.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +3 -0
- package/dist/fields/config/fetchSources.js +5 -3
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +5 -4
- package/dist/fields/readForDocument.js +6 -2
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/collection.js +4 -31
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +2 -2
- package/dist/goals/trackGoalAction.js +1 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/ingest/normalizeEvent.js +1 -1
- package/dist/native/nativeAdapter.d.ts +6 -0
- package/dist/native/nativeAdapter.js +3 -2
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/plugin/createRuntime.js +6 -3
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -0
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/pluginCollections.js +11 -5
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +11 -0
- package/dist/plugin/readContextForRequest.js +25 -15
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/runtime.js +13 -5
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +8 -9
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/ProvidersListNotice.d.ts +11 -0
- package/dist/providers/ProvidersListNotice.js +36 -0
- package/dist/providers/ProvidersListNotice.js.map +1 -0
- package/dist/providers/collection.d.ts +9 -1
- package/dist/providers/collection.js +107 -42
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +1 -1
- package/dist/providers/factory.js +8 -11
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/probe.js +5 -1
- package/dist/providers/probe.js.map +1 -1
- package/dist/providers/registry.js +49 -39
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/resolver.js +6 -3
- package/dist/providers/resolver.js.map +1 -1
- package/dist/providers/scopeUnique.js +41 -0
- package/dist/providers/scopeUnique.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/tracker/config.d.ts +5 -0
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +4 -1
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/tracker/sinks/posthog.js +30 -2
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +2 -2
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +7 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +5 -0
- package/dist/ui/components/SourcesNoticeBanner.js +20 -0
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
- package/dist/view/ViewRoot.js +2 -0
- package/dist/view/ViewRoot.js.map +1 -1
- package/dist/view/registerView.js +5 -4
- package/dist/view/registerView.js.map +1 -1
- package/dist/view/viewContext.d.ts +1 -1
- package/dist/view/viewProps.d.ts +1 -1
- package/dist/view/viewProps.js +3 -2
- package/dist/view/viewProps.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +1 -0
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +1 -0
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/defaultLayout.d.ts +26 -0
- package/dist/widgets/defaultLayout.js +51 -0
- package/dist/widgets/defaultLayout.js.map +1 -0
- package/dist/widgets/notices.js +1 -0
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/prepareWidgetRead.d.ts +14 -1
- package/dist/widgets/prepareWidgetRead.js +6 -2
- package/dist/widgets/prepareWidgetRead.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +4 -4
- package/dist/widgets/readForWidget.js +3 -1
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
- package/dist/widgets/readForWidgetBreakdown.js +3 -1
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +4 -4
- package/dist/widgets/readForWidgetGoals.js +3 -1
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
- package/dist/widgets/readForWidgetRealtime.js +3 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +4 -4
- package/dist/widgets/readForWidgetSeries.js +3 -1
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +3 -1
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareWidgetRead.js","names":[],"sources":["../../src/widgets/prepareWidgetRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport {\n\ttype CapabilityRequirement,\n\tcomparisonOf,\n\tfilterOperatorsFor,\n\tsatisfiesCapabilities,\n\tunsupportedFilter,\n} from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDateRange,\n\tGranularity,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { readAsAsked, servedName } from '../core/metricAliases'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { type GoalRead, goalHintFor } from '../plugin/goalHint'\nimport { type AnalyticsRuntime, getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { exceedsRangeCap } from '../query/limits'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\n/**\n * `unavailable` is a source that cannot serve the read at all, `busy` one that failed for now\n * (a retry can fix it), `invalid` a read refused as asked, `range-too-long` over the query cap.\n */\nexport type WidgetReadStatus =\n\t| 'ok'\n\t| 'not-configured'\n\t| 'unavailable'\n\t| 'busy'\n\t| 'invalid'\n\t| 'range-too-long'\n\t| 'filter-unsupported'\n\t| 'no-access'\n\t| 'no-scope'\n\t| 'misconfigured'\n\t| 'host-refused'\n\n/**\n * Whether the serving source can apply every filter, asked before the query so a source that\n * cannot filter says so rather than returning site-wide numbers that pass for filtered ones.\n */\nconst supportsFilters = (caps: AnalyticsCapabilities, filters?: AnalyticsFilter[]): boolean =>\n\t!filters || unsupportedFilter(caps, filters) === undefined\n\ninterface PrepareWidgetReadBase {\n\treq: PayloadRequest\n\tnow: Date\n\tadapterId?: string\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/** What the source must serve for the read to be worth making. */\n\trequires?: CapabilityRequirement\n\t/** The finest bucket the read needs, gated against the source's `minGranularity`. */\n\tgranularity?: Granularity\n\t/**\n\t * Goal hint read, resolved once the adapter is known so a caller narrowing metrics against the\n\t * source hints on the list it will ask for. Omitted asks about no goals.\n\t */\n\tgoalRead?: (adapter: AnalyticsAdapter) => GoalRead\n\t/** A hint the caller already resolved, which wins over `goalRead`. */\n\tgoalSlugs?: string[] | 'unresolved'\n\t/** The latent built-in slugs behind that hint; read together with `goalSlugs`. */\n\tbuiltinGoalSlugs?: string[]\n}\n\n/**\n * A preset or the window itself. Without `scope` the read is the request's own; a `scope` must\n * be already cleared for this request, or be a job's own with `principal: SYSTEM`.\n */\nexport type PrepareWidgetReadArgs = PrepareWidgetReadBase &\n\tReadPrincipal &\n\t({ timeframe: TimeframePreset; range?: DateRange } | { timeframe?: undefined; range: DateRange })\n\nexport type PreparedWidgetRead =\n\t| {\n\t\t\tok: true\n\t\t\truntime: AnalyticsRuntime\n\t\t\tadapter: AnalyticsAdapter\n\t\t\t/** Reporting timezone the window was resolved in. */\n\t\t\ttz: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The read's own scope, null for install-wide and aggregate reads. */\n\t\t\tscope: string | null\n\t\t\t/** Principal and scope that sub-reads pin so all of them answer about one thing. */\n\t\t\tpin: ReadPrincipal\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t\t\t/** The scope's goal slugs, `'unresolved'`, or absent for a read about no goals. */\n\t\t\tgoalSlugs?: string[] | 'unresolved'\n\t\t\t/**\n\t\t\t * Slugs among them the install never declared: the latent built-in goal. A report\n\t\t\t * lists one only once it has conversions, and never counts it as having goals.\n\t\t\t */\n\t\t\tbuiltinGoalSlugs: string[]\n\t\t\t/** The resolved goals' names, when this read resolved the goals itself. */\n\t\t\tgoalNames: Array<{ slug: string; name: string }>\n\t }\n\t| {\n\t\t\tok: false\n\t\t\tstatus: WidgetReadStatus\n\t\t\tadapterId: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The timezone the window was read in: the resolved one, or the caller's own, or UTC. */\n\t\t\ttz: string\n\t }\n\ntype PreparedSource = Pick<\n\tExtract<PreparedWidgetRead, { ok: true }>,\n\t'runtime' | 'adapter' | 'tz' | 'dateRange'\n>\n\n/** The engine read of a prepared source, each metric asked under the name the source serves. */\nexport const engineRead =\n\t({ runtime, adapter }: Pick<PreparedSource, 'runtime' | 'adapter'>, timeframe: TimeframePreset) =>\n\t(query: AnalyticsQuery): Promise<AnalyticsResult> =>\n\t\treadAsAsked(\n\t\t\t(served) => runtime.engine.read(adapter, served, { timeframe }),\n\t\t\tquery,\n\t\t\tadapter.capabilities.metrics\n\t\t)\n\n/**\n * The `scope` a result names for a link to it, only on a read the caller scoped itself: a needless\n * one refuses every reader without `access.crossScope`.\n */\nexport const pinnedScope = (\n\targs: ReadPrincipal,\n\tqueryScope: string | undefined\n): { scope?: string } =>\n\targs.scope === undefined || queryScope === undefined ? {} : { scope: queryScope }\n\n/**\n * The previous window a read compares against: only when the install and the source both compare\n * and the source still keeps data that far back.\n */\nexport const comparisonWindow = (read: PreparedSource, now: Date): DateRange | undefined => {\n\tconst { runtime, adapter, tz } = read\n\tif (!runtime.comparison || !comparisonOf(adapter.capabilities)) {\n\t\treturn undefined\n\t}\n\tconst previous = previousWindow(read.dateRange, tz)\n\treturn previous && withinLookback(previous, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t? previous\n\t\t: undefined\n}\n\n/**\n * Prologue every widget read shares: runtime, scope, adapter, timezone, window and capability\n * gates. A refusal carries the widget's status and window, so a helper's failure is one spread.\n */\nexport const prepareWidgetRead = async (\n\targs: PrepareWidgetReadArgs\n): Promise<PreparedWidgetRead> => {\n\tconst { req, now } = args\n\tconst windowIn = (zone?: string): DateRange =>\n\t\targs.timeframe === undefined\n\t\t\t? args.range\n\t\t\t: (args.range ?? resolveTimeframe(args.timeframe, now, zone))\n\n\tconst runtime = getRuntime(req.payload)\n\tconst ctx = runtime\n\t\t? await resolveReadContext({\n\t\t\t\truntime,\n\t\t\t\treq,\n\t\t\t\tadapterId: args.adapterId,\n\t\t\t\t...readPrincipalOf(args),\n\t\t\t})\n\t\t: { ok: false as const }\n\tif (!runtime || !ctx.ok) {\n\t\tconst reason = ctx.ok ? undefined : ctx.reason\n\t\tconst status: WidgetReadStatus =\n\t\t\treason === 'no-access' || reason === 'not-member'\n\t\t\t\t? 'no-access'\n\t\t\t\t: reason === 'no-scope'\n\t\t\t\t\t? 'no-scope'\n\t\t\t\t\t: 'unavailable'\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus,\n\t\t\tadapterId: args.adapterId ?? '',\n\t\t\tdateRange: windowIn(args.timezone),\n\t\t\ttz: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t}\n\t}\n\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = windowIn(tz)\n\tconst adapter = ctx.adapter\n\tconst refuse = (status: WidgetReadStatus): PreparedWidgetRead => ({\n\t\tok: false,\n\t\tstatus,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttz,\n\t})\n\tif (!adapter.isConfigured()) {\n\t\treturn refuse('not-configured')\n\t}\n\tif (args.range && exceedsRangeCap(args.range)) {\n\t\treturn refuse('range-too-long')\n\t}\n\t// The widget's own filters count toward where its metric reads (a page filter for a metric\n\t// read only per page); one the source cannot apply at all is the filter check's to report.\n\tconst filteredBy = (args.filters ?? [])\n\t\t.map((filter) => filter.dimension)\n\t\t.filter((dimension) => filterOperatorsFor(adapter.capabilities, dimension).length > 0)\n\t// A metric served under another name (`visits` as `sessions`) is read under that one.\n\tconst metrics = args.requires?.metrics?.map((m) => servedName(m, adapter.capabilities.metrics))\n\tif (\n\t\targs.requires &&\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\t...args.requires,\n\t\t\t...(metrics ? { metrics } : {}),\n\t\t\tfilters: [...(args.requires.filters ?? []), ...filteredBy],\n\t\t})\n\t) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (args.granularity && !supportsGranularity(adapter.capabilities, args.granularity)) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (!supportsFilters(adapter.capabilities, args.filters)) {\n\t\treturn refuse('filter-unsupported')\n\t}\n\n\tconst resolved =\n\t\targs.goalSlugs === undefined && args.goalRead\n\t\t\t? await goalHintFor({ runtime, req, scope: ctx.scope, ...args.goalRead(adapter) })\n\t\t\t: undefined\n\tconst goalSlugs = args.goalSlugs ?? resolved?.slugs\n\treturn {\n\t\tok: true,\n\t\truntime,\n\t\tadapter,\n\t\ttz,\n\t\tdateRange,\n\t\tscope: ctx.scope,\n\t\tpin: ctx.pin,\n\t\tbuiltinGoalSlugs: args.builtinGoalSlugs ?? resolved?.builtin ?? [],\n\t\tgoalNames: resolved?.names ?? [],\n\t\t...(ctx.queryScope === undefined ? {} : { queryScope: ctx.queryScope }),\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiDA,MAAM,mBAAmB,MAA6B,YACrD,CAAC,WAAW,kBAAkB,MAAM,OAAO,MAAM,KAAA;;AA0ElD,MAAa,cACX,EAAE,SAAS,WAAwD,eACnE,UACA,aACE,WAAW,QAAQ,OAAO,KAAK,SAAS,QAAQ,EAAE,UAAU,CAAC,GAC9D,OACA,QAAQ,aAAa,OACtB;;;;;AAMF,MAAa,eACZ,MACA,eAEA,KAAK,UAAU,KAAA,KAAa,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,WAAW;;;;;AAMjF,MAAa,oBAAoB,MAAsB,QAAqC;CAC3F,MAAM,EAAE,SAAS,SAAS,OAAO;CACjC,IAAI,CAAC,QAAQ,cAAc,CAAC,aAAa,QAAQ,YAAY,GAC5D;CAED,MAAM,WAAW,eAAe,KAAK,WAAW,EAAE;CAClD,OAAO,YAAY,eAAe,UAAU,QAAQ,aAAa,iBAAiB;EAAE;EAAI;CAAI,CAAC,IAC1F,WACA,KAAA;AACJ;;;;;AAMA,MAAa,oBAAoB,OAChC,SACiC;CACjC,MAAM,EAAE,KAAK,QAAQ;CACrB,MAAM,YAAY,SACjB,KAAK,cAAc,KAAA,IAChB,KAAK,QACJ,KAAK,SAAS,iBAAiB,KAAK,WAAW,KAAK,IAAI;CAE7D,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,MAAM,MAAM,UACT,MAAM,mBAAmB;EACzB;EACA;E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Ac,KAAK,OAAO,GACtD,OAAO,OAAO,oBAAoB;CAGnC,MAAM,WACL,KAAK,cAAc,KAAA,KAAa,KAAK,WAClC,MAAM,YAAY;EAAE;EAAS;EAAK,OAAO,IAAI;EAAO,GAAG,KAAK,SAAS,OAAO;CAAE,CAAC,IAC/E,KAAA;CACJ,MAAM,YAAY,KAAK,aAAa,UAAU;CAC9C,OAAO;EACN,IAAI;EACJ;EACA;EACA;EACA;EACA,OAAO,IAAI;EACX,KAAK,IAAI;EACT,kBAAkB,KAAK,oBAAoB,UAAU,WAAW,CAAC;EACjE,WAAW,UAAU,SAAS,CAAC;EAC/B,GAAI,IAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,IAAI,WAAW;EACrE,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CAChD;AACD"}
|
|
1
|
+
{"version":3,"file":"prepareWidgetRead.js","names":[],"sources":["../../src/widgets/prepareWidgetRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport {\n\ttype CapabilityRequirement,\n\tcomparisonOf,\n\tfilterOperatorsFor,\n\tsatisfiesCapabilities,\n\tunsupportedFilter,\n} from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDateRange,\n\tGranularity,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { readAsAsked, servedName } from '../core/metricAliases'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { type GoalRead, goalHintFor } from '../plugin/goalHint'\nimport { type AnalyticsRuntime, getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { exceedsRangeCap } from '../query/limits'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\n/**\n * `unavailable` is a source that cannot serve the read at all, `busy` one that failed for now\n * (a retry can fix it), `invalid` a read refused as asked, `range-too-long` over the query cap.\n */\nexport type WidgetReadStatus =\n\t| 'ok'\n\t| 'not-configured'\n\t| 'unavailable'\n\t| 'busy'\n\t| 'invalid'\n\t| 'range-too-long'\n\t| 'filter-unsupported'\n\t| 'no-access'\n\t| 'no-scope'\n\t| 'misconfigured'\n\t| 'host-refused'\n\n/**\n * Whether the serving source can apply every filter, asked before the query so a source that\n * cannot filter says so rather than returning site-wide numbers that pass for filtered ones.\n */\nconst supportsFilters = (caps: AnalyticsCapabilities, filters?: AnalyticsFilter[]): boolean =>\n\t!filters || unsupportedFilter(caps, filters) === undefined\n\n/** What a read of a stored source (a widget's `dataSource`) may take. */\nexport interface StoredSourceRead {\n\t/**\n\t * Read the scope's default when `adapterId` names a source this reader cannot read, saying so\n\t * in `substitutedFrom`. For a stored choice only, never a source a caller just picked.\n\t */\n\tfallbackWhenUnreadable?: boolean\n}\n\n/** What a read says when it did not read the source it was asked for. */\nexport interface SubstitutedSource {\n\t/** The source asked for, which this reader cannot read; the scope default answered instead. */\n\tsubstitutedFrom?: string\n}\n\n/** The substitution a prepared read made, spread into the helper's own result. */\nexport const substitutionOf = (prepared: SubstitutedSource): SubstitutedSource =>\n\tprepared.substitutedFrom === undefined ? {} : { substitutedFrom: prepared.substitutedFrom }\n\ninterface PrepareWidgetReadBase extends StoredSourceRead {\n\treq: PayloadRequest\n\tnow: Date\n\tadapterId?: string\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/** What the source must serve for the read to be worth making. */\n\trequires?: CapabilityRequirement\n\t/** The finest bucket the read needs, gated against the source's `minGranularity`. */\n\tgranularity?: Granularity\n\t/**\n\t * Goal hint read, resolved once the adapter is known so a caller narrowing metrics against the\n\t * source hints on the list it will ask for. Omitted asks about no goals.\n\t */\n\tgoalRead?: (adapter: AnalyticsAdapter) => GoalRead\n\t/** A hint the caller already resolved, which wins over `goalRead`. */\n\tgoalSlugs?: string[] | 'unresolved'\n\t/** The latent built-in slugs behind that hint; read together with `goalSlugs`. */\n\tbuiltinGoalSlugs?: string[]\n}\n\n/**\n * A preset or the window itself. Without `scope` the read is the request's own; a `scope` must\n * be already cleared for this request, or be a job's own with `principal: SYSTEM`.\n */\nexport type PrepareWidgetReadArgs = PrepareWidgetReadBase &\n\tReadPrincipal &\n\t({ timeframe: TimeframePreset; range?: DateRange } | { timeframe?: undefined; range: DateRange })\n\nexport type PreparedWidgetRead =\n\t| ({\n\t\t\tok: true\n\t\t\truntime: AnalyticsRuntime\n\t\t\tadapter: AnalyticsAdapter\n\t\t\t/** Reporting timezone the window was resolved in. */\n\t\t\ttz: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The read's own scope, null for install-wide and aggregate reads. */\n\t\t\tscope: string | null\n\t\t\t/** Principal and scope that sub-reads pin so all of them answer about one thing. */\n\t\t\tpin: ReadPrincipal\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t\t\t/** The scope's goal slugs, `'unresolved'`, or absent for a read about no goals. */\n\t\t\tgoalSlugs?: string[] | 'unresolved'\n\t\t\t/**\n\t\t\t * Slugs among them the install never declared: the latent built-in goal. A report\n\t\t\t * lists one only once it has conversions, and never counts it as having goals.\n\t\t\t */\n\t\t\tbuiltinGoalSlugs: string[]\n\t\t\t/** The resolved goals' names, when this read resolved the goals itself. */\n\t\t\tgoalNames: Array<{ slug: string; name: string }>\n\t } & SubstitutedSource)\n\t| {\n\t\t\tok: false\n\t\t\tstatus: WidgetReadStatus\n\t\t\tadapterId: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The timezone the window was read in: the resolved one, or the caller's own, or UTC. */\n\t\t\ttz: string\n\t }\n\ntype PreparedSource = Pick<\n\tExtract<PreparedWidgetRead, { ok: true }>,\n\t'runtime' | 'adapter' | 'tz' | 'dateRange'\n>\n\n/** The engine read of a prepared source, each metric asked under the name the source serves. */\nexport const engineRead =\n\t({ runtime, adapter }: Pick<PreparedSource, 'runtime' | 'adapter'>, timeframe: TimeframePreset) =>\n\t(query: AnalyticsQuery): Promise<AnalyticsResult> =>\n\t\treadAsAsked(\n\t\t\t(served) => runtime.engine.read(adapter, served, { timeframe }),\n\t\t\tquery,\n\t\t\tadapter.capabilities.metrics\n\t\t)\n\n/**\n * The `scope` a result names for a link to it, only on a read the caller scoped itself: a needless\n * one refuses every reader without `access.crossScope`.\n */\nexport const pinnedScope = (\n\targs: ReadPrincipal,\n\tqueryScope: string | undefined\n): { scope?: string } =>\n\targs.scope === undefined || queryScope === undefined ? {} : { scope: queryScope }\n\n/**\n * The previous window a read compares against: only when the install and the source both compare\n * and the source still keeps data that far back.\n */\nexport const comparisonWindow = (read: PreparedSource, now: Date): DateRange | undefined => {\n\tconst { runtime, adapter, tz } = read\n\tif (!runtime.comparison || !comparisonOf(adapter.capabilities)) {\n\t\treturn undefined\n\t}\n\tconst previous = previousWindow(read.dateRange, tz)\n\treturn previous && withinLookback(previous, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t? previous\n\t\t: undefined\n}\n\n/**\n * Prologue every widget read shares: runtime, scope, adapter, timezone, window and capability\n * gates. A refusal carries the widget's status and window, so a helper's failure is one spread.\n */\nexport const prepareWidgetRead = async (\n\targs: PrepareWidgetReadArgs\n): Promise<PreparedWidgetRead> => {\n\tconst { req, now } = args\n\tconst windowIn = (zone?: string): DateRange =>\n\t\targs.timeframe === undefined\n\t\t\t? args.range\n\t\t\t: (args.range ?? resolveTimeframe(args.timeframe, now, zone))\n\n\tconst runtime = getRuntime(req.payload)\n\tconst ctx = runtime\n\t\t? await resolveReadContext({\n\t\t\t\truntime,\n\t\t\t\treq,\n\t\t\t\tadapterId: args.adapterId,\n\t\t\t\t...readPrincipalOf(args),\n\t\t\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\t\t})\n\t\t: { ok: false as const }\n\tif (!runtime || !ctx.ok) {\n\t\tconst reason = ctx.ok ? undefined : ctx.reason\n\t\tconst status: WidgetReadStatus =\n\t\t\treason === 'no-access' || reason === 'not-member'\n\t\t\t\t? 'no-access'\n\t\t\t\t: reason === 'no-scope'\n\t\t\t\t\t? 'no-scope'\n\t\t\t\t\t: 'unavailable'\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus,\n\t\t\tadapterId: args.adapterId ?? '',\n\t\t\tdateRange: windowIn(args.timezone),\n\t\t\ttz: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t}\n\t}\n\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = windowIn(tz)\n\tconst adapter = ctx.adapter\n\tconst refuse = (status: WidgetReadStatus): PreparedWidgetRead => ({\n\t\tok: false,\n\t\tstatus,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttz,\n\t})\n\tif (!adapter.isConfigured()) {\n\t\treturn refuse('not-configured')\n\t}\n\tif (args.range && exceedsRangeCap(args.range)) {\n\t\treturn refuse('range-too-long')\n\t}\n\t// The widget's own filters count toward where its metric reads (a page filter for a metric\n\t// read only per page); one the source cannot apply at all is the filter check's to report.\n\tconst filteredBy = (args.filters ?? [])\n\t\t.map((filter) => filter.dimension)\n\t\t.filter((dimension) => filterOperatorsFor(adapter.capabilities, dimension).length > 0)\n\t// A metric served under another name (`visits` as `sessions`) is read under that one.\n\tconst metrics = args.requires?.metrics?.map((m) => servedName(m, adapter.capabilities.metrics))\n\tif (\n\t\targs.requires &&\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\t...args.requires,\n\t\t\t...(metrics ? { metrics } : {}),\n\t\t\tfilters: [...(args.requires.filters ?? []), ...filteredBy],\n\t\t})\n\t) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (args.granularity && !supportsGranularity(adapter.capabilities, args.granularity)) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (!supportsFilters(adapter.capabilities, args.filters)) {\n\t\treturn refuse('filter-unsupported')\n\t}\n\n\tconst resolved =\n\t\targs.goalSlugs === undefined && args.goalRead\n\t\t\t? await goalHintFor({ runtime, req, scope: ctx.scope, ...args.goalRead(adapter) })\n\t\t\t: undefined\n\tconst goalSlugs = args.goalSlugs ?? resolved?.slugs\n\treturn {\n\t\tok: true,\n\t\truntime,\n\t\tadapter,\n\t\ttz,\n\t\tdateRange,\n\t\tscope: ctx.scope,\n\t\tpin: ctx.pin,\n\t\tbuiltinGoalSlugs: args.builtinGoalSlugs ?? resolved?.builtin ?? [],\n\t\tgoalNames: resolved?.names ?? [],\n\t\t...substitutionOf(ctx),\n\t\t...(ctx.queryScope === undefined ? {} : { queryScope: ctx.queryScope }),\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiDA,MAAM,mBAAmB,MAA6B,YACrD,CAAC,WAAW,kBAAkB,MAAM,OAAO,MAAM,KAAA;;AAkBlD,MAAa,kBAAkB,aAC9B,SAAS,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,SAAS,gBAAgB;;AA0E3F,MAAa,cACX,EAAE,SAAS,WAAwD,eACnE,UACA,aACE,WAAW,QAAQ,OAAO,KAAK,SAAS,QAAQ,EAAE,UAAU,CAAC,GAC9D,OACA,QAAQ,aAAa,OACtB;;;;;AAMF,MAAa,eACZ,MACA,eAEA,KAAK,UAAU,KAAA,KAAa,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,WAAW;;;;;AAMjF,MAAa,oBAAoB,MAAsB,QAAqC;CAC3F,MAAM,EAAE,SAAS,SAAS,OAAO;CACjC,IAAI,CAAC,QAAQ,cAAc,CAAC,aAAa,QAAQ,YAAY,GAC5D;CAED,MAAM,WAAW,eAAe,KAAK,WAAW,EAAE;CAClD,OAAO,YAAY,eAAe,UAAU,QAAQ,a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,WAAW,GAAG,QAAQ,aAAa,OAAO,CAAC;CAC9F,IACC,KAAK,YACL,CAAC,sBAAsB,QAAQ,cAAc;EAC5C,GAAG,KAAK;EACR,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC7B,SAAS,CAAC,GAAI,KAAK,SAAS,WAAW,CAAC,GAAI,GAAG,UAAU;CAC1D,CAAC,GAED,OAAO,OAAO,aAAa;CAE5B,IAAI,KAAK,eAAe,CAAC,oBAAoB,QAAQ,cAAc,KAAK,WAAW,GAClF,OAAO,OAAO,aAAa;CAE5B,IAAI,CAAC,gBAAgB,QAAQ,cAAc,KAAK,OAAO,GACtD,OAAO,OAAO,oBAAoB;CAGnC,MAAM,WACL,KAAK,cAAc,KAAA,KAAa,KAAK,WAClC,MAAM,YAAY;EAAE;EAAS;EAAK,OAAO,IAAI;EAAO,GAAG,KAAK,SAAS,OAAO;CAAE,CAAC,IAC/E,KAAA;CACJ,MAAM,YAAY,KAAK,aAAa,UAAU;CAC9C,OAAO;EACN,IAAI;EACJ;EACA;EACA;EACA;EACA,OAAO,IAAI;EACX,KAAK,IAAI;EACT,kBAAkB,KAAK,oBAAoB,UAAU,WAAW,CAAC;EACjE,WAAW,UAAU,SAAS,CAAC;EAC/B,GAAG,eAAe,GAAG;EACrB,GAAI,IAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,IAAI,WAAW;EACrE,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CAChD;AACD"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { AnalyticsFilter, DateRange, MetricKey, MetricValues } from "../core/contract.js";
|
|
2
|
+
import { ReadPrincipal } from "../access/principal.js";
|
|
2
3
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
4
|
import { ReadNotices } from "./readMeta.js";
|
|
4
|
-
import {
|
|
5
|
-
import { WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
5
|
+
import { StoredSourceRead, SubstitutedSource, WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
6
6
|
import { PayloadRequest } from "payload";
|
|
7
7
|
|
|
8
8
|
//#region src/widgets/readForWidget.d.ts
|
|
9
|
-
interface WidgetReadResult extends Partial<ReadNotices
|
|
9
|
+
interface WidgetReadResult extends Partial<ReadNotices>, SubstitutedSource {
|
|
10
10
|
status: WidgetReadStatus;
|
|
11
11
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
12
12
|
retryAfterMs?: number;
|
|
@@ -34,7 +34,7 @@ interface WidgetReadResult extends Partial<ReadNotices> {
|
|
|
34
34
|
* Without `scope` the read is the request's own, behind `access.read`. A `scope` must be one
|
|
35
35
|
* already cleared for this request, or a job's own with `principal: SYSTEM`.
|
|
36
36
|
*/
|
|
37
|
-
type ReadForWidgetArgs = ReadPrincipal & {
|
|
37
|
+
type ReadForWidgetArgs = ReadPrincipal & StoredSourceRead & {
|
|
38
38
|
req: PayloadRequest;
|
|
39
39
|
metrics: MetricKey[];
|
|
40
40
|
timeframe: TimeframePreset;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readPrincipalOf } from "../access/principal.js";
|
|
2
2
|
import { readFailureOf } from "../surfacing/classifyError.js";
|
|
3
|
-
import { comparisonWindow, engineRead, pinnedScope, prepareWidgetRead } from "./prepareWidgetRead.js";
|
|
3
|
+
import { comparisonWindow, engineRead, pinnedScope, prepareWidgetRead, substitutionOf } from "./prepareWidgetRead.js";
|
|
4
4
|
import { readMeta } from "./readMeta.js";
|
|
5
5
|
import { hasNoDeclaredGoals } from "../goals/latent.js";
|
|
6
6
|
//#region src/widgets/readForWidget.ts
|
|
@@ -16,6 +16,7 @@ const readForWidget = async (args) => {
|
|
|
16
16
|
timeframe,
|
|
17
17
|
adapterId,
|
|
18
18
|
...readPrincipalOf(args),
|
|
19
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
19
20
|
timezone: args.timezone,
|
|
20
21
|
range,
|
|
21
22
|
filters,
|
|
@@ -62,6 +63,7 @@ const readForWidget = async (args) => {
|
|
|
62
63
|
return {
|
|
63
64
|
status: "ok",
|
|
64
65
|
adapterId: adapter.id,
|
|
66
|
+
...substitutionOf(prepared),
|
|
65
67
|
...pinnedScope(args, prepared.queryScope),
|
|
66
68
|
dateRange,
|
|
67
69
|
timezone: tz,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidget.js","names":[],"sources":["../../src/widgets/readForWidget.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport type {\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { hasNoDeclaredGoals } from '../goals/latent'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport {\n\tcomparisonWindow,\n\tengineRead,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport type { WidgetReadStatus } from './prepareWidgetRead'\n\nexport interface WidgetReadResult extends Partial<ReadNotices
|
|
1
|
+
{"version":3,"file":"readForWidget.js","names":[],"sources":["../../src/widgets/readForWidget.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport type {\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { hasNoDeclaredGoals } from '../goals/latent'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport {\n\tcomparisonWindow,\n\tengineRead,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport type { WidgetReadStatus } from './prepareWidgetRead'\n\nexport interface WidgetReadResult extends Partial<ReadNotices>, SubstitutedSource {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/** The reporting timezone the read resolved in, which names its days. */\n\ttimezone?: string\n\t/**\n\t * Scope a link to this read must name, set only when the viewer would not resolve it alone:\n\t * a needless `scope` refuses every reader without `access.crossScope`.\n\t */\n\tscope?: string\n\tdateRange: DateRange\n\t/** An average with nothing to average over reads `null`; render it as no data, not zero. */\n\tmetrics: MetricValues\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** The read asked about goals and the scope declared none of its own. */\n\tnoGoals?: boolean\n\t/** Previous-window totals, present only when the adapter supports comparison. */\n\tpreviousMetrics?: MetricValues\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n}\n\n/**\n * Without `scope` the read is the request's own, behind `access.read`. A `scope` must be one\n * already cleared for this request, or a job's own with `principal: SYSTEM`.\n */\nexport type ReadForWidgetArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\tmetrics: MetricKey[]\n\t\ttimeframe: TimeframePreset\n\t\tadapterId?: string\n\t\tnow: Date\n\t\trange?: DateRange\n\t\t/**\n\t\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t\t */\n\t\ttimezone?: string\n\t\tfilters?: AnalyticsFilter[]\n\t\t/**\n\t\t * Read the previous window too, where the install and the source both allow it. Defaults\n\t\t * to on; a caller that never renders a delta passes false to save the second read.\n\t\t */\n\t\tcomparison?: boolean\n\t}\n\n/**\n * Totals of `metrics` over a widget's window, beside the previous window's where the install and\n * the source compare. A source that fails answers with a status rather than a throw.\n */\nexport const readForWidget = async (args: ReadForWidgetArgs): Promise<WidgetReadResult> => {\n\tconst { req, metrics, timeframe, adapterId, now, range, filters } = args\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics },\n\t\tgoalRead: () => ({ metrics }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\tmetrics: {},\n\t\t}\n\t}\n\tconst { adapter, tz, dateRange } = prepared\n\tconst comparisonRange = args.comparison === false ? undefined : comparisonWindow(prepared, now)\n\tconst readBase = {\n\t\tmetrics,\n\t\tfilters,\n\t\ttimezone: tz,\n\t\tscope: prepared.queryScope,\n\t\t...(prepared.goalSlugs === undefined ? {} : { goalSlugs: prepared.goalSlugs }),\n\t}\n\tconst read = engineRead(prepared, timeframe)\n\t// The number first: a comparison that fails drops the delta, never the number itself.\n\tconst main = read({ ...readBase, dateRange })\n\tconst comparing = comparisonRange\n\t\t? read({ ...readBase, dateRange: comparisonRange }).catch(() => undefined)\n\t\t: undefined\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await main\n\t} catch (err) {\n\t\treturn { ...readFailureOf(err), adapterId: adapter.id, dateRange, metrics: {} }\n\t}\n\tconst previous = await comparing\n\tconst previousMetrics = previous ? (previous.totals ?? {}) : undefined\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...substitutionOf(prepared),\n\t\t...pinnedScope(args, prepared.queryScope),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tmetrics: result.totals ?? {},\n\t\t...readMeta(result),\n\t\tnoGoals:\n\t\t\tArray.isArray(prepared.goalSlugs) &&\n\t\t\thasNoDeclaredGoals(prepared.goalSlugs, prepared.builtinGoalSlugs),\n\t\tpreviousMet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AAe,QAAQ;EAC1B,GAAG,YAAY,MAAM,SAAS,UAAU;EACxC;EACA,UAAU;EACV,SAAS,OAAO,UAAU,CAAC;EAC3B,GAAG,SAAS,MAAM;EAClB,SACC,MAAM,QAAQ,SAAS,SAAS,KAChC,mBAAmB,SAAS,WAAW,SAAS,gBAAgB;EACjE;EACA,iBAAiB,WAAW,kBAAkB,KAAA;CAC/C;AACD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { AnalyticsFilter, DateRange, DimensionKey, MetricKey, MetricValue, MetricValues } from "../core/contract.js";
|
|
2
|
+
import { ReadPrincipal } from "../access/principal.js";
|
|
2
3
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
4
|
import { ReadNotices } from "./readMeta.js";
|
|
4
|
-
import {
|
|
5
|
-
import { WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
5
|
+
import { StoredSourceRead, SubstitutedSource, WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
6
6
|
import { PayloadRequest } from "payload";
|
|
7
7
|
|
|
8
8
|
//#region src/widgets/readForWidgetBreakdown.d.ts
|
|
@@ -19,7 +19,7 @@ interface BreakdownRow {
|
|
|
19
19
|
/** Every metric the read asked for, present only when `extraMetrics` asked for more. */
|
|
20
20
|
metrics?: MetricValues;
|
|
21
21
|
}
|
|
22
|
-
interface WidgetBreakdownResult extends Partial<ReadNotices
|
|
22
|
+
interface WidgetBreakdownResult extends Partial<ReadNotices>, SubstitutedSource {
|
|
23
23
|
status: WidgetReadStatus;
|
|
24
24
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
25
25
|
retryAfterMs?: number;
|
|
@@ -44,7 +44,7 @@ interface WidgetBreakdownResult extends Partial<ReadNotices> {
|
|
|
44
44
|
}>;
|
|
45
45
|
}
|
|
46
46
|
/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */
|
|
47
|
-
type ReadForWidgetBreakdownArgs = ReadPrincipal & {
|
|
47
|
+
type ReadForWidgetBreakdownArgs = ReadPrincipal & StoredSourceRead & {
|
|
48
48
|
req: PayloadRequest;
|
|
49
49
|
metric: MetricKey;
|
|
50
50
|
dimension: DimensionKey;
|
|
@@ -4,7 +4,7 @@ import { readFailureOf } from "../surfacing/classifyError.js";
|
|
|
4
4
|
import { asTranslate } from "../translations/server.js";
|
|
5
5
|
import { emptyReading } from "../core/metricValues.js";
|
|
6
6
|
import { intlLocale } from "../translations/intl.js";
|
|
7
|
-
import { engineRead, pinnedScope, prepareWidgetRead } from "./prepareWidgetRead.js";
|
|
7
|
+
import { engineRead, pinnedScope, prepareWidgetRead, substitutionOf } from "./prepareWidgetRead.js";
|
|
8
8
|
import { readMeta } from "./readMeta.js";
|
|
9
9
|
import { resolveItemLabels } from "../plugin/itemLabels.js";
|
|
10
10
|
import { hasNoDeclaredGoals, isLatentGoalRow } from "../goals/latent.js";
|
|
@@ -23,6 +23,7 @@ const readForWidgetBreakdown = async (args) => {
|
|
|
23
23
|
timeframe,
|
|
24
24
|
adapterId,
|
|
25
25
|
...readPrincipalOf(args),
|
|
26
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
26
27
|
timezone: args.timezone,
|
|
27
28
|
range,
|
|
28
29
|
filters,
|
|
@@ -93,6 +94,7 @@ const readForWidgetBreakdown = async (args) => {
|
|
|
93
94
|
return {
|
|
94
95
|
status: "ok",
|
|
95
96
|
adapterId: adapter.id,
|
|
97
|
+
...substitutionOf(prepared),
|
|
96
98
|
...pinnedScope(args, prepared.queryScope),
|
|
97
99
|
dateRange,
|
|
98
100
|
timezone: tz,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport { metricReaches } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n\tMetricValue,\n\tMetricValues,\n} from '../core/contract'\nimport { emptyReading } from '../core/metricValues'\nimport { hasNoDeclaredGoals, isLatentGoalRow } from '../goals/latent'\nimport { resolveItemLabels } from '../plugin/itemLabels'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { asTranslate } from '../translations/server'\nimport { valueLabel } from '../view/labels'\nimport {\n\tengineRead,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport interface BreakdownRow {\n\t/**\n\t * What the reader sees, in the admin language as every built-in surface labels the row:\n\t * a goal's name, a country's, an item's title, `Not set` for a row with no value.\n\t */\n\tlabel: string\n\t/** The stored value, `''` for a row with no value: what a filter or a link to the view keeps. */\n\tdimensionValue: string\n\t/** `null` when the row has no reading for an average, which is no data rather than zero. */\n\tvalue: MetricValue\n\t/** Every metric the read asked for, present only when `extraMetrics` asked for more. */\n\tmetrics?: MetricValues\n}\n\nexport interface WidgetBreakdownResult extends Partial<ReadNotices> {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/** The reporting timezone the read resolved in, which names its days. */\n\ttimezone?: string\n\t/**\n\t * Scope a link to this read must name, set only when the viewer would not resolve it alone:\n\t * a needless `scope` refuses every reader without `access.crossScope`.\n\t */\n\tscope?: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** True when the read asked about goals and the scope declared none: an empty table. */\n\tnoGoals?: boolean\n\t/** The scope's goals behind a `goal` read's slugs, so its rows read as names. */\n\tgoals?: Array<{ slug: string; name: string }>\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetBreakdownArgs = ReadPrincipal & {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/**\n\t * Further metrics read beside the ranked one, narrowed to what the source serves so an\n\t * unsupported one never fails the read. Ranking and status follow `metric` alone.\n\t */\n\textraMetrics?: MetricKey[]\n\t/**\n\t * Scope's goal slugs for a `goal` or `conversions` read, or `'unresolved'` if the caller's\n\t * resolver failed. Resolved here when omitted.\n\t */\n\tgoalSlugs?: string[] | 'unresolved'\n\t/** The latent built-in slugs behind that hint; resolved here when omitted. */\n\tbuiltinGoalSlugs?: string[]\n}\n\n/**\n * Ranked breakdown of one metric by one dimension: `readForWidget` gated on the dimension too,\n * each row labelled as built-in widgets label it. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range, filters } = args\n\tconst metricsFor = (adapter: AnalyticsAdapter): MetricKey[] => [\n\t\tmetric,\n\t\t...(args.extraMetrics ?? []).filter(\n\t\t\t(m) =>\n\t\t\t\tm !== metric &&\n\t\t\t\tadapter.capabilities.metrics.has(m) &&\n\t\t\t\tmetricReaches(adapter.capabilities, m, { dimensions: [dimension] })\n\t\t),\n\t]\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics: [metric], dimensions: [dimension] },\n\t\tgoalRead: (adapter) => ({ metrics: metricsFor(adapter), dimensions: [dimension] }),\n\t\tgoalSlugs: args.goalSlugs,\n\t\t...(args.builtinGoalSlugs === undefined ? {} : { builtinGoalSlugs: args.builtinGoalSlugs }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\trows: [],\n\t\t}\n\t}\n\tconst { adapter, tz, dateRange, goalSlugs, builtinGoalSlugs, goalNames } = prepared\n\tconst metrics = metricsFor(adapter)\n\tconst read = engineRead(prepared, timeframe)\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await read({\n\t\t\tmetrics,\n\t\t\tdimensions: [dimension],\n\t\t\tdateRange,\n\t\t\tlimit,\n\t\t\torder: { metric, direction: 'desc' },\n\t\t\tfilters,\n\t\t\ttimezone: tz,\n\t\t\tscope: prepared.queryScope,\n\t\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t\t})\n\t} catch (err) {\n\t\t// A failed read is a status, never a throw through the render tree.\n\t\treturn { ...readFailureOf(err), adapterId: adapter.id, dateRange, rows: [] }\n\t}\n\tconst kept = result.rows\n\t\t.map((row) => ({\n\t\t\tdimensionValue: row.dimensions?.[dimension] ?? '',\n\t\t\tvalue: row.metrics[metric] ?? emptyReading(metric),\n\t\t\t...(metrics.length > 1 ? { metrics: row.metrics } : {}),\n\t\t}))\n\t\t// A built-in goal is latent: it earns a row once someone has converted on it, and until\n\t\t// then a site that sells nothing would read a \"Purchase\" row at zero in every report.\n\t\t.filter(\n\t\t\t(row) =>\n\t\t\t\tdimension !== 'goal' ||\n\t\t\t\t!isLatentGoalRow(\n\t\t\t\t\trow.dimensionValue,\n\t\t\t\t\tmetric === 'conversions' ? row.value : row.metrics?.conversions,\n\t\t\t\t\tbuiltinGoalSlugs\n\t\t\t\t)\n\t\t)\n\tconst itemLabels =\n\t\tdimension === 'item'\n\t\t\t? await resolveItemLabels(\n\t\t\t\t\treq,\n\t\t\t\t\tkept.map((row) => row.dimensionValue)\n\t\t\t\t).catch((): undefined => undefined)\n\t\t\t: undefined\n\t// A request built without Payload's i18n (a bare Local API caller) has no words to label with.\n\tconst translate = req.i18n?.t\n\tconst locale = intlLocale(req.i18n?.language)\n\tconst rows: BreakdownRow[] = kept.map((row) => ({\n\t\tlabel:\n\t\t\ttranslate === undefined\n\t\t\t\t? row.dimensionValue\n\t\t\t\t: valueLabel({\n\t\t\t\t\t\tdimension,\n\t\t\t\t\t\tvalue: row.dimensionValue,\n\t\t\t\t\t\tprovider: result.meta.provider,\n\t\t\t\t\t\tt: asTranslate(translate),\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tgoals: goalNames,\n\t\t\t\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t\t\t\t}),\n\t\t...row,\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...pinnedScope(args, prepared.queryScope),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...readMeta(result),\n\t\t// The hint is set only for a read about goals, so one carrying nothing the install\n\t\t// declared is a scope that configured none rather than a read that never asked.\n\t\tnoGoals: Array.isArray(goalSlugs) && hasNoDeclaredGoals(goalSlugs, builtinGoalSlugs),\n\t\t...(dimension === 'goal' && goalNames.length > 0 ? { goals: goalNames } : {}),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmGA,MAAa,yBAAyB,OACrC,SACoC;CACpC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,OAAO,WAAW,KAAK,OAAO,YAAY;CACrF,MAAM,cAAc,YAA2C,CAC9D,QACA,IAAI,KAAK,gBAAgB,CAAC,GAAG,QAC3B,MACA,MAAM,UACN,QAAQ,aAAa,QAAQ,IAAI,CAAC,KAClC,cAAc,QAAQ,cAAc,GAAG,EAAE,YAAY,CAAC,SAAS,EAAE,CAAC,CACpE,CACD;CACA,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,GAAG,gBA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,CACrC,EAAE,YAAuB,KAAA,CAAS,IACjC,KAAA;CAEJ,MAAM,YAAY,IAAI,MAAM;CAC5B,MAAM,SAAS,WAAW,IAAI,MAAM,QAAQ;CAC5C,MAAM,OAAuB,KAAK,KAAK,SAAS;EAC/C,OACC,cAAc,KAAA,IACX,IAAI,iBACJ,WAAW;GACX;GACA,OAAO,IAAI;GACX,UAAU,OAAO,KAAK;GACtB,GAAG,YAAY,SAAS;GACxB;GACA,OAAO;GACP,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACpC,CAAC;EACJ,GAAG;CACJ,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB,GAAG,YAAY,MAAM,SAAS,UAAU;EACxC;EACA,UAAU;EACV;EACA,GAAG,SAAS,MAAM;EAGlB,SAAS,MAAM,QAAQ,SAAS,KAAK,mBAAmB,WAAW,gBAAgB;EACnF,GAAI,cAAc,UAAU,UAAU,SAAS,IAAI,EAAE,OAAO,UAAU,IAAI,CAAC;CAC5E;AACD"}
|
|
1
|
+
{"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport { metricReaches } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n\tMetricValue,\n\tMetricValues,\n} from '../core/contract'\nimport { emptyReading } from '../core/metricValues'\nimport { hasNoDeclaredGoals, isLatentGoalRow } from '../goals/latent'\nimport { resolveItemLabels } from '../plugin/itemLabels'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { intlLocale } from '../translations/intl'\nimport { asTranslate } from '../translations/server'\nimport { valueLabel } from '../view/labels'\nimport {\n\tengineRead,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport interface BreakdownRow {\n\t/**\n\t * What the reader sees, in the admin language as every built-in surface labels the row:\n\t * a goal's name, a country's, an item's title, `Not set` for a row with no value.\n\t */\n\tlabel: string\n\t/** The stored value, `''` for a row with no value: what a filter or a link to the view keeps. */\n\tdimensionValue: string\n\t/** `null` when the row has no reading for an average, which is no data rather than zero. */\n\tvalue: MetricValue\n\t/** Every metric the read asked for, present only when `extraMetrics` asked for more. */\n\tmetrics?: MetricValues\n}\n\nexport interface WidgetBreakdownResult extends Partial<ReadNotices>, SubstitutedSource {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/** The reporting timezone the read resolved in, which names its days. */\n\ttimezone?: string\n\t/**\n\t * Scope a link to this read must name, set only when the viewer would not resolve it alone:\n\t * a needless `scope` refuses every reader without `access.crossScope`.\n\t */\n\tscope?: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** True when the read asked about goals and the scope declared none: an empty table. */\n\tnoGoals?: boolean\n\t/** The scope's goals behind a `goal` read's slugs, so its rows read as names. */\n\tgoals?: Array<{ slug: string; name: string }>\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetBreakdownArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\tmetric: MetricKey\n\t\tdimension: DimensionKey\n\t\ttimeframe: TimeframePreset\n\t\tlimit: number\n\t\tadapterId?: string\n\t\tnow: Date\n\t\trange?: DateRange\n\t\t/**\n\t\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t\t */\n\t\ttimezone?: string\n\t\tfilters?: AnalyticsFilter[]\n\t\t/**\n\t\t * Further metrics read beside the ranked one, narrowed to what the source serves so an\n\t\t * unsupported one never fails the read. Ranking and status follow `metric` alone.\n\t\t */\n\t\textraMetrics?: MetricKey[]\n\t\t/**\n\t\t * Scope's goal slugs for a `goal` or `conversions` read, or `'unresolved'` if the caller's\n\t\t * resolver failed. Resolved here when omitted.\n\t\t */\n\t\tgoalSlugs?: string[] | 'unresolved'\n\t\t/** The latent built-in slugs behind that hint; resolved here when omitted. */\n\t\tbuiltinGoalSlugs?: string[]\n\t}\n\n/**\n * Ranked breakdown of one metric by one dimension: `readForWidget` gated on the dimension too,\n * each row labelled as built-in widgets label it. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range, filters } = args\n\tconst metricsFor = (adapter: AnalyticsAdapter): MetricKey[] => [\n\t\tmetric,\n\t\t...(args.extraMetrics ?? []).filter(\n\t\t\t(m) =>\n\t\t\t\tm !== metric &&\n\t\t\t\tadapter.capabilities.metrics.has(m) &&\n\t\t\t\tmetricReaches(adapter.capabilities, m, { dimensions: [dimension] })\n\t\t),\n\t]\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics: [metric], dimensions: [dimension] },\n\t\tgoalRead: (adapter) => ({ metrics: metricsFor(adapter), dimensions: [dimension] }),\n\t\tgoalSlugs: args.goalSlugs,\n\t\t...(args.builtinGoalSlugs === undefined ? {} : { builtinGoalSlugs: args.builtinGoalSlugs }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\trows: [],\n\t\t}\n\t}\n\tconst { adapter, tz, dateRange, goalSlugs, builtinGoalSlugs, goalNames } = prepared\n\tconst metrics = metricsFor(adapter)\n\tconst read = engineRead(prepared, timeframe)\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await read({\n\t\t\tmetrics,\n\t\t\tdimensions: [dimension],\n\t\t\tdateRange,\n\t\t\tlimit,\n\t\t\torder: { metric, direction: 'desc' },\n\t\t\tfilters,\n\t\t\ttimezone: tz,\n\t\t\tscope: prepared.queryScope,\n\t\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t\t})\n\t} catch (err) {\n\t\t// A failed read is a status, never a throw through the render tree.\n\t\treturn { ...readFailureOf(err), adapterId: adapter.id, dateRange, rows: [] }\n\t}\n\tconst kept = result.rows\n\t\t.map((row) => ({\n\t\t\tdimensionValue: row.dimensions?.[dimension] ?? '',\n\t\t\tvalue: row.metrics[metric] ?? emptyReading(metric),\n\t\t\t...(metrics.length > 1 ? { metrics: row.metrics } : {}),\n\t\t}))\n\t\t// A built-in goal is latent: it earns a row once someone has converted on it, and until\n\t\t// then a site that sells nothing would read a \"Purchase\" row at zero in every report.\n\t\t.filter(\n\t\t\t(row) =>\n\t\t\t\tdimension !== 'goal' ||\n\t\t\t\t!isLatentGoalRow(\n\t\t\t\t\trow.dimensionValue,\n\t\t\t\t\tmetric === 'conversions' ? row.value : row.metrics?.conversions,\n\t\t\t\t\tbuiltinGoalSlugs\n\t\t\t\t)\n\t\t)\n\tconst itemLabels =\n\t\tdimension === 'item'\n\t\t\t? await resolveItemLabels(\n\t\t\t\t\treq,\n\t\t\t\t\tkept.map((row) => row.dimensionValue)\n\t\t\t\t).catch((): undefined => undefined)\n\t\t\t: undefined\n\t// A request built without Payload's i18n (a bare Local API caller) has no words to label with.\n\tconst translate = req.i18n?.t\n\tconst locale = intlLocale(req.i18n?.language)\n\tconst rows: BreakdownRow[] = kept.map((row) => ({\n\t\tlabel:\n\t\t\ttranslate === undefined\n\t\t\t\t? row.dimensionValue\n\t\t\t\t: valueLabel({\n\t\t\t\t\t\tdimension,\n\t\t\t\t\t\tvalue: row.dimensionValue,\n\t\t\t\t\t\tprovider: result.meta.provider,\n\t\t\t\t\t\tt: asTranslate(translate),\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tgoals: goalNames,\n\t\t\t\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t\t\t\t}),\n\t\t...row,\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...substitutionOf(prepared),\n\t\t...pinnedScope(args, prepared.queryScope),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...readMeta(result),\n\t\t// The hint is set only for a read about goals, so one carrying nothing the install\n\t\t// declared is a scope that configured none rather than a read that never asked.\n\t\tnoGoals: Array.isArray(goalSlugs) && hasNoDeclaredGoals(goalSlugs, builtinGoalSlugs),\n\t\t...(dimension === 'goal' && goalNames.length > 0 ? { goals: goalNames } : {}),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuGA,MAAa,yBAAyB,OACrC,SACoC;CACpC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,OAAO,WAAW,KAAK,OAAO,YAAY;CACrF,MAAM,cAAc,YAA2C,CAC9D,QACA,IAAI,KAAK,gBAAgB,CAAC,GAAG,QAC3B,MACA,MAAM,UACN,QAAQ,aAAa,QAAQ,IAAI,CAAC,KAClC,cAAc,QAAQ,cAAc,GAAG,EAAE,YAAY,CAAC,SAAS,EAAE,CAAC,CACpE,CACD;CACA,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,GAAG,gBAAgB,IAAI;EACvB,GAAI,KAAK,yBAAyB,EAAE,wBAAwB,KAAK,IAAI,CAAC;EACtE,UAAU,KAAK;EACf;EACA;EACA,UAAU;GAAE,SAAS,CAAC,MAAM;GAAG,YAAY,CAAC,SA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,WAAW,IAAI,MAAM,QAAQ;CAC5C,MAAM,OAAuB,KAAK,KAAK,SAAS;EAC/C,OACC,cAAc,KAAA,IACX,IAAI,iBACJ,WAAW;GACX;GACA,OAAO,IAAI;GACX,UAAU,OAAO,KAAK;GACtB,GAAG,YAAY,SAAS;GACxB;GACA,OAAO;GACP,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACpC,CAAC;EACJ,GAAG;CACJ,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB,GAAG,eAAe,QAAQ;EAC1B,GAAG,YAAY,MAAM,SAAS,UAAU;EACxC;EACA,UAAU;EACV;EACA,GAAG,SAAS,MAAM;EAGlB,SAAS,MAAM,QAAQ,SAAS,KAAK,mBAAmB,WAAW,gBAAgB;EACnF,GAAI,cAAc,UAAU,UAAU,SAAS,IAAI,EAAE,OAAO,UAAU,IAAI,CAAC;CAC5E;AACD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { DateRange } from "../core/contract.js";
|
|
2
|
+
import { ReadPrincipal } from "../access/principal.js";
|
|
2
3
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
4
|
import { ReadNotices } from "./readMeta.js";
|
|
4
|
-
import {
|
|
5
|
-
import { WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
5
|
+
import { StoredSourceRead, SubstitutedSource, WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
6
6
|
import { PayloadRequest } from "payload";
|
|
7
7
|
|
|
8
8
|
//#region src/widgets/readForWidgetGoals.d.ts
|
|
@@ -16,7 +16,7 @@ interface GoalRow {
|
|
|
16
16
|
rate?: number;
|
|
17
17
|
previousConversions?: number;
|
|
18
18
|
}
|
|
19
|
-
interface WidgetGoalsResult extends Partial<ReadNotices
|
|
19
|
+
interface WidgetGoalsResult extends Partial<ReadNotices>, SubstitutedSource {
|
|
20
20
|
status: WidgetReadStatus;
|
|
21
21
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
22
22
|
retryAfterMs?: number;
|
|
@@ -37,7 +37,7 @@ interface WidgetGoalsResult extends Partial<ReadNotices> {
|
|
|
37
37
|
noGoals?: boolean;
|
|
38
38
|
}
|
|
39
39
|
/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */
|
|
40
|
-
type ReadForWidgetGoalsArgs = ReadPrincipal & {
|
|
40
|
+
type ReadForWidgetGoalsArgs = ReadPrincipal & StoredSourceRead & {
|
|
41
41
|
req: PayloadRequest;
|
|
42
42
|
timeframe: TimeframePreset;
|
|
43
43
|
limit: number; /** Read the previous window too, when the source can compare. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readPrincipalOf } from "../access/principal.js";
|
|
2
2
|
import { goalNamesFor, resolveGoalsDetailedFor } from "../plugin/runtime.js";
|
|
3
|
-
import { comparisonWindow, pinnedScope, prepareWidgetRead } from "./prepareWidgetRead.js";
|
|
3
|
+
import { comparisonWindow, pinnedScope, prepareWidgetRead, substitutionOf } from "./prepareWidgetRead.js";
|
|
4
4
|
import { mergeNotices } from "./readMeta.js";
|
|
5
5
|
import { readForWidget } from "./readForWidget.js";
|
|
6
6
|
import { readForWidgetBreakdown } from "./readForWidgetBreakdown.js";
|
|
@@ -53,6 +53,7 @@ const readForWidgetGoals = async (args) => {
|
|
|
53
53
|
timeframe,
|
|
54
54
|
adapterId,
|
|
55
55
|
...readPrincipalOf(args),
|
|
56
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
56
57
|
timezone: args.timezone,
|
|
57
58
|
range: args.range
|
|
58
59
|
});
|
|
@@ -127,6 +128,7 @@ const readForWidgetGoals = async (args) => {
|
|
|
127
128
|
return {
|
|
128
129
|
status: "ok",
|
|
129
130
|
adapterId: adapter.id,
|
|
131
|
+
...substitutionOf(prepared),
|
|
130
132
|
...pinnedScope(args, prepared.queryScope),
|
|
131
133
|
dateRange,
|
|
132
134
|
timezone: tz,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetGoals.js","names":[],"sources":["../../src/widgets/readForWidgetGoals.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport type { DateRange } from '../core/contract'\nimport { type AnalyticsRuntime, goalNamesFor, resolveGoalsDetailedFor } from '../plugin/runtime'\nimport { MAX_QUERY_LIMIT } from '../query/limits'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { conversionRate } from '../view/conversionRate'\nimport {\n\tcomparisonWindow,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { readForWidget } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\nimport { mergeNotices, type ReadNotices } from './readMeta'\n\nexport interface GoalRow {\n\tslug: string\n\t/** The goal's admin-facing name, or its slug when no configured goal claims it. */\n\tname: string\n\tconversions: number\n\trevenue?: number\n\t/** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */\n\trate?: number\n\tpreviousConversions?: number\n}\n\nexport interface WidgetGoalsResult extends Partial<ReadNotices> {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/**\n\t * Scope a link to this read must name, set only when the viewer would not resolve it alone:\n\t * a needless `scope` refuses every reader without `access.crossScope`.\n\t */\n\tscope?: string\n\tdateRange: DateRange\n\ttimezone: string\n\trows: GoalRow[]\n\t/** Range total the rate divides by; absent when the source does not serve visitors. */\n\tsiteVisitors?: number\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** True when the scope declares no goals of its own: an empty table, not a failure. */\n\tnoGoals?: boolean\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetGoalsArgs = ReadPrincipal & {\n\treq: PayloadRequest\n\ttimeframe: TimeframePreset\n\tlimit: number\n\t/** Read the previous window too, when the source can compare. */\n\tcompare: boolean\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n}\n\n/**\n * How much wider than the table the previous window is read: each window ranks by its own\n * conversions, so a goal in today's top rows may rank too low there to keep its delta.\n */\nconst PREVIOUS_LIMIT_FACTOR = 4\n\nconst previousLimit = (limit: number): number =>\n\tMath.min(limit * PREVIOUS_LIMIT_FACTOR, MAX_QUERY_LIMIT)\n\n/**\n * The scope's goal slugs and their display names. A throwing resolver must not cost the table:\n * rows fall back to slugs and `'unresolved'` tells the read apart from a scope with no goals.\n */\nconst goalNames = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<{ slugs: string[]; names: Map<string, string>; builtin: string[] } | 'unresolved'> => {\n\ttry {\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\tconst shown = await goalNamesFor({ runtime, req, scope, resolved })\n\t\treturn {\n\t\t\tslugs: resolved.map(({ goal }) => goal.slug),\n\t\t\tnames: new Map(shown.map((goal) => [goal.slug, goal.name])),\n\t\t\tbuiltin: resolved.filter((entry) => entry.source === 'builtin').map(({ goal }) => goal.slug),\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`)\n\t\treturn 'unresolved'\n\t}\n}\n\n/**\n * Goals table from a `goal` breakdown, a visitors total for the rate and, when comparing, the\n * previous window's breakdown. Status is the breakdown's: a table without rows shows nothing.\n */\nexport const readForWidgetGoals = async (\n\targs: ReadForWidgetGoalsArgs\n): Promise<WidgetGoalsResult> => {\n\tconst { req, timeframe, limit, compare, adapterId, now } = args\n\tconst fallback = (\n\t\tstatus: WidgetReadStatus,\n\t\tid: string,\n\t\twindow: { dateRange: DateRange; timezone: string }\n\t): WidgetGoalsResult => ({ status, adapterId: id, rows: [], ...window })\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\ttimezone: args.timezone,\n\t\trange: args.range,\n\t})\n\tif (!prepared.ok) {\n\t\treturn fallback(prepared.status, prepared.adapterId, {\n\t\t\tdateRange: prepared.dateRange,\n\t\t\ttimezone: prepared.tz,\n\t\t})\n\t}\n\tconst { runtime, adapter, tz, dateRange } = prepared\n\t// The sub-reads resolve their own context; pinning the adapter, scope, timezone and\n\t// window keeps all three answering about exactly the same read.\n\tconst shared = { req, timeframe, adapterId: adapter.id, ...prepared.pin, timezone: tz, now }\n\tconst comparisonRange = compare ? comparisonWindow(prepared, now) : undefined\n\n\t// The names are resolved first: their slugs are the hint a provider source restricts its\n\t// goal rows to, so both reads below need them before they run.\n\tconst resolved = await goalNames(runtime, req, prepared.scope)\n\tconst names = resolved === 'unresolved' ? new Map<string, string>() : resolved.names\n\tconst builtinGoalSlugs = resolved === 'unresolved' ? [] : resolved.builtin\n\tconst goalSlugs = resolved === 'unresolved' ? 'unresolved' : resolved.slugs\n\tconst [breakdown, totals, previous] = await Promise.all([\n\t\treadForWidgetBreakdown({\n\t\t\t...shared,\n\t\t\trange: dateRange,\n\t\t\tmetric: 'conversions',\n\t\t\tdimension: 'goal',\n\t\t\tlimit,\n\t\t\textraMetrics: ['revenue', 'visitors'],\n\t\t\tgoalSlugs,\n\t\t\tbuiltinGoalSlugs,\n\t\t}),\n\t\tadapter.capabilities.metrics.has('visitors')\n\t\t\t? // The site total is a denominator, never a delta: its own previous window would\n\t\t\t\t// be a second read nothing renders.\n\t\t\t\treadForWidget({ ...shared, range: dateRange, metrics: ['visitors'], comparison: false })\n\t\t\t: undefined,\n\t\tcomparisonRange\n\t\t\t? readForWidgetBreakdown({\n\t\t\t\t\t...shared,\n\t\t\t\t\trange: comparisonRange,\n\t\t\t\t\tmetric: 'conversions',\n\t\t\t\t\tdimension: 'goal',\n\t\t\t\t\tlimit: previousLimit(limit),\n\t\t\t\t\tgoalSlugs,\n\t\t\t\t\tbuiltinGoalSlugs,\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\tif (breakdown.status !== 'ok') {\n\t\treturn {\n\t\t\t...fallback(breakdown.status, breakdown.adapterId, { dateRange, timezone: tz }),\n\t\t\t...(breakdown.retryAfterMs === undefined ? {} : { retryAfterMs: breakdown.retryAfterMs }),\n\t\t}\n\t}\n\n\tconst previousBySlug = new Map(\n\t\t(previous?.status === 'ok' ? previous.rows : []).map((row) => [row.dimensionValue, row.value])\n\t)\n\tconst visitorTotal = totals?.status === 'ok' ? totals.metrics.visitors : undefined\n\tconst siteVisitors = typeof visitorTotal === 'number' ? visitorTotal : undefined\n\tconst rows: GoalRow[] = breakdown.rows\n\t\t.map((row) => {\n\t\t\tconst rate = conversionRate(row.metrics?.visitors, siteVisitors)\n\t\t\tconst previousConversions = previousBySlug.get(row.dimensionValue)\n\t\t\tconst revenue = row.metrics?.revenue\n\t\t\treturn {\n\t\t\t\tslug: row.dimensionValue,\n\t\t\t\tname: names.get(row.dimensionValue) ?? row.dimensionValue,\n\t\t\t\tconversions: row.value ?? 0,\n\t\t\t\t...(typeof revenue === 'number' ? { revenue } : {}),\n\t\t\t\t...(rate !== null ? { rate } : {}),\n\t\t\t\t...(typeof previousConversions === 'number' ? { previousConversions } : {}),\n\t\t\t}\n\t\t})\n\t\t// The adapter ranks and caps already; re-applying both keeps one that does not from\n\t\t// spilling a long, unranked table into a dashboard card.\n\t\t.sort((a, b) => b.conversions - a.conversions)\n\t\t.slice(0, limit)\n\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t// The caller's own scope, not the one this pinned onto its sub-reads: those are always\n\t\t// explicitly scoped, so reading their answer back would name every viewer's own scope.\n\t\t...pinnedScope(args, prepared.queryScope),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...(siteVisitors !== undefined ? { siteVisitors } : {}),\n\t\t...(breakdown.provider === undefined ? {} : { provider: breakdown.provider }),\n\t\t...mergeNotices(breakdown, totals, previous),\n\t\tgoalsUnresolved: breakdown.goalsUnresolved === true,\n\t\tnoGoals: breakdown.noGoals === true,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAsEA,MAAM,wBAAwB;AAE9B,MAAM,iBAAiB,UACtB,KAAK,IAAI,QAAQ,uBAAA,GAAsC;;;;;AAMxD,MAAM,YAAY,OACjB,SACA,KACA,UACgG;CAChG,IAAI;EACH,MAAM,WAAW,MAAM,wBAAwB,SAAS,KAAK,KAAK;EAClE,MAAM,QAAQ,MAAM,aAAa;GAAE;GAAS;GAAK;GAAO;EAAS,CAAC;EAClE,OAAO;GACN,OAAO,SAAS,KAAK,EAAE,WAAW,KAAK,IAAI;GAC3C,OAAO,IAAI,IAAI,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC;GAC1D,SAAS,SAAS,QAAQ,UAAU,MAAM,WAAW,SAAS,EAAE,KAAK,EAAE,WAAW,KAAK,IAAI;EAC5F;CACD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,mDAAmD,OAAO,GAAG,GAAG;EACzF,OAAO;CACR;AACD;;;;;AAMA,MAAa,qBAAqB,OACjC,SACgC;CAChC,MAAM,EAAE,KAAK,WAAW,OAAO,SAAS,WAAW,QAAQ;CAC3D,MAAM,YACL,QACA,IACA,YACwB;EAAE;EAAQ,WAAW;EAAI,MAAM,CAAC;EAAG,GAAG;CAAO;CAEtE,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,GAAG,gBAAgB,IAAI;EACvB,UAAU,KAAK;EACf,OAAO,KAAK;CACb,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO,SAAS,SAAS,QAAQ,SAAS,WAAW;EACpD,WAAW,SAAS;EACpB,UAAU,SAAS;CACpB,CAAC;CAEF,MAAM,EAAE,SAAS,SAAS,IAAI,cAAc;CAG5C,MAAM,S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M,OAAkB,UAAU,KAChC,KAAK,QAAQ;EACb,MAAM,OAAO,eAAe,IAAI,SAAS,UAAU,YAAY;EAC/D,MAAM,sBAAsB,eAAe,IAAI,IAAI,cAAc;EACjE,MAAM,UAAU,IAAI,SAAS;EAC7B,OAAO;GACN,MAAM,IAAI;GACV,MAAM,MAAM,IAAI,IAAI,cAAc,KAAK,IAAI;GAC3C,aAAa,IAAI,SAAS;GAC1B,GAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,IAAI,CAAC;GACjD,GAAI,SAAS,OAAO,EAAE,KAAK,IAAI,CAAC;GAChC,GAAI,OAAO,wBAAwB,WAAW,EAAE,oBAAoB,IAAI,CAAC;EAC1E;CACD,CAAC,EAGA,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,WAAW,EAC5C,MAAM,GAAG,KAAK;CAEhB,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EAGnB,GAAG,YAAY,MAAM,SAAS,UAAU;EACxC;EACA,UAAU;EACV;EACA,GAAI,iBAAiB,KAAA,IAAY,EAAE,aAAa,IAAI,CAAC;EACrD,GAAI,UAAU,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,UAAU,SAAS;EAC3E,GAAG,aAAa,WAAW,QAAQ,QAAQ;EAC3C,iBAAiB,UAAU,oBAAoB;EAC/C,SAAS,UAAU,YAAY;CAChC;AACD"}
|
|
1
|
+
{"version":3,"file":"readForWidgetGoals.js","names":[],"sources":["../../src/widgets/readForWidgetGoals.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport type { DateRange } from '../core/contract'\nimport { type AnalyticsRuntime, goalNamesFor, resolveGoalsDetailedFor } from '../plugin/runtime'\nimport { MAX_QUERY_LIMIT } from '../query/limits'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { conversionRate } from '../view/conversionRate'\nimport {\n\tcomparisonWindow,\n\tpinnedScope,\n\tprepareWidgetRead,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { readForWidget } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\nimport { mergeNotices, type ReadNotices } from './readMeta'\n\nexport interface GoalRow {\n\tslug: string\n\t/** The goal's admin-facing name, or its slug when no configured goal claims it. */\n\tname: string\n\tconversions: number\n\trevenue?: number\n\t/** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */\n\trate?: number\n\tpreviousConversions?: number\n}\n\nexport interface WidgetGoalsResult extends Partial<ReadNotices>, SubstitutedSource {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/**\n\t * Scope a link to this read must name, set only when the viewer would not resolve it alone:\n\t * a needless `scope` refuses every reader without `access.crossScope`.\n\t */\n\tscope?: string\n\tdateRange: DateRange\n\ttimezone: string\n\trows: GoalRow[]\n\t/** Range total the rate divides by; absent when the source does not serve visitors. */\n\tsiteVisitors?: number\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** True when the scope declares no goals of its own: an empty table, not a failure. */\n\tnoGoals?: boolean\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetGoalsArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\ttimeframe: TimeframePreset\n\t\tlimit: number\n\t\t/** Read the previous window too, when the source can compare. */\n\t\tcompare: boolean\n\t\tadapterId?: string\n\t\tnow: Date\n\t\trange?: DateRange\n\t\t/**\n\t\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t\t */\n\t\ttimezone?: string\n\t}\n\n/**\n * How much wider than the table the previous window is read: each window ranks by its own\n * conversions, so a goal in today's top rows may rank too low there to keep its delta.\n */\nconst PREVIOUS_LIMIT_FACTOR = 4\n\nconst previousLimit = (limit: number): number =>\n\tMath.min(limit * PREVIOUS_LIMIT_FACTOR, MAX_QUERY_LIMIT)\n\n/**\n * The scope's goal slugs and their display names. A throwing resolver must not cost the table:\n * rows fall back to slugs and `'unresolved'` tells the read apart from a scope with no goals.\n */\nconst goalNames = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<{ slugs: string[]; names: Map<string, string>; builtin: string[] } | 'unresolved'> => {\n\ttry {\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\tconst shown = await goalNamesFor({ runtime, req, scope, resolved })\n\t\treturn {\n\t\t\tslugs: resolved.map(({ goal }) => goal.slug),\n\t\t\tnames: new Map(shown.map((goal) => [goal.slug, goal.name])),\n\t\t\tbuiltin: resolved.filter((entry) => entry.source === 'builtin').map(({ goal }) => goal.slug),\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`)\n\t\treturn 'unresolved'\n\t}\n}\n\n/**\n * Goals table from a `goal` breakdown, a visitors total for the rate and, when comparing, the\n * previous window's breakdown. Status is the breakdown's: a table without rows shows nothing.\n */\nexport const readForWidgetGoals = async (\n\targs: ReadForWidgetGoalsArgs\n): Promise<WidgetGoalsResult> => {\n\tconst { req, timeframe, limit, compare, adapterId, now } = args\n\tconst fallback = (\n\t\tstatus: WidgetReadStatus,\n\t\tid: string,\n\t\twindow: { dateRange: DateRange; timezone: string }\n\t): WidgetGoalsResult => ({ status, adapterId: id, rows: [], ...window })\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\ttimezone: args.timezone,\n\t\trange: args.range,\n\t})\n\tif (!prepared.ok) {\n\t\treturn fallback(prepared.status, prepared.adapterId, {\n\t\t\tdateRange: prepared.dateRange,\n\t\t\ttimezone: prepared.tz,\n\t\t})\n\t}\n\tconst { runtime, adapter, tz, dateRange } = prepared\n\t// The sub-reads resolve their own context; pinning the adapter, scope, timezone and\n\t// window keeps all three answering about exactly the same read.\n\tconst shared = { req, timeframe, adapterId: adapter.id, ...prepared.pin, timezone: tz, now }\n\tconst comparisonRange = compare ? comparisonWindow(prepared, now) : undefined\n\n\t// The names are resolved first: their slugs are the hint a provider source restricts its\n\t// goal rows to, so both reads below need them before they run.\n\tconst resolved = await goalNames(runtime, req, prepared.scope)\n\tconst names = resolved === 'unresolved' ? new Map<string, string>() : resolved.names\n\tconst builtinGoalSlugs = resolved === 'unresolved' ? [] : resolved.builtin\n\tconst goalSlugs = resolved === 'unresolved' ? 'unresolved' : resolved.slugs\n\tconst [breakdown, totals, previous] = await Promise.all([\n\t\treadForWidgetBreakdown({\n\t\t\t...shared,\n\t\t\trange: dateRange,\n\t\t\tmetric: 'conversions',\n\t\t\tdimension: 'goal',\n\t\t\tlimit,\n\t\t\textraMetrics: ['revenue', 'visitors'],\n\t\t\tgoalSlugs,\n\t\t\tbuiltinGoalSlugs,\n\t\t}),\n\t\tadapter.capabilities.metrics.has('visitors')\n\t\t\t? // The site total is a denominator, never a delta: its own previous window would\n\t\t\t\t// be a second read nothing renders.\n\t\t\t\treadForWidget({ ...shared, range: dateRange, metrics: ['visitors'], comparison: false })\n\t\t\t: undefined,\n\t\tcomparisonRange\n\t\t\t? readForWidgetBreakdown({\n\t\t\t\t\t...shared,\n\t\t\t\t\trange: comparisonRange,\n\t\t\t\t\tmetric: 'conversions',\n\t\t\t\t\tdimension: 'goal',\n\t\t\t\t\tlimit: previousLimit(limit),\n\t\t\t\t\tgoalSlugs,\n\t\t\t\t\tbuiltinGoalSlugs,\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\tif (breakdown.status !== 'ok') {\n\t\treturn {\n\t\t\t...fallback(breakdown.status, breakdown.adapterId, { dateRange, timezone: tz }),\n\t\t\t...(breakdown.retryAfterMs === undefined ? {} : { retryAfterMs: breakdown.retryAfterMs }),\n\t\t}\n\t}\n\n\tconst previousBySlug = new Map(\n\t\t(previous?.status === 'ok' ? previous.rows : []).map((row) => [row.dimensionValue, row.value])\n\t)\n\tconst visitorTotal = totals?.status === 'ok' ? totals.metrics.visitors : undefined\n\tconst siteVisitors = typeof visitorTotal === 'number' ? visitorTotal : undefined\n\tconst rows: GoalRow[] = breakdown.rows\n\t\t.map((row) => {\n\t\t\tconst rate = conversionRate(row.metrics?.visitors, siteVisitors)\n\t\t\tconst previousConversions = previousBySlug.get(row.dimensionValue)\n\t\t\tconst revenue = row.metrics?.revenue\n\t\t\treturn {\n\t\t\t\tslug: row.dimensionValue,\n\t\t\t\tname: names.get(row.dimensionValue) ?? row.dimensionValue,\n\t\t\t\tconversions: row.value ?? 0,\n\t\t\t\t...(typeof revenue === 'number' ? { revenue } : {}),\n\t\t\t\t...(rate !== null ? { rate } : {}),\n\t\t\t\t...(typeof previousConversions === 'number' ? { previousConversions } : {}),\n\t\t\t}\n\t\t})\n\t\t// The adapter ranks and caps already; re-applying both keeps one that does not from\n\t\t// spilling a long, unranked table into a dashboard card.\n\t\t.sort((a, b) => b.conversions - a.conversions)\n\t\t.slice(0, limit)\n\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...substitutionOf(prepared),\n\t\t// The caller's own scope, not the one this pinned onto its sub-reads: those are always\n\t\t// explicitly scoped, so reading their answer back would name every viewer's own scope.\n\t\t...pinnedScope(args, prepared.queryScope),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...(siteVisitors !== undefined ? { siteVisitors } : {}),\n\t\t...(breakdown.provider === undefined ? {} : { provider: breakdown.provider }),\n\t\t...mergeNotices(breakdown, totals, previous),\n\t\tgoalsUnresolved: breakdown.goalsUnresolved === true,\n\t\tnoGoals: breakdown.noGoals === true,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0EA,MAAM,wBAAwB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c;EACjE,MAAM,UAAU,IAAI,SAAS;EAC7B,OAAO;GACN,MAAM,IAAI;GACV,MAAM,MAAM,IAAI,IAAI,cAAc,KAAK,IAAI;GAC3C,aAAa,IAAI,SAAS;GAC1B,GAAI,OAAO,YAAY,WAAW,EAAE,QAAQ,IAAI,CAAC;GACjD,GAAI,SAAS,OAAO,EAAE,KAAK,IAAI,CAAC;GAChC,GAAI,OAAO,wBAAwB,WAAW,EAAE,oBAAoB,IAAI,CAAC;EAC1E;CACD,CAAC,EAGA,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,WAAW,EAC5C,MAAM,GAAG,KAAK;CAEhB,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB,GAAG,eAAe,QAAQ;EAG1B,GAAG,YAAY,MAAM,SAAS,UAAU;EACxC;EACA,UAAU;EACV;EACA,GAAI,iBAAiB,KAAA,IAAY,EAAE,aAAa,IAAI,CAAC;EACrD,GAAI,UAAU,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,UAAU,SAAS;EAC3E,GAAG,aAAa,WAAW,QAAQ,QAAQ;EAC3C,iBAAiB,UAAU,oBAAoB;EAC/C,SAAS,UAAU,YAAY;CAChC;AACD"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { MetricKey } from "../core/contract.js";
|
|
2
|
-
import { ReadNotices } from "./readMeta.js";
|
|
3
2
|
import { ReadPrincipal } from "../access/principal.js";
|
|
3
|
+
import { ReadNotices } from "./readMeta.js";
|
|
4
|
+
import { StoredSourceRead, SubstitutedSource } from "./prepareWidgetRead.js";
|
|
4
5
|
import { PayloadRequest } from "payload";
|
|
5
6
|
|
|
6
7
|
//#region src/widgets/readForWidgetRealtime.d.ts
|
|
@@ -13,7 +14,7 @@ interface RealtimePoint {
|
|
|
13
14
|
date: string;
|
|
14
15
|
value: number;
|
|
15
16
|
}
|
|
16
|
-
interface WidgetRealtimeResult extends Partial<ReadNotices
|
|
17
|
+
interface WidgetRealtimeResult extends Partial<ReadNotices>, SubstitutedSource {
|
|
17
18
|
status: WidgetRealtimeStatus;
|
|
18
19
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
19
20
|
retryAfterMs?: number;
|
|
@@ -27,7 +28,7 @@ interface WidgetRealtimeResult extends Partial<ReadNotices> {
|
|
|
27
28
|
scope?: string;
|
|
28
29
|
}
|
|
29
30
|
/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */
|
|
30
|
-
type ReadForWidgetRealtimeArgs = ReadPrincipal & {
|
|
31
|
+
type ReadForWidgetRealtimeArgs = ReadPrincipal & StoredSourceRead & {
|
|
31
32
|
req: PayloadRequest;
|
|
32
33
|
metric: MetricKey;
|
|
33
34
|
windowMinutes: number;
|
|
@@ -2,7 +2,7 @@ import { readPrincipalOf } from "../access/principal.js";
|
|
|
2
2
|
import { cacheEpochsFor } from "../plugin/runtime.js";
|
|
3
3
|
import { readFailureOf } from "../surfacing/classifyError.js";
|
|
4
4
|
import { buildRealtimeKey } from "../core/cacheKey.js";
|
|
5
|
-
import { prepareWidgetRead } from "./prepareWidgetRead.js";
|
|
5
|
+
import { prepareWidgetRead, substitutionOf } from "./prepareWidgetRead.js";
|
|
6
6
|
import { readMeta } from "./readMeta.js";
|
|
7
7
|
//#region src/widgets/readForWidgetRealtime.ts
|
|
8
8
|
const empty = (status, adapterId) => ({
|
|
@@ -26,6 +26,7 @@ const readRealtime = async (args, failed) => {
|
|
|
26
26
|
timezone: "UTC",
|
|
27
27
|
adapterId,
|
|
28
28
|
...readPrincipalOf(args),
|
|
29
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
29
30
|
requires: { realtime: true }
|
|
30
31
|
});
|
|
31
32
|
if (!prepared.ok) return empty(prepared.status === "not-configured" || prepared.status === "no-access" || prepared.status === "no-scope" ? prepared.status : "unavailable", prepared.adapterId);
|
|
@@ -59,6 +60,7 @@ const readRealtime = async (args, failed) => {
|
|
|
59
60
|
return {
|
|
60
61
|
status: "ok",
|
|
61
62
|
adapterId: adapter.id,
|
|
63
|
+
...substitutionOf(prepared),
|
|
62
64
|
activeNow: result.totals?.[metric] ?? 0,
|
|
63
65
|
series: result.rows.map((r) => ({
|
|
64
66
|
date: r.timestamp ?? "",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport { buildRealtimeKey } from '../core/cacheKey'\nimport type { AnalyticsQuery, AnalyticsResult, MetricKey } from '../core/contract'\nimport { cacheEpochsFor } from '../plugin/runtime'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport {
|
|
1
|
+
{"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport { buildRealtimeKey } from '../core/cacheKey'\nimport type { AnalyticsQuery, AnalyticsResult, MetricKey } from '../core/contract'\nimport { cacheEpochsFor } from '../plugin/runtime'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport {\n\tprepareWidgetRead,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\n/**\n * What the live count reports: `unavailable` a source counting no one live, `busy` one that failed\n * to count for now, `misconfigured` and `host-refused` one whose setup refused the read.\n */\nexport type WidgetRealtimeStatus =\n\t| 'ok'\n\t| 'not-configured'\n\t| 'unavailable'\n\t| 'busy'\n\t| 'invalid'\n\t| 'no-access'\n\t| 'no-scope'\n\t| 'misconfigured'\n\t| 'host-refused'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult extends Partial<ReadNotices>, SubstitutedSource {\n\tstatus: WidgetRealtimeStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/** The window's total for the metric that was asked for, not visitors specifically. */\n\tactiveNow: number\n\tseries: RealtimePoint[]\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** The scope the read narrowed to, absent for an install-wide one. */\n\tscope?: string\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetRealtimeArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\tmetric: MetricKey\n\t\twindowMinutes: number\n\t\tadapterId?: string\n\t\tnow: Date\n\t\t/** Count only the visitors on this path; omitted counts the whole site. */\n\t\tpath?: string\n\t\t/** False reads the window's total alone, its `series` left empty. Default true. */\n\t\tseries?: boolean\n\t}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/** The live count both callers share; `failed` answers for a source read that throws. */\nconst readRealtime = async (\n\targs: ReadForWidgetRealtimeArgs,\n\tfailed: (err: unknown, adapterId: string) => WidgetRealtimeResult\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now, path } = args\n\tconst series = args.series ?? true\n\tconst dateRange = { start: new Date(now.getTime() - windowMinutes * 60_000), end: now }\n\t// The window is anchored on `now` and never rendered in a zone, so the poll skips the\n\t// install's timezone resolver rather than paying for it ahead of the cache check.\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\trange: dateRange,\n\t\ttimezone: DEFAULT_TIMEZONE,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\trequires: { realtime: true },\n\t})\n\tif (!prepared.ok) {\n\t\t// The window carries no filters, so `filter-unsupported` cannot arise here.\n\t\tconst status =\n\t\t\tprepared.status === 'not-configured' ||\n\t\t\tprepared.status === 'no-access' ||\n\t\t\tprepared.status === 'no-scope'\n\t\t\t\t? prepared.status\n\t\t\t\t: 'unavailable'\n\t\treturn empty(status, prepared.adapterId)\n\t}\n\tconst { runtime, adapter, queryScope } = prepared\n\t// The capability says the source counts live visitors; the hook is what reads them.\n\tconst realtime = adapter.realtime\n\tif (!realtime) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime\n\t// Built outside the engine, so it carries the scope's epochs itself. The path is in it: two\n\t// pages of one site share everything else, so one page's count would otherwise serve the other's.\n\tconst key = buildRealtimeKey(\n\t\tadapter.id,\n\t\t{\n\t\t\tmetric,\n\t\t\twindowMinutes,\n\t\t\tseries,\n\t\t\t...(queryScope === undefined ? {} : { scope: queryScope }),\n\t\t\t...(path === undefined ? {} : { path }),\n\t\t},\n\t\tawait cacheEpochsFor(runtime, queryScope)\n\t)\n\tlet result: AnalyticsResult | undefined = runtime.memo?.get(key)\n\tif (!result) {\n\t\tconst query: AnalyticsQuery = {\n\t\t\tmetrics: [metric],\n\t\t\tdateRange,\n\t\t\tscope: queryScope,\n\t\t\t...(path === undefined ? {} : { path }),\n\t\t\t...(series ? { granularity: 'minute' as const } : {}),\n\t\t}\n\t\t// Through the source's lane like every other read of it, waiting ahead of background work;\n\t\t// the native engine's lane stays its own. A runtime built by hand may have no lanes.\n\t\ttry {\n\t\t\tresult = runtime.engine.realtime\n\t\t\t\t? await runtime.engine.realtime(adapter, query)\n\t\t\t\t: await realtime.call(adapter, query, { payload: req.payload })\n\t\t} catch (err) {\n\t\t\treturn failed(err, adapter.id)\n\t\t}\n\t\truntime.memo?.set(key, result, ttlSeconds * 1000)\n\t}\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...substitutionOf(prepared),\n\t\tactiveNow: result.totals?.[metric] ?? 0,\n\t\tseries: result.rows.map((r) => ({ date: r.timestamp ?? '', value: r.metrics[metric] ?? 0 })),\n\t\t...(queryScope === undefined ? {} : { scope: queryScope }),\n\t\t...readMeta(result),\n\t}\n}\n\n/**\n * Realtime read for the \"active now\" widget, memoized in-process only (a by-the-minute count is\n * not worth a cache write) and keyed here, since the engine's key day-snaps the range.\n */\nexport const readForWidgetRealtime = (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> =>\n\treadRealtime(args, (err, adapterId) => {\n\t\tconst { status, retryAfterMs } = readFailureOf(err)\n\t\treturn {\n\t\t\t...empty(status, adapterId),\n\t\t\t...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n\t\t}\n\t})\n\n/** The same read for the live endpoint, which answers a failed read with its own error response. */\nexport const readRealtimeOrThrow = (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> =>\n\treadRealtime(args, (err) => {\n\t\tthrow err\n\t})\n"],"mappings":";;;;;;;AA+DA,MAAM,SAAS,QAA8B,eAA6C;CACzF;CACA;CACA,WAAW;CACX,QAAQ,CAAC;AACV;;AAGA,MAAM,eAAe,OACpB,MACA,WACmC;CACnC,MAAM,EAAE,KAAK,QAAQ,eAAe,WAAW,KAAK,SAAS;CAC7D,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,YAAY;EAAE,uBAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,gBAAgB,GAAM;EAAG,KAAK;CAAI;CAGtF,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA,OAAO;EACP,UAAA;EACA;EACA,GAAG,gBAAgB,IAAI;EACvB,GAAI,KAAK,yBAAyB,EAAE,wBAAwB,KAAK,IAAI,CAAC;EACtE,UAAU,EAAE,UAAU,KAAK;CAC5B,CAAC;CACD,IAAI,CAAC,SAAS,IAQb,OAAO,MALN,SAAS,WAAW,oBACpB,SAAS,WAAW,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AACD;;;;;AAMA,MAAa,yBACZ,SAEA,aAAa,OAAO,KAAK,cAAc;CACtC,MAAM,EAAE,QAAQ,iBAAiB,cAAc,GAAG;CAClD,OAAO;EACN,GAAG,MAAM,QAAQ,SAAS;EAC1B,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;CACtD;AACD,CAAC;;AAGF,MAAa,uBACZ,SAEA,aAAa,OAAO,QAAQ;CAC3B,MAAM;AACP,CAAC"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { AnalyticsFilter, DateRange, MetricKey, MetricValue } from "../core/contract.js";
|
|
2
|
+
import { ReadPrincipal } from "../access/principal.js";
|
|
2
3
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
3
4
|
import { ReadNotices } from "./readMeta.js";
|
|
4
|
-
import {
|
|
5
|
+
import { StoredSourceRead, SubstitutedSource, WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
5
6
|
import { SeriesGranularity, SeriesPoint } from "../charts/series.js";
|
|
6
|
-
import { WidgetReadStatus } from "./prepareWidgetRead.js";
|
|
7
7
|
import { PayloadRequest } from "payload";
|
|
8
8
|
|
|
9
9
|
//#region src/widgets/readForWidgetSeries.d.ts
|
|
10
|
-
interface WidgetSeriesResult extends Partial<ReadNotices
|
|
10
|
+
interface WidgetSeriesResult extends Partial<ReadNotices>, SubstitutedSource {
|
|
11
11
|
status: WidgetReadStatus;
|
|
12
12
|
/** How long until a `busy` read can succeed, when the source or the plugin knows. */
|
|
13
13
|
retryAfterMs?: number;
|
|
@@ -38,7 +38,7 @@ interface WidgetSeriesResult extends Partial<ReadNotices> {
|
|
|
38
38
|
comparisonPoints?: SeriesPoint[];
|
|
39
39
|
}
|
|
40
40
|
/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */
|
|
41
|
-
type ReadForWidgetSeriesArgs = ReadPrincipal & {
|
|
41
|
+
type ReadForWidgetSeriesArgs = ReadPrincipal & StoredSourceRead & {
|
|
42
42
|
req: PayloadRequest;
|
|
43
43
|
metric: MetricKey;
|
|
44
44
|
timeframe: TimeframePreset;
|
|
@@ -2,7 +2,7 @@ import { readPrincipalOf } from "../access/principal.js";
|
|
|
2
2
|
import { readFailureOf } from "../surfacing/classifyError.js";
|
|
3
3
|
import { emptyReading } from "../core/metricValues.js";
|
|
4
4
|
import { alignSeries, fillSeries, seriesGranularityFor } from "../charts/series.js";
|
|
5
|
-
import { comparisonWindow, engineRead, prepareWidgetRead } from "./prepareWidgetRead.js";
|
|
5
|
+
import { comparisonWindow, engineRead, prepareWidgetRead, substitutionOf } from "./prepareWidgetRead.js";
|
|
6
6
|
import { readMeta } from "./readMeta.js";
|
|
7
7
|
//#region src/widgets/readForWidgetSeries.ts
|
|
8
8
|
/**
|
|
@@ -17,6 +17,7 @@ const readForWidgetSeries = async (args) => {
|
|
|
17
17
|
timeframe,
|
|
18
18
|
adapterId,
|
|
19
19
|
...readPrincipalOf(args),
|
|
20
|
+
...args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {},
|
|
20
21
|
timezone: args.timezone,
|
|
21
22
|
range,
|
|
22
23
|
filters,
|
|
@@ -79,6 +80,7 @@ const readForWidgetSeries = async (args) => {
|
|
|
79
80
|
return {
|
|
80
81
|
status: "ok",
|
|
81
82
|
adapterId: adapter.id,
|
|
83
|
+
...substitutionOf(prepared),
|
|
82
84
|
...prepared.queryScope === void 0 ? {} : { scope: prepared.queryScope },
|
|
83
85
|
dateRange,
|
|
84
86
|
timezone: tz,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport {\n\talignSeries,\n\tfillSeries,\n\ttype SeriesGranularity,\n\ttype SeriesPoint,\n\tseriesGranularityFor,\n} from '../charts/series'\nimport type {\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tMetricKey,\n\tMetricValue,\n} from '../core/contract'\nimport { emptyReading } from '../core/metricValues'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport {\n\tcomparisonWindow,\n\tengineRead,\n\tprepareWidgetRead,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport type { SeriesGranularity, SeriesPoint } from '../charts/series'\n\nexport interface WidgetSeriesResult extends Partial<ReadNotices
|
|
1
|
+
{"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf } from '../access/principal'\nimport {\n\talignSeries,\n\tfillSeries,\n\ttype SeriesGranularity,\n\ttype SeriesPoint,\n\tseriesGranularityFor,\n} from '../charts/series'\nimport type {\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tMetricKey,\n\tMetricValue,\n} from '../core/contract'\nimport { emptyReading } from '../core/metricValues'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport {\n\tcomparisonWindow,\n\tengineRead,\n\tprepareWidgetRead,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n\ttype WidgetReadStatus,\n} from './prepareWidgetRead'\nimport { type ReadNotices, readMeta } from './readMeta'\n\nexport type { SeriesGranularity, SeriesPoint } from '../charts/series'\n\nexport interface WidgetSeriesResult extends Partial<ReadNotices>, SubstitutedSource {\n\tstatus: WidgetReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\tadapterId: string\n\t/** The scope the read narrowed to, absent for an install-wide one. */\n\tscope?: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\t/**\n\t * The bucket the points actually carry. A window of a day or two is charted by hour, so\n\t * `day` there says the source serves no hourly rows and the series is a single point.\n\t */\n\tseriesGranularity?: SeriesGranularity\n\t/** The window's headline reading; `null` for an average with no samples in it. */\n\ttotal: MetricValue\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: MetricValue\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/**\n\t * Previous window's series at the same granularity, when `compare` ran. Zero-filled to the\n\t * length of `points`, so its bucket i overlays `points[i]`.\n\t */\n\tcomparisonPoints?: SeriesPoint[]\n}\n\n/** Scoped like `ReadForWidgetArgs`: the request's own scope unless one is pinned. */\nexport type ReadForWidgetSeriesArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\tmetric: MetricKey\n\t\ttimeframe: TimeframePreset\n\t\tadapterId?: string\n\t\tnow: Date\n\t\trange?: DateRange\n\t\t/**\n\t\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t\t */\n\t\ttimezone?: string\n\t\tfilters?: AnalyticsFilter[]\n\t\t/** Also return the previous window's series, for the chart's comparison overlay. */\n\t\tcompare?: boolean\n\t}\n\n/**\n * Trend read: a zero-filled series plus headline total. A window of a day or two reads by hour\n * where served (a daily axis there is one point); see {@link seriesGranularityFor}.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range, filters, compare } = args\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\t...readPrincipalOf(args),\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics: [metric] },\n\t\tgranularity: 'day',\n\t\tgoalRead: () => ({ metrics: [metric] }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\ttimezone: prepared.tz,\n\t\t\tpoints: [],\n\t\t\ttotal: 0,\n\t\t}\n\t}\n\tconst { adapter, tz, dateRange, goalSlugs } = prepared\n\tconst granularity = seriesGranularityFor(dateRange, adapter.capabilities)\n\tconst comparisonRange = comparisonWindow(prepared, now)\n\tconst readBase = {\n\t\tmetrics: [metric],\n\t\tfilters,\n\t\ttimezone: tz,\n\t\tscope: prepared.queryScope,\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n\tconst read = engineRead(prepared, timeframe)\n\tconst main = read({ ...readBase, dateRange, granularity })\n\t// The overlay needs the previous window bucketed like the primary; the delta only its total.\n\t// One that fails drops the overlay and the delta, never the series itself.\n\tconst comparing = comparisonRange\n\t\t? read({\n\t\t\t\t...readBase,\n\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t...(compare ? { granularity } : {}),\n\t\t\t}).catch(() => undefined)\n\t\t: undefined\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await main\n\t} catch (err) {\n\t\treturn {\n\t\t\t...readFailureOf(err),\n\t\t\tadapterId: adapter.id,\n\t\t\tdateRange,\n\t\t\ttimezone: tz,\n\t\t\tpoints: [],\n\t\t\ttotal: 0,\n\t\t}\n\t}\n\tconst previous = await comparing\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\tconst points = fillSeries({ rows: result.rows, dateRange, metric, tz, granularity })\n\tconst total = result.totals?.[metric]\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\t...substitutionOf(prepared),\n\t\t...(prepared.queryScope === undefined ? {} : { scope: prepared.queryScope }),\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints,\n\t\tseriesGranularity: granularity,\n\t\ttotal: total === undefined ? emptyReading(metric) : total,\n\t\t...readMeta(result),\n\t\tpreviousTotal,\n\t\tcomparisonRange: previous ? comparisonRange : undefined,\n\t\t...(compare && previous && comparisonRange\n\t\t\t? {\n\t\t\t\t\tcomparisonPoints: alignSeries(\n\t\t\t\t\t\tfillSeries({\n\t\t\t\t\t\t\trows: previous.rows,\n\t\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\t\tmetric,\n\t\t\t\t\t\t\ttz,\n\t\t\t\t\t\t\tgranularity,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tpoints,\n\t\t\t\t\t\tmetric\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAsFA,MAAa,sBAAsB,OAClC,SACiC;CACjC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,KAAK,OAAO,SAAS,YAAY;CAE5E,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,GAAG,gBAAgB,IAAI;EACvB,GAAI,KAAK,yBAAyB,EAAE,wBAAwB,KAAK,IAAI,CAAC;EACtE,UAAU,KAAK;EACf;EACA;EACA,UAAU,EAAE,SAAS,CAAC,MAAM,EAAE;EAC9B,aAAa;EACb,iBAAiB,EAAE,SAAS,CAAC,MAAM,EAAE;CACtC,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO;EACN,QAAQ,SAAS;EACjB,WAAW,SAAS;EACpB,WAAW,SAAS;EACpB,UAAU,SAAS;EACnB,QAAQ,CAAC;EACT,OAAO;CACR;CAED,MAAM,EAAE,SAAS,IAAI,WAAW,cAAc;CAC9C,MAAM,cAAc,qBAAqB,WAAW,QAAQ,YAAY;CACxE,MAAM,kBAAkB,iBAAiB,UAAU,GAAG;CACtD,MAAM,WAAW;EAChB,SAAS,CAAC,MAAM;EAChB;EACA,UAAU;EACV,OAAO,SAAS;EAChB,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CAChD;CACA,MAAM,OAAO,WAAW,UAAU,SAAS;CAC3C,MAAM,OAAO,KAAK;EAAE,GAAG;EAAU;EAAW;CAAY,CAAC;CAGzD,MAAM,YAAY,kBACf,KAAK;EACL,GAAG;EACH,WAAW;EACX,GAAI,UAAU,EAAE,YAAY,IAAI,CAAC;CAClC,CAAC,EAAE,YAAY,KAAA,CAAS,IACvB,KAAA;CACH,IAAI;CACJ,IAAI;EACH,SAAS,MAAM;CAChB,SAAS,KAAK;EACb,OAAO;GACN,GAAG,cAAc,GAAG;GACpB,WAAW,QAAQ;GACnB;GACA,UAAU;GACV,QAAQ,CAAC;GACT,OAAO;EACR;CACD;CACA,MAAM,WAAW,MAAM;CACvB,MAAM,gBAAgB,WAAW,SAAS,SAAS,UAAU,KAAA;CAC7D,MAAM,SAAS,WAAW;EAAE,MAAM,OAAO;EAAM;EAAW;EAAQ;EAAI;CAAY,CAAC;CACnF,MAAM,QAAQ,OAAO,SAAS;CAC9B,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB,GAAG,eAAe,QAAQ;EAC1B,GAAI,SAAS,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,SAAS,WAAW;EAC1E;EACA,UAAU;EACV;EACA,mBAAmB;EACnB,OAAO,UAAU,KAAA,IAAY,aAAa,MAAM,IAAI;EACpD,GAAG,SAAS,MAAM;EAClB;EACA,iBAAiB,WAAW,kBAAkB,KAAA;EAC9C,GAAI,WAAW,YAAY,kBACxB,EACA,kBAAkB,YACjB,WAAW;GACV,MAAM,SAAS;GACf,WAAW;GACX;GACA;GACA;EACD,CAAC,GACD,QACA,MACD,EACD,IACC,CAAC;CACL;AACD"}
|
|
@@ -301,6 +301,8 @@ const WIDGET_DEFS = [
|
|
|
301
301
|
fields: (args) => breakdownWidgetFields(args, spec)
|
|
302
302
|
}))
|
|
303
303
|
];
|
|
304
|
+
/** What a built-in widget asks of every source before the install offers it; none for others. */
|
|
305
|
+
const builtInWidgetRequires = (slug) => WIDGET_DEFS.find((def) => def.slug === slug)?.requires;
|
|
304
306
|
/**
|
|
305
307
|
* The widget's component: the plugin's own, or the host's in its place. Either way it keeps the
|
|
306
308
|
* plugin's server props, which the host's own `serverProps` add to.
|
|
@@ -363,6 +365,6 @@ const registerWidgets = (config, args) => {
|
|
|
363
365
|
};
|
|
364
366
|
};
|
|
365
367
|
//#endregion
|
|
366
|
-
export { registerWidgets };
|
|
368
|
+
export { builtInWidgetRequires, registerWidgets };
|
|
367
369
|
|
|
368
370
|
//# sourceMappingURL=registerWidgets.js.map
|