@10x-media/analytics 0.1.0-beta.4 → 0.1.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/capabilities.d.ts +13 -2
  3. package/dist/core/capabilities.js +11 -1
  4. package/dist/core/capabilities.js.map +1 -1
  5. package/dist/core/options.d.ts +4 -2
  6. package/dist/core/options.js +7 -2
  7. package/dist/core/options.js.map +1 -1
  8. package/dist/core/scopedRead.js +7 -6
  9. package/dist/core/scopedRead.js.map +1 -1
  10. package/dist/exports/client.d.ts +5 -1
  11. package/dist/exports/client.js +4 -1
  12. package/dist/exports/rsc.d.ts +1 -1
  13. package/dist/exports/types.d.ts +2 -1
  14. package/dist/fields/config/MetricSelectField.d.ts +23 -0
  15. package/dist/fields/config/MetricSelectField.js +51 -0
  16. package/dist/fields/config/MetricSelectField.js.map +1 -0
  17. package/dist/fields/config/SourceSelectField.d.ts +14 -0
  18. package/dist/fields/config/SourceSelectField.js +46 -0
  19. package/dist/fields/config/SourceSelectField.js.map +1 -0
  20. package/dist/fields/config/fetchSources.d.ts +12 -0
  21. package/dist/fields/config/fetchSources.js +29 -0
  22. package/dist/fields/config/fetchSources.js.map +1 -0
  23. package/dist/fields/config/narrow.js +30 -0
  24. package/dist/fields/config/narrow.js.map +1 -0
  25. package/dist/fields/config/sourcesState.js +11 -0
  26. package/dist/fields/config/sourcesState.js.map +1 -0
  27. package/dist/fields/config/toSelectOption.js +27 -0
  28. package/dist/fields/config/toSelectOption.js.map +1 -0
  29. package/dist/fields/config/useAnalyticsSources.d.ts +19 -0
  30. package/dist/fields/config/useAnalyticsSources.js +59 -0
  31. package/dist/fields/config/useAnalyticsSources.js.map +1 -0
  32. package/dist/index.js +20 -9
  33. package/dist/index.js.map +1 -1
  34. package/dist/plugin/paths.js +3 -1
  35. package/dist/plugin/paths.js.map +1 -1
  36. package/dist/plugin/realtimeEndpoint.js +2 -2
  37. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  38. package/dist/plugin/runtime.js.map +1 -1
  39. package/dist/plugin/sourcesEndpoint.js +53 -0
  40. package/dist/plugin/sourcesEndpoint.js.map +1 -0
  41. package/dist/providers/access.js +2 -1
  42. package/dist/providers/access.js.map +1 -1
  43. package/dist/providers/collection.js +1 -0
  44. package/dist/providers/collection.js.map +1 -1
  45. package/dist/widgets/AnalyticsRealtimeWidget.js +2 -2
  46. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  47. package/dist/widgets/realtimePoll.js +4 -1
  48. package/dist/widgets/realtimePoll.js.map +1 -1
  49. package/dist/widgets/registerWidgets.js +14 -4
  50. package/dist/widgets/registerWidgets.js.map +1 -1
  51. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @10x-media/analytics
2
2
 
