@shware/workflow-ui 2.2.8 → 2.2.10
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/dist/cli.mjs +10 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +7 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +51 -7
- package/dist/index.mjs.map +1 -1
- package/dist/postgres.mjs +3 -0
- package/dist/postgres.mjs.map +1 -1
- package/package.json +2 -2
- package/src/app/routes/workflows.tsx +17 -10
- package/src/components/layout.ts +32 -6
- package/src/components/node-inspector.tsx +3 -1
- package/src/components/workflow-canvas.tsx +52 -11
- package/src/postgres.ts +3 -0
- package/src/server.ts +10 -1
package/dist/postgres.mjs
CHANGED
|
@@ -238,10 +238,13 @@ function postgresStats(options) {
|
|
|
238
238
|
select c.url, count(*)::int as clicks
|
|
239
239
|
from ${t("message_click")} c
|
|
240
240
|
join ${t("message")} m on m.id = c.message_id
|
|
241
|
+
join ${t("message_link")} l on l.message_id = c.message_id and l.position = c.position
|
|
241
242
|
where m.workflow = ${workflow} and ${channelFilter(query.channel)}
|
|
242
243
|
and c.clicked_at between ${from} and ${to}
|
|
243
244
|
-- People's clicks only: a scanner follows every link, the footer's included
|
|
244
245
|
and not c.machine
|
|
246
|
+
-- Links of the content only: following the unsubscribe link is not engagement
|
|
247
|
+
and l.purpose is null
|
|
245
248
|
group by c.url order by clicks desc limit 50`;
|
|
246
249
|
},
|
|
247
250
|
async messages(workflow, query) {
|
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 /**\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,QACJ,WACA,yCAAyB,IAAI,IAAI;AAEnC,SAAS,KAA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AEA,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 join ${t('message_link')} l on l.message_id = c.message_id and l.position = c.position\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 -- Links of the content only: following the unsubscribe link is not engagement\n and l.purpose is null\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,QACJ,WACA,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;;;;;;AAOA,SAAgB,eAA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AgB,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.2.
|
|
3
|
+
"version": "2.2.10",
|
|
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.3.1",
|
|
43
|
-
"@shware/workflow": "12.0
|
|
43
|
+
"@shware/workflow": "12.1.0",
|
|
44
44
|
"@tailwindcss/vite": "^4.3.5",
|
|
45
45
|
"@tanstack/react-query": "^5.108.3",
|
|
46
46
|
"@tanstack/react-router": "^1.170.46",
|
|
@@ -191,6 +191,19 @@ export const workflowDetailRoute = createRoute({
|
|
|
191
191
|
|
|
192
192
|
const SELECTION_KEY = 'workflow-ui:canvas-selection';
|
|
193
193
|
|
|
194
|
+
/** The node last selected on `workflowId`'s canvas in this tab, if any. */
|
|
195
|
+
export function rememberedSelection(workflowId: string): string | undefined {
|
|
196
|
+
if (typeof sessionStorage === 'undefined') return undefined;
|
|
197
|
+
return sessionStorage.getItem(`${SELECTION_KEY}:${workflowId}`) ?? undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Keep (or, with no node, forget) the selection of `workflowId`'s canvas: each workflow remembers its own. */
|
|
201
|
+
export function rememberSelection(workflowId: string, nodeId: string | undefined): void {
|
|
202
|
+
const key = `${SELECTION_KEY}:${workflowId}`;
|
|
203
|
+
if (nodeId === undefined) sessionStorage.removeItem(key);
|
|
204
|
+
else sessionStorage.setItem(key, nodeId);
|
|
205
|
+
}
|
|
206
|
+
|
|
194
207
|
function CanvasTab() {
|
|
195
208
|
const { id } = workflowDetailRoute.useParams();
|
|
196
209
|
const { config } = workflowDetailRoute.useRouteContext();
|
|
@@ -201,17 +214,11 @@ function CanvasTab() {
|
|
|
201
214
|
* full-reload the page; without this the panel you were reading vanishes and
|
|
202
215
|
* you lose your place.
|
|
203
216
|
*/
|
|
204
|
-
const [selectedId, setSelectedId] = useState<string | undefined>(() =>
|
|
205
|
-
typeof sessionStorage === 'undefined'
|
|
206
|
-
? undefined
|
|
207
|
-
: (sessionStorage.getItem(`${SELECTION_KEY}:${id}`) ?? undefined)
|
|
208
|
-
);
|
|
217
|
+
const [selectedId, setSelectedId] = useState<string | undefined>(() => rememberedSelection(id));
|
|
209
218
|
const select = useCallback(
|
|
210
|
-
(
|
|
211
|
-
setSelectedId(
|
|
212
|
-
|
|
213
|
-
if (id === undefined) sessionStorage.removeItem(key);
|
|
214
|
-
else sessionStorage.setItem(key, id);
|
|
219
|
+
(nodeId: string | undefined) => {
|
|
220
|
+
setSelectedId(nodeId);
|
|
221
|
+
rememberSelection(id, nodeId);
|
|
215
222
|
},
|
|
216
223
|
[id]
|
|
217
224
|
);
|
package/src/components/layout.ts
CHANGED
|
@@ -65,8 +65,13 @@ export interface CanvasEdge {
|
|
|
65
65
|
source: string;
|
|
66
66
|
target: string;
|
|
67
67
|
label?: string;
|
|
68
|
-
/**
|
|
69
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Label anchor: `target` = the arm's entry corner (real arm); `source` = just below the deciding node (empty pass-through arm).
|
|
70
|
+
* `lane` is the x of the empty arm's own column, set when the straight way down from the
|
|
71
|
+
* deciding node is taken by another arm's cards: the connector then runs down that column and
|
|
72
|
+
* turns back to its target below the arms, with its label hanging in the column.
|
|
73
|
+
*/
|
|
74
|
+
data?: { anchor: 'source' | 'target'; lane?: number };
|
|
70
75
|
}
|
|
71
76
|
|
|
72
77
|
/**
|
|
@@ -108,7 +113,10 @@ const OP_LABEL: Record<string, string> = {
|
|
|
108
113
|
function conditionLabel(c: ConditionIR, fallback: string): string {
|
|
109
114
|
if (c.type === 'segment') return c.segment;
|
|
110
115
|
if (c.type === 'not') return `not ${conditionLabel(c.condition, fallback)}`;
|
|
111
|
-
if (c.type === 'property') {
|
|
116
|
+
if (c.type === 'property' || c.type === 'trigger_payload') {
|
|
117
|
+
// A field of the event that started the journey reads as `trigger.<field>`, apart from a
|
|
118
|
+
// profile property of the same name
|
|
119
|
+
const path = c.type === 'property' ? c.path : `trigger.${c.path}`;
|
|
112
120
|
const op = OP_LABEL[c.op] ?? c.op;
|
|
113
121
|
const value =
|
|
114
122
|
c.op === 'between'
|
|
@@ -118,7 +126,7 @@ function conditionLabel(c: ConditionIR, fallback: string): string {
|
|
|
118
126
|
: c.value !== undefined
|
|
119
127
|
? String(c.value)
|
|
120
128
|
: '';
|
|
121
|
-
return value === '' ? `${
|
|
129
|
+
return value === '' ? `${path} ${op}` : `${path} ${op} ${value}`;
|
|
122
130
|
}
|
|
123
131
|
if (c.type === 'performed') return `did ${c.event}`;
|
|
124
132
|
if (c.type === 'reachable') return `reachable by ${c.channel}`;
|
|
@@ -279,6 +287,7 @@ interface Tail {
|
|
|
279
287
|
id: string;
|
|
280
288
|
label?: string;
|
|
281
289
|
anchor?: 'source' | 'target';
|
|
290
|
+
lane?: number;
|
|
282
291
|
}
|
|
283
292
|
|
|
284
293
|
export function layout(
|
|
@@ -306,7 +315,9 @@ export function layout(
|
|
|
306
315
|
source: t.id,
|
|
307
316
|
target,
|
|
308
317
|
...(t.label !== undefined ? { label: t.label } : {}),
|
|
309
|
-
...(t.anchor !== undefined
|
|
318
|
+
...(t.anchor !== undefined
|
|
319
|
+
? { data: { anchor: t.anchor, ...(t.lane !== undefined ? { lane: t.lane } : {}) } }
|
|
320
|
+
: {}),
|
|
310
321
|
});
|
|
311
322
|
}
|
|
312
323
|
};
|
|
@@ -349,12 +360,27 @@ export function layout(
|
|
|
349
360
|
const groupTop = bottom + FORK_GAP;
|
|
350
361
|
let maxBottom = groupTop;
|
|
351
362
|
const groupTails: Tail[] = [];
|
|
363
|
+
// An empty group rejoins straight down the centre line. With an odd number of arms (a
|
|
364
|
+
// three-way branch with no `otherwise`) an arm's column sits on that line, and the
|
|
365
|
+
// connector would be drawn through its cards: it takes the empty group's own column then
|
|
366
|
+
let left = gx;
|
|
367
|
+
const blocked = groups.some((g, gi) => {
|
|
368
|
+
const right = left + (widths[gi] ?? W);
|
|
369
|
+
const across = g.nodes.length > 0 && left < cx && cx < right;
|
|
370
|
+
left = right + HGAP;
|
|
371
|
+
return across;
|
|
372
|
+
});
|
|
352
373
|
|
|
353
374
|
groups.forEach((g, gi) => {
|
|
354
375
|
const center = gx + (widths[gi] ?? W) / 2;
|
|
355
376
|
if (g.nodes.length === 0) {
|
|
356
377
|
// Empty group: the parent rejoins straight down, so anchor the label right below it
|
|
357
|
-
groupTails.push({
|
|
378
|
+
groupTails.push({
|
|
379
|
+
id: n.id,
|
|
380
|
+
label: g.label,
|
|
381
|
+
anchor: 'source',
|
|
382
|
+
...(blocked ? { lane: center } : {}),
|
|
383
|
+
});
|
|
358
384
|
} else {
|
|
359
385
|
const r = layoutSeq(g.nodes, center, groupTop, [
|
|
360
386
|
{ id: n.id, label: g.label, anchor: 'target' },
|
|
@@ -100,7 +100,9 @@ function conditionFields(condition: ConditionIR, scope: string): NodeField[] {
|
|
|
100
100
|
const own: NodeField[] = [];
|
|
101
101
|
|
|
102
102
|
if (
|
|
103
|
-
(condition.type === 'property' ||
|
|
103
|
+
(condition.type === 'property' ||
|
|
104
|
+
condition.type === 'payload' ||
|
|
105
|
+
condition.type === 'trigger_payload') &&
|
|
104
106
|
condition.value !== undefined
|
|
105
107
|
) {
|
|
106
108
|
own.push({ key: 'value', value: String(condition.value), scope });
|
|
@@ -303,7 +303,7 @@ const edgeLabelStyle: CSSProperties = {
|
|
|
303
303
|
pointerEvents: 'none',
|
|
304
304
|
};
|
|
305
305
|
|
|
306
|
-
type WfEdge = Edge<{ anchor?: 'source' | 'target' }, 'wf'>;
|
|
306
|
+
type WfEdge = Edge<{ anchor?: 'source' | 'target'; lane?: number }, 'wf'>;
|
|
307
307
|
|
|
308
308
|
/* ----------------------------- Connector routing ---------------------------- */
|
|
309
309
|
|
|
@@ -311,6 +311,12 @@ type WfEdge = Edge<{ anchor?: 'source' | 'target' }, 'wf'>;
|
|
|
311
311
|
const BEND = 16;
|
|
312
312
|
/** How far a labelled fork runs straight down before it turns. */
|
|
313
313
|
const FORK_STEM = 28;
|
|
314
|
+
/**
|
|
315
|
+
* How far above its target a lane connector turns back. The layout keeps the arms' last card 72
|
|
316
|
+
* above the node they rejoin at, and that arm's own connector turns halfway down: the lane
|
|
317
|
+
* joins it on the same line.
|
|
318
|
+
*/
|
|
319
|
+
const LANE_REJOIN = 36;
|
|
314
320
|
/** Where a label pill hangs below the deciding node. */
|
|
315
321
|
const LABEL_DROP = 56;
|
|
316
322
|
const DOT_R = 3.5;
|
|
@@ -367,6 +373,39 @@ function orthogonalPath(sx: number, sy: number, tx: number, ty: number, splitY:
|
|
|
367
373
|
].join(' ');
|
|
368
374
|
}
|
|
369
375
|
|
|
376
|
+
/**
|
|
377
|
+
* A pass-through arm's route when the straight way down is taken by another arm's cards (see
|
|
378
|
+
* `CanvasEdge.data.lane`): out to the arm's own empty column like any fork, down that column
|
|
379
|
+
* past the arms, and back in to the target.
|
|
380
|
+
*/
|
|
381
|
+
export function lanePath(
|
|
382
|
+
sx: number,
|
|
383
|
+
sy: number,
|
|
384
|
+
tx: number,
|
|
385
|
+
ty: number,
|
|
386
|
+
lane: number,
|
|
387
|
+
splitY: number
|
|
388
|
+
): string {
|
|
389
|
+
const rejoinY = Math.max(splitY, ty - LANE_REJOIN);
|
|
390
|
+
const out = Math.sign(lane - sx);
|
|
391
|
+
const back = Math.sign(tx - lane);
|
|
392
|
+
const drop = rejoinY - splitY;
|
|
393
|
+
const r1 = Math.max(0, Math.min(BEND, Math.abs(lane - sx) / 2, splitY - sy, drop / 2));
|
|
394
|
+
const r2 = Math.max(0, Math.min(BEND, Math.abs(tx - lane) / 2, drop / 2, ty - rejoinY));
|
|
395
|
+
return [
|
|
396
|
+
`M ${sx} ${sy}`,
|
|
397
|
+
`L ${sx} ${splitY - r1}`,
|
|
398
|
+
corner(sx, splitY - r1, sx, splitY, sx + out * r1, splitY),
|
|
399
|
+
`L ${lane - out * r1} ${splitY}`,
|
|
400
|
+
corner(lane - out * r1, splitY, lane, splitY, lane, splitY + r1),
|
|
401
|
+
`L ${lane} ${rejoinY - r2}`,
|
|
402
|
+
corner(lane, rejoinY - r2, lane, rejoinY, lane + back * r2, rejoinY),
|
|
403
|
+
`L ${tx - back * r2} ${rejoinY}`,
|
|
404
|
+
corner(tx - back * r2, rejoinY, tx, rejoinY, tx, rejoinY + r2),
|
|
405
|
+
`L ${tx} ${ty}`,
|
|
406
|
+
].join(' ');
|
|
407
|
+
}
|
|
408
|
+
|
|
370
409
|
/**
|
|
371
410
|
* Custom edge with an HTML label: SVG EdgeText's height floats with the font's
|
|
372
411
|
* bounding box, and only HTML can be pinned to exact pixels.
|
|
@@ -393,21 +432,23 @@ function WorkflowEdge({
|
|
|
393
432
|
* descends through. A source anchor hangs directly under the deciding node,
|
|
394
433
|
* where the path has already turned away at FORK_STEM, leaving the pill
|
|
395
434
|
* stranded in open space; so for those the stem runs all the way down to the
|
|
396
|
-
* pill and turns behind it.
|
|
435
|
+
* pill and turns behind it. A pass-through arm sent down its own column (a
|
|
436
|
+
* lane) is in the first case: the pill hangs in that column, on the line.
|
|
397
437
|
*/
|
|
398
|
-
const
|
|
438
|
+
const lane = data?.lane;
|
|
439
|
+
const anchoredAtSource = data?.anchor === 'source' && lane === undefined;
|
|
399
440
|
const splitY = label
|
|
400
441
|
? sourceY + (anchoredAtSource ? LABEL_DROP : FORK_STEM)
|
|
401
442
|
: (sourceY + targetY) / 2;
|
|
402
|
-
const path =
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
targetY + HANDLE_INSET,
|
|
407
|
-
splitY
|
|
408
|
-
);
|
|
443
|
+
const path =
|
|
444
|
+
lane === undefined
|
|
445
|
+
? orthogonalPath(sourceX, sourceY - HANDLE_INSET, targetX, targetY + HANDLE_INSET, splitY)
|
|
446
|
+
: lanePath(sourceX, sourceY - HANDLE_INSET, targetX, targetY + HANDLE_INSET, lane, splitY);
|
|
409
447
|
// The label hangs below the split line, pinned to its own arm's column
|
|
410
|
-
const labelPos = {
|
|
448
|
+
const labelPos = {
|
|
449
|
+
x: lane ?? (anchoredAtSource ? sourceX : targetX),
|
|
450
|
+
y: sourceY + LABEL_DROP,
|
|
451
|
+
};
|
|
411
452
|
return (
|
|
412
453
|
<>
|
|
413
454
|
<BaseEdge id={id} path={path} style={style} />
|
package/src/postgres.ts
CHANGED
|
@@ -334,10 +334,13 @@ export function postgresStats(options: PostgresStatsOptions): StatsSource {
|
|
|
334
334
|
select c.url, count(*)::int as clicks
|
|
335
335
|
from ${t('message_click')} c
|
|
336
336
|
join ${t('message')} m on m.id = c.message_id
|
|
337
|
+
join ${t('message_link')} l on l.message_id = c.message_id and l.position = c.position
|
|
337
338
|
where m.workflow = ${workflow} and ${channelFilter(query.channel)}
|
|
338
339
|
and c.clicked_at between ${from} and ${to}
|
|
339
340
|
-- People's clicks only: a scanner follows every link, the footer's included
|
|
340
341
|
and not c.machine
|
|
342
|
+
-- Links of the content only: following the unsubscribe link is not engagement
|
|
343
|
+
and l.purpose is null
|
|
341
344
|
group by c.url order by clicks desc limit 50`;
|
|
342
345
|
},
|
|
343
346
|
|
package/src/server.ts
CHANGED
|
@@ -442,15 +442,24 @@ const VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];
|
|
|
442
442
|
* journey project keeps beside its code. `fs.allow` spans the project and its linked workspace
|
|
443
443
|
* packages (see {@link studioFsAllow}), so without these
|
|
444
444
|
* `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would
|
|
445
|
-
* be one request away for any page that can reach the port.
|
|
445
|
+
* be one request away for any page that can reach the port. The same goes for what sits beside
|
|
446
|
+
* any project: registry and network tokens (`.npmrc`, `.netrc`), direnv's `.envrc` (which
|
|
447
|
+
* `.env.*` does not match), key stores, and the wrangler config with its `vars`.
|
|
446
448
|
*/
|
|
447
449
|
export const STUDIO_FS_DENY: readonly string[] = [
|
|
448
450
|
...VITE_DEFAULT_DENY,
|
|
449
451
|
'**/.dev.vars*',
|
|
452
|
+
'**/.envrc',
|
|
453
|
+
'**/.npmrc',
|
|
454
|
+
'**/.netrc',
|
|
455
|
+
'**/wrangler.{toml,json,jsonc}',
|
|
450
456
|
'**/*.p8',
|
|
451
457
|
'**/*.plist',
|
|
452
458
|
'**/google-services.json',
|
|
453
459
|
'**/*.pfx',
|
|
460
|
+
'**/*.p12',
|
|
461
|
+
'**/*.jks',
|
|
462
|
+
'**/*.keystore',
|
|
454
463
|
'**/*.pem',
|
|
455
464
|
'**/*.key',
|
|
456
465
|
];
|