@hogsend/engine 0.52.1 → 0.53.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 +10 -10
- package/src/index.ts +1 -0
- package/src/lib/links.ts +118 -7
- package/src/routes/admin/links.ts +57 -25
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hogsend/engine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.53.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -53,17 +53,17 @@
|
|
|
53
53
|
"svix": "^1.95.1",
|
|
54
54
|
"winston": "^3.19.0",
|
|
55
55
|
"zod": "^4.4.3",
|
|
56
|
-
"@hogsend/
|
|
57
|
-
"@hogsend/
|
|
58
|
-
"@hogsend/db": "^0.
|
|
59
|
-
"@hogsend/email": "^0.
|
|
60
|
-
"@hogsend/plugin-posthog": "^0.
|
|
61
|
-
"@hogsend/plugin-resend": "^0.
|
|
62
|
-
"@hogsend/sms": "^0.
|
|
56
|
+
"@hogsend/core": "^0.53.0",
|
|
57
|
+
"@hogsend/attribution": "^0.53.0",
|
|
58
|
+
"@hogsend/db": "^0.53.0",
|
|
59
|
+
"@hogsend/email": "^0.53.0",
|
|
60
|
+
"@hogsend/plugin-posthog": "^0.53.0",
|
|
61
|
+
"@hogsend/plugin-resend": "^0.53.0",
|
|
62
|
+
"@hogsend/sms": "^0.53.0"
|
|
63
63
|
},
|
|
64
64
|
"optionalDependencies": {
|
|
65
|
-
"@hogsend/plugin-postmark": "^0.
|
|
66
|
-
"@hogsend/plugin-twilio": "^0.
|
|
65
|
+
"@hogsend/plugin-postmark": "^0.53.0",
|
|
66
|
+
"@hogsend/plugin-twilio": "^0.53.0"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"@types/node": "^22.15.3",
|
package/src/index.ts
CHANGED
|
@@ -583,6 +583,7 @@ export {
|
|
|
583
583
|
// filter, the 'qr' source marker) is deliberately NOT exported — it is
|
|
584
584
|
// internal mechanics behind the /qr endpoint, not semver surface.
|
|
585
585
|
export {
|
|
586
|
+
IdempotencyConflictError,
|
|
586
587
|
type LinkType,
|
|
587
588
|
type MintedLink,
|
|
588
589
|
type MintLinkOptions,
|
package/src/lib/links.ts
CHANGED
|
@@ -59,6 +59,15 @@ export interface MintLinkOptions {
|
|
|
59
59
|
* OAuth redirect_uri destinations.
|
|
60
60
|
*/
|
|
61
61
|
appendRef?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* Idempotent-mint key for slugless links: re-minting with the same key +
|
|
64
|
+
* same destination returns the EXISTING link (`existing: true`) instead of
|
|
65
|
+
* a duplicate; same key + different destination is an
|
|
66
|
+
* IdempotencyConflictError (→ 409). Unique among LIVE links only (partial
|
|
67
|
+
* index) — archiving frees the key. Mutually exclusive with `slug` (a slug
|
|
68
|
+
* IS an idempotency key: same slug + same url + same type recovers too).
|
|
69
|
+
*/
|
|
70
|
+
idempotencyKey?: string;
|
|
62
71
|
}
|
|
63
72
|
|
|
64
73
|
export interface MintedLink {
|
|
@@ -72,6 +81,11 @@ export interface MintedLink {
|
|
|
72
81
|
slug: string | null;
|
|
73
82
|
/** The vanity short URL (`${baseUrl}/l/:slug`), if a slug was minted. */
|
|
74
83
|
vanityUrl: string | null;
|
|
84
|
+
/**
|
|
85
|
+
* True when the mint RECOVERED an existing live link (same slug or
|
|
86
|
+
* idempotencyKey + same destination) instead of inserting a new one.
|
|
87
|
+
*/
|
|
88
|
+
existing: boolean;
|
|
75
89
|
}
|
|
76
90
|
|
|
77
91
|
// ---------------------------------------------------------------------------
|
|
@@ -105,11 +119,12 @@ export function normalizeSlug(raw: string): string {
|
|
|
105
119
|
}
|
|
106
120
|
|
|
107
121
|
/**
|
|
108
|
-
* True when a DB error is the Postgres unique_violation on the
|
|
109
|
-
* Walks the cause chain — drizzle wraps the driver's
|
|
110
|
-
* DrizzleQueryError whose `cause` carries the actual
|
|
122
|
+
* True when a DB error is the Postgres unique_violation on the named
|
|
123
|
+
* constraint. Walks the cause chain — drizzle wraps the driver's
|
|
124
|
+
* PostgresError in a DrizzleQueryError whose `cause` carries the actual
|
|
125
|
+
* code/constraint.
|
|
111
126
|
*/
|
|
112
|
-
|
|
127
|
+
function isUniqueViolationOn(err: unknown, constraint: string): boolean {
|
|
113
128
|
for (let e = err, depth = 0; e && depth < 5; depth++) {
|
|
114
129
|
const candidate = e as {
|
|
115
130
|
code?: string;
|
|
@@ -119,8 +134,8 @@ export function isSlugUniqueViolation(err: unknown): boolean {
|
|
|
119
134
|
};
|
|
120
135
|
if (
|
|
121
136
|
candidate.code === "23505" &&
|
|
122
|
-
(candidate.constraint_name ===
|
|
123
|
-
(candidate.message?.includes(
|
|
137
|
+
(candidate.constraint_name === constraint ||
|
|
138
|
+
(candidate.message?.includes(constraint) ?? false))
|
|
124
139
|
) {
|
|
125
140
|
return true;
|
|
126
141
|
}
|
|
@@ -129,6 +144,31 @@ export function isSlugUniqueViolation(err: unknown): boolean {
|
|
|
129
144
|
return false;
|
|
130
145
|
}
|
|
131
146
|
|
|
147
|
+
/** True when a DB error is the unique_violation on the slug index. */
|
|
148
|
+
export function isSlugUniqueViolation(err: unknown): boolean {
|
|
149
|
+
return isUniqueViolationOn(err, "links_slug_unique");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* True when a DB error is the unique_violation on the partial (live-rows-only)
|
|
154
|
+
* idempotency-key index.
|
|
155
|
+
*/
|
|
156
|
+
export function isIdempotencyKeyViolation(err: unknown): boolean {
|
|
157
|
+
return isUniqueViolationOn(err, "links_idempotency_key_unique");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Thrown when an idempotencyKey is already held by a LIVE link with a
|
|
162
|
+
* DIFFERENT destination → HTTP 409. (Same destination is not a conflict — it
|
|
163
|
+
* recovers the existing link.)
|
|
164
|
+
*/
|
|
165
|
+
export class IdempotencyConflictError extends Error {
|
|
166
|
+
constructor(key: string) {
|
|
167
|
+
super(`Idempotency key "${key}" already used for a different destination`);
|
|
168
|
+
this.name = "IdempotencyConflictError";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
132
172
|
export function vanityUrlFor(baseUrl: string, slug: string): string {
|
|
133
173
|
return `${baseUrl}/l/${slug}`;
|
|
134
174
|
}
|
|
@@ -240,8 +280,39 @@ export function assertHttpUrl(url: string): void {
|
|
|
240
280
|
}
|
|
241
281
|
}
|
|
242
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Build the MintedLink for an already-existing LIVE links row (idempotent
|
|
285
|
+
* recovery): resolves its CANONICAL tracked row (the redirect row, never the
|
|
286
|
+
* lazily-minted QR scan row) via the shared canonical-row predicate. Returns
|
|
287
|
+
* null if the link somehow has no tracked row — callers fall back to their
|
|
288
|
+
* conflict path rather than fabricating a dead redirect URL.
|
|
289
|
+
*/
|
|
290
|
+
async function recoverExistingLink(
|
|
291
|
+
db: Database,
|
|
292
|
+
baseUrl: string,
|
|
293
|
+
row: { id: string; slug: string | null },
|
|
294
|
+
): Promise<MintedLink | null> {
|
|
295
|
+
const [tracked] = await db
|
|
296
|
+
.select({ id: sql<string | null>`min(${trackedLinks.id}::text)` })
|
|
297
|
+
.from(trackedLinks)
|
|
298
|
+
.where(and(eq(trackedLinks.linkId, row.id), canonicalTrackedRowFilter()));
|
|
299
|
+
const trackedLinkId = tracked?.id ?? null;
|
|
300
|
+
if (!trackedLinkId) return null;
|
|
301
|
+
return {
|
|
302
|
+
linkId: row.id,
|
|
303
|
+
trackedLinkId,
|
|
304
|
+
url: `${baseUrl}/v1/t/c/${trackedLinkId}`,
|
|
305
|
+
slug: row.slug,
|
|
306
|
+
vanityUrl: row.slug ? vanityUrlFor(baseUrl, row.slug) : null,
|
|
307
|
+
existing: true,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
243
311
|
export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
244
312
|
assertHttpUrl(opts.url);
|
|
313
|
+
if (opts.slug !== undefined && opts.idempotencyKey !== undefined) {
|
|
314
|
+
throw new Error("mintLink: slug and idempotencyKey are mutually exclusive");
|
|
315
|
+
}
|
|
245
316
|
const type: LinkType = opts.type ?? "public";
|
|
246
317
|
// A public link must NEVER carry a person token — drop any distinctId.
|
|
247
318
|
const distinctId = type === "personal" ? (opts.distinctId ?? null) : null;
|
|
@@ -267,6 +338,7 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
267
338
|
source: opts.source,
|
|
268
339
|
distinctId,
|
|
269
340
|
createdBy: opts.createdBy ?? null,
|
|
341
|
+
idempotencyKey: opts.idempotencyKey ?? null,
|
|
270
342
|
});
|
|
271
343
|
await tx.insert(trackedLinks).values({
|
|
272
344
|
id: trackedLinkId,
|
|
@@ -278,7 +350,45 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
278
350
|
});
|
|
279
351
|
});
|
|
280
352
|
} catch (err) {
|
|
281
|
-
|
|
353
|
+
// Idempotent recovery. NOTE: these queries run AFTER the aborted
|
|
354
|
+
// transaction, on opts.db directly — the tx object is dead.
|
|
355
|
+
if (slug && isSlugUniqueViolation(err)) {
|
|
356
|
+
// A slug re-mint with the SAME destination + type is the same intent —
|
|
357
|
+
// return the existing LIVE link instead of 409ing a retry.
|
|
358
|
+
const [row] = await opts.db
|
|
359
|
+
.select()
|
|
360
|
+
.from(links)
|
|
361
|
+
.where(and(eq(links.slug, slug), isNull(links.archivedAt)))
|
|
362
|
+
.limit(1);
|
|
363
|
+
if (row && row.originalUrl === opts.url && row.type === type) {
|
|
364
|
+
const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
|
|
365
|
+
if (recovered) return recovered;
|
|
366
|
+
}
|
|
367
|
+
// Slug held by an ARCHIVED link (the live lookup misses — archived
|
|
368
|
+
// links keep their slug reserved), a different destination, or a
|
|
369
|
+
// different type → conflict.
|
|
370
|
+
throw new SlugTakenError(slug);
|
|
371
|
+
}
|
|
372
|
+
if (opts.idempotencyKey && isIdempotencyKeyViolation(err)) {
|
|
373
|
+
const [row] = await opts.db
|
|
374
|
+
.select()
|
|
375
|
+
.from(links)
|
|
376
|
+
.where(
|
|
377
|
+
and(
|
|
378
|
+
eq(links.idempotencyKey, opts.idempotencyKey),
|
|
379
|
+
isNull(links.archivedAt),
|
|
380
|
+
),
|
|
381
|
+
)
|
|
382
|
+
.limit(1);
|
|
383
|
+
if (row && row.originalUrl === opts.url) {
|
|
384
|
+
const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
|
|
385
|
+
if (recovered) return recovered;
|
|
386
|
+
}
|
|
387
|
+
if (row) throw new IdempotencyConflictError(opts.idempotencyKey);
|
|
388
|
+
// Defensive: the partial index only covers live rows, so the winning
|
|
389
|
+
// row should always be live — if it vanished, surface the raw error.
|
|
390
|
+
throw err;
|
|
391
|
+
}
|
|
282
392
|
throw err;
|
|
283
393
|
}
|
|
284
394
|
|
|
@@ -288,5 +398,6 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
|
|
|
288
398
|
url: `${opts.baseUrl}/v1/t/c/${trackedLinkId}`,
|
|
289
399
|
slug,
|
|
290
400
|
vanityUrl: slug ? vanityUrlFor(opts.baseUrl, slug) : null,
|
|
401
|
+
existing: false,
|
|
291
402
|
};
|
|
292
403
|
}
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
assertHttpUrl,
|
|
18
18
|
canonicalTrackedRowFilter,
|
|
19
19
|
ensureQrTrackedLink,
|
|
20
|
+
IdempotencyConflictError,
|
|
20
21
|
isSlugUniqueViolation,
|
|
21
22
|
mintLink,
|
|
22
23
|
normalizeSlug,
|
|
@@ -118,6 +119,12 @@ const destinationStatSchema = z.object({
|
|
|
118
119
|
lastAt: z.string(),
|
|
119
120
|
});
|
|
120
121
|
|
|
122
|
+
// POST-only extension of the shared flat shape: `existing` reports whether the
|
|
123
|
+
// mint recovered an already-live link (idempotent re-mint) instead of
|
|
124
|
+
// inserting. Deliberately NOT on linkSchema — GET/list/PATCH/DELETE have no
|
|
125
|
+
// mint semantics.
|
|
126
|
+
const createdLinkSchema = linkSchema.extend({ existing: z.boolean() });
|
|
127
|
+
|
|
121
128
|
const linkDetailSchema = linkSchema.extend({
|
|
122
129
|
clicks: z.array(clickSchema),
|
|
123
130
|
destinations: z.array(destinationStatSchema),
|
|
@@ -183,29 +190,47 @@ const createLinkRoute = createRoute({
|
|
|
183
190
|
body: {
|
|
184
191
|
content: {
|
|
185
192
|
"application/json": {
|
|
186
|
-
schema: z
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
193
|
+
schema: z
|
|
194
|
+
.object({
|
|
195
|
+
url: z.string().url(),
|
|
196
|
+
type: z.enum(["personal", "public"]).default("public"),
|
|
197
|
+
// Optional vanity slug (`/l/:slug`). Normalized lowercase; 409 if
|
|
198
|
+
// already taken by a different destination (same destination +
|
|
199
|
+
// type recovers the existing link — see idempotencyKey).
|
|
200
|
+
slug: z.string().optional(),
|
|
201
|
+
label: z.string().optional(),
|
|
202
|
+
description: z.string().optional(),
|
|
203
|
+
appendRef: z.boolean().optional(),
|
|
204
|
+
campaign: z.string().optional(),
|
|
205
|
+
// Honoured ONLY for personal links (the share-safe invariant in
|
|
206
|
+
// mintLink drops it for public). A canonical contact key the click
|
|
207
|
+
// should stitch the visitor's anon session into.
|
|
208
|
+
distinctId: z.string().optional(),
|
|
209
|
+
// Honest originating channel: Studio UI mints say "studio", SDK/
|
|
210
|
+
// programmatic mints say "api".
|
|
211
|
+
source: z.enum(["studio", "api"]).default("studio"),
|
|
212
|
+
// Idempotent-mint key for slugless links: same key + same url
|
|
213
|
+
// returns the existing link (existing: true); same key +
|
|
214
|
+
// different url is a 409. Mutually exclusive with slug (a slug
|
|
215
|
+
// IS an idempotency key).
|
|
216
|
+
idempotencyKey: z
|
|
217
|
+
.string()
|
|
218
|
+
.min(1)
|
|
219
|
+
.max(255)
|
|
220
|
+
.regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/)
|
|
221
|
+
.optional(),
|
|
222
|
+
})
|
|
223
|
+
.refine((d) => !(d.slug && d.idempotencyKey), {
|
|
224
|
+
message: "slug and idempotencyKey are mutually exclusive",
|
|
225
|
+
}),
|
|
201
226
|
},
|
|
202
227
|
},
|
|
203
228
|
},
|
|
204
229
|
},
|
|
205
230
|
responses: {
|
|
206
231
|
200: {
|
|
207
|
-
content: { "application/json": { schema:
|
|
208
|
-
description: "Minted link",
|
|
232
|
+
content: { "application/json": { schema: createdLinkSchema } },
|
|
233
|
+
description: "Minted link (existing: true = idempotent re-mint)",
|
|
209
234
|
},
|
|
210
235
|
400: {
|
|
211
236
|
content: { "application/json": { schema: errorSchema } },
|
|
@@ -213,7 +238,7 @@ const createLinkRoute = createRoute({
|
|
|
213
238
|
},
|
|
214
239
|
409: {
|
|
215
240
|
content: { "application/json": { schema: errorSchema } },
|
|
216
|
-
description: "Slug already taken",
|
|
241
|
+
description: "Slug or idempotency key already taken",
|
|
217
242
|
},
|
|
218
243
|
},
|
|
219
244
|
});
|
|
@@ -415,7 +440,7 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
|
|
|
415
440
|
db,
|
|
416
441
|
url: body.url,
|
|
417
442
|
baseUrl: env.API_PUBLIC_URL,
|
|
418
|
-
source:
|
|
443
|
+
source: body.source,
|
|
419
444
|
type: body.type,
|
|
420
445
|
slug: body.slug,
|
|
421
446
|
label: body.label,
|
|
@@ -424,6 +449,7 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
|
|
|
424
449
|
campaign: body.campaign,
|
|
425
450
|
distinctId: body.distinctId,
|
|
426
451
|
createdBy: resolveActor(c) ?? undefined,
|
|
452
|
+
idempotencyKey: body.idempotencyKey,
|
|
427
453
|
});
|
|
428
454
|
|
|
429
455
|
const [row] = await db
|
|
@@ -436,16 +462,22 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
|
|
|
436
462
|
return c.json({ error: "Mint succeeded but link not found" }, 400);
|
|
437
463
|
}
|
|
438
464
|
|
|
465
|
+
// One aggregate path for BOTH fresh and recovered mints: a fresh mint
|
|
466
|
+
// aggregates to clicks:0/scans:0 with the canonical trackedLinkId; a
|
|
467
|
+
// recovered link reports its real counts.
|
|
468
|
+
const agg = await aggregateFor(db, [minted.linkId]);
|
|
439
469
|
return c.json(
|
|
440
|
-
|
|
441
|
-
row,
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
),
|
|
470
|
+
{
|
|
471
|
+
...serializeLink(row, agg.get(minted.linkId), env.API_PUBLIC_URL),
|
|
472
|
+
existing: minted.existing,
|
|
473
|
+
},
|
|
445
474
|
200,
|
|
446
475
|
);
|
|
447
476
|
} catch (err) {
|
|
448
|
-
if (
|
|
477
|
+
if (
|
|
478
|
+
err instanceof SlugTakenError ||
|
|
479
|
+
err instanceof IdempotencyConflictError
|
|
480
|
+
) {
|
|
449
481
|
return c.json({ error: err.message }, 409);
|
|
450
482
|
}
|
|
451
483
|
const message = err instanceof Error ? err.message : "Mint failed";
|