feat(product-analytics): destination transforms (where, keep/drop, rename, set)

The destination catalogue had no transforms (recount A23): every destination
got every event with every property.

A destination may now carry a declarative transform, applied by the exports
runner before any send for every kind (webhook, S3, Slack, Discord, HubSpot,
ClickHouse, BigQuery): 'where' keeps the events matching every condition (on
a property, the event name or distinct_id; eq, neq, in, not_in, exists,
not_exists, contains, gt, lt), then 'keep' or 'drop', 'rename' and 'set'
reshape the properties. Events are never mutated in place; the cursor moves
past every row read even when nothing is sent. No code runs, so a transform
cannot reach the network or the database. POST and PUT /exports take it (PUT
with null removes it); the console form has the field.

Also: the surveys and vendor tests resolve the upstream SDK from the
wrapper's own install, else the service's pin of the same version (checked),
so they run on a fresh checkout instead of failing or skipping.

Tests: qy/transforms (unit, refusals, end to end through a webhook,
replace/remove). All product analytics suites (a1, a2, a3, qy): 206 passed,
4 skipped (no cached Chromium on this machine), 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
caelum0x 2026-10-06 17:24:34 +03:00
parent a5ae15ae28
commit 41653aebf1
10 changed files with 324 additions and 13 deletions

View File