3
+ ## 0.1.0-beta.5
4
+
5
+ ### Minor Changes
6
+
7
+ - Scope-aware widget pickers. A new authenticated `GET /api/analytics/sources` endpoint lists the adapters visible to the requesting scope (config adapters plus the scope's runtime providers) with their capabilities, and the widget `dataSource` and `metric` selects now render through client components that consume it: a tenant's own providers finally appear in pickers, labeled by the provider document's name (a generated label stands in when unset), and the metric list narrows to what the selected source can actually serve. Without JavaScript or when the endpoint is unreachable the pickers fall back to the config-time option lists, and stored values the endpoint no longer lists keep the previous behavior of degrading at read time.
8
+
9
+ The sources endpoint response now carries a top-level `defaultId` and a `kind: 'config' | 'runtime'` per source, and serialized capabilities are a deliberate allowlist (`metrics`, `dimensions`, `realtime`, `realtimeWindowMinutes`, `perPageQuery`, `comparison`, `minGranularity`, `maxLookbackDays`); adapter internals such as rate limits and TTL recommendations are no longer on the wire. New client reuse surface: `useAnalyticsSources` and the `WireSource` type from `@10x-media/analytics/client`, `SerializedCapabilities` from `/types`, and a `sourceFieldPath` prop on `MetricSelectField` for custom widgets. The widget data source default now follows `defaultAdapter`, and the realtime poller builds its URL from the configured API route instead of a hardcoded `/api`.
10
+
11
+ - **Breaking:** fail-closed defaults for scoped installs. With a `scopeResolver` configured, `access.platformRead` now defaults to deny instead of any authenticated user; configure it (for example a role check) so platform admins can read cross-scope and manage every tenant's provider documents. Scoped reads through a shared config adapter that cannot filter by scope are now gated behind `platformRead` even when the adapter is not designated as `platformAdapter`; a tenant's own runtime providers are never gated. A `scopeResolver` returning an empty string is now treated as the install-wide scope (fail closed) everywhere, matching ingest and registry semantics. `providers.collection.scopeField` must be a top-level field name; a dotted path now throws at config build. The provider collection's admin duplicate action is disabled (a duplicate could never carry the write-only credentials). Unscoped installs are unchanged.
12
+
3
13
  ## 0.1.0-beta.4
4
14
 
5
15
  ### Minor Changes
@@ -1,4 +1,4 @@
1
- import { DimensionKey, MetricKey } from "./contract.js";
1
+ import { DimensionKey, Granularity, MetricKey } from "./contract.js";
2
2
 
3
3
  //#region src/core/capabilities.d.ts
4
4
  interface CapabilityRequirement {
@@ -7,6 +7,17 @@ interface CapabilityRequirement {
7
7
  realtime?: boolean;
8
8
  perPageQuery?: boolean;
9
9
  }
10
+ /** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */
11
+ type SerializedCapabilities = {
12
+ metrics: MetricKey[];
13
+ dimensions: DimensionKey[];
14
+ realtime: boolean;
15
+ realtimeWindowMinutes?: number;
16
+ perPageQuery: boolean;
17
+ comparison: boolean;
18
+ minGranularity: Granularity;
19
+ maxLookbackDays: number | null;
20
+ };
10
21
  //#endregion
11
- export { CapabilityRequirement };
22
+ export { CapabilityRequirement, SerializedCapabilities };
12
23
  //# sourceMappingURL=capabilities.d.ts.map
@@ -6,7 +6,17 @@ function satisfiesCapabilities(caps, req) {
6
6
  if (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false;
7
7
  return true;
8
8
  }
9
+ const serializeCapabilities = (caps) => ({
10
+ metrics: [...caps.metrics],
11
+ dimensions: [...caps.dimensions],
12
+ realtime: caps.realtime,
13
+ ...caps.realtimeWindowMinutes !== void 0 ? { realtimeWindowMinutes: caps.realtimeWindowMinutes } : {},
14
+ perPageQuery: caps.perPageQuery,
15
+ comparison: caps.comparison,
16
+ minGranularity: caps.minGranularity,
17
+ maxLookbackDays: caps.maxLookbackDays
18
+ });
9
19
  //#endregion
10
- export { satisfiesCapabilities };
20
+ export { satisfiesCapabilities, serializeCapabilities };
11
21
 
12
22
  //# sourceMappingURL=capabilities.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n"],"mappings":";AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR"}
1
+ {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, Granularity, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: caps.comparison,\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR;AAcA,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,KAAK;CACjB,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
@@ -66,8 +66,10 @@ type PlatformReadAccess = (args: {
66
66
  type AnalyticsAccessOptions = {
67
67
  /**
68
68
  * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through
69
- * a platform adapter that cannot filter by scope. Defaults to any authenticated
70
- * admin-panel user.
69
+ * a shared config adapter that cannot filter by scope. Scoped installs
70
+ * (`scopeResolver` configured) default to deny; configure it, for example a role
71
+ * check, so platform admins can read cross-scope and manage every tenant's
72
+ * providers. Unscoped installs default to any authenticated admin-panel user.
71
73
  */
72
74
  platformRead?: PlatformReadAccess;
73
75
  };
@@ -67,6 +67,10 @@ function resolveOptions(options) {
67
67
  },
68
68
  resolve: options.providers?.resolve
69
69
  };
70
+ if (providers.collection.enabled) {
71
+ if (providers.collection.scopeField.trim() === "") throw new Error("analytics: providers.collection.scopeField must be a non-empty field name");
72
+ if (providers.collection.scopeField.includes(".")) throw new Error("analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key");
73
+ }
70
74
  const syncOpt = options.sync;
71
75
  const sync = syncOpt === true ? {
72
76
  enabled: true,
@@ -88,14 +92,15 @@ function resolveOptions(options) {
88
92
  lookbackDays: DEFAULT_SYNC_LOOKBACK,
89
93
  hidden: true
90
94
  };
95
+ const scoped = options.scopeResolver !== void 0;
91
96
  return {
92
97
  adapters: options.adapters,
93
98
  defaultAdapter: options.defaultAdapter,
94
99
  scopeResolver: options.scopeResolver ?? (() => null),
95
- scoped: options.scopeResolver !== void 0,
100
+ scoped,
96
101
  reportingTimezone: options.reportingTimezone,
97
102
  platformAdapter: options.platformAdapter,
98
- access: { platformRead: options.access?.platformRead ?? (({ req }) => Boolean(req.user)) },
103
+ access: { platformRead: options.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)) },
99
104
  providers,
100
105
  bindings: resolveBindings(options.collections),
101
106
  cache: {
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a platform adapter that cannot filter by scope. Defaults to any authenticated\n\t * admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped: options.scopeResolver !== undefined,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: { platformRead: options.access?.platformRead ?? (({ req }) => Boolean(req.user)) },\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;AAQA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AA4L5B,MAAM,mBACL,gBACqC;CACrC,MAAM,MAAuC,CAAC;CAC9C,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,eAAe,CAAC,CAAC,GAAG;EAChE,IAAI,CAAC,SAAS;EACd,IAAI,CAAC,QAAQ,QAAQ,CAAC,QAAQ,WAC7B,MAAM,IAAI,MAAM,2BAA2B,KAAK,uCAAuC;EAIxF,IAAI,QAAQ;CACb;CACA,OAAO;AACR;AAEA,SAAgB,eAAe,SAAkD;CAChF,IAAI,CAAC,QAAQ,YAAY,QAAQ,SAAS,WAAW,GACpD,MAAM,IAAI,MAAM,6CAA6C;CAE9D,IACC,QAAQ,oBAAoB,KAAA,KAC5B,CAAC,QAAQ,SAAS,MAAM,MAAM,EAAE,OAAO,QAAQ,eAAe,GAE9D,MAAM,IAAI,MAAM,wCAAwC,QAAQ,gBAAgB,EAAE;CAEnF,MAAM,UACL,QAAQ,YAAY,QACjB;EACA,SAAS;EACT,UAAU,CAAC;EACX,UAAU,CAAC;EACX,cAAc;EACd,YAAY;CACb,IACC,QAAQ,YAAY,KAAA,KAAa,QAAQ,YAAY,OACpD;EACA,SAAS;EACT,UAAU,CAAC;EACX,UAAU,CAAC;EACX,cAAc;EACd,YAAY;CACb,IACC;EACA,SAAS;EACT,UAAU,QAAQ,QAAQ,YAAY,CAAC;EACvC,UAAU,QAAQ,QAAQ,YAAY,CAAC;EACvC,cAAc,QAAQ,QAAQ,gBAAgB;EAC9C,YAAY,QAAQ,QAAQ,cAAc;CAC3C;CACJ,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,OACL,YAAY,OACT;EAAE,SAAS;EAAM,MAAM;CAAkB,IACzC,WAAW,OAAO,YAAY,WAC7B;EAAE,SAAS;EAAM,MAAM,QAAQ,QAAQ;CAAkB,IACzD;EAAE,SAAS;EAAO,MAAM;CAAkB;CAC/C,MAAM,gBAAgB,QAAQ,WAAW;CACzC,MAAM,YAAY;EACjB,YACC,kBAAkB,OACf;GAAE,SAAS;GAAM,MAAM;GAAgB,YAAY;EAAoB,IACvE,iBAAiB,OAAO,kBAAkB,WACzC;GACA,SAAS;GACT,MAAM,cAAc,QAAA;GACpB,YAAY,cAAc,cAAc;GACxC,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB,YAAY,cAAc;EAC3B,IACC;GAAE,SAAS;GAAO,MAAM;GAAgB,YAAY;EAAoB;EAC7E,SAAS,QAAQ,WAAW;CAC7B;CACA,MAAM,UAAU,QAAQ;CACxB,MAAM,OACL,YAAY,OACT;EACA,SAAS;EACT,gBAAgB;EAChB,MAAM;EACN,cAAc;EACd,QAAQ;CACT,IACC,WAAW,OAAO,YAAY,WAC7B;EACA,SAAS;EACT,gBAAgB,QAAQ,kBAAkB;EAC1C,MAAM,QAAQ,QAAQ;EACtB,cAAc,QAAQ,gBAAgB;EACtC,UAAU,QAAQ;EAClB,QAAQ,QAAQ,UAAU;CAC3B,IACC;EACA,SAAS;EACT,gBAAgB;EAChB,MAAM;EACN,cAAc;EACd,QAAQ;CACT;CACJ,OAAO;EACN,UAAU,QAAQ;EAClB,gBAAgB,QAAQ;EACxB,eAAe,QAAQ,wBAAwB;EAC/C,QAAQ,QAAQ,kBAAkB,KAAA;EAClC,mBAAmB,QAAQ;EAC3B,iBAAiB,QAAQ;EACzB,QAAQ,EAAE,cAAc,QAAQ,QAAQ,kBAAkB,EAAE,UAAU,QAAQ,IAAI,IAAI,GAAG;EACzF;EACA,UAAU,gBAAgB,QAAQ,WAAW;EAC7C,OAAO;GAGN,KAAK;IACJ,WAAW,QAAQ,OAAO,KAAK;IAC/B,UAAU,QAAQ,OAAO,KAAK;GAC/B;GACA;EACD;EACA;EACA;CACD;AACD"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t},\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":"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"}
@@ -5,11 +5,12 @@ import "./contract.js";
5
5
  * Resolve one read's scope and adapter: explicit scope wins over the request's
6
6
  * resolved scope, the registry is resolved per scope, then the adapter is picked
7
7
  * by id (or the registry default). Cross-scope reads fail closed behind
8
- * `platformRead`: an explicit `'*'` scope always, and a scoped read through the
9
- * platform adapter when it cannot narrow the query to one scope. Any resolution
10
- * failure (unknown adapter id, a throwing scopeResolver or provider lookup)
11
- * degrades to `{ ok: false }` so read paths render their unavailable state
12
- * instead of throwing.
8
+ * `platformRead`: an explicit `'*'` scope always, and any scoped read through a
9
+ * shared config adapter that cannot narrow the query to one scope, whether or
10
+ * not it is the designated platform adapter. A tenant's own runtime adapters
11
+ * are never gated. Any resolution failure (unknown adapter id, a throwing
12
+ * scopeResolver or provider lookup) degrades to `{ ok: false }` so read paths
13
+ * render their unavailable state instead of throwing.
13
14
  */
14
15
  const resolveReadContext = async (args) => {
15
16
  const { runtime, req, adapterId } = args;
@@ -31,7 +32,7 @@ const resolveReadContext = async (args) => {
31
32
  queryScope: void 0
32
33
  };
33
34
  }
34
- if (scope !== null && adapter.id === runtime.platformAdapterId && !adapter.capabilities.scopedQueries) {
35
+ if (scope !== null && runtime.configAdapterIds.has(adapter.id) && !adapter.capabilities.scopedQueries) {
35
36
  if (!await platformReadFor(runtime, req)) return { ok: false };
36
37
  return {
37
38
  ok: true,
@@ -1 +1 @@
1
- {"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always, and a scoped read through the\n * platform adapter when it cannot narrow the query to one scope. Any resolution\n * failure (unknown adapter id, a throwing scopeResolver or provider lookup)\n * degrades to `{ ok: false }` so read paths render their unavailable state\n * instead of throwing.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\ttry {\n\t\tconst scope = args.scope !== undefined ? args.scope : await resolveScopeFor(runtime, req)\n\t\tconst registryScope = scope === PLATFORM_SCOPE ? null : scope\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\tconst adapter = adapterId ? registry.get(adapterId) : registry.default()\n\t\tif (scope === PLATFORM_SCOPE) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope: null, queryScope: undefined }\n\t\t}\n\t\tif (\n\t\t\tscope !== null &&\n\t\t\tadapter.id === runtime.platformAdapterId &&\n\t\t\t!adapter.capabilities.scopedQueries\n\t\t) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope, queryScope: undefined }\n\t\t}\n\t\treturn { ok: true, adapter, scope, queryScope: scope ?? undefined }\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,MAAa,qBAAqB,OAAO,SAAuD;CAC/F,MAAM,EAAE,SAAS,KAAK,cAAc;CACpC,IAAI;EACH,MAAM,QAAQ,KAAK,UAAU,KAAA,IAAY,KAAK,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EACxF,MAAM,gBAAgB,UAAA,MAA2B,OAAO;EACxD,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,MAAM,UAAU,YAAY,SAAS,IAAI,SAAS,IAAI,SAAS,QAAQ;EACvE,IAAI,UAAA,KAA0B;GAC7B,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS,OAAO;IAAM,YAAY,KAAA;GAAU;EAChE;EACA,IACC,UAAU,QACV,QAAQ,OAAO,QAAQ,qBACvB,CAAC,QAAQ,aAAa,eACrB;GACD,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS;IAAO,YAAY,KAAA;GAAU;EAC1D;EACA,OAAO;GAAE,IAAI;GAAM;GAAS;GAAO,YAAY,SAAS,KAAA;EAAU;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
1
+ {"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always, and any scoped read through a\n * shared config adapter that cannot narrow the query to one scope, whether or\n * not it is the designated platform adapter. A tenant's own runtime adapters\n * are never gated. Any resolution failure (unknown adapter id, a throwing\n * scopeResolver or provider lookup) degrades to `{ ok: false }` so read paths\n * render their unavailable state instead of throwing.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\ttry {\n\t\tconst scope = args.scope !== undefined ? args.scope : await resolveScopeFor(runtime, req)\n\t\tconst registryScope = scope === PLATFORM_SCOPE ? null : scope\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\tconst adapter = adapterId ? registry.get(adapterId) : registry.default()\n\t\tif (scope === PLATFORM_SCOPE) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope: null, queryScope: undefined }\n\t\t}\n\t\tif (\n\t\t\tscope !== null &&\n\t\t\truntime.configAdapterIds.has(adapter.id) &&\n\t\t\t!adapter.capabilities.scopedQueries\n\t\t) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope, queryScope: undefined }\n\t\t}\n\t\treturn { ok: true, adapter, scope, queryScope: scope ?? undefined }\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,MAAa,qBAAqB,OAAO,SAAuD;CAC/F,MAAM,EAAE,SAAS,KAAK,cAAc;CACpC,IAAI;EACH,MAAM,QAAQ,KAAK,UAAU,KAAA,IAAY,KAAK,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EACxF,MAAM,gBAAgB,UAAA,MAA2B,OAAO;EACxD,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,MAAM,UAAU,YAAY,SAAS,IAAI,SAAS,IAAI,SAAS,QAAQ;EACvE,IAAI,UAAA,KAA0B;GAC7B,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS,OAAO;IAAM,YAAY,KAAA;GAAU;EAChE;EACA,IACC,UAAU,QACV,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,KACvC,CAAC,QAAQ,aAAa,eACrB;GACD,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS;IAAO,YAAY,KAAA;GAAU;EAC1D;EACA,OAAO;GAAE,IAAI;GAAM;GAAS;GAAO,YAAY,SAAS,KAAA;EAAU;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
@@ -1,5 +1,9 @@
1
1
  import { BarList, BarListProps } from "../charts/BarList.js";
2
2
  import { TrendChart, TrendChartProps } from "../charts/TrendChart.js";
3
+ import { WireSource } from "../fields/config/fetchSources.js";
4
+ import { MetricSelectField, MetricSelectFieldProps } from "../fields/config/MetricSelectField.js";
5
+ import { SourceSelectField } from "../fields/config/SourceSelectField.js";
6
+ import { useAnalyticsSources } from "../fields/config/useAnalyticsSources.js";
3
7
  import { DateRangeField } from "../fields/dateRange/ui.js";
4
8
  import { RealtimeCounter } from "../widgets/RealtimeCounter.js";
5
- export { BarList, type BarListProps, DateRangeField, RealtimeCounter, TrendChart, type TrendChartProps };
9
+ export { BarList, type BarListProps, DateRangeField, MetricSelectField, type MetricSelectFieldProps, RealtimeCounter, SourceSelectField, TrendChart, type TrendChartProps, type WireSource, useAnalyticsSources };
@@ -1,6 +1,9 @@
1
1
  "use client";
2
2
  import { BarList } from "../charts/BarList.js";
3
3
  import { TrendChart } from "../charts/TrendChart.js";
4
+ import { useAnalyticsSources } from "../fields/config/useAnalyticsSources.js";
5
+ import { MetricSelectField } from "../fields/config/MetricSelectField.js";
6
+ import { SourceSelectField } from "../fields/config/SourceSelectField.js";
4
7
  import { DateRangeField } from "../fields/dateRange/ui.js";
5
8
  import { RealtimeCounter } from "../widgets/RealtimeCounter.js";
6
- export { BarList, DateRangeField, RealtimeCounter, TrendChart };
9
+ export { BarList, DateRangeField, MetricSelectField, RealtimeCounter, SourceSelectField, TrendChart, useAnalyticsSources };
@@ -1,6 +1,6 @@
1
1
  import { DateRange, DimensionKey, MetricKey } from "../core/contract.js";
2
- import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
3
2
  import { CapabilityRequirement } from "../core/capabilities.js";
3
+ import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
4
4
  import { AnalyticsStatField } from "../fields/AnalyticsStatField.js";
5
5
  import { AnalyticsPanelField } from "../fields/AnalyticsPanelField.js";
6
6
  import { formatMetricValue } from "../fields/format.js";
@@ -1,6 +1,7 @@
1
1
  import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
2
+ import { SerializedCapabilities } from "../core/capabilities.js";
2
3
  import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "../binding/types.js";
3
4
  import { TimeframePreset } from "../timeframe/presets.js";
4
5
  import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions } from "../fields/factories.js";
5
6
  import { AnalyticsPluginOptions } from "../core/options.js";
6
- export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type TimeframePreset };
7
+ export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };
@@ -0,0 +1,23 @@
1
+ import { CapabilityRequirement } from "../../core/capabilities.js";
2
+ import { SelectFieldClientProps } from "payload";
3
+
4
+ //#region src/fields/config/MetricSelectField.d.ts
5
+ type MetricSelectFieldProps = SelectFieldClientProps & {
6
+ /** Extra capability requirement (beyond the picked metric) a widget's other config imposes, e.g. a breakdown dimension. */requires?: Omit<CapabilityRequirement, 'metrics'>;
7
+ /**
8
+ * Path of the sibling source select this picker narrows against, for
9
+ * custom widgets whose source field is named differently. Defaults to
10
+ * `'dataSource'`.
11
+ */
12
+ sourceFieldPath?: string;
13
+ };
14
+ /**
15
+ * Metric picker for scoped widget config: narrows the static option list to
16
+ * what the sibling source field's selected source can actually serve, once
17
+ * the sources endpoint answers. Never clears an already-picked value that
18
+ * narrowing filters out; the read path degrades that case on its own.
19
+ */
20
+ declare const MetricSelectField: (props: MetricSelectFieldProps) => import("react/jsx-runtime").JSX.Element;
21
+ //#endregion
22
+ export { MetricSelectField, MetricSelectFieldProps };
23
+ //# sourceMappingURL=MetricSelectField.d.ts.map
@@ -0,0 +1,51 @@
1
+ "use client";
2
+ import { useTranslation as useTranslation$1 } from "../../translations/useTranslation.js";
3
+ import { narrowMetricOptions } from "./narrow.js";
4
+ import { toSelectOption } from "./toSelectOption.js";
5
+ import { useAnalyticsSources } from "./useAnalyticsSources.js";
6
+ import { useMemo } from "react";
7
+ import { jsx } from "react/jsx-runtime";
8
+ import { SelectInput, useField, useFormFields } from "@payloadcms/ui";
9
+ //#region src/fields/config/MetricSelectField.tsx
10
+ /**
11
+ * Metric picker for scoped widget config: narrows the static option list to
12
+ * what the sibling source field's selected source can actually serve, once
13
+ * the sources endpoint answers. Never clears an already-picked value that
14
+ * narrowing filters out; the read path degrades that case on its own.
15
+ */
16
+ const MetricSelectField = (props) => {
17
+ const { field, path, readOnly, requires, sourceFieldPath = "dataSource" } = props;
18
+ const { i18n } = useTranslation$1();
19
+ const locale = i18n.language;
20
+ const { setValue, showError, value } = useField({ path });
21
+ const { sources } = useAnalyticsSources();
22
+ const sourceId = useFormFields(([fields]) => fields?.[sourceFieldPath]?.value);
23
+ const options = narrowMetricOptions({
24
+ options: useMemo(() => field.options.map((option) => toSelectOption(option, locale)), [field.options, locale]),
25
+ requires,
26
+ sourceId,
27
+ sources: sources ?? []
28
+ }).map((option) => ({
29
+ label: option.label,
30
+ value: option.value
31
+ }));
32
+ return /* @__PURE__ */ jsx(SelectInput, {
33
+ isClearable: false,
34
+ label: field.label,
35
+ name: field.name,
36
+ onChange: (selected) => {
37
+ const option = Array.isArray(selected) ? selected[0] : selected;
38
+ setValue(option ? String(option.value) : null);
39
+ },
40
+ options,
41
+ path,
42
+ readOnly,
43
+ required: field.required,
44
+ showError,
45
+ value
46
+ });
47
+ };
48
+ //#endregion
49
+ export { MetricSelectField };
50
+
51
+ //# sourceMappingURL=MetricSelectField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetricSelectField.js","names":["useTranslation"],"sources":["../../../src/fields/config/MetricSelectField.tsx"],"sourcesContent":["'use client'\n\nimport { type ReactSelectOption, SelectInput, useField, useFormFields } from '@payloadcms/ui'\nimport type { SelectFieldClientProps } from 'payload'\nimport { useMemo } from 'react'\nimport type { CapabilityRequirement } from '../../core/capabilities'\nimport { useTranslation } from '../../translations/useTranslation'\nimport { narrowMetricOptions } from './narrow'\nimport { toSelectOption } from './toSelectOption'\nimport { useAnalyticsSources } from './useAnalyticsSources'\n\nexport type MetricSelectFieldProps = SelectFieldClientProps & {\n\t/** Extra capability requirement (beyond the picked metric) a widget's other config imposes, e.g. a breakdown dimension. */\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n\t/**\n\t * Path of the sibling source select this picker narrows against, for\n\t * custom widgets whose source field is named differently. Defaults to\n\t * `'dataSource'`.\n\t */\n\tsourceFieldPath?: string\n}\n\n/**\n * Metric picker for scoped widget config: narrows the static option list to\n * what the sibling source field's selected source can actually serve, once\n * the sources endpoint answers. Never clears an already-picked value that\n * narrowing filters out; the read path degrades that case on its own.\n */\nexport const MetricSelectField = (props: MetricSelectFieldProps) => {\n\tconst { field, path, readOnly, requires, sourceFieldPath = 'dataSource' } = props\n\tconst { i18n } = useTranslation()\n\tconst locale = i18n.language\n\tconst { setValue, showError, value } = useField<string>({ path })\n\tconst { sources } = useAnalyticsSources()\n\tconst sourceId = useFormFields(\n\t\t([fields]) => fields?.[sourceFieldPath]?.value as string | undefined\n\t)\n\n\tconst staticOptions = useMemo(\n\t\t() => field.options.map((option) => toSelectOption(option, locale)),\n\t\t[field.options, locale]\n\t)\n\n\tconst options = narrowMetricOptions({\n\t\toptions: staticOptions,\n\t\trequires,\n\t\tsourceId,\n\t\tsources: sources ?? [],\n\t}).map((option) => ({ label: option.label as string, value: option.value }))\n\n\treturn (\n\t\t<SelectInput\n\t\t\tisClearable={false}\n\t\t\tlabel={field.label}\n\t\t\tname={field.name}\n\t\t\tonChange={(selected: ReactSelectOption | ReactSelectOption[]) => {\n\t\t\t\tconst option = Array.isArray(selected) ? selected[0] : selected\n\t\t\t\tsetValue(option ? String(option.value) : null)\n\t\t\t}}\n\t\t\toptions={options}\n\t\t\tpath={path}\n\t\t\treadOnly={readOnly}\n\t\t\trequired={field.required}\n\t\t\tshowError={showError}\n\t\t\tvalue={value}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,MAAa,qBAAqB,UAAkC;CACnE,MAAM,EAAE,OAAO,MAAM,UAAU,UAAU,kBAAkB,iBAAiB;CAC5E,MAAM,EAAE,SAASA,iBAAe;CAChC,MAAM,SAAS,KAAK;CACpB,MAAM,EAAE,UAAU,WAAW,UAAU,SAAiB,EAAE,KAAK,CAAC;CAChE,MAAM,EAAE,YAAY,oBAAoB;CACxC,MAAM,WAAW,eACf,CAAC,YAAY,SAAS,kBAAkB,KAC1C;CAOA,MAAM,UAAU,oBAAoB;EACnC,SANqB,cACf,MAAM,QAAQ,KAAK,WAAW,eAAe,QAAQ,MAAM,CAAC,GAClE,CAAC,MAAM,SAAS,MAAM,CAID;EACrB;EACA;EACA,SAAS,WAAW,CAAC;CACtB,CAAC,EAAE,KAAK,YAAY;EAAE,OAAO,OAAO;EAAiB,OAAO,OAAO;CAAM,EAAE;CAE3E,OACC,oBAAC,aAAD;EACC,aAAa;EACb,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,WAAW,aAAsD;GAChE,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK;GACvD,SAAS,SAAS,OAAO,OAAO,KAAK,IAAI,IAAI;EAC9C;EACS;EACH;EACI;EACV,UAAU,MAAM;EACL;EACJ;CACP,CAAA;AAEH"}
@@ -0,0 +1,14 @@
1
+ import { SelectFieldClientProps } from "payload";
2
+
3
+ //#region src/fields/config/SourceSelectField.d.ts
4
+ /**
5
+ * Source picker for scoped widget config: starts from the field's static
6
+ * option list and, once the caller-scope sources endpoint answers, replaces
7
+ * it with the live adapter list so a tenant only ever sees sources it can
8
+ * actually read from. A failed fetch keeps the static list rather than
9
+ * emptying the picker.
10
+ */
11
+ declare const SourceSelectField: (props: SelectFieldClientProps) => import("react/jsx-runtime").JSX.Element;
12
+ //#endregion
13
+ export { SourceSelectField };
14
+ //# sourceMappingURL=SourceSelectField.d.ts.map
@@ -0,0 +1,46 @@
1
+ "use client";
2
+ import { useTranslation as useTranslation$1 } from "../../translations/useTranslation.js";
3
+ import { toSelectOption } from "./toSelectOption.js";
4
+ import { useAnalyticsSources } from "./useAnalyticsSources.js";
5
+ import { useMemo } from "react";
6
+ import { jsx } from "react/jsx-runtime";
7
+ import { SelectInput, useField } from "@payloadcms/ui";
8
+ //#region src/fields/config/SourceSelectField.tsx
9
+ /**
10
+ * Source picker for scoped widget config: starts from the field's static
11
+ * option list and, once the caller-scope sources endpoint answers, replaces
12
+ * it with the live adapter list so a tenant only ever sees sources it can
13
+ * actually read from. A failed fetch keeps the static list rather than
14
+ * emptying the picker.
15
+ */
16
+ const SourceSelectField = (props) => {
17
+ const { field, path, readOnly } = props;
18
+ const { i18n } = useTranslation$1();
19
+ const locale = i18n.language;
20
+ const { setValue, showError, value } = useField({ path });
21
+ const { sources } = useAnalyticsSources();
22
+ const staticOptions = useMemo(() => field.options.map((option) => toSelectOption(option, locale)), [field.options, locale]);
23
+ const options = sources && sources.length > 0 ? sources.map((source) => ({
24
+ value: source.id,
25
+ label: source.label
26
+ })) : staticOptions;
27
+ return /* @__PURE__ */ jsx(SelectInput, {
28
+ isClearable: false,
29
+ label: field.label,
30
+ name: field.name,
31
+ onChange: (selected) => {
32
+ const option = Array.isArray(selected) ? selected[0] : selected;
33
+ setValue(option ? String(option.value) : null);
34
+ },
35
+ options,
36
+ path,
37
+ readOnly,
38
+ required: field.required,
39
+ showError,
40
+ value
41
+ });
42
+ };
43
+ //#endregion
44
+ export { SourceSelectField };
45
+
46
+ //# sourceMappingURL=SourceSelectField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SourceSelectField.js","names":["useTranslation"],"sources":["../../../src/fields/config/SourceSelectField.tsx"],"sourcesContent":["'use client'\n\nimport { type ReactSelectOption, SelectInput, useField } from '@payloadcms/ui'\nimport type { SelectFieldClientProps } from 'payload'\nimport { useMemo } from 'react'\nimport { useTranslation } from '../../translations/useTranslation'\nimport { toSelectOption } from './toSelectOption'\nimport { useAnalyticsSources } from './useAnalyticsSources'\n\n/**\n * Source picker for scoped widget config: starts from the field's static\n * option list and, once the caller-scope sources endpoint answers, replaces\n * it with the live adapter list so a tenant only ever sees sources it can\n * actually read from. A failed fetch keeps the static list rather than\n * emptying the picker.\n */\nexport const SourceSelectField = (props: SelectFieldClientProps) => {\n\tconst { field, path, readOnly } = props\n\tconst { i18n } = useTranslation()\n\tconst locale = i18n.language\n\tconst { setValue, showError, value } = useField<string>({ path })\n\tconst { sources } = useAnalyticsSources()\n\n\tconst staticOptions = useMemo(\n\t\t() => field.options.map((option) => toSelectOption(option, locale)),\n\t\t[field.options, locale]\n\t)\n\n\tconst options =\n\t\tsources && sources.length > 0\n\t\t\t? sources.map((source) => ({ value: source.id, label: source.label }))\n\t\t\t: staticOptions\n\n\treturn (\n\t\t<SelectInput\n\t\t\tisClearable={false}\n\t\t\tlabel={field.label}\n\t\t\tname={field.name}\n\t\t\tonChange={(selected: ReactSelectOption | ReactSelectOption[]) => {\n\t\t\t\tconst option = Array.isArray(selected) ? selected[0] : selected\n\t\t\t\tsetValue(option ? String(option.value) : null)\n\t\t\t}}\n\t\t\toptions={options}\n\t\t\tpath={path}\n\t\t\treadOnly={readOnly}\n\t\t\trequired={field.required}\n\t\t\tshowError={showError}\n\t\t\tvalue={value}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAa,qBAAqB,UAAkC;CACnE,MAAM,EAAE,OAAO,MAAM,aAAa;CAClC,MAAM,EAAE,SAASA,iBAAe;CAChC,MAAM,SAAS,KAAK;CACpB,MAAM,EAAE,UAAU,WAAW,UAAU,SAAiB,EAAE,KAAK,CAAC;CAChE,MAAM,EAAE,YAAY,oBAAoB;CAExC,MAAM,gBAAgB,cACf,MAAM,QAAQ,KAAK,WAAW,eAAe,QAAQ,MAAM,CAAC,GAClE,CAAC,MAAM,SAAS,MAAM,CACvB;CAEA,MAAM,UACL,WAAW,QAAQ,SAAS,IACzB,QAAQ,KAAK,YAAY;EAAE,OAAO,OAAO;EAAI,OAAO,OAAO;CAAM,EAAE,IACnE;CAEJ,OACC,oBAAC,aAAD;EACC,aAAa;EACb,OAAO,MAAM;EACb,MAAM,MAAM;EACZ,WAAW,aAAsD;GAChE,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,SAAS,KAAK;GACvD,SAAS,SAAS,OAAO,OAAO,KAAK,IAAI,IAAI;EAC9C;EACS;EACH;EACI;EACV,UAAU,MAAM;EACL;EACJ;CACP,CAAA;AAEH"}
@@ -0,0 +1,12 @@
1
+ import { SerializedCapabilities } from "../../core/capabilities.js";
2
+
3
+ //#region src/fields/config/fetchSources.d.ts
4
+ interface WireSource {
5
+ id: string;
6
+ label: string;
7
+ kind: 'config' | 'runtime';
8
+ capabilities: SerializedCapabilities;
9
+ }
10
+ //#endregion
11
+ export { WireSource };
12
+ //# sourceMappingURL=fetchSources.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { SOURCES_PATH } from "../../plugin/paths.js";
2
+ //#region src/fields/config/fetchSources.ts
3
+ const cache = /* @__PURE__ */ new Map();
4
+ /**
5
+ * Fetch the caller-scope source list once per user per admin session and share
6
+ * it between every picker instance on the page; a failed fetch clears its cache
7
+ * entry so a later mount retries instead of pinning the error. Keying by user
8
+ * id keeps a soft-navigation logout/login from serving the previous user's
9
+ * cached sources.
10
+ */
11
+ const fetchSources = (serverURL, apiRoute, userKey) => {
12
+ const url = `${serverURL}${apiRoute}${SOURCES_PATH}`;
13
+ const key = `${userKey}:${url}`;
14
+ const hit = cache.get(key);
15
+ if (hit) return hit;
16
+ const p = fetch(url, { credentials: "include" }).then((res) => {
17
+ if (!res.ok) throw new Error(`sources ${res.status}`);
18
+ return res.json();
19
+ }).catch((err) => {
20
+ cache.delete(key);
21
+ throw err;
22
+ });
23
+ cache.set(key, p);
24
+ return p;
25
+ };
26
+ //#endregion
27
+ export { fetchSources };
28
+
29
+ //# sourceMappingURL=fetchSources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchSources.js","names":[],"sources":["../../../src/fields/config/fetchSources.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../../core/capabilities'\nimport { SOURCES_PATH } from '../../plugin/paths'\n\nexport interface WireSource {\n\tid: string\n\tlabel: string\n\tkind: 'config' | 'runtime'\n\tcapabilities: SerializedCapabilities\n}\n\nexport interface SourcesResponse {\n\tdefaultId: string | null\n\tsources: WireSource[]\n}\n\nconst cache = new Map<string, Promise<SourcesResponse>>()\n\n/**\n * Fetch the caller-scope source list once per user per admin session and share\n * it between every picker instance on the page; a failed fetch clears its cache\n * entry so a later mount retries instead of pinning the error. Keying by user\n * id keeps a soft-navigation logout/login from serving the previous user's\n * cached sources.\n */\nexport const fetchSources = (\n\tserverURL: string,\n\tapiRoute: string,\n\tuserKey: string\n): Promise<SourcesResponse> => {\n\tconst url = `${serverURL}${apiRoute}${SOURCES_PATH}`\n\tconst key = `${userKey}:${url}`\n\tconst hit = cache.get(key)\n\tif (hit) return hit\n\tconst p = fetch(url, { credentials: 'include' })\n\t\t.then((res) => {\n\t\t\tif (!res.ok) throw new Error(`sources ${res.status}`)\n\t\t\treturn res.json() as Promise<SourcesResponse>\n\t\t})\n\t\t.catch((err) => {\n\t\t\tcache.delete(key)\n\t\t\tthrow err\n\t\t})\n\tcache.set(key, p)\n\treturn p\n}\n"],"mappings":";;AAeA,MAAM,wBAAQ,IAAI,IAAsC;;;;;;;;AASxD,MAAa,gBACZ,WACA,UACA,YAC8B;CAC9B,MAAM,MAAM,GAAG,YAAY,WAAW;CACtC,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,MAAM,MAAM,MAAM,IAAI,GAAG;CACzB,IAAI,KAAK,OAAO;CAChB,MAAM,IAAI,MAAM,KAAK,EAAE,aAAa,UAAU,CAAC,EAC7C,MAAM,QAAQ;EACd,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,WAAW,IAAI,QAAQ;EACpD,OAAO,IAAI,KAAK;CACjB,CAAC,EACA,OAAO,QAAQ;EACf,MAAM,OAAO,GAAG;EAChB,MAAM;CACP,CAAC;CACF,MAAM,IAAI,KAAK,CAAC;CAChB,OAAO;AACR"}
@@ -0,0 +1,30 @@
1
+ //#region src/fields/config/narrow.ts
2
+ /** satisfiesCapabilities over the wire form (arrays instead of Sets). */
3
+ const satisfiesSerialized = (caps, req) => {
4
+ if (req.realtime && !caps.realtime) return false;
5
+ if (req.perPageQuery && !caps.perPageQuery) return false;
6
+ if (req.metrics?.some((m) => !caps.metrics.includes(m))) return false;
7
+ if (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false;
8
+ return true;
9
+ };
10
+ /**
11
+ * Options for the metric picker, narrowed to what the selected source can
12
+ * serve. An unknown source id (a stale value, a source the endpoint could not
13
+ * list) keeps the full static list, mirroring the server-side filterOptions
14
+ * fallback, and a source that cannot meet the widget's extra requirements at
15
+ * all falls back to the full list rather than an empty picker.
16
+ */
17
+ const narrowMetricOptions = (args) => {
18
+ const src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : void 0;
19
+ if (!src) return args.options;
20
+ if (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) return args.options;
21
+ const narrowed = args.options.filter((o) => satisfiesSerialized(src.capabilities, {
22
+ ...args.requires,
23
+ metrics: [o.value]
24
+ }));
25
+ return narrowed.length > 0 ? narrowed : args.options;
26
+ };
27
+ //#endregion
28
+ export { narrowMetricOptions };
29
+
30
+ //# sourceMappingURL=narrow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
@@ -0,0 +1,11 @@
1
+ //#region src/fields/config/sourcesState.ts
2
+ const EMPTY_SOURCES = {
3
+ defaultId: null,
4
+ sources: null
5
+ };
6
+ /** Sources fetched for another user never render: a key mismatch reads as not-yet-loaded. */
7
+ const resolveSourcesState = (state, userKey) => state.key === userKey ? state.data : EMPTY_SOURCES;
8
+ //#endregion
9
+ export { EMPTY_SOURCES, resolveSourcesState };
10
+
11
+ //# sourceMappingURL=sourcesState.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sourcesState.js","names":[],"sources":["../../../src/fields/config/sourcesState.ts"],"sourcesContent":["import type { AnalyticsSources } from './useAnalyticsSources'\n\nexport interface KeyedSources {\n\tkey: string\n\tdata: AnalyticsSources\n}\n\nexport const EMPTY_SOURCES: AnalyticsSources = { defaultId: null, sources: null }\n\n/** Sources fetched for another user never render: a key mismatch reads as not-yet-loaded. */\nexport const resolveSourcesState = (state: KeyedSources, userKey: string): AnalyticsSources =>\n\tstate.key === userKey ? state.data : EMPTY_SOURCES\n"],"mappings":";AAOA,MAAa,gBAAkC;CAAE,WAAW;CAAM,SAAS;AAAK;;AAGhF,MAAa,uBAAuB,OAAqB,YACxD,MAAM,QAAQ,UAAU,MAAM,OAAO"}
@@ -0,0 +1,27 @@
1
+ //#region src/fields/config/toSelectOption.ts
2
+ /**
3
+ * Static select options in this plugin carry per-locale label maps
4
+ * (Record<string, string>) from registerWidgets. Resolve an `Option` to a
5
+ * plain `{ value, label }` pair for the current locale, falling back to
6
+ * English, then to the raw value.
7
+ */
8
+ const toSelectOption = (option, locale) => {
9
+ if (typeof option === "string") return {
10
+ label: option,
11
+ value: option
12
+ };
13
+ const { label, value } = option;
14
+ if (typeof label === "string") return {
15
+ label,
16
+ value
17
+ };
18
+ const map = label;
19
+ return {
20
+ label: map?.[locale] ?? map?.en ?? value,
21
+ value
22
+ };
23
+ };
24
+ //#endregion
25
+ export { toSelectOption };
26
+
27
+ //# sourceMappingURL=toSelectOption.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toSelectOption.js","names":[],"sources":["../../../src/fields/config/toSelectOption.ts"],"sourcesContent":["import type { Option } from 'payload'\n\n/**\n * Static select options in this plugin carry per-locale label maps\n * (Record<string, string>) from registerWidgets. Resolve an `Option` to a\n * plain `{ value, label }` pair for the current locale, falling back to\n * English, then to the raw value.\n */\nexport const toSelectOption = (\n\toption: Option,\n\tlocale: string\n): { label: string; value: string } => {\n\tif (typeof option === 'string') return { label: option, value: option }\n\tconst { label, value } = option\n\tif (typeof label === 'string') return { label, value }\n\tconst map = label as Record<string, string> | undefined\n\treturn { label: map?.[locale] ?? map?.en ?? value, value }\n}\n"],"mappings":";;;;;;;AAQA,MAAa,kBACZ,QACA,WACsC;CACtC,IAAI,OAAO,WAAW,UAAU,OAAO;EAAE,OAAO;EAAQ,OAAO;CAAO;CACtE,MAAM,EAAE,OAAO,UAAU;CACzB,IAAI,OAAO,UAAU,UAAU,OAAO;EAAE;EAAO;CAAM;CACrD,MAAM,MAAM;CACZ,OAAO;EAAE,OAAO,MAAM,WAAW,KAAK,MAAM;EAAO;CAAM;AAC1D"}
@@ -0,0 +1,19 @@
1
+ import { WireSource } from "./fetchSources.js";
2
+
3
+ //#region src/fields/config/useAnalyticsSources.d.ts
4
+ interface AnalyticsSources {
5
+ sources: WireSource[] | null;
6
+ defaultId: string | null;
7
+ }
8
+ /**
9
+ * Fetches the caller-scope source list for widget config pickers, sharing the
10
+ * per-user cache `fetchSources` already keeps. `sources` and `defaultId` stay
11
+ * null until the fetch resolves, on a failed fetch, or when there is no
12
+ * authenticated user yet; consumers fall back to their static option list in
13
+ * that window. Sources fetched for a previous user are never returned while
14
+ * a new user's fetch is pending.
15
+ */
16
+ declare const useAnalyticsSources: () => AnalyticsSources;
17
+ //#endregion
18
+ export { useAnalyticsSources };
19
+ //# sourceMappingURL=useAnalyticsSources.d.ts.map