@delmaredigital/payload-experiments 0.4.0-rc.6 → 0.4.0-rc.9
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 +12 -12
- package/dist/admin/blocks/BlockPanel.js +6 -4
- package/dist/admin/blocks/inject.js +1 -0
- package/dist/admin/blocks/model.d.ts +3 -2
- package/dist/admin/blocks/model.js +9 -5
- package/dist/admin/copy/blocks.d.ts +3 -2
- package/dist/admin/copy/blocks.js +8 -7
- package/dist/admin/surface/ResultsRoute.js +18 -11
- package/dist/admin/surface/TestsHome.d.ts +2 -1
- package/dist/admin/surface/TestsHome.js +131 -44
- package/dist/admin/surface/TestsSurface.js +3 -0
- package/dist/admin/surface/home.model.d.ts +2 -0
- package/dist/admin/surface/newTest/PageWizard.js +9 -2
- package/dist/admin/surface/newTest/newTest.css +1 -1
- package/dist/admin/surface/results/ResultsHeader.js +11 -6
- package/dist/admin/surface/test/TestPage.js +3 -3
- package/dist/admin/views/TestsSurfaceClient.d.ts +3 -0
- package/dist/admin/views/TestsSurfaceClient.js +11 -0
- package/dist/admin/views/buildSurfaceProps.js +10 -3
- package/dist/blocks/bindings.js +3 -2
- package/dist/blocks/formState.js +1 -1
- package/dist/blocks/placementLanguages.d.ts +7 -0
- package/dist/blocks/placementLanguages.js +27 -0
- package/dist/blocks/placementLocale.d.ts +21 -7
- package/dist/blocks/placementLocale.js +218 -67
- package/dist/collections/experiments/config.js +8 -3
- package/dist/collections/experiments/deleteGuard.js +2 -2
- package/dist/collections/experiments/lockHook.js +21 -2
- package/dist/collections/experiments/pickSlug.js +2 -0
- package/dist/collections/metricsGuards.js +2 -0
- package/dist/collections/serialize.js +5 -4
- package/dist/constants.d.ts +1 -0
- package/dist/constants.js +1 -0
- package/dist/db/adapter.d.ts +9 -1
- package/dist/db/adapter.js +77 -1
- package/dist/db/appends.d.ts +13 -0
- package/dist/db/appends.js +49 -0
- package/dist/db/bulkPlacementRemoval.js +8 -4
- package/dist/db/delete.d.ts +1 -1
- package/dist/db/delete.js +2 -4
- package/dist/db/events.d.ts +9 -0
- package/dist/db/events.js +42 -8
- package/dist/db/executor.d.ts +7 -1
- package/dist/db/executor.js +7 -3
- package/dist/db/results.d.ts +5 -1
- package/dist/db/results.js +21 -5
- package/dist/db/snapshots.d.ts +1 -0
- package/dist/endpoints/contentLocale.d.ts +6 -0
- package/dist/endpoints/contentLocale.js +15 -0
- package/dist/endpoints/deleteImpact.d.ts +6 -0
- package/dist/endpoints/deleteImpact.js +207 -0
- package/dist/endpoints/events.js +103 -39
- package/dist/endpoints/index.js +9 -8
- package/dist/endpoints/pages.js +7 -3
- package/dist/endpoints/placementStatus.js +13 -5
- package/dist/endpoints/preflight.d.ts +1 -1
- package/dist/endpoints/preflight.js +17 -2
- package/dist/endpoints/results.d.ts +1 -1
- package/dist/endpoints/results.js +6 -2
- package/dist/endpoints/routeId.d.ts +2 -2
- package/dist/endpoints/routeId.js +11 -5
- package/dist/endpoints/summary.js +46 -12
- package/dist/endpoints/transitions.js +37 -24
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +6 -0
- package/dist/events/request.d.ts +6 -2
- package/dist/events/request.js +35 -8
- package/dist/events/rows.d.ts +1 -1
- package/dist/events/rows.js +24 -8
- package/dist/events/writable.d.ts +9 -0
- package/dist/events/writable.js +13 -0
- package/dist/exports/adminClient.d.ts +1 -1
- package/dist/exports/adminClient.js +1 -1
- package/dist/exports/index.d.ts +1 -1
- package/dist/exports/rsc.d.ts +1 -0
- package/dist/exports/rsc.js +1 -0
- package/dist/goals/fairness.js +38 -31
- package/dist/hooks/blockRemovalRule.d.ts +2 -2
- package/dist/hooks/blockRemovalRule.js +16 -14
- package/dist/hooks/hostHook.js +6 -2
- package/dist/hooks/pageGuard.d.ts +3 -0
- package/dist/hooks/pageGuard.js +37 -23
- package/dist/hooks/puckNestedTests.d.ts +8 -0
- package/dist/hooks/puckNestedTests.js +36 -0
- package/dist/lib/fetchAllDocs.d.ts +1 -1
- package/dist/lib/placementPages.d.ts +2 -1
- package/dist/lib/placementPages.js +10 -2
- package/dist/manifest/compile.d.ts +2 -1
- package/dist/manifest/compile.js +13 -6
- package/dist/onInit.js +14 -0
- package/dist/options.js +5 -0
- package/dist/proxy/pageNavigation.d.ts +4 -0
- package/dist/proxy/pageNavigation.js +28 -0
- package/dist/proxy/resolve.js +52 -25
- package/dist/puck/ExperimentPicker.js +40 -37
- package/dist/puck/editor/ConfigureTestDrawer.d.ts +8 -4
- package/dist/puck/editor/ConfigureTestDrawer.js +5 -2
- package/dist/puck/editor/ExperimentSlotEditor.js +313 -158
- package/dist/puck/editor/LeftoverVersions.d.ts +1 -1
- package/dist/puck/editor/LeftoverVersions.js +40 -43
- package/dist/puck/editor/QuickTestActions.d.ts +5 -2
- package/dist/puck/editor/QuickTestActions.js +16 -4
- package/dist/puck/editor/ResultsReadout.d.ts +2 -1
- package/dist/puck/editor/ResultsReadout.js +2 -1
- package/dist/puck/editor/VersionBuilder.d.ts +31 -3
- package/dist/puck/editor/VersionBuilder.js +336 -74
- package/dist/puck/editor/armWrites.js +1 -1
- package/dist/puck/editor/armsCache.js +1 -3
- package/dist/puck/editor/blockClipboard.d.ts +16 -0
- package/dist/puck/editor/blockClipboard.js +20 -0
- package/dist/puck/editor/copy.d.ts +12 -2
- package/dist/puck/editor/copy.js +13 -2
- package/dist/puck/editor/editor.chrome.css +118 -3
- package/dist/puck/editor/editor.css +131 -8
- package/dist/puck/editor/editor.model.d.ts +3 -1
- package/dist/puck/editor/editor.model.js +2 -2
- package/dist/puck/editor/localPlacements.d.ts +1 -0
- package/dist/puck/editor/localPlacements.js +12 -0
- package/dist/puck/editor/placementsCache.d.ts +22 -12
- package/dist/puck/editor/placementsCache.js +62 -49
- package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
- package/dist/puck/editor/usePageSaveReadiness.js +34 -0
- package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
- package/dist/puck/editor/usePlacementNotice.js +6 -4
- package/dist/puck/experimentSlug.d.ts +2 -0
- package/dist/puck/experimentSlug.js +3 -0
- package/dist/puck/nestedTestCopy.d.ts +8 -0
- package/dist/puck/nestedTestCopy.js +22 -0
- package/dist/puck/nestedTests.d.ts +17 -0
- package/dist/puck/nestedTests.js +30 -0
- package/dist/puck/slotConfig.d.ts +1 -1
- package/dist/puck/slotConfig.js +17 -4
- package/dist/puck/visibility.d.ts +2 -3
- package/dist/puck/visibility.js +11 -7
- package/dist/results/aggregate.d.ts +6 -3
- package/dist/results/aggregate.js +9 -9
- package/dist/results/health.d.ts +8 -0
- package/dist/results/health.js +28 -0
- package/dist/results/identityCredit.d.ts +1 -0
- package/dist/results/identityCredit.js +4 -1
- package/dist/results/verdict.js +2 -1
- package/dist/runtime/cookie.d.ts +10 -2
- package/dist/runtime/cookie.js +38 -6
- package/dist/runtime/cookieOptions.d.ts +6 -0
- package/dist/runtime/cookieOptions.js +14 -0
- package/dist/runtime/proxyRuntime.d.ts +1 -0
- package/dist/runtime/proxyRuntime.js +18 -8
- package/dist/runtime/signing.d.ts +1 -0
- package/dist/runtime/signing.js +5 -0
- package/dist/sanitizeReadinessDetail.d.ts +2 -2
- package/dist/sanitizeReadinessDetail.js +20 -2
- package/dist/server/getAssignments.js +11 -10
- package/dist/server/recordContentChange.d.ts +1 -1
- package/dist/server/recordContentChange.js +45 -21
- package/dist/server/resolveExperimentBlocks.js +2 -4
- package/dist/server/resolveExperimentData.js +4 -7
- package/dist/server/runResults.js +52 -14
- package/dist/server/startExperiment.d.ts +20 -0
- package/dist/server/startExperiment.js +70 -0
- package/dist/server/trackConversion.js +10 -13
- package/dist/testSurface/PreviewLinks.js +6 -2
- package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
- package/dist/testSurface/actions/DecideDialog.js +32 -14
- package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
- package/dist/testSurface/actions/MakeContentResult.js +9 -1
- package/dist/testSurface/api.d.ts +11 -8
- package/dist/testSurface/api.js +27 -11
- package/dist/testSurface/contentLocaleURL.d.ts +2 -0
- package/dist/testSurface/contentLocaleURL.js +3 -0
- package/dist/testSurface/copy/actions.d.ts +1 -0
- package/dist/testSurface/copy/actions.js +1 -0
- package/dist/testSurface/copy/common.d.ts +6 -0
- package/dist/testSurface/copy/common.js +11 -5
- package/dist/testSurface/copy/languages.d.ts +12 -0
- package/dist/testSurface/copy/languages.js +8 -0
- package/dist/testSurface/copy/metrics.d.ts +1 -0
- package/dist/testSurface/copy/metrics.js +1 -0
- package/dist/testSurface/copy/readiness.d.ts +13 -2
- package/dist/testSurface/copy/readiness.js +19 -2
- package/dist/testSurface/copy/results.d.ts +5 -2
- package/dist/testSurface/copy/results.js +5 -2
- package/dist/testSurface/copy/testPage.d.ts +40 -1
- package/dist/testSurface/copy/testPage.js +53 -1
- package/dist/testSurface/placementLabel.d.ts +8 -0
- package/dist/testSurface/placementLabel.js +24 -0
- package/dist/testSurface/placements/placementLabels.d.ts +2 -0
- package/dist/testSurface/placements/placementLabels.js +2 -1
- package/dist/testSurface/readPreflight.d.ts +5 -0
- package/dist/testSurface/readPreflight.js +7 -0
- package/dist/testSurface/readinessRead.d.ts +3 -0
- package/dist/testSurface/readinessRead.js +4 -0
- package/dist/testSurface/results/VerdictHero.d.ts +2 -1
- package/dist/testSurface/results/VerdictHero.js +5 -1
- package/dist/testSurface/results/results.css +1 -1
- package/dist/testSurface/results/results.model.d.ts +1 -1
- package/dist/testSurface/results/results.model.js +6 -2
- package/dist/testSurface/surface/contracts.d.ts +10 -1
- package/dist/testSurface/surface/editorPlacement.d.ts +7 -2
- package/dist/testSurface/surface/editorPlacement.js +19 -1
- package/dist/testSurface/surface/pageBlock/pageBlock.model.js +4 -3
- package/dist/testSurface/surface/pageBlock/parts.js +24 -6
- package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
- package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
- package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
- package/dist/testSurface/surface/readiness/Banner.js +23 -12
- package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
- package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
- package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
- package/dist/testSurface/surface/readiness/readiness.model.js +116 -12
- package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
- package/dist/testSurface/surface/readiness/useTransition.js +12 -10
- package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
- package/dist/testSurface/surface/results/ReleasePages.js +5 -4
- package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
- package/dist/testSurface/surface/results/ResultsBody.js +86 -43
- package/dist/testSurface/surface/results/useResults.d.ts +11 -7
- package/dist/testSurface/surface/results/useResults.js +3 -2
- package/dist/testSurface/surface/setting/parts.js +58 -18
- package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
- package/dist/testSurface/surface/test/DeleteTest.d.ts +19 -0
- package/dist/testSurface/surface/test/DeleteTest.js +262 -0
- package/dist/testSurface/surface/test/GoalSection.js +7 -3
- package/dist/testSurface/surface/test/LengthSection.js +3 -0
- package/dist/testSurface/surface/test/PageHoldout.js +4 -1
- package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
- package/dist/testSurface/surface/test/TargetingSection.js +77 -12
- package/dist/testSurface/surface/test/TestSurface.js +97 -15
- package/dist/testSurface/surface/test/VersionsSection.js +56 -29
- package/dist/testSurface/surface/test/fields.d.ts +29 -4
- package/dist/testSurface/surface/test/fields.js +159 -39
- package/dist/testSurface/surface/test/pageParts.js +14 -5
- package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
- package/dist/testSurface/surface/test/testPage.model.js +6 -0
- package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
- package/dist/testSurface/surface/testDocument.model.js +4 -1
- package/dist/testSurface/surface/useTestDocument.d.ts +23 -4
- package/dist/testSurface/surface/useTestDocument.js +425 -162
- package/dist/testSurface/useApi.d.ts +9 -6
- package/dist/testSurface/useOnTestReturn.d.ts +2 -0
- package/dist/testSurface/useOnTestReturn.js +27 -0
- package/dist/testSurface/useReadinessPolling.js +3 -1
- package/dist/transitions/addMetric.d.ts +1 -4
- package/dist/transitions/allocate.d.ts +2 -2
- package/dist/transitions/allocate.js +3 -1
- package/dist/transitions/archive.d.ts +1 -1
- package/dist/transitions/archive.js +3 -2
- package/dist/transitions/checkStart.d.ts +5 -1
- package/dist/transitions/checkStart.js +130 -16
- package/dist/transitions/contentFields.js +9 -5
- package/dist/transitions/decide.d.ts +1 -1
- package/dist/transitions/decide.js +5 -3
- package/dist/transitions/deleteExperiment.d.ts +2 -2
- package/dist/transitions/deleteExperiment.js +17 -7
- package/dist/transitions/kernel.d.ts +2 -0
- package/dist/transitions/kernel.js +9 -4
- package/dist/transitions/makeContent.d.ts +2 -1
- package/dist/transitions/makeContent.js +17 -12
- package/dist/transitions/nestedPlacementNames.d.ts +5 -0
- package/dist/transitions/nestedPlacementNames.js +32 -0
- package/dist/transitions/pageVersions.js +3 -1
- package/dist/transitions/phaseRecord.d.ts +2 -0
- package/dist/transitions/phaseRecord.js +5 -0
- package/dist/transitions/placementInteractions.d.ts +3 -3
- package/dist/transitions/placementInteractions.js +15 -11
- package/dist/transitions/placements.d.ts +28 -1
- package/dist/transitions/placements.js +223 -60
- package/dist/transitions/preflightData.d.ts +5 -3
- package/dist/transitions/preflightData.js +126 -37
- package/dist/transitions/releaseHoldout.d.ts +2 -1
- package/dist/transitions/releaseHoldout.js +3 -1
- package/dist/transitions/releasePages.d.ts +2 -1
- package/dist/transitions/releasePages.js +3 -1
- package/dist/transitions/resolveCaps.d.ts +2 -4
- package/dist/transitions/start.d.ts +6 -8
- package/dist/transitions/start.js +70 -34
- package/dist/transitions/startReads.d.ts +7 -0
- package/dist/transitions/startReads.js +28 -0
- package/dist/transitions/stop.d.ts +2 -1
- package/dist/transitions/stop.js +3 -2
- package/dist/types/contracts.d.ts +6 -3
- package/dist/types/endpoints.d.ts +86 -9
- package/dist/types/endpoints.js +1 -1
- package/dist/types/runtime.d.ts +15 -9
- package/dist/types/snapshot.d.ts +2 -0
- package/dist/types/surface.d.ts +2 -0
- package/dist/ui/Button.js +2 -2
- package/dist/ui/ChipsInput.d.ts +8 -1
- package/dist/ui/ChipsInput.js +17 -4
- package/dist/ui/Inputs.d.ts +4 -3
- package/dist/ui/Inputs.js +9 -9
- package/dist/ui/SelectControl.d.ts +33 -0
- package/dist/ui/SelectControl.js +504 -0
- package/dist/ui/ui.css +13 -5
- package/package.json +3 -2
|
@@ -44,16 +44,21 @@ export function experimentsCollection(options) {
|
|
|
44
44
|
},
|
|
45
45
|
access: {
|
|
46
46
|
...managedAccess(options),
|
|
47
|
-
delete: async ({ req })=>
|
|
47
|
+
delete: async ({ req, id })=>{
|
|
48
|
+
if (await options.access.manage({
|
|
48
49
|
req
|
|
49
|
-
})
|
|
50
|
+
}) !== true) return false;
|
|
51
|
+
// Single deletes report status through the locked beforeDelete guard.
|
|
52
|
+
// Payload catches per-document hook failures in bulk deletes, so keep their status filter in access.
|
|
53
|
+
return id != null ? true : {
|
|
50
54
|
status: {
|
|
51
55
|
in: [
|
|
52
56
|
'draft',
|
|
53
57
|
'archived'
|
|
54
58
|
]
|
|
55
59
|
}
|
|
56
|
-
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
57
62
|
},
|
|
58
63
|
admin: {
|
|
59
64
|
group: SURFACE_COPY.title,
|
|
@@ -3,8 +3,8 @@ import { xpOptionsFromReq } from '../../options/fromReq.js';
|
|
|
3
3
|
export const deleteGuard = async ({ req, id })=>{
|
|
4
4
|
await deleteExperiment(req, id);
|
|
5
5
|
};
|
|
6
|
-
export const deleteGuardAfter = async ({ req,
|
|
7
|
-
await deleteExperimentAfter(req
|
|
6
|
+
export const deleteGuardAfter = async ({ req, doc })=>{
|
|
7
|
+
await deleteExperimentAfter(req);
|
|
8
8
|
return doc;
|
|
9
9
|
};
|
|
10
10
|
export const deleteGuardBeforeOperation = async ({ operation, args, req })=>{
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withSlotsFor } from '../../arms/model.js';
|
|
1
2
|
import { XpLockedFieldError, XpRefusal } from '../../errors.js';
|
|
2
3
|
import { XP_IF_UPDATED_AT_HEADER } from '../../constants.js';
|
|
3
4
|
import { txExecutor } from '../../db/executor.js';
|
|
@@ -64,6 +65,24 @@ const dates = new Set([
|
|
|
64
65
|
}
|
|
65
66
|
const same = (a, b, path)=>JSON.stringify(normalize(a, path)) === JSON.stringify(normalize(b, path));
|
|
66
67
|
export const lockHook = async ({ data, originalDoc, operation, req })=>{
|
|
68
|
+
const kind = operation === 'create' ? data.kind : originalDoc.kind;
|
|
69
|
+
const storedArms = operation === 'update' ? originalDoc.arms : undefined;
|
|
70
|
+
const canonicalSlots = (value)=>{
|
|
71
|
+
if (kind !== 'block' || !Array.isArray(value) || value.some((row)=>!isObject(row))) return value;
|
|
72
|
+
return withSlotsFor(value, 'block');
|
|
73
|
+
};
|
|
74
|
+
const canonicalArms = canonicalSlots(storedArms);
|
|
75
|
+
// Payload runs collection beforeChange before field validation on Create,
|
|
76
|
+
// Update and Restore. Derive slots here so the arms validator sees them.
|
|
77
|
+
const arms = data.arms === undefined ? storedArms : data.arms;
|
|
78
|
+
const repaired = arms === storedArms ? canonicalArms : canonicalSlots(arms);
|
|
79
|
+
if (repaired !== arms) {
|
|
80
|
+
if (operation === 'create') data = {
|
|
81
|
+
...data,
|
|
82
|
+
arms: repaired
|
|
83
|
+
};
|
|
84
|
+
else data.arms = repaired;
|
|
85
|
+
}
|
|
67
86
|
if (req.context.xpTransition === true) return data;
|
|
68
87
|
const baseline = req.headers.get(XP_IF_UPDATED_AT_HEADER);
|
|
69
88
|
if (operation === 'update' && baseline !== null) {
|
|
@@ -71,7 +90,7 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
|
|
|
71
90
|
// so a competing save observes the preceding save's committed timestamp.
|
|
72
91
|
const stored = await lockExperimentUpdatedAt(txExecutor(req), originalDoc.id);
|
|
73
92
|
if (stored === null || new Date(baseline).getTime() !== new Date(stored).getTime()) {
|
|
74
|
-
throw new XpRefusal('stale-edit', '
|
|
93
|
+
throw new XpRefusal('stale-edit', 'This test changed. Read the latest settings and try again.', undefined, 409);
|
|
75
94
|
}
|
|
76
95
|
}
|
|
77
96
|
const admin = async ()=>{
|
|
@@ -139,7 +158,7 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
|
|
|
139
158
|
].includes(field) && isObject(value)) {
|
|
140
159
|
for (const [key, nested] of Object.entries(value))await check(`${field}.${key}`, nested, originalDoc[field]?.[key]);
|
|
141
160
|
} else {
|
|
142
|
-
await check(field, value, originalDoc[field]);
|
|
161
|
+
await check(field, value, field === 'arms' ? canonicalArms : originalDoc[field]);
|
|
143
162
|
// Replacing the group also changes its method, including clearing it.
|
|
144
163
|
if (field === 'analysis' && !same(value, originalDoc.analysis, field) && originalDoc.analysis?.method != null && !await admin()) throw new XpLockedFieldError('analysis.method', status);
|
|
145
164
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { assertReadCommitted } from '../../db/adapter.js';
|
|
1
2
|
import { pickSlug } from '../../db/slugs.js';
|
|
2
3
|
import { pooledExecutor, txExecutor } from '../../db/executor.js';
|
|
3
4
|
export const pickExperimentSlug = async ({ req, data, operation })=>{
|
|
4
5
|
if (operation !== 'create' || typeof data.slug !== 'string' || !data.slug) return data;
|
|
5
6
|
const transactional = await req.transactionID != null;
|
|
7
|
+
if (transactional) await assertReadCommitted(req);
|
|
6
8
|
data.slug = await pickSlug(transactional ? txExecutor(req) : pooledExecutor(req.payload), data.slug, transactional);
|
|
7
9
|
return data;
|
|
8
10
|
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertReadCommitted } from '../db/adapter.js';
|
|
1
2
|
import { pooledExecutor, txExecutor } from '../db/executor.js';
|
|
2
3
|
import { findMetricUsage, lockMetricRow } from '../db/metricUsage.js';
|
|
3
4
|
/** Payload's REST formatter preserves public plugin errors and their 4xx status. */ export class XpGoalInUseError extends Error {
|
|
@@ -8,6 +9,7 @@ import { findMetricUsage, lockMetricRow } from '../db/metricUsage.js';
|
|
|
8
9
|
async function executor(req, id, mode) {
|
|
9
10
|
const transactionID = await req.transactionID;
|
|
10
11
|
if (transactionID != null) {
|
|
12
|
+
await assertReadCommitted(req);
|
|
11
13
|
const exec = txExecutor(req);
|
|
12
14
|
await lockMetricRow(exec, id, mode);
|
|
13
15
|
return exec;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { browserWritableMetric } from '../events/writable.js';
|
|
1
2
|
export function serializeFlagPoints(options) {
|
|
2
3
|
return (options.flagPoints ?? []).map(({ id, label, description, params, defaultParams })=>({
|
|
3
4
|
id,
|
|
@@ -19,19 +20,19 @@ export function serializeMetricSources(options) {
|
|
|
19
20
|
keyedBy: 'visitor',
|
|
20
21
|
clientWritable: true
|
|
21
22
|
},
|
|
22
|
-
...(options.metricSources ?? []).map(({ id, label, kind, keyedBy
|
|
23
|
+
...(options.metricSources ?? []).map(({ id, label, kind, keyedBy })=>({
|
|
23
24
|
id,
|
|
24
25
|
label,
|
|
25
26
|
kind,
|
|
26
27
|
keyedBy,
|
|
27
|
-
clientWritable:
|
|
28
|
+
clientWritable: browserWritableMetric(id, options)
|
|
28
29
|
})),
|
|
29
|
-
...(options.eventSources ?? []).map(({ name
|
|
30
|
+
...(options.eventSources ?? []).map(({ name })=>({
|
|
30
31
|
id: `events:${name}`,
|
|
31
32
|
label: name,
|
|
32
33
|
kind: 'binomial',
|
|
33
34
|
keyedBy: 'visitor',
|
|
34
|
-
clientWritable
|
|
35
|
+
clientWritable: browserWritableMetric(`events:${name}`, options)
|
|
35
36
|
}))
|
|
36
37
|
];
|
|
37
38
|
}
|
package/dist/constants.d.ts
CHANGED
|
@@ -7,3 +7,4 @@ export declare const XP_PREVIEW_PARAM = "xp_preview";
|
|
|
7
7
|
export declare const XP_MANIFEST_KEY_HEADER = "x-xp-manifest-key";
|
|
8
8
|
export declare const XP_REQUEST_HEADER = "x-xp-request";
|
|
9
9
|
export declare const XP_IF_UPDATED_AT_HEADER = "x-xp-if-updated-at";
|
|
10
|
+
export declare const USER_BROWSER_CONVERSION_PREFIX = "conversion:cu:";
|
package/dist/constants.js
CHANGED
|
@@ -7,3 +7,4 @@ export const XP_PREVIEW_PARAM = 'xp_preview';
|
|
|
7
7
|
export const XP_MANIFEST_KEY_HEADER = 'x-xp-manifest-key';
|
|
8
8
|
export const XP_REQUEST_HEADER = 'x-xp-request';
|
|
9
9
|
export const XP_IF_UPDATED_AT_HEADER = 'x-xp-if-updated-at';
|
|
10
|
+
export const USER_BROWSER_CONVERSION_PREFIX = 'conversion:cu:';
|
package/dist/db/adapter.d.ts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { APIError, type Payload, type PayloadRequest } from 'payload';
|
|
2
|
+
export declare class XpTransactionIsolationError extends APIError {
|
|
3
|
+
constructor();
|
|
4
|
+
}
|
|
5
|
+
/** Payload's initTransaction cannot pass options to the adapter. Like that
|
|
6
|
+
* helper, publish the pending transaction on the request before awaiting it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function initTransitionTransaction(req: PayloadRequest): Promise<boolean>;
|
|
9
|
+
export declare function assertReadCommitted(req: PayloadRequest): Promise<void>;
|
|
2
10
|
export declare function assertPostgresAdapter(payload: Payload): void;
|
|
3
11
|
export declare function probeTransactions(payload: Payload): Promise<void>;
|
package/dist/db/adapter.js
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { XpNoTransactionError } from '../errors.js';
|
|
3
|
+
import { API_MESSAGES } from '../testSurface/copy/common.js';
|
|
4
|
+
import { transactionSession, txExecutor } from './executor.js';
|
|
5
|
+
const transitionIsolation = 'read committed';
|
|
6
|
+
const isolationMessage = 'Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.';
|
|
7
|
+
const checkedSessions = new WeakMap();
|
|
8
|
+
export class XpTransactionIsolationError extends APIError {
|
|
9
|
+
constructor(){
|
|
10
|
+
super(API_MESSAGES.transactionIsolation, 500, null, true);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Payload's initTransaction cannot pass options to the adapter. Like that
|
|
14
|
+
* helper, publish the pending transaction on the request before awaiting it.
|
|
15
|
+
*/ export async function initTransitionTransaction(req) {
|
|
16
|
+
if (req.transactionID != null) {
|
|
17
|
+
await req.transactionID;
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const db = req.payload.db;
|
|
21
|
+
const pending = db.beginTransaction({
|
|
22
|
+
...db.transactionOptions || {},
|
|
23
|
+
isolationLevel: transitionIsolation
|
|
24
|
+
}).then((id)=>{
|
|
25
|
+
if (id == null) throw new XpNoTransactionError();
|
|
26
|
+
const session = db.sessions?.[id];
|
|
27
|
+
if (session) checkedSessions.set(session, Promise.resolve());
|
|
28
|
+
req.transactionID = id;
|
|
29
|
+
return id;
|
|
30
|
+
});
|
|
31
|
+
req.transactionID = pending;
|
|
32
|
+
try {
|
|
33
|
+
await pending;
|
|
34
|
+
return true;
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (req.transactionID === pending) delete req.transactionID;
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** A borrowed transaction may already have taken its snapshot. Check the
|
|
41
|
+
* effective isolation on that session before relying on a post-lock read.
|
|
42
|
+
*/ async function isReadCommitted(exec) {
|
|
43
|
+
const { rows } = await exec.query('SHOW transaction_isolation');
|
|
44
|
+
const level = rows[0]?.transaction_isolation;
|
|
45
|
+
// PostgreSQL implements READ UNCOMMITTED as READ COMMITTED (docs §13.2).
|
|
46
|
+
return level === transitionIsolation || level === 'read uncommitted';
|
|
47
|
+
}
|
|
48
|
+
export async function assertReadCommitted(req) {
|
|
49
|
+
const transaction = {
|
|
50
|
+
payload: req.payload,
|
|
51
|
+
transactionID: await req.transactionID
|
|
52
|
+
};
|
|
53
|
+
// The adapter resolves the ID to a unique session object until commit or
|
|
54
|
+
// rollback. Cache the pending check so concurrent hooks share the same query.
|
|
55
|
+
const session = await transactionSession(transaction);
|
|
56
|
+
let checked = checkedSessions.get(session);
|
|
57
|
+
if (!checked) {
|
|
58
|
+
checked = isReadCommitted(txExecutor(transaction)).then((valid)=>{
|
|
59
|
+
if (!valid) {
|
|
60
|
+
try {
|
|
61
|
+
console.error('Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.');
|
|
62
|
+
} catch {}
|
|
63
|
+
throw new XpTransactionIsolationError();
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
checkedSessions.set(session, checked);
|
|
67
|
+
}
|
|
68
|
+
await checked;
|
|
69
|
+
}
|
|
1
70
|
export function assertPostgresAdapter(payload) {
|
|
2
71
|
// @payloadcms/db-postgres/dist/index.js:133 declares this package marker.
|
|
3
72
|
if (payload.db.packageName !== '@payloadcms/db-postgres') throw new Error('Experiments requires @payloadcms/db-postgres');
|
|
@@ -5,5 +74,12 @@ export function assertPostgresAdapter(payload) {
|
|
|
5
74
|
export async function probeTransactions(payload) {
|
|
6
75
|
const id = await payload.db.beginTransaction();
|
|
7
76
|
if (id == null) throw new Error('Experiments transactions are disabled');
|
|
8
|
-
|
|
77
|
+
try {
|
|
78
|
+
if (!await isReadCommitted(txExecutor({
|
|
79
|
+
payload,
|
|
80
|
+
transactionID: id
|
|
81
|
+
}))) throw new Error(isolationMessage);
|
|
82
|
+
} finally{
|
|
83
|
+
await payload.db.rollbackTransaction(id);
|
|
84
|
+
}
|
|
9
85
|
}
|
package/dist/db/appends.d.ts
CHANGED
|
@@ -24,6 +24,19 @@ type AppendArgs<T> = {
|
|
|
24
24
|
* before the audit savepoint can recover.
|
|
25
25
|
*/
|
|
26
26
|
export declare function storedContent(req: PayloadRequest, collection: string, id: DocId): Promise<Record<string, unknown> | undefined>;
|
|
27
|
+
export interface PlacementSavePath {
|
|
28
|
+
versionId?: DocId;
|
|
29
|
+
bulk?: boolean;
|
|
30
|
+
draft?: boolean;
|
|
31
|
+
trashing?: boolean;
|
|
32
|
+
publishSpecificLocale?: string;
|
|
33
|
+
}
|
|
34
|
+
/** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
|
|
35
|
+
* starts from main rows except draft/trash saves. utilities/update then replaces
|
|
36
|
+
* unselected locales with the latest published version (publishSpecificLocale).
|
|
37
|
+
* Localized publication status is refused at init. Restore uses the selected version. */
|
|
38
|
+
export declare function placementMergeBase(path: PlacementSavePath): 'restore' | 'main' | 'published' | 'latest';
|
|
39
|
+
export declare function placementWriteContent(req: PayloadRequest, collection: string, id: DocId, main: Record<string, unknown> | undefined, path?: PlacementSavePath): Promise<Record<string, unknown> | undefined>;
|
|
27
40
|
/** Read the main collection row BEFORE the host write. Draft version retention
|
|
28
41
|
* and unpublishing cannot remove this baseline.
|
|
29
42
|
*/
|
package/dist/db/appends.js
CHANGED
|
@@ -18,6 +18,55 @@ import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
|
|
|
18
18
|
});
|
|
19
19
|
return doc ?? undefined;
|
|
20
20
|
}
|
|
21
|
+
/** Payload 3.90.2: updateByID starts from the latest version; update (bulk)
|
|
22
|
+
* starts from main rows except draft/trash saves. utilities/update then replaces
|
|
23
|
+
* unselected locales with the latest published version (publishSpecificLocale).
|
|
24
|
+
* Localized publication status is refused at init. Restore uses the selected version. */ export function placementMergeBase(path) {
|
|
25
|
+
if (path.versionId != null) return 'restore';
|
|
26
|
+
if (path.publishSpecificLocale) return 'published';
|
|
27
|
+
return path.bulk && !path.draft && !path.trashing ? 'main' : 'latest';
|
|
28
|
+
}
|
|
29
|
+
export async function placementWriteContent(req, collection, id, main, path = {}) {
|
|
30
|
+
const config = req.payload.config.collections?.find((entry)=>entry.slug === collection);
|
|
31
|
+
if (!config?.versions || !config.versions.drafts) return main;
|
|
32
|
+
const base = placementMergeBase(path);
|
|
33
|
+
if (base === 'main') return main;
|
|
34
|
+
// Adapter read on the guarded write's transaction; no Local API hook recursion.
|
|
35
|
+
const latest = await req.payload.db.findVersions({
|
|
36
|
+
collection,
|
|
37
|
+
req,
|
|
38
|
+
limit: 1,
|
|
39
|
+
pagination: false,
|
|
40
|
+
sort: '-updatedAt',
|
|
41
|
+
where: base === 'restore' ? {
|
|
42
|
+
id: {
|
|
43
|
+
equals: path.versionId
|
|
44
|
+
}
|
|
45
|
+
} : {
|
|
46
|
+
and: [
|
|
47
|
+
{
|
|
48
|
+
parent: {
|
|
49
|
+
equals: id
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
base === 'published' ? {
|
|
53
|
+
'version._status': {
|
|
54
|
+
equals: 'published'
|
|
55
|
+
}
|
|
56
|
+
} : {
|
|
57
|
+
latest: {
|
|
58
|
+
equals: true
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
},
|
|
63
|
+
overrideAccess: false
|
|
64
|
+
});
|
|
65
|
+
return latest.docs[0] ? {
|
|
66
|
+
...latest.docs[0].version,
|
|
67
|
+
id
|
|
68
|
+
} : base === 'published' ? undefined : main;
|
|
69
|
+
}
|
|
21
70
|
/** Read the main collection row BEFORE the host write. Draft version retention
|
|
22
71
|
* and unpublishing cannot remove this baseline.
|
|
23
72
|
*/ export async function previousPublishedContent(req, collection, id) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
|
|
1
|
+
import { placementLocaleContent, mergedPlacementLocales, removedPlacementViews, placementDocumentKey } from '../blocks/placementLocale.js';
|
|
2
2
|
// Payload starts/ends a transaction per bulk document with this adapter option.
|
|
3
3
|
export function usesBulkDocumentTransactions(req) {
|
|
4
4
|
return req.payload.db.bulkOperationsSingleTransaction === true;
|
|
@@ -98,10 +98,14 @@ const operationRequestState = Symbol('xpPlacementRequestState');
|
|
|
98
98
|
collection,
|
|
99
99
|
String(doc.id)
|
|
100
100
|
]))) return false;
|
|
101
|
-
|
|
102
|
-
|
|
101
|
+
// locale=all data and the adapter row share the same all-language shape.
|
|
102
|
+
// A single-locale write instead merges its flattened values once.
|
|
103
|
+
const input = req.locale === 'all' ? 'all-locales' : 'localized';
|
|
104
|
+
const pending = {
|
|
105
|
+
...input === 'all-locales' ? doc : placementLocaleContent(req, collection, doc, 'all-locales'),
|
|
103
106
|
...change.data
|
|
104
107
|
};
|
|
105
|
-
const
|
|
108
|
+
const after = input === 'all-locales' ? pending : mergedPlacementLocales(req, collection, doc, pending);
|
|
109
|
+
const views = removedPlacementViews(req, collection, doc, after, change.deleting || after.deletedAt != null || after._status === 'draft', 'all-locales');
|
|
106
110
|
return (views.get(slug) ?? []).some((removed)=>placementDocumentKey(collection, doc.id, removed) === placementDocumentKey(collection, doc.id, view));
|
|
107
111
|
}
|
package/dist/db/delete.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { PayloadRequest } from 'payload';
|
|
2
2
|
import type { DocId } from '../types/contracts.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type Executor } from './executor.js';
|
|
4
4
|
interface DeleteState {
|
|
5
5
|
tail: Promise<void>;
|
|
6
6
|
retiredSlugs: Set<string>;
|
package/dist/db/delete.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { transactionSession } from './executor.js';
|
|
2
2
|
import { COLUMNS, TABLES } from './names.js';
|
|
3
3
|
import { qualifiedTable, quoteIdentifier as quote } from './sql.js';
|
|
4
4
|
// Key by the actual session: borrowed requests in one transaction share a queue,
|
|
@@ -9,9 +9,7 @@ const transactions = new WeakMap();
|
|
|
9
9
|
* Successful beforeDelete bodies retain exclusions until the transaction ends:
|
|
10
10
|
* another row can be between hooks with its children gone but its row present.
|
|
11
11
|
*/ export async function serializeDelete(req, fn) {
|
|
12
|
-
const
|
|
13
|
-
const session = id == null ? undefined : req.payload.db.sessions?.[id];
|
|
14
|
-
if (!session) throw new XpNoTransactionError();
|
|
12
|
+
const session = await transactionSession(req);
|
|
15
13
|
let state = transactions.get(session);
|
|
16
14
|
if (!state) {
|
|
17
15
|
state = {
|
package/dist/db/events.d.ts
CHANGED
|
@@ -17,5 +17,14 @@ export interface EventRow {
|
|
|
17
17
|
attributes?: Record<string, unknown>;
|
|
18
18
|
dedupeKey: string;
|
|
19
19
|
}
|
|
20
|
+
type ServerConversion = Pick<EventRow, 'unitId' | 'unitType' | 'userId' | 'ts'> & {
|
|
21
|
+
eventName: string;
|
|
22
|
+
value: number;
|
|
23
|
+
idempotencyKey: string;
|
|
24
|
+
};
|
|
25
|
+
/** A retained legacy row suppresses retries for its event name. The scoped key's
|
|
26
|
+
* unique index handles concurrent writes after the old writers have been drained. */
|
|
27
|
+
export declare function insertServerConversion(exec: Executor, event: ServerConversion, log: (message: string) => void): Promise<void>;
|
|
20
28
|
/** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */
|
|
21
29
|
export declare function insertEvents(exec: Executor, rows: EventRow[], log?: (message: string) => void): Promise<number>;
|
|
30
|
+
export {};
|
package/dist/db/events.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { exposureDimensions } from '../events/dimensions.js';
|
|
2
3
|
import { COLUMNS, TABLES } from './names.js';
|
|
3
4
|
import { qualifiedTable, quoteIdentifier } from './sql.js';
|
|
@@ -6,7 +7,7 @@ import { qualifiedTable, quoteIdentifier } from './sql.js';
|
|
|
6
7
|
experimentId
|
|
7
8
|
]);
|
|
8
9
|
}
|
|
9
|
-
const quote =
|
|
10
|
+
const quote = quoteIdentifier;
|
|
10
11
|
const c = COLUMNS.events;
|
|
11
12
|
function foreignKeyViolation(error) {
|
|
12
13
|
const seen = new Set();
|
|
@@ -28,15 +29,48 @@ function foreignKeyViolation(error) {
|
|
|
28
29
|
return null;
|
|
29
30
|
}
|
|
30
31
|
}
|
|
32
|
+
function hasFiniteValue(value, log) {
|
|
33
|
+
if (value === undefined || Number.isFinite(value)) return true;
|
|
34
|
+
log('Experiments: dropped event with non-finite value');
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
/** A retained legacy row suppresses retries for its event name. The scoped key's
|
|
38
|
+
* unique index handles concurrent writes after the old writers have been drained. */ export async function insertServerConversion(exec, event, log) {
|
|
39
|
+
if (!hasFiniteValue(event.value, log)) return;
|
|
40
|
+
const table = qualifiedTable(exec, TABLES.events);
|
|
41
|
+
const digest = createHash('sha256').update(JSON.stringify([
|
|
42
|
+
event.eventName,
|
|
43
|
+
event.idempotencyKey
|
|
44
|
+
])).digest('hex');
|
|
45
|
+
await exec.query(`INSERT INTO ${table} (${[
|
|
46
|
+
c.type,
|
|
47
|
+
c.unitId,
|
|
48
|
+
c.unitType,
|
|
49
|
+
c.userId,
|
|
50
|
+
c.eventName,
|
|
51
|
+
c.value,
|
|
52
|
+
c.ts,
|
|
53
|
+
c.dedupeKey,
|
|
54
|
+
c.createdAt,
|
|
55
|
+
c.updatedAt
|
|
56
|
+
].map(quote).join(', ')})
|
|
57
|
+
SELECT 'conversion', $1, $2, $3, $4, $5, $6, $7, now(), now()
|
|
58
|
+
WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE ${quote(c.dedupeKey)} = $8 AND ${quote(c.eventName)} = $4)
|
|
59
|
+
ON CONFLICT (${quote(c.dedupeKey)}) DO NOTHING`, [
|
|
60
|
+
event.unitId,
|
|
61
|
+
event.unitType,
|
|
62
|
+
event.userId ?? null,
|
|
63
|
+
event.eventName,
|
|
64
|
+
event.value,
|
|
65
|
+
event.ts,
|
|
66
|
+
`conversion:s2:${digest}`,
|
|
67
|
+
`conversion:s:${event.idempotencyKey}`
|
|
68
|
+
]);
|
|
69
|
+
}
|
|
31
70
|
/** Pooled/autocommit executor required: an FK failure must not poison a caller's transaction. */ export async function insertEvents(exec, rows, log = console.error) {
|
|
32
|
-
const valid = rows.filter((row)=>
|
|
33
|
-
if (row.value === undefined || Number.isFinite(row.value)) return true;
|
|
34
|
-
log('Experiments: dropped event with non-finite value');
|
|
35
|
-
return false;
|
|
36
|
-
});
|
|
71
|
+
const valid = rows.filter((row)=>hasFiniteValue(row.value, log));
|
|
37
72
|
if (!valid.length) return 0;
|
|
38
|
-
const
|
|
39
|
-
const table = `${schema ? `${quote(schema)}.` : ''}${quote(TABLES.events)}`;
|
|
73
|
+
const table = qualifiedTable(exec, TABLES.events);
|
|
40
74
|
async function insert(batch) {
|
|
41
75
|
const params = [];
|
|
42
76
|
const values = batch.map((row)=>{
|
package/dist/db/executor.d.ts
CHANGED
|
@@ -2,7 +2,13 @@ import type { Payload, PayloadRequest } from 'payload';
|
|
|
2
2
|
import type { Executor } from './pgExecutor.js';
|
|
3
3
|
export type { Executor } from './pgExecutor.js';
|
|
4
4
|
export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, ResultsBudgetError, RESULTS_TIMEOUT_MARGIN_MS } from './pgExecutor.js';
|
|
5
|
-
|
|
5
|
+
type TransactionRequest = Pick<PayloadRequest, 'payload' | 'transactionID'>;
|
|
6
|
+
export declare function transactionSession(req: TransactionRequest): Promise<{
|
|
7
|
+
db: unknown;
|
|
8
|
+
reject: () => Promise<void>;
|
|
9
|
+
resolve: () => Promise<void>;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function txExecutor(req: TransactionRequest): Executor & {
|
|
6
12
|
schemaName?: string;
|
|
7
13
|
};
|
|
8
14
|
export declare function pooledExecutor(payload: Payload): Executor & {
|
package/dist/db/executor.js
CHANGED
|
@@ -14,14 +14,18 @@ export { pgPoolExecutor, ownConnection, withStatementTimeout, raceDeadline, Resu
|
|
|
14
14
|
chunks.push(sql.raw(text.slice(start)));
|
|
15
15
|
return sql.join(chunks, sql.raw(''));
|
|
16
16
|
}
|
|
17
|
+
export async function transactionSession(req) {
|
|
18
|
+
const id = await req.transactionID;
|
|
19
|
+
const session = id == null ? undefined : req.payload.db.sessions?.[id];
|
|
20
|
+
if (!session) throw new XpNoTransactionError();
|
|
21
|
+
return session;
|
|
22
|
+
}
|
|
17
23
|
export function txExecutor(req) {
|
|
18
24
|
const db = req.payload.db;
|
|
19
25
|
return {
|
|
20
26
|
schemaName: db.schemaName,
|
|
21
27
|
async query (text, params = []) {
|
|
22
|
-
const
|
|
23
|
-
const session = id == null ? undefined : db.sessions?.[id];
|
|
24
|
-
if (!session) throw new XpNoTransactionError();
|
|
28
|
+
const session = await transactionSession(req);
|
|
25
29
|
return normalise(await session.db.execute(bind(text, params)));
|
|
26
30
|
}
|
|
27
31
|
};
|
package/dist/db/results.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export interface PhaseExposureRow {
|
|
|
5
5
|
unitId: string;
|
|
6
6
|
arm: string;
|
|
7
7
|
ts: number;
|
|
8
|
+
unitAgeMs?: number;
|
|
8
9
|
}
|
|
9
10
|
export interface RolloutExposureRow {
|
|
10
11
|
unitId: string;
|
|
@@ -16,6 +17,7 @@ export interface MetricEventRow {
|
|
|
16
17
|
userId: string | null;
|
|
17
18
|
value: number;
|
|
18
19
|
ts: number;
|
|
20
|
+
unitAgeMs?: number;
|
|
19
21
|
}
|
|
20
22
|
export interface IdentityRow {
|
|
21
23
|
anonymousId: string;
|
|
@@ -41,12 +43,14 @@ export declare function rolloutExposureRows(exec: Executor, { experimentId, resp
|
|
|
41
43
|
* or userIds for stored user_id (user units and visitor identity credit). Each distinct
|
|
42
44
|
* ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
|
|
43
45
|
*/
|
|
44
|
-
export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to }: {
|
|
46
|
+
export declare function metricEventRows(exec: Executor, { eventName, unitIds, userIds, from, to, readAge, forVisitors }: {
|
|
45
47
|
eventName: string;
|
|
46
48
|
unitIds?: readonly string[];
|
|
47
49
|
userIds?: readonly string[];
|
|
48
50
|
from: Timestamp;
|
|
49
51
|
to: Timestamp;
|
|
52
|
+
readAge?: boolean;
|
|
53
|
+
forVisitors?: boolean;
|
|
50
54
|
}): Promise<MetricEventRow[]>;
|
|
51
55
|
/** Linked visitors for creditUserEvents; disjoint ANY batches of ≤ 10,000 IDs. */
|
|
52
56
|
export declare function identityRows(exec: Executor, { anonymousIds }: {
|
package/dist/db/results.js
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import { timestampMs } from '../results/aggregate.js';
|
|
2
2
|
import { COLUMNS, TABLES } from './names.js';
|
|
3
|
+
import { USER_BROWSER_CONVERSION_PREFIX } from '../constants.js';
|
|
3
4
|
import { qualifiedTable, quoteIdentifier as q } from './sql.js';
|
|
4
5
|
const c = COLUMNS.events;
|
|
5
6
|
const batchSize = 10_000;
|
|
6
7
|
const iso = (ts)=>new Date(timestampMs(ts)).toISOString();
|
|
7
8
|
// round()::bigint keeps exact milliseconds on servers where extract() returns a float (PG ≤ 13).
|
|
8
9
|
const epochMs = `round(extract(epoch from ${q(c.ts)}) * 1000)::bigint`;
|
|
10
|
+
const signedAge = `${q(c.attributes)}->'_xp'->'unitAgeMs' AS "unitAgeMs"`;
|
|
11
|
+
function knownAge(unitAgeMs) {
|
|
12
|
+
// A reissued legacy ID counts as known and older than the rapid activity window.
|
|
13
|
+
if (unitAgeMs === 'legacy') return {
|
|
14
|
+
unitAgeMs: Infinity
|
|
15
|
+
};
|
|
16
|
+
return typeof unitAgeMs === 'number' && Number.isSafeInteger(unitAgeMs) && unitAgeMs >= 0 ? {
|
|
17
|
+
unitAgeMs
|
|
18
|
+
} : {};
|
|
19
|
+
}
|
|
9
20
|
function phaseFilter({ experimentId, phase, endedAt }, type) {
|
|
10
21
|
const params = [
|
|
11
22
|
experimentId,
|
|
@@ -24,11 +35,12 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
|
|
|
24
35
|
}
|
|
25
36
|
/** All phase exposures, including multi-arm rows for firstExposures to exclude. */ export async function phaseExposureRows(exec, opts) {
|
|
26
37
|
const filter = phaseFilter(opts, 'exposure');
|
|
27
|
-
const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts" FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
|
|
38
|
+
const { rows } = await exec.query(`SELECT ${q(c.unitId)} AS "unitId", ${q(c.arm)} AS "arm", ${epochMs} AS "ts", ${signedAge} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${filter.text} ORDER BY ${q(c.ts)}, ${q(c.unitId)}`, filter.params);
|
|
28
39
|
return rows.map((row)=>({
|
|
29
40
|
unitId: row.unitId,
|
|
30
41
|
arm: row.arm,
|
|
31
|
-
ts: Number(row.ts)
|
|
42
|
+
ts: Number(row.ts),
|
|
43
|
+
...knownAge(row.unitAgeMs)
|
|
32
44
|
}));
|
|
33
45
|
}
|
|
34
46
|
/** Diagnostic distinct units only; this never contributes to multi-arm exclusion. */ export async function armMismatchCount(exec, opts) {
|
|
@@ -52,7 +64,7 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
|
|
|
52
64
|
/** events:<name> conversion rows in [from, to). Choose unitIds for stored unit_id,
|
|
53
65
|
* or userIds for stored user_id (user units and visitor identity credit). Each distinct
|
|
54
66
|
* ID occurs in one ANY array of at most 10,000, so batching cannot duplicate rows.
|
|
55
|
-
*/ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to }) {
|
|
67
|
+
*/ export async function metricEventRows(exec, { eventName, unitIds, userIds, from, to, readAge = false, forVisitors = false }) {
|
|
56
68
|
if (unitIds !== undefined && userIds !== undefined) throw new RangeError('Choose unitIds or userIds');
|
|
57
69
|
const params = [
|
|
58
70
|
'conversion',
|
|
@@ -60,7 +72,10 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
|
|
|
60
72
|
iso(from),
|
|
61
73
|
iso(to)
|
|
62
74
|
];
|
|
63
|
-
|
|
75
|
+
// A browser conversion without a visitor cookie cannot count for a visitor,
|
|
76
|
+
// even through the separate linked-user lookup.
|
|
77
|
+
const visitorFilter = forVisitors ? ` AND ${q(c.dedupeKey)} NOT LIKE '${USER_BROWSER_CONVERSION_PREFIX}%'` : '';
|
|
78
|
+
const text = `SELECT ${q(c.unitId)} AS "unitId", ${q(c.userId)} AS "userId", ${q(c.value)} AS "value", ${epochMs} AS "ts"${readAge ? `, ${signedAge}` : ''} FROM ${qualifiedTable(exec, TABLES.events)} WHERE ${q(c.type)} = $1 AND ${q(c.eventName)} = $2 AND ${q(c.ts)} >= $3 AND ${q(c.ts)} < $4${visitorFilter}`;
|
|
64
79
|
const filterIds = userIds ?? unitIds;
|
|
65
80
|
const column = userIds === undefined ? c.unitId : c.userId;
|
|
66
81
|
const ids = filterIds === undefined ? undefined : [
|
|
@@ -77,7 +92,8 @@ function phaseFilter({ experimentId, phase, endedAt }, type) {
|
|
|
77
92
|
unitId: row.unitId,
|
|
78
93
|
userId: row.userId == null ? null : String(row.userId),
|
|
79
94
|
value: Number(row.value),
|
|
80
|
-
ts: Number(row.ts)
|
|
95
|
+
ts: Number(row.ts),
|
|
96
|
+
...knownAge(row.unitAgeMs)
|
|
81
97
|
});
|
|
82
98
|
}
|
|
83
99
|
if (ids === undefined) break;
|
package/dist/db/snapshots.d.ts
CHANGED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type PayloadRequest } from 'payload';
|
|
2
|
+
/** Validate advisory-read metadata language; placement discovery still scans all languages. */
|
|
3
|
+
export declare function contentLocale(req: PayloadRequest): {
|
|
4
|
+
locale: string | null | undefined;
|
|
5
|
+
fallbackLocale: false | "none" | "false" | "null" | ({} & string) | ({} & string)[] | null | undefined;
|
|
6
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { sanitizeFallbackLocale } from 'payload';
|
|
2
|
+
/** Validate advisory-read metadata language; placement discovery still scans all languages. */ export function contentLocale(req) {
|
|
3
|
+
const localization = req.payload.config.localization;
|
|
4
|
+
const requested = new URL(req.url ?? 'http://xp.invalid').searchParams.get('locale') ?? req.locale;
|
|
5
|
+
const locale = localization ? localization.localeCodes.includes(requested ?? '') ? requested : localization.defaultLocale : undefined;
|
|
6
|
+
const fallbackLocale = localization ? sanitizeFallbackLocale({
|
|
7
|
+
fallbackLocale: req.fallbackLocale ?? null,
|
|
8
|
+
locale: locale,
|
|
9
|
+
localization
|
|
10
|
+
}) : req.fallbackLocale;
|
|
11
|
+
return {
|
|
12
|
+
locale,
|
|
13
|
+
fallbackLocale
|
|
14
|
+
};
|
|
15
|
+
}
|