@hogsend/engine 0.65.0 → 0.67.0
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 +12 -12
- package/src/account-links/battlenet.ts +84 -0
- package/src/account-links/epic.ts +87 -0
- package/src/account-links/index.ts +12 -5
- package/src/account-links/riot.ts +82 -0
- package/src/account-links/xbox.ts +92 -0
- package/src/app.ts +9 -1
- package/src/container.ts +77 -0
- package/src/env.ts +18 -2
- package/src/index.ts +84 -0
- package/src/lib/account-links-from-env.ts +94 -30
- package/src/lib/contacts.ts +94 -2
- package/src/lib/ingestion.ts +61 -0
- package/src/lib/links.ts +94 -11
- package/src/lib/outbound.ts +94 -0
- package/src/lib/referral-intent.ts +723 -0
- package/src/lib/referral-link.ts +200 -0
- package/src/lib/referral-registry.ts +83 -0
- package/src/lib/referral-report.ts +739 -0
- package/src/lib/referral-runtime.ts +49 -0
- package/src/lib/referrals-no-emit.test.ts +109 -0
- package/src/lib/referrals.ts +712 -0
- package/src/lib/snippet.ts +76 -0
- package/src/lib/webhook-signing.ts +10 -0
- package/src/routes/admin/api-keys.ts +5 -0
- package/src/routes/admin/index.ts +2 -0
- package/src/routes/admin/links.ts +14 -5
- package/src/routes/admin/referrals.ts +565 -0
- package/src/routes/contacts/index.ts +78 -0
- package/src/routes/index.ts +45 -0
- package/src/routes/referrals/index.ts +41 -0
- package/src/routes/referrals/me.ts +123 -0
- package/src/routes/referrals/report.ts +285 -0
- package/src/routes/referrals/shared.ts +34 -0
- package/src/routes/referrals/touch.ts +313 -0
- package/src/routes/snippet.test.ts +70 -0
- package/src/routes/snippet.ts +58 -0
- package/src/routes/tracking/arrive.ts +90 -0
- package/src/routes/tracking/click-pipeline.ts +8 -0
- package/src/workflows/import-contacts.ts +6 -0
package/src/index.ts
CHANGED
|
@@ -495,6 +495,7 @@ export {
|
|
|
495
495
|
type IdentityKind,
|
|
496
496
|
identifiedContactFilter,
|
|
497
497
|
type MergedLinkUnlink,
|
|
498
|
+
projectPublicContact,
|
|
498
499
|
type ResolvePolicy,
|
|
499
500
|
resolveContactNoCreate,
|
|
500
501
|
resolveOrCreateContact,
|
|
@@ -700,6 +701,7 @@ export {
|
|
|
700
701
|
// internal mechanics behind the /qr endpoint, not semver surface.
|
|
701
702
|
export {
|
|
702
703
|
IdempotencyConflictError,
|
|
704
|
+
LinkOwnershipError,
|
|
703
705
|
type LinkType,
|
|
704
706
|
type MintedLink,
|
|
705
707
|
type MintLinkOptions,
|
|
@@ -765,6 +767,82 @@ export {
|
|
|
765
767
|
getRedis,
|
|
766
768
|
getRedisIfConnected,
|
|
767
769
|
} from "./lib/redis.js";
|
|
770
|
+
// --- Referral intent layer (the ONE place the store is called AND emits) ---
|
|
771
|
+
export {
|
|
772
|
+
type BindReferralInput,
|
|
773
|
+
bindReferral,
|
|
774
|
+
type ConvertReferralInput,
|
|
775
|
+
convertReferral,
|
|
776
|
+
type QualifyReferralInput,
|
|
777
|
+
qualifyReferral,
|
|
778
|
+
qualifyReferralsForEvent,
|
|
779
|
+
REFERRAL_TREE_MAX_DEPTH,
|
|
780
|
+
type ReferralIntentHandles,
|
|
781
|
+
type TouchReferralInput,
|
|
782
|
+
type TouchReferralResult,
|
|
783
|
+
touchReferral,
|
|
784
|
+
} from "./lib/referral-intent.js";
|
|
785
|
+
// --- Referrals: definition wiring + the journey-safe link mint ---
|
|
786
|
+
// `defineReferral` itself lives in `@hogsend/core` (re-exported from the core
|
|
787
|
+
// barrel). Pass definitions to `createHogsendClient({ referrals: [...] })` in
|
|
788
|
+
// BOTH index.ts and worker.ts; `client.referrals` is the resolved registry.
|
|
789
|
+
export {
|
|
790
|
+
type GetReferralLinkOptions,
|
|
791
|
+
getReferralLink,
|
|
792
|
+
type ReferralLink,
|
|
793
|
+
type ReferralLinkContainer,
|
|
794
|
+
} from "./lib/referral-link.js";
|
|
795
|
+
export { ReferralRegistry } from "./lib/referral-registry.js";
|
|
796
|
+
// --- Referral REPORT (report-time model/window/depth/weights, PRD 05 §5.3) ---
|
|
797
|
+
export {
|
|
798
|
+
type CurrencyValue,
|
|
799
|
+
getReferralReport,
|
|
800
|
+
getReferralTree,
|
|
801
|
+
InvalidWindowError,
|
|
802
|
+
NO_CURRENCY,
|
|
803
|
+
parseWindowMs,
|
|
804
|
+
REFERRAL_MODELS,
|
|
805
|
+
REFERRAL_REPORT_MAX_DEPTH,
|
|
806
|
+
type ReferralBeneficiary,
|
|
807
|
+
type ReferralModel,
|
|
808
|
+
type ReferralReport,
|
|
809
|
+
type ReferralTreeLevel,
|
|
810
|
+
type ReferralTreeNode,
|
|
811
|
+
resolveLevelWeights,
|
|
812
|
+
} from "./lib/referral-report.js";
|
|
813
|
+
export {
|
|
814
|
+
getReferralRuntime,
|
|
815
|
+
type ReferralRuntime,
|
|
816
|
+
resetReferralRuntime,
|
|
817
|
+
setReferralRuntime,
|
|
818
|
+
} from "./lib/referral-runtime.js";
|
|
819
|
+
// --- Referral store (the ONE writer of referral_touches; NEVER emits) ---
|
|
820
|
+
// The store returns mutation FACTS; the intent layer emits `referral.*`
|
|
821
|
+
// outbound and re-ingests for journeys, side by side (PRD 05 §6). Pinned by
|
|
822
|
+
// `lib/referrals-no-emit.test.ts`.
|
|
823
|
+
export {
|
|
824
|
+
type BindTouchesInput,
|
|
825
|
+
type BindTouchesResult,
|
|
826
|
+
bindTouches,
|
|
827
|
+
type ListTouchesInput,
|
|
828
|
+
listTouchesForReferee,
|
|
829
|
+
listTouchesForReferrer,
|
|
830
|
+
type QualifyTouchInput,
|
|
831
|
+
type QualifyTouchResult,
|
|
832
|
+
qualifyTouch,
|
|
833
|
+
REFERRAL_IDEMPOTENCY_PROPERTY,
|
|
834
|
+
REFERRAL_VETO_REASON_PROPERTY,
|
|
835
|
+
type RecordTouchInput,
|
|
836
|
+
type RecordTouchResult,
|
|
837
|
+
type ReferralRejectReason,
|
|
838
|
+
type ReferralTouchRecord,
|
|
839
|
+
type ReferralTouchSource,
|
|
840
|
+
type ReferralTouchStatus,
|
|
841
|
+
type RejectTouchInput,
|
|
842
|
+
type RejectTouchResult,
|
|
843
|
+
recordTouch,
|
|
844
|
+
rejectTouch,
|
|
845
|
+
} from "./lib/referrals.js";
|
|
768
846
|
// --- Refinement (`refineContact` — a STANDALONE import, never on `ctx`) ---
|
|
769
847
|
export {
|
|
770
848
|
REFINE_EVENT,
|
|
@@ -833,6 +911,11 @@ export type {
|
|
|
833
911
|
SmsTrackedSendResult,
|
|
834
912
|
} from "./lib/sms-service-types.js";
|
|
835
913
|
export { SMS_CHANNEL_ID } from "./lib/sms-tracked.js";
|
|
914
|
+
export {
|
|
915
|
+
type LoadedSnippet,
|
|
916
|
+
loadSnippet,
|
|
917
|
+
resolveSnippetPath,
|
|
918
|
+
} from "./lib/snippet.js";
|
|
836
919
|
export { type MountStudioResult, mountStudio } from "./lib/studio.js";
|
|
837
920
|
// --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
|
|
838
921
|
export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
|
|
@@ -971,6 +1054,7 @@ export {
|
|
|
971
1054
|
serializeLinkedAccount,
|
|
972
1055
|
serializePublicLinkedAccount,
|
|
973
1056
|
} from "./routes/accounts/serialize.js";
|
|
1057
|
+
export { createSnippetRouter } from "./routes/snippet.js";
|
|
974
1058
|
// --- Contact sources (Clay/Attio/generic-webhook → cold prospects) ---
|
|
975
1059
|
export {
|
|
976
1060
|
type ColdChannelPosture,
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { AccountLinkProvider } from "@hogsend/core";
|
|
2
|
+
import { battlenetAccountLink } from "../account-links/battlenet.js";
|
|
3
|
+
import { epicAccountLink } from "../account-links/epic.js";
|
|
4
|
+
import { riotAccountLink } from "../account-links/riot.js";
|
|
2
5
|
import { steamAccountLink } from "../account-links/steam.js";
|
|
3
6
|
import { twitchAccountLink } from "../account-links/twitch.js";
|
|
7
|
+
import { xboxAccountLink } from "../account-links/xbox.js";
|
|
4
8
|
import type { env as envSchema } from "../env.js";
|
|
5
9
|
|
|
6
10
|
export interface AccountLinkEnvResult {
|
|
@@ -31,6 +35,14 @@ function hasEnvIntent(env: typeof envSchema): boolean {
|
|
|
31
35
|
env.ACCOUNT_LINK_TWITCH_CLIENT_ID ||
|
|
32
36
|
env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET ||
|
|
33
37
|
env.STEAM_WEB_API_KEY ||
|
|
38
|
+
env.ACCOUNT_LINK_BATTLENET_CLIENT_ID ||
|
|
39
|
+
env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET ||
|
|
40
|
+
env.ACCOUNT_LINK_EPIC_CLIENT_ID ||
|
|
41
|
+
env.ACCOUNT_LINK_EPIC_CLIENT_SECRET ||
|
|
42
|
+
env.ACCOUNT_LINK_XBOX_CLIENT_ID ||
|
|
43
|
+
env.ACCOUNT_LINK_XBOX_CLIENT_SECRET ||
|
|
44
|
+
env.ACCOUNT_LINK_RIOT_CLIENT_ID ||
|
|
45
|
+
env.ACCOUNT_LINK_RIOT_CLIENT_SECRET ||
|
|
34
46
|
env.ACCOUNT_LINK_ALLOWED_ORIGINS,
|
|
35
47
|
);
|
|
36
48
|
}
|
|
@@ -41,9 +53,9 @@ function hasEnvIntent(env: typeof envSchema): boolean {
|
|
|
41
53
|
* deliberate divergences:
|
|
42
54
|
*
|
|
43
55
|
* 1. **Static imports.** No `loadOptionalPlugin`, no runtime-assembled
|
|
44
|
-
* specifier, because
|
|
45
|
-
* `@hogsend/core` presets, not opt-in plugin packages (DECISIONS §3.1).
|
|
46
|
-
* top-level `await`, so `createHogsendClient` stays synchronous.
|
|
56
|
+
* specifier, because the six built-in providers are IN-PACKAGE config over
|
|
57
|
+
* the `@hogsend/core` presets, not opt-in plugin packages (DECISIONS §3.1).
|
|
58
|
+
* No top-level `await`, so `createHogsendClient` stays synchronous.
|
|
47
59
|
* 2. **It returns warnings rather than calling `console.warn`.** The email
|
|
48
60
|
* preset builder warns straight to `console.warn` because it runs before a
|
|
49
61
|
* logger exists; here the container already has `logger`, so the strings
|
|
@@ -55,7 +67,7 @@ function hasEnvIntent(env: typeof envSchema): boolean {
|
|
|
55
67
|
* preserving this repo's inert-when-unconfigured posture: a deploy that
|
|
56
68
|
* never asked for account linking gets no public `/v1/accounts/*` surface
|
|
57
69
|
* and no boot warning. Intent is EITHER env-side ({@link hasEnvIntent}: any
|
|
58
|
-
* `
|
|
70
|
+
* `ACCOUNT_LINK_*` var, `STEAM_WEB_API_KEY`, or
|
|
59
71
|
* `ACCOUNT_LINK_ALLOWED_ORIGINS` set) OR code-side
|
|
60
72
|
* ({@link AccountLinksFromEnvOptions.consumerOptedIn}: any `accountLinks`
|
|
61
73
|
* option passed, even `{}`). No intent ⇒ empty result.
|
|
@@ -70,13 +82,12 @@ function hasEnvIntent(env: typeof envSchema): boolean {
|
|
|
70
82
|
* `API_PUBLIC_URL` (already required by the engine env), trailing slash
|
|
71
83
|
* stripped — Steam rejects the assertion under a wrong realm. Steam
|
|
72
84
|
* contributes no warning and cannot be half-configured.
|
|
73
|
-
* - Twitch
|
|
74
|
-
* `
|
|
75
|
-
* registration (absent from the registry, not
|
|
76
|
-
* warning naming the MISSING var.
|
|
77
|
-
* -
|
|
78
|
-
*
|
|
79
|
-
* writer, so no third branch is added here.
|
|
85
|
+
* - OAuth providers (Twitch, Battle.net, Epic, Xbox, Riot) are registered iff
|
|
86
|
+
* BOTH `ACCOUNT_LINK_<ID>_CLIENT_ID` and `_CLIENT_SECRET` are set. Exactly
|
|
87
|
+
* one set ⇒ no registration (absent from the registry, not
|
|
88
|
+
* present-but-disabled) plus a warning naming the MISSING var.
|
|
89
|
+
* - Discord is the only excluded platform: it already ships via
|
|
90
|
+
* `plugin-discord`, and a second writer on `contacts.discordId` would drift.
|
|
80
91
|
*
|
|
81
92
|
* These presets come FIRST in the container's merge — a consumer-supplied
|
|
82
93
|
* provider of the same id wins (last-writer-wins on the registry).
|
|
@@ -101,25 +112,78 @@ export function accountLinksFromEnv(
|
|
|
101
112
|
}),
|
|
102
113
|
);
|
|
103
114
|
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
115
|
+
const oauthPresets: Array<{
|
|
116
|
+
id: string;
|
|
117
|
+
clientId: string | undefined;
|
|
118
|
+
clientSecret: string | undefined;
|
|
119
|
+
idVar: string;
|
|
120
|
+
secretVar: string;
|
|
121
|
+
factory: (cfg: {
|
|
122
|
+
clientId: string;
|
|
123
|
+
clientSecret: string;
|
|
124
|
+
}) => AccountLinkProvider;
|
|
125
|
+
portal: string;
|
|
126
|
+
}> = [
|
|
127
|
+
{
|
|
128
|
+
id: "twitch",
|
|
129
|
+
clientId: env.ACCOUNT_LINK_TWITCH_CLIENT_ID,
|
|
130
|
+
clientSecret: env.ACCOUNT_LINK_TWITCH_CLIENT_SECRET,
|
|
131
|
+
idVar: "ACCOUNT_LINK_TWITCH_CLIENT_ID",
|
|
132
|
+
secretVar: "ACCOUNT_LINK_TWITCH_CLIENT_SECRET",
|
|
133
|
+
factory: twitchAccountLink,
|
|
134
|
+
portal: "https://dev.twitch.tv/console/apps",
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
id: "battlenet",
|
|
138
|
+
clientId: env.ACCOUNT_LINK_BATTLENET_CLIENT_ID,
|
|
139
|
+
clientSecret: env.ACCOUNT_LINK_BATTLENET_CLIENT_SECRET,
|
|
140
|
+
idVar: "ACCOUNT_LINK_BATTLENET_CLIENT_ID",
|
|
141
|
+
secretVar: "ACCOUNT_LINK_BATTLENET_CLIENT_SECRET",
|
|
142
|
+
factory: battlenetAccountLink,
|
|
143
|
+
portal: "https://develop.battle.net/access",
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
id: "epic",
|
|
147
|
+
clientId: env.ACCOUNT_LINK_EPIC_CLIENT_ID,
|
|
148
|
+
clientSecret: env.ACCOUNT_LINK_EPIC_CLIENT_SECRET,
|
|
149
|
+
idVar: "ACCOUNT_LINK_EPIC_CLIENT_ID",
|
|
150
|
+
secretVar: "ACCOUNT_LINK_EPIC_CLIENT_SECRET",
|
|
151
|
+
factory: epicAccountLink,
|
|
152
|
+
portal: "https://dev.epicgames.com/portal",
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
id: "xbox",
|
|
156
|
+
clientId: env.ACCOUNT_LINK_XBOX_CLIENT_ID,
|
|
157
|
+
clientSecret: env.ACCOUNT_LINK_XBOX_CLIENT_SECRET,
|
|
158
|
+
idVar: "ACCOUNT_LINK_XBOX_CLIENT_ID",
|
|
159
|
+
secretVar: "ACCOUNT_LINK_XBOX_CLIENT_SECRET",
|
|
160
|
+
factory: xboxAccountLink,
|
|
161
|
+
portal: "https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps",
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
id: "riot",
|
|
165
|
+
clientId: env.ACCOUNT_LINK_RIOT_CLIENT_ID,
|
|
166
|
+
clientSecret: env.ACCOUNT_LINK_RIOT_CLIENT_SECRET,
|
|
167
|
+
idVar: "ACCOUNT_LINK_RIOT_CLIENT_ID",
|
|
168
|
+
secretVar: "ACCOUNT_LINK_RIOT_CLIENT_SECRET",
|
|
169
|
+
factory: riotAccountLink,
|
|
170
|
+
portal: "https://developer.riotgames.com",
|
|
171
|
+
},
|
|
172
|
+
];
|
|
173
|
+
|
|
174
|
+
for (const p of oauthPresets) {
|
|
175
|
+
if (p.clientId && p.clientSecret) {
|
|
176
|
+
providers.push(
|
|
177
|
+
p.factory({ clientId: p.clientId, clientSecret: p.clientSecret }),
|
|
178
|
+
);
|
|
179
|
+
} else if (p.clientId || p.clientSecret) {
|
|
180
|
+
const missing = p.clientId ? p.secretVar : p.idVar;
|
|
181
|
+
warnings.push(
|
|
182
|
+
`${p.id} account linking is half-configured: ${missing} is unset, ` +
|
|
183
|
+
`so the ${p.id} provider is NOT registered. Set both ${p.idVar} ` +
|
|
184
|
+
`and ${p.secretVar} (from ${p.portal}), or unset both`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
123
187
|
}
|
|
124
188
|
|
|
125
189
|
return { providers, warnings };
|
package/src/lib/contacts.ts
CHANGED
|
@@ -434,6 +434,38 @@ export function serializeContact(
|
|
|
434
434
|
};
|
|
435
435
|
}
|
|
436
436
|
|
|
437
|
+
/**
|
|
438
|
+
* The BROWSER-safe projection of a contact (`GET /v1/contacts/me`). Applies the
|
|
439
|
+
* operator allowlist: only EXACT `publicProperties` keys survive, and `email`
|
|
440
|
+
* is present only when `exposeEmail` is on. A missing row projects to
|
|
441
|
+
* `{ identified: false, traits: {} }` — the route never 404s, so the absence of
|
|
442
|
+
* a contact is indistinguishable from an empty allowlist.
|
|
443
|
+
*
|
|
444
|
+
* `identified` means the row carries a real identity (`externalId` or `email`);
|
|
445
|
+
* an anonymous-only row reads its own traits but is NOT identified.
|
|
446
|
+
*/
|
|
447
|
+
export function projectPublicContact(
|
|
448
|
+
row: ContactRow | null | undefined,
|
|
449
|
+
config: { publicProperties: string[]; exposeEmail: boolean },
|
|
450
|
+
): {
|
|
451
|
+
identified: boolean;
|
|
452
|
+
traits: Record<string, unknown>;
|
|
453
|
+
email?: string | null;
|
|
454
|
+
} {
|
|
455
|
+
const props = (row?.properties ?? {}) as Record<string, unknown>;
|
|
456
|
+
const traits: Record<string, unknown> = {};
|
|
457
|
+
if (row) {
|
|
458
|
+
for (const key of config.publicProperties) {
|
|
459
|
+
if (Object.hasOwn(props, key)) traits[key] = props[key];
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return {
|
|
463
|
+
identified: Boolean(row && (row.externalId || row.email)),
|
|
464
|
+
traits,
|
|
465
|
+
...(config.exposeEmail ? { email: row?.email ?? null } : {}),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
437
469
|
export function serializePrefs(row: typeof emailPreferences.$inferSelect) {
|
|
438
470
|
return {
|
|
439
471
|
id: row.id,
|
|
@@ -1079,6 +1111,21 @@ interface ResolveContactOptions {
|
|
|
1079
1111
|
source?: string;
|
|
1080
1112
|
/** Timestamp paired with {@link source}; defaults to now() at create time. */
|
|
1081
1113
|
sourcedAt?: Date;
|
|
1114
|
+
/**
|
|
1115
|
+
* JOURNEY-PLANE opt-out for the merge fold's `account.unlinked` re-ingest
|
|
1116
|
+
* (PRD 08 T5). Default `true`: an organic resolve (a live `/v1/events`
|
|
1117
|
+
* ingest that happens to fold two contacts) SHOULD enrol journeys on the
|
|
1118
|
+
* `account.unlinked` a merge produced, exactly as a direct unlink would.
|
|
1119
|
+
*
|
|
1120
|
+
* A BULK importer sets `false`. A CSV import is a statement about the PAST,
|
|
1121
|
+
* and one job can merge many rows whose losers each held a live linked
|
|
1122
|
+
* account — so left on, a single import would fan out one journey enrolment
|
|
1123
|
+
* per such row (the same amplification class the `/v1/accounts/import`
|
|
1124
|
+
* route gates with its own `enrollJourneys`). This suppresses ONLY the
|
|
1125
|
+
* journey plane; the outbound `account.unlinked` webhook still fires, so the
|
|
1126
|
+
* customer's mirror converges whether or not a journey ran.
|
|
1127
|
+
*/
|
|
1128
|
+
enrollJourneys?: boolean;
|
|
1082
1129
|
}
|
|
1083
1130
|
|
|
1084
1131
|
/**
|
|
@@ -1485,6 +1532,44 @@ async function resolveContactShared(
|
|
|
1485
1532
|
// Only the singleton-COLLISION soft-unlinks are here. The repoint that moves
|
|
1486
1533
|
// the loser's surviving links to the survivor is deliberately silent — see
|
|
1487
1534
|
// the note on step 4 of `foldLinkedAccounts`.
|
|
1535
|
+
// REFERRAL BIND (PRD 05 stage 3), post-commit for the same reason the
|
|
1536
|
+
// account-link emit above is: `bindReferral` announces `referral.bound` on
|
|
1537
|
+
// both planes, and a resolve that rolled back must never have announced a
|
|
1538
|
+
// bind that never happened. This is the ONE bind site precisely because
|
|
1539
|
+
// `resolveContactShared` is the ONE owner of every `resolveOrCreateContact`
|
|
1540
|
+
// / `resolveContactNoCreate` call.
|
|
1541
|
+
//
|
|
1542
|
+
// The keys scanned are every key this resolve just made this contact's:
|
|
1543
|
+
// the resolved canonical key (which the create arm's `adoptOrphanHistory`
|
|
1544
|
+
// just stamped history under), the anon key supplied by the identify call,
|
|
1545
|
+
// and any key a merge absorbed. `bindTouches` is a no-op for a key with no
|
|
1546
|
+
// unbound touch, so the extra scans cost one indexed lookup on a partial
|
|
1547
|
+
// index built for exactly this query.
|
|
1548
|
+
if (resolved.id !== null) {
|
|
1549
|
+
const boundContactId = resolved.id;
|
|
1550
|
+
const keys = new Set<string>([resolved.resolvedKey]);
|
|
1551
|
+
if (opts.anonymousId) keys.add(opts.anonymousId);
|
|
1552
|
+
for (const key of resolved.mergedKeys ?? []) keys.add(key);
|
|
1553
|
+
// AWAITED, not fire-and-forget: the same ingest that identifies the
|
|
1554
|
+
// referee may ALSO be the qualify event (a `signup` carrying the email),
|
|
1555
|
+
// and `ingestEvent`'s qualify hook runs after this resolve and reads
|
|
1556
|
+
// `status = 'bound'`. A detached bind would lose that race and the touch
|
|
1557
|
+
// would sit at `touched` until the next qualifying event. Errors are still
|
|
1558
|
+
// swallowed with an attributed log: an identify must never fail because a
|
|
1559
|
+
// referral edge could not be stamped.
|
|
1560
|
+
try {
|
|
1561
|
+
const { bindReferral } = await import("./referral-intent.js");
|
|
1562
|
+
for (const refereeKey of keys) {
|
|
1563
|
+
await bindReferral({ db, refereeKey, contactId: boundContactId });
|
|
1564
|
+
}
|
|
1565
|
+
} catch (error: unknown) {
|
|
1566
|
+
logger.warn("referral bind failed", {
|
|
1567
|
+
contactId: boundContactId,
|
|
1568
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1488
1573
|
if (resolved.linkUnlinks && resolved.linkUnlinks.length > 0) {
|
|
1489
1574
|
emitAccountUnlinked(db, resolved.linkUnlinks);
|
|
1490
1575
|
// THE JOURNEY PLANE, beside the outbound one (PRD 08 T5). TWO DIFFERENT
|
|
@@ -1500,8 +1585,15 @@ async function resolveContactShared(
|
|
|
1500
1585
|
// and returns without probing value keys — so it can neither merge again
|
|
1501
1586
|
// nor produce a second `linkUnlinks`. It is also fire-and-forget and
|
|
1502
1587
|
// strictly post-commit, so it cannot slow or fail the resolve.
|
|
1503
|
-
|
|
1504
|
-
|
|
1588
|
+
//
|
|
1589
|
+
// A BULK importer opts OUT here (`enrollJourneys: false`): one job can fold
|
|
1590
|
+
// many rows, and left on it would fan out one enrolment per merged row that
|
|
1591
|
+
// dropped a live link. The outbound `emitAccountUnlinked` above is
|
|
1592
|
+
// deliberately NOT gated — the customer's mirror converges regardless.
|
|
1593
|
+
if (opts.enrollJourneys !== false) {
|
|
1594
|
+
for (const fact of resolved.linkUnlinks) {
|
|
1595
|
+
ingestAccountUnlinked(db, fact);
|
|
1596
|
+
}
|
|
1505
1597
|
}
|
|
1506
1598
|
}
|
|
1507
1599
|
|
package/src/lib/ingestion.ts
CHANGED
|
@@ -802,6 +802,38 @@ export async function ingestEvent(opts: {
|
|
|
802
802
|
}
|
|
803
803
|
: null;
|
|
804
804
|
|
|
805
|
+
// (5b-referral) REFERRAL QUALIFY (PRD 05 §6 qualify). Does THIS event
|
|
806
|
+
// promote one of this contact's BOUND touches? Cheap on a miss (one map
|
|
807
|
+
// lookup keyed by `qualify.event`), so it runs on every ingested event, and
|
|
808
|
+
// entirely inert with no referrals registered.
|
|
809
|
+
//
|
|
810
|
+
// Gated on `contactId !== null` for the same reason site 5 is: a touch can
|
|
811
|
+
// only qualify once it is BOUND, and a bound touch by definition has a
|
|
812
|
+
// referee CONTACT — a refused resolve has no contact to look one up for.
|
|
813
|
+
// Best-effort: the event is already durable.
|
|
814
|
+
if (insertedRow && contactId !== null) {
|
|
815
|
+
try {
|
|
816
|
+
const { qualifyReferralsForEvent } = await import("./referral-intent.js");
|
|
817
|
+
await qualifyReferralsForEvent({
|
|
818
|
+
handles: {
|
|
819
|
+
db,
|
|
820
|
+
hatchet,
|
|
821
|
+
registry,
|
|
822
|
+
logger,
|
|
823
|
+
...(opts.analytics ? { analytics: opts.analytics } : {}),
|
|
824
|
+
},
|
|
825
|
+
event: event.event,
|
|
826
|
+
eventProperties: event.eventProperties,
|
|
827
|
+
contactId,
|
|
828
|
+
});
|
|
829
|
+
} catch (err) {
|
|
830
|
+
logger.warn("referral qualify evaluation failed", {
|
|
831
|
+
event: event.event,
|
|
832
|
+
error: err instanceof Error ? err.message : String(err),
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
805
837
|
// (5c) Conversion-point evaluation (plan §5.1) — the unique
|
|
806
838
|
// (definition, event) index makes any replay a no-op.
|
|
807
839
|
//
|
|
@@ -869,6 +901,35 @@ export async function ingestEvent(opts: {
|
|
|
869
901
|
error: err instanceof Error ? err.message : String(err),
|
|
870
902
|
});
|
|
871
903
|
}
|
|
904
|
+
|
|
905
|
+
// THE REFERRAL TREE (PRD 05 §6 convert). Beside the attribution
|
|
906
|
+
// ledger, never inside it: the ledger answers "which touchpoints get
|
|
907
|
+
// credit", the tree answers "which PEOPLE get told". Announces
|
|
908
|
+
// `referral.converted` to the direct referrer and
|
|
909
|
+
// `referral.tree_converted` to each ancestor to depth 5, with `level`
|
|
910
|
+
// as a FACT on the event so a reward journey filters on it. Inert
|
|
911
|
+
// with no referrals registered; isolated so a tree failure can never
|
|
912
|
+
// cost a conversion.
|
|
913
|
+
try {
|
|
914
|
+
const { convertReferral } = await import("./referral-intent.js");
|
|
915
|
+
await convertReferral({
|
|
916
|
+
db,
|
|
917
|
+
hatchet,
|
|
918
|
+
registry,
|
|
919
|
+
logger,
|
|
920
|
+
...(opts.analytics ? { analytics: opts.analytics } : {}),
|
|
921
|
+
contactId,
|
|
922
|
+
conversionId: firedConversion.conversionId,
|
|
923
|
+
value: firedConversion.value ?? null,
|
|
924
|
+
currency: firedConversion.currency ?? null,
|
|
925
|
+
occurredAt: insertedRow.occurredAt,
|
|
926
|
+
});
|
|
927
|
+
} catch (err) {
|
|
928
|
+
logger.warn("referral conversion walk failed", {
|
|
929
|
+
conversionId: firedConversion.conversionId,
|
|
930
|
+
error: err instanceof Error ? err.message : String(err),
|
|
931
|
+
});
|
|
932
|
+
}
|
|
872
933
|
}
|
|
873
934
|
} catch (err) {
|
|
874
935
|
logger.warn("Conversion evaluation failed", {
|
package/src/lib/links.ts
CHANGED
|
@@ -16,9 +16,26 @@ import { and, eq, isNull, ne, or, sql } from "drizzle-orm";
|
|
|
16
16
|
* SHARE-SAFE INVARIANT: a link is identity-bearing (carries a `distinctId` the
|
|
17
17
|
* click can stitch + may mint a single-use `hs_t`) ONLY when `type: "personal"`
|
|
18
18
|
* AND an explicit `distinctId` is passed. A `"public"` link NEVER carries a
|
|
19
|
-
* person token
|
|
19
|
+
* person token - a shared/reshared public link attributes by campaign only.
|
|
20
|
+
* `"shared"` (a referral link) is owned by a person and clicked by SOMEONE
|
|
21
|
+
* ELSE, so it sits on the PUBLIC side of that invariant: it attributes to
|
|
22
|
+
* `ownerContactId` and stitches nobody.
|
|
20
23
|
*/
|
|
21
|
-
export type LinkType = "personal" | "public";
|
|
24
|
+
export type LinkType = "personal" | "public" | "shared";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Thrown when the `shared` link ownership invariant is broken (PRD 05 5.2):
|
|
28
|
+
* a `shared` link with no `ownerContactId` credits nobody, and an
|
|
29
|
+
* `ownerContactId` on a `personal`/`public` link is a silent no-op that reads
|
|
30
|
+
* as if attribution were configured. Both are authoring errors, so they throw
|
|
31
|
+
* at mint time rather than minting a link that quietly does nothing.
|
|
32
|
+
*/
|
|
33
|
+
export class LinkOwnershipError extends Error {
|
|
34
|
+
constructor(message: string) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = "LinkOwnershipError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
22
39
|
|
|
23
40
|
export interface MintLinkOptions {
|
|
24
41
|
db: Database;
|
|
@@ -28,8 +45,22 @@ export interface MintLinkOptions {
|
|
|
28
45
|
baseUrl: string;
|
|
29
46
|
/** Originating channel: "studio" | "discord" | "sms" | "referral" | … (open). */
|
|
30
47
|
source: string;
|
|
31
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* "personal" (1:1, identity-bearing) | "public" (shareable) | "shared"
|
|
50
|
+
* (owned by a person, clicked by others - a referral link). Default
|
|
51
|
+
* "public".
|
|
52
|
+
*/
|
|
32
53
|
type?: LinkType;
|
|
54
|
+
/**
|
|
55
|
+
* The contact this link earns credit FOR. REQUIRED for `type: "shared"`,
|
|
56
|
+
* forbidden on `personal`/`public` (see {@link LinkOwnershipError}).
|
|
57
|
+
*
|
|
58
|
+
* This is an ATTRIBUTION field, never an identity one: it is deliberately
|
|
59
|
+
* not `distinctId`, because a referral link's clicker must never be stitched
|
|
60
|
+
* to its owner. Reusing `personal` for this would identify every referee AS
|
|
61
|
+
* the referrer, which is precisely the share-safe invariant's failure mode.
|
|
62
|
+
*/
|
|
63
|
+
ownerContactId?: string;
|
|
33
64
|
/** Operator-facing name (Studio list). */
|
|
34
65
|
label?: string;
|
|
35
66
|
/**
|
|
@@ -40,8 +71,16 @@ export interface MintLinkOptions {
|
|
|
40
71
|
/** UTM-style campaign grouping (public links). */
|
|
41
72
|
campaign?: string;
|
|
42
73
|
/**
|
|
43
|
-
* The
|
|
44
|
-
*
|
|
74
|
+
* The `defineReferral` id this link belongs to (`getReferralLink` sets it).
|
|
75
|
+
* Stored on the row so a CLICK can find the DEFINITION that owns it - the
|
|
76
|
+
* hooks, the bind window and the qualify rule - without inferring it from
|
|
77
|
+
* `campaign`, which is operator-facing grouping and may be absent or shared.
|
|
78
|
+
*/
|
|
79
|
+
referralId?: string;
|
|
80
|
+
/**
|
|
81
|
+
* The canonical contact key a click should stitch - honoured ONLY for
|
|
82
|
+
* `type: "personal"`; dropped for public AND shared links (the share-safe
|
|
83
|
+
* invariant).
|
|
45
84
|
*/
|
|
46
85
|
distinctId?: string;
|
|
47
86
|
/** The admin actor who minted it (Studio). */
|
|
@@ -81,6 +120,10 @@ export interface MintedLink {
|
|
|
81
120
|
slug: string | null;
|
|
82
121
|
/** The vanity short URL (`${baseUrl}/l/:slug`), if a slug was minted. */
|
|
83
122
|
vanityUrl: string | null;
|
|
123
|
+
/** The link's type, as stored. */
|
|
124
|
+
type: LinkType;
|
|
125
|
+
/** The credited owner for a `shared` link; null for personal/public. */
|
|
126
|
+
ownerContactId: string | null;
|
|
84
127
|
/**
|
|
85
128
|
* True when the mint RECOVERED an existing live link (same slug or
|
|
86
129
|
* idempotencyKey + same destination) instead of inserting a new one.
|
|
@@ -290,7 +333,12 @@ export function assertHttpUrl(url: string): void {
|
|
|
290
333
|
async function recoverExistingLink(
|
|
291
334
|
db: Database,
|
|
292
335
|
baseUrl: string,
|
|
293
|
-
row: {
|
|
336
|
+
row: {
|
|
337
|
+
id: string;
|
|
338
|
+
slug: string | null;
|
|
339
|
+
type: string;
|
|
340
|
+
ownerContactId: string | null;
|
|
341
|
+
},
|
|
294
342
|
): Promise<MintedLink | null> {
|
|
295
343
|
const [tracked] = await db
|
|
296
344
|
.select({ id: sql<string | null>`min(${trackedLinks.id}::text)` })
|
|
@@ -304,6 +352,8 @@ async function recoverExistingLink(
|
|
|
304
352
|
url: `${baseUrl}/v1/t/c/${trackedLinkId}`,
|
|
305
353
|
slug: row.slug,
|
|
306
354
|
vanityUrl: row.slug ? vanityUrlFor(baseUrl, row.slug) : null,
|
|
355
|
+
type: row.type as LinkType,
|
|
356
|
+
ownerContactId: row.ownerContactId,
|
|
307
357
|
existing: true,
|
|
308
358
|
};
|
|
309
359
|
}
|
|
@@ -314,7 +364,25 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
314
364
|
throw new Error("mintLink: slug and idempotencyKey are mutually exclusive");
|
|
315
365
|
}
|
|
316
366
|
const type: LinkType = opts.type ?? "public";
|
|
317
|
-
//
|
|
367
|
+
// THE OWNERSHIP INVARIANT (PRD 05 5.2). Loud at mint time, because both
|
|
368
|
+
// halves fail SILENTLY otherwise: an unowned shared link records touches
|
|
369
|
+
// that credit nobody, and an owner set on a public link looks like
|
|
370
|
+
// attribution is wired when nothing reads it.
|
|
371
|
+
const ownerContactId = opts.ownerContactId ?? null;
|
|
372
|
+
if (type === "shared" && !ownerContactId) {
|
|
373
|
+
throw new LinkOwnershipError(
|
|
374
|
+
'mintLink: type "shared" requires ownerContactId - a shared link is ' +
|
|
375
|
+
"owned by the person it credits",
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
if (type !== "shared" && ownerContactId) {
|
|
379
|
+
throw new LinkOwnershipError(
|
|
380
|
+
`mintLink: ownerContactId is only valid for type "shared", got "${type}"`,
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
// Only a PERSONAL link carries a person token. A public link must never
|
|
384
|
+
// carry one, and neither must a shared link: it is clicked by someone other
|
|
385
|
+
// than its owner, so stitching would identify every referee as the referrer.
|
|
318
386
|
const distinctId = type === "personal" ? (opts.distinctId ?? null) : null;
|
|
319
387
|
const slug = opts.slug !== undefined ? normalizeSlug(opts.slug) : null;
|
|
320
388
|
|
|
@@ -335,8 +403,10 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
335
403
|
description: opts.description ?? null,
|
|
336
404
|
appendRef: opts.appendRef ?? false,
|
|
337
405
|
campaign: opts.campaign ?? null,
|
|
406
|
+
referralId: opts.referralId ?? null,
|
|
338
407
|
source: opts.source,
|
|
339
408
|
distinctId,
|
|
409
|
+
ownerContactId,
|
|
340
410
|
createdBy: opts.createdBy ?? null,
|
|
341
411
|
idempotencyKey: opts.idempotencyKey ?? null,
|
|
342
412
|
});
|
|
@@ -360,13 +430,19 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
360
430
|
.from(links)
|
|
361
431
|
.where(and(eq(links.slug, slug), isNull(links.archivedAt)))
|
|
362
432
|
.limit(1);
|
|
363
|
-
if (
|
|
433
|
+
if (
|
|
434
|
+
row &&
|
|
435
|
+
row.originalUrl === opts.url &&
|
|
436
|
+
row.type === type &&
|
|
437
|
+
row.ownerContactId === ownerContactId
|
|
438
|
+
) {
|
|
364
439
|
const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
|
|
365
440
|
if (recovered) return recovered;
|
|
366
441
|
}
|
|
367
442
|
// Slug held by an ARCHIVED link (the live lookup misses — archived
|
|
368
|
-
// links keep their slug reserved), a different destination,
|
|
369
|
-
// different type
|
|
443
|
+
// links keep their slug reserved), a different destination, a
|
|
444
|
+
// different type, or a different owner (two referrers whose slugFrom
|
|
445
|
+
// collide must NOT share one link) → conflict.
|
|
370
446
|
throw new SlugTakenError(slug);
|
|
371
447
|
}
|
|
372
448
|
if (opts.idempotencyKey && isIdempotencyKeyViolation(err)) {
|
|
@@ -380,7 +456,12 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
380
456
|
),
|
|
381
457
|
)
|
|
382
458
|
.limit(1);
|
|
383
|
-
if (
|
|
459
|
+
if (
|
|
460
|
+
row &&
|
|
461
|
+
row.originalUrl === opts.url &&
|
|
462
|
+
row.type === type &&
|
|
463
|
+
row.ownerContactId === ownerContactId
|
|
464
|
+
) {
|
|
384
465
|
const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
|
|
385
466
|
if (recovered) return recovered;
|
|
386
467
|
}
|
|
@@ -398,6 +479,8 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
398
479
|
url: `${opts.baseUrl}/v1/t/c/${trackedLinkId}`,
|
|
399
480
|
slug,
|
|
400
481
|
vanityUrl: slug ? vanityUrlFor(opts.baseUrl, slug) : null,
|
|
482
|
+
type,
|
|
483
|
+
ownerContactId,
|
|
401
484
|
existing: false,
|
|
402
485
|
};
|
|
403
486
|
}
|