@ -363,12 +363,26 @@ export function experimentFromForm(form: Record<string, string>): Record<string,
};
}
/**
* A23: the optional transform typed as JSON. Text that is not JSON is passed
* through as-is, so the service answers with its own message (400).
*/
function transformFromForm(raw: string | undefined): { transform?: unknown } {
const t = (raw ?? "").trim();
if (!t) return {};
try {
return { transform: JSON.parse(t) };
} catch {
return { transform: t };
}
}
export function destinationFromForm(form: Record<string, string>): Record<string, unknown> {
const events = (form.events ?? "")
.split(/[\n,]/)
.map((s) => s.trim())
.filter(Boolean);
const common = { name: form.name ?? "", start: form.start === "all" ? "all" : "now", ...(events.length ? { events } : {}) };
const common = { name: form.name ?? "", start: form.start === "all" ? "all" : "now", ...(events.length ? { events } : {}), ...transformFromForm(form.transform) };
if (form.kind === "slack" || form.kind === "discord" || form.kind === "hubspot") {
// QY1.4: the webhook address (Slack, Discord) or the private app token (HubSpot) is sealed by the service.
return { ...common, kind: form.kind, config: { label: form.label ?? "" }, secret: form.target ?? "" };

View File

@ -146,6 +146,15 @@ export default async function NewDestinationPage({ searchParams }: { searchParam
<span className="muted">Only these events, comma separated (leave empty for all)</span>
<input name="events" placeholder="signup, purchase" />
</label>
<label style={input}>
<span className="muted">Transform (JSON, optional): where, keep or drop, rename, set</span>
<textarea
name="transform"
rows={3}
spellCheck={false}
placeholder='{"where":[{"property":"plan","op":"eq","value":"pro"}],"drop":["email"]}'
/>
</label>
<label style={input}>
<span className="muted">Start with</span>
<select name="start" defaultValue="now">

View File

@ -13,6 +13,7 @@ import { ApiError, text } from "../replay/shared/console-guard.ts";
import { checkUrlShape, DestinationRefused } from "./net-guard.ts";
import { newSigningSecret, seal, SecretsUnavailable } from "./secrets.ts";
import { checkCatalogue, isCatalogue, sealBundle, type CatalogueKind } from "./catalogue.ts";
import { checkTransform, type Transform } from "./transform.ts";
/** Destinations per project (target, copy-source: apps/product-analytics/src/exports/destinations.ts). */
export const MAX_DESTINATIONS = 6;
@ -27,7 +28,7 @@ export interface Destination {
project_id: string;
name: string;
kind: "webhook" | "s3" | CatalogueKind;
config: WebhookConfig | S3DestConfig | CatalogueConfig;
config: (WebhookConfig | S3DestConfig | CatalogueConfig) & { transform?: Transform };
events: string[] | null;
enabled: boolean;
status: "ok" | "retrying" | "failing";
@ -54,7 +55,7 @@ export const toDestination = (r: Record<string, unknown>): Destination => ({
export interface NewDestination {
name: string;
kind: "webhook" | "s3" | CatalogueKind;
config: WebhookConfig | S3DestConfig | CatalogueConfig;
config: (WebhookConfig | S3DestConfig | CatalogueConfig) & { transform?: Transform };
/** What is sealed: the signing secret, the S3 key, or a catalogue bundle (JSON). */
secret: string;
/** The signing secret shown once (webhook and catalogue kinds). */
@ -72,7 +73,14 @@ function guard<T>(fn: () => T): T {
}
}
/** Validates a new destination, its kind's settings and its transform (A23). */
export function checkDestination(b: Record<string, unknown>): NewDestination {
const transform = checkTransform(b.transform);
const d = checkKind(b);
return transform ? { ...d, config: { ...d.config, transform } } : d;
}
function checkKind(b: Record<string, unknown>): NewDestination {
const name = text(b.name, "Name", 200)!;
const events = b.events === undefined || b.events === null ? null : b.events;
if (events !== null && (!Array.isArray(events) || events.length === 0 || events.length > MAX_EVENT_FILTER || !events.every((e) => typeof e === "string" && e.length >= 1 && e.length <= 200))) {
@ -145,11 +153,17 @@ export async function updateDestination(db: Db, projectId: string, id: string, b
return db.asProject(projectId, async (c) => {
await getDestination(c, projectId, id);
if (b.enabled !== undefined && typeof b.enabled !== "boolean") throw new ApiError(400, "enabled must be true or false.");
// A23: `transform` replaces the destination's transform; null removes it.
const changeTransform = Object.prototype.hasOwnProperty.call(b, "transform");
const transform = changeTransform ? checkTransform(b.transform) : null;
const r = await c.query(
`update pa.export_destinations set enabled = coalesce($3, enabled),
next_attempt_at = case when $4 then null else next_attempt_at end, updated_at = $5
next_attempt_at = case when $4 then null else next_attempt_at end, updated_at = $5,
config = case when not $6 then config
when $7::jsonb is null then config - 'transform'
else jsonb_set(config, '{transform}', $7::jsonb) end
where project_id = $1 and id = $2 returning ${COLS}`,
[projectId, id, b.enabled ?? null, b.retry_now === true, now.toISOString()],
[projectId, id, b.enabled ?? null, b.retry_now === true, now.toISOString(), changeTransform, transform ? JSON.stringify(transform) : null],
);
return toDestination(r.rows[0]);
});

View File

@ -20,6 +20,7 @@ import { checkUrlShape, DestinationRefused } from "./net-guard.ts";
import { guardedFetch } from "./guarded-fetch.ts";
import { open } from "./secrets.ts";
import { isCatalogue, openBundle, sendCatalogue, type SecretBundle } from "./catalogue.ts";
import { applyTransform, type Transform } from "./transform.ts";
export const BATCH_SIZE = 500;
export const MAX_BATCHES_PER_RUN = 20;
@ -164,17 +165,22 @@ export async function deliver(db: Db, raw: Record<string, unknown>, now: Date, o
const started = now;
let bytes = 0;
let httpStatus: number | null = null;
// A23: the destination's transform filters and reshapes what it receives;
// the cursor still moves past every row read.
const out = applyTransform((d.config as { transform?: Transform }).transform, rows);
try {
if (d.kind === "webhook") {
const body = JSON.stringify({ type: "events", project_id: d.project_id, batch_id: batchId, events: rows.map(exported) });
if (out.length === 0) {
// Nothing of this batch is for this destination.
} else if (d.kind === "webhook") {
const body = JSON.stringify({ type: "events", project_id: d.project_id, batch_id: batchId, events: out.map(exported) });
bytes = Buffer.byteLength(body);
httpStatus = await sendWebhook(d.config as WebhookConfig, secret, body, `msg_${batchId}`, now, fetchImpl);
} else if (isCatalogue(d.kind) && bundle) {
const sent = await sendCatalogue(d.kind, bundle, rows.map(exported), `msg_${batchId}`, now, fetchImpl, d.config as Record<string, unknown>);
const sent = await sendCatalogue(d.kind, bundle, out.map(exported), `msg_${batchId}`, now, fetchImpl, d.config as Record<string, unknown>);
bytes = sent.bytes;
httpStatus = sent.status;
} else {
bytes = await sendS3(d, secret, rows, batchId, fetchImpl);
bytes = await sendS3(d, secret, out, batchId, fetchImpl);
}
} catch (err) {
const e = err instanceof DeliveryError ? err : new DeliveryError((err as Error).message.slice(0, 300));

View File

@ -0,0 +1,145 @@
// Destination transforms (A23): what a destination receives, declared per
// destination and applied by the exports runner before any send, the same for
// every kind (webhook, S3, Slack, Discord, HubSpot, ClickHouse, BigQuery).
//
// { "where": [{ "property": "plan", "op": "eq", "value": "pro" }, ...],
// "drop": ["$ip", "email"],
// "keep": ["plan", "amount"],
// "rename": { "amount": "revenue" },
// "set": { "source": "railyard" } }
//
// `where` keeps the events matching every condition (on a property, or on
// `event` / `distinct_id`); then `keep` (an allow list) or `drop` (a deny
// list), `rename` and `set` reshape the properties. Events are never mutated
// in place. Declarative only: there is no code to run, so a transform can
// never reach the network or the database.
import { ApiError } from "../replay/shared/console-guard.ts";
import type { ExportedEvent } from "./runner.ts";
type Scalar = string | number | boolean;
const OPS = ["eq", "neq", "in", "not_in", "exists", "not_exists", "contains", "gt", "lt"] as const;
type Op = (typeof OPS)[number];
export interface Condition {
property: string;
op: Op;
value?: Scalar | Scalar[];
}
export interface Transform {
where?: Condition[];
drop?: string[];
keep?: string[];
rename?: Record<string, string>;
set?: Record<string, Scalar>;
}
const MAX_ITEMS = 50;
const KEY = /^[$A-Za-z0-9_.:\-]{1,200}$/;
const isScalar = (v: unknown): v is Scalar => typeof v === "string" || typeof v === "number" || typeof v === "boolean";
function keyList(v: unknown, what: string): string[] {
if (!Array.isArray(v) || v.length === 0 || v.length > MAX_ITEMS || !v.every((k) => typeof k === "string" && KEY.test(k))) {
throw new ApiError(400, `The transform's ${what} must list 1 to ${MAX_ITEMS} property names.`);
}
return v as string[];
}
/** Validates a transform from the API; `null` when none is given. */
export function checkTransform(raw: unknown): Transform | null {
if (raw === undefined || raw === null) return null;
if (typeof raw !== "object" || Array.isArray(raw)) throw new ApiError(400, "The transform must be an object.");
const r = raw as Record<string, unknown>;
const unknown = Object.keys(r).filter((k) => !["where", "drop", "keep", "rename", "set"].includes(k));
if (unknown.length) throw new ApiError(400, `The transform has unknown fields: ${unknown.join(", ")}.`);
const out: Transform = {};
if (r.where !== undefined) {
if (!Array.isArray(r.where) || r.where.length === 0 || r.where.length > MAX_ITEMS) throw new ApiError(400, `The transform's where must list 1 to ${MAX_ITEMS} conditions.`);
out.where = r.where.map((c, i) => {
const cond = (c ?? {}) as Record<string, unknown>;
if (typeof cond.property !== "string" || !KEY.test(cond.property)) throw new ApiError(400, `Condition ${i + 1} needs a property name.`);
if (typeof cond.op !== "string" || !(OPS as readonly string[]).includes(cond.op)) throw new ApiError(400, `Condition ${i + 1} has an unknown op; use ${OPS.join(", ")}.`);
const op = cond.op as Op;
if (op === "exists" || op === "not_exists") return { property: cond.property, op };
if (op === "in" || op === "not_in") {
if (!Array.isArray(cond.value) || cond.value.length === 0 || cond.value.length > MAX_ITEMS || !cond.value.every(isScalar)) {
throw new ApiError(400, `Condition ${i + 1} needs a list of 1 to ${MAX_ITEMS} values.`);
}
return { property: cond.property, op, value: cond.value as Scalar[] };
}
if ((op === "gt" || op === "lt") && typeof cond.value !== "number") throw new ApiError(400, `Condition ${i + 1} needs a number.`);
if (!isScalar(cond.value)) throw new ApiError(400, `Condition ${i + 1} needs a value.`);
return { property: cond.property, op, value: cond.value };
});
}
if (r.drop !== undefined && r.keep !== undefined) throw new ApiError(400, "Use keep or drop in a transform, not both.");
if (r.drop !== undefined) out.drop = keyList(r.drop, "drop");
if (r.keep !== undefined) out.keep = keyList(r.keep, "keep");
for (const [field, label] of [["rename", "rename"], ["set", "set"]] as const) {
const m = r[field];
if (m === undefined) continue;
if (!m || typeof m !== "object" || Array.isArray(m)) throw new ApiError(400, `The transform's ${label} must be an object.`);
const entries = Object.entries(m as Record<string, unknown>);
if (entries.length === 0 || entries.length > MAX_ITEMS) throw new ApiError(400, `The transform's ${label} must have 1 to ${MAX_ITEMS} entries.`);
for (const [k, v] of entries) {
if (!KEY.test(k)) throw new ApiError(400, `The transform's ${label} has an invalid property name.`);
if (field === "rename" && (typeof v !== "string" || !KEY.test(v))) throw new ApiError(400, "The transform's rename must map names to names.");
if (field === "set" && (!isScalar(v) || (typeof v === "string" && v.length > 1000))) throw new ApiError(400, "The transform's set values must be short text, numbers or true/false.");
}
if (field === "rename") out.rename = m as Record<string, string>;
else out.set = m as Record<string, Scalar>;
}
return Object.keys(out).length ? out : null;
}
function valueOf(e: ExportedEvent, property: string): unknown {
if (property === "event") return e.event;
if (property === "distinct_id") return e.distinct_id;
return e.properties?.[property];
}
function matches(e: ExportedEvent, c: Condition): boolean {
const v = valueOf(e, c.property);
switch (c.op) {
case "exists":
return v !== undefined && v !== null;
case "not_exists":
return v === undefined || v === null;
case "eq":
return v === c.value || (v !== undefined && v !== null && String(v) === String(c.value));
case "neq":
return !(v === c.value || (v !== undefined && v !== null && String(v) === String(c.value)));
case "in":
return (c.value as Scalar[]).some((x) => v !== undefined && v !== null && String(v) === String(x));
case "not_in":
return !(c.value as Scalar[]).some((x) => v !== undefined && v !== null && String(v) === String(x));
case "contains":
return typeof v === "string" && v.includes(String(c.value));
case "gt":
return typeof v === "number" ? v > (c.value as number) : Number(v) > (c.value as number);
case "lt":
return typeof v === "number" ? v < (c.value as number) : Number(v) < (c.value as number);
}
}
function reshape(props: Record<string, unknown>, t: Transform): Record<string, unknown> {
let out: Record<string, unknown> = t.keep
? Object.fromEntries(Object.entries(props).filter(([k]) => t.keep!.includes(k)))
: t.drop
? Object.fromEntries(Object.entries(props).filter(([k]) => !t.drop!.includes(k)))
: { ...props };
if (t.rename) {
out = Object.fromEntries(Object.entries(out).map(([k, v]) => [t.rename![k] ?? k, v]));
}
if (t.set) out = { ...out, ...t.set };
return out;
}
/** The events a destination receives: filtered, then reshaped (new objects). */
export function applyTransform<T extends ExportedEvent>(t: Transform | null | undefined, events: T[]): T[] {
if (!t) return events;
return events
.filter((e) => (t.where ?? []).every((c) => matches(e, c)))
.map((e) => (t.drop || t.keep || t.rename || t.set ? { ...e, properties: reshape(e.properties ?? {}, t) } : e));
}

View File

@ -17,6 +17,7 @@ import { surveyTargetingAnswers } from "../../src/surveys/targeting.ts";
import { targetingFlagKey } from "../../src/surveys/model.ts";
import { makeSite, migratedPg, skipNoPg, startService, type Running, type ScratchPg } from "../a1/helpers.ts";
import { api, insertEvents, SECRET, waitFor, type Row } from "./helpers.ts";
import { sdkEsmPath, sdkPackageDir } from "../sdk-deps.ts";
const HERE = dirname(fileURLToPath(import.meta.url));
const PKG = join(HERE, "../../../../packages/analytics-js");
@ -183,7 +184,7 @@ test("web example: the survey shows on the targeted page in Chromium and its ans
</script></body></html>`;
const files: Record<string, [string, string]> = {
"/checkout": [page, "text/html"],
"/vendor/sdk.mjs": [readFileSync(join(PKG, "node_modules/posthog-js/dist/module.mjs"), "utf8"), "text/javascript"],
"/vendor/sdk.mjs": [readFileSync(sdkEsmPath(PKG), "utf8"), "text/javascript"],
"/pkg/index.mjs": [readFileSync(join(PKG, "src/index.mjs"), "utf8"), "text/javascript"],
"/pkg/env.mjs": [readFileSync(join(PKG, "src/env.mjs"), "utf8"), "text/javascript"],
};
@ -254,7 +255,7 @@ test("Expo example: the React Native SDK reads the survey, matches it on the dev
let surveys: Record<string, unknown>[] = [];
assert.ok(await waitFor(async () => (surveys = await client.getSurveys()).length === 2, 15_000, 200), "the SDK read the surveys from the app's config");
assert.deepEqual(surveys.map((x) => x.id).sort(), [s.id, web.id].sort());
const rnRequire = createRequire(join(PKG, "node_modules/posthog-react-native/package.json"));
const rnRequire = createRequire(join(sdkPackageDir(PKG, "posthog-react-native"), "package.json"));
const { getActiveMatchingSurveys } = rnRequire("./dist/surveys/getActiveMatchingSurveys.js");
const active = getActiveMatchingSurveys(surveys, {}, [], new Set());
assert.deepEqual(active.map((x: { id: string }) => x.id), [s.id], "the page-address survey is web only");

View File

@ -7,6 +7,7 @@ import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { sdkPackageDir } from "../sdk-deps.ts";
const SVC = join(dirname(fileURLToPath(import.meta.url)), "../..");
const sha = (p: string) => createHash("sha256").update(readFileSync(join(SVC, p))).digest("hex").slice(0, 16);
@ -32,9 +33,13 @@ test("vendored files are unchanged and keep their licences", () => {
for (const n of ["public/player/NOTICE", "src/replay/NOTICE", "src/experiments/NOTICE"]) assert.ok(existsSync(join(SVC, n)), n);
});
test("the SDK parts served at /static/ are the wrapper's SDK version", { skip: existsSync(join(SVC, "../../packages/analytics-js/node_modules/posthog-js/package.json")) ? false : "wrapper dependencies not installed" }, () => {
const wrapper = join(SVC, "../../packages/analytics-js/node_modules/posthog-js");
test("the SDK parts served at /static/ are the wrapper's SDK version", () => {
const pkg = join(SVC, "../../packages/analytics-js");
const declared = JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).dependencies["posthog-js"];
// The wrapper's own install, else this service's pin of the same version.
const wrapper = sdkPackageDir(pkg, "posthog-js");
const version = JSON.parse(readFileSync(join(wrapper, "package.json"), "utf8")).version;
assert.equal(version, declared, "the installed SDK is the wrapper's pinned version");
assert.equal(JSON.parse(readFileSync(join(SVC, "public/player/sdk/package.json"), "utf8")).version, version);
for (const f of ["lazy-recorder.js", "surveys.js", "dead-clicks-autocapture.js"]) assert.ok(readFileSync(join(wrapper, "dist", f)).equals(readFileSync(join(SVC, "public/player/sdk", f))), f);
});

View File

@ -244,4 +244,8 @@ test("console forms map to what the service takes", async () => {
secret: "{}",
});
assert.equal(destinationTarget({ kind: "bigquery", config: { project_id: "p", dataset: "d", table: "t" } }), "BigQuery table p.d.t");
// A23: the transform field is parsed as JSON (and passed through when it is not JSON).
assert.deepEqual(destinationFromForm({ name: "T", kind: "webhook", url: "https://h.example/x", transform: '{"drop":["email"]}' }).transform, { drop: ["email"] });
assert.equal(destinationFromForm({ name: "T", kind: "webhook", url: "https://h.example/x", transform: "not json" }).transform, "not json");
assert.equal("transform" in destinationFromForm({ name: "T", kind: "webhook", url: "https://h.example/x", transform: " " }), false);
});

View File

@ -0,0 +1,107 @@
// A23: destination transforms. A destination receives only the events its
// `where` keeps, with properties reshaped by keep/drop, rename and set; the
// cursor still moves past every row read; a transform can be replaced or
// removed later; bad transforms are refused with 400.
import { before, test } from "node:test";
import assert from "node:assert/strict";
import { randomBytes } from "node:crypto";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { CURSOR_LAG_MS, runExports, type ExportedEvent } from "../../src/exports/runner.ts";
import { applyTransform, checkTransform } from "../../src/exports/transform.ts";
import { silentLogger } from "../../src/log.ts";
import { makeSite, migratedPg, skipNoPg, startService, type Running, type ScratchPg } from "../a1/helpers.ts";
import { api, insertEvents, SECRET, type Row } from "../a3/helpers.ts";
process.env.PA_EXPORTS_KEY = randomBytes(32).toString("base64");
process.env.PA_EXPORTS_ALLOW_PRIVATE = "1";
let pg: ScratchPg;
let run: Running;
let base = "";
const bodies: string[] = [];
const site = makeSite({ name: "shop" });
let now = new Date(Math.ceil(Date.now() / 3600_000) * 3600_000);
const later = () => (now = new Date(now.getTime() + CURSOR_LAG_MS + 3600_000));
before(async () => {
if (skipNoPg) return;
const srv = createServer((req, res) => {
let body = "";
req.on("data", (d) => (body += d));
req.on("end", () => {
bodies.push(body);
res.writeHead(200).end("{}");
});
});
await new Promise<void>((r) => srv.listen(0, "127.0.0.1", () => r()));
base = `http://127.0.0.1:${(srv.address() as AddressInfo).port}`;
pg = await migratedPg();
run = await startService(pg, [site], { consoleSecret: SECRET, now: () => now });
});
const e = (event: string, properties: Record<string, unknown>): ExportedEvent => ({
uuid: `u-${event}-${JSON.stringify(properties)}`,
event,
distinct_id: "d1",
person_id: "p1",
timestamp: "2026-10-06T10:00:00.000Z",
properties,
elements_chain: null,
session_id: null,
});
test("where keeps matching events; keep/drop, rename and set reshape without mutating", () => {
const events = [e("purchase", { plan: "pro", amount: 30, email: "a@x.io" }), e("purchase", { plan: "free", amount: 0 }), e("signup", { plan: "pro" })];
const t = checkTransform({ where: [{ property: "event", op: "eq", value: "purchase" }, { property: "amount", op: "gt", value: 10 }], drop: ["email"], rename: { amount: "revenue" }, set: { source: "railyard" } });
const out = applyTransform(t, events);
assert.deepEqual(out.map((x) => x.properties), [{ plan: "pro", revenue: 30, source: "railyard" }]);
assert.equal(events[0].properties.email, "a@x.io", "the input events are untouched");
const kept = applyTransform(checkTransform({ keep: ["plan"], where: [{ property: "plan", op: "in", value: ["pro", "team"] }] }), events);
assert.deepEqual(kept.map((x) => x.properties), [{ plan: "pro" }, { plan: "pro" }]);
assert.equal(applyTransform(checkTransform({ where: [{ property: "email", op: "exists" }] }), events).length, 1);
assert.equal(applyTransform(null, events), events);
});
test("bad transforms are refused", () => {
for (const bad of [[], { where: [] }, { where: [{ property: "x", op: "like", value: 1 }] }, { where: [{ property: "x", op: "gt", value: "a" }] }, { keep: ["a"], drop: ["b"] }, { rename: { a: 1 } }, { set: { a: { nested: 1 } } }, { run: "code" }]) {
assert.throws(() => checkTransform(bad), /transform|Condition/i, JSON.stringify(bad));
}
assert.equal(checkTransform(null), null);
});
test("a webhook destination receives only what its transform keeps; the transform can be replaced and removed", { skip: skipNoPg }, async () => {
const made = await api(run, site, "/exports", {
now,
body: { name: "pro-only", kind: "webhook", start: "all", config: { url: `${base}/hook` }, transform: { where: [{ property: "plan", op: "eq", value: "pro" }], keep: ["plan"] } },
});
assert.equal(made.status, 201, JSON.stringify(made.body));
assert.deepEqual(made.body.destination.config.transform.keep, ["plan"]);
const rows: Row[] = [
{ event: "purchase", distinct_id: "a", timestamp: new Date(now.getTime() - 1000), properties: { plan: "pro", email: "a@x.io" } },
{ event: "purchase", distinct_id: "b", timestamp: new Date(now.getTime() - 1000), properties: { plan: "free" } },
];
await insertEvents(pg, site.project_id, rows);
bodies.length = 0;
await runExports(run.svc.deps.db, later(), { log: silentLogger });
assert.equal(bodies.length, 1);
const sent = JSON.parse(bodies[0]).events;
assert.deepEqual(sent.map((x: { distinct_id: string; properties: unknown }) => [x.distinct_id, x.properties]), [["a", { plan: "pro" }]]);
// Only filtered-out events: nothing is sent, the cursor still moves.
await insertEvents(pg, site.project_id, [{ event: "purchase", distinct_id: "c", timestamp: new Date(now.getTime() + 1000), properties: { plan: "free" } }]);
bodies.length = 0;
await runExports(run.svc.deps.db, later(), { log: silentLogger });
assert.equal(bodies.length, 0);
const d1 = (await api(run, site, `/exports/${made.body.destination.id}`, { now })).body.destination;
assert.equal(d1.status, "ok");
// Replace, then remove the transform.
const put = await api(run, site, `/exports/${made.body.destination.id}`, { now, method: "PUT", body: { transform: { set: { source: "rail" } } } });
assert.equal(put.status, 200, JSON.stringify(put.body));
assert.deepEqual(put.body.destination.config.transform, { set: { source: "rail" } });
assert.equal((await api(run, site, `/exports/${made.body.destination.id}`, { now, method: "PUT", body: { transform: { where: [] } } })).status, 400);
const cleared = await api(run, site, `/exports/${made.body.destination.id}`, { now, method: "PUT", body: { transform: null } });
assert.equal(cleared.body.destination.config.transform, undefined);
assert.equal(cleared.body.destination.config.url, `${base}/hook`, "the rest of the config stays");
});

View File

@ -30,3 +30,9 @@ export function sdkEsmPath(pkgDir: string): string {
const own = join(pkgDir, "node_modules/posthog-js/dist/module.mjs");
return existsSync(own) ? own : join(SERVICE_ROOT, "node_modules/posthog-js/dist/module.mjs");
}
/** An upstream SDK package's directory: the package's own install, else this service's. */
export function sdkPackageDir(pkgDir: string, name: string): string {
const own = join(pkgDir, "node_modules", name);
return existsSync(own) ? own : join(SERVICE_ROOT, "node_modules", name);
}