@shware/workflow-ui 2.0.6 → 2.1.2
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 -2
- package/dist/cli.mjs +42 -7
- package/dist/cli.mjs.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/postgres.d.mts +12 -1
- package/dist/postgres.d.mts.map +1 -1
- package/dist/postgres.mjs +10 -2
- package/dist/postgres.mjs.map +1 -1
- package/package.json +2 -2
- package/src/app/locales/en-US/common.ts +2 -0
- package/src/app/locales/zh-CN/common.ts +2 -0
- package/src/app/routes/metrics.tsx +87 -12
- package/src/components/node-inspector.tsx +3 -7
- package/src/components/templates-page.tsx +7 -0
- package/src/postgres.ts +16 -5
- package/src/server.ts +37 -1
- package/src/utils/lookup.ts +5 -1
package/dist/postgres.d.mts
CHANGED
|
@@ -24,11 +24,22 @@ export interface PostgresStatsOptions {
|
|
|
24
24
|
/** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */
|
|
25
25
|
config: JourneyConfig;
|
|
26
26
|
connectionString: string;
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Which `runtime` entry the data was written under; `production` by default. A fast-forwarded
|
|
29
|
+
* environment stretches every date by its `timeScale`, so name the environment the database
|
|
30
|
+
* belongs to: a production database read as `development` had every journey day plotted as
|
|
31
|
+
* minutes.
|
|
32
|
+
*/
|
|
28
33
|
environment?: string;
|
|
29
34
|
/** The zone the Studio's days are cut in; this machine's by default. */
|
|
30
35
|
timeZone?: string;
|
|
31
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* The time scale the data was written at: the config's `runtime` entry for `environment`,
|
|
39
|
+
* `production` when none is named. The old default, `development`, read a production database
|
|
40
|
+
* at the fast-forwarded scale and plotted every journey day as minutes.
|
|
41
|
+
*/
|
|
42
|
+
export declare function statsTimeScale(config: JourneyConfig, environment?: string): number;
|
|
32
43
|
export declare function postgresStats(options: PostgresStatsOptions): StatsSource;
|
|
33
44
|
//#endregion
|
|
34
45
|
//# sourceMappingURL=postgres.d.mts.map
|
package/dist/postgres.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.d.mts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBA+BiB;;EAEf,QAAQ;EACR;;EAEA
|
|
1
|
+
{"version":3,"file":"postgres.d.mts","names":[],"sources":["../src/postgres.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBA+BiB;;EAEf,QAAQ;EACR;;;;;;;EAOA;;EAEA;;;;;;;wBA6Bc,eAAe,QAAQ,eAAe;wBAItC,cAAc,SAAS,uBAAuB"}
|
package/dist/postgres.mjs
CHANGED
|
@@ -22,12 +22,20 @@ function pool(connectionString) {
|
|
|
22
22
|
}
|
|
23
23
|
return sql;
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* The time scale the data was written at: the config's `runtime` entry for `environment`,
|
|
27
|
+
* `production` when none is named. The old default, `development`, read a production database
|
|
28
|
+
* at the fast-forwarded scale and plotted every journey day as minutes.
|
|
29
|
+
*/
|
|
30
|
+
function statsTimeScale(config, environment = "production") {
|
|
31
|
+
return resolveRuntime(config.runtime, environment).timeScale;
|
|
32
|
+
}
|
|
25
33
|
function postgresStats(options) {
|
|
26
34
|
const sql = pool(options.connectionString);
|
|
27
35
|
const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;
|
|
28
36
|
/** A table of the engine's schema. */
|
|
29
37
|
const t = (name) => sql(`${schema}.${name}`);
|
|
30
|
-
const scale =
|
|
38
|
+
const scale = statsTimeScale(options.config, options.environment);
|
|
31
39
|
const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
32
40
|
/**
|
|
33
41
|
* The moment the journey clock reads "now": the latest activity in the data, so a
|
|
@@ -308,6 +316,6 @@ function postgresStats(options) {
|
|
|
308
316
|
});
|
|
309
317
|
}
|
|
310
318
|
//#endregion
|
|
311
|
-
export { postgresStats };
|
|
319
|
+
export { postgresStats, statsTimeScale };
|
|
312
320
|
|
|
313
321
|
//# sourceMappingURL=postgres.mjs.map
|
package/dist/postgres.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["import { type JourneyConfig, resolveRuntime } from '@shware/workflow';\nimport { DEFAULT_SCHEMA } from '@shware/workflow/store';\nimport postgres from 'postgres';\nimport {\n type Granularity,\n type MetricChannel,\n type StatsRange,\n type StatsSource,\n defineStats,\n} from './config';\n\n/**\n * `@shware/workflow-ui/postgres` — the Studio's numbers read straight from the reporting a\n * journeyWorker on Postgres keeps (the engine's schema, `database.schema` in the config). The\n * Studio runs a stats source on its dev server, never in the browser, so it connects with a real\n * connection string:\n *\n * // workflow.stats.ts\n * export default postgresStats({ config, connectionString: process.env.STATS_DATABASE_URL });\n *\n * Time: a fast-forwarded environment (`runtime.<environment>.timeScale`) plays a journey day out\n * in minutes, so every timestamp is read on the journey's clock — `now - (anchor - t) ×\n * timeScale`, the anchor being the latest activity — and the Studio's date ranges are mapped back\n * the same way. A local run of an hour then reads as weeks of history; production (scale 1) is\n * unchanged.\n *\n * Days: the Studio's dates are the viewer's calendar days, so buckets are cut in the same time\n * zone (this machine's by default). Cut in UTC instead, \"today\" east of Greenwich is an empty\n * bucket on every chart.\n */\n\nexport interface PostgresStatsOptions {\n /** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */\n config: JourneyConfig;\n connectionString: string;\n /** Which `runtime` entry the data was written under; `development` by default. */\n environment?: string;\n /** The zone the Studio's days are cut in; this machine's by default. */\n timeZone?: string;\n}\n\n/** A calendar day `count` days from a `YYYY-MM-DD` one: plain date math, no zone in it. */\nconst addDays = (day: string, count: number) =>\n new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);\n\n/**\n * One pool per database across reloads: the dev server re-evaluates the stats module on every\n * config change, and a pool per evaluation kept its connections open until Postgres ran out.\n */\nconst pools = ((\n globalThis as { __workflowStatsPools?: Map<string, postgres.Sql> }\n).__workflowStatsPools ??= new Map());\n\nfunction pool(connectionString: string): postgres.Sql {\n let sql = pools.get(connectionString);\n if (sql === undefined) {\n sql = postgres(connectionString, { max: 4, idle_timeout: 20, fetch_types: false });\n pools.set(connectionString, sql);\n }\n return sql;\n}\n\nexport function postgresStats(options: PostgresStatsOptions): StatsSource {\n const sql = pool(options.connectionString);\n const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;\n /** A table of the engine's schema. */\n const t = (name: string) => sql(`${schema}.${name}`);\n const scale = resolveRuntime(\n options.config.runtime,\n options.environment ?? 'development'\n ).timeScale;\n const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n /**\n * The moment the journey clock reads \"now\": the latest activity in the data, so a\n * fast-forwarded run keeps reading as the history up to today however long ago it ran —\n * anchored on the real now instead, a run from last night had drifted hundreds of journey days\n * out of every range by morning. Refreshed at the start of every call; with scale 1 it is now.\n */\n let anchor = Date.now();\n\n async function refreshAnchor(): Promise<void> {\n if (scale === 1) {\n anchor = Date.now();\n return;\n }\n const rows = await sql<{ latest: Date | null }[]>`\n select greatest(\n (select max(sent_at) from ${t('message')}),\n (select max(node_at) from ${t('instance')}),\n (select max(finished_at) from ${t('instance')}),\n (select max(taken_at) from ${t('segment_snapshot')})\n ) as latest`;\n const row = rows.at(0);\n const latest =\n row?.latest === null || row?.latest === undefined\n ? Date.now()\n : new Date(row.latest).getTime();\n anchor = Math.min(latest, Date.now());\n }\n\n /** An instant on the journey's clock: `now - (anchor - t) × timeScale`. */\n const onJourneyClock = (instant: postgres.PendingQuery<postgres.Row[]>) =>\n sql`(${new Date().toISOString()}::timestamptz - (${new Date(anchor).toISOString()}::timestamptz - ${instant}) * ${scale}::float)`;\n const virtual = (column: string) => onJourneyClock(sql`${sql(column)}`);\n\n /** A column on the journey's clock, as a wall-clock time in the viewer's zone. */\n const local = (column: string) => sql`(${virtual(column)} at time zone ${timeZone})`;\n\n /** `YYYY-MM-DD` of an instant in the viewer's zone. */\n const localDate = (ms: number) =>\n new Intl.DateTimeFormat('en-CA', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(ms);\n\n /** The instant a local calendar day starts. */\n function startOfLocalDay(day: string): number {\n const utcMidnight = Date.parse(`${day}T00:00:00Z`);\n // The zone's offset at that moment: how far its wall clock reads from UTC\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat('en-US', {\n timeZone,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .formatToParts(utcMidnight)\n .map((part) => [part.type, part.value])\n );\n const n = (type: string) => Number(parts[type] ?? 0);\n const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second'));\n return utcMidnight - (wall - utcMidnight);\n }\n\n /** The real instants a virtual `YYYY-MM-DD` range (both ends inclusive, local days) covers. */\n function realRange({ from, to }: StatsRange): { from: string; to: string } {\n const now = Date.now();\n const back = (ms: number) => new Date(anchor - (now - ms) / scale).toISOString();\n // The end is the start of the next local day, not 24 hours on: a DST day is 23 or 25\n return { from: back(startOfLocalDay(from)), to: back(startOfLocalDay(addDays(to, 1))) };\n }\n\n /**\n * When a copy reached its recipient: the transport's acceptance for email and Android, the\n * device's own report for iOS and the web — a push APNs or a push service accepted can still\n * never arrive (the app was deleted, the device stayed off). An app version without the\n * reporting extension shows its iOS pushes undelivered.\n */\n const reached = sql`(case when m.channel in ('push_ios', 'push_web') then m.device_delivered_at else m.delivered_at end)`;\n\n /**\n * A converted instance: `converted_at` is set whatever the status (with `exitOnMatch: false` a\n * conversion ends `completed`); rows written before the column existed only had status `goal`.\n */\n const converted = sql`(converted_at is not null or status = 'goal')`;\n\n const channelFilter = (channel: MetricChannel | undefined) =>\n channel === undefined ? sql`true` : sql`m.channel = ${channel}`;\n\n /** The last 14 journey days, oldest first, as local `YYYY-MM-DD`. */\n function lastDays(count = 14): string[] {\n const today = localDate(Date.now());\n return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)));\n }\n\n return defineStats({\n async reports() {\n await refreshAnchor();\n const totals = await sql<\n { id: string; entered: number; active: number; completed: number; converted: number }[]\n >`\n select workflow as id,\n count(*)::int as entered,\n count(*) filter (where status = 'running')::int as active,\n count(*) filter (where status in ('completed', 'exited', 'exit_when', 'goal'))::int as completed,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')} group by workflow`;\n const engagement = await sql<\n { id: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m group by workflow`;\n const days = lastDays();\n const series = await sql<\n { id: string; day: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id, to_char(${local('delivered_at')}, 'YYYY-MM-DD') as day,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m where delivered_at is not null\n group by 1, 2`;\n const conversions = await sql<{ id: string; day: string; converted: number }[]>`\n select workflow as id,\n to_char(${onJourneyClock(sql`coalesce(converted_at, finished_at)`)} at time zone ${timeZone}, 'YYYY-MM-DD') as day,\n count(*)::int as converted\n from ${t('instance')} where ${converted} group by 1, 2`;\n const daily = (id: string, rows: { id: string; day: string }[], key: string) =>\n days.map(\n (day) =>\n (\n rows.find((r) => r.id === id && r.day === day) as Record<string, number> | undefined\n )?.[key] ?? 0\n );\n return totals.map((total) => {\n const e = engagement.find((row) => row.id === total.id);\n return {\n id: total.id,\n entered: total.entered,\n active: total.active,\n completed: total.completed,\n converted: total.converted,\n delivered: e?.delivered ?? 0,\n opened: e?.opened ?? 0,\n clicked: e?.clicked ?? 0,\n series: {\n delivered: daily(total.id, series, 'delivered'),\n opened: daily(total.id, series, 'opened'),\n clicked: daily(total.id, series, 'clicked'),\n converted: daily(total.id, conversions, 'converted'),\n },\n };\n });\n },\n\n async nodeStats(workflow) {\n await refreshAnchor();\n const rows = await sql<{ node_id: string; users: number }[]>`\n select node_id, count(*)::int as users from ${t('instance')}\n where workflow = ${workflow} and status = 'running' and node_id is not null\n group by node_id`;\n return Object.fromEntries(rows.map((row) => [row.node_id, row.users]));\n },\n\n async metrics(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n const unit: Granularity = query.granularity;\n const bucket = (column: string) =>\n sql`to_char(date_trunc(${unit}, ${local(column)}), 'YYYY-MM-DD')`;\n const messages = await sql<\n {\n day: string;\n sent: number;\n delivered: number;\n opened: number;\n opened_human: number;\n clicked: number;\n clicked_human: number;\n }[]\n >`\n with m as (\n select * from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n ),\n events as (\n select ${bucket('sent_at')} as day, 'sent' as kind, false as human from m\n where sent_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'delivered', false from m\n where ${reached} is not null and delivered_at between ${from} and ${to}\n -- Opens and clicks count against the bucket the message was delivered in (its cohort),\n -- not the day they happened: the rates drawn are opened / delivered, and an open\n -- counted on another day than its delivery reads as 160% on a quiet day\n union all select ${bucket('delivered_at')}, 'opened', human_opened_at is not null from m\n where opened_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'clicked', human_clicked_at is not null from m\n where clicked_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n )\n select day,\n count(*) filter (where kind = 'sent')::int as sent,\n count(*) filter (where kind = 'delivered')::int as delivered,\n count(*) filter (where kind = 'opened')::int as opened,\n count(*) filter (where kind = 'opened' and human)::int as opened_human,\n count(*) filter (where kind = 'clicked')::int as clicked,\n count(*) filter (where kind = 'clicked' and human)::int as clicked_human\n from events group by day`;\n // Users by the bucket they entered in, and how many of each cohort reached the goal: the\n // conversion rate is a share of one group of people, so it stays within 100%\n const cohorts = await sql<{ day: string; entered: number; converted: number }[]>`\n select ${bucket('entered_at')} as day, count(*)::int as entered,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')}\n where workflow = ${workflow} and entered_at between ${from} and ${to}\n group by 1`;\n const buckets = await sql<{ day: string }[]>`\n select to_char(d, 'YYYY-MM-DD') as day\n from generate_series(date_trunc(${unit}, ${query.from}::date), ${query.to}::date, ${`1 ${unit}`}::interval) d`;\n return buckets.map(({ day }) => {\n const m = messages.find((row) => row.day === day);\n const opened = m?.opened ?? 0;\n const clicked = m?.clicked ?? 0;\n const cohort = cohorts.find((row) => row.day === day);\n return {\n date: day,\n sent: m?.sent ?? 0,\n delivered: m?.delivered ?? 0,\n opened,\n openedHuman: m?.opened_human ?? 0,\n openedMachine: opened - (m?.opened_human ?? 0),\n clicked,\n clickedHuman: m?.clicked_human ?? 0,\n clickedMachine: clicked - (m?.clicked_human ?? 0),\n entered: cohort?.entered ?? 0,\n converted: cohort?.converted ?? 0,\n };\n });\n },\n\n async links(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<{ url: string; clicks: number }[]>`\n select c.url, count(*)::int as clicks\n from ${t('message_click')} c\n join ${t('message')} m on m.id = c.message_id\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and c.clicked_at between ${from} and ${to}\n -- People's clicks only: a scanner follows every link, the footer's included\n and not c.machine\n group by c.url order by clicks desc limit 50`;\n },\n\n async messages(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<\n {\n nodeId: string;\n template: string;\n channel: MetricChannel;\n sent: number;\n delivered: number;\n opened: number;\n clicked: number;\n unsubscribed: number;\n }[]\n >`\n select node_id as \"nodeId\", template, channel,\n count(*)::int as sent,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked,\n count(unsubscribed_at)::int as unsubscribed\n from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and m.sent_at between ${from} and ${to}\n group by node_id, template, channel order by node_id, channel`;\n },\n\n async segments() {\n await refreshAnchor();\n const sizes = await sql<{ id: string; size: number }[]>`\n select s.id, count(m.user_id)::int as size\n from ${t('segment')} s\n left join ${t('segment_member')} m on m.segment = s.id\n group by s.id`;\n const days = lastDays();\n // The last snapshot of each journey day\n const snapshots = await sql<{ id: string; day: string; size: number }[]>`\n select distinct on (segment, day) segment as id, day, size from (\n select segment, size, taken_at, to_char(${local('taken_at')}, 'YYYY-MM-DD') as day\n from ${t('segment_snapshot')}\n ) s order by segment, day, taken_at desc`;\n return sizes.map(({ id, size }) => {\n let last = 0;\n const series = days.map((day) => {\n last = snapshots.find((s) => s.id === id && s.day === day)?.size ?? last;\n return last;\n });\n return { id, size, series };\n });\n },\n\n async profiles(segment, { limit, offset }) {\n await refreshAnchor();\n const counts = await sql<{ total: number }[]>`\n select count(*)::int as total from ${t('segment_member')} where segment = ${segment}`;\n const count = counts.at(0);\n // \"Created\" is the user's first event: the engine knows nothing older about them\n const rows = await sql<\n { id: string; props: Record<string, unknown> | null; created_at: Date | null }[]\n >`\n select m.user_id as id, p.props,\n ${onJourneyClock(sql`first_event.ts`)} as created_at\n from ${t('segment_member')} m\n left join ${t('profile')} p on p.user_id = m.user_id\n left join lateral (\n select min(ts) as ts from ${t('event')} e where e.user_id = m.user_id\n ) first_event on true\n where m.segment = ${segment}\n order by m.ts desc, m.user_id\n limit ${limit} offset ${offset}`;\n return {\n total: count?.total ?? 0,\n profiles: rows.map(({ id, props, created_at }) => {\n const { email, ...properties } = props ?? {};\n const profile: { id: string; email?: string; createdAt?: string } & {\n properties: Record<string, unknown>;\n } = { id, properties };\n if (typeof email === 'string') profile.email = email;\n if (created_at !== null) profile.createdAt = new Date(created_at).toISOString();\n return profile;\n }),\n };\n },\n });\n}\n"],"mappings":";;;;;;AA0CA,MAAM,WAAW,KAAa,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EAAE,OAAO,MAAM,EAAE,QAAQ,GAAG,CAAC,EAAE,QAAQ;MACpE,OAAO;KACT,CACwB;IAAE;GAC5B,CAAC;EACH;EAEA,MAAM,SAAS,SAAS,EAAE,OAAO,UAAU;GACzC,MAAM,cAAc;GAGpB,MAAM,SAAQ,MAFO,GAAwB;6CACN,EAAE,gBAAgB,EAAE,mBAAmB,UAAA,CACzD,GAAG,CAAC;GAEzB,MAAM,OAAO,MAAM,GAElB;;YAEK,eAAe,GAAG,gBAAgB,EAAE;eACjC,EAAE,gBAAgB,EAAE;oBACf,EAAE,SAAS,EAAE;;sCAEK,EAAE,OAAO,EAAE;;4BAErB,QAAQ;;gBAEpB,MAAM,UAAU;GAC1B,OAAO;IACL,OAAO,OAAO,SAAS;IACvB,UAAU,KAAK,KAAK,EAAE,IAAI,OAAO,iBAAiB;KAChD,MAAM,EAAE,OAAO,GAAG,eAAe,SAAS,CAAC;KAC3C,MAAM,UAEF;MAAE;MAAI;KAAW;KACrB,IAAI,OAAO,UAAU,UAAU,QAAQ,QAAQ;KAC/C,IAAI,eAAe,MAAM,QAAQ,YAAY,IAAI,KAAK,UAAU,CAAC,CAAC,YAAY;KAC9E,OAAO;IACT,CAAC;GACH;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"postgres.mjs","names":[],"sources":["../src/postgres.ts"],"sourcesContent":["import { type JourneyConfig, resolveRuntime } from '@shware/workflow';\nimport { DEFAULT_SCHEMA } from '@shware/workflow/store';\nimport postgres from 'postgres';\nimport {\n type Granularity,\n type MetricChannel,\n type StatsRange,\n type StatsSource,\n defineStats,\n} from './config';\n\n/**\n * `@shware/workflow-ui/postgres` — the Studio's numbers read straight from the reporting a\n * journeyWorker on Postgres keeps (the engine's schema, `database.schema` in the config). The\n * Studio runs a stats source on its dev server, never in the browser, so it connects with a real\n * connection string:\n *\n * // workflow.stats.ts\n * export default postgresStats({ config, connectionString: process.env.STATS_DATABASE_URL });\n *\n * Time: a fast-forwarded environment (`runtime.<environment>.timeScale`) plays a journey day out\n * in minutes, so every timestamp is read on the journey's clock — `now - (anchor - t) ×\n * timeScale`, the anchor being the latest activity — and the Studio's date ranges are mapped back\n * the same way. A local run of an hour then reads as weeks of history; production (scale 1) is\n * unchanged.\n *\n * Days: the Studio's dates are the viewer's calendar days, so buckets are cut in the same time\n * zone (this machine's by default). Cut in UTC instead, \"today\" east of Greenwich is an empty\n * bucket on every chart.\n */\n\nexport interface PostgresStatsOptions {\n /** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */\n config: JourneyConfig;\n connectionString: string;\n /**\n * Which `runtime` entry the data was written under; `production` by default. A fast-forwarded\n * environment stretches every date by its `timeScale`, so name the environment the database\n * belongs to: a production database read as `development` had every journey day plotted as\n * minutes.\n */\n environment?: string;\n /** The zone the Studio's days are cut in; this machine's by default. */\n timeZone?: string;\n}\n\n/** A calendar day `count` days from a `YYYY-MM-DD` one: plain date math, no zone in it. */\nconst addDays = (day: string, count: number) =>\n new Date(Date.parse(`${day}T00:00:00Z`) + count * 86_400_000).toISOString().slice(0, 10);\n\n/**\n * One pool per database across reloads: the dev server re-evaluates the stats module on every\n * config change, and a pool per evaluation kept its connections open until Postgres ran out.\n */\nconst pools = ((\n globalThis as { __workflowStatsPools?: Map<string, postgres.Sql> }\n).__workflowStatsPools ??= new Map());\n\nfunction pool(connectionString: string): postgres.Sql {\n let sql = pools.get(connectionString);\n if (sql === undefined) {\n sql = postgres(connectionString, { max: 4, idle_timeout: 20, fetch_types: false });\n pools.set(connectionString, sql);\n }\n return sql;\n}\n\n/**\n * The time scale the data was written at: the config's `runtime` entry for `environment`,\n * `production` when none is named. The old default, `development`, read a production database\n * at the fast-forwarded scale and plotted every journey day as minutes.\n */\nexport function statsTimeScale(config: JourneyConfig, environment = 'production'): number {\n return resolveRuntime(config.runtime, environment).timeScale;\n}\n\nexport function postgresStats(options: PostgresStatsOptions): StatsSource {\n const sql = pool(options.connectionString);\n const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;\n /** A table of the engine's schema. */\n const t = (name: string) => sql(`${schema}.${name}`);\n const scale = statsTimeScale(options.config, options.environment);\n const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n /**\n * The moment the journey clock reads \"now\": the latest activity in the data, so a\n * fast-forwarded run keeps reading as the history up to today however long ago it ran —\n * anchored on the real now instead, a run from last night had drifted hundreds of journey days\n * out of every range by morning. Refreshed at the start of every call; with scale 1 it is now.\n */\n let anchor = Date.now();\n\n async function refreshAnchor(): Promise<void> {\n if (scale === 1) {\n anchor = Date.now();\n return;\n }\n const rows = await sql<{ latest: Date | null }[]>`\n select greatest(\n (select max(sent_at) from ${t('message')}),\n (select max(node_at) from ${t('instance')}),\n (select max(finished_at) from ${t('instance')}),\n (select max(taken_at) from ${t('segment_snapshot')})\n ) as latest`;\n const row = rows.at(0);\n const latest =\n row?.latest === null || row?.latest === undefined\n ? Date.now()\n : new Date(row.latest).getTime();\n anchor = Math.min(latest, Date.now());\n }\n\n /** An instant on the journey's clock: `now - (anchor - t) × timeScale`. */\n const onJourneyClock = (instant: postgres.PendingQuery<postgres.Row[]>) =>\n sql`(${new Date().toISOString()}::timestamptz - (${new Date(anchor).toISOString()}::timestamptz - ${instant}) * ${scale}::float)`;\n const virtual = (column: string) => onJourneyClock(sql`${sql(column)}`);\n\n /** A column on the journey's clock, as a wall-clock time in the viewer's zone. */\n const local = (column: string) => sql`(${virtual(column)} at time zone ${timeZone})`;\n\n /** `YYYY-MM-DD` of an instant in the viewer's zone. */\n const localDate = (ms: number) =>\n new Intl.DateTimeFormat('en-CA', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(ms);\n\n /** The instant a local calendar day starts. */\n function startOfLocalDay(day: string): number {\n const utcMidnight = Date.parse(`${day}T00:00:00Z`);\n // The zone's offset at that moment: how far its wall clock reads from UTC\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat('en-US', {\n timeZone,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n .formatToParts(utcMidnight)\n .map((part) => [part.type, part.value])\n );\n const n = (type: string) => Number(parts[type] ?? 0);\n const wall = Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second'));\n return utcMidnight - (wall - utcMidnight);\n }\n\n /** The real instants a virtual `YYYY-MM-DD` range (both ends inclusive, local days) covers. */\n function realRange({ from, to }: StatsRange): { from: string; to: string } {\n const now = Date.now();\n const back = (ms: number) => new Date(anchor - (now - ms) / scale).toISOString();\n // The end is the start of the next local day, not 24 hours on: a DST day is 23 or 25\n return { from: back(startOfLocalDay(from)), to: back(startOfLocalDay(addDays(to, 1))) };\n }\n\n /**\n * When a copy reached its recipient: the transport's acceptance for email and Android, the\n * device's own report for iOS and the web — a push APNs or a push service accepted can still\n * never arrive (the app was deleted, the device stayed off). An app version without the\n * reporting extension shows its iOS pushes undelivered.\n */\n const reached = sql`(case when m.channel in ('push_ios', 'push_web') then m.device_delivered_at else m.delivered_at end)`;\n\n /**\n * A converted instance: `converted_at` is set whatever the status (with `exitOnMatch: false` a\n * conversion ends `completed`); rows written before the column existed only had status `goal`.\n */\n const converted = sql`(converted_at is not null or status = 'goal')`;\n\n const channelFilter = (channel: MetricChannel | undefined) =>\n channel === undefined ? sql`true` : sql`m.channel = ${channel}`;\n\n /** The last 14 journey days, oldest first, as local `YYYY-MM-DD`. */\n function lastDays(count = 14): string[] {\n const today = localDate(Date.now());\n return Array.from({ length: count }, (_, i) => addDays(today, i - (count - 1)));\n }\n\n return defineStats({\n async reports() {\n await refreshAnchor();\n const totals = await sql<\n { id: string; entered: number; active: number; completed: number; converted: number }[]\n >`\n select workflow as id,\n count(*)::int as entered,\n count(*) filter (where status = 'running')::int as active,\n count(*) filter (where status in ('completed', 'exited', 'exit_when', 'goal'))::int as completed,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')} group by workflow`;\n const engagement = await sql<\n { id: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m group by workflow`;\n const days = lastDays();\n const series = await sql<\n { id: string; day: string; delivered: number; opened: number; clicked: number }[]\n >`\n select workflow as id, to_char(${local('delivered_at')}, 'YYYY-MM-DD') as day,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked\n from ${t('message')} m where delivered_at is not null\n group by 1, 2`;\n const conversions = await sql<{ id: string; day: string; converted: number }[]>`\n select workflow as id,\n to_char(${onJourneyClock(sql`coalesce(converted_at, finished_at)`)} at time zone ${timeZone}, 'YYYY-MM-DD') as day,\n count(*)::int as converted\n from ${t('instance')} where ${converted} group by 1, 2`;\n const daily = (id: string, rows: { id: string; day: string }[], key: string) =>\n days.map(\n (day) =>\n (\n rows.find((r) => r.id === id && r.day === day) as Record<string, number> | undefined\n )?.[key] ?? 0\n );\n return totals.map((total) => {\n const e = engagement.find((row) => row.id === total.id);\n return {\n id: total.id,\n entered: total.entered,\n active: total.active,\n completed: total.completed,\n converted: total.converted,\n delivered: e?.delivered ?? 0,\n opened: e?.opened ?? 0,\n clicked: e?.clicked ?? 0,\n series: {\n delivered: daily(total.id, series, 'delivered'),\n opened: daily(total.id, series, 'opened'),\n clicked: daily(total.id, series, 'clicked'),\n converted: daily(total.id, conversions, 'converted'),\n },\n };\n });\n },\n\n async nodeStats(workflow) {\n await refreshAnchor();\n const rows = await sql<{ node_id: string; users: number }[]>`\n select node_id, count(*)::int as users from ${t('instance')}\n where workflow = ${workflow} and status = 'running' and node_id is not null\n group by node_id`;\n return Object.fromEntries(rows.map((row) => [row.node_id, row.users]));\n },\n\n async metrics(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n const unit: Granularity = query.granularity;\n const bucket = (column: string) =>\n sql`to_char(date_trunc(${unit}, ${local(column)}), 'YYYY-MM-DD')`;\n const messages = await sql<\n {\n day: string;\n sent: number;\n delivered: number;\n opened: number;\n opened_human: number;\n clicked: number;\n clicked_human: number;\n }[]\n >`\n with m as (\n select * from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n ),\n events as (\n select ${bucket('sent_at')} as day, 'sent' as kind, false as human from m\n where sent_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'delivered', false from m\n where ${reached} is not null and delivered_at between ${from} and ${to}\n -- Opens and clicks count against the bucket the message was delivered in (its cohort),\n -- not the day they happened: the rates drawn are opened / delivered, and an open\n -- counted on another day than its delivery reads as 160% on a quiet day\n union all select ${bucket('delivered_at')}, 'opened', human_opened_at is not null from m\n where opened_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n union all select ${bucket('delivered_at')}, 'clicked', human_clicked_at is not null from m\n where clicked_at is not null and ${reached} is not null and delivered_at between ${from} and ${to}\n )\n select day,\n count(*) filter (where kind = 'sent')::int as sent,\n count(*) filter (where kind = 'delivered')::int as delivered,\n count(*) filter (where kind = 'opened')::int as opened,\n count(*) filter (where kind = 'opened' and human)::int as opened_human,\n count(*) filter (where kind = 'clicked')::int as clicked,\n count(*) filter (where kind = 'clicked' and human)::int as clicked_human\n from events group by day`;\n // Users by the bucket they entered in, and how many of each cohort reached the goal: the\n // conversion rate is a share of one group of people, so it stays within 100%\n const cohorts = await sql<{ day: string; entered: number; converted: number }[]>`\n select ${bucket('entered_at')} as day, count(*)::int as entered,\n count(*) filter (where ${converted})::int as converted\n from ${t('instance')}\n where workflow = ${workflow} and entered_at between ${from} and ${to}\n group by 1`;\n const buckets = await sql<{ day: string }[]>`\n select to_char(d, 'YYYY-MM-DD') as day\n from generate_series(date_trunc(${unit}, ${query.from}::date), ${query.to}::date, ${`1 ${unit}`}::interval) d`;\n return buckets.map(({ day }) => {\n const m = messages.find((row) => row.day === day);\n const opened = m?.opened ?? 0;\n const clicked = m?.clicked ?? 0;\n const cohort = cohorts.find((row) => row.day === day);\n return {\n date: day,\n sent: m?.sent ?? 0,\n delivered: m?.delivered ?? 0,\n opened,\n openedHuman: m?.opened_human ?? 0,\n openedMachine: opened - (m?.opened_human ?? 0),\n clicked,\n clickedHuman: m?.clicked_human ?? 0,\n clickedMachine: clicked - (m?.clicked_human ?? 0),\n entered: cohort?.entered ?? 0,\n converted: cohort?.converted ?? 0,\n };\n });\n },\n\n async links(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<{ url: string; clicks: number }[]>`\n select c.url, count(*)::int as clicks\n from ${t('message_click')} c\n join ${t('message')} m on m.id = c.message_id\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and c.clicked_at between ${from} and ${to}\n -- People's clicks only: a scanner follows every link, the footer's included\n and not c.machine\n group by c.url order by clicks desc limit 50`;\n },\n\n async messages(workflow, query) {\n await refreshAnchor();\n const { from, to } = realRange(query);\n return sql<\n {\n nodeId: string;\n template: string;\n channel: MetricChannel;\n sent: number;\n delivered: number;\n opened: number;\n clicked: number;\n unsubscribed: number;\n }[]\n >`\n select node_id as \"nodeId\", template, channel,\n count(*)::int as sent,\n count(${reached})::int as delivered,\n count(opened_at) filter (where ${reached} is not null)::int as opened,\n count(clicked_at) filter (where ${reached} is not null)::int as clicked,\n count(unsubscribed_at)::int as unsubscribed\n from ${t('message')} m\n where m.workflow = ${workflow} and ${channelFilter(query.channel)}\n and m.sent_at between ${from} and ${to}\n group by node_id, template, channel order by node_id, channel`;\n },\n\n async segments() {\n await refreshAnchor();\n const sizes = await sql<{ id: string; size: number }[]>`\n select s.id, count(m.user_id)::int as size\n from ${t('segment')} s\n left join ${t('segment_member')} m on m.segment = s.id\n group by s.id`;\n const days = lastDays();\n // The last snapshot of each journey day\n const snapshots = await sql<{ id: string; day: string; size: number }[]>`\n select distinct on (segment, day) segment as id, day, size from (\n select segment, size, taken_at, to_char(${local('taken_at')}, 'YYYY-MM-DD') as day\n from ${t('segment_snapshot')}\n ) s order by segment, day, taken_at desc`;\n return sizes.map(({ id, size }) => {\n let last = 0;\n const series = days.map((day) => {\n last = snapshots.find((s) => s.id === id && s.day === day)?.size ?? last;\n return last;\n });\n return { id, size, series };\n });\n },\n\n async profiles(segment, { limit, offset }) {\n await refreshAnchor();\n const counts = await sql<{ total: number }[]>`\n select count(*)::int as total from ${t('segment_member')} where segment = ${segment}`;\n const count = counts.at(0);\n // \"Created\" is the user's first event: the engine knows nothing older about them\n const rows = await sql<\n { id: string; props: Record<string, unknown> | null; created_at: Date | null }[]\n >`\n select m.user_id as id, p.props,\n ${onJourneyClock(sql`first_event.ts`)} as created_at\n from ${t('segment_member')} m\n left join ${t('profile')} p on p.user_id = m.user_id\n left join lateral (\n select min(ts) as ts from ${t('event')} e where e.user_id = m.user_id\n ) first_event on true\n where m.segment = ${segment}\n order by m.ts desc, m.user_id\n limit ${limit} offset ${offset}`;\n return {\n total: count?.total ?? 0,\n profiles: rows.map(({ id, props, created_at }) => {\n const { email, ...properties } = props ?? {};\n const profile: { id: string; email?: string; createdAt?: string } & {\n properties: Record<string, unknown>;\n } = { id, properties };\n if (typeof email === 'string') profile.email = email;\n if (created_at !== null) profile.createdAt = new Date(created_at).toISOString();\n return profile;\n }),\n };\n },\n });\n}\n"],"mappings":";;;;;;AA+CA,MAAM,WAAW,KAAa,UAC5B,IAAI,KAAK,KAAK,MAAM,GAAG,IAAI,WAAW,IAAI,QAAQ,KAAU,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE;;;;;AAMzF,MAAM,QAAS,WAEb,yCAAyB,IAAI,IAAI;AAEnC,SAAS,KAAK,kBAAwC;CACpD,IAAI,MAAM,MAAM,IAAI,gBAAgB;CACpC,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,SAAS,kBAAkB;GAAE,KAAK;GAAG,cAAc;GAAI,aAAa;EAAM,CAAC;EACjF,MAAM,IAAI,kBAAkB,GAAG;CACjC;CACA,OAAO;AACT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B,EAAE;eACjC,EAAE,gBAAgB,EAAE;oBACf,EAAE,SAAS,EAAE;;sCAEK,EAAE,OAAO,EAAE;;4BAErB,QAAQ;;gBAEpB,MAAM,UAAU;GAC1B,OAAO;IACL,OAAO,OAAO,SAAS;IACvB,UAAU,KAAK,KAAK,EAAE,IAAI,OAAO,iBAAiB;KAChD,MAAM,EAAE,OAAO,GAAG,eAAe,SAAS,CAAC;KAC3C,MAAM,UAEF;MAAE;MAAI;KAAW;KACrB,IAAI,OAAO,UAAU,UAAU,QAAQ,QAAQ;KAC/C,IAAI,eAAe,MAAM,QAAQ,YAAY,IAAI,KAAK,UAAU,CAAC,CAAC,YAAY;KAC9E,OAAO;IACT,CAAC;GACH;EACF;CACF,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shware/workflow-ui",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.2",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/ShwareHQ/shware-sdk.git"
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"@floating-ui/react": "^0.27.20",
|
|
41
41
|
"@fontsource-variable/inter": "^5.3.0",
|
|
42
42
|
"@react-email/render": "^2.1.1",
|
|
43
|
-
"@shware/workflow": "
|
|
43
|
+
"@shware/workflow": "4.1.1",
|
|
44
44
|
"@tailwindcss/vite": "^4.3.3",
|
|
45
45
|
"@tanstack/react-query": "^5.104.3",
|
|
46
46
|
"@tanstack/react-router": "^1.170.45",
|
|
@@ -58,6 +58,8 @@ export default {
|
|
|
58
58
|
noSourceHint:
|
|
59
59
|
'Add a stats.metrics function to workflow.config.ts to chart the funnel over time.',
|
|
60
60
|
noData: 'No data for this workflow in this range.',
|
|
61
|
+
loading: 'Loading…',
|
|
62
|
+
error: 'Could not load metrics: {{message}}',
|
|
61
63
|
sent: 'Sent',
|
|
62
64
|
delivered: 'Delivered',
|
|
63
65
|
opened: 'Opened',
|
|
@@ -61,6 +61,64 @@ function trendOf(delta: number): Trend {
|
|
|
61
61
|
const asChannel = (value: string): MetricChannel | undefined =>
|
|
62
62
|
METRIC_CHANNELS.find((channel) => channel === value);
|
|
63
63
|
|
|
64
|
+
/* ------------------------------- Query state ------------------------------- */
|
|
65
|
+
|
|
66
|
+
export type StatsStatus = 'pending' | 'error' | 'empty' | 'ready';
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* What a stats-driven panel is looking at. The three non-ready states used to
|
|
70
|
+
* collapse into one "No data": a slow source showed it while loading, and a
|
|
71
|
+
* failing one showed it for good once the toast had gone.
|
|
72
|
+
*/
|
|
73
|
+
export function statsStatus(
|
|
74
|
+
query: { isPending: boolean; isError: boolean },
|
|
75
|
+
count: number
|
|
76
|
+
): StatsStatus {
|
|
77
|
+
if (query.isPending) return 'pending';
|
|
78
|
+
if (query.isError) return 'error';
|
|
79
|
+
return count === 0 ? 'empty' : 'ready';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The message of a failed query, for a line the toast's disappearance does not take away. */
|
|
83
|
+
export function errorMessage(error: unknown): string {
|
|
84
|
+
return error instanceof Error ? error.message : String(error);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The one line a panel shows instead of its data: loading, the failure, or
|
|
89
|
+
* that the range is empty. `role` lets a screen reader tell the three apart
|
|
90
|
+
* the way the copy does.
|
|
91
|
+
*/
|
|
92
|
+
export function StatsNotice({
|
|
93
|
+
status,
|
|
94
|
+
error,
|
|
95
|
+
empty,
|
|
96
|
+
className = 'mt-6 text-sm',
|
|
97
|
+
}: {
|
|
98
|
+
status: Exclude<StatsStatus, 'ready'>;
|
|
99
|
+
error?: unknown;
|
|
100
|
+
/** The empty-state copy: panels word theirs differently. */
|
|
101
|
+
empty: string;
|
|
102
|
+
className?: string;
|
|
103
|
+
}) {
|
|
104
|
+
const { t } = useTranslation();
|
|
105
|
+
if (status === 'pending') {
|
|
106
|
+
return (
|
|
107
|
+
<p role="status" className={`${className} text-muted`}>
|
|
108
|
+
{t('metrics.loading')}
|
|
109
|
+
</p>
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
if (status === 'error') {
|
|
113
|
+
return (
|
|
114
|
+
<p role="alert" className={`${className} text-red-700 dark:text-red-300`}>
|
|
115
|
+
{t('metrics.error', { message: errorMessage(error) })}
|
|
116
|
+
</p>
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return <p className={`${className} text-muted`}>{empty}</p>;
|
|
120
|
+
}
|
|
121
|
+
|
|
64
122
|
/* --------------------------------- Layout --------------------------------- */
|
|
65
123
|
|
|
66
124
|
/**
|
|
@@ -206,12 +264,13 @@ function MetricsTab() {
|
|
|
206
264
|
const ir = lookup(config.workflows, id);
|
|
207
265
|
const workflowName = ir?.id ?? '';
|
|
208
266
|
|
|
209
|
-
const
|
|
267
|
+
const pointsQuery = useQuery({
|
|
210
268
|
queryKey: ['metrics', workflowName, range.from, range.to, granularity, channel ?? ALL],
|
|
211
269
|
queryFn: async () =>
|
|
212
270
|
(await config.stats?.metrics?.(workflowName, { ...range, granularity, channel })) ?? [],
|
|
213
271
|
enabled: ir !== undefined && config.stats?.metrics !== undefined,
|
|
214
272
|
});
|
|
273
|
+
const points = pointsQuery.data;
|
|
215
274
|
|
|
216
275
|
const previous = previousRange(range);
|
|
217
276
|
const { data: previousPoints } = useQuery({
|
|
@@ -221,18 +280,20 @@ function MetricsTab() {
|
|
|
221
280
|
enabled: ir !== undefined && config.stats?.metrics !== undefined,
|
|
222
281
|
});
|
|
223
282
|
|
|
224
|
-
const
|
|
283
|
+
const linksQuery = useQuery({
|
|
225
284
|
queryKey: ['links', workflowName, range.from, range.to, channel ?? ALL],
|
|
226
285
|
queryFn: async () => (await config.stats?.links?.(workflowName, { ...range, channel })) ?? [],
|
|
227
286
|
enabled: ir !== undefined && config.stats?.links !== undefined,
|
|
228
287
|
});
|
|
288
|
+
const links = linksQuery.data;
|
|
229
289
|
|
|
230
|
-
const
|
|
290
|
+
const messagesQuery = useQuery({
|
|
231
291
|
queryKey: ['message-stats', workflowName, range.from, range.to, channel ?? ALL],
|
|
232
292
|
queryFn: async () =>
|
|
233
293
|
(await config.stats?.messages?.(workflowName, { ...range, channel })) ?? [],
|
|
234
294
|
enabled: ir !== undefined && config.stats?.messages !== undefined,
|
|
235
295
|
});
|
|
296
|
+
const messages = messagesQuery.data;
|
|
236
297
|
|
|
237
298
|
/* The same glyphs the message table puts in front of its rows: a channel has
|
|
238
299
|
to read the same in the picker as it does in the data it filters. */
|
|
@@ -364,6 +425,10 @@ function MetricsTab() {
|
|
|
364
425
|
const topLinks = [...(links ?? [])].sort((a, b) => b.clicks - a.clicks).slice(0, LINK_LIMIT);
|
|
365
426
|
const totals = totalsOf(rows.map((entry) => entry.row));
|
|
366
427
|
|
|
428
|
+
const cardsStatus = statsStatus(pointsQuery, buckets.length);
|
|
429
|
+
const messagesStatus = statsStatus(messagesQuery, rows.length);
|
|
430
|
+
const linksStatus = statsStatus(linksQuery, topLinks.length);
|
|
431
|
+
|
|
367
432
|
return (
|
|
368
433
|
<div className="flex-1 p-6">
|
|
369
434
|
<div className="flex flex-wrap items-center gap-2">
|
|
@@ -385,10 +450,10 @@ function MetricsTab() {
|
|
|
385
450
|
/>
|
|
386
451
|
</div>
|
|
387
452
|
|
|
388
|
-
{
|
|
389
|
-
<p className="mt-6 text-sm text-muted">{t('metrics.noData')}</p>
|
|
390
|
-
) : (
|
|
453
|
+
{cardsStatus === 'ready' ? (
|
|
391
454
|
<div className="mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{CARD_KEYS.map(cardOf)}</div>
|
|
455
|
+
) : (
|
|
456
|
+
<StatsNotice status={cardsStatus} error={pointsQuery.error} empty={t('metrics.noData')} />
|
|
392
457
|
)}
|
|
393
458
|
|
|
394
459
|
{config.stats.messages !== undefined && (
|
|
@@ -418,10 +483,15 @@ function MetricsTab() {
|
|
|
418
483
|
</tr>
|
|
419
484
|
</thead>
|
|
420
485
|
<tbody>
|
|
421
|
-
{
|
|
486
|
+
{messagesStatus !== 'ready' ? (
|
|
422
487
|
<tr>
|
|
423
|
-
<td className="px-4 py-4
|
|
424
|
-
|
|
488
|
+
<td className="px-4 py-4" colSpan={MESSAGE_COLUMNS.length + 1}>
|
|
489
|
+
<StatsNotice
|
|
490
|
+
status={messagesStatus}
|
|
491
|
+
error={messagesQuery.error}
|
|
492
|
+
empty={t('metrics.messages.empty')}
|
|
493
|
+
className="text-sm"
|
|
494
|
+
/>
|
|
425
495
|
</td>
|
|
426
496
|
</tr>
|
|
427
497
|
) : (
|
|
@@ -508,10 +578,15 @@ function MetricsTab() {
|
|
|
508
578
|
</tr>
|
|
509
579
|
</thead>
|
|
510
580
|
<tbody>
|
|
511
|
-
{
|
|
581
|
+
{linksStatus !== 'ready' ? (
|
|
512
582
|
<tr>
|
|
513
|
-
<td className="px-5 py-4
|
|
514
|
-
|
|
583
|
+
<td className="px-5 py-4" colSpan={2}>
|
|
584
|
+
<StatsNotice
|
|
585
|
+
status={linksStatus}
|
|
586
|
+
error={linksQuery.error}
|
|
587
|
+
empty={t('metrics.links.empty')}
|
|
588
|
+
className="text-sm"
|
|
589
|
+
/>
|
|
515
590
|
</td>
|
|
516
591
|
</tr>
|
|
517
592
|
) : (
|
|
@@ -161,19 +161,15 @@ function summary(node: NodeIR): { label: string; value: string }[] {
|
|
|
161
161
|
value: branchCase.label ?? '—',
|
|
162
162
|
}));
|
|
163
163
|
case 'cohort':
|
|
164
|
+
// Weights are percentages in the IR (they sum to 100), as the canvas prints them
|
|
164
165
|
return node.arms.map((arm) => ({
|
|
165
166
|
label: arm.name,
|
|
166
|
-
value: `${arm.weight
|
|
167
|
+
value: `${arm.weight}%`,
|
|
167
168
|
}));
|
|
168
169
|
case 'send_event':
|
|
169
170
|
return [{ label: 'event', value: node.event }];
|
|
170
171
|
case 'action':
|
|
171
|
-
return [
|
|
172
|
-
{ label: 'action', value: node.action },
|
|
173
|
-
...(node.codeHash !== undefined
|
|
174
|
-
? [{ label: 'code', value: node.codeHash.slice(0, 12) }]
|
|
175
|
-
: []),
|
|
176
|
-
];
|
|
172
|
+
return [{ label: 'action', value: node.action }];
|
|
177
173
|
default:
|
|
178
174
|
return [];
|
|
179
175
|
}
|
|
@@ -498,6 +498,13 @@ export function TemplatesPage({
|
|
|
498
498
|
<iframe
|
|
499
499
|
title={`${active.key} preview`}
|
|
500
500
|
srcDoc={`${html ?? ''}${NO_SCROLL}${scheme === 'dark' ? DARK_SIMULATION : ''}`}
|
|
501
|
+
/*
|
|
502
|
+
* Same-origin so the document's height is readable below;
|
|
503
|
+
* no allow-scripts, so nothing in the email runs — a script
|
|
504
|
+
* in a template would otherwise run as the studio page and
|
|
505
|
+
* could read /__studio/stats. Same as the thumbnail.
|
|
506
|
+
*/
|
|
507
|
+
sandbox="allow-same-origin"
|
|
501
508
|
/*
|
|
502
509
|
* Sized to its document rather than the pane, so long emails
|
|
503
510
|
* scroll in the outer container — which can pad past the
|
package/src/postgres.ts
CHANGED
|
@@ -33,7 +33,12 @@ export interface PostgresStatsOptions {
|
|
|
33
33
|
/** The project's `workflow.config.ts`: its database schema, and the runtime's time scale. */
|
|
34
34
|
config: JourneyConfig;
|
|
35
35
|
connectionString: string;
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Which `runtime` entry the data was written under; `production` by default. A fast-forwarded
|
|
38
|
+
* environment stretches every date by its `timeScale`, so name the environment the database
|
|
39
|
+
* belongs to: a production database read as `development` had every journey day plotted as
|
|
40
|
+
* minutes.
|
|
41
|
+
*/
|
|
37
42
|
environment?: string;
|
|
38
43
|
/** The zone the Studio's days are cut in; this machine's by default. */
|
|
39
44
|
timeZone?: string;
|
|
@@ -60,15 +65,21 @@ function pool(connectionString: string): postgres.Sql {
|
|
|
60
65
|
return sql;
|
|
61
66
|
}
|
|
62
67
|
|
|
68
|
+
/**
|
|
69
|
+
* The time scale the data was written at: the config's `runtime` entry for `environment`,
|
|
70
|
+
* `production` when none is named. The old default, `development`, read a production database
|
|
71
|
+
* at the fast-forwarded scale and plotted every journey day as minutes.
|
|
72
|
+
*/
|
|
73
|
+
export function statsTimeScale(config: JourneyConfig, environment = 'production'): number {
|
|
74
|
+
return resolveRuntime(config.runtime, environment).timeScale;
|
|
75
|
+
}
|
|
76
|
+
|
|
63
77
|
export function postgresStats(options: PostgresStatsOptions): StatsSource {
|
|
64
78
|
const sql = pool(options.connectionString);
|
|
65
79
|
const schema = options.config.database?.schema ?? DEFAULT_SCHEMA;
|
|
66
80
|
/** A table of the engine's schema. */
|
|
67
81
|
const t = (name: string) => sql(`${schema}.${name}`);
|
|
68
|
-
const scale =
|
|
69
|
-
options.config.runtime,
|
|
70
|
-
options.environment ?? 'development'
|
|
71
|
-
).timeScale;
|
|
82
|
+
const scale = statsTimeScale(options.config, options.environment);
|
|
72
83
|
const timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
73
84
|
|
|
74
85
|
/**
|
package/src/server.ts
CHANGED
|
@@ -4,7 +4,13 @@ import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import tailwindcss from '@tailwindcss/vite';
|
|
6
6
|
import react from '@vitejs/plugin-react';
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
type Plugin,
|
|
9
|
+
type ViteDevServer,
|
|
10
|
+
createServer,
|
|
11
|
+
normalizePath,
|
|
12
|
+
searchForWorkspaceRoot,
|
|
13
|
+
} from 'vite';
|
|
8
14
|
import svgr from 'vite-plugin-svgr';
|
|
9
15
|
import {
|
|
10
16
|
STATS_METHODS,
|
|
@@ -428,6 +434,35 @@ function sourcePosition(cwd: string, rawFile: string, line: number): Located {
|
|
|
428
434
|
return { file: path, line };
|
|
429
435
|
}
|
|
430
436
|
|
|
437
|
+
/** Vite's own `server.fs.deny` default; setting the option replaces it, so it is spelled out. */
|
|
438
|
+
const VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* `server.fs.deny` patterns for files the page must never be served.
|
|
442
|
+
*
|
|
443
|
+
* `fs.allow` covers the whole workspace so the browser can import the
|
|
444
|
+
* template registries, which also made `GET /@fs/<cwd>/workflow.stats.ts`
|
|
445
|
+
* answer with the stats source — a file the README calls server-only, and the
|
|
446
|
+
* one place a connection string is likely to be written as a literal. The
|
|
447
|
+
* browser never imports the config or the stats file (the virtual module
|
|
448
|
+
* imports the registries by their own paths; a registry written inline in the
|
|
449
|
+
* config is refused for this reason), so both are denied outright.
|
|
450
|
+
*
|
|
451
|
+
* Patterns go through picomatch, so the path is spelled literally: its glob
|
|
452
|
+
* characters escaped, slashes normalized the way Vite normalizes the file it
|
|
453
|
+
* checks. A symlinked file is denied under both of its names.
|
|
454
|
+
*/
|
|
455
|
+
export function projectFileDeny(paths: readonly (string | undefined)[]): string[] {
|
|
456
|
+
const deny = new Set<string>();
|
|
457
|
+
for (const path of paths) {
|
|
458
|
+
if (path === undefined) continue;
|
|
459
|
+
const literal = resolve(path);
|
|
460
|
+
deny.add(normalizePath(literal));
|
|
461
|
+
if (existsSync(literal)) deny.add(normalizePath(realpathSync(literal)));
|
|
462
|
+
}
|
|
463
|
+
return [...deny].map((path) => path.replace(/[\\*?[\]{}()!+@]/g, '\\$&'));
|
|
464
|
+
}
|
|
465
|
+
|
|
431
466
|
export interface StartOptions {
|
|
432
467
|
cwd?: string;
|
|
433
468
|
config?: string;
|
|
@@ -474,6 +509,7 @@ export async function startStudio(options: StartOptions = {}): Promise<ViteDevSe
|
|
|
474
509
|
searchForWorkspaceRoot(packageRoot),
|
|
475
510
|
appRoot,
|
|
476
511
|
],
|
|
512
|
+
deny: [...VITE_DEFAULT_DENY, ...projectFileDeny([configPath, statsPath])],
|
|
477
513
|
},
|
|
478
514
|
},
|
|
479
515
|
// The app and the user's project each have their own react; one copy only. One
|
package/src/utils/lookup.ts
CHANGED
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
* looks up comes from outside the type system — a route param, a template ref
|
|
6
6
|
* in the IR — so a miss is ordinary. This states the `| undefined` once, which
|
|
7
7
|
* is what makes the callers' guards real instead of dead code.
|
|
8
|
+
*
|
|
9
|
+
* Own properties only: the registries are plain objects, so a route param of
|
|
10
|
+
* `constructor` or `toString` used to find Object.prototype's and hand the
|
|
11
|
+
* page a function where it expected an IR — a crash instead of a not-found.
|
|
8
12
|
*/
|
|
9
13
|
export function lookup<T>(registry: Record<string, T>, key: string): T | undefined {
|
|
10
|
-
return registry[key];
|
|
14
|
+
return Object.hasOwn(registry, key) ? registry[key] : undefined;
|
|
11
15
|
}
|