@hogsend/engine 0.45.0 → 0.46.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.45.0",
3
+ "version": "0.46.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -51,17 +51,17 @@
51
51
  "svix": "^1.95.1",
52
52
  "winston": "^3.19.0",
53
53
  "zod": "^4.4.3",
54
- "@hogsend/attribution": "^0.45.0",
55
- "@hogsend/core": "^0.45.0",
56
- "@hogsend/db": "^0.45.0",
57
- "@hogsend/email": "^0.45.0",
58
- "@hogsend/plugin-posthog": "^0.45.0",
59
- "@hogsend/plugin-resend": "^0.45.0",
60
- "@hogsend/sms": "^0.45.0"
54
+ "@hogsend/attribution": "^0.46.1",
55
+ "@hogsend/core": "^0.46.1",
56
+ "@hogsend/db": "^0.46.1",
57
+ "@hogsend/email": "^0.46.1",
58
+ "@hogsend/plugin-posthog": "^0.46.1",
59
+ "@hogsend/plugin-resend": "^0.46.1",
60
+ "@hogsend/sms": "^0.46.1"
61
61
  },
62
62
  "optionalDependencies": {
63
- "@hogsend/plugin-postmark": "^0.45.0",
64
- "@hogsend/plugin-twilio": "^0.45.0"
63
+ "@hogsend/plugin-postmark": "^0.46.1",
64
+ "@hogsend/plugin-twilio": "^0.46.1"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/node": "^22.15.3",
package/src/container.ts CHANGED
@@ -239,6 +239,16 @@ export interface HogsendClient {
239
239
  * with acorn to derive a visual workflow. Empty when no journeys are wired.
240
240
  */
241
241
  journeySources: Map<string, string>;
242
+ /**
243
+ * The consumer's `Templates`/`Events` `as const` maps, normalized to always
244
+ * be present (`{ templates: {}, events: {} }` when unwired). Consumed by the
245
+ * Studio journey-graph route to resolve `Templates.X` / `Events.X` member
246
+ * expressions to their real values, for exact previews + stable node ids.
247
+ */
248
+ journeyConstants: {
249
+ templates: Record<string, string>;
250
+ events: Record<string, string>;
251
+ };
242
252
  /**
243
253
  * Map of enabled journey id → its `defineJourney` call-site `{ path, line }`.
244
254
  * Populated by `buildJourneyRegistry`. Consumed by the Studio journey-graph
@@ -308,6 +318,18 @@ export interface HogsendClient {
308
318
  export interface HogsendClientOptions {
309
319
  /** Journeys to register in the {@link JourneyRegistry}. Defaults to none. */
310
320
  journeys?: DefinedJourney[];
321
+ /**
322
+ * The consumer's `Templates`/`Events` `as const` maps (each a
323
+ * `CONST_NAME -> "value"` record). Threaded into the Studio journey-graph
324
+ * route so `Templates.X` / `Events.X` member expressions in a journey's `run`
325
+ * source resolve to their real runtime values — yielding exact email-template
326
+ * previews and stable, join-safe `wait-event:${value}` / `digest:${value}`
327
+ * node ids (instead of positional `unstable` synthetics). Defaults to none.
328
+ */
329
+ journeyConstants?: {
330
+ templates?: Record<string, string>;
331
+ events?: Record<string, string>;
332
+ };
311
333
  /** Buckets to register in the {@link BucketRegistry}. Defaults to none. */
312
334
  buckets?: DefinedBucket[];
313
335
  /**
@@ -1428,6 +1450,10 @@ export function createHogsendClient(
1428
1450
  identity,
1429
1451
  registry,
1430
1452
  journeySources: getJourneySources(),
1453
+ journeyConstants: {
1454
+ templates: opts.journeyConstants?.templates ?? {},
1455
+ events: opts.journeyConstants?.events ?? {},
1456
+ },
1431
1457
  journeySourceLocations: getJourneySourceLocations(),
1432
1458
  bucketRegistry,
1433
1459
  listRegistry,
@@ -120,8 +120,12 @@ interface Raw {
120
120
  timeout?: Record<string, number>;
121
121
  eventLiteral?: string;
122
122
  eventIdent?: string;
123
+ /** OBJECT qualifier of an `X.PROP` event member-expr (`Events.NPS` → "Events"). */
124
+ eventObject?: string;
123
125
  templateLiteral?: string;
124
126
  templateIdent?: string;
127
+ /** OBJECT qualifier of an `X.PROP` template member-expr (`Templates.WELCOME` → "Templates"). */
128
+ templateObject?: string;
125
129
  connectorId?: string;
126
130
  action?: string;
127
131
  idempotencyLabel?: string;
@@ -129,16 +133,31 @@ interface Raw {
129
133
  calleeName?: string;
130
134
  }
131
135
 
136
+ /**
137
+ * The consumer's `Templates`/`Events` `as const` maps (`CONST_NAME -> "value"`),
138
+ * threaded through so `Templates.X` / `Events.X` member expressions in a
139
+ * journey's source resolve to their REAL runtime values. This is what makes the
140
+ * derived node ids deterministic (stable `wait-event:${value}` / `digest:${value}`
141
+ * ids that join to `journeyStates.currentNodeId`) and populates `meta.template` /
142
+ * `meta.event` for exact previews — with NO other extraction changes.
143
+ */
144
+ export interface JourneyGraphConsts {
145
+ templates?: Record<string, string>;
146
+ events?: Record<string, string>;
147
+ }
148
+
132
149
  export function buildJourneyGraph({
133
150
  runSource,
134
151
  meta,
152
+ consts,
135
153
  }: {
136
154
  runSource?: string;
137
155
  meta: JourneyMeta;
156
+ consts?: JourneyGraphConsts;
138
157
  }): JourneyGraph {
139
158
  if (!runSource) return degradedGraphFromMeta(meta);
140
159
  try {
141
- return extract(runSource, meta);
160
+ return extract(runSource, meta, consts);
142
161
  } catch {
143
162
  return degradedGraphFromMeta(meta);
144
163
  }
@@ -165,7 +184,57 @@ export function degradedGraphFromMeta(meta: JourneyMeta): JourneyGraph {
165
184
  };
166
185
  }
167
186
 
168
- function extract(runSource: string, meta: JourneyMeta): JourneyGraph {
187
+ /**
188
+ * Deterministic const-resolution pass: for each raw whose template/event slot
189
+ * is a member-expr IDENTIFIER (`Templates.DOCS_WELCOME` → ident `DOCS_WELCOME`)
190
+ * but has no literal, fill the literal from the matching const map value. Only
191
+ * fills from the ident (never overwrites an existing literal) and only for own,
192
+ * non-empty-string entries — so prototype keys can't leak in. Filling the
193
+ * literal is enough: the node builders already prefer the literal for the id,
194
+ * `meta`, subtitle, and the `unstable` flag, so everything downstream becomes
195
+ * deterministic with no other change.
196
+ *
197
+ * The fill is GATED on the OBJECT qualifier being the conventional const-object
198
+ * name — `Templates` for templates, `Events` for events (the documented
199
+ * consumer convention: CLAUDE.md's `Templates`/`Events` `as const` maps + the
200
+ * create-hogsend scaffold). This prevents a property-name collision — e.g. an
201
+ * unrelated `SomeEnum.SUBMITTED` whose `SUBMITTED` key also lives in the events
202
+ * map but maps to a different value — from confidently resolving to a WRONG
203
+ * literal. An aliased/non-conventional object name degrades gracefully to the
204
+ * pre-fill fallback (positional id / heuristic) instead of risking a wrong value.
205
+ */
206
+ function resolveRawConsts(raws: Raw[], consts?: JourneyGraphConsts): void {
207
+ if (!consts) return;
208
+ const fill = (
209
+ map: Record<string, string> | undefined,
210
+ ident: string | undefined,
211
+ ): string | undefined => {
212
+ if (!map || ident === undefined || !Object.hasOwn(map, ident)) {
213
+ return undefined;
214
+ }
215
+ const value = map[ident];
216
+ return typeof value === "string" && value.length > 0 ? value : undefined;
217
+ };
218
+ for (const raw of raws) {
219
+ if (
220
+ raw.templateLiteral === undefined &&
221
+ raw.templateObject === "Templates"
222
+ ) {
223
+ const value = fill(consts.templates, raw.templateIdent);
224
+ if (value !== undefined) raw.templateLiteral = value;
225
+ }
226
+ if (raw.eventLiteral === undefined && raw.eventObject === "Events") {
227
+ const value = fill(consts.events, raw.eventIdent);
228
+ if (value !== undefined) raw.eventLiteral = value;
229
+ }
230
+ }
231
+ }
232
+
233
+ function extract(
234
+ runSource: string,
235
+ meta: JourneyMeta,
236
+ consts?: JourneyGraphConsts,
237
+ ): JourneyGraph {
169
238
  const wrapped = `(${runSource})`;
170
239
  const ast = acorn.parse(wrapped, {
171
240
  ecmaVersion: "latest",
@@ -190,6 +259,11 @@ function extract(runSource: string, meta: JourneyMeta): JourneyGraph {
190
259
  });
191
260
  raws.sort((a, b) => a.start - b.start);
192
261
 
262
+ // Resolve `Templates.X` / `Events.X` member-expr idents to their real runtime
263
+ // values from the consumer's const maps BEFORE id assignment, so the node
264
+ // builders (which already prefer the literal) mint deterministic ids + meta.
265
+ resolveRawConsts(raws, consts);
266
+
193
267
  // --- Pass B: assign ids (A2 join-key rules) ---
194
268
  const emitted = assignNodes(raws, meta.trigger.event);
195
269
  dedupeIds(emitted);
@@ -316,6 +390,21 @@ function lastIdentOf(node: Node | undefined): string | undefined {
316
390
  return undefined;
317
391
  }
318
392
 
393
+ /**
394
+ * The OBJECT identifier of a simple `Object.PROP` member expression
395
+ * (`Templates.DOCS_WELCOME` → "Templates", `Events.NPS_SUBMITTED` → "Events").
396
+ * Returns undefined for anything that isn't `<plain Identifier>.<prop>` —
397
+ * nested member exprs (`Foo.Bar.BAZ`), computed access (`Map[k]`), or a bare
398
+ * identifier. Used to gate const resolution on the CONVENTIONAL object name so a
399
+ * property-name collision on an unrelated enum can't resolve to a wrong value.
400
+ */
401
+ function objectIdentOf(node: Node | undefined): string | undefined {
402
+ if (!node || node.type !== "MemberExpression" || node.computed) {
403
+ return undefined;
404
+ }
405
+ return node.object.type === "Identifier" ? node.object.name : undefined;
406
+ }
407
+
319
408
  function objectProp(
320
409
  obj: acorn.ObjectExpression,
321
410
  key: string,
@@ -536,6 +625,7 @@ function ctxNodeFields(
536
625
  labelUnstable: label?.unstable,
537
626
  eventLiteral: stringLiteral(eventNode),
538
627
  eventIdent: lastIdentOf(eventNode),
628
+ eventObject: objectIdentOf(eventNode),
539
629
  timeout: arg ? extractDuration(objectProp(arg, "timeout")) : undefined,
540
630
  };
541
631
  }
@@ -549,6 +639,7 @@ function ctxNodeFields(
549
639
  labelUnstable: label?.unstable,
550
640
  eventLiteral: stringLiteral(eventNode),
551
641
  eventIdent: lastIdentOf(eventNode),
642
+ eventObject: objectIdentOf(eventNode),
552
643
  duration: arg ? extractDuration(objectProp(arg, "window")) : undefined,
553
644
  };
554
645
  }
@@ -558,6 +649,7 @@ function ctxNodeFields(
558
649
  kind,
559
650
  eventLiteral: stringLiteral(eventNode),
560
651
  eventIdent: lastIdentOf(eventNode),
652
+ eventObject: objectIdentOf(eventNode),
561
653
  };
562
654
  }
563
655
 
@@ -568,6 +660,7 @@ function sendFields(arg: acorn.ObjectExpression): ClassifiedFields {
568
660
  kind: "send",
569
661
  templateLiteral: stringLiteral(templateNode),
570
662
  templateIdent: lastIdentOf(templateNode),
663
+ templateObject: objectIdentOf(templateNode),
571
664
  // Only a literal idempotencyLabel is a stable id "site".
572
665
  idempotencyLabel: idem && !idem.unstable ? idem.value : undefined,
573
666
  };
@@ -46,8 +46,21 @@ export interface ProvisionPostHogLoopOptions {
46
46
  logger: Logger;
47
47
  /** Display name for a NEWLY created function. Default: MANAGED_NAME. */
48
48
  name?: string;
49
+ /**
50
+ * Placeholder mode (local instances PostHog can't reach): provision the
51
+ * destination DISABLED, pointing at the obvious stand-in
52
+ * `https://CHANGEME.yourdomain.com/...` instead of `apiPublicUrl`. The
53
+ * destination then EXISTS in PostHog — name, filters, secret header, all
54
+ * inspectable — with zero failed deliveries. Going live after deploy is one
55
+ * re-run WITHOUT this flag (`--provision-only --url https://real`): the
56
+ * reconciler swaps the URL and re-enables in a single PATCH.
57
+ */
58
+ placeholder?: boolean;
49
59
  }
50
60
 
61
+ /** The stand-in base URL placeholder mode provisions against. */
62
+ export const PLACEHOLDER_PUBLIC_URL = "https://CHANGEME.yourdomain.com";
63
+
51
64
  export interface ProvisionPostHogLoopResult {
52
65
  action: "created" | "updated" | "unchanged";
53
66
  /** Hog function UUID. */
@@ -64,6 +77,8 @@ export interface ProvisionPostHogLoopResult {
64
77
  projectApiKey?: string;
65
78
  /** Best-effort deep link (pattern unverified — cosmetic, confirm in e2e). */
66
79
  dashboardUrl: string;
80
+ /** false ⇒ placeholder mode: disabled destination, CHANGEME URL. */
81
+ enabled: boolean;
67
82
  }
68
83
 
69
84
  export type ProvisionPostHogLoopErrorCode =
@@ -243,6 +258,8 @@ interface HogFunctionDetail {
243
258
  interface DesiredLoop {
244
259
  webhookUrl: string;
245
260
  webhookSecret: string;
261
+ /** false only in placeholder mode — see ProvisionPostHogLoopOptions. */
262
+ enabled: boolean;
246
263
  }
247
264
 
248
265
  /**
@@ -266,7 +283,11 @@ export async function provisionPostHogLoop(
266
283
  });
267
284
  }
268
285
 
269
- const webhookUrl = joinUrl(apiPublicUrl, HOGSEND_LOOP_PATH);
286
+ const placeholder = opts.placeholder === true;
287
+ const webhookUrl = joinUrl(
288
+ placeholder ? PLACEHOLDER_PUBLIC_URL : apiPublicUrl,
289
+ HOGSEND_LOOP_PATH,
290
+ );
270
291
  const hostname = tryParseUrl(webhookUrl)?.hostname;
271
292
  if (hostname === "localhost" || hostname === "127.0.0.1") {
272
293
  logger.warn(
@@ -282,7 +303,11 @@ export async function provisionPostHogLoop(
282
303
  });
283
304
 
284
305
  const basePath = `/api/environments/${projectId}/hog_functions/`;
285
- const desired: DesiredLoop = { webhookUrl, webhookSecret };
306
+ const desired: DesiredLoop = {
307
+ webhookUrl,
308
+ webhookSecret,
309
+ enabled: !placeholder,
310
+ };
286
311
 
287
312
  const found = await findLoopFunction({ privateHost, accessToken, basePath });
288
313
 
@@ -339,6 +364,7 @@ export async function provisionPostHogLoop(
339
364
  dashboardUrl:
340
365
  `${privateHost.replace(/\/+$/, "")}/project/${projectId}` +
341
366
  `/pipeline/destinations/hog-${functionId}/configuration`,
367
+ enabled: desired.enabled,
342
368
  };
343
369
  }
344
370
 
@@ -562,7 +588,7 @@ async function findLoopFunction(opts: {
562
588
 
563
589
  /** true ⇒ no PATCH needed. */
564
590
  function isCompliant(fn: HogFunctionDetail, desired: DesiredLoop): boolean {
565
- if (fn.enabled !== true) return false;
591
+ if (fn.enabled !== desired.enabled) return false;
566
592
  if (inputValue(fn.inputs, "url") !== desired.webhookUrl) return false;
567
593
  if (inputValue(fn.inputs, "method") !== "POST") return false;
568
594
  if (!deepEquals(inputValue(fn.inputs, "body"), CANONICAL_BODY)) return false;
@@ -614,7 +640,7 @@ function buildCreatePayload(
614
640
  name: name ?? MANAGED_NAME,
615
641
  description: MANAGED_DESCRIPTION,
616
642
  template_id: "template-webhook",
617
- enabled: true,
643
+ enabled: desired.enabled,
618
644
  inputs: {
619
645
  url: { value: desired.webhookUrl },
620
646
  method: { value: "POST" },
@@ -636,11 +662,12 @@ function buildCreatePayload(
636
662
 
637
663
  /**
638
664
  * Reconciled PATCH body: enforce what we manage, preserve the rest.
639
- * `enabled: true` always — connect is an explicit operator action, so
640
- * re-enabling a paused loop is the expected outcome. PostHog replaces
641
- * `inputs` WHOLESALE on PATCH (verified), so all five keys are always
642
- * sent. `name`/`description` are never touched on adopt — the operator
643
- * may have renamed deliberately.
665
+ * `enabled` follows `desired` — true on a real provision (connect is an
666
+ * explicit operator action, so re-enabling a paused loop is the expected
667
+ * outcome), false in placeholder mode (a CHANGEME URL must never receive
668
+ * deliveries). PostHog replaces `inputs` WHOLESALE on PATCH (verified), so
669
+ * all five keys are always sent. `name`/`description` are never touched on
670
+ * adopt — the operator may have renamed deliberately.
644
671
  */
645
672
  function buildUpdatePayload(
646
673
  fn: HogFunctionDetail,
@@ -665,7 +692,7 @@ function buildUpdatePayload(
665
692
  filters.properties = properties;
666
693
 
667
694
  const payload: Record<string, unknown> = {
668
- enabled: true,
695
+ enabled: desired.enabled,
669
696
  inputs: {
670
697
  url: { value: desired.webhookUrl },
671
698
  method: { value: "POST" },
@@ -123,6 +123,8 @@ const provisionLoopResponseSchema = z.object({
123
123
  hogFunctionId: z.string(),
124
124
  webhookUrl: z.string(),
125
125
  dashboardUrl: z.string(),
126
+ /** false ⇒ placeholder mode: destination is DISABLED with a CHANGEME URL. */
127
+ enabled: z.boolean(),
126
128
  });
127
129
 
128
130
  const provisionFailureSchema = z.object({
@@ -157,6 +159,12 @@ const provisionLoopRoute = createRoute({
157
159
  path: "/provision-loop",
158
160
  tags: ["Admin — Analytics"],
159
161
  summary: "Provision the PostHog → Hogsend event loop (webhook destination)",
162
+ request: {
163
+ // `?placeholder=true` — pre-create the destination DISABLED with the
164
+ // CHANGEME stand-in URL (for local instances PostHog can't reach). A
165
+ // query param (not a body) keeps older CLIs' bare POST byte-compatible.
166
+ query: z.object({ placeholder: z.enum(["true", "false"]).optional() }),
167
+ },
160
168
  responses: {
161
169
  200: {
162
170
  content: {
@@ -224,6 +232,7 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
224
232
  .openapi(provisionLoopRoute, async (c) => {
225
233
  const { db, env, logger } = c.get("container");
226
234
  const info = resolveConnectInfo(env);
235
+ const placeholder = c.req.valid("query").placeholder === "true";
227
236
 
228
237
  // Credential check FIRST (M3), secret refusal second (enforced by the
229
238
  // provisioner itself). The container does NOT expose the token manager
@@ -252,7 +261,9 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
252
261
  // PostHog Cloud cannot deliver webhooks to a loopback address — and a
253
262
  // local instance with a misconfigured API_PUBLIC_URL must never repoint
254
263
  // a production destination at localhost. Refuse BEFORE any PostHog call.
255
- if (isLoopbackPublicUrl(info.apiPublicUrl)) {
264
+ // Placeholder mode is exempt: it never uses apiPublicUrl (the destination
265
+ // is created DISABLED against the CHANGEME stand-in URL).
266
+ if (!placeholder && isLoopbackPublicUrl(info.apiPublicUrl)) {
256
267
  return c.json(
257
268
  {
258
269
  error: "api_public_url_unreachable",
@@ -297,6 +308,7 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
297
308
  apiPublicUrl: info.apiPublicUrl,
298
309
  webhookSecret,
299
310
  logger,
311
+ placeholder,
300
312
  });
301
313
 
302
314
  // Opportunistically persist the phc_ (project api_token) the provisioner
@@ -325,6 +337,7 @@ export const analyticsAdminRouter = new OpenAPIHono<AppEnv>()
325
337
  hogFunctionId: result.functionId,
326
338
  webhookUrl: result.webhookUrl,
327
339
  dashboardUrl: result.dashboardUrl,
340
+ enabled: result.enabled,
328
341
  },
329
342
  200,
330
343
  );
@@ -2,6 +2,7 @@ import { contacts, userEvents } from "@hogsend/db";
2
2
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
3
  import { and, count, desc, eq, gte, isNull, lte, or, sql } from "drizzle-orm";
4
4
  import type { AppEnv } from "../../app.js";
5
+ import type { HogsendClient } from "../../container.js";
5
6
  import {
6
7
  eventNameEntrySchema,
7
8
  listEventNameVocabulary,
@@ -16,8 +17,8 @@ const eventSchema = z.object({
16
17
  occurredAt: z.string(),
17
18
  // Where the event entered the pipeline ("posthog", "api", "studio", …).
18
19
  source: z.string().nullable(),
19
- // Resolved from the matching live contact (user_events.userId ==
20
- // contacts.externalId), so the Events feed can show WHO an event is from.
20
+ // Resolved from THE live contact whose key (externalId, anonymousId, or
21
+ // id) matches user_events.userId — shows WHO an event is from.
21
22
  userEmail: z.string().nullable(),
22
23
  contactId: z.string().nullable(),
23
24
  });
@@ -45,21 +46,36 @@ function serializeEvent(row: JoinedEvent) {
45
46
  }
46
47
 
47
48
  /**
48
- * LEFT JOIN to the live contact for the userId. `userEvents.userId` holds the
49
- * resolved canonical key (`external_id ?? anonymous_id ?? id`), so match all
50
- * three — covering email-only/anonymous contacts, not just externalId-keyed
51
- * ones. Each key is partial-unique among live rows, and the three namespaces
52
- * don't overlap in practice, so at most one live contact matches per userId.
49
+ * LATERAL pick of THE live contact for an event's userId. `userEvents.userId`
50
+ * holds the resolved canonical key (`external_id ?? anonymous_id ?? id`), so
51
+ * match all three — covering email-only/anonymous contacts, not just
52
+ * externalId-keyed ones. Each column is partial-unique among live rows, but
53
+ * the three namespaces are NOT guaranteed disjoint across contacts: a
54
+ * mis-keyed emitter can park one contact's key in another contact's
55
+ * anonymous_id, and a bare OR-join then matches BOTH — fanning every event
56
+ * out into one display row per matching contact. The lateral picks exactly
57
+ * one, by the same precedence ingest resolves keys with.
53
58
  */
54
- const contactJoin = and(
55
- or(
56
- eq(contacts.externalId, userEvents.userId),
57
- eq(contacts.anonymousId, userEvents.userId),
58
- eq(sql`${contacts.id}::text`, userEvents.userId),
59
- ),
60
- isNull(contacts.deletedAt),
61
- );
62
- const contactCols = { id: contacts.id, email: contacts.email };
59
+ function liveContactFor(db: HogsendClient["db"]) {
60
+ return db
61
+ .select({ id: contacts.id, email: contacts.email })
62
+ .from(contacts)
63
+ .where(
64
+ and(
65
+ or(
66
+ eq(contacts.externalId, userEvents.userId),
67
+ eq(contacts.anonymousId, userEvents.userId),
68
+ eq(sql`${contacts.id}::text`, userEvents.userId),
69
+ ),
70
+ isNull(contacts.deletedAt),
71
+ ),
72
+ )
73
+ .orderBy(
74
+ sql`case when ${contacts.externalId} = ${userEvents.userId} then 0 when ${contacts.anonymousId} = ${userEvents.userId} then 1 else 2 end`,
75
+ )
76
+ .limit(1)
77
+ .as("live_contact");
78
+ }
63
79
 
64
80
  const listRoute = createRoute({
65
81
  method: "get",
@@ -234,11 +250,15 @@ export const eventsRouter = new OpenAPIHono<AppEnv>()
234
250
 
235
251
  const where = conditions.length > 0 ? and(...conditions) : undefined;
236
252
 
253
+ const liveContact = liveContactFor(db);
237
254
  const [rows, totalRows] = await Promise.all([
238
255
  db
239
- .select({ event: userEvents, contact: contactCols })
256
+ .select({
257
+ event: userEvents,
258
+ contact: { id: liveContact.id, email: liveContact.email },
259
+ })
240
260
  .from(userEvents)
241
- .leftJoin(contacts, contactJoin)
261
+ .leftJoinLateral(liveContact, sql`true`)
242
262
  .where(where)
243
263
  .orderBy(desc(userEvents.occurredAt))
244
264
  .limit(limit)
@@ -276,10 +296,14 @@ export const eventsRouter = new OpenAPIHono<AppEnv>()
276
296
  const { db } = c.get("container");
277
297
  const { id } = c.req.valid("param");
278
298
 
299
+ const liveContact = liveContactFor(db);
279
300
  const rows = await db
280
- .select({ event: userEvents, contact: contactCols })
301
+ .select({
302
+ event: userEvents,
303
+ contact: { id: liveContact.id, email: liveContact.email },
304
+ })
281
305
  .from(userEvents)
282
- .leftJoin(contacts, contactJoin)
306
+ .leftJoinLateral(liveContact, sql`true`)
283
307
  .where(eq(userEvents.id, id))
284
308
  .limit(1);
285
309
 
@@ -1,4 +1,8 @@
1
- import { type JourneyGraph, journeyGraphSchema } from "@hogsend/core";
1
+ import {
2
+ type JourneyGraph,
3
+ journeyGraphSchema,
4
+ resolveTemplateKeyFromConst,
5
+ } from "@hogsend/core";
2
6
  import {
3
7
  type Database,
4
8
  emailSends,
@@ -900,8 +904,14 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
900
904
  );
901
905
  })
902
906
  .openapi(graphRoute, async (c) => {
903
- const { db, registry, journeySources, journeySourceLocations, templates } =
904
- c.get("container");
907
+ const {
908
+ db,
909
+ registry,
910
+ journeySources,
911
+ journeySourceLocations,
912
+ journeyConstants,
913
+ templates,
914
+ } = c.get("container");
905
915
  const { id } = c.req.valid("param");
906
916
 
907
917
  const meta = registry.get(id);
@@ -914,7 +924,11 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
914
924
  // call-site (also static per process) is baked into the cached graph.
915
925
  let graph = journeyGraphCache.get(id);
916
926
  if (!graph) {
917
- graph = buildJourneyGraph({ runSource: journeySources.get(id), meta });
927
+ graph = buildJourneyGraph({
928
+ runSource: journeySources.get(id),
929
+ meta,
930
+ consts: journeyConstants,
931
+ });
918
932
  const source = journeySourceLocations.get(id);
919
933
  if (source) graph.source = source;
920
934
  journeyGraphCache.set(id, graph);
@@ -972,13 +986,13 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
972
986
  // the React Email component — no send data), so STATIC resolution is the
973
987
  // primary mechanism and a never-sent journey still previews. Priority:
974
988
  // (1) literal `meta.template` — already the registry key.
975
- // (2) STATIC exact: the node's `subtitle` is the Templates const name for
976
- // member-expr sends (`FEEDBACK_NPS_SURVEY`); lowercase + `_`→`-`
977
- // (`feedback-nps-survey`) and use it IFF that key is in the registry.
978
- // (2b) STATIC prefix: else the single LONGEST registry key that is a
979
- // segment-prefix of the kebab'd const name (`activation-nudge-series`
980
- // → `activation-nudge`). Only when that longest prefix is unique — a
981
- // wrong preview is worse than none, so an ambiguous tie stays unresolved.
989
+ // (2) STATIC segment match (`resolveTemplateKeyFromConst`): the node's
990
+ // `subtitle` is the Templates const name for member-expr sends
991
+ // (`FEEDBACK_NPS_SURVEY`, `DOCS_WELCOME`). Split it and each registry
992
+ // key on any of `/ _ -` and compare SEGMENTS, so slash-namespaced keys
993
+ // (`docs/welcome`) resolve too — else the unique longest segment-prefix
994
+ // key (`activation-nudge-series` → `activation-nudge`). Ambiguous ties
995
+ // stay unresolved — a wrong preview is worse than none.
982
996
  // (3) journey_logs rows (action='send') whose `to_node_id` is this send
983
997
  // node's site id (`send:<site>`), reading `detail.template` — site-
984
998
  // keyed, so two sends of one template on different branches stay
@@ -1010,31 +1024,12 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
1010
1024
  }
1011
1025
 
1012
1026
  // (2/2b) static const-name → registry key (no runtime data needed):
1013
- // exact kebab match, else the unique longest segment-prefix key.
1027
+ // separator-agnostic SEGMENT match, so slash-namespaced keys
1028
+ // (`docs/welcome`) resolve from `DOCS_WELCOME` just as hyphen ones do.
1014
1029
  const registryKeys = getTemplateNames(templates) as string[];
1015
- const registeredKeys = new Set<string>(registryKeys);
1016
- const resolveStatic = (constName: string): string | undefined => {
1017
- const kebab = constName.toLowerCase().replace(/_/g, "-");
1018
- if (registeredKeys.has(kebab)) return kebab;
1019
- // Longest registry key that is a segment-prefix of the kebab'd name.
1020
- let best: string | undefined;
1021
- let bestLen = -1;
1022
- let ambiguous = false;
1023
- for (const key of registryKeys) {
1024
- if (!kebab.startsWith(`${key}-`)) continue;
1025
- if (key.length > bestLen) {
1026
- best = key;
1027
- bestLen = key.length;
1028
- ambiguous = false;
1029
- } else if (key.length === bestLen) {
1030
- ambiguous = true;
1031
- }
1032
- }
1033
- return ambiguous ? undefined : best;
1034
- };
1035
1030
  for (const node of sendNodes) {
1036
1031
  if (nodeMetrics[node.id]?.templateKey || !node.subtitle) continue;
1037
- const key = resolveStatic(node.subtitle);
1032
+ const key = resolveTemplateKeyFromConst(node.subtitle, registryKeys);
1038
1033
  if (key) setTemplate(node.id, key);
1039
1034
  }
1040
1035
 
@@ -78,7 +78,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
78
78
  detail: env.HATCHET_CLIENT_TOKEN
79
79
  ? `Connected (${env.HATCHET_CLIENT_HOST_PORT}).`
80
80
  : "Set HATCHET_CLIENT_TOKEN so the worker can run your journeys.",
81
- docsUrl: DOCS,
81
+ docsUrl: `${DOCS}/docs/getting-started/hatchet`,
82
82
  });
83
83
 
84
84
  // 3. Email provider key — sends fail without it.
@@ -98,7 +98,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
98
98
  detail: providerKeyPresent
99
99
  ? `${providerId} key configured.`
100
100
  : `No ${providerId} API key yet — sends will fail until one is set.`,
101
- docsUrl: DOCS,
101
+ docsUrl: `${DOCS}/docs/guides/email`,
102
102
  });
103
103
 
104
104
  // 4. Data-plane API key — any non-revoked key lets your app code ingest.
@@ -120,7 +120,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
120
120
  dataPlaneKeys > 0
121
121
  ? `${dataPlaneKeys} active key${dataPlaneKeys === 1 ? "" : "s"}.`
122
122
  : "Mint one (run bootstrap, or POST /v1/admin/api-keys) so your app can send events.",
123
- docsUrl: DOCS,
123
+ docsUrl: `${DOCS}/docs/data-api/authentication`,
124
124
  });
125
125
 
126
126
  // 5. Sending domain — derive from the (now graceful) domain status. A bad
@@ -134,7 +134,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
134
134
  status: "optional",
135
135
  detail:
136
136
  "No EMAIL_DOMAIN set — sends use the provider default. Configure one to send from your own domain.",
137
- docsUrl: DOCS,
137
+ docsUrl: `${DOCS}/docs/operating/production-email`,
138
138
  });
139
139
  } else if (dom.status?.state === "verified") {
140
140
  checks.push({
@@ -152,7 +152,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
152
152
  dom.status === null
153
153
  ? `${dom.domain}: can't read status — confirm your ${providerId} key can read domains.`
154
154
  : `${dom.domain} is ${dom.status.state.replace("_", " ")} — verify it below.`,
155
- docsUrl: DOCS,
155
+ docsUrl: `${DOCS}/docs/operating/production-email`,
156
156
  });
157
157
  }
158
158
  } catch {
@@ -161,7 +161,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
161
161
  label: "Sending domain",
162
162
  status: "action",
163
163
  detail: "Couldn't read domain status — check your email provider key.",
164
- docsUrl: DOCS,
164
+ docsUrl: `${DOCS}/docs/operating/production-email`,
165
165
  });
166
166
  }
167
167
 
@@ -175,7 +175,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
175
175
  detail: analyticsConfigured
176
176
  ? "Connected."
177
177
  : "Optional — connect PostHog to capture events and person properties.",
178
- docsUrl: DOCS,
178
+ docsUrl: `${DOCS}/docs/getting-started/posthog-setup`,
179
179
  });
180
180
 
181
181
  // 7–10. Attribution readiness (impact plan §5.4) — the "how's it doing"
@@ -234,7 +234,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
234
234
  : seen
235
235
  ? okDetail
236
236
  : missingDetail,
237
- docsUrl: `${DOCS}/conversions/impact`,
237
+ docsUrl: `${DOCS}/docs/conversions/impact`,
238
238
  });
239
239
  checks.push(
240
240
  probeCheck(