@delmaredigital/payload-experiments 0.4.1 → 0.5.0
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/README.md +9 -5
- package/dist/admin/blocks/model.js +2 -0
- package/dist/admin/copy/blocks.d.ts +1 -0
- package/dist/admin/copy/blocks.js +1 -0
- package/dist/admin/copy/status.d.ts +3 -0
- package/dist/admin/copy/status.js +3 -0
- package/dist/admin/placementStatus.model.js +3 -0
- package/dist/admin/status.model.d.ts +3 -2
- package/dist/admin/status.model.js +9 -3
- package/dist/admin/surface/ResultsRoute.js +2 -1
- package/dist/admin/surface/TestsHome.d.ts +2 -1
- package/dist/admin/surface/TestsHome.js +31 -11
- package/dist/admin/surface/TestsSurface.js +4 -0
- package/dist/admin/surface/home.model.d.ts +11 -6
- package/dist/admin/surface/home.model.js +19 -8
- package/dist/admin/surface/newTest/PageWizard.js +13 -3
- package/dist/admin/surface/results/ResultsHeader.js +43 -9
- package/dist/admin/surface/test/TestPage.js +11 -1
- package/dist/admin/useLayerUsage.d.ts +1 -1
- package/dist/admin/views/buildSurfaceProps.js +3 -0
- package/dist/cohorts/build.d.ts +35 -0
- package/dist/cohorts/build.js +134 -0
- package/dist/cohorts/key.d.ts +12 -0
- package/dist/cohorts/key.js +15 -0
- package/dist/cohorts/maintenance.d.ts +10 -0
- package/dist/cohorts/maintenance.js +70 -0
- package/dist/cohorts/readiness.d.ts +30 -0
- package/dist/cohorts/readiness.js +54 -0
- package/dist/cohorts/readinessData.d.ts +29 -0
- package/dist/cohorts/readinessData.js +123 -0
- package/dist/cohorts/rule.d.ts +33 -0
- package/dist/cohorts/rule.js +50 -0
- package/dist/collections/cohortMembers.d.ts +4 -0
- package/dist/collections/cohortMembers.js +95 -0
- package/dist/collections/experiments/config.js +157 -7
- package/dist/collections/experiments/editability.js +10 -6
- package/dist/collections/experiments/lockHook.js +39 -20
- package/dist/collections/index.js +4 -1
- package/dist/collections/phases.js +4 -1
- package/dist/constants.d.ts +2 -0
- package/dist/constants.js +2 -0
- package/dist/db/adapter.d.ts +1 -1
- package/dist/db/adapter.js +14 -4
- package/dist/db/appends.js +1 -1
- package/dist/db/cohortMembership.d.ts +11 -0
- package/dist/db/cohortMembership.js +31 -0
- package/dist/db/cohortPool.d.ts +9 -0
- package/dist/db/cohortPool.js +53 -0
- package/dist/db/cohortTransactions.d.ts +3 -0
- package/dist/db/cohortTransactions.js +52 -0
- package/dist/db/cohorts.d.ts +72 -0
- package/dist/db/cohorts.js +280 -0
- package/dist/db/erase.d.ts +2 -0
- package/dist/db/erase.js +21 -2
- package/dist/db/events.d.ts +2 -0
- package/dist/db/events.js +8 -0
- package/dist/db/executor.d.ts +2 -0
- package/dist/db/executor.js +8 -0
- package/dist/db/locks.d.ts +7 -0
- package/dist/db/locks.js +13 -1
- package/dist/db/names.d.ts +95 -1
- package/dist/db/names.js +95 -1
- package/dist/db/occupancy.d.ts +21 -0
- package/dist/db/occupancy.js +46 -0
- package/dist/db/pageOccupancy.d.ts +4 -4
- package/dist/db/pageOccupancy.js +13 -10
- package/dist/db/pgExecutor.d.ts +4 -0
- package/dist/db/pgExecutor.js +1 -1
- package/dist/db/placements.js +1 -1
- package/dist/db/results.d.ts +5 -2
- package/dist/db/results.js +32 -5
- package/dist/db/slices.d.ts +9 -2
- package/dist/db/slices.js +15 -8
- package/dist/db/snapshots.d.ts +16 -1
- package/dist/db/snapshots.js +27 -2
- package/dist/db/sql.d.ts +2 -2
- package/dist/db/sql.js +1 -2
- package/dist/endpoints/cohortSources.d.ts +16 -0
- package/dist/endpoints/cohortSources.js +335 -0
- package/dist/endpoints/contentLocale.d.ts +1 -1
- package/dist/endpoints/events.js +82 -18
- package/dist/endpoints/index.js +45 -1
- package/dist/endpoints/pausedBy.d.ts +14 -0
- package/dist/endpoints/pausedBy.js +94 -0
- package/dist/endpoints/preflight.js +4 -1
- package/dist/endpoints/previewToken.js +2 -0
- package/dist/endpoints/results.d.ts +2 -2
- package/dist/endpoints/results.js +111 -3
- package/dist/endpoints/routeId.d.ts +2 -1
- package/dist/endpoints/routeId.js +6 -2
- package/dist/endpoints/summary.js +24 -1
- package/dist/endpoints/transitions.d.ts +7 -0
- package/dist/endpoints/transitions.js +50 -1
- package/dist/events/rows.d.ts +1 -1
- package/dist/events/rows.js +5 -3
- package/dist/exports/index.d.ts +2 -0
- package/dist/exports/index.js +1 -0
- package/dist/exports/runtimeProxy.d.ts +1 -0
- package/dist/exports/runtimeProxy.js +1 -0
- package/dist/hooks/blockRemovalRule.js +7 -4
- package/dist/hooks/pageGuard.js +1 -1
- package/dist/labels/status.d.ts +15 -0
- package/dist/labels/status.js +12 -0
- package/dist/manifest/compile.d.ts +15 -4
- package/dist/manifest/compile.js +91 -3
- package/dist/onInit.js +4 -1
- package/dist/options.d.ts +1 -0
- package/dist/options.js +10 -0
- package/dist/proxy/consentFallback.d.ts +1 -1
- package/dist/proxy/consentFallback.js +4 -4
- package/dist/proxy/control.d.ts +1 -1
- package/dist/proxy/control.js +2 -2
- package/dist/proxy/pageRewrite.d.ts +1 -1
- package/dist/proxy/pageRewrite.js +3 -2
- package/dist/proxy/resolve.js +76 -17
- package/dist/puck/ExperimentPicker.js +2 -1
- package/dist/puck/copy.d.ts +6 -5
- package/dist/puck/copy.js +3 -7
- package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
- package/dist/puck/editor/QuickTestActions.js +7 -1
- package/dist/puck/editor/armWrites.js +6 -1
- package/dist/puck/editor/copy.d.ts +3 -0
- package/dist/puck/editor/copy.js +3 -0
- package/dist/puck/editor/editor.css +2 -1
- package/dist/puck/editor/editor.model.d.ts +2 -1
- package/dist/puck/editor/editor.model.js +2 -0
- package/dist/puck/editor/placementsCache.d.ts +1 -1
- package/dist/puck/editor/placementsCache.js +6 -3
- package/dist/results/analyse.d.ts +3 -1
- package/dist/results/analyse.js +20 -3
- package/dist/results/health.d.ts +11 -0
- package/dist/results/health.js +38 -0
- package/dist/results/power.d.ts +1 -1
- package/dist/results/power.js +1 -1
- package/dist/results/snapshot.d.ts +8 -2
- package/dist/results/snapshot.js +23 -1
- package/dist/results/unitValues.d.ts +48 -0
- package/dist/results/unitValues.js +166 -0
- package/dist/runtime/assign.d.ts +7 -3
- package/dist/runtime/assign.js +12 -4
- package/dist/runtime/cohortCookie.d.ts +15 -0
- package/dist/runtime/cohortCookie.js +72 -0
- package/dist/runtime/cohortLookup.d.ts +9 -0
- package/dist/runtime/cohortLookup.js +25 -0
- package/dist/runtime/eligibility.d.ts +11 -5
- package/dist/runtime/eligibility.js +33 -7
- package/dist/runtime/header.d.ts +1 -0
- package/dist/runtime/header.js +1 -1
- package/dist/runtime/proxyRuntime.js +5 -1
- package/dist/runtime/targeting.d.ts +3 -2
- package/dist/runtime/targeting.js +2 -1
- package/dist/sanitizeReadinessDetail.d.ts +2 -2
- package/dist/sanitizeReadinessDetail.js +41 -4
- package/dist/schedule/activeTime.d.ts +28 -0
- package/dist/schedule/activeTime.js +322 -0
- package/dist/schedule/ranges.d.ts +13 -0
- package/dist/schedule/ranges.js +11 -0
- package/dist/schedule/roundTime.d.ts +10 -0
- package/dist/schedule/roundTime.js +45 -0
- package/dist/schedule/types.d.ts +29 -0
- package/dist/schedule/types.js +1 -0
- package/dist/server/cohortLookup.d.ts +3 -0
- package/dist/server/cohortLookup.js +7 -0
- package/dist/server/eraseUser.d.ts +1 -0
- package/dist/server/getAssignments.js +63 -40
- package/dist/server/previewDraft.d.ts +1 -1
- package/dist/server/previewDraft.js +3 -2
- package/dist/server/recordExposures.js +4 -2
- package/dist/server/runResults.js +97 -150
- package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
- package/dist/testSurface/actions/LifecycleAction.js +15 -5
- package/dist/testSurface/actions/actions.model.d.ts +13 -2
- package/dist/testSurface/actions/actions.model.js +38 -5
- package/dist/testSurface/api.d.ts +13 -1
- package/dist/testSurface/api.js +19 -0
- package/dist/testSurface/copy/actions.d.ts +13 -0
- package/dist/testSurface/copy/actions.js +13 -0
- package/dist/testSurface/copy/cohorts.d.ts +68 -0
- package/dist/testSurface/copy/cohorts.js +81 -0
- package/dist/testSurface/copy/common.d.ts +2 -3
- package/dist/testSurface/copy/common.js +4 -4
- package/dist/testSurface/copy/inputs.d.ts +3 -0
- package/dist/testSurface/copy/inputs.js +3 -0
- package/dist/testSurface/copy/readiness.d.ts +20 -6
- package/dist/testSurface/copy/readiness.js +42 -9
- package/dist/testSurface/copy/results.d.ts +1 -0
- package/dist/testSurface/copy/results.js +1 -0
- package/dist/testSurface/copy/schedule.d.ts +58 -0
- package/dist/testSurface/copy/schedule.js +150 -0
- package/dist/testSurface/copy/surface.d.ts +2 -0
- package/dist/testSurface/copy/surface.js +2 -0
- package/dist/testSurface/copy/testPage.d.ts +12 -2
- package/dist/testSurface/copy/testPage.js +17 -2
- package/dist/testSurface/format/roundProgress.d.ts +13 -1
- package/dist/testSurface/format/roundProgress.js +34 -5
- package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
- package/dist/testSurface/format/scheduleStatus.js +93 -0
- package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
- package/dist/testSurface/format/useScheduleClock.js +20 -0
- package/dist/testSurface/labels.d.ts +4 -9
- package/dist/testSurface/labels.js +2 -7
- package/dist/testSurface/lockedNotice.model.d.ts +2 -2
- package/dist/testSurface/lockedNotice.model.js +16 -3
- package/dist/testSurface/readPreflight.d.ts +3 -0
- package/dist/testSurface/readPreflight.js +14 -0
- package/dist/testSurface/readinessRead.d.ts +2 -2
- package/dist/testSurface/results/DataQualityPanel.js +7 -7
- package/dist/testSurface/results/results.model.d.ts +1 -1
- package/dist/testSurface/results/results.model.js +34 -6
- package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
- package/dist/testSurface/review/cohortEstimate.js +32 -0
- package/dist/testSurface/surface/contracts.d.ts +2 -1
- package/dist/testSurface/surface/contracts.js +1 -0
- package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
- package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
- package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
- package/dist/testSurface/surface/readiness/Banner.js +29 -11
- package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
- package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
- package/dist/testSurface/surface/readiness/useTransition.js +17 -5
- package/dist/testSurface/surface/results/ResultsBody.js +44 -8
- package/dist/testSurface/surface/results/useResults.d.ts +16 -1
- package/dist/testSurface/surface/results/useResults.js +17 -6
- package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
- package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
- package/dist/testSurface/surface/test/LengthSection.js +26 -6
- package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
- package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
- package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
- package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
- package/dist/testSurface/surface/test/Section.js +1 -1
- package/dist/testSurface/surface/test/TargetingSection.js +306 -182
- package/dist/testSurface/surface/test/TestSurface.js +9 -0
- package/dist/testSurface/surface/test/fields.d.ts +2 -1
- package/dist/testSurface/surface/test/fields.js +3 -3
- package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
- package/dist/testSurface/surface/test/jumpToSection.js +4 -4
- package/dist/testSurface/surface/test/testPage.css +26 -0
- package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
- package/dist/testSurface/surface/testDocument.model.js +2 -1
- package/dist/testSurface/surface/useTestDocument.js +11 -4
- package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
- package/dist/testSurface/targeting/targeting.model.js +1 -1
- package/dist/testSurface/useApi.d.ts +12 -0
- package/dist/transitions/addMetric.js +5 -2
- package/dist/transitions/allocate.js +6 -1
- package/dist/transitions/assertNoOverlap.d.ts +9 -0
- package/dist/transitions/assertNoOverlap.js +24 -0
- package/dist/transitions/buildCohorts.d.ts +10 -0
- package/dist/transitions/buildCohorts.js +68 -0
- package/dist/transitions/cancelSchedule.d.ts +4 -0
- package/dist/transitions/cancelSchedule.js +42 -0
- package/dist/transitions/checkStart.d.ts +17 -3
- package/dist/transitions/checkStart.js +20 -7
- package/dist/transitions/decide.js +35 -11
- package/dist/transitions/kernel.d.ts +3 -1
- package/dist/transitions/kernel.js +5 -2
- package/dist/transitions/pause.d.ts +4 -0
- package/dist/transitions/pause.js +35 -0
- package/dist/transitions/phaseRecord.d.ts +19 -2
- package/dist/transitions/phaseRecord.js +50 -11
- package/dist/transitions/placementInteractions.js +1 -1
- package/dist/transitions/preflightData.d.ts +11 -3
- package/dist/transitions/preflightData.js +134 -81
- package/dist/transitions/reschedule.d.ts +4 -0
- package/dist/transitions/reschedule.js +58 -0
- package/dist/transitions/resume.d.ts +4 -0
- package/dist/transitions/resume.js +32 -0
- package/dist/transitions/scheduledRound.d.ts +18 -0
- package/dist/transitions/scheduledRound.js +42 -0
- package/dist/transitions/start.d.ts +4 -0
- package/dist/transitions/start.js +136 -55
- package/dist/transitions/startReads.d.ts +14 -0
- package/dist/transitions/startReads.js +27 -0
- package/dist/transitions/stop.d.ts +10 -0
- package/dist/transitions/stop.js +35 -22
- package/dist/types/admin.d.ts +1 -1
- package/dist/types/contracts.d.ts +7 -1
- package/dist/types/endpoints.d.ts +72 -3
- package/dist/types/manifest.d.ts +9 -0
- package/dist/types/runtime.d.ts +5 -0
- package/dist/types/snapshot.d.ts +10 -0
- package/dist/types/status.d.ts +1 -0
- package/dist/types/status.js +1 -0
- package/dist/types/surface.d.ts +1 -0
- package/dist/ui/Feedback.d.ts +9 -6
- package/dist/ui/Feedback.js +10 -9
- package/dist/ui/SelectControl.js +1 -1
- package/dist/ui/ui.css +2 -1
- package/package.json +2 -2
package/dist/results/power.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { GaussianPrior, TestStatistic } from '@delmaredigital/experiments-stats';
|
|
2
2
|
import type { Snapshot } from '../types/snapshot.js';
|
|
3
3
|
/** Present the stats engine's pairwise sample estimate at observed exposed-unit
|
|
4
|
-
* traffic.
|
|
4
|
+
* traffic per active day. Planning uses 10% relative lift and 80% power (as Review does).
|
|
5
5
|
* Called for running test verdict rows 4 and 9; rollout and concluded tests omit estimates.
|
|
6
6
|
*/
|
|
7
7
|
export declare function remainingPower(input: {
|
package/dist/results/power.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { abTestMoments, midExperimentPower, sequentialTwoSidedTTest } from '@delmaredigital/experiments-stats';
|
|
2
2
|
/** Present the stats engine's pairwise sample estimate at observed exposed-unit
|
|
3
|
-
* traffic.
|
|
3
|
+
* traffic per active day. Planning uses 10% relative lift and 80% power (as Review does).
|
|
4
4
|
* Called for running test verdict rows 4 and 9; rollout and concluded tests omit estimates.
|
|
5
5
|
*/ export function remainingPower(input) {
|
|
6
6
|
const lowerBound = input.method === 'sequential';
|
|
@@ -4,6 +4,12 @@ export declare function jsonInterval(ci: readonly [number | null, number | null]
|
|
|
4
4
|
/** Validate the frozen JSON shape and headline/rollout invariants before storage.
|
|
5
5
|
* This also accepts the shared CORE-13/admin fixtures without any I/O.
|
|
6
6
|
*/
|
|
7
|
-
export declare function validateSnapshot(value: unknown): asserts value is
|
|
7
|
+
export declare function validateSnapshot(value: unknown): asserts value is SnapshotWithLegacyExposures;
|
|
8
|
+
export type SnapshotWithLegacyExposures = Omit<Snapshot, 'exposures'> & {
|
|
9
|
+
exposures: Omit<Snapshot['exposures'], 'cohortExits'> & {
|
|
10
|
+
cohortExits?: number;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
export declare function withCohortExitDefault(snapshot: SnapshotWithLegacyExposures): Snapshot;
|
|
8
14
|
/** Assemble the already-computed snapshot at the pure/I/O boundary. */
|
|
9
|
-
export declare function assembleSnapshot(snapshot:
|
|
15
|
+
export declare function assembleSnapshot(snapshot: SnapshotWithLegacyExposures): Snapshot;
|
package/dist/results/snapshot.js
CHANGED
|
@@ -64,6 +64,8 @@ const shape = object({
|
|
|
64
64
|
armMismatch: count,
|
|
65
65
|
identityConflictShare: probability,
|
|
66
66
|
capped: record(count)
|
|
67
|
+
}, {
|
|
68
|
+
cohortExits: count
|
|
67
69
|
}),
|
|
68
70
|
srm: object({
|
|
69
71
|
p: probability,
|
|
@@ -141,6 +143,7 @@ const shape = object({
|
|
|
141
143
|
by: nullable(id)
|
|
142
144
|
}))
|
|
143
145
|
}, {
|
|
146
|
+
activeDays: count,
|
|
144
147
|
goalFairnessNotice: string,
|
|
145
148
|
health: list(union(object({
|
|
146
149
|
code: oneOf('version-page-unavailable', 'version-page-unchecked'),
|
|
@@ -156,6 +159,16 @@ const shape = object({
|
|
|
156
159
|
id,
|
|
157
160
|
path: string
|
|
158
161
|
})
|
|
162
|
+
}), object({
|
|
163
|
+
code: oneOf('rapid-browser-events')
|
|
164
|
+
}), object({
|
|
165
|
+
code: oneOf('cohort-no-exposures')
|
|
166
|
+
}), object({
|
|
167
|
+
code: oneOf('paused-share'),
|
|
168
|
+
pausedDays: number
|
|
169
|
+
}), object({
|
|
170
|
+
code: oneOf('schedule-population'),
|
|
171
|
+
summary: string
|
|
159
172
|
})))
|
|
160
173
|
});
|
|
161
174
|
/** Validate the frozen JSON shape and headline/rollout invariants before storage.
|
|
@@ -167,7 +180,16 @@ const shape = object({
|
|
|
167
180
|
throw new XpAnalysisError('snapshot-invariants');
|
|
168
181
|
}
|
|
169
182
|
}
|
|
183
|
+
export function withCohortExitDefault(snapshot) {
|
|
184
|
+
return {
|
|
185
|
+
...snapshot,
|
|
186
|
+
exposures: {
|
|
187
|
+
...snapshot.exposures,
|
|
188
|
+
cohortExits: snapshot.exposures.cohortExits ?? 0
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
170
192
|
/** Assemble the already-computed snapshot at the pure/I/O boundary. */ export function assembleSnapshot(snapshot) {
|
|
171
193
|
validateSnapshot(snapshot);
|
|
172
|
-
return snapshot;
|
|
194
|
+
return withCohortExitDefault(snapshot);
|
|
173
195
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ResolvedOptions, UnitType } from '../types/contracts.js';
|
|
2
|
+
import { type Executor } from '../db/executor.js';
|
|
3
|
+
import type { ResultsPhase } from '../db/snapshots.js';
|
|
4
|
+
import { type ExposedUnit, type MetricEvent } from './aggregate.js';
|
|
5
|
+
/** Attribution uses all exposed units before an audience selects source arms. */
|
|
6
|
+
export declare function unitValueContext(exec: Executor, unitType: UnitType, units: ReadonlyMap<string, ExposedUnit>): Promise<{
|
|
7
|
+
ids: string[];
|
|
8
|
+
identities: import("../db/results.js").IdentityRow[];
|
|
9
|
+
userIds: string[];
|
|
10
|
+
identityConflicts: Set<string>;
|
|
11
|
+
credit: (events: Array<MetricEvent & {
|
|
12
|
+
userId?: string | null;
|
|
13
|
+
}>, userKeyed: boolean) => MetricEvent[];
|
|
14
|
+
}>;
|
|
15
|
+
type MetricRead = Awaited<ReturnType<typeof readUnitMetricEvents>>;
|
|
16
|
+
/** Shared conversion and identity attribution for results and cohort membership. */
|
|
17
|
+
export declare function readUnitMetricEvents(exec: Executor, { phase, unitType, units, context, definition, options, to, deadline, includePrePeriod, readAge, }: {
|
|
18
|
+
phase: ResultsPhase;
|
|
19
|
+
unitType: UnitType;
|
|
20
|
+
units: ReadonlyMap<string, ExposedUnit>;
|
|
21
|
+
context: Awaited<ReturnType<typeof unitValueContext>>;
|
|
22
|
+
definition: ResultsPhase['metricDefinitions'][number];
|
|
23
|
+
options: Pick<ResolvedOptions, 'eventSources' | 'metricSources'>;
|
|
24
|
+
to: Date;
|
|
25
|
+
deadline: number;
|
|
26
|
+
includePrePeriod?: boolean;
|
|
27
|
+
readAge?: boolean;
|
|
28
|
+
}): Promise<{
|
|
29
|
+
events: MetricEvent[];
|
|
30
|
+
source: undefined;
|
|
31
|
+
userKeyed: boolean;
|
|
32
|
+
kind: "binomial" | "count" | "revenue";
|
|
33
|
+
windowHours: number;
|
|
34
|
+
} | {
|
|
35
|
+
events: MetricEvent[];
|
|
36
|
+
source: import("../types/contracts.js").MetricSource;
|
|
37
|
+
userKeyed: boolean;
|
|
38
|
+
kind: "binomial" | "count" | "revenue";
|
|
39
|
+
windowHours: number;
|
|
40
|
+
}>;
|
|
41
|
+
export declare function metricUnitValues(units: ReadonlyMap<string, ExposedUnit>, definition: ResultsPhase['metricDefinitions'][number], { events, kind, windowHours }: MetricRead, to: Date, readAge?: boolean): {
|
|
42
|
+
values: Map<string, number>;
|
|
43
|
+
ages: Map<string, {
|
|
44
|
+
ts: number;
|
|
45
|
+
unitAgeMs: number;
|
|
46
|
+
}>;
|
|
47
|
+
};
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { XpAnalysisError } from '../errors.js';
|
|
2
|
+
import { identityRows, metricEventRows } from '../db/results.js';
|
|
3
|
+
import { raceDeadline } from '../db/executor.js';
|
|
4
|
+
import { DAY_MS } from '../schedule/roundTime.js';
|
|
5
|
+
import { perUnitValues, timestampMs } from './aggregate.js';
|
|
6
|
+
import { creditUserEvents, eligibleIdentityLinks } from './identityCredit.js';
|
|
7
|
+
/** Attribution uses all exposed units before an audience selects source arms. */ export async function unitValueContext(exec, unitType, units) {
|
|
8
|
+
const ids = [
|
|
9
|
+
...units.keys()
|
|
10
|
+
];
|
|
11
|
+
const identities = unitType === 'visitor' ? await identityRows(exec, {
|
|
12
|
+
anonymousIds: ids
|
|
13
|
+
}) : [];
|
|
14
|
+
const userIds = [
|
|
15
|
+
...new Set(identities.map((identity)=>identity.userId))
|
|
16
|
+
];
|
|
17
|
+
const linked = new Set(userIds);
|
|
18
|
+
const identityConflicts = new Set();
|
|
19
|
+
const userByVisitor = new Map(identities.map((identity)=>[
|
|
20
|
+
identity.anonymousId,
|
|
21
|
+
identity.userId
|
|
22
|
+
]));
|
|
23
|
+
const linksByUser = new Map();
|
|
24
|
+
for (const identity of identities){
|
|
25
|
+
const links = linksByUser.get(identity.userId) ?? [];
|
|
26
|
+
links.push(identity);
|
|
27
|
+
linksByUser.set(identity.userId, links);
|
|
28
|
+
}
|
|
29
|
+
// Last arm credited per user: enough to detect that a user's credited events span arms (a conflict).
|
|
30
|
+
const creditedArms = new Map();
|
|
31
|
+
const noteCredit = (userId, unitId)=>{
|
|
32
|
+
const arm = units.get(unitId)?.arm;
|
|
33
|
+
if (arm === undefined) return;
|
|
34
|
+
const previous = creditedArms.get(userId);
|
|
35
|
+
if (previous !== undefined && previous !== arm) identityConflicts.add(userId);
|
|
36
|
+
creditedArms.set(userId, arm);
|
|
37
|
+
};
|
|
38
|
+
const credit = (events, userKeyed)=>{
|
|
39
|
+
if (unitType === 'user') return events.map((event)=>({
|
|
40
|
+
...event,
|
|
41
|
+
unitId: event.userId ?? event.unitId
|
|
42
|
+
}));
|
|
43
|
+
// §8.3's earliest exposed linked visitor applies only when the event has no
|
|
44
|
+
// exposed unit of its own. A visitor-keyed event stays on its own exposed
|
|
45
|
+
// browser even if an earlier linked browser saw another arm or is ineligible.
|
|
46
|
+
const direct = userKeyed ? [] : events.filter((event)=>units.has(event.unitId) || event.userId == null || !linked.has(event.userId));
|
|
47
|
+
const userEvents = events.filter((event)=>userKeyed || !units.has(event.unitId) && event.userId != null && linked.has(event.userId)).map((event)=>({
|
|
48
|
+
...event,
|
|
49
|
+
userId: String(event.userId ?? event.unitId)
|
|
50
|
+
}));
|
|
51
|
+
const credited = creditUserEvents(units, identities, userEvents, (userId)=>identityConflicts.add(userId)).events;
|
|
52
|
+
for (const event of direct)if (event.userId != null && linked.has(event.userId)) {
|
|
53
|
+
noteCredit(event.userId, event.unitId);
|
|
54
|
+
// Keep the eligible-link diagnostic when direct credit bypasses the helper.
|
|
55
|
+
const arms = new Set(eligibleIdentityLinks(linksByUser.get(event.userId), event.ts).map((link)=>units.get(link.anonymousId).arm));
|
|
56
|
+
arms.add(units.get(event.unitId).arm);
|
|
57
|
+
if (arms.size > 1) identityConflicts.add(event.userId);
|
|
58
|
+
}
|
|
59
|
+
for (const event of credited)noteCredit(userByVisitor.get(event.unitId), event.unitId);
|
|
60
|
+
return [
|
|
61
|
+
...direct,
|
|
62
|
+
...credited
|
|
63
|
+
];
|
|
64
|
+
};
|
|
65
|
+
return {
|
|
66
|
+
ids,
|
|
67
|
+
identities,
|
|
68
|
+
userIds,
|
|
69
|
+
identityConflicts,
|
|
70
|
+
credit
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Shared conversion and identity attribution for results and cohort membership. */ export async function readUnitMetricEvents(exec, { phase, unitType, units, context, definition, options, to, deadline, includePrePeriod = false, readAge = false }) {
|
|
74
|
+
const { ids, userIds, credit } = context;
|
|
75
|
+
const kind = definition.kind;
|
|
76
|
+
const windowHours = phase.analysis.attributionWindowHours ?? definition.attributionWindowHours ?? 168;
|
|
77
|
+
const from = new Date([
|
|
78
|
+
...units.values()
|
|
79
|
+
].reduce((earliest, unit)=>Math.min(earliest, +unit.firstTs), timestampMs(phase.startedAt)));
|
|
80
|
+
const storedEvents = definition.source.startsWith('events:') || definition.source.startsWith('click:');
|
|
81
|
+
if (storedEvents) {
|
|
82
|
+
const eventName = definition.source.startsWith('click:') ? definition.source : definition.source.slice(7);
|
|
83
|
+
if (!definition.source.startsWith('click:') && !options.eventSources?.some((source)=>source.name === eventName)) throw new XpAnalysisError('source-unavailable');
|
|
84
|
+
const read = async (start)=>{
|
|
85
|
+
if (unitType === 'user') return metricEventRows(exec, {
|
|
86
|
+
eventName,
|
|
87
|
+
userIds: ids,
|
|
88
|
+
from: start,
|
|
89
|
+
to,
|
|
90
|
+
readAge
|
|
91
|
+
});
|
|
92
|
+
const direct = await metricEventRows(exec, {
|
|
93
|
+
eventName,
|
|
94
|
+
unitIds: ids,
|
|
95
|
+
from: start,
|
|
96
|
+
to,
|
|
97
|
+
readAge,
|
|
98
|
+
forVisitors: true
|
|
99
|
+
});
|
|
100
|
+
const signedIn = await metricEventRows(exec, {
|
|
101
|
+
eventName,
|
|
102
|
+
userIds,
|
|
103
|
+
from: start,
|
|
104
|
+
to,
|
|
105
|
+
readAge,
|
|
106
|
+
forVisitors: true
|
|
107
|
+
});
|
|
108
|
+
// The two lookups overlap when a linked user's own browser was exposed.
|
|
109
|
+
return [
|
|
110
|
+
...direct,
|
|
111
|
+
...signedIn.filter((event)=>!units.has(event.unitId))
|
|
112
|
+
];
|
|
113
|
+
};
|
|
114
|
+
const start = includePrePeriod ? new Date(+from - 14 * DAY_MS) : from;
|
|
115
|
+
return {
|
|
116
|
+
events: credit(await read(start), false),
|
|
117
|
+
source: undefined,
|
|
118
|
+
userKeyed: false,
|
|
119
|
+
kind,
|
|
120
|
+
windowHours
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const source = options.metricSources?.find((source)=>source.id === definition.source);
|
|
124
|
+
if (!source || source.kind !== kind || definition.keyedBy && source.keyedBy !== definition.keyedBy) throw new XpAnalysisError('source-unavailable');
|
|
125
|
+
const userKeyed = source.keyedBy === 'user' && unitType === 'visitor';
|
|
126
|
+
if (unitType === 'user' && source.keyedBy !== 'user') throw new XpAnalysisError('unit-type-unavailable');
|
|
127
|
+
const sourceIds = userKeyed ? userIds : ids;
|
|
128
|
+
const events = credit(await raceDeadline(deadline, ()=>source.query({
|
|
129
|
+
from,
|
|
130
|
+
to,
|
|
131
|
+
unitIds: sourceIds
|
|
132
|
+
})), userKeyed);
|
|
133
|
+
return {
|
|
134
|
+
events,
|
|
135
|
+
source,
|
|
136
|
+
userKeyed,
|
|
137
|
+
kind,
|
|
138
|
+
windowHours
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export function metricUnitValues(units, definition, { events, kind, windowHours }, to, readAge = false) {
|
|
142
|
+
if (events.some((event)=>!Number.isFinite(event.value))) throw new XpAnalysisError('non-finite-values');
|
|
143
|
+
// The click-goal delta supersedes whole-phase attribution for mid-test adds.
|
|
144
|
+
// Retain pre-period events for CUPED above; exclude them from the outcome.
|
|
145
|
+
const outcomeEvents = definition.source.startsWith('click:') && definition.addedAt ? events.filter((event)=>timestampMs(event.ts) >= timestampMs(definition.addedAt)) : events;
|
|
146
|
+
const ages = new Map();
|
|
147
|
+
const values = perUnitValues(units, outcomeEvents, {
|
|
148
|
+
kind,
|
|
149
|
+
windowHours,
|
|
150
|
+
endedAt: to,
|
|
151
|
+
onAttributed: readAge ? (event, ts)=>{
|
|
152
|
+
if (event.unitAgeMs === undefined) return;
|
|
153
|
+
const previous = ages.get(event.unitId);
|
|
154
|
+
if (!previous || ts < previous.ts || ts === previous.ts && event.unitAgeMs > previous.unitAgeMs) {
|
|
155
|
+
ages.set(event.unitId, {
|
|
156
|
+
ts,
|
|
157
|
+
unitAgeMs: event.unitAgeMs
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
} : undefined
|
|
161
|
+
});
|
|
162
|
+
return {
|
|
163
|
+
values,
|
|
164
|
+
ages
|
|
165
|
+
};
|
|
166
|
+
}
|
package/dist/runtime/assign.d.ts
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
import type { Assignments } from '../types/assignments.js';
|
|
2
2
|
import type { Attributes } from '../types/contracts.js';
|
|
3
3
|
import type { Manifest } from '../types/manifest.js';
|
|
4
|
-
import { type AssignmentUnit } from './eligibility.js';
|
|
4
|
+
import { type AssignmentUnit, type CohortState } from './eligibility.js';
|
|
5
5
|
import type { AttributeKeys } from './targeting.js';
|
|
6
6
|
/** Deferred slugs travel on the wire and are evaluated after server session resolution. */
|
|
7
7
|
export interface AssignmentResult extends Assignments {
|
|
8
8
|
deferred: string[];
|
|
9
9
|
}
|
|
10
10
|
export interface AssignOptions {
|
|
11
|
-
|
|
11
|
+
/** Numeric callers supply Unix seconds. */
|
|
12
|
+
now: Date | number;
|
|
12
13
|
staff?: boolean;
|
|
13
14
|
bot?: boolean;
|
|
14
15
|
preview?: boolean;
|
|
15
16
|
sessionUnknown?: boolean;
|
|
16
17
|
method?: string;
|
|
17
18
|
attributeKeys?: AttributeKeys;
|
|
19
|
+
cohorts?: CohortState;
|
|
20
|
+
/** Exposure validation can count a variant beacon rejected by cohort targeting. */
|
|
21
|
+
onCohortIneligible?(slug: string): void;
|
|
18
22
|
onInvalid?(slug: string, reason: string): void;
|
|
19
23
|
}
|
|
20
24
|
/** Also used after header decoding so flag results always reflect the rendered content. */
|
|
21
|
-
export declare function fillFlagPoints(result: Assignments, manifest: Manifest): void;
|
|
25
|
+
export declare function fillFlagPoints(result: Assignments, manifest: Manifest, now?: Date): void;
|
|
22
26
|
/** Pure shared assignment path; time is supplied by the request's caller. */
|
|
23
27
|
export declare function assign(manifest: Manifest, unit: AssignmentUnit, attributes: Attributes, opts: AssignOptions): AssignmentResult;
|
package/dist/runtime/assign.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { assignArm, hash, inRange, rolloutBucketRanges } from '@delmaredigital/experiments-stats';
|
|
2
|
-
import { eligibility } from './eligibility.js';
|
|
3
|
-
/** Also used after header decoding so flag results always reflect the rendered content. */ export function fillFlagPoints(result, manifest) {
|
|
2
|
+
import { eligibility, isEntryActive } from './eligibility.js';
|
|
3
|
+
/** Also used after header decoding so flag results always reflect the rendered content. */ export function fillFlagPoints(result, manifest, now = new Date()) {
|
|
4
4
|
for (const [id, value] of Object.entries(manifest.flagDefaults)){
|
|
5
5
|
result.flagPoints[id] = {
|
|
6
6
|
arm: value.winnerArm,
|
|
@@ -11,9 +11,14 @@ import { eligibility } from './eligibility.js';
|
|
|
11
11
|
exposable: false
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
|
+
const activePoints = new Set();
|
|
14
15
|
for (const experiment of manifest.experiments){
|
|
15
16
|
const assignment = result.bySlug[experiment.slug];
|
|
16
17
|
if (!experiment.flagPoint || !assignment) continue;
|
|
18
|
+
// Non-overlapping schedules can share a point. Only the active test can
|
|
19
|
+
// override another test's control fallback.
|
|
20
|
+
if (isEntryActive(experiment, now)) activePoints.add(experiment.flagPoint);
|
|
21
|
+
else if (activePoints.has(experiment.flagPoint)) continue;
|
|
17
22
|
const contentArm = experiment.arms.find((arm)=>arm.key === assignment.arm && arm.kind !== 'holdout') ?? experiment.arms.find((arm)=>arm.kind === 'control');
|
|
18
23
|
result.flagPoints[experiment.flagPoint] = {
|
|
19
24
|
arm: assignment.arm,
|
|
@@ -30,6 +35,7 @@ import { eligibility } from './eligibility.js';
|
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
37
|
/** Pure shared assignment path; time is supplied by the request's caller. */ export function assign(manifest, unit, attributes, opts) {
|
|
38
|
+
const now = typeof opts.now === 'number' ? new Date(opts.now * 1000) : opts.now;
|
|
33
39
|
const result = {
|
|
34
40
|
revision: manifest.revision,
|
|
35
41
|
visitorId: unit.visitorId,
|
|
@@ -58,12 +64,14 @@ import { eligibility } from './eligibility.js';
|
|
|
58
64
|
}
|
|
59
65
|
const eligible = eligibility(experiment, unit, attributes, {
|
|
60
66
|
...opts,
|
|
67
|
+
now,
|
|
61
68
|
sessionUnknown: result.sessionUnknown
|
|
62
69
|
});
|
|
63
70
|
if (eligible.kind === 'deferred') {
|
|
64
71
|
result.deferred.push(experiment.slug);
|
|
65
72
|
continue;
|
|
66
73
|
}
|
|
74
|
+
if (eligible.kind === 'cohort-ineligible') opts.onCohortIneligible?.(experiment.slug);
|
|
67
75
|
const control = experiment.arms.find((arm)=>arm.kind === 'control');
|
|
68
76
|
let arm = control.key, exposable = false;
|
|
69
77
|
if (eligible.kind === 'eligible') {
|
|
@@ -96,9 +104,9 @@ import { eligibility } from './eligibility.js';
|
|
|
96
104
|
phase: experiment.phase,
|
|
97
105
|
exposable: exposable && !result.staff && !result.bot && !result.preview && result.method.toUpperCase() !== 'HEAD',
|
|
98
106
|
policy: experiment.exposurePolicy,
|
|
99
|
-
source: eligible.kind === '
|
|
107
|
+
source: eligible.kind === 'eligible' ? 'recomputed' : 'fallback'
|
|
100
108
|
};
|
|
101
109
|
}
|
|
102
|
-
fillFlagPoints(result, manifest);
|
|
110
|
+
fillFlagPoints(result, manifest, now);
|
|
103
111
|
return result;
|
|
104
112
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Manifest } from '../types/manifest.js';
|
|
2
|
+
import type { AssignmentUnit, CohortState } from './eligibility.js';
|
|
3
|
+
export declare const cohortCookieMaxAgeMs = 86400000;
|
|
4
|
+
type Identity = Pick<AssignmentUnit, 'visitorId' | 'userId'>;
|
|
5
|
+
type CohortCookie = {
|
|
6
|
+
issuedAtMs: number;
|
|
7
|
+
entries: Map<string, boolean>;
|
|
8
|
+
};
|
|
9
|
+
export declare function readCohortCookie(value: string | undefined, identity: Identity, secrets: readonly string[], nowMs: number): CohortCookie | null;
|
|
10
|
+
export declare function closedCohortKeys(manifest: Manifest, nowMs: number): Set<string>;
|
|
11
|
+
export declare function updateCohortCookie(current: CohortCookie | null, answered: CohortState, closed: ReadonlySet<string>, identity: Identity, secrets: readonly string[], nowMs: number): {
|
|
12
|
+
value: string;
|
|
13
|
+
maxAge: number;
|
|
14
|
+
} | undefined;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { DAY_MS } from './cookieOptions.js';
|
|
2
|
+
import { sign, verify } from './signing.js';
|
|
3
|
+
export const cohortCookieMaxAgeMs = DAY_MS;
|
|
4
|
+
const MAX_BYTES = 1024;
|
|
5
|
+
const ENTRY = /^([a-zA-Z0-9_-]+):([01])$/;
|
|
6
|
+
const message = ({ visitorId, userId }, issuedAtMs, entries)=>'xp:cohort:' + [
|
|
7
|
+
'v1',
|
|
8
|
+
visitorId ?? '',
|
|
9
|
+
userId ?? '',
|
|
10
|
+
issuedAtMs,
|
|
11
|
+
entries
|
|
12
|
+
].join('|');
|
|
13
|
+
export function readCohortCookie(value, identity, secrets, nowMs) {
|
|
14
|
+
if (!value || Buffer.byteLength(value) > MAX_BYTES) return null;
|
|
15
|
+
const match = /^v1\.(0|[1-9][0-9]{0,15})\.([A-Za-z0-9_:,-]+)\.([A-Za-z0-9_-]{43})$/.exec(value);
|
|
16
|
+
if (!match || encodeURIComponent(value).length > MAX_BYTES) return null;
|
|
17
|
+
const issuedAtMs = Number(match[1]), encoded = match[2];
|
|
18
|
+
const age = nowMs - issuedAtMs;
|
|
19
|
+
if (!Number.isSafeInteger(issuedAtMs) || !(age >= 0 && age < cohortCookieMaxAgeMs) || !verify(message(identity, issuedAtMs, encoded), match[3], secrets)) return null;
|
|
20
|
+
const entries = new Map();
|
|
21
|
+
for (const entry of encoded.split(',')){
|
|
22
|
+
const parsed = ENTRY.exec(entry);
|
|
23
|
+
if (!parsed || entries.has(parsed[1])) return null;
|
|
24
|
+
entries.set(parsed[1], parsed[2] === '1');
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
issuedAtMs,
|
|
28
|
+
entries
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function closedCohortKeys(manifest, nowMs) {
|
|
32
|
+
const closed = new Set(), open = new Set();
|
|
33
|
+
for (const entry of manifest.experiments){
|
|
34
|
+
for (const { key, sourceClosedAt } of entry.cohorts ?? []){
|
|
35
|
+
if (sourceClosedAt !== null && Date.parse(sourceClosedAt) <= nowMs) closed.add(key);
|
|
36
|
+
else open.add(key);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// Multiple tests can reference a key. Cache only when every reference agrees it is closed.
|
|
40
|
+
for (const key of open)closed.delete(key);
|
|
41
|
+
return closed;
|
|
42
|
+
}
|
|
43
|
+
export function updateCohortCookie(current, answered, closed, identity, secrets, nowMs) {
|
|
44
|
+
const entries = new Map([
|
|
45
|
+
...answered
|
|
46
|
+
].filter(([key])=>closed.has(key)));
|
|
47
|
+
if (!entries.size) return undefined;
|
|
48
|
+
const issuedAtMs = current?.issuedAtMs ?? nowMs;
|
|
49
|
+
const maxAge = Math.floor((cohortCookieMaxAgeMs - (nowMs - issuedAtMs)) / 1000);
|
|
50
|
+
if (maxAge <= 0) return undefined;
|
|
51
|
+
for (const [key, member] of current?.entries ?? []){
|
|
52
|
+
if (closed.has(key) && !entries.has(key)) entries.set(key, member);
|
|
53
|
+
}
|
|
54
|
+
const prefix = `v1.${issuedAtMs}.`;
|
|
55
|
+
let size = prefix.length + 44 // Dot and 43-character MAC.
|
|
56
|
+
;
|
|
57
|
+
const encoded = [];
|
|
58
|
+
for (const [key, member] of entries){
|
|
59
|
+
const entry = `${key}:${member ? 1 : 0}`;
|
|
60
|
+
if (!ENTRY.test(entry)) continue;
|
|
61
|
+
// Next percent-encodes both the entry's colon and the comma separator.
|
|
62
|
+
size += encodeURIComponent(entry).length + (encoded.length ? 3 : 0);
|
|
63
|
+
if (size > MAX_BYTES) break;
|
|
64
|
+
encoded.push(entry);
|
|
65
|
+
}
|
|
66
|
+
if (!encoded.length) return undefined;
|
|
67
|
+
const body = encoded.join(',');
|
|
68
|
+
return {
|
|
69
|
+
value: `${prefix}${body}.${sign(message(identity, issuedAtMs, body), secrets)}`,
|
|
70
|
+
maxAge
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Pool } from 'pg';
|
|
2
|
+
import type { CohortLookupArgs } from '../db/cohortMembership.js';
|
|
3
|
+
export type CohortLookup = (args: CohortLookupArgs) => Promise<Set<string>>;
|
|
4
|
+
export declare function createPostgresCohortLookup({ pool, schemaName }: {
|
|
5
|
+
pool: Pool;
|
|
6
|
+
schemaName?: string;
|
|
7
|
+
}): CohortLookup;
|
|
8
|
+
/** Bound host-supplied adapters too. Missing and failed lookups leave all requested keys unknown. */
|
|
9
|
+
export declare function resolveCohorts(lookup: CohortLookup | undefined, args: CohortLookupArgs): Promise<Map<string, boolean> | undefined>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { COHORT_LOOKUP_TIMEOUT_MS, lookupPooledCohorts } from '../db/cohortPool.js';
|
|
2
|
+
export function createPostgresCohortLookup({ pool, schemaName }) {
|
|
3
|
+
return (args)=>lookupPooledCohorts(pool, schemaName, args);
|
|
4
|
+
}
|
|
5
|
+
/** Bound host-supplied adapters too. Missing and failed lookups leave all requested keys unknown. */ export async function resolveCohorts(lookup, args) {
|
|
6
|
+
if (!lookup || !args.keys.length) return undefined;
|
|
7
|
+
let timer;
|
|
8
|
+
try {
|
|
9
|
+
const deadline = new Promise((_, reject)=>{
|
|
10
|
+
timer = setTimeout(()=>reject(new Error('Cohort lookup timed out')), COHORT_LOOKUP_TIMEOUT_MS);
|
|
11
|
+
});
|
|
12
|
+
const members = await Promise.race([
|
|
13
|
+
Promise.resolve().then(()=>lookup(args)),
|
|
14
|
+
deadline
|
|
15
|
+
]);
|
|
16
|
+
return new Map(args.keys.map((key)=>[
|
|
17
|
+
key,
|
|
18
|
+
members.has(key)
|
|
19
|
+
]));
|
|
20
|
+
} catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
} finally{
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
import type { Attributes } from '../types/contracts.js';
|
|
2
|
-
import type { ManifestExperiment } from '../types/manifest.js';
|
|
2
|
+
import type { Manifest, ManifestExperiment } from '../types/manifest.js';
|
|
3
3
|
import { type AttributeKeys } from './targeting.js';
|
|
4
4
|
export interface AssignmentUnit {
|
|
5
5
|
visitorId?: string;
|
|
6
6
|
userId?: string;
|
|
7
7
|
sessionUnknown?: boolean;
|
|
8
8
|
}
|
|
9
|
+
export type CohortState = ReadonlyMap<string, boolean>;
|
|
9
10
|
export type Eligibility = {
|
|
10
|
-
kind: 'deferred';
|
|
11
|
-
} | {
|
|
12
|
-
kind: 'ineligible';
|
|
11
|
+
kind: 'deferred' | 'ineligible' | 'cohort-ineligible';
|
|
13
12
|
} | {
|
|
14
13
|
kind: 'eligible';
|
|
15
14
|
unitId: string;
|
|
16
15
|
inLayer: boolean;
|
|
17
16
|
coverage: number;
|
|
18
17
|
};
|
|
19
|
-
|
|
18
|
+
type EligibilityOptions = {
|
|
19
|
+
now: Date;
|
|
20
20
|
sessionUnknown?: boolean;
|
|
21
21
|
attributeKeys?: AttributeKeys;
|
|
22
|
+
};
|
|
23
|
+
export declare function isEntryActive(entry: ManifestExperiment, now: Date): boolean;
|
|
24
|
+
export declare function cohortKeysToResolve(manifest: Manifest, unit: AssignmentUnit, attributes: Attributes, opts: EligibilityOptions): string[];
|
|
25
|
+
export declare function eligibility(experiment: ManifestExperiment, unit: AssignmentUnit, attributes: Attributes, opts: EligibilityOptions & {
|
|
26
|
+
cohorts?: CohortState;
|
|
22
27
|
}): Eligibility;
|
|
28
|
+
export {};
|
|
@@ -1,15 +1,41 @@
|
|
|
1
1
|
import { layerSlice } from '@delmaredigital/experiments-stats';
|
|
2
|
+
import { isActive } from '../schedule/activeTime.js';
|
|
2
3
|
import { evaluateTargeting } from './targeting.js';
|
|
3
|
-
export function
|
|
4
|
+
export function isEntryActive(entry, now) {
|
|
5
|
+
if (entry.resumedAt && !(Date.parse(entry.resumedAt) <= now.getTime())) return false;
|
|
6
|
+
if (!entry.active) return true;
|
|
7
|
+
try {
|
|
8
|
+
return isActive(entry.active, [], now);
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function eligibleUnit(experiment, unit, attributes, opts) {
|
|
14
|
+
if (!isEntryActive(experiment, opts.now)) return false;
|
|
4
15
|
const unitId = experiment.unitType === 'visitor' ? unit.visitorId : unit.userId;
|
|
16
|
+
if (!unitId) return experiment.unitType === 'user' ? undefined : false;
|
|
17
|
+
if ((opts.sessionUnknown ?? unit.sessionUnknown) && (experiment.cohorts?.length || experiment.targeting.some((rule)=>rule.attribute === 'loggedIn' || rule.attribute === 'staff'))) return undefined;
|
|
18
|
+
return evaluateTargeting(experiment.targeting, attributes, opts.attributeKeys) ? unitId : false;
|
|
19
|
+
}
|
|
20
|
+
export function cohortKeysToResolve(manifest, unit, attributes, opts) {
|
|
21
|
+
let keys;
|
|
22
|
+
for (const entry of manifest.experiments){
|
|
23
|
+
if (!entry.cohorts?.length || entry.status !== 'running' && entry.status !== 'decided') continue;
|
|
24
|
+
if (!eligibleUnit(entry, unit, attributes, opts)) continue;
|
|
25
|
+
keys ??= new Set();
|
|
26
|
+
for (const rule of entry.cohorts)keys.add(rule.key);
|
|
27
|
+
}
|
|
28
|
+
return keys ? [
|
|
29
|
+
...keys
|
|
30
|
+
].sort() : [];
|
|
31
|
+
}
|
|
32
|
+
export function eligibility(experiment, unit, attributes, opts) {
|
|
33
|
+
const unitId = eligibleUnit(experiment, unit, attributes, opts);
|
|
5
34
|
if (!unitId) return {
|
|
6
|
-
kind:
|
|
7
|
-
};
|
|
8
|
-
if ((opts.sessionUnknown ?? unit.sessionUnknown) && experiment.targeting.some((rule)=>rule.attribute === 'loggedIn' || rule.attribute === 'staff')) return {
|
|
9
|
-
kind: 'deferred'
|
|
35
|
+
kind: unitId === undefined ? 'deferred' : 'ineligible'
|
|
10
36
|
};
|
|
11
|
-
if (
|
|
12
|
-
kind: 'ineligible'
|
|
37
|
+
if (experiment.cohorts?.some((rule)=>opts.cohorts?.get(rule.key) !== rule.include)) return {
|
|
38
|
+
kind: 'cohort-ineligible'
|
|
13
39
|
};
|
|
14
40
|
return {
|
|
15
41
|
kind: 'eligible',
|
package/dist/runtime/header.d.ts
CHANGED
package/dist/runtime/header.js
CHANGED
|
@@ -12,6 +12,9 @@ export function defineExperimentsProxyRuntime(opts) {
|
|
|
12
12
|
] : opts.secret;
|
|
13
13
|
assertSigningSecrets(secrets);
|
|
14
14
|
assertUnitRateLimit(opts.rateLimitUnit);
|
|
15
|
+
if (opts.lookupCohorts !== undefined && typeof opts.lookupCohorts !== 'function') {
|
|
16
|
+
throw new Error('Experiments requires lookupCohorts to be a function when configured.');
|
|
17
|
+
}
|
|
15
18
|
const maxAgeDays = opts.cookie?.maxAgeDays;
|
|
16
19
|
const cookie = Object.freeze({
|
|
17
20
|
...opts.cookie,
|
|
@@ -27,6 +30,7 @@ export function defineExperimentsProxyRuntime(opts) {
|
|
|
27
30
|
cookie,
|
|
28
31
|
loadManifest: opts.loadManifest,
|
|
29
32
|
getUnit: opts.getUnit,
|
|
30
|
-
rateLimitUnit: opts.rateLimitUnit
|
|
33
|
+
rateLimitUnit: opts.rateLimitUnit,
|
|
34
|
+
lookupCohorts: opts.lookupCohorts
|
|
31
35
|
});
|
|
32
36
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { type FrozenCohortRule } from '../cohorts/rule.js';
|
|
1
2
|
import type { Attributes, ExperimentsPluginOptions, TargetingRule } from '../types/contracts.js';
|
|
2
3
|
export type AttributeKeys = NonNullable<ExperimentsPluginOptions['attributeKeys']>;
|
|
3
4
|
/** Frozen manifest types take precedence; declarations still support draft rules. */
|
|
4
|
-
export declare function evaluateTargeting(rules: readonly (TargetingRule & {
|
|
5
|
+
export declare function evaluateTargeting(rules: readonly ((TargetingRule & {
|
|
5
6
|
type?: 'string' | 'number' | 'boolean';
|
|
6
|
-
})[], attributes: Attributes, attributeKeys?: AttributeKeys): boolean;
|
|
7
|
+
}) | FrozenCohortRule)[], attributes: Attributes, attributeKeys?: AttributeKeys): boolean;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { isCohortRule } from '../cohorts/rule.js';
|
|
1
2
|
import { evaluateOp } from '../targeting/ops.js';
|
|
2
3
|
/** Frozen manifest types take precedence; declarations still support draft rules. */ export function evaluateTargeting(rules, attributes, attributeKeys) {
|
|
3
4
|
return rules.every((rule)=>{
|
|
4
|
-
if (!Object.hasOwn(attributes, rule.attribute)) return false;
|
|
5
|
+
if (isCohortRule(rule) || !Object.hasOwn(attributes, rule.attribute)) return false;
|
|
5
6
|
if (rule.type === undefined && attributeKeys && !Object.hasOwn(attributeKeys, rule.attribute)) return false;
|
|
6
7
|
const type = rule.type ?? attributeKeys?.[rule.attribute]?.type ?? (Array.isArray(rule.value) ? 'string' : typeof rule.value);
|
|
7
8
|
return evaluateOp(type, rule.op, attributes[rule.attribute], rule.value);
